Skip to content
GitHub

API Reference

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.).

connect
async def connect() -> None

Open the underlying connection (spawn process, open socket, etc.).

disconnect
async def disconnect() -> None

Close the underlying connection and free resources.

send
async def send(message: dict[str, Any]) -> None

Write a JSON-RPC message to the server.

Parameters
ParameterTypeDescription
`message`dict[str, Any]Fully-formed JSON-RPC request or notification dict.
receive
async def receive() -> dict[str, Any]

Read and return the next JSON-RPC message from the server.

Returns
TypeDescription
dict[str, Any]Parsed JSON-RPC response dict.
Raises
ExceptionDescription
MCPTransportErrorOn I/O failure or malformed data.

Protocol for handling MCP prompt-related methods.

Handles prompts/list and prompts/get methods.

list_prompts
async def list_prompts() -> list[dict[str, Any]]

Handle prompts/list method.

Returns list of available prompt templates.

get_prompt
async def get_prompt(
    name: str,
    arguments: dict[str, Any] | None = None
) -> dict[str, Any]

Handle prompts/get method.

Returns a prompt with arguments filled in.


Protocol for providing prompt templates to the MCP server.
list_prompts
async def list_prompts() -> list[dict[str, Any]]

List available prompt templates.

get_prompt
async def get_prompt(
    name: str,
    arguments: dict[str, Any] | None = None
) -> dict[str, Any]

Get a prompt template with arguments filled.


Protocol for handling MCP resource-related methods.

Handles resources/list, resources/read, and resources/templates/list.

list_resources
async def list_resources() -> list[dict[str, Any]]

Handle resources/list method.

Returns list of available resources.

read_resource
async def read_resource(uri: str) -> dict[str, Any]

Handle resources/read method.

Returns content of a specific resource.

list_templates
async def list_templates() -> list[dict[str, Any]]

Handle resources/templates/list method.

Returns list of URI templates for resources.


Protocol for providing resources to the MCP server.

Resources are data that AI clients can browse and read — database records, files, configuration, etc.

list_resources
async def list_resources() -> list[dict[str, Any]]

List available resources in MCP format.

read_resource
async def read_resource(uri: str) -> dict[str, Any]

Read a resource by URI.


Protocol for the MCP server.

The server routes JSON-RPC messages to handlers and returns JSON-RPC responses.

handle_message
async def handle_message(message: dict[str, Any]) -> dict[str, Any] | None

Handle a JSON-RPC message and return the response.

Returns None for notifications (no response expected).


Protocol for handling MCP tool-related methods.

Handles tools/list and tools/call methods.

list_tools
async def list_tools() -> list[dict[str, Any]]

Handle tools/list method.

Returns list of available tools with their definitions.

call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any]
) -> dict[str, Any]

Handle tools/call method.

Executes a tool and returns the result.


Protocol for providing tools to the MCP server.

Satisfied by:

  • ToolRegistryAdapter (bridges lexigram-agents ToolRegistry)
  • Any custom tool provider
list_tools
async def list_tools() -> list[dict[str, Any]]

List all available tools in MCP format.

Returns list of dicts with name, description, inputSchema keys.

call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any]
) -> dict[str, Any]

Execute a tool by name with given arguments.


Protocol for MCP transport implementations.

A transport handles the I/O layer — reading requests and writing responses. The MCP server is transport-agnostic.

start
async def start() -> None

Start the transport.

stop
async def stop() -> None

Stop the transport.


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
async def start() -> None

Start the transport.

stop
async def stop() -> None

Stop the transport.

send
async def send(message: dict[str, Any]) -> None

Send a message through the transport.

Parameters
ParameterTypeDescription
`message`dict[str, Any]JSON-RPC message to send.
receive
async def receive() -> dict[str, Any] | None

Receive a message from the transport.

Returns
TypeDescription
dict[str, Any] | NoneParsed JSON-RPC message, or None if no message available.

MCPPromptProviderProtocol backed by a list of MCPController instances.

Aggregates all @prompt-decorated methods and dispatches get_prompt calls to the matching handler.

__init__
def __init__(controller_instances: list[MCPController]) -> None

Initialize with a list of already-constructed controller instances.

