This is page 2 of 2. Use http://codebase.md/jwaldor/mcp-scrape-copilot?lines=true&page={x} to view the full context.
# Directory Structure
```
├── .gitignore
├── Dockerfile
├── index.ts
├── llm.txt
├── package-lock.json
├── package.json
├── README.md
├── tsconfig.json
├── types.ts
└── utilities.ts
```
# Files
--------------------------------------------------------------------------------
/llm.txt:
--------------------------------------------------------------------------------
```
   1 | # Example Clients
   2 | 
   3 | A list of applications that support MCP integrations
   4 | 
   5 | 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.
   6 | 
   7 | ## Feature support matrix
   8 | 
   9 | | Client                               | [Resources] | [Prompts] | [Tools] | [Sampling] | Roots | Notes                                                              |
  10 | | ------------------------------------ | ----------- | --------- | ------- | ---------- | ----- | ------------------------------------------------------------------ |
  11 | | [Claude Desktop App][Claude]         | ✅           | ✅         | ✅       | ❌          | ❌     | Full support for all MCP features                                  |
  12 | | [Zed][Zed]                           | ❌           | ✅         | ❌       | ❌          | ❌     | Prompts appear as slash commands                                   |
  13 | | [Sourcegraph Cody][Cody]             | ✅           | ❌         | ❌       | ❌          | ❌     | Supports resources through OpenCTX                                 |
  14 | | [Firebase Genkit][Genkit]            | ⚠️          | ✅         | ✅       | ❌          | ❌     | Supports resource list and lookup through tools.                   |
  15 | | [Continue][Continue]                 | ✅           | ✅         | ✅       | ❌          | ❌     | Full support for all MCP features                                  |
  16 | | [GenAIScript][GenAIScript]           | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools.                                                    |
  17 | | [Cline][Cline]                       | ✅           | ❌         | ✅       | ❌          | ❌     | Supports tools and resources.                                      |
  18 | | [LibreChat][LibreChat]               | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools for Agents                                          |
  19 | | [TheiaAI/TheiaIDE][TheiaAI/TheiaIDE] | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools for Agents in Theia AI and the AI-powered Theia IDE |
  20 | | [Superinterface][Superinterface]     | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools                                                     |
  21 | | [5ire][5ire]                         | ❌           | ❌         | ✅       | ❌          | ❌     | Supports tools.                                                    |
  22 | 
  23 | [Claude]: https://claude.ai/download
  24 | 
  25 | [Zed]: https://zed.dev
  26 | 
  27 | [Cody]: https://sourcegraph.com/cody
  28 | 
  29 | [Genkit]: https://github.com/firebase/genkit
  30 | 
  31 | [Continue]: https://github.com/continuedev/continue
  32 | 
  33 | [GenAIScript]: https://microsoft.github.io/genaiscript/reference/scripts/mcp-tools/
  34 | 
  35 | [Cline]: https://github.com/cline/cline
  36 | 
  37 | [LibreChat]: https://github.com/danny-avila/LibreChat
  38 | 
  39 | [TheiaAI/TheiaIDE]: https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/
  40 | 
  41 | [Superinterface]: https://superinterface.ai
  42 | 
  43 | [5ire]: https://github.com/nanbingxyz/5ire
  44 | 
  45 | [Resources]: https://modelcontextprotocol.io/docs/concepts/resources
  46 | 
  47 | [Prompts]: https://modelcontextprotocol.io/docs/concepts/prompts
  48 | 
  49 | [Tools]: https://modelcontextprotocol.io/docs/concepts/tools
  50 | 
  51 | [Sampling]: https://modelcontextprotocol.io/docs/concepts/sampling
  52 | 
  53 | ## Client details
  54 | 
  55 | ### Claude Desktop App
  56 | 
  57 | The Claude desktop application provides comprehensive support for MCP, enabling deep integration with local tools and data sources.
  58 | 
  59 | **Key features:**
  60 | 
  61 | *   Full support for resources, allowing attachment of local files and data
  62 | *   Support for prompt templates
  63 | *   Tool integration for executing commands and scripts
  64 | *   Local server connections for enhanced privacy and security
  65 | 
  66 | > ⓘ Note: The Claude.ai web application does not currently support MCP. MCP features are only available in the desktop application.
  67 | 
  68 | ### Zed
  69 | 
  70 | [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.
  71 | 
  72 | **Key features:**
  73 | 
  74 | *   Prompt templates surface as slash commands in the editor
  75 | *   Tool integration for enhanced coding workflows
  76 | *   Tight integration with editor features and workspace context
  77 | *   Does not support MCP resources
  78 | 
  79 | ### Sourcegraph Cody
  80 | 
  81 | [Cody](https://openctx.org/docs/providers/modelcontextprotocol) is Sourcegraph's AI coding assistant, which implements MCP through OpenCTX.
  82 | 
  83 | **Key features:**
  84 | 
  85 | *   Support for MCP resources
  86 | *   Integration with Sourcegraph's code intelligence
  87 | *   Uses OpenCTX as an abstraction layer
  88 | *   Future support planned for additional MCP features
  89 | 
  90 | ### Firebase Genkit
  91 | 
  92 | [Genkit](https://github.com/firebase/genkit) is Firebase's 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.
  93 | 
  94 | **Key features:**
  95 | 
  96 | *   Client support for tools and prompts (resources partially supported)
  97 | *   Rich discovery with support in Genkit's Dev UI playground
  98 | *   Seamless interoperability with Genkit's existing tools and prompts
  99 | *   Works across a wide variety of GenAI models from top providers
 100 | 
 101 | ### Continue
 102 | 
 103 | [Continue](https://github.com/continuedev/continue) is an open-source AI code assistant, with built-in support for all MCP features.
 104 | 
 105 | **Key features**
 106 | 
 107 | *   Type "@" to mention MCP resources
 108 | *   Prompt templates surface as slash commands
 109 | *   Use both built-in and MCP tools directly in chat
 110 | *   Supports VS Code and JetBrains IDEs, with any LLM
 111 | 
 112 | ### GenAIScript
 113 | 
 114 | Programmatically assemble prompts for LLMs using [GenAIScript](https://microsoft.github.io/genaiscript/) (in JavaScript). Orchestrate LLMs, tools, and data in JavaScript.
 115 | 
 116 | **Key features:**
 117 | 
 118 | *   JavaScript toolbox to work with prompts
 119 | *   Abstraction to make it easy and productive
 120 | *   Seamless Visual Studio Code integration
 121 | 
 122 | ### Cline
 123 | 
 124 | [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.
 125 | 
 126 | **Key features:**
 127 | 
 128 | *   Create and add tools through natural language (e.g. "add a tool that searches the web")
 129 | *   Share custom MCP servers Cline creates with others via the `~/Documents/Cline/MCP` directory
 130 | *   Displays configured MCP servers along with their tools, resources, and any error logs
 131 | 
 132 | ### LibreChat
 133 | 
 134 | [LibreChat](https://github.com/danny-avila/LibreChat) is an open-source, customizable AI chat UI that supports multiple AI providers, now including MCP integration.
 135 | 
 136 | **Key features:**
 137 | 
 138 | *   Extend current tool ecosystem, including [Code Interpreter](https://www.librechat.ai/docs/features/code_interpreter) and Image generation tools, through MCP servers
 139 | *   Add tools to customizable [Agents](https://www.librechat.ai/docs/features/agents), using a variety of LLMs from top providers
 140 | *   Open-source and self-hostable, with secure multi-user support
 141 | *   Future roadmap includes expanded MCP feature support
 142 | 
 143 | ### TheiaAI/TheiaIDE
 144 | 
 145 | [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.
 146 | 
 147 | **Key features:**
 148 | 
 149 | *   **Tool Integration**: Theia AI enables AI agents, including those in the Theia IDE, to utilize MCP servers for seamless tool interaction.
 150 | *   **Customizable Prompts**: The Theia IDE allows users to define and adapt prompts, dynamically integrating MCP servers for tailored workflows.
 151 | *   **Custom agents**: The Theia IDE supports creating custom agents that leverage MCP capabilities, enabling users to design dedicated workflows on the fly.
 152 | 
 153 | Theia AI and Theia IDE's MCP integration provide users with flexibility, making them powerful platforms for exploring and adapting MCP.
 154 | 
 155 | **Learn more:**
 156 | 
 157 | *   [Theia IDE and Theia AI MCP Announcement](https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/)
 158 | *   [Download the AI-powered Theia IDE](https://theia-ide.org/)
 159 | 
 160 | ### Superinterface
 161 | 
 162 | [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.
 163 | 
 164 | **Key features:**
 165 | 
 166 | *   Use tools from MCP servers in assistants embedded via React components or script tags
 167 | *   SSE transport support
 168 | *   Use any AI model from any AI provider (OpenAI, Anthropic, Ollama, others)
 169 | 
 170 | ### 5ire
 171 | 
 172 | [5ire](https://github.com/nanbingxyz/5ire) is an open source cross-platform desktop AI assistant that supports tools through MCP servers.
 173 | 
 174 | **Key features:**
 175 | 
 176 | *   Built-in MCP servers can be quickly enabled and disabled.
 177 | *   Users can add more servers by modifying the configuration file.
 178 | *   It is open-source and user-friendly, suitable for beginners.
 179 | *   Future support for MCP will be continuously improved.
 180 | 
 181 | ## Adding MCP support to your application
 182 | 
 183 | 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.
 184 | 
 185 | Benefits of adding MCP support:
 186 | 
 187 | *   Enable users to bring their own context and tools
 188 | *   Join a growing ecosystem of interoperable AI applications
 189 | *   Provide users with flexible integration options
 190 | *   Support local-first AI workflows
 191 | 
 192 | 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)
 193 | 
 194 | ## Updates and corrections
 195 | 
 196 | 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/docs/issues).
 197 | 
 198 | 
 199 | # Contributing
 200 | 
 201 | How to participate in Model Context Protocol development
 202 | 
 203 | 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.
 204 | 
 205 | All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md).
 206 | 
 207 | For questions and discussions, please use [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions).
 208 | 
 209 | 
 210 | # Roadmap
 211 | 
 212 | Our plans for evolving Model Context Protocol (H1 2025)
 213 | 
 214 | The Model Context Protocol is rapidly evolving. This page outlines our current thinking on key priorities and future direction for **the first half of 2025**, though these may change significantly as the project develops.
 215 | 
 216 | <Note>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.</Note>
 217 | 
 218 | We encourage community participation! Each section links to relevant discussions where you can learn more and contribute your thoughts.
 219 | 
 220 | ## Remote MCP Support
 221 | 
 222 | Our top priority is enabling [remote MCP connections](https://github.com/modelcontextprotocol/specification/discussions/102), allowing clients to securely connect to MCP servers over the internet. Key initiatives include:
 223 | 
 224 | *   [**Authentication & Authorization**](https://github.com/modelcontextprotocol/specification/discussions/64): Adding standardized auth capabilities, particularly focused on OAuth 2.0 support.
 225 | 
 226 | *   [**Service Discovery**](https://github.com/modelcontextprotocol/specification/discussions/69): Defining how clients can discover and connect to remote MCP servers.
 227 | 
 228 | *   [**Stateless Operations**](https://github.com/modelcontextprotocol/specification/discussions/102): Thinking about whether MCP could encompass serverless environments too, where they will need to be mostly stateless.
 229 | 
 230 | ## Reference Implementations
 231 | 
 232 | To help developers build with MCP, we want to offer documentation for:
 233 | 
 234 | *   **Client Examples**: Comprehensive reference client implementation(s), demonstrating all protocol features
 235 | *   **Protocol Drafting**: Streamlined process for proposing and incorporating new protocol features
 236 | 
 237 | ## Distribution & Discovery
 238 | 
 239 | Looking ahead, we're exploring ways to make MCP servers more accessible. Some areas we may investigate include:
 240 | 
 241 | *   **Package Management**: Standardized packaging format for MCP servers
 242 | *   **Installation Tools**: Simplified server installation across MCP clients
 243 | *   **Sandboxing**: Improved security through server isolation
 244 | *   **Server Registry**: A common directory for discovering available MCP servers
 245 | 
 246 | ## Agent Support
 247 | 
 248 | We're expanding MCP's capabilities for [complex agentic workflows](https://github.com/modelcontextprotocol/specification/discussions/111), particularly focusing on:
 249 | 
 250 | *   [**Hierarchical Agent Systems**](https://github.com/modelcontextprotocol/specification/discussions/94): Improved support for trees of agents through namespacing and topology awareness.
 251 | 
 252 | *   [**Interactive Workflows**](https://github.com/modelcontextprotocol/specification/issues/97): Better handling of user permissions and information requests across agent hierarchies, and ways to send output to users instead of models.
 253 | 
 254 | *   [**Streaming Results**](https://github.com/modelcontextprotocol/specification/issues/117): Real-time updates from long-running agent operations.
 255 | 
 256 | ## Broader Ecosystem
 257 | 
 258 | We're also invested in:
 259 | 
 260 | *   **Community-Led Standards Development**: Fostering a collaborative ecosystem where all AI providers can help shape MCP as an open standard through equal participation and shared governance, ensuring it meets the needs of diverse AI applications and use cases.
 261 | *   [**Additional Modalities**](https://github.com/modelcontextprotocol/specification/discussions/88): Expanding beyond text to support audio, video, and other formats.
 262 | *   \[**Standardization**] Considering standardization through a standardization body.
 263 | 
 264 | ## Get Involved
 265 | 
 266 | We welcome community participation in shaping MCP's future. Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to join the conversation and contribute your ideas.
 267 | 
 268 | 
 269 | # Core architecture
 270 | 
 271 | Understand how MCP connects clients, servers, and LLMs
 272 | 
 273 | 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.
 274 | 
 275 | ## Overview
 276 | 
 277 | MCP follows a client-server architecture where:
 278 | 
 279 | *   **Hosts** are LLM applications (like Claude Desktop or IDEs) that initiate connections
 280 | *   **Clients** maintain 1:1 connections with servers, inside the host application
 281 | *   **Servers** provide context, tools, and prompts to clients
 282 | 
 283 | ```mermaid
 284 | flowchart LR
 285 |     subgraph " Host (e.g., Claude Desktop) "
 286 |         client1[MCP Client]
 287 |         client2[MCP Client]
 288 |     end
 289 |     subgraph "Server Process"
 290 |         server1[MCP Server]
 291 |     end
 292 |     subgraph "Server Process"
 293 |         server2[MCP Server]
 294 |     end
 295 | 
 296 |     client1 <-->|Transport Layer| server1
 297 |     client2 <-->|Transport Layer| server2
 298 | ```
 299 | 
 300 | ## Core components
 301 | 
 302 | ### Protocol layer
 303 | 
 304 | The protocol layer handles message framing, request/response linking, and high-level communication patterns.
 305 | 
 306 | <Tabs>
 307 |   <Tab title="TypeScript">
 308 |     ```typescript
 309 |     class Protocol<Request, Notification, Result> {
 310 |         // Handle incoming requests
 311 |         setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void
 312 | 
 313 |         // Handle incoming notifications
 314 |         setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void
 315 | 
 316 |         // Send requests and await responses
 317 |         request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>
 318 | 
 319 |         // Send one-way notifications
 320 |         notification(notification: Notification): Promise<void>
 321 |     }
 322 |     ```
 323 |   </Tab>
 324 | 
 325 |   <Tab title="Python">
 326 |     ```python
 327 |     class Session(BaseSession[RequestT, NotificationT, ResultT]):
 328 |         async def send_request(
 329 |             self,
 330 |             request: RequestT,
 331 |             result_type: type[Result]
 332 |         ) -> Result:
 333 |             """
 334 |             Send request and wait for response. Raises McpError if response contains error.
 335 |             """
 336 |             # Request handling implementation
 337 | 
 338 |         async def send_notification(
 339 |             self,
 340 |             notification: NotificationT
 341 |         ) -> None:
 342 |             """Send one-way notification that doesn't expect response."""
 343 |             # Notification handling implementation
 344 | 
 345 |         async def _received_request(
 346 |             self,
 347 |             responder: RequestResponder[ReceiveRequestT, ResultT]
 348 |         ) -> None:
 349 |             """Handle incoming request from other side."""
 350 |             # Request handling implementation
 351 | 
 352 |         async def _received_notification(
 353 |             self,
 354 |             notification: ReceiveNotificationT
 355 |         ) -> None:
 356 |             """Handle incoming notification from other side."""
 357 |             # Notification handling implementation
 358 |     ```
 359 |   </Tab>
 360 | </Tabs>
 361 | 
 362 | Key classes include:
 363 | 
 364 | *   `Protocol`
 365 | *   `Client`
 366 | *   `Server`
 367 | 
 368 | ### Transport layer
 369 | 
 370 | The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:
 371 | 
 372 | 1.  **Stdio transport**
 373 |     *   Uses standard input/output for communication
 374 |     *   Ideal for local processes
 375 | 
 376 | 2.  **HTTP with SSE transport**
 377 |     *   Uses Server-Sent Events for server-to-client messages
 378 |     *   HTTP POST for client-to-server messages
 379 | 
 380 | All transports use [JSON-RPC](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](https://spec.modelcontextprotocol.io) for detailed information about the Model Context Protocol message format.
 381 | 
 382 | ### Message types
 383 | 
 384 | MCP has these main types of messages:
 385 | 
 386 | 1.  **Requests** expect a response from the other side:
 387 |     ```typescript
 388 |     interface Request {
 389 |       method: string;
 390 |       params?: { ... };
 391 |     }
 392 |     ```
 393 | 
 394 | 2.  **Results** are successful responses to requests:
 395 |     ```typescript
 396 |     interface Result {
 397 |       [key: string]: unknown;
 398 |     }
 399 |     ```
 400 | 
 401 | 3.  **Errors** indicate that a request failed:
 402 |     ```typescript
 403 |     interface Error {
 404 |       code: number;
 405 |       message: string;
 406 |       data?: unknown;
 407 |     }
 408 |     ```
 409 | 
 410 | 4.  **Notifications** are one-way messages that don't expect a response:
 411 |     ```typescript
 412 |     interface Notification {
 413 |       method: string;
 414 |       params?: { ... };
 415 |     }
 416 |     ```
 417 | 
 418 | ## Connection lifecycle
 419 | 
 420 | ### 1. Initialization
 421 | 
 422 | ```mermaid
 423 | sequenceDiagram
 424 |     participant Client
 425 |     participant Server
 426 | 
 427 |     Client->>Server: initialize request
 428 |     Server->>Client: initialize response
 429 |     Client->>Server: initialized notification
 430 | 
 431 |     Note over Client,Server: Connection ready for use
 432 | ```
 433 | 
 434 | 1.  Client sends `initialize` request with protocol version and capabilities
 435 | 2.  Server responds with its protocol version and capabilities
 436 | 3.  Client sends `initialized` notification as acknowledgment
 437 | 4.  Normal message exchange begins
 438 | 
 439 | ### 2. Message exchange
 440 | 
 441 | After initialization, the following patterns are supported:
 442 | 
 443 | *   **Request-Response**: Client or server sends requests, the other responds
 444 | *   **Notifications**: Either party sends one-way messages
 445 | 
 446 | ### 3. Termination
 447 | 
 448 | Either party can terminate the connection:
 449 | 
 450 | *   Clean shutdown via `close()`
 451 | *   Transport disconnection
 452 | *   Error conditions
 453 | 
 454 | ## Error handling
 455 | 
 456 | MCP defines these standard error codes:
 457 | 
 458 | ```typescript
 459 | enum ErrorCode {
 460 |   // Standard JSON-RPC error codes
 461 |   ParseError = -32700,
 462 |   InvalidRequest = -32600,
 463 |   MethodNotFound = -32601,
 464 |   InvalidParams = -32602,
 465 |   InternalError = -32603
 466 | }
 467 | ```
 468 | 
 469 | SDKs and applications can define their own error codes above -32000.
 470 | 
 471 | Errors are propagated through:
 472 | 
 473 | *   Error responses to requests
 474 | *   Error events on transports
 475 | *   Protocol-level error handlers
 476 | 
 477 | ## Implementation example
 478 | 
 479 | Here's a basic example of implementing an MCP server:
 480 | 
 481 | <Tabs>
 482 |   <Tab title="TypeScript">
 483 |     ```typescript
 484 |     import { Server } from "@modelcontextprotocol/sdk/server/index.js";
 485 |     import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 486 | 
 487 |     const server = new Server({
 488 |       name: "example-server",
 489 |       version: "1.0.0"
 490 |     }, {
 491 |       capabilities: {
 492 |         resources: {}
 493 |       }
 494 |     });
 495 | 
 496 |     // Handle requests
 497 |     server.setRequestHandler(ListResourcesRequestSchema, async () => {
 498 |       return {
 499 |         resources: [
 500 |           {
 501 |             uri: "example://resource",
 502 |             name: "Example Resource"
 503 |           }
 504 |         ]
 505 |       };
 506 |     });
 507 | 
 508 |     // Connect transport
 509 |     const transport = new StdioServerTransport();
 510 |     await server.connect(transport);
 511 |     ```
 512 |   </Tab>
 513 | 
 514 |   <Tab title="Python">
 515 |     ```python
 516 |     import asyncio
 517 |     import mcp.types as types
 518 |     from mcp.server import Server
 519 |     from mcp.server.stdio import stdio_server
 520 | 
 521 |     app = Server("example-server")
 522 | 
 523 |     @app.list_resources()
 524 |     async def list_resources() -> list[types.Resource]:
 525 |         return [
 526 |             types.Resource(
 527 |                 uri="example://resource",
 528 |                 name="Example Resource"
 529 |             )
 530 |         ]
 531 | 
 532 |     async def main():
 533 |         async with stdio_server() as streams:
 534 |             await app.run(
 535 |                 streams[0],
 536 |                 streams[1],
 537 |                 app.create_initialization_options()
 538 |             )
 539 | 
 540 |     if __name__ == "__main__":
 541 |         asyncio.run(main)
 542 |     ```
 543 |   </Tab>
 544 | </Tabs>
 545 | 
 546 | ## Best practices
 547 | 
 548 | ### Transport selection
 549 | 
 550 | 1.  **Local communication**
 551 |     *   Use stdio transport for local processes
 552 |     *   Efficient for same-machine communication
 553 |     *   Simple process management
 554 | 
 555 | 2.  **Remote communication**
 556 |     *   Use SSE for scenarios requiring HTTP compatibility
 557 |     *   Consider security implications including authentication and authorization
 558 | 
 559 | ### Message handling
 560 | 
 561 | 1.  **Request processing**
 562 |     *   Validate inputs thoroughly
 563 |     *   Use type-safe schemas
 564 |     *   Handle errors gracefully
 565 |     *   Implement timeouts
 566 | 
 567 | 2.  **Progress reporting**
 568 |     *   Use progress tokens for long operations
 569 |     *   Report progress incrementally
 570 |     *   Include total progress when known
 571 | 
 572 | 3.  **Error management**
 573 |     *   Use appropriate error codes
 574 |     *   Include helpful error messages
 575 |     *   Clean up resources on errors
 576 | 
 577 | ## Security considerations
 578 | 
 579 | 1.  **Transport security**
 580 |     *   Use TLS for remote connections
 581 |     *   Validate connection origins
 582 |     *   Implement authentication when needed
 583 | 
 584 | 2.  **Message validation**
 585 |     *   Validate all incoming messages
 586 |     *   Sanitize inputs
 587 |     *   Check message size limits
 588 |     *   Verify JSON-RPC format
 589 | 
 590 | 3.  **Resource protection**
 591 |     *   Implement access controls
 592 |     *   Validate resource paths
 593 |     *   Monitor resource usage
 594 |     *   Rate limit requests
 595 | 
 596 | 4.  **Error handling**
 597 |     *   Don't leak sensitive information
 598 |     *   Log security-relevant errors
 599 |     *   Implement proper cleanup
 600 |     *   Handle DoS scenarios
 601 | 
 602 | ## Debugging and monitoring
 603 | 
 604 | 1.  **Logging**
 605 |     *   Log protocol events
 606 |     *   Track message flow
 607 |     *   Monitor performance
 608 |     *   Record errors
 609 | 
 610 | 2.  **Diagnostics**
 611 |     *   Implement health checks
 612 |     *   Monitor connection state
 613 |     *   Track resource usage
 614 |     *   Profile performance
 615 | 
 616 | 3.  **Testing**
 617 |     *   Test different transports
 618 |     *   Verify error handling
 619 |     *   Check edge cases
 620 |     *   Load test servers
 621 | 
 622 | 
 623 | # Prompts
 624 | 
 625 | Create reusable prompt templates and workflows
 626 | 
 627 | 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.
 628 | 
 629 | <Note>
 630 |   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.
 631 | </Note>
 632 | 
 633 | ## Overview
 634 | 
 635 | Prompts in MCP are predefined templates that can:
 636 | 
 637 | *   Accept dynamic arguments
 638 | *   Include context from resources
 639 | *   Chain multiple interactions
 640 | *   Guide specific workflows
 641 | *   Surface as UI elements (like slash commands)
 642 | 
 643 | ## Prompt structure
 644 | 
 645 | Each prompt is defined with:
 646 | 
 647 | ```typescript
 648 | {
 649 |   name: string;              // Unique identifier for the prompt
 650 |   description?: string;      // Human-readable description
 651 |   arguments?: [              // Optional list of arguments
 652 |     {
 653 |       name: string;          // Argument identifier
 654 |       description?: string;  // Argument description
 655 |       required?: boolean;    // Whether argument is required
 656 |     }
 657 |   ]
 658 | }
 659 | ```
 660 | 
 661 | ## Discovering prompts
 662 | 
 663 | Clients can discover available prompts through the `prompts/list` endpoint:
 664 | 
 665 | ```typescript
 666 | // Request
 667 | {
 668 |   method: "prompts/list"
 669 | }
 670 | 
 671 | // Response
 672 | {
 673 |   prompts: [
 674 |     {
 675 |       name: "analyze-code",
 676 |       description: "Analyze code for potential improvements",
 677 |       arguments: [
 678 |         {
 679 |           name: "language",
 680 |           description: "Programming language",
 681 |           required: true
 682 |         }
 683 |       ]
 684 |     }
 685 |   ]
 686 | }
 687 | ```
 688 | 
 689 | ## Using prompts
 690 | 
 691 | To use a prompt, clients make a `prompts/get` request:
 692 | 
 693 | ````typescript
 694 | // Request
 695 | {
 696 |   method: "prompts/get",
 697 |   params: {
 698 |     name: "analyze-code",
 699 |     arguments: {
 700 |       language: "python"
 701 |     }
 702 |   }
 703 | }
 704 | 
 705 | // Response
 706 | {
 707 |   description: "Analyze Python code for potential improvements",
 708 |   messages: [
 709 |     {
 710 |       role: "user",
 711 |       content: {
 712 |         type: "text",
 713 |         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```"
 714 |       }
 715 |     }
 716 |   ]
 717 | }
 718 | ````
 719 | 
 720 | ## Dynamic prompts
 721 | 
 722 | Prompts can be dynamic and include:
 723 | 
 724 | ### Embedded resource context
 725 | 
 726 | ```json
 727 | {
 728 |   "name": "analyze-project",
 729 |   "description": "Analyze project logs and code",
 730 |   "arguments": [
 731 |     {
 732 |       "name": "timeframe",
 733 |       "description": "Time period to analyze logs",
 734 |       "required": true
 735 |     },
 736 |     {
 737 |       "name": "fileUri",
 738 |       "description": "URI of code file to review",
 739 |       "required": true
 740 |     }
 741 |   ]
 742 | }
 743 | ```
 744 | 
 745 | When handling the `prompts/get` request:
 746 | 
 747 | ```json
 748 | {
 749 |   "messages": [
 750 |     {
 751 |       "role": "user",
 752 |       "content": {
 753 |         "type": "text",
 754 |         "text": "Analyze these system logs and the code file for any issues:"
 755 |       }
 756 |     },
 757 |     {
 758 |       "role": "user",
 759 |       "content": {
 760 |         "type": "resource",
 761 |         "resource": {
 762 |           "uri": "logs://recent?timeframe=1h",
 763 |           "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",
 764 |           "mimeType": "text/plain"
 765 |         }
 766 |       }
 767 |     },
 768 |     {
 769 |       "role": "user",
 770 |       "content": {
 771 |         "type": "resource",
 772 |         "resource": {
 773 |           "uri": "file:///path/to/code.py",
 774 |           "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",
 775 |           "mimeType": "text/x-python"
 776 |         }
 777 |       }
 778 |     }
 779 |   ]
 780 | }
 781 | ```
 782 | 
 783 | ### Multi-step workflows
 784 | 
 785 | ```typescript
 786 | const debugWorkflow = {
 787 |   name: "debug-error",
 788 |   async getMessages(error: string) {
 789 |     return [
 790 |       {
 791 |         role: "user",
 792 |         content: {
 793 |           type: "text",
 794 |           text: `Here's an error I'm seeing: ${error}`
 795 |         }
 796 |       },
 797 |       {
 798 |         role: "assistant",
 799 |         content: {
 800 |           type: "text",
 801 |           text: "I'll help analyze this error. What have you tried so far?"
 802 |         }
 803 |       },
 804 |       {
 805 |         role: "user",
 806 |         content: {
 807 |           type: "text",
 808 |           text: "I've tried restarting the service, but the error persists."
 809 |         }
 810 |       }
 811 |     ];
 812 |   }
 813 | };
 814 | ```
 815 | 
 816 | ## Example implementation
 817 | 
 818 | Here's a complete example of implementing prompts in an MCP server:
 819 | 
 820 | <Tabs>
 821 |   <Tab title="TypeScript">
 822 |     ```typescript
 823 |     import { Server } from "@modelcontextprotocol/sdk/server";
 824 |     import {
 825 |       ListPromptsRequestSchema,
 826 |       GetPromptRequestSchema
 827 |     } from "@modelcontextprotocol/sdk/types";
 828 | 
 829 |     const PROMPTS = {
 830 |       "git-commit": {
 831 |         name: "git-commit",
 832 |         description: "Generate a Git commit message",
 833 |         arguments: [
 834 |           {
 835 |             name: "changes",
 836 |             description: "Git diff or description of changes",
 837 |             required: true
 838 |           }
 839 |         ]
 840 |       },
 841 |       "explain-code": {
 842 |         name: "explain-code",
 843 |         description: "Explain how code works",
 844 |         arguments: [
 845 |           {
 846 |             name: "code",
 847 |             description: "Code to explain",
 848 |             required: true
 849 |           },
 850 |           {
 851 |             name: "language",
 852 |             description: "Programming language",
 853 |             required: false
 854 |           }
 855 |         ]
 856 |       }
 857 |     };
 858 | 
 859 |     const server = new Server({
 860 |       name: "example-prompts-server",
 861 |       version: "1.0.0"
 862 |     }, {
 863 |       capabilities: {
 864 |         prompts: {}
 865 |       }
 866 |     });
 867 | 
 868 |     // List available prompts
 869 |     server.setRequestHandler(ListPromptsRequestSchema, async () => {
 870 |       return {
 871 |         prompts: Object.values(PROMPTS)
 872 |       };
 873 |     });
 874 | 
 875 |     // Get specific prompt
 876 |     server.setRequestHandler(GetPromptRequestSchema, async (request) => {
 877 |       const prompt = PROMPTS[request.params.name];
 878 |       if (!prompt) {
 879 |         throw new Error(`Prompt not found: ${request.params.name}`);
 880 |       }
 881 | 
 882 |       if (request.params.name === "git-commit") {
 883 |         return {
 884 |           messages: [
 885 |             {
 886 |               role: "user",
 887 |               content: {
 888 |                 type: "text",
 889 |                 text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}`
 890 |               }
 891 |             }
 892 |           ]
 893 |         };
 894 |       }
 895 | 
 896 |       if (request.params.name === "explain-code") {
 897 |         const language = request.params.arguments?.language || "Unknown";
 898 |         return {
 899 |           messages: [
 900 |             {
 901 |               role: "user",
 902 |               content: {
 903 |                 type: "text",
 904 |                 text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}`
 905 |               }
 906 |             }
 907 |           ]
 908 |         };
 909 |       }
 910 | 
 911 |       throw new Error("Prompt implementation not found");
 912 |     });
 913 |     ```
 914 |   </Tab>
 915 | 
 916 |   <Tab title="Python">
 917 |     ```python
 918 |     from mcp.server import Server
 919 |     import mcp.types as types
 920 | 
 921 |     # Define available prompts
 922 |     PROMPTS = {
 923 |         "git-commit": types.Prompt(
 924 |             name="git-commit",
 925 |             description="Generate a Git commit message",
 926 |             arguments=[
 927 |                 types.PromptArgument(
 928 |                     name="changes",
 929 |                     description="Git diff or description of changes",
 930 |                     required=True
 931 |                 )
 932 |             ],
 933 |         ),
 934 |         "explain-code": types.Prompt(
 935 |             name="explain-code",
 936 |             description="Explain how code works",
 937 |             arguments=[
 938 |                 types.PromptArgument(
 939 |                     name="code",
 940 |                     description="Code to explain",
 941 |                     required=True
 942 |                 ),
 943 |                 types.PromptArgument(
 944 |                     name="language",
 945 |                     description="Programming language",
 946 |                     required=False
 947 |                 )
 948 |             ],
 949 |         )
 950 |     }
 951 | 
 952 |     # Initialize server
 953 |     app = Server("example-prompts-server")
 954 | 
 955 |     @app.list_prompts()
 956 |     async def list_prompts() -> list[types.Prompt]:
 957 |         return list(PROMPTS.values())
 958 | 
 959 |     @app.get_prompt()
 960 |     async def get_prompt(
 961 |         name: str, arguments: dict[str, str] | None = None
 962 |     ) -> types.GetPromptResult:
 963 |         if name not in PROMPTS:
 964 |             raise ValueError(f"Prompt not found: {name}")
 965 | 
 966 |         if name == "git-commit":
 967 |             changes = arguments.get("changes") if arguments else ""
 968 |             return types.GetPromptResult(
 969 |                 messages=[
 970 |                     types.PromptMessage(
 971 |                         role="user",
 972 |                         content=types.TextContent(
 973 |                             type="text",
 974 |                             text=f"Generate a concise but descriptive commit message "
 975 |                             f"for these changes:\n\n{changes}"
 976 |                         )
 977 |                     )
 978 |                 ]
 979 |             )
 980 | 
 981 |         if name == "explain-code":
 982 |             code = arguments.get("code") if arguments else ""
 983 |             language = arguments.get("language", "Unknown") if arguments else "Unknown"
 984 |             return types.GetPromptResult(
 985 |                 messages=[
 986 |                     types.PromptMessage(
 987 |                         role="user",
 988 |                         content=types.TextContent(
 989 |                             type="text",
 990 |                             text=f"Explain how this {language} code works:\n\n{code}"
 991 |                         )
 992 |                     )
 993 |                 ]
 994 |             )
 995 | 
 996 |         raise ValueError("Prompt implementation not found")
 997 |     ```
 998 |   </Tab>
 999 | </Tabs>
1000 | 
1001 | ## Best practices
1002 | 
1003 | When implementing prompts:
1004 | 
1005 | 1.  Use clear, descriptive prompt names
1006 | 2.  Provide detailed descriptions for prompts and arguments
1007 | 3.  Validate all required arguments
1008 | 4.  Handle missing arguments gracefully
1009 | 5.  Consider versioning for prompt templates
1010 | 6.  Cache dynamic content when appropriate
1011 | 7.  Implement error handling
1012 | 8.  Document expected argument formats
1013 | 9.  Consider prompt composability
1014 | 10. Test prompts with various inputs
1015 | 
1016 | ## UI integration
1017 | 
1018 | Prompts can be surfaced in client UIs as:
1019 | 
1020 | *   Slash commands
1021 | *   Quick actions
1022 | *   Context menu items
1023 | *   Command palette entries
1024 | *   Guided workflows
1025 | *   Interactive forms
1026 | 
1027 | ## Updates and changes
1028 | 
1029 | Servers can notify clients about prompt changes:
1030 | 
1031 | 1.  Server capability: `prompts.listChanged`
1032 | 2.  Notification: `notifications/prompts/list_changed`
1033 | 3.  Client re-fetches prompt list
1034 | 
1035 | ## Security considerations
1036 | 
1037 | When implementing prompts:
1038 | 
1039 | *   Validate all arguments
1040 | *   Sanitize user input
1041 | *   Consider rate limiting
1042 | *   Implement access controls
1043 | *   Audit prompt usage
1044 | *   Handle sensitive data appropriately
1045 | *   Validate generated content
1046 | *   Implement timeouts
1047 | *   Consider prompt injection risks
1048 | *   Document security requirements
1049 | 
1050 | 
1051 | # Resources
1052 | 
1053 | Expose data and content from your servers to LLMs
1054 | 
1055 | 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.
1056 | 
1057 | <Note>
1058 |   Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used.
1059 |   Different MCP clients may handle resources differently. For example:
1060 | 
1061 |   *   Claude Desktop currently requires users to explicitly select resources before they can be used
1062 |   *   Other clients might automatically select resources based on heuristics
1063 |   *   Some implementations may even allow the AI model itself to determine which resources to use
1064 | 
1065 |   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).
1066 | </Note>
1067 | 
1068 | ## Overview
1069 | 
1070 | Resources represent any kind of data that an MCP server wants to make available to clients. This can include:
1071 | 
1072 | *   File contents
1073 | *   Database records
1074 | *   API responses
1075 | *   Live system data
1076 | *   Screenshots and images
1077 | *   Log files
1078 | *   And more
1079 | 
1080 | Each resource is identified by a unique URI and can contain either text or binary data.
1081 | 
1082 | ## Resource URIs
1083 | 
1084 | Resources are identified using URIs that follow this format:
1085 | 
1086 | ```
1087 | [protocol]://[host]/[path]
1088 | ```
1089 | 
1090 | For example:
1091 | 
1092 | *   `file:///home/user/documents/report.pdf`
1093 | *   `postgres://database/customers/schema`
1094 | *   `screen://localhost/display1`
1095 | 
1096 | The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.
1097 | 
1098 | ## Resource types
1099 | 
1100 | Resources can contain two types of content:
1101 | 
1102 | ### Text resources
1103 | 
1104 | Text resources contain UTF-8 encoded text data. These are suitable for:
1105 | 
1106 | *   Source code
1107 | *   Configuration files
1108 | *   Log files
1109 | *   JSON/XML data
1110 | *   Plain text
1111 | 
1112 | ### Binary resources
1113 | 
1114 | Binary resources contain raw binary data encoded in base64. These are suitable for:
1115 | 
1116 | *   Images
1117 | *   PDFs
1118 | *   Audio files
1119 | *   Video files
1120 | *   Other non-text formats
1121 | 
1122 | ## Resource discovery
1123 | 
1124 | Clients can discover available resources through two main methods:
1125 | 
1126 | ### Direct resources
1127 | 
1128 | Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes:
1129 | 
1130 | ```typescript
1131 | {
1132 |   uri: string;           // Unique identifier for the resource
1133 |   name: string;          // Human-readable name
1134 |   description?: string;  // Optional description
1135 |   mimeType?: string;     // Optional MIME type
1136 | }
1137 | ```
1138 | 
1139 | ### Resource templates
1140 | 
1141 | For dynamic resources, servers can expose [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) that clients can use to construct valid resource URIs:
1142 | 
1143 | ```typescript
1144 | {
1145 |   uriTemplate: string;   // URI template following RFC 6570
1146 |   name: string;          // Human-readable name for this type
1147 |   description?: string;  // Optional description
1148 |   mimeType?: string;     // Optional MIME type for all matching resources
1149 | }
1150 | ```
1151 | 
1152 | ## Reading resources
1153 | 
1154 | To read a resource, clients make a `resources/read` request with the resource URI.
1155 | 
1156 | The server responds with a list of resource contents:
1157 | 
1158 | ```typescript
1159 | {
1160 |   contents: [
1161 |     {
1162 |       uri: string;        // The URI of the resource
1163 |       mimeType?: string;  // Optional MIME type
1164 | 
1165 |       // One of:
1166 |       text?: string;      // For text resources
1167 |       blob?: string;      // For binary resources (base64 encoded)
1168 |     }
1169 |   ]
1170 | }
1171 | ```
1172 | 
1173 | <Tip>
1174 |   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.
1175 | </Tip>
1176 | 
1177 | ## Resource updates
1178 | 
1179 | MCP supports real-time updates for resources through two mechanisms:
1180 | 
1181 | ### List changes
1182 | 
1183 | Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification.
1184 | 
1185 | ### Content changes
1186 | 
1187 | Clients can subscribe to updates for specific resources:
1188 | 
1189 | 1.  Client sends `resources/subscribe` with resource URI
1190 | 2.  Server sends `notifications/resources/updated` when the resource changes
1191 | 3.  Client can fetch latest content with `resources/read`
1192 | 4.  Client can unsubscribe with `resources/unsubscribe`
1193 | 
1194 | ## Example implementation
1195 | 
1196 | Here's a simple example of implementing resource support in an MCP server:
1197 | 
1198 | <Tabs>
1199 |   <Tab title="TypeScript">
1200 |     ```typescript
1201 |     const server = new Server({
1202 |       name: "example-server",
1203 |       version: "1.0.0"
1204 |     }, {
1205 |       capabilities: {
1206 |         resources: {}
1207 |       }
1208 |     });
1209 | 
1210 |     // List available resources
1211 |     server.setRequestHandler(ListResourcesRequestSchema, async () => {
1212 |       return {
1213 |         resources: [
1214 |           {
1215 |             uri: "file:///logs/app.log",
1216 |             name: "Application Logs",
1217 |             mimeType: "text/plain"
1218 |           }
1219 |         ]
1220 |       };
1221 |     });
1222 | 
1223 |     // Read resource contents
1224 |     server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
1225 |       const uri = request.params.uri;
1226 | 
1227 |       if (uri === "file:///logs/app.log") {
1228 |         const logContents = await readLogFile();
1229 |         return {
1230 |           contents: [
1231 |             {
1232 |               uri,
1233 |               mimeType: "text/plain",
1234 |               text: logContents
1235 |             }
1236 |           ]
1237 |         };
1238 |       }
1239 | 
1240 |       throw new Error("Resource not found");
1241 |     });
1242 |     ```
1243 |   </Tab>
1244 | 
1245 |   <Tab title="Python">
1246 |     ```python
1247 |     app = Server("example-server")
1248 | 
1249 |     @app.list_resources()
1250 |     async def list_resources() -> list[types.Resource]:
1251 |         return [
1252 |             types.Resource(
1253 |                 uri="file:///logs/app.log",
1254 |                 name="Application Logs",
1255 |                 mimeType="text/plain"
1256 |             )
1257 |         ]
1258 | 
1259 |     @app.read_resource()
1260 |     async def read_resource(uri: AnyUrl) -> str:
1261 |         if str(uri) == "file:///logs/app.log":
1262 |             log_contents = await read_log_file()
1263 |             return log_contents
1264 | 
1265 |         raise ValueError("Resource not found")
1266 | 
1267 |     # Start server
1268 |     async with stdio_server() as streams:
1269 |         await app.run(
1270 |             streams[0],
1271 |             streams[1],
1272 |             app.create_initialization_options()
1273 |         )
1274 |     ```
1275 |   </Tab>
1276 | </Tabs>
1277 | 
1278 | ## Best practices
1279 | 
1280 | When implementing resource support:
1281 | 
1282 | 1.  Use clear, descriptive resource names and URIs
1283 | 2.  Include helpful descriptions to guide LLM understanding
1284 | 3.  Set appropriate MIME types when known
1285 | 4.  Implement resource templates for dynamic content
1286 | 5.  Use subscriptions for frequently changing resources
1287 | 6.  Handle errors gracefully with clear error messages
1288 | 7.  Consider pagination for large resource lists
1289 | 8.  Cache resource contents when appropriate
1290 | 9.  Validate URIs before processing
1291 | 10. Document your custom URI schemes
1292 | 
1293 | ## Security considerations
1294 | 
1295 | When exposing resources:
1296 | 
1297 | *   Validate all resource URIs
1298 | *   Implement appropriate access controls
1299 | *   Sanitize file paths to prevent directory traversal
1300 | *   Be cautious with binary data handling
1301 | *   Consider rate limiting for resource reads
1302 | *   Audit resource access
1303 | *   Encrypt sensitive data in transit
1304 | *   Validate MIME types
1305 | *   Implement timeouts for long-running reads
1306 | *   Handle resource cleanup appropriately
1307 | 
1308 | 
1309 | # Roots
1310 | 
1311 | Understanding roots in MCP
1312 | 
1313 | 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.
1314 | 
1315 | ## What are Roots?
1316 | 
1317 | 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.
1318 | 
1319 | For example, roots could be:
1320 | 
1321 | ```
1322 | file:///home/user/projects/myapp
1323 | https://api.example.com/v1
1324 | ```
1325 | 
1326 | ## Why Use Roots?
1327 | 
1328 | Roots serve several important purposes:
1329 | 
1330 | 1.  **Guidance**: They inform servers about relevant resources and locations
1331 | 2.  **Clarity**: Roots make it clear which resources are part of your workspace
1332 | 3.  **Organization**: Multiple roots let you work with different resources simultaneously
1333 | 
1334 | ## How Roots Work
1335 | 
1336 | When a client supports roots, it:
1337 | 
1338 | 1.  Declares the `roots` capability during connection
1339 | 2.  Provides a list of suggested roots to the server
1340 | 3.  Notifies the server when roots change (if supported)
1341 | 
1342 | While roots are informational and not strictly enforcing, servers should:
1343 | 
1344 | 1.  Respect the provided roots
1345 | 2.  Use root URIs to locate and access resources
1346 | 3.  Prioritize operations within root boundaries
1347 | 
1348 | ## Common Use Cases
1349 | 
1350 | Roots are commonly used to define:
1351 | 
1352 | *   Project directories
1353 | *   Repository locations
1354 | *   API endpoints
1355 | *   Configuration locations
1356 | *   Resource boundaries
1357 | 
1358 | ## Best Practices
1359 | 
1360 | When working with roots:
1361 | 
1362 | 1.  Only suggest necessary resources
1363 | 2.  Use clear, descriptive names for roots
1364 | 3.  Monitor root accessibility
1365 | 4.  Handle root changes gracefully
1366 | 
1367 | ## Example
1368 | 
1369 | Here's how a typical MCP client might expose roots:
1370 | 
1371 | ```json
1372 | {
1373 |   "roots": [
1374 |     {
1375 |       "uri": "file:///home/user/projects/frontend",
1376 |       "name": "Frontend Repository"
1377 |     },
1378 |     {
1379 |       "uri": "https://api.example.com/v1",
1380 |       "name": "API Endpoint"
1381 |     }
1382 |   ]
1383 | }
1384 | ```
1385 | 
1386 | This configuration suggests the server focus on both a local repository and an API endpoint while keeping them logically separated.
1387 | 
1388 | 
1389 | # Sampling
1390 | 
1391 | Let your servers request completions from LLMs
1392 | 
1393 | 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.
1394 | 
1395 | <Info>
1396 |   This feature of MCP is not yet supported in the Claude Desktop client.
1397 | </Info>
1398 | 
1399 | ## How sampling works
1400 | 
1401 | The sampling flow follows these steps:
1402 | 
1403 | 1.  Server sends a `sampling/createMessage` request to the client
1404 | 2.  Client reviews the request and can modify it
1405 | 3.  Client samples from an LLM
1406 | 4.  Client reviews the completion
1407 | 5.  Client returns the result to the server
1408 | 
1409 | This human-in-the-loop design ensures users maintain control over what the LLM sees and generates.
1410 | 
1411 | ## Message format
1412 | 
1413 | Sampling requests use a standardized message format:
1414 | 
1415 | ```typescript
1416 | {
1417 |   messages: [
1418 |     {
1419 |       role: "user" | "assistant",
1420 |       content: {
1421 |         type: "text" | "image",
1422 | 
1423 |         // For text:
1424 |         text?: string,
1425 | 
1426 |         // For images:
1427 |         data?: string,             // base64 encoded
1428 |         mimeType?: string
1429 |       }
1430 |     }
1431 |   ],
1432 |   modelPreferences?: {
1433 |     hints?: [{
1434 |       name?: string                // Suggested model name/family
1435 |     }],
1436 |     costPriority?: number,         // 0-1, importance of minimizing cost
1437 |     speedPriority?: number,        // 0-1, importance of low latency
1438 |     intelligencePriority?: number  // 0-1, importance of capabilities
1439 |   },
1440 |   systemPrompt?: string,
1441 |   includeContext?: "none" | "thisServer" | "allServers",
1442 |   temperature?: number,
1443 |   maxTokens: number,
1444 |   stopSequences?: string[],
1445 |   metadata?: Record<string, unknown>
1446 | }
1447 | ```
1448 | 
1449 | ## Request parameters
1450 | 
1451 | ### Messages
1452 | 
1453 | The `messages` array contains the conversation history to send to the LLM. Each message has:
1454 | 
1455 | *   `role`: Either "user" or "assistant"
1456 | *   `content`: The message content, which can be:
1457 |     *   Text content with a `text` field
1458 |     *   Image content with `data` (base64) and `mimeType` fields
1459 | 
1460 | ### Model preferences
1461 | 
1462 | The `modelPreferences` object allows servers to specify their model selection preferences:
1463 | 
1464 | *   `hints`: Array of model name suggestions that clients can use to select an appropriate model:
1465 |     *   `name`: String that can match full or partial model names (e.g. "claude-3", "sonnet")
1466 |     *   Clients may map hints to equivalent models from different providers
1467 |     *   Multiple hints are evaluated in preference order
1468 | 
1469 | *   Priority values (0-1 normalized):
1470 |     *   `costPriority`: Importance of minimizing costs
1471 |     *   `speedPriority`: Importance of low latency response
1472 |     *   `intelligencePriority`: Importance of advanced model capabilities
1473 | 
1474 | Clients make the final model selection based on these preferences and their available models.
1475 | 
1476 | ### System prompt
1477 | 
1478 | An optional `systemPrompt` field allows servers to request a specific system prompt. The client may modify or ignore this.
1479 | 
1480 | ### Context inclusion
1481 | 
1482 | The `includeContext` parameter specifies what MCP context to include:
1483 | 
1484 | *   `"none"`: No additional context
1485 | *   `"thisServer"`: Include context from the requesting server
1486 | *   `"allServers"`: Include context from all connected MCP servers
1487 | 
1488 | The client controls what context is actually included.
1489 | 
1490 | ### Sampling parameters
1491 | 
1492 | Fine-tune the LLM sampling with:
1493 | 
1494 | *   `temperature`: Controls randomness (0.0 to 1.0)
1495 | *   `maxTokens`: Maximum tokens to generate
1496 | *   `stopSequences`: Array of sequences that stop generation
1497 | *   `metadata`: Additional provider-specific parameters
1498 | 
1499 | ## Response format
1500 | 
1501 | The client returns a completion result:
1502 | 
1503 | ```typescript
1504 | {
1505 |   model: string,  // Name of the model used
1506 |   stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
1507 |   role: "user" | "assistant",
1508 |   content: {
1509 |     type: "text" | "image",
1510 |     text?: string,
1511 |     data?: string,
1512 |     mimeType?: string
1513 |   }
1514 | }
1515 | ```
1516 | 
1517 | ## Example request
1518 | 
1519 | Here's an example of requesting sampling from a client:
1520 | 
1521 | ```json
1522 | {
1523 |   "method": "sampling/createMessage",
1524 |   "params": {
1525 |     "messages": [
1526 |       {
1527 |         "role": "user",
1528 |         "content": {
1529 |           "type": "text",
1530 |           "text": "What files are in the current directory?"
1531 |         }
1532 |       }
1533 |     ],
1534 |     "systemPrompt": "You are a helpful file system assistant.",
1535 |     "includeContext": "thisServer",
1536 |     "maxTokens": 100
1537 |   }
1538 | }
1539 | ```
1540 | 
1541 | ## Best practices
1542 | 
1543 | When implementing sampling:
1544 | 
1545 | 1.  Always provide clear, well-structured prompts
1546 | 2.  Handle both text and image content appropriately
1547 | 3.  Set reasonable token limits
1548 | 4.  Include relevant context through `includeContext`
1549 | 5.  Validate responses before using them
1550 | 6.  Handle errors gracefully
1551 | 7.  Consider rate limiting sampling requests
1552 | 8.  Document expected sampling behavior
1553 | 9.  Test with various model parameters
1554 | 10. Monitor sampling costs
1555 | 
1556 | ## Human in the loop controls
1557 | 
1558 | Sampling is designed with human oversight in mind:
1559 | 
1560 | ### For prompts
1561 | 
1562 | *   Clients should show users the proposed prompt
1563 | *   Users should be able to modify or reject prompts
1564 | *   System prompts can be filtered or modified
1565 | *   Context inclusion is controlled by the client
1566 | 
1567 | ### For completions
1568 | 
1569 | *   Clients should show users the completion
1570 | *   Users should be able to modify or reject completions
1571 | *   Clients can filter or modify completions
1572 | *   Users control which model is used
1573 | 
1574 | ## Security considerations
1575 | 
1576 | When implementing sampling:
1577 | 
1578 | *   Validate all message content
1579 | *   Sanitize sensitive information
1580 | *   Implement appropriate rate limits
1581 | *   Monitor sampling usage
1582 | *   Encrypt data in transit
1583 | *   Handle user data privacy
1584 | *   Audit sampling requests
1585 | *   Control cost exposure
1586 | *   Implement timeouts
1587 | *   Handle model errors gracefully
1588 | 
1589 | ## Common patterns
1590 | 
1591 | ### Agentic workflows
1592 | 
1593 | Sampling enables agentic patterns like:
1594 | 
1595 | *   Reading and analyzing resources
1596 | *   Making decisions based on context
1597 | *   Generating structured data
1598 | *   Handling multi-step tasks
1599 | *   Providing interactive assistance
1600 | 
1601 | ### Context management
1602 | 
1603 | Best practices for context:
1604 | 
1605 | *   Request minimal necessary context
1606 | *   Structure context clearly
1607 | *   Handle context size limits
1608 | *   Update context as needed
1609 | *   Clean up stale context
1610 | 
1611 | ### Error handling
1612 | 
1613 | Robust error handling should:
1614 | 
1615 | *   Catch sampling failures
1616 | *   Handle timeout errors
1617 | *   Manage rate limits
1618 | *   Validate responses
1619 | *   Provide fallback behaviors
1620 | *   Log errors appropriately
1621 | 
1622 | ## Limitations
1623 | 
1624 | Be aware of these limitations:
1625 | 
1626 | *   Sampling depends on client capabilities
1627 | *   Users control sampling behavior
1628 | *   Context size has limits
1629 | *   Rate limits may apply
1630 | *   Costs should be considered
1631 | *   Model availability varies
1632 | *   Response times vary
1633 | *   Not all content types supported
1634 | 
1635 | 
1636 | # Tools
1637 | 
1638 | Enable LLMs to perform actions through your server
1639 | 
1640 | 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.
1641 | 
1642 | <Note>
1643 |   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).
1644 | </Note>
1645 | 
1646 | ## Overview
1647 | 
1648 | 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:
1649 | 
1650 | *   **Discovery**: Clients can list available tools through the `tools/list` endpoint
1651 | *   **Invocation**: Tools are called using the `tools/call` endpoint, where servers perform the requested operation and return results
1652 | *   **Flexibility**: Tools can range from simple calculations to complex API interactions
1653 | 
1654 | 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.
1655 | 
1656 | ## Tool definition structure
1657 | 
1658 | Each tool is defined with the following structure:
1659 | 
1660 | ```typescript
1661 | {
1662 |   name: string;          // Unique identifier for the tool
1663 |   description?: string;  // Human-readable description
1664 |   inputSchema: {         // JSON Schema for the tool's parameters
1665 |     type: "object",
1666 |     properties: { ... }  // Tool-specific parameters
1667 |   }
1668 | }
1669 | ```
1670 | 
1671 | ## Implementing tools
1672 | 
1673 | Here's an example of implementing a basic tool in an MCP server:
1674 | 
1675 | <Tabs>
1676 |   <Tab title="TypeScript">
1677 |     ```typescript
1678 |     const server = new Server({
1679 |       name: "example-server",
1680 |       version: "1.0.0"
1681 |     }, {
1682 |       capabilities: {
1683 |         tools: {}
1684 |       }
1685 |     });
1686 | 
1687 |     // Define available tools
1688 |     server.setRequestHandler(ListToolsRequestSchema, async () => {
1689 |       return {
1690 |         tools: [{
1691 |           name: "calculate_sum",
1692 |           description: "Add two numbers together",
1693 |           inputSchema: {
1694 |             type: "object",
1695 |             properties: {
1696 |               a: { type: "number" },
1697 |               b: { type: "number" }
1698 |             },
1699 |             required: ["a", "b"]
1700 |           }
1701 |         }]
1702 |       };
1703 |     });
1704 | 
1705 |     // Handle tool execution
1706 |     server.setRequestHandler(CallToolRequestSchema, async (request) => {
1707 |       if (request.params.name === "calculate_sum") {
1708 |         const { a, b } = request.params.arguments;
1709 |         return {
1710 |           content: [
1711 |             {
1712 |               type: "text",
1713 |               text: String(a + b)
1714 |             }
1715 |           ]
1716 |         };
1717 |       }
1718 |       throw new Error("Tool not found");
1719 |     });
1720 |     ```
1721 |   </Tab>
1722 | 
1723 |   <Tab title="Python">
1724 |     ```python
1725 |     app = Server("example-server")
1726 | 
1727 |     @app.list_tools()
1728 |     async def list_tools() -> list[types.Tool]:
1729 |         return [
1730 |             types.Tool(
1731 |                 name="calculate_sum",
1732 |                 description="Add two numbers together",
1733 |                 inputSchema={
1734 |                     "type": "object",
1735 |                     "properties": {
1736 |                         "a": {"type": "number"},
1737 |                         "b": {"type": "number"}
1738 |                     },
1739 |                     "required": ["a", "b"]
1740 |                 }
1741 |             )
1742 |         ]
1743 | 
1744 |     @app.call_tool()
1745 |     async def call_tool(
1746 |         name: str,
1747 |         arguments: dict
1748 |     ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
1749 |         if name == "calculate_sum":
1750 |             a = arguments["a"]
1751 |             b = arguments["b"]
1752 |             result = a + b
1753 |             return [types.TextContent(type="text", text=str(result))]
1754 |         raise ValueError(f"Tool not found: {name}")
1755 |     ```
1756 |   </Tab>
1757 | </Tabs>
1758 | 
1759 | ## Example tool patterns
1760 | 
1761 | Here are some examples of types of tools that a server could provide:
1762 | 
1763 | ### System operations
1764 | 
1765 | Tools that interact with the local system:
1766 | 
1767 | ```typescript
1768 | {
1769 |   name: "execute_command",
1770 |   description: "Run a shell command",
1771 |   inputSchema: {
1772 |     type: "object",
1773 |     properties: {
1774 |       command: { type: "string" },
1775 |       args: { type: "array", items: { type: "string" } }
1776 |     }
1777 |   }
1778 | }
1779 | ```
1780 | 
1781 | ### API integrations
1782 | 
1783 | Tools that wrap external APIs:
1784 | 
1785 | ```typescript
1786 | {
1787 |   name: "github_create_issue",
1788 |   description: "Create a GitHub issue",
1789 |   inputSchema: {
1790 |     type: "object",
1791 |     properties: {
1792 |       title: { type: "string" },
1793 |       body: { type: "string" },
1794 |       labels: { type: "array", items: { type: "string" } }
1795 |     }
1796 |   }
1797 | }
1798 | ```
1799 | 
1800 | ### Data processing
1801 | 
1802 | Tools that transform or analyze data:
1803 | 
1804 | ```typescript
1805 | {
1806 |   name: "analyze_csv",
1807 |   description: "Analyze a CSV file",
1808 |   inputSchema: {
1809 |     type: "object",
1810 |     properties: {
1811 |       filepath: { type: "string" },
1812 |       operations: {
1813 |         type: "array",
1814 |         items: {
1815 |           enum: ["sum", "average", "count"]
1816 |         }
1817 |       }
1818 |     }
1819 |   }
1820 | }
1821 | ```
1822 | 
1823 | ## Best practices
1824 | 
1825 | When implementing tools:
1826 | 
1827 | 1.  Provide clear, descriptive names and descriptions
1828 | 2.  Use detailed JSON Schema definitions for parameters
1829 | 3.  Include examples in tool descriptions to demonstrate how the model should use them
1830 | 4.  Implement proper error handling and validation
1831 | 5.  Use progress reporting for long operations
1832 | 6.  Keep tool operations focused and atomic
1833 | 7.  Document expected return value structures
1834 | 8.  Implement proper timeouts
1835 | 9.  Consider rate limiting for resource-intensive operations
1836 | 10. Log tool usage for debugging and monitoring
1837 | 
1838 | ## Security considerations
1839 | 
1840 | When exposing tools:
1841 | 
1842 | ### Input validation
1843 | 
1844 | *   Validate all parameters against the schema
1845 | *   Sanitize file paths and system commands
1846 | *   Validate URLs and external identifiers
1847 | *   Check parameter sizes and ranges
1848 | *   Prevent command injection
1849 | 
1850 | ### Access control
1851 | 
1852 | *   Implement authentication where needed
1853 | *   Use appropriate authorization checks
1854 | *   Audit tool usage
1855 | *   Rate limit requests
1856 | *   Monitor for abuse
1857 | 
1858 | ### Error handling
1859 | 
1860 | *   Don't expose internal errors to clients
1861 | *   Log security-relevant errors
1862 | *   Handle timeouts appropriately
1863 | *   Clean up resources after errors
1864 | *   Validate return values
1865 | 
1866 | ## Tool discovery and updates
1867 | 
1868 | MCP supports dynamic tool discovery:
1869 | 
1870 | 1.  Clients can list available tools at any time
1871 | 2.  Servers can notify clients when tools change using `notifications/tools/list_changed`
1872 | 3.  Tools can be added or removed during runtime
1873 | 4.  Tool definitions can be updated (though this should be done carefully)
1874 | 
1875 | ## Error handling
1876 | 
1877 | 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:
1878 | 
1879 | 1.  Set `isError` to `true` in the result
1880 | 2.  Include error details in the `content` array
1881 | 
1882 | Here's an example of proper error handling for tools:
1883 | 
1884 | <Tabs>
1885 |   <Tab title="TypeScript">
1886 |     ```typescript
1887 |     try {
1888 |       // Tool operation
1889 |       const result = performOperation();
1890 |       return {
1891 |         content: [
1892 |           {
1893 |             type: "text",
1894 |             text: `Operation successful: ${result}`
1895 |           }
1896 |         ]
1897 |       };
1898 |     } catch (error) {
1899 |       return {
1900 |         isError: true,
1901 |         content: [
1902 |           {
1903 |             type: "text",
1904 |             text: `Error: ${error.message}`
1905 |           }
1906 |         ]
1907 |       };
1908 |     }
1909 |     ```
1910 |   </Tab>
1911 | 
1912 |   <Tab title="Python">
1913 |     ```python
1914 |     try:
1915 |         # Tool operation
1916 |         result = perform_operation()
1917 |         return types.CallToolResult(
1918 |             content=[
1919 |                 types.TextContent(
1920 |                     type="text",
1921 |                     text=f"Operation successful: {result}"
1922 |                 )
1923 |             ]
1924 |         )
1925 |     except Exception as error:
1926 |         return types.CallToolResult(
1927 |             isError=True,
1928 |             content=[
1929 |                 types.TextContent(
1930 |                     type="text",
1931 |                     text=f"Error: {str(error)}"
1932 |                 )
1933 |             ]
1934 |         )
1935 |     ```
1936 |   </Tab>
1937 | </Tabs>
1938 | 
1939 | This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention.
1940 | 
1941 | ## Testing tools
1942 | 
1943 | A comprehensive testing strategy for MCP tools should cover:
1944 | 
1945 | *   **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately
1946 | *   **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies
1947 | *   **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting
1948 | *   **Performance testing**: Check behavior under load, timeout handling, and resource cleanup
1949 | *   **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources
1950 | 
1951 | 
1952 | # Transports
1953 | 
1954 | Learn about MCP's communication mechanisms
1955 | 
1956 | 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.
1957 | 
1958 | ## Message Format
1959 | 
1960 | 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.
1961 | 
1962 | There are three types of JSON-RPC messages used:
1963 | 
1964 | ### Requests
1965 | 
1966 | ```typescript
1967 | {
1968 |   jsonrpc: "2.0",
1969 |   id: number | string,
1970 |   method: string,
1971 |   params?: object
1972 | }
1973 | ```
1974 | 
1975 | ### Responses
1976 | 
1977 | ```typescript
1978 | {
1979 |   jsonrpc: "2.0",
1980 |   id: number | string,
1981 |   result?: object,
1982 |   error?: {
1983 |     code: number,
1984 |     message: string,
1985 |     data?: unknown
1986 |   }
1987 | }
1988 | ```
1989 | 
1990 | ### Notifications
1991 | 
1992 | ```typescript
1993 | {
1994 |   jsonrpc: "2.0",
1995 |   method: string,
1996 |   params?: object
1997 | }
1998 | ```
1999 | 
2000 | ## Built-in Transport Types
2001 | 
2002 | MCP includes two standard transport implementations:
2003 | 
2004 | ### Standard Input/Output (stdio)
2005 | 
2006 | The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.
2007 | 
2008 | Use stdio when:
2009 | 
2010 | *   Building command-line tools
2011 | *   Implementing local integrations
2012 | *   Needing simple process communication
2013 | *   Working with shell scripts
2014 | 
2015 | <Tabs>
2016 |   <Tab title="TypeScript (Server)">
2017 |     ```typescript
2018 |     const server = new Server({
2019 |       name: "example-server",
2020 |       version: "1.0.0"
2021 |     }, {
2022 |       capabilities: {}
2023 |     });
2024 | 
2025 |     const transport = new StdioServerTransport();
2026 |     await server.connect(transport);
2027 |     ```
2028 |   </Tab>
2029 | 
2030 |   <Tab title="TypeScript (Client)">
2031 |     ```typescript
2032 |     const client = new Client({
2033 |       name: "example-client",
2034 |       version: "1.0.0"
2035 |     }, {
2036 |       capabilities: {}
2037 |     });
2038 | 
2039 |     const transport = new StdioClientTransport({
2040 |       command: "./server",
2041 |       args: ["--option", "value"]
2042 |     });
2043 |     await client.connect(transport);
2044 |     ```
2045 |   </Tab>
2046 | 
2047 |   <Tab title="Python (Server)">
2048 |     ```python
2049 |     app = Server("example-server")
2050 | 
2051 |     async with stdio_server() as streams:
2052 |         await app.run(
2053 |             streams[0],
2054 |             streams[1],
2055 |             app.create_initialization_options()
2056 |         )
2057 |     ```
2058 |   </Tab>
2059 | 
2060 |   <Tab title="Python (Client)">
2061 |     ```python
2062 |     params = StdioServerParameters(
2063 |         command="./server",
2064 |         args=["--option", "value"]
2065 |     )
2066 | 
2067 |     async with stdio_client(params) as streams:
2068 |         async with ClientSession(streams[0], streams[1]) as session:
2069 |             await session.initialize()
2070 |     ```
2071 |   </Tab>
2072 | </Tabs>
2073 | 
2074 | ### Server-Sent Events (SSE)
2075 | 
2076 | SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication.
2077 | 
2078 | Use SSE when:
2079 | 
2080 | *   Only server-to-client streaming is needed
2081 | *   Working with restricted networks
2082 | *   Implementing simple updates
2083 | 
2084 | <Tabs>
2085 |   <Tab title="TypeScript (Server)">
2086 |     ```typescript
2087 |     const server = new Server({
2088 |       name: "example-server",
2089 |       version: "1.0.0"
2090 |     }, {
2091 |       capabilities: {}
2092 |     });
2093 | 
2094 |     const transport = new SSEServerTransport("/message", response);
2095 |     await server.connect(transport);
2096 |     ```
2097 |   </Tab>
2098 | 
2099 |   <Tab title="TypeScript (Client)">
2100 |     ```typescript
2101 |     const client = new Client({
2102 |       name: "example-client",
2103 |       version: "1.0.0"
2104 |     }, {
2105 |       capabilities: {}
2106 |     });
2107 | 
2108 |     const transport = new SSEClientTransport(
2109 |       new URL("http://localhost:3000/sse")
2110 |     );
2111 |     await client.connect(transport);
2112 |     ```
2113 |   </Tab>
2114 | 
2115 |   <Tab title="Python (Server)">
2116 |     ```python
2117 |     from mcp.server.sse import SseServerTransport
2118 |     from starlette.applications import Starlette
2119 |     from starlette.routing import Route
2120 | 
2121 |     app = Server("example-server")
2122 |     sse = SseServerTransport("/messages")
2123 | 
2124 |     async def handle_sse(scope, receive, send):
2125 |         async with sse.connect_sse(scope, receive, send) as streams:
2126 |             await app.run(streams[0], streams[1], app.create_initialization_options())
2127 | 
2128 |     async def handle_messages(scope, receive, send):
2129 |         await sse.handle_post_message(scope, receive, send)
2130 | 
2131 |     starlette_app = Starlette(
2132 |         routes=[
2133 |             Route("/sse", endpoint=handle_sse),
2134 |             Route("/messages", endpoint=handle_messages, methods=["POST"]),
2135 |         ]
2136 |     )
2137 |     ```
2138 |   </Tab>
2139 | 
2140 |   <Tab title="Python (Client)">
2141 |     ```python
2142 |     async with sse_client("http://localhost:8000/sse") as streams:
2143 |         async with ClientSession(streams[0], streams[1]) as session:
2144 |             await session.initialize()
2145 |     ```
2146 |   </Tab>
2147 | </Tabs>
2148 | 
2149 | ## Custom Transports
2150 | 
2151 | MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface:
2152 | 
2153 | You can implement custom transports for:
2154 | 
2155 | *   Custom network protocols
2156 | *   Specialized communication channels
2157 | *   Integration with existing systems
2158 | *   Performance optimization
2159 | 
2160 | <Tabs>
2161 |   <Tab title="TypeScript">
2162 |     ```typescript
2163 |     interface Transport {
2164 |       // Start processing messages
2165 |       start(): Promise<void>;
2166 | 
2167 |       // Send a JSON-RPC message
2168 |       send(message: JSONRPCMessage): Promise<void>;
2169 | 
2170 |       // Close the connection
2171 |       close(): Promise<void>;
2172 | 
2173 |       // Callbacks
2174 |       onclose?: () => void;
2175 |       onerror?: (error: Error) => void;
2176 |       onmessage?: (message: JSONRPCMessage) => void;
2177 |     }
2178 |     ```
2179 |   </Tab>
2180 | 
2181 |   <Tab title="Python">
2182 |     Note that while MCP Servers are often implemented with asyncio, we recommend
2183 |     implementing low-level interfaces like transports with `anyio` for wider compatibility.
2184 | 
2185 |     ```python
2186 |     @contextmanager
2187 |     async def create_transport(
2188 |         read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
2189 |         write_stream: MemoryObjectSendStream[JSONRPCMessage]
2190 |     ):
2191 |         """
2192 |         Transport interface for MCP.
2193 | 
2194 |         Args:
2195 |             read_stream: Stream to read incoming messages from
2196 |             write_stream: Stream to write outgoing messages to
2197 |         """
2198 |         async with anyio.create_task_group() as tg:
2199 |             try:
2200 |                 # Start processing messages
2201 |                 tg.start_soon(lambda: process_messages(read_stream))
2202 | 
2203 |                 # Send messages
2204 |                 async with write_stream:
2205 |                     yield write_stream
2206 | 
2207 |             except Exception as exc:
2208 |                 # Handle errors
2209 |                 raise exc
2210 |             finally:
2211 |                 # Clean up
2212 |                 tg.cancel_scope.cancel()
2213 |                 await write_stream.aclose()
2214 |                 await read_stream.aclose()
2215 |     ```
2216 |   </Tab>
2217 | </Tabs>
2218 | 
2219 | ## Error Handling
2220 | 
2221 | Transport implementations should handle various error scenarios:
2222 | 
2223 | 1.  Connection errors
2224 | 2.  Message parsing errors
2225 | 3.  Protocol errors
2226 | 4.  Network timeouts
2227 | 5.  Resource cleanup
2228 | 
2229 | Example error handling:
2230 | 
2231 | <Tabs>
2232 |   <Tab title="TypeScript">
2233 |     ```typescript
2234 |     class ExampleTransport implements Transport {
2235 |       async start() {
2236 |         try {
2237 |           // Connection logic
2238 |         } catch (error) {
2239 |           this.onerror?.(new Error(`Failed to connect: ${error}`));
2240 |           throw error;
2241 |         }
2242 |       }
2243 | 
2244 |       async send(message: JSONRPCMessage) {
2245 |         try {
2246 |           // Sending logic
2247 |         } catch (error) {
2248 |           this.onerror?.(new Error(`Failed to send message: ${error}`));
2249 |           throw error;
2250 |         }
2251 |       }
2252 |     }
2253 |     ```
2254 |   </Tab>
2255 | 
2256 |   <Tab title="Python">
2257 |     Note that while MCP Servers are often implemented with asyncio, we recommend
2258 |     implementing low-level interfaces like transports with `anyio` for wider compatibility.
2259 | 
2260 |     ```python
2261 |     @contextmanager
2262 |     async def example_transport(scope: Scope, receive: Receive, send: Send):
2263 |         try:
2264 |             # Create streams for bidirectional communication
2265 |             read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
2266 |             write_stream, write_stream_reader = anyio.create_memory_object_stream(0)
2267 | 
2268 |             async def message_handler():
2269 |                 try:
2270 |                     async with read_stream_writer:
2271 |                         # Message handling logic
2272 |                         pass
2273 |                 except Exception as exc:
2274 |                     logger.error(f"Failed to handle message: {exc}")
2275 |                     raise exc
2276 | 
2277 |             async with anyio.create_task_group() as tg:
2278 |                 tg.start_soon(message_handler)
2279 |                 try:
2280 |                     # Yield streams for communication
2281 |                     yield read_stream, write_stream
2282 |                 except Exception as exc:
2283 |                     logger.error(f"Transport error: {exc}")
2284 |                     raise exc
2285 |                 finally:
2286 |                     tg.cancel_scope.cancel()
2287 |                     await write_stream.aclose()
2288 |                     await read_stream.aclose()
2289 |         except Exception as exc:
2290 |             logger.error(f"Failed to initialize transport: {exc}")
2291 |             raise exc
2292 |     ```
2293 |   </Tab>
2294 | </Tabs>
2295 | 
2296 | ## Best Practices
2297 | 
2298 | When implementing or using MCP transport:
2299 | 
2300 | 1.  Handle connection lifecycle properly
2301 | 2.  Implement proper error handling
2302 | 3.  Clean up resources on connection close
2303 | 4.  Use appropriate timeouts
2304 | 5.  Validate messages before sending
2305 | 6.  Log transport events for debugging
2306 | 7.  Implement reconnection logic when appropriate
2307 | 8.  Handle backpressure in message queues
2308 | 9.  Monitor connection health
2309 | 10. Implement proper security measures
2310 | 
2311 | ## Security Considerations
2312 | 
2313 | When implementing transport:
2314 | 
2315 | ### Authentication and Authorization
2316 | 
2317 | *   Implement proper authentication mechanisms
2318 | *   Validate client credentials
2319 | *   Use secure token handling
2320 | *   Implement authorization checks
2321 | 
2322 | ### Data Security
2323 | 
2324 | *   Use TLS for network transport
2325 | *   Encrypt sensitive data
2326 | *   Validate message integrity
2327 | *   Implement message size limits
2328 | *   Sanitize input data
2329 | 
2330 | ### Network Security
2331 | 
2332 | *   Implement rate limiting
2333 | *   Use appropriate timeouts
2334 | *   Handle denial of service scenarios
2335 | *   Monitor for unusual patterns
2336 | *   Implement proper firewall rules
2337 | 
2338 | ## Debugging Transport
2339 | 
2340 | Tips for debugging transport issues:
2341 | 
2342 | 1.  Enable debug logging
2343 | 2.  Monitor message flow
2344 | 3.  Check connection states
2345 | 4.  Validate message formats
2346 | 5.  Test error scenarios
2347 | 6.  Use network analysis tools
2348 | 7.  Implement health checks
2349 | 8.  Monitor resource usage
2350 | 9.  Test edge cases
2351 | 10. Use proper error tracking
2352 | 
2353 | 
2354 | # Debugging
2355 | 
2356 | A comprehensive guide to debugging Model Context Protocol (MCP) integrations
2357 | 
2358 | 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.
2359 | 
2360 | <Info>
2361 |   This guide is for macOS. Guides for other platforms are coming soon.
2362 | </Info>
2363 | 
2364 | ## Debugging tools overview
2365 | 
2366 | MCP provides several tools for debugging at different levels:
2367 | 
2368 | 1.  **MCP Inspector**
2369 |     *   Interactive debugging interface
2370 |     *   Direct server testing
2371 |     *   See the [Inspector guide](/docs/tools/inspector) for details
2372 | 
2373 | 2.  **Claude Desktop Developer Tools**
2374 |     *   Integration testing
2375 |     *   Log collection
2376 |     *   Chrome DevTools integration
2377 | 
2378 | 3.  **Server Logging**
2379 |     *   Custom logging implementations
2380 |     *   Error tracking
2381 |     *   Performance monitoring
2382 | 
2383 | ## Debugging in Claude Desktop
2384 | 
2385 | ### Checking server status
2386 | 
2387 | The Claude.app interface provides basic server status information:
2388 | 
2389 | 1.  Click the <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-plug-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
2390 |     *   Connected servers
2391 |     *   Available prompts and resources
2392 | 
2393 | 2.  Click the <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
2394 |     *   Tools made available to the model
2395 | 
2396 | ### Viewing logs
2397 | 
2398 | Review detailed MCP logs from Claude Desktop:
2399 | 
2400 | ```bash
2401 | # Follow logs in real-time
2402 | tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
2403 | ```
2404 | 
2405 | The logs capture:
2406 | 
2407 | *   Server connection events
2408 | *   Configuration issues
2409 | *   Runtime errors
2410 | *   Message exchanges
2411 | 
2412 | ### Using Chrome DevTools
2413 | 
2414 | Access Chrome's developer tools inside Claude Desktop to investigate client-side errors:
2415 | 
2416 | 1.  Enable DevTools:
2417 | 
2418 | ```bash
2419 | jq '.allowDevTools = true' ~/Library/Application\ Support/Claude/developer_settings.json > tmp.json \
2420 |   && mv tmp.json ~/Library/Application\ Support/Claude/developer_settings.json
2421 | ```
2422 | 
2423 | 2.  Open DevTools: `Command-Option-Shift-i`
2424 | 
2425 | Note: You'll see two DevTools windows:
2426 | 
2427 | *   Main content window
2428 | *   App title bar window
2429 | 
2430 | Use the Console panel to inspect client-side errors.
2431 | 
2432 | Use the Network panel to inspect:
2433 | 
2434 | *   Message payloads
2435 | *   Connection timing
2436 | 
2437 | ## Common issues
2438 | 
2439 | ### Working directory
2440 | 
2441 | When using MCP servers with Claude Desktop:
2442 | 
2443 | *   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
2444 | *   Always use absolute paths in your configuration and `.env` files to ensure reliable operation
2445 | *   For testing servers directly via command line, the working directory will be where you run the command
2446 | 
2447 | For example in `claude_desktop_config.json`, use:
2448 | 
2449 | ```json
2450 | {
2451 |   "command": "npx",
2452 |   "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/data"]
2453 | }
2454 | ```
2455 | 
2456 | Instead of relative paths like `./data`
2457 | 
2458 | ### Environment variables
2459 | 
2460 | MCP servers inherit only a subset of environment variables automatically, like `USER`, `HOME`, and `PATH`.
2461 | 
2462 | To override the default variables or provide your own, you can specify an `env` key in `claude_desktop_config.json`:
2463 | 
2464 | ```json
2465 | {
2466 |   "myserver": {
2467 |     "command": "mcp-server-myapp",
2468 |     "env": {
2469 |       "MYAPP_API_KEY": "some_key",
2470 |     }
2471 |   }
2472 | }
2473 | ```
2474 | 
2475 | ### Server initialization
2476 | 
2477 | Common initialization problems:
2478 | 
2479 | 1.  **Path Issues**
2480 |     *   Incorrect server executable path
2481 |     *   Missing required files
2482 |     *   Permission problems
2483 |     *   Try using an absolute path for `command`
2484 | 
2485 | 2.  **Configuration Errors**
2486 |     *   Invalid JSON syntax
2487 |     *   Missing required fields
2488 |     *   Type mismatches
2489 | 
2490 | 3.  **Environment Problems**
2491 |     *   Missing environment variables
2492 |     *   Incorrect variable values
2493 |     *   Permission restrictions
2494 | 
2495 | ### Connection problems
2496 | 
2497 | When servers fail to connect:
2498 | 
2499 | 1.  Check Claude Desktop logs
2500 | 2.  Verify server process is running
2501 | 3.  Test standalone with [Inspector](/docs/tools/inspector)
2502 | 4.  Verify protocol compatibility
2503 | 
2504 | ## Implementing logging
2505 | 
2506 | ### Server-side logging
2507 | 
2508 | 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.
2509 | 
2510 | <Warning>
2511 |   Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation.
2512 | </Warning>
2513 | 
2514 | For all [transports](/docs/concepts/transports), you can also provide logging to the client by sending a log message notification:
2515 | 
2516 | <Tabs>
2517 |   <Tab title="Python">
2518 |     ```python
2519 |     server.request_context.session.send_log_message(
2520 |       level="info",
2521 |       data="Server started successfully",
2522 |     )
2523 |     ```
2524 |   </Tab>
2525 | 
2526 |   <Tab title="TypeScript">
2527 |     ```typescript
2528 |     server.sendLoggingMessage({
2529 |       level: "info",
2530 |       data: "Server started successfully",
2531 |     });
2532 |     ```
2533 |   </Tab>
2534 | </Tabs>
2535 | 
2536 | Important events to log:
2537 | 
2538 | *   Initialization steps
2539 | *   Resource access
2540 | *   Tool execution
2541 | *   Error conditions
2542 | *   Performance metrics
2543 | 
2544 | ### Client-side logging
2545 | 
2546 | In client applications:
2547 | 
2548 | 1.  Enable debug logging
2549 | 2.  Monitor network traffic
2550 | 3.  Track message exchanges
2551 | 4.  Record error states
2552 | 
2553 | ## Debugging workflow
2554 | 
2555 | ### Development cycle
2556 | 
2557 | 1.  Initial Development
2558 |     *   Use [Inspector](/docs/tools/inspector) for basic testing
2559 |     *   Implement core functionality
2560 |     *   Add logging points
2561 | 
2562 | 2.  Integration Testing
2563 |     *   Test in Claude Desktop
2564 |     *   Monitor logs
2565 |     *   Check error handling
2566 | 
2567 | ### Testing changes
2568 | 
2569 | To test changes efficiently:
2570 | 
2571 | *   **Configuration changes**: Restart Claude Desktop
2572 | *   **Server code changes**: Use Command-R to reload
2573 | *   **Quick iteration**: Use [Inspector](/docs/tools/inspector) during development
2574 | 
2575 | ## Best practices
2576 | 
2577 | ### Logging strategy
2578 | 
2579 | 1.  **Structured Logging**
2580 |     *   Use consistent formats
2581 |     *   Include context
2582 |     *   Add timestamps
2583 |     *   Track request IDs
2584 | 
2585 | 2.  **Error Handling**
2586 |     *   Log stack traces
2587 |     *   Include error context
2588 |     *   Track error patterns
2589 |     *   Monitor recovery
2590 | 
2591 | 3.  **Performance Tracking**
2592 |     *   Log operation timing
2593 |     *   Monitor resource usage
2594 |     *   Track message sizes
2595 |     *   Measure latency
2596 | 
2597 | ### Security considerations
2598 | 
2599 | When debugging:
2600 | 
2601 | 1.  **Sensitive Data**
2602 |     *   Sanitize logs
2603 |     *   Protect credentials
2604 |     *   Mask personal information
2605 | 
2606 | 2.  **Access Control**
2607 |     *   Verify permissions
2608 |     *   Check authentication
2609 |     *   Monitor access patterns
2610 | 
2611 | ## Getting help
2612 | 
2613 | When encountering issues:
2614 | 
2615 | 1.  **First Steps**
2616 |     *   Check server logs
2617 |     *   Test with [Inspector](/docs/tools/inspector)
2618 |     *   Review configuration
2619 |     *   Verify environment
2620 | 
2621 | 2.  **Support Channels**
2622 |     *   GitHub issues
2623 |     *   GitHub discussions
2624 | 
2625 | 3.  **Providing Information**
2626 |     *   Log excerpts
2627 |     *   Configuration files
2628 |     *   Steps to reproduce
2629 |     *   Environment details
2630 | 
2631 | ## Next steps
2632 | 
2633 | <CardGroup cols={2}>
2634 |   <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
2635 |     Learn to use the MCP Inspector
2636 |   </Card>
2637 | </CardGroup>
2638 | 
2639 | 
2640 | # Inspector
2641 | 
2642 | In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers
2643 | 
2644 | 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.
2645 | 
2646 | ## Getting started
2647 | 
2648 | ### Installation and basic usage
2649 | 
2650 | The Inspector runs directly through `npx` without requiring installation:
2651 | 
2652 | ```bash
2653 | npx @modelcontextprotocol/inspector <command>
2654 | ```
2655 | 
2656 | ```bash
2657 | npx @modelcontextprotocol/inspector <command> <arg1> <arg2>
2658 | ```
2659 | 
2660 | #### Inspecting servers from NPM or PyPi
2661 | 
2662 | A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com).
2663 | 
2664 | <Tabs>
2665 |   <Tab title="NPM package">
2666 |     ```bash
2667 |     npx -y @modelcontextprotocol/inspector npx <package-name> <args>
2668 |     # For example
2669 |     npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb
2670 |     ```
2671 |   </Tab>
2672 | 
2673 |   <Tab title="PyPi package">
2674 |     ```bash
2675 |     npx @modelcontextprotocol/inspector uvx <package-name> <args>
2676 |     # For example
2677 |     npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
2678 |     ```
2679 |   </Tab>
2680 | </Tabs>
2681 | 
2682 | #### Inspecting locally developed servers
2683 | 
2684 | To inspect servers locally developed or downloaded as a repository, the most common
2685 | way is:
2686 | 
2687 | <Tabs>
2688 |   <Tab title="TypeScript">
2689 |     ```bash
2690 |     npx @modelcontextprotocol/inspector node path/to/server/index.js args...
2691 |     ```
2692 |   </Tab>
2693 | 
2694 |   <Tab title="Python">
2695 |     ```bash
2696 |     npx @modelcontextprotocol/inspector \
2697 |       uv \
2698 |       --directory path/to/server \
2699 |       run \
2700 |       package-name \
2701 |       args...
2702 |     ```
2703 |   </Tab>
2704 | </Tabs>
2705 | 
2706 | Please carefully read any attached README for the most accurate instructions.
2707 | 
2708 | ## Feature overview
2709 | 
2710 | <Frame caption="The MCP Inspector interface">
2711 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/mcp-inspector.png" />
2712 | </Frame>
2713 | 
2714 | The Inspector provides several features for interacting with your MCP server:
2715 | 
2716 | ### Server connection pane
2717 | 
2718 | *   Allows selecting the [transport](/docs/concepts/transports) for connecting to the server
2719 | *   For local servers, supports customizing the command-line arguments and environment
2720 | 
2721 | ### Resources tab
2722 | 
2723 | *   Lists all available resources
2724 | *   Shows resource metadata (MIME types, descriptions)
2725 | *   Allows resource content inspection
2726 | *   Supports subscription testing
2727 | 
2728 | ### Prompts tab
2729 | 
2730 | *   Displays available prompt templates
2731 | *   Shows prompt arguments and descriptions
2732 | *   Enables prompt testing with custom arguments
2733 | *   Previews generated messages
2734 | 
2735 | ### Tools tab
2736 | 
2737 | *   Lists available tools
2738 | *   Shows tool schemas and descriptions
2739 | *   Enables tool testing with custom inputs
2740 | *   Displays tool execution results
2741 | 
2742 | ### Notifications pane
2743 | 
2744 | *   Presents all logs recorded from the server
2745 | *   Shows notifications received from the server
2746 | 
2747 | ## Best practices
2748 | 
2749 | ### Development workflow
2750 | 
2751 | 1.  Start Development
2752 |     *   Launch Inspector with your server
2753 |     *   Verify basic connectivity
2754 |     *   Check capability negotiation
2755 | 
2756 | 2.  Iterative testing
2757 |     *   Make server changes
2758 |     *   Rebuild the server
2759 |     *   Reconnect the Inspector
2760 |     *   Test affected features
2761 |     *   Monitor messages
2762 | 
2763 | 3.  Test edge cases
2764 |     *   Invalid inputs
2765 |     *   Missing prompt arguments
2766 |     *   Concurrent operations
2767 |     *   Verify error handling and error responses
2768 | 
2769 | ## Next steps
2770 | 
2771 | <CardGroup cols={2}>
2772 |   <Card title="Inspector Repository" icon="github" href="https://github.com/modelcontextprotocol/inspector">
2773 |     Check out the MCP Inspector source code
2774 |   </Card>
2775 | 
2776 |   <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
2777 |     Learn about broader debugging strategies
2778 |   </Card>
2779 | </CardGroup>
2780 | 
2781 | 
2782 | # Example Servers
2783 | 
2784 | A list of example servers and implementations
2785 | 
2786 | 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.
2787 | 
2788 | ## Reference implementations
2789 | 
2790 | These official reference servers demonstrate core MCP features and SDK usage:
2791 | 
2792 | ### Data and file systems
2793 | 
2794 | *   **[Filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)** - Secure file operations with configurable access controls
2795 | *   **[PostgreSQL](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres)** - Read-only database access with schema inspection capabilities
2796 | *   **[SQLite](https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite)** - Database interaction and business intelligence features
2797 | *   **[Google Drive](https://github.com/modelcontextprotocol/servers/tree/main/src/gdrive)** - File access and search capabilities for Google Drive
2798 | 
2799 | ### Development tools
2800 | 
2801 | *   **[Git](https://github.com/modelcontextprotocol/servers/tree/main/src/git)** - Tools to read, search, and manipulate Git repositories
2802 | *   **[GitHub](https://github.com/modelcontextprotocol/servers/tree/main/src/github)** - Repository management, file operations, and GitHub API integration
2803 | *   **[GitLab](https://github.com/modelcontextprotocol/servers/tree/main/src/gitlab)** - GitLab API integration enabling project management
2804 | *   **[Sentry](https://github.com/modelcontextprotocol/servers/tree/main/src/sentry)** - Retrieving and analyzing issues from Sentry.io
2805 | 
2806 | ### Web and browser automation
2807 | 
2808 | *   **[Brave Search](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)** - Web and local search using Brave's Search API
2809 | *   **[Fetch](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch)** - Web content fetching and conversion optimized for LLM usage
2810 | *   **[Puppeteer](https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer)** - Browser automation and web scraping capabilities
2811 | 
2812 | ### Productivity and communication
2813 | 
2814 | *   **[Slack](https://github.com/modelcontextprotocol/servers/tree/main/src/slack)** - Channel management and messaging capabilities
2815 | *   **[Google Maps](https://github.com/modelcontextprotocol/servers/tree/main/src/google-maps)** - Location services, directions, and place details
2816 | *   **[Memory](https://github.com/modelcontextprotocol/servers/tree/main/src/memory)** - Knowledge graph-based persistent memory system
2817 | 
2818 | ### AI and specialized tools
2819 | 
2820 | *   **[EverArt](https://github.com/modelcontextprotocol/servers/tree/main/src/everart)** - AI image generation using various models
2821 | *   **[Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking)** - Dynamic problem-solving through thought sequences
2822 | *   **[AWS KB Retrieval](https://github.com/modelcontextprotocol/servers/tree/main/src/aws-kb-retrieval-server)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime
2823 | 
2824 | ## Official integrations
2825 | 
2826 | These MCP servers are maintained by companies for their platforms:
2827 | 
2828 | *   **[Axiom](https://github.com/axiomhq/mcp-server-axiom)** - Query and analyze logs, traces, and event data using natural language
2829 | *   **[Browserbase](https://github.com/browserbase/mcp-server-browserbase)** - Automate browser interactions in the cloud
2830 | *   **[Cloudflare](https://github.com/cloudflare/mcp-server-cloudflare)** - Deploy and manage resources on the Cloudflare developer platform
2831 | *   **[E2B](https://github.com/e2b-dev/mcp-server)** - Execute code in secure cloud sandboxes
2832 | *   **[Neon](https://github.com/neondatabase/mcp-server-neon)** - Interact with the Neon serverless Postgres platform
2833 | *   **[Obsidian Markdown Notes](https://github.com/calclavia/mcp-obsidian)** - Read and search through Markdown notes in Obsidian vaults
2834 | *   **[Qdrant](https://github.com/qdrant/mcp-server-qdrant/)** - Implement semantic memory using the Qdrant vector search engine
2835 | *   **[Raygun](https://github.com/MindscapeHQ/mcp-server-raygun)** - Access crash reporting and monitoring data
2836 | *   **[Search1API](https://github.com/fatwang2/search1api-mcp)** - Unified API for search, crawling, and sitemaps
2837 | *   **[Tinybird](https://github.com/tinybirdco/mcp-tinybird)** - Interface with the Tinybird serverless ClickHouse platform
2838 | 
2839 | ## Community highlights
2840 | 
2841 | A growing ecosystem of community-developed servers extends MCP's capabilities:
2842 | 
2843 | *   **[Docker](https://github.com/ckreiling/mcp-server-docker)** - Manage containers, images, volumes, and networks
2844 | *   **[Kubernetes](https://github.com/Flux159/mcp-server-kubernetes)** - Manage pods, deployments, and services
2845 | *   **[Linear](https://github.com/jerhadf/linear-mcp-server)** - Project management and issue tracking
2846 | *   **[Snowflake](https://github.com/datawiz168/mcp-snowflake-service)** - Interact with Snowflake databases
2847 | *   **[Spotify](https://github.com/varunneal/spotify-mcp)** - Control Spotify playback and manage playlists
2848 | *   **[Todoist](https://github.com/abhiz123/todoist-mcp-server)** - Task management integration
2849 | 
2850 | > **Note:** Community servers are untested and should be used at your own risk. They are not affiliated with or endorsed by Anthropic.
2851 | 
2852 | For a complete list of community servers, visit the [MCP Servers Repository](https://github.com/modelcontextprotocol/servers).
2853 | 
2854 | ## Getting started
2855 | 
2856 | ### Using reference servers
2857 | 
2858 | TypeScript-based servers can be used directly with `npx`:
2859 | 
2860 | ```bash
2861 | npx -y @modelcontextprotocol/server-memory
2862 | ```
2863 | 
2864 | Python-based servers can be used with `uvx` (recommended) or `pip`:
2865 | 
2866 | ```bash
2867 | # Using uvx
2868 | uvx mcp-server-git
2869 | 
2870 | # Using pip
2871 | pip install mcp-server-git
2872 | python -m mcp_server_git
2873 | ```
2874 | 
2875 | ### Configuring with Claude
2876 | 
2877 | To use an MCP server with Claude, add it to your configuration:
2878 | 
2879 | ```json
2880 | {
2881 |   "mcpServers": {
2882 |     "memory": {
2883 |       "command": "npx",
2884 |       "args": ["-y", "@modelcontextprotocol/server-memory"]
2885 |     },
2886 |     "filesystem": {
2887 |       "command": "npx",
2888 |       "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
2889 |     },
2890 |     "github": {
2891 |       "command": "npx",
2892 |       "args": ["-y", "@modelcontextprotocol/server-github"],
2893 |       "env": {
2894 |         "GITHUB_PERSONAL_ACCESS_TOKEN": "<YOUR_TOKEN>"
2895 |       }
2896 |     }
2897 |   }
2898 | }
2899 | ```
2900 | 
2901 | ## Additional resources
2902 | 
2903 | *   [MCP Servers Repository](https://github.com/modelcontextprotocol/servers) - Complete collection of reference implementations and community servers
2904 | *   [Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers) - Curated list of MCP servers
2905 | *   [MCP CLI](https://github.com/wong2/mcp-cli) - Command-line inspector for testing MCP servers
2906 | *   [MCP Get](https://mcp-get.com) - Tool for installing and managing MCP servers
2907 | *   [Supergateway](https://github.com/supercorp-ai/supergateway) - Run MCP stdio servers over SSE
2908 | 
2909 | Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to engage with the MCP community.
2910 | 
2911 | 
2912 | # Introduction
2913 | 
2914 | Get started with the Model Context Protocol (MCP)
2915 | 
2916 | MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.
2917 | 
2918 | ## Why MCP?
2919 | 
2920 | MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides:
2921 | 
2922 | *   A growing list of pre-built integrations that your LLM can directly plug into
2923 | *   The flexibility to switch between LLM providers and vendors
2924 | *   Best practices for securing your data within your infrastructure
2925 | 
2926 | ### General architecture
2927 | 
2928 | At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:
2929 | 
2930 | ```mermaid
2931 | flowchart LR
2932 |     subgraph "Your Computer"
2933 |         Host["Host with MCP Client\n(Claude, IDEs, Tools)"]
2934 |         S1["MCP Server A"]
2935 |         S2["MCP Server B"]
2936 |         S3["MCP Server C"]
2937 |         Host <-->|"MCP Protocol"| S1
2938 |         Host <-->|"MCP Protocol"| S2
2939 |         Host <-->|"MCP Protocol"| S3
2940 |         S1 <--> D1[("Local\nData Source A")]
2941 |         S2 <--> D2[("Local\nData Source B")]
2942 |     end
2943 |     subgraph "Internet"
2944 |         S3 <-->|"Web APIs"| D3[("Remote\nService C")]
2945 |     end
2946 | ```
2947 | 
2948 | *   **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access data through MCP
2949 | *   **MCP Clients**: Protocol clients that maintain 1:1 connections with servers
2950 | *   **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
2951 | *   **Local Data Sources**: Your computer's files, databases, and services that MCP servers can securely access
2952 | *   **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to
2953 | 
2954 | ## Get started
2955 | 
2956 | Choose the path that best fits your needs:
2957 | 
2958 | #### Quick Starts
2959 | 
2960 | <CardGroup cols={2}>
2961 |   <Card title="For Server Developers" icon="bolt" href="/quickstart/server">
2962 |     Get started building your own server to use in Claude for Desktop and other clients
2963 |   </Card>
2964 | 
2965 |   <Card title="For Client Developers" icon="bolt" href="/quickstart/client">
2966 |     Get started building your own client that can integrate with all MCP servers
2967 |   </Card>
2968 | 
2969 |   <Card title="For Claude Desktop Users" icon="bolt" href="/quickstart/user">
2970 |     Get started using pre-built servers in Claude for Desktop
2971 |   </Card>
2972 | </CardGroup>
2973 | 
2974 | #### Examples
2975 | 
2976 | <CardGroup cols={2}>
2977 |   <Card title="Example Servers" icon="grid" href="/examples">
2978 |     Check out our gallery of official MCP servers and implementations
2979 |   </Card>
2980 | 
2981 |   <Card title="Example Clients" icon="cubes" href="/clients">
2982 |     View the list of clients that support MCP integrations
2983 |   </Card>
2984 | </CardGroup>
2985 | 
2986 | ## Tutorials
2987 | 
2988 | <CardGroup cols={2}>
2989 |   <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms">
2990 |     Learn how to use LLMs like Claude to speed up your MCP development
2991 |   </Card>
2992 | 
2993 |   <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
2994 |     Learn how to effectively debug MCP servers and integrations
2995 |   </Card>
2996 | 
2997 |   <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
2998 |     Test and inspect your MCP servers with our interactive debugging tool
2999 |   </Card>
3000 | </CardGroup>
3001 | 
3002 | ## Explore MCP
3003 | 
3004 | Dive deeper into MCP's core concepts and capabilities:
3005 | 
3006 | <CardGroup cols={2}>
3007 |   <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture">
3008 |     Understand how MCP connects clients, servers, and LLMs
3009 |   </Card>
3010 | 
3011 |   <Card title="Resources" icon="database" href="/docs/concepts/resources">
3012 |     Expose data and content from your servers to LLMs
3013 |   </Card>
3014 | 
3015 |   <Card title="Prompts" icon="message" href="/docs/concepts/prompts">
3016 |     Create reusable prompt templates and workflows
3017 |   </Card>
3018 | 
3019 |   <Card title="Tools" icon="wrench" href="/docs/concepts/tools">
3020 |     Enable LLMs to perform actions through your server
3021 |   </Card>
3022 | 
3023 |   <Card title="Sampling" icon="robot" href="/docs/concepts/sampling">
3024 |     Let your servers request completions from LLMs
3025 |   </Card>
3026 | 
3027 |   <Card title="Transports" icon="network-wired" href="/docs/concepts/transports">
3028 |     Learn about MCP's communication mechanism
3029 |   </Card>
3030 | </CardGroup>
3031 | 
3032 | ## Contributing
3033 | 
3034 | Want to contribute? Check out our [Contributing Guide](/development/contributing) to learn how you can help improve MCP.
3035 | 
3036 | 
3037 | # For Client Developers
3038 | 
3039 | Get started building your own client that can integrate with all MCP servers.
3040 | 
3041 | In this tutorial, you'll learn how to build a LLM-powered chatbot client that connects to MCP servers. It helps to have gone through the [Server quickstart](/quickstart/server) that guides you through the basic of building your first server.
3042 | 
3043 | <Tabs>
3044 |   <Tab title="Python">
3045 |     [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client)
3046 | 
3047 |     ## System Requirements
3048 | 
3049 |     Before starting, ensure your system meets these requirements:
3050 | 
3051 |     *   Mac or Windows computer
3052 |     *   Latest Python version installed
3053 |     *   Latest version of `uv` installed
3054 | 
3055 |     ## Setting Up Your Environment
3056 | 
3057 |     First, create a new Python project with `uv`:
3058 | 
3059 |     ```bash
3060 |     # Create project directory
3061 |     uv init mcp-client
3062 |     cd mcp-client
3063 | 
3064 |     # Create virtual environment
3065 |     uv venv
3066 | 
3067 |     # Activate virtual environment
3068 |     # On Windows:
3069 |     .venv\Scripts\activate
3070 |     # On Unix or MacOS:
3071 |     source .venv/bin/activate
3072 | 
3073 |     # Install required packages
3074 |     uv add mcp anthropic python-dotenv
3075 | 
3076 |     # Remove boilerplate files
3077 |     rm hello.py
3078 | 
3079 |     # Create our main file
3080 |     touch client.py
3081 |     ```
3082 | 
3083 |     ## Setting Up Your API Key
3084 | 
3085 |     You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
3086 | 
3087 |     Create a `.env` file to store it:
3088 | 
3089 |     ```bash
3090 |     # Create .env file
3091 |     touch .env
3092 |     ```
3093 | 
3094 |     Add your key to the `.env` file:
3095 | 
3096 |     ```bash
3097 |     ANTHROPIC_API_KEY=<your key here>
3098 |     ```
3099 | 
3100 |     Add `.env` to your `.gitignore`:
3101 | 
3102 |     ```bash
3103 |     echo ".env" >> .gitignore
3104 |     ```
3105 | 
3106 |     <Warning>
3107 |       Make sure you keep your `ANTHROPIC_API_KEY` secure!
3108 |     </Warning>
3109 | 
3110 |     ## Creating the Client
3111 | 
3112 |     ### Basic Client Structure
3113 | 
3114 |     First, let's set up our imports and create the basic client class:
3115 | 
3116 |     ```python
3117 |     import asyncio
3118 |     from typing import Optional
3119 |     from contextlib import AsyncExitStack
3120 | 
3121 |     from mcp import ClientSession, StdioServerParameters
3122 |     from mcp.client.stdio import stdio_client
3123 | 
3124 |     from anthropic import Anthropic
3125 |     from dotenv import load_dotenv
3126 | 
3127 |     load_dotenv()  # load environment variables from .env
3128 | 
3129 |     class MCPClient:
3130 |         def __init__(self):
3131 |             # Initialize session and client objects
3132 |             self.session: Optional[ClientSession] = None
3133 |             self.exit_stack = AsyncExitStack()
3134 |             self.anthropic = Anthropic()
3135 |         # methods will go here
3136 |     ```
3137 | 
3138 |     ### Server Connection Management
3139 | 
3140 |     Next, we'll implement the method to connect to an MCP server:
3141 | 
3142 |     ```python
3143 |     async def connect_to_server(self, server_script_path: str):
3144 |         """Connect to an MCP server
3145 |         
3146 |         Args:
3147 |             server_script_path: Path to the server script (.py or .js)
3148 |         """
3149 |         is_python = server_script_path.endswith('.py')
3150 |         is_js = server_script_path.endswith('.js')
3151 |         if not (is_python or is_js):
3152 |             raise ValueError("Server script must be a .py or .js file")
3153 |             
3154 |         command = "python" if is_python else "node"
3155 |         server_params = StdioServerParameters(
3156 |             command=command,
3157 |             args=[server_script_path],
3158 |             env=None
3159 |         )
3160 |         
3161 |         stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
3162 |         self.stdio, self.write = stdio_transport
3163 |         self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
3164 |         
3165 |         await self.session.initialize()
3166 |         
3167 |         # List available tools
3168 |         response = await self.session.list_tools()
3169 |         tools = response.tools
3170 |         print("\nConnected to server with tools:", [tool.name for tool in tools])
3171 |     ```
3172 | 
3173 |     ### Query Processing Logic
3174 | 
3175 |     Now let's add the core functionality for processing queries and handling tool calls:
3176 | 
3177 |     ```python
3178 |     async def process_query(self, query: str) -> str:
3179 |         """Process a query using Claude and available tools"""
3180 |         messages = [
3181 |             {
3182 |                 "role": "user",
3183 |                 "content": query
3184 |             }
3185 |         ]
3186 | 
3187 |         response = await self.session.list_tools()
3188 |         available_tools = [{ 
3189 |             "name": tool.name,
3190 |             "description": tool.description,
3191 |             "input_schema": tool.inputSchema
3192 |         } for tool in response.tools]
3193 | 
3194 |         # Initial Claude API call
3195 |         response = self.anthropic.messages.create(
3196 |             model="claude-3-5-sonnet-20241022",
3197 |             max_tokens=1000,
3198 |             messages=messages,
3199 |             tools=available_tools
3200 |         )
3201 | 
3202 |         # Process response and handle tool calls
3203 |         tool_results = []
3204 |         final_text = []
3205 | 
3206 |         for content in response.content:
3207 |             if content.type == 'text':
3208 |                 final_text.append(content.text)
3209 |             elif content.type == 'tool_use':
3210 |                 tool_name = content.name
3211 |                 tool_args = content.input
3212 |                 
3213 |                 # Execute tool call
3214 |                 result = await self.session.call_tool(tool_name, tool_args)
3215 |                 tool_results.append({"call": tool_name, "result": result})
3216 |                 final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
3217 | 
3218 |                 # Continue conversation with tool results
3219 |                 if hasattr(content, 'text') and content.text:
3220 |                     messages.append({
3221 |                       "role": "assistant",
3222 |                       "content": content.text
3223 |                     })
3224 |                 messages.append({
3225 |                     "role": "user", 
3226 |                     "content": result.content
3227 |                 })
3228 | 
3229 |                 # Get next response from Claude
3230 |                 response = self.anthropic.messages.create(
3231 |                     model="claude-3-5-sonnet-20241022",
3232 |                     max_tokens=1000,
3233 |                     messages=messages,
3234 |                 )
3235 | 
3236 |                 final_text.append(response.content[0].text)
3237 | 
3238 |         return "\n".join(final_text)
3239 |     ```
3240 | 
3241 |     ### Interactive Chat Interface
3242 | 
3243 |     Now we'll add the chat loop and cleanup functionality:
3244 | 
3245 |     ```python
3246 |     async def chat_loop(self):
3247 |         """Run an interactive chat loop"""
3248 |         print("\nMCP Client Started!")
3249 |         print("Type your queries or 'quit' to exit.")
3250 |         
3251 |         while True:
3252 |             try:
3253 |                 query = input("\nQuery: ").strip()
3254 |                 
3255 |                 if query.lower() == 'quit':
3256 |                     break
3257 |                     
3258 |                 response = await self.process_query(query)
3259 |                 print("\n" + response)
3260 |                     
3261 |             except Exception as e:
3262 |                 print(f"\nError: {str(e)}")
3263 | 
3264 |     async def cleanup(self):
3265 |         """Clean up resources"""
3266 |         await self.exit_stack.aclose()
3267 |     ```
3268 | 
3269 |     ### Main Entry Point
3270 | 
3271 |     Finally, we'll add the main execution logic:
3272 | 
3273 |     ```python
3274 |     async def main():
3275 |         if len(sys.argv) < 2:
3276 |             print("Usage: python client.py <path_to_server_script>")
3277 |             sys.exit(1)
3278 |             
3279 |         client = MCPClient()
3280 |         try:
3281 |             await client.connect_to_server(sys.argv[1])
3282 |             await client.chat_loop()
3283 |         finally:
3284 |             await client.cleanup()
3285 | 
3286 |     if __name__ == "__main__":
3287 |         import sys
3288 |         asyncio.run(main())
3289 |     ```
3290 | 
3291 |     You can find the complete `client.py` file [here.](https://gist.github.com/zckly/f3f28ea731e096e53b39b47bf0a2d4b1)
3292 | 
3293 |     ## Key Components Explained
3294 | 
3295 |     ### 1. Client Initialization
3296 | 
3297 |     *   The `MCPClient` class initializes with session management and API clients
3298 |     *   Uses `AsyncExitStack` for proper resource management
3299 |     *   Configures the Anthropic client for Claude interactions
3300 | 
3301 |     ### 2. Server Connection
3302 | 
3303 |     *   Supports both Python and Node.js servers
3304 |     *   Validates server script type
3305 |     *   Sets up proper communication channels
3306 |     *   Initializes the session and lists available tools
3307 | 
3308 |     ### 3. Query Processing
3309 | 
3310 |     *   Maintains conversation context
3311 |     *   Handles Claude's responses and tool calls
3312 |     *   Manages the message flow between Claude and tools
3313 |     *   Combines results into a coherent response
3314 | 
3315 |     ### 4. Interactive Interface
3316 | 
3317 |     *   Provides a simple command-line interface
3318 |     *   Handles user input and displays responses
3319 |     *   Includes basic error handling
3320 |     *   Allows graceful exit
3321 | 
3322 |     ### 5. Resource Management
3323 | 
3324 |     *   Proper cleanup of resources
3325 |     *   Error handling for connection issues
3326 |     *   Graceful shutdown procedures
3327 | 
3328 |     ## Common Customization Points
3329 | 
3330 |     1.  **Tool Handling**
3331 |         *   Modify `process_query()` to handle specific tool types
3332 |         *   Add custom error handling for tool calls
3333 |         *   Implement tool-specific response formatting
3334 | 
3335 |     2.  **Response Processing**
3336 |         *   Customize how tool results are formatted
3337 |         *   Add response filtering or transformation
3338 |         *   Implement custom logging
3339 | 
3340 |     3.  **User Interface**
3341 |         *   Add a GUI or web interface
3342 |         *   Implement rich console output
3343 |         *   Add command history or auto-completion
3344 | 
3345 |     ## Running the Client
3346 | 
3347 |     To run your client with any MCP server:
3348 | 
3349 |     ```bash
3350 |     uv run client.py path/to/server.py # python server
3351 |     uv run client.py path/to/build/index.js # node server
3352 |     ```
3353 | 
3354 |     <Note>
3355 |       If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `python client.py .../weather/src/weather/server.py`
3356 |     </Note>
3357 | 
3358 |     The client will:
3359 | 
3360 |     1.  Connect to the specified server
3361 |     2.  List available tools
3362 |     3.  Start an interactive chat session where you can:
3363 |         *   Enter queries
3364 |         *   See tool executions
3365 |         *   Get responses from Claude
3366 | 
3367 |     Here's an example of what it should look like if connected to the weather server from the server quickstart:
3368 | 
3369 |     <Frame>
3370 |       <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/client-claude-cli-python.png" />
3371 |     </Frame>
3372 | 
3373 |     ## How It Works
3374 | 
3375 |     When you submit a query:
3376 | 
3377 |     1.  The client gets the list of available tools from the server
3378 |     2.  Your query is sent to Claude along with tool descriptions
3379 |     3.  Claude decides which tools (if any) to use
3380 |     4.  The client executes any requested tool calls through the server
3381 |     5.  Results are sent back to Claude
3382 |     6.  Claude provides a natural language response
3383 |     7.  The response is displayed to you
3384 | 
3385 |     ## Best practices
3386 | 
3387 |     1.  **Error Handling**
3388 |         *   Always wrap tool calls in try-catch blocks
3389 |         *   Provide meaningful error messages
3390 |         *   Gracefully handle connection issues
3391 | 
3392 |     2.  **Resource Management**
3393 |         *   Use `AsyncExitStack` for proper cleanup
3394 |         *   Close connections when done
3395 |         *   Handle server disconnections
3396 | 
3397 |     3.  **Security**
3398 |         *   Store API keys securely in `.env`
3399 |         *   Validate server responses
3400 |         *   Be cautious with tool permissions
3401 | 
3402 |     ## Troubleshooting
3403 | 
3404 |     ### Server Path Issues
3405 | 
3406 |     *   Double-check the path to your server script is correct
3407 |     *   Use the absolute path if the relative path isn't working
3408 |     *   For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
3409 |     *   Verify the server file has the correct extension (.py for Python or .js for Node.js)
3410 | 
3411 |     Example of correct path usage:
3412 | 
3413 |     ```bash
3414 |     # Relative path
3415 |     uv run client.py ./server/weather.py
3416 | 
3417 |     # Absolute path
3418 |     uv run client.py /Users/username/projects/mcp-server/weather.py
3419 | 
3420 |     # Windows path (either format works)
3421 |     uv run client.py C:/projects/mcp-server/weather.py
3422 |     uv run client.py C:\\projects\\mcp-server\\weather.py
3423 |     ```
3424 | 
3425 |     ### Response Timing
3426 | 
3427 |     *   The first response might take up to 30 seconds to return
3428 |     *   This is normal and happens while:
3429 |         *   The server initializes
3430 |         *   Claude processes the query
3431 |         *   Tools are being executed
3432 |     *   Subsequent responses are typically faster
3433 |     *   Don't interrupt the process during this initial waiting period
3434 | 
3435 |     ### Common Error Messages
3436 | 
3437 |     If you see:
3438 | 
3439 |     *   `FileNotFoundError`: Check your server path
3440 |     *   `Connection refused`: Ensure the server is running and the path is correct
3441 |     *   `Tool execution failed`: Verify the tool's required environment variables are set
3442 |     *   `Timeout error`: Consider increasing the timeout in your client configuration
3443 |   </Tab>
3444 | </Tabs>
3445 | 
3446 | ## Next steps
3447 | 
3448 | <CardGroup cols={2}>
3449 |   <Card title="Example servers" icon="grid" href="/examples">
3450 |     Check out our gallery of official MCP servers and implementations
3451 |   </Card>
3452 | 
3453 |   <Card title="Clients" icon="cubes" href="/clients">
3454 |     View the list of clients that support MCP integrations
3455 |   </Card>
3456 | 
3457 |   <Card title="Building MCP with LLMs" icon="comments" href="/building-mcp-with-llms">
3458 |     Learn how to use LLMs like Claude to speed up your MCP development
3459 |   </Card>
3460 | 
3461 |   <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture">
3462 |     Understand how MCP connects clients, servers, and LLMs
3463 |   </Card>
3464 | </CardGroup>
3465 | 
3466 | 
3467 | # For Server Developers
3468 | 
3469 | Get started building your own server to use in Claude for Desktop and other clients.
3470 | 
3471 | In this tutorial, we'll build a simple MCP weather server and connect it to a host, Claude for Desktop. We'll start with a basic setup, and then progress to more complex use cases.
3472 | 
3473 | ### What we'll be building
3474 | 
3475 | Many LLMs (including Claude) do not currently have the ability to fetch the forecast and severe weather alerts. Let's use MCP to solve that!
3476 | 
3477 | We'll build a server that exposes two tools: `get-alerts` and `get-forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop):
3478 | 
3479 | <Frame>
3480 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" />
3481 | </Frame>
3482 | 
3483 | <Frame>
3484 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" />
3485 | </Frame>
3486 | 
3487 | <Note>
3488 |   Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have guides on [building your own client](/quickstart/client) as well as a [list of other clients here](/clients).
3489 | </Note>
3490 | 
3491 | <Accordion title="Why Claude for Desktop and not Claude.ai?">
3492 |   Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development.
3493 | </Accordion>
3494 | 
3495 | ### Core MCP Concepts
3496 | 
3497 | MCP servers can provide three main types of capabilities:
3498 | 
3499 | 1.  **Resources**: File-like data that can be read by clients (like API responses or file contents)
3500 | 2.  **Tools**: Functions that can be called by the LLM (with user approval)
3501 | 3.  **Prompts**: Pre-written templates that help users accomplish specific tasks
3502 | 
3503 | This tutorial will primarily focus on tools.
3504 | 
3505 | <Tabs>
3506 |   <Tab title="Python">
3507 |     Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)
3508 | 
3509 |     ### Prerequisite knowledge
3510 | 
3511 |     This quickstart assumes you have familiarity with:
3512 | 
3513 |     *   Python
3514 |     *   LLMs like Claude
3515 | 
3516 |     ### System requirements
3517 | 
3518 |     *   Python 3.10 or higher installed.
3519 |     *   You must use the Python MCP SDK 1.2.0 or higher.
3520 | 
3521 |     ### Set up your environment
3522 | 
3523 |     First, let's install `uv` and set up our Python project and environment:
3524 | 
3525 |     <CodeGroup>
3526 |       ```bash MacOS/Linux
3527 |       curl -LsSf https://astral.sh/uv/install.sh | sh
3528 |       ```
3529 | 
3530 |       ```powershell Windows
3531 |       powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
3532 |       ```
3533 |     </CodeGroup>
3534 | 
3535 |     Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
3536 | 
3537 |     Now, let's create and set up our project:
3538 | 
3539 |     <CodeGroup>
3540 |       ```bash MacOS/Linux
3541 |       # Create a new directory for our project
3542 |       uv init weather
3543 |       cd weather
3544 | 
3545 |       # Create virtual environment and activate it
3546 |       uv venv
3547 |       source .venv/bin/activate
3548 | 
3549 |       # Install dependencies
3550 |       uv add mcp[cli] httpx
3551 | 
3552 |       # Create our server file
3553 |       touch weather.py
3554 |       ```
3555 | 
3556 |       ```powershell Windows
3557 |       # Create a new directory for our project
3558 |       uv init weather
3559 |       cd weather
3560 | 
3561 |       # Create virtual environment and activate it
3562 |       uv venv
3563 |       .venv\Scripts\activate
3564 | 
3565 |       # Install dependencies
3566 |       uv add mcp[cli] httpx
3567 | 
3568 |       # Create our server file
3569 |       new-item weather.py
3570 |       ```
3571 |     </CodeGroup>
3572 | 
3573 |     Now let's dive into building your server.
3574 | 
3575 |     ## Building your server
3576 | 
3577 |     ### Importing packages and setting up the instance
3578 | 
3579 |     Add these to the top of your `weather.py`:
3580 | 
3581 |     ```python
3582 |     from typing import Any
3583 |     import httpx
3584 |     from mcp.server.fastmcp import FastMCP
3585 | 
3586 |     # Initialize FastMCP server
3587 |     mcp = FastMCP("weather")
3588 | 
3589 |     # Constants
3590 |     NWS_API_BASE = "https://api.weather.gov"
3591 |     USER_AGENT = "weather-app/1.0"
3592 |     ```
3593 | 
3594 |     The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.
3595 | 
3596 |     ### Helper functions
3597 | 
3598 |     Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
3599 | 
3600 |     ```python
3601 |     async def make_nws_request(url: str) -> dict[str, Any] | None:
3602 |         """Make a request to the NWS API with proper error handling."""
3603 |         headers = {
3604 |             "User-Agent": USER_AGENT,
3605 |             "Accept": "application/geo+json"
3606 |         }
3607 |         async with httpx.AsyncClient() as client:
3608 |             try:
3609 |                 response = await client.get(url, headers=headers, timeout=30.0)
3610 |                 response.raise_for_status()
3611 |                 return response.json()
3612 |             except Exception:
3613 |                 return None
3614 | 
3615 |     def format_alert(feature: dict) -> str:
3616 |         """Format an alert feature into a readable string."""
3617 |         props = feature["properties"]
3618 |         return f"""
3619 |     Event: {props.get('event', 'Unknown')}
3620 |     Area: {props.get('areaDesc', 'Unknown')}
3621 |     Severity: {props.get('severity', 'Unknown')}
3622 |     Description: {props.get('description', 'No description available')}
3623 |     Instructions: {props.get('instruction', 'No specific instructions provided')}
3624 |     """
3625 |     ```
3626 | 
3627 |     ### Implementing tool execution
3628 | 
3629 |     The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
3630 | 
3631 |     ```python
3632 |     @mcp.tool()
3633 |     async def get_alerts(state: str) -> str:
3634 |         """Get weather alerts for a US state.
3635 | 
3636 |         Args:
3637 |             state: Two-letter US state code (e.g. CA, NY)
3638 |         """
3639 |         url = f"{NWS_API_BASE}/alerts/active/area/{state}"
3640 |         data = await make_nws_request(url)
3641 | 
3642 |         if not data or "features" not in data:
3643 |             return "Unable to fetch alerts or no alerts found."
3644 | 
3645 |         if not data["features"]:
3646 |             return "No active alerts for this state."
3647 | 
3648 |         alerts = [format_alert(feature) for feature in data["features"]]
3649 |         return "\n---\n".join(alerts)
3650 | 
3651 |     @mcp.tool()
3652 |     async def get_forecast(latitude: float, longitude: float) -> str:
3653 |         """Get weather forecast for a location.
3654 | 
3655 |         Args:
3656 |             latitude: Latitude of the location
3657 |             longitude: Longitude of the location
3658 |         """
3659 |         # First get the forecast grid endpoint
3660 |         points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
3661 |         points_data = await make_nws_request(points_url)
3662 | 
3663 |         if not points_data:
3664 |             return "Unable to fetch forecast data for this location."
3665 | 
3666 |         # Get the forecast URL from the points response
3667 |         forecast_url = points_data["properties"]["forecast"]
3668 |         forecast_data = await make_nws_request(forecast_url)
3669 | 
3670 |         if not forecast_data:
3671 |             return "Unable to fetch detailed forecast."
3672 | 
3673 |         # Format the periods into a readable forecast
3674 |         periods = forecast_data["properties"]["periods"]
3675 |         forecasts = []
3676 |         for period in periods[:5]:  # Only show next 5 periods
3677 |             forecast = f"""
3678 |     {period['name']}:
3679 |     Temperature: {period['temperature']}°{period['temperatureUnit']}
3680 |     Wind: {period['windSpeed']} {period['windDirection']}
3681 |     Forecast: {period['detailedForecast']}
3682 |     """
3683 |             forecasts.append(forecast)
3684 | 
3685 |         return "\n---\n".join(forecasts)
3686 |     ```
3687 | 
3688 |     Your server is complete! Run `uv run weather.py` to confirm that everything's working.
3689 | 
3690 |     Let's now test your server from an existing MCP host, Claude for Desktop.
3691 | 
3692 |     ## Testing your server with Claude for Desktop
3693 | 
3694 |     <Note>
3695 |       Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
3696 |     </Note>
3697 | 
3698 |     First, make sure you have Claude for Desktop installed. [You can install the latest version
3699 |     here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
3700 | 
3701 |     We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
3702 | 
3703 |     For example, if you have [VS Code](https://code.visualstudio.com/) installed:
3704 | 
3705 |     <Tabs>
3706 |       <Tab title="MacOS/Linux">
3707 |         ```bash
3708 |         code ~/Library/Application\ Support/Claude/claude_desktop_config.json
3709 |         ```
3710 |       </Tab>
3711 | 
3712 |       <Tab title="Windows">
3713 |         ```powershell
3714 |         code $env:AppData\Claude\claude_desktop_config.json
3715 |         ```
3716 |       </Tab>
3717 |     </Tabs>
3718 | 
3719 |     You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
3720 | 
3721 |     In this case, we'll add our single weather server like so:
3722 | 
3723 |     <Tabs>
3724 |       <Tab title="MacOS/Linux">
3725 |         ```json Python
3726 |         {
3727 |             "mcpServers": {
3728 |                 "weather": {
3729 |                     "command": "uv",
3730 |                     "args": [
3731 |                         "--directory",
3732 |                         "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
3733 |                         "run",
3734 |                         "weather.py"
3735 |                     ]
3736 |                 }
3737 |             }
3738 |         }
3739 |         ```
3740 |       </Tab>
3741 | 
3742 |       <Tab title="Windows">
3743 |         ```json Python
3744 |         {
3745 |             "mcpServers": {
3746 |                 "weather": {
3747 |                     "command": "uv",
3748 |                     "args": [
3749 |                         "--directory",
3750 |                         "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
3751 |                         "run",
3752 |                         "weather.py"
3753 |                     ]
3754 |                 }
3755 |             }
3756 |         }
3757 |         ```
3758 |       </Tab>
3759 |     </Tabs>
3760 | 
3761 |     <Note>
3762 |       Make sure you pass in the absolute path to your server.
3763 |     </Note>
3764 | 
3765 |     This tells Claude for Desktop:
3766 | 
3767 |     1.  There's an MCP server named "weather"
3768 |     2.  To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather`
3769 | 
3770 |     Save the file, and restart **Claude for Desktop**.
3771 |   </Tab>
3772 | 
3773 |   <Tab title="Node">
3774 |     Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)
3775 | 
3776 |     ### Prerequisite knowledge
3777 | 
3778 |     This quickstart assumes you have familiarity with:
3779 | 
3780 |     *   TypeScript
3781 |     *   LLMs like Claude
3782 | 
3783 |     ### System requirements
3784 | 
3785 |     For TypeScript, make sure you have the latest version of Node installed.
3786 | 
3787 |     ### Set up your environment
3788 | 
3789 |     First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
3790 |     Verify your Node.js installation:
3791 | 
3792 |     ```bash
3793 |     node --version
3794 |     npm --version
3795 |     ```
3796 | 
3797 |     For this tutorial, you'll need Node.js version 16 or higher.
3798 | 
3799 |     Now, let's create and set up our project:
3800 | 
3801 |     <CodeGroup>
3802 |       ```bash MacOS/Linux
3803 |       # Create a new directory for our project
3804 |       mkdir weather
3805 |       cd weather
3806 | 
3807 |       # Initialize a new npm project
3808 |       npm init -y
3809 | 
3810 |       # Install dependencies
3811 |       npm install @modelcontextprotocol/sdk zod
3812 |       npm install -D @types/node typescript
3813 | 
3814 |       # Create our files
3815 |       mkdir src
3816 |       touch src/index.ts
3817 |       ```
3818 | 
3819 |       ```powershell Windows
3820 |       # Create a new directory for our project
3821 |       md weather
3822 |       cd weather
3823 | 
3824 |       # Initialize a new npm project
3825 |       npm init -y
3826 | 
3827 |       # Install dependencies
3828 |       npm install @modelcontextprotocol/sdk zod
3829 |       npm install -D @types/node typescript
3830 | 
3831 |       # Create our files
3832 |       md src
3833 |       new-item src\index.ts
3834 |       ```
3835 |     </CodeGroup>
3836 | 
3837 |     Update your package.json to add type: "module" and a build script:
3838 | 
3839 |     ```json package.json
3840 |     {
3841 |       "type": "module",
3842 |       "bin": {
3843 |         "weather": "./build/index.js"
3844 |       },
3845 |       "scripts": {
3846 |         "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
3847 |       },
3848 |       "files": [
3849 |         "build"
3850 |       ],
3851 |     }
3852 |     ```
3853 | 
3854 |     Create a `tsconfig.json` in the root of your project:
3855 | 
3856 |     ```json tsconfig.json
3857 |     {
3858 |       "compilerOptions": {
3859 |         "target": "ES2022",
3860 |         "module": "Node16",
3861 |         "moduleResolution": "Node16",
3862 |         "outDir": "./build",
3863 |         "rootDir": "./src",
3864 |         "strict": true,
3865 |         "esModuleInterop": true,
3866 |         "skipLibCheck": true,
3867 |         "forceConsistentCasingInFileNames": true
3868 |       },
3869 |       "include": ["src/**/*"],
3870 |       "exclude": ["node_modules"]
3871 |     }
3872 |     ```
3873 | 
3874 |     Now let's dive into building your server.
3875 | 
3876 |     ## Building your server
3877 | 
3878 |     ### Importing packages
3879 | 
3880 |     Add these to the top of your `src/index.ts`:
3881 | 
3882 |     ```typescript
3883 |     import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3884 |     import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3885 |     import {
3886 |       CallToolRequestSchema,
3887 |       ListToolsRequestSchema,
3888 |     } from "@modelcontextprotocol/sdk/types.js";
3889 |     import { z } from "zod";
3890 |     ```
3891 | 
3892 |     ### Setting up the instance
3893 | 
3894 |     Then initialize the NWS API base URL, validation schemas, and server instance:
3895 | 
3896 |     ```typescript
3897 |     const NWS_API_BASE = "https://api.weather.gov";
3898 |     const USER_AGENT = "weather-app/1.0";
3899 | 
3900 |     // Define Zod schemas for validation
3901 |     const AlertsArgumentsSchema = z.object({
3902 |       state: z.string().length(2),
3903 |     });
3904 | 
3905 |     const ForecastArgumentsSchema = z.object({
3906 |       latitude: z.number().min(-90).max(90),
3907 |       longitude: z.number().min(-180).max(180),
3908 |     });
3909 | 
3910 |     // Create server instance
3911 |     const server = new Server(
3912 |       {
3913 |         name: "weather",
3914 |         version: "1.0.0",
3915 |       },
3916 |       {
3917 |         capabilities: {
3918 |           tools: {},
3919 |         },
3920 |       }
3921 |     );
3922 |     ```
3923 | 
3924 |     ### Implementing tool listing
3925 | 
3926 |     We need to tell clients what tools are available. This `server.setRequestHandler` call will register this list for us:
3927 | 
3928 |     ```typescript
3929 |     // List available tools
3930 |     server.setRequestHandler(ListToolsRequestSchema, async () => {
3931 |       return {
3932 |         tools: [
3933 |           {
3934 |             name: "get-alerts",
3935 |             description: "Get weather alerts for a state",
3936 |             inputSchema: {
3937 |               type: "object",
3938 |               properties: {
3939 |                 state: {
3940 |                   type: "string",
3941 |                   description: "Two-letter state code (e.g. CA, NY)",
3942 |                 },
3943 |               },
3944 |               required: ["state"],
3945 |             },
3946 |           },
3947 |           {
3948 |             name: "get-forecast",
3949 |             description: "Get weather forecast for a location",
3950 |             inputSchema: {
3951 |               type: "object",
3952 |               properties: {
3953 |                 latitude: {
3954 |                   type: "number",
3955 |                   description: "Latitude of the location",
3956 |                 },
3957 |                 longitude: {
3958 |                   type: "number",
3959 |                   description: "Longitude of the location",
3960 |                 },
3961 |               },
3962 |               required: ["latitude", "longitude"],
3963 |             },
3964 |           },
3965 |         ],
3966 |       };
3967 |     });
3968 |     ```
3969 | 
3970 |     This defines our two tools: `get-alerts` and `get-forecast`.
3971 | 
3972 |     ### Helper functions
3973 | 
3974 |     Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
3975 | 
3976 |     ```typescript
3977 |     // Helper function for making NWS API requests
3978 |     async function makeNWSRequest<T>(url: string): Promise<T | null> {
3979 |       const headers = {
3980 |         "User-Agent": USER_AGENT,
3981 |         Accept: "application/geo+json",
3982 |       };
3983 | 
3984 |       try {
3985 |         const response = await fetch(url, { headers });
3986 |         if (!response.ok) {
3987 |           throw new Error(`HTTP error! status: ${response.status}`);
3988 |         }
3989 |         return (await response.json()) as T;
3990 |       } catch (error) {
3991 |         console.error("Error making NWS request:", error);
3992 |         return null;
3993 |       }
3994 |     }
3995 | 
3996 |     interface AlertFeature {
3997 |       properties: {
3998 |         event?: string;
3999 |         areaDesc?: string;
4000 |         severity?: string;
4001 |         status?: string;
4002 |         headline?: string;
4003 |       };
4004 |     }
4005 | 
4006 |     // Format alert data
4007 |     function formatAlert(feature: AlertFeature): string {
4008 |       const props = feature.properties;
4009 |       return [
4010 |         `Event: ${props.event || "Unknown"}`,
4011 |         `Area: ${props.areaDesc || "Unknown"}`,
4012 |         `Severity: ${props.severity || "Unknown"}`,
4013 |         `Status: ${props.status || "Unknown"}`,
4014 |         `Headline: ${props.headline || "No headline"}`,
4015 |         "---",
4016 |       ].join("\n");
4017 |     }
4018 | 
4019 |     interface ForecastPeriod {
4020 |       name?: string;
4021 |       temperature?: number;
4022 |       temperatureUnit?: string;
4023 |       windSpeed?: string;
4024 |       windDirection?: string;
4025 |       shortForecast?: string;
4026 |     }
4027 | 
4028 |     interface AlertsResponse {
4029 |       features: AlertFeature[];
4030 |     }
4031 | 
4032 |     interface PointsResponse {
4033 |       properties: {
4034 |         forecast?: string;
4035 |       };
4036 |     }
4037 | 
4038 |     interface ForecastResponse {
4039 |       properties: {
4040 |         periods: ForecastPeriod[];
4041 |       };
4042 |     }
4043 |     ```
4044 | 
4045 |     ### Implementing tool execution
4046 | 
4047 |     The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
4048 | 
4049 |     ```typescript
4050 |     // Handle tool execution
4051 |     server.setRequestHandler(CallToolRequestSchema, async (request) => {
4052 |       const { name, arguments: args } = request.params;
4053 | 
4054 |       try {
4055 |         if (name === "get-alerts") {
4056 |           const { state } = AlertsArgumentsSchema.parse(args);
4057 |           const stateCode = state.toUpperCase();
4058 | 
4059 |           const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
4060 |           const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
4061 | 
4062 |           if (!alertsData) {
4063 |             return {
4064 |               content: [
4065 |                 {
4066 |                   type: "text",
4067 |                   text: "Failed to retrieve alerts data",
4068 |                 },
4069 |               ],
4070 |             };
4071 |           }
4072 | 
4073 |           const features = alertsData.features || [];
4074 |           if (features.length === 0) {
4075 |             return {
4076 |               content: [
4077 |                 {
4078 |                   type: "text",
4079 |                   text: `No active alerts for ${stateCode}`,
4080 |                 },
4081 |               ],
4082 |             };
4083 |           }
4084 | 
4085 |           const formattedAlerts = features.map(formatAlert).slice(0, 20) // only take the first 20 alerts;
4086 |           const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join(
4087 |             "\n"
4088 |           )}`;
4089 | 
4090 |           return {
4091 |             content: [
4092 |               {
4093 |                 type: "text",
4094 |                 text: alertsText,
4095 |               },
4096 |             ],
4097 |           };
4098 |         } else if (name === "get-forecast") {
4099 |           const { latitude, longitude } = ForecastArgumentsSchema.parse(args);
4100 | 
4101 |           // Get grid point data
4102 |           const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(
4103 |             4
4104 |           )},${longitude.toFixed(4)}`;
4105 |           const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
4106 | 
4107 |           if (!pointsData) {
4108 |             return {
4109 |               content: [
4110 |                 {
4111 |                   type: "text",
4112 |                   text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
4113 |                 },
4114 |               ],
4115 |             };
4116 |           }
4117 | 
4118 |           const forecastUrl = pointsData.properties?.forecast;
4119 |           if (!forecastUrl) {
4120 |             return {
4121 |               content: [
4122 |                 {
4123 |                   type: "text",
4124 |                   text: "Failed to get forecast URL from grid point data",
4125 |                 },
4126 |               ],
4127 |             };
4128 |           }
4129 | 
4130 |           // Get forecast data
4131 |           const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
4132 |           if (!forecastData) {
4133 |             return {
4134 |               content: [
4135 |                 {
4136 |                   type: "text",
4137 |                   text: "Failed to retrieve forecast data",
4138 |                 },
4139 |               ],
4140 |             };
4141 |           }
4142 | 
4143 |           const periods = forecastData.properties?.periods || [];
4144 |           if (periods.length === 0) {
4145 |             return {
4146 |               content: [
4147 |                 {
4148 |                   type: "text",
4149 |                   text: "No forecast periods available",
4150 |                 },
4151 |               ],
4152 |             };
4153 |           }
4154 | 
4155 |           // Format forecast periods
4156 |           const formattedForecast = periods.map((period: ForecastPeriod) =>
4157 |             [
4158 |               `${period.name || "Unknown"}:`,
4159 |               `Temperature: ${period.temperature || "Unknown"}°${
4160 |                 period.temperatureUnit || "F"
4161 |               }`,
4162 |               `Wind: ${period.windSpeed || "Unknown"} ${
4163 |                 period.windDirection || ""
4164 |               }`,
4165 |               `${period.shortForecast || "No forecast available"}`,
4166 |               "---",
4167 |             ].join("\n")
4168 |           );
4169 | 
4170 |           const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join(
4171 |             "\n"
4172 |           )}`;
4173 | 
4174 |           return {
4175 |             content: [
4176 |               {
4177 |                 type: "text",
4178 |                 text: forecastText,
4179 |               },
4180 |             ],
4181 |           };
4182 |         } else {
4183 |           throw new Error(`Unknown tool: ${name}`);
4184 |         }
4185 |       } catch (error) {
4186 |         if (error instanceof z.ZodError) {
4187 |           throw new Error(
4188 |             `Invalid arguments: ${error.errors
4189 |               .map((e) => `${e.path.join(".")}: ${e.message}`)
4190 |               .join(", ")}`
4191 |           );
4192 |         }
4193 |         throw error;
4194 |       }
4195 |     });
4196 |     ```
4197 | 
4198 |     ### Running the server
4199 | 
4200 |     Finally, implement the main function to run the server:
4201 | 
4202 |     ```typescript
4203 |     // Start the server
4204 |     async function main() {
4205 |       const transport = new StdioServerTransport();
4206 |       await server.connect(transport);
4207 |       console.error("Weather MCP Server running on stdio");
4208 |     }
4209 | 
4210 |     main().catch((error) => {
4211 |       console.error("Fatal error in main():", error);
4212 |       process.exit(1);
4213 |     });
4214 |     ```
4215 | 
4216 |     Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
4217 | 
4218 |     Let's now test your server from an existing MCP host, Claude for Desktop.
4219 | 
4220 |     ## Testing your server with Claude for Desktop
4221 | 
4222 |     <Note>
4223 |       Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
4224 |     </Note>
4225 | 
4226 |     First, make sure you have Claude for Desktop installed. [You can install the latest version
4227 |     here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
4228 | 
4229 |     We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
4230 | 
4231 |     For example, if you have [VS Code](https://code.visualstudio.com/) installed:
4232 | 
4233 |     <Tabs>
4234 |       <Tab title="MacOS/Linux">
4235 |         ```bash
4236 |         code ~/Library/Application\ Support/Claude/claude_desktop_config.json
4237 |         ```
4238 |       </Tab>
4239 | 
4240 |       <Tab title="Windows">
4241 |         ```powershell
4242 |         code $env:AppData\Claude\claude_desktop_config.json
4243 |         ```
4244 |       </Tab>
4245 |     </Tabs>
4246 | 
4247 |     You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
4248 | 
4249 |     In this case, we'll add our single weather server like so:
4250 | 
4251 |     <Tabs>
4252 |       <Tab title="MacOS/Linux">
4253 |         <CodeGroup>
4254 |           ```json Node 
4255 |           {
4256 |               "mcpServers": {
4257 |                   "weather": {
4258 |                       "command": "node",
4259 |                       "args": [
4260 |                           "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"
4261 |                       ]
4262 |                   }
4263 |               }
4264 |           }
4265 |           ```
4266 |         </CodeGroup>
4267 |       </Tab>
4268 | 
4269 |       <Tab title="Windows">
4270 |         <CodeGroup>
4271 |           ```json Node
4272 |           {
4273 |               "mcpServers": {
4274 |                   "weather": {
4275 |                       "command": "node",
4276 |                       "args": [
4277 |                           "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"
4278 |                       ]
4279 |                   }
4280 |               }
4281 |           }
4282 |           ```
4283 |         </CodeGroup>
4284 |       </Tab>
4285 |     </Tabs>
4286 | 
4287 |     This tells Claude for Desktop:
4288 | 
4289 |     1.  There's an MCP server named "weather"
4290 |     2.  Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
4291 | 
4292 |     Save the file, and restart **Claude for Desktop**.
4293 |   </Tab>
4294 | </Tabs>
4295 | 
4296 | ### Test with commands
4297 | 
4298 | Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the hammer <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon:
4299 | 
4300 | <Frame>
4301 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/visual-indicator-mcp-tools.png" />
4302 | </Frame>
4303 | 
4304 | After clicking on the hammer icon, you should see two tools listed:
4305 | 
4306 | <Frame>
4307 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/available-mcp-tools.png" />
4308 | </Frame>
4309 | 
4310 | If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
4311 | 
4312 | If the hammer icon has shown up, you can now test your server by running the following commands in Claude for Desktop:
4313 | 
4314 | *   What's the weather in Sacramento?
4315 | *   What are the active weather alerts in Texas?
4316 | 
4317 | <Frame>
4318 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" />
4319 | </Frame>
4320 | 
4321 | <Frame>
4322 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" />
4323 | </Frame>
4324 | 
4325 | <Note>
4326 |   Since this is the US National Weather service, the queries will only work for US locations.
4327 | </Note>
4328 | 
4329 | ## What's happening under the hood
4330 | 
4331 | When you ask a question:
4332 | 
4333 | 1.  The client sends your question to Claude
4334 | 2.  Claude analyzes the available tools and decides which one(s) to use
4335 | 3.  The client executes the chosen tool(s) through the MCP server
4336 | 4.  The results are sent back to Claude
4337 | 5.  Claude formulates a natural language response
4338 | 6.  The response is displayed to you!
4339 | 
4340 | ## Troubleshooting
4341 | 
4342 | <AccordionGroup>
4343 |   <Accordion title="Claude for Desktop Integration Issues">
4344 |     **Getting logs from Claude for Desktop**
4345 | 
4346 |     Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude`:
4347 | 
4348 |     *   `mcp.log` will contain general logging about MCP connections and connection failures.
4349 |     *   Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
4350 | 
4351 |     You can run the following command to list recent logs and follow along with any new ones:
4352 | 
4353 |     ```bash
4354 |     # Check Claude's logs for errors
4355 |     tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
4356 |     ```
4357 | 
4358 |     **Server not showing up in Claude**
4359 | 
4360 |     1.  Check your `claude_desktop_config.json` file syntax
4361 |     2.  Make sure the path to your project is absolute and not relative
4362 |     3.  Restart Claude for Desktop completely
4363 | 
4364 |     **Tool calls failing silently**
4365 | 
4366 |     If Claude attempts to use the tools but they fail:
4367 | 
4368 |     1.  Check Claude's logs for errors
4369 |     2.  Verify your server builds and runs without errors
4370 |     3.  Try restarting Claude for Desktop
4371 | 
4372 |     **None of this is working. What do I do?**
4373 | 
4374 |     Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance.
4375 |   </Accordion>
4376 | 
4377 |   <Accordion title="Weather API Issues">
4378 |     **Error: Failed to retrieve grid point data**
4379 | 
4380 |     This usually means either:
4381 | 
4382 |     1.  The coordinates are outside the US
4383 |     2.  The NWS API is having issues
4384 |     3.  You're being rate limited
4385 | 
4386 |     Fix:
4387 | 
4388 |     *   Verify you're using US coordinates
4389 |     *   Add a small delay between requests
4390 |     *   Check the NWS API status page
4391 | 
4392 |     **Error: No active alerts for \[STATE]**
4393 | 
4394 |     This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
4395 |   </Accordion>
4396 | </AccordionGroup>
4397 | 
4398 | <Note>
4399 |   For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/tools/debugging)
4400 | </Note>
4401 | 
4402 | ## Next steps
4403 | 
4404 | <CardGroup cols={2}>
4405 |   <Card title="Building a client" icon="outlet" href="/quickstart/client">
4406 |     Learn how to build your own MCP client that can connect to your server
4407 |   </Card>
4408 | 
4409 |   <Card title="Example servers" icon="grid" href="/examples">
4410 |     Check out our gallery of official MCP servers and implementations
4411 |   </Card>
4412 | 
4413 |   <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
4414 |     Learn how to effectively debug MCP servers and integrations
4415 |   </Card>
4416 | 
4417 |   <Card title="Building MCP with LLMs" icon="comments" href="/building-mcp-with-llms">
4418 |     Learn how to use LLMs like Claude to speed up your MCP development
4419 |   </Card>
4420 | </CardGroup>
4421 | 
4422 | 
4423 | # For Claude Desktop Users
4424 | 
4425 | Get started using pre-built servers in Claude for Desktop.
4426 | 
4427 | In this tutorial, you will extend [Claude for Desktop](https://claude.ai/download) so that it can read from your computer's file system, write new files, move files, and even search files.
4428 | 
4429 | <Frame>
4430 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-filesystem.png" />
4431 | </Frame>
4432 | 
4433 | Don't worry — it will ask you for your permission before executing these actions!
4434 | 
4435 | ## 1. Download Claude for Desktop
4436 | 
4437 | Start by downloading [Claude for Desktop](https://claude.ai/download), choosing either macOS or Windows. (Linux is not yet supported for Claude for Desktop.)
4438 | 
4439 | Follow the installation instructions.
4440 | 
4441 | If you already have Claude for Desktop, make sure it's on the latest version by clicking on the Claude menu on your computer and selecting "Check for Updates..."
4442 | 
4443 | <Accordion title="Why Claude for Desktop and not Claude.ai?">
4444 |   Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development.
4445 | </Accordion>
4446 | 
4447 | ## 2. Add the Filesystem MCP Server
4448 | 
4449 | To add this filesystem functionality, we will be installing a pre-built [Filesystem MCP Server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) to Claude for Desktop. This is one of dozens of [servers](https://github.com/modelcontextprotocol/servers/tree/main) created by Anthropic and the community.
4450 | 
4451 | Get started by opening up the Claude menu on your computer and select "Settings..." Please note that these are not the Claude Account Settings found in the app window itself.
4452 | 
4453 | This is what it should look like on a Mac:
4454 | 
4455 | <Frame style={{ textAlign: 'center' }}>
4456 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-menu.png" width="400" />
4457 | </Frame>
4458 | 
4459 | Click on "Developer" in the lefthand bar of the Settings pane, and then click on "Edit Config":
4460 | 
4461 | <Frame>
4462 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-developer.png" />
4463 | </Frame>
4464 | 
4465 | This will create a configuration file at:
4466 | 
4467 | *   macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
4468 | *   Windows: `%APPDATA%\Claude\claude_desktop_config.json`
4469 | 
4470 | if you don't already have one, and will display the file in your file system.
4471 | 
4472 | Open up the configuration file in any text editor. Replace the file contents with this:
4473 | 
4474 | <Tabs>
4475 |   <Tab title="MacOS/Linux">
4476 |     ```json
4477 |     {
4478 |       "mcpServers": {
4479 |         "filesystem": {
4480 |           "command": "npx",
4481 |           "args": [
4482 |             "-y",
4483 |             "@modelcontextprotocol/server-filesystem",
4484 |             "/Users/username/Desktop",
4485 |             "/Users/username/Downloads"
4486 |           ]
4487 |         }
4488 |       }
4489 |     }
4490 |     ```
4491 |   </Tab>
4492 | 
4493 |   <Tab title="Windows">
4494 |     ```json
4495 |     {
4496 |       "mcpServers": {
4497 |         "filesystem": {
4498 |           "command": "npx",
4499 |           "args": [
4500 |             "-y",
4501 |             "@modelcontextprotocol/server-filesystem",
4502 |             "C:\\Users\\username\\Desktop",
4503 |             "C:\\Users\\username\\Downloads"
4504 |           ]
4505 |         }
4506 |       }
4507 |     }
4508 |     ```
4509 |   </Tab>
4510 | </Tabs>
4511 | 
4512 | Make sure to replace `username` with your computer's username. The paths should point to valid directories that you want Claude to be able to access and modify. It's set up to work for Desktop and Downloads, but you can add more paths as well.
4513 | 
4514 | You will also need [Node.js](https://nodejs.org) on your computer for this to run properly. To verify you have Node installed, open the command line on your computer.
4515 | 
4516 | *   On macOS, open the Terminal from your Applications folder
4517 | *   On Windows, press Windows + R, type "cmd", and press Enter
4518 | 
4519 | Once in the command line, verify you have Node installed by entering in the following command:
4520 | 
4521 | ```bash
4522 | node --version
4523 | ```
4524 | 
4525 | If you get an error saying "command not found" or "node is not recognized", download Node from [nodejs.org](https://nodejs.org/).
4526 | 
4527 | <Tip>
4528 |   **How does the configuration file work?**
4529 | 
4530 |   This configuration file tells Claude for Dekstop which MCP servers to start up every time you start the application. In this case, we have added one server called "filesystem" that will use the Node `npx` command to install and run `@modelcontextprotocol/server-filesystem`. This server, described [here](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem), will let you access your file system in Claude for Desktop.
4531 | </Tip>
4532 | 
4533 | ## 3. Restart Claude
4534 | 
4535 | After updating your configuration file, you need to restart Claude for Desktop.
4536 | 
4537 | Upon restarting, you should see a hammer <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon in the bottom right corner of the input box:
4538 | 
4539 | <Frame>
4540 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-hammer.png" />
4541 | </Frame>
4542 | 
4543 | After clicking on the hammer icon, you should see the tools that come with the Filesystem MCP Server:
4544 | 
4545 | <Frame style={{ textAlign: 'center' }}>
4546 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-tools.png" width="400" />
4547 | </Frame>
4548 | 
4549 | If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
4550 | 
4551 | ## 4. Try it out!
4552 | 
4553 | You can now talk to Claude and ask it about your filesystem. It should know when to call the relevant tools.
4554 | 
4555 | Things you might try asking Claude:
4556 | 
4557 | *   Can you write a poem and save it to my desktop?
4558 | *   What are some work-related files in my downloads folder?
4559 | *   Can you take all the images on my desktop and move them to a new folder called "Images"?
4560 | 
4561 | As needed, Claude will call the relevant tools and seek your approval before taking an action:
4562 | 
4563 | <Frame style={{ textAlign: 'center' }}>
4564 |   <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-approve.png" width="500" />
4565 | </Frame>
4566 | 
4567 | ## Troubleshooting
4568 | 
4569 | <AccordionGroup>
4570 |   <Accordion title="Server not showing up in Claude / hammer icon missing">
4571 |     1.  Restart Claude for Desktop completely
4572 |     2.  Check your `claude_desktop_config.json` file syntax
4573 |     3.  Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative
4574 |     4.  Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting
4575 |     5.  In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors:
4576 | 
4577 |     <Tabs>
4578 |       <Tab title="MacOS/Linux">
4579 |         ```bash
4580 |         npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads`
4581 |         ```
4582 |       </Tab>
4583 | 
4584 |       <Tab title="Windows">
4585 |         ```bash
4586 |         npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads
4587 |         ```
4588 |       </Tab>
4589 |     </Tabs>
4590 |   </Accordion>
4591 | 
4592 |   <Accordion title="Getting logs from Claude for Desktop">
4593 |     Claude.app logging related to MCP is written to log files in:
4594 | 
4595 |     *   macOS: `~/Library/Logs/Claude`
4596 | 
4597 |     *   Windows: `%APPDATA%\Claude\logs`
4598 | 
4599 |     *   `mcp.log` will contain general logging about MCP connections and connection failures.
4600 | 
4601 |     *   Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
4602 | 
4603 |     You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs):
4604 | 
4605 |     <Tabs>
4606 |       <Tab title="MacOS/Linux">
4607 |         ```bash
4608 |         # Check Claude's logs for errors
4609 |         tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
4610 |         ```
4611 |       </Tab>
4612 | 
4613 |       <Tab title="Windows">
4614 |         ```bash
4615 |         type "%APPDATA%\Claude\logs\mcp*.log"
4616 |         ```
4617 |       </Tab>
4618 |     </Tabs>
4619 |   </Accordion>
4620 | 
4621 |   <Accordion title="Tool calls failing silently">
4622 |     If Claude attempts to use the tools but they fail:
4623 | 
4624 |     1.  Check Claude's logs for errors
4625 |     2.  Verify your server builds and runs without errors
4626 |     3.  Try restarting Claude for Desktop
4627 |   </Accordion>
4628 | 
4629 |   <Accordion title="None of this is working. What do I do?">
4630 |     Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance.
4631 |   </Accordion>
4632 | </AccordionGroup>
4633 | 
4634 | ## Next steps
4635 | 
4636 | <CardGroup cols={2}>
4637 |   <Card title="Explore other servers" icon="grid" href="/examples">
4638 |     Check out our gallery of official MCP servers and implementations
4639 |   </Card>
4640 | 
4641 |   <Card title="Build your own server" icon="code" href="/quickstart/server">
4642 |     Now build your own custom server to use in Claude for Desktop and other clients
4643 |   </Card>
4644 | </CardGroup>
4645 | 
4646 | 
4647 | # Building MCP with LLMs
4648 | 
4649 | Speed up your MCP development using LLMs such as Claude!
4650 | 
4651 | This guide will help you use LLMs to help you build custom Model Context Protocol (MCP) servers and clients. We'll be focusing on Claude for this tutorial, but you can do this with any frontier LLM.
4652 | 
4653 | ## Preparing the documentation
4654 | 
4655 | Before starting, gather the necessary documentation to help Claude understand MCP:
4656 | 
4657 | 1.  Visit [https://modelcontextprotocol.io/llms-full.txt](https://modelcontextprotocol.io/llms-full.txt) and copy the full documentation text
4658 | 2.  Navigate to either the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) or [Python SDK repository](https://github.com/modelcontextprotocol/python-sdk)
4659 | 3.  Copy the README files and other relevant documentation
4660 | 4.  Paste these documents into your conversation with Claude
4661 | 
4662 | ## Describing your server
4663 | 
4664 | Once you've provided the documentation, clearly describe to Claude what kind of server you want to build. Be specific about:
4665 | 
4666 | *   What resources your server will expose
4667 | *   What tools it will provide
4668 | *   Any prompts it should offer
4669 | *   What external systems it needs to interact with
4670 | 
4671 | For example:
4672 | 
4673 | ```
4674 | Build an MCP server that:
4675 | - Connects to my company's PostgreSQL database
4676 | - Exposes table schemas as resources
4677 | - Provides tools for running read-only SQL queries
4678 | - Includes prompts for common data analysis tasks
4679 | ```
4680 | 
4681 | ## Working with Claude
4682 | 
4683 | When working with Claude on MCP servers:
4684 | 
4685 | 1.  Start with the core functionality first, then iterate to add more features
4686 | 2.  Ask Claude to explain any parts of the code you don't understand
4687 | 3.  Request modifications or improvements as needed
4688 | 4.  Have Claude help you test the server and handle edge cases
4689 | 
4690 | Claude can help implement all the key MCP features:
4691 | 
4692 | *   Resource management and exposure
4693 | *   Tool definitions and implementations
4694 | *   Prompt templates and handlers
4695 | *   Error handling and logging
4696 | *   Connection and transport setup
4697 | 
4698 | ## Best practices
4699 | 
4700 | When building MCP servers with Claude:
4701 | 
4702 | *   Break down complex servers into smaller pieces
4703 | *   Test each component thoroughly before moving on
4704 | *   Keep security in mind - validate inputs and limit access appropriately
4705 | *   Document your code well for future maintenance
4706 | *   Follow MCP protocol specifications carefully
4707 | 
4708 | ## Next steps
4709 | 
4710 | After Claude helps you build your server:
4711 | 
4712 | 1.  Review the generated code carefully
4713 | 2.  Test the server with the MCP Inspector tool
4714 | 3.  Connect it to Claude.app or other MCP clients
4715 | 4.  Iterate based on real usage and feedback
4716 | 
4717 | Remember that Claude can help you modify and improve your server as requirements change over time.
4718 | 
4719 | Need more guidance? Just ask Claude specific questions about implementing MCP features or troubleshooting issues that arise.
4720 | 
4721 | 
```