ExAgent.MCP.Client (ExAgent v3.0.0)

View Source

A client for Model Context Protocol servers over stdio or opt-in Streamable HTTP, exposing tools as ExAgent.Tools.

Stability — Stable.

For HTTP use transport: :streamable_http, url: url with either :headers_provider or an application-owned HTTP1-only :finch pool. Allow at least two pooled connections if the peer sends requests during legacy SSE. By default HTTP probes MCP 2026-07-28 with server/discover and uses initialize when the peer speaks an earlier Streamable HTTP revision. Pass :protocol_version to pin a revision. HTTP never follows redirects or resumes a stream. Configure transport limits on start_link/1. After a session404, reconnect/1 explicitly starts a new handshake. No tool request is replayed. Direct call_tool/3 is transport IO, not runtime approval. Generated tools use the normal validation and permission boundary. Persisted continuation requires explicit trusted endpoint/principal references through :continuation_binding; ordinary tools work without those references.

The candidate HTTP authorization challenge maps a 401 or 403 with a Bearer challenge to {:error, {:authorization_required, challenge}}. See authorization_challenge/0 for the fields supplied by the peer. The host discovers the authorization server, obtains a token and updates the source read by :headers_provider. It can then retry the rejected operation once. The client makes no OAuth requests or automatic retries. An unconfirmed tool outcome must be reconciled before another invocation. An HTTP denial with no valid Bearer challenge returns :unauthorized or :forbidden as before.

An MCP server is an external process that speaks JSON-RPC 2.0 over stdin/stdout (e.g. npx -y @modelcontextprotocol/server-filesystem ./). This client spawns it, performs the initialize handshake, lists its tools, and turns each into an ExAgent.Tool whose execution forwards a tools/call back to the server.

Example

chat_model is an explicitly configured ExAgent.Models.ReqLLM instance with credentials and the qualified tool profile (see the README recipe).

# 1) start the server + handshake
{:ok, client} =
  ExAgent.MCP.Client.start_link(
    command: System.find_executable("npx") || raise("npx not found on PATH"),
    args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"]
  )

# 2) discover its tools as ExAgent tools
{:ok, tools} = ExAgent.MCP.Client.tools(client)

# 3) use them like any ExAgent tool
agent = ExAgent.new(model: chat_model, tools: tools)
ExAgent.run(agent, "list the files")

Concurrency and request ownership

A client owns one transport. Requests are sent independently and can execute concurrently on the remote server; the GenServer does not serialize remote tool effects. Each pending request has a deadline and monitors its caller. A pending tool timeout returns {:error, {:result_unconfirmed, :timeout}}. Caller death drops the local request. Neither proves that a remote tool stopped or rolled back, and neither triggers replay. Requests beyond :max_pending return {:error, :busy} before sending.

Incoming newline-delimited frames are limited by :max_frame_bytes. An oversized frame closes the transport, fails remaining pending requests, and leaves the client not ready. Complete responses preceding that frame are processed first, independently of transport chunk boundaries. These bounds limit pending state and individual frames, not the BEAM mailbox or aggregate traffic from a push transport.

Testing seam

The transport is pluggable: pass transport: {send_fun, ref} (mostly for tests) to inject a fake transport instead of spawning a real process. The client receives data as messages shaped {ref, {:data, binary}}. send_fun must return promptly: it runs in the client process, so a blocking callback delays deadlines and other client operations. {:error, reason}, false, exceptions and throws/exits indicate an unconfirmed send; other return values (including the value returned by send/2) retain their existing meaning.

Summary

Types

The peer's protected resource metadata URL, space-delimited OAuth scope string and OAuth error code. Each absent or invalid field is nil. Treat these values as untrusted input to the host's OAuth implementation.

t()

Functions

Call a tool on the server by name. A successful reply returns {:ok, text} or the opted-in image projection. Empty content can project structured data as JSON text. A valid reply with isError: true returns {:tool_error, text}. Use a callback from tools/1 for a map validated against the discovered tool's object result schema.

Returns a specification to start this module under a supervisor.

Shut down. HTTP makes a bounded DELETE when sessionful. A missing client returns {:error, :unavailable}. An unacknowledged close has the same uncertainty receipts as call_tool/3. A DELETE error still stops the client.

Start a fresh HTTP handshake after session invalidation. A missing client returns {:error, :unavailable}. A lost acknowledgement returns {:error, :result_unconfirmed} or {:error, {:result_unconfirmed, cause}}. Reconnection never replays tools.

Capture canonical JSON declarations with a lowercase SHA-256 digest.

Start the client and negotiate its revision. Stdio spawns a server and initializes it. HTTP uses the header provider or the supplied application-owned Finch instance.