Parameters
ParameterTypeDescription
`controller_instances`list[MCPController]Instantiated MCPController objects to aggregate.
list_prompts
async def list_prompts() -> list[dict[str, Any]]

List all prompt templates from registered controllers in MCP format.

Returns
TypeDescription
list[dict[str, Any]]MCP prompt definitions with ``name``, ``description``, ``arguments``.
get_prompt
async def get_prompt(
    name: str,
    arguments: dict[str, Any] | None = None
) -> dict[str, Any]

Get a prompt template by name with arguments filled in.

Parameters
ParameterTypeDescription
`name`strPrompt name.
`arguments`dict[str, Any] | NoneOptional arguments dict from the MCP client.
Returns
TypeDescription
dict[str, Any]MCP-format prompt response with ``description`` and ``messages``.
Raises
ExceptionDescription
MCPPromptErrorIf no prompt with the given name is registered.

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.

__init__
def __init__(controller_instances: list[MCPController]) -> None

Initialize with a list of already-constructed controller instances.

Parameters
ParameterTypeDescription
`controller_instances`list[MCPController]Instantiated MCPController objects to aggregate.
list_resources
async def list_resources() -> list[dict[str, Any]]

List all resources from all registered controllers in MCP format.

Returns
TypeDescription
list[dict[str, Any]]MCP resource definitions with ``uri``, ``name``, ``description``.
read_resource
async def read_resource(uri: str) -> dict[str, Any]

Read a resource by URI, matching exact URIs and {var} patterns.

Parameters
ParameterTypeDescription
`uri`strConcrete URI from the MCP client (e.g. ``"users://123"``).
Returns
TypeDescription
dict[str, Any]Resource content dict.
Raises
ExceptionDescription
MCPResourceErrorIf no resource pattern matches the given URI.
list_templates
async def list_templates() -> list[dict[str, Any]]

List URI templates for resources that contain {var} placeholders.

Returns
TypeDescription
list[dict[str, Any]]MCP URI template definitions with ``uriTemplate``, ``name``, ``description``.

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.

__init__
def __init__(controller_instances: list[MCPController]) -> None

Initialize with a list of already-constructed controller instances.

Parameters
ParameterTypeDescription
`controller_instances`list[MCPController]Instantiated MCPController objects to aggregate.
list_tools
async def list_tools() -> list[dict[str, Any]]

List all tools from all registered controllers in MCP format.

Returns
TypeDescription
list[dict[str, Any]]MCP tool definitions with ``name``, ``description``, ``inputSchema``.
call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any]
) -> Any

Dispatch a tool call to the matching controller method.

