GitHub

mcp_client

API reference for mcp_client.

An MCP client (Effect's McpClient): call the tools, prompts and resources of an MCP server over stdio or Streamable HTTP.

The client speaks one revision, mcp_protocol.v2025_11_25 (initialize and a session) or mcp_protocol.v2026_07_28 (stateless); make negotiates it within timeout (60 seconds by default)::

client = yield from mcp_client.make(name="app", version="1.0.0")
tools = yield from client.list_tools()
result = yield from client.call_tool(tools[0], {"query": "pyfect"})

layer_stdio runs the server as a child process and layer_http reaches one at a URL; toolkit turns the server's tools into a Toolkit a language model can call. Every failure is an McpClientError with its reason.

Re-exports

Values

AttributeTypeDescription
DEFAULT_TIMEOUTDuration
MAX_DISCOVERY_PAGESint
MAX_DISCOVERY_ITEMSint
DEFAULT_DISCOVERY_LIMITSDiscoveryLimits

Types

TypeDefinitionDescription
OnInvalidSkilltype OnInvalidSkill = Callable[[InvalidSkill], Effect[None]]
RemoteTooltype RemoteTool[SS = str, HE = McpClientError, RR = Never] = Tool.Tool[Any, object, SS, McpClientError, HE, RR]

A tool bound to a remote MCP tool (Effect's RemoteTool): its success SS is str (result_mode="text") or CallToolResult ("complete"), its failure McpClientError, raised (HE = McpClientError, failure_mode="error") or returned to the model (HE = Never, "return"), and RR what transform_tool added to its handler's requirements.

ClientProtocoltype ClientProtocol = ProtocolAdapter[ClientProtocolVersion]
ClientProtocolVersiontype ClientProtocolVersion = Literal['2025-11-25', '2026-07-28']

Classes

Functions

make

make(*, name, version, title=None, description=None, website_url=None, icons=(), timeout=None, discovery_limits=None, extensions=None) -> Effect[McpClientService, McpClientError, Transport | Scope]

Connect over the Transport: initialize (2025-11-25) or discover the server (2026-07-28) within timeout, which also bounds each complete list scan. discovery_limits sets the default scan limits (100 pages, 10,000 items). extensions={"skills": True} declares the Skills extension and enables the skill methods (else they fail with a ConfigurationError).

ParameterTypeDescription
namestr
versionstr
titlestr | None = None
descriptionstr | None = None
website_urlstr | None = None
iconsSequence[Icon] = ()
timeoutDurationInput | None = None
discovery_limitsDiscoveryLimitsOptions | None = None
extensionsClientExtensions | None = None

Returns Effect[McpClientService, McpClientError, Transport | Scope]

def make(  # noqa: PLR0915
    *,
    name: str,
    version: str,
    title: str | None = None,
    description: str | None = None,
    website_url: str | None = None,
    icons: Sequence[Icon] = (),
    timeout: DurationInput | None = None,
    discovery_limits: DiscoveryLimitsOptions | None = None,
    extensions: ClientExtensions | None = None,
) -> Effect[McpClientService, McpClientError, Transport | Scope]:
    """Connect over the ``Transport``: initialize (2025-11-25) or discover
    the server (2026-07-28) within ``timeout``, which also bounds each
    complete list scan. ``discovery_limits`` sets the default scan limits
    (100 pages, 10,000 items). ``extensions={"skills": True}`` declares the
    Skills extension and enables the skill methods (else they fail with a
    ``ConfigurationError``)."""
    limit = DEFAULT_TIMEOUT if timeout is None else from_input_unsafe(timeout)
    skills_enabled = (extensions or {}).get("skills") is True
    capabilities_declared = client_capabilities(skills_enabled)

    @gen
    def run():  # noqa: PLR0915
        transport = yield from Transport()
        protocol: ClientProtocol = transport.protocol
        protocol_version = protocol.protocol_version
        modern = protocol_version == "2026-07-28"
        limits = yield from resolve_limits(discovery_limits, DEFAULT_DISCOVERY_LIMITS)
        closed = Deferred[Never, McpClientError]()
        yield from add_finalizer(
            lambda _: closed.fail(failure(ClosedError(description="MCP client scope closed")))
        )
        ids = iter(range(1, 1 << 62))
        client_info: Implementation = {"name": name, "version": version}
        for key, value in (
            ("title", title),
            ("description", description),
            ("websiteUrl", website_url),
        ):
            if value is not None:
                client_info[key] = value
        if icons:
            client_info["icons"] = list(icons)
        meta: JsonObject = {
            "io.modelcontextprotocol/protocolVersion": protocol_version,
            "io.modelcontextprotocol/clientInfo": cast("Any", client_info),
            "io.modelcontextprotocol/clientCapabilities": capabilities_declared,
        }

        def request(
            method: str, params: JsonObject, tool: McpTool | None
        ) -> Effect[Any, McpClientError]:
            # Each run takes its own id: a retried request is a new request.
            return suspend(lambda: send(method, params, tool))

        def send(
            method: str, params: JsonObject, tool: McpTool | None
        ) -> Effect[Any, McpClientError]:
            payload: JsonObject = {**params, "_meta": meta} if modern else params
            message: JsonObject = {
                "jsonrpc": "2.0",
                "id": next(ids),
                "method": method,
                "params": payload,
            }

            def answered(response: JsonObject) -> Effect[Any, McpClientError]:
                error = response.get("error")
                if isinstance(error, dict):
                    remote = cast("Mapping[str, Any]", error)
                    return fail(
                        failure(
                            ProtocolError(
                                remote.get("code"), remote.get("data"), remote.get("message")
                            )
                        )
                    )
                result: Any = response.get("result")
                if not isinstance(result, dict):
                    return fail(failure(ValidationError("Invalid MCP payload")))
                body = cast("dict[str, Any]", result)
                if modern and "resultType" not in body:
                    body = {**body, "resultType": "complete"}
                if method == "tools/list" and isinstance(body.get("tools"), list):
                    body = {**body, "tools": [t for t in body["tools"] if not requires_tasks(t)]}
                if body.get("resultType") == "input_required":
                    return fail(
                        failure(UnsupportedError("MCP input continuation is not supported"))
                    )
                return succeed(body)

            return _traced(transport.request(message, tool).flat_map(answered), method, tool)

        def deadline(
            effect: Effect[Any, McpClientError], operation: str, duration: Duration | None
        ) -> Effect[Any, McpClientError]:
            open_ = effect.race_first(closed.wait())
            if duration is None:
                return open_
            return open_.timeout_or_else(duration, lambda: fail(failure(TimeoutError(operation))))

        @gen
        def initialize():
            if not modern:
                return (
                    yield from request(
                        "initialize",
                        {
                            "protocolVersion": protocol_version,
                            "capabilities": capabilities_declared,
                            "clientInfo": cast("Any", client_info),
                        },
                        None,
                    )
                )
            discover = request("server/discover", {}, None)
            return (
                yield from discover.catch_if(
                    lambda error: _version_rejected(error, protocol_version), lambda _: discover
                )
            )

        @gen
        def connect():
            result: dict[str, Any] = yield from initialize
            supported = (
                protocol_version in (result.get("supportedVersions") or [])
                if modern
                else result.get("protocolVersion") == protocol_version
            )
            if not supported:
                return (
                    yield from fail(
                        failure(
                            UnsupportedError(
                                "Server does not support the explicitly selected protocol version"
                            )
                        )
                    )
                )
            meta: dict[str, Any] = result.get("_meta") or {}
            identity: object = meta.get(_SERVER_INFO_META) if modern else result.get("serverInfo")
            capabilities: ServerCapabilities = yield from _decode(
                SERVER_CAPABILITIES, result.get("capabilities")
            )
            server_info: Implementation | None = (
                None if identity is None else (yield from _decode(IMPLEMENTATION, identity))
            )
            if not modern:
                yield from transport.notify(
                    {"jsonrpc": "2.0", "method": "notifications/initialized"}
                )
            instructions: str | None = result.get("instructions")
            return capabilities, instructions, server_info

        def invalid(error: McpClientError) -> McpClientError:
            if isinstance(error.reason, ValidationError):
                return failure(
                    ProtocolError(
                        description="Invalid MCP initialization result", cause=error.reason.cause
                    )
                )
            return error

        connected = yield from deadline(connect.map_error(invalid), "initialization", limit)
        capabilities, instructions, server_info = connected
        return McpClientService(
            protocol_version,
            server_info,
            instructions,
            capabilities,
            request,
            deadline,
            transport.is_callable,
            limit,
            SkillsClient(request, deadline, limit, capabilities, limits, skills_enabled, modern),
        )

    return run

stdio

stdio(*, command, protocol, max_message_bytes=None) -> Effect[TransportService, McpClientError, ChildProcessSpawner | Scope]

A transport to a child process on its standard input and output.

ParameterTypeDescription
commandCommand
protocolClientProtocol
max_message_bytesint | None = None

Returns Effect[TransportService, McpClientError, ChildProcessSpawner | Scope]

def stdio(
    *, command: Command, protocol: ClientProtocol, max_message_bytes: int | None = None
) -> Effect[TransportService, McpClientError, ChildProcessSpawner | Scope]:
    """A transport to a child process on its standard input and output."""
    return _stdio(command=command, protocol=protocol, max_message_bytes=max_message_bytes)

http

http(*, url, protocol, headers=None, max_message_bytes=None) -> Effect[TransportService, McpClientError, HttpClient | Scope]

A Streamable HTTP transport to url.

ParameterTypeDescription
urlstr
protocolClientProtocol
headersMapping[str, str] | None = None
max_message_bytesint | None = None

Returns Effect[TransportService, McpClientError, HttpClient | Scope]

def http(
    *,
    url: str,
    protocol: ClientProtocol,
    headers: Mapping[str, str] | None = None,
    max_message_bytes: int | None = None,
) -> Effect[TransportService, McpClientError, HttpClient | Scope]:
    """A Streamable HTTP transport to ``url``."""
    return _http(url=url, protocol=protocol, headers=headers, max_message_bytes=max_message_bytes)

layer_stdio

layer_stdio(*, name, version, command, protocol, title=None, description=None, website_url=None, icons=(), timeout=None, discovery_limits=None, extensions=None, max_message_bytes=None) -> Layer[McpClient, McpClientError, ChildProcessSpawner]

An McpClient of the server command runs.

ParameterTypeDescription
namestr
versionstr
commandCommand
protocolClientProtocol
titlestr | None = None
descriptionstr | None = None
website_urlstr | None = None
iconsSequence[Icon] = ()
timeoutDurationInput | None = None
discovery_limitsDiscoveryLimitsOptions | None = None
extensionsClientExtensions | None = None
max_message_bytesint | None = None

Returns Layer[McpClient, McpClientError, ChildProcessSpawner]

def layer_stdio(
    *,
    name: str,
    version: str,
    command: Command,
    protocol: ClientProtocol,
    title: str | None = None,
    description: str | None = None,
    website_url: str | None = None,
    icons: Sequence[Icon] = (),
    timeout: DurationInput | None = None,
    discovery_limits: DiscoveryLimitsOptions | None = None,
    extensions: ClientExtensions | None = None,
    max_message_bytes: int | None = None,
) -> Layer[McpClient, McpClientError, ChildProcessSpawner]:
    """An ``McpClient`` of the server ``command`` runs."""
    client = make(
        name=name,
        version=version,
        title=title,
        description=description,
        website_url=website_url,
        icons=icons,
        timeout=timeout,
        discovery_limits=discovery_limits,
        extensions=extensions,
    )
    transport = layer_effect(
        Transport, stdio(command=command, protocol=protocol, max_message_bytes=max_message_bytes)
    )
    return layer_effect(McpClient, client).pipe(provide(transport))

layer_http

layer_http(*, name, version, url, protocol, headers=None, title=None, description=None, website_url=None, icons=(), timeout=None, discovery_limits=None, extensions=None, max_message_bytes=None) -> Layer[McpClient, McpClientError, HttpClient]

An McpClient of the server at url.

ParameterTypeDescription
namestr
versionstr
urlstr
protocolClientProtocol
headersMapping[str, str] | None = None
titlestr | None = None
descriptionstr | None = None
website_urlstr | None = None
iconsSequence[Icon] = ()
timeoutDurationInput | None = None
discovery_limitsDiscoveryLimitsOptions | None = None
extensionsClientExtensions | None = None
max_message_bytesint | None = None

Returns Layer[McpClient, McpClientError, HttpClient]

def layer_http(
    *,
    name: str,
    version: str,
    url: str,
    protocol: ClientProtocol,
    headers: Mapping[str, str] | None = None,
    title: str | None = None,
    description: str | None = None,
    website_url: str | None = None,
    icons: Sequence[Icon] = (),
    timeout: DurationInput | None = None,
    discovery_limits: DiscoveryLimitsOptions | None = None,
    extensions: ClientExtensions | None = None,
    max_message_bytes: int | None = None,
) -> Layer[McpClient, McpClientError, HttpClient]:
    """An ``McpClient`` of the server at ``url``."""
    client = make(
        name=name,
        version=version,
        title=title,
        description=description,
        website_url=website_url,
        icons=icons,
        timeout=timeout,
        discovery_limits=discovery_limits,
        extensions=extensions,
    )
    transport = layer_effect(
        Transport,
        http(url=url, protocol=protocol, headers=headers, max_message_bytes=max_message_bytes),
    )
    return layer_effect(McpClient, client).pipe(provide(transport))

toolkit

toolkit[RR = Never](client: McpClientService, prefix: str = '', *, tools: Sequence[McpTool] | None = None, result_mode: Literal['text'] = 'text', failure_mode: Literal['error'] = 'error', trust_annotations: bool = False, timeout: DurationInput | None = None, transform_tool: Callable[[RemoteTool[str, McpClientError], McpTool], RemoteTool[str, McpClientError, RR]] | None = None) -> Effect[Toolkit.WithHandler[Any, Any, McpClientError, RR], McpClientError]
toolkit[RR = Never](client: McpClientService, prefix: str = '', *, tools: Sequence[McpTool] | None = None, result_mode: Literal['text'] = 'text', failure_mode: Literal['return'], trust_annotations: bool = False, timeout: DurationInput | None = None, transform_tool: Callable[[RemoteTool[str, Never], McpTool], RemoteTool[str, Never, RR]] | None = None) -> Effect[Toolkit.WithHandler[Any, Any, Never, RR], McpClientError]
toolkit[RR = Never](client: McpClientService, prefix: str = '', *, tools: Sequence[McpTool] | None = None, result_mode: Literal['complete'], failure_mode: Literal['error'] = 'error', trust_annotations: bool = False, timeout: DurationInput | None = None, transform_tool: Callable[[RemoteTool[CallToolResult, McpClientError], McpTool], RemoteTool[CallToolResult, McpClientError, RR]] | None = None) -> Effect[Toolkit.WithHandler[Any, Any, McpClientError, RR], McpClientError]
toolkit[RR = Never](client: McpClientService, prefix: str = '', *, tools: Sequence[McpTool] | None = None, result_mode: Literal['complete'], failure_mode: Literal['return'], trust_annotations: bool = False, timeout: DurationInput | None = None, transform_tool: Callable[[RemoteTool[CallToolResult, Never], McpTool], RemoteTool[CallToolResult, Never, RR]] | None = None) -> Effect[Toolkit.WithHandler[Any, Any, Never, RR], McpClientError]

The server's tools (or the approved snapshot tools, without listing) as a toolkit with handlers. A model tool's name is prefix and the tool's name joined as they are (pass "docs__"), 1 to 64 letters, digits, _ and -. Remote JSON Schemas are sent as they are. Build a new toolkit to see remote changes.

A result is its text (result_mode="text"), or the whole CallToolResult ("complete"), whose content the model gets as text and file parts. A tool error (isError) or a failed request fails the call (failure_mode="error") or goes back to the model ("return") as the McpClientError; a ToolError keeps the result.

timeout bounds each call. trust_annotations copies the server's hints into the tool's annotations (never its approval). transform_tool gets each annotated tool and its descriptor and returns a tool derived from it (set_needs_approval, annotate, add_dependency), keeping its name, schemas and failure mode; a failure schema of McpClientError encoded otherwise (set_failure) changes only what the model reads of a returned failure.

ParameterTypeDescription
client
prefix= ''
tools= None
result_mode= 'text'
failure_mode= 'error'
trust_annotations= False
timeout= None
transform_tool= None
@overload
def toolkit[RR = Never](
    client: McpClientService,
    prefix: str = "",
    *,
    tools: Sequence[McpTool] | None = None,
    result_mode: Literal["text"] = "text",
    failure_mode: Literal["error"] = "error",
    trust_annotations: bool = False,
    timeout: DurationInput | None = None,
    transform_tool: Callable[
        [RemoteTool[str, McpClientError], McpTool], RemoteTool[str, McpClientError, RR]
    ]
    | None = None,
) -> Effect[Toolkit.WithHandler[Any, Any, McpClientError, RR], McpClientError]: ...
@overload
def toolkit[RR = Never](
    client: McpClientService,
    prefix: str = "",
    *,
    tools: Sequence[McpTool] | None = None,
    result_mode: Literal["text"] = "text",
    failure_mode: Literal["return"],
    trust_annotations: bool = False,
    timeout: DurationInput | None = None,
    transform_tool: Callable[[RemoteTool[str, Never], McpTool], RemoteTool[str, Never, RR]]
    | None = None,
) -> Effect[Toolkit.WithHandler[Any, Any, Never, RR], McpClientError]: ...
@overload
def toolkit[RR = Never](
    client: McpClientService,
    prefix: str = "",
    *,
    tools: Sequence[McpTool] | None = None,
    result_mode: Literal["complete"],
    failure_mode: Literal["error"] = "error",
    trust_annotations: bool = False,
    timeout: DurationInput | None = None,
    transform_tool: Callable[
        [RemoteTool[CallToolResult, McpClientError], McpTool],
        RemoteTool[CallToolResult, McpClientError, RR],
    ]
    | None = None,
) -> Effect[Toolkit.WithHandler[Any, Any, McpClientError, RR], McpClientError]: ...
@overload
def toolkit[RR = Never](
    client: McpClientService,
    prefix: str = "",
    *,
    tools: Sequence[McpTool] | None = None,
    result_mode: Literal["complete"],
    failure_mode: Literal["return"],
    trust_annotations: bool = False,
    timeout: DurationInput | None = None,
    transform_tool: Callable[
        [RemoteTool[CallToolResult, Never], McpTool], RemoteTool[CallToolResult, Never, RR]
    ]
    | None = None,
) -> Effect[Toolkit.WithHandler[Any, Any, Never, RR], McpClientError]: ...
def toolkit(
    client: McpClientService,
    prefix: str = "",
    *,
    tools: Sequence[McpTool] | None = None,
    result_mode: ResultMode = "text",
    failure_mode: Tool.FailureMode = "error",
    trust_annotations: bool = False,
    timeout: DurationInput | None = None,
    transform_tool: _Transform | None = None,
) -> Effect[Toolkit.WithHandler[Any, Any, Any, Any], McpClientError]:
    """The server's tools (or the approved snapshot ``tools``, without
    listing) as a toolkit with handlers. A model tool's name is ``prefix``
    and the tool's name joined as they are (pass ``"docs__"``), 1 to 64
    letters, digits, ``_`` and ``-``. Remote JSON Schemas are sent as they
    are. Build a new toolkit to see remote changes.

    A result is its text (``result_mode="text"``), or the whole
    ``CallToolResult`` (``"complete"``), whose content the model gets as
    text and file parts. A tool error (``isError``) or a failed request
    fails the call (``failure_mode="error"``) or goes back to the model
    (``"return"``) as the ``McpClientError``; a ``ToolError`` keeps the
    result.

    ``timeout`` bounds each call. ``trust_annotations`` copies the server's
    hints into the tool's annotations (never its approval).
    ``transform_tool`` gets each annotated tool and its descriptor and
    returns a tool derived from it (``set_needs_approval``, ``annotate``,
    ``add_dependency``), keeping its name, schemas and failure mode; a
    failure schema of ``McpClientError`` encoded otherwise (``set_failure``)
    changes only what the model reads of a returned failure."""
    complete = result_mode == "complete"

    @gen
    def run():
        descriptors: Sequence[McpTool] = (
            (yield from client.list_tools()) if tools is None else tools
        )
        bound: list[Tool.AnyTool] = []
        handlers: list[Tool.Handler[Any]] = []
        for descriptor in descriptors:
            name = f"{prefix}{descriptor['name']}"
            if _MODEL_TOOL_NAME.match(name) is None or any(t.name == name for t in bound):
                return (
                    yield from fail(
                        failure(
                            ConfigurationError(f"Invalid or duplicate MCP model tool name: {name}")
                        )
                    )
                )
            remote = _remote_tool(name, descriptor, complete, failure_mode, trust_annotations)
            bound.append(remote if transform_tool is None else transform_tool(remote, descriptor))
            handlers.append(remote.handler(_handler(client, descriptor, complete, timeout)))
        kit = Toolkit.make(*bound)
        context: Context[Any] = yield from kit.to_handlers(*handlers)
        built: Toolkit.WithHandler[Any, Any, Any, Any] = yield from cast(
            "Effect[Any, Never, Never]", kit
        ).pipe(provide_context(context))
        return built

    return run