### Install MCP Server for Claude Desktop Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This command installs the `server.py` MCP server, created in the quickstart, into Claude Desktop. This makes the server's defined tools and resources accessible for interaction within the Claude AI environment. ```bash mcp install server.py ``` -------------------------------- ### Execute Asynchronous MCP Client Example in Python Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This standard Python `if __name__ == "__main__"` block serves as the entry point for the script. It imports the `asyncio` library and uses `asyncio.run()` to execute the main asynchronous `run` function, initiating the MCP client example. ```python if __name__ == "__main__": import asyncio asyncio.run(run()) ``` -------------------------------- ### MCP Client Session Initialization Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md Demonstrates the initial setup for connecting to an MCP server using the high-level client interface provided by the SDK. It shows importing necessary classes like `ClientSession`, `StdioServerParameters`, and `types` for establishing a client connection. ```python from mcp import ClientSession, StdioServerParameters, types from mcp.client.stdio import stdio_client ``` -------------------------------- ### Low-Level MCP Server with Prompt Handling and Capabilities Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md A comprehensive example of a low-level MCP server, showcasing how to define prompt listing and retrieval handlers, set up server capabilities, and run the server using standard I/O streams. It demonstrates explicit control over server initialization and communication, including handling `InitializationOptions` and `NotificationOptions`. ```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()) ``` -------------------------------- ### Install MCP Python SDK with uv Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This command adds the MCP Python SDK, including command-line interface dependencies, to a project managed by uv, a fast Python package installer and resolver. It's the recommended way to manage dependencies with uv. ```bash uv add "mcp[cli]" ``` -------------------------------- ### Install MCP Python SDK with pip Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This command installs the core MCP Python SDK package using pip, the standard Python package installer. It's an alternative for projects not using uv for dependency management. ```bash pip install mcp ``` -------------------------------- ### Installing FastMCP Server for Claude Desktop Integration Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md These commands demonstrate how to install your FastMCP server for integration with Claude Desktop. You can specify a custom name for your server and pass environment variables, either individually or from a .env file, to configure your deployment. ```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 ``` -------------------------------- ### Run MCP Client Session and Interact with Server in Python Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This `run` asynchronous function showcases the full lifecycle of an MCP client session. It establishes a connection via `stdio_client`, initializes the session, and demonstrates common operations such as listing prompts, resources, and tools, getting a specific prompt, reading resource content, and calling a tool. ```python 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"}) ``` -------------------------------- ### Overview of Model Context Protocol (MCP) Core Primitives Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This API documentation outlines the three fundamental primitives defined by the MCP protocol: Prompts, Resources, and Tools. For each primitive, it details its control mechanism (user or application/model), a brief description of its purpose, and typical example use cases within an MCP system. ```APIDOC MCP Primitives: Prompts: Control: User-controlled Description: Interactive templates invoked by user choice Example Use: Slash commands, menu options Resources: Control: Application-controlled Description: Contextual data managed by the client application Example Use: File contents, API responses Tools: Control: Model-controlled Description: Functions exposed to the LLM to take actions Example Use: API calls, data updates ``` -------------------------------- ### FastMCP Resource Definition for LLM Data Exposure Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This section illustrates how to define 'resources' in FastMCP, which are used to expose data to Large Language Models (LLMs). Resources function similarly to GET endpoints in a REST API, providing data without significant computation or side effects. Examples include static configuration and dynamic user profiles. ```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}" ``` -------------------------------- ### Mounting FastMCP SSE Server to Existing ASGI Application Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This example demonstrates how to integrate the FastMCP SSE (Server-Sent Events) server with an existing ASGI server, such as Starlette. By mounting `mcp.sse_app()` to a path, you can seamlessly combine FastMCP functionalities with other ASGI applications. ```python from starlette.applications import Starlette from starlette.routes 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()), ] ) ``` -------------------------------- ### Run MCP CLI with uv Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This command executes the MCP command-line interface tool within a uv-managed Python environment, ensuring correct dependency resolution and access to the installed `mcp` package. ```bash uv run mcp ``` -------------------------------- ### FastMCP Image Handling with `Image` Class Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This snippet demonstrates how FastMCP simplifies handling image data using its built-in `Image` class. It shows an example of a tool that takes an image path, processes it (e.g., creates a thumbnail using PIL), and returns the processed image data in a specified format. ```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") ``` -------------------------------- ### FastMCP SQLite Explorer for Database Schema and Queries Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md An example of a FastMCP server that interacts with an SQLite database. It provides a resource to retrieve the database schema and a tool to execute SQL queries safely, demonstrating database integration within an MCP server. ```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)}" ``` -------------------------------- ### FastMCP Context Object for Tool/Resource Capabilities Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This example illustrates how the `Context` object provides tools and resources with access to various FastMCP capabilities. It enables functionalities like logging messages (`ctx.info`) and reporting progress (`ctx.report_progress`) during long-running operations, enhancing user feedback. ```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" ``` -------------------------------- ### FastMCP Tool Definition for LLM Actions Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This snippet demonstrates how to define 'tools' in FastMCP, enabling LLMs to perform actions that involve computation and side effects. Unlike resources, tools are designed for active operations. Examples include calculating BMI and asynchronously fetching weather data using an HTTP client. ```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 ``` -------------------------------- ### Create a Simple MCP Server with Tools and Resources Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This Python snippet demonstrates how to initialize a FastMCP server and define both a callable tool (`add`) and a dynamic resource (`get_greeting`). The `add` tool allows for arithmetic operations, while the `get_greeting` resource provides personalized text based on a URL path. It showcases the basic structure for exposing functionality and data via MCP for LLM interaction. ```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}!" ``` -------------------------------- ### MCP Server Initialization Capabilities and Feature Flags Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This API documentation describes the various capabilities that an MCP server can declare during its initialization phase. It lists each capability, associated feature flags (if any), and a concise description of the functionality it enables, such as prompt management, resource handling, tool discovery, logging, and argument completion. ```APIDOC Server Capabilities: prompts: Feature Flag: listChanged Description: Prompt template management resources: Feature Flag: subscribe, listChanged Description: Resource exposure and updates tools: Feature Flag: listChanged Description: Tool discovery and execution logging: Feature Flag: - Description: Server logging configuration completion: Feature Flag: - Description: Argument completion suggestions ``` -------------------------------- ### Initialize FastMCP Server with Lifespan Support (Partial) Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This Python snippet illustrates the basic initialization of a `FastMCP` server instance, named 'My App'. It includes imports for `asynccontextmanager` and `dataclass`, indicating preparation for managing server lifecycle events (startup/shutdown) and using strong typing for context, although the full lifespan implementation is not provided in this excerpt. ```python # Add lifespan support for startup/shutdown with strong typing from contextlib import asynccontextmanager from dataclasses import dataclass from typing import AsyncIterator 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") ``` -------------------------------- ### Low-Level MCP Server Lifespan Management Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md Illustrates advanced server control using the low-level MCP server implementation. It demonstrates how to manage server startup and shutdown lifecycle with an `asynccontextmanager` for resource initialization and cleanup, and how to access these initialized resources within request handlers. ```python from contextlib import asynccontextmanager from typing 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"]) ``` -------------------------------- ### FastMCP Echo Server with Resources, Tools, and Prompts Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md A simple FastMCP server demonstrating the creation of resources, tools, and prompts to echo messages. It showcases the basic decorators (`@mcp.resource`, `@mcp.tool`, `@mcp.prompt`) for defining different interaction types within the MCP framework. ```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}" ``` -------------------------------- ### Configure Stdio Server Parameters for MCP in Python Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This Python snippet demonstrates how to initialize `StdioServerParameters` to define the executable command and optional arguments for an MCP server running over standard I/O. It sets up the basic connection configuration for the server process. ```python server_params = StdioServerParameters( command="python", # Executable args=["example_server.py"], # Optional command line arguments env=None, # Optional environment variables ) ``` -------------------------------- ### Direct Execution of FastMCP Server Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This snippet shows how to run the FastMCP server directly, which is useful for advanced scenarios like custom deployments. It includes a Python script that initializes and runs the server, along with corresponding bash commands for execution. ```python from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") if __name__ == "__main__": mcp.run() ``` ```bash python server.py # or mcp run server.py ``` -------------------------------- ### Mounting Starlette Application as Host Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md Demonstrates how to dynamically mount a Starlette application as a host route using the `Host` class from Starlette's routing module. This allows an application to respond to requests for a specific hostname. ```python app.router.routes.append(Host('mcp.acme.corp', app=mcp.sse_app())) ``` -------------------------------- ### FastMCP Application Lifespan Management with Type-Safe Context Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This snippet demonstrates how to define application dependencies, manage the server's lifecycle using an asynchronous context manager for startup and shutdown operations, and access a type-safe application context within your tools. It ensures resources like database connections are properly initialized and cleaned up. ```python 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() ``` -------------------------------- ### FastMCP Prompt Definition for Reusable LLM Templates Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This section shows how to create reusable prompt templates in FastMCP, which help LLMs interact with your server more effectively. Prompts can be simple string formats or more complex structures involving multiple message types for conversational flows. ```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?"), ] ``` -------------------------------- ### Test MCP Server with MCP Inspector Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This command runs the `server.py` MCP server in development mode, enabling real-time testing and inspection using the MCP Inspector tool. It's useful for debugging and verifying server functionality locally. ```bash mcp dev server.py ``` -------------------------------- ### Running FastMCP Server in Development Mode Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md This section provides commands for running your FastMCP server in development mode using the MCP Inspector. This mode is ideal for rapid testing and debugging, allowing you to easily add dependencies or mount local code for live updates. ```bash mcp dev server.py # Add dependencies mcp dev server.py --with pandas --with numpy # Mount local code mcp dev server.py --with-editable . ``` -------------------------------- ### FastMCP Class API Reference Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md The `FastMCP` class is the foundational component for constructing Model Context Protocol (MCP) servers in Python. It is responsible for managing client connections, ensuring adherence to the MCP specification, and routing messages to defined resources, tools, and prompts. This entry outlines its core purpose and constructor. ```APIDOC FastMCP: Description: Core interface for building MCP servers. Responsibilities: - Connection management - Protocol compliance - Message routing Constructor: __init__(self, name: str) name (str): A unique name for the MCP server instance. ``` -------------------------------- ### Implement Asynchronous Sampling Callback for MCP Messages in Python Source: https://github.com/cris-0k/mcp-server-python-template/blob/main/protocals/sdk.md The `handle_sampling_message` asynchronous function serves as a callback for processing incoming `CreateMessageRequestParams`. It illustrates how to construct and return a `CreateMessageResult` with assistant content, model information, and a stop reason, simulating a model's response. ```python 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", ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.