Parameters
ParameterTypeDescription
`name`strMCP tool name.
`arguments`dict[str, Any]Argument dict from the MCP client.
Returns
TypeDescription
AnyHandler return value.
Raises
ExceptionDescription
MCPToolCallErrorIf no tool with the given name is registered.

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()
async with MCPClient(transport) as client:
tools = await client.list_tools()
Parameters
ParameterTypeDescription
`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.
__init__
def __init__(
    transport: MCPClientTransport,
    *,
    request_timeout: float = 30.0
) -> None
connect
async def connect() -> None

Connect the transport and perform the MCP initialize handshake.

Raises
ExceptionDescription
MCPInitializationErrorIf the server rejects the handshake.
MCPTransportErrorOn transport-level failures.
disconnect
async def disconnect() -> None

Close the transport connection.

list_tools
async def list_tools() -> list[dict[str, Any]]

Return the list of tools exposed by the server.

Returns
TypeDescription
list[dict[str, Any]]List of MCP tool definition dicts, each with ``name``, ``description``, and ``inputSchema``.
call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any] | None = None
) -> Any

Call a tool by name on the server.

Parameters
ParameterTypeDescription
`name`strTool name as returned by list_tools.
`arguments`dict[str, Any] | NoneTool input arguments. Pass ``None`` for tools that take no parameters.
Returns
TypeDescription
AnyThe ``result`` field from the server's JSON-RPC response.
Raises
ExceptionDescription
MCPToolCallErrorIf the server returns an error for the tool call.
list_resources
async def list_resources() -> list[dict[str, Any]]

Return the list of resources exposed by the server.

Returns
TypeDescription
list[dict[str, Any]]List of MCP resource dicts, each with ``uri``, ``name``, ``description``, and ``mimeType``.
list_prompts
async def list_prompts() -> list[dict[str, Any]]

Return the list of prompt templates exposed by the server.

Returns
TypeDescription
list[dict[str, Any]]List of MCP prompt dicts, each with ``name``, ``description``, and ``arguments``.

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",
),
]
),
],
)
app = LexigramApplication(
modules=[
MCPClientModule.configure(
connections=[
MCPConnection.stdio(
["uvx", "mcp-server-git"],
name="git",
),
]
),
],
)
__init__
def __init__(connections: list[MCPConnection] | None = None) -> None
configure
def configure(
    cls,
    connections: list[MCPConnection]
) -> MCPClientModule

Create an MCPClientModule for the given connections.

Parameters
ParameterTypeDescription
`connections`list[MCPConnection]List of MCPConnection objects describing each external MCP server. Each must have a unique *name*.
Returns
TypeDescription
MCPClientModuleAn ``MCPClientModule`` ready to be added to the application.
Raises
ExceptionDescription
ValueErrorIf *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"),
],
)
MCPClientModule.configure(
connections=[
MCPConnection.stdio(["npx", "github-mcp"], name="github"),
MCPConnection.sse("http://localhost:9000/mcp", name="local"),
],
)
providers
def providers() -> list

Return the DI providers for this module.


__init__
def __init__(connections: list[MCPConnection]) -> None
register
async def register(container: ContainerRegistrarProtocol) -> None

Register MCPClientRegistry (and a single MCPClient if one connection).

boot
async def boot(container: ContainerResolverProtocol) -> None

Boot hook for MCP client provider.

shutdown
async def shutdown() -> None

Shutdown MCP client provider resources.


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")
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).

__init__
def __init__(clients: dict[str, MCPClient]) -> None

Initialize with a pre-built mapping of names → clients.

Parameters
ParameterTypeDescription
`clients`dict[str, MCPClient]Dict mapping each connection name to its MCPClient instance.
get
def get(name: str) -> MCPClient

Return the client registered under name.

Parameters
ParameterTypeDescription
`name`strThe connection name passed to MCPConnection.stdio or MCPConnection.sse.
Returns
TypeDescription
MCPClientThe corresponding MCPClient.
Raises
ExceptionDescription
KeyErrorIf no client was registered with the given *name*.
names
def names() -> list[str]

Return the names of all registered connections.

Returns
TypeDescription
list[str]Sorted list of registered connection names.

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).


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).

stdio
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.

Parameters
ParameterTypeDescription
`command`list[str]The command and arguments to launch the MCP server.
`name`strUnique name for use with MCPClientRegistry.
`env`dict[str, str] | NoneOptional extra environment variables.
`startup_timeout`floatSeconds to wait for process start.
`request_timeout`floatPer-request timeout in seconds.
Returns
TypeDescription
MCPConnectionA configured ``MCPConnection`` describing this stdio server.

Example

MCPConnection.stdio(
["uvx", "mcp-server-git", "--repository", "/repo"],
name="git",
)
MCPConnection.stdio(
["uvx", "mcp-server-git", "--repository", "/repo"],
name="git",
)
sse
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.

Parameters
ParameterTypeDescription
`url`strBase URL of the MCP server (e.g. ``http://localhost:8080/mcp``).
`name`strUnique name for use with MCPClientRegistry.
`headers`dict[str, str] | NoneOptional extra HTTP headers (e.g. auth tokens).
`request_timeout`floatPer-request timeout in seconds.
Returns
TypeDescription
MCPConnectionA configured ``MCPConnection`` describing this SSE server.

Example

MCPConnection.sse(
"http://analytics.internal/mcp",
name="analytics",
headers={"Authorization": "Bearer secret"},
)
MCPConnection.sse(
"http://analytics.internal/mcp",
name="analytics",
headers={"Authorization": "Bearer secret"},
)
build_transport
def build_transport() -> Any

Instantiate and return the appropriate transport for this connection.

Returns
TypeDescription
AnyA StdioClientTransport or SSEClientTransport instance.
Raises
ExceptionDescription
ValueErrorIf *transport_type* is not ``"stdio"`` or ``"sse"``.
build_client
def build_client() -> MCPClient

Build an MCPClient from this connection description.

Returns
TypeDescription
MCPClientAn unconnected MCPClient ready for use.

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({})
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_tools
def collect_tools(cls) -> list[dict[str, Any]]

Collect tool-decorated methods from the class hierarchy.

Returns
TypeDescription
list[dict[str, Any]]List of dicts with keys ``name``, ``description``, ``handler_name``.
collect_resources
def collect_resources(cls) -> list[dict[str, Any]]

Collect resource-decorated methods from the class hierarchy.

Returns
TypeDescription
list[dict[str, Any]]List of dicts with keys ``uri_pattern``, ``name``, ``description``, ``handler_name``.
collect_prompts
def collect_prompts(cls) -> list[dict[str, Any]]

Collect prompt-decorated methods from the class hierarchy.

Returns
TypeDescription
list[dict[str, Any]]List of dicts with keys ``name``, ``description``, ``handler_name``.

Result of the initialize method.
to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


JSON-RPC request message.
to_dict
def to_dict() -> dict[str, Any]

Serialize to JSON-RPC format.


JSON-RPC response message.
to_dict
def to_dict() -> dict[str, Any]

Serialize to JSON-RPC format.

create_success
def create_success(
    result: dict[str, Any],
    request_id: int | str | None = None
) -> MCPJSONRPCResponse

Create a success response.

create_error
def create_error(
    code: int,
    message: str,
    request_id: int | str | None = None,
    data: Any | None = None
) -> MCPJSONRPCResponse

Create an error response.


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_*"],
),
],
)
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_*"],
),
],
)
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_*"],
),
],
)
app = LexigramApplication(
modules=[
...,
MCPModule.from_services(
services=[UserService, AnalyticsService],
include_methods=["search", "get_*"],
),
],
)
from_services
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.

Parameters
ParameterTypeDescription
`services`list[type]Service classes whose public methods are exposed as tools.
`include_methods`list[str] | NoneOptional glob patterns to restrict which methods are exposed (e.g. ``["search", "get_*"]``).
`config`MCPConfig | NoneOptional MCPConfig override.
Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.
configure
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.

Parameters
ParameterTypeDescription
`config`MCPConfig | NoneOptional MCPConfig.
`controllers`list[type] | NoneMCPController subclasses to register with the server.
`services`list[type] | NoneService classes to auto-expose as MCP tools.
`include_methods`list[str] | NoneGlob patterns to restrict auto-exposed methods.
`enable_streaming`boolEnable 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.
Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.
stub
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.

Parameters
ParameterTypeDescription
`config`MCPConfig | NoneOptional MCPConfig override. Uses safe test defaults when ``None``.
Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.

An MCP prompt template that clients can use.
to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


A message in an MCP prompt response.
to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


__init__
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
register
async def register(container: ContainerRegistrarProtocol) -> None

Register MCPConfig with the DI container.

boot
async def boot(container: BootContainerProtocol) -> None

Wire up all MCP components using the resolved container.

shutdown
async def shutdown() -> None

Clean up MCP provider resources.

health_check
async def health_check(timeout: float = 5.0) -> HealthCheckResult

Return a health check result for this provider.

Parameters
ParameterTypeDescription
`timeout`floatMaximum seconds to wait for health response.
Returns
TypeDescription
HealthCheckResultA HealthCheckResult reflecting the current MCP provider state.

An MCP resource that clients can browse and read.
to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


Content of an MCP resource returned to the client.
to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


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)
server = MCPServer(
name="my-app",
tool_handler=tool_handler,
resource_handler=resource_handler,
)
response = await server.handle_message(request)
__init__
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.

Parameters
ParameterTypeDescription
`config`Any | NoneOptional MCP server configuration.
`name`str | NoneServer name (overrides config if provided).
`version`str | NoneServer version (overrides config if provided).
`tool_handler`Any | NoneHandler for tool-related methods.
`resource_handler`Any | NoneHandler for resource-related methods.
`prompt_handler`Any | NoneHandler for prompt-related methods.
`sampling_handler`Any | NoneHandler for sampling/createMessage (optional).
`logging_handler`Any | NoneHandler for logging/setLevel (optional).
handle_message
async def handle_message(message: dict[str, Any]) -> dict[str, Any] | None

Handle a JSON-RPC message and return the response.

Parameters
ParameterTypeDescription
`message`dict[str, Any]Parsed JSON-RPC request message.
Returns
TypeDescription
dict[str, Any] | NoneJSON-RPC response dict, or None for notifications.

Server capabilities sent during initialization.
to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


Server metadata sent during initialization.
to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


Payload fired after the MCP server completes its startup sequence.

Attributes: transport: Transport type in use (e.g. "stdio" or "sse").


Payload fired after the MCP server shuts down.

Attributes: transport: Transport type that was in use at shutdown.


MCP tool definition sent to clients during tools/list.

Maps directly to the MCP tool schema format.

to_dict
def to_dict() -> dict[str, Any]

Serialize to MCP protocol format.


Payload fired each time a tool is invoked through the MCP protocol.

Attributes: tool_name: Name of the MCP tool that was called.


Prompt provider built from module-level ``@prompt``-decorated functions.

Use from_module to scan a Python module for decorated callables.

__init__
def __init__(funcs: list[Any]) -> None

Initialize with a list of decorated functions.

Parameters
ParameterTypeDescription
`funcs`list[Any]Callables that have ``_prompt_config`` set by ``@prompt()``.
from_module
def from_module(
    cls,
    module: Any
) -> ModulePromptProvider

Scan module for @prompt-decorated functions.

Parameters
ParameterTypeDescription
`module`AnyA Python module object.
Returns
TypeDescription
ModulePromptProviderA new ``ModulePromptProvider`` with all discovered prompts.
list_prompts
async def list_prompts() -> list[dict[str, Any]]

Return all registered prompt definitions.

get_prompt
async def get_prompt(
    name: str,
    arguments: dict[str, Any] | None = None
) -> Any

Return a prompt by name.

Parameters
ParameterTypeDescription
`name`strPrompt name.
`arguments`dict[str, Any] | NoneOptional template arguments.
Returns
TypeDescription
AnyMCP prompt response dict.
Raises
ExceptionDescription
MCPPromptErrorIf the prompt name is not registered.

Resource provider built from module-level ``@resource``-decorated functions.

Use from_module to scan a Python module for decorated callables.

__init__
def __init__(funcs: list[Any]) -> None

Initialize with a list of decorated functions.

Parameters
ParameterTypeDescription
`funcs`list[Any]Callables that have ``_resource_config`` set by ``@resource()``.
from_module
def from_module(
    cls,
    module: Any
) -> ModuleResourceProvider

Scan module for @resource-decorated functions.

Parameters
ParameterTypeDescription
`module`AnyA Python module object.
Returns
TypeDescription
ModuleResourceProviderA new ``ModuleResourceProvider`` with all discovered resources.
list_resources
async def list_resources() -> list[dict[str, Any]]

Return all registered resource definitions.

read_resource
async def read_resource(uri: str) -> Any

Read a resource by URI.

Parameters
ParameterTypeDescription
`uri`strConcrete URI from the MCP client.
Returns
TypeDescription
AnyResource content.
Raises
ExceptionDescription
MCPResourceErrorIf no resource pattern matches the given URI.
list_templates
async def list_templates() -> list[dict[str, Any]]

Return URI templates (resources with {var} placeholders).


Tool provider built from module-level ``@tool``-decorated functions.

Use from_module to scan a Python module for decorated callables

import my_tools
provider = ModuleToolProvider.from_module(my_tools)
import my_tools
provider = ModuleToolProvider.from_module(my_tools)

Or pass functions directly

provider = ModuleToolProvider([search_users, create_user])
provider = ModuleToolProvider([search_users, create_user])
__init__
def __init__(funcs: list[Any]) -> None

Initialize with a list of decorated functions.

Parameters
ParameterTypeDescription
`funcs`list[Any]Callables that have ``_tool_config`` set by ``@tool()``.
from_module
def from_module(
    cls,
    module: Any
) -> ModuleToolProvider

Scan module for @tool-decorated functions.

Parameters
ParameterTypeDescription
`module`AnyA Python module object.
Returns
TypeDescription
ModuleToolProviderA new ``ModuleToolProvider`` with all discovered tools.
list_tools
async def list_tools() -> list[dict[str, Any]]

Return MCP tool definitions for all registered functions.

call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any]
) -> Any

Invoke the tool function by name.

Parameters
ParameterTypeDescription
`name`strTool name.
`arguments`dict[str, Any]Arguments dict from the MCP client.
Returns
TypeDescription
AnyTool result.
Raises
ExceptionDescription
MCPToolCallErrorIf the tool name is not registered.

Handler for MCP prompt-related methods.

Handles prompts/list and prompts/get methods by delegating to an MCPPromptProviderProtocol implementation.

__init__
def __init__(prompt_provider: Any | None = None) -> None

Initialize the prompt handler.

Parameters
ParameterTypeDescription
`prompt_provider`Any | NoneProvider that handles prompt operations.
list_prompts
async def list_prompts() -> Result[dict[str, Any], MCPError]

Handle prompts/list method.

Returns
TypeDescription
Result[dict[str, Any], MCPError]``Result`` containing prompts list in MCP format.
get_prompt
async def get_prompt(
    name: str,
    arguments: dict[str, Any] | None = None
) -> Result[dict[str, Any], MCPError]

Handle prompts/get method.

Parameters
ParameterTypeDescription
`name`strName of the prompt to get.
`arguments`dict[str, Any] | NoneArguments to fill in the prompt template.
Returns
TypeDescription
Result[dict[str, Any], MCPError]``Result[dict[str, Any], MCPError]`` with prompt payload.

Handler for MCP resource-related methods.

Handles resources/list, resources/read, and resources/templates/list methods by delegating to an MCPResourceProviderProtocol implementation.

__init__
def __init__(resource_provider: Any | None = None) -> None

Initialize the resource handler.

Parameters
ParameterTypeDescription
`resource_provider`Any | NoneProvider that handles resource operations.
list_resources
async def list_resources() -> Result[dict[str, Any], MCPError]

Handle resources/list method.

Returns
TypeDescription
Result[dict[str, Any], MCPError]``Result`` containing resources list in MCP format.
read_resource
async def read_resource(uri: str) -> Result[dict[str, Any], MCPError]

Handle resources/read method.

Parameters
ParameterTypeDescription
`uri`strURI of the resource to read.
Returns
TypeDescription
Result[dict[str, Any], MCPError]``Result[dict[str, Any], MCPError]`` with MCP-formatted contents.
list_templates
async def list_templates() -> Result[dict[str, Any], MCPError]

Handle resources/templates/list method.

Returns
TypeDescription
Result[dict[str, Any], MCPError]``Result`` containing URI templates in MCP format.

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).

Parameters
ParameterTypeDescription
`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.
__init__
def __init__(
    url: str,
    *,
    headers: dict[str, str] | None = None,
    request_timeout: float = 30.0
) -> None
connect
async def connect() -> None

