Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

Runtime Server

The runtime executes agents and exposes chat, session, and tool APIs. Hosted deployments supply authentication and durable storage through the platform. The CLI runs a local server with in-memory storage.

Use the Platform API to manage agents, source, and deployments. Use the endpoints below to interact with a running agent.

Endpoints

MCP and A2A

These routes are enabled only for a configured publication with eligible definitions and supported identity settings. Use the deployment's canonical origin. Protocol callers use publication access, which is separate from the native chat/session API credentials below.

MethodPathPurpose
POST/mcpStreamable HTTP MCP: initialize, discover authorized tools, and invoke them.
GET/.well-known/oauth-protected-resource/mcpProtected-resource metadata identifying the selected issuer. Unavailable for anonymous publication.
GET/mcp/runs/:id/traceAuthorized, redacted trace for a run receipt.
GET/.well-known/agent-card.jsonA2A deployment card with authorized skills.
GET/.well-known/:recipient/agent-card.jsonCard for an exposed main agent or named subagent, addressed by public name.
POST/a2aA2A JSON-RPC: explicit skill/version submission and task observation.
POST/a2a/:recipientA2A delegation to the highest startable version of a published agent.
GET/a2a/runs/:id/traceAuthorized trace for an A2A task.

The MCP endpoint is stateless Streamable HTTP with JSON responses. GET and DELETE on /mcp return 405; it does not offer a server-initiated SSE stream. Client disconnects do not cancel durable runs. Discovery returns tool descriptions and schemas, including start/result tools, agent answer tools, connection confirmation via amodal_run_confirm, and authorized trace/cancel helpers. Connection writes use native endpoint policy and the durable approval flow: read the pending preview from the result tool, then submit {runId, confirmationId, approved} through amodal_run_confirm. MCP resources, prompts, session listing, and chat-history access are not implemented. See Runs, retries, and errors.

A2A implements the 0.3 JSON-RPC polling profile: message/send with configuration.blocking: false, tasks/get, and tasks/cancel. Streaming, push notifications, and blocking submissions are not supported. Each message has one text or data part. The root endpoint takes a data part with {skillId, input}; named agents accept task text or structured input. Use the canonical /a2a audience even for named endpoints. See Call a published agent.

Trace requests need the same caller identity and receipt as result retrieval, plus runs.trace for signed callers. Public anonymous receipts act as run credentials; team-only anonymous receipts additionally require the original member's session. Protocol access does not grant access to the native session APIs listed below.

Chat

MethodPathResponse
POST/chat or /chat/streamSSE stream of Amodal events
POST/chat/syncComplete response after execution finishes, or 502 AGENT_TURN_FAILED when it fails
POST/chat/ai-streamAI SDK streaming protocol

The ordinary chat SSE stream is a POST response. Use fetch or the SDK; browser EventSource supports GET only.

A chat request whose session_id already has a turn running returns 409 {error: 'turn_in_progress'}. To send a message while a turn runs, use POST /chat/sessions/:id/messages.

Runtime auth from curl

Hosted chat requires a runtime bearer token or the hosted browser session flow. Public access to an app's static files does not grant access to chat.

With AMODAL_API_BASE, AMODAL_AGENT_ID, AMODAL_PLATFORM_TOKEN, and AMODAL_AGENT_URL set, mint a short-lived runtime token:

AMODAL_AGENT_TOKEN="$(
  curl -fsS "$AMODAL_API_BASE/api/agents/$AMODAL_AGENT_ID/tokens" \
    -H "Authorization: Bearer $AMODAL_PLATFORM_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"ttl":600}' \
    | node -e 'const fs = require("fs"); const body = JSON.parse(fs.readFileSync(0, "utf8")); process.stdout.write(body.token)'
)"
 
curl -fN "$AMODAL_AGENT_URL/chat/stream" \
  -H "Authorization: Bearer $AMODAL_AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message":"Say hello."}'

The platform token needs permission to mint runtime tokens for that agent. Keep it on your backend. See Authentication for persistent agent API keys and browser authentication.