List the server's tools as ExAgent.Tools. Each tool's call forwards a tools/call to the server. A declared object outputSchema becomes Tool.result_schema. A successful call returns its validated structuredContent map. Other tools return text or the opted-in image result. Discovery rejects an invalid object schema with {:error, :invalid_tools}.

Types

authorization_challenge()

(candidate API)
@type authorization_challenge() :: %{
  resource_metadata: String.t() | nil,
  scope: String.t() | nil,
  error: String.t() | nil
}

The peer's protected resource metadata URL, space-delimited OAuth scope string and OAuth error code. Each absent or invalid field is nil. Treat these values as untrusted input to the host's OAuth implementation.

t()

@type t() :: GenServer.server()

Functions

call_tool(client, name, arguments)

@spec call_tool(GenServer.server(), String.t(), map()) ::
  {:ok, String.t()}
  | {:content, [map()]}
  | {:tool_error, String.t()}
  | {:error, term()}

Call a tool on the server by name. A successful reply returns {:ok, text} or the opted-in image projection. Empty content can project structured data as JSON text. A valid reply with isError: true returns {:tool_error, text}. Use a callback from tools/1 for a map validated against the discovered tool's object result schema.

With negotiated Tasks, this call polls by ID until the result is ready or the original request deadline elapses. Use ExAgent.MCP.Client.Tasks.start_tool/3 to obtain the handle for work that can outlive that deadline.

A missing client returns {:error, :unavailable}. If the client exits after dispatch without replying, the result is {:error, :result_unconfirmed}. If a transport or protocol cause is known, the result is {:error, {:result_unconfirmed, cause}}. Examples include a tool timeout, an incomplete response, a failed stdio send, or an HTTP worker dying while awaiting the result. Generated tools return {:unknown, cause} (or {:unknown, :result_unconfirmed} without a cause). Reconcile the effect before another call. A caller linked to a failed client can receive its exit signal.

With a header provider, failure before upload returns {:error, {:mcp_headers, :unavailable | :invalid | :principal_mismatch}} or {:error, :http_pre_dispatch_timeout}. These receipts confirm that the tool POST did not start. A callback failure while answering an SSE control request can leave the original tool result unconfirmed.

A top-level {:authorization_required, challenge} is a confirmed HTTP rejection. A challenge on an SSE control POST or on a task poll is nested under :result_unconfirmed because the original tool was already dispatched.

The request's own HTTP 404 returns {:error, :session_expired}. A pending tool interrupted by another request's 404 returns {:error, {:result_unconfirmed, :session_invalidated}}. Confirmed JSON-RPC rejections return {:error, {:jsonrpc_error, code}} with just the integer code. A peer reporting an uncertain effect, with wire code -32004 or July's 10001, gives {:error, :result_unconfirmed} on all transports. A generated tool returns {:unknown, :result_unconfirmed}. A host tool forwarding the direct error also records an unknown outcome.

With a name listed in :image_tools, an image reply returns {:content, parts} using the shapes in ExAgent.Tool.Content. With the HTTP 2026-07-28 profile, direct calls read the catalogue first to obtain any declared parameter headers. They can reuse fresh declarations from the same session and credentials. The server authorizes every tool call. A confirmed catalogue rejection or list-change notification clears the cache for subsequent requests. Generated tools use the routing and result declarations from their own discovery result. If the route becomes stale again after one fresh lookup, the direct call returns {:error, :session_invalidated} before uploading.

Pinned calls require a verified catalogue. Before verification or after invalidation, the client returns {:error, :mcp_catalogue_unverified}. A tool excluded by known drift returns the drift diagnostic. A name outside the lock returns {:error, :mcp_tool_not_pinned}.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

close(client)

@spec close(GenServer.server()) :: :ok | {:error, term()}

Shut down. HTTP makes a bounded DELETE when sessionful. A missing client returns {:error, :unavailable}. An unacknowledged close has the same uncertainty receipts as call_tool/3. A DELETE error still stops the client.

reconnect(client)

@spec reconnect(GenServer.server()) ::
  :ok | {:ok, {:mcp_catalogue_drift, map()}} | {:error, term()}

Start a fresh HTTP handshake after session invalidation. A missing client returns {:error, :unavailable}. A lost acknowledgement returns {:error, :result_unconfirmed} or {:error, {:result_unconfirmed, cause}}. Reconnection never replays tools.

For a pinned client, connect its transport if needed and verify a fresh tools/list. Exact matches return :ok. Drift returns {:error, {:mcp_catalogue_drift, details}} with :reject or {:ok, {:mcp_catalogue_drift, details}} with :serve_pinned. A declarations-only client returns {:error, :not_available}.

snapshot(client)

