Skip to content

MCP server

Ocman embeds an optional MCP (Model Context Protocol) server exposing Factory, Inbox, routine, pull-request, session inspection, creation and messaging, and file-embedding tools.

Ocman works fine as a plain dashboard without this. Install it only if you want conversational Factory handoff, Inbox delivery, routine management, session inspection, or embedded file display.

Endpoint

The server uses the Streamable HTTP transport and listens on its own loopback-only port, separate from the web UI:

  • http://127.0.0.1:8227/mcp is the dedicated MCP listener (-mcp-addr). It works the same in dev and production and requires the install’s bearer token (see Authentication ).
  • http://localhost:8228/mcp is the same endpoint on the web UI’s port, both in dev (Vite proxies it to the backend on :8229) and for the production binary’s default -addr. Password auth applies there, so a native MCP client gets 403 when auth is configured.

/api/capabilities also reports the recommended URL as mcpServer.url. Both paths are localhost-only. Origin-less native MCP clients work, cross-origin browser requests are rejected.

The dedicated listener exists because MCP clients cannot present an auth cookie. It is unsafe to accept them on the web UI’s port, where every request forwarded by a reverse proxy arrives from 127.0.0.1. Binding a separate loopback-only listener keeps it out of reach of a proxy pointed at the main port. Ocman refuses to bind -mcp-addr to a non-loopback address, and -mcp-addr "" disables the dedicated listener entirely.

Authentication

Every local user, not only you, can connect to a loopback port, so the dedicated listener does not trust the peer address alone. /mcp and POST /hook on it require Authorization: Bearer <token> and answer 401 otherwise.

Ocman generates the token once per install, keeps it sealed in state.db and writes it on every start to mcp-token in the state directory (~/.local/share/ocman/mcp-token by default, beside state.db) with mode 0600. If ocman cannot load the token, the dedicated listener stays off.

  • OpenCode: the installed entry carries "headers": {"Authorization": "Bearer {file:<state dir>/mcp-token}"}. OpenCode substitutes the file’s contents when it loads the config, so the token never lands in opencode.json. On startup ocman adds this header to an entry installed by an older version, after the usual backup. Restart OpenCode to pick it up.

  • Claude Code and Codex sessions that ocman launches receive the token from ocman itself: Claude through a private --mcp-config file in the state directory, Codex through ACP session setup. Neither puts it on a command line.

  • The Claude hook plugin’s ocman hook command reads the token from the file named by --token-file (default: the state directory’s mcp-token).

  • Any other client, for example a Claude Code you start in a terminal, needs the header from a private configuration file. Do not pass the token as a command-line argument, for example with claude mcp add --header or claude mcp add-json: other local users can read a process’s arguments. For Claude Code, write an MCP config file that only you can read, the same way ocman configures the Claude sessions it launches:

    (
      umask 077
      mkdir -p ~/.config/ocman
      printf '{"mcpServers":{"ocman":{"type":"http","url":"http://127.0.0.1:8227/mcp","headers":{"Authorization":"Bearer %s"}}}}\n' \
        "$(cat ~/.local/share/ocman/mcp-token)" > ~/.config/ocman/claude-mcp.json
    )
    claude --mcp-config ~/.config/ocman/claude-mcp.json

    umask 077 creates the file with mode 0600. printf is a shell builtin in bash and zsh, and cat only receives the token file’s path, so the token never appears in any process’s arguments. Pass the file’s path to --mcp-config on every start, for example from a shell alias. The file holds a copy of the token, so keep it private and rewrite it if you replace mcp-token. The token never goes in a URL or query string.

Setup

Ocman checks OpenCode’s global config on every page load and, if it doesn’t find its own entry, shows a toast offering to install it. Clicking Install writes the entry below into ~/.config/opencode/opencode.json ($XDG_CONFIG_HOME and OPENCODE_CONFIG are honoured), after copying the original to opencode.<timestamp>-backup.json in the same directory. Every other key in the file survives, including any other MCP servers. Restart OpenCode afterwards, since it reads the config at startup.

