Portable Agent File (Open Agent Spec)
An agent file is one JSON document that describes an agent. You write it from an AgentConfig and load it back into the same AgentConfig, so the agent you build in code can be saved, checked into a repository and loaded somewhere else. The rax CLI runs and serves the same file (see Run a file from the CLI), and the Cortex Lab exports and imports it (see Export and import in Cortex).
The file is an Open Agent Spec Agent document: an open, framework-neutral agent format with no executable code and no inline secrets. Portable fields sit in their standard places, so another Agent Spec runtime can read the core agent. Settings only Reactive Agents understands sit under metadata["reactive-agents"].
Three functions do the work. They are exported from reactive-agents and @reactive-agents/runtime:
| Function | Does |
|---|---|
agentConfigToAgentSpec(config, options?) |
AgentConfig to an Agent Spec Agent document (a plain object). |
agentConfigFromAgentSpec(doc, options?) |
Agent Spec document to AgentConfig. Returns an Effect that fails with AgentSpecError. |
loadAgentFile(path, options?) |
Reads a JSON file: an Agent Spec document or a plain AgentConfig JSON. Fails with AgentSpecError or AgentFileReadError. |
This API is new and unstable: the mapping may still change between minor versions. The file format itself is versioned (see Versions).
Write a file
Section titled “Write a file”import { writeFile } from "node:fs/promises";import { agentConfigToAgentSpec } from "reactive-agents";
const doc = agentConfigToAgentSpec( { name: "Release Assistant", provider: "anthropic", model: "claude-sonnet-4-5", systemPrompt: "You prepare release notes.", persona: { role: "release engineer", tone: "concise" }, mcpServers: [ { name: "github", transport: "streamable-http", endpoint: "https://api.example.com/mcp", headers: { Authorization: "Bearer <token>" }, }, ], approvalPolicy: { mode: "block", tools: ["publish_release"] }, gateway: { webhooks: [{ path: "/hook", adapter: "github", secret: "<webhook secret>" }] }, userInteraction: { timeoutMs: 60000 }, }, { // Tools defined in code are declared by name and inputs only. tools: [{ name: "publish_release", description: "Publish a GitHub release", inputs: [{ title: "tag", type: "string" }] }], },);
await writeFile("release-assistant.agent.json", JSON.stringify(doc, null, 2));agentConfigToAgentSpec is a pure function. Its options:
| Option | Effect |
|---|---|
tools |
Code tools (defineTool, host tools) to declare as ServerTool entries: { name, description?, inputs? }. inputs are Agent Spec input properties: JSON Schema objects with a title (the argument name). |
llmUrl |
Written to llm_config.url. AgentConfig has no endpoint field, so pass the model endpoint here. For Ollama it defaults to http://localhost:11434, because OllamaConfig requires a url. |
The file
Section titled “The file”The example above writes this document. It is the anthropic-http-tool.agent.json fixture in the runtime tests, which pin the exact output:
{ "component_type": "Agent", "id": "release-assistant", "name": "Release Assistant", "description": null, "metadata": { "reactive-agents": { "schemaVersion": 1, "config": { "persona": { "role": "release engineer", "tone": "concise" }, "approvalPolicy": { "mode": "block", "tools": ["publish_release"] }, "gateway": { "webhooks": [{ "path": "/hook", "adapter": "github", "secret": { "$env": "GATEWAY_HOOK_SECRET" } }] }, "userInteraction": { "timeoutMs": 60000 } }, "generatedId": true } }, "inputs": [], "outputs": [], "system_prompt": "You prepare release notes.\n\nRole: release engineer\nTone: concise", "llm_config": { "component_type": "LlmConfig", "id": "release-assistant-llm", "name": "claude-sonnet-4-5", "description": null, "metadata": {}, "model_id": "claude-sonnet-4-5", "default_generation_parameters": null, "provider": "anthropic", "api_key": { "$component_ref": "release-assistant-llm.api_key" } }, "tools": [ { "component_type": "ServerTool", "id": "tool-publish-release", "name": "publish_release", "description": "Publish a GitHub release", "metadata": {}, "inputs": [{ "title": "tag", "type": "string" }], "outputs": [], "requires_confirmation": true } ], "toolboxes": [ { "component_type": "MCPToolBox", "id": "mcp-github", "name": "github", "description": null, "metadata": { "reactive-agents": { "schemaVersion": 1, "server": { "headers": { "Authorization": { "$env": "MCP_GITHUB_AUTHORIZATION" } } } } }, "client_transport": { "component_type": "StreamableHTTPTransport", "id": "mcp-github-transport", "name": "mcp-github-transport", "description": null, "metadata": {}, "url": "https://api.example.com/mcp", "headers": null, "sensitive_headers": { "$component_ref": "mcp-github-transport.sensitive_headers" } }, "tool_filter": null, "requires_confirmation": false } ], "human_in_the_loop": true, "agentspec_version": "26.1.2"}Field names follow the Agent Spec reference implementation (pyagentspec): the type is component_type, the model block is llm_config, and a reference is { "$component_ref": "<id>" }.
Field mapping
Section titled “Field mapping”AgentConfig |
Agent Spec | Notes |
|---|---|---|
name |
name |
|
agentId |
id |
With no agentId, the id is made from the name (Release Assistant becomes release-assistant) and the metadata records generatedId: true, so import does not invent an agentId. |
systemPrompt and persona |
system_prompt |
The persona’s name, role, background, instructions and tone are appended as Role: ... lines, so other runtimes see them. The exact persona object also stays in the metadata, and import splits the prompt back. |
provider, model |
llm_config and its model_id |
ollama writes OllamaConfig (with url), openai writes OpenAiConfig, gemini writes GeminiConfig, and every other provider writes a base LlmConfig with provider set. On import, a base LlmConfig with provider: "google" reads as gemini. |
temperature, maxTokens |
llm_config.default_generation_parameters (temperature, max_tokens) |
|
mcpServers with stdio, sse or streamable-http |
toolboxes: one MCPToolBox per server with a StdioTransport, SSETransport or StreamableHTTPTransport |
command, args and cwd (stdio) or the endpoint as url (HTTP) go to the transport. Other server fields (env, headers, readOnly, trustAnnotations, …) go to the toolbox’s own metadata["reactive-agents"].server. A stdio server whose transport was inferred from command keeps it unset on import. |
mcpServers with websocket, or an endpoint with no transport |
metadata["reactive-agents"].config.mcpServers |
Agent Spec has no standard transport for them. |
userInteraction |
human_in_the_loop |
true when userInteraction is set and not false. An options object ({ timeoutMs }) and an explicit false also stay in the metadata. |
approvalPolicy.tools |
requires_confirmation on each declared tool |
The whole approvalPolicy also stays in the metadata. |
Code tools (the tools export option) |
tools: ServerTool entries |
Name, description and inputs only, never code. |
| Everything else (reasoning, memory, guardrails, cost, execution, gateway, …) | metadata["reactive-agents"] = { schemaVersion: 1, config } |
Import reverses each row. Standard fields win: if a person or another tool edits system_prompt, llm_config.model_id or human_in_the_loop, the edited value is used, and the metadata only fills fields that have no standard home.
human_in_the_loop defaults to true in the spec, so a document from another runtime that leaves it out imports with userInteraction: true. With human_in_the_loop: false, userInteraction is left unset unless the metadata says false. On import, every declared tool with requires_confirmation: true is added to approvalPolicy.tools.
Secrets
Section titled “Secrets”Secrets are never written to the file.
- Provider API keys become a sensitive-field reference, for example
{ "$component_ref": "release-assistant-llm.api_key" }(for Gemini it sits underllm_config.auth). Keyless providers (ollama,test,litellm) get no reference. Reactive Agents reads provider keys from its own environment variables, so import does not resolve these references, and a literalapi_keyin a foreign document is never copied (it is listed inignored).rax run --agentandrax serve --agentalso fall back to a key saved withrax keys set <provider>when the environment variable is not set. - MCP header values make the transport’s
sensitive_headersa reference, and the values sit in the toolbox metadata as environment references. - Other secret values become
{ "$env": "NAME" }markers. That covers every MCPenvvalue and strings under a secret-named key. A key is secret-named when it containssecret,password(orpasswd),tokenorcredential, ends inapiKey,privateKey,accessKey,signingKeyorencryptionKey(api_keyandPRIVATE_KEYspellings too), or is exactlykey. The match ignores case, soclientSecret,privateKey,accessTokenandcredentialsare covered. - URLs with credentials become a marker for the whole URL: userinfo (
https://user:pass@host), a query parameter named liketoken,key,secret,authorsig, or a secret path segment (a key prefix as in/v1/sk-abc123/mcp, any segment after a credential word such astokenorwebhookexcept a final transport name like/sse, or a long opaque string). This covers MCP endpoints,remoteUrl, the Cortex URL and telemetry endpoints. An MCP toolbox’s standardurldrops userinfo and credential query parameters and shows[redacted]for a secret segment. ThellmUrlexport option works the same way:llm_config.urlgets that URL, and the full URL is{ "$env": "LLM_URL" }in the metadata. A short path token with no key prefix or credential word before it is missed. - Secret MCP stdio args become markers too: the value after a secret flag (
--api-key X), the value part of--token=X, and a bare string with a known key prefix (sk-,ghp_,xoxb-,glpat-,AKIA, …). A flag that names a reference rather than a secret (--token-file,--key-id) is left alone. The standardargsthen carry$NAMEplaceholders, for example--token=$MCP_FS_TOKEN, so another runtime sees where the secret goes. - Repeated secrets. An arg or endpoint holding one of the server’s secret values (8+ characters) becomes a marker.
toConfig()[redacted:NAME]markers export as references.
Environment names follow the same rules as agentConfigToSource, which prints the same secrets as process.env.NAME. An MCP env value keeps its key (FS_TOKEN). An MCP header becomes MCP_<SERVER>_<HEADER> (MCP_GITHUB_AUTHORIZATION). A secret stdio arg becomes MCP_<SERVER>_<FLAG>, or MCP_<SERVER>_ARG_<index> for a bare key. Other secrets get an upper-snake name from where they sit (a gateway webhook secret on /hook becomes GATEWAY_HOOK_SECRET, an MCP endpoint becomes MCP_<SERVER>_ENDPOINT, a remote agent’s remoteUrl becomes AGENTTOOLS_<NAME>_REMOTEURL, and an MCP OAuth clientSecret on server cc becomes MCP_CC_CLIENTSECRET).
On import, { "$env": "NAME" } markers resolve from the env option. agentConfigFromAgentSpec defaults to an empty environment, so pass { env: process.env } to use yours; loadAgentFile passes process.env by default.
A marker reads only the name its field allows. It resolves only when NAME is the name the export writes for that position (MCP_GITHUB_AUTHORIZATION for that header, GATEWAY_HOOK_SECRET for that webhook, LLM_URL for the model endpoint), so a downloaded file cannot send ANTHROPIC_API_KEY, AWS_* or GITHUB_TOKEN to its own MCP server. Any other name is refused: the field is left out and missingSecrets lists "NAME (refused: this field reads EXPECTED; pass allowEnv to permit another name)". MCP env markers resolve only on a stdio server (one with a command), which runs a local command anyway. Keys in the metadata config that are not AgentConfig fields are dropped unread. To let a file you trust read other names, pass them in allowEnv:
import { Effect } from "effect";import { loadAgentFile } from "reactive-agents";
const loaded = await Effect.runPromise(loadAgentFile("./ops.agent.json", { allowEnv: ["SHARED_GITHUB_TOKEN"] }));console.log(`this file reads: ${loaded.resolvedEnv.join(", ")}`);resolvedEnv lists every name that was read. Show it before you connect to the file’s servers, because those values leave the process.
A secret that is not set is left out of the config, and its name is listed in missingSecrets. A secret stdio arg that does not resolve keeps the $NAME placeholder args, never a shifted list. A sensitive_headers reference whose values are not in the metadata (a document from another runtime) is listed by its $component_ref id.
Telemetry and Cortex reporting
Section titled “Telemetry and Cortex reporting”A file cannot turn on reporting that sends run data off your machine. By default, loadAgentFile and agentConfigFromAgentSpec leave out:
reactiveIntelligence.telemetrywhen the file sets it totrue, setsenabled: true, or names anendpoint;observability.cortexwhen the file sets aurl.
This applies to both file formats (Agent Spec and plain AgentConfig JSON). Each left-out path is listed in droppedTelemetry ("reactiveIntelligence.telemetry", "observability.cortex"), and telemetry and Cortex reporting stay as your own code sets them. A left-out endpoint reference reads no environment variable. Settings that keep data local load as written: telemetry: false, telemetry: { enabled: false } and cortex: true.
To keep these settings from a file you trust (for example one you exported yourself), pass allowTelemetry: true:
import { Effect } from "effect";import { loadAgentFile } from "reactive-agents";
const loaded = await Effect.runPromise(loadAgentFile("./ops.agent.json"));if (loaded.droppedTelemetry.length > 0) { console.warn(`left out: ${loaded.droppedTelemetry.join(", ")} (pass allowTelemetry: true to keep them)`);}
const mine = await Effect.runPromise(loadAgentFile("./my-export.agent.json", { allowTelemetry: true }));If your app imports config objects of its own, call the same rule instead of copying it. dropUntrustedTelemetry(config, { allowTelemetry }) returns { config, droppedTelemetry } (empty parent blocks go too; the input is not changed). telemetrySettingsLeavingMachine(config) only lists the paths, for example to show what a trusted file keeps:
import { dropUntrustedTelemetry, telemetrySettingsLeavingMachine } from "reactive-agents";
telemetrySettingsLeavingMachine({ observability: { cortex: { url: "https://example.com" } } });// ["observability.cortex"]
const { config, droppedTelemetry } = dropUntrustedTelemetry({ reactiveIntelligence: { telemetry: true } });// config: {}, droppedTelemetry: ["reactiveIntelligence.telemetry"]observability.telemetry is kept in every mode: it feeds an in-process aggregator and sends nothing over the network.
In the CLI. rax run --agent and rax serve --agent print one stderr line for each left-out setting, naming it and saying that --trust-file keeps it. --trust-file keeps them, and rax lists each one (with the Cortex URL) among the trusted items on stderr before anything connects. A y at the terminal prompt does not keep them. See Files that run commands.
In Cortex. Lab Import leaves these settings out in every format it reads (Agent Spec, plain AgentConfig and Lab configs) and lists them in the import notes. Cortex never opts in, so a downloaded file cannot choose where your runs report. To report somewhere, set it yourself in the Lab under All framework options.
Read a file
Section titled “Read a file”import { Effect } from "effect";import { agentConfigToBuilder, loadAgentFile } from "reactive-agents";
const loaded = await Effect.runPromise(loadAgentFile("./release-assistant.agent.json"));
// The file declares code tools by name; you supply each implementation.const myTools = new Set(["publish_release"]);const missingTools = loaded.requiredTools.filter((name) => !myTools.has(name));if (missingTools.length > 0) throw new Error(`agent file needs tools: ${missingTools.join(", ")}`);if (loaded.missingSecrets.length > 0) console.warn(`set these variables: ${loaded.missingSecrets.join(", ")}`);
const builder = await agentConfigToBuilder(loaded.config);loadAgentFile reads a document with a component_type as Agent Spec, and anything else as a plain AgentConfig JSON (the output of agentConfigToJSON), so existing config files keep loading.
For a file you already parsed (an upload, an HTTP body), call readAgentFileValue(value, options). It reads both formats with the same rules as loadAgentFile, including the telemetry rule, but resolves secrets only from options.env (default: empty), never from process.env. Use agentConfigFromJSON only for config text you wrote yourself, because it keeps every setting.
To convert an Agent Spec document you already parsed, call agentConfigFromAgentSpec:
import { readFile } from "node:fs/promises";import { Effect } from "effect";import { agentConfigFromAgentSpec, createAgent } from "reactive-agents";
const doc: unknown = JSON.parse(await readFile("./release-assistant.agent.json", "utf8"));const { config, llmUrl } = await Effect.runPromise(agentConfigFromAgentSpec(doc, { env: process.env }));// Only for a file you trust: an Ollama API key, if set, may be sent to this URL.if (llmUrl && config.provider === "ollama") process.env.OLLAMA_ENDPOINT = llmUrl;
const agent = await createAgent(config);Both return an AgentSpecImport:
| Field | Meaning |
|---|---|
config |
The AgentConfig, ready for agentConfigToBuilder or createAgent. |
format |
"agent-spec" for an Agent Spec document, "agent-config" for plain AgentConfig JSON. |
requiredTools |
Names of the ServerTool and ClientTool entries. The file cannot carry their code: register an implementation for each name on the builder (see Custom tools), or fail naming the missing ones. |
missingSecrets |
Secrets that did not resolve; their fields are left out. Each entry is an unset environment variable name, a $component_ref id, or "NAME (refused: ...)" for a name the field may not read (see Secrets). |
resolvedEnv |
Environment variable names that were read, sorted. Show them before connecting to the file’s servers: these values leave the process. A plain AgentConfig JSON reads none, so it is empty. |
ignored |
Standard fields that were present but have no AgentConfig home, so they had no effect: a literal llm_config.api_key, llm_config.retry_policy, llm_config.default_generation_parameters.top_p, non-empty inputs, outputs or transforms, description, and a transport’s auth. |
droppedTelemetry |
Config paths the file set but the import left out because they send run data off the machine: "reactiveIntelligence.telemetry", "observability.cortex". Empty when nothing was left out or allowTelemetry: true was passed. See Telemetry and Cortex reporting. |
llmUrl |
llm_config.url, when set. AgentConfig has no endpoint field, so apply it yourself; for Ollama, set OLLAMA_ENDPOINT. The file chose this URL: do not send an API key to it unless you trust the file (the CLI asks for --allow-file-endpoint). |
References listed under $referenced_components anywhere in the document are inlined before the document is read.
Errors
Section titled “Errors”agentConfigFromAgentSpec and loadAgentFile fail with AgentSpecError. Its reason:
reason |
When |
|---|---|
unsupported-component |
The root is not an Agent (for example a Flow), or a tool, toolbox, transport or LLM config type has no mapping (for example a RemoteTool or a VllmConfig). A toolbox with a non-empty tool_filter also fails here. |
unsupported-version |
agentspec_version is newer than this reader, or metadata["reactive-agents"].schemaVersion is not 1. |
unsupported-format |
loadAgentFile was given a .yaml or .yml path. |
invalid-document |
Malformed JSON, a document that does not match the Agent Spec schema, an agentspec_version that is not YEAR.QUARTER.PATCH, or a result that is not a valid AgentConfig. |
loadAgentFile fails with AgentFileReadError (with the path) when the file cannot be read.
Versions
Section titled “Versions”Two versions are in every file:
agentspec_versionversions the document. The writer writes26.1.2(AGENT_SPEC_VERSION). The reader accepts any version up to26.4.0(AGENT_SPEC_MAX_READ_VERSION, from@reactive-agents/runtime), and a document with noagentspec_version.metadata["reactive-agents"].schemaVersionversions the Reactive Agents block. It is1, and the reader refuses any other value.
Limits
Section titled “Limits”- JSON only. YAML agent files are not read yet.
Agentroots only. AFlow(a multi-step workflow) or any other root fails withunsupported-component; it is never dropped silently.- No code. Tools defined in code travel as declarations. The program that loads the file must provide their implementations.
- Lossy edges with other runtimes. A document written by another Agent Spec runtime keeps only what maps: the fields listed in
ignoredhave no effect,tool_filteris refused, provider keys come from your environment (or, underrax, the key store), not the file, and an LLM config other thanOllamaConfig,OpenAiConfig,GeminiConfigor a baseLlmConfigwith a Reactive Agents provider is refused. Another runtime reading a Reactive Agents file sees the standard fields and ignores the metadata block, so reasoning, memory, guardrails and the other metadata settings apply only in Reactive Agents.
Run a file from the CLI
Section titled “Run a file from the CLI”rax run --agent runs a file once and rax serve --agent serves it over A2A, or to MCP hosts with --protocol mcp:
rax run --agent release-assistant.agent.json "Draft the notes for v1.2"rax run --agent release-assistant.agent.json "Draft the notes for v1.2" --provider ollama --model qwen3:8brax serve --agent release-assistant.agent.json --port 4000rax serve --agent release-assistant.agent.json --protocol mcp --transport stdioThe last line is the command an MCP host (Claude Code, Cursor, Codex) starts to call the agent as a tool: Serve an agent over MCP.
The CLI reads the file with loadAgentFile, then applies the command line:
--provider,--modeland--namereplace the file’s values. A--providerthat differs from the file’s provider also drops the file’s model (it named a model of the other provider), unless you pass--modeltoo.- Secrets that did not resolve, and fields with no Reactive Agents equivalent, are printed as warnings on stderr, and the run continues without them. A
$envname its field may not read is reported as refused, not as unset (see Secrets). - A file with
requiredToolsis refused, because the CLI has no code tools to register. Run it from your own program with the tools registered.
A file may come from a download or a cloned repository, so the CLI treats it as untrusted input. Before it builds the agent, it checks what the file runs and where your API key would go. Every agent file problem (unreadable, unsupported, invalid, code tools, not trusted, a refused endpoint) exits 2 before the agent is built.
Files that run commands
Section titled “Files that run commands”A file needs your trust when it does any of these:
- starts a local command: an MCP server with a
command(stdio transport); - sends task text to a remote agent: an
agentToolsentry with aremoteUrl; - gives the model a shell:
tools.terminalis set, which addsshell-execute; - reads values from your environment:
$envreferences that resolved (resolvedEnv).
rax lists each command with its arguments, each remote agent with its URL, the shell grant and the environment names the file reads. On a terminal it asks Run it? [y/N]; any answer other than y or yes exits 2 and nothing runs. Without a terminal (CI, a pipe, an MCP host that starts rax serve --transport stdio), it exits 2 unless you pass --trust-file. With --trust-file, rax still prints the list on stderr before it connects.
rax run --agent downloaded.agent.json --trust-file "Summarize the repo"Read the file before you pass --trust-file: its commands run with your user’s permissions.
--trust-file also keeps the file’s telemetry and Cortex URL; a y at the prompt does not (see Telemetry and Cortex reporting).
rax run applies the same check to an MCP config file: the auto-detected .rax/mcp.json in the current directory or an explicit --mcp-config <path>. Each stdio server’s command and arguments are listed. Approve them at the terminal prompt or pass --trust-file; off a terminal without the flag, rax run exits 2 and starts nothing. Nothing is remembered between runs, so a stdio server in your own .rax/mcp.json asks once per terminal run. A config with only HTTP or SSE servers needs no trust.
The file’s model endpoint
Section titled “The file’s model endpoint”llm_config.url never decides on its own where your API key goes. For Ollama (OLLAMA_ENDPOINT) and LiteLLM (LITELLM_BASE_URL):
- If you set that variable yourself, your value is used. A different file URL is not applied, and a warning says so.
- If the file names the endpoint you already use (your environment, else the provider default), nothing changes.
- If no environment or saved key for the provider would be sent to the file’s URL,
raxapplies it and prints a notice naming the endpoint. - If a key would be sent there,
raxexits2and names the endpoint. Pass--allow-file-endpointto accept it (raxthen prints the endpoint on stderr), or set the variable yourself.
For other providers llm_config.url is not applied, and a warning says so. Other exit codes and the process contract: rax run.
Export and import in Cortex
Section titled “Export and import in Cortex”In the Cortex Lab, Export > Agent file (JSON) downloads the Builder’s agent as <name>.agent.json and lists the Cortex-only settings the file leaves out. Import reads an Agent Spec document, a plain AgentConfig JSON or the Lab’s older export, and lists what did not carry over: code tools, MCP servers Cortex has not saved, secret references (Cortex never reads secrets from a file), ignored fields and the model endpoint. A Flow root is refused. Details: Lab builder.
Install
Bun (recommended)bun add reactive-agentsNode 22.5+npm install reactive-agentsGet notified on new releases
Release notes, about once a month.