(candidate API)
@spec snapshot(GenServer.server()) :: {:ok, binary()} | {:error, term()}

Capture canonical JSON declarations with a lowercase SHA-256 digest.

An unpinned client traverses the live catalogue without using the TTL cache. A pinned client returns the original lock bytes without contacting the peer. The bytes are accepted by the :pinned option and ExAgent.MCP.Snapshot.decode/1.

start_link(opts)

@spec start_link(keyword()) :: GenServer.on_start()

Start the client and negotiate its revision. Stdio spawns a server and initializes it. HTTP uses the header provider or the supplied application-owned Finch instance.

Options

  • :command — path to the executable to spawn directly (required for stdio). To look up a command on the host's PATH, use System.find_executable/1.
  • :args — list of args passed to the command (default []).
  • :env — explicit environment for the spawned server (default []). A list of {name, value} pairs accepts binaries or charlists. Set the value to false to remove a variable. Later pairs win.
  • :environment_policy — :isolated (default) retains a small set of OS runtime variables, including PATH, plus explicit :env. :inherit starts with the whole parent environment. This policy applies when the client owns the stdio subprocess.
  • :timeout — handshake / per-request timeout in ms (default 5000). Accepts integers in 1..4_294_967_295. A timed-out tool call can have effects.
  • :control_timeout — Streamable HTTP timeout in ms for control messages and session deletion (default 1000). Accepts the same range as :timeout.
  • :tasks — opt in to the candidate MCP Tasks extension (default false). With the 2026-07-28 HTTP profile, the client checks server discovery before advertising Tasks on a tool call. Other peers receive the ordinary call. See ExAgent.MCP.Client.Tasks.
  • :pinned — candidate canonical JSON bytes from snapshot/1. Build the tool declarations without connecting or spawning a subprocess. Supply the normal transport options to enable execution. The snapshot fixes the revision and Tasks mode.
  • :connect_on_start — candidate boolean (default false). Set true with :pinned to connect and verify the lock before returning from start_link/1. An explicit false also works without :pinned. With :reject, drift fails startup. With :serve_pinned, only tools allowed by that policy are available and drift emits telemetry. Use this option in a supervisor child to verify on each start. With the default, call reconnect/1 when ready to enable execution.
  • :on_drift — candidate policy for pinned clients. The default :reject rejects the catalogue. :serve_pinned permits matching declarations and description-only changes. Added, removed and incompatible tools stay unavailable.
  • :max_pending — maximum concurrent pending requests (default 128).
  • :image_tools — names of tools whose successful MCP ImageContent should reach the model. Discovery declares them multimodal. Defaults to [].
  • :max_frame_bytes — maximum bytes in a newline-delimited incoming frame, excluding its newline (default 8388608, 8 MiB). Also bounds partial frames. Both limits must be positive integers.
  • :cd — working directory for the spawned server.
  • :transport — {send_fun, ref} test seam (see moduledoc). When set, no process is spawned; send_fun.(ref, iodata) must deliver bytes to the server and responses must arrive as {ref, {:data, binary}} messages. Alternatively :streamable_http selects the HTTP adapter and requires :url and either :headers_provider or :finch. With Finch, :headers defaults to [] and is sent on each request. Finch telemetry carries static request headers in metadata.request.headers and response headers in the recv stop event. Use :headers_provider for credentials. HTTP accepts :protocol_version as described below. Positive integer limits include :max_request_bytes and :max_response_bytes (1 MiB each), :max_header_bytes (16 KiB), :max_session_bytes (256), :max_line_bytes (64 KiB), :max_event_bytes (256 KiB), :max_tools (256), :max_controls (16), :max_control_bytes (64 KiB) and :max_control_workers (4). Byte limits apply to decoded HTTP data delivered to the client.
  • :headers_provider — host function fn %{deadline: ms, principal: expected} -> result end. It runs in the request worker for each HTTP exchange, including handshake, control POSTs and DELETE. Return {:ok, principal, [{name, value}]} or {:error, reason}. The deadline is absolute monotonic milliseconds. The returned principal is a non-secret id/version reference, equal to expected when a continuation binding is present. Otherwise expected is nil. Use a source scoped to the client's principal. The credential path opens one HTTP/1.1 connection per exchange with Mint's default TLS verification for HTTPS. Omit :finch and :headers in this mode.
  • :trace — opt in to OpenTelemetry client spans and W3C Trace Context in params._meta for the configured peer (default false). This captures the caller's span before dispatch and carries traceparent and optional tracestate without baggage. The host owns the optional OTel SDK.
  • :continuation_binding — %{endpoint: reference, principal: reference} for persisted tool identity; each reference is a non-secret %{"id" => stable_id, "version" => version} supplied by the trusted host. HTTP also binds a digest of its effective public URL and requires no userinfo, query or fragment. Stdio's endpoint reference identifies the command/args/environment's semantics without persisting those values. Transport and protocol are bound by the client. References do not authenticate the peer or prove the principal of supplied credentials; the host must maintain that association. A header provider can rotate credentials for the same principal on the existing client. A different principal requires a different binding and approval for persisted work. Headers, credentials, Finch names, PIDs and session IDs are never in this binding. Missing binding leaves ordinary IO usable but durable execution fails before model/tool IO; invalid explicit binding rejects startup. Stdio may add protocol_version: inside :continuation_binding with one of the accepted revisions (default "2025-06-18"). Records persisted by 2.x bound "2024-11-05": restore them with a client that pins that value inside :continuation_binding. For HTTP set the revision as the top-level :protocol_version option alongside :continuation_binding to restore with the revision already stored by C7.

