Turn functions in your Elixir app into tools that AI clients can call through the Model Context Protocol (MCP). McpHouse also gives your app a client for other MCP servers.
- Serve tools from your existing router. Mount one Plug in Phoenix or Plug.Router. Each handler receives validated arguments and the authenticated connection. Serve a tool
- Use remote and local tools. Connect to a server over HTTP or launch a local process over stdio. The same client can read resources, fetch prompts, and request completions. Call a tool
- Keep session storage in your application. Start stateless, use the built-in memory store, or supply your own adapter to share sessions across nodes. Configure sessions
- Bound tool execution. Set a deadline per mount or tool and track outcomes with telemetry. Request logging is opt-in. Configure deadlines and telemetry
MCP protocol support
The HTTP server enables only 2026-07-28 by default. To accept a legacy revision, include it in the mount’s :protocol_versions list.
| Protocol version | Server | Client | New features |
|---|---|---|---|
| 2026-07-28 | ✅ | ✅ | • Stateless requests<br>• server/discover<br>• HTTP routing headers |
| 2025-11-25 | ✅ | ✅ | • OpenID Connect discovery<br>• SSE polling |
| 2025-06-18 | ✅ | ✅ | • Structured tool output<br>• MCP-Protocol-Version header |
| 2025-03-26 | ✅ | ✅ | Streamable HTTP and JSON-RPC batches |
| 2024-11-05 | ✅ | ✅ | HTTP+SSE with separate stream and message endpoints |
Installation
def deps do
[
{:mcp_house, "~> 0.1.0"}
]
endServe an MCP tool
Define a tool with an input schema and a handler, then mount it at the path your app chooses.
defmodule MyApp.MCP do
def options do
[
name: "MyApp",
version: "1.0",
tools: [
%{
name: "echo",
description: "Return the supplied text",
input_schema: %{
"type" => "object",
"properties" => %{"text" => %{"type" => "string"}},
"required" => ["text"]
},
handler: &__MODULE__.echo/2
}
]
]
end
def echo(%{"text" => text}, _conn), do: {:ok, text}
endIn a plain Plug router, forward with the tool options.
defmodule MyApp.Router do
use Plug.Router
plug :match
plug :dispatch
forward "/mcp", to: McpHouse.Server, init_opts: MyApp.MCP.options()
endIn a Phoenix router, use the same options in the appropriate API scope.
scope "/" do
pipe_through :api
forward "/mcp", McpHouse.Server, MyApp.MCP.options()
end- Access control. Authenticate in the host pipeline before forwarding. Use
:tool_visible?with the tool name and connection to filter both listings and direct calls. Check resource-specific permissions in the handler. - Tool results. Return
{:ok, value}or{:error, user_facing_value}with UTF-8 text or a JSON object. Clients receive objects as bothstructuredContentand JSON text. Add hints such as"readOnlyHint"in the tool’s:annotationsmap. - HTTP limits. Add each allowed browser origin to
:allowed_origins. The server caps bodies it reads at 1 MiB. IfPlug.Parsersreads the body first, set the limit there.
Call an MCP tool
Use the client from an Elixir application or a Phoenix context. Give it the server's MCP endpoint and pass tool arguments as a map.
alias McpHouse.Client
with {:ok, client} <- Client.connect("http://127.0.0.1:8000/mcp"),
{:ok, %{"tools" => tools}} <- Client.list_tools(client),
{:ok, result} <- Client.call_tool(client, "echo", %{"text" => "hello"}) do
{:ok, tools, result}
endThe client accepts JSON and SSE replies over Streamable HTTP. A tool execution
error is reported in the result's "isError" field. A JSON-RPC error returns
{:error, {:rpc, error}}. Run bin/setup-tests and then mix test --include python to exercise the
client against the Python SDK.
The client defaults to automatic negotiation. To start directly with the
2025-11-25 handshake, use
Client.connect(url, protocol_version: "2025-11-25"). When finished, call
Client.close(client) to release a server-assigned session. If a session
expires, the client returns {:error, :session_expired}. Call connect/2
again to open a new session.
Server configuration
Handshake-era clients and session storage
To serve all five revisions, add the following option to the mount.
protocol_versions: ~w(2026-07-28 2025-11-25 2025-06-18 2025-03-26 2024-11-05)During initialize, the server accepts an enabled handshake revision or offers
the first enabled handshake revision for the transport. Session storage is optional.
For 2024-11-05, point the client at the mount URL (for example,
Client.connect(url, protocol_version: "2024-11-05")). A GET opens the SSE
stream and advertises the POST URL under the mount, such as
/mcp/messages?session_id=…. Forward both paths to the Plug. In a multi-node
deployment, route the POSTs to the node holding the stream. Closing the
client closes its stream. The stdio client also accepts all five revisions.
Legacy clients carry the method and tool arguments in the JSON body. If your
upstream access policy relies on modern routing headers, keep the mount on
2026-07-28.
To bind handshake sessions to authenticated users, configure a session store.
defmodule MyApp.MCPIdentity do
def principal(conn), do: conn.assigns[:authenticated_client_id]
end
# Merge these options into the existing MCP mount options.
[
protocol_versions: ["2026-07-28", "2025-11-25", "2025-06-18"],
sessions: [
namespace: "public-catalog",
principal: &MyApp.MCPIdentity.principal/1,
store: {McpHouse.Server.SessionStore.Memory, MyApp.MCPSessions}
]
]- Supervision and routing. Start
{McpHouse.Server.SessionStore.Memory, name: MyApp.MCPSessions}in your supervision tree. It stores sessions on one BEAM node until restart. Use sticky routing or supply a shared adapter. - Session scope. Each handshake session gets an opaque ID. Omitting
:sessionskeeps Streamable HTTP handshakes stateless. To require a session for every tool call, enable only handshake revisions. - Identity. Authenticate every request upstream. Return a stable, nonempty binary from the principal callback, such as a grant ID or an unambiguous issuer and subject pair. Give each mount its own namespace when sharing a backend.
- Expiry. Idle sessions expire after 30 minutes and all sessions expire after 24 hours by default. Set
:idle_timeoutand:max_lifetimein milliseconds to change either limit. The memory store checks expiry on access and sweeps every 60 seconds. - Streamable HTTP follow-up requests and DELETE. Send the negotiated revision and session ID with both. A successful DELETE returns 204. Work admitted before deletion or expiry may finish.
| HTTP status | Session outcome |
|---|---|
| 400 | The session owner supplied a different revision. |
| 401 | The principal callback found no authenticated identity. |
| 404 | The session is inaccessible or expired. |
| 503 | The store or identity provider is unavailable. |
App-owned adapters. Set store: {MyApp.MCPSessionStore, MyApp.Repo}.
Implement the McpHouse.Server.SessionStore behaviour in your module. The
first argument to every callback is the supplied repo or backend reference.
defmodule MyApp.MCPSessionStore do
@behaviour McpHouse.Server.SessionStore
# MyApp.SessionQueries supplies the backend-specific atomic operations.
@impl true
defdelegate open(repo, namespace, principal, revision, idle_ms, lifetime_ms),
to: MyApp.SessionQueries
@impl true
defdelegate admit(repo, namespace, session_id, principal, revision, action),
to: MyApp.SessionQueries
@impl true
defdelegate close(repo, namespace, session_id, principal, revision),
to: MyApp.SessionQueries
endopen/6 returns {:ok, id} for a fresh cryptographically random ID.
admit/6 verifies ownership, revision and expiry atomically with the idle
refresh. Its action is :request or :initialized. close/5 checks the
same conditions atomically with deletion. A closed session cannot be revived
by a concurrent admission. The adapter reports :ok or a tagged error, and
McpHouse maps that outcome to MCP and HTTP. Use the store's clock for TTLs.
Run the reusable provisional contract in your own ExUnit suite. Load
Path.join(:code.priv_dir(:mcp_house), "session_store_contract.exs") with
Code.require_file/1, then use McpHouse.Server.SessionStore.Contract.
Supply %{store: {module, ref}, advance: advance_clock_by_ms} for each case.
In this repository, mix test --include python test/mcp_house/server_store_test.exs
also checks an independent SQLite adapter across two BEAM nodes using Python 3.
Handler deadlines and telemetry
Set handler_timeout: 5_000 on a mount to bound listing, visibility and
tool execution. A tool map can set its own :handler_timeout, including a
longer duration. The default :infinity runs inline. With a finite limit,
a request-owned worker runs the callbacks, so handlers should use connection
assigns for caller context. McpHouse.Server.remaining_time(conn) returns
the remaining milliseconds or :infinity for downstream calls.
Expiry terminates the worker before replying with JSON-RPC code -32603
and data.type equal to "handler_timeout". Terminating the request process
also stops its worker. Hosts own independently spawned tasks, database
transactions, and any effects already committed to external services.
Attach telemetry handlers to [:mcp_house, :server, :session] for an operation
count and [:mcp_house, :server, :execution] for a duration in native time
units. Both events carry only :operation and :outcome metadata.
The server emits no request logs by default. To diagnose a particular mount,
set its Plug option log: :debug and enable debug output in the host's
Elixir Logger configuration. Each completed HTTP exchange emits one debug
message with the HTTP verb category, status and elapsed microseconds. The
measurement spans the Plug call through the adapter sending the response,
including early rejection, timeouts and store outages. Requests terminated
before a response completes have no completion log. The host controls
formatting, filtering and destinations. Use the telemetry events above for
per-operation measurements.
Tools with HTTP header parameters
For a tool that declares x-mcp-header on an argument, pass its definition
from list_tools/2 as the second argument to call_tool/4. McpHouse mirrors
the annotated values into Mcp-Param-* headers on 2026-07-28.
with {:ok, %{"tools" => tools}} <- Client.list_tools(client),
%{} = tool <- Enum.find(tools, &(&1["name"] == "routed_echo")) do
Client.call_tool(client, tool, %{"region" => "west", "limit" => 12, "enabled" => true})
endCalls by name still work. If the server rejects a modern call with a header mismatch, McpHouse refreshes the tool definition and retries once when the headers change. The Python interoperability tests exercise this retry against an annotated tool.
Resources, prompts, and completions
The same client APIs work in plain Elixir and in a Phoenix context. List functions
return one page. Pass the server's nextCursor back as :cursor for the
next page.
{:ok, %{"resources" => resources}} = Client.list_resources(client)
{:ok, %{"contents" => contents}} = Client.read_resource(client, "note://weekly")
{:ok, %{"prompts" => prompts}} = Client.list_prompts(client)
{:ok, prompt} = Client.get_prompt(client, "greet", %{"name" => "Ada"})
{:ok, completion} =
Client.complete(client, %{"type" => "ref/prompt", "name" => "greet"},
%{"name" => "name", "value" => "A"})Client.list_resource_templates/2 lists templated URIs. The client returns
{:error, {:unsupported_capability, capability}} when the server does not
advertise the required feature.
Optional stdio transport
On Unix, add {:erlexec, "~> 2.4", runtime: false} to the host app to use
stdio. The process manager starts when connect_stdio/3 runs. For a Mix
release that uses stdio, include erlexec: :load in its applications. The
process manager needs a configured SHELL and builds a native executable.
{:ok, local} = Client.connect_stdio("/path/to/python", ["server.py"])
{:ok, listing} = Client.list_tools(local)
:ok = Client.close(local)The process calling connect_stdio/3 owns the subprocess.
Protected HTTP endpoints
Pass a bearer token string or a zero-arity token provider to
Client.connect(url, bearer_token: ...). Use a provider callable from other
processes when starting asynchronous calls or subscriptions.
McpHouse.Client.OAuth.discover/2 discovers protected-resource and issuer
metadata for a caller-selected issuer. begin_authorization/2 builds a
PKCE authorization URL for a supplied client ID and redirect URI.
The host app presents the URL and sends the callback parameters to
exchange_code/2. The host also owns token storage and can use refresh/3
to obtain a replacement token. Discovery accepts resource metadata URLs on
the MCP endpoint's origin and uses HTTPS for remote endpoints.
For a hosted HTTP client, pass network_policy: [] to require verified
HTTPS and public destination addresses. Set options inside the
network_policy: list. For example, pass
network_policy: [allow_endpoint: fn uri -> uri.host == "mcp.example.com" end]
to approve the endpoint before DNS resolution. A custom resolver can return
IPv4 and IPv6 tuples. McpHouse validates the results before connecting and
preserves the original hostname for TLS and HTTP. Set :allow_address
inside the same list when the host needs to allow specific private addresses.
Pass the same policy to OAuth discovery to cover its metadata and token requests.
Use headers: for static custom headers and request_headers: for a unary
provider that returns {:ok, headers} or {:error, reason}. The provider
can return a saved OAuth header set. Use admit: to recheck permission
immediately before each request is written. Both callbacks receive the
endpoint, HTTP method, RPC method, session ID, monotonic deadline, and
request purpose. For retirement traffic, supply a separate cleanup_headers:
provider that grants use of existing credentials. This covers session DELETE,
legacy cancellation, and unsubscribe, including recovery of a cleanup response.
The HTTP :timeout applies to the whole operation, including SSE recovery.
Set :limits to tune setup, cleanup, and listener idle timeouts and the
request, response, SSE frame, and aggregate SSE stream byte limits. The client
accepts identity encoding. See McpHouse.Client.connect/2 for option names and
defaults.
Progress, subscriptions, and elicitation
Pass on_progress: fn params -> ... end to call_tool/4. Use
start_tool_call/4 when the caller needs to cancel a running request or
continue other work. await/2 collects its result and cancel/1 stops it.
On a resumable 2025-11-25 SSE response, the client resumes by event ID
without resending the tool call.
Set submission_errors: true on an HTTP tool call to receive
{:error, {category, reason}}. The categories are :not_submitted when the
client stopped before attempting a write, :remote_error for a correlated
JSON-RPC error, and :outcome_unknown when a write may have reached the server.
The same option applies to the terminal result returned by await/2 after
cancellation.
Use Client.subscribe/4 for HTTP change events. Pass a filter such as
%{"toolsListChanged" => true} and an event callback. The :on_ready
callback receives the supported filter. Open one legacy listener per
session and use Client.cancel/1 to close it. Call Client.await/2 to collect
the terminal result. If legacy cleanup fails,
close the HTTP session.
Set on_elicitation: fn params -> ... end when connecting to handle server
requests for user input. Return a map with "action" set to "accept",
"decline", or "cancel". Include "content" with accepted form values.
The client sends a legacy response or continues a modern input round
according to the negotiated revision. The host decides how to present the
prompt to the user.
Development and releases
With Git, Elixir, Hex, Erlang, and uv installed, run bin/setup-tests to fetch
locked Mix dependencies and prepare the Python SDK used by the interoperability
tests. Run mix lint and mix test for the default checks. To include the
Python interoperability and server contract tests, run
mix test --include python --include python_server_contract.
Run scripts/verify-server to exercise the mounted Plug against the pinned Python client and upstream JSON transport tests using ephemeral loopback listeners.
Run bin/bump-version patch, minor, or major to update the package version
in mix.exs. Rename the ## Unreleased heading in CHANGELOG.md to
## X.Y.Z - YYYY-MM-DD and commit the release notes with the version change.
Then run bin/release to create
the local vX.Y.Z tag. Pushing the tag and publishing to Hex are separate steps.