Ocman won’t touch a config it can’t rewrite losslessly, meaning a .jsonc file or a .json file with comments. The toast then shows the URL to paste in yourself. It also offers to update a stale entry, say one still pointing at an older port. GET /api/mcp/config returns the same information.

To do it by hand, add the server to your project’s opencode.json or the global config:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "ocman": {
      "type": "remote",
      "url": "http://127.0.0.1:8227/mcp",
      "enabled": true,
      "headers": {
        "Authorization": "Bearer {file:~/.local/share/ocman/mcp-token}"
      }
    }
  }
}

The MCP port is fixed, so this config works for both make dev and the production binary. Change it if you moved the listener with -mcp-addr.

Tools

Factory tools are available only when the instance-wide Factory beta toggle is enabled under Settings → App → Beta features. Disabling it removes them from discovery and rejects calls, including from clients with a cached tool list. Other MCP tools remain available. Factory also dispatches new work only while the toggle is on; sessions already running are not stopped.

Agents should include a short, goal-focused intent string on every tool call, including help and read-only calls, for example "intent": "Find the session that reported the build failure". The tool schemas and bundled skills encourage this; the API keeps the field optional for existing callers. Ocman shows it beside the tool name in the conversation. It does not change the operation, permissions, or confirmation requirements. Omit it to keep the usual argument summary. In Code Mode, supply intent as an inline string literal in tools.ocman calls; variables and computed values are not evaluated for display.

ToolDescription
factoryNative Factory control surface. Use action: "help" for actions, validation, examples, output schemas, and domain errors. Formula actions accept TOML only. Implementation Issues run sequentially on a shared branch; complete_attempt records a verified clean, pushed commit checkpoint without pr_url. A separate final delivery Issue creates or reuses the review-ready PR and completes with pr_url.
factory_controlProposes a change to an Epic: reopen, typed mutate_graph (applied without plan approval), resolve_recovery, deliver_as_is, pause, or resume, with a one-line summary. It only records the proposal; Ocman renders a card under the call and runs the change when the user clicks Confirm.
artifactsPublish and inspect project artifacts (reports, screenshots, generated files, links). Actions help, create, list, get; there is no delete. create needs directory and title, takes an optional platform + session_id pair, files ({path} or {name, content, mime}) and links ({url, label}), and returns the artifact id, its ocman UI url, item URLs, and a markdown snippet. list filters by directory or session and pages with cursor/limit. Installed skill: ocman-artifacts.
inboxSend owner-local Inbox items and recall them by opaque ID. Unknown and already recalled IDs are successful no-ops. Use action: "help" for schemas and examples. Agents should send only asynchronous completions needing attention, blocked decisions, or important failures, not routine progress.
routinesCreate, inspect, update, run, and soft-delete routines. Use action: "help" for current inputs, examples, output schemas, and domain errors.
webhooksCreate and inspect owner-local webhook inboxes, subscribe or unsubscribe routines, inspect recent deliveries, and redeliver a stored delivery by ID to the current subscribers. Actions help, list, get, create, subscribe, unsubscribe, deliveries, redeliver. Uses the saved relay settings. Ingestion URLs are credentials; shared secrets and relay management credentials are omitted.
pull_requestsBrowse project PRs, checks and mergeability; launch PR sessions or worktrees; link/unlink PRs to sessions; start/stop persistent watches; prepare unsent feedback, checks and conflict task prompts. Use action: "help" for required inputs and examples. Project actions require an absolute directory and explicit remote_id; session actions accept session_id and platform, or an absolute directory for automatic unique-session lookup. Optional platform and remote_id narrow lookup; ambiguity returns candidates without performing the action. checks also accepts a linked PR’s host, repo and number and reads its head commit; linked is compact by default and filters by number. Does not create or merge PRs, change credentials, or approve cross-fork fetches. See Pull requests .
sessionsSession listing, search, detail inspection, creation, messaging, and archiving. Use action: "help" for schemas and examples. list, search, and get are read-only; search matches all available session IDs, titles, directories, platforms, and host names. With content: true it also scans user and assistant message text (not tool output) from the last since_days (default 7). Each hit returns up to five {partId, messageId, role, snippet} matches. Content search reads this machine’s retained conversation history across platforms and never covers remote owners. Results depend on history ingestion progress. get and send need the recipient’s session_id; pass platform when that ID is ambiguous. create starts a new session. send delivers prompt to an existing session. archive and unarchive take a session_id and optional platform and resolve the session’s update time on the server. An idle session is archived immediately. A busy session on this machine, including one archiving itself, returns deferred: true and is archived when its current turn finishes, because activity after the archive time would resurface it; a restart before then drops the deferred archive. A busy remote session is rejected. The tool cannot cancel sessions.
modelsRead the model catalog for an absolute directory, with optional platform. Pass the target’s compound platform ID for a remote machine; omit it only when one platform is available. Returns platform, models, defaults, hasProviders, and liveConnection. Each model includes provider, model, isAvailable, and any reasoning variants. Use provider/model with sessions creation. Reads an existing instance without launching one; historical entries remain visible when live provider data is unavailable.
embed_fileMake a file on disk viewable to the user in the ocman UI. Takes an absolute path (plus an optional label) and returns a signed URL and a markdown snippet the agent pastes into its reply. Images and SVGs render inline in the conversation; PDFs and other types open or download in the browser. See Embedding generated assets .
render_uiRender a structured result directly below the tool call using A2UI v0.9.1 and Ocman’s custom catalog. Call action: "help" for the catalog, schemas and examples, then action: "render" with title, summary and messages. Supports text, layouts, sortable tables, charts, stat tiles, text fields, checkboxes and buttons. See Agent-generated results .
plugin_session_toolDispatcher for tools a plugin grants to a private session it started. Only usable with that session’s binding. See Plugin session tools .
Plugin agent toolsTools declared by enabled plugins on this machine and approved with tool.agent, listed under their declared names. Arguments are validated against each tool’s schema. Requests needing consent return confirmation_required until the user approves them in ocman; repeat the call with confirmation_id. See Plugin agent tools .

