# `AshAi.Mcp.Client`
[🔗](https://github.com/ash-project/ash_ai/blob/v1.5.6/lib/ash_ai/mcp/client.ex#L6)

A client for MCP servers reached over the Streamable HTTP transport.

The client keeps no process state. `connect/1` settles the protocol details
for a `AshAi.Mcp.Client.Server` and returns an `AshAi.Mcp.Client.Connection`,
a plain struct that the other functions take, so a job can build one, use it,
and drop it.

    server =
      AshAi.Mcp.Client.server(
        name: "linear",
        url: "https://mcp.linear.app/mcp",
        auth: {AshAi.Mcp.OAuth, store: MyApp.McpTokens, owner: user.id}
      )

    {:ok, conn} = AshAi.Mcp.Client.connect(server)
    {:ok, definitions} = AshAi.Mcp.Client.list_tools(conn)
    tools = AshAi.Mcp.Client.req_llm_tools(conn, definitions)

    AshAi.ToolLoop.run(messages, extra_tools: tools, ...)

## Resources

`list_resources/1`, `list_resource_templates/1`, and `read_resource/2` reach
the server's resources, and `format_resource/1` turns a read into text or
ReqLLM content parts, for example to attach a resource a person picked to
their message. To let the model list and read them itself, pass
`resources: true` to `req_llm_tools/3`.

## Protocol versions

The client prefers revision `2026-07-28`, which carries the protocol version,
client info, and capabilities on every request and needs no handshake. It
falls back to the `initialize`-based revisions (`2025-11-25`, `2025-06-18`,
`2025-03-26`) for servers that don't support it:

1. `connect/1` sends `server/discover` as a `2026-07-28` request.
2. A result means the server is modern. An `UnsupportedProtocolVersionError`
   also means it is modern; the client retries with a version from the
   error's `supported` list.
3. Any other rejection (an HTTP 4xx, or a JSON-RPC error that only a legacy
   server would send) means the server is legacy. The client sends
   `initialize`, then `notifications/initialized`, and sends the
   negotiated `MCP-Protocol-Version` and any `Mcp-Session-Id` on every
   later request.

Set the server's `protocol_version` to a previously negotiated
`Connection.protocol_version` to skip the probe. For a `2026-07-28` server,
`connect/1` then makes no request at all.

## Tool definitions and prompt caching

`list_tools/1` fetches definitions, and `req_llm_tools/3` turns definitions
into ReqLLM tools. They are separate so an app can store the definitions it
fetched when a conversation starts and build the same tools from them on
every turn: a server changing its tool list then can't change the tools
array mid-conversation and invalidate the prompt cache.

## Not supported yet

Server-to-client features (sampling, elicitation, roots) aren't
implemented. A `2026-07-28` result asking for input
(`resultType: "input_required"`) returns `{:error, {:input_required, result}}`.
A legacy server's requests on a response stream are answered with
JSON-RPC "method not found", except `ping`. `subscriptions/listen`,
resource subscriptions (`resources/subscribe`), and the deprecated HTTP+SSE
transport aren't supported.

# `resource_result`

```elixir
@type resource_result() :: %{contents: [map()], meta: map() | nil}
```

# `result`

```elixir
@type result() :: %{
  content: [map()],
  structured_content: term(),
  meta: map() | nil,
  is_error: boolean()
}
```

# `annotations`

```elixir
@spec annotations(
  AshAi.Mcp.Client.Connection.t() | AshAi.Mcp.Client.Server.t() | String.t(),
  [map()],
  String.t()
) :: map() | nil
```

The MCP annotations of the tool named `tool_name` (a ReqLLM tool name), or
`nil` when `definitions` has no such tool.

# `call_tool`

```elixir
@spec call_tool(AshAi.Mcp.Client.Connection.t(), String.t(), map() | nil, keyword()) ::
  {:ok, result()} | {:error, term()}
```

Calls a tool on the server.

`name` is the server's own tool name, not the `mcp__...` name from
`req_llm_tools/3`. Pass the tool's definition as `definition:` so the
client can mirror `x-mcp-header` parameters into headers.

Returns `{:ok, %{content: blocks, structured_content: value, meta: map, is_error: boolean}}`,
where `meta` is the result's `_meta` (or `nil`).
A tool that failed while running is still `{:ok, %{is_error: true}}`;
`{:error, reason}` means the request itself failed.

# `close`

```elixir
@spec close(AshAi.Mcp.Client.Connection.t()) :: :ok
```

Ends a legacy session with `DELETE`, if the server assigned one.

Servers may refuse to end sessions, so the result is ignored.

# `connect`

```elixir
@spec connect(AshAi.Mcp.Client.Server.t() | keyword()) ::
  {:ok, AshAi.Mcp.Client.Connection.t()} | {:error, term()}
```

Settles the protocol version to use with `server` and returns a connection.

Accepts a `AshAi.Mcp.Client.Server` or the options for one.

# `format_resource`

```elixir
@spec format_resource(resource_result()) ::
  {:ok, String.t() | [ReqLLM.Message.ContentPart.t()]}
```

Turns a `read_resource/2` result into text or ReqLLM content parts, for a
tool result or a message.

Text items come back as their text. Blobs are handled as `format_result/1`
handles embedded resources: PNG, JPEG, GIF, and WebP images up to 3.75 MB
become image parts, typed by their contents, and other blobs are
described without their data. When the read returned several items, each
is introduced by a line naming its URI. A result with images comes back
as content parts, and any other as one string.

# `format_result`

```elixir
@spec format_result(result()) ::
  {:ok, String.t() | [ReqLLM.Message.ContentPart.t()]} | {:error, String.t()}
```

Turns a `call_tool/4` result into what a ReqLLM tool callback returns.

Text blocks are joined with newlines, and other blocks are JSON-encoded.
A result with images, as image blocks or embedded image resources, comes
back as content parts with an image part for each. `AshAi.ToolLoop`
describes them in text instead for models that can't receive images in
tool results. PNG, JPEG, GIF, and WebP images up to 3.75 MB are kept,
typed by their contents rather than the type the server gave; other
images, audio, and other binary resources are described without their
data. A result with only `structuredContent` is JSON-encoded. `isError`
results become `{:error, text}`.

# `list_resource_templates`

```elixir
@spec list_resource_templates(AshAi.Mcp.Client.Connection.t()) ::
  {:ok, [map()]} | {:error, term()}
```

Lists the server's resource templates, following `nextCursor` pagination.

Returns the template entries as the server sent them (string keys), leaving
out any without a string `uriTemplate`. Each `uriTemplate` is an RFC 6570
URI template: expand it and pass the URI to `read_resource/2`.

# `list_resources`

```elixir
@spec list_resources(AshAi.Mcp.Client.Connection.t()) ::
  {:ok, [map()]} | {:error, term()}
```

Lists the server's resources, following `nextCursor` pagination.

Returns the resource entries as the server sent them (string keys), leaving
out any without a string `uri`. Templated resources are listed separately,
by `list_resource_templates/1`.

# `list_tools`

```elixir
@spec list_tools(AshAi.Mcp.Client.Connection.t()) :: {:ok, [map()]} | {:error, term()}
```

Lists the server's tools, following `nextCursor` pagination.

Returns the tool definitions as the server sent them (string keys). Tools
whose `inputSchema` carries an invalid `x-mcp-header` annotation are left
out with a warning, as the transport requires.

# `read_resource`

```elixir
@spec read_resource(AshAi.Mcp.Client.Connection.t(), String.t()) ::
  {:ok, resource_result()} | {:error, term()}
```

Reads a resource from the server.

Returns `{:ok, %{contents: items, meta: map}}`, where each item is a map
with a `"uri"`, an optional `"mimeType"`, and either `"text"` or a base64
`"blob"`, as the server sent it, and `meta` is the result's `_meta` (or
`nil`). A resource the server doesn't have is a JSON-RPC error: `-32602`
from `2026-07-28` servers, `-32002` from earlier ones.

