#
tokens: 40729/50000 11/11 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .gitignore
├── 2024-12-02-screenshot_1.png
├── LICENSE
├── package-lock.json
├── package.json
├── prompts
│   ├── 01-oauthtoken.md
│   ├── 02-boards-as-resources.md
│   └── ref
│       ├── mcp-llms.txt.md
│       └── mcp-types.ts
├── README.md
├── resources
│   └── boards-key-facts.md
├── src
│   ├── index.ts
│   └── MiroClient.ts
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
node_modules/
build/
*.log
.env*
prompts/ref/miro-spec.json

```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# mcp-miro MCP Server
[![smithery badge](https://smithery.ai/badge/@llmindset/mcp-miro)](https://smithery.ai/server/@llmindset/mcp-miro)

A Model Context Protocol server to connect to the MIRO Whiteboard Application.

- Allows Board manipulation, sticky creation, bulk operations and more.
- Pass your OAuth key as an Environment Variable, or using the "--token" argument.
- Taking a photo of stickies and asking Claude to create MIRO equivalent works _really_ well.

<a href="https://glama.ai/mcp/servers/gr5t7vthv3"><img width="380" height="200" src="https://glama.ai/mcp/servers/gr5t7vthv3/badge" alt="mcp-miro MCP server" /></a>

## Installation

### Installing via Smithery

To install MIRO Whiteboard Connector for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@llmindset/mcp-miro):

```bash
npx -y @smithery/cli install @llmindset/mcp-miro --client claude
```

### Using mcp-get

You can install this package using mcp-get:

```bash
npx @michaellatman/mcp-get@latest install @llmindset/mcp-miro
```

_Note - if you are using an old version of Windows PowerShell, you may need to run_ `Set-ExecutionPolicy Bypass -Scope Process` _before this command._

## Features

![MIRO/Claude Desktop Screenshot](./2024-12-02-screenshot_1.png)

### Resources
- Get Board Contents 

### Tools
- Create Sticky, Shape
- Read Board, Frame, Contents
- Bulk Create

### Prompts
- Instruct on Board Coordinates etc.

## Development

Install dependencies:
```bash
npm install
```

Build the server:
```bash
npm run build
```

For development with auto-rebuild:
```bash
npm run watch
```

## Installation

To use with Claude Desktop, add the server config:

On MacOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
On Windows: `%APPDATA%/Claude/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "mcp-miro": {
      "command": "/path/to/node-or-npx",
      "arguments": [
        "/path/to/mcp-miro/build/index.js",
        "--token","MIRO-OAUTH-KEY"
      ]
    }
  }
}
```

### Debugging

Since MCP servers communicate over stdio, debugging can be challenging. We recommend using the [MCP Inspector](https://github.com/modelcontextprotocol/inspector), which is available as a package script:

```bash
npm run inspector
```

The Inspector will provide a URL to access debugging tools in your browser.

In Dev environment recommend adding https://github.com/miroapp/api-clients/blob/041de24ebf7955432b447d887ede066ad4c7e2c7/packages/generator/spec.json for reference.

```

--------------------------------------------------------------------------------
/prompts/01-oauthtoken.md:
--------------------------------------------------------------------------------

```markdown
we need to have access to an OAUTH token to access an API. it should be possible to be passed in either as an environment variable "MIRO_OAUTH_TOKEN", or as a command line argument. if both are present, the command line takes precedence. use standard typescript and node technique/libraries to achieve this.

```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

```

--------------------------------------------------------------------------------
/resources/boards-key-facts.md:
--------------------------------------------------------------------------------

```markdown
# Key facts about Miro boards and coordinates

## Board Coordinates

- Boards are infinite and zoomable in all directions
- The board center is at coordinates (0,0)
- All board-level coordinates are relative to this center point
- Board items use x,y coordinates to specify their position
- Item coordinates mark the CENTER point of the item

## Coordinate Types

- Board-level: Items directly on board use coordinates relative to board center (0,0)
- Parent-child: Child items inside parent containers (like frames) use coordinates relative to parent's top-left corner

## Units

- Measurements use board units
- 100 board units = 100 device-independent pixels at 100% zoom

## Default Behavior

 -Items created without specified coordinates default to board center (0,0)
 -Frames always appear behind other board items in the z-order
 -The initial viewport center when creating a new board becomes the board's (0,0) reference point

```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "@llmindset/mcp-miro",
  "version": "0.1.1",
  "description": "A Model Context Protocol server to connect to the MIRO Whiteboard Application",
  "type": "module",
  "publishConfig": {
    "access": "public"
  },  
  "bin": {
    "mcp-miro": "./build/index.js"
  },
  "files": [
    "build"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/evalstate/mcp-miro"
  },
  "bugs":{
    "url": "https://github.com/evalstate/mcp-miro/issues"
  },  
  "scripts": {
    "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
    "prepare": "npm run build",
    "watch": "tsc --watch",
    "inspector": "npx @modelcontextprotocol/inspector build/index.js"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "0.6.0",
    "node-fetch": "^3.3.2",
    "yargs": "^17.7.2"
  },
  "devDependencies": {
    "@types/node": "^20.11.24",
    "@types/yargs": "^17.0.33",
    "typescript": "^5.3.3"
  }
}

```

--------------------------------------------------------------------------------
/src/MiroClient.ts:
--------------------------------------------------------------------------------

```typescript

import fetch from 'node-fetch';

interface MiroBoard {
  id: string;
  name: string;
  description?: string;
}

interface MiroBoardsResponse {
  data: MiroBoard[];
  total: number;
  size: number;
  offset: number;
}

interface MiroItem {
  id: string;
  type: string;
  [key: string]: any;
}

interface MiroItemsResponse {
  data: MiroItem[];
  cursor?: string;
}

export class MiroClient {
  constructor(private token: string) {}

  private async fetchApi(path: string, options: { method?: string; body?: any } = {}) {
    const response = await fetch(`https://api.miro.com/v2${path}`, {
      method: options.method || 'GET',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json'
      },
      ...(options.body ? { body: JSON.stringify(options.body) } : {})
    });
    
    if (!response.ok) {
      throw new Error(`Miro API error: ${response.status} ${response.statusText}`);
    }

    return response.json();
  }

  async getBoards(): Promise<MiroBoard[]> {
    const response = await this.fetchApi('/boards') as MiroBoardsResponse;
    return response.data;
  }

  async getBoardItems(boardId: string): Promise<MiroItem[]> {
    const response = await this.fetchApi(`/boards/${boardId}/items?limit=50`) as MiroItemsResponse;
    return response.data;
  }

  async createStickyNote(boardId: string, data: any): Promise<MiroItem> {
    return this.fetchApi(`/boards/${boardId}/sticky_notes`, {
      method: 'POST',
      body: data
    }) as Promise<MiroItem>;
  }

  async bulkCreateItems(boardId: string, items: any[]): Promise<MiroItem[]> {
    const response = await fetch(`https://api.miro.com/v2/boards/${boardId}/items/bulk`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(items)
    });
    
    if (!response.ok) {
      const error = await response.json() as { message?: string };
      throw new Error(`Miro API error: ${error.message || response.statusText}`);
    }

    const result = await response.json() as { data: MiroItem[] };
    return result.data || [];
  }

  async getFrames(boardId: string): Promise<MiroItem[]> {
    const response = await this.fetchApi(`/boards/${boardId}/items?type=frame&limit=50`) as MiroItemsResponse;
    return response.data;
  }

  async getItemsInFrame(boardId: string, frameId: string): Promise<MiroItem[]> {
    const response = await this.fetchApi(`/boards/${boardId}/items?parent_item_id=${frameId}&limit=50`) as MiroItemsResponse;
    return response.data;
  }

  async createShape(boardId: string, data: any): Promise<MiroItem> {
    return this.fetchApi(`/boards/${boardId}/shapes`, {
      method: 'POST',
      body: data
    }) as Promise<MiroItem>;
  }
}
```

--------------------------------------------------------------------------------
/prompts/02-boards-as-resources.md:
--------------------------------------------------------------------------------

```markdown
</MIRO_API_1> <MIRO_API_2> "/v2/boards/{board_id}/items": { "get": { "description": "Retrieves a list of items for a specific board. You can retrieve all items on the board, a list of child items inside a parent item, or a list of specific types of items by specifying URL query parameter values.\n\nThis method returns results using a cursor-based approach. A cursor-paginated method returns a portion of the total set of results based on the limit specified and a cursor that points to the next portion of the results. To retrieve the next portion of the collection, on your next call to the same method, set the `cursor` parameter equal to the `cursor` value you received in the response of the previous request. For example, if you set the `limit` query parameter to `10` and the board contains 20 objects, the first call will return information about the first 10 objects in the response along with a cursor parameter and value. In this example, let's say the cursor parameter value returned in the response is `foo`. If you want to retrieve the next set of objects, on your next call to the same method, set the cursor parameter value to `foo`.<br/><h3>Required scope</h3> <a target=_blank href=https://developers.miro.com/reference/scopes>boards:read</a> <br/><h3>Rate limiting</h3> <a target=_blank href=\"/docs/miro-rest-api-introduction#rate-limiting\">Level 2</a><br/>", "operationId": "get-items", "parameters": [ { "in": "query", "name": "limit", "schema": { "type": "string", "default": "10", "description": "The maximum number of results to return per call. If the number of items in the response is greater than the limit specified, the response returns the cursor parameter with a value.", "maximum": 50, "minimum": 10 } }, { "in": "query", "name": "type", "schema": { "type": "string", "enum": [ "text", "shape", "sticky_note", "image", "document", "card", "app_card", "preview", "frame", "embed" ], "description": "If you want to get a list of items of a specific type, specify an item type. For example, if you want to retrieve the list of card items, set `type` to `cards`.\n Possible values: `app_card`, `card`, `document`, `embed`, `frame`, `image`, `shape`, `sticky_note`, `text`" } }, { "in": "query", "name": "cursor", "schema": { "type": "string", "description": "A cursor-paginated method returns a portion of the total set of results based on the limit specified and a `cursor` that points to the next portion of the results. To retrieve the next portion of the collection, set the `cursor` parameter equal to the `cursor` value you received in the response of the previous request." } }, { "description": "Unique identifier (ID) of the board for which you want to retrieve the list of available items.", "in": "path", "name": "board_id", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/GenericItemCursorPaged" } } }, "description": "Items retrieved" }, "400": { "$ref": "#/components/responses/400" }, "404": { "$ref": "#/components/responses/404" }, "429": { "$ref": "#/components/responses/429" } }, "summary": "Get items on board", "tags": ["items"] } }, </MIRO_API_2>
i would like to expose the available MIRO boards as resources. each board should return it's items as JSON.

that will mean calling GetBoards in the MIRO API and for each board calling GetItems. GetItems should return a JSON string which is the Resource content. #file:index.ts
```

--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------

```typescript
#!/usr/bin/env node

import yargs from "yargs/yargs";
import { hideBin } from "yargs/helpers";
import { MiroClient } from "./MiroClient.js";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  ListResourcesRequestSchema,
  ReadResourceRequestSchema,
  ListToolsRequestSchema,
  CallToolRequestSchema,
  ListPromptsRequestSchema,
  GetPromptRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import fs from 'fs/promises';
import path from 'path';

// Parse command line arguments
const argv = await yargs(hideBin(process.argv))
  .option("token", {
    alias: "t",
    type: "string",
    description: "Miro OAuth token",
  })
  .help().argv;

// Get token with precedence: command line > environment variable
const oauthToken = (argv.token as string) || process.env.MIRO_OAUTH_TOKEN;

if (!oauthToken) {
  console.error(
    "Error: Miro OAuth token is required. Provide it via MIRO_OAUTH_TOKEN environment variable or --token argument"
  );
  process.exit(1);
}

const server = new Server(
  {
    name: "mcp-miro",
    version: "0.1.0",
  },
  {
    capabilities: {
      resources: {},
      tools: {},
      prompts: {},
    },
  }
);

const miroClient = new MiroClient(oauthToken);

server.setRequestHandler(ListResourcesRequestSchema, async () => {
  const boards = await miroClient.getBoards();

  return {
    resources: boards.map((board) => ({
      uri: `miro://board/${board.id}`,
      mimeType: "application/json",
      name: board.name,
      description: board.description || `Miro board: ${board.name}`,
    })),
  };
});

server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  const url = new URL(request.params.uri);

  if (!request.params.uri.startsWith("miro://board/")) {
    throw new Error(
      "Invalid Miro resource URI - must start with miro://board/"
    );
  }

  const boardId = url.pathname.substring(1); // Remove leading slash from pathname
  const items = await miroClient.getBoardItems(boardId);

  return {
    contents: [
      {
        uri: request.params.uri,
        mimeType: "application/json",
        text: JSON.stringify(items, null, 2),
      },
    ],
  };
});

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "list_boards",
        description: "List all available Miro boards and their IDs",
        inputSchema: {
          type: "object",
          properties: {},
        },
      },
      {
        name: "create_sticky_note",
        description:
          "Create a sticky note on a Miro board. By default, sticky notes are 199x228 and available in these colors: gray, light_yellow, yellow, orange, light_green, green, dark_green, cyan, light_pink, pink, violet, red, light_blue, blue, dark_blue, black.",
        inputSchema: {
          type: "object",
          properties: {
            boardId: {
              type: "string",
              description: "ID of the board to create the sticky note on",
            },
            content: {
              type: "string",
              description: "Text content of the sticky note",
            },
            color: {
              type: "string",
              description:
                "Color of the sticky note (e.g. 'yellow', 'blue', 'pink')",
              enum: [
                "gray",
                "light_yellow",
                "yellow",
                "orange",
                "light_green",
                "green",
                "dark_green",
                "cyan",
                "light_pink",
                "pink",
                "violet",
                "red",
                "light_blue",
                "blue",
                "dark_blue",
                "black",
              ],
              default: "yellow",
            },
            x: {
              type: "number",
              description: "X coordinate position",
              default: 0,
            },
            y: {
              type: "number",
              description: "Y coordinate position",
              default: 0,
            },
          },
          required: ["boardId", "content"],
        },
      },
      {
        name: "bulk_create_items",
        description:
          "Create multiple items on a Miro board in a single transaction (max 20 items)",
        inputSchema: {
          type: "object",
          properties: {
            boardId: {
              type: "string",
              description: "ID of the board to create the items on",
            },
            items: {
              type: "array",
              description: "Array of items to create",
              items: {
                type: "object",
                properties: {
                  type: {
                    type: "string",
                    enum: [
                      "app_card",
                      "text",
                      "shape",
                      "sticky_note",
                      "image",
                      "document",
                      "card",
                      "frame",
                      "embed",
                    ],
                    description: "Type of item to create",
                  },
                  data: {
                    type: "object",
                    description: "Item-specific data configuration",
                  },
                  style: {
                    type: "object",
                    description: "Item-specific style configuration",
                  },
                  position: {
                    type: "object",
                    description: "Item position configuration",
                  },
                  geometry: {
                    type: "object",
                    description: "Item geometry configuration",
                  },
                  parent: {
                    type: "object",
                    description: "Parent item configuration",
                  },
                },
                required: ["type"],
              },
              minItems: 1,
              maxItems: 20,
            },
          },
          required: ["boardId", "items"],
        },
      },
      {
        name: "get_frames",
        description: "Get all frames from a Miro board",
        inputSchema: {
          type: "object",
          properties: {
            boardId: {
              type: "string",
              description: "ID of the board to get frames from",
            },
          },
          required: ["boardId"],
        },
      },
      {
        name: "get_items_in_frame",
        description:
          "Get all items contained within a specific frame on a Miro board",
        inputSchema: {
          type: "object",
          properties: {
            boardId: {
              type: "string",
              description: "ID of the board that contains the frame",
            },
            frameId: {
              type: "string",
              description: "ID of the frame to get items from",
            },
          },
          required: ["boardId", "frameId"],
        },
      },
      {
        name: "create_shape",
        description:
          "Create a shape on a Miro board. Available shapes include basic shapes (rectangle, circle, etc.) and flowchart shapes (process, decision, etc.). Standard geometry specs: width and height in pixels (default 200x200)",
        inputSchema: {
          type: "object",
          properties: {
            boardId: {
              type: "string",
              description: "ID of the board to create the shape on",
            },
            content: {
              type: "string",
              description: "Text content to display on the shape",
            },
            shape: {
              type: "string",
              description: "Type of shape to create",
              enum: [
                // Basic shapes
                "rectangle",
                "round_rectangle",
                "circle",
                "triangle",
                "rhombus",
                "parallelogram",
                "trapezoid",
                "pentagon",
                "hexagon",
                "octagon",
                "wedge_round_rectangle_callout",
                "star",
                "flow_chart_predefined_process",
                "cloud",
                "cross",
                "can",
                "right_arrow",
                "left_arrow",
                "left_right_arrow",
                "left_brace",
                "right_brace",
                // Flowchart shapes
                "flow_chart_connector",
                "flow_chart_magnetic_disk",
                "flow_chart_input_output",
                "flow_chart_decision",
                "flow_chart_delay",
                "flow_chart_display",
                "flow_chart_document",
                "flow_chart_magnetic_drum",
                "flow_chart_internal_storage",
                "flow_chart_manual_input",
                "flow_chart_manual_operation",
                "flow_chart_merge",
                "flow_chart_multidocuments",
                "flow_chart_note_curly_left",
                "flow_chart_note_curly_right",
                "flow_chart_note_square",
                "flow_chart_offpage_connector",
                "flow_chart_or",
                "flow_chart_predefined_process_2",
                "flow_chart_preparation",
                "flow_chart_process",
                "flow_chart_online_storage",
                "flow_chart_summing_junction",
                "flow_chart_terminator",
              ],
              default: "rectangle",
            },
            style: {
              type: "object",
              description: "Style configuration for the shape",
              properties: {
                borderColor: { type: "string" },
                borderOpacity: { type: "number", minimum: 0, maximum: 1 },
                borderStyle: {
                  type: "string",
                  enum: ["normal", "dotted", "dashed"],
                },
                borderWidth: { type: "number", minimum: 1, maximum: 24 },
                color: { type: "string" },
                fillColor: { type: "string" },
                fillOpacity: { type: "number", minimum: 0, maximum: 1 },
                fontFamily: { type: "string" },
                fontSize: { type: "number", minimum: 10, maximum: 288 },
                textAlign: {
                  type: "string",
                  enum: ["left", "center", "right"],
                },
                textAlignVertical: {
                  type: "string",
                  enum: ["top", "middle", "bottom"],
                },
              },
            },
            position: {
              type: "object",
              properties: {
                x: { type: "number", default: 0 },
                y: { type: "number", default: 0 },
                origin: { type: "string", default: "center" },
              },
            },
            geometry: {
              type: "object",
              properties: {
                width: { type: "number", default: 200 },
                height: { type: "number", default: 200 },
                rotation: { type: "number", default: 0 },
              },
            },
          },
          required: ["boardId", "shape"],
        },
      },
    ],
  };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  switch (request.params.name) {
    case "list_boards": {
      const boards = await miroClient.getBoards();
      return {
        content: [
          {
            type: "text",
            text: "Here are the available Miro boards:",
          },
          ...boards.map((b) => ({
            type: "text",
            text: `Board ID: ${b.id}, Name: ${b.name}`,
          })),
        ],
      };
    }

    case "create_sticky_note": {
      const {
        boardId,
        content,
        color = "yellow",
        x = 0,
        y = 0,
      } = request.params.arguments as any;

      const stickyNote = await miroClient.createStickyNote(boardId, {
        data: {
          content: content,
        },
        style: {
          fillColor: color,
        },
        position: {
          x: x,
          y: y,
        },
      });

      return {
        content: [
          {
            type: "text",
            text: `Created sticky note ${stickyNote.id} on board ${boardId}`,
          },
        ],
      };
    }

    case "bulk_create_items": {
      const { boardId, items } = request.params.arguments as any;

      const createdItems = await miroClient.bulkCreateItems(boardId, items);

      return {
        content: [
          {
            type: "text",
            text: `Created ${createdItems.length} items on board ${boardId}`,
          },
        ],
      };
    }

    case "get_frames": {
      const { boardId } = request.params.arguments as any;
      const frames = await miroClient.getFrames(boardId);

      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(frames, null, 2),
          },
        ],
      };
    }

    case "get_items_in_frame": {
      const { boardId, frameId } = request.params.arguments as any;
      const items = await miroClient.getItemsInFrame(boardId, frameId);

      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(items, null, 2),
          },
        ],
      };
    }

    case "create_shape": {
      const { boardId, shape, content, style, position, geometry } = request
        .params.arguments as any;

      const shapeItem = await miroClient.createShape(boardId, {
        data: {
          shape: shape,
          content: content,
        },
        style: style || {},
        position: position || { x: 0, y: 0 },
        geometry: geometry || { width: 200, height: 200, rotation: 0 },
      });

      return {
        content: [
          {
            type: "text",
            text: `Created ${shape} shape with ID ${shapeItem.id} on board ${boardId}`,
          },
        ],
      };
    }

    default:
      throw new Error("Unknown tool");
  }
});

