Raxol.MCP.Transport.Stdio (Raxol MCP v2.9.2)

Copy Markdown View Source

Stdio transport for MCP.

Reads JSON-RPC messages line-by-line from stdin, routes them to the MCP Server, and writes responses to stdout. This is the transport used by Claude Code and other CLI MCP clients.

Bytes

The wire is bytes, read and written unchanged. A device left in its own encoding re-encodes them: under a non-UTF-8 locale standard input and output are latin1, so non-ASCII text would arrive and leave corrupted, and one invalid byte from the peer switches a UTF-8 device to latin1. The transport therefore sets both devices to latin1, in which a byte is a character, and reads and writes binaries.

Line limit

A line longer than :max_line_bytes (default 8_000_000, the SSE transport's :max_body_bytes; the terminator is not counted) is refused as it arrives: it is answered with one JSON-RPC error, id null, code -32600, "Request line too large", and one warning is logged. The rest of the line is discarded as it streams in, and the next line is read as usual. A line of exactly the limit is served.

On the VM's standard input (:io_device :stdio, the default, while this process's group leader is user or an application master; :standard_io, likewise; :user; or the user process itself, as mix mcp.server passes it), the transport reads fd 0 through a {:fd, 0, 1} port opened :in, in pieces of at most 64 KiB, so it never holds more than the limit plus one piece, however long the line. Reading through user instead would not bound anything: under -noshell, user collects a whole line as a charlist before handing it over (about 60 bytes of memory per byte of input). If the port cannot be opened, the transport logs one warning and reads user as before; the limit then still decides what is refused, but not how much memory a line takes. Any other device (a test's) is read with IO.binread/2, with the same rule and the same caveat. stdout is written as before, through user, by this process alone.

On macOS, opening the port logs one [error] from the runtime ("... stealing control of fd=0 from resource prim_tty:tty"): user's tty reader had fd 0 registered, and the port takes it over. It is expected, and it goes wherever Logger writes, which must be stderr (see "Important").

Closing the port leaves fds 0 and 1 open, so a transport restarted by its supervisor opens a new port and reads on from where the last one stopped.

Stray reads

While the port reads stdin, any read that reaches user would take fd 0 back: user's tty reader registers fd 0 again, and from then on stdin goes to user, not to the transport, for good. So before the port opens, the transport puts an io server in place of user that passes output through unchanged and answers every read (get_line, get_chars, get_until, get_password) with {:error, :enotsup}, logging one warning per reading process. It takes the name user; becomes the group leader of every process whose group leader was user, or an application master that relays io to user; and, when application_controller's group leader is user, takes that place too, so masters started later relay to it. An application whose master relays elsewhere is left alone: raxol mcp points application_controller at standard_error, which refuses reads itself. Which master relays where is told by how it answers a request no io server knows, compared with how user and standard_error answer it directly; if those two answers ever coincide, no master's processes are moved and one warning says so. When the transport stops, everything is put back. A second transport on standard input finds the guard in place, logs a warning, and installs none of its own. The guard's warnings, like the transport's, go through Logger, so to stderr on both raxol mcp and mix mcp.server.

Known limits:

  • An application master keeps the device it relays to in its own state, so it cannot be moved, only its processes. A process that later makes such a master its group leader itself (Process.group_leader/2) reads user directly, and takes stdin from the transport.
  • :application.get_application/0 (and /1 with a pid) finds an application through the group leader, so in a process moved off a master it returns :undefined while the transport runs, and so do the calls that use it: :application.get_env/1, get_key/1, get_all_env/0 and get_all_key/0. This applies only to applications whose master relays to user (under mix or elixir, not in the raxol mcp release). Application.get_env/2,3, :application.get_application/1 with a module, and per-application log levels are unaffected.

Ordering and cancellation

The reader never waits for the server: each line goes out in read order through Raxol.MCP.Server.request/3, so a slow tools/call does not hold up the tools/list behind it, and methods the server handles inline keep their order. Replies arrive in this process's mailbox and only this process writes stdout. Requests run concurrently, up to the server's :max_in_flight_per_connection share of :max_in_flight (half, by default), so a stdio client's excess calls are answered server_busy while other connections keep the rest.

notifications/cancelled cancels the named in-flight request, which kills its callback worker. That holds for a tools/call waiting on an elicitation answer too: it stays in flight until it is answered, so a cancel drops it unanswered, or kills its tool once the answer approved it. A request that reuses the id of one still in flight is answered -32600 and not run. At end of input every reply already produced is still written (methods the server answers inline, such as initialize and ping, and worker-run requests that finished first); every request still running in a callback worker (tools/*, resources/*, prompts/*, completion/complete, logging/setLevel) or waiting on an elicitation answer is cancelled and gets no reply. The transport stops :normal once nothing is outstanding; halting the VM is the caller's job.

If the transport dies any other way (killed, a crash), the server cancels its outstanding requests, since it monitors every Raxol.MCP.Server.request/3 caller, and the linked reader exits with it rather than go on consuming input.

The transport monitors the server it subscribed to and stops with {:server_down, reason} when that server goes down, whether or not a request is pending, and with {:server_down, :noproc} at start if no server is running. A restarted server (Raxol.MCP.Supervisor restarts it under the same name) knows nothing of this transport's subscription, so carrying on would leave it unable to receive notifications or be asked for an elicitation; stopping lets the client restart the whole server process.

The transport traps exits (to see its reader's), and keeps ordinary link semantics otherwise: when the process that started it exits, it stops with the same reason, as any OTP process that traps exits does, and an abnormal exit of any other linked process stops it with that reason (a :normal one is ignored, as an untrapped link would ignore it).

Notifications

Subscribes to the MCP Server for push notifications (e.g. notifications/tools/list_changed). Notifications are written to stdout as unsolicited JSON-RPC messages.

Important

When using this transport, configure Logger to write to stderr to avoid corrupting the JSON-RPC stream on stdout (the transport itself logs a refused line, a refused stray read and, on macOS, the runtime's message when the port opens):

config :logger, :default_handler, %{config: %{type: :standard_error}}

Or at runtime:

Logger.configure_backend(:console, device: :standard_error)

Summary

Types

input()

@type input() :: {:stdin, user :: pid()} | {:device, IO.device()}

t()

@type t() :: %Raxol.MCP.Transport.Stdio{
  closing: boolean(),
  guard: pid() | nil,
  in_flight: %{optional(term()) => reference()},
  input: input(),
  max_line_bytes: pos_integer(),
  output_device: IO.device(),
  reader: pid() | nil,
  requests: :gen_server.request_id_collection(),
  server: GenServer.server(),
  server_monitor: reference() | nil
}

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

handle_manager_call(request, from, state)

Callback implementation for Raxol.Core.Behaviours.BaseManager.handle_manager_call/3.

handle_manager_cast(msg, state)

Callback implementation for Raxol.Core.Behaviours.BaseManager.handle_manager_cast/2.

start_link(init_opts \\ [])

@spec start_link(keyword()) :: GenServer.on_start()

Start the stdio transport.

Options

  • :server -- MCP Server pid or name (default: Raxol.MCP.Server)
  • :name -- GenServer name (optional)
  • :io_device -- input device (default: :stdio). :stdio, :standard_io, :user and the user process mean the VM's standard input, read through a port (see "Line limit"); any other device, such as a test's, is read with IO.binread/2
  • :output_device -- output device (default: :stdio), useful for testing
  • :max_line_bytes -- the longest line accepted, terminator not counted (default: Raxol.MCP.Protocol.max_message_bytes/0, 8_000_000, the SSE transport's :max_body_bytes default)