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.).
async def connect() -> None
Open the underlying connection (spawn process, open socket, etc.).
async def disconnect() -> None
Close the underlying connection and free resources.
async def send(message: dict[str, Any]) -> None
Write a JSON-RPC message to the server.
| Parameter | Type | Description |
|---|---|---|
message | dict[str, Any] | Fully-formed JSON-RPC request or notification dict. |
async def receive() -> dict[str, Any]
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. |
MCPPromptHandlerProtocol
Section titled “MCPPromptHandlerProtocol”Protocol for handling MCP prompt-related methods.
Handles prompts/list and prompts/get methods.
async def list_prompts() -> list[dict[str, Any]]
Handle prompts/list method.
Returns list of available prompt templates.
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.
MCPPromptProviderProtocol
Section titled “MCPPromptProviderProtocol”Protocol for providing prompt templates to the MCP server.
async def list_prompts() -> list[dict[str, Any]]
List available prompt templates.
async def get_prompt( name: str, arguments: dict[str, Any] | None = None ) -> dict[str, Any]
Get a prompt template with arguments filled.
MCPResourceHandlerProtocol
Section titled “MCPResourceHandlerProtocol”Protocol for handling MCP resource-related methods.
Handles resources/list, resources/read, and resources/templates/list.
async def list_resources() -> list[dict[str, Any]]
Handle resources/list method.
Returns list of available resources.
async def read_resource(uri: str) -> dict[str, Any]
Handle resources/read method.
Returns content of a specific resource.
async def list_templates() -> list[dict[str, Any]]
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.
async def list_resources() -> list[dict[str, Any]]
List available resources in MCP format.
async def read_resource(uri: str) -> dict[str, Any]
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.
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).
MCPToolHandlerProtocol
Section titled “MCPToolHandlerProtocol”Protocol for handling MCP tool-related methods.
Handles tools/list and tools/call methods.
async def list_tools() -> list[dict[str, Any]]
Handle tools/list method.
Returns list of available tools with their definitions.
async def call_tool( name: str, arguments: dict[str, Any] ) -> dict[str, Any]
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 quadkit-agents ToolRegistry)- Any custom tool provider
async def list_tools() -> list[dict[str, Any]]
List all available tools in MCP format.
Returns list of dicts with name, description,
inputSchema keys.
async def call_tool( name: str, arguments: dict[str, Any] ) -> dict[str, Any]
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.
async def start() -> None
Start the transport.
async def stop() -> None
Stop the transport.
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.
async def start() -> None
Start the transport.
async def stop() -> None
Stop the transport.
async def send(message: dict[str, Any]) -> None
Send a message through the transport.
| Parameter | Type | Description |
|---|---|---|
message | dict[str, Any] | JSON-RPC message to send. |
async def receive() -> dict[str, Any] | None
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. |
async def list_prompts() -> list[dict[str, Any]]
List all prompt templates from registered controllers in MCP format.
| Type | Description |
|---|---|
| list[dict[str, Any]] | MCP prompt definitions with `name, description, arguments`. |
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.
| 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. |
async def list_resources() -> list[dict[str, Any]]
List all resources from all registered controllers in MCP format.
| Type | Description |
|---|---|
| list[dict[str, Any]] | MCP resource definitions with `uri, name, description`. |
async def read_resource(uri: str) -> dict[str, Any]
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. |
async def list_templates() -> list[dict[str, Any]]
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. |
async def list_tools() -> list[dict[str, Any]]
List all tools from all registered controllers in MCP format.
| Type | Description |
|---|---|
| list[dict[str, Any]] | MCP tool definitions with `name, description, inputSchema`. |
async def call_tool( name: str, arguments: dict[str, Any] ) -> Any
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()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:~quadkit.ai.mcp.exceptions.MCPTransportError is raised. |
def __init__( transport: MCPClientTransport, *, request_timeout: float = 30.0 ) -> None
async def connect() -> None
Connect the transport and perform the MCP initialize handshake.
| Exception | Description |
|---|---|
| MCPInitializationError | If the server rejects the handshake. |
| MCPTransportError | On transport-level failures. |
async def disconnect() -> None
Close the transport connection.
async def list_tools() -> list[dict[str, Any]]
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`. |
async def call_tool( name: str, arguments: dict[str, Any] | None = None ) -> Any
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. |
async def list_resources() -> list[dict[str, Any]]
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`. |
async def list_prompts() -> list[dict[str, Any]]
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 = QuadkitApplication( modules=[ MCPClientModule.configure( connections=[ MCPConnection.stdio( ["uvx", "mcp-server-git"], name="git", ), ] ), ],)app = QuadkitApplication( 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"), ],)MCPClientModule.configure( connections=[ MCPConnection.stdio(["npx", "github-mcp"], name="github"), MCPConnection.sse("http://localhost:9000/mcp", name="local"), ],)def providers() -> list
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.
async def shutdown() -> None
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")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*. |
def names() -> list[str]
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",)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://localhost:8080/mcp", name="analytics", headers={"Authorization": "Bearer secret"},)MCPConnection.sse( "http://localhost:8080/mcp", name="analytics", headers={"Authorization": "Bearer secret"},)def build_transport() -> Any
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 quadkit-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({})def collect_tools(cls) -> list[dict[str, Any]]
Collect tool-decorated methods from the class hierarchy.
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of dicts with keys `name, description, handler_name`. |
def collect_resources(cls) -> list[dict[str, Any]]
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`. |
def collect_prompts(cls) -> list[dict[str, Any]]
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.
def to_dict() -> dict[str, Any]
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 = QuadkitApplication( modules=[..., MCPModule.configure()],)
# With MCPController subclasses::
app = QuadkitApplication( modules=[..., MCPModule.configure(controllers=[DataToolsController])],)
# Auto-expose existing services as MCP tools::
app = QuadkitApplication( modules=[ ..., MCPModule.from_services( services=[UserService, AnalyticsService], include_methods=["search", "get_*"], ), ],)app = QuadkitApplication( modules=[..., MCPModule.configure()],)
# With MCPController subclassesapp = QuadkitApplication( modules=[..., MCPModule.configure(controllers=[DataToolsController])],)
# Auto-expose existing services as MCP tools::
app = QuadkitApplication( modules=[ ..., MCPModule.from_services( services=[UserService, AnalyticsService], include_methods=["search", "get_*"], ), ],)app = QuadkitApplication( modules=[..., MCPModule.configure(controllers=[DataToolsController])],)
# Auto-expose existing services as MCP toolsapp = QuadkitApplication( modules=[ ..., MCPModule.from_services( services=[UserService, AnalyticsService], include_methods=["search", "get_*"], ), ],)app = QuadkitApplication( 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.
async def boot(container: BootContainerProtocol) -> None
Wire up all MCP components using the resolved container.
async def shutdown() -> None
Clean up MCP provider resources.
async def health_check(timeout: float = 5.0) -> HealthCheckResult
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)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, authorizer: MCPAuthorizerProtocol | None = None, allow_unauthenticated: bool = False ) -> 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). |
authorizer | MCPAuthorizerProtocol | None | Optional authz hook consulted once per non-handshake request post-initialize. `None means requests are denied with -32000 unless allow_unauthenticated` is set. |
allow_unauthenticated | bool | When `True (and no authorizer) restore the open posture: non-handshake methods dispatch without authorization. Defaults to False` (fail-closed). |
async def handle_message(message: dict[str, Any]) -> dict[str, Any] | None
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.
def __init__(funcs: list[Any]) -> None
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. |
async def list_prompts() -> list[dict[str, Any]]
Return all registered prompt definitions.
async def get_prompt( name: str, arguments: dict[str, Any] | None = None ) -> Any
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.
def __init__(funcs: list[Any]) -> None
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. |
async def list_resources() -> list[dict[str, Any]]
Return all registered resource definitions.
async def read_resource(uri: str) -> Any
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. |
async def list_templates() -> list[dict[str, Any]]
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)import my_toolsprovider = ModuleToolProvider.from_module(my_tools)Or pass functions directly
provider = ModuleToolProvider([search_users, create_user])provider = ModuleToolProvider([search_users, create_user])def __init__(funcs: list[Any]) -> None
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. |
async def list_tools() -> list[dict[str, Any]]
Return MCP tool definitions for all registered functions.
async def call_tool( name: str, arguments: dict[str, Any] ) -> Any
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.
def __init__(prompt_provider: Any | None = None) -> None
Initialize the prompt handler.
| Parameter | Type | Description |
|---|---|---|
prompt_provider | Any | None | Provider that handles prompt operations. |
async def list_prompts() -> Result[dict[str, Any], MCPError]
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.
def __init__(resource_provider: Any | None = None) -> None
Initialize the resource handler.
| Parameter | Type | Description |
|---|---|---|
resource_provider | Any | None | Provider that handles resource operations. |
async def list_resources() -> Result[dict[str, Any], MCPError]
Handle resources/list method.
| Type | Description |
|---|---|
| Result[dict[str, Any], MCPError] | `Result` containing resources list in MCP format. |
async def read_resource(uri: str) -> Result[dict[str, Any], MCPError]
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. |
async def list_templates() -> Result[dict[str, Any], MCPError]
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
async def connect() -> None
Open an aiohttp session.
async def disconnect() -> None
Close the aiohttp session.
async def send(message: dict[str, Any]) -> None
Queue message for the next receive call via HTTP POST.
async def receive() -> dict[str, Any]
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.
def __init__(server: Any | None = None) -> None
Initialize the SSE transport.
| Parameter | Type | Description |
|---|---|---|
server | Any | None | Optional HTTP server instance. |
async def start() -> None
Start the SSE transport.
async def stop() -> None
Stop the SSE transport.
async def send(message: dict[str, Any]) -> None
Send a message via SSE.
| Parameter | Type | Description |
|---|---|---|
message | dict[str, Any] | JSON-RPC message to send. |
| Exception | Description |
|---|---|
| MCPTransportError | If sending fails. |
async def receive() -> dict[str, Any] | None
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). |
def get_queued_messages() -> list[dict[str, Any]]
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_*"],)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.
def __init__(entries: list[tuple[Any, str, str, str]]) -> None
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. |
async def list_tools() -> list[dict[str, Any]]
Return MCP tool definitions for all discovered service methods.
async def call_tool( name: str, arguments: dict[str, Any] ) -> Any
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:~quadkit.ai.mcp.exceptions.MCPTransportError. |
def __init__( command: list[str], *, env: dict[str, str] | None = None, startup_timeout: float = 10.0 ) -> None
async def connect() -> None
Spawn the subprocess.
async def disconnect() -> None
Terminate the subprocess.
async def send(message: dict[str, Any]) -> None
Write a newline-delimited JSON message to the subprocess stdin.
async def receive() -> dict[str, Any]
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). |
async def start() -> None
Start the stdio transport.
async def stop() -> None
Stop the stdio transport.
async def send(message: dict[str, Any]) -> None
Send a message through stdio.
| Parameter | Type | Description |
|---|---|---|
message | dict[str, Any] | JSON-RPC message to send. |
| Exception | Description |
|---|---|
| MCPTransportError | If sending fails. |
async def receive() -> dict[str, Any] | None
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.
def __init__(tool_provider: Any | None = None) -> None
Initialize the tool handler.
| Parameter | Type | Description |
|---|---|---|
tool_provider | Any | None | Provider that handles tool listing and execution. |
async def list_tools() -> Result[dict[str, Any], MCPError]
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 quadkit-agents ToolRegistry to MCPToolProviderProtocol.
This adapter allows the MCP server to use the @tool-decorated functions from quadkit-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
async def list_tools() -> list[dict[str, Any]]
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`). |
async def call_tool( name: str, arguments: dict[str, Any] ) -> Any
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”prompt
Section titled “prompt”
def prompt( name: str, *, description: str = '' ) -> Any
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..."@prompt("summarize", description="Generate a summary prompt")async def summarize_prompt(self) -> str: return "Summarize the following data..."resource
Section titled “resource”
def resource( uri_pattern: str, *, description: str = '', name: str | None = None ) -> Any
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: ...@resource("users://{user_id}", description="Expose user by ID")async def get_user(self, user_id: str) -> dict: ...
def tool( name: str, *, description: str = '' ) -> Any
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]: ...@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.
def __init__( message: str = 'MCP error', **kwargs: Any ) -> None
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.
def __init__( message: str = 'MCP initialization failed', *, reason: str | None = None, **kwargs: Any ) -> None
MCPMethodNotFoundError
Section titled “MCPMethodNotFoundError”Unknown MCP method requested by client.
Raised when the client requests an MCP method that the server does not support.
def __init__( message: str = 'MCP method not found', *, method: str | None = None, **kwargs: Any ) -> None
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.
def __init__( message: str = 'MCP prompt error', *, prompt_name: str | None = None, **kwargs: Any ) -> None
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.
def __init__( message: str = 'MCP protocol error', *, details: dict[str, Any] | None = None, **kwargs: Any ) -> None
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.
def __init__( message: str = 'MCP resource error', *, uri: str | None = None, **kwargs: Any ) -> None
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.
def __init__( message: str = 'MCP tool call failed', *, tool_name: str | None = None, **kwargs: Any ) -> None