server.setRequestHandler(ListPromptsRequestSchema, async () => {
  return {
    prompts: [
      {
        name: "Working with MIRO",
        description: "Basic prompt for working with MIRO boards",
      },
    ],
  };
});

server.setRequestHandler(GetPromptRequestSchema, async (request) => {
  if (request.params.name === "Working with MIRO") {
    const keyFactsPath = path.join(process.cwd(), 'resources', 'boards-key-facts.md');
    const keyFacts = await fs.readFile(keyFactsPath, 'utf-8');
    return {
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: keyFacts,
          },
        },
      ],
    };
  }
  throw new Error("Unknown prompt");
});

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main().catch((error) => {
  console.error("Server error:", error);
  process.exit(1);
});

```

--------------------------------------------------------------------------------
/prompts/ref/mcp-types.ts:
--------------------------------------------------------------------------------

```typescript
import { z } from "zod";

export const LATEST_PROTOCOL_VERSION = "2024-11-05";
export const SUPPORTED_PROTOCOL_VERSIONS = [
  LATEST_PROTOCOL_VERSION,
  "2024-10-07",
];

/* JSON-RPC types */
export const JSONRPC_VERSION = "2.0";

/**
 * A progress token, used to associate progress notifications with the original request.
 */
export const ProgressTokenSchema = z.union([z.string(), z.number().int()]);

/**
 * An opaque token used to represent a cursor for pagination.
 */
export const CursorSchema = z.string();

const BaseRequestParamsSchema = z
  .object({
    _meta: z.optional(
      z
        .object({
          /**
           * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
           */
          progressToken: z.optional(ProgressTokenSchema),
        })
        .passthrough(),
    ),
  })
  .passthrough();

export const RequestSchema = z.object({
  method: z.string(),
  params: z.optional(BaseRequestParamsSchema),
});

const BaseNotificationParamsSchema = z
  .object({
    /**
     * This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.
     */
    _meta: z.optional(z.object({}).passthrough()),
  })
  .passthrough();

export const NotificationSchema = z.object({
  method: z.string(),
  params: z.optional(BaseNotificationParamsSchema),
});

export const ResultSchema = z
  .object({
    /**
     * This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.
     */
    _meta: z.optional(z.object({}).passthrough()),
  })
  .passthrough();

/**
 * A uniquely identifying ID for a request in JSON-RPC.
 */
export const RequestIdSchema = z.union([z.string(), z.number().int()]);

/**
 * A request that expects a response.
 */
export const JSONRPCRequestSchema = z
  .object({
    jsonrpc: z.literal(JSONRPC_VERSION),
    id: RequestIdSchema,
  })
  .merge(RequestSchema)
  .strict();

/**
 * A notification which does not expect a response.
 */
export const JSONRPCNotificationSchema = z
  .object({
    jsonrpc: z.literal(JSONRPC_VERSION),
  })
  .merge(NotificationSchema)
  .strict();

/**
 * A successful (non-error) response to a request.
 */
export const JSONRPCResponseSchema = z
  .object({
    jsonrpc: z.literal(JSONRPC_VERSION),
    id: RequestIdSchema,
    result: ResultSchema,
  })
  .strict();

/**
 * An incomplete set of error codes that may appear in JSON-RPC responses.
 */
export enum ErrorCode {
  // SDK error codes
  ConnectionClosed = -1,
  RequestTimeout = -2,

  // Standard JSON-RPC error codes
  ParseError = -32700,
  InvalidRequest = -32600,
  MethodNotFound = -32601,
  InvalidParams = -32602,
  InternalError = -32603,
}

/**
 * A response to a request that indicates an error occurred.
 */
export const JSONRPCErrorSchema = z
  .object({
    jsonrpc: z.literal(JSONRPC_VERSION),
    id: RequestIdSchema,
    error: z.object({
      /**
       * The error type that occurred.
       */
      code: z.number().int(),
      /**
       * A short description of the error. The message SHOULD be limited to a concise single sentence.
       */
      message: z.string(),
      /**
       * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
       */
      data: z.optional(z.unknown()),
    }),
  })
  .strict();

export const JSONRPCMessageSchema = z.union([
  JSONRPCRequestSchema,
  JSONRPCNotificationSchema,
  JSONRPCResponseSchema,
  JSONRPCErrorSchema,
]);

/* Empty result */
/**
 * A response that indicates success but carries no data.
 */
export const EmptyResultSchema = ResultSchema.strict();

/* Cancellation */
/**
 * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
 *
 * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
 *
 * This notification indicates that the result will be unused, so any associated processing SHOULD cease.
 *
 * A client MUST NOT attempt to cancel its `initialize` request.
 */
export const CancelledNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/cancelled"),
  params: BaseNotificationParamsSchema.extend({
    /**
     * The ID of the request to cancel.
     *
     * This MUST correspond to the ID of a request previously issued in the same direction.
     */
    requestId: RequestIdSchema,

    /**
     * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
     */
    reason: z.string().optional(),
  }),
});

/* Initialization */
/**
 * Describes the name and version of an MCP implementation.
 */
export const ImplementationSchema = z
  .object({
    name: z.string(),
    version: z.string(),
  })
  .passthrough();

/**
 * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
 */
export const ClientCapabilitiesSchema = z
  .object({
    /**
     * Experimental, non-standard capabilities that the client supports.
     */
    experimental: z.optional(z.object({}).passthrough()),
    /**
     * Present if the client supports sampling from an LLM.
     */
    sampling: z.optional(z.object({}).passthrough()),
    /**
     * Present if the client supports listing roots.
     */
    roots: z.optional(
      z
        .object({
          /**
           * Whether the client supports issuing notifications for changes to the roots list.
           */
          listChanged: z.optional(z.boolean()),
        })
        .passthrough(),
    ),
  })
  .passthrough();

/**
 * This request is sent from the client to the server when it first connects, asking it to begin initialization.
 */
export const InitializeRequestSchema = RequestSchema.extend({
  method: z.literal("initialize"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
     */
    protocolVersion: z.string(),
    capabilities: ClientCapabilitiesSchema,
    clientInfo: ImplementationSchema,
  }),
});

/**
 * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
 */
export const ServerCapabilitiesSchema = z
  .object({
    /**
     * Experimental, non-standard capabilities that the server supports.
     */
    experimental: z.optional(z.object({}).passthrough()),
    /**
     * Present if the server supports sending log messages to the client.
     */
    logging: z.optional(z.object({}).passthrough()),
    /**
     * Present if the server offers any prompt templates.
     */
    prompts: z.optional(
      z
        .object({
          /**
           * Whether this server supports issuing notifications for changes to the prompt list.
           */
          listChanged: z.optional(z.boolean()),
        })
        .passthrough(),
    ),
    /**
     * Present if the server offers any resources to read.
     */
    resources: z.optional(
      z
        .object({
          /**
           * Whether this server supports clients subscribing to resource updates.
           */
          subscribe: z.optional(z.boolean()),

          /**
           * Whether this server supports issuing notifications for changes to the resource list.
           */
          listChanged: z.optional(z.boolean()),
        })
        .passthrough(),
    ),
    /**
     * Present if the server offers any tools to call.
     */
    tools: z.optional(
      z
        .object({
          /**
           * Whether this server supports issuing notifications for changes to the tool list.
           */
          listChanged: z.optional(z.boolean()),
        })
        .passthrough(),
    ),
  })
  .passthrough();

/**
 * After receiving an initialize request from the client, the server sends this response.
 */
export const InitializeResultSchema = ResultSchema.extend({
  /**
   * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
   */
  protocolVersion: z.string(),
  capabilities: ServerCapabilitiesSchema,
  serverInfo: ImplementationSchema,
});

/**
 * This notification is sent from the client to the server after initialization has finished.
 */
export const InitializedNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/initialized"),
});

/* Ping */
/**
 * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
 */
export const PingRequestSchema = RequestSchema.extend({
  method: z.literal("ping"),
});

/* Progress notifications */
export const ProgressSchema = z
  .object({
    /**
     * The progress thus far. This should increase every time progress is made, even if the total is unknown.
     */
    progress: z.number(),
    /**
     * Total number of items to process (or total progress required), if known.
     */
    total: z.optional(z.number()),
  })
  .passthrough();

/**
 * An out-of-band notification used to inform the receiver of a progress update for a long-running request.
 */
export const ProgressNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/progress"),
  params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
    /**
     * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
     */
    progressToken: ProgressTokenSchema,
  }),
});

/* Pagination */
export const PaginatedRequestSchema = RequestSchema.extend({
  params: BaseRequestParamsSchema.extend({
    /**
     * An opaque token representing the current pagination position.
     * If provided, the server should return results starting after this cursor.
     */
    cursor: z.optional(CursorSchema),
  }).optional(),
});

export const PaginatedResultSchema = ResultSchema.extend({
  /**
   * An opaque token representing the pagination position after the last returned result.
   * If present, there may be more results available.
   */
  nextCursor: z.optional(CursorSchema),
});

/* Resources */
/**
 * The contents of a specific resource or sub-resource.
 */
export const ResourceContentsSchema = z
  .object({
    /**
     * The URI of this resource.
     */
    uri: z.string(),
    /**
     * The MIME type of this resource, if known.
     */
    mimeType: z.optional(z.string()),
  })
  .passthrough();

export const TextResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
   */
  text: z.string(),
});

export const BlobResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * A base64-encoded string representing the binary data of the item.
   */
  blob: z.string().base64(),
});

/**
 * A known resource that the server is capable of reading.
 */
export const ResourceSchema = z
  .object({
    /**
     * The URI of this resource.
     */
    uri: z.string(),

    /**
     * A human-readable name for this resource.
     *
     * This can be used by clients to populate UI elements.
     */
    name: z.string(),

    /**
     * A description of what this resource represents.
     *
     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
     */
    description: z.optional(z.string()),

    /**
     * The MIME type of this resource, if known.
     */
    mimeType: z.optional(z.string()),
  })
  .passthrough();

/**
 * A template description for resources available on the server.
 */
export const ResourceTemplateSchema = z
  .object({
    /**
     * A URI template (according to RFC 6570) that can be used to construct resource URIs.
     */
    uriTemplate: z.string(),

    /**
     * A human-readable name for the type of resource this template refers to.
     *
     * This can be used by clients to populate UI elements.
     */
    name: z.string(),

    /**
     * A description of what this template is for.
     *
     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
     */
    description: z.optional(z.string()),

    /**
     * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
     */
    mimeType: z.optional(z.string()),
  })
  .passthrough();

/**
 * Sent from the client to request a list of resources the server has.
 */
export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({
  method: z.literal("resources/list"),
});

/**
 * The server's response to a resources/list request from the client.
 */
export const ListResourcesResultSchema = PaginatedResultSchema.extend({
  resources: z.array(ResourceSchema),
});

/**
 * Sent from the client to request a list of resource templates the server has.
 */
export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend(
  {
    method: z.literal("resources/templates/list"),
  },
);

/**
 * The server's response to a resources/templates/list request from the client.
 */
export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
  resourceTemplates: z.array(ResourceTemplateSchema),
});

/**
 * Sent from the client to the server, to read a specific resource URI.
 */
export const ReadResourceRequestSchema = RequestSchema.extend({
  method: z.literal("resources/read"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
     */
    uri: z.string(),
  }),
});

/**
 * The server's response to a resources/read request from the client.
 */
export const ReadResourceResultSchema = ResultSchema.extend({
  contents: z.array(
    z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
  ),
});

/**
 * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.
 */
export const ResourceListChangedNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/resources/list_changed"),
});

/**
 * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.
 */
export const SubscribeRequestSchema = RequestSchema.extend({
  method: z.literal("resources/subscribe"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
     */
    uri: z.string(),
  }),
});

/**
 * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.
 */
export const UnsubscribeRequestSchema = RequestSchema.extend({
  method: z.literal("resources/unsubscribe"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The URI of the resource to unsubscribe from.
     */
    uri: z.string(),
  }),
});

/**
 * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.
 */
export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/resources/updated"),
  params: BaseNotificationParamsSchema.extend({
    /**
     * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
     */
    uri: z.string(),
  }),
});

/* Prompts */
/**
 * Describes an argument that a prompt can accept.
 */
export const PromptArgumentSchema = z
  .object({
    /**
     * The name of the argument.
     */
    name: z.string(),
    /**
     * A human-readable description of the argument.
     */
    description: z.optional(z.string()),
    /**
     * Whether this argument must be provided.
     */
    required: z.optional(z.boolean()),
  })
  .passthrough();

/**
 * A prompt or prompt template that the server offers.
 */
export const PromptSchema = z
  .object({
    /**
     * The name of the prompt or prompt template.
     */
    name: z.string(),
    /**
     * An optional description of what this prompt provides
     */
    description: z.optional(z.string()),
    /**
     * A list of arguments to use for templating the prompt.
     */
    arguments: z.optional(z.array(PromptArgumentSchema)),
  })
  .passthrough();

/**
 * Sent from the client to request a list of prompts and prompt templates the server has.
 */
export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({
  method: z.literal("prompts/list"),
});

/**
 * The server's response to a prompts/list request from the client.
 */
export const ListPromptsResultSchema = PaginatedResultSchema.extend({
  prompts: z.array(PromptSchema),
});

/**
 * Used by the client to get a prompt provided by the server.
 */
export const GetPromptRequestSchema = RequestSchema.extend({
  method: z.literal("prompts/get"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The name of the prompt or prompt template.
     */
    name: z.string(),
    /**
     * Arguments to use for templating the prompt.
     */
    arguments: z.optional(z.record(z.string())),
  }),
});

/**
 * Text provided to or from an LLM.
 */
export const TextContentSchema = z
  .object({
    type: z.literal("text"),
    /**
     * The text content of the message.
     */
    text: z.string(),
  })
  .passthrough();

/**
 * An image provided to or from an LLM.
 */
export const ImageContentSchema = z
  .object({
    type: z.literal("image"),
    /**
     * The base64-encoded image data.
     */
    data: z.string().base64(),
    /**
     * The MIME type of the image. Different providers may support different image types.
     */
    mimeType: z.string(),
  })
  .passthrough();

/**
 * The contents of a resource, embedded into a prompt or tool call result.
 */
export const EmbeddedResourceSchema = z
  .object({
    type: z.literal("resource"),
    resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
  })
  .passthrough();

/**
 * Describes a message returned as part of a prompt.
 */
export const PromptMessageSchema = z
  .object({
    role: z.enum(["user", "assistant"]),
    content: z.union([
      TextContentSchema,
      ImageContentSchema,
      EmbeddedResourceSchema,
    ]),
  })
  .passthrough();

/**
 * The server's response to a prompts/get request from the client.
 */
export const GetPromptResultSchema = ResultSchema.extend({
  /**
   * An optional description for the prompt.
   */
  description: z.optional(z.string()),
  messages: z.array(PromptMessageSchema),
});

/**
 * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.
 */
export const PromptListChangedNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/prompts/list_changed"),
});

/* Tools */
/**
 * Definition for a tool the client can call.
 */
export const ToolSchema = z
  .object({
    /**
     * The name of the tool.
     */
    name: z.string(),
    /**
     * A human-readable description of the tool.
     */
    description: z.optional(z.string()),
    /**
     * A JSON Schema object defining the expected parameters for the tool.
     */
    inputSchema: z
      .object({
        type: z.literal("object"),
        properties: z.optional(z.object({}).passthrough()),
      })
      .passthrough(),
  })
  .passthrough();

/**
 * Sent from the client to request a list of tools the server has.
 */
export const ListToolsRequestSchema = PaginatedRequestSchema.extend({
  method: z.literal("tools/list"),
});

/**
 * The server's response to a tools/list request from the client.
 */
export const ListToolsResultSchema = PaginatedResultSchema.extend({
  tools: z.array(ToolSchema),
});

/**
 * The server's response to a tool call.
 */
