1. Project Overview & Quickstart (modelcontextprotocol/typescript-sdk)
File: README.md
MCP TypeScript SDK
[!IMPORTANT]
This is themainbranch โ v2 of the SDK (@modelcontextprotocol/server,@modelcontextprotocol/client), implementing the 2026-07-28 MCP spec.Have feedback? Please open a v2 issue โ it is the most useful thing you can do for the SDK right now. The v2 documentation starts with a ten-minute server tutorial.
v2 is the stable release line, released alongside the 2026-07-28 spec. v1.x continues to receive bug fixes and security updates for at least 6 months after v2's release. v1 documentation: ts.sdk.modelcontextprotocol.io ยท v2:
/v2/.
[!WARNING]
We're limiting pull requests to 1 per new contributor while v2 settles after the 2026-07-28 spec release.Issues are the most useful feedback right now โ we'll reopen PRs as v2 stabilizes.
Table of Contents
Overview
The Model Context Protocol (MCP) allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction.
This repository contains the TypeScript SDK implementation of the MCP specification. It runs on Node.js, Bun, and Deno, and ships:
- MCP server libraries (tools/resources/prompts, Streamable HTTP, stdio, auth helpers)
- MCP client libraries (transports, high-level helpers, OAuth helpers)
- Optional middleware packages for specific runtimes/frameworks (Express, Fastify, Hono, Node.js HTTP)
- Runnable examples (under
examples/)
Packages
This monorepo publishes split packages:
@modelcontextprotocol/server: build MCP servers@modelcontextprotocol/client: build MCP clients
Tool and prompt schemas use Standard Schema โ bring Zod v4, Valibot, ArkType, or any compatible library.
Middleware packages (optional)
The SDK also publishes small "middleware" packages under packages/middleware/ that help you wire MCP into a specific runtime or web framework.
They are intentionally thin adapters: they should not introduce new MCP functionality or business logic. See packages/middleware/README.md for details.
@modelcontextprotocol/node: Node.js Streamable HTTP transport wrapper forIncomingMessage/ServerResponse@modelcontextprotocol/express: Express helpers (app defaults + Host header validation)@modelcontextprotocol/fastify: Fastify helpers (app defaults + Host header validation)@modelcontextprotocol/hono: Hono helpers (app defaults + JSON body parsing hook + Host header validation)
Installation
Server
npm install @modelcontextprotocol/server
# or
bun add @modelcontextprotocol/server
# or
deno add npm:@modelcontextprotocol/serverClient
npm install @modelcontextprotocol/client
# or
bun add @modelcontextprotocol/client
# or
deno add npm:@modelcontextprotocol/clientOptional middleware packages
The SDK also publishes optional โmiddlewareโ packages that help you wire MCP into a specific runtime or web framework (for example Express, Fastify, Hono, or Node.js http).
These packages are intentionally thin adapters and should not introduce additional MCP features or business logic. See packages/middleware/README.md for details.
# Node.js HTTP (IncomingMessage/ServerResponse) Streamable HTTP transport:
npm install @modelcontextprotocol/node
# Express integration:
npm install @modelcontextprotocol/express express
# Fastify integration:
npm install @modelcontextprotocol/fastify fastify
# Hono integration:
npm install @modelcontextprotocol/hono honoGetting Started
Here is what an MCP server looks like. This minimal example exposes a single greet tool over stdio:
import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
const server = new McpServer({ name: 'greeting-server', version: '1.0.0' });
server.registerTool(
'greet',
{
inputSchema: z.object({ name: z.string() })
},
async ({ name }) => ({
content: [{ type: 'text', text: `Hello, ${name}!` }]
})
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main();Ready to build something real? Follow the step-by-step tutorials:
- Build your first server โ a stdio weather-alert server, from
npm initto a tool call - Build your first client โ connect to that server, list its tools, and call them
For runnable, end-to-end examples beyond the tutorials, see:
examples/README.mdโ runnable, self-verifying client/server example pairs (one story per directory)
Documentation
- Build a server โ your first MCP server, step by step
- Build a client โ your first MCP client, step by step
- Documentation site โ the full guides: tools, resources, prompts, serving over HTTP and stdio, clients, OAuth, and migration
- Troubleshooting โ common errors and their fixes
- API reference
- MCP documentation
- MCP specification
Building docs locally
To work on the documentation site locally:
pnpm docs:api # Generate the API reference markdown (output: docs/api/)
pnpm docs:dev # Start the VitePress dev server for the V2 site
pnpm docs:build # Build the V2 site (output: docs/.vitepress/dist/)
pnpm docs:multi # Build the combined V1 + V2 site (output: tmp/docs-combined/)The docs:multi script builds the V2 site from the current checkout, checks out the v1.x branch via a git worktree to build the V1 site, and produces a combined site with V1 docs at the root and V2 docs under /v2/.
v1 (legacy) documentation and fixes
If you are using the v1 generation of the SDK, the v1 API documentation is available at https://ts.sdk.modelcontextprotocol.io/. The v1 source code and any v1-specific fixes live on the long-livedv1.x branch. V2 API docs are at /v2/.
Contributing
Issues and pull requests are welcome on GitHub at https://github.com/modelcontextprotocol/typescript-sdk.
License
This project is licensed under the Apache License 2.0 for new contributions, with existing code under MIT. See the LICENSE file for details.
File: docs/index.md
shape: landing
MCP TypeScript SDK
::: info v2
This is the documentation for v2 of the SDK, the stable release line implementing the 2026-07-28 spec. Report issues โ and if you need v1, its documentation is at ts.sdk.modelcontextprotocol.io.
:::
The Model Context Protocol (MCP) is an open standard that connects AI applications to the systems where your data and tools live. You write a server that exposes tools, resources, and prompts; any MCP host โ Claude Code, VS Code, Cursor, your own application โ connects to it and lets a model use them. The protocol is defined by the MCP specification; this SDK is its TypeScript implementation, on Node.js, Bun, and Deno.
A complete server is one file:
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
serveStdio(() => {
const server = new McpServer({ name: 'weather', version: '1.0.0' });
server.registerTool(
'get-forecast',
{
inputSchema: z.object({ city: z.string() })
},
async ({ city }) => ({
content: [{ type: 'text', text: `Sunny in ${city} all week.` }]
})
);
return server;
});Any MCP host that launches this program lists and calls get-forecast; the SDK validates every call against that z.object(...) schema before your handler runs. Build a server installs the packages and runs it end to end.
Pick a path
- Expose your API or data to AI applications โ Build a server
- Build an application that talks to MCP servers โ Build a client
- Coming from v1 (
@modelcontextprotocol/sdk) โ Upgrade - Drop MCP into the app you already run โ Express ยท Hono ยท Fastify ยท Workers
For exact signatures, go to the API reference.
Recap
- MCP connects AI applications to the systems where your tools and data live; you build one side, a host brings the model.
registerTool(name, config, handler)with az.object(...)inputSchemadefines a tool;serveStdioserves it over stdio.- Four starting points: build a server, build a client, upgrade from v1, or drop into Express, Hono, Fastify, or Workers.
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:
MCP Inspector
- Interactive debugging interface
- Direct server testing
- See the Inspector guide for details
Claude Desktop Developer Tools
- Integration testing
- Log collection
- Chrome DevTools integration
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:
Click the icon to view:
- Connected servers
- Available prompts and resources
Click the icon to view:
- Tools made available to the model
Viewing logs
Review detailed MCP logs from Claude Desktop:
# Follow logs in real-time
tail -n 20 -F ~/Library/Logs/Claude/mcp*.logThe 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:
- Create a
developer_settings.jsonfile withallowDevToolsset to true:
echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json- 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.jsonmay be undefined (like/on macOS) since Claude Desktop could be started from anywhere - Always use absolute paths in your configuration and
.envfiles 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:
{
"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:
{
"myserver": {
"command": "mcp-server-myapp",
"env": {
"MYAPP_API_KEY": "some_key",
}
}
}Server initialization
Common initialization problems:
Path Issues
- Incorrect server executable path
- Missing required files
- Permission problems
- Try using an absolute path for
command
Configuration Errors
- Invalid JSON syntax
- Missing required fields
- Type mismatches
Environment Problems
- Missing environment variables
- Incorrect variable values
- Permission restrictions
Connection problems
When servers fail to connect:
- Check Claude Desktop logs
- Verify server process is running
- Test standalone with Inspector
- 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.
For all transports, you can also provide logging to the client by sending a log message notification:
Important events to log:
- Initialization steps
- Resource access
- Tool execution
- Error conditions
- Performance metrics
Client-side logging
In client applications:
- Enable debug logging
- Monitor network traffic
- Track message exchanges
- Record error states
Debugging workflow
Development cycle
Initial Development
- Use Inspector for basic testing
- Implement core functionality
- Add logging points
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
Structured Logging
- Use consistent formats
- Include context
- Add timestamps
- Track request IDs
Error Handling
- Log stack traces
- Include error context
- Track error patterns
- Monitor recovery
Performance Tracking
- Log operation timing
- Monitor resource usage
- Track message sizes
- Measure latency
Security considerations
When debugging:
Sensitive Data
- Sanitize logs
- Protect credentials
- Mask personal information
Access Control
- Verify permissions
- Check authentication
- Monitor access patterns
Getting help
When encountering issues:
First Steps
- Check server logs
- Test with Inspector
- Review configuration
- Verify environment
Support Channels
- GitHub issues
- GitHub discussions
Providing Information
- Log excerpts
- Configuration files
- Steps to reproduce
- Environment details
Next steps
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:
npx @modelcontextprotocol/inspector <command>npx @modelcontextprotocol/inspector <command> <arg1> <arg2>Inspecting servers from NPM or PyPi
A common way to start server packages from NPM or PyPi.
Inspecting locally developed servers
To inspect servers locally developed or downloaded as a repository, the most common
way is:
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
Start Development
- Launch Inspector with your server
- Verify basic connectivity
- Check capability negotiation
Iterative testing
- Make server changes
- Rebuild the server
- Reconnect the Inspector
- Test affected features
- Monitor messages
Test edge cases
- Invalid inputs
- Missing prompt arguments
- Concurrent operations
- Verify error handling and error responses
Next steps
<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
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| server2Core components
Protocol layer
The protocol layer handles message framing, request/response linking, and high-level communication patterns.
// 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>
}
```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:
ProtocolClientServer
Transport layer
The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:
Stdio transport
- Uses standard input/output for communication
- Ideal for local processes
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:
Requests expect a response from the other side:
typescriptinterface Request { method: string; params?: { ... }; }Results are successful responses to requests:
typescriptinterface Result { [key: string]: unknown; }Errors indicate that a request failed:
typescriptinterface Error { code: number; message: string; data?: unknown; }Notifications are one-way messages that don't expect a response:
typescriptinterface Notification { method: string; params?: { ... }; }
Connection lifecycle
1. Initialization
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- Client sends
initializerequest with protocol version and capabilities - Server responds with its protocol version and capabilities
- Client sends
initializednotification as acknowledgment - 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:
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:
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);
```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
Local communication
- Use stdio transport for local processes
- Efficient for same-machine communication
- Simple process management
Remote communication
- Use SSE for scenarios requiring HTTP compatibility
- Consider security implications including authentication and authorization
Message handling
Request processing
- Validate inputs thoroughly
- Use type-safe schemas
- Handle errors gracefully
- Implement timeouts
Progress reporting
- Use progress tokens for long operations
- Report progress incrementally
- Include total progress when known
Error management
- Use appropriate error codes
- Include helpful error messages
- Clean up resources on errors
Security considerations
Transport security
- Use TLS for remote connections
- Validate connection origins
- Implement authentication when needed
Message validation
- Validate all incoming messages
- Sanitize inputs
- Check message size limits
- Verify JSON-RPC format
Resource protection
- Implement access controls
- Validate resource paths
- Monitor resource usage
- Rate limit requests
Error handling
- Don't leak sensitive information
- Log security-relevant errors
- Implement proper cleanup
- Handle DoS scenarios
Debugging and monitoring
Logging
- Log protocol events
- Track message flow
- Monitor performance
- Record errors
Diagnostics
- Implement health checks
- Monitor connection state
- Track resource usage
- Profile performance
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.
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:
{
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:
// 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:
// 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
{
"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:
{
"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
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:
Best practices
When implementing prompts:
- Use clear, descriptive prompt names
- Provide detailed descriptions for prompts and arguments
- Validate all required arguments
- Handle missing arguments gracefully
- Consider versioning for prompt templates
- Cache dynamic content when appropriate
- Implement error handling
- Document expected argument formats
- Consider prompt composability
- 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:
- Server capability:
prompts.listChanged - Notification:
notifications/prompts/list_changed - 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.
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:
[protocol]://[host]/[path]For example:
file:///home/user/documents/report.pdfpostgres://database/customers/schemascreen://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:
{
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:
{
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:
{
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)
}
]
}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:
- Client sends
resources/subscribewith resource URI - Server sends
notifications/resources/updatedwhen the resource changes - Client can fetch latest content with
resources/read - Client can unsubscribe with
resources/unsubscribe
Example implementation
Here's a simple example of implementing resource support in an MCP server:
// 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");
});
```@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:
- Use clear, descriptive resource names and URIs
- Include helpful descriptions to guide LLM understanding
- Set appropriate MIME types when known
- Implement resource templates for dynamic content
- Use subscriptions for frequently changing resources
- Handle errors gracefully with clear error messages
- Consider pagination for large resource lists
- Cache resource contents when appropriate
- Validate URIs before processing
- 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:
file:///home/user/projects/myapp
https://api.example.com/v1Why Use Roots?
Roots serve several important purposes:
- Guidance: They inform servers about relevant resources and locations
- Clarity: Roots make it clear which resources are part of your workspace
- Organization: Multiple roots let you work with different resources simultaneously
How Roots Work
When a client supports roots, it:
- Declares the
rootscapability during connection - Provides a list of suggested roots to the server
- Notifies the server when roots change (if supported)
While roots are informational and not strictly enforcing, servers should:
- Respect the provided roots
- Use root URIs to locate and access resources
- 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:
- Only suggest necessary resources
- Use clear, descriptive names for roots
- Monitor root accessibility
- Handle root changes gracefully
Example
Here's how a typical MCP client might expose roots:
{
"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:
- Server sends a
sampling/createMessagerequest to the client - Client reviews the request and can modify it
- Client samples from an LLM
- Client reviews the completion
- 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:
{
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
textfield - Image content with
data(base64) andmimeTypefields
- Text content with a
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 costsspeedPriority: Importance of low latency responseintelligencePriority: 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 generatestopSequences: Array of sequences that stop generationmetadata: Additional provider-specific parameters
Response format
The client returns a completion result:
{
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:
{
"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:
- Always provide clear, well-structured prompts
- Handle both text and image content appropriately
- Set reasonable token limits
- Include relevant context through
includeContext - Validate responses before using them
- Handle errors gracefully
- Consider rate limiting sampling requests
- Document expected sampling behavior
- Test with various model parameters
- 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.
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/listendpoint - Invocation: Tools are called using the
tools/callendpoint, 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:
{
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:
// 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");
});
```@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:
{
name: "execute_command",
inputSchema: {
type: "object",
properties: {
command: { type: "string" },
args: { type: "array", items: { type: "string" } }
}
}
}API integrations
Tools that wrap external APIs:
{
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:
{
name: "analyze_csv",
inputSchema: {
type: "object",
properties: {
filepath: { type: "string" },
operations: {
type: "array",
items: {
enum: ["sum", "average", "count"]
}
}
}
}
}Best practices
When implementing tools:
- Provide clear, descriptive names and descriptions
- Use detailed JSON Schema definitions for parameters
- Include examples in tool descriptions to demonstrate how the model should use them
- Implement proper error handling and validation
- Use progress reporting for long operations
- Keep tool operations focused and atomic
- Document expected return value structures
- Implement proper timeouts
- Consider rate limiting for resource-intensive operations
- 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:
- Clients can list available tools at any time
- Servers can notify clients when tools change using
notifications/tools/list_changed - Tools can be added or removed during runtime
- 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:
- Set
isErrortotruein the result - Include error details in the
contentarray
Here's an example of proper error handling for tools:
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
{
jsonrpc: "2.0",
id: number | string,
method: string,
params?: object
}Responses
{
jsonrpc: "2.0",
id: number | string,
result?: object,
error?: {
code: number,
message: string,
data?: unknown
}
}Notifications
{
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
const transport = new StdioServerTransport();
await server.connect(transport);
```const transport = new StdioClientTransport({
command: "./server",
args: ["--option", "value"]
});
await client.connect(transport);
```async with stdio_server() as streams:
await app.run(
streams[0],
streams[1],
app.create_initialization_options()
)
```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
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);
```const transport = new SSEClientTransport(
new URL("http://localhost:3000/sse")
);
await client.connect(transport);
```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"]),
]
)
```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
// 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;
}
```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:
- Connection errors
- Message parsing errors
- Protocol errors
- Network timeouts
- Resource cleanup
Example error handling:
async send(message: JSONRPCMessage) {
try {
// Sending logic
} catch (error) {
this.onerror?.(new Error(`Failed to send message: ${error}`));
throw error;
}
}
}
```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:
- Handle connection lifecycle properly
- Implement proper error handling
- Clean up resources on connection close
- Use appropriate timeouts
- Validate messages before sending
- Log transport events for debugging
- Implement reconnection logic when appropriate
- Handle backpressure in message queues
- Monitor connection health
- 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:
- Enable debug logging
- Monitor message flow
- Check connection states
- Validate message formats
- Test error scenarios
- Use network analysis tools
- Implement health checks
- Monitor resource usage
- Test edge cases
- Use proper error tracking