Client API Reference¶
lauren_mcp
¶
lauren-mcp — Model Context Protocol server and client for Lauren applications.
McpServer
¶
Static factory for creating MCP clients for different transports.
Usage::
# stdio subprocess
client = McpServer.stdio(["python", "-m", "my_mcp_server"])
# WebSocket (requires lauren-mcp[ws])
client = McpServer.ws("ws://localhost:8000/mcp/ws")
# HTTP + SSE, legacy 2024-11-05 transport (requires lauren-mcp[sse])
client = McpServer.http("http://localhost:8000/mcp")
# Streamable HTTP, 2025-03-26 transport (requires lauren-mcp[sse])
client = McpServer.streamable_http("http://localhost:8000/mcp")
await client.connect()
tools = await client.list_tools()
await client.close()
All factories accept these optional keyword arguments:
protocol_version
Protocol version to request during the handshake (defaults to the
latest the library supports).
roots
Static list of :class:~lauren_mcp.Root or a callable returning the
current roots; advertised via the roots capability.
progress_handler / log_handler / list_changed_handler
Callbacks invoked when the server pushes the matching notification.
resource_updated_handler
Callback invoked with the resource URI string whenever the server
pushes a notifications/resources/updated notification. Only
fired for resources that the client has subscribed to via
:meth:~McpClientProtocol.subscribe_resource.
sampling_handler / elicitation_handler
Callbacks answering server-initiated sampling/createMessage /
elicitation/create requests.
sampling_tools
When True and a sampling_handler is provided, advertises
{"tools": True} in the sampling capability during the
handshake, indicating the client can handle tool-use sampling loops.
After connect(), all clients expose:
set_logging_level(level)
Send logging/setLevel to the server. level is one of
"debug", "info", "notice", "warning", "error",
"critical", "alert", "emergency".
subscribe_resource(uri) / unsubscribe_resource(uri)
Subscribe / unsubscribe to notifications/resources/updated for
the given URI.
complete(ref, argument)
Request completion suggestions (completion/complete).
stdio
staticmethod
¶
Create an MCP stdio client that launches command as a subprocess.
Parameters¶
command:
Argv sequence, e.g. ["python", "-m", "myserver"].
max_retries:
Subprocess restart attempts on unexpected EOF.
startup_timeout:
Seconds to wait for the initialize handshake response.
Source code in src/lauren_mcp/_client/_factory.py
ws
staticmethod
¶
Create an MCP WebSocket client.
Requires pip install 'lauren-mcp[ws]'.
Parameters¶
url:
Full WebSocket URL, e.g. "ws://localhost:8000/mcp/ws".
headers:
Optional extra HTTP headers sent during the upgrade handshake.
max_retries:
Reconnect attempts after unexpected disconnect.
startup_timeout:
Seconds to wait for the initialize handshake response.
Source code in src/lauren_mcp/_client/_factory.py
http
staticmethod
¶
Create an MCP HTTP+SSE client (legacy 2024-11-05 transport).
Requires pip install 'lauren-mcp[sse]'.
For servers speaking the 2025-03-26 Streamable HTTP transport use
:meth:streamable_http instead.
Parameters¶
url:
Base URL of the MCP HTTP+SSE server, e.g.
"http://localhost:8000/mcp".
headers:
Optional extra HTTP headers included in every request.
auth:
Optional httpx-compatible auth object (e.g.
:class:~lauren_mcp._client._oauth.ClientCredentialsProvider).
max_retries:
Reconnect attempts after SSE stream closes unexpectedly.
startup_timeout:
Seconds to wait for the initialize handshake response.
Source code in src/lauren_mcp/_client/_factory.py
streamable_http
staticmethod
¶
streamable_http(
url,
*,
headers=None,
auth=None,
max_retries=3,
startup_timeout=10.0,
**feature_kwargs,
)
Create an MCP Streamable HTTP client (2025-03-26 transport).
Requires pip install 'lauren-mcp[sse]'.
Parameters¶
url:
Base URL of the MCP endpoint, e.g. "http://localhost:8000/mcp".
headers:
Optional extra HTTP headers included in every request.
auth:
Optional httpx-compatible auth object (e.g.
:class:~lauren_mcp._client._oauth.ClientCredentialsProvider).
max_retries:
Reconnect attempts after the connection drops.
startup_timeout:
Seconds to wait for the initialize handshake response.
Source code in src/lauren_mcp/_client/_factory.py
McpClientProtocol
¶
Bases: ABC
Abstract interface for all MCP transport clients.
Concrete implementations must provide transport-specific connect / close logic and override all abstract methods. The protocol methods map one-to-one to MCP JSON-RPC methods.
connect
abstractmethod
async
¶
Establish the transport connection and complete the MCP handshake.
Must be called before any protocol method. Calling connect() on an already-connected client has implementation-defined behaviour (either a no-op or a re-connect).
Source code in src/lauren_mcp/_client/_protocol.py
close
abstractmethod
async
¶
Tear down the transport connection gracefully.
Cancels any pending in-flight requests, closes the underlying socket / pipe, and cleans up background tasks.
list_tools
abstractmethod
async
¶
Retrieve the server's tool catalogue (tools/list).
Returns a list of :class:~lauren_mcp._types.ToolSchema objects
describing each available tool.
call_tool
abstractmethod
async
¶
Invoke a tool on the server (tools/call).
Parameters¶
name:
The tool name as reported by :meth:list_tools.
arguments:
Keyword arguments to pass to the tool. Must conform to the
tool's inputSchema.
Returns¶
Any The raw result value from the server's response.
Source code in src/lauren_mcp/_client/_protocol.py
list_resources
abstractmethod
async
¶
Retrieve the server's resource catalogue (resources/list).
Returns a list of :class:~lauren_mcp._types.ResourceSchema
objects.
read_resource
abstractmethod
async
¶
Read a resource by URI (resources/read).
Parameters¶
uri:
The exact URI of the resource to read, which may be a
concrete instantiation of a URI template returned by
:meth:list_resources.
Returns¶
Any The raw contents returned by the server.
Source code in src/lauren_mcp/_client/_protocol.py
subscribe_resource
abstractmethod
async
¶
Subscribe to change notifications for the resource at uri.
Sends resources/subscribe with {"uri": uri}. After a
successful subscription the server will push
notifications/resources/updated whenever the resource changes.
The server returns METHOD_NOT_FOUND if it does not support
subscriptions; this is surfaced as :class:McpCallError with
code == -32601.
Parameters¶
uri:
The exact resource URI previously returned by :meth:list_resources.
Source code in src/lauren_mcp/_client/_protocol.py
unsubscribe_resource
abstractmethod
async
¶
Cancel a previously established resource subscription.
Sends resources/unsubscribe with {"uri": uri}. The server
will stop pushing notifications/resources/updated for this URI.
Parameters¶
uri:
The URI that was passed to :meth:subscribe_resource.
Source code in src/lauren_mcp/_client/_protocol.py
list_prompts
abstractmethod
async
¶
Retrieve the server's prompt catalogue (prompts/list).
Returns a list of :class:~lauren_mcp._types.PromptSchema
objects.
get_prompt
abstractmethod
async
¶
Retrieve a rendered prompt from the server (prompts/get).
Parameters¶
name:
The prompt name as reported by :meth:list_prompts.
arguments:
String arguments to substitute into the prompt template.
Returns¶
Any The raw GetPromptResult value from the server.
Source code in src/lauren_mcp/_client/_protocol.py
ping
abstractmethod
async
¶
Send a ping request and await the empty {} response.
Useful for connection health-checks and keep-alive probing.
Raises :class:McpCallError (or a subclass) on failure.
Source code in src/lauren_mcp/_client/_protocol.py
set_logging_level
abstractmethod
async
¶
Ask the server to change its minimum log-notification threshold.
Sends logging/setLevel with {"level": level}. The server
will suppress notifications/message entries below level from
that point forward.
Parameters¶
level:
One of "debug", "info", "notice", "warning",
"error", "critical", "alert", "emergency".
Raises¶
ValueError If level is not one of the accepted strings. McpCallError If the server returns a JSON-RPC error response.
Source code in src/lauren_mcp/_client/_protocol.py
complete
abstractmethod
async
¶
Request completion suggestions from the server (completion/complete).
Parameters¶
ref:
A reference object identifying the completable item, e.g.
{"type": "ref/prompt", "name": "greet"}.
argument:
The argument being completed, e.g.
{"name": "nam", "value": "Jo"}.
Returns¶
Any The raw completion result from the server.
Source code in src/lauren_mcp/_client/_protocol.py
McpServerConfig
dataclass
¶
Named wrapper pairing an alias string with an MCP client.
McpToolBridge
¶
SINGLETON that manages MCP client lifecycles and populates ToolRegistry.
This class is optional — it is only usable when lauren-ai is installed. Instantiate via AgentModule.for_root(mcp_servers=[...]).
Note: this class deliberately does NOT use @injectable from lauren so that it can be used without lauren-ai as a standalone orchestration helper.
Source code in src/lauren_mcp/_bridge.py
set_registry
¶
Attach a ToolRegistry (or any object with register_mcp_server) to this bridge.
Must be called before :meth:connect_all if tool registration is desired.
connect_all
async
¶
Connect every configured MCP server and load tools into the registry.
For each configured server the method:
- Calls
client.connect()to perform the MCP initialize handshake. - Calls
client.list_tools()to retrieve all available tool schemas. - Registers those tools via
registry.register_mcp_server(alias, tools, client)(skipped when no registry has been attached via :meth:set_registry).
Failures in individual servers are caught and logged at ERROR level so that a single broken server does not prevent the remaining servers from loading.
Source code in src/lauren_mcp/_bridge.py
disconnect_all
async
¶
Cancel all watch tasks and close every configured MCP client.
Exceptions raised by individual client.close() calls are silently
suppressed so that all clients receive a close attempt regardless of
whether earlier ones failed.
Source code in src/lauren_mcp/_bridge.py
_ClientFeaturesMixin
¶
Notification handlers, roots, and protocol-version state for clients.
Consuming classes must provide _send_raw(obj) -> Awaitable[None].
protocol_version
property
¶
The protocol version negotiated with the server.
Raises RuntimeError before :meth:connect completes.
on_progress
¶
Register a handler for notifications/progress.
on_log
¶
Register a handler for notifications/message (server logs).
on_list_changed
¶
Register a handler for tool/resource/prompt list_changed.
Source code in src/lauren_mcp/_client/_features.py
on_resource_updated
¶
Register a handler for notifications/resources/updated.
Returns a zero-arg callable that removes the handler when called.
Parameters¶
handler: Callable invoked with the resource URI string whenever a subscribed resource changes.
Source code in src/lauren_mcp/_client/_features.py
notify_roots_changed
async
¶
Send notifications/roots/list_changed to the server.
Only meaningful when dynamic roots (a callable) were supplied.
Source code in src/lauren_mcp/_client/_features.py
ClientCredentialsProvider
¶
ClientCredentialsProvider(
token_endpoint,
client_id,
client_secret,
scopes=None,
storage=None,
extra_params=None,
)
httpx.AsyncAuth-compatible OAuth 2.0 client-credentials token provider.
Fetches a bearer token from token_endpoint using the
client_credentials grant, caches it in storage, and automatically
refreshes it when the cache misses (or is about to expire). On a 401
response the provider invalidates the cache and retries the request once.
Usage::
auth = ClientCredentialsProvider(
token_endpoint="https://auth.example.com/oauth/token",
client_id="my-service",
client_secret="s3cr3t",
scopes=["mcp.read", "mcp.write"],
)
client = McpServer.streamable_http("https://api.example.com/mcp", auth=auth)
await client.connect()
Parameters¶
token_endpoint:
Full URL of the token endpoint.
client_id:
OAuth client identifier.
client_secret:
OAuth client secret.
scopes:
Optional list of scope strings to request.
storage:
Token cache backend. Defaults to :class:InMemoryTokenStorage.
extra_params:
Additional form fields to include in the token request body
(e.g. {"audience": "https://api.example.com"} for Auth0).
Source code in src/lauren_mcp/_client/_oauth.py
get_token
async
¶
Return a valid bearer token, fetching a new one if necessary.
Source code in src/lauren_mcp/_client/_oauth.py
async_auth_flow
async
¶
Attach a Bearer token; on 401 invalidate and retry once.
Source code in src/lauren_mcp/_client/_oauth.py
InMemoryTokenStorage
¶
McpStreamableHttpClient
¶
McpStreamableHttpClient(
url,
*,
headers=None,
auth=None,
max_retries=3,
startup_timeout=10.0,
client_info=None,
**feature_kwargs,
)
Bases: _McpBaseRemoteClient
MCP client speaking the 2025-03-26 Streamable HTTP transport.
All messages POST to the single MCP endpoint. Responses arrive either
as direct application/json bodies or as text/event-stream bodies
(when the server streams notifications before the final response). A
background GET stream is opened after the handshake to receive
server-push notifications.
Requires httpx::
pip install 'lauren-mcp[sse]'
Source code in src/lauren_mcp/_client/_streamable.py
connect
async
¶
Open the transport and complete the MCP handshake.