export const CallToolResultSchema = ResultSchema.extend({
  content: z.array(
    z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema]),
  ),
  isError: z.boolean().default(false).optional(),
});

/**
 * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.
 */
export const CompatibilityCallToolResultSchema = CallToolResultSchema.or(
  ResultSchema.extend({
    toolResult: z.unknown(),
  }),
);

/**
 * Used by the client to invoke a tool provided by the server.
 */
export const CallToolRequestSchema = RequestSchema.extend({
  method: z.literal("tools/call"),
  params: BaseRequestParamsSchema.extend({
    name: z.string(),
    arguments: z.optional(z.record(z.unknown())),
  }),
});

/**
 * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.
 */
export const ToolListChangedNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/tools/list_changed"),
});

/* Logging */
/**
 * The severity of a log message.
 */
export const LoggingLevelSchema = z.enum([
  "debug",
  "info",
  "notice",
  "warning",
  "error",
  "critical",
  "alert",
  "emergency",
]);

/**
 * A request from the client to the server, to enable or adjust logging.
 */
export const SetLevelRequestSchema = RequestSchema.extend({
  method: z.literal("logging/setLevel"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
     */
    level: LoggingLevelSchema,
  }),
});

/**
 * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.
 */
export const LoggingMessageNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/message"),
  params: BaseNotificationParamsSchema.extend({
    /**
     * The severity of this log message.
     */
    level: LoggingLevelSchema,
    /**
     * An optional name of the logger issuing this message.
     */
    logger: z.optional(z.string()),
    /**
     * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
     */
    data: z.unknown(),
  }),
});

/* Sampling */
/**
 * Hints to use for model selection.
 */
export const ModelHintSchema = z
  .object({
    /**
     * A hint for a model name.
     */
    name: z.string().optional(),
  })
  .passthrough();

/**
 * The server's preferences for model selection, requested of the client during sampling.
 */
export const ModelPreferencesSchema = z
  .object({
    /**
     * Optional hints to use for model selection.
     */
    hints: z.optional(z.array(ModelHintSchema)),
    /**
     * How much to prioritize cost when selecting a model.
     */
    costPriority: z.optional(z.number().min(0).max(1)),
    /**
     * How much to prioritize sampling speed (latency) when selecting a model.
     */
    speedPriority: z.optional(z.number().min(0).max(1)),
    /**
     * How much to prioritize intelligence and capabilities when selecting a model.
     */
    intelligencePriority: z.optional(z.number().min(0).max(1)),
  })
  .passthrough();

/**
 * Describes a message issued to or received from an LLM API.
 */
export const SamplingMessageSchema = z
  .object({
    role: z.enum(["user", "assistant"]),
    content: z.union([TextContentSchema, ImageContentSchema]),
  })
  .passthrough();

/**
 * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.
 */
export const CreateMessageRequestSchema = RequestSchema.extend({
  method: z.literal("sampling/createMessage"),
  params: BaseRequestParamsSchema.extend({
    messages: z.array(SamplingMessageSchema),
    /**
     * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
     */
    systemPrompt: z.optional(z.string()),
    /**
     * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.
     */
    includeContext: z.optional(z.enum(["none", "thisServer", "allServers"])),
    temperature: z.optional(z.number()),
    /**
     * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
     */
    maxTokens: z.number().int(),
    stopSequences: z.optional(z.array(z.string())),
    /**
     * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
     */
    metadata: z.optional(z.object({}).passthrough()),
    /**
     * The server's preferences for which model to select.
     */
    modelPreferences: z.optional(ModelPreferencesSchema),
  }),
});

/**
 * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it.
 */
export const CreateMessageResultSchema = ResultSchema.extend({
  /**
   * The name of the model that generated the message.
   */
  model: z.string(),
  /**
   * The reason why sampling stopped.
   */
  stopReason: z.optional(
    z.enum(["endTurn", "stopSequence", "maxTokens"]).or(z.string()),
  ),
  role: z.enum(["user", "assistant"]),
  content: z.discriminatedUnion("type", [
    TextContentSchema,
    ImageContentSchema,
  ]),
});

/* Autocomplete */
/**
 * A reference to a resource or resource template definition.
 */
export const ResourceReferenceSchema = z
  .object({
    type: z.literal("ref/resource"),
    /**
     * The URI or URI template of the resource.
     */
    uri: z.string(),
  })
  .passthrough();

/**
 * Identifies a prompt.
 */
export const PromptReferenceSchema = z
  .object({
    type: z.literal("ref/prompt"),
    /**
     * The name of the prompt or prompt template
     */
    name: z.string(),
  })
  .passthrough();

/**
 * A request from the client to the server, to ask for completion options.
 */
export const CompleteRequestSchema = RequestSchema.extend({
  method: z.literal("completion/complete"),
  params: BaseRequestParamsSchema.extend({
    ref: z.union([PromptReferenceSchema, ResourceReferenceSchema]),
    /**
     * The argument's information
     */
    argument: z
      .object({
        /**
         * The name of the argument
         */
        name: z.string(),
        /**
         * The value of the argument to use for completion matching.
         */
        value: z.string(),
      })
      .passthrough(),
  }),
});

/**
 * The server's response to a completion/complete request
 */
export const CompleteResultSchema = ResultSchema.extend({
  completion: z
    .object({
      /**
       * An array of completion values. Must not exceed 100 items.
       */
      values: z.array(z.string()).max(100),
      /**
       * The total number of completion options available. This can exceed the number of values actually sent in the response.
       */
      total: z.optional(z.number().int()),
      /**
       * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
       */
      hasMore: z.optional(z.boolean()),
    })
    .passthrough(),
});

/* Roots */
/**
 * Represents a root directory or file that the server can operate on.
 */
export const RootSchema = z
  .object({
    /**
     * The URI identifying the root. This *must* start with file:// for now.
     */
    uri: z.string().startsWith("file://"),
    /**
     * An optional name for the root.
     */
    name: z.optional(z.string()),
  })
  .passthrough();

/**
 * Sent from the server to request a list of root URIs from the client.
 */
export const ListRootsRequestSchema = RequestSchema.extend({
  method: z.literal("roots/list"),
});

/**
 * The client's response to a roots/list request from the server.
 */
export const ListRootsResultSchema = ResultSchema.extend({
  roots: z.array(RootSchema),
});

/**
 * A notification from the client to the server, informing it that the list of roots has changed.
 */
export const RootsListChangedNotificationSchema = NotificationSchema.extend({
  method: z.literal("notifications/roots/list_changed"),
});

/* Client messages */
export const ClientRequestSchema = z.union([
  PingRequestSchema,
  InitializeRequestSchema,
  CompleteRequestSchema,
  SetLevelRequestSchema,
  GetPromptRequestSchema,
  ListPromptsRequestSchema,
  ListResourcesRequestSchema,
  ListResourceTemplatesRequestSchema,
  ReadResourceRequestSchema,
  SubscribeRequestSchema,
  UnsubscribeRequestSchema,
  CallToolRequestSchema,
  ListToolsRequestSchema,
]);

export const ClientNotificationSchema = z.union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  InitializedNotificationSchema,
  RootsListChangedNotificationSchema,
]);

export const ClientResultSchema = z.union([
  EmptyResultSchema,
  CreateMessageResultSchema,
  ListRootsResultSchema,
]);

/* Server messages */
export const ServerRequestSchema = z.union([
  PingRequestSchema,
  CreateMessageRequestSchema,
  ListRootsRequestSchema,
]);

export const ServerNotificationSchema = z.union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  LoggingMessageNotificationSchema,
  ResourceUpdatedNotificationSchema,
  ResourceListChangedNotificationSchema,
  ToolListChangedNotificationSchema,
  PromptListChangedNotificationSchema,
]);

export const ServerResultSchema = z.union([
  EmptyResultSchema,
  InitializeResultSchema,
  CompleteResultSchema,
  GetPromptResultSchema,
  ListPromptsResultSchema,
  ListResourcesResultSchema,
  ListResourceTemplatesResultSchema,
  ReadResourceResultSchema,
  CallToolResultSchema,
  ListToolsResultSchema,
]);

export class McpError extends Error {
  constructor(
    public readonly code: number,
    message: string,
    public readonly data?: unknown,
  ) {
    super(`MCP error ${code}: ${message}`);
  }
}

/* JSON-RPC types */
export type ProgressToken = z.infer<typeof ProgressTokenSchema>;
export type Cursor = z.infer<typeof CursorSchema>;
export type Request = z.infer<typeof RequestSchema>;
export type Notification = z.infer<typeof NotificationSchema>;
export type Result = z.infer<typeof ResultSchema>;
export type RequestId = z.infer<typeof RequestIdSchema>;
export type JSONRPCRequest = z.infer<typeof JSONRPCRequestSchema>;
export type JSONRPCNotification = z.infer<typeof JSONRPCNotificationSchema>;
export type JSONRPCResponse = z.infer<typeof JSONRPCResponseSchema>;
export type JSONRPCError = z.infer<typeof JSONRPCErrorSchema>;
export type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>;

/* Empty result */
export type EmptyResult = z.infer<typeof EmptyResultSchema>;

/* Cancellation */
export type CancelledNotification = z.infer<typeof CancelledNotificationSchema>;

/* Initialization */
export type Implementation = z.infer<typeof ImplementationSchema>;
export type ClientCapabilities = z.infer<typeof ClientCapabilitiesSchema>;
export type InitializeRequest = z.infer<typeof InitializeRequestSchema>;
export type ServerCapabilities = z.infer<typeof ServerCapabilitiesSchema>;
export type InitializeResult = z.infer<typeof InitializeResultSchema>;
export type InitializedNotification = z.infer<
  typeof InitializedNotificationSchema
>;

/* Ping */
export type PingRequest = z.infer<typeof PingRequestSchema>;

/* Progress notifications */
export type Progress = z.infer<typeof ProgressSchema>;
export type ProgressNotification = z.infer<typeof ProgressNotificationSchema>;

/* Pagination */
export type PaginatedRequest = z.infer<typeof PaginatedRequestSchema>;
export type PaginatedResult = z.infer<typeof PaginatedResultSchema>;

/* Resources */
export type ResourceContents = z.infer<typeof ResourceContentsSchema>;
export type TextResourceContents = z.infer<typeof TextResourceContentsSchema>;
export type BlobResourceContents = z.infer<typeof BlobResourceContentsSchema>;
export type Resource = z.infer<typeof ResourceSchema>;
export type ResourceTemplate = z.infer<typeof ResourceTemplateSchema>;
export type ListResourcesRequest = z.infer<typeof ListResourcesRequestSchema>;
export type ListResourcesResult = z.infer<typeof ListResourcesResultSchema>;
export type ListResourceTemplatesRequest = z.infer<
  typeof ListResourceTemplatesRequestSchema
>;
export type ListResourceTemplatesResult = z.infer<
  typeof ListResourceTemplatesResultSchema
>;
export type ReadResourceRequest = z.infer<typeof ReadResourceRequestSchema>;
export type ReadResourceResult = z.infer<typeof ReadResourceResultSchema>;
export type ResourceListChangedNotification = z.infer<
  typeof ResourceListChangedNotificationSchema
>;
export type SubscribeRequest = z.infer<typeof SubscribeRequestSchema>;
export type UnsubscribeRequest = z.infer<typeof UnsubscribeRequestSchema>;
export type ResourceUpdatedNotification = z.infer<
  typeof ResourceUpdatedNotificationSchema
>;

/* Prompts */
export type PromptArgument = z.infer<typeof PromptArgumentSchema>;
export type Prompt = z.infer<typeof PromptSchema>;
export type ListPromptsRequest = z.infer<typeof ListPromptsRequestSchema>;
export type ListPromptsResult = z.infer<typeof ListPromptsResultSchema>;
export type GetPromptRequest = z.infer<typeof GetPromptRequestSchema>;
export type TextContent = z.infer<typeof TextContentSchema>;
export type ImageContent = z.infer<typeof ImageContentSchema>;
export type EmbeddedResource = z.infer<typeof EmbeddedResourceSchema>;
export type PromptMessage = z.infer<typeof PromptMessageSchema>;
export type GetPromptResult = z.infer<typeof GetPromptResultSchema>;
export type PromptListChangedNotification = z.infer<
  typeof PromptListChangedNotificationSchema
>;

/* Tools */
export type Tool = z.infer<typeof ToolSchema>;
export type ListToolsRequest = z.infer<typeof ListToolsRequestSchema>;
export type ListToolsResult = z.infer<typeof ListToolsResultSchema>;
export type CallToolResult = z.infer<typeof CallToolResultSchema>;
export type CompatibilityCallToolResult = z.infer<
  typeof CompatibilityCallToolResultSchema
>;
export type CallToolRequest = z.infer<typeof CallToolRequestSchema>;
export type ToolListChangedNotification = z.infer<
  typeof ToolListChangedNotificationSchema
>;

/* Logging */
export type LoggingLevel = z.infer<typeof LoggingLevelSchema>;
export type SetLevelRequest = z.infer<typeof SetLevelRequestSchema>;
export type LoggingMessageNotification = z.infer<
  typeof LoggingMessageNotificationSchema
>;

/* Sampling */
export type SamplingMessage = z.infer<typeof SamplingMessageSchema>;
export type CreateMessageRequest = z.infer<typeof CreateMessageRequestSchema>;
export type CreateMessageResult = z.infer<typeof CreateMessageResultSchema>;

/* Autocomplete */
export type ResourceReference = z.infer<typeof ResourceReferenceSchema>;
export type PromptReference = z.infer<typeof PromptReferenceSchema>;
export type CompleteRequest = z.infer<typeof CompleteRequestSchema>;
export type CompleteResult = z.infer<typeof CompleteResultSchema>;

/* Roots */
export type Root = z.infer<typeof RootSchema>;
export type ListRootsRequest = z.infer<typeof ListRootsRequestSchema>;
export type ListRootsResult = z.infer<typeof ListRootsResultSchema>;
export type RootsListChangedNotification = z.infer<
  typeof RootsListChangedNotificationSchema
>;

/* Client messages */
export type ClientRequest = z.infer<typeof ClientRequestSchema>;
export type ClientNotification = z.infer<typeof ClientNotificationSchema>;
export type ClientResult = z.infer<typeof ClientResultSchema>;

/* Server messages */
export type ServerRequest = z.infer<typeof ServerRequestSchema>;
export type ServerNotification = z.infer<typeof ServerNotificationSchema>;
export type ServerResult = z.infer<typeof ServerResultSchema>;
```

--------------------------------------------------------------------------------
/prompts/ref/mcp-llms.txt.md:
--------------------------------------------------------------------------------

```markdown
# Clients

A list of applications that support MCP integrations

This page provides an overview of applications that support the Model Context Protocol (MCP). Each client may support different MCP features, allowing for varying levels of integration with MCP servers.

## Feature support matrix

| Client                       | [Resources] | [Prompts] | [Tools] | [Sampling] | Roots | Notes                              |
| ---------------------------- | ----------- | --------- | ------- | ---------- | ----- | ---------------------------------- |
| [Claude Desktop App][Claude] | ✅           | ✅         | ✅       | ❌          | ❌     | Full support for all MCP features  |
| [Zed][Zed]                   | ❌           | ✅         | ❌       | ❌          | ❌     | Prompts appear as slash commands   |
| [Sourcegraph Cody][Cody]     | ✅           | ❌         | ❌       | ❌          | ❌     | Supports resources through OpenCTX |

[Claude]: https://claude.ai/download

[Zed]: https://zed.dev

[Cody]: https://sourcegraph.com/cody

[Resources]: https://modelcontextprotocol.io/docs/concepts/resources

[Prompts]: https://modelcontextprotocol.io/docs/concepts/prompts

[Tools]: https://modelcontextprotocol.io/docs/concepts/tools

[Sampling]: https://modelcontextprotocol.io/docs/concepts/sampling

## Client details

### Claude Desktop App

The Claude desktop application provides comprehensive support for MCP, enabling deep integration with local tools and data sources.

**Key features:**

*   Full support for resources, allowing attachment of local files and data
*   Support for prompt templates
*   Tool integration for executing commands and scripts
*   Local server connections for enhanced privacy and security

> ⓘ Note: The Claude.ai web application does not currently support MCP. MCP features are only available in the desktop application.

### Zed

