# Directory Structure ``` ├── .gitignore ├── AI-learn-resource │ ├── MCP-About.txt │ └── README.md ├── Dockerfile ├── README.md ├── requirements.txt ├── test_mcp.py └── xiaohongshu_mcp.py ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` .DS_Store ``` -------------------------------------------------------------------------------- /AI-learn-resource/README.md: -------------------------------------------------------------------------------- ```markdown # MCP Python SDK <div align="center"> <strong>Python implementation of the Model Context Protocol (MCP)</strong> [![PyPI][pypi-badge]][pypi-url] [![MIT licensed][mit-badge]][mit-url] [![Python Version][python-badge]][python-url] [![Documentation][docs-badge]][docs-url] [![Specification][spec-badge]][spec-url] [![GitHub Discussions][discussions-badge]][discussions-url] </div> <!-- omit in toc --> ## Table of Contents - [MCP Python SDK](#mcp-python-sdk) - [Overview](#overview) - [Installation](#installation) - [Adding MCP to your python project](#adding-mcp-to-your-python-project) - [Running the standalone MCP development tools](#running-the-standalone-mcp-development-tools) - [Quickstart](#quickstart) - [What is MCP?](#what-is-mcp) - [Core Concepts](#core-concepts) - [Server](#server) - [Resources](#resources) - [Tools](#tools) - [Prompts](#prompts) - [Images](#images) - [Context](#context) - [Running Your Server](#running-your-server) - [Development Mode](#development-mode) - [Claude Desktop Integration](#claude-desktop-integration) - [Direct Execution](#direct-execution) - [Mounting to an Existing ASGI Server](#mounting-to-an-existing-asgi-server) - [Examples](#examples) - [Echo Server](#echo-server) - [SQLite Explorer](#sqlite-explorer) - [Advanced Usage](#advanced-usage) - [Low-Level Server](#low-level-server) - [Writing MCP Clients](#writing-mcp-clients) - [MCP Primitives](#mcp-primitives) - [Server Capabilities](#server-capabilities) - [Documentation](#documentation) - [Contributing](#contributing) - [License](#license) [pypi-badge]: https://img.shields.io/pypi/v/mcp.svg [pypi-url]: https://pypi.org/project/mcp/ [mit-badge]: https://img.shields.io/pypi/l/mcp.svg [mit-url]: https://github.com/modelcontextprotocol/python-sdk/blob/main/LICENSE [python-badge]: https://img.shields.io/pypi/pyversions/mcp.svg [python-url]: https://www.python.org/downloads/ [docs-badge]: https://img.shields.io/badge/docs-modelcontextprotocol.io-blue.svg [docs-url]: https://modelcontextprotocol.io [spec-badge]: https://img.shields.io/badge/spec-spec.modelcontextprotocol.io-blue.svg [spec-url]: https://spec.modelcontextprotocol.io [discussions-badge]: https://img.shields.io/github/discussions/modelcontextprotocol/python-sdk [discussions-url]: https://github.com/modelcontextprotocol/python-sdk/discussions ## Overview The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This Python SDK implements the full MCP specification, making it easy to: - Build MCP clients that can connect to any MCP server - Create MCP servers that expose resources, prompts and tools - Use standard transports like stdio and SSE - Handle all MCP protocol messages and lifecycle events ## Installation ### Adding MCP to your python project We recommend using [uv](https://docs.astral.sh/uv/) to manage your Python projects. If you haven't created a uv-managed project yet, create one: ```bash uv init mcp-server-demo cd mcp-server-demo ``` Then add MCP to your project dependencies: ```bash uv add "mcp[cli]" ``` Alternatively, for projects using pip for dependencies: ```bash pip install "mcp[cli]" ``` ### Running the standalone MCP development tools To run the mcp command with uv: ```bash uv run mcp ``` ## Quickstart Let's create a simple MCP server that exposes a calculator tool and some data: ```python # server.py from mcp.server.fastmcp import FastMCP # Create an MCP server mcp = FastMCP("Demo") # Add an addition tool @mcp.tool() def add(a: int, b: int) -> int: """Add two numbers""" return a + b # Add a dynamic greeting resource @mcp.resource("greeting://{name}") def get_greeting(name: str) -> str: """Get a personalized greeting""" return f"Hello, {name}!" ``` You can install this server in [Claude Desktop](https://claude.ai/download) and interact with it right away by running: ```bash mcp install server.py ``` Alternatively, you can test it with the MCP Inspector: ```bash mcp dev server.py ``` ## What is MCP? The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can: - Expose data through **Resources** (think of these sort of like GET endpoints; they are used to load information into the LLM's context) - Provide functionality through **Tools** (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect) - Define interaction patterns through **Prompts** (reusable templates for LLM interactions) - And more! ## Core Concepts ### Server The FastMCP server is your core interface to the MCP protocol. It handles connection management, protocol compliance, and message routing: ```python # Add lifespan support for startup/shutdown with strong typing from contextlib import asynccontextmanager from collections.abc import AsyncIterator from dataclasses import dataclass from fake_database import Database # Replace with your actual DB type from mcp.server.fastmcp import Context, FastMCP # Create a named server mcp = FastMCP("My App") # Specify dependencies for deployment and development mcp = FastMCP("My App", dependencies=["pandas", "numpy"]) @dataclass class AppContext: db: Database @asynccontextmanager async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]: """Manage application lifecycle with type-safe context""" # Initialize on startup db = await Database.connect() try: yield AppContext(db=db) finally: # Cleanup on shutdown await db.disconnect() # Pass lifespan to server mcp = FastMCP("My App", lifespan=app_lifespan) # Access type-safe lifespan context in tools @mcp.tool() def query_db(ctx: Context) -> str: """Tool that uses initialized resources""" db = ctx.request_context.lifespan_context.db return db.query() ``` ### Resources Resources are how you expose data to LLMs. They're similar to GET endpoints in a REST API - they provide data but shouldn't perform significant computation or have side effects: ```python from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") @mcp.resource("config://app") def get_config() -> str: """Static configuration data""" return "App configuration here" @mcp.resource("users://{user_id}/profile") def get_user_profile(user_id: str) -> str: """Dynamic user data""" return f"Profile data for user {user_id}" ``` ### Tools Tools let LLMs take actions through your server. Unlike resources, tools are expected to perform computation and have side effects: ```python import httpx from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") @mcp.tool() def calculate_bmi(weight_kg: float, height_m: float) -> float: """Calculate BMI given weight in kg and height in meters""" return weight_kg / (height_m**2) @mcp.tool() async def fetch_weather(city: str) -> str: """Fetch current weather for a city""" async with httpx.AsyncClient() as client: response = await client.get(f"https://api.weather.com/{city}") return response.text ``` ### Prompts Prompts are reusable templates that help LLMs interact with your server effectively: ```python from mcp.server.fastmcp import FastMCP from mcp.server.fastmcp.prompts import base mcp = FastMCP("My App") @mcp.prompt() def review_code(code: str) -> str: return f"Please review this code:\n\n{code}" @mcp.prompt() def debug_error(error: str) -> list[base.Message]: return [ base.UserMessage("I'm seeing this error:"), base.UserMessage(error), base.AssistantMessage("I'll help debug that. What have you tried so far?"), ] ``` ### Images FastMCP provides an `Image` class that automatically handles image data: ```python from mcp.server.fastmcp import FastMCP, Image from PIL import Image as PILImage mcp = FastMCP("My App") @mcp.tool() def create_thumbnail(image_path: str) -> Image: """Create a thumbnail from an image""" img = PILImage.open(image_path) img.thumbnail((100, 100)) return Image(data=img.tobytes(), format="png") ``` ### Context The Context object gives your tools and resources access to MCP capabilities: ```python from mcp.server.fastmcp import FastMCP, Context mcp = FastMCP("My App") @mcp.tool() async def long_task(files: list[str], ctx: Context) -> str: """Process multiple files with progress tracking""" for i, file in enumerate(files): ctx.info(f"Processing {file}") await ctx.report_progress(i, len(files)) data, mime_type = await ctx.read_resource(f"file://{file}") return "Processing complete" ``` ## Running Your Server ### Development Mode The fastest way to test and debug your server is with the MCP Inspector: ```bash mcp dev server.py # Add dependencies mcp dev server.py --with pandas --with numpy # Mount local code mcp dev server.py --with-editable . ``` ### Claude Desktop Integration Once your server is ready, install it in Claude Desktop: ```bash mcp install server.py # Custom name mcp install server.py --name "My Analytics Server" # Environment variables mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://... mcp install server.py -f .env ``` ### Direct Execution For advanced scenarios like custom deployments: ```python from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") if __name__ == "__main__": mcp.run() ``` Run it with: ```bash python server.py # or mcp run server.py ``` ### Mounting to an Existing ASGI Server You can mount the SSE server to an existing ASGI server using the `sse_app` method. This allows you to integrate the SSE server with other ASGI applications. ```python from starlette.applications import Starlette from starlette.routing import Mount, Host from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") # Mount the SSE server to the existing ASGI server app = Starlette( routes=[ Mount('/', app=mcp.sse_app()), ] ) # or dynamically mount as host app.router.routes.append(Host('mcp.acme.corp', app=mcp.sse_app())) ``` For more information on mounting applications in Starlette, see the [Starlette documentation](https://www.starlette.io/routing/#submounting-routes). ## Examples ### Echo Server A simple server demonstrating resources, tools, and prompts: ```python from mcp.server.fastmcp import FastMCP mcp = FastMCP("Echo") @mcp.resource("echo://{message}") def echo_resource(message: str) -> str: """Echo a message as a resource""" return f"Resource echo: {message}" @mcp.tool() def echo_tool(message: str) -> str: """Echo a message as a tool""" return f"Tool echo: {message}" @mcp.prompt() def echo_prompt(message: str) -> str: """Create an echo prompt""" return f"Please process this message: {message}" ``` ### SQLite Explorer A more complex example showing database integration: ```python import sqlite3 from mcp.server.fastmcp import FastMCP mcp = FastMCP("SQLite Explorer") @mcp.resource("schema://main") def get_schema() -> str: """Provide the database schema as a resource""" conn = sqlite3.connect("database.db") schema = conn.execute("SELECT sql FROM sqlite_master WHERE type='table'").fetchall() return "\n".join(sql[0] for sql in schema if sql[0]) @mcp.tool() def query_data(sql: str) -> str: """Execute SQL queries safely""" conn = sqlite3.connect("database.db") try: result = conn.execute(sql).fetchall() return "\n".join(str(row) for row in result) except Exception as e: return f"Error: {str(e)}" ``` ## Advanced Usage ### Low-Level Server For more control, you can use the low-level server implementation directly. This gives you full access to the protocol and allows you to customize every aspect of your server, including lifecycle management through the lifespan API: ```python from contextlib import asynccontextmanager from collections.abc import AsyncIterator from fake_database import Database # Replace with your actual DB type from mcp.server import Server @asynccontextmanager async def server_lifespan(server: Server) -> AsyncIterator[dict]: """Manage server startup and shutdown lifecycle.""" # Initialize resources on startup db = await Database.connect() try: yield {"db": db} finally: # Clean up on shutdown await db.disconnect() # Pass lifespan to server server = Server("example-server", lifespan=server_lifespan) # Access lifespan context in handlers @server.call_tool() async def query_db(name: str, arguments: dict) -> list: ctx = server.request_context db = ctx.lifespan_context["db"] return await db.query(arguments["query"]) ``` The lifespan API provides: - A way to initialize resources when the server starts and clean them up when it stops - Access to initialized resources through the request context in handlers - Type-safe context passing between lifespan and request handlers ```python import mcp.server.stdio import mcp.types as types from mcp.server.lowlevel import NotificationOptions, Server from mcp.server.models import InitializationOptions # Create a server instance server = Server("example-server") @server.list_prompts() async def handle_list_prompts() -> list[types.Prompt]: return [ types.Prompt( name="example-prompt", description="An example prompt template", arguments=[ types.PromptArgument( name="arg1", description="Example argument", required=True ) ], ) ] @server.get_prompt() async def handle_get_prompt( name: str, arguments: dict[str, str] | None ) -> types.GetPromptResult: if name != "example-prompt": raise ValueError(f"Unknown prompt: {name}") return types.GetPromptResult( description="Example prompt", messages=[ types.PromptMessage( role="user", content=types.TextContent(type="text", text="Example prompt text"), ) ], ) async def run(): async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="example", server_version="0.1.0", capabilities=server.get_capabilities( notification_options=NotificationOptions(), experimental_capabilities={}, ), ), ) if __name__ == "__main__": import asyncio asyncio.run(run()) ``` ### Writing MCP Clients The SDK provides a high-level client interface for connecting to MCP servers: ```python from mcp import ClientSession, StdioServerParameters, types from mcp.client.stdio import stdio_client # Create server parameters for stdio connection server_params = StdioServerParameters( command="python", # Executable args=["example_server.py"], # Optional command line arguments env=None, # Optional environment variables ) # Optional: create a sampling callback async def handle_sampling_message( message: types.CreateMessageRequestParams, ) -> types.CreateMessageResult: return types.CreateMessageResult( role="assistant", content=types.TextContent( type="text", text="Hello, world! from model", ), model="gpt-3.5-turbo", stopReason="endTurn", ) async def run(): async with stdio_client(server_params) as (read, write): async with ClientSession( read, write, sampling_callback=handle_sampling_message ) as session: # Initialize the connection await session.initialize() # List available prompts prompts = await session.list_prompts() # Get a prompt prompt = await session.get_prompt( "example-prompt", arguments={"arg1": "value"} ) # List available resources resources = await session.list_resources() # List available tools tools = await session.list_tools() # Read a resource content, mime_type = await session.read_resource("file://some/path") # Call a tool result = await session.call_tool("tool-name", arguments={"arg1": "value"}) if __name__ == "__main__": import asyncio asyncio.run(run()) ``` ### MCP Primitives The MCP protocol defines three core primitives that servers can implement: | Primitive | Control | Description | Example Use | |-----------|-----------------------|-----------------------------------------------------|------------------------------| | Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options | | Resources | Application-controlled| Contextual data managed by the client application | File contents, API responses | | Tools | Model-controlled | Functions exposed to the LLM to take actions | API calls, data updates | ### Server Capabilities MCP servers declare capabilities during initialization: | Capability | Feature Flag | Description | |-------------|------------------------------|------------------------------------| | `prompts` | `listChanged` | Prompt template management | | `resources` | `subscribe`<br/>`listChanged`| Resource exposure and updates | | `tools` | `listChanged` | Tool discovery and execution | | `logging` | - | Server logging configuration | | `completion`| - | Argument completion suggestions | ## Documentation - [Model Context Protocol documentation](https://modelcontextprotocol.io) - [Model Context Protocol specification](https://spec.modelcontextprotocol.io) - [Officially supported servers](https://github.com/modelcontextprotocol/servers) ## Contributing We are passionate about supporting contributors of all levels of experience and would love to see you get involved in the project. See the [contributing guide](CONTRIBUTING.md) to get started. ## License This project is licensed under the MIT License - see the LICENSE file for details. ``` -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- ``` playwright>=1.40.0 pytest-playwright>=0.4.0 pandas>=2.1.1 numpy>=1.26.4 asyncio==3.4.3 mcp[cli] python-dotenv==1.0.0 requests==2.31.0 schedule==1.2.0 tqdm==4.66.1 fastapi>=0.95.1 uvicorn>=0.22.0 ``` -------------------------------------------------------------------------------- /AI-learn-resource/MCP-About.txt: -------------------------------------------------------------------------------- ``` # Introduction > Get started with the Model Context Protocol (MCP) MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools. ## Why MCP? MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides: * A growing list of pre-built integrations that your LLM can directly plug into * The flexibility to switch between LLM providers and vendors * Best practices for securing your data within your infrastructure ### 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["Host with MCP Client\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 <--> D1[("Local\nData Source A")] S2 <--> D2[("Local\nData Source B")] end subgraph "Internet" S3 <-->|"Web APIs"| D3[("Remote\nService C")] end ``` * **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access data 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 Data Sources**: Your computer's files, databases, and services that MCP servers can securely access * **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to # 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 "Host" client1[MCP Client] client2[MCP Client] end subgraph "Server Process" server1[MCP Server] end subgraph "Server Process" server2[MCP Server] end client1 <-->|Transport Layer| server1 client2 <-->|Transport Layer| server2 ``` ## Core components ### Protocol layer The protocol layer handles message framing, request/response linking, and high-level communication patterns. #### for 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> } ``` #### For 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 ``` Key classes include: * `Protocol` * `Client` * `Server` ### Transport layer The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms: 1. **Stdio transport** * Uses standard input/output for communication * Ideal for local processes 2. **HTTP with SSE transport** * Uses Server-Sent Events for server-to-client messages * HTTP POST for client-to-server messages All transports use [JSON-RPC](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](/specification/) for detailed information about the Model Context Protocol message format. ### Message types MCP has these main types of messages: 1. **Requests** expect a response from the other side: ```typescript interface Request { method: string; params?: { ... }; } ``` 2. **Results** are successful responses to requests: ```typescript interface Result { [key: string]: unknown; } ``` 3. **Errors** indicate that a request failed: ```typescript interface Error { code: number; message: string; data?: unknown; } ``` 4. **Notifications** are one-way messages that don't expect a response: ```typescript interface Notification { method: string; params?: { ... }; } ``` ## Connection lifecycle ### 1. Initialization ```mermaid sequenceDiagram participant Client participant Server Client->>Server: initialize request Server->>Client: initialize response Client->>Server: initialized notification Note over Client,Server: Connection ready for use ``` 1. Client sends `initialize` request with protocol version and capabilities 2. Server responds with its protocol version and capabilities 3. Client sends `initialized` notification as acknowledgment 4. Normal message exchange begins ### 2. Message exchange After initialization, the following patterns are supported: * **Request-Response**: Client or server sends requests, the other responds * **Notifications**: Either party sends one-way messages ### 3. Termination Either party can terminate the connection: * Clean shutdown via `close()` * Transport disconnection * Error conditions ## Error handling MCP defines these standard error codes: ```typescript enum ErrorCode { // Standard JSON-RPC error codes ParseError = -32700, InvalidRequest = -32600, MethodNotFound = -32601, InvalidParams = -32602, InternalError = -32603 } ``` SDKs and applications can define their own error codes above -32000. Errors are propagated through: * Error responses to requests * Error events on transports * Protocol-level error handlers ## Implementation example Here's a basic example of implementing an MCP server: ### For 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); ``` ### For 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()) ``` ## 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 # For Server Developers > Get started building your own server to use in Claude for Desktop and other clients. In this tutorial, we'll build a simple MCP weather server and connect it to a host, Claude for Desktop. We'll start with a basic setup, and then progress to more complex use cases. ### What we'll be building Many LLMs do not currently have the ability to fetch the forecast and severe weather alerts. Let's use MCP to solve that! We'll build a server that exposes two tools: `get-alerts` and `get-forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop): <Frame> <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" /> </Frame> <Frame> <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" /> </Frame> <Note> Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have guides on [building your own client](/quickstart/client) as well as a [list of other clients here](/clients). </Note> <Accordion title="Why Claude for Desktop and not Claude.ai?"> Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development. </Accordion> ### Core MCP Concepts MCP servers can provide three main types of capabilities: 1. **Resources**: File-like data that can be read by clients (like API responses or file contents) 2. **Tools**: Functions that can be called by the LLM (with user approval) 3. **Prompts**: Pre-written templates that help users accomplish specific tasks This tutorial will primarily focus on tools. #### For Python Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python) ##### Prerequisite knowledge This quickstart assumes you have familiarity with: * Python * LLMs like Claude ##### System requirements * Python 3.10 or higher installed. * You must use the Python MCP SDK 1.2.0 or higher. ##### Set up your environment First, let's install `uv` and set up our Python project and environment: ```bash MacOS/Linux curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell Windows powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up. Now, let's create and set up our project: ```bash MacOS/Linux # Create a new directory for our project uv init weather cd weather # Create virtual environment and activate it uv venv source .venv/bin/activate # Install dependencies uv add "mcp[cli]" httpx # Create our server file touch weather.py ``` ```powershell Windows # Create a new directory for our project uv init weather cd weather # Create virtual environment and activate it uv venv .venv\Scripts\activate # Install dependencies uv add mcp[cli] httpx # Create our server file new-item weather.py ``` Now let's dive into building your server. ##### Building your server ###### Importing packages and setting up the instance Add these to the top of your `weather.py`: ```python from typing import Any import httpx from mcp.server.fastmcp import FastMCP # Initialize FastMCP server mcp = FastMCP("weather") # Constants NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" ``` The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools. ###### Helper functions Next, let's add our helper functions for querying and formatting the data from the National Weather Service API: ```python async def make_nws_request(url: str) -> dict[str, Any] | None: """Make a request to the NWS API with proper error handling.""" headers = { "User-Agent": USER_AGENT, "Accept": "application/geo+json" } async with httpx.AsyncClient() as client: try: response = await client.get(url, headers=headers, timeout=30.0) response.raise_for_status() return response.json() except Exception: return None def format_alert(feature: dict) -> str: """Format an alert feature into a readable string.""" props = feature["properties"] return f""" Event: {props.get('event', 'Unknown')} Area: {props.get('areaDesc', 'Unknown')} Severity: {props.get('severity', 'Unknown')} Description: {props.get('description', 'No description available')} Instructions: {props.get('instruction', 'No specific instructions provided')} """ ``` ###### Implementing tool execution The tool execution handler is responsible for actually executing the logic of each tool. Let's add it: ```python @mcp.tool() async def get_alerts(state: str) -> str: """Get weather alerts for a US state. Args: state: Two-letter US state code (e.g. CA, NY) """ url = f"{NWS_API_BASE}/alerts/active/area/{state}" data = await make_nws_request(url) if not data or "features" not in data: return "Unable to fetch alerts or no alerts found." if not data["features"]: return "No active alerts for this state." alerts = [format_alert(feature) for feature in data["features"]] return "\n---\n".join(alerts) @mcp.tool() async def get_forecast(latitude: float, longitude: float) -> str: """Get weather forecast for a location. Args: latitude: Latitude of the location longitude: Longitude of the location """ # First get the forecast grid endpoint points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}" points_data = await make_nws_request(points_url) if not points_data: return "Unable to fetch forecast data for this location." # Get the forecast URL from the points response forecast_url = points_data["properties"]["forecast"] forecast_data = await make_nws_request(forecast_url) if not forecast_data: return "Unable to fetch detailed forecast." # Format the periods into a readable forecast periods = forecast_data["properties"]["periods"] forecasts = [] for period in periods[:5]: # Only show next 5 periods forecast = f""" {period['name']}: Temperature: {period['temperature']}°{period['temperatureUnit']} Wind: {period['windSpeed']} {period['windDirection']} Forecast: {period['detailedForecast']} """ forecasts.append(forecast) return "\n---\n".join(forecasts) ``` ###### Running the server Finally, let's initialize and run the server: ```python if __name__ == "__main__": # Initialize and run the server mcp.run(transport='stdio') ``` Your server is complete! Run `uv run weather.py` to confirm that everything's working. Let's now test your server from an existing MCP host, Claude for Desktop. ##### Testing your server with Claude for Desktop <Note> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built. </Note> First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.** We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist. For example, if you have [VS Code](https://code.visualstudio.com/) installed: ```bash MacOS/Linux code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ```powershell Windows code $env:AppData\Claude\claude_desktop_config.json ``` You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured. In this case, we'll add our single weather server like so: MacOS/Linux ```json Python { "mcpServers": { "weather": { "command": "uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather", "run", "weather.py" ] } } } ``` Windows ```json Python { "mcpServers": { "weather": { "command": "uv", "args": [ "--directory", "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather", "run", "weather.py" ] } } } ``` <Warning> You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on MacOS/Linux or `where uv` on Windows. </Warning> <Note> Make sure you pass in the absolute path to your server. </Note> This tells Claude for Desktop: 1. There's an MCP server named "weather" 2. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py` Save the file, and restart **Claude for Desktop**. #### For Node Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript) ##### Prerequisite knowledge This quickstart assumes you have familiarity with: * TypeScript * LLMs like Claude ##### System requirements For TypeScript, make sure you have the latest version of Node installed. ##### Set up your environment First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/). Verify your Node.js installation: ```bash node --version npm --version ``` For this tutorial, you'll need Node.js version 16 or higher. Now, let's create and set up our project: ```bash MacOS/Linux # Create a new directory for our project mkdir weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files mkdir src touch src/index.ts ``` ```powershell Windows # Create a new directory for our project md weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files md src new-item src\index.ts ``` Update your package.json to add type: "module" and a build script: ```json package.json { "type": "module", "bin": { "weather": "./build/index.js" }, "scripts": { "build": "tsc && chmod 755 build/index.js" }, "files": [ "build" ], } ``` Create a `tsconfig.json` in the root of your project: ```json tsconfig.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"] } ``` Now let's dive into building your server. ##### Building your server ###### Importing packages and setting up the instance Add these to the top of your `src/index.ts`: ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; const NWS_API_BASE = "https://api.weather.gov"; const USER_AGENT = "weather-app/1.0"; // Create server instance const server = new McpServer({ name: "weather", version: "1.0.0", capabilities: { resources: {}, tools: {}, }, }); ``` ###### Helper functions Next, let's add our helper functions for querying and formatting the data from the National Weather Service API: ```typescript // Helper function for making NWS API requests async function makeNWSRequest<T>(url: string): Promise<T | null> { const headers = { "User-Agent": USER_AGENT, Accept: "application/geo+json", }; try { const response = await fetch(url, { headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return (await response.json()) as T; } catch (error) { console.error("Error making NWS request:", error); return null; } } interface AlertFeature { properties: { event?: string; areaDesc?: string; severity?: string; status?: string; headline?: string; }; } // Format alert data function formatAlert(feature: AlertFeature): string { const props = feature.properties; return [ `Event: ${props.event || "Unknown"}`, `Area: ${props.areaDesc || "Unknown"}`, `Severity: ${props.severity || "Unknown"}`, `Status: ${props.status || "Unknown"}`, `Headline: ${props.headline || "No headline"}`, "---", ].join("\n"); } interface ForecastPeriod { name?: string; temperature?: number; temperatureUnit?: string; windSpeed?: string; windDirection?: string; shortForecast?: string; } interface AlertsResponse { features: AlertFeature[]; } interface PointsResponse { properties: { forecast?: string; }; } interface ForecastResponse { properties: { periods: ForecastPeriod[]; }; } ``` ###### Implementing tool execution The tool execution handler is responsible for actually executing the logic of each tool. Let's add it: ```typescript // Register weather tools server.tool( "get-alerts", "Get weather alerts for a state", { state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)"), }, async ({ state }) => { const stateCode = state.toUpperCase(); const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`; const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl); if (!alertsData) { return { content: [ { type: "text", text: "Failed to retrieve alerts data", }, ], }; } const features = alertsData.features || []; if (features.length === 0) { return { content: [ { type: "text", text: `No active alerts for ${stateCode}`, }, ], }; } const formattedAlerts = features.map(formatAlert); const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`; return { content: [ { type: "text", text: alertsText, }, ], }; }, ); server.tool( "get-forecast", "Get weather forecast for a location", { latitude: z.number().min(-90).max(90).describe("Latitude of the location"), longitude: z.number().min(-180).max(180).describe("Longitude of the location"), }, async ({ latitude, longitude }) => { // Get grid point data const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`; const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl); if (!pointsData) { return { content: [ { type: "text", text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`, }, ], }; } const forecastUrl = pointsData.properties?.forecast; if (!forecastUrl) { return { content: [ { type: "text", text: "Failed to get forecast URL from grid point data", }, ], }; } // Get forecast data const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl); if (!forecastData) { return { content: [ { type: "text", text: "Failed to retrieve forecast data", }, ], }; } const periods = forecastData.properties?.periods || []; if (periods.length === 0) { return { content: [ { type: "text", text: "No forecast periods available", }, ], }; } // Format forecast periods const formattedForecast = periods.map((period: ForecastPeriod) => [ `${period.name || "Unknown"}:`, `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`, `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`, `${period.shortForecast || "No forecast available"}`, "---", ].join("\n"), ); const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`; return { content: [ { type: "text", text: forecastText, }, ], }; }, ); ``` ###### Running the server Finally, implement the main function to run the server: ```typescript async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("Weather MCP Server running on stdio"); } main().catch((error) => { console.error("Fatal error in main():", error); process.exit(1); }); ``` Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect. Let's now test your server from an existing MCP host, Claude for Desktop. ##### Testing your server with Claude for Desktop <Note> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built. </Note> First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.** We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist. For example, if you have [VS Code](https://code.visualstudio.com/) installed: MacOS/Linux ```bash code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` Windows ```powershell code $env:AppData\Claude\claude_desktop_config.json ``` You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured. In this case, we'll add our single weather server like so: MacOS/Linux ```json Node { "mcpServers": { "weather": { "command": "node", "args": [ "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js" ] } } } ``` Windows ```json Node { "mcpServers": { "weather": { "command": "node", "args": [ "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js" ] } } } ``` This tells Claude for Desktop: 1. There's an MCP server named "weather" 2. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js` Save the file, and restart **Claude for Desktop**. ### Test with commands Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the hammer <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon: <Frame> <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/visual-indicator-mcp-tools.png" /> </Frame> After clicking on the hammer icon, you should see two tools listed: <Frame> <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/available-mcp-tools.png" /> </Frame> If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips. If the hammer icon has shown up, you can now test your server by running the following commands in Claude for Desktop: * What's the weather in Sacramento? * What are the active weather alerts in Texas? <Frame> <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" /> </Frame> <Frame> <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" /> </Frame> <Note> Since this is the US National Weather service, the queries will only work for US locations. </Note> ## What's happening under the hood When you ask a question: 1. The client sends your question to Claude 2. Claude analyzes the available tools and decides which one(s) to use 3. The client executes the chosen tool(s) through the MCP server 4. The results are sent back to Claude 5. Claude formulates a natural language response 6. The response is displayed to you! ## Troubleshooting <AccordionGroup> <Accordion title="Claude for Desktop Integration Issues"> **Getting logs from Claude for Desktop** Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude`: * `mcp.log` will contain general logging about MCP connections and connection failures. * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server. You can run the following command to list recent logs and follow along with any new ones: ```bash # Check Claude's logs for errors tail -n 20 -f ~/Library/Logs/Claude/mcp*.log ``` **Server not showing up in Claude** 1. Check your `claude_desktop_config.json` file syntax 2. Make sure the path to your project is absolute and not relative 3. Restart Claude for Desktop completely **Tool calls failing silently** If Claude attempts to use the tools but they fail: 4. Check Claude's logs for errors 5. Verify your server builds and runs without errors 6. Try restarting Claude for Desktop **None of this is working. What do I do?** Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance. </Accordion> <Accordion title="Weather API Issues"> **Error: Failed to retrieve grid point data** This usually means either: 1. The coordinates are outside the US 2. The NWS API is having issues 3. You're being rate limited Fix: * Verify you're using US coordinates * Add a small delay between requests * Check the NWS API status page **Error: No active alerts for \[STATE]** This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather. </Accordion> </AccordionGroup> <Note> For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/tools/debugging) </Note> # 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. Different MCP clients may handle resources differently. For example: * Claude Desktop currently requires users to explicitly select resources before they can be used * Other clients might automatically select resources based on heuristics * Some implementations may even allow the AI model itself to determine which resources to use Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a **model-controlled** primitive such as [Tools](./tools). </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: 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"); }); ``` 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() ) ``` ## 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 # 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: 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"); }); ``` 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") ``` ## 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 # 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 }, annotations?: { // Optional hints about tool behavior title?: string; // Human-readable title for the tool readOnlyHint?: boolean; // If true, the tool does not modify its environment destructiveHint?: boolean; // If true, the tool may perform destructive updates idempotentHint?: boolean; // If true, repeated calls with same args have no additional effect openWorldHint?: boolean; // If true, tool interacts with external entities } } ``` ## Implementing tools Here's an example of implementing a basic tool in an MCP server: TypeScript ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { tools: {} } }); // Define available tools server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [{ name: "calculate_sum", description: "Add two numbers together", inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] } }] }; }); // Handle tool execution server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "calculate_sum") { const { a, b } = request.params.arguments; return { content: [ { type: "text", text: String(a + b) } ] }; } throw new Error("Tool not found"); }); ``` Python ```python app = Server("example-server") @app.list_tools() async def list_tools() -> list[types.Tool]: return [ types.Tool( name="calculate_sum", description="Add two numbers together", inputSchema={ "type": "object", "properties": { "a": {"type": "number"}, "b": {"type": "number"} }, "required": ["a", "b"] } ) ] @app.call_tool() async def call_tool( name: str, arguments: dict ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: if name == "calculate_sum": a = arguments["a"] b = arguments["b"] result = a + b return [types.TextContent(type="text", text=str(result))] raise ValueError(f"Tool not found: {name}") ``` ## Example tool patterns Here are some examples of types of tools that a server could provide: ### System operations Tools that interact with the local system: ```typescript { name: "execute_command", description: "Run a shell command", inputSchema: { type: "object", properties: { command: { type: "string" }, args: { type: "array", items: { type: "string" } } } } } ``` ### API integrations Tools that wrap external APIs: ```typescript { name: "github_create_issue", description: "Create a GitHub issue", inputSchema: { type: "object", properties: { title: { type: "string" }, body: { type: "string" }, labels: { type: "array", items: { type: "string" } } } } } ``` ### Data processing Tools that transform or analyze data: ```typescript { name: "analyze_csv", description: "Analyze a CSV file", inputSchema: { type: "object", properties: { filepath: { type: "string" }, operations: { type: "array", items: { enum: ["sum", "average", "count"] } } } } } ``` ## Best practices When implementing tools: 1. Provide clear, descriptive names and descriptions 2. Use detailed JSON Schema definitions for parameters 3. Include examples in tool descriptions to demonstrate how the model should use them 4. Implement proper error handling and validation 5. Use progress reporting for long operations 6. Keep tool operations focused and atomic 7. Document expected return value structures 8. Implement proper timeouts 9. Consider rate limiting for resource-intensive operations 10. Log tool usage for debugging and monitoring ## Security considerations When exposing tools: ### Input validation * Validate all parameters against the schema * Sanitize file paths and system commands * Validate URLs and external identifiers * Check parameter sizes and ranges * Prevent command injection ### Access control * Implement authentication where needed * Use appropriate authorization checks * Audit tool usage * Rate limit requests * Monitor for abuse ### Error handling * Don't expose internal errors to clients * Log security-relevant errors * Handle timeouts appropriately * Clean up resources after errors * Validate return values ## Tool discovery and updates MCP supports dynamic tool discovery: 1. Clients can list available tools at any time 2. Servers can notify clients when tools change using `notifications/tools/list_changed` 3. Tools can be added or removed during runtime 4. Tool definitions can be updated (though this should be done carefully) ## Error handling Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error: 1. Set `isError` to `true` in the result 2. Include error details in the `content` array Here's an example of proper error handling for tools: TypeScript ```typescript try { // Tool operation const result = performOperation(); return { content: [ { type: "text", text: `Operation successful: ${result}` } ] }; } catch (error) { return { isError: true, content: [ { type: "text", text: `Error: ${error.message}` } ] }; } ``` Python ```python try: # Tool operation result = perform_operation() return types.CallToolResult( content=[ types.TextContent( type="text", text=f"Operation successful: {result}" ) ] ) except Exception as error: return types.CallToolResult( isError=True, content=[ types.TextContent( type="text", text=f"Error: {str(error)}" ) ] ) ``` This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention. ## Tool annotations Tool annotations provide additional metadata about a tool's behavior, helping clients understand how to present and manage tools. These annotations are hints that describe the nature and impact of a tool, but should not be relied upon for security decisions. ### Purpose of tool annotations Tool annotations serve several key purposes: 1. Provide UX-specific information without affecting model context 2. Help clients categorize and present tools appropriately 3. Convey information about a tool's potential side effects 4. Assist in developing intuitive interfaces for tool approval ### Available tool annotations The MCP specification defines the following annotations for tools: | Annotation | Type | Default | Description | | ----------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `title` | string | - | A human-readable title for the tool, useful for UI display | | `readOnlyHint` | boolean | false | If true, indicates the tool does not modify its environment | | `destructiveHint` | boolean | true | If true, the tool may perform destructive updates (only meaningful when `readOnlyHint` is false) | | `idempotentHint` | boolean | false | If true, calling the tool repeatedly with the same arguments has no additional effect (only meaningful when `readOnlyHint` is false) | | `openWorldHint` | boolean | true | If true, the tool may interact with an "open world" of external entities | ### Example usage Here's how to define tools with annotations for different scenarios: ```typescript // A read-only search tool { name: "web_search", description: "Search the web for information", inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] }, annotations: { title: "Web Search", readOnlyHint: true, openWorldHint: true } } // A destructive file deletion tool { name: "delete_file", description: "Delete a file from the filesystem", inputSchema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] }, annotations: { title: "Delete File", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false } } // A non-destructive database record creation tool { name: "create_record", description: "Create a new record in the database", inputSchema: { type: "object", properties: { table: { type: "string" }, data: { type: "object" } }, required: ["table", "data"] }, annotations: { title: "Create Database Record", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false } } ``` ### Integrating annotations in server implementation TypeScript ```typescript server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [{ name: "calculate_sum", description: "Add two numbers together", inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] }, annotations: { title: "Calculate Sum", readOnlyHint: true, openWorldHint: false } }] }; }); ``` Python ```python from mcp.server.fastmcp import FastMCP mcp = FastMCP("example-server") @mcp.tool( annotations={ "title": "Calculate Sum", "readOnlyHint": True, "openWorldHint": False } ) async def calculate_sum(a: float, b: float) -> str: """Add two numbers together. Args: a: First number to add b: Second number to add """ result = a + b return str(result) ``` ### Best practices for tool annotations 1. **Be accurate about side effects**: Clearly indicate whether a tool modifies its environment and whether those modifications are destructive. 2. **Use descriptive titles**: Provide human-friendly titles that clearly describe the tool's purpose. 3. **Indicate idempotency properly**: Mark tools as idempotent only if repeated calls with the same arguments truly have no additional effect. 4. **Set appropriate open/closed world hints**: Indicate whether a tool interacts with a closed system (like a database) or an open system (like the web). 5. **Remember annotations are hints**: All properties in ToolAnnotations are hints and not guaranteed to provide a faithful description of tool behavior. Clients should never make security-critical decisions based solely on annotations. ## Testing tools A comprehensive testing strategy for MCP tools should cover: * **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately * **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies * **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting * **Performance testing**: Check behavior under load, timeout handling, and resource cleanup * **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources # 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 TypeScript (Server) ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: {} }); const transport = new StdioServerTransport(); await server.connect(transport); ``` 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); ``` Python (Server) ```python app = Server("example-server") async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) ``` 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() ``` ### Server-Sent Events (SSE) SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication. Use SSE when: * Only server-to-client streaming is needed * Working with restricted networks * Implementing simple updates #### Security Warning: DNS Rebinding Attacks SSE transports can be vulnerable to DNS rebinding attacks if not properly secured. To prevent this: 1. **Always validate Origin headers** on incoming SSE connections to ensure they come from expected sources 2. **Avoid binding servers to all network interfaces** (0.0.0.0) when running locally - bind only to localhost (127.0.0.1) instead 3. **Implement proper authentication** for all SSE connections Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites. TypeScript (Server) ```typescript import express from "express"; const app = express(); const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: {} }); let transport: SSEServerTransport | null = null; app.get("/sse", (req, res) => { transport = new SSEServerTransport("/messages", res); server.connect(transport); }); app.post("/messages", (req, res) => { if (transport) { transport.handlePostMessage(req, res); } }); app.listen(3000); ``` TypeScript (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); ``` 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"]), ] ) ``` 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() ``` ## Custom Transports MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface: You can implement custom transports for: * Custom network protocols * Specialized communication channels * Integration with existing systems * Performance optimization TypeScript ```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; } ``` 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() ``` ## Error Handling Transport implementations should handle various error scenarios: 1. Connection errors 2. Message parsing errors 3. Protocol errors 4. Network timeouts 5. Resource cleanup Example error handling: TypeScript ```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; } } } ``` 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 ``` ## Best Practices When implementing or using MCP transport: 1. Handle connection lifecycle properly 2. Implement proper error handling 3. Clean up resources on connection close 4. Use appropriate timeouts 5. Validate messages before sending 6. Log transport events for debugging 7. Implement reconnection logic when appropriate 8. Handle backpressure in message queues 9. Monitor connection health 10. Implement proper security measures ## Security Considerations When implementing transport: ### Authentication and Authorization * Implement proper authentication mechanisms * Validate client credentials * Use secure token handling * Implement authorization checks ### Data Security * Use TLS for network transport * Encrypt sensitive data * Validate message integrity * Implement message size limits * Sanitize input data ### Network Security * Implement rate limiting * Use appropriate timeouts * Handle denial of service scenarios * Monitor for unusual patterns * Implement proper firewall rules * For SSE transports, validate Origin headers to prevent DNS rebinding attacks * For local SSE servers, bind only to localhost (127.0.0.1) instead of all interfaces (0.0.0.0) ## Debugging Transport Tips for debugging transport issues: 1. Enable debug logging 2. Monitor message flow 3. Check connection states 4. Validate message formats 5. Test error scenarios 6. Use network analysis tools 7. Implement health checks 8. Monitor resource usage 9. Test edge cases 10. Use proper error tracking ```