`format_resource/1` turns the result into text or ReqLLM content parts.

# `req_llm_tools`

```elixir
@spec req_llm_tools(
  AshAi.Mcp.Client.Connection.t() | AshAi.Mcp.Client.Server.t(),
  [map()],
  keyword()
) ::
  [{ReqLLM.Tool.t(), (map(), map() -&gt; {:ok, term()} | {:error, term()})}]
```

Builds ReqLLM tools for `definitions`, for `AshAi.ToolLoop`'s `extra_tools`.

Returns `[{%ReqLLM.Tool{}, callback}]`, sorted by name so the same
definitions always produce the same tools array. Each tool is named by
`tool_name/2`, takes the definition's `inputSchema` as its JSON Schema,
and calls the tool on `conn`.

Pass a `Server` instead of a connection to connect on each call. Tools
then build without a request, so a loop can start from a stored snapshot
of the definitions even while the server needs authorization; a call
that needs it pauses the loop. Set the server's `protocol_version` to
the one it negotiated before (`Connection.protocol_version`) and a
2026-07-28 server needs no extra request per call.

## Resources

With `resources: true`, two more tools let the model read the server's
resources:

* `mcp__<server>__list_resources` lists one page of the server's
  resources, plus its resource templates on the first page. It takes the
  `nextCursor` of a previous page as `cursor`.