[Zed](https://zed.dev/docs/assistant/model-context-protocol) is a high-performance code editor with built-in MCP support, focusing on prompt templates and tool integration.

**Key features:**

*   Prompt templates surface as slash commands in the editor
*   Tool integration for enhanced coding workflows
*   Tight integration with editor features and workspace context
*   Does not support MCP resources

### Sourcegraph Cody

[Cody](https://openctx.org/docs/providers/modelcontextprotocol) is Sourcegraph's AI coding assistant, which implements MCP through OpenCTX.

**Key features:**

*   Support for MCP resources
*   Integration with Sourcegraph's code intelligence
*   Uses OpenCTX as an abstraction layer
*   Future support planned for additional MCP features

## Adding MCP support to your application

If you've added MCP support to your application, we encourage you to submit a pull request to add it to this list. MCP integration can provide your users with powerful contextual AI capabilities and make your application part of the growing MCP ecosystem.

Benefits of adding MCP support:

*   Enable users to bring their own context and tools
*   Join a growing ecosystem of interoperable AI applications
*   Provide users with flexible integration options
*   Support local-first AI workflows

To get started with implementing MCP in your application, check out our [Python](https://github.com/modelcontextprotocol/python-sdk) or [TypeScript SDK Documentation](https://github.com/modelcontextprotocol/typescript-sdk)

## Updates and corrections

This list is maintained by the community. If you notice any inaccuracies or would like to update information about MCP support in your application, please submit a pull request or [open an issue in our documentation repository](https://github.com/modelcontextprotocol/docs/issues).


# Core architecture

Understand how MCP connects clients, servers, and LLMs

The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and integrations. This document covers the core architectural components and concepts.

## Overview

MCP follows a client-server architecture where:

*   **Hosts** are LLM applications (like Claude Desktop or IDEs) that initiate connections
*   **Clients** maintain 1:1 connections with servers, inside the host application
*   **Servers** provide context, tools, and prompts to clients

```mermaid
flowchart LR
    subgraph "&nbsp;Host (e.g., Claude Desktop)&nbsp;"
        client1[MCP Client]
        client2[MCP Client]
    end
    subgraph "Server Process"
        server1[MCP Server]
    end
    subgraph "Server Process"
        server2[MCP Server]
    end

    client1 <-->|Transport Layer| server1
    client2 <-->|Transport Layer| server2
```

## Core components

### Protocol layer

The protocol layer handles message framing, request/response linking, and high-level communication patterns.

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    class Protocol<Request, Notification, Result> {
        // Handle incoming requests
        setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void

        // Handle incoming notifications
        setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void

        // Send requests and await responses
        request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>

        // Send one-way notifications
        notification(notification: Notification): Promise<void>
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python
    class Session(BaseSession[RequestT, NotificationT, ResultT]):
        async def send_request(
            self,
            request: RequestT,
            result_type: type[Result]
        ) -> Result:
            """
            Send request and wait for response. Raises McpError if response contains error.
            """
            # Request handling implementation

        async def send_notification(
            self,
            notification: NotificationT
        ) -> None:
            """Send one-way notification that doesn't expect response."""
            # Notification handling implementation

        async def _received_request(
            self,
            responder: RequestResponder[ReceiveRequestT, ResultT]
        ) -> None:
            """Handle incoming request from other side."""
            # Request handling implementation

        async def _received_notification(
            self,
            notification: ReceiveNotificationT
        ) -> None:
            """Handle incoming notification from other side."""
            # Notification handling implementation
    ```
  </Tab>
</Tabs>

Key classes include:

*   `Protocol`
*   `Client`
*   `Server`

### Transport layer

The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:

1.  **Stdio transport**
    *   Uses standard input/output for communication
    *   Ideal for local processes

2.  **HTTP with SSE transport**
    *   Uses Server-Sent Events for server-to-client messages
    *   HTTP POST for client-to-server messages

All transports use [JSON-RPC](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](https://spec.modelcontextprotocol.io) for detailed information about the Model Context Protocol message format.

### Message types

MCP has these main types of messages:

1.  **Requests** expect a response from the other side:
    ```typescript
    interface Request {
      method: string;
      params?: { ... };
    }
    ```

2.  **Notifications** are one-way messages that don't expect a response:
    ```typescript
    interface Notification {
      method: string;
      params?: { ... };
    }
    ```

3.  **Results** are successful responses to requests:
    ```typescript
    interface Result {
      [key: string]: unknown;
    }
    ```

4.  **Errors** indicate that a request failed:
    ```typescript
    interface Error {
      code: number;
      message: string;
      data?: unknown;
    }
    ```

## Connection lifecycle

### 1. Initialization

```mermaid
sequenceDiagram
    participant Client
    participant Server

    Client->>Server: initialize request
    Server->>Client: initialize response
    Client->>Server: initialized notification

    Note over Client,Server: Connection ready for use
```

1.  Client sends `initialize` request with protocol version and capabilities
2.  Server responds with its protocol version and capabilities
3.  Client sends `initialized` notification as acknowledgment
4.  Normal message exchange begins

### 2. Message exchange

After initialization, the following patterns are supported:

*   **Request-Response**: Client or server sends requests, the other responds
*   **Notifications**: Either party sends one-way messages

### 3. Termination

Either party can terminate the connection:

*   Clean shutdown via `close()`
*   Transport disconnection
*   Error conditions

## Error handling

MCP defines these standard error codes:

```typescript
enum ErrorCode {
  // Standard JSON-RPC error codes
  ParseError = -32700,
  InvalidRequest = -32600,
  MethodNotFound = -32601,
  InvalidParams = -32602,
  InternalError = -32603
}
```

SDKs and applications can define their own error codes above -32000.

Errors are propagated through:

*   Error responses to requests
*   Error events on transports
*   Protocol-level error handlers

## Implementation example

Here's a basic example of implementing an MCP server:

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    import { Server } from "@modelcontextprotocol/sdk/server/index.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

    const server = new Server({
      name: "example-server",
      version: "1.0.0"
    }, {
      capabilities: {
        resources: {}
      }
    });

    // Handle requests
    server.setRequestHandler(ListResourcesRequestSchema, async () => {
      return {
        resources: [
          {
            uri: "example://resource",
            name: "Example Resource"
          }
        ]
      };
    });

    // Connect transport
    const transport = new StdioServerTransport();
    await server.connect(transport);
    ```
  </Tab>

  <Tab title="Python">
    ```python
    import asyncio
    import mcp.types as types
    from mcp.server import Server
    from mcp.server.stdio import stdio_server

    app = Server("example-server")

    @app.list_resources()
    async def list_resources() -> list[types.Resource]:
        return [
            types.Resource(
                uri="example://resource",
                name="Example Resource"
            )
        ]

    async def main():
        async with stdio_server() as streams:
            await app.run(
                streams[0],
                streams[1],
                app.create_initialization_options()
            )

    if __name__ == "__main__":
        asyncio.run(main)
    ```
  </Tab>
</Tabs>

## Best practices

### Transport selection

1.  **Local communication**
    *   Use stdio transport for local processes
    *   Efficient for same-machine communication
    *   Simple process management

2.  **Remote communication**
    *   Use SSE for scenarios requiring HTTP compatibility
    *   Consider security implications including authentication and authorization

### Message handling

1.  **Request processing**
    *   Validate inputs thoroughly
    *   Use type-safe schemas
    *   Handle errors gracefully
    *   Implement timeouts

2.  **Progress reporting**
    *   Use progress tokens for long operations
    *   Report progress incrementally
    *   Include total progress when known

3.  **Error management**
    *   Use appropriate error codes
    *   Include helpful error messages
    *   Clean up resources on errors

## Security considerations

1.  **Transport security**
    *   Use TLS for remote connections
    *   Validate connection origins
    *   Implement authentication when needed

2.  **Message validation**
    *   Validate all incoming messages
    *   Sanitize inputs
    *   Check message size limits
    *   Verify JSON-RPC format

3.  **Resource protection**
    *   Implement access controls
    *   Validate resource paths
    *   Monitor resource usage
    *   Rate limit requests

4.  **Error handling**
    *   Don't leak sensitive information
    *   Log security-relevant errors
    *   Implement proper cleanup
    *   Handle DoS scenarios

## Debugging and monitoring

1.  **Logging**
    *   Log protocol events
    *   Track message flow
    *   Monitor performance
    *   Record errors

2.  **Diagnostics**
    *   Implement health checks
    *   Monitor connection state
    *   Track resource usage
    *   Profile performance

3.  **Testing**
    *   Test different transports
    *   Verify error handling
    *   Check edge cases
    *   Load test servers


# Prompts

Create reusable prompt templates and workflows

Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions.

<Note>
  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.
</Note>

## Overview

Prompts in MCP are predefined templates that can:

*   Accept dynamic arguments
*   Include context from resources
*   Chain multiple interactions
*   Guide specific workflows
*   Surface as UI elements (like slash commands)

## Prompt structure

Each prompt is defined with:

```typescript
{
  name: string;              // Unique identifier for the prompt
  description?: string;      // Human-readable description
  arguments?: [              // Optional list of arguments
    {
      name: string;          // Argument identifier
      description?: string;  // Argument description
      required?: boolean;    // Whether argument is required
    }
  ]
}
```

## Discovering prompts

Clients can discover available prompts through the `prompts/list` endpoint:

```typescript
// Request
{
  method: "prompts/list"
}

// Response
{
  prompts: [
    {
      name: "analyze-code",
      description: "Analyze code for potential improvements",
      arguments: [
        {
          name: "language",
          description: "Programming language",
          required: true
        }
      ]
    }
  ]
}
```

## Using prompts

To use a prompt, clients make a `prompts/get` request:

````typescript
// Request
{
  method: "prompts/get",
  params: {
    name: "analyze-code",
    arguments: {
      language: "python"
    }
  }
}

// Response
{
  description: "Analyze Python code for potential improvements",
  messages: [
    {
      role: "user",
      content: {
        type: "text",
        text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n    total = 0\n    for num in numbers:\n        total = total + num\n    return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
      }
    }
  ]
}
````

## Dynamic prompts

Prompts can be dynamic and include:

### Embedded resource context

```json
{
  "name": "analyze-project",
  "description": "Analyze project logs and code",
  "arguments": [
    {
      "name": "timeframe",
      "description": "Time period to analyze logs",
      "required": true
    },
    {
      "name": "fileUri",
      "description": "URI of code file to review",
      "required": true
    }
  ]
}
```

When handling the `prompts/get` request:

```json
{
  "messages": [
    {
      "role": "user",
      "content": {
        "type": "text",
        "text": "Analyze these system logs and the code file for any issues:"
      }
    },
    {
      "role": "user",
      "content": {
        "type": "resource",
        "resource": {
          "uri": "logs://recent?timeframe=1h",
          "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded",
          "mimeType": "text/plain"
        }
      }
    },
    {
      "role": "user",
      "content": {
        "type": "resource",
        "resource": {
          "uri": "file:///path/to/code.py",
          "text": "def connect_to_service(timeout=30):\n    retries = 3\n    for attempt in range(retries):\n        try:\n            return establish_connection(timeout)\n        except TimeoutError:\n            if attempt == retries - 1:\n                raise\n            time.sleep(5)\n\ndef establish_connection(timeout):\n    # Connection implementation\n    pass",
          "mimeType": "text/x-python"
        }
      }
    }
  ]
}
```

### Multi-step workflows

```typescript
const debugWorkflow = {
  name: "debug-error",
  async getMessages(error: string) {
    return [
      {
        role: "user",
        content: {
          type: "text",
          text: `Here's an error I'm seeing: ${error}`
        }
      },
      {
        role: "assistant",
        content: {
          type: "text",
          text: "I'll help analyze this error. What have you tried so far?"
        }
      },
      {
        role: "user",
        content: {
          type: "text",
          text: "I've tried restarting the service, but the error persists."
        }
      }
    ];
  }
};
```

## Example implementation

Here's a complete example of implementing prompts in an MCP server:

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    import { Server } from "@modelcontextprotocol/sdk/server";
    import {
      ListPromptsRequestSchema,
      GetPromptRequestSchema
    } from "@modelcontextprotocol/sdk/types";

    const PROMPTS = {
      "git-commit": {
        name: "git-commit",
        description: "Generate a Git commit message",
        arguments: [
          {
            name: "changes",
            description: "Git diff or description of changes",
            required: true
          }
        ]
      },
      "explain-code": {
        name: "explain-code",
        description: "Explain how code works",
        arguments: [
          {
            name: "code",
            description: "Code to explain",
            required: true
          },
          {
            name: "language",
            description: "Programming language",
            required: false
          }
        ]
      }
    };

    const server = new Server({
      name: "example-prompts-server",
      version: "1.0.0"
    }, {
      capabilities: {
        prompts: {}
      }
    });

    // List available prompts
    server.setRequestHandler(ListPromptsRequestSchema, async () => {
      return {
        prompts: Object.values(PROMPTS)
      };
    });

    // Get specific prompt
    server.setRequestHandler(GetPromptRequestSchema, async (request) => {
      const prompt = PROMPTS[request.params.name];
      if (!prompt) {
        throw new Error(`Prompt not found: ${request.params.name}`);
      }

      if (request.params.name === "git-commit") {
        return {
          messages: [
            {
              role: "user",
              content: {
                type: "text",
                text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}`
              }
            }
          ]
        };
      }

      if (request.params.name === "explain-code") {
        const language = request.params.arguments?.language || "Unknown";
        return {
          messages: [
            {
              role: "user",
              content: {
                type: "text",
                text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}`
              }
            }
          ]
        };
      }

      throw new Error("Prompt implementation not found");
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python
    from mcp.server import Server
    import mcp.types as types

    # Define available prompts
    PROMPTS = {
        "git-commit": types.Prompt(
            name="git-commit",
            description="Generate a Git commit message",
            arguments=[
                types.PromptArgument(
                    name="changes",
                    description="Git diff or description of changes",
                    required=True
                )
            ],
        ),
        "explain-code": types.Prompt(
            name="explain-code",
            description="Explain how code works",
            arguments=[
                types.PromptArgument(
                    name="code",
                    description="Code to explain",
                    required=True
                ),
                types.PromptArgument(
                    name="language",
                    description="Programming language",
                    required=False
                )
            ],
        )
    }

    # Initialize server
    app = Server("example-prompts-server")

    @app.list_prompts()
    async def list_prompts() -> list[types.Prompt]:
        return list(PROMPTS.values())

    @app.get_prompt()
    async def get_prompt(
        name: str, arguments: dict[str, str] | None = None
    ) -> types.GetPromptResult:
        if name not in PROMPTS:
            raise ValueError(f"Prompt not found: {name}")

        if name == "git-commit":
            changes = arguments.get("changes") if arguments else ""
            return types.GetPromptResult(
                messages=[
                    types.PromptMessage(
                        role="user",
                        content=types.TextContent(
                            type="text",
                            text=f"Generate a concise but descriptive commit message "
                            f"for these changes:\n\n{changes}"
                        )
                    )
                ]
            )

        if name == "explain-code":
            code = arguments.get("code") if arguments else ""
            language = arguments.get("language", "Unknown") if arguments else "Unknown"
            return types.GetPromptResult(
                messages=[
                    types.PromptMessage(
                        role="user",
                        content=types.TextContent(
                            type="text",
                            text=f"Explain how this {language} code works:\n\n{code}"
                        )
                    )
                ]
            )

        raise ValueError("Prompt implementation not found")
    ```
  </Tab>
</Tabs>

## Best practices

When implementing prompts:

1.  Use clear, descriptive prompt names
2.  Provide detailed descriptions for prompts and arguments
3.  Validate all required arguments
4.  Handle missing arguments gracefully
5.  Consider versioning for prompt templates
6.  Cache dynamic content when appropriate
7.  Implement error handling
8.  Document expected argument formats
9.  Consider prompt composability
10. Test prompts with various inputs

## UI integration

Prompts can be surfaced in client UIs as:

*   Slash commands
*   Quick actions
*   Context menu items
*   Command palette entries
*   Guided workflows
*   Interactive forms

## Updates and changes

Servers can notify clients about prompt changes:

1.  Server capability: `prompts.listChanged`
2.  Notification: `notifications/prompts/list_changed`
3.  Client re-fetches prompt list

## Security considerations

When implementing prompts:

*   Validate all arguments
*   Sanitize user input
*   Consider rate limiting
*   Implement access controls
*   Audit prompt usage
*   Handle sensitive data appropriately
*   Validate generated content
*   Implement timeouts
*   Consider prompt injection risks
*   Document security requirements


# Resources

Expose data and content from your servers to LLMs

Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions.

<Note>
  Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used.

  For example, one application may require users to explicitly select resources, while another could automatically select them based on heuristics or even at the discretion of the AI model itself.
</Note>

## Overview

Resources represent any kind of data that an MCP server wants to make available to clients. This can include:

*   File contents
*   Database records
*   API responses
*   Live system data
*   Screenshots and images
*   Log files
*   And more

Each resource is identified by a unique URI and can contain either text or binary data.

## Resource URIs

Resources are identified using URIs that follow this format:

```
[protocol]://[host]/[path]
```

For example:

*   `file:///home/user/documents/report.pdf`
*   `postgres://database/customers/schema`
*   `screen://localhost/display1`

The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.

## Resource types

Resources can contain two types of content:

### Text resources

Text resources contain UTF-8 encoded text data. These are suitable for:

*   Source code
*   Configuration files
*   Log files
*   JSON/XML data
*   Plain text

### Binary resources

Binary resources contain raw binary data encoded in base64. These are suitable for:

*   Images
*   PDFs
*   Audio files
*   Video files
*   Other non-text formats

## Resource discovery

Clients can discover available resources through two main methods:

### Direct resources

Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes:

```typescript
{
  uri: string;           // Unique identifier for the resource
  name: string;          // Human-readable name
  description?: string;  // Optional description
  mimeType?: string;     // Optional MIME type
}
```

### Resource templates

For dynamic resources, servers can expose [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) that clients can use to construct valid resource URIs:

```typescript
{
  uriTemplate: string;   // URI template following RFC 6570
  name: string;          // Human-readable name for this type
  description?: string;  // Optional description
  mimeType?: string;     // Optional MIME type for all matching resources
}
```

## Reading resources

To read a resource, clients make a `resources/read` request with the resource URI.

The server responds with a list of resource contents:

```typescript
{
  contents: [
    {
      uri: string;        // The URI of the resource
      mimeType?: string;  // Optional MIME type

      // One of:
      text?: string;      // For text resources
      blob?: string;      // For binary resources (base64 encoded)
    }
  ]
}
```

<Tip>
  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.
</Tip>

## Resource updates

MCP supports real-time updates for resources through two mechanisms:

### List changes

Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification.

### Content changes

Clients can subscribe to updates for specific resources:

1.  Client sends `resources/subscribe` with resource URI
2.  Server sends `notifications/resources/updated` when the resource changes
3.  Client can fetch latest content with `resources/read`
4.  Client can unsubscribe with `resources/unsubscribe`

## Example implementation

Here's a simple example of implementing resource support in an MCP server:

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    const server = new Server({
      name: "example-server",
      version: "1.0.0"
    }, {
      capabilities: {
        resources: {}
      }
    });

    // List available resources
    server.setRequestHandler(ListResourcesRequestSchema, async () => {
      return {
        resources: [
          {
            uri: "file:///logs/app.log",
            name: "Application Logs",
            mimeType: "text/plain"
          }
        ]
      };
    });

    // Read resource contents
    server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
      const uri = request.params.uri;

      if (uri === "file:///logs/app.log") {
        const logContents = await readLogFile();
        return {
          contents: [
            {
              uri,
              mimeType: "text/plain",
              text: logContents
            }
          ]
        };
      }

      throw new Error("Resource not found");
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python
    app = Server("example-server")

    @app.list_resources()
    async def list_resources() -> list[types.Resource]:
        return [
            types.Resource(
                uri="file:///logs/app.log",
                name="Application Logs",
                mimeType="text/plain"
            )
        ]

    @app.read_resource()
    async def read_resource(uri: AnyUrl) -> str:
        if str(uri) == "file:///logs/app.log":
            log_contents = await read_log_file()
            return log_contents

        raise ValueError("Resource not found")

    # Start server
    async with stdio_server() as streams:
        await app.run(
            streams[0],
            streams[1],
            app.create_initialization_options()
        )
    ```
  </Tab>
</Tabs>

## Best practices

When implementing resource support:

1.  Use clear, descriptive resource names and URIs
2.  Include helpful descriptions to guide LLM understanding
3.  Set appropriate MIME types when known
4.  Implement resource templates for dynamic content
5.  Use subscriptions for frequently changing resources
6.  Handle errors gracefully with clear error messages
7.  Consider pagination for large resource lists
8.  Cache resource contents when appropriate
9.  Validate URIs before processing
10. Document your custom URI schemes

## Security considerations

When exposing resources:

*   Validate all resource URIs
*   Implement appropriate access controls
*   Sanitize file paths to prevent directory traversal
*   Be cautious with binary data handling
*   Consider rate limiting for resource reads
*   Audit resource access
*   Encrypt sensitive data in transit
*   Validate MIME types
*   Implement timeouts for long-running reads
*   Handle resource cleanup appropriately


# Sampling

Let your servers request completions from LLMs

Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy.

<Info>
  This feature of MCP is not yet supported in the Claude Desktop client.
</Info>

## How sampling works

The sampling flow follows these steps:

1.  Server sends a `sampling/createMessage` request to the client
2.  Client reviews the request and can modify it
3.  Client samples from an LLM
4.  Client reviews the completion
5.  Client returns the result to the server

This human-in-the-loop design ensures users maintain control over what the LLM sees and generates.

## Message format

Sampling requests use a standardized message format:

```typescript
{
  messages: [
    {
      role: "user" | "assistant",
      content: {
        type: "text" | "image",

        // For text:
        text?: string,

        // For images:
        data?: string,             // base64 encoded
        mimeType?: string
      }
    }
  ],
  modelPreferences?: {
    hints?: [{
      name?: string                // Suggested model name/family
    }],
    costPriority?: number,         // 0-1, importance of minimizing cost
    speedPriority?: number,        // 0-1, importance of low latency
    intelligencePriority?: number  // 0-1, importance of capabilities
  },
  systemPrompt?: string,
  includeContext?: "none" | "thisServer" | "allServers",
  temperature?: number,
  maxTokens: number,
  stopSequences?: string[],
  metadata?: Record<string, unknown>
}
```

## Request parameters

### Messages

The `messages` array contains the conversation history to send to the LLM. Each message has:

*   `role`: Either "user" or "assistant"
*   `content`: The message content, which can be:
    *   Text content with a `text` field
    *   Image content with `data` (base64) and `mimeType` fields

### Model preferences

The `modelPreferences` object allows servers to specify their model selection preferences:

*   `hints`: Array of model name suggestions that clients can use to select an appropriate model:
    *   `name`: String that can match full or partial model names (e.g. "claude-3", "sonnet")
    *   Clients may map hints to equivalent models from different providers
    *   Multiple hints are evaluated in preference order

*   Priority values (0-1 normalized):
    *   `costPriority`: Importance of minimizing costs
    *   `speedPriority`: Importance of low latency response
    *   `intelligencePriority`: Importance of advanced model capabilities

Clients make the final model selection based on these preferences and their available models.

### System prompt

An optional `systemPrompt` field allows servers to request a specific system prompt. The client may modify or ignore this.

### Context inclusion

The `includeContext` parameter specifies what MCP context to include:

*   `"none"`: No additional context
*   `"thisServer"`: Include context from the requesting server
*   `"allServers"`: Include context from all connected MCP servers

The client controls what context is actually included.

### Sampling parameters

Fine-tune the LLM sampling with:

*   `temperature`: Controls randomness (0.0 to 1.0)
*   `maxTokens`: Maximum tokens to generate
*   `stopSequences`: Array of sequences that stop generation
*   `metadata`: Additional provider-specific parameters

## Response format

The client returns a completion result:

```typescript
{
  model: string,  // Name of the model used
  stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
  role: "user" | "assistant",
  content: {
    type: "text" | "image",
    text?: string,
    data?: string,
    mimeType?: string
  }
}
```

## Example request

Here's an example of requesting sampling from a client:

```json
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "What files are in the current directory?"
        }
      }
    ],
    "systemPrompt": "You are a helpful file system assistant.",
    "includeContext": "thisServer",
    "maxTokens": 100
  }
}
```

## Best practices

When implementing sampling:

1.  Always provide clear, well-structured prompts
2.  Handle both text and image content appropriately
3.  Set reasonable token limits
4.  Include relevant context through `includeContext`
5.  Validate responses before using them
6.  Handle errors gracefully
7.  Consider rate limiting sampling requests
8.  Document expected sampling behavior
9.  Test with various model parameters
10. Monitor sampling costs

## Human in the loop controls

Sampling is designed with human oversight in mind:

### For prompts

*   Clients should show users the proposed prompt
*   Users should be able to modify or reject prompts
*   System prompts can be filtered or modified
*   Context inclusion is controlled by the client

### For completions

*   Clients should show users the completion
*   Users should be able to modify or reject completions
*   Clients can filter or modify completions
*   Users control which model is used

## Security considerations

When implementing sampling:

*   Validate all message content
*   Sanitize sensitive information
*   Implement appropriate rate limits
*   Monitor sampling usage
*   Encrypt data in transit
*   Handle user data privacy
*   Audit sampling requests
*   Control cost exposure
*   Implement timeouts
*   Handle model errors gracefully

## Common patterns

### Agentic workflows

Sampling enables agentic patterns like:

*   Reading and analyzing resources
*   Making decisions based on context
*   Generating structured data
*   Handling multi-step tasks
*   Providing interactive assistance

### Context management

Best practices for context:

*   Request minimal necessary context
*   Structure context clearly
*   Handle context size limits
*   Update context as needed
*   Clean up stale context

### Error handling

Robust error handling should:

*   Catch sampling failures
*   Handle timeout errors
*   Manage rate limits
*   Validate responses
*   Provide fallback behaviors
*   Log errors appropriately

## Limitations

Be aware of these limitations:

*   Sampling depends on client capabilities
*   Users control sampling behavior
*   Context size has limits
*   Rate limits may apply
*   Costs should be considered
*   Model availability varies
*   Response times vary
*   Not all content types supported


# Tools

Enable LLMs to perform actions through your server

Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.

<Note>
  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).
</Note>

## Overview

Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include:

*   **Discovery**: Clients can list available tools through the `tools/list` endpoint
*   **Invocation**: Tools are called using the `tools/call` endpoint, where servers perform the requested operation and return results
*   **Flexibility**: Tools can range from simple calculations to complex API interactions

Like [resources](/docs/concepts/resources), tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems.

## Tool definition structure

Each tool is defined with the following structure:

```typescript
{
  name: string;          // Unique identifier for the tool
  description?: string;  // Human-readable description
  inputSchema: {         // JSON Schema for the tool's parameters
    type: "object",
    properties: { ... }  // Tool-specific parameters
  }
}
```

## Implementing tools

Here's an example of implementing a basic tool in an MCP server:

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    const server = new Server({
      name: "example-server",
      version: "1.0.0"
    }, {
      capabilities: {
        tools: {}
      }
    });

    // Define available tools
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [{
          name: "calculate_sum",
          description: "Add two numbers together",
          inputSchema: {
            type: "object",
            properties: {
              a: { type: "number" },
              b: { type: "number" }
            },
            required: ["a", "b"]
          }
        }]
      };
    });

    // Handle tool execution
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name === "calculate_sum") {
        const { a, b } = request.params.arguments;
        return {
          toolResult: a + b
        };
      }
      throw new Error("Tool not found");
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python
    app = Server("example-server")

    @app.list_tools()
    async def list_tools() -> list[types.Tool]:
        return [
            types.Tool(
                name="calculate_sum",
                description="Add two numbers together",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "a": {"type": "number"},
                        "b": {"type": "number"}
                    },
                    "required": ["a", "b"]
                }
            )
        ]

    @app.call_tool()
    async def call_tool(
        name: str,
        arguments: dict
    ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
        if name == "calculate_sum":
            a = arguments["a"]
            b = arguments["b"]
            result = a + b
            return [types.TextContent(type="text", text=str(result))]
        raise ValueError(f"Tool not found: {name}")
    ```
  </Tab>
</Tabs>

## Example tool patterns

Here are some examples of types of tools that a server could provide:

### System operations

Tools that interact with the local system:

```typescript
{
  name: "execute_command",
  description: "Run a shell command",
  inputSchema: {
    type: "object",
    properties: {
      command: { type: "string" },
      args: { type: "array", items: { type: "string" } }
    }
  }
}
```

### API integrations

Tools that wrap external APIs:

```typescript
{
  name: "github_create_issue",
  description: "Create a GitHub issue",
  inputSchema: {
    type: "object",
    properties: {
      title: { type: "string" },
      body: { type: "string" },
      labels: { type: "array", items: { type: "string" } }
    }
  }
}
```

### Data processing

Tools that transform or analyze data:

```typescript
{
  name: "analyze_csv",
  description: "Analyze a CSV file",
  inputSchema: {
    type: "object",
    properties: {
      filepath: { type: "string" },
      operations: {
        type: "array",
        items: {
          enum: ["sum", "average", "count"]
        }
      }
    }
  }
}
```

## Best practices

When implementing tools:

1.  Provide clear, descriptive names and descriptions
2.  Use detailed JSON Schema definitions for parameters
3.  Include examples in tool descriptions to demonstrate how the model should use them
4.  Implement proper error handling and validation
5.  Use progress reporting for long operations
6.  Keep tool operations focused and atomic
7.  Document expected return value structures
8.  Implement proper timeouts
9.  Consider rate limiting for resource-intensive operations
10. Log tool usage for debugging and monitoring

## Security considerations

When exposing tools:

### Input validation

*   Validate all parameters against the schema
*   Sanitize file paths and system commands
*   Validate URLs and external identifiers
*   Check parameter sizes and ranges
*   Prevent command injection

### Access control

*   Implement authentication where needed
*   Use appropriate authorization checks
*   Audit tool usage
*   Rate limit requests
*   Monitor for abuse

### Error handling

*   Don't expose internal errors to clients
*   Log security-relevant errors
*   Handle timeouts appropriately
*   Clean up resources after errors
*   Validate return values

## Tool discovery and updates

MCP supports dynamic tool discovery:

1.  Clients can list available tools at any time
2.  Servers can notify clients when tools change using `notifications/tools/list_changed`
3.  Tools can be added or removed during runtime
4.  Tool definitions can be updated (though this should be done carefully)

## Error handling

Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error:

1.  Set `isError` to `true` in the result
2.  Include error details in the `content` array

Here's an example of proper error handling for tools:

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    try {
      // Tool operation
      const result = performOperation();
      return {
        content: [
          {
            type: "text",
            text: `Operation successful: ${result}`
          }
        ]
      };
    } catch (error) {
      return {
        isError: true,
        content: [
          {
            type: "text",
            text: `Error: ${error.message}`
          }
        ]
      };
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python
    try:
        # Tool operation
        result = perform_operation()
        return types.CallToolResult(
            content=[
                types.TextContent(
                    type="text",
                    text=f"Operation successful: {result}"
                )
            ]
        )
    except Exception as error:
        return types.CallToolResult(
            isError=True,
            content=[
                types.TextContent(
                    type="text",
                    text=f"Error: {str(error)}"
                )
            ]
        )
    ```
  </Tab>
</Tabs>

This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention.

## Testing tools

A comprehensive testing strategy for MCP tools should cover:

*   **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately
*   **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies
*   **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting
*   **Performance testing**: Check behavior under load, timeout handling, and resource cleanup
*   **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources


# Transports

Learn about MCP's communication mechanisms

Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received.

## Message Format

MCP uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 as its wire format. The transport layer is responsible for converting MCP protocol messages into JSON-RPC format for transmission and converting received JSON-RPC messages back into MCP protocol messages.

There are three types of JSON-RPC messages used:

### Requests

```typescript
{
  jsonrpc: "2.0",
  id: number | string,
  method: string,
  params?: object
}
```

### Responses

```typescript
{
  jsonrpc: "2.0",
  id: number | string,
  result?: object,
  error?: {
    code: number,
    message: string,
    data?: unknown
  }
}
```

### Notifications

```typescript
{
  jsonrpc: "2.0",
  method: string,
  params?: object
}
```

## Built-in Transport Types

MCP includes two standard transport implementations:

### Standard Input/Output (stdio)

The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.

Use stdio when:

*   Building command-line tools
*   Implementing local integrations
*   Needing simple process communication
*   Working with shell scripts

<Tabs>
  <Tab title="TypeScript (Server)">
    ```typescript
    const server = new Server({
      name: "example-server",
      version: "1.0.0"
    }, {
      capabilities: {}
    });

    const transport = new StdioServerTransport();
    await server.connect(transport);
    ```
  </Tab>

  <Tab title="TypeScript (Client)">
    ```typescript
    const client = new Client({
      name: "example-client",
      version: "1.0.0"
    }, {
      capabilities: {}
    });

    const transport = new StdioClientTransport({
      command: "./server",
      args: ["--option", "value"]
    });
    await client.connect(transport);
    ```
  </Tab>

  <Tab title="Python (Server)">
    ```python
    app = Server("example-server")

    async with stdio_server() as streams:
        await app.run(
            streams[0],
            streams[1],
            app.create_initialization_options()
        )
    ```
  </Tab>

  <Tab title="Python (Client)">
    ```python
    params = StdioServerParameters(
        command="./server",
        args=["--option", "value"]
    )

    async with stdio_client(params) as streams:
        async with ClientSession(streams[0], streams[1]) as session:
            await session.initialize()
    ```
  </Tab>
</Tabs>

### Server-Sent Events (SSE)

SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication.

Use SSE when:

*   Only server-to-client streaming is needed
*   Working with restricted networks
*   Implementing simple updates

<Tabs>
  <Tab title="TypeScript (Server)">
    ```typescript
    const server = new Server({
      name: "example-server",
      version: "1.0.0"
    }, {
      capabilities: {}
    });

    const transport = new SSEServerTransport("/message", response);
    await server.connect(transport);
    ```
  </Tab>

  <Tab title="TypeScript (Client)">
    ```typescript
    const client = new Client({
      name: "example-client",
      version: "1.0.0"
    }, {
      capabilities: {}
    });

    const transport = new SSEClientTransport(
      new URL("http://localhost:3000/sse")
    );
    await client.connect(transport);
    ```
  </Tab>

  <Tab title="Python (Server)">
    ```python
    from mcp.server.sse import SseServerTransport
    from starlette.applications import Starlette
    from starlette.routing import Route

    app = Server("example-server")
    sse = SseServerTransport("/messages")

    async def handle_sse(scope, receive, send):
        async with sse.connect_sse(scope, receive, send) as streams:
            await app.run(streams[0], streams[1], app.create_initialization_options())

    async def handle_messages(scope, receive, send):
        await sse.handle_post_message(scope, receive, send)

    starlette_app = Starlette(
        routes=[
            Route("/sse", endpoint=handle_sse),
            Route("/messages", endpoint=handle_messages, methods=["POST"]),
        ]
    )
    ```
  </Tab>

  <Tab title="Python (Client)">
    ```python
    async with sse_client("http://localhost:8000/sse") as streams:
        async with ClientSession(streams[0], streams[1]) as session:
            await session.initialize()
    ```
  </Tab>
</Tabs>

## Custom Transports

MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface:

You can implement custom transports for:

*   Custom network protocols
*   Specialized communication channels
*   Integration with existing systems
*   Performance optimization

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    interface Transport {
      // Start processing messages
      start(): Promise<void>;

      // Send a JSON-RPC message
      send(message: JSONRPCMessage): Promise<void>;

      // Close the connection
      close(): Promise<void>;

      // Callbacks
      onclose?: () => void;
      onerror?: (error: Error) => void;
      onmessage?: (message: JSONRPCMessage) => void;
    }
    ```
  </Tab>

  <Tab title="Python">
    Note that while MCP Servers are often implemented with asyncio, we recommend
    implementing low-level interfaces like transports with `anyio` for wider compatibility.

    ```python
    @contextmanager
    async def create_transport(
        read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
        write_stream: MemoryObjectSendStream[JSONRPCMessage]
    ):
        """
        Transport interface for MCP.

        Args:
            read_stream: Stream to read incoming messages from
            write_stream: Stream to write outgoing messages to
        """
        async with anyio.create_task_group() as tg:
            try:
                # Start processing messages
                tg.start_soon(lambda: process_messages(read_stream))

                # Send messages
                async with write_stream:
                    yield write_stream

            except Exception as exc:
                # Handle errors
                raise exc
            finally:
                # Clean up
                tg.cancel_scope.cancel()
                await write_stream.aclose()
                await read_stream.aclose()
    ```
  </Tab>
</Tabs>

## Error Handling

Transport implementations should handle various error scenarios:

1.  Connection errors
2.  Message parsing errors
3.  Protocol errors
4.  Network timeouts
5.  Resource cleanup

Example error handling:

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    class ExampleTransport implements Transport {
      async start() {
        try {
          // Connection logic
        } catch (error) {
          this.onerror?.(new Error(`Failed to connect: ${error}`));
          throw error;
        }
      }

      async send(message: JSONRPCMessage) {
        try {
          // Sending logic
        } catch (error) {
          this.onerror?.(new Error(`Failed to send message: ${error}`));
          throw error;
        }
      }
    }
    ```
  </Tab>

  <Tab title="Python">
    Note that while MCP Servers are often implemented with asyncio, we recommend
    implementing low-level interfaces like transports with `anyio` for wider compatibility.

    ```python
    @contextmanager
    async def example_transport(scope: Scope, receive: Receive, send: Send):
        try:
            # Create streams for bidirectional communication
            read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
            write_stream, write_stream_reader = anyio.create_memory_object_stream(0)

            async def message_handler():
                try:
                    async with read_stream_writer:
                        # Message handling logic
                        pass
                except Exception as exc:
                    logger.error(f"Failed to handle message: {exc}")
                    raise exc

            async with anyio.create_task_group() as tg:
                tg.start_soon(message_handler)
                try:
                    # Yield streams for communication
                    yield read_stream, write_stream
                except Exception as exc:
                    logger.error(f"Transport error: {exc}")
                    raise exc
                finally:
                    tg.cancel_scope.cancel()
                    await write_stream.aclose()
                    await read_stream.aclose()
        except Exception as exc:
            logger.error(f"Failed to initialize transport: {exc}")
            raise exc
    ```
  </Tab>
</Tabs>

## Best Practices

When implementing or using MCP transport:

1.  Handle connection lifecycle properly
2.  Implement proper error handling
3.  Clean up resources on connection close
4.  Use appropriate timeouts
5.  Validate messages before sending
6.  Log transport events for debugging
7.  Implement reconnection logic when appropriate
8.  Handle backpressure in message queues
9.  Monitor connection health
10. Implement proper security measures

## Security Considerations

When implementing transport:

### Authentication and Authorization

*   Implement proper authentication mechanisms
*   Validate client credentials
*   Use secure token handling
*   Implement authorization checks

### Data Security

*   Use TLS for network transport
*   Encrypt sensitive data
*   Validate message integrity
*   Implement message size limits
*   Sanitize input data

### Network Security

*   Implement rate limiting
*   Use appropriate timeouts
*   Handle denial of service scenarios
*   Monitor for unusual patterns
*   Implement proper firewall rules

## Debugging Transport

Tips for debugging transport issues:

1.  Enable debug logging
2.  Monitor message flow
3.  Check connection states
4.  Validate message formats
5.  Test error scenarios
6.  Use network analysis tools
7.  Implement health checks
8.  Monitor resource usage
9.  Test edge cases
10. Use proper error tracking


# Python

Create a simple MCP server in Python in 15 minutes

Let's build your first MCP server in Python! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools.

<Note>
  This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along.
</Note>

## Prerequisites

<Info>
  The following steps are for macOS. Guides for other platforms are coming soon.
</Info>

<Steps>
  <Step title="Install Python">
    You'll need Python 3.10 or higher:

    ```bash
    python --version  # Should be 3.10 or higher
    ```
  </Step>

  <Step title="Install uv via homebrew">
    See [https://docs.astral.sh/uv/](https://docs.astral.sh/uv/) for more information.

    ```bash
    brew install uv
    uv --version # Should be 0.4.18 or higher
    ```
  </Step>

  <Step title="Create a new project using the MCP project creator">
    ```bash
    uvx create-mcp-server --path weather_service
    cd weather_service
    ```
  </Step>

  <Step title="Install additional dependencies">
    ```bash
    uv add httpx python-dotenv
    ```
  </Step>

  <Step title="Set up environment">
    Create `.env`:

    ```bash
    OPENWEATHER_API_KEY=your-api-key-here
    ```
  </Step>
</Steps>

## Create your server

<Steps>
  <Step title="Add the base imports and setup">
    In `weather_service/src/weather_service/server.py`

    ```python
    import os
    import json
    import logging
    from datetime import datetime, timedelta
    from collections.abc import Sequence
    from functools import lru_cache
    from typing import Any

    import httpx
    import asyncio
    from dotenv import load_dotenv
    from mcp.server import Server
    from mcp.types import (
        Resource,
        Tool,
        TextContent,
        ImageContent,
        EmbeddedResource,
        LoggingLevel
    )
    from pydantic import AnyUrl

    # Load environment variables
    load_dotenv()

    # Configure logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger("weather-server")

    # API configuration
    API_KEY = os.getenv("OPENWEATHER_API_KEY")
    if not API_KEY:
        raise ValueError("OPENWEATHER_API_KEY environment variable required")

    API_BASE_URL = "http://api.openweathermap.org/data/2.5"
    DEFAULT_CITY = "London"
    CURRENT_WEATHER_ENDPOINT = "weather"
    FORECAST_ENDPOINT = "forecast"

    # The rest of our server implementation will go here
    ```
  </Step>

  <Step title="Add weather fetching functionality">
    Add this functionality:

    ```python
    # Create reusable params
    http_params = {
        "appid": API_KEY,
        "units": "metric"
    }

    async def fetch_weather(city: str) -> dict[str, Any]:
        async with httpx.AsyncClient() as client:
            response = await client.get(
                f"{API_BASE_URL}/weather",
                params={"q": city, **http_params}
            )
            response.raise_for_status()
            data = response.json()

        return {
            "temperature": data["main"]["temp"],
            "conditions": data["weather"][0]["description"],
            "humidity": data["main"]["humidity"],
            "wind_speed": data["wind"]["speed"],
            "timestamp": datetime.now().isoformat()
        }


    app = Server("weather-server")
    ```
  </Step>

  <Step title="Implement resource handlers">
    Add these resource-related handlers to our main function:

    ```python
    app = Server("weather-server")

    @app.list_resources()
    async def list_resources() -> list[Resource]:
        """List available weather resources."""
        uri = AnyUrl(f"weather://{DEFAULT_CITY}/current")
        return [
            Resource(
                uri=uri,
                name=f"Current weather in {DEFAULT_CITY}",
                mimeType="application/json",
                description="Real-time weather data"
            )
        ]

    @app.read_resource()
    async def read_resource(uri: AnyUrl) -> str:
        """Read current weather data for a city."""
        city = DEFAULT_CITY
        if str(uri).startswith("weather://") and str(uri).endswith("/current"):
            city = str(uri).split("/")[-2]
        else:
            raise ValueError(f"Unknown resource: {uri}")

        try:
            weather_data = await fetch_weather(city)
            return json.dumps(weather_data, indent=2)
        except httpx.HTTPError as e:
            raise RuntimeError(f"Weather API error: {str(e)}")

    ```
  </Step>

  <Step title="Implement tool handlers">
    Add these tool-related handlers:

    ```python
    app = Server("weather-server")

    # Resource implementation ...

    @app.list_tools()
    async def list_tools() -> list[Tool]:
        """List available weather tools."""
        return [
            Tool(
                name="get_forecast",
                description="Get weather forecast for a city",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "City name"
                        },
                        "days": {
                            "type": "number",
                            "description": "Number of days (1-5)",
                            "minimum": 1,
                            "maximum": 5
                        }
                    },
                    "required": ["city"]
                }
            )
        ]

    @app.call_tool()
    async def call_tool(name: str, arguments: Any) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
        """Handle tool calls for weather forecasts."""
        if name != "get_forecast":
            raise ValueError(f"Unknown tool: {name}")

        if not isinstance(arguments, dict) or "city" not in arguments:
            raise ValueError("Invalid forecast arguments")

        city = arguments["city"]
        days = min(int(arguments.get("days", 3)), 5)

        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(
                    f"{API_BASE_URL}/{FORECAST_ENDPOINT}",
                    params={
                        "q": city,
                        "cnt": days * 8,  # API returns 3-hour intervals
                        **http_params,
                    }
                )
                response.raise_for_status()
                data = response.json()

            forecasts = []
            for i in range(0, len(data["list"]), 8):
                day_data = data["list"][i]
                forecasts.append({
                    "date": day_data["dt_txt"].split()[0],
                    "temperature": day_data["main"]["temp"],
                    "conditions": day_data["weather"][0]["description"]
                })

            return [
                TextContent(
                    type="text",
                    text=json.dumps(forecasts, indent=2)
                )
            ]
        except httpx.HTTPError as e:
            logger.error(f"Weather API error: {str(e)}")
            raise RuntimeError(f"Weather API error: {str(e)}")
    ```
  </Step>

  <Step title="Add the main function">
    Add this to the end of `weather_service/src/weather_service/server.py`:

    ```python
    async def main():
        # Import here to avoid issues with event loops
        from mcp.server.stdio import stdio_server

        async with stdio_server() as (read_stream, write_stream):
            await app.run(
                read_stream,
                write_stream,
                app.create_initialization_options()
            )
    ```
  </Step>

  <Step title="Check your entry point in __init__.py">
    Add this to the end of `weather_service/src/weather_service/__init__.py`:

    ```python
    from . import server
    import asyncio

    def main():
       """Main entry point for the package."""
       asyncio.run(server.main())

    # Optionally expose other important items at package level
    __all__ = ['main', 'server']
    ```
  </Step>
</Steps>

## Connect to Claude Desktop

<Steps>
  <Step title="Update Claude config">
    Add to `claude_desktop_config.json`:

    ```json
    {
      "mcpServers": {
        "weather": {
          "command": "uv",
          "args": [
            "--directory",
            "path/to/your/project",
            "run",
            "weather-service"
          ],
          "env": {
            "OPENWEATHER_API_KEY": "your-api-key"
          }
        }
      }
    }
    ```
  </Step>

  <Step title="Restart Claude">
    1.  Quit Claude completely

    2.  Start Claude again

    3.  Look for your weather server in the 🔌 menu
  </Step>
</Steps>

## Try it out!

<AccordionGroup>
  <Accordion title="Check Current Weather" active>
    Ask Claude:

    ```
    What's the current weather in San Francisco? Can you analyze the conditions and tell me if it's a good day for outdoor activities?
    ```
  </Accordion>

  <Accordion title="Get a Forecast">
    Ask Claude:

    ```
    Can you get me a 5-day forecast for Tokyo and help me plan what clothes to pack for my trip?
    ```
  </Accordion>

  <Accordion title="Compare Weather">
    Ask Claude:

    ```
    Can you analyze the forecast for both Tokyo and San Francisco and tell me which city would be better for outdoor photography this week?
    ```
  </Accordion>
</AccordionGroup>

## Understanding the code

<Tabs>
  <Tab title="Type Hints">
    ```python
    async def read_resource(self, uri: str) -> ReadResourceResult:
        # ...
    ```

    Python type hints help catch errors early and improve code maintainability.
  </Tab>

  <Tab title="Resources">
    ```python
    @app.list_resources()
    async def list_resources(self) -> ListResourcesResult:
        return ListResourcesResult(
            resources=[
                Resource(
                    uri=f"weather://{DEFAULT_CITY}/current",
                    name=f"Current weather in {DEFAULT_CITY}",
                    mimeType="application/json",
                    description="Real-time weather data"
                )
            ]
        )
    ```

    Resources provide data that Claude can access as context.
  </Tab>

  <Tab title="Tools">
    ```python
    Tool(
        name="get_forecast",
        description="Get weather forecast for a city",
        inputSchema={
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name"
                },
                "days": {
                    "type": "number",
                    "description": "Number of days (1-5)",
                    "minimum": 1,
                    "maximum": 5
                }
            },
            "required": ["city"]
        }
    )
    ```

    Tools let Claude take actions through your server with validated inputs.
  </Tab>

  <Tab title="Server Structure">
    ```python
    # Create server instance with name
    app = Server("weather-server")

    # Register resource handler
    @app.list_resources()
    async def list_resources() -> list[Resource]:
        """List available resources"""
        return [...]

    # Register tool handler
    @app.call_tool()
    async def call_tool(name: str, arguments: Any) -> Sequence[TextContent]:
        """Handle tool execution"""
        return [...]

    # Register additional handlers
    @app.read_resource()
    ...
    @app.list_tools()
    ...
    ```

    The MCP server uses a simple app pattern - create a Server instance and register handlers with decorators. Each handler maps to a specific MCP protocol operation.
  </Tab>
</Tabs>

## Best practices

<CardGroup cols={1}>
  <Card title="Error Handling" icon="shield">
    ```python
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(..., params={..., **http_params})
            response.raise_for_status()
    except httpx.HTTPError as e:
        raise McpError(
            ErrorCode.INTERNAL_ERROR,
            f"API error: {str(e)}"
        )
    ```
  </Card>

  <Card title="Type Validation" icon="check">
    ```python
    if not isinstance(args, dict) or "city" not in args:
        raise McpError(
            ErrorCode.INVALID_PARAMS,
            "Invalid forecast arguments"
        )
    ```
  </Card>

  <Card title="Environment Variables" icon="gear">
    ```python
    if not API_KEY:
        raise ValueError("OPENWEATHER_API_KEY is required")
    ```
  </Card>
</CardGroup>

## Available transports

While this guide uses stdio transport, MCP supports additonal transport options:

### SSE (Server-Sent Events)

```python
from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.routing import Route

