python-sdk Documentation

The official Python SDK for Model Context Protocol servers and clients

23,997 stars Python Python 1 file ยท ~20,685 tokens #mcp#mcp-client#mcp-server#python
RAW Doc

1. Project Overview & Quickstart (modelcontextprotocol/python-sdk)

File: README.md

MCP Python SDK

[!NOTE]
This is v2 of the MCP Python SDK, the current stable release line. It is a major rework of the SDK, both to support the 2026-07-28 MCP specification (and every earlier revision) and to fix long-standing architectural issues. Coming from v1? See What's new in v2 for the tour of what changed and the migration guide for every breaking change.

Not ready to migrate? v1.x lives on the v1.x branch, continues to receive critical bug fixes and security patches, and is documented at https://py.sdk.modelcontextprotocol.io/v1/. Since pip install mcp now installs 2.x, keep a <2 upper bound on your requirement (for example mcp>=1.28,<2) until you've migrated.

Something rough, confusing, or broken? Open an issue or find us in #python-sdk-dev on the MCP Contributors Discord.

Documentation

The documentation lives at https://py.sdk.modelcontextprotocol.io/.

It has a Get started guide, What's new in v2, the API reference, and the migration guide.

What is MCP?

The Model Context Protocol lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but designed for LLM interactions. With this SDK you can:

  • Build MCP servers that expose tools, resources, and prompts to any MCP host
  • Build MCP clients that connect to any MCP server
  • Speak every standard transport: stdio, Streamable HTTP, and SSE

Requirements

Python 3.10+.

Installation

bash
uv add "mcp[cli]"      # or: pip install "mcp[cli]"

The cli extra adds the mcp command-line tool (mcp dev, mcp run, mcp install) on top of the SDK; install plain mcp if you don't need it. For one-off commands, uv run --with "mcp[cli]" mcp ... works without a project.

A server in 15 lines

Create a server.py:

python
from mcp.server import MCPServer

mcp = MCPServer("Demo")


@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b


@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
    """Greet someone by name."""
    return f"Hello, {name}!"

Full example: docs_src/index/tutorial001.py

That's a complete MCP server: one tool, one templated resource. Open it in the MCP Inspector:

bash
uv run mcp dev server.py

Call add with a=1, b=2 and you get 3 back.

Notice what you did not write: no JSON Schema (a: int, b: int is the schema), no request parsing, no validation code, no protocol handling. Two type-hinted Python functions and a docstring.

Get started takes it from here.

A client in 10 lines

The same package is a full MCP client. Serve server.py over HTTP:

bash
uv run mcp run server.py --transport streamable-http

then point a Client at it:

python
import asyncio

from mcp import Client


async def main() -> None:
    async with Client("http://localhost:8000/mcp") as client:
        result = await client.call_tool("add", {"a": 1, "b": 2})
        print(result.structured_content)  # {'result': 3}


asyncio.run(main())

A URL means Streamable HTTP, the transport you deploy. Client can also launch a local server as a stdio subprocess or take any custom transport; Clients has the rest.

Contributing

We are passionate about supporting contributors of all levels of experience and would love to see you get involved in the project. See the contributing guide to get started.

License

This project is licensed under the MIT License. See the LICENSE file for details.


File: docs/index.md

MCP Python SDK

!!! info "This documents v2, the current stable release line"
New to v2, or coming from v1? What's new in v2 is the five-minute tour of what changed, and the Migration Guide covers every breaking change.
Still on v1.x? Its documentation lives at the v1.x docs.
Something rough or confusing? Tell us.

The Model Context Protocol (MCP) lets applications provide context to LLMs in a standardized way, separating the concern of providing context from the LLM interaction itself.

This is the official Python SDK for it. With it you can:

  • Build MCP servers that expose tools, resources, and prompts to any MCP host.
  • Build MCP clients that connect to any MCP server.
  • Speak every standard transport: stdio, Streamable HTTP, and SSE.

Requirements

Python 3.10+.

Installation

=== "uv"

text
```bash
uv add "mcp[cli]"
```

=== "pip"

text
```bash
pip install "mcp[cli]"
```

The [cli] extra gives you the mcp command; you'll want it for development.
See Installation for what each dependency is for.

Example

Create it

Create a file server.py:

python title="server.py"
--8<-- "docs_src/index/tutorial001.py"

That's a complete MCP server.

