mirror of
https://github.com/aljazceru/mcp-python-sdk.git
synced 2025-12-19 23:04:25 +01:00
249 lines
8.3 KiB
Markdown
249 lines
8.3 KiB
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
|
|
|
|
- [Overview](#overview)
|
|
- [Installation](#installation)
|
|
- [Writing MCP Servers](#writing-mcp-servers)
|
|
- [FastMCP (Recommended)](#fastmcp-recommended)
|
|
- [Low-Level Server (Advanced)](#low-level-server-advanced)
|
|
- [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
|
|
|
|
We recommend the use of [uv](https://docs.astral.sh/uv/) to manage your Python projects:
|
|
|
|
```bash
|
|
uv add mcp
|
|
```
|
|
|
|
Alternatively, add mcp to your `requirements.txt`:
|
|
```
|
|
pip install mcp
|
|
# or add to requirements.txt
|
|
pip install -r requirements.txt
|
|
```
|
|
|
|
## Writing MCP Servers
|
|
|
|
The MCP Python SDK provides two ways to implement servers:
|
|
|
|
### FastMCP (Recommended)
|
|
|
|
FastMCP provides a high-level, Pythonic interface for building MCP servers quickly and easily. It handles all the complex protocol details so you can focus on building great tools:
|
|
|
|
```python
|
|
from mcp.server.fastmcp import FastMCP
|
|
|
|
mcp = FastMCP("Demo")
|
|
|
|
@mcp.tool()
|
|
def add(a: int, b: int) -> int:
|
|
"""Add two numbers"""
|
|
return a + b
|
|
|
|
@mcp.resource("greeting://{name}")
|
|
def get_greeting(name: str) -> str:
|
|
"""Get a personalized greeting"""
|
|
return f"Hello, {name}!"
|
|
```
|
|
|
|
FastMCP features:
|
|
- Simple, decorator-based API
|
|
- Automatic type handling and validation
|
|
- Built-in support for async functions
|
|
- Progress reporting and logging
|
|
- Resource templating
|
|
- Image handling
|
|
|
|
### Low-Level Server (Advanced)
|
|
|
|
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:
|
|
|
|
```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())
|
|
```
|
|
|
|
## Writing MCP Clients
|
|
|
|
The SDK provides a high-level client interface for connecting to MCP servers:
|
|
|
|
```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
|
|
resource = 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. |