# Create SSE transport with endpoint
sse = SseServerTransport("/messages")

# Handler for SSE connections
async def handle_sse(scope, receive, send):
    async with sse.connect_sse(scope, receive, send) as streams:
        await app.run(
            streams[0], streams[1], app.create_initialization_options()
        )

# Handler for client messages
async def handle_messages(scope, receive, send):
    await sse.handle_post_message(scope, receive, send)

# Create Starlette app with routes
app = Starlette(
    debug=True,
    routes=[
        Route("/sse", endpoint=handle_sse),
        Route("/messages", endpoint=handle_messages, methods=["POST"]),
    ],
)

# Run with any ASGI server
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
```

## Advanced features

<Steps>
  <Step title="Understanding Request Context">
    The request context provides access to the current request's metadata and the active client session. Access it through `server.request_context`:

    ```python
    @app.call_tool()
    async def call_tool(name: str, arguments: Any) -> Sequence[TextContent]:
        # Access the current request context
        ctx = self.request_context

        # Get request metadata like progress tokens
        if progress_token := ctx.meta.progressToken:
            # Send progress notifications via the session
            await ctx.session.send_progress_notification(
                progress_token=progress_token,
                progress=0.5,
                total=1.0
            )

        # Sample from the LLM client
        result = await ctx.session.create_message(
            messages=[
                SamplingMessage(
                    role="user",
                    content=TextContent(
                        type="text",
                        text="Analyze this weather data: " + json.dumps(arguments)
                    )
                )
            ],
            max_tokens=100
        )

        return [TextContent(type="text", text=result.content.text)]
    ```
  </Step>

  <Step title="Add caching">
    ```python
    # Cache settings
    cache_timeout = timedelta(minutes=15)
    last_cache_time = None
    cached_weather = None

    async def fetch_weather(city: str) -> dict[str, Any]:
        global cached_weather, last_cache_time

        now = datetime.now()
        if (cached_weather is None or
            last_cache_time is None or
            now - last_cache_time > cache_timeout):

            async with httpx.AsyncClient() as client:
                response = await client.get(
                    f"{API_BASE_URL}/{CURRENT_WEATHER_ENDPOINT}",
                    params={"q": city, **http_params}
                )
                response.raise_for_status()
                data = response.json()

            cached_weather = {
                "temperature": data["main"]["temp"],
                "conditions": data["weather"][0]["description"],
                "humidity": data["main"]["humidity"],
                "wind_speed": data["wind"]["speed"],
                "timestamp": datetime.now().isoformat()
            }
            last_cache_time = now

        return cached_weather
    ```
  </Step>

  <Step title="Add progress notifications">
    ```python
    @self.call_tool()
    async def call_tool(self, name: str, arguments: Any) -> CallToolResult:
        if progress_token := self.request_context.meta.progressToken:
            # Send progress notifications
            await self.request_context.session.send_progress_notification(
                progress_token=progress_token,
                progress=1,
                total=2
            )

            # Fetch data...

            await self.request_context.session.send_progress_notification(
                progress_token=progress_token,
                progress=2,
                total=2
            )

        # Rest of the method implementation...
    ```
  </Step>

  <Step title="Add logging support">
    ```python
    # Set up logging
    logger = logging.getLogger("weather-server")
    logger.setLevel(logging.INFO)

    @app.set_logging_level()
    async def set_logging_level(level: LoggingLevel) -> EmptyResult:
        logger.setLevel(level.upper())
        await app.request_context.session.send_log_message(
            level="info",
            data=f"Log level set to {level}",
            logger="weather-server"
        )
        return EmptyResult()

    # Use logger throughout the code
    # For example:
    # logger.info("Weather data fetched successfully")
    # logger.error(f"Error fetching weather data: {str(e)}")
    ```
  </Step>

  <Step title="Add resource templates">
    ```python
    @app.list_resource_templates()
    async def list_resource_templates() -> list[ResourceTemplate]:
        return [
            ResourceTemplate(
                uriTemplate="weather://{city}/current",
                name="Current weather for any city",
                mimeType="application/json"
            )
        ]
    ```
  </Step>
</Steps>

## Testing

<Steps>
  <Step title="Create test file">
    Create `tests/weather_test.py`:

    ```python
    import pytest
    import os
    from unittest.mock import patch, Mock
    from datetime import datetime
    import json
    from pydantic import AnyUrl
    os.environ["OPENWEATHER_API_KEY"] = "TEST"

    from weather_service.server import (
        fetch_weather,
        read_resource,
        call_tool,
        list_resources,
        list_tools,
        DEFAULT_CITY
    )

    @pytest.fixture
    def anyio_backend():
        return "asyncio"

    @pytest.fixture
    def mock_weather_response():
        return {
            "main": {
                "temp": 20.5,
                "humidity": 65
            },
            "weather": [
                {"description": "scattered clouds"}
            ],
            "wind": {
                "speed": 3.6
            }
        }

    @pytest.fixture
    def mock_forecast_response():
        return {
            "list": [
                {
                    "dt_txt": "2024-01-01 12:00:00",
                    "main": {"temp": 18.5},
                    "weather": [{"description": "sunny"}]
                },
                {
                    "dt_txt": "2024-01-02 12:00:00",
                    "main": {"temp": 17.2},
                    "weather": [{"description": "cloudy"}]
                }
            ]
        }

    @pytest.mark.anyio
    async def test_fetch_weather(mock_weather_response):
        with patch('requests.Session.get') as mock_get:
            mock_get.return_value.json.return_value = mock_weather_response
            mock_get.return_value.raise_for_status = Mock()

            weather = await fetch_weather("London")

            assert weather["temperature"] == 20.5
            assert weather["conditions"] == "scattered clouds"
            assert weather["humidity"] == 65
            assert weather["wind_speed"] == 3.6
            assert "timestamp" in weather

    @pytest.mark.anyio
    async def test_read_resource():
        with patch('weather_service.server.fetch_weather') as mock_fetch:
            mock_fetch.return_value = {
                "temperature": 20.5,
                "conditions": "clear sky",
                "timestamp": datetime.now().isoformat()
            }

            uri = AnyUrl("weather://London/current")
            result = await read_resource(uri)

            assert isinstance(result, str)
            assert "temperature" in result
            assert "clear sky" in result

    @pytest.mark.anyio
    async def test_call_tool(mock_forecast_response):
        class Response():
            def raise_for_status(self):
                pass

            def json(self):
                return mock_forecast_response

        class AsyncClient():
            def __aenter__(self):
                return self

            async def __aexit__(self, *exc_info):
                pass

            async def get(self, *args, **kwargs):
                return Response()

        with patch('httpx.AsyncClient', new=AsyncClient) as mock_client:
            result = await call_tool("get_forecast", {"city": "London", "days": 2})

            assert len(result) == 1
            assert result[0].type == "text"
            forecast_data = json.loads(result[0].text)
            assert len(forecast_data) == 1
            assert forecast_data[0]["temperature"] == 18.5
            assert forecast_data[0]["conditions"] == "sunny"

    @pytest.mark.anyio
    async def test_list_resources():
        resources = await list_resources()
        assert len(resources) == 1
        assert resources[0].name == f"Current weather in {DEFAULT_CITY}"
        assert resources[0].mimeType == "application/json"

    @pytest.mark.anyio
    async def test_list_tools():
        tools = await list_tools()
        assert len(tools) == 1
        assert tools[0].name == "get_forecast"
        assert "city" in tools[0].inputSchema["properties"]
    ```
  </Step>

  <Step title="Run tests">
    ```bash
    uv add --dev pytest
    uv run pytest
    ```
  </Step>
</Steps>

## Troubleshooting

### Installation issues

```bash
# Check Python version
python --version