Chat request body

FieldTypeDescription
messagestring, requiredUser text. May be empty when images or attachments are supplied.
session_idstringContinue this conversation; omit to start one.
scope_idstringTenant, user, or object scope. Scope requirements depend on the host; see below.
contextRecord<string, string>App facts for prompt templates and connection context injection. These are not trusted authorization claims.
metadataRecord<string, string>Recorded on the turn's trace and the session. Apart from timezone, never sent to the model. See below.
agentstringNamed agent under agents/. Omit to use default when defined, otherwise the unscoped default chat.
skillstringSelect a skill-scoped session.
deploy_idstringDeployment hint for a host that resolves bundles dynamically. It does not switch the deployment behind a fixed agent URL.
model{provider, model, effort?}Model selection for the session, subject to the host's provider access.
max_session_tokenspositive integerCumulative session token budget. Checked between transitions, so usage can exceed it during a model call.
imagesarrayUp to 5 image attachments.
attachmentsarrayFiles as {mimeType, data, filename?, delivery?}, where data is base64 without a data-URI prefix, or uploads as {fileId, delivery?}.
turn_idstringClient-supplied UUID that identifies a resumable turn.
continue_on_disconnectbooleanKeep the turn running on the runtime if the SSE connection closes so a reconnecting client can observe or cancel it.

Your application backend must authorize the scope and any requested session before forwarding the call; see Embedding.

A scope_id claim on the caller's token overrides the request's scope_id. The runtime then limits that caller's chat resume, session history, and durable session actions to the claimed scope. The direct store API uses the caller's scope for every store not marked shared. A hosted browser session without a scope_id claim may request only its own user ID or <user ID>/<suffix>, and uses its own user ID when it requests none; any other scope_id returns 403. Its automations under /api/automations use its own user ID in place of the agent-level scope, which holds the operator's automations. An automation runs with the authority of the user who saved it: an end user's runs get the end-user tool set and restrictions. An end user's automation is disabled at its next run once that user can no longer use the agent.

Attachments support PDF, plain text, Markdown, CSV, PNG, JPEG, GIF, WebP, Office Open XML, OpenDocument, and RTF. The model receives Office, OpenDocument, and RTF files converted to text. An agent with a sandbox also accepts Outlook messages (application/vnd.ms-outlook), emails (message/rfc822), ZIP archives, legacy Word and Excel files (application/msword, application/vnd.ms-excel), HTML, and JSON; an agent without one receives a note for these types in place of their content. Each PNG, JPEG, GIF, or WebP image embedded in an Office or OpenDocument file follows its text as a separate image attachment named <filename>/<image>, up to 20 images and 15 MB across all attachments in the request, each image at most 3.75 MiB. The converted text lists the attached images and any embedded media left out, with the reason.

metadata describes where the request came from, such as {"userId": "u_42", "screen": "/billing"}. It accepts at most 50 keys, each up to 64 characters, with string values up to 1,024 characters; a request over these limits is rejected with 400. The runtime records each key on the turn's root span as amodal.meta.<key> and keeps the latest value of each key on the session. The model, tools, prompt templates, and guardrails never see it, with one exception: a timezone key that holds a valid IANA time zone, as the SDK sends, reaches the built-in automation tools, which read cron schedules and report run times in that zone. Any caller can set any value, so Amodal labels it unverified. The authenticated user, organization, and sign-in method are recorded separately as amodal.user.id, amodal.user.org_id, and amodal.auth.method, and metadata cannot override them. Amodal shows the email of an authenticated user who is an active member with read access to the agent's organization or an active collaborator on the agent. Amodal filters runs, sessions, and feedback by the userId and screen keys. Do not put secrets or sensitive personal data in metadata.

The per-file base64 limit is 28,000,000 characters (about 20 MB decoded), within a 50 MB JSON request limit. A message carries at most 50 attachments. delivery: "inline" sends content to the model; "context" exposes a manifest to the model and keeps the bytes available to tools. When omitted, runtime delivery policy applies.