Open an aiohttp session.

disconnect
async def disconnect() -> None

Close the aiohttp session.

send
async def send(message: dict[str, Any]) -> None

Queue message for the next receive call via HTTP POST.

receive
async def receive() -> dict[str, Any]

POST the pending request and return the parsed JSON-RPC response.


Server-Sent Events transport for MCP server.

This transport uses HTTP POST for requests and SSE for streaming responses. Ideal for web-based integrations.

__init__
def __init__(server: Any | None = None) -> None

Initialize the SSE transport.

Parameters
ParameterTypeDescription
`server`Any | NoneOptional HTTP server instance.
start
async def start() -> None

Start the SSE transport.

stop
async def stop() -> None

Stop the SSE transport.

send
async def send(message: dict[str, Any]) -> None

Send a message via SSE.

Parameters
ParameterTypeDescription
`message`dict[str, Any]JSON-RPC message to send.
Raises
ExceptionDescription
MCPTransportErrorIf sending fails.
receive
async def receive() -> dict[str, Any] | None

Receive is not applicable for SSE (pull-based).

For HTTP+SSE, use the HTTP endpoint directly instead.

Returns
TypeDescription
dict[str, Any] | NoneNone (receiving is handled via HTTP POST).
get_queued_messages
def get_queued_messages() -> list[dict[str, Any]]