# Reinstall dependencies
uv sync --reinstall
```

### Type checking

```bash
# Install mypy
uv add --dev pyright

# Run type checker
uv run pyright src
```

## Next steps

<CardGroup cols={2}>
  <Card title="Architecture overview" icon="sitemap" href="/docs/concepts/architecture">
    Learn more about the MCP architecture
  </Card>

  <Card title="Python SDK" icon="python" href="https://github.com/modelcontextprotocol/python-sdk">
    Check out the Python SDK on GitHub
  </Card>
</CardGroup>


# TypeScript

Create a simple MCP server in TypeScript in 15 minutes

Let's build your first MCP server in TypeScript! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools.

<Note>
  This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along.
</Note>

## Prerequisites

<Steps>
  <Step title="Install Node.js">
    You'll need Node.js 18 or higher:

    ```bash
    node --version  # Should be v18 or higher
    npm --version
    ```
  </Step>

  <Step title="Create a new project">
    You can use our [create-typescript-server](https://github.com/modelcontextprotocol/create-typescript-server) tool to bootstrap a new project:

    ```bash
    npx @modelcontextprotocol/create-server weather-server
    cd weather-server
    ```
  </Step>

  <Step title="Install dependencies">
    ```bash
    npm install --save axios dotenv
    ```
  </Step>

  <Step title="Set up environment">
    Create `.env`:

    ```bash
    OPENWEATHER_API_KEY=your-api-key-here
    ```

    Make sure to add your environment file to `.gitignore`

    ```bash
    .env
    ```
  </Step>
</Steps>

## Create your server

<Steps>
  <Step title="Define types">
    Create a file `src/types.ts`, and add the following:

    ```typescript
    export interface OpenWeatherResponse {
      main: {
        temp: number;
        humidity: number;
      };
      weather: Array<{
        description: string;
      }>;
      wind: {
        speed: number;
      };
      dt_txt?: string;
    }

    export interface WeatherData {
      temperature: number;
      conditions: string;
      humidity: number;
      wind_speed: number;
      timestamp: string;
    }

    export interface ForecastDay {
      date: string;
      temperature: number;
      conditions: string;
    }

    export interface GetForecastArgs {
      city: string;
      days?: number;
    }

    // Type guard for forecast arguments
    export function isValidForecastArgs(args: any): args is GetForecastArgs {
      return (
        typeof args === "object" && 
        args !== null && 
        "city" in args &&
        typeof args.city === "string" &&
        (args.days === undefined || typeof args.days === "number")
      );
    }
    ```
  </Step>

  <Step title="Add the base code">
    Replace `src/index.ts` with the following:

    ```typescript
    #!/usr/bin/env node
    import { Server } from "@modelcontextprotocol/sdk/server/index.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
    import {
      ListResourcesRequestSchema,
      ReadResourceRequestSchema,
      ListToolsRequestSchema,
      CallToolRequestSchema,
      ErrorCode,
      McpError
    } from "@modelcontextprotocol/sdk/types.js";
    import axios from "axios";
    import dotenv from "dotenv";
    import { 
      WeatherData, 
      ForecastDay, 
      OpenWeatherResponse,
      isValidForecastArgs 
    } from "./types.js";

    dotenv.config();

    const API_KEY = process.env.OPENWEATHER_API_KEY;
    if (!API_KEY) {
      throw new Error("OPENWEATHER_API_KEY environment variable is required");
    }

    const API_CONFIG = {
      BASE_URL: 'http://api.openweathermap.org/data/2.5',
      DEFAULT_CITY: 'San Francisco',
      ENDPOINTS: {
        CURRENT: 'weather',
        FORECAST: 'forecast'
      }
    } as const;

    class WeatherServer {
      private server: Server;
      private axiosInstance;

      constructor() {
        this.server = new Server({
          name: "example-weather-server",
          version: "0.1.0"
        }, {
          capabilities: {
            resources: {},
            tools: {}
          }
        });

        // Configure axios with defaults
        this.axiosInstance = axios.create({
          baseURL: API_CONFIG.BASE_URL,
          params: {
            appid: API_KEY,
            units: "metric"
          }
        });

        this.setupHandlers();
        this.setupErrorHandling();
      }

      private setupErrorHandling(): void {
        this.server.onerror = (error) => {
          console.error("[MCP Error]", error);
        };

        process.on('SIGINT', async () => {
          await this.server.close();
          process.exit(0);
        });
      }

      private setupHandlers(): void {
        this.setupResourceHandlers();
        this.setupToolHandlers();
      }

      private setupResourceHandlers(): void {
        // Implementation continues in next section
      }

      private setupToolHandlers(): void {
        // Implementation continues in next section
      }

      async run(): Promise<void> {
        const transport = new StdioServerTransport();
        await this.server.connect(transport);
        
        // Although this is just an informative message, we must log to stderr,
        // to avoid interfering with MCP communication that happens on stdout
        console.error("Weather MCP server running on stdio");
      }
    }

    const server = new WeatherServer();
    server.run().catch(console.error);
    ```
  </Step>

  <Step title="Add resource handlers">
    Add this to the `setupResourceHandlers` method:

    ```typescript
    private setupResourceHandlers(): void {
      this.server.setRequestHandler(
        ListResourcesRequestSchema,
        async () => ({
          resources: [{
            uri: `weather://${API_CONFIG.DEFAULT_CITY}/current`,
            name: `Current weather in ${API_CONFIG.DEFAULT_CITY}`,
            mimeType: "application/json",
            description: "Real-time weather data including temperature, conditions, humidity, and wind speed"
          }]
        })
      );

      this.server.setRequestHandler(
        ReadResourceRequestSchema,
        async (request) => {
          const city = API_CONFIG.DEFAULT_CITY;
          if (request.params.uri !== `weather://${city}/current`) {
            throw new McpError(
              ErrorCode.InvalidRequest,
              `Unknown resource: ${request.params.uri}`
            );
          }

          try {
            const response = await this.axiosInstance.get<OpenWeatherResponse>(
              API_CONFIG.ENDPOINTS.CURRENT,
              {
                params: { q: city }
              }
            );

            const weatherData: WeatherData = {
              temperature: response.data.main.temp,
              conditions: response.data.weather[0].description,
              humidity: response.data.main.humidity,
              wind_speed: response.data.wind.speed,
              timestamp: new Date().toISOString()
            };

            return {
              contents: [{
                uri: request.params.uri,
                mimeType: "application/json",
                text: JSON.stringify(weatherData, null, 2)
              }]
            };
          } catch (error) {
            if (axios.isAxiosError(error)) {
              throw new McpError(
                ErrorCode.InternalError,
                `Weather API error: ${error.response?.data.message ?? error.message}`
              );
            }
            throw error;
          }
        }
      );
    }
    ```
  </Step>

  <Step title="Add tool handlers">
    Add these handlers to the `setupToolHandlers` method:

    ```typescript
    private setupToolHandlers(): void {
      this.server.setRequestHandler(
        ListToolsRequestSchema,
        async () => ({
          tools: [{
            name: "get_forecast",
            description: "Get weather forecast for a city",
            inputSchema: {
              type: "object",
              properties: {
                city: {
                  type: "string",
                  description: "City name"
                },
                days: {
                  type: "number",
                  description: "Number of days (1-5)",
                  minimum: 1,
                  maximum: 5
                }
              },
              required: ["city"]
            }
          }]
        })
      );

      this.server.setRequestHandler(
        CallToolRequestSchema,
        async (request) => {
          if (request.params.name !== "get_forecast") {
            throw new McpError(
              ErrorCode.MethodNotFound,
              `Unknown tool: ${request.params.name}`
            );
          }

          if (!isValidForecastArgs(request.params.arguments)) {
            throw new McpError(
              ErrorCode.InvalidParams,
              "Invalid forecast arguments"
            );
          }

          const city = request.params.arguments.city;
          const days = Math.min(request.params.arguments.days || 3, 5);

          try {
            const response = await this.axiosInstance.get<{
              list: OpenWeatherResponse[]
            }>(API_CONFIG.ENDPOINTS.FORECAST, {
              params: {
                q: city,
                cnt: days * 8 // API returns 3-hour intervals
              }
            });

            const forecasts: ForecastDay[] = [];
            for (let i = 0; i < response.data.list.length; i += 8) {
              const dayData = response.data.list[i];
              forecasts.push({
                date: dayData.dt_txt?.split(' ')[0] ?? new Date().toISOString().split('T')[0],
                temperature: dayData.main.temp,
                conditions: dayData.weather[0].description
              });
            }

            return {
              content: [{
                type: "text",
                text: JSON.stringify(forecasts, null, 2)
              }]
            };
          } catch (error) {
            if (axios.isAxiosError(error)) {
              return {
                content: [{
                  type: "text",
                  text: `Weather API error: ${error.response?.data.message ?? error.message}`
                }],
                isError: true,
              }
            }
            throw error;
          }
        }
      );
    }
    ```
  </Step>

  <Step title="Build and test">
    ```bash
    npm run build
    ```
  </Step>
</Steps>

## Connect to Claude Desktop

<Steps>
  <Step title="Update Claude config">
    If you didn't already connect to Claude Desktop during project setup, add to `claude_desktop_config.json`:

    ```json
    {
      "mcpServers": {
        "weather": {
          "command": "node",
          "args": ["/path/to/weather-server/build/index.js"],
          "env": {
            "OPENWEATHER_API_KEY": "your-api-key",
          }
        }
      }
    }
    ```
  </Step>

  <Step title="Restart Claude">
    1.  Quit Claude completely
    2.  Start Claude again
    3.  Look for your weather server in the 🔌 menu
  </Step>
</Steps>

## Try it out!

<AccordionGroup>
  <Accordion title="Check Current Weather" active>
    Ask Claude:

    ```
    What's the current weather in San Francisco? Can you analyze the conditions?
    ```
  </Accordion>

  <Accordion title="Get a Forecast">
    Ask Claude:

    ```
    Can you get me a 5-day forecast for Tokyo and tell me if I should pack an umbrella?
    ```
  </Accordion>

  <Accordion title="Compare Weather">
    Ask Claude:

    ```
    Can you analyze the forecast for both Tokyo and San Francisco and tell me which city will be warmer this week?
    ```
  </Accordion>
</AccordionGroup>

## Understanding the code

<Tabs>
  <Tab title="Type Safety">
    ```typescript
    interface WeatherData {
      temperature: number;
      conditions: string;
      humidity: number;
      wind_speed: number;
      timestamp: string;
    }
    ```

    TypeScript adds type safety to our MCP server, making it more reliable and easier to maintain.
  </Tab>

  <Tab title="Resources">
    ```typescript
    this.server.setRequestHandler(
      ListResourcesRequestSchema,
      async () => ({
        resources: [{
          uri: `weather://${DEFAULT_CITY}/current`,
          name: `Current weather in ${DEFAULT_CITY}`,
          mimeType: "application/json"
        }]
      })
    );
    ```

    Resources provide data that Claude can access as context.
  </Tab>

  <Tab title="Tools">
    ```typescript
    {
      name: "get_forecast",
      description: "Get weather forecast for a city",
      inputSchema: {
        type: "object",
        properties: {
          city: { type: "string" },
          days: { type: "number" }
        }
      }
    }
    ```

    Tools let Claude take actions through your server with type-safe inputs.
  </Tab>
</Tabs>

## Best practices

<CardGroup cols={1}>
  <Card title="Error Handling" icon="shield">
    When a tool encounters an error, return the error message with `isError: true`, so the model can self-correct:

    ```typescript
    try {
      const response = await axiosInstance.get(...);
    } catch (error) {
      if (axios.isAxiosError(error)) {
        return {
          content: {
            mimeType: "text/plain",
            text: `Weather API error: ${error.response?.data.message ?? error.message}`
          },
          isError: true,
        }
      }
      throw error;
    }
    ```

    For other handlers, throw an error, so the application can notify the user:

    ```typescript
    try {
      const response = await this.axiosInstance.get(...);
    } catch (error) {
      if (axios.isAxiosError(error)) {
        throw new McpError(
          ErrorCode.InternalError,
          `Weather API error: ${error.response?.data.message}`
        );
      }
      throw error;
    }
    ```
  </Card>

  <Card title="Type Validation" icon="check">
    ```typescript
    function isValidForecastArgs(args: any): args is GetForecastArgs {
      return (
        typeof args === "object" && 
        args !== null && 
        "city" in args &&
        typeof args.city === "string"
      );
    }
    ```

    <Tip>You can also use libraries like [Zod](https://zod.dev/) to perform this validation automatically.</Tip>
  </Card>
</CardGroup>

## Available transports

While this guide uses stdio to run the MCP server as a local process, MCP supports other [transports](/docs/concepts/transports) as well.

## Troubleshooting

<Info>
  The following troubleshooting tips are for macOS. Guides for other platforms are coming soon.
</Info>

### Build errors

```bash
# Check TypeScript version
npx tsc --version