Session search matches the full available catalogue, including older and archived sessions, before applying limit (default 100, maximum 500 results). It does not restrict matching to the newest 500 sessions. since_days only controls the content-search window, not title or other metadata matching.

Session list returns compact rows by default: id, platform, title, directory, branch, status, origin, routineId, parentId, timeCreated, timeUpdated, archived and remoteId. Pass detail: true for the full metadata, including costs, tokens and read state. since_days keeps sessions updated in the last 1–365 days. origin selects and exclude_origin drops comma-separated creation origins (user, routine, plugin, factory, external). For example, exclude_origin: "plugin,routine" hides automated sessions. Owners report the origin recorded in their session catalogue, including remote machines. Rows without a recorded origin count as user, or as routine or factory when linked to one. Filters apply before limit, so automated sessions cannot push matching sessions past the cap.

sessions with action: "send" wraps the prompt in an agent-message envelope before using the existing direct-send path. Native history retains that envelope; the dashboard renders it as an Agent message, not a user bubble. The source is ocman.sessions, not an authenticated sending-session ID, and the message does not carry user authority. Older plain-text deliveries remain unchanged because they have no reliable agent-origin marker.

Session creation returns platform, session_id, directory, and a browser-ready url. Render url as a clickable Markdown link for the user. The link includes the owning platform or connection, including remote sessions. Internal MCP links are root-relative, such as /session/…?platform=…, so opening them keeps the viewer’s current dashboard domain and port. Keep them relative in Markdown. External links, such as forge and relay URLs, remain absolute. If creation succeeds but setup or prompt delivery fails, the error also includes a link to the created session.

To create a session on a specific platform, pass an absolute directory and platform, such as claudecode or r-machine:claudecode. No caller session_id is needed. Supply both platform and session_id only when using an existing session to infer its project directory.

For example, list models before choosing one for a new session:

{"directory":"/absolute/project/path","platform":"opencode"}