Get queued messages for SSE delivery.

Returns
TypeDescription
list[dict[str, Any]]List of queued JSON-RPC messages.

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_*"],
)
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.

__init__
def __init__(entries: list[tuple[Any, str, str, str]]) -> None

Initialize with pre-built tool entries.

Parameters
ParameterTypeDescription
`entries`list[tuple[Any, str, str, str]]List of ``(instance, method_name, tool_name, description)`` tuples.
from_services
def from_services(
    cls,
    service_instances: Any,
    include_patterns: list[str] | None = None
) -> ServiceToolProvider

Scan service_instances and expose matching public methods as tools.

Parameters
ParameterTypeDescription
`service_instances`AnyA single instantiated service object or a list.
`include_patterns`list[str] | NoneGlob patterns to filter method names (e.g. ``["search", "get_*"]``). When ``None``, all public non-dunder methods are included.
Returns
TypeDescription
ServiceToolProviderA new ``ServiceToolProvider`` with entries for every matched method.
list_tools
async def list_tools() -> list[dict[str, Any]]

Return MCP tool definitions for all discovered service methods.

call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any]
) -> Any

Invoke the service method mapped to name.

Parameters
ParameterTypeDescription
`name`strTool name.
`arguments`dict[str, Any]Arguments dict from the MCP client.
Returns
TypeDescription
AnyMethod return value (sync or awaited coroutine).
Raises
ExceptionDescription
MCPToolCallErrorIf no method is registered under *name*.

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.