# Clean and rebuild
rm -rf build/
npm run build
```

### Runtime errors

Look for detailed error messages in the Claude Desktop logs:

```bash
# Monitor logs
tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
```

### Type errors

```bash
# Check types without building
npx tsc --noEmit
```

## Next steps

<CardGroup cols={2}>
  <Card title="Architecture overview" icon="sitemap" href="/docs/concepts/architecture">
    Learn more about the MCP architecture
  </Card>

  <Card title="TypeScript SDK" icon="square-js" href="https://github.com/modelcontextprotocol/typescript-sdk">
    Check out the TypeScript SDK on GitHub
  </Card>
</CardGroup>

<Note>
  Need help? Ask Claude! Since it has access to the MCP SDK documentation, it can help you debug issues and suggest improvements to your server.
</Note>


# Debugging

A comprehensive guide to debugging Model Context Protocol (MCP) integrations

Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem.

<Info>
  This guide is for macOS. Guides for other platforms are coming soon.
</Info>

## Debugging tools overview

MCP provides several tools for debugging at different levels:

1.  **MCP Inspector**
    *   Interactive debugging interface
    *   Direct server testing
    *   See the [Inspector guide](/docs/tools/inspector) for details

2.  **Claude Desktop Developer Tools**
    *   Integration testing
    *   Log collection
    *   Chrome DevTools integration

3.  **Server Logging**
    *   Custom logging implementations
    *   Error tracking
    *   Performance monitoring

## Debugging in Claude Desktop

### Checking server status

The Claude.app interface provides basic server status information:

1.  Click the 🔌 icon to view:
    *   Connected servers
    *   Available prompts and resources

2.  Click the 🔨 icon to view:
    *   Tools made available to the model

### Viewing logs

Review detailed MCP logs from Claude Desktop:

```bash
# Follow logs in real-time
tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
```

The logs capture:

*   Server connection events
*   Configuration issues
*   Runtime errors
*   Message exchanges

### Using Chrome DevTools

Access Chrome's developer tools inside Claude Desktop to investigate client-side errors:

1.  Enable DevTools:

```bash
jq '.allowDevTools = true' ~/Library/Application\ Support/Claude/developer_settings.json > tmp.json \
  && mv tmp.json ~/Library/Application\ Support/Claude/developer_settings.json