Call models with these arguments. When hasProviders is true, entries with isAvailable: true belong to connected providers. When it is false, availability is unconfirmed and the list falls back to historical models and favorites.

Agent-generated results

The render_ui tool advertises A2UI support in its description. Agents call {"action":"help"} to discover the supported protocol version, catalog ID, JSON schemas, limits, a complete form example and a chart example. This works through the existing MCP connection; no A2A or AG-UI server is required. Agents should use it when a table, chart or form communicates better than prose, and keep a short text summary for clients without Ocman’s renderer.

Each render call contains one self-contained surface. Its messages use version: "v0.9.1", start with createSurface, then define components through updateComponents and optionally replace scalar form data with updateDataModel. The catalog ID is https://ocman.dev/a2ui/results/v1/catalog.json. It is an identifier, not a URL the renderer fetches. This is a restricted custom catalog, not support for the complete A2UI basic catalog.

Supported components are Text, Column, Row, Card, Divider, Table, BarChart, PieChart, MultiBarChart, LineChart, ScatterChart, Stat, TextField, CheckBox and Button. Bindings reference a single top-level data field, such as {"path":"/job"}. See the tool’s help for exact properties. HTML, scripts, external resources, functions, templates, theme overrides, deleteSurface and updates to earlier calls are not supported.

The Go tool and browser validate against the same schemas. Results are limited to 64 KiB, 32 messages, 100 components, depth 16 and 500 rendered nodes. Tables have at most 200 rows and 12 columns; bar charts have at most 50 non-negative values. See Charts for the other chart limits. Invalid results remain available as ordinary tool output rather than being partially rendered. Tool validation errors use VALIDATION_FAILED so the agent can correct its payload.

Results are retained with normal conversation tool output and can be rendered again after reload. Unsaved form edits are local to the mounted result and reset on reload or session changes. They are not sent while typing.

Clicking a result button opens a review dialog showing the resolved A2UI action. Only Send response sends it as a normal user message to the displayed session’s owning platform. The agent receives the action name, surface and component IDs, timestamp and resolved context. Rendering never performs an operation, and sending an action does not bypass session permissions. Read-only, shared and disconnected conversations disable form editing and action delivery. Tables can still be sorted locally.

Charts

Charts take data, never colors or styles. Each chart has a label, used as its caption and accessible name, and optional unit (a short suffix such as cores or MiB) and format hints. format is number (the default), compact (1.2K), percent (values already on a 0–100 scale) or bytes (raw bytes shown as KiB, MiB or GiB).

ComponentDataLimits
BarChartOne series of labelled values50 non-negative values
PieChartLabelled slices; variant is donut (default, with the total in the middle) or pie1–50 non-negative slices with unique labels
MultiBarChartcategories plus series; mode is grouped or stacked, orientation is vertical or horizontal1–50 categories, 1–8 series of non-negative values or null
LineChartx of type category, number or date, plus series; area fills to zero2–366 x values, 1–8 series of numbers or null gaps
ScatterChartseries of [x, y] points, with xUnit for the x axis1–3 series of up to 200 points
StatOne headline value, optional delta, deltaLabel and better (up, down or neither)—

Every series has one value per category or x value, and series names are unique within a chart. Numeric and date x values must strictly increase. Dates are YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS[.sss]] with an optional Z or ±HH:MM offset; times without a zone are UTC. A result renders at most 12 pie, multi-bar, line or scatter charts.

Pies sort slices largest first and show at most eight. The rest, and slices under 2% of the total when there are at least two of them, fold into a neutral Other slice. The data table still lists every slice.

Colors come from a fixed colorblind-safe palette of eight --series-* tokens, chosen so neighboring slots stay distinguishable under common color-vision deficiencies. Except in scatter charts, each distinct series or slice name keeps one color in every chart of a result, in order of first appearance. A pie of per-app CPU and a pie of per-app memory therefore color the same app the same way. A chart that includes a name past the first eight colors its series in its own order instead. Names called Other are always neutral. Scatter charts are capped at three series because only the first three palette colors stay distinct when every pair is compared. Scatter always assigns those colors in its own series order, ahead of cross-chart name consistency. Other stays neutral.