In an agent with a sandbox, the runtime keeps the original bytes of every attachment for the conversation, up to 500 MB per conversation, and copies them to in/<sha256>/<filename> before each sandbox tool call; in/index.json lists them with their file ids. Documents are not sent inline unless delivery is "inline". Up to five images of at most 3.75 MiB each are sent inline to a vision model unless delivery is "context". The message carries a manifest that names each file, its sandbox path, and its id.

Uploads

An agent with a sandbox takes files uploaded ahead of the message, so a message is not bound by the JSON request limit.

MethodPathPurpose
GET/api/uploadsUpload limits as {maxFiles, maxFileBytes, maxConversationBytes, accept}, where accept lists the accepted extensions and MIME types. 404 when the agent has no sandbox. Takes deploy_id.
POST/api/uploadsUpload one file as the raw request body with Content-Type: application/octet-stream. Query: filename (required), mime_type, scope_id. Answers 201 with {fileId, filename, mimeType, size, sha256}.

The file's extension decides its type; mime_type is used only for a file without a known extension. A message carries at most 50 files, a file at most 50 MB, and a conversation at most 500 MB of files. Errors: 400 INVALID_FILENAME, 400 EMPTY_FILE, 413 FILE_TOO_LARGE, 415 UNSUPPORTED_MEDIA_TYPE for another content type, and 415 UNSUPPORTED_FILE_TYPE.

An upload belongs to the uploader, the agent, and the scope. The first chat message that names it in attachments attaches it to that conversation, and it cannot be attached to another. A chat request answers 404 FILE_NOT_FOUND for an upload the caller may not use, 413 CONVERSATION_FILES_LIMIT past the conversation cap, and 400 UPLOADS_UNAVAILABLE when the agent has no sandbox. An upload no message names becomes unavailable 24 hours after it was uploaded; an attached one, 30 days after. GET /api/files/:fileId downloads an upload for the callers who may see its conversation, or only its uploader before it is attached.

Sessions

MethodPathPurpose
POST/sessionsPrepare a session before its first message.
GET/sessions/historyList sessions, up to 500; accepts ?scope_id=.
GET/sessions/history/:idRead a session's history.
PATCH/sessions/history/:idUpdate session metadata.
DELETE/sessions/history/:idDelete a session.
GET/sessions/pending-approvalsList sessions waiting for an operator answer.
GET/api/sessions/:id/feedbackList the caller's ratings of the session's answers.
PUT/api/sessions/:id/turns/:turnId/feedbackRate one answer.

Each answer in GET /sessions/history/:id carries turnId, the turn_id of the turn that wrote it. Answers saved by runtimes that did not record it have none and cannot be rated. PUT /api/sessions/:id/turns/:turnId/feedback takes {rating: "up" | "down" | null, comment?}, with a comment of up to 2,000 characters, and returns 204. Each caller has one rating per answer: rating again replaces it, and null removes it. GET /api/sessions/:id/feedback returns {ratings: [{turn_id, rating, comment}]} with the caller's own ratings. Both routes return 404 for a session the caller cannot read, and 502 with FEEDBACK_UNAVAILABLE when the rating cannot be stored. They exist only when the runtime stores ratings, as hosted runtimes and amodal dev with session sync do.

PATCH /sessions/history/:id accepts title (string), tags (array of strings), pinned (boolean), and archived (boolean), and ignores other fields. The list returns the stored values under metadata.

Each row of GET /sessions/history carries the session's state:

  • status: running while a chat turn runs, then idle, failed, or cancelled. A background run reports its own status, such as queued, awaiting-input, scheduled, or complete.
  • pending: {kind, tool_name, question, asked_at} while the session waits for an answer, otherwise null.
  • last_turn_ended_at: when the latest chat turn ended, or null.
  • unread: true when a turn ended after the owner last read the chat.

PATCH /sessions/history/:id with {"read": true} marks the chat read and ignores every other field. Only the session's owner may set it, and any other caller who can see the session gets 403 with read_marker_owner_only. A session without an owner can be marked read by anyone who can see it. The runtime stamps its own time, never earlier than the end of the latest turn, and keeps updated_at unchanged, so reading a chat does not reorder lists.

