Model Context Protocol SDK for building MCP servers and clients in Python
npx @tessl/cli install tessl/pypi-mcp@1.13.0A comprehensive Python SDK for the Model Context Protocol (MCP), an open-source standard for connecting AI applications to external systems. The SDK enables developers to build both MCP servers that expose resources, tools, and prompts to AI systems, and MCP clients that can interact with these servers.
pip install mcpimport mcpFor client operations:
from mcp import ClientSession, ClientSessionGroup, stdio_client, StdioServerParametersFor server operations:
from mcp.server import FastMCP, ServerFor type definitions:
from mcp import (
Tool, Resource, Prompt,
CallToolRequest, GetPromptRequest, ReadResourceRequest,
McpError
)import asyncio
from mcp import ClientSession, stdio_client, StdioServerParameters
async def client_example():
# Connect to an MCP server
server_params = StdioServerParameters(command="my-mcp-server")
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the session
await session.initialize()
# List available tools
tools = await session.list_tools()
print(f"Available tools: {[tool.name for tool in tools.tools]}")
# Call a tool
result = await session.call_tool("example_tool", {"param": "value"})
print(f"Tool result: {result}")
# List and read resources
resources = await session.list_resources()
if resources.resources:
content = await session.read_resource(resources.resources[0].uri)
print(f"Resource content: {content}")
asyncio.run(client_example())from mcp.server import FastMCP
import asyncio
# Create server instance
app = FastMCP("example-server")
@app.tool()
async def calculate_sum(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
@app.resource("config://settings")
async def get_settings() -> str:
"""Get application settings."""
return "setting1=value1\nsetting2=value2"
@app.prompt()
async def greeting_prompt(name: str) -> str:
"""Generate a personalized greeting."""
return f"Hello, {name}! How can I help you today?"
# Run the server
if __name__ == "__main__":
app.run_stdio()The MCP Python SDK is organized around several key components:
Core client functionality for connecting to and interacting with MCP servers, including session management, tool calling, resource access, and prompt handling.
class ClientSession:
async def initialize(self) -> InitializeResult: ...
async def list_tools(self, cursor: str | None = None) -> ListToolsResult: ...
async def call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> CallToolResult: ...
async def list_resources(self, cursor: str | None = None) -> ListResourcesResult: ...
async def read_resource(self, uri: AnyUrl) -> ReadResourceResult: ...
async def list_prompts(self, cursor: str | None = None) -> ListPromptsResult: ...
async def get_prompt(self, name: str, arguments: dict[str, str] | None = None) -> GetPromptResult: ...
class ClientSessionGroup:
async def connect_to_server(self, server_params: ServerParameters) -> ClientSession: ...
async def call_tool(self, name: str, args: dict[str, Any]) -> CallToolResult: ...
@property
def tools(self) -> dict[str, Tool]: ...
@property
def resources(self) -> dict[str, Resource]: ...High-level server framework using decorators for rapid MCP server development, with built-in support for tools, resources, prompts, and HTTP endpoints.
class FastMCP:
def __init__(self, name: str, **kwargs): ...
def tool(self) -> Callable: ...
def resource(self, uri: str) -> Callable: ...
def prompt(self) -> Callable: ...
def get(self, path: str) -> Callable: ...
def post(self, path: str) -> Callable: ...
def run_stdio(self) -> None: ...
async def run_sse(self, host: str = "127.0.0.1", port: int = 8000) -> None: ...
class Context:
@property
def request_id(self) -> str: ...
@property
def client_session(self) -> ServerSession: ...Low-level server implementation providing full control over MCP protocol handling with decorator-based request handlers and custom lifecycle management.
class Server:
def __init__(self, name: str, version: str | None = None, **kwargs): ...
def list_tools(self) -> Callable: ...
def call_tool(self) -> Callable: ...
def list_resources(self) -> Callable: ...
def read_resource(self) -> Callable: ...
def list_prompts(self) -> Callable: ...
def get_prompt(self) -> Callable: ...
async def run(self, read_stream, write_stream, options: InitializationOptions) -> None: ...
class NotificationOptions:
def __init__(self, tools_changed: bool = True, resources_changed: bool = True, **kwargs): ...Transport layer implementations for various connection types including stdio, HTTP, WebSocket, and streaming protocols with authentication and security features.
def stdio_client(server: StdioServerParameters) -> AsyncContextManager: ...
def stdio_server() -> AsyncContextManager: ...
class StdioServerParameters:
def __init__(self, command: str | list[str], **kwargs): ...
def websocket_client(url: str, **kwargs) -> AsyncContextManager: ...
def sse_client(url: str, **kwargs) -> AsyncContextManager: ...
def streamablehttp_client(url: str, **kwargs) -> AsyncContextManager: ...OAuth 2.0 authentication, bearer token verification, transport security settings, and middleware for protecting MCP server endpoints.
class AuthSettings:
def __init__(
self,
client_id: str,
client_secret: str,
authorization_endpoint: str,
token_endpoint: str,
**kwargs
): ...
class TokenVerifier:
async def verify_token(self, token: str) -> dict[str, Any]: ...
class TransportSecuritySettings:
def __init__(self, dns_rebinding_protection: bool = True, **kwargs): ...Complete MCP protocol type definitions including requests, responses, notifications, capabilities, and data models for tools, resources, and prompts.
# Core Protocol Types
class InitializeRequest(BaseModel): ...
class InitializeResult(BaseModel): ...
class Tool(BaseModel): ...
class Resource(BaseModel): ...
class Prompt(BaseModel): ...
# Content Types
class TextContent(BaseModel): ...
class ImageContent(BaseModel): ...
class EmbeddedResource(BaseModel): ...
# Capabilities
class ClientCapabilities(BaseModel): ...
class ServerCapabilities(BaseModel): ...
# Exceptions
class McpError(Exception): ...Command-line interface for MCP development, testing, and debugging with tools for server inspection and protocol validation.
# Available via CLI
mcp --help
mcp server inspect <server-command>
mcp client connect <server-params>