Charts show exact values in hover tooltips, add a legend for two or more series, and include a collapsible data table. The canvas has an accessible name describing the chart. Stat deltas show an arrow and a sign, and screen readers also get “better” or “worse”, so color never carries the meaning on its own.

How results are rendered

    flowchart LR
    Agent[Agent MCP client] -->|render_ui help and render| Module[agentui module]
    Schemas[Shared A2UI catalog and schemas] --> Module
    Module -->|validated self-contained tool result| History[Normal conversation history]
    History --> Renderer[Native React result renderer]
    Schemas --> Renderer
    Renderer -->|explicit action review| User[User confirmation]
    User -->|normal owner-qualified message| Session[Existing session send path]
    Session --> Agent
  
  • internal/agentui contributes the render_ui MCP tool and validates the restricted A2UI v0.9.1 result catalog. It has no database tables, network fetches or session-mutation endpoints. Each call is an independent snapshot.
  • The browser revalidates retained tool output against the same schemas using Ajv, then renders shared Ocman controls and tables. Charts use the dashboard’s chart.js setup, loaded with the first chart a conversation shows. The catalog allows no generated code or external resources. Graph validation bounds recursion and rendered node counts on both sides.
  • Action callbacks are scoped by OcmanRuntimeProvider to the owning platform and session. User confirmation sends a normal message through the existing send path. Shared, disconnected and ownerless views have no action callback; session changes discard unsent UI interactions.

Security boundary

The A2UI renderer accepts data, not web content. Text, table cells, chart labels and form values are rendered as literal text. The catalog rejects images, iframes, HTML properties, arbitrary styles, resource URLs and function calls. Catalog and schema identifiers are never fetched from the network. The only network operation a result can initiate is a user-confirmed response through Ocman’s existing session API.

The dashboard and relay viewer add a browser-level defense. Their CSP blocks external image loads and scopes WebSockets to the serving host and port. Local and embedded images still render. External conversation images require an explicit per-image opt-in in authenticated views, using a script-free opaque iframe whose policy allows only that image’s origin. Consent resets on reload and is unavailable in public shared views. The wrapper does not fetch on the server or expose Ocman’s DOM/storage; the external image request can still disclose the viewer’s IP or that site’s cookies. Normal user-clicked links remain links. See HTTP serving .

Do not add URL-bearing components or generated HTML/JavaScript to the native A2UI catalog without a separate security review.

HTML artifact previews have a separate iframe sandbox. Opt-in script execution never grants allow-same-origin. Both preview modes block external subresources; the interactive policy also blocks fetches. A sandboxed document can still navigate itself, so that mode is not a strict no-egress environment.

Factory

Ocman installs the ocman-factory skill globally for OpenCode. It teaches the single action-based factory tool and directs agents to action: "help" before using detailed actions. When a result creates an epic or needs a human action, it carries a [[ocman:card ...]] marker and Ocman renders the card under that tool call. The tool text tells the agent a card is waiting for the user and that the user must handle it there; agents do not copy the marker into replies.

Factory tool errors intentionally contain only domain-level guidance. Open Factory at /factory to inspect the native Issue graph.

Agents can list and append persistent Issue comments with issue_comments and add_issue_comment. Comments are append-only and remain separate from the linked session conversation.

Agent MCP sessions cannot perform operator decisions or change Factory configuration. Agents can propose executable tickets and structural edits with mutate_graph; each revised graph requires human approval before new work runs. While the initial proposal awaits materialization, revise that proposal instead of editing live work. create can create Epics after explicitly acknowledging local execution and uses the built-in tracer Formula. save_formula, set_capacity_policy, Plan decisions, recovery decisions, authority decisions, and reopen_issue (returning failed work to the queue) are refused. Each permission denial returns a card marker that renders with the tool call. Ocman interprets its type, target IDs, and action, then reads the live state to decide whether to render a card. Action markers show nothing while loading or after that action is resolved. Creation markers remain visible. A marker written in assistant text also renders; ordinary markdown links stay links and markers inside code examples are displayed literally.