On a hosted runtime, these routes require authentication. History and pending-approval lists hide sessions owned by another verified user and, for a token with a scope_id claim, sessions in other scopes. Reading, updating, or deleting a hidden session returns 404, the same response as a missing session. Updates and deletions check both live and persisted ownership. Sessions without an owner remain shared, and trusted server credentials without a verified user ID retain access to owned sessions.

For a token without a scope_id claim, the ?scope_id= query is a caller-supplied list filter, not an ownership credential. Lists filter ownership after fetching up to 500 rows, so fewer visible sessions can be returned even when other accessible sessions exist. For tenant-specific rules or calls using server credentials, have your application backend authorize each operation and retain the runtime credential.

Memory

MethodPathPurpose
GET/api/memoryList memories; accepts ?archived=true, ?topic=, and ?scope_id=.
POST/api/memorySave a memory: {content, tier?, topic?, source_ids?}.
PATCH/api/memory/:idEdit, archive, restore, retopic, or change tier: {content?, topic?, archived?, tier?, base_updated_at?}. topic: null clears the topic.

These routes exist when the agent sets memory.enabled and return 404 with MEMORY_DISABLED otherwise. They use the caller's scope as chat does. A caller sees the company memories of the scope and its own private memories; another person's private memory answers 404. When the agent sets sourceAccess, a company memory the caller cannot see under that rule is left out of GET and answers 404 to PATCH.

GET returns {memories, writable_tiers}. ?topic= keeps the memories whose topic is exactly that value. writable_tiers is ["private", "company"] for a signed-in person and ["company"] for a caller who names no person, under editableBy: "any". Under "admin", only operators get those tiers, and under "none" nobody does. POST and PATCH return 403 with MEMORY_READ_ONLY outside the caller's writable tiers. POST defaults tier to the first writable tier and returns 201 {memory}; PATCH returns 200 {memory}. Only a memory's owner can change its tier, to share a private memory or make a company memory private; anyone else gets 403 with NOT_OWNER, and a memory saved without a person has no owner. When base_updated_at is set and differs from the memory's updated_at, PATCH changes nothing and returns 409 {error, memory} with STALE_EDIT and the memory as it stands. A write that exceeds the tier's budget returns 409 with BUDGET_EXCEEDED. There is no delete route: archive a memory instead, and delete it from Studio. Responses are not cached.

Interactions

MethodPathPurpose
POST/chat/sessions/:id/ask-user-responseAnswer an ordinary chat confirmation with {correlation_id, approved}. ask_id is also accepted.
POST/chat/sessions/:id/messagesQueue {message} for the agent while a turn runs. Returns 202 {status, message_id}, 409 {error: 'no_active_turn'} when no turn is accepting messages, or 422 {error: {code: 'MESSAGE_BLOCKED'}} when a preInput guardrail blocks the message.
GET/chat/sessions/:id/turns/:turnIdObserve an active or buffered resumable turn over SSE (?after=<seq>).
POST/chat/sessions/:id/turns/:turnId/cancelCancel an active turn.
POST/api/sessions/:id/answerAnswer a parked durable workflow.
POST/api/sessions/:id/cancelCancel a durable workflow session.
POST/api/sessions/:id/restartRun a durable tool session's tool again in a new session.

Use the correlation_id from confirmation_required for an ordinary confirmation. The chat loop waits for that response. Choice selections from ask_choice are sent as the next chat message.

A durable_approval_required event identifies a separate parked session. Answer that session through the durable workflow API; see Agent Workflows.

GET /sessions/history/:id returns the questions a conversation still waits on as content blocks after the tool call that asked them: an ask_choice block (askId, question, options, multi) when the last answer ended on ask_choice, and a durable_approval block (sessionId, toolName, question, context?, inputType?, options?) for each parked session the caller can read that still awaits input. A reopened chat shows them as the cards the live stream showed.