It exposes one tool, add, and one templated resource, greeting://{name}.

Run it

console
uv run mcp dev server.py

This starts your server and opens the MCP Inspector, an interactive UI for poking at it. Open the URL it prints.

!!! note
The Inspector is a Node.js app, so mcp dev needs npx on your PATH.

Try it

In the Inspector, go to Tools and call add with a=1, b=2.

You get 3 back. โœจ

The Inspector built that form (a required integer field for a, another for b) from your type hints. So will Claude, and every other MCP host.

Now go to Resources and read greeting://World:

text
Hello, World!

Recap

Look again at what you did not write:

  • No JSON Schema. a: int, b: int is the schema.
  • No request parsing, no serialization, no validation code.
  • No protocol handling at all.

You wrote two Python functions with type hints and a docstring. The SDK does the rest.

Where to go next

  • Get started takes you from install to a working, tested server.
  • Building an application that uses MCP servers? Start with Clients.
  • Already have a FastAPI or Starlette app? Add to an existing app mounts an MCP server inside it.
  • Hunting an exact error message? Troubleshooting is keyed by the verbatim text.
  • Wondering what changed in v2? What's new in v2 is the five-minute tour.
  • Migrating from v1? Start with the Migration Guide.
  • Hunting for an exact signature? The API Reference is generated from the source.
  • Reading with an LLM? This documentation is also published in the llms.txt format:
    llms.txt is an index of the pages, and
    llms-full.txt contains every page in a single file.

File: examples/clients/simple-chatbot/README.MD

MCP Simple Chatbot

This example demonstrates how to integrate the Model Context Protocol (MCP) into a simple CLI chatbot. The implementation showcases MCP's flexibility by supporting multiple tools through MCP servers and is compatible with any LLM provider that follows OpenAI API standards.

Requirements

  • Python 3.10
  • python-dotenv
  • requests
  • mcp
  • uvicorn

Installation

  1. Install the dependencies:

    bash
    pip install -r requirements.txt
  2. Set up environment variables:

    Create a .env file in the root directory and add your API key:

    plaintext
    LLM_API_KEY=your_api_key_here

    Note: The current implementation is configured to use the Groq API endpoint (https://api.groq.com/openai/v1/chat/completions) with the llama-3.2-90b-vision-preview model. If you plan to use a different LLM provider, you'll need to modify the LLMClient class in main.py to use the appropriate endpoint URL and model parameters.

  3. Configure servers:

    The servers_config.json follows the same structure as Claude Desktop, allowing for easy integration of multiple servers.
    Here's an example:

    json
    {
      "mcpServers": {
        "sqlite": {
          "command": "uvx",
          "args": ["mcp-server-sqlite", "--db-path", "./test.db"]
        },
        "puppeteer": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
        }
      }
    }

    Environment variables are supported as well. Pass them as you would with the Claude Desktop App.

    Example:

    json
    {
      "mcpServers": {
        "server_name": {
          "command": "uvx",
          "args": ["mcp-server-name", "--additional-args"],
          "env": {
            "API_KEY": "your_api_key_here"
          }
        }
      }
    }

Usage

  1. Run the client:

    bash
    python main.py
  2. Interact with the assistant:

    The assistant will automatically detect available tools and can respond to queries based on the tools provided by the configured servers.

  3. Exit the session:

    Type quit or exit to end the session.

Architecture

  • Tool Discovery: Tools are automatically discovered from configured servers.
  • System Prompt: Tools are dynamically included in the system prompt, allowing the LLM to understand available capabilities.
  • Server Integration: Supports any MCP-compatible server, tested with various server implementations including Uvicorn and Node.js.

Class Structure

  • Configuration: Manages environment variables and server configurations
  • Server: Handles MCP server initialization, tool discovery, and execution
  • Tool: Represents individual tools with their properties and formatting
  • LLMClient: Manages communication with the LLM provider
  • ChatSession: Orchestrates the interaction between user, LLM, and tools

Logic Flow

  1. Tool Integration:

    • Tools are dynamically discovered from MCP servers
    • Tool descriptions are automatically included in system prompt
    • Tool execution is handled through standardized MCP protocol
  2. Runtime Flow:

    • User input is received
    • Input is sent to LLM with context of available tools
    • LLM response is parsed:
      • If it's a tool call โ†’ execute tool and return result
      • If it's a direct response โ†’ return to user
    • Tool results are sent back to LLM for interpretation
    • Final response is presented to user

