Skip to content
DocsStar33Playground

Serve an agent over MCP

How-to guideExperimentalLast updated 2026-12-04 · 99b8f5257Quickstart

Any Reactive Agents agent can run as an MCP server. An MCP host such as Claude Code, Cursor or Codex then sees one tool, run_agent, whose one required argument is the string input. Each call runs the agent once and returns its answer as the tool result. The call can also ask for more of the run’s data and, with an opt-in, a second tool lets a caller steer a live run.

This is the opposite direction from MCP tools, where your agent calls other MCP servers. To serve an agent to other agents instead of MCP hosts, use A2A.

Three ways to serve:

Way Transport Use it when
rax serve --protocol mcp --transport stdio stdio The host should start the agent itself. Simplest for a local coding tool
rax serve --protocol mcp streamable HTTP The agent runs as its own process and hosts connect to a URL
agent.serveMCP() streamable HTTP You build the agent in code, or need the host and origin allowlists or OAuth

The serving API is experimental: option names and HTTP defaults can change between minors.

The CLI serves an agent file or a flag-defined agent. Over stdio, the host starts the command:

Terminal window
rax serve --agent researcher.agent.json --protocol mcp --transport stdio

stdout carries MCP messages only; everything else rax and the agent print goes to stderr. On start, rax prints the host config on stderr with the agent file path made absolute. When the host closes stdin, rax stops and exits 0.

Over HTTP, start the server yourself:

3001/mcp
rax serve --agent researcher.agent.json --protocol mcp

Without an agent file, flags define the agent. --provider defaults to test, so set a real provider:

Terminal window
rax serve --name researcher --provider anthropic --with-tools --protocol mcp

All flags, RA_MCP_HOST, RA_MCP_TOKEN and RA_MCP_ALLOWED_HOSTS, and exit codes: rax serve.

Build the agent in the Cortex Lab, then Export > Agent file (JSON) downloads <name>.agent.json. Serve that file with the stdio command above. The file carries no secrets, so the provider key comes from the environment the host passes to rax.

The server key (researcher below) can be any name. For stdio, rax must be on the host’s PATH (bun add -g @reactive-agents/cli or npm install -g @reactive-agents/cli) and the agent file path must be absolute. Pass provider keys through the host’s environment setting.

Claude Code, stdio:

Terminal window
claude mcp add researcher -e ANTHROPIC_API_KEY=sk-ant-... -- rax serve --agent /abs/path/researcher.agent.json --protocol mcp --transport stdio

Claude Code, HTTP (server already running):

Terminal window
claude mcp add --transport http researcher http://127.0.0.1:3001/mcp

Cursor (.cursor/mcp.json), stdio:

{
"mcpServers": {
"researcher": {
"command": "rax",
"args": ["serve", "--agent", "/abs/path/researcher.agent.json", "--protocol", "mcp", "--transport", "stdio"],
"env": { "ANTHROPIC_API_KEY": "sk-ant-..." }
}
}
}

Or HTTP: { "mcpServers": { "researcher": { "url": "http://127.0.0.1:3001/mcp" } } }.

Codex (~/.codex/config.toml), stdio:

[mcp_servers.researcher]
command = "rax"
args = ["serve", "--agent", "/abs/path/researcher.agent.json", "--protocol", "mcp", "--transport", "stdio"]
env = { ANTHROPIC_API_KEY = "sk-ant-..." }

Host config formats change; check your host’s MCP docs if a key is rejected. A server started with a token needs the Authorization: Bearer <token> header in the host config (see Security).

agent.serveMCP() starts a streamable HTTP server and returns once the port is bound:

import { ReactiveAgents } from "reactive-agents";
const agent = await ReactiveAgents.create()
.withName("researcher")
.withProvider("anthropic")
.withTools({ builtins: true })
.build();
const server = await agent.serveMCP();
console.log(server.url); // http://127.0.0.1:3001/mcp
process.on("SIGINT", async () => {
await server.stop();
await agent.dispose();
});