For example:

[[ocman:card type=factory-epic epic=my-epic action=created]]
[[ocman:card type=factory-issue epic=my-epic issue=my-epic.3 action=reopen_issue]]

IDs are percent-encoded when needed. The renderer handles live status, button availability, and click results, so the model does not need to reproduce UI logic. reopen_issue with epic_id and issue_id produces a card with Reopen issue for failed or cancelled implementation work. Rendering the card does nothing; clicking the button uses the same human-action endpoint as the Factory action inbox. The card refreshes live state and reports action errors. It also offers planning, materialization, plan decisions, recovery, and authority decisions when available. Graph editing, formula editing, and capacity changes link to their existing Factory screens. Requests without a resolvable target remain links to the action inbox.

submit_proposal additionally requires the active Planning Attempt’s attempt_id and attempt_token. Its manifest accepts an issue graph with nodes and typed edges (blocks or on_failure); legacy per-node dependsOn remains accepted for stored and older proposals.

For a complete plan made in a regular session, use create, then issues to find the root mol ID, then import_proposal. It accepts epic_id, manifest_json in the same format as submit_proposal, and optional rationale_markdown, without attempt credentials. Import is allowed only before any Factory attempt has been claimed and while the approval gate is unresolved. It creates a proposal and returns a human approval card, without launching a planning session or implementation. Re-import after a revision request to submit the updated plan. The agent still cannot approve it. See Use an existing plan .

Each Epic has one read-only control session where the user steers it (see Control session ). The agent there explains and proposes; every change goes through factory_control, whose card keeps it behind an explicit user confirmation in the conversation.

Upgrade warning: the native Factory cutover does not migrate legacy Factory runs. Retired YAML Formula tables are kept under legacy_factory_* names for manual recovery when the v66 migration completed successfully; an installation already stamped with the defective v66 migration may have empty repair tables because dropped data cannot be reconstructed. The native Factory does not read these tables.

Routines

Ocman installs the ocman-routines skill globally for OpenCode. The action-based routines tool supports listing, reading, creating, patching in place (only the fields passed change), replacing, running, soft-deleting, and viewing run history. Its help action is the authoritative contract for agents.

Webhook triggers

Use webhooks with action: "help" for the current schema and a GitHub PR filter example. Configure the relay URL and enrollment token once in Settings → Webhooks, then:

  1. Create a disabled routine with routines, or disable an existing one and set its schedule_kind to none.
  2. Use webhooks list to reuse an inbox, or create with a name. The result includes the provider’s ingestion URL. Treat it as a credential.
  3. Call subscribe with inbox_id, routine_id, header_predicates, and json_predicates. Both predicate arguments are JSON strings containing objects keyed by header name or RFC 6901 JSON pointer. Use explicit "{}" for an unfiltered source. Conditions combine with AND and support equals, oneOf, and exists.
  4. Register the URL with the provider, then enable the routine with routines patch. Use webhooks deliveries to inspect recent outcomes.

For an author-only GitHub review, filter X-GitHub-Event to pull_request, /repository/owner/login to the organization, /pull_request/user/login to the author, /pull_request/draft to boolean false, and /action to opened, synchronize, reopened, or ready_for_review. Filtering sender would select whoever caused the event, not the PR author.

Subscribing updates the filters for that inbox/routine pair. It does not change the routine’s schedule, enabled state, or other subscriptions. Unsubscribe the old inbox when switching triggers. Remote routines are rejected.

The optional secret and secret_header on create describe a literal header value. They do not validate GitHub’s HMAC signatures. Without a shared header, the relay authenticates ingestion using the token in the URL. Delivery payloads are untrusted data, not instructions.

Inbox

Ocman installs the ocman-inbox skill globally for OpenCode. It permits only the inbox actions help, send, and recall. Agents should use send for an asynchronous completion that needs attention, a blocked decision, or an important failure outside the active conversation. Routine progress and successful intermediate steps stay in the conversation. Reading or archiving Inbox items is a user-only dashboard operation and is not exposed to agents.

