### Install Dependencies Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/clients/simple-chatbot/README.MD Installs the required Python packages for the chatbot example. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CONTRIBUTING.md Installs project dependencies including development extras using uv. Ensure you have uv installed and the repository cloned. ```bash uv sync --frozen --all-extras --dev ``` -------------------------------- ### Environment Variables Setup Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/clients/simple-chatbot/README.MD Sets up the necessary environment variables, including the LLM API key. ```plaintext LLM_API_KEY=your_api_key_here ``` -------------------------------- ### Run the Chatbot Client Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/clients/simple-chatbot/README.MD Starts the simple CLI chatbot client application. ```bash python main.py ``` -------------------------------- ### Create a SQLite Explorer Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md This example shows how to integrate with a SQLite database to expose schema and execute queries as tools. ```python from mcp.server.fastmcp import FastMCP import sqlite3 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)}" ``` -------------------------------- ### Create an Echo Server with Resources, Tools, and Prompts Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md This example demonstrates how to define resources, tools, and prompts for an echo server using the `FastMCP` class. ```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}" ``` -------------------------------- ### Start MCP Simple Resource Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/servers/simple-resource/README.md Commands to start the MCP Simple Resource server using either the default stdio transport or the SSE transport on a custom port. ```bash # Using stdio transport (default) uv run mcp-simple-resource # Using SSE transport on custom port uv run mcp-simple-resource --transport sse --port 8000 ``` -------------------------------- ### Start MCP Simple Prompt Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/servers/simple-prompt/README.md Use these commands to start the MCP Simple Prompt server. The default transport is stdio, but SSE can be used on a custom port. ```bash uv run mcp-simple-prompt ``` ```bash uv run mcp-simple-prompt --transport sse --port 8000 ``` -------------------------------- ### Install MCP Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Alternatively, install the MCP package using pip. ```bash pip install mcp ``` -------------------------------- ### Install MCP Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Install a Python MCP server script into Claude Desktop. ```bash mcp install server.py ``` -------------------------------- ### Start Simple MCP Tool Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/servers/simple-tool/README.md Run the MCP tool server using either the default stdio transport or SSE transport on a custom port. ```bash # Using stdio transport (default) uv run mcp-simple-tool # Using SSE transport on custom port uv run mcp-simple-tool --transport sse --port 8000 ``` -------------------------------- ### Install MCP with CLI Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Use uv to add the MCP package with CLI support to your project. ```bash uv add "mcp[cli]" ``` -------------------------------- ### MCP Servers Configuration Example Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/clients/simple-chatbot/README.MD Configures MCP servers, including SQLite and Puppeteer, for tool integration. ```json { "mcpServers": { "sqlite": { "command": "uvx", "args": ["mcp-server-sqlite", "--db-path", "./test.db"] }, "puppeteer": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-puppeteer"] } } } ``` -------------------------------- ### Call Fetch Tool with MCP Client Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/servers/simple-tool/README.md Example of using the MCP client to interact with the 'fetch' tool. This snippet demonstrates initializing the client, listing tools, and calling the 'fetch' tool with a URL. ```python import asyncio from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters, stdio_client async def main(): async with stdio_client( StdioServerParameters(command="uv", args=["run", "mcp-simple-tool"]) ) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # List available tools tools = await session.list_tools() print(tools) # Call the fetch tool result = await session.call_tool("fetch", {"url": "https://example.com"}) print(result) asyncio.run(main()) ``` -------------------------------- ### Install MCP Server in Claude Desktop Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Use `mcp install` to add your server to Claude Desktop. You can specify a custom name or load environment variables from a file. ```bash mcp install server.py ``` ```bash mcp install server.py --name "My Analytics Server" ``` ```bash mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://... ``` ```bash mcp install server.py -f .env ``` -------------------------------- ### MCP Client Example: List and Read Resources Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/servers/simple-resource/README.md A Python script demonstrating how to use the MCP client to connect to the simple resource server via stdio, list available resources, and read a specific text file resource. ```python import asyncio from mcp.types import AnyUrl from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters, stdio_client async def main(): async with stdio_client( StdioServerParameters(command="uv", args=["run", "mcp-simple-resource"]) ) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # List available resources resources = await session.list_resources() print(resources) # Get a specific resource resource = await session.read_resource(AnyUrl("file:///greeting.txt")) print(resource) asyncio.run(main()) ``` -------------------------------- ### MCP Server Configuration with Environment Variables Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/clients/simple-chatbot/README.MD Example of configuring an MCP server with environment variables, such as an API key. ```json { "mcpServers": { "server_name": { "command": "uvx", "args": ["mcp-server-name", "--additional-args"], "env": { "API_KEY": "your_api_key_here" } } } } ``` -------------------------------- ### Run MCP Server in Development Mode Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Use `mcp dev` to start your server for testing. You can add dependencies or mount local code. ```bash mcp dev server.py ``` ```bash mcp dev server.py --with pandas --with numpy ``` ```bash mcp dev server.py --with-editable . ``` -------------------------------- ### Define a Resource Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Decorate a function to expose data as a resource, similar to a GET endpoint. Resources should not perform significant computation or have side effects. ```python @mcp.resource("config://app") def get_config() -> str: """Static configuration data""" return "App configuration here" ``` ```python @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}" ``` -------------------------------- ### Create MCP Client with Stdio Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md This snippet demonstrates how to create a high-level MCP client that connects to a server using stdio. It shows initialization and calls to various client methods like listing prompts and reading resources. ```python from mcp import ClientSession, StdioServerParameters 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 ) async def run(): async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) 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()) ``` -------------------------------- ### Create a FastMCP Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Instantiate the FastMCP server, optionally specifying dependencies for deployment and development. ```python from mcp.server.fastmcp import FastMCP # Create a named server mcp = FastMCP("My App") # Specify dependencies for deployment and development mcp = FastMCP("My App", dependencies=["pandas", "numpy"]) ``` -------------------------------- ### Run Tool with uv Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CLAUDE.md Execute project tools, such as linters or formatters, using uv. ```bash uv run tool ``` -------------------------------- ### Implement Low-Level MCP Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Use this snippet to create a custom MCP server with full protocol control. It requires importing server components and defining handlers for prompts. ```python from mcp.server.lowlevel import Server, NotificationOptions from mcp.server.models import InitializationOptions import mcp.server.stdio import mcp.types as types # 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()) ``` -------------------------------- ### Interact with MCP Simple Prompt Server using Python Client Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/examples/servers/simple-prompt/README.md This Python script demonstrates how to connect to the MCP Simple Prompt server using the STDIO transport, list available prompts, and retrieve a specific prompt with context and topic arguments. ```python import asyncio from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters, stdio_client async def main(): async with stdio_client( StdioServerParameters(command="uv", args=["run", "mcp-simple-prompt"]) ) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # List available prompts prompts = await session.list_prompts() print(prompts) # Get the prompt with arguments prompt = await session.get_prompt( "simple", { "context": "User is a software developer", "topic": "Python async programming", }, ) print(prompt) asyncio.run(main()) ``` -------------------------------- ### Create a Simple MCP Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md This Python code defines an MCP server using FastMCP, exposing an addition tool and a dynamic greeting resource. ```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}!" ``` -------------------------------- ### Define a Prompt Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Decorate a function to create a reusable prompt template for LLMs. Prompts help structure LLM interactions with the server. ```python @mcp.prompt() def review_code(code: str) -> str: return f"Please review this code:\n\n{code}" ``` ```python @mcp.prompt() def debug_error(error: str) -> list[Message]: return [ UserMessage("I'm seeing this error:"), UserMessage(error), AssistantMessage("I'll help debug that. What have you tried so far?") ] ``` -------------------------------- ### Upgrade Package with uv Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CLAUDE.md Upgrade a development package and its dependencies. ```bash uv add --dev package --upgrade-package package ``` -------------------------------- ### Develop MCP Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Run an MCP server in development mode for testing with the MCP Inspector. ```bash mcp dev server.py ``` -------------------------------- ### Create a Thumbnail with Image Class Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Utilize the `Image` class to handle image data automatically when creating a thumbnail from an image file. ```python from mcp.server.fastmcp import FastMCP, Image from PIL import Image as PILImage @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") ``` -------------------------------- ### Direct Execution of MCP Server Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md For advanced deployment scenarios, you can directly execute your MCP server script using Python or the `mcp run` command. ```python from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") if __name__ == "__main__": mcp.run() ``` ```bash python server.py ``` ```bash mcp run server.py ``` -------------------------------- ### Add Package with uv Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CLAUDE.md Use this command to add a new package to your project's dependencies. ```bash uv add package ``` -------------------------------- ### Define a Tool Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Decorate a function to create a tool that allows LLMs to take actions. Tools are expected to perform computation and may have side effects. ```python @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) ``` ```python @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 ``` -------------------------------- ### Format Code with ruff Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CONTRIBUTING.md Applies code formatting rules using ruff to ensure consistency across the project. This should be run before submitting changes. ```bash uv run ruff format . ``` -------------------------------- ### Run Type Checking with pyright Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CONTRIBUTING.md Performs static type checking on the codebase using pyright. This helps catch type errors before runtime. ```bash uv run pyright ``` -------------------------------- ### Process Files with Context Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/README.md Use the `Context` object within tools or resources to access MCP capabilities, such as logging information, reporting progress, and reading resources. ```python from mcp.server.fastmcp import FastMCP, Context @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" ``` -------------------------------- ### Fix Code with Ruff Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CLAUDE.md Automatically fix linting errors and style violations using Ruff. ```bash uv run ruff check . --fix ``` -------------------------------- ### Run Tests with pytest Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CONTRIBUTING.md Executes the project's test suite using pytest. This command should be run after making code changes to ensure tests pass. ```bash uv run pytest ``` -------------------------------- ### Commit with User Report Trailer Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CLAUDE.md Add a trailer to your commit message to indicate it fixes a bug or adds a feature reported by a user. ```bash git commit --trailer "Reported-by:" ``` -------------------------------- ### Commit with Github Issue Trailer Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CLAUDE.md Add a trailer to your commit message to link it to a specific Github issue. ```bash git commit --trailer "Github-Issue:#" ``` -------------------------------- ### Check Code with ruff Source: https://github.com/ai-app/modelcontextprotocol.python-sdk/blob/main/CONTRIBUTING.md Runs the ruff linter to check for code style violations and potential errors. This command should be executed as part of the development workflow. ```bash uv run ruff check . ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.