API Reference
Protocols
Section titled “Protocols”MCPClientTransport
Section titled “MCPClientTransport”Protocol for outbound MCP transports.
A transport is responsible for sending JSON-RPC requests to an external MCP server and returning the parsed JSON-RPC response. Each call maps to one logical request-response pair; the transport handles any framing details (length-delimited lines, HTTP bodies, etc.).
Open the underlying connection (spawn process, open socket, etc.).
Close the underlying connection and free resources.
Write a JSON-RPC message to the server.
| Parameter | Type | Description |
|---|---|---|
| `message` | dict[str, Any] | Fully-formed JSON-RPC request or notification dict. |
Read and return the next JSON-RPC message from the server.
| Type | Description |
|---|---|
| dict[str, Any] | Parsed JSON-RPC response dict. |
| Exception | Description |
|---|---|
| MCPTransportError | On I/O failure or malformed data. |
MCPPromptHandler
Section titled “MCPPromptHandler”Protocol for handling MCP prompt-related methods.
Handles prompts/list and prompts/get methods.
Handle prompts/list method.
Returns list of available prompt templates.
Handle prompts/get method.
Returns a prompt with arguments filled in.
MCPPromptProviderProtocol
Section titled “MCPPromptProviderProtocol”Protocol for providing prompt templates to the MCP server.
List available prompt templates.
Get a prompt template with arguments filled.
MCPResourceHandler
Section titled “MCPResourceHandler”Protocol for handling MCP resource-related methods.
Handles resources/list, resources/read, and resources/templates/list.
Handle resources/list method.
Returns list of available resources.
Handle resources/read method.
Returns content of a specific resource.
Handle resources/templates/list method.
Returns list of URI templates for resources.
MCPResourceProviderProtocol
Section titled “MCPResourceProviderProtocol”Protocol for providing resources to the MCP server.
Resources are data that AI clients can browse and read — database records, files, configuration, etc.
List available resources in MCP format.
Read a resource by URI.
MCPServerProtocol
Section titled “MCPServerProtocol”Protocol for the MCP server.
The server routes JSON-RPC messages to handlers and returns JSON-RPC responses.
Handle a JSON-RPC message and return the response.
Returns None for notifications (no response expected).
MCPToolHandler
Section titled “MCPToolHandler”Protocol for handling MCP tool-related methods.
Handles tools/list and tools/call methods.
Handle tools/list method.
Returns list of available tools with their definitions.
Handle tools/call method.
Executes a tool and returns the result.
MCPToolProviderProtocol
Section titled “MCPToolProviderProtocol”Protocol for providing tools to the MCP server.
Satisfied by:
ToolRegistryAdapter(bridges lexigram-agents ToolRegistry)- Any custom tool provider
List all available tools in MCP format.
Returns list of dicts with name, description,
inputSchema keys.
Execute a tool by name with given arguments.
MCPTransportProtocol
Section titled “MCPTransportProtocol”Protocol for MCP transport implementations.
A transport handles the I/O layer — reading requests and writing responses. The MCP server is transport-agnostic.
Classes
Section titled “Classes”AbstractTransport
Section titled “AbstractTransport”Abstract base class for MCP transport implementations.
A transport handles the I/O layer - reading requests and writing responses. The MCP server is transport-agnostic.
Start the transport.
Stop the transport.
Send a message through the transport.
| Parameter | Type | Description |
|---|---|---|
| `message` | dict[str, Any] | JSON-RPC message to send. |
Receive a message from the transport.
| Type | Description |
|---|---|
| dict[str, Any] | None | Parsed JSON-RPC message, or None if no message available. |
ControllerPromptProvider
Section titled “ControllerPromptProvider”MCPPromptProviderProtocol backed by a list of MCPController instances.
Aggregates all @prompt-decorated methods and dispatches
get_prompt calls to the matching handler.
def __init__(controller_instances: list[MCPController]) -> None
Initialize with a list of already-constructed controller instances.
| Parameter | Type | Description |
|---|---|---|
| `controller_instances` | list[MCPController] | Instantiated MCPController objects to aggregate. |
List all prompt templates from registered controllers in MCP format.
| Type | Description |
|---|---|
| list[dict[str, Any]] | MCP prompt definitions with ``name``, ``description``, ``arguments``. |
Get a prompt template by name with arguments filled in.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Prompt name. |
| `arguments` | dict[str, Any] | None | Optional arguments dict from the MCP client. |
| Type | Description |
|---|---|
| dict[str, Any] | MCP-format prompt response with ``description`` and ``messages``. |
| Exception | Description |
|---|---|
| MCPPromptError | If no prompt with the given name is registered. |
ControllerResourceProvider
Section titled “ControllerResourceProvider”MCPResourceProviderProtocol backed by a list of MCPController instances.
Aggregates all @resource-decorated methods, exposes them for listing,
and routes read_resource calls via URI pattern matching.
def __init__(controller_instances: list[MCPController]) -> None
Initialize with a list of already-constructed controller instances.
| Parameter | Type | Description |
|---|---|---|
| `controller_instances` | list[MCPController] | Instantiated MCPController objects to aggregate. |
List all resources from all registered controllers in MCP format.
| Type | Description |
|---|---|
| list[dict[str, Any]] | MCP resource definitions with ``uri``, ``name``, ``description``. |
Read a resource by URI, matching exact URIs and {var} patterns.
| Parameter | Type | Description |
|---|---|---|
| `uri` | str | Concrete URI from the MCP client (e.g. ``"users://123"``). |
| Type | Description |
|---|---|
| dict[str, Any] | Resource content dict. |
| Exception | Description |
|---|---|
| MCPResourceError | If no resource pattern matches the given URI. |
List URI templates for resources that contain {var} placeholders.
| Type | Description |
|---|---|
| list[dict[str, Any]] | MCP URI template definitions with ``uriTemplate``, ``name``, ``description``. |
ControllerToolProvider
Section titled “ControllerToolProvider”MCPToolProviderProtocol backed by a list of MCPController instances.
Aggregates all @tool-decorated methods across multiple controllers,
auto-generates JSON Schema from type annotations, and dispatches
call_tool to the matching handler.
def __init__(controller_instances: list[MCPController]) -> None
Initialize with a list of already-constructed controller instances.
| Parameter | Type | Description |
|---|---|---|
| `controller_instances` | list[MCPController] | Instantiated MCPController objects to aggregate. |
List all tools from all registered controllers in MCP format.
| Type | Description |
|---|---|
| list[dict[str, Any]] | MCP tool definitions with ``name``, ``description``, ``inputSchema``. |
Dispatch a tool call to the matching controller method.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | MCP tool name. |
| `arguments` | dict[str, Any] | Argument dict from the MCP client. |
| Type | Description |
|---|---|
| Any | Handler return value. |
| Exception | Description |
|---|---|
| MCPToolCallError | If no tool with the given name is registered. |
MCPClient
Section titled “MCPClient”Client for connecting to and calling tools on external MCP servers.
Manages the MCP protocol handshake (initialize / initialized
notification) and exposes ergonomic methods for the most common MCP
operations. The underlying MCPClientTransport handles the I/O;
see StdioClientTransport and SSEClientTransport.
Supports async context manager usage for automatic lifecycle management
async with MCPClient(transport) as client: tools = await client.list_tools()| Parameter | Type | Description |
|---|---|---|
| `transport` | The transport to use for server communication. | |
| `request_timeout` | Per-request wait timeout in seconds. If a response is not received within this window a :exc:`~lexigram.ai.mcp.exceptions.MCPTransportError` is raised. |
def __init__( transport: MCPClientTransport, *, request_timeout: float = 30.0 ) -> None
Connect the transport and perform the MCP initialize handshake.
| Exception | Description |
|---|---|
| MCPInitializationError | If the server rejects the handshake. |
| MCPTransportError | On transport-level failures. |
Close the transport connection.
Return the list of tools exposed by the server.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of MCP tool definition dicts, each with ``name``, ``description``, and ``inputSchema``. |
Call a tool by name on the server.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Tool name as returned by list_tools. |
| `arguments` | dict[str, Any] | None | Tool input arguments. Pass ``None`` for tools that take no parameters. |
| Type | Description |
|---|---|
| Any | The ``result`` field from the server's JSON-RPC response. |
| Exception | Description |
|---|---|
| MCPToolCallError | If the server returns an error for the tool call. |
Return the list of resources exposed by the server.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of MCP resource dicts, each with ``uri``, ``name``, ``description``, and ``mimeType``. |
Return the list of prompt templates exposed by the server.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of MCP prompt dicts, each with ``name``, ``description``, and ``arguments``. |
MCPClientModule
Section titled “MCPClientModule”Module for consuming external MCP servers via DI-injected clients.
Registers one or more MCPClient instances (wrapped in an MCPClientRegistry) so any service in the application can call external MCP tools.
Use configure to configure connections
app = LexigramApplication( modules=[ MCPClientModule.configure( connections=[ MCPConnection.stdio( ["uvx", "mcp-server-git"], name="git", ), ] ), ],)def __init__(connections: list[MCPConnection] | None = None) -> None
def configure( cls, connections: list[MCPConnection] ) -> MCPClientModule
Create an MCPClientModule for the given connections.
| Parameter | Type | Description |
|---|---|---|
| `connections` | list[MCPConnection] | List of MCPConnection objects describing each external MCP server. Each must have a unique *name*. |
| Type | Description |
|---|---|
| MCPClientModule | An ``MCPClientModule`` ready to be added to the application. |
| Exception | Description |
|---|---|
| ValueError | If *connections* is empty or contains duplicate names. |
Example
MCPClientModule.configure( connections=[ MCPConnection.stdio(["npx", "github-mcp"], name="github"), MCPConnection.sse("http://localhost:9000/mcp", name="local"), ],)Return the DI providers for this module.
MCPClientProvider
Section titled “MCPClientProvider”
def __init__(connections: list[MCPConnection]) -> None
async def register(container: ContainerRegistrarProtocol) -> None
Register MCPClientRegistry (and a single MCPClient if one connection).
async def boot(container: ContainerResolverProtocol) -> None
Boot hook for MCP client provider.
Shutdown MCP client provider resources.
MCPClientRegistry
Section titled “MCPClientRegistry”Registry of named MCPClient instances.
Registered in the DI container by MCPClientModule. Inject this in services that need to call multiple external MCP servers
class ReportService: def __init__(self, registry: MCPClientRegistry) -> None: self._git = registry.get("git") self._analytics = registry.get("analytics")Call MCPClient.connect before making requests (or use the client as an async context manager for automatic lifecycle management).
def __init__(clients: dict[str, MCPClient]) -> None
Initialize with a pre-built mapping of names → clients.
| Parameter | Type | Description |
|---|---|---|
| `clients` | dict[str, MCPClient] | Dict mapping each connection name to its MCPClient instance. |
def get(name: str) -> MCPClient
Return the client registered under name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | The connection name passed to MCPConnection.stdio or MCPConnection.sse. |
| Exception | Description |
|---|---|
| KeyError | If no client was registered with the given *name*. |
Return the names of all registered connections.
| Type | Description |
|---|---|
| list[str] | Sorted list of registered connection names. |
MCPConfig
Section titled “MCPConfig”Configuration for the MCP server.
Attributes: host: Host to bind to (for HTTP transport). port: Port to bind to (for HTTP transport). path: URL path for MCP endpoint (default /mcp). enable_sse: Enable Server-Sent Events for streaming responses. stdio_mode: Use stdio transport instead of HTTP. server_name: Name of the MCP server. server_version: Version of the MCP server. cors_origins: CORS allowed origins (for HTTP transport).
MCPConnection
Section titled “MCPConnection”Immutable description of one external MCP server connection.
Do not construct directly — use the stdio or sse class methods.
Attributes:
name: Unique identifier for this connection used by
MCPClientRegistry.
transport_type: "stdio" or "sse".
command: (stdio only) Subprocess command to launch the MCP server.
url: (sse only) Base HTTP URL of the MCP server.
env: (stdio only) Optional extra environment variables.
headers: (sse only) Optional extra HTTP headers.
request_timeout: Per-request timeout in seconds (default 30).
startup_timeout: (stdio only) Wait timeout for process start (default 10).
def stdio( cls, command: list[str], *, name: str, env: dict[str, str] | None = None, startup_timeout: float = 10.0, request_timeout: float = 30.0 ) -> MCPConnection
Create a connection that communicates with a stdio-based MCP server.
Spawns command as a subprocess and exchanges newline-delimited JSON-RPC messages over its stdin/stdout.
| Parameter | Type | Description |
|---|---|---|
| `command` | list[str] | The command and arguments to launch the MCP server. |
| `name` | str | Unique name for use with MCPClientRegistry. |
| `env` | dict[str, str] | None | Optional extra environment variables. |
| `startup_timeout` | float | Seconds to wait for process start. |
| `request_timeout` | float | Per-request timeout in seconds. |
| Type | Description |
|---|---|
| MCPConnection | A configured ``MCPConnection`` describing this stdio server. |
Example
MCPConnection.stdio( ["uvx", "mcp-server-git", "--repository", "/repo"], name="git",)def sse( cls, url: str, *, name: str, headers: dict[str, str] | None = None, request_timeout: float = 30.0 ) -> MCPConnection
Create a connection to an HTTP+SSE MCP server.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Base URL of the MCP server (e.g. ``http://localhost:8080/mcp``). |
| `name` | str | Unique name for use with MCPClientRegistry. |
| `headers` | dict[str, str] | None | Optional extra HTTP headers (e.g. auth tokens). |
| `request_timeout` | float | Per-request timeout in seconds. |
| Type | Description |
|---|---|
| MCPConnection | A configured ``MCPConnection`` describing this SSE server. |
Example
MCPConnection.sse( "http://analytics.internal/mcp", name="analytics", headers={"Authorization": "Bearer secret"},)Instantiate and return the appropriate transport for this connection.
| Type | Description |
|---|---|
| Any | A StdioClientTransport or SSEClientTransport instance. |
| Exception | Description |
|---|---|
| ValueError | If *transport_type* is not ``"stdio"`` or ``"sse"``. |
def build_client() -> MCPClient
Build an MCPClient from this connection description.
MCPController
Section titled “MCPController”Base class for MCP controllers.
Groups related MCP tools, resources, and prompt templates into a single
class — mirroring the Controller DX from lexigram-web. Register
decorated subclasses via MCPModule(controllers=[...]).
Example
class DataToolsController(MCPController): def __init__(self, repo: UserRepository) -> None: self.repo = repo
@tool("get_user", description="Fetch a user by ID") async def get_user(self, user_id: str) -> dict: result = await self.repo.get(user_id) return result.unwrap_or({})Collect tool-decorated methods from the class hierarchy.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of dicts with keys ``name``, ``description``, ``handler_name``. |
Collect resource-decorated methods from the class hierarchy.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of dicts with keys ``uri_pattern``, ``name``, ``description``, ``handler_name``. |
Collect prompt-decorated methods from the class hierarchy.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of dicts with keys ``name``, ``description``, ``handler_name``. |
MCPInitializeResult
Section titled “MCPInitializeResult”Result of the initialize method.
MCPJSONRPCRequest
Section titled “MCPJSONRPCRequest”JSON-RPC request message.
MCPJSONRPCResponse
Section titled “MCPJSONRPCResponse”JSON-RPC response message.
Serialize to JSON-RPC format.
def create_success( result: dict[str, Any], request_id: int | str | None = None ) -> MCPJSONRPCResponse
Create a success response.
def create_error( code: int, message: str, request_id: int | str | None = None, data: Any | None = None ) -> MCPJSONRPCResponse
Create an error response.
MCPModule
Section titled “MCPModule”Module for MCP server.
Provides MCP server, handlers, and transports to the application.
Usage
app = LexigramApplication( modules=[..., MCPModule.configure()],)
# With MCPController subclasses::
app = LexigramApplication( modules=[..., MCPModule.configure(controllers=[DataToolsController])],)
# Auto-expose existing services as MCP tools::
app = LexigramApplication( modules=[ ..., MCPModule.from_services( services=[UserService, AnalyticsService], include_methods=["search", "get_*"], ), ],)def from_services( cls, services: list[type], *, include_methods: list[str] | None = None, config: MCPConfig | None = None ) -> DynamicModule
Create an MCPModule that auto-exposes service methods as MCP tools.
| Parameter | Type | Description |
|---|---|---|
| `services` | list[type] | Service classes whose public methods are exposed as tools. |
| `include_methods` | list[str] | None | Optional glob patterns to restrict which methods are exposed (e.g. ``["search", "get_*"]``). |
| `config` | MCPConfig | None | Optional MCPConfig override. |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule descriptor. |
def configure( cls, *, config: MCPConfig | None = None, controllers: list[type] | None = None, services: list[type] | None = None, include_methods: list[str] | None = None, enable_streaming: bool = True, **provider_kwargs: Any ) -> DynamicModule
Create an MCPModule with explicit provider configuration.
| Parameter | Type | Description |
|---|---|---|
| `config` | MCPConfig | None | Optional MCPConfig. |
| `controllers` | list[type] | None | MCPController subclasses to register with the server. |
| `services` | list[type] | None | Service classes to auto-expose as MCP tools. |
| `include_methods` | list[str] | None | Glob patterns to restrict auto-exposed methods. |
| `enable_streaming` | bool | Enable SSE streaming transport support. Defaults to ``True``; set to ``False`` to restrict the server to stdio-only transport. **provider_kwargs: Additional keyword arguments forwarded to MCPProvider. |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule descriptor. |
def stub( cls, config: MCPConfig | None = None ) -> DynamicModule
Create an MCPModule suitable for unit and integration testing.
Uses in-memory transport with no external MCP server connections. Streaming is disabled by default to simplify test assertions.
| Parameter | Type | Description |
|---|---|---|
| `config` | MCPConfig | None | Optional MCPConfig override. Uses safe test defaults when ``None``. |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule descriptor. |
MCPPrompt
Section titled “MCPPrompt”An MCP prompt template that clients can use.
MCPPromptMessage
Section titled “MCPPromptMessage”A message in an MCP prompt response.
MCPProvider
Section titled “MCPProvider”
def __init__( config: MCPConfig | None = None, controllers: list[type] | None = None, services: list[type] | None = None, include_methods: list[str] | None = None, enable_streaming: bool = True, **provider_kwargs: Any ) -> None
async def register(container: ContainerRegistrarProtocol) -> None
Register MCPConfig with the DI container.
Wire up all MCP components using the resolved container.
Clean up MCP provider resources.
Return a health check result for this provider.
| Parameter | Type | Description |
|---|---|---|
| `timeout` | float | Maximum seconds to wait for health response. |
| Type | Description |
|---|---|
| HealthCheckResult | A HealthCheckResult reflecting the current MCP provider state. |
MCPResource
Section titled “MCPResource”An MCP resource that clients can browse and read.
MCPResourceContent
Section titled “MCPResourceContent”Content of an MCP resource returned to the client.
MCPServer
Section titled “MCPServer”Core MCP server — routes JSON-RPC messages to handlers.
The server is transport-agnostic. It receives parsed JSON-RPC messages and returns JSON-RPC responses. The transport layer (stdio or HTTP+SSE) handles serialization and I/O.
Usage
server = MCPServer( name="my-app", tool_handler=tool_handler, resource_handler=resource_handler,)response = await server.handle_message(request)def __init__( config: Any | None = None, name: str | None = None, version: str | None = None, tool_handler: Any | None = None, resource_handler: Any | None = None, prompt_handler: Any | None = None, sampling_handler: Any | None = None, logging_handler: Any | None = None ) -> None
Initialize the MCP server.
| Parameter | Type | Description |
|---|---|---|
| `config` | Any | None | Optional MCP server configuration. |
| `name` | str | None | Server name (overrides config if provided). |
| `version` | str | None | Server version (overrides config if provided). |
| `tool_handler` | Any | None | Handler for tool-related methods. |
| `resource_handler` | Any | None | Handler for resource-related methods. |
| `prompt_handler` | Any | None | Handler for prompt-related methods. |
| `sampling_handler` | Any | None | Handler for sampling/createMessage (optional). |
| `logging_handler` | Any | None | Handler for logging/setLevel (optional). |
Handle a JSON-RPC message and return the response.
| Parameter | Type | Description |
|---|---|---|
| `message` | dict[str, Any] | Parsed JSON-RPC request message. |
| Type | Description |
|---|---|
| dict[str, Any] | None | JSON-RPC response dict, or None for notifications. |
MCPServerCapabilities
Section titled “MCPServerCapabilities”Server capabilities sent during initialization.
MCPServerInfo
Section titled “MCPServerInfo”Server metadata sent during initialization.
MCPServerStartedHook
Section titled “MCPServerStartedHook”Payload fired after the MCP server completes its startup sequence.
Attributes:
transport: Transport type in use (e.g. "stdio" or "sse").
MCPServerStoppedHook
Section titled “MCPServerStoppedHook”Payload fired after the MCP server shuts down.
Attributes: transport: Transport type that was in use at shutdown.
MCPToolDefinition
Section titled “MCPToolDefinition”MCP tool definition sent to clients during tools/list.
Maps directly to the MCP tool schema format.
MCPToolInvokedHook
Section titled “MCPToolInvokedHook”Payload fired each time a tool is invoked through the MCP protocol.
Attributes: tool_name: Name of the MCP tool that was called.
ModulePromptProvider
Section titled “ModulePromptProvider”Prompt provider built from module-level ``@prompt``-decorated functions.
Use from_module to scan a Python module for decorated callables.
Initialize with a list of decorated functions.
| Parameter | Type | Description |
|---|---|---|
| `funcs` | list[Any] | Callables that have ``_prompt_config`` set by ``@prompt()``. |
def from_module( cls, module: Any ) -> ModulePromptProvider
Scan module for @prompt-decorated functions.
| Parameter | Type | Description |
|---|---|---|
| `module` | Any | A Python module object. |
| Type | Description |
|---|---|
| ModulePromptProvider | A new ``ModulePromptProvider`` with all discovered prompts. |
Return all registered prompt definitions.
Return a prompt by name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Prompt name. |
| `arguments` | dict[str, Any] | None | Optional template arguments. |
| Type | Description |
|---|---|
| Any | MCP prompt response dict. |
| Exception | Description |
|---|---|
| MCPPromptError | If the prompt name is not registered. |
ModuleResourceProvider
Section titled “ModuleResourceProvider”Resource provider built from module-level ``@resource``-decorated functions.
Use from_module to scan a Python module for decorated callables.
Initialize with a list of decorated functions.
| Parameter | Type | Description |
|---|---|---|
| `funcs` | list[Any] | Callables that have ``_resource_config`` set by ``@resource()``. |
def from_module( cls, module: Any ) -> ModuleResourceProvider
Scan module for @resource-decorated functions.
| Parameter | Type | Description |
|---|---|---|
| `module` | Any | A Python module object. |
| Type | Description |
|---|---|
| ModuleResourceProvider | A new ``ModuleResourceProvider`` with all discovered resources. |
Return all registered resource definitions.
Read a resource by URI.
| Parameter | Type | Description |
|---|---|---|
| `uri` | str | Concrete URI from the MCP client. |
| Type | Description |
|---|---|
| Any | Resource content. |
| Exception | Description |
|---|---|
| MCPResourceError | If no resource pattern matches the given URI. |
Return URI templates (resources with {var} placeholders).
ModuleToolProvider
Section titled “ModuleToolProvider”Tool provider built from module-level ``@tool``-decorated functions.
Use from_module to scan a Python module for decorated callables
import my_toolsprovider = ModuleToolProvider.from_module(my_tools)Or pass functions directly
provider = ModuleToolProvider([search_users, create_user])Initialize with a list of decorated functions.
| Parameter | Type | Description |
|---|---|---|
| `funcs` | list[Any] | Callables that have ``_tool_config`` set by ``@tool()``. |
def from_module( cls, module: Any ) -> ModuleToolProvider
Scan module for @tool-decorated functions.
| Parameter | Type | Description |
|---|---|---|
| `module` | Any | A Python module object. |
| Type | Description |
|---|---|
| ModuleToolProvider | A new ``ModuleToolProvider`` with all discovered tools. |
Return MCP tool definitions for all registered functions.
Invoke the tool function by name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Tool name. |
| `arguments` | dict[str, Any] | Arguments dict from the MCP client. |
| Type | Description |
|---|---|
| Any | Tool result. |
| Exception | Description |
|---|---|
| MCPToolCallError | If the tool name is not registered. |
PromptHandler
Section titled “PromptHandler”Handler for MCP prompt-related methods.
Handles prompts/list and prompts/get methods by delegating to an MCPPromptProviderProtocol implementation.
Initialize the prompt handler.
| Parameter | Type | Description |
|---|---|---|
| `prompt_provider` | Any | None | Provider that handles prompt operations. |
Handle prompts/list method.
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | ``Result`` containing prompts list in MCP format. |
async def get_prompt( name: str, arguments: dict[str, Any] | None = None ) -> Result[dict[str, Any], MCPError]
Handle prompts/get method.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Name of the prompt to get. |
| `arguments` | dict[str, Any] | None | Arguments to fill in the prompt template. |
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | ``Result[dict[str, Any], MCPError]`` with prompt payload. |
ResourceHandler
Section titled “ResourceHandler”Handler for MCP resource-related methods.
Handles resources/list, resources/read, and resources/templates/list methods by delegating to an MCPResourceProviderProtocol implementation.
Initialize the resource handler.
| Parameter | Type | Description |
|---|---|---|
| `resource_provider` | Any | None | Provider that handles resource operations. |
Handle resources/list method.
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | ``Result`` containing resources list in MCP format. |
Handle resources/read method.
| Parameter | Type | Description |
|---|---|---|
| `uri` | str | URI of the resource to read. |
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | ``Result[dict[str, Any], MCPError]`` with MCP-formatted contents. |
Handle resources/templates/list method.
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | ``Result`` containing URI templates in MCP format. |
SSEClientTransport
Section titled “SSEClientTransport”MCP client transport that communicates with an HTTP+SSE MCP server.
Sends JSON-RPC requests as HTTP POST bodies and reads the responses from
the response body. Uses aiohttp for async HTTP — ensure it is
installed (pip install aiohttp or the http extra of this package).
| Parameter | Type | Description |
|---|---|---|
| `url` | Base URL of the MCP HTTP endpoint (e.g. ``http://localhost:8080/mcp``). | |
| `headers` | Additional HTTP headers to include with every request (e.g. ``{"Authorization": "Bearer | |
| `request_timeout` | Per-request timeout in seconds. |
def __init__( url: str, *, headers: dict[str, str] | None = None, request_timeout: float = 30.0 ) -> None
Open an aiohttp session.
Close the aiohttp session.
Queue message for the next receive call via HTTP POST.
POST the pending request and return the parsed JSON-RPC response.
SSETransport
Section titled “SSETransport”Server-Sent Events transport for MCP server.
This transport uses HTTP POST for requests and SSE for streaming responses. Ideal for web-based integrations.
Initialize the SSE transport.
| Parameter | Type | Description |
|---|---|---|
| `server` | Any | None | Optional HTTP server instance. |
Start the SSE transport.
Stop the SSE transport.
Send a message via SSE.
| Parameter | Type | Description |
|---|---|---|
| `message` | dict[str, Any] | JSON-RPC message to send. |
| Exception | Description |
|---|---|
| MCPTransportError | If sending fails. |
Receive is not applicable for SSE (pull-based).
For HTTP+SSE, use the HTTP endpoint directly instead.
| Type | Description |
|---|---|
| dict[str, Any] | None | None (receiving is handled via HTTP POST). |
Get queued messages for SSE delivery.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of queued JSON-RPC messages. |
ServiceToolProvider
Section titled “ServiceToolProvider”Tool provider that auto-exposes public methods of service instances as MCP tools.
Created via MCPModule.from_services or directly
provider = ServiceToolProvider.from_services( [user_service, analytics_service], include_patterns=["search", "get_*"],)Tool names are prefixed with the lowercase service class name to avoid
collisions (e.g. UserService.search_users() → "userservice_search_users").
The first line of each method’s docstring is used as the tool description.
Both async def and plain def methods are supported.
Initialize with pre-built tool entries.
| Parameter | Type | Description |
|---|---|---|
| `entries` | list[tuple[Any, str, str, str]] | List of ``(instance, method_name, tool_name, description)`` tuples. |
def from_services( cls, service_instances: Any, include_patterns: list[str] | None = None ) -> ServiceToolProvider
Scan service_instances and expose matching public methods as tools.
| Parameter | Type | Description |
|---|---|---|
| `service_instances` | Any | A single instantiated service object or a list. |
| `include_patterns` | list[str] | None | Glob patterns to filter method names (e.g. ``["search", "get_*"]``). When ``None``, all public non-dunder methods are included. |
| Type | Description |
|---|---|
| ServiceToolProvider | A new ``ServiceToolProvider`` with entries for every matched method. |
Return MCP tool definitions for all discovered service methods.
Invoke the service method mapped to name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Tool name. |
| `arguments` | dict[str, Any] | Arguments dict from the MCP client. |
| Type | Description |
|---|---|
| Any | Method return value (sync or awaited coroutine). |
| Exception | Description |
|---|---|
| MCPToolCallError | If no method is registered under *name*. |
StdioClientTransport
Section titled “StdioClientTransport”MCP client transport that communicates with a subprocess via stdio.
Spawns command as an asyncio subprocess and exchanges newline-delimited JSON-RPC messages over its stdin/stdout pipes.
| Parameter | Type | Description |
|---|---|---|
| `command` | The command and arguments to launch the MCP server process. | |
| `env` | Optional extra environment variables to pass to the subprocess. If *None*, the current process environment is inherited. | |
| `startup_timeout` | Seconds to wait for the process to start before | |
| `raising` | exc:`~lexigram.ai.mcp.exceptions.MCPTransportError`. |
def __init__( command: list[str], *, env: dict[str, str] | None = None, startup_timeout: float = 10.0 ) -> None
Spawn the subprocess.
Terminate the subprocess.
Write a newline-delimited JSON message to the subprocess stdin.
Read a newline-delimited JSON message from subprocess stdout.
StdioTransport
Section titled “StdioTransport”Stdio-based transport for MCP server.
This transport reads JSON-RPC messages from stdin and writes responses to stdout. Ideal for CLI/desktop integration.
def __init__( reader: asyncio.StreamReader | None = None, writer: asyncio.StreamWriter | None = None ) -> None
Initialize the stdio transport.
| Parameter | Type | Description |
|---|---|---|
| `reader` | asyncio.StreamReader | None | Optional stream reader (for testing). |
| `writer` | asyncio.StreamWriter | None | Optional stream writer (for testing). |
Start the stdio transport.
Stop the stdio transport.
Send a message through stdio.
| Parameter | Type | Description |
|---|---|---|
| `message` | dict[str, Any] | JSON-RPC message to send. |
| Exception | Description |
|---|---|
| MCPTransportError | If sending fails. |
Receive a message from stdio.
| Type | Description |
|---|---|
| dict[str, Any] | None | Parsed JSON-RPC message, or None if no data available. |
| Exception | Description |
|---|---|
| MCPTransportError | If receiving fails. |
ToolHandler
Section titled “ToolHandler”Handler for MCP tool-related methods.
Handles tools/list and tools/call methods by delegating to a MCPToolProviderProtocol implementation.
All handler methods return Result so callers can handle expected
failures without raising exceptions.
Initialize the tool handler.
| Parameter | Type | Description |
|---|---|---|
| `tool_provider` | Any | None | Provider that handles tool listing and execution. |
Handle tools/list method.
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | ``Result`` containing tools list in MCP format. |
async def call_tool( name: str, arguments: dict[str, Any] | None = None ) -> Result[dict[str, Any], MCPError]
Handle tools/call method.
Returns a Result — Ok wraps the serialized MCP tool result dict;
Err wraps an MCPToolCallError
describing what went wrong.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Name of the tool to call. |
| `arguments` | dict[str, Any] | None | Arguments to pass to the tool. |
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | ``Result[dict[str, Any], MCPError]`` — never raises expected errors. |
ToolRegistryAdapter
Section titled “ToolRegistryAdapter”Adapter that bridges lexigram-agents ToolRegistry to MCPToolProviderProtocol.
This adapter allows the MCP server to use the @tool-decorated functions from lexigram-agents. The translation is minimal:
ToolProtocol.parameters_schema→ MCPinputSchemaToolRegistryProtocol.get()→ lookup by nameToolProtocol.execute(**kw)→ tool invocation
def __init__(tool_registry: ToolRegistryProtocol | None = None) -> None
List all available tools in MCP format.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of tool definitions with ``name``, ``description``, and ``inputSchema`` (JSON Schema produced by ``@tool``). |
Execute a tool by name with given arguments.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Name of the tool to call. |
| `arguments` | dict[str, Any] | Arguments to pass to the tool. |
| Type | Description |
|---|---|
| Any | Tool execution result. |
Functions
Section titled “Functions”
Register a method as an MCP prompt template handler.
Stores _prompt_config on the decorated method for discovery by
collect_prompts.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | MCP prompt name exposed to AI clients. |
| `description` | str | Human-readable description of the prompt template. |
| Type | Description |
|---|---|
| Any | Decorator that attaches prompt metadata to the method. |
Example
@prompt("summarize", description="Generate a summary prompt")async def summarize_prompt(self) -> str: return "Summarize the following data..."resource
Section titled “resource”
Register a method as an MCP resource handler.
Stores _resource_config on the decorated method for discovery by
collect_resources.
| Parameter | Type | Description |
|---|---|---|
| `uri_pattern` | str | URI template (e.g. ``"users://{user_id}"``). |
| `description` | str | Human-readable description of the resource. |
| `name` | str | None | Optional display name; defaults to the URI pattern. |
| Type | Description |
|---|---|
| Any | Decorator that attaches resource metadata to the method. |
Example
@resource("users://{user_id}", description="Expose user by ID")async def get_user(self, user_id: str) -> dict: ...
Register a method as an MCP tool handler.
Stores _tool_config on the decorated method for discovery by
collect_tools.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | MCP tool name exposed to AI clients. |
| `description` | str | Human-readable description for the tool schema. |
| Type | Description |
|---|---|
| Any | Decorator that attaches tool metadata to the method. |
Example
@tool("search_users", description="Search users by name")async def search_users(self, name: str = "") -> list[dict]: ...Exceptions
Section titled “Exceptions”MCPError
Section titled “MCPError”Base exception for all MCP errors.
MCPInitializationError
Section titled “MCPInitializationError”MCP server initialization failed.
Raised when the MCP server cannot be initialized, usually due to missing required handlers or configuration errors.
MCPMethodNotFoundError
Section titled “MCPMethodNotFoundError”Unknown MCP method requested by client.
Raised when the client requests an MCP method that the server does not support.
MCPPromptError
Section titled “MCPPromptError”Prompt retrieval or list failed.
Raised when a prompt operation fails, such as when a prompt is not found or arguments are invalid.
MCPProtocolError
Section titled “MCPProtocolError”Protocol violation (malformed message, invalid state).
Raised when an MCP message violates the protocol specification, such as missing required fields or invalid JSON-RPC structure.
MCPResourceError
Section titled “MCPResourceError”Resource read or list failed.
Raised when a resource operation fails, such as when a resource is not found or cannot be read.
MCPToolCallError
Section titled “MCPToolCallError”Tool call failed during MCP execution.
Raised when a tool invocation fails, either due to the tool not existing or raising an exception.