MCP API¶
This section documents the Model Context Protocol (MCP) implementation, including server interfaces and session management.
Model Context Protocol (MCP) Package |
|
MCP Servers Package |
|
Session management for MCP servers. |
MCP Server Protocol¶
MCP Server Protocol Module
This module defines the abstract base class for Model Context Protocol servers. It provides a standardized interface for different server implementations to connect to external resources, list available tools, and invoke tools.
- class MCPServerProtocol[source]¶
Bases:
BaseModel
,ABC
Abstract base class defining the protocol for MCP servers.
This class establishes the common interface that all MCP server implementations must adhere to, including connection management, tool discovery, resource listing, and tool invocation.
Implementing classes must provide concrete implementations for all abstract methods defined in this interface.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- abstract property name: str¶
Get a readable name for the server.
- Returns:
A human-readable name identifying the server.
- Return type:
- list_resource_contents(uri)[source]¶
- Parameters:
uri (str)
- Return type:
Sequence[TextResourceContents | BlobResourceContents]
- abstractmethod async connect_async()[source]¶
Connect to the MCP server.
Establishes a connection to the server, which might involve spawning a subprocess, opening a network connection, or other initialization steps. The server is expected to remain connected until cleanup() is called.
- Returns:
None
- Raises:
ConnectionError – If connection cannot be established.
- Return type:
None
- abstractmethod async cleanup_async()[source]¶
Clean up the server connection.
Performs necessary cleanup operations such as closing a subprocess, terminating a network connection, or releasing other resources.
- Returns:
None
- Return type:
None
- abstractmethod async list_tools_async()[source]¶
List the tools available on the server.
Retrieves a list of tools that are available for use through this server.
- Returns:
A sequence of Tool objects describing the available tools.
- Return type:
Sequence[Tool]
- Raises:
ConnectionError – If the server is not connected.
- abstractmethod async list_resources_async()[source]¶
List the resources available on the server.
Retrieves a list of resources that are available through this server.
- Returns:
A sequence of Resource objects describing the available resources.
- Return type:
Sequence[Resource]
- Raises:
ConnectionError – If the server is not connected.
- abstractmethod async list_resource_contents_async(uri)[source]¶
List the contents of a specific resource.
Retrieves the contents of a resource identified by its URI.
- Parameters:
uri (str) – The URI of the resource to retrieve contents for.
- Returns:
A sequence of resource content objects, which can be either text or binary data.
- Return type:
Sequence[TextResourceContents | BlobResourceContents]
- Raises:
ConnectionError – If the server is not connected.
ValueError – If the URI is invalid or the resource does not exist.
- abstractmethod async call_tool_async(tool_name, arguments)[source]¶
Invoke a tool on the server.
Calls a specified tool with the provided arguments and returns the result.
- Parameters:
- Returns:
The result of the tool invocation.
- Return type:
CallToolResult
- Raises:
ConnectionError – If the server is not connected.
ValueError – If the tool does not exist or the arguments are invalid.
Streamable HTTP MCP Server¶
Streamable HTTP implementation of the Model Context Protocol (MCP) server client.
This module provides an HTTP client implementation for interacting with MCP servers using the Streamable HTTP transport as defined in the MCP 2025-03-26 specification. It enables connection management, tool discovery, resource querying, and tool execution through a standardized MCP endpoint.
The implementation follows the MCPServerProtocol interface and uses httpx for asynchronous HTTP communication.
- class StreamableHTTPMCPServer(*, server_name, server_url, mcp_endpoint='/mcp', headers=<factory>, timeout_s=100.0, session_manager=<factory>)[source]¶
Bases:
MCPServerProtocol
Streamable HTTP implementation of the MCP (Model Context Protocol) server client.
This class provides a client implementation for interacting with remote MCP servers over HTTP using the Streamable HTTP transport (MCP 2025-03-26 spec). It supports both regular and streaming responses, session management, and handles connection management, tool discovery, resource management, and tool execution.
- Parameters:
server_name (str)
server_url (str)
headers (MutableMapping[str, str])
timeout_s (float)
session_manager (SessionManager)
- server_url¶
The base URL of the HTTP server
- Type:
AnyUrl
- session_manager¶
Manager for storing session information
- Type:
- Usage:
server = StreamableHTTPMCPServer(server_name=”Example MCP”, server_url=”http://example.com”, mcp_endpoint=”/mcp”) await server.connect() tools = await server.list_tools() result = await server.call_tool(“tool_name”, {“param”: “value”}) await server.cleanup()
- session_manager: SessionManager¶
- property name: str¶
Get a readable name for the server.
- Returns:
The human-readable server name
- Return type:
- async connect_async()[source]¶
Connect to the HTTP MCP server and initialize the MCP protocol.
Establishes an HTTP client connection to the server and performs the initialization handshake as defined in the MCP specification.
- Raises:
ConnectionError – If the connection to the server cannot be established
- Return type:
None
- async cleanup_async()[source]¶
Clean up the server connection.
Closes the HTTP client connection if it exists. If a session ID was established, attempts to terminate the session with a DELETE request.
- Returns:
None
- Return type:
None
- async list_tools_async()[source]¶
List the tools available on the server.
- Returns:
A list of Tool objects available on the server
- Return type:
Sequence[Tool]
- Raises:
ConnectionError – If the server is not connected
httpx.RequestError – If there’s an error during the HTTP request
- async list_resources_async()[source]¶
List the resources available on the server.
- Returns:
A list of Resource objects available on the server
- Return type:
Sequence[Resource]
- Raises:
ConnectionError – If the server is not connected
httpx.RequestError – If there’s an error during the HTTP request
- async list_resource_contents_async(uri)[source]¶
List contents of a specific resource.
- Parameters:
uri (str) – The URI of the resource to retrieve contents for
- Returns:
A list of resource contents
- Return type:
Sequence[TextResourceContents | BlobResourceContents]
- Raises:
ConnectionError – If the server is not connected
httpx.RequestError – If there’s an error during the HTTP request
- async call_tool_async(tool_name, arguments)[source]¶
Invoke a tool on the server.
- Parameters:
- Returns:
The result of the tool invocation
- Return type:
CallToolResult
- Raises:
ConnectionError – If the server is not connected
httpx.RequestError – If there’s an error during the HTTP request
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)¶
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self (BaseModel) – The BaseModel instance.
context (Any) – The context.
- Return type:
None
Stdio MCP Server¶
Stdio implementation of the Model Context Protocol (MCP) server client.
This module provides a client implementation for interacting with MCP servers over standard input/output streams. It enables connection management, tool discovery, resource querying, and tool execution through stdin/stdout communication.
The implementation follows the MCPServerProtocol interface and uses asyncio streams for communication.
- class StdioMCPServer(*, server_name, command, server_env=<factory>, working_dir=None, request_timeout_s=100.0)[source]¶
Bases:
MCPServerProtocol
Stdio implementation of the MCP (Model Context Protocol) server client.
This class provides a client implementation for interacting with MCP servers over standard input/output streams. It handles connection management, tool discovery, resource management, and tool invocation through stdin/stdout communication.
- Parameters:
- Usage:
- server = StdioMCPServer(
server_name=”Example MCP”, command=”path/to/server”, server_env={“DEBUG”: “1”}, working_dir=”/path/to/working/dir”
) await server.connect() tools = await server.list_tools() result = await server.call_tool(“tool_name”, {“param”: “value”}) await server.cleanup()
- async connect_async()[source]¶
Connect to the MCP server over stdin/stdout.
Launches the server process and sets up communication channels. Initializes the MCP protocol.
- Raises:
ConnectionError – If the server process cannot be started
TimeoutError – If the initialization takes too long
- Return type:
None
- property name: str¶
Get a readable name for the server.
- Returns:
The human-readable server name
- Return type:
- async cleanup_async()[source]¶
Clean up the server connection.
Terminates the server process and cleans up resources.
- Return type:
None
- async list_tools_async()[source]¶
List the tools available on the server.
- Returns:
A list of Tool objects available on the server
- Return type:
Sequence[Tool]
- Raises:
ConnectionError – If the server is not connected
- async list_resources_async()[source]¶
List the resources available on the server.
- Returns:
A list of Resource objects available on the server
- Return type:
Sequence[Resource]
- Raises:
ConnectionError – If the server is not connected
- async list_resource_contents_async(uri)[source]¶
List contents of a specific resource.
- Parameters:
uri (str) – The URI of the resource to retrieve contents for
- Returns:
A list of resource contents
- Return type:
Sequence[TextResourceContents | BlobResourceContents]
- Raises:
ConnectionError – If the server is not connected
- async call_tool_async(tool_name, arguments)[source]¶
Invoke a tool on the server.
- Parameters:
- Returns:
The result of the tool invocation
- Return type:
CallToolResult
- Raises:
ConnectionError – If the server is not connected
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)¶
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self (BaseModel) – The BaseModel instance.
context (Any) – The context.
- Return type:
None
Session Management¶
Abstract base class defining the interface for MCP session management.
This module provides the interface that all session management implementations must follow, ensuring consistent behavior across different storage backends.
- class SessionManager[source]¶
Bases:
ABC
Abstract base class for MCP session management.
This class defines the interface that all session management implementations must implement to handle MCP session data across requests and potentially across different processes.
- abstractmethod async get_session(server_key)[source]¶
Retrieve session information for a specific server.
- abstractmethod async store_session(server_key, session_data)[source]¶
Store session information for a specific server.
In-memory implementation of the MCP session manager.
This module provides a thread-safe in-memory session manager implementation suitable for use in single-process applications.
- class InMemorySessionManager[source]¶
Bases:
SessionManager
Thread-safe in-memory implementation of the SessionManager interface.
This implementation stores session data in an in-memory dictionary and uses a threading lock to ensure thread safety. It is suitable for single-process applications but will not share session data across multiple processes or workers.
- async store_session(server_key, session_data)[source]¶
Store session information for a specific server.
Redis-based implementation of the MCP session manager.
This module provides a Redis-backed session manager implementation suitable for use in multi-process applications and production environments.
- class RedisSessionManager(redis_url='redis://localhost:6379/0', key_prefix='mcp_session:', expiration_seconds=3600)[source]¶
Bases:
SessionManager
Redis-backed implementation of the SessionManager interface.
This implementation stores session data in Redis, making it suitable for use in multi-process applications and production environments where session data needs to be shared across multiple workers.
- __init__(redis_url='redis://localhost:6379/0', key_prefix='mcp_session:', expiration_seconds=3600)[source]¶
Initialize the Redis session manager.
- async get_session(server_key)[source]¶
Retrieve session information for a specific server from Redis.
- async store_session(server_key, session_data)[source]¶
Store session information for a specific server in Redis.