The same route returns what a tool call showed through ctx.emit and ctx.setLabel. Each widget, show_preview, and connection_panel event a call emitted follows that call's tool_calls block as a content block of the same type. A connection_panel block always has state: 'idle'. Each skill_activated event becomes an entry in the message's skillActivations, and the tool call carries the last runningLabel and completedLabel the call set. Conversations saved before the runtime recorded these events return none of them.

System and artifacts

MethodPathPurpose
GET/healthHealth check ({ status: "ok" | "draining" | "starting", version, uptime_ms, active_sessions }).
GET/api/eventsRuntime state subscription, when mounted by the host.
GET/api/files/:fileIdDownload a file published by publish_file in a sandbox session, or an upload.
GET/api/sessions/:sessionId/artifactsList structured artifacts registered in the session.
GET/api/sessions/:sessionId/artifacts/:eventId/contentDownload a verified artifact's bytes.
GET/api/sessions/:sessionId/artifacts/:eventId/previewPDF rendering of a verified artifact, when its registration has previewUrl.
POST/channels/:channelType/webhookInbound messaging-channel webhook.

SSE event types

Chat frames contain a JSON object with type, timestamp, and event-specific fields. The server sends data: frames without a separate event: line.

Common events are listed below. The React SDK exports SSEEvent from @amodalai/react for typed chat stream handling.

TypeFieldsPurpose
initsession_id, turn_idSession created or resumed
text_deltacontentIncremental answer text
thinking_deltacontentModel reasoning output, when supplied
completion_feedbackcontentCheck feedback; discard prior text
tool_call_starttool_name, tool_id, parameters, running_label?, completed_label?Tool execution started
tool_label_updatetool_id, running_label?, completed_label?Tool display label changed
tool_call_resulttool_id, status, result?, content?, parameters?, duration_ms?, error?Tool result or error
tool_logtool_name, messageHandler progress log
subagent_eventparent_tool_id, agent_name, event_type, tool_name?, tool_args?, result?, text?, error?Specialist activity
skill_activatedskill_nameSkill loaded
filefile_id, name, mime_type, size, url, description?, artifact?Sandbox file or registered artifact
widgetwidget_type, dataStructured content for the client
confirmation_requiredendpoint, method, reason, escalated, params?, connection_name?, correlation_id?Ordinary tool approval
approved / deniedresource_type, preview_idApproval decision applied
ask_choiceask_id, question, options, multi?Question with selectable options
durable_approval_requiredsession_id, tool_name, question?, options?, allow_edits?Parked workflow approval
agent_handofffrom, to, removed_toolsSession changed its root agent
user_message_deliveredmessage_id, textQueued mid-turn message delivered
input_redactedtextUser input was redacted
compaction_startestimated_tokens, thresholdContext summarization started
compaction_endtokens_before, tokens_after, compaction_tokensContext summarization completed
warningmessageNon-fatal problem
errormessageExecution error
doneturn_id, reason?, turns?, trace_id?, usage?, model?Turn completed

Streaming example

data: {"type":"init","session_id":"session-123","turn_id":"0f9c1c3e-5a3b-4d0e-9a51-2b7c8e1d4f60","timestamp":"2026-09-07T10:00:00Z"}

data: {"type":"text_delta","content":"Hello.","timestamp":"2026-09-07T10:00:01Z"}

data: {"type":"done","turn_id":"0f9c1c3e-5a3b-4d0e-9a51-2b7c8e1d4f60","reason":"model_stop","turns":1,"usage":{"input_tokens":100,"output_tokens":2,"cached_tokens":0,"total_tokens":102},"timestamp":"2026-09-07T10:00:01Z"}

turn_id identifies the answer the turn writes. Session history returns it as turnId, and a rating names it. The runtime resolves the run the answer came from, so a rating links to that run in Amodal. trace_id is the trace of that run, present when the runtime exports traces. model is the model that answered, as {provider, id, effort?, fallback?}, taken from the last model step that produced answer text. fallback is true when a fallback provider in the chain answered instead of the primary. Session history returns the same object as model on each answer, and answers saved by runtimes that did not record it have none.

Done reasons

