# `McpHouse.Client`
[🔗](https://github.com/HashNuke/mcp_house/blob/main/lib/mcp_house/client.ex#L1)

Discover and call MCP servers from an Elixir application.

`connect/2` supports Streamable HTTP and legacy HTTP+SSE endpoints.
It returns a client holding the negotiated capabilities and session. A client can
be shared across processes when its callbacks can run there. Use
`connect_stdio/3` for a local subprocess.

Calls for resources, prompts, and completions return
`{:error, {:unsupported_capability, capability}}` when the server does not
advertise the required capability.

## List and call a tool

This example uses Bandit to run a local `McpHouse.Server` on an ephemeral
port. Run it in an environment with Bandit installed, such as this project's
test environment. To talk to a running MCP server, pass its endpoint to
`connect/2`.

    iex> echo = %{
    ...>   name: "echo",
    ...>   description: "Return the supplied text",
    ...>   input_schema: %{
    ...>     "type" => "object",
    ...>     "required" => ["text"],
    ...>     "properties" => %{"text" => %{"type" => "string"}}
    ...>   },
    ...>   handler: fn %{"text" => text}, _conn -> {:ok, text} end
    ...> }
    iex> opts = McpHouse.Server.init(name: "Example", version: "1.0", tools: [echo])
    iex> plug = fn conn, _opts -> McpHouse.Server.call(conn, opts) end
    iex> {:ok, listener} = Bandit.start_link(plug: plug, port: 0, ip: {127, 0, 0, 1}, startup_log: false)
    iex> {:ok, {_, port}} = ThousandIsland.listener_info(listener)
    iex> try do
    ...>   {:ok, client} = McpHouse.Client.connect("http://127.0.0.1:#{port}/mcp")
    ...>   {:ok, %{"tools" => [tool]}} = McpHouse.Client.list_tools(client)
    ...>   {:ok, %{"content" => [%{"text" => text}]}} =
    ...>     McpHouse.Client.call_tool(client, tool, %{"text" => "hello"})
    ...>   operation = McpHouse.Client.start_tool_call(client, tool, %{"text" => "again"})
    ...>   {:ok, %{"content" => [%{"text" => later}]}} = McpHouse.Client.await(operation)
    ...>   :ok = McpHouse.Client.close(client)
    ...>   {tool["name"], text, later}
    ...> after
    ...>   Supervisor.stop(listener)
    ...> end
    {"echo", "hello", "again"}

# `await`

Collects the terminal result of a tool call or subscription.

The wait defaults to 5,000 milliseconds. You can pass `:infinity` to
wait until the operation finishes. A wait timeout returns
`{:error, :await_timeout}` and leaves the operation running.

# `call_tool`

Calls a tool with a map of arguments and returns `{:ok, result}` or
`{:error, reason}`.

Tool execution errors arrive in the result's `"isError"` field. JSON-RPC
errors return `{:error, {:rpc, error}}` by default. Pass `:on_progress` to
receive progress parameter maps while the call runs. Supply an explicit
`:progress_token` when you need to correlate those notifications yourself.

Pass a tool definition from `list_tools/2` to send annotated parameter
headers on the first attempt. On a `2026-07-28` header mismatch, the client
looks up the current definition and retries once if the headers changed.

On HTTP, set `:submission_errors` to `true` to classify failures as
`:not_submitted`, `:remote_error`, or `:outcome_unknown` in an
`{:error, {category, reason}}` tuple. Pass `:timeout` to override the
operation timeout for this call.

# `cancel`

Stops an operation and releases its stream. Returns `:ok` or a cleanup
error. Use `await/2` to collect the terminal tool or subscription result.
An operation that completed before cancellation retains its result.

# `close`

Terminates a server-assigned HTTP session or stops the stdio subprocess.

Returns `:ok` on success, for a stateless HTTP client, or if the server
does not support session termination. If scoped cleanup is configured,
the cleanup provider must authorize the HTTP DELETE.

# `complete`

Completes an argument for a prompt or resource template.

Pass a string-keyed MCP reference and an argument map with `"name"` and
`"value"`. Use `:context_arguments` to include previously resolved argument
values. Returns `{:ok, result}` with candidates under `"completion"`.

```elixir
McpHouse.Client.complete(
  client,
  %{"type" => "ref/prompt", "name" => "greet"},
  %{"name" => "person", "value" => "Ad"}
)
```

# `connect`

Discovers the server at an HTTP or HTTPS MCP endpoint and returns
`{:ok, client}` or `{:error, reason}`. Pass the MCP endpoint path, such
as `https://example.com/mcp`.

Set `:timeout` to a positive number of milliseconds per operation (default
30,000). Set `:client_info` to a map with string keys `"name"` and
`"version"` to identify the host application.

Pass a `:limits` keyword list to tune `:setup_timeout`, `:cleanup_timeout`,
`:stream_idle_timeout`, `:request_bytes`, `:response_bytes`, `:sse_frame_bytes`,
and `:sse_stream_bytes`. Setup defaults to the operation timeout, cleanup
to at most 5 seconds, and open subscription idle time to 60 seconds. Body
limits default to 8 MiB per request, 16 MiB per response, 1 MiB per SSE frame,
and 32 MiB across an SSE stream and its resumptions.

The default `:protocol_version` is `:auto`, which probes 2026-07-28 first.
Pass a revision string to require that revision. The three 2025 revisions
start with an initialization POST. For `"2024-11-05"`, pass the SSE URL.
The calling process owns its stream until it exits or calls `close/1`.

For a protected HTTP endpoint, pass a token or zero-arity token provider
as `:bearer_token`. A provider supplies the current token on each request.
When using `:limits` or `:network_policy`, the bearer provider and stream
callbacks run in worker processes within the active deadline.
Supply static custom `:headers` or a unary `:request_headers` provider returning
`{:ok, headers}` or `{:error, reason}`, where reason is an atom. The client
validates header names and values and scopes them to the configured endpoint.
Set `:header_max_bytes` to change the combined credential header limit (8192
by default). A `:cleanup_headers` provider separately authorizes retirement
requests with a complete set of existing headers. Use a saved snapshot in
this provider so it can retire a session without renewing its credentials.
When using scoped headers, admission, or a bounded bearer provider,
retirement requires this grant.

Pass a `:network_policy` keyword list to require verified HTTPS and public
addresses. Inside that list, set `:allow_endpoint` to check the URI before
resolution. An optional unary `:resolver` returns `{:ok, addresses}` with IPv4
or IPv6 tuples. Every returned address must pass the policy before dialing.
Supply an `:allow_address` callback of arity two (endpoint URI and address) to define
the permitted HTTPS addresses. These callbacks run in a worker process
within the request budget. The `:cacerts` option supplies trusted DER CA
certificates. Set `:allow_loopback_http` to `true` for local test fixtures.

Set `:on_elicitation` to a unary handler that accepts the server's request
parameters and returns a map with an `"action"` of `"accept"`, `"decline"`,
or `"cancel"`. Include `"content"` in an accepted form answer. Set `:input_max_rounds` to
limit modern continuations (default 10).

Set `:admit` to a function receiving the HTTP request context immediately
before the write. Return `:ok` or `{:error, reason}`, where reason is an atom.
The context includes `:endpoint`, `:http_method`, `:rpc_method`, `:session_id`,
the monotonic `:deadline` in milliseconds, and `:purpose`
(`:operation`, `:resume`, or `:cleanup`). The context flags resumed requests
with `:resuming?`. Header and admission callbacks run in worker processes.
Retirement uses `:cleanup_headers` for admission.

    iex> McpHouse.Client.connect("ftp://example.com/mcp")
    {:error, :invalid_endpoint}

    iex> McpHouse.Client.connect("https://mcp.example/mcp",
    ...>   network_policy: [allow_endpoint: fn uri -> uri.host == "internal.example" end])
    {:error, {:network_policy, :endpoint_denied}}

# `connect_stdio`

Launches an MCP server over stdio. The calling process owns its lifetime.

Pass an executable path or an executable name on PATH and its arguments
as a list of strings. The optional `:erlexec` dependency enables this
transport. The result is `{:ok, client}` after protocol negotiation.
See `connect/2` for protocol selection and timeout options.

    iex> McpHouse.Client.connect_stdio("")
    {:error, :stdio_executable_not_found}

# `get_prompt`

Renders a named prompt with a map of string arguments.

Returns `{:ok, result}` with a `"messages"` list. Arguments
default to an empty map. Requires the server's `"prompts"` capability.

# `list_prompts`

Returns `{:ok, page}` with one page of prompt definitions under the
`"prompts"` key.

Pass the previous result's `"nextCursor"` as `:cursor` to fetch another
page. Use `get_prompt/3` with a listed name to render it.

# `list_resource_templates`

Returns `{:ok, page}` with one page of URI templates under the
`"resourceTemplates"` key.

Pass the previous result's `"nextCursor"` as `:cursor` to fetch another
page. Expand a template to a resource URI before passing it to
`read_resource/2`.

# `list_resources`

Returns `{:ok, page}` with one page of available resources under the
`"resources"` key.

Pass the previous result's `"nextCursor"` as `:cursor` to fetch another
page. Requires the server's `"resources"` capability.

# `list_tools`

Returns `{:ok, %{"tools" => tools}}` for one page of tools. If the result
includes a `"nextCursor"`, pass it as `:cursor` to fetch the next page.
Each tool definition can be passed directly to `call_tool/4`.

# `read_resource`

Reads a resource by its URI and returns `{:ok, result}` on success.

The `"contents"` list can contain text entries with `"text"` or binary
entries with a Base64-encoded `"blob"`. The URI is sent to the connected
MCP server.

# `start_tool_call`

Starts a tool call in the background and returns a `McpHouse.Client.Operation`.

Accepts the same tool, arguments and options as `call_tool/4`. Use
`await/2` to collect the result or `cancel/1` to stop the operation.
Callbacks and bearer token providers must work from another process.

# `subscribe`

Starts a Streamable HTTP subscription and delivers matching notification
maps to `on_event`. Returns `{:ok, operation}` once the operation starts.
The `:on_ready` callback receives the supported filter when the stream is
ready. On revision `2026-07-28`, `on_event` also receives the
`"notifications/subscriptions/acknowledged"` notification. Use `cancel/1`
to stop the subscription and `await/2` to read its terminal result.

Filters take string keys such as `"toolsListChanged"`, `"promptsListChanged"`,
or `"resourcesListChanged"` with value `true`. For updates to specific
resources, pass a list of URIs under `"resourceSubscriptions"`.
Open one subscription per session on revision `2025-11-25`. When its GET stream
disconnects, the listener reopens it with the latest event ID if available.
Recovery honors the stream idle deadline and runs the header and admission
callbacks again. The ready callback runs once.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