It returns { port, url, stop() }. port is the bound port, the real one when you pass port: 0.

Option Default Description
port 3001 Port to bind; 0 picks a free port. A2A defaults to 3000, so both can run
hostname 127.0.0.1 Interface to bind. A non-loopback bind requires token or oauth
token none Static bearer token required on every request. Exclusive with oauth
oauth none OAuth 2.1 resource-server mode: accept access tokens from your authorization server. Exclusive with token. See OAuth 2.1 resource server
name .withName() value, else the agent id Server name and tool title
description Runs the <name> agent on a task and returns its answer. ... Tool description the host’s model reads. Say what the agent is good at
toolName run_agent Tool name
path /mcp Endpoint path; every other path gets 404
allowedHosts localhost, 127.0.0.1, [::1] for a loopback bind, else the bound hostname Host names accepted in the Host header. Required for a wildcard bind (0.0.0.0, ::). rax serve reads it from RA_MCP_ALLOWED_HOSTS
allowedOrigins none Exact Origin values accepted from browser clients
maxConcurrentRuns 4 Most agent runs in flight at once, across all requests. See Bounded work
runTimeoutMs 300000 (five minutes) Wall-clock budget for one run, a positive integer up to 2147483647. A run past it gets the tool error Agent run timed out, its abort signal fires and its slot is freed. The detail goes to onError. See Bounded work
responseFormat "text" "text" returns the plain answer in the text block. "json" puts the JSON of structuredContent there, so a text-only host can pipe it to jq. See What the host gets back
steering false List a steer_run tool beside run_agent. See Steer a live run and read its authentication warning first
allowUnauthenticatedSteering false With steering: true over HTTP and no token or oauth, accepts an open endpoint instead of throwing McpServerConfigError. rax serve sets it from --allow-unauthenticated-steering
onError one line on stderr Receives the detail of a failed run. The caller sees only Agent run failed. See What the host gets back

These options configure the streamable HTTP server. For stdio, call agent.serveMCP({ transport: "stdio" }) (options: name, description, toolName, maxConcurrentRuns, runTimeoutMs, responseFormat, steering, onError, and optional stdin/stdout streams; it returns { stop() }), or use rax serve --protocol mcp --transport stdio. Over stdio, stdout carries the protocol, so keep your own logging on stderr. reactive-agents (and @reactive-agents/runtime) exports the type of the two options both transports share as ServeMcpRunOptions.

  • A run with success: true returns its output as the tool result text.
  • A run with success: false returns a tool error (isError: true):
    • An abstention says Agent declined to complete the task: <reason>.
    • A run that failed with an error says only Agent run failed. The error text goes to the onError hook (default: one line on stderr), never to the caller.
    • Any other decline returns the partial output, else Agent declined to complete the task.
  • A run that throws (a run() rejection, including a run stopped because the caller cancelled) also returns Agent run failed, with the error passed to onError. The server keeps running.
  • agent.serveA2A() words failures the same way and takes its own onError. See A2A protocol.
  • A call made while every run slot is taken returns the tool error Server busy: too many agent runs in progress. Retry later. and the agent does not run. See Bounded work.
  • A missing or empty input is an MCP InvalidParams error; the agent does not run. An unknown tool name is refused without echoing the name back.

Each call is a separate run. The host’s conversation does not carry over between calls unless the agent has memory.

A successful call returns the text block above and, next to it, structuredContent. The tool advertises a matching outputSchema, which allows additional properties. By default structuredContent is minimal: answer and the runId. The calling agent asks for more per call with two optional run_agent arguments (input is unchanged and still required):

Argument Values Effect
include an array of receipt, tool_calls, sources, unknowns, extra Adds only the named fields the run reported. receipt is the trust receipt as a JSON object, tool_calls the tool names in call order, unknowns what an abstention said was missing (else the contract criteria left outstanding)
format "text" or "json" Overrides the server’s responseFormat for this call. "json" makes the text block the JSON of structuredContent