ReasonMeaning
model_stopThe model finished without requesting more tools, or a tool ended execution.
max_turnsThe run reached its model-turn limit, 50 by default.
user_abortThe request was cancelled or the client disconnected.
errorAn unrecoverable error ended the run.
budget_exceededAccumulated session tokens reached max_session_tokens. The check runs before the run starts and between steps, so one model call can exceed the budget.

When a top-level run stops on max_turns or budget_exceeded, one final model call streams a summary as ordinary text, and the done event keeps the original reason. For max_turns the summary says what was done, what is left, and what the user should say to continue. For budget_exceeded it says what was done and what is left, and that a new conversation is needed. A tool call requested in that final turn is not run. If the summary call fails or writes no text, the runtime streams a fixed message naming the limit. A run that starts at or over the budget makes no model call. Cancelled runs, subagents, and runs with a turn limit of 1 make no summary call.

Normal completion emits done with usage and the reason. A disconnected client cannot rely on receiving it; read the persisted session history to inspect an interrupted request.

Building a client

streamChat parses the chat stream and accepts an abort signal and runtime token. This helper requires the React package and its peer dependencies; it can be used without rendering a chat component.

import { streamChat } from '@amodalai/react';
 
async function chat(runtimeUrl: string, token: string, message: string, sessionId?: string) {
  for await (const event of streamChat(
    runtimeUrl,
    {
      message,
      ...(sessionId ? { session_id: sessionId } : {}),
    },
    undefined,
    token,
  )) {
    if (event.type === 'init') sessionId = event.session_id;
    if (event.type === 'text_delta') console.log(event.content);
    if (event.type === 'error') throw new Error(event.message);
  }
  return sessionId;
}

Store the returned session ID and pass it with the next message. This minimal example prints text; it does not render widgets or answer confirmations. Use useChat or AmodalChat for those interactions.

Session lifecycle

A request without session_id creates a session. Later requests with that ID resume the conversation. The runtime records the verified user ID of the session's creator and refuses to reuse the session for a request whose verified user ID differs, starting a fresh session instead. A caller with no verified user ID, such as an API key or a service token, can resume any session. When the caller's token has a scope_id claim, the runtime also refuses to resume a session stored in another scope and starts a fresh session instead. Without that claim, the runtime does not compare the session's scope with the request. Your application backend must authorize a resume request before forwarding it.

POST /sessions creates a session ahead of the first message. It accepts the chat body's agent, skill, deploy_id, max_session_tokens, model, scope_id, and context, builds the session from them, and returns 201 with {session_id, idle_ttl_ms}, where idle_ttl_ms is the runtime's idle session timeout in milliseconds. The first message that carries that ID skips the session setup and goes straight to the model. Send the same fields you will chat with, because a live session keeps its skill, deploy, model, and token budget. A prepared session is not persisted until its first turn, and an unused one expires with the idle timeout. The React SDK's chat hooks prepare a session when they mount; see Chat hooks.

The runtime evicts a session from memory after 30 minutes idle. Hosted sessions persist in the platform, so eviction does not delete history and the next request reloads the conversation. Local development keeps sessions and stores in memory only, so they are lost on restart.

An ordinary chat stream disconnect cancels the active request. Sending the same session_id continues the conversation; it does not replay the interrupted SSE response. Use durable workflows when work must continue independently of the connection.

Context compaction

When estimated context passes 90% of the model's context window, the runtime manages history in two ways:

  • Tool-result clearing. Once the conversation holds more than 15 tool-result messages, results older than the latest 5 become short summaries or cleared-result markers. Selection is by recency, not size.
  • Compaction. The runtime summarizes older turns with the session's model and keeps the latest 6 user turns verbatim. The summary is capped at 4,000 tokens and covers the current task, key data, actions taken, errors, and next steps. It emits compaction_start and compaction_end.

Exact wording and tool-result details can be lost. Save facts that must survive in a store. If summarization fails, the run continues with the existing history; after 3 consecutive failures, compaction stops for that run. These thresholds are not configurable from agent source.