Parameters
ParameterTypeDescription
`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`.
__init__
def __init__(
    command: list[str],
    *,
    env: dict[str, str] | None = None,
    startup_timeout: float = 10.0
) -> None
connect
async def connect() -> None

Spawn the subprocess.

disconnect
async def disconnect() -> None

Terminate the subprocess.

send
async def send(message: dict[str, Any]) -> None

Write a newline-delimited JSON message to the subprocess stdin.

receive
async def receive() -> dict[str, Any]

Read a newline-delimited JSON message from subprocess stdout.


Stdio-based transport for MCP server.

This transport reads JSON-RPC messages from stdin and writes responses to stdout. Ideal for CLI/desktop integration.

__init__
def __init__(
    reader: asyncio.StreamReader | None = None,
    writer: asyncio.StreamWriter | None = None
) -> None

Initialize the stdio transport.

Parameters
ParameterTypeDescription
`reader`asyncio.StreamReader | NoneOptional stream reader (for testing).
`writer`asyncio.StreamWriter | NoneOptional stream writer (for testing).
start
async def start() -> None

Start the stdio transport.

stop
async def stop() -> None

Stop the stdio transport.

send
async def send(message: dict[str, Any]) -> None

Send a message through stdio.

Parameters
ParameterTypeDescription
`message`dict[str, Any]JSON-RPC message to send.
Raises
ExceptionDescription
MCPTransportErrorIf sending fails.
receive
async def receive() -> dict[str, Any] | None