Fields the run did not produce are left out. agent.serveMCP() reports no sources, because the run result carries no source list. A bad include or format is an InvalidParams error that never echoes the value, and error results stay plain text. The server forwards the fields the executor reports as given and does not redact them: if you write your own executor for createAgentMcpServer(), it decides what to report.

The run_agent description ends with the run limits (input length, maxConcurrentRuns, runTimeoutMs), so the host model reads them when it lists tools. The server also exposes an agent://card resource (resources/read, JSON): by default the name, description, version, the tool and the limits. agent.serveMCP() serves that default card. A server you build with createAgentMcpServer() or serveAgentMcpHttp() can pass its own card option, for example the A2A agent card, so both surfaces agree.

With agent.serveMCP({ steering: true }) the server lists a second tool, steer_run, beside run_agent. It takes { runId, text } and sends a steering message (user input the live run applies at its next iteration boundary) to that run. The receipt comes back as structuredContent: { accepted: true, id } or { accepted: false, reason }, with the reasons from steer.

To steer a run you must name it. Give run_agent an optional runId argument (1 to 128 characters of letters, digits, _, ., :, -). A call that carries a runId runs as a streamed run under that id, so steer_run with the same id reaches it, and the run applies the message before its next model call. A malformed id, or one a live run already uses anywhere in the process, is refused as Invalid runId. and never overwrites another run; the same answer for both means a caller cannot learn which runs exist. A call without a runId is a plain run and cannot be steered: steer_run answers no-live-run for it. The runId is echoed in structuredContent.runId.

Remote steering is narrower than in-process agent.steer(). steer_run reaches only the runs this server started (run_agent calls that carried a runId); any other id, including a live run another agent in the process started, answers no-live-run.

steer_run checks its input at the MCP edge, in the advertised input schema and in the handler: runId follows the same pattern as in run_agent, and text is at most 4000 characters. A bad value is an InvalidParams error that never echoes the value. At most 8 messages are queued per run; more answer queue-full.

const server = await agent.serveMCP({
steering: true,
token: process.env.RA_MCP_TOKEN, // required in practice: see the warning
});

Steering works on the reactive kernel only. For plan-execute, plan-execute-reflect, reflexion and tree-of-thought the message is accepted but never applied. createAgentMcpServer() and serveAgentMcpHttp() enable the tool when you pass a steer function, such as agent.steer; without it the tool list is exactly run_agent, and toolName must not be steer_run.

  • Loopback by default. The server binds 127.0.0.1. Binding any other interface without token or oauth fails at start.
  • Bearer token. With token (or RA_MCP_TOKEN), every request needs Authorization: Bearer <token>. The token authenticates the HTTP request only: it never reaches the agent, its tools or its trace.
  • Host and Origin checks. A request whose Host header is not an allowed host name gets 403, which blocks DNS rebinding. A request with any Origin header gets 403 unless the origin is in allowedOrigins. Desktop hosts and CLIs send no Origin. The 403 body does not repeat the rejected value. allowedHosts entries are lowercased and a bare IPv6 address gets brackets, so "LocalHost" and "::1" match; an entry with a port is refused at start.
  • Stateless. There are no session IDs. The endpoint accepts POST only (GET and DELETE get 405), and request bodies are capped at 1 MiB.
  • No error echo. A run that throws or fails with an error reaches the caller only as Agent run failed; the detail goes to onError.

One request starts at most one run, and the whole server runs a fixed number of agents at once:

  • One tools/call per request. A JSON-RPC batch that carries more than one tools/call gets 400 (Invalid Request: at most one tools/call per request) before any agent run starts. A batch with one call, or calls to other methods, is served as usual. This applies to the HTTP transport.
  • maxConcurrentRuns (default 4). Caps agent runs in flight across all requests. A call past the limit gets the tool error Server busy: too many agent runs in progress. Retry later. and does not run. A run holds its slot until it settles. A caller that cancels or disconnects stops its run, which frees the slot (see Limits for the exceptions).
  • runTimeoutMs (default five minutes). A wall-clock budget per run. A run past it gets the tool error Agent run timed out, its abort signal fires and its slot is freed. The timeout detail goes to onError, not to the caller.