File: examples/clients/simple-auth-client/README.md

Simple Auth Client Example

A demonstration of how to use the MCP Python SDK with OAuth authentication over streamable HTTP or SSE transport.

Features

  • OAuth 2.0 authentication with PKCE
  • Support for both StreamableHTTP and SSE transports
  • Interactive command-line interface

Installation

bash
cd examples/clients/simple-auth-client
uv sync --reinstall

Usage

1. Start an MCP server with OAuth support

The simple-auth server example provides three server configurations. See examples/servers/simple-auth/README.md for full details.

Separate Authorization Server and Resource Server:

bash
# Terminal 1: Start Authorization Server on port 9000
cd examples/servers/simple-auth
uv run mcp-simple-auth-as --port=9000

# Terminal 2: Start Resource Server on port 8001
cd examples/servers/simple-auth
uv run mcp-simple-auth-rs --port=8001 --auth-server=http://localhost:9000 --transport=streamable-http

Option B: Legacy Server (Backwards Compatibility)

bash
# Single server that acts as both AS and RS (port 8000)
cd examples/servers/simple-auth
uv run mcp-simple-auth-legacy --port=8000 --transport=streamable-http

2. Run the client

bash
# Connect to Resource Server (new architecture, default port 8001)
MCP_SERVER_PORT=8001 uv run mcp-simple-auth-client

# Connect to Legacy Server (port 8000)
uv run mcp-simple-auth-client

# Use SSE transport
MCP_SERVER_PORT=8001 MCP_TRANSPORT_TYPE=sse uv run mcp-simple-auth-client

3. Complete OAuth flow

The client will open your browser for authentication. After completing OAuth, you can use commands:

  • list - List available tools
  • call <tool_name> [args] - Call a tool with optional JSON arguments
  • quit - Exit

Example

markdown
๐Ÿš€ Simple MCP Auth Client
Connecting to: http://localhost:8001/mcp
Transport type: streamable-http

๐Ÿ”— Attempting to connect to http://localhost:8001/mcp...
๐Ÿ“ก Opening StreamableHTTP transport connection with auth...
Opening browser for authorization: http://localhost:9000/authorize?...

โœ… Connected to MCP server at http://localhost:8001/mcp

mcp> list
๐Ÿ“‹ Available tools:
1. get_time
mcp> call get_time
๐Ÿ”ง Tool 'get_time' result:
{"current_time": "2024-01-15T10:30:00", "timezone": "UTC", ...}

mcp> quit

Configuration

Environment Variable Description Default
MCP_SERVER_PORT Port number of the MCP server 8000
MCP_TRANSPORT_TYPE Transport type: streamable-http or sse streamable-http
MCP_CLIENT_METADATA_URL Optional URL for client metadata (CIMD) None

File: examples/servers/simple-tool/README.md

A simple MCP server that exposes a website fetching tool.

Usage

Start the server using either stdio (default) or Streamable HTTP transport:

bash
# Using stdio transport (default)
uv run mcp-simple-tool

# Using Streamable HTTP transport on custom port
uv run mcp-simple-tool --transport streamable-http --port 8000

The server exposes a tool named "fetch" that accepts one required argument:

  • url: The URL of the website to fetch

Example

Using the MCP client, you can use the tool like this using the STDIO transport:

python
import asyncio
from mcp.client.session import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client


async def main():
    async with stdio_client(
        StdioServerParameters(command="uv", args=["run", "mcp-simple-tool"])
    ) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # List available tools
            tools = await session.list_tools()
            print(tools)

            # Call the fetch tool
            result = await session.call_tool("fetch", {"url": "https://example.com"})
            print(result)


asyncio.run(main())

File: examples/servers/simple-streamablehttp-stateless/README.md

MCP Simple StreamableHttp Stateless Server Example

A stateless MCP server example demonstrating the StreamableHttp transport without maintaining session state. This example is ideal for understanding how to deploy MCP servers in multi-node environments where requests can be routed to any instance.

Features

  • Uses the StreamableHTTP transport in stateless mode (mcp_session_id=None)
  • Each request creates a new ephemeral connection
  • No session state maintained between requests
  • Suitable for deployment in multi-node environments

Usage

Start the server:

