The server core is synchronous: Snodo.Server.dispatch/3 runs one JSON-RPC
request in the calling process against an immutable runtime. Transports add
framing, concurrency, cancellation, and delivery around that core.
raw JSON-RPC map
-> protocol registry and exact profile inspection
-> selected dialect: context and admission
-> core operation or negotiated extension route
-> router callback (tool, resource, prompt, completion)
-> protocol-neutral result, or an opened subscription
-> selected dialect: wire and stream shapingExecutor
Snodo.Server.Executor is the transport-neutral execution layer: bounded
admission, a bounded queue, deadlines, cancellation tokens, and supervised
worker tasks, with cleanup when the submitting process dies. Stdio, native
HTTP, and Plug use it. An application can inject its own executor.
:max_concurrency (default 32) bounds running work and :max_queue (default
- bounds work waiting for a slot, in one first-in, first-out queue for
every submitter. With both full, a request is refused with -32603
Server execution capacity exhausted(HTTP 503).
The executor's :default_timeout (30,000 ms) covers both queue wait and
execution, starting at executor admission. A per-submit :timeout overrides
it. Stdio, native HTTP, and Plug each pass an explicit :request_timeout to
the executor. Each transport defaults to 30,000 ms, including with an
injected executor. Progress leaves the deadline fixed. The executor admits
work through one coordinator and provides no per-peer fairness or adaptive
load shedding. The executor load record
measures both transports at 1,000 concurrent requests with the repository's
snodo.load Mix task; it predates the queue-wait deadline.
:max_queue_wait sets an additional queue cap in milliseconds. It accepts a
non-negative integer or :infinity (the default). The effective queue limit
is the smaller of the cap and the request timeout. A cap of zero expires any
admitted work that needs to queue. Set this option on stdio or native HTTP
when they own the executor, or on the injected executor directly.
A request that expires while queued is removed and reported as
:queue_timed_out without invoking its handler. Stdio, native HTTP, and Plug
return JSON-RPC -32603 with the message Request expired in the execution queue. HTTP uses 504 for an admitted request whose deadline elapsed and 503
for a request refused at admission because the queue was full.
Limits on message content
Every transport decodes JSON with the same limits. An integer literal longer
than 64 digits is a parse error (-32700). A request id must be a string of at
most 256 bytes or an integer in the int64 range (-32600 otherwise), and a
progressToken must meet the same bounds (-32602 otherwise). These values are
echoed in every response and notification for a request, so an error for a
request whose id is out of bounds carries a null id instead.
Resource template matching is linear in the length of the requested URI, with no backtracking, so the message size limit bounds it. Templates themselves are limited to 1,024 bytes and 32 variables when the resource module compiles; see Components.
Stdio
:ok = Snodo.Transport.Stdio.serve(MyServer.runtime())serve/2 runs until EOF and until admitted requests finish, then returns.
Messages are one JSON object per line. Requests run concurrently, responses are
written atomically, and notifications/cancelled stops a request with no late
response. Output escapes non-ASCII characters as JSON \u escapes, so the
bytes do not depend on the device's encoding.
Options include :input and :output devices, :write_timeout (default
5,000 ms; a blocked write is terminal), :max_line_bytes (default 2,000,000;
a longer message is refused with -32600 before decoding), :request_timeout,
and :executor. A leading UTF-8 byte order mark is ignored.
Standard input is read in chunks that hold at most :max_line_bytes of a line
when the VM runs with -noinput, and on OTP 28 and later when stdin is a
socket, as Node.js clients provide. Otherwise the VM holds each line in full
before the limit applies. Clients that start the server with a pipe, as Python
and Erlang clients do, are bounded only with -noinput: elixir --erl -noinput,
emu_args for an escript, or vm.args for a release.
An application process can send its own server-to-client notification on an
open stdio connection, for example a vendor hint while the connection is idle.
Enable the method names with :notification_methods (default []; each must
start with notifications/ and not be one the protocol defines), then call
Snodo.Transport.Stdio.notify(transport, method, params) with the transport's
pid or :name. The frame has no id and goes through the same serialized write
path as responses. A disallowed method or non-map or non-JSON params returns
{:error, %Snodo.Error{}} and writes nothing; a closed connection returns
{:error, :closed}; a failed or timed-out write is terminal, as for any
output, and returns {:error, {:output_failed, reason}}; if the transport
process exits during the call, it returns {:error, {:transport_down, reason}}.
There is no queue: callers wait for their own write, each bounded by the call
timeout (default 10,000 ms), and nothing is retried. If the call returns
{:error, :timeout}, the caller stopped waiting and it is unknown whether the
frame was written; do not assume it was or was not delivered.
With :output set to :stdio, the transport redirects the default
:logger_std_h handler from stdout to stderr so stdout carries only protocol
messages. The redirect is VM-wide. The last transport using it restores the
original handler configuration if the installed configuration is still
current. If the application changed or removed the handler in the meantime,
it is left as is. Set redirect_logger?: false to skip the redirect.
With standard output, stdio also routes raw handler IO such as IO.puts/1 to
stderr when the standard error device is available.
sessions: true makes the connection the session of an initialize-era client;
see Initialize-era sessions.
Native HTTP listener
children = [
{Snodo.Transport.StreamableHTTP.Server, runtime: MyServer.runtime(), port: 4000}
]Or through the server's generated child spec, which supplies the runtime:
children = [
{MyServer, transports: [{Snodo.Transport.StreamableHTTP.Server, port: 4000}]}
]A dependency-free listener that binds to 127.0.0.1 by default and serves
POST /mcp. A connection serves further requests after each complete
response (HTTP/1.1 keep-alive), and closes after an error response, an event
stream, Connection: close, or an HTTP/1.0 request. It answers:
application/jsonfor ordinary results.text/event-streamwhen a handler reports progress, and forsubscriptions/listen, with keepalive comments and proxy buffering disabled.- 405 for GET and DELETE at
/mcp, and no session IDs, unless initialize-era sessions are on.
It checks media types, the mirrored MCP-Protocol-Version, Mcp-Method, and
Mcp-Name headers, the Mcp-Param-* headers for a tool's x-mcp-header
arguments (see Components) for
tools in the router or served by an extension's tool_input_schema/2, such
as Snodo.Proxy's merged tools, and
Origin when present: loopback names by default,
:allowed_origin_hosts to change, where an entry with a port
("localhost:3000") pins the port and an Origin with userinfo is refused.
:allowed_hosts additionally requires the Host header to name a listed host.
It is off by default, because a reverse proxy commonly forwards the public name.
A client disconnect cancels the request.
Options include :ip, :port, :path, :request_timeout, :read_timeout,
:max_header_bytes (32 KB, including the final \r\n\r\n), and
:max_body_bytes (2 MB). Body bytes received with the head count only toward
:max_body_bytes.
The listener is unauthenticated unless :request_gate is set to a
{module, options} implementing Snodo.Transport.StreamableHTTP.RequestGate.
The gate sees the parsed method, path, and headers before the body is read. It
can serve a separate route, refuse the request, or return trusted identity for
Snodo.Authorization. An invalid result or exception fails closed with 500.
The listener bounds the gate with :request_gate_timeout; the gate must also
bound and clean up any external calls it makes. For OAuth bearer tokens and
protected resource metadata, use Snodo.OAuth.ResourceServer.Native from
snodo_oauth.
Binding :ip outside loopback logs a startup warning, even with a request
gate: the native listener still serves plaintext HTTP. Bind it privately
behind a TLS reverse proxy, or use Snodo.Transport.Plug in an HTTP server
with TLS. Configure authentication with a request gate or in the Plug pipeline.
The listener also bounds what clients can hold open:
:max_connections(default 1,024). A connection accepted at the limit is closed without being read.:backlog(default 1,024, matching:max_connections). Connections the kernel holds before the listener accepts them, capped on Linux bynet.core.somaxconn. The kernel decides what happens to connection attempts that overflow it. In the executor load record, a burst of 1,000 connections against a backlog of 128 on Linux had clients retrying after about a second.:head_timeout(default 10,000 ms from accept). The request head must be complete by then;:read_timeout(5,000 ms) still bounds each read.:keepalive_timeout(default 5,000 ms). How long an idle connection waits for its next request before it closes. The next request's:head_timeoutstarts when its first bytes arrive.:max_keepalive_requests(default 100). The most requests one connection serves; the last response carriesConnection: close.:request_gate_timeout(default 10,000 ms). A gate that does not return in time gets a 504 response.:body_timeout(default 10,000 ms from the end of the head, or from gate admission when a gate is configured). The request body must be read by then;:read_timeoutstill bounds each read.:max_subscriptions(default 256). Asubscriptions/listenstream over the limit is closed at its source and the request gets 503. A slot returns when the connection serving a stream exits, including a client disconnect.:drain_timeout(default 5,000 ms). How long a stopping listener waits for open connections; see Shutdown.
Snodo.Transport.StreamableHTTP.Server.url/1 returns the endpoint URL, which is
useful with port: 0 in tests.
MCP Server Cards
| Option | Default | Meaning |
|---|---|---|
:server_card | false | Set to %{endpoint_url: "https://example.com/mcp"} to publish a card. Use the external Streamable HTTP endpoint URL, including the path clients use through any reverse proxy. |
The native listener and Plug append /server-card to the configured MCP
:path after removing trailing slashes. For example, /services/mcp serves
the card at GET /services/mcp/server-card. Serve it over HTTPS with TLS 1.2
or later in production. For the native listener, terminate TLS at a reverse
proxy. Use the proxy or HTTP server to apply request rate limits.
The route uses application/mcp-server-card+json, wildcard CORS, and
Cache-Control: public, max-age=3600. GET and HEAD return 304 when
If-None-Match matches the ETag. HEAD includes the card's content length
and an empty body. OPTIONS returns 204, including for browser preflight.
Other methods receive 405. The card route applies :allowed_hosts and accepts cross-origin
requests independently of :allowed_origin_hosts. The native request gate
is bypassed for the card route. In Plug, allow the card route through the
application's authentication pipeline so anonymous clients can retrieve it.
The Plug README shows a wrapper that routes the card before bearer
authentication. Plug Server Card setup
The configured endpoint must be an absolute HTTP(S) URL without user
information, query, or fragment. The same URL rules apply to the optional
websiteUrl field. The runtime must supply a
namespace/name of 3 to 200 characters, a single version string of at most
255 characters, and a description of 1 to 100 characters. An optional title
must also contain 1 to 100 characters. Invalid card configuration or
metadata raises ArgumentError when the transport initializes. Review the
published identity fields, including links and icons, for public suitability.
See Server Cards for the optional AI Catalog.
Shutdown
When the listener stops, including when its supervisor shuts it down, it drains before exiting:
- The listening socket closes. New connections are refused.
- A connection whose request head or body is still arriving gets 503 and closes. A request read in full before the drain began runs to its response.
- Each open
subscriptions/listenstream gets its successful completion response, its source is closed with reason:shutdown, and the connection closes. - Connections still open after
:drain_timeout(default 5,000 ms) are killed. Their executor work is cancelled and their subscription sources are closed. - An executor the listener started is stopped. An executor passed with
:executorkeeps running.
The default drain covers ordinary tool calls and fits, with the rest of an
application's shutdown, inside common stop windows such as Docker's 10-second
default. A platform with a shorter stop window, such as Fly's default 5-second
kill_timeout, needs a smaller :drain_timeout or a longer platform timeout.
Raise it toward :request_timeout when requests run longer and the host allows
a longer stop.
The listener's child spec sets :shutdown to :drain_timeout plus 5,000 ms so
the supervisor waits for the drain. A child spec that overrides :shutdown
must keep it above :drain_timeout; a supervisor that kills the listener
earlier skips the rest of the drain. The release or platform that stops the VM
must allow for the drain as well.
JSON-RPC errors over HTTP
The native listener and Snodo.Transport.Plug use the same status rules for
2026-07-28. The response body carries the JSON-RPC error and its request ID.
| Error source | JSON-RPC code | HTTP status |
|---|---|---|
| Malformed JSON or invalid JSON-RPC request | -32700 or -32600 | 400 |
| Invalid params during request admission or protocol validation | -32602 | 400 |
| Internal failure during request admission or protocol validation | -32603 | 500 |
| Missing or mismatched routing headers, missing client capability, or unsupported protocol version | -32020, -32021, or -32022 | 400 |
| Unknown RPC method | -32601 | 404 |
| Invalid params or internal failure during method execution, including a missing resource or a handler exception | -32602 or -32603 | 200 |
For these two codes, the status depends on whether request validation passed.
validate_route/5 calls the dialect's or extension's validate_operation/3.
Once that validation passes, errors from lookups, middleware, handlers, and
result shaping belong to method execution. For example:
- A non-string
cursorgets 400. A well-formed cursor from a stale catalog gets 200. - A non-map
inputResponsesgets 400. An invalid answer consumed from a valid map gets 200. - Tasks middleware reports
Task input is larger than N byteson 200. This error previously used 400. - Non-object
tools/callargumentsget 400. Tool schema validation failures, including missing required arguments, continue to returnisErrorresults on 200.
A request timeout, including queue expiry, gets 504, a crashed worker or unavailable executor gets 500, capacity refusal gets 503, and a duplicate in-flight request ID gets 409. See the native listener limits and Plug limits.
If the HTTP response has already started as an SSE stream, the terminal JSON-RPC error is delivered in that stream with its committed status.
Initialize-era sessions
Clients of the opt-in 2025-11-25 and 2025-06-18 dialects (see
Initialize-era clients) can have a session. With
one, a handler's input requests reach them as server-initiated
elicitation/create, sampling/createMessage, and roots/list requests, and
resources/subscribe, resources/unsubscribe, and list_changed notifications
work. Sessions are off by default; without them the dialects run sessionless.
2026-07-28 requests never use a session, whatever the setting.
| Transport | Option |
|---|---|
| Native HTTP listener | sessions: true, or a keyword list of Snodo.Session.Manager options. The listener starts its own manager. |
Snodo.Transport.Plug | sessions: MyApp.MCPSessions, the name of a Snodo.Session.Manager the application starts before the HTTP server. |
| Stdio | sessions: true. The connection is the session and no ID is issued. |
children = [
{Snodo.Subscription.Hub, name: MyApp.Hub},
{Snodo.Transport.StreamableHTTP.Server,
runtime: MyServer.runtime(subscription_source: Snodo.Subscription.Hub.source(MyApp.Hub)),
port: 4000,
sessions: [max_sessions: 512, idle_timeout: :timer.minutes(10)]}
]A handler written for 2026-07-28 input requests serves these clients
unchanged. It returns Snodo.Result.input_required/1; the transport sends each
input request to the client as a JSON-RPC request on the original request's
event stream (or the stdio connection), waits for the answers, and calls the
handler again with the answers in Snodo.Context.input_responses and the
result's requestState in Snodo.Context.request_state. Every round runs
inside the request's :request_timeout, so a server that waits for people to
answer elicitations needs a longer one than the 30-second default. At most 10
rounds run before the request fails with -32603, and a client that answers an input request with an error fails
the request with that error. Cancelling the request, or ending the session,
ends the exchange. A client that did not declare the capability an input
request needs gets -32021, as on 2026-07-28. A 2025-06-18 client receives form
elicitations without mode, which that revision does not define.
With a :subscription_source on the runtime, initialize advertises the
runtime's listChanged and resources.subscribe settings, and the session
opens the source for them. Over HTTP the events go out on the session's
standalone GET stream; an event that arrives while no stream is open is
dropped. A resource the authorization policy does not let the principal read
is not subscribed, and resources/subscribe still answers {}. A source
that refuses the changed filter answers the request with its error, and the
session keeps the resources and the subscription it had.
Over HTTP:
| Request | Answer |
|---|---|
initialize | Starts a session and returns its ID in Mcp-Session-Id (32 URL-safe base64 characters from :crypto.strong_rand_bytes/1). A failed initialization keeps no session, and an initialize sent as a notification starts none. |
Any other request, notification, or response without Mcp-Session-Id | 400. A response object that names no initialize-era version gets 202, as without sessions. |
| An unknown or expired ID, or a session bound to another principal | 404 with JSON-RPC code -32001. A new session starts with an initialize request without a session ID. |
MCP-Protocol-Version that differs from the session's | 400 |
| A JSON-RPC response object | Routed to the server request waiting for it; 202 |
notifications/cancelled | Cancels the named request in flight on the session; 202 |
GET with Accept: text/event-stream | The standalone stream, with a keepalive comment every :subscription_keepalive_ms (the Plug's at most every :disconnect_probe_ms). A second one for the same session gets 409. |
GET or DELETE naming 2026-07-28 | 405 with Allow: POST, as without sessions |
DELETE | Ends the session; 200 |
When Snodo.Client receives HTTP 404 on an initialize-era request carrying
a session ID, it invalidates the session and returns a transport error with
cause: :session_not_found. This applies to bare 404s, JSON-RPC error bodies,
and POST responses that advertise SSE. Reconnect the client
to initialize a new session.
A session is bound to the principal that created it: the auth value a request
gate returns, or the Plug's auth assign. Authentication still runs on every
request, and a request with the session's ID and a different principal is
answered as if the session did not exist. By default the principal is the
:principal and :client_id of an auth map that has a :principal key (the
shape snodo_oauth assigns, so a refreshed token for the same subject keeps
the session), and the whole auth value otherwise; the manager's :principal
option takes a function to change that.
Limits, each with a default and a defined failure:
:max_sessions(default 1,024). Aninitializeover the limit gets 503.:idle_timeout(default 1,800,000 ms, 30 minutes). A session with no request, answer, or open stream for that long ends, and its ID gets 404.:infinitykeeps sessions untilDELETEor shutdown.- One standalone stream per session; a second
GETgets 409. - 1,000 subscribed resources per session, the bound on one 2026-07-28
subscriptions/listenrequest. One moreresources/subscribegets -32602. - The request's existing bounds apply to each exchange:
:request_timeoutacross all rounds,:max_body_bytesfor each answer, and 10 rounds.
A session process runs on the node that handled initialize. The manager
finds sessions through a Snodo.Session.Registry, Snodo.Session.Registry.Local
by default, and the core does not route requests between nodes. A deployment
with more than one node behind a load balancer needs sticky routing that sends
every request carrying a given Mcp-Session-Id to the node that issued it;
otherwise a request that lands elsewhere gets 404 and the client starts over.
There is no Last-Event-ID replay: a dropped stream loses the events sent
while it was closed, and the client opens a new one with GET.
Component limits
The opt-in wrappers in Snodo.Component.Wrap bound individual tools,
resources, and prompts after router checks. They apply to direct, stdio, and
HTTP requests alike. Their defaults are:
| Wrapper | Default | Defined failure |
|---|---|---|
Timeout | timeout: 5_000 ms | Component timed out |
Concurrency | limit: 32 in-flight callbacks per component and key | Component concurrency limit reached |
RateLimit | limit: 60 calls per window_ms: 60_000, max_keys: 10_000 per component | Component rate limit reached or Component rate key capacity reached |
All numeric options must be positive integers; an invalid declaration fails
compilation. Concurrency and rate wrappers use one shared bucket by default.
Pass key: fn context -> ... end to group by a stable context value such as a
verified principal. The core application owns the counters. Concurrency
permits return when a callback finishes or its process exits. Rate buckets
start with the first call for a key and reset after the configured window;
expired keys are pruned when capacity is needed. Counts reset if the core
application restarts. A rejected rate call consumes no callback work, while
an admitted call counts even if its handler later fails.
The Timeout wrapper runs the callback in a supervised task linked to the
request owner. The shared task supervisor admits at most 1,024 concurrent
timeout workers and returns Component timeout worker unavailable when full.
It stops a task on timeout or owner termination, but cannot undo external
side effects. The built-ins return tool isError results, or
JSON-RPC error -32603 for resources and prompts. If the core application is
not running, they return a defined unavailable error.
Skills limits
use Snodo.Skills (see Extensions) checks every skill
when its module compiles, and Snodo.Skills.Client checks every file before
reading it:
| Option | Where | Default | Defined failure |
|---|---|---|---|
:max_skill_files | use Snodo.Skills | 512 files per skill, SKILL.md included | ArgumentError naming the skill; the module does not compile |
:max_skill_bytes | use Snodo.Skills | 16,777,216 bytes (16 MiB) per skill, all files | ArgumentError naming the skill; the module does not compile |
:page_size | use Snodo.Skills | 50 skills per skills/list page | A longer listing is paged; an invalid or expired cursor gets -32602 |
:directory_page_size | use Snodo.Skills | 100 children per resources/directory/read page | As for :page_size |
:max_response_bytes | use Snodo.Skills | 16,777,216 bytes (16 MiB) per response, 4,096 of them left for the envelope and 2 more for the brackets around a single file, entry, or child | A file's resources/read content, a skills/get entry, or a resources/directory/read child over it, on HTTP or stdio: ArgumentError naming it; the module does not compile. skills/list and resources/directory/read pages end early instead |
:max_file_bytes | Snodo.Skills.Client | 16,777,216 bytes (16 MiB) per file, by the listed size | -32000 with "reason" => "too_large"; nothing is read. A response over the transport's own limit fails with that transport error |
:max_pages | Snodo.Skills.Client.list/2 | the client's :max_pages, 1,000 | -32000 transport error |
| Frontmatter size | Snodo.Skills.Frontmatter built-in parser | 1,048,576 bytes (1 MiB), fixed | Snodo.Skills.Frontmatter.Error with reason :too_large: ArgumentError in use Snodo.Skills, -32000 with "reason" => "frontmatter_unreadable" in Snodo.Skills.Client |
| Number digits | Snodo.Skills.Frontmatter built-in parser | 1,000 digits per number, fixed | As for the frontmatter size |
The skill limits follow the sizes SEP-2640 recommends a server not exceed. For
:directory, the file count and the file sizes are checked before any file of
the skill is read, and the byte total is checked again as files are read, in
case one grew in between. A symbolic link under :directory raises
ArgumentError instead of being followed.
The two frontmatter limits apply to the built-in YAML subset only, not to a
configured :frontmatter_parser. Within them the parser runs in time linear
in the frontmatter size, so a hostile SKILL.md cannot make
Snodo.Skills.Client.load/3 or verify/4 raise or run for minutes.
skills/list and resources/directory/read cursors are opaque and stay under
100 bytes whatever the length of the directory URI, because the directory is
hashed into them. A cursor over 1,024 bytes, or one issued for another
listing, another directory, or another build of the catalog, gets -32602.
:max_response_bytes bounds the part of each response that comes from the
skills: the "contents" array of a resources/read result, which holds the
one file, the entry of a skills/get result, and the "skills" or
"resources" array of a skills/list or resources/directory/read page.
That part, an array measured with its brackets and commas, is kept at or
under :max_response_bytes less 4,096 bytes on both transports. Its size is
the larger of the HTTP encoding, raw UTF-8, and the stdio framing, which
writes every character outside ASCII as a \uXXXX escape (6 bytes for an
"é", 12 for a character above U+FFFF), measured with the framing itself. A
file's content, a skill entry, and a directory child are each checked when
the module compiles, and must take at most the budget less 2 bytes, so that
each fits in brackets as a page or a "contents" array of its own; a
skills/get entry, sent without brackets, is checked the same way because
it is also a skills/list element. Pages hold up to :page_size or
:directory_page_size entries, fewer when the next one would take the
array past the budget. A skill entry is never split across pages, and since
no single entry or child can be over the budget, every page but the last
advances.
Without this bound a default server could send more than a default client
reads (:max_response_bytes over HTTP and :max_line_bytes over stdio, both
16 MiB): a full skills/list page of 50 skills with 512 files each is about
4.2 MB with short file names and about 9.9 MB with 200-byte ones, and grows
with the frontmatter; a single 16 MiB file encodes to more than 16 MiB, a
binary one to about 21.3 MiB, and three million "é" (6 MB) to 18 MB on stdio.
At the defaults a binary file of more than about 12 MiB, or a text file whose
escaping takes it past the budget, fails compilation: raise
:max_response_bytes together with the client's limits, or keep such files
out of skills.
The whole response fits the client limit only if everything else in it fits
in the 4,096 bytes left over: the JSON-RPC envelope and the request id the
client sent, resultType, ttlMs, cacheScope, and on a page that has
more a nextCursor, and, for resources/read only, the _meta the core adds, which
carries the server's whole server_info under
io.modelcontextprotocol/serverInfo. The request id is bounded by the core:
Snodo.Envelope accepts a string of at most 256 bytes or an integer in the
int64 range, and answers any other id with -32600. The ttlMs is not
bounded: it is the :cache ttl_ms of use Snodo.Skills for the three
extension results and the server's :resources_cache ttl_ms for
resources/read, and each digit after the first adds a byte. A cursor is
skills1. and the unpadded base64url of [method, offset, scope], with a
16-character scope, so it takes 8 + ⌈4 × (J + k) / 3⌉ bytes for an offset of
k digits, where J is 35 for skills/list and 48 for
resources/directory/read: 56 and 74 bytes for a one-digit offset. The
offset indexes a list the server holds in memory, so it is below 2^64, at
most 20 digits, and the longest cursor the server can emit is 99 bytes, a
resources/directory/read cursor at 20 digits. With ttlMs 0, cacheScope
"private", and a server_info of a name and a version, that part is 174
bytes for a skills/list page with a cursor and 194 bytes for a
resources/read with the integer id Snodo.Client sends. With the largest
id the core accepts, a 256-byte string of control characters that JSON
writes as 1,536 bytes, it is 1,638 bytes for skills/get, 1,639 for a
skills/list page and 1,642 for a resources/directory/read page before
the 16 bytes of ,"nextCursor":"" and the cursor itself (so 1,711 and 1,732
with one-digit offsets), and 1,731 for a resources/read. So, with a
ttlMs of d digits and any accepted id, everything outside the skills array
takes at most 1,657 + d bytes plus the cursor, which is at most 1,756 + d
bytes, on a skills/list, skills/get, or resources/directory/read
response, which fits for any ttlMs of fewer than 2,341 digits, and at most
1,688 + d bytes plus the encoded server_info object on a resources/read
response. That response fits when
the encoded server_info (stdio-sized, as above) is at most 2,408 − d
bytes: 2,407 for a ttlMs of 0 to 9, 2,403 for 60,000. The core does not
bound server_info, and Snodo.Skills cannot check it: an extension does
not see it when the runtime is built, and a generated resource module sees
it only while it answers a request. So a server_info with large fields,
such as icons with data: URIs, can take a resources/read response whose
content is near the budget past the client limit. The server still sends it.
A default HTTP client then fails the request with -32000 and
cause: {:max_response_bytes, limit}; a default stdio client discards the
line, so the request times out with -32001. Keep the encoded server_info
within 2,408 − d bytes, or lower :max_response_bytes by the difference.
Plug and Bandit
The snodo_plug package provides Snodo.Transport.Plug for applications that
already run Plug, Bandit, or Phoenix, with their own authentication pipeline,
TLS, and timeouts:
children = [
{Snodo.Server.Executor, name: MyApp.SnodoExecutor, max_concurrency: 32, max_queue: 128},
{Bandit,
plug: {Snodo.Transport.Plug, runtime: MyServer.runtime(), executor: MyApp.SnodoExecutor},
ip: {127, 0, 0, 1},
port: 4000}
]It supports the same JSON, progress SSE, and subscription SSE lifecycles. Plug
only reveals a disconnect when a write fails, so a request still running after
:disconnect_probe_ms (default 5,000) switches to SSE and writes keepalive
comments; a failed write cancels the work. :max_subscriptions (default 256)
bounds open subscription streams; the count is held in the executor, so Plugs
that share an executor share it. :body_timeout (default 10,000 ms from when
the Plug starts reading) bounds the whole request body and answers 408; a
request that declares Transfer-Encoding gets 411 without being read. Over
HTTP/2 the deadline is checked only when an adapter read returns, so it does not
bound a client that keeps sending small DATA frames. :sessions names a
Snodo.Session.Manager for initialize-era sessions.
See
the snodo_plug documentation and the
application stack for choosing between the native
listener and Plug.
Phoenix endpoint
Add snodo_plug and Bandit to the Phoenix application's dependencies. Keep the
existing endpoint; start the executor before it in the application supervisor:
children = [
{Snodo.Server.Executor,
name: MyApp.SnodoExecutor, max_concurrency: 32, max_queue: 128},
MyAppWeb.Endpoint
]Mount the transport in a dedicated router pipeline. The authentication Plug
must verify the caller, assign trusted identity with
Plug.Conn.assign(conn, :mcp_auth, %{principal: user.id}), and send a 401 or 403
response with halt/1 when access is denied. Do not copy an unverified header
into the assign. A verified client-instance identifier may also be assigned to
:mcp_cancellation_scope for cross-request cancellation; distinguish client
instances even when they share a user. The transport does not authenticate
callers itself. For OAuth 2.1 bearer tokens, the
snodo_oauth package supplies that plug,
the protected resource metadata document, and a scope policy.
pipeline :mcp do
plug MyAppWeb.Plugs.MCPAuth
end
scope "/" do
pipe_through :mcp
forward "/mcp", Snodo.Transport.Plug,
runtime: MyApp.MCPServer.runtime(),
executor: MyApp.SnodoExecutor,
path: "/mcp",
max_body_bytes: 2_000_000,
read_timeout: 5_000,
body_timeout: 10_000,
request_timeout: 30_000,
allowed_origin_hosts: ["app.example.com"],
allowed_hosts: ["app.example.com"]
endPhoenix's forward evaluates its options when the router compiles and calls
Snodo.Transport.Plug.init/1 with them on every request. That works for a
runtime made only of data, as above. Refer to processes by registered name, not
pid: subscription_source: Snodo.Subscription.Hub.source(MyApp.SubscriptionHub) with
the hub started as {Snodo.Subscription.Hub, name: MyApp.SubscriptionHub}, because a pid
in the options would be the one from compile time. A runtime that holds a
function (an authorization option, a Tasks scope: function) cannot be
compiled into the router at all. For such a runtime, build the options once at
startup and forward to a small Plug that reads them:
defmodule MyAppWeb.MCPPlug do
@behaviour Plug
# Call from MyApp.Application.start/2 before starting the supervisor.
def configure do
opts =
Snodo.Transport.Plug.init(
runtime: MyApp.MCPServer.runtime(),
executor: MyApp.SnodoExecutor,
path: "/mcp"
)
:persistent_term.put(__MODULE__, opts)
end
@impl true
def init(opts), do: opts
@impl true
def call(conn, _opts),
do: Snodo.Transport.Plug.call(conn, :persistent_term.get(__MODULE__))
endforward "/mcp", MyAppWeb.MCPPlugPhoenix's forward removes the /mcp prefix from conn.path_info and adds it
to conn.script_name, but leaves conn.request_path as /mcp.
Snodo.Transport.Plug compares path: with conn.request_path, so keep the
full public path in that option. Replace the example hosts with the public host
names used by clients. An Origin header, when present, is checked against
allowed_origin_hosts; a value such as "localhost:3000" also restricts the
port. This is a host check, not a CORS policy. allowed_hosts checks the
request Host header, so include the Host
value your reverse proxy forwards. See the snodo_plug options
for defaults and response behavior.
The Plug needs the raw request body. Phoenix endpoint plugs run before the
router pipelines, and a generated endpoint commonly runs Plug.Parsers there.
Replace that parser plug with a conditional wrapper before plug MyAppWeb.Router;
keep the application's existing parser options for all other paths:
@parser_opts Plug.Parsers.init(
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Jason
)
plug :parse_non_mcp
plug MyAppWeb.Router
defp parse_non_mcp(%Plug.Conn{request_path: "/mcp"} = conn, _opts), do: conn
defp parse_non_mcp(conn, _opts), do: Plug.Parsers.call(conn, @parser_opts)Do not add a body parser to the :mcp router pipeline. The MCP request
requires Content-Length, and a request declaring Transfer-Encoding gets 411.
With Bandit's Phoenix adapter, set endpoint HTTP bounds alongside the transport bounds above. For example, merge these options into the application's existing endpoint configuration:
config :my_app, MyAppWeb.Endpoint,
adapter: Bandit.PhoenixAdapter,
http: [
port: 4000,
http_1_options: [max_header_length: 10_000, max_header_count: 50],
http_2_options: [enabled: false],
thousand_island_options: [
transport_options: [send_timeout: 5_000, send_timeout_close: true]
]
]Set connection, header, read, write, and shutdown limits on the endpoint and
reverse proxy as well. The transport's body_timeout is checked when an adapter
read returns; under HTTP/2, a client sending small DATA frames can keep that
read open. Disable HTTP/2 on an endpoint serving untrusted MCP clients, as
above, or buffer request bodies at a proxy. Disabling it on the endpoint affects
all routes there. The finite send timeout bounds writes that the transport
cannot interrupt. The 21_plug_bandit.exs example
checks the transport without adding Phoenix to this repository's dependencies.
Other hosts
Snodo.Transport.StreamableHTTP.prepare/3 admits and decodes a
Snodo.Transport.StreamableHTTP.Request without running a handler. It returns
{:ok, prepared}, or {:response, response} when admission fails. execute/3
runs a prepared request and returns a Response or a StreamResponse. A
different HTTP server can translate its requests into that shape. handle/3
runs both steps synchronously.
HTTP client connections
Snodo.Client.connect({:http, url}, opts) keeps up to four pooled requests open
for that client and origin. Extra concurrent requests wait up to their request
timeout for a free connection. Set :pool_size to change the cap (default 4),
:pool_idle_timeout to change how long an unused connection stays open (default
30,000 ms), and :pool_max_requests to retire a connection after a fixed
number of requests (default 100). Each option requires a positive integer.
The client reuses only HTTP/1.1 responses with a complete Content-Length
body and no Connection: close directive. Event streams, responses framed by
socket close or chunked transfer, malformed responses, and failed requests
close their sockets. Event streams detach from the pool and use a separate
socket while they run. Snodo.Client.close/1 closes idle connections; active
requests finish on their own sockets. Response-size and page limits apply on
every request, including those sent over reused connections.
Examples
examples/04_stdio_concurrency.exs, 05_http_tools.exs, 21_plug_bandit.exs
(from integrations/plug), and 24_client_transports.exs.