agent.serveMCP() takes both options on HTTP and stdio:

const server = await agent.serveMCP({
maxConcurrentRuns: 2,
onError: (error) => console.error("[researcher] run failed:", error),
});
Option Default Description
maxConcurrentRuns 4 Most agent runs in flight at once, across all requests. A positive integer; anything else is refused at start with McpServerConfigError
onError one line on stderr Receives the detail of a failed run: the error a run() rejection carries, or the error string of a success: false result. The caller sees only Agent run failed (or the abstention reason)

serveAgentMcpHttp() and createAgentMcpServer() from @reactive-agents/mcp-server take the same two options when you write your own executor. createAgentMcpServer() is the transport-neutral builder for stdio or your own HTTP layer. The concurrency cap applies to every transport; the one-call-per-request rule is enforced by the HTTP server.

For a remote deployment, bind a specific address or use allowedHosts, set a long random token (or use OAuth), and put the server behind a TLS proxy:

import { ReactiveAgents } from "reactive-agents";
const agent = await ReactiveAgents.create().withName("researcher").withProvider("anthropic").build();
const server = await agent.serveMCP({
hostname: "0.0.0.0",
allowedHosts: ["agents.example.com"],
token: process.env.RA_MCP_TOKEN,
});

From the CLI, the same deployment is RA_MCP_HOST=0.0.0.0 RA_MCP_TOKEN=... RA_MCP_ALLOWED_HOSTS=agents.example.com rax serve --agent researcher.agent.json --protocol mcp. A wildcard RA_MCP_HOST without RA_MCP_ALLOWED_HOSTS exits with code 2; see rax serve.

Instead of one shared token, the server can accept access tokens issued by your own OAuth 2.1 authorization server, following the MCP authorization spec. Pass oauth to agent.serveMCP(), or to serveAgentMcpHttp() from @reactive-agents/mcp-server. The server only checks tokens: it never issues them or registers clients.

OAuth is available from code only. rax serve has no OAuth flags, and stdio has no OAuth: the MCP spec defines authorization for HTTP transports, and a stdio server takes its credentials from the environment the host passes it.

  1. Register an API or resource whose identifier (often called the audience) is the public URL of the MCP endpoint, for example https://agents.example.com/mcp. Tokens must carry exactly this value in aud.
  2. Define the scope callers need, for example agents:run.
  3. Note the issuer URL (the token’s iss, including any trailing slash) and the JWKS URL.
import { ReactiveAgents } from "reactive-agents";
const agent = await ReactiveAgents.create().withName("researcher").withProvider("anthropic").build();
const server = await agent.serveMCP({
hostname: "0.0.0.0",
allowedHosts: ["agents.example.com"],
oauth: {
resource: "https://agents.example.com/mcp",
authorizationServers: ["https://auth.example.com/"],
jwksUri: "https://auth.example.com/.well-known/jwks.json",
requiredScopes: ["agents:run"],
},
});

oauth satisfies the non-loopback rule, so this binds every interface without a static token. Put it behind a TLS proxy that forwards both /mcp and /.well-known/oauth-protected-resource* to the server.

Option Default Description
resource required Canonical URL of this MCP server. Tokens must carry it as their audience (RFC 8707). https unless the host is loopback; no #fragment
authorizationServers required Issuer URLs, listed in the metadata. A JWT’s iss must equal one exactly. At least one; https unless loopback
jwksUri none JWKS endpoint for the built-in JWT check (signature, iss, aud, exp, nbf). https unless loopback
verifier none Custom verifier for opaque tokens, for example RFC 7662 introspection. Pass exactly one of jwksUri and verifier
requiredScopes none Scopes every call needs, read from the token’s scope string or scp array. Advertised as scopes_supported and in the 401 challenge
algorithms ["RS256", "ES256", "EdDSA"] Accepted JWS algorithms. HS* and none are dropped even if listed
requireAccessTokenType false With jwksUri: require the RFC 9068 JWT header typ: "at+jwt" (application/at+jwt also matches), else 401. Stops an ID token or another JWT from the same issuer and audience from passing as an access token. Off by default because some authorization servers mint access tokens with typ: "JWT". Refused at start together with verifier
allowTokensWithoutExpiry false With verifier: accept a result that has no expiresAt. Set it only when your verifier already rejects expired tokens. The JWT path always requires exp