* `mcp__<server>__read_resource` reads a resource by URI, formatted by
  `format_resource/1`: one that was listed, one built from a template,
  or a `resource_link` in one of the server's tool results.

MCP leaves it to the app to decide which resources reach the model, so
these are off by default. Only add them for servers whose resources the
model may read. If the server has tools of its own with these names, its
tools are kept and a warning is logged.

## Options

* `:provider_options` - ReqLLM provider options for every tool, such as
  `[anthropic: [defer_loading: true]]`, or a function of the definition
  returning them. For the resource tools, the function gets a definition
  named `"list_resources"` or `"read_resource"`.
* `:format_result` - replaces `format_result/1`.
* `:resources` - adds the resource tools described above. Defaults to `false`.
* `:format_resource` - replaces `format_resource/1`.

# `request`

```elixir
@spec request(AshAi.Mcp.Client.Connection.t(), String.t(), map(), keyword()) ::
  {:ok, map()} | {:error, term()}
```

Sends a JSON-RPC request and returns its result.

`params` uses string keys. For `2026-07-28` the client adds the required
`_meta` fields. Pass extra HTTP headers as `headers:`.

# `server`

```elixir
@spec server(keyword()) :: AshAi.Mcp.Client.Server.t()
```

Builds a server configuration. See `AshAi.Mcp.Client.Server.new/1` for the options.

# `supported_protocol_versions`

```elixir
@spec supported_protocol_versions() :: [String.t()]
```

The protocol versions this client supports, newest first.

# `tool_info`

```elixir
@spec tool_info(
  AshAi.Mcp.Client.Connection.t() | AshAi.Mcp.Client.Server.t() | String.t(),
  [map()]
) ::
  %{required(String.t()) =&gt; map()}
```

Describes each of `definitions` by its ReqLLM tool name.

Returns `%{tool_name => %{server: name, name: mcp_name, annotations: map, definition: map}}`.
Approval hooks can use the MCP annotations (`readOnlyHint`,
`destructiveHint`, `idempotentHint`, `openWorldHint`) to decide which calls
need a person's approval. Annotations come from the server, so only trust
them from servers you trust.

# `tool_name`

```elixir
@spec tool_name(
  AshAi.Mcp.Client.Connection.t() | AshAi.Mcp.Client.Server.t() | String.t(),
  String.t()
) ::
  String.t()
```

The ReqLLM tool name for an MCP server's tool: `mcp__<server>__<tool>`.

Names are limited to the characters and length every LLM provider accepts.
A name that has to be changed to fit gets a short hash of the original
appended, so names stay unique and come out the same on every run, which
prompt caching depends on.

---

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