Receive a message from stdio.

Returns
TypeDescription
dict[str, Any] | NoneParsed JSON-RPC message, or None if no data available.
Raises
ExceptionDescription
MCPTransportErrorIf receiving fails.

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.

__init__
def __init__(tool_provider: Any | None = None) -> None

Initialize the tool handler.

Parameters
ParameterTypeDescription
`tool_provider`Any | NoneProvider that handles tool listing and execution.
list_tools
async def list_tools() -> Result[dict[str, Any], MCPError]

Handle tools/list method.

Returns
TypeDescription
Result[dict[str, Any], MCPError]``Result`` containing tools list in MCP format.
call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any] | None = None
) -> Result[dict[str, Any], MCPError]

Handle tools/call method.

Returns a ResultOk wraps the serialized MCP tool result dict; Err wraps an MCPToolCallError describing what went wrong.

Parameters
ParameterTypeDescription
`name`strName of the tool to call.
`arguments`dict[str, Any] | NoneArguments to pass to the tool.
Returns
TypeDescription
Result[dict[str, Any], MCPError]``Result[dict[str, Any], MCPError]`` — never raises expected errors.

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 → MCP inputSchema
  • ToolRegistryProtocol.get() → lookup by name
  • ToolProtocol.execute(**kw) → tool invocation