Sessions

The sessions tool inspects sessions with list, search, and get, and starts new top-level sessions with create. Use send to message an existing session when the user requests it:

{"action":"send","session_id":"ses_recipient","platform":"opencode","prompt":"The tests passed. Continue with the review.","intent":"Send the test results to the review session"}

For send, session_id identifies the recipient, not the calling session. platform is optional for an unambiguous ID; use the compound platform ID for a remote recipient. Delivery uses normal project/session model selection and the recipient’s permissions, and sends immediately, including mid-turn, without changing its held queue. The response {platform, session_id, sent: true} acknowledges delivery, not completion. Use get to inspect replies. Do not blindly retry a failed request whose delivery is uncertain, since that can send the same prompt twice.

create sends prompt to the new session. OpenCode supplies the invoking session through its per-call _meta["ai.opencode/sessionID"], including in Code Mode. Managed Claude and Codex sessions receive caller headers through their MCP configuration when launched or resumed. The agent does not need to discover or repeat its identity. No prompt injection, extra process or polling is involved.

Clients without transport context must supply either the caller’s platform and session_id, or an explicit target platform, model (provider/model), and absolute directory. Directory-only requests from unbound clients are rejected rather than silently selecting defaults. This requirement applies only to MCP creation, not the plugin session API. Caller context is correlation and inheritance context, not authentication or authorization. agent, worktree, and title are optional. With caller identity, an omitted model inherits the calling session’s current model when available, even with an explicit directory. Without an available caller model, it uses the project’s first configured model, then the platform’s default selection. An omitted agent uses Settings’ default agent. Explicit model and agent values override those defaults. Explicit models are checked against the destination catalog before launching a runtime, worktree or session. An unknown platform, unavailable model or failed catalog lookup returns an error instructing the agent to ask for clarification, not to remove the requested selection or substitute a default. Initial model and agent selections also travel with owner-routed creation. For the first prompt, an explicit MCP model bypasses project defaults and provider cooldown fallthrough. A failing requested model must not silently become another model. Ordinary composer sends retain their existing fallthrough behavior.

Creation acknowledges prompt admission, not execution. Verify the actual platform and an assistant message’s model using get before reporting that the requested agent started. A stored user prompt or default model is not evidence of execution. When startup remains unverified, report it without automatically resending the prompt or sending a nudge.

A failed creation that allocated no session names the stage that failed, such as worktree setup, runtime preparation or session allocation, a classified cause and whether a retry can help. For example, a disconnected machine or a platform without a ready instance can succeed later, while a rejected request or an unexpected server error fails the same way on an unchanged retry. Raw causes such as host paths and command output stay in the server log under MCP session creation failed, with the same stage. When allocation may already have happened, the error names the session that may exist and says not to create another, because a new request would not deduplicate against it.

Like the new-conversation composer, an omitted worktree creates a fresh worktree when the directory is eligible. Non-repositories, existing linked worktrees, and repositories without a usable base use the current checkout. Set worktree: false to use the given directory, or worktree: true to require a fresh worktree. Git probe failures return an error rather than choosing a target. directory must be absolute. When omitted, the target is the project root of the calling session, identified by transport context or platform and session_id. platform also selects the machine that runs the new session. Without caller identity, all three target fields are required even when model has a platform prefix. New sessions use the platform’s default permissions and do not inherit the caller’s rules.

Caller context is resolved using indexed local catalogue lookups, not conversation history or native-runtime probes. Native IDs must match exactly one retained physical binding on this owner. Canonical IDs retain their exact account routing key. Unknown, ambiguous, purged, disconnected or conflicting transport context stops creation before allocating a child. An explicit destination never disables this check. Existing authentication remains required; caller metadata grants no additional permissions. Optional model inheritance may read the latest message, but a failed history read cannot erase the creator link.

