```
├── .gitattributes
├── .github/
├── workflows/
├── main.yml
├── markdown-format.yml
├── .gitignore
├── .npmrc
├── .nvmrc
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── docs/
├── clients.mdx
├── development/
├── contributing.mdx
├── roadmap.mdx
├── updates.mdx
├── docs.json
├── docs/
├── concepts/
├── architecture.mdx
├── prompts.mdx
├── resources.mdx
├── roots.mdx
├── sampling.mdx
├── tools.mdx
├── transports.mdx
├── tools/
├── debugging.mdx
├── inspector.mdx
├── examples.mdx
├── faqs.mdx
├── favicon.svg
├── images/
├── available-mcp-tools.png
├── claude-desktop-mcp-hammer-icon.svg
├── claude-desktop-mcp-plug-icon.svg
├── client-claude-cli-python.png
├── current-weather.png
├── hero-dark.svg
├── hero-light.svg
├── java/
├── class-diagrams.puml
├── java-mcp-client-architecture.jpg
├── java-mcp-server-architecture.jpg
├── java-mcp-uml-classdiagram.svg
├── mcp-stack.svg
```
## /.gitattributes
```gitattributes path="/.gitattributes"
package-lock.json linguist-generated=true
```
## /.github/workflows/main.yml
```yml path="/.github/workflows/main.yml"
on:
push:
branches:
- main
pull_request:
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run validate:schema
- run: npm run generate:json
- name: Verify that `npm run generate:json` did not change outputs (if it did, please re-run it and re-commit!)
run: git diff --exit-code
```
## /.github/workflows/markdown-format.yml
```yml path="/.github/workflows/markdown-format.yml"
name: Markdown Format Check
on:
push:
paths:
- '**/*.md'
pull_request:
paths:
- '**/*.md'
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Check markdown formatting
run: npm run format:check
```
## /.gitignore
```gitignore path="/.gitignore"
node_modules/
.DS_Store
```
## /.npmrc
```npmrc path="/.npmrc"
registry = "https://registry.npmjs.org/"
```
## /.nvmrc
```nvmrc path="/.nvmrc"
v20.16.0
```
## /CODE_OF_CONDUCT.md
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a
harassment-free experience for everyone, regardless of age, body size, visible or
invisible disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal appearance,
race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse,
inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community
include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and
learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without
their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional
setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in response to
any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments,
commits, code, wiki edits, issues, and other contributions that are not aligned to this
Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an
individual is officially representing the community in public spaces. Examples of
representing our community include using an official e-mail address, posting via an
official social media account, or acting as an appointed representative at an online or
offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to
the community leaders responsible for enforcement at mcp-coc@anthropic.com. All
complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter
of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the
consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity
around the nature of the violation and an explanation of why the behavior was
inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with
the people involved, including unsolicited interaction with those enforcing the Code of
Conduct, for a specified period of time. This includes avoiding interactions in community
spaces as well as external channels like social media. Violating these terms may lead to
a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained
inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication
with the community for a specified period of time. No public or private interaction with
the people involved, including unsolicited interaction with those enforcing the Code of
Conduct, is allowed during this period. Violating these terms may lead to a permanent
ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards,
including sustained inappropriate behavior, harassment of an individual, or aggression
toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
## /CONTRIBUTING.md
# Contributing to Model Context Protocol
Thank you for your interest in contributing to the Model Context Protocol specification!
This document outlines how to contribute to this project.
## Prerequisites
The following software is required to work on the spec:
- Node.js 20 or above
- TypeScript
- TypeScript JSON Schema (for generating JSON schema)
- [Mintlify](https://mintlify.com/) (optional, for docs)
- nvm (optional, for managing Node versions)
## Getting Started
1. Fork the repository
2. Clone your fork:
```bash
git clone https://github.com/YOUR-USERNAME/specification.git
cd specification
```
3. Install dependencies:
```bash
nvm install # install correct Node version
npm install # install dependencies
```
## Making Changes
Note that schema changes are made to `schema.ts`. `schema.json` is generated from
`schema.ts` using `npm run validate:schema`.
1. Create a new branch:
```bash
git checkout -b feature/your-feature-name
```
2. Make your changes
3. Validate your changes:
```bash
npm run validate:schema # validate schema
npm run generate:json # generate JSON schema
```
4. Run docs locally (optional):
```bash
npm run serve:docs
```
### Documentation Guidelines
When contributing to the documentation:
- Keep content clear, concise, and technically accurate
- Follow the existing file structure and naming conventions
- Include code examples where appropriate
- Use proper MDX formatting and components
- Test all links and code samples
- Use appropriate headings: "When to use", "Steps", and "Tips" for tutorials
- Place new pages in appropriate sections (concepts, tutorials, etc.)
- Update docs.json when adding new pages
- Follow existing file naming conventions (kebab-case.mdx)
- Include proper frontmatter in MDX files
## Submitting Changes
1. Push your changes to your fork
2. Submit a pull request to the main repository
3. Follow the pull request template
4. Wait for review
## Code of Conduct
This project follows a Code of Conduct. Please review it in
[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
## Questions
If you have questions, please create an issue in the repository.
## License
By contributing, you agree that your contributions will be licensed under the MIT
License.
## Security
Please review our [Security Policy](SECURITY.md) for reporting security issues.
## /LICENSE
``` path="/LICENSE"
MIT License
Copyright (c) 2024–2025 Anthropic, PBC and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## /README.md
# Model Context Protocol specification
This repo contains the specification and protocol schema for the Model Context Protocol.
The schema is [defined in TypeScript](schema/2025-03-26/schema.ts) first, but
[made available as JSON Schema](schema/2025-03-26/schema.json) as well, for wider
compatibility.
The official MCP documentation is built using Mintlify and available at
[modelcontextprotocol.io](https://modelcontextprotocol.io).
## Contributing
Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this
project.
## License
This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for
details.
## /SECURITY.md
# Security Policy
Thank you for helping us keep the SDKs and systems they interact with secure.
## Reporting Security Issues
This SDK is maintained by [Anthropic](https://www.anthropic.com/) as part of the Model
Context Protocol project.
The security of our systems and user data is Anthropic’s top priority. We appreciate the
work of security researchers acting in good faith in identifying and reporting potential
vulnerabilities.
Our security program is managed on HackerOne and we ask that any validated vulnerability
in this functionality be reported through their
[submission form](https://hackerone.com/anthropic-vdp/reports/new?type=team&report_type=vulnerability).
## Vulnerability Disclosure Program
Our Vulnerability Program Guidelines are defined on our
[HackerOne program page](https://hackerone.com/anthropic-vdp).
## /docs/clients.mdx
---
title: "Example Clients"
description: "A list of applications that support MCP integrations"
---
This page provides an overview of applications that support the Model Context Protocol (MCP). Each client may support different MCP features, allowing for varying levels of integration with MCP servers.
## Feature support matrix
| Client | [Resources] | [Prompts] | [Tools] | [Sampling] | Roots | Notes |
|---------------------------------------------|-------------|-----------|---------|------------|--------|-----------------------------------------------------------------------------|
| [5ire][5ire] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. |
| [Apify MCP Tester][Apify MCP Tester] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools |
| [BeeAI Framework][BeeAI Framework] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools in agentic workflows. |
| [Claude Code][Claude Code] | ❌ | ✅ | ✅ | ❌ | ❌ | Supports prompts and tools |
| [Claude Desktop App][Claude Desktop] | ✅ | ✅ | ✅ | ❌ | ❌ | Supports tools, prompts, and resources. |
| [Cline][Cline] | ✅ | ❌ | ✅ | ❌ | ❌ | Supports tools and resources. |
| [Continue][Continue] | ✅ | ✅ | ✅ | ❌ | ❌ | Supports tools, prompts, and resources. |
| [Copilot-MCP][CopilotMCP] | ✅ | ❌ | ✅ | ❌ | ❌ | Supports tools and resources. |
| [Cursor][Cursor] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. |
| [Daydreams Agents][Daydreams] | ✅ | ✅ | ✅ | ❌ | ❌ | Support for drop in Servers to Daydreams agents |
| [Emacs Mcp][Mcp.el] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools in Emacs. |
| [fast-agent][fast-agent] | ✅ | ✅ | ✅ | ✅ | ✅ | Full multimodal MCP support, with end-to-end tests |
| [FLUJO][FLUJO] | ❌ | ❌ | ✅ | ❌ | ❌ | Support for resources, Prompts and Roots are coming soon |
| [Genkit][Genkit] | ⚠️ | ✅ | ✅ | ❌ | ❌ | Supports resource list and lookup through tools. |
| [GenAIScript][GenAIScript] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. |
| [Goose][Goose] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. |
| [gptme][gptme] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. |
| [Klavis AI Slack/Discord/Web][Klavis AI] | ✅ | ❌ | ✅ | ❌ | ❌ | Supports tools and resources. |
| [LibreChat][LibreChat] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools for Agents |
| [Lutra][Lutra] | ✅ | ✅ | ✅ | ❌ | ❌ | Supports any MCP server for reusable playbook creation. |
| [mcp-agent][mcp-agent] | ❌ | ❌ | ✅ | ⚠️ | ❌ | Supports tools, server connection management, and agent workflows. |
| [MCPHub][MCPHub] | ✅ | ✅ | ✅ | ❌ | ❌ | Supports tools, resources, and prompts in Neovim
| [MCPOmni-Connect][MCPOmni-Connect] | ✅ | ✅ | ✅ | ✅ | ❌ | Supports tools with agentic mode, ReAct, and orchestrator capabilities. |
| [Microsoft Copilot Studio] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools |
| [MindPal][MindPal] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools for no-code AI agents and multi-agent workflows. |
| [OpenSumi][OpenSumi] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools in OpenSumi |
| [oterm][oterm] | ❌ | ✅ | ✅ | ✅ | ❌ | Supports tools, prompts and sampling for Ollama. |
| [Roo Code][Roo Code] | ✅ | ❌ | ✅ | ❌ | ❌ | Supports tools and resources. |
| [Sourcegraph Cody][Cody] | ✅ | ❌ | ❌ | ❌ | ❌ | Supports resources through OpenCTX |
| [SpinAI][SpinAI] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools for Typescript AI Agents |
| [Superinterface][Superinterface] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools |
| [TheiaAI/TheiaIDE][TheiaAI/TheiaIDE] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools for Agents in Theia AI and the AI-powered Theia IDE |
| [TypingMind App][TypingMind App] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools at app-level (appear as plugins) or when assigned to Agents |
| [VS Code GitHub Copilot][VS Code] | ❌ | ❌ | ✅ | ❌ | ✅ | Supports dynamic tool/roots discovery, secure secret configuration, and explicit tool prompting |
| [Windsurf Editor][Windsurf] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools with AI Flow for collaborative development. |
| [Witsy][Witsy] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools in Witsy. |
| [Zed][Zed] | ❌ | ✅ | ❌ | ❌ | ❌ | Prompts appear as slash commands |
[5ire]: https://github.com/nanbingxyz/5ire
[Apify MCP Tester]: https://apify.com/jiri.spilka/tester-mcp-client
[BeeAI Framework]: https://i-am-bee.github.io/beeai-framework
[Claude Code]: https://claude.ai/code
[Claude Desktop]: https://claude.ai/download
[Cline]: https://github.com/cline/cline
[Continue]: https://github.com/continuedev/continue
[CopilotMCP]: https://github.com/VikashLoomba/copilot-mcp
[Cursor]: https://cursor.com
[Daydreams]: https://github.com/daydreamsai/daydreams
[Klavis AI]: https://www.klavis.ai/
[Mcp.el]: https://github.com/lizqwerscott/mcp.el
[fast-agent]: https://github.com/evalstate/fast-agent
[FLUJO]: https://github.com/mario-andreschak/flujo
[Genkit]: https://github.com/firebase/genkit
[GenAIScript]: https://microsoft.github.io/genaiscript/reference/scripts/mcp-tools/
[Goose]: https://block.github.io/goose/docs/goose-architecture/#interoperability-with-extensions
[LibreChat]: https://github.com/danny-avila/LibreChat
[Lutra]: https://lutra.ai
[mcp-agent]: https://github.com/lastmile-ai/mcp-agent
[MCPHub]: https://github.com/ravitemer/mcphub.nvim
[MCPOmni-Connect]: https://github.com/Abiorh001/mcp_omni_connect
[Microsoft Copilot Studio]: https://learn.microsoft.com/en-us/microsoft-copilot-studio/agent-extend-action-mcp
[MindPal]: https://mindpal.io
[OpenSumi]: https://github.com/opensumi/core
[oterm]: https://github.com/ggozad/oterm
[Roo Code]: https://roocode.com
[Cody]: https://sourcegraph.com/cody
[SpinAI]: https://spinai.dev
[Superinterface]: https://superinterface.ai
[TheiaAI/TheiaIDE]: https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/
[TypingMind App]: https://www.typingmind.com
[VS Code]: https://code.visualstudio.com/
[Windsurf]: https://codeium.com/windsurf
[gptme]: https://github.com/gptme/gptme
[Witsy]: https://github.com/nbonamy/witsy
[Zed]: https://zed.dev
[Resources]: https://modelcontextprotocol.io/docs/concepts/resources
[Prompts]: https://modelcontextprotocol.io/docs/concepts/prompts
[Tools]: https://modelcontextprotocol.io/docs/concepts/tools
[Sampling]: https://modelcontextprotocol.io/docs/concepts/sampling
## Client details
### 5ire
[5ire](https://github.com/nanbingxyz/5ire) is an open source cross-platform desktop AI assistant that supports tools through MCP servers.
**Key features:**
- Built-in MCP servers can be quickly enabled and disabled.
- Users can add more servers by modifying the configuration file.
- It is open-source and user-friendly, suitable for beginners.
- Future support for MCP will be continuously improved.
### Apify MCP Tester
[Apify MCP Tester](https://github.com/apify/tester-mcp-client) is an open-source client that connects to any MCP server using Server-Sent Events (SSE).
It is a standalone Apify Actor designed for testing MCP servers over SSE, with support for Authorization headers.
It uses plain JavaScript (old-school style) and is hosted on Apify, allowing you to run it without any setup.
**Key features:**
- Connects to any MCP server via SSE.
- Works with the [Apify MCP Server](https://apify.com/apify/actors-mcp-server) to interact with one or more Apify [Actors](https://apify.com/store).
- Dynamically utilizes tools based on context and user queries (if supported by the server).
### BeeAI Framework
[BeeAI Framework](https://i-am-bee.github.io/beeai-framework) is an open-source framework for building, deploying, and serving powerful agentic workflows at scale. The framework includes the **MCP Tool**, a native feature that simplifies the integration of MCP servers into agentic workflows.
**Key features:**
- Seamlessly incorporate MCP tools into agentic workflows.
- Quickly instantiate framework-native tools from connected MCP client(s).
- Planned future support for agentic MCP capabilities.
**Learn more:**
- [Example of using MCP tools in agentic workflow](https://i-am-bee.github.io/beeai-framework/#/typescript/tools?id=using-the-mcptool-class)
### Claude Code
Claude Code is an interactive agentic coding tool from Anthropic that helps you code faster through natural language commands. It supports MCP integration for prompts and tools, and also functions as an MCP server to integrate with other clients.
**Key features:**
- Tool and prompt support for MCP servers
- Offers its own tools through an MCP server for integrating with other MCP clients
### Claude Desktop App
The Claude desktop application provides comprehensive support for MCP, enabling deep integration with local tools and data sources.
**Key features:**
- Full support for resources, allowing attachment of local files and data
- Support for prompt templates
- Tool integration for executing commands and scripts
- Local server connections for enhanced privacy and security
> ⓘ Note: The Claude.ai web application does not currently support MCP. MCP features are only available in the desktop application.
### Cline
[Cline](https://github.com/cline/cline) is an autonomous coding agent in VS Code that edits files, runs commands, uses a browser, and more–with your permission at each step.
**Key features:**
- Create and add tools through natural language (e.g. "add a tool that searches the web")
- Share custom MCP servers Cline creates with others via the `~/Documents/Cline/MCP` directory
- Displays configured MCP servers along with their tools, resources, and any error logs
### Continue
[Continue](https://github.com/continuedev/continue) is an open-source AI code assistant, with built-in support for all MCP features.
**Key features**
- Type "@" to mention MCP resources
- Prompt templates surface as slash commands
- Use both built-in and MCP tools directly in chat
- Supports VS Code and JetBrains IDEs, with any LLM
### Copilot-MCP
[Copilot-MCP](https://github.com/VikashLoomba/copilot-mcp) enables AI coding assistance via MCP.
**Key features:**
- Support for MCP tools and resources
- Integration with development workflows
- Extensible AI capabilities
### Cursor
[Cursor](https://docs.cursor.com/advanced/model-context-protocol) is an AI code editor.
**Key Features**:
- Support for MCP tools in Cursor Composer
- Support for both STDIO and SSE
### Daydreams
[Daydreams](https://github.com/daydreamsai/daydreams) is a generative agent framework for executing anything onchain
**Key features:**
- Supports MCP Servers in config
- Exposes MCP Client
### Emacs Mcp
[Emacs Mcp](https://github.com/lizqwerscott/mcp.el) is an Emacs client designed to interface with MCP servers, enabling seamless connections and interactions. It provides MCP tool invocation support for AI plugins like [gptel](https://github.com/karthink/gptel) and [llm](https://github.com/ahyatt/llm), adhering to Emacs' standard tool invocation format. This integration enhances the functionality of AI tools within the Emacs ecosystem.
**Key features:**
- Provides MCP tool support for Emacs.
### fast-agent
[fast-agent](https://github.com/evalstate/fast-agent) is a Python Agent framework, with simple declarative support for creating Agents and Workflows, with full multi-modal support for Anthropic and OpenAI models.
**Key features:**
- PDF and Image support, based on MCP Native types
- Interactive front-end to develop and diagnose Agent applications, including passthrough and playback simulators
- Built in support for "Building Effective Agents" workflows.
- Deploy Agents as MCP Servers
### FLUJO
Think n8n + ChatGPT. FLUJO is an desktop application that integrates with MCP to provide a workflow-builder interface for AI interactions. Built with Next.js and React, it supports both online and offline (ollama) models, it manages API Keys and environment variables centrally and can install MCP Servers from GitHub. FLUJO has an ChatCompletions endpoint and flows can be executed from other AI applications like Cline, Roo or Claude.
**Key features:**
- Environment & API Key Management
- Model Management
- MCP Server Integration
- Workflow Orchestration
- Chat Interface
### Genkit
[Genkit](https://github.com/firebase/genkit) is a cross-language SDK for building and integrating GenAI features into applications. The [genkitx-mcp](https://github.com/firebase/genkit/tree/main/js/plugins/mcp) plugin enables consuming MCP servers as a client or creating MCP servers from Genkit tools and prompts.
**Key features:**
- Client support for tools and prompts (resources partially supported)
- Rich discovery with support in Genkit's Dev UI playground
- Seamless interoperability with Genkit's existing tools and prompts
- Works across a wide variety of GenAI models from top providers
### GenAIScript
Programmatically assemble prompts for LLMs using [GenAIScript](https://microsoft.github.io/genaiscript/) (in JavaScript). Orchestrate LLMs, tools, and data in JavaScript.
**Key features:**
- JavaScript toolbox to work with prompts
- Abstraction to make it easy and productive
- Seamless Visual Studio Code integration
### Goose
[Goose](https://github.com/block/goose) is an open source AI agent that supercharges your software development by automating coding tasks.
**Key features:**
- Expose MCP functionality to Goose through tools.
- MCPs can be installed directly via the [extensions directory](https://block.github.io/goose/v1/extensions/), CLI, or UI.
- Goose allows you to extend its functionality by [building your own MCP servers](https://block.github.io/goose/docs/tutorials/custom-extensions).
- Includes built-in tools for development, web scraping, automation, memory, and integrations with JetBrains and Google Drive.
### gptme
[gptme](https://github.com/gptme/gptme) is a open-source terminal-based personal AI assistant/agent, designed to assist with programming tasks and general knowledge work.
**Key features:**
- CLI-first design with a focus on simplicity and ease of use
- Rich set of built-in tools for shell commands, Python execution, file operations, and web browsing
- Local-first approach with support for multiple LLM providers
- Open-source, built to be extensible and easy to modify
### Klavis AI Slack/Discord/Web
[Klavis AI](https://www.klavis.ai/) is an Open-Source Infra to Use, Build & Scale MCPs with ease.
**Key features:**
- Slack/Discord/Web MCP clients for using MCPs directly
- Simple web UI dashboard for easy MCP configuration
- Direct OAuth integration with Slack & Discord Clients and MCP Servers for secure user authentication
- SSE transport support
- Open-source infrastructure ([GitHub repository](https://github.com/Klavis-AI/klavis))
**Learn more:**
- [Demo video showing MCP usage in Slack/Discord](https://youtu.be/9-QQAhrQWw8)
### LibreChat
[LibreChat](https://github.com/danny-avila/LibreChat) is an open-source, customizable AI chat UI that supports multiple AI providers, now including MCP integration.
**Key features:**
- Extend current tool ecosystem, including [Code Interpreter](https://www.librechat.ai/docs/features/code_interpreter) and Image generation tools, through MCP servers
- Add tools to customizable [Agents](https://www.librechat.ai/docs/features/agents), using a variety of LLMs from top providers
- Open-source and self-hostable, with secure multi-user support
- Future roadmap includes expanded MCP feature support
### Lutra
[Lutra](https://lutra.ai) is an AI agent that transforms conversations into actionable, automated workflows.
**Key features:**
- Easy MCP Integration: Connecting Lutra to MCP servers is as simple as providing the server URL; Lutra handles the rest behind the scenes.
- Chat to Take Action: Lutra understands your conversational context and goals, automatically integrating with your existing apps to perform tasks.
- Reusable Playbooks: After completing a task, save the steps as reusable, automated workflows—simplifying repeatable processes and reducing manual effort.
- Shareable Automations: Easily share your saved playbooks with teammates to standardize best practices and accelerate collaborative workflows.
**Learn more:**
- [Lutra AI agent explained](https://www.youtube.com/watch?v=W5ZpN0cMY70)
### mcp-agent
[mcp-agent] is a simple, composable framework to build agents using Model Context Protocol.
**Key features:**
- Automatic connection management of MCP servers.
- Expose tools from multiple servers to an LLM.
- Implements every pattern defined in [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents).
- Supports workflow pause/resume signals, such as waiting for human feedback.
### MCPHub
[MCPHub] is a powerful Neovim plugin that integrates MCP (Model Context Protocol) servers into your workflow.
**Key features**
- Install, configure and manage MCP servers with an intuitive UI.
- Built-in Neovim MCP server with support for file operations (read, write, search, replace), command execution, terminal integration, LSP integration, buffers, and diagnostics.
- Create Lua-based MCP servers directly in Neovim.
- Inegrates with popular Neovim chat plugins Avante.nvim and CodeCompanion.nvim
### MCPOmni-Connect
[MCPOmni-Connect](https://github.com/Abiorh001/mcp_omni_connect) is a versatile command-line interface (CLI) client designed to connect to various Model Context Protocol (MCP) servers using both stdio and SSE transport.
**Key features:**
- Support for resources, prompts, tools, and sampling
- Agentic mode with ReAct and orchestrator capabilities
- Seamless integration with OpenAI models and other LLMs
- Dynamic tool and resource management across multiple servers
- Support for both stdio and SSE transport protocols
- Comprehensive tool orchestration and resource analysis capabilities
### Microsoft Copilot Studio
[Microsoft Copilot Studio] is a robust SaaS platform designed for building custom AI-driven applications and intelligent agents, empowering developers to create, deploy, and manage sophisticated AI solutions.
**Key features:**
- Support for MCP tools
- Extend Copilot Studio agents with MCP servers
- Leveraging Microsoft unified, governed, and secure API management solutions
### MindPal
[MindPal](https://mindpal.io) is a no-code platform for building and running AI agents and multi-agent workflows for business processes.
**Key features:**
- Build custom AI agents with no-code
- Connect any SSE MCP server to extend agent tools
- Create multi-agent workflows for complex business processes
- User-friendly for both technical and non-technical professionals
- Ongoing development with continuous improvement of MCP support
**Learn more:**
- [MindPal MCP Documentation](https://docs.mindpal.io/agent/mcp)
### OpenSumi
[OpenSumi](https://github.com/opensumi/core) is a framework helps you quickly build AI Native IDE products.
**Key features:**
- Supports MCP tools in OpenSumi
- Supports built-in IDE MCP servers and custom MCP servers
### oterm
[oterm] is a terminal client for Ollama allowing users to create chats/agents.
**Key features:**
- Support for multiple fully customizable chat sessions with Ollama connected with tools.
- Support for MCP tools.
### Roo Code
[Roo Code](https://roocode.com) enables AI coding assistance via MCP.
**Key features:**
- Support for MCP tools and resources
- Integration with development workflows
- Extensible AI capabilities
### Sourcegraph Cody
[Cody](https://openctx.org/docs/providers/modelcontextprotocol) is Sourcegraph's AI coding assistant, which implements MCP through OpenCTX.
**Key features:**
- Support for MCP resources
- Integration with Sourcegraph's code intelligence
- Uses OpenCTX as an abstraction layer
- Future support planned for additional MCP features
### SpinAI
[SpinAI](https://spinai.dev) is an open-source TypeScript framework for building observable AI agents. The framework provides native MCP compatibility, allowing agents to seamlessly integrate with MCP servers and tools.
**Key features:**
- Built-in MCP compatibility for AI agents
- Open-source TypeScript framework
- Observable agent architecture
- Native support for MCP tools integration
### Superinterface
[Superinterface](https://superinterface.ai) is AI infrastructure and a developer platform to build in-app AI assistants with support for MCP, interactive components, client-side function calling and more.
**Key features:**
- Use tools from MCP servers in assistants embedded via React components or script tags
- SSE transport support
- Use any AI model from any AI provider (OpenAI, Anthropic, Ollama, others)
### TheiaAI/TheiaIDE
[Theia AI](https://eclipsesource.com/blogs/2024/10/07/introducing-theia-ai/) is a framework for building AI-enhanced tools and IDEs. The [AI-powered Theia IDE](https://eclipsesource.com/blogs/2024/10/08/introducting-ai-theia-ide/) is an open and flexible development environment built on Theia AI.
**Key features:**
- **Tool Integration**: Theia AI enables AI agents, including those in the Theia IDE, to utilize MCP servers for seamless tool interaction.
- **Customizable Prompts**: The Theia IDE allows users to define and adapt prompts, dynamically integrating MCP servers for tailored workflows.
- **Custom agents**: The Theia IDE supports creating custom agents that leverage MCP capabilities, enabling users to design dedicated workflows on the fly.
Theia AI and Theia IDE's MCP integration provide users with flexibility, making them powerful platforms for exploring and adapting MCP.
**Learn more:**
- [Theia IDE and Theia AI MCP Announcement](https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/)
- [Download the AI-powered Theia IDE](https://theia-ide.org/)
### TypingMind App
[TypingMind](https://www.typingmind.com) is an advanced frontend for LLMs with MCP support. TypingMind supports all popular LLM providers like OpenAI, Gemini, Claude, and users can use with their own API keys.
**Key features:**
- **MCP Tool Integration**: Once MCP is configured, MCP tools will show up as plugins that can be enabled/disabled easily via the main app interface.
- **Assign MCP Tools to Agents**: TypingMind allows users to create AI agents that have a set of MCP servers assigned.
- **Remote MCP servers**: Allows users to customize where to run the MCP servers via its MCP Connector configuration, allowing the use of MCP tools across multiple devices (laptop, mobile devices, etc.) or control MCP servers from a remote private server.
**Learn more:**
- [TypingMind MCP Document](https://www.typingmind.com/mcp)
- [Download TypingMind (PWA)](https://www.typingmind.com/)
### VS Code GitHub Copilot
[VS Code](https://code.visualstudio.com/) integrates MCP with GitHub Copilot through [agent mode](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode), allowing direct interaction with MCP-provided tools within your agentic coding workflow. Configure servers in Claude Desktop, workspace or user settings, with guided MCP installation and secure handling of keys in input variables to avoid leaking hard-coded keys.
**Key features:**
- Support for stdio and server-sent events (SSE) transport
- Per-session selection of tools per agent session for optimal performance
- Easy server debugging with restart commands and output logging
- Tool calls with editable inputs and always-allow toggle
- Integration with existing VS Code extension system to register MCP servers from extensions
### Windsurf Editor
[Windsurf Editor](https://codeium.com/windsurf) is an agentic IDE that combines AI assistance with developer workflows. It features an innovative AI Flow system that enables both collaborative and independent AI interactions while maintaining developer control.
**Key features:**
- Revolutionary AI Flow paradigm for human-AI collaboration
- Intelligent code generation and understanding
- Rich development tools with multi-model support
### Witsy
[Witsy](https://github.com/nbonamy/witsy) is an AI desktop assistant, supoorting Anthropic models and MCP servers as LLM tools.
**Key features:**
- Multiple MCP servers support
- Tool integration for executing commands and scripts
- Local server connections for enhanced privacy and security
- Easy-install from Smithery.ai
- Open-source, available for macOS, Windows and Linux
### Zed
[Zed](https://zed.dev/docs/assistant/model-context-protocol) is a high-performance code editor with built-in MCP support, focusing on prompt templates and tool integration.
**Key features:**
- Prompt templates surface as slash commands in the editor
- Tool integration for enhanced coding workflows
- Tight integration with editor features and workspace context
- Does not support MCP resources
## Adding MCP support to your application
If you've added MCP support to your application, we encourage you to submit a pull request to add it to this list. MCP integration can provide your users with powerful contextual AI capabilities and make your application part of the growing MCP ecosystem.
Benefits of adding MCP support:
- Enable users to bring their own context and tools
- Join a growing ecosystem of interoperable AI applications
- Provide users with flexible integration options
- Support local-first AI workflows
To get started with implementing MCP in your application, check out our [Python](https://github.com/modelcontextprotocol/python-sdk) or [TypeScript SDK Documentation](https://github.com/modelcontextprotocol/typescript-sdk)
## Updates and corrections
This list is maintained by the community. If you notice any inaccuracies or would like to update information about MCP support in your application, please submit a pull request or [open an issue in our documentation repository](https://github.com/modelcontextprotocol/modelcontextprotocol/issues).
## /docs/development/contributing.mdx
---
title: Contributing
description: How to participate in Model Context Protocol development
---
We welcome contributions from the community! Please review our [contributing guidelines](https://github.com/modelcontextprotocol/.github/blob/main/CONTRIBUTING.md) for details on how to submit changes.
All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md).
For questions and discussions, please use [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions).
## /docs/development/roadmap.mdx
---
title: Roadmap
description: Our plans for evolving Model Context Protocol
---
Last updated: **2025-03-27**
The Model Context Protocol is rapidly evolving. This page outlines our current thinking on key priorities and direction for approximately **the next six months**, though these may change significantly as the project develops. To see what's changed recently, check out the **[specification changelog](/specification/2025-03-26/changelog/)**.
The ideas presented here are not commitments—we may solve these challenges differently than described, or some may not materialize at all. This is also not an _exhaustive_ list; we may incorporate work that isn't mentioned here.
We value community participation! Each section links to relevant discussions where you can learn more and contribute your thoughts.
For a technical view of our standardization process, visit the [Standards Track](https://github.com/orgs/modelcontextprotocol/projects/2/views/2) on GitHub, which tracks how proposals progress toward inclusion in the official [MCP specification](https://spec.modelcontextprotocol.io).
## Validation
To foster a robust developer ecosystem, we plan to invest in:
- **Reference Client Implementations**: demonstrating protocol features with high-quality AI applications
- **Compliance Test Suites**: automated verification that clients, servers, and SDKs properly implement the specification
These tools will help developers confidently implement MCP while ensuring consistent behavior across the ecosystem.
## Registry
For MCP to reach its full potential, we need streamlined ways to distribute and discover MCP servers.
We plan to develop an [**MCP Registry**](https://github.com/orgs/modelcontextprotocol/discussions/159) that will enable centralized server discovery and metadata. This registry will primarily function as an API layer that third-party marketplaces and discovery services can build upon.
## Agents
As MCP increasingly becomes part of agentic workflows, we're exploring [improvements](https://github.com/modelcontextprotocol/specification/discussions/111) such as:
- **[Agent Graphs](https://github.com/modelcontextprotocol/specification/discussions/94)**: enabling complex agent topologies through namespacing and graph-aware communication patterns
- **Interactive Workflows**: improving human-in-the-loop experiences with granular permissioning, standardized interaction patterns, and [ways to directly communicate](https://github.com/modelcontextprotocol/specification/issues/97) with the end user
## Multimodality
Supporting the full spectrum of AI capabilities in MCP, including:
- **Additional Modalities**: video and other media types
- **[Streaming](https://github.com/modelcontextprotocol/specification/issues/117)**: multipart, chunked messages, and bidirectional communication for interactive experiences
## Governance
We're implementing governance structures that prioritize:
- **Community-Led Development**: fostering a collaborative ecosystem where community members and AI developers can all participate in MCP's evolution, ensuring it serves diverse applications and use cases
- **Transparent Standardization**: establishing clear processes for contributing to the specification, while exploring formal standardization via industry bodies
## Get Involved
We welcome your contributions to MCP's future! Join our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to share ideas, provide feedback, or participate in the development process.
## /docs/development/updates.mdx
---
title: "What's New"
description: 'The latest updates and improvements to MCP'
---
- Version [0.9.0](https://github.com/modelcontextprotocol/java-sdk/releases/tag/v0.9.0) of the MCP Java SDK has been released.
- Refactored logging system to use exchange mechanism
- Custom Context Paths
- Server Instructions
- CallToolResult Enhancement
- Fix issues and cleanup API
- Added binary compatibility tracking to avoid breaking changes
- Drop jdk requirements to JDK8
- Added Claude Desktop integration with sample
- The full changelog can be found here: https://github.com/modelcontextprotocol/kotlin-sdk/releases/tag/0.4.0
- Version [0.8.1](https://github.com/modelcontextprotocol/java-sdk/releases/tag/v0.8.1) of the MCP Java SDK has been released,
providing important bug fixes.
- We are exited to announce the availability of the MCP
[C# SDK](https://github.com/modelcontextprotocol/csharp-sdk/) developed by
[Peder Holdgaard Pedersen](http://github.com/PederHP) and Microsoft. This joins our growing
list of supported languages. The C# SDK is also available as
[NuGet package](https://www.nuget.org/packages/ModelContextProtocol)
- Python SDK 1.5.0 was released with multiple fixes and improvements.
- Version [0.8.0](https://github.com/modelcontextprotocol/java-sdk/releases/tag/v0.8.0) of the MCP Java SDK has been released,
delivering important session management improvements and bug fixes.
- Typescript SDK 1.7.0 was released with multiple fixes and improvements.
- We're excited to announce that the Java SDK developed by Spring AI at VMware Tanzu is now
the official [Java SDK](https://github.com/modelcontextprotocol/java-sdk) for MCP.
This joins our existing Kotlin SDK in our growing list of supported languages.
The Spring AI team will maintain the SDK as an integral part of the Model Context Protocol
organization. We're thrilled to welcome them to the MCP community!
- Version [1.2.1](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v1.2.1) of the MCP Python SDK has been released,
delivering important stability improvements and bug fixes.
- Simplified, express-like API in the [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
- Added 8 new clients to the [clients page](https://modelcontextprotocol.io/clients)
- FastMCP API in the [Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- Dockerized MCP servers in the [servers repo](https://github.com/modelcontextprotocol/servers)
- Jetbrains released a Kotlin SDK for MCP!
- For a sample MCP Kotlin server, check out [this repository](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-server)
## /docs/docs.json
```json path="/docs/docs.json"
{
"$schema": "https://mintlify.com/docs.json",
"theme": "willow",
"name": "Model Context Protocol",
"colors": {
"primary": "#09090b",
"light": "#FAFAFA",
"dark": "#09090b"
},
"favicon": "/favicon.svg",
"navigation": {
"tabs": [
{
"tab": "User Guide",
"groups": [
{
"group": "Get Started",
"pages": [
"introduction",
{
"group": "Quickstart",
"pages": [
"quickstart/server",
"quickstart/client",
"quickstart/user"
]
},
"examples",
"clients",
"faqs"
]
},
{
"group": "Tutorials",
"pages": [
"tutorials/building-mcp-with-llms",
"docs/tools/debugging",
"docs/tools/inspector"
]
},
{
"group": "Concepts",
"pages": [
"docs/concepts/architecture",
"docs/concepts/resources",
"docs/concepts/prompts",
"docs/concepts/tools",
"docs/concepts/sampling",
"docs/concepts/roots",
"docs/concepts/transports"
]
},
{
"group": "Development",
"pages": [
"development/updates",
"development/roadmap",
"development/contributing"
]
}
]
},
{
"tab": "SDKs",
"icon": "book-open",
"groups": [
{
"group": "Java",
"pages": [
"sdk/java/mcp-overview",
"sdk/java/mcp-client",
"sdk/java/mcp-server"
]
}
]
},
{
"tab": "Specification",
"icon": "book",
"groups": [
{
"group": "2025-03-26 (Latest)",
"pages": [
"specification/2025-03-26/index",
"specification/2025-03-26/changelog",
"specification/2025-03-26/architecture/index",
{
"group": "Base Protocol",
"pages": [
"specification/2025-03-26/basic/index",
"specification/2025-03-26/basic/lifecycle",
"specification/2025-03-26/basic/transports",
"specification/2025-03-26/basic/authorization",
{
"group": "Utilities",
"pages": [
"specification/2025-03-26/basic/utilities/cancellation",
"specification/2025-03-26/basic/utilities/ping",
"specification/2025-03-26/basic/utilities/progress"
]
}
]
},
{
"group": "Client Features",
"pages": [
"specification/2025-03-26/client/roots",
"specification/2025-03-26/client/sampling"
]
},
{
"group": "Server Features",
"pages": [
"specification/2025-03-26/server/index",
"specification/2025-03-26/server/prompts",
"specification/2025-03-26/server/resources",
"specification/2025-03-26/server/tools",
{
"group": "Utilities",
"pages": [
"specification/2025-03-26/server/utilities/completion",
"specification/2025-03-26/server/utilities/logging",
"specification/2025-03-26/server/utilities/pagination"
]
}
]
}
]
},
{
"group": "2024-11-05",
"pages": [
"specification/2024-11-05/index",
"specification/2024-11-05/architecture/index",
{
"group": "Base Protocol",
"pages": [
"specification/2024-11-05/basic/index",
"specification/2024-11-05/basic/lifecycle",
"specification/2024-11-05/basic/messages",
"specification/2024-11-05/basic/transports",
{
"group": "Utilities",
"pages": [
"specification/2024-11-05/basic/utilities/cancellation",
"specification/2024-11-05/basic/utilities/ping",
"specification/2024-11-05/basic/utilities/progress"
]
}
]
},
{
"group": "Client Features",
"pages": [
"specification/2024-11-05/client/roots",
"specification/2024-11-05/client/sampling"
]
},
{
"group": "Server Features",
"pages": [
"specification/2024-11-05/server/index",
"specification/2024-11-05/server/prompts",
"specification/2024-11-05/server/resources",
"specification/2024-11-05/server/tools",
{
"group": "Utilities",
"pages": [
"specification/2024-11-05/server/utilities/completion",
"specification/2024-11-05/server/utilities/logging",
"specification/2024-11-05/server/utilities/pagination"
]
}
]
}
]
},
{
"group": "draft",
"pages": [
"specification/draft/index",
"specification/draft/changelog",
"specification/draft/architecture/index",
{
"group": "Base Protocol",
"pages": [
"specification/draft/basic/index",
"specification/draft/basic/lifecycle",
"specification/draft/basic/transports",
"specification/draft/basic/authorization",
{
"group": "Utilities",
"pages": [
"specification/draft/basic/utilities/cancellation",
"specification/draft/basic/utilities/ping",
"specification/draft/basic/utilities/progress"
]
}
]
},
{
"group": "Client Features",
"pages": [
"specification/draft/client/roots",
"specification/draft/client/sampling"
]
},
{
"group": "Server Features",
"pages": [
"specification/draft/server/index",
"specification/draft/server/prompts",
"specification/draft/server/resources",
"specification/draft/server/tools",
{
"group": "Utilities",
"pages": [
"specification/draft/server/utilities/completion",
"specification/draft/server/utilities/logging",
"specification/draft/server/utilities/pagination"
]
}
]
}
]
},
{
"group": "Resources",
"pages": [
"specification/versioning",
"specification/contributing"
]
}
]
}
],
"global": {
"anchors": [
{
"anchor": "Python SDK",
"href": "https://github.com/modelcontextprotocol/python-sdk",
"icon": "python"
},
{
"anchor": "TypeScript SDK",
"href": "https://github.com/modelcontextprotocol/typescript-sdk",
"icon": "square-js"
},
{
"anchor": "Java SDK",
"href": "https://github.com/modelcontextprotocol/java-sdk",
"icon": "java"
},
{
"anchor": "Kotlin SDK",
"href": "https://github.com/modelcontextprotocol/kotlin-sdk",
"icon": "square-k"
},
{
"anchor": "C# SDK",
"href": "https://github.com/modelcontextprotocol/csharp-sdk",
"icon": "square-c"
}
]
}
},
"logo": {
"light": "/logo/light.svg",
"dark": "/logo/dark.svg"
},
"navbar": {
"links": [],
"primary": {
"type": "button",
"label": "GitHub",
"href": "https://github.com/modelcontextprotocol"
}
},
"seo": {
"metatags": {
"og:image": "https://raw.githubusercontent.com/modelcontextprotocol/docs/2eb6171ddbfeefde349dc3b8d5e2b87414c26250/images/og-image.png"
},
"indexing": "navigable"
},
"footer": {
"socials": {
"github": "https://github.com/modelcontextprotocol"
}
},
"redirects": [
{
"source": "/tutorials/building-a-client",
"destination": "/quickstart/client"
},
{
"source": "/quickstart",
"destination": "/quickstart/server"
},
{
"source": "/specification/latest",
"destination": "/specification/2025-03-26",
"permanent": false
}
],
"contextual": {
"options": [
"copy",
"view"
]
}
}
```
## /docs/docs/concepts/architecture.mdx
---
title: "Core architecture"
description: "Understand how MCP connects clients, servers, and LLMs"
---
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
// Handle incoming notifications
setNotificationHandler(schema: T, handler: (notification: T) => Promise): void
// Send requests and await responses
request(request: Request, schema: T, options?: RequestOptions): Promise
// Send one-way notifications
notification(notification: Notification): Promise
}
```
```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
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](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](/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";
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
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
## /docs/docs/concepts/prompts.mdx
---
title: "Prompts"
description: "Create reusable prompt templates and workflows"
---
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",
description: "Analyze code for potential improvements",
arguments: [
{
name: "language",
description: "Programming 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
{
description: "Analyze Python code for potential improvements",
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:
```typescript
import { Server } from "@modelcontextprotocol/sdk/server";
import {
ListPromptsRequestSchema,
GetPromptRequestSchema
} from "@modelcontextprotocol/sdk/types";
const PROMPTS = {
"git-commit": {
name: "git-commit",
description: "Generate a Git commit message",
arguments: [
{
name: "changes",
description: "Git diff or description of changes",
required: true
}
]
},
"explain-code": {
name: "explain-code",
description: "Explain how code works",
arguments: [
{
name: "code",
description: "Code to explain",
required: true
},
{
name: "language",
description: "Programming language",
required: false
}
]
}
};
const server = new Server({
name: "example-prompts-server",
version: "1.0.0"
}, {
capabilities: {
prompts: {}
}
});
// List available prompts
server.setRequestHandler(ListPromptsRequestSchema, async () => {
return {
prompts: Object.values(PROMPTS)
};
});
// Get specific prompt
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
const prompt = PROMPTS[request.params.name];
if (!prompt) {
throw new Error(`Prompt not found: ${request.params.name}`);
}
if (request.params.name === "git-commit") {
return {
messages: [
{
role: "user",
content: {
type: "text",
text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}`
}
}
]
};
}
if (request.params.name === "explain-code") {
const language = request.params.arguments?.language || "Unknown";
return {
messages: [
{
role: "user",
content: {
type: "text",
text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}`
}
}
]
};
}
throw new Error("Prompt implementation not found");
});
```
```python
from mcp.server import Server
import mcp.types as types
# Define available prompts
PROMPTS = {
"git-commit": types.Prompt(
name="git-commit",
description="Generate a Git commit message",
arguments=[
types.PromptArgument(
name="changes",
description="Git diff or description of changes",
required=True
)
],
),
"explain-code": types.Prompt(
name="explain-code",
description="Explain how code works",
arguments=[
types.PromptArgument(
name="code",
description="Code to explain",
required=True
),
types.PromptArgument(
name="language",
description="Programming language",
required=False
)
],
)
}
# Initialize server
app = Server("example-prompts-server")
@app.list_prompts()
async def list_prompts() -> list[types.Prompt]:
return list(PROMPTS.values())
@app.get_prompt()
async def get_prompt(
name: str, arguments: dict[str, str] | None = None
) -> types.GetPromptResult:
if name not in PROMPTS:
raise ValueError(f"Prompt not found: {name}")
if name == "git-commit":
changes = arguments.get("changes") if arguments else ""
return types.GetPromptResult(
messages=[
types.PromptMessage(
role="user",
content=types.TextContent(
type="text",
text=f"Generate a concise but descriptive commit message "
f"for these changes:\n\n{changes}"
)
)
]
)
if name == "explain-code":
code = arguments.get("code") if arguments else ""
language = arguments.get("language", "Unknown") if arguments else "Unknown"
return types.GetPromptResult(
messages=[
types.PromptMessage(
role="user",
content=types.TextContent(
type="text",
text=f"Explain how this {language} code works:\n\n{code}"
)
)
]
)
raise ValueError("Prompt implementation not found")
```
## 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
## /docs/docs/concepts/resources.mdx
---
title: "Resources"
description: "Expose data and content from your servers to LLMs"
---
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](./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.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](https://datatracker.ietf.org/doc/html/rfc6570) 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: {}
}
});
// 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")
@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
## /docs/docs/concepts/roots.mdx
---
title: "Roots"
description: "Understanding roots in MCP"
---
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/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.
## /docs/docs/concepts/sampling.mdx
---
title: "Sampling"
description: "Let your servers request completions from LLMs"
---
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
}
```
## 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
## /docs/docs/concepts/tools.mdx
---
title: "Tools"
description: "Enable LLMs to perform actions through your server"
---
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](/docs/concepts/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
},
annotations?: { // Optional hints about tool behavior
title?: string; // Human-readable title for the tool
readOnlyHint?: boolean; // If true, the tool does not modify its environment
destructiveHint?: boolean; // If true, the tool may perform destructive updates
idempotentHint?: boolean; // If true, repeated calls with same args have no additional effect
openWorldHint?: boolean; // If true, tool interacts with external entities
}
}
```
## 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: {}
}
});
// Define available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [{
name: "calculate_sum",
description: "Add two numbers together",
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")
@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",
description: "Run a shell 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",
description: "Create a GitHub 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",
description: "Analyze a CSV file",
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.
## Tool annotations
Tool annotations provide additional metadata about a tool's behavior, helping clients understand how to present and manage tools. These annotations are hints that describe the nature and impact of a tool, but should not be relied upon for security decisions.
### Purpose of tool annotations
Tool annotations serve several key purposes:
1. Provide UX-specific information without affecting model context
2. Help clients categorize and present tools appropriately
3. Convey information about a tool's potential side effects
4. Assist in developing intuitive interfaces for tool approval
### Available tool annotations
The MCP specification defines the following annotations for tools:
| Annotation | Type | Default | Description |
|------------|------|---------|-------------|
| `title` | string | - | A human-readable title for the tool, useful for UI display |
| `readOnlyHint` | boolean | false | If true, indicates the tool does not modify its environment |
| `destructiveHint` | boolean | true | If true, the tool may perform destructive updates (only meaningful when `readOnlyHint` is false) |
| `idempotentHint` | boolean | false | If true, calling the tool repeatedly with the same arguments has no additional effect (only meaningful when `readOnlyHint` is false) |
| `openWorldHint` | boolean | true | If true, the tool may interact with an "open world" of external entities |
### Example usage
Here's how to define tools with annotations for different scenarios:
```typescript
// A read-only search tool
{
name: "web_search",
description: "Search the web for information",
inputSchema: {
type: "object",
properties: {
query: { type: "string" }
},
required: ["query"]
},
annotations: {
title: "Web Search",
readOnlyHint: true,
openWorldHint: true
}
}
// A destructive file deletion tool
{
name: "delete_file",
description: "Delete a file from the filesystem",
inputSchema: {
type: "object",
properties: {
path: { type: "string" }
},
required: ["path"]
},
annotations: {
title: "Delete File",
readOnlyHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: false
}
}
// A non-destructive database record creation tool
{
name: "create_record",
description: "Create a new record in the database",
inputSchema: {
type: "object",
properties: {
table: { type: "string" },
data: { type: "object" }
},
required: ["table", "data"]
},
annotations: {
title: "Create Database Record",
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false
}
}
```
### Integrating annotations in server implementation
```typescript
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [{
name: "calculate_sum",
description: "Add two numbers together",
inputSchema: {
type: "object",
properties: {
a: { type: "number" },
b: { type: "number" }
},
required: ["a", "b"]
},
annotations: {
title: "Calculate Sum",
readOnlyHint: true,
openWorldHint: false
}
}]
};
});
```
```python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("example-server")
@mcp.tool(
annotations={
"title": "Calculate Sum",
"readOnlyHint": True,
"openWorldHint": False
}
)
async def calculate_sum(a: float, b: float) -> str:
"""Add two numbers together.
Args:
a: First number to add
b: Second number to add
"""
result = a + b
return str(result)
```
### Best practices for tool annotations
1. **Be accurate about side effects**: Clearly indicate whether a tool modifies its environment and whether those modifications are destructive.
2. **Use descriptive titles**: Provide human-friendly titles that clearly describe the tool's purpose.
3. **Indicate idempotency properly**: Mark tools as idempotent only if repeated calls with the same arguments truly have no additional effect.
4. **Set appropriate open/closed world hints**: Indicate whether a tool interacts with a closed system (like a database) or an open system (like the web).
5. **Remember annotations are hints**: All properties in ToolAnnotations are hints and not guaranteed to provide a faithful description of tool behavior. Clients should never make security-critical decisions based solely on annotations.
## 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
## /docs/docs/concepts/transports.mdx
---
title: "Transports"
description: "Learn about MCP's communication mechanisms"
---
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](https://www.jsonrpc.org/) 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: {}
});
const transport = new StdioServerTransport();
await server.connect(transport);
```
```typescript
const client = new Client({
name: "example-client",
version: "1.0.0"
}, {
capabilities: {}
});
const transport = new StdioClientTransport({
command: "./server",
args: ["--option", "value"]
});
await client.connect(transport);
```
```python
app = Server("example-server")
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"]
)
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
#### Security Warning: DNS Rebinding Attacks
SSE transports can be vulnerable to DNS rebinding attacks if not properly secured. To prevent this:
1. **Always validate Origin headers** on incoming SSE connections to ensure they come from expected sources
2. **Avoid binding servers to all network interfaces** (0.0.0.0) when running locally - bind only to localhost (127.0.0.1) instead
3. **Implement proper authentication** for all SSE connections
Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites.
```typescript
import express from "express";
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: {}
});
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
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;
// Send a JSON-RPC message
send(message: JSONRPCMessage): Promise;
// Close the connection
close(): Promise;
// 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.
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;
}
}
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)
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
- For SSE transports, validate Origin headers to prevent DNS rebinding attacks
- For local SSE servers, bind only to localhost (127.0.0.1) instead of all interfaces (0.0.0.0)
## 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
## /docs/docs/tools/debugging.mdx
---
title: Debugging
description: A comprehensive guide to debugging Model Context Protocol (MCP) integrations
---
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](/docs/tools/inspector) 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
```
2. 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](/docs/tools/inspector)
4. Verify protocol compatibility
## Implementing logging
### Server-side logging
When building a server that uses the local stdio [transport](/docs/concepts/transports), 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](/docs/concepts/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](/docs/tools/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](/docs/tools/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](/docs/tools/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
## /docs/docs/tools/inspector.mdx
---
title: Inspector
description: In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers
---
The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is an interactive developer tool for testing and debugging MCP servers. While the [Debugging Guide](/docs/tools/debugging) 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
```
```bash
npx @modelcontextprotocol/inspector
```
#### Inspecting servers from NPM or PyPi
A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com).
```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](/docs/concepts/transports) 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
Learn about broader debugging strategies
## /docs/examples.mdx
---
title: Example Servers
description: 'A list of example servers and implementations'
---
This page showcases various Model Context Protocol (MCP) servers that demonstrate the protocol's capabilities and versatility. These servers enable Large Language Models (LLMs) to securely access tools and data sources.
## Reference implementations
These official reference servers demonstrate core MCP features and SDK usage:
### Data and file systems
- **[Filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)** - Secure file operations with configurable access controls
- **[PostgreSQL](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres)** - Read-only database access with schema inspection capabilities
- **[SQLite](https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite)** - Database interaction and business intelligence features
- **[Google Drive](https://github.com/modelcontextprotocol/servers/tree/main/src/gdrive)** - File access and search capabilities for Google Drive
### Development tools
- **[Git](https://github.com/modelcontextprotocol/servers/tree/main/src/git)** - Tools to read, search, and manipulate Git repositories
- **[GitHub](https://github.com/modelcontextprotocol/servers/tree/main/src/github)** - Repository management, file operations, and GitHub API integration
- **[GitLab](https://github.com/modelcontextprotocol/servers/tree/main/src/gitlab)** - GitLab API integration enabling project management
- **[Sentry](https://github.com/modelcontextprotocol/servers/tree/main/src/sentry)** - Retrieving and analyzing issues from Sentry.io
### Web and browser automation
- **[Brave Search](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)** - Web and local search using Brave's Search API
- **[Fetch](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch)** - Web content fetching and conversion optimized for LLM usage
- **[Puppeteer](https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer)** - Browser automation and web scraping capabilities
### Productivity and communication
- **[Slack](https://github.com/modelcontextprotocol/servers/tree/main/src/slack)** - Channel management and messaging capabilities
- **[Google Maps](https://github.com/modelcontextprotocol/servers/tree/main/src/google-maps)** - Location services, directions, and place details
- **[Memory](https://github.com/modelcontextprotocol/servers/tree/main/src/memory)** - Knowledge graph-based persistent memory system
### AI and specialized tools
- **[EverArt](https://github.com/modelcontextprotocol/servers/tree/main/src/everart)** - AI image generation using various models
- **[Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking)** - Dynamic problem-solving through thought sequences
- **[AWS KB Retrieval](https://github.com/modelcontextprotocol/servers/tree/main/src/aws-kb-retrieval-server)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime
## Official integrations
These MCP servers are maintained by companies for their platforms:
- **[Axiom](https://github.com/axiomhq/mcp-server-axiom)** - Query and analyze logs, traces, and event data using natural language
- **[Browserbase](https://github.com/browserbase/mcp-server-browserbase)** - Automate browser interactions in the cloud
- **[Cloudflare](https://github.com/cloudflare/mcp-server-cloudflare)** - Deploy and manage resources on the Cloudflare developer platform
- **[E2B](https://github.com/e2b-dev/mcp-server)** - Execute code in secure cloud sandboxes
- **[Neon](https://github.com/neondatabase/mcp-server-neon)** - Interact with the Neon serverless Postgres platform
- **[Obsidian Markdown Notes](https://github.com/calclavia/mcp-obsidian)** - Read and search through Markdown notes in Obsidian vaults
- **[Prisma](https://pris.ly/docs/mcp-server)** - Manage and interact with Prisma Postgres databases
- **[Qdrant](https://github.com/qdrant/mcp-server-qdrant/)** - Implement semantic memory using the Qdrant vector search engine
- **[Raygun](https://github.com/MindscapeHQ/mcp-server-raygun)** - Access crash reporting and monitoring data
- **[Search1API](https://github.com/fatwang2/search1api-mcp)** - Unified API for search, crawling, and sitemaps
- **[Stripe](https://github.com/stripe/agent-toolkit)** - Interact with the Stripe API
- **[Tinybird](https://github.com/tinybirdco/mcp-tinybird)** - Interface with the Tinybird serverless ClickHouse platform
- **[Weaviate](https://github.com/weaviate/mcp-server-weaviate)** - Enable Agentic RAG through your Weaviate collection(s)
## Community highlights
A growing ecosystem of community-developed servers extends MCP's capabilities:
- **[Docker](https://github.com/ckreiling/mcp-server-docker)** - Manage containers, images, volumes, and networks
- **[Kubernetes](https://github.com/Flux159/mcp-server-kubernetes)** - Manage pods, deployments, and services
- **[Linear](https://github.com/jerhadf/linear-mcp-server)** - Project management and issue tracking
- **[Snowflake](https://github.com/datawiz168/mcp-snowflake-service)** - Interact with Snowflake databases
- **[Spotify](https://github.com/varunneal/spotify-mcp)** - Control Spotify playback and manage playlists
- **[Todoist](https://github.com/abhiz123/todoist-mcp-server)** - Task management integration
> **Note:** Community servers are untested and should be used at your own risk. They are not affiliated with or endorsed by Anthropic.
For a complete list of community servers, visit the [MCP Servers Repository](https://github.com/modelcontextprotocol/servers).
## Getting started
### Using reference servers
TypeScript-based servers can be used directly with `npx`:
```bash
npx -y @modelcontextprotocol/server-memory
```
Python-based servers can be used with `uvx` (recommended) or `pip`:
```bash
# Using uvx
uvx mcp-server-git
# Using pip
pip install mcp-server-git
python -m mcp_server_git
```
### Configuring with Claude
To use an MCP server with Claude, add it to your configuration:
```json
{
"mcpServers": {
"memory": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-memory"]
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": ""
}
}
}
}
```
## Additional resources
- [MCP Servers Repository](https://github.com/modelcontextprotocol/servers) - Complete collection of reference implementations and community servers
- [Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers) - Curated list of MCP servers
- [MCP CLI](https://github.com/wong2/mcp-cli) - Command-line inspector for testing MCP servers
- [MCP Get](https://mcp-get.com) - Tool for installing and managing MCP servers
- [Pipedream MCP](https://mcp.pipedream.com) - MCP servers with built-in auth for 3,000+ APIs and 10,000+ tools
- [Supergateway](https://github.com/supercorp-ai/supergateway) - Run MCP stdio servers over SSE
- [Zapier MCP](https://zapier.com/mcp) - MCP Server with over 7,000+ apps and 30,000+ actions
Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to engage with the MCP community.
## /docs/faqs.mdx
---
title: "FAQs"
description: "Explaining MCP and why it matters in simple terms"
---
## What is MCP?
MCP (Model Context Protocol) is a standard way for AI applications and agents to connect to and work with your data sources (e.g. local files, databases, or content repositories) and tools (e.g. GitHub, Google Maps, or Puppeteer).
Think of MCP as a universal adapter for AI applications, similar to what USB-C is for physical devices. USB-C acts as a universal adapter to connect devices to various peripherals and accessories. Similarly, MCP provides a standardized way to connect AI applications to different data and tools.
Before USB-C, you needed different cables for different connections. Similarly, before MCP, developers had to build custom connections to each data source or tool they wanted their AI application to work with—a time-consuming process that often resulted in limited functionality. Now, with MCP, developers can easily add connections to their AI applications, making their applications much more powerful from day one.
## Why does MCP matter?
### For AI application users
MCP means your AI applications can access the information and tools you work with every day, making them much more helpful. Rather than AI being limited to what it already knows about, it can now understand your specific documents, data, and work context.
For example, by using MCP servers, applications can access your personal documents from Google Drive or data about your codebase from GitHub, providing more personalized and contextually relevant assistance.
Imagine asking an AI assistant: "Summarize last week's team meeting notes and schedule follow-ups with everyone."
By using connections to data sources powered by MCP, the AI assistant can:
- Connect to your Google Drive through an MCP server to read meeting notes
- Understand who needs follow-ups based on the notes
- Connect to your calendar through another MCP server to schedule the meetings automatically
### For developers
MCP reduces development time and complexity when building AI applications that need to access various data sources. With MCP, developers can focus on building great AI experiences rather than repeatedly creating custom connectors.
Traditionally, connecting applications with data sources required building custom, one-off connections for each data source and each application. This created significant duplicative work—every developer wanting to connect their AI application to Google Drive or Slack needed to build their own connection.
MCP simplifies this by enabling developers to build MCP servers for data sources that are then reusable by various applications. For example, using the open source Google Drive MCP server, many different applications can access data from Google Drive without each developer needing to build a custom connection.
This open source ecosystem of MCP servers means developers can leverage existing work rather than starting from scratch, making it easier to build powerful AI applications that seamlessly integrate with the tools and data sources their users already rely on.
## How does MCP work?
MCP creates a bridge between your AI applications and your data through a straightforward system:
- **MCP servers** connect to your data sources and tools (like Google Drive or Slack)
- **MCP clients** are run by AI applications (like Claude Desktop) to connect them to these servers
- When you give permission, your AI application discovers available MCP servers
- The AI model can then use these connections to read information and take actions
This modular system means new capabilities can be added without changing AI applications themselves—just like adding new accessories to your computer without upgrading your entire system.
## Who creates and maintains MCP servers?
MCP servers are developed and maintained by:
- Developers at Anthropic who build servers for common tools and data sources
- Open source contributors who create servers for tools they use
- Enterprise development teams building servers for their internal systems
- Software providers making their applications AI-ready
Once an open source MCP server is created for a data source, it can be used by any MCP-compatible AI application, creating a growing ecosystem of connections. See our [list of example servers](https://modelcontextprotocol.io/examples), or [get started building your own server](https://modelcontextprotocol.io/quickstart/server).
## /docs/favicon.svg
```svg path="/docs/favicon.svg"
```
## /docs/images/available-mcp-tools.png
Binary file available at https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/docs/images/available-mcp-tools.png
## /docs/images/claude-desktop-mcp-hammer-icon.svg
```svg path="/docs/images/claude-desktop-mcp-hammer-icon.svg"
```
## /docs/images/claude-desktop-mcp-plug-icon.svg
```svg path="/docs/images/claude-desktop-mcp-plug-icon.svg"
```
## /docs/images/client-claude-cli-python.png
Binary file available at https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/docs/images/client-claude-cli-python.png
## /docs/images/current-weather.png
Binary file available at https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/docs/images/current-weather.png
## /docs/images/hero-dark.svg
```svg path="/docs/images/hero-dark.svg"
```
## /docs/images/hero-light.svg
```svg path="/docs/images/hero-light.svg"
```
## /docs/images/java/class-diagrams.puml
```puml path="/docs/images/java/class-diagrams.puml"
@startuml Core Components
' Core Interfaces
interface McpTransport {
+Mono connect(Function, Mono> handler)
+Mono sendMessage(JSONRPCMessage message)
+void close()
+Mono closeGracefully()
+ T unmarshalFrom(Object data, TypeReference typeRef)
}
interface McpSession {
+ Mono sendRequest(String method, Object requestParams, TypeReference typeRef)
+Mono sendNotification(String method, Map params)
+Mono closeGracefully()
+void close()
}
' Core Implementation Classes
class DefaultMcpSession {
+interface RequestHandler
+interface NotificationHandler
}
' Client Classes
class McpClient {
+{static} Builder using(ClientMcpTransport transport)
}
class McpAsyncClient {
+Mono initialize()
+ServerCapabilities getServerCapabilities()
+Implementation getServerInfo()
+ClientCapabilities getClientCapabilities()
+Implementation getClientInfo()
+void close()
+Mono closeGracefully()
+Mono