Options are checked per transport before anything starts: an unknown option, an option of the other transport (for example :url with stdio or :env with :streamable_http), a duplicate, or a missing :command (stdio) or :url plus :finch or :headers_provider (HTTP) raises ArgumentError naming the keys. An invalid option value, including :continuation_binding, also raises ArgumentError in the caller naming the key, for both transports. start_link/1 returns {:error, reason} only for runtime failures: {:stdio_spawn_failed, reason}, a failed handshake (:timeout, {:jsonrpc_error, code}, :invalid_initialize, :unsupported_protocol_version, ...) or :mcp_protocol_binding_mismatch.

Protocol revision

Stdio requests MCP 2025-06-18. An unbound stdio client accepts the server's answer in 2025-06-18, 2025-03-26 or 2024-11-05. An initialize result requires a capabilities object and a serverInfo with string name and version; otherwise :invalid_initialize. Another revision gives :unsupported_protocol_version. A bound stdio client requests the pinned revision of its :continuation_binding and requires the same answer, otherwise :mcp_protocol_binding_mismatch.

Stdio and legacy HTTP SSE answer well-formed server requests with either a ping result or JSON-RPC -32601 for unsupported methods. A request whose params is present and is not an object, or whose ID is invalid, receives -32600. The error uses a null ID when the request ID is unusable.

An unpinned HTTP client starts with server/discover at 2026-07-28. A legacy rejection or a compatible revision offered by the peer leads to initialize at 2025-11-25, 2025-06-18 or 2025-03-26. A malformed discovery returns :invalid_discovery. An incompatible revision returns :unsupported_protocol_version. An explicit pin limits the exchange to that revision. The negotiated revision applies for the life of the client and to any persisted tool binding.

Modern requests include per-request metadata and routing headers. A server request on response SSE ends the exchange with :unexpected_server_request. A negotiated Tasks response is followed by task-ID lookups. A bound C7 root tool advertises form elicitation and pauses on input_required. Use ExAgent.Continuation.supply_result/4 with {:input, responses} and resume the run to send the next round. Unknown result types leave the tool outcome unconfirmed.

tools(client)

@spec tools(GenServer.server()) :: {:ok, [ExAgent.Tool.t()]} | {:error, term()}

List the server's tools as ExAgent.Tools. Each tool's call forwards a tools/call to the server. A declared object outputSchema becomes Tool.result_schema. A successful call returns its validated structuredContent map. Other tools return text or the opted-in image result. Discovery rejects an invalid object schema with {:error, :invalid_tools}.

Confirmed JSON-RPC rejections return {:error, {:jsonrpc_error, code}}. A peer reporting an uncertain effect returns {:unknown, :result_unconfirmed} from the generated callback. Discovery returns {:error, :unavailable} if the client process cannot be reached or exits without replying.

Paginated catalogues are followed through nextCursor, up to 32 pages; Streamable HTTP's :max_tools bounds the whole catalogue. A name repeated across pages, a repeated cursor or too many pages return {:error, :invalid_tools} or {:error, :discovery_limit}, never a truncated catalogue. Every page must contain a tools list. An empty list can carry a cursor to the next page. If a registered name now resolves to a different ready client, or the HTTP client has reconnected between pages, discovery returns {:error, :session_invalidated}. Call tools/1 again on the ready client to read the catalogue from the first page. Streamable HTTP discovery can also return the session errors described in call_tool/3.

For an unbound client, a complete catalogue with positive ttlMs and matching cacheScope hints on every page can be reused until the earliest page expiry. Concurrent lookups for the same identity can wait for one cold traversal. The local cache admits up to 256 declarations and 1 MiB of external term bytes. A continuation-bound client discovers live definitions for C7 fingerprints. A pinned client lists the verified lock declarations locally (even before connecting). After a comparison it omits incompatible declarations with :serve_pinned or returns the drift error with :reject.