A verifier implements verifyAccessToken(token) and returns the MCP SDK’s AuthInfo (import type { McpOAuthOptions, OAuthTokenVerifier, AuthInfo } from "reactive-agents"). Its resource must equal oauth.resource (fragment ignored) and it must carry an expiresAt in the future; otherwise the request gets 401. A result with no expiresAt also gets 401 unless you set allowTokensWithoutExpiry: true. Required scopes are still enforced.

If your authorization server stamps typ: "at+jwt" on access tokens, turn on the type check:

import type { McpOAuthOptions } from "reactive-agents";
const oauth: McpOAuthOptions = {
resource: "https://agents.example.com/mcp",
authorizationServers: ["https://auth.example.com/"],
jwksUri: "https://auth.example.com/.well-known/jwks.json",
requireAccessTokenType: true,
};

The server publishes RFC 9728 protected-resource metadata without authentication, at the path-suffixed URL and at the root:

  • https://agents.example.com/.well-known/oauth-protected-resource/mcp (the suffix is the path of resource)
  • https://agents.example.com/.well-known/oauth-protected-resource

The JSON lists resource, authorization_servers, scopes_supported (when requiredScopes is set) and bearer_methods_supported: ["header"]. MCP hosts read it from the 401 challenge to find your authorization server.

Request Status WWW-Authenticate
No Authorization: Bearer header 401 Bearer resource_metadata="<metadata URL>", scope="<required scopes>"
Token fails verification 401 Same, with error="invalid_token"
Valid token without a required scope 403 Bearer error="insufficient_scope", scope="...", resource_metadata="..."
access_token in the query string, even a valid one 400 Bearer error="invalid_request", resource_metadata="..."

scope in a challenge never includes offline_access. The Authorization header is the only accepted token carrier.

A token fails verification when its signature, key, iss or aud does not match, when it is expired, not yet valid or has no exp (60 seconds of clock leeway), when its algorithm is not allowed, when requireAccessTokenType is on and its typ is not at+jwt, when a custom verifier’s result has no expiresAt (unless allowTokensWithoutExpiry is set), when the JWKS endpoint cannot be reached, or when a custom verifier throws. Error responses never echo the token or a verifier’s error text.

Unsafe configuration is refused at start: serveMCP() rejects with McpServerConfigError when both token and oauth are set, a URL uses http on a non-loopback host, resource has a fragment, authorizationServers is empty, there is not exactly one of jwksUri and verifier, requireAccessTokenType is set with a verifier, no asymmetric algorithm is left, a required scope has invalid characters, or an allowedHosts entry carries a port.

Only the allow-or-deny decision crosses into the MCP handler. The agent, its tools and its trace never see the access token or its claims, so a run cannot tell which caller sent it.

  • Cancelling stops the run, except on durable agents. A host cancel, a closed connection or stop() passes the call’s abort signal to run(input, { signal }), which interrupts the run and frees its run slot. Agents built with .withDurableRuns() do not honor the signal yet: their runs continue in the background until they finish and keep their slot until then. Bound those with the agent’s own limits (iterations, timeout, budget).
  • Four runs at a time by default. Calls past maxConcurrentRuns get Server busy instead of queuing; the host or its model has to retry.
  • No progress notifications. The result arrives as one response when the run ends.
  • One tool, two with steering. The host sees run_agent (and steer_run when steering is on), not the agent’s own tools.

Install

Bun (recommended)bun add reactive-agents
Node 22.5+npm install reactive-agents

Get notified on new releases

Release notes, about once a month.