#
tokens: 58484/50000 1/48 files (page 4/4)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 4 of 4. Use http://codebase.md/infinitiq-tech/mcp-jira?lines=true&page={x} to view the full context.

# Directory Structure

```
├── .env.example
├── .github
│   ├── copilot-instructions.md
│   └── ISSUE_TEMPLATE
│       ├── bug_report.yml
│       ├── config.yml
│       ├── copilot.yml
│       ├── story.yml
│       └── task.yml
├── .gitignore
├── .lock
├── bin
│   ├── activate
│   ├── activate.csh
│   ├── activate.fish
│   ├── Activate.ps1
│   ├── dotenv
│   ├── httpx
│   ├── jirashell
│   ├── mcp
│   ├── mcp-server-jira
│   ├── normalizer
│   ├── pip
│   ├── pip3
│   ├── pip3.10
│   ├── python
│   ├── python3
│   ├── python3.10
│   └── uvicorn
├── claude_reference
│   ├── jira_advanced.txt
│   ├── jira_api_documentation.txt
│   ├── jira_examples.txt
│   ├── jira_installation.md
│   └── jira_shell.txt
├── Dockerfile
├── docs
│   └── create_issues_v3_conversion.md
├── glama.json
├── jira.py
├── LICENSE
├── mcp
│   ├── __init__.py
│   ├── server
│   │   └── __init__.py
│   └── types
│       └── __init__.py
├── MCPReadme.md
├── pyproject.toml
├── pytest.ini
├── pyvenv.cfg
├── README.md
├── run_server.py
├── src
│   ├── __init__.py
│   ├── mcp
│   │   ├── __init__.py
│   │   ├── server
│   │   │   ├── __init__.py
│   │   │   └── stdio.py
│   │   └── types
│   │       └── __init__.py
│   └── mcp_server_jira
│       ├── __init__.py
│       ├── __main__.py
│       ├── jira_v3_api.py
│       └── server.py
├── tests
│   ├── __init__.py
│   ├── test_add_comment_v3_api_only.py
│   ├── test_bulk_create_issues_v3_api.py
│   ├── test_create_issue_v3_api_only.py
│   ├── test_create_issues_integration.py
│   ├── test_create_jira_issues_server.py
│   ├── test_get_transitions_v3.py
│   ├── test_jira_v3_api.py
│   ├── test_search_issues_v3_api.py
│   ├── test_server.py
│   └── test_transition_issue_v3_api_only.py
└── uv.lock
```

# Files

--------------------------------------------------------------------------------
/MCPReadme.md:
--------------------------------------------------------------------------------

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