__init__
def __init__(tool_registry: ToolRegistryProtocol | None = None) -> None
list_tools
async def list_tools() -> list[dict[str, Any]]

List all available tools in MCP format.

Returns
TypeDescription
list[dict[str, Any]]List of tool definitions with ``name``, ``description``, and ``inputSchema`` (JSON Schema produced by ``@tool``).
call_tool
async def call_tool(
    name: str,
    arguments: dict[str, Any]
) -> Any

Execute a tool by name with given arguments.

Parameters
ParameterTypeDescription
`name`strName of the tool to call.
`arguments`dict[str, Any]Arguments to pass to the tool.
Returns
TypeDescription
AnyTool execution result.

prompt
def prompt(
    name: str,
    *,
    description: str = ''
) -> Any
Register a method as an MCP prompt template handler.

Stores _prompt_config on the decorated method for discovery by collect_prompts.

Parameters
ParameterTypeDescription
`name`strMCP prompt name exposed to AI clients.
`description`strHuman-readable description of the prompt template.
Returns
TypeDescription
AnyDecorator 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..."
@prompt("summarize", description="Generate a summary prompt")
async def summarize_prompt(self) -> str:
return "Summarize the following data..."

resource
def resource(
    uri_pattern: str,
    *,
    description: str = '',
    name: str | None = None
) -> Any
Register a method as an MCP resource handler.

Stores _resource_config on the decorated method for discovery by collect_resources.

Parameters
ParameterTypeDescription
`uri_pattern`strURI template (e.g. ``"users://{user_id}"``).
`description`strHuman-readable description of the resource.
`name`str | NoneOptional display name; defaults to the URI pattern.
Returns
TypeDescription
AnyDecorator 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:
...
@resource("users://{user_id}", description="Expose user by ID")
async def get_user(self, user_id: str) -> dict:
...

tool
def tool(
    name: str,
    *,
    description: str = ''
) -> Any
Register a method as an MCP tool handler.

Stores _tool_config on the decorated method for discovery by collect_tools.

Parameters
ParameterTypeDescription
`name`strMCP tool name exposed to AI clients.
`description`strHuman-readable description for the tool schema.
Returns
TypeDescription
AnyDecorator 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]:
...
@tool("search_users", description="Search users by name")
async def search_users(self, name: str = "") -> list[dict]:
...

Base exception for all MCP errors.
__init__
def __init__(
    message: str = 'MCP error',
    **kwargs: Any
) -> None

MCP server initialization failed.

Raised when the MCP server cannot be initialized, usually due to missing required handlers or configuration errors.

__init__
def __init__(
    message: str = 'MCP initialization failed',
    *,
    reason: str | None = None,
    **kwargs: Any
) -> None

Unknown MCP method requested by client.

Raised when the client requests an MCP method that the server does not support.

__init__
def __init__(
    message: str = 'MCP method not found',
    *,
    method: str | None = None,
    **kwargs: Any
) -> None

Prompt retrieval or list failed.

Raised when a prompt operation fails, such as when a prompt is not found or arguments are invalid.

__init__
def __init__(
    message: str = 'MCP prompt error',
    *,
    prompt_name: str | None = None,
    **kwargs: Any
) -> None

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.

__init__
def __init__(
    message: str = 'MCP protocol error',
    *,
    details: dict[str, Any] | None = None,
    **kwargs: Any
) -> None

Resource read or list failed.

Raised when a resource operation fails, such as when a resource is not found or cannot be read.

__init__
def __init__(
    message: str = 'MCP resource error',
    *,
    uri: str | None = None,
    **kwargs: Any
) -> None

Tool call failed during MCP execution.

Raised when a tool invocation fails, either due to the tool not existing or raising an exception.

__init__
def __init__(
    message: str = 'MCP tool call failed',
    *,
    tool_name: str | None = None,
    **kwargs: Any
) -> None