The Model Context Protocol (MCP) lets your ExAgent apps consume external tool servers (GitHub, Jira, filesystems, internal APIs) and publish your own Elixir tools and agents as an authenticated MCP server for other clients.

What ExAgent simplifies:

  • Stdio & Streamable HTTP clients (ExAgent.MCP.Client): Discover remote tools (including paginated catalogues and outputSchema validation) and pass them directly into ExAgent.new(tools: ...) alongside ordinary Elixir tools.
  • Production security built in: Pin tool catalogues against supply-chain drift, rotate HTTP credentials dynamically, enforce per-principal catalogue authorization, and combine multiple servers with ExAgent.Toolset.
  • Publish your own MCP server (ExAgent.MCP.Server & Plug): Expose Elixir tools, agents, resources and prompts over 2025-06-18 or stateless multi-replica 2026-07-28 HTTP right inside Phoenix or Plug.
  • Durable MCP continuations: Pause for MCP elicitation forms, long-running MCP tasks and approvals under the same PostgreSQL ExAgent.Continuation engine.

Need full JSON-RPC error codes, wire headers or protocol negotiation rules?

For exhaustive 2025-06-18 / 2026-07-28 wire contracts, OAuth metadata rules and reconciliation edge cases, see Runtime & ops contracts.

Connect a stdio server

Start a local MCP subprocess under your supervision (always from trusted host config, never from model text), discover its tools, and hand them to ExAgent.new/1:

{:ok, client} = ExAgent.MCP.Client.start_link(
  command: System.find_executable("npx") || raise("npx not found on PATH"),
  args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"],
  timeout: 5000,
  max_pending: 16
)

try do
  {:ok, tools} = ExAgent.MCP.Client.tools(client)
  agent = ExAgent.new(model: chat_model, tools: tools)
  ExAgent.run(agent, "List the allowed files.")
after
  ExAgent.MCP.Client.close(client)
end

By default, spawned servers inherit only a minimal safe OS environment; pass explicit secrets via env: [{"MCP_TOKEN", ...}]. When a discovered tool declares an object outputSchema, ExAgent validates structuredContent before returning it (under MCP 2025-06-18, structured-only replies still carry a content array):

{
  "jsonrpc": "2.0",
  "id": 7,
  "result": {
    "content": [],
    "structuredContent": {"count": 2}
  }
}

For huge remote catalogues, combine MCP tools with on-demand tool search.

Combine servers

Use ExAgent.Toolset to prefix tools from multiple MCP servers and require human approval on write-heavy servers:

alias ExAgent.Toolset

{:ok, github} = ExAgent.MCP.Client.tools(github_client)
{:ok, jira} = ExAgent.MCP.Client.tools(jira_client)
tools = Toolset.prefix(github, "gh_") ++ (jira |> Toolset.require_approval() |> Toolset.prefix("jira_"))
agent = ExAgent.new(model: model, tools: tools)

Supply an HTTP pool

For remote Streamable HTTP MCP servers, supervise an HTTP/1.1-only Finch pool in your application:

{Finch, name: MyApp.MCPFinch,
  pools: %{
    default: [
      protocols: [:http1],
      size: 8,
      count: 1,
      conn_opts: [transport_opts: [nodelay: true]]
    ]
  }}

Then start ExAgent.MCP.Client against your endpoint (it probes 2026-07-28 and falls back cleanly to 2025-06-18 when talking to a legacy server):

{:ok, client} = ExAgent.MCP.Client.start_link(
  transport: :streamable_http,
  url: "https://mcp.example.invalid/mcp",
  finch: MyApp.MCPFinch,
  headers: [],
  timeout: 5000,
  max_pending: 16
)

Cache tool catalogues

Avoid re-fetching tools/list on every user turn by caching discovered tools per client session (and clearing/refreshing when Client.reconnect/1 runs or a session invalidates).

Pin an MCP tool catalogue