bash
# Using default port 3000
uv run mcp-simple-streamablehttp-stateless

# Using custom port
uv run mcp-simple-streamablehttp-stateless --port 3000

# Custom logging level
uv run mcp-simple-streamablehttp-stateless --log-level DEBUG

# Enable JSON responses instead of SSE streams
uv run mcp-simple-streamablehttp-stateless --json-response

The server exposes a tool named "start-notification-stream" that accepts three arguments:

  • interval: Time between notifications in seconds (e.g., 1.0)
  • count: Number of notifications to send (e.g., 5)
  • caller: Identifier string for the caller

Client

You can connect to this server using an HTTP client. For now, only the TypeScript SDK has streamable HTTP client examples, or you can use Inspector for testing.


File: examples/servers/simple-streamablehttp/README.md

MCP Simple StreamableHttp Server Example

A simple MCP server example demonstrating the StreamableHttp transport, which enables HTTP-based communication with MCP servers using streaming.

Features

  • Uses the StreamableHTTP transport for server-client communication
  • Supports REST API operations (POST, GET, DELETE) for /mcp endpoint
  • Ability to send multiple notifications over time to the client
  • Resumability support via InMemoryEventStore

Usage

Start the server on the default or custom port:

bash
# Using custom port
uv run mcp-simple-streamablehttp --port 3000

# Custom logging level
uv run mcp-simple-streamablehttp --log-level DEBUG

# Enable JSON responses instead of SSE streams
uv run mcp-simple-streamablehttp --json-response

The server exposes a tool named "start-notification-stream" that accepts three arguments:

  • interval: Time between notifications in seconds (e.g., 1.0)
  • count: Number of notifications to send (e.g., 5)
  • caller: Identifier string for the caller

Resumability Support

This server includes resumability support through the InMemoryEventStore. This enables clients to:

  • Reconnect to the server after a disconnection
  • Resume event streaming from where they left off using the Last-Event-ID header

The server will:

  • Generate unique event IDs for each SSE message
  • Store events in memory for later replay
  • Replay missed events when a client reconnects with a Last-Event-ID header

Note: The InMemoryEventStore is designed for demonstration purposes only. For production use, consider implementing a persistent storage solution.

Client

You can connect to this server using an HTTP client, for now only Typescript SDK has streamable HTTP client examples or you can use Inspector


File: examples/servers/simple-resource/README.md

MCP Simple Resource

A simple MCP server that exposes sample text files as resources.

Usage

Start the server using either stdio (default) or Streamable HTTP transport:

bash
# Using stdio transport (default)
uv run mcp-simple-resource

# Using Streamable HTTP transport on custom port
uv run mcp-simple-resource --transport streamable-http --port 8000

The server exposes some basic text file resources that can be read by clients.

Example

Using the MCP client, you can retrieve resources like this using the STDIO transport:

python
import asyncio
from pydantic import AnyUrl
from mcp.client.session import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client


async def main():
    async with stdio_client(
        StdioServerParameters(command="uv", args=["run", "mcp-simple-resource"])
    ) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # List available resources
            resources = await session.list_resources()
            print(resources)

            # Get a specific resource
            resource = await session.read_resource(AnyUrl("file:///greeting.txt"))
            print(resource)


asyncio.run(main())

File: examples/servers/simple-prompt/README.md

MCP Simple Prompt

A simple MCP server that exposes a customizable prompt template with optional context and topic parameters.

Usage

Start the server using either stdio (default) or Streamable HTTP transport:

bash
# Using stdio transport (default)
uv run mcp-simple-prompt

# Using Streamable HTTP transport on custom port
uv run mcp-simple-prompt --transport streamable-http --port 8000

The server exposes a prompt named "simple" that accepts two optional arguments:

  • context: Additional context to consider
  • topic: Specific topic to focus on

Example

Using the MCP client, you can retrieve the prompt like this using the STDIO transport:

python
import asyncio
from mcp.client.session import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client


async def main():
    async with stdio_client(
        StdioServerParameters(command="uv", args=["run", "mcp-simple-prompt"])
    ) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # List available prompts
            prompts = await session.list_prompts()
            print(prompts)

            # Get the prompt with arguments
            prompt = await session.get_prompt(
                "simple",
                {
                    "context": "User is a software developer",
                    "topic": "Python async programming",
                },
            )
            print(prompt)


asyncio.run(main())

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