Validated caller identity is saved as the new session’s creator in the MCP-serving instance’s state.db, including launches in another project and on a remote machine. Both references retain their platform and machine scope. The link is saved before the first prompt and remains if prompt delivery fails. Failure to save the link stops prompt delivery and returns the created session’s identity. Unbound external requests without caller identity have no creator link. This provenance is separate from native subagent ancestry and does not change session grouping, lifecycle, or permission inheritance. Older launches are not backfilled.

    flowchart LR
    OC[OpenCode per-call metadata] --> Resolve[Catalogue caller lookup]
    Managed[Claude / Codex session headers] --> Resolve
    Resolve -->|unique local owner and source| Caller[Canonical caller and account]
    Resolve -->|unresolved or conflicting| Refuse[Refuse before launch]
    Caller --> Selection[Validate explicit selection]
    Target[Explicit destination or caller defaults] --> Selection
    Selection -->|unresolved| Refuse
    Selection --> Launch[Owner-routed child creation]
    Launch --> Link[Persist creator link]
    Link --> Prompt[First prompt]
  

sessions.get and GET /api/session/{id} return a separate optional creator object with platform, sessionId and createdAt (Unix milliseconds), read from the serving instance’s saved launch provenance. The platform includes machine scope for remote creators. This field does not replace session.parentId or add the creator to sessionTree. Sessions without a saved link omit it. A detail provenance read failure is logged and omits the field without blocking conversation access.

The compact sidebar response also includes session.creator, fetched in one batch from the serving instance. Detail rows carry the same reference so an activity refresh or open-session fallback retains the link. The sidebar nests these independent sessions under their creator when both are in the displayed list, including cross-project and cross-platform launches. Native parentId takes precedence. Missing or filtered creators leave the session top-level; cycles cannot hide rows. Independent sessions keep full cards and ordinary archive behavior, while native subagents remain compact. The children and origin filters follow these display links without changing lifecycle or permissions. Sidebar nesting and row keys use canonical ocm_* identities directly; there is no fallback to platform-prefixed native IDs. Creator references still require the matching platform and machine scope.

OpenCode permissions apply to whole tools, so requiring approval for create or send also requires it for the read-only actions.

Use create for independent work that should show up as its own session. For work inside the current turn, OpenCode’s native Task tool handles subagent delegation. A configured subagent model overrides the caller’s model; otherwise the subagent inherits the invoking primary agent’s model. The installed ocman-sessions skill also documents one-off Task model selection.

Embedding generated assets

Agents routinely produce files a chat transcript cannot show: a rendered chart, an SVG diagram, a generated PDF. embed_file closes that gap.

  1. The agent writes the file to disk as usual.
  2. It calls embed_file with the absolute path.
  3. Ocman returns a domain-free URL under /api/file/{token} plus a markdown snippet, which the agent includes in its reply.
  4. The ocman UI renders that markdown: images and SVGs appear inline in the conversation, other types become a link the browser opens or downloads.

The token carries the absolute path and an expiry six to seven days out, both covered by an HMAC signed with a key persisted in state.db. Links survive restarts, while a hand-crafted, altered or expired token is rejected with 403. Transcripts keep the original URL, so when the ocman UI renders an embed whose URL has expired, or expires within a day, it asks POST /api/files/refresh for a fresh URL to the same file. Copies of the URL outside ocman, such as exported or pasted transcripts, stop working on their own. URLs minted before expiries existed are refreshed the same way but are no longer served directly. The endpoint sits behind the normal dashboard auth guard, and responses carry nosniff plus a Content-Security-Policy: sandbox header so an SVG or HTML asset opened as a top-level document cannot run script.

MCP callers are local and already run as your user, so the tool does not restrict which paths may be embedded. An agent that can call it can read those files directly anyway.

Installed skill

MCP interaction guidance lives in:

.opencode/skills/ocman-factory/SKILL.md
.opencode/skills/ocman-routines/SKILL.md
.opencode/skills/ocman-sessions/SKILL.md
.opencode/skills/ocman-inbox/SKILL.md
.opencode/skills/ocman-artifacts/SKILL.md

At startup, ocman extracts and links the skill into OpenCode’s global skill directory. Restart OpenCode after installing or upgrading ocman so every conversation can discover it.