Protect production apps from unexpected remote schema changes or prompt injection via tool descriptions by locking discovered catalogues into priv/exagent/mcp/*.lock.json and passing pinned: lock to ExAgent.MCP.Client.start_link/1:

alias ExAgent.MCP.Client

lock = File.read!(Application.app_dir(:my_app, "priv/exagent/mcp/inventory.lock.json"))
opts = MyApp.InventoryMCP.connection_options()
{:ok, client} = Client.start_link(Keyword.put(opts, :pinned, lock))
{:ok, tools} = Client.tools(client)

Rotate HTTP credentials

Pass :headers_provider (a callback returning fresh headers and a principal ref) instead of static headers: when using short-lived OAuth tokens — this rotates tokens cleanly without restarting the client and keeps bearer tokens out of Finch telemetry:

alias ExAgent.MCP.Client

principal = %{"id" => "inventory-reader", "version" => "1"}
{:ok, credentials} = Agent.start_link(fn -> {principal, "local-first"} end)

provider = fn %{deadline: deadline, principal: ^principal} ->
  remaining = max(deadline - System.monotonic_time(:millisecond), 1)
  {current_principal, token} = Agent.get(credentials, & &1, remaining)
  {:ok, current_principal, [{"authorization", "Bearer " <> token}]}
end

{:ok, client} =
  Client.start_link(
    transport: :streamable_http,
    url: url,
    protocol_version: protocol_version,
    headers_provider: provider,
    continuation_binding: %{
      endpoint: %{"id" => "inventory", "version" => "1"},
      principal: principal
    }
  )

try do
  {:ok, [echo]} = Client.tools(client)
  before = echo.call.(%{"text" => "before"})
  Agent.update(credentials, fn _ -> {principal, "local-rotated"} end)
  after_rotation = echo.call.(%{"text" => "after"})
  {before, after_rotation}
after
  Client.close(client)
  Agent.stop(credentials)
end

Handle an HTTP authorization challenge

When a remote MCP server responds with {:error, {:authorization_required, challenge}}, run your host OAuth/token acquisition flow using the challenge metadata and retry the call:

case operation.() do
  {:error, {:authorization_required, challenge}} ->
    with :ok <- authorize_for.(url, challenge), do: operation.()

  reply ->
    reply
end

Call long-running MCP tools

Use ExAgent.MCP.Client.Tasks for MCP servers that expose asynchronous tasks returning a taskId and poll interval:

alias ExAgent.MCP.Client.Tasks

case Tasks.start_tool(client, "render", %{"asset" => "intro"}) do
  {:task, %{"taskId" => task_id} = task} ->
    {:pending, task_id, Map.get(task, "pollIntervalMs", 500)}

  result ->
    result
end

Reconcile an MCP task in C7

When an MCP task pauses inside a durable continuation, reconcile its remote status cleanly with ExAgent.Continuation.reconcile_tool/4 once the peer reports completion (MCP continuation binding).

Reconcile a task the peer no longer knows

If a remote MCP server restarted and lost track of task_id, attach a :reconcile callback on the tool that checks independent business evidence (your database or external API receipt) before confirming success or failure:

alias ExAgent.Continuation

evidence_tool = %{
  tool
  | reconcile: fn key, %{"task_id" => task_id} ->
      case lookup_terminal_evidence.(key, task_id) do
        {:ok, :failed} ->
          {:confirmed, %{"status" => "failed", "data" => "External receipt confirms failure."}}

        _ ->
          :unknown
      end
    end
}

Continuation.reconcile_tool(store, call.id, call.deferral_id,
  record_id: call.record_id,
  revision: call.revision,
  operation_id: operation_id,
  actor: actor,
  authorize: authorize,
  tool: evidence_tool
)

Answer a form without a Store

MCP servers can request structured user input mid-call (elicitation forms). For interactive storeless runs, handle forms inline with :on_input (candidate):

ExAgent.run(agent, prompt,
  on_input: fn %{forms: forms} ->
    case review_form.(forms) do
      {:ok, responses} -> {:ok, responses}
      :deny -> :deny
    end
  end
)

Answer a form in an MCP continuation

In durable runs, an MCP form pauses the continuation cleanly until your UI submits the user's answers via ExAgent.Continuation.supply_result/4 with {:input, responses} and resumes:

responses = %{"approval" => %{"action" => "accept", "content" => %{"approve" => true}}}

{:ok, %{continuation: reference}} =
  ExAgent.Continuation.supply_result(store, call, {:input, responses},
    tool: tool,
    actor: actor,
    authorize: authorize
  )

ExAgent.resume(agent, reference, run_options)

Trace MCP requests

Enable W3C Trace Context propagation on MCP.Client and MCP.Server.Plug (for explicitly trusted authenticated principals) to connect client tool spans and remote server spans in one OpenTelemetry trace (Observability).

Own failures and cleanup

Always supervise long-lived MCP.Client processes or close short-lived ones in after. If a remote MCP call times out after leaving your node, treat the remote effect as :unknown and reconcile explicitly — reconnecting never means it is safe to replay an unconfirmed write.

Publish tools and agents

Supervise an ExAgent.MCP.Server to expose your Elixir tools and whole agents over MCP (remember every exported :result_schema must have "type": "object" at its root):

alias ExAgent.{Tool, UsageLimits}
alias ExAgent.MCP.Server

schema = %{type: "object", properties: %{text: %{type: "string"}}, required: ["text"]}
echo = Tool.new(
  name: "echo",
  description: "Return the supplied text.",
  parameters_json_schema: schema,
  result_schema: schema,
  call: fn _ctx, args -> Map.take(args, ["text"]) end
)

agent = ExAgent.new(model: %ExAgent.Models.Test{label: "Hello"},
                    usage_limits: %UsageLimits{request_limit: 2})
chat = Server.agent_tool(agent, name: "chat", timeout: 5_000)
children = [{Server, name: MyApp.MCP, tools: [echo, chat]}]
{:ok, supervisor} = Supervisor.start_link(children, strategy: :one_for_one)

Mount ExAgent.MCP.Server.Plug before any Plug.Parsers body parser so it can read the raw body, enforce max_body_bytes:, validate Origin and reject duplicate JSON keys:

defmodule MyApp.MCPEndpoint do
  def init(_opts) do
    ExAgent.MCP.Server.Plug.init(
      server: MyApp.MCP,
      origins: ["https://app.example"],
      max_body_bytes: 1_048_576,
      authorize: &__MODULE__.authorize/1
    )
  end

  def authorize(conn) do
    case conn.assigns[:verified_principal_id] do
      id when is_binary(id) and id != "" -> {:ok, id}
      _ -> {:error, :unauthenticated}
    end
  end

  defdelegate call(conn, opts), to: ExAgent.MCP.Server.Plug
end

defmodule MyApp.MCPRouter do
  use Plug.Router

  plug :match
  plug :dispatch

  forward "/mcp", to: MyApp.MCPEndpoint
end

Authorize the catalogue per principal

Filter visible tools, resources and prompts per authenticated principal with :catalog_policy (hidden entries return the exact same error as unknown names so callers cannot enumerate restricted tools):

grants = %{
  "alice" => %{tools: ["echo"], resources: ["memo:help"], prompts: ["review"]},
  "bob" => %{tools: ["chat"]}
}

catalog_policy = fn %{principal: principal, kind: kind} ->
  {:ok, get_in(grants, [principal, kind]) || []}
end

[
  {ExAgent.MCP.Server,
   name: MyApp.MCP,
   tools: [echo, chat],
   resources: [%{uri: "memo:help", name: "Help", text: "Request an inventory check."}],
   prompts: [%{name: "review", messages: [%{role: "user", text: "Review inventory."}]}],
   catalog_policy: catalog_policy,
   catalog_policy_timeout: 500}
]

Serve stateless HTTP across replicas

Set protocol_version: "2026-07-28" on ExAgent.MCP.Server.Plug to run stateless multi-replica MCP behind any load balancer without sticky sessions. Annotate schema properties with "x-mcp-header" to expose HTTP routing headers (Mcp-Param-Order):

%{
  "type" => "object",
  "properties" => %{
    "order" => %{"type" => "string", "x-mcp-header" => "order"}
  },
  "required" => ["order"]
}

Approve a stateless MCP tool

Configure mrtr_approval: on ExAgent.MCP.Server with a shared store and MAC key to support signed multi-replica tool approvals cleanly across stateless HTTP nodes.

Publish OAuth protected resource metadata

Pass protected_resource: to ExAgent.MCP.Server.Plug (with :resource, :authorization_servers and :scopes_supported) and mount both /.well-known/oauth-protected-resource and /.well-known/oauth-protected-resource/mcp alongside your /mcp route so OAuth clients can discover authorization servers automatically.

Note that direct ExAgent.MCP.Client.call_tool/3 calls return raw text or projected content, whereas discovered ExAgent.MCP.Client.tools/1 callbacks enforce each tool's declared object outputSchema before returning {:ok, map}.

API: ExAgent.MCP.Client, ExAgent.MCP.Client.Tasks, ExAgent.MCP.Server, ExAgent.MCP.Server.Plug.