```

2.  Open DevTools: `Command-Option-Shift-i`

Note: You'll see two DevTools windows:

*   Main content window
*   App title bar window

Use the Console panel to inspect client-side errors.

Use the Network panel to inspect:

*   Message payloads
*   Connection timing

## Common issues

### Environment variables

MCP servers inherit only a subset of environment variables automatically, like `USER`, `HOME`, and `PATH`.

To override the default variables or provide your own, you can specify an `env` key in `claude_desktop_config.json`:

```json
{
  "myserver": {
    "command": "mcp-server-myapp",
    "env": {
      "MYAPP_API_KEY": "some_key",
    }
  }
}
```

### Server initialization

Common initialization problems:

1.  **Path Issues**
    *   Incorrect server executable path
    *   Missing required files
    *   Permission problems

2.  **Configuration Errors**
    *   Invalid JSON syntax
    *   Missing required fields
    *   Type mismatches

3.  **Environment Problems**
    *   Missing environment variables
    *   Incorrect variable values
    *   Permission restrictions

### Connection problems

When servers fail to connect:

1.  Check Claude Desktop logs
2.  Verify server process is running
3.  Test standalone with [Inspector](/docs/tools/inspector)
4.  Verify protocol compatibility

## Implementing logging

### Server-side logging

When building a server that uses the local stdio [transport](/docs/concepts/transports), all messages logged to stderr (standard error) will be captured by the host application (e.g., Claude Desktop) automatically.

<Warning>
  Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation.
</Warning>

For all [transports](/docs/concepts/transports), you can also provide logging to the client by sending a log message notification:

<Tabs>
  <Tab title="Python">
    ```python
    server.request_context.session.send_log_message(
      level="info",
      data="Server started successfully",
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript
    server.sendLoggingMessage({
      level: "info",
      data: "Server started successfully",
    });
    ```
  </Tab>
</Tabs>

Important events to log:

*   Initialization steps
*   Resource access
*   Tool execution
*   Error conditions
*   Performance metrics

### Client-side logging

In client applications:

1.  Enable debug logging
2.  Monitor network traffic
3.  Track message exchanges
4.  Record error states

## Debugging workflow

### Development cycle

1.  Initial Development
    *   Use [Inspector](/docs/tools/inspector) for basic testing
    *   Implement core functionality
    *   Add logging points

2.  Integration Testing
    *   Test in Claude Desktop
    *   Monitor logs
    *   Check error handling

### Testing changes

To test changes efficiently:

*   **Configuration changes**: Restart Claude Desktop
*   **Server code changes**: Use Command-R to reload
*   **Quick iteration**: Use [Inspector](/docs/tools/inspector) during development

## Best practices

### Logging strategy

1.  **Structured Logging**
    *   Use consistent formats
    *   Include context
    *   Add timestamps
    *   Track request IDs

2.  **Error Handling**
    *   Log stack traces
    *   Include error context
    *   Track error patterns
    *   Monitor recovery

3.  **Performance Tracking**
    *   Log operation timing
    *   Monitor resource usage
    *   Track message sizes
    *   Measure latency

### Security considerations

When debugging:

1.  **Sensitive Data**
    *   Sanitize logs
    *   Protect credentials
    *   Mask personal information

2.  **Access Control**
    *   Verify permissions
    *   Check authentication
    *   Monitor access patterns

## Getting help

When encountering issues:

1.  **First Steps**
    *   Check server logs
    *   Test with [Inspector](/docs/tools/inspector)
    *   Review configuration
    *   Verify environment

2.  **Support Channels**
    *   GitHub issues
    *   GitHub discussions

3.  **Providing Information**
    *   Log excerpts
    *   Configuration files
    *   Steps to reproduce
    *   Environment details

## Next steps

<CardGroup cols={2}>
  <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
    Learn to use the MCP Inspector
  </Card>
</CardGroup>


# Inspector

In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers

The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is an interactive developer tool for testing and debugging MCP servers. While the [Debugging Guide](/docs/tools/debugging) covers the Inspector as part of the overall debugging toolkit, this document provides a detailed exploration of the Inspector's features and capabilities.

## Getting started

### Installation and basic usage

The Inspector runs directly through `npx` without requiring installation:

```bash
npx @modelcontextprotocol/inspector <command>
```

```bash
npx @modelcontextprotocol/inspector <command> <arg1> <arg2>
```

#### Inspecting servers from NPM or PyPi

A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com).

<Tabs>
  <Tab title="NPM package">
    ```bash
    npx -y @modelcontextprotocol/inspector npx <package-name> <args>
    # For example
    npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb
    ```
  </Tab>

  <Tab title="PyPi package">
    ```bash
    npx @modelcontextprotocol/inspector uvx <package-name> <args>
    # For example
    npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
    ```
  </Tab>
</Tabs>

#### Inspecting locally developed servers

To inspect servers locally developed or downloaded as a repository, the most common
way is:

<Tabs>
  <Tab title="TypeScript">
    ```bash
    npx @modelcontextprotocol/inspector node path/to/server/index.js args...
    ```
  </Tab>

  <Tab title="Python">
    ```bash
    npx @modelcontextprotocol/inspector \
      uv \
      --directory path/to/server \
      run \
      package-name \
      args...
    ```
  </Tab>
</Tabs>

Please carefully read any attached README for the most accurate instructions.

## Feature overview

<Frame caption="The MCP Inspector interface">
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/mcp-inspector.png" />
</Frame>

The Inspector provides several features for interacting with your MCP server:

### Server connection pane

*   Allows selecting the [transport](/docs/concepts/transports) for connecting to the server
*   For local servers, supports customizing the command-line arguments and environment

### Resources tab

*   Lists all available resources
*   Shows resource metadata (MIME types, descriptions)
*   Allows resource content inspection
*   Supports subscription testing

### Prompts tab

*   Displays available prompt templates
*   Shows prompt arguments and descriptions
*   Enables prompt testing with custom arguments
*   Previews generated messages

### Tools tab

*   Lists available tools
*   Shows tool schemas and descriptions
*   Enables tool testing with custom inputs
*   Displays tool execution results

### Notifications pane

*   Presents all logs recorded from the server
*   Shows notifications received from the server

## Best practices

### Development workflow

1.  Start Development
    *   Launch Inspector with your server
    *   Verify basic connectivity
    *   Check capability negotiation

2.  Iterative testing
    *   Make server changes
    *   Rebuild the server
    *   Reconnect the Inspector
    *   Test affected features
    *   Monitor messages

3.  Test edge cases
    *   Invalid inputs
    *   Missing prompt arguments
    *   Concurrent operations
    *   Verify error handling and error responses

## Next steps

<CardGroup cols={2}>
  <Card title="Inspector Repository" icon="github" href="https://github.com/modelcontextprotocol/inspector">
    Check out the MCP Inspector source code
  </Card>

  <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
    Learn about broader debugging strategies
  </Card>
</CardGroup>


# Introduction

Get started with the Model Context Protocol (MCP)

The Model Context Protocol (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need.

## Get started with MCP

Choose the path that best fits your needs:

<CardGroup cols={1}>
  <Card title="Quickstart" icon="bolt" href="/quickstart">
    The fastest way to see MCP in action—connect example servers to Claude Desktop
  </Card>

  <Card title="Build your first server (Python)" icon="python" href="/docs/first-server/python">
    Create a simple MCP server in Python to understand the basics
  </Card>

  <Card title="Build your first server (TypeScript)" icon="square-js" href="/docs/first-server/typescript">
    Create a simple MCP server in TypeScript to understand the basics
  </Card>
</CardGroup>

## Development tools

Essential tools for building and debugging MCP servers:

<CardGroup cols={2}>
  <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
    Learn how to effectively debug MCP servers and integrations
  </Card>

  <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
    Test and inspect your MCP servers with our interactive debugging tool
  </Card>
</CardGroup>

## Explore MCP

Dive deeper into MCP's core concepts and capabilities:

<CardGroup cols={2}>
  <Card title="Core Architecture" icon="sitemap" href="/docs/concepts/architecture">
    Understand how MCP connects clients, servers, and LLMs
  </Card>

  <Card title="Resources" icon="database" href="/docs/concepts/resources">
    Expose data and content from your servers to LLMs
  </Card>

  <Card title="Prompts" icon="message" href="/docs/concepts/prompts">
    Create reusable prompt templates and workflows
  </Card>

  <Card title="Tools" icon="wrench" href="/docs/concepts/tools">
    Enable LLMs to perform actions through your server
  </Card>

  <Card title="Sampling" icon="robot" href="/docs/concepts/sampling">
    Let your servers request completions from LLMs
  </Card>

  <Card title="Transports" icon="network-wired" href="/docs/concepts/transports">
    Learn about MCP's communication mechanism
  </Card>
</CardGroup>

## Contributing

Want to contribute? Check out [@modelcontextprotocol](https://github.com/modelcontextprotocol) on GitHub to join our growing community of developers building with MCP.


# Quickstart

Get started with MCP in less than 5 minutes

MCP is a protocol that enables secure connections between host applications, such as [Claude Desktop](https://claude.ai/download), and local services. In this quickstart guide, you'll learn how to:

*   Set up a local SQLite database
*   Connect Claude Desktop to it through MCP
*   Query and analyze your data securely

<Note>
  While this guide focuses on using Claude Desktop as an example MCP host, the protocol is open and can be integrated by any application. IDEs, AI tools, and other software can all use MCP to connect to local integrations in a standardized way.
</Note>

<Warning>
  Claude Desktop's MCP support is currently in developer preview and only supports connecting to local MCP servers running on your machine. Remote MCP connections are not yet supported. This integration is only available in the Claude Desktop app, not the Claude web interface (claude.ai).
</Warning>

## How MCP works

MCP (Model Context Protocol) is an open protocol that enables secure, controlled interactions between AI applications and local or remote resources. Let's break down how it works, then look at how we'll use it in this guide.

### General Architecture

At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:

```mermaid
flowchart LR
    subgraph "Your Computer"
        Host["MCP Host\n(Claude, IDEs, Tools)"]
        S1["MCP Server A"]
        S2["MCP Server B"]
        S3["MCP Server C"]

        Host <-->|"MCP Protocol"| S1
        Host <-->|"MCP Protocol"| S2
        Host <-->|"MCP Protocol"| S3

        S1 <--> R1[("Local\nResource A")]
        S2 <--> R2[("Local\nResource B")]
    end

    subgraph "Internet"
        S3 <-->|"Web APIs"| R3[("Remote\nResource C")]
    end
```

*   **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access resources through MCP
*   **MCP Clients**: Protocol clients that maintain 1:1 connections with servers
*   **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
*   **Local Resources**: Your computer's resources (databases, files, services) that MCP servers can securely access
*   **Remote Resources**: Resources available over the internet (e.g., through APIs) that MCP servers can connect to

### In This Guide

For this quickstart, we'll implement a focused example using SQLite:

```mermaid
flowchart LR
    subgraph "Your Computer"
        direction LR
        Claude["Claude Desktop"]
        MCP["SQLite MCP Server"]
        DB[(SQLite Database\n~/test.db)]

        Claude <-->|"MCP Protocol\n(Queries & Results)"| MCP
        MCP <-->|"Local Access\n(SQL Operations)"| DB
    end
```

1.  Claude Desktop acts as our MCP client
2.  A SQLite MCP Server provides secure database access
3.  Your local SQLite database stores the actual data

The communication between the SQLite MCP server and your local SQLite database happens entirely on your machine—your SQLite database is not exposed to the internet. The Model Context Protocol ensures that Claude Desktop can only perform approved database operations through well-defined interfaces. This gives you a secure way to let Claude analyze and interact with your local data while maintaining complete control over what it can access.

## Prerequisites

*   macOS or Windows
*   The latest version of [Claude Desktop](https://claude.ai/download) installed
*   [uv](https://docs.astral.sh/uv/) 0.4.18 or higher (`uv --version` to check)
*   Git (`git --version` to check)
*   SQLite (`sqlite3 --version` to check)

<AccordionGroup>
  <Accordion title="Installing prerequisites (macOS)">
    ```bash
    # Using Homebrew
    brew install uv git sqlite3

    # Or download directly:
    # uv: https://docs.astral.sh/uv/
    # Git: https://git-scm.com
    # SQLite: https://www.sqlite.org/download.html
    ```
  </Accordion>

  <Accordion title="Installing prerequisites (Windows)">
    ```powershell
    # Using winget
    winget install --id=astral-sh.uv -e
    winget install git.git sqlite.sqlite

    # Or download directly:
    # uv: https://docs.astral.sh/uv/
    # Git: https://git-scm.com
    # SQLite: https://www.sqlite.org/download.html
    ```
  </Accordion>
</AccordionGroup>

## Installation

<Tabs>
  <Tab title="macOS">
    <Steps>
      <Step title="Create a sample database">
        Let's create a simple SQLite database for testing:

        ```bash
        # Create a new SQLite database
        sqlite3 ~/test.db <<EOF
        CREATE TABLE products (
          id INTEGER PRIMARY KEY,
          name TEXT,
          price REAL
        );

        INSERT INTO products (name, price) VALUES
          ('Widget', 19.99),
          ('Gadget', 29.99),
          ('Gizmo', 39.99),
          ('Smart Watch', 199.99),
          ('Wireless Earbuds', 89.99),
          ('Portable Charger', 24.99),
          ('Bluetooth Speaker', 79.99),
          ('Phone Stand', 15.99),
          ('Laptop Sleeve', 34.99),
          ('Mini Drone', 299.99),
          ('LED Desk Lamp', 45.99),
          ('Keyboard', 129.99),
          ('Mouse Pad', 12.99),
          ('USB Hub', 49.99),
          ('Webcam', 69.99),
          ('Screen Protector', 9.99),
          ('Travel Adapter', 27.99),
          ('Gaming Headset', 159.99),
          ('Fitness Tracker', 119.99),
          ('Portable SSD', 179.99);
        EOF
        ```
      </Step>

      <Step title="Configure Claude Desktop">
        Open your Claude Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.

        For example, if you have [VS Code](https://code.visualstudio.com/) installed:

        ```bash
        code ~/Library/Application\ Support/Claude/claude_desktop_config.json
        ```

        Add this configuration (replace YOUR\_USERNAME with your actual username):

        ```json
        {
          "mcpServers": {
            "sqlite": {
              "command": "uvx",
              "args": ["mcp-server-sqlite", "--db-path", "/Users/YOUR_USERNAME/test.db"]
            }
          }
        }
        ```

        This tells Claude Desktop:

        1.  There's an MCP server named "sqlite"
        2.  Launch it by running `uvx mcp-server-sqlite`
        3.  Connect it to your test database

        Save the file, and restart **Claude Desktop**.
      </Step>
    </Steps>
  </Tab>

  <Tab title="Windows">
    <Steps>
      <Step title="Create a sample database">
        Let's create a simple SQLite database for testing:

        ```powershell
        # Create a new SQLite database
        $sql = @'
        CREATE TABLE products (
          id INTEGER PRIMARY KEY,
          name TEXT,
          price REAL
        );

        INSERT INTO products (name, price) VALUES
          ('Widget', 19.99),
          ('Gadget', 29.99),
          ('Gizmo', 39.99),
          ('Smart Watch', 199.99),
          ('Wireless Earbuds', 89.99),
          ('Portable Charger', 24.99),
          ('Bluetooth Speaker', 79.99),
          ('Phone Stand', 15.99),
          ('Laptop Sleeve', 34.99),
          ('Mini Drone', 299.99),
          ('LED Desk Lamp', 45.99),
          ('Keyboard', 129.99),
          ('Mouse Pad', 12.99),
          ('USB Hub', 49.99),
          ('Webcam', 69.99),
          ('Screen Protector', 9.99),
          ('Travel Adapter', 27.99),
          ('Gaming Headset', 159.99),
          ('Fitness Tracker', 119.99),
          ('Portable SSD', 179.99);
        '@

        cd ~
        & sqlite3 test.db $sql
        ```
      </Step>

      <Step title="Configure Claude Desktop">
        Open your Claude Desktop App configuration at `%APPDATA%\Claude\claude_desktop_config.json` in a text editor.

        For example, if you have [VS Code](https://code.visualstudio.com/) installed:

        ```powershell
        code $env:AppData\Claude\claude_desktop_config.json
        ```

        Add this configuration (replace YOUR\_USERNAME with your actual username):

        ```json
        {
          "mcpServers": {
            "sqlite": {
              "command": "uvx",
              "args": [
                "mcp-server-sqlite",
                "--db-path",
                "C:\\Users\\YOUR_USERNAME\\test.db"
              ]
            }
          }
        }
        ```

        This tells Claude Desktop:

        1.  There's an MCP server named "sqlite"
        2.  Launch it by running `uvx mcp-server-sqlite`
        3.  Connect it to your test database

        Save the file, and restart **Claude Desktop**.
      </Step>
    </Steps>
  </Tab>
</Tabs>

## Test it out

Let's verify everything is working. Try sending this prompt to Claude Desktop:

```
Can you connect to my SQLite database and tell me what products are available, and their prices?
```

Claude Desktop will:

1.  Connect to the SQLite MCP server
2.  Query your local database
3.  Format and present the results

<Frame caption="Claude Desktop successfully queries our SQLite database 🎉">
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-screenshot.png" alt="Example Claude Desktop conversation showing database query results" />
</Frame>

## What's happening under the hood?

When you interact with Claude Desktop using MCP:

1.  **Server Discovery**: Claude Desktop connects to your configured MCP servers on startup

2.  **Protocol Handshake**: When you ask about data, Claude Desktop:
    *   Identifies which MCP server can help (sqlite in this case)
    *   Negotiates capabilities through the protocol
    *   Requests data or actions from the MCP server

3.  **Interaction Flow**:
    ```mermaid
    sequenceDiagram
        participant C as Claude Desktop
        participant M as MCP Server
        participant D as SQLite DB

        C->>M: Initialize connection
        M-->>C: Available capabilities

        C->>M: Query request
        M->>D: SQL query
        D-->>M: Results
        M-->>C: Formatted results
    ```

4.  **Security**:
    *   MCP servers only expose specific, controlled capabilities
    *   MCP servers run locally on your machine, and the resources they access are not exposed to the internet
    *   Claude Desktop requires user confirmation for sensitive operations

## Try these examples

Now that MCP is working, try these increasingly powerful examples:

<AccordionGroup>
  <Accordion title="Basic Queries" active>
    ```
    What's the average price of all products in the database?
    ```
  </Accordion>

  <Accordion title="Data Analysis">
    ```
    Can you analyze the price distribution and suggest any pricing optimizations?
    ```
  </Accordion>

  <Accordion title="Complex Operations">
    ```
    Could you help me design and create a new table for storing customer orders?
    ```
  </Accordion>
</AccordionGroup>

## Add more capabilities

Want to give Claude Desktop more local integration capabilities? Add these servers to your configuration:

<Note>
  Note that these MCP servers will require [Node.js](https://nodejs.org/en) to be installed on your machine.
</Note>

<AccordionGroup>
  <Accordion title="File System Access" icon="folder-open">
    Add this to your config to let Claude Desktop read and analyze files:

    ```json
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/YOUR_USERNAME/Desktop"]
    }
    ```
  </Accordion>

  <Accordion title="PostgreSQL Connection" icon="database">
    Connect Claude Desktop to your PostgreSQL database:

    ```json
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
    }
    ```
  </Accordion>
</AccordionGroup>

## More MCP Clients

While this guide demonstrates MCP using Claude Desktop as a client, several other applications support MCP integration:

<CardGroup cols={2}>
  <Card title="Zed Editor" icon="pen-to-square" href="https://zed.dev">
    A high-performance, multiplayer code editor with built-in MCP support for AI-powered coding assistance
  </Card>

  <Card title="Cody" icon="magnifying-glass" href="https://sourcegraph.com/cody">
    Code intelligence platform featuring MCP integration for enhanced code search and analysis capabilities
  </Card>
</CardGroup>

Each host application may implement MCP features differently or support different capabilities. Check their respective documentation for specific setup instructions and supported features.

## Troubleshooting

<AccordionGroup>
  <Accordion title="Nothing showing up in Claude Desktop?">
    1.  Check if MCP is enabled:
        *   Click the 🔌 icon in Claude Desktop, next to the chat box
        *   Expand "Installed MCP Servers"
        *   You should see your configured servers

    2.  Verify your config:
        *   From Claude Desktop, go to Claude > Settings…
        *   Open the "Developer" tab to see your configuration

    3.  Restart Claude Desktop completely:
        *   Quit the app (not just close the window)
        *   Start it again
  </Accordion>

  <Accordion title="MCP or database errors?">
    1.  Check Claude Desktop's logs:
        ```bash
        tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
        ```

    2.  Verify database access:
        ```bash
        # Test database connection
        sqlite3 ~/test.db ".tables"
        ```

    3.  Common fixes:
        *   Check file paths in your config
        *   Verify database file permissions
        *   Ensure SQLite is installed properly
  </Accordion>
</AccordionGroup>

## Next steps

<CardGroup cols={2}>
  <Card title="Build your first MCP server" icon="code" href="/docs/first-server/python">
    Create your own MCP servers to give your LLM clients new capabilities.
  </Card>

  <Card title="Explore examples" icon="github" href="https://github.com/modelcontextprotocol/servers">
    Browse our collection of example servers to see what's possible.
  </Card>
</CardGroup>


```