docs/internal/bridgemcp.md
Native bridges and shared MCP
Shared proxy
internal/bridgemcp owns the authenticated Unix MCP endpoint shared by Muse and Claude. It never executes tools. Exact
hashed registration names, collision checks, canonical request-ID replay
protection, encoded limits, held responses and synchronized shutdown live here.
Calls publishes one held request at a time. Release returns the finalized
host text and error status with Muse's unchanged text encoding. ReleaseContent
uses the same transition for ordered standard MCP text, inline images and embedded
PDF blob resources. It validates and copies the content before asynchronous framed
delivery. The resource URI is identity metadata, never a path to open or URL to
fetch. Foreign, stale and duplicate releases fail.
Retirement unblocks handlers without inventing a result. Close joins Unix
connections and callbacks. A successful write is not proof of remote consumption.
One held MCP handler is not a one-call-per-model-response restriction. The
adapter owns the complete model call list independently of MCP arrival. Claude
yields that full list after message_stop and the first held handler, then
requires all finalized host results on the immediate next provider request. It
delivers them by native ID through successive serialized handlers. The host
executes tools sequentially unless a tool explicitly opts into parallelism; it
does not invoke the model between individual results from one batch.
Muse joins MCP requests by their _meta.callId, separately from JSON-RPC IDs.
Its required native interface, verified on Muse 1.4.20-R8619.1, includes the
experimental MSP turn/toolBatchSubmitted notification. Multi-call model support
itself is not experimental. Startup requires the experimentalApi acknowledgment;
its absence fails before session construction. Missing MCP call identity retires
the session before host admission. Neither failure triggers a singleton fallback
or replay. The catalog marks every host tool readOnlyHint:false, retaining
serial native handlers and the shared proxy's overlap rejection. An
installed-native loopback check covers the production backend with two
equal-argument calls and both finalized results on the next native request,
without login or online inference. The private project entry took precedence
over a same-name global endpoint on this version, but unrelated inherited MCP
servers can still start. A tool namespace filter is not configuration exclusion.
See the
Muse command.
Adapter options preserve Muse's defaults:
Describe,DiagnosticLabel,Trace,Failurekeep Muse-specific reminders and safe diagnostics outside the shared implementation.NonReadOnlyToolsaddsreadOnlyHint:falsefor serialized native handlers.AllowCatalogWhilePendingallows catalog replacement without changing the held call's original identity. Muse continues to reject replacement while held.NotifyToolListChangesadvertiseslistChangedand sends standardnotifications/tools/list_changedframes on the active stream, including while a tool result is held.AwaitCatalogwaits for the current revision.MaxRequestsdefaults to Muse's 4,096 requests. A negative value removes the count ceiling, not replay detection or the 1,024-byte encoded ID limit.ResetReplayOnReconnectdefaults to false, preserving process-wide replay tombstones. Claude opts into a fresh RPC-ID namespace after a clean reconnect because its native client restarts IDs. Muse retains its tombstones.SocketPolicyselectsauto,abstractorfilesystem;SocketRootcan select a private filesystem root. Caller root aliases are resolved and checked.Correlateconsumes an adapter-owned native ID before exact-name admission, including recoverable unavailable-tool rejections. Missing or mismatched correlation retires the proxy. Correlation never authorizes dispatch.CorrelateMetadatainstead consumes the native request's_metaobject. Muse validates itscallId; Claude keeps its pre-tool callback. The options are mutually exclusive and run after authentication, replay and overlap checks.RejectUnavailablereports an exact-name rejection with no host dispatch. Muse uses this proof to retire the corresponding native call; callback errors retire the proxy instead of returning recoverable selection guidance.
Authenticated stdio relay
Both native apps launch the absolute bridge executable with --mcp-relay ADDRESS.
This mode only authenticates and forwards bounded newline-delimited MCP JSON-RPC
frames between stdio and AF_UNIX. It does not launch a native app, load native
credentials or execute tools. Neither production bridge opens a TCP MCP listener.
There is no HTTP transport inside the Unix stream.
Frames over 32 MiB, including their newline, close the relay without dispatch;
there is no request-local HTTP 413 or replacement wire error. An idle owner can
accept a new relay; outstanding tool work retires the owner without replay.
Encoded tool-result JSON is limited to 32 MiB minus 8,192 bytes, reserving space
for the maximum RPC ID, its JSON escaping, the envelope and newline. Limit
diagnostics report the exact encoded result bytes and this result-only ceiling.
Each owner draws an independent mcp_<12hex> instance/address and a
check_<32hex> credential. Native configuration explicitly forwards
EZ_AGENT_MCP_CHECK through its supported child env expansion. Only the
variable reference, never its value, appears in Claude's private configuration file
or Muse's private project .mcp.json. The check is absent from argv, logs and
model content. The internal hello is exactly {"check":"check_<32hex>"}\n and
the acknowledgment is {"ok":true}\n, before any native MCP bytes. This is not
a change to native initialize or EzAgent provider JSONL. Authentication uses a
constant-time check, a 256-byte hello bound and a two-second deadline. Linux,
macOS and FreeBSD also check the effective peer UID before quota admission.
At most eight connections, including unauthenticated handshakes, are owned at
once. At capacity, admission closes and joins the oldest unauthenticated peer
before accepting its replacement. Authenticated active or waiting peers are
never evicted. This permits startup after a fixed batch of incomplete hellos;
it does not prevent generic IPC denial by a continuously flooding same-UID process.
There is one authenticated active relay. A competing valid connection can wait only until its authentication deadline for that relay to leave; it cannot replace a healthy one. Invalid clients neither consume correlation nor retire the owner. Every new stream must initialize. Reinitializing the active stream is rejected without clearing replay tombstones. A clean idle disconnect allows a new relay while preserving replay tombstones by default. Claude explicitly resets the transport RPC-ID namespace for native counters that restart at zero. Losing a held response, uncertain result delivery or cancellation of the held RPC retires the owner. No tool work is replayed. Unrelated cancellation IDs are ignored. The native tool IDs, exact offered snapshot and host execution controls remain authoritative after authentication, including on remote provider hosts.
Both commands accept --mcp-socket auto|abstract|filesystem, before or after
--stdio. auto uses abstract Unix on Linux and filesystem Unix elsewhere.
Explicit abstract fails on unsupported platforms. Abstract mode creates no
files. Filesystem mode creates an exclusive private mcp_<12hex> directory and
mode-0600 socket, below the adapter scratch root or process temporary root.
The daemon's outer provider scratch is the crash-cleanup backstop. Startup
failure and normal close remove only the owned socket/directory identities;
foreign replacements are left intact. No stale-socket scanner runs. Overlong
filesystem addresses fail rather than falling back to TCP or another policy.
Production handlers serialize writes with notifications and keep reading while
a tool result is held, so initialization, catalog refresh and cancellation are
not blocked by a held call. Close closes unauthenticated and active connections
and joins all owned handlers. Admission/replay regressions also retain a small
HTTP harness in _test.go; it calls the same dispatcher and is not shipped.
RunRelay owns its input/output until return and joins both forwarding workers.
Inherited stdio descriptors are duplicated and made nonblocking before forwarding
so closing the owned files interrupts pipe/socket I/O, including an idle stdin
on socket loss or SIGTERM. Other supplied streams must unblock on Close.
Snapshot copies diagnostic state. FailSnapshot freezes evidence and retirement
under the admission lock. Callbacks are synchronous and must not reenter the
proxy. Do not log arbitrary tool names or arguments from snapshots.
internal/musebridge/mcp_shim.go is the
compatibility wrapper. Muse retains its descriptions, diagnostics, replay ceiling,
catalog policy and native lifecycle. Common proxy tests live in bridgemcp.
Both native bridges also reuse Linux process-group cleanup in
internal/bridgeprocess, which pins the leader
through descendant cleanup before reaping it.
Claude adapter
internal/claudebridge implements the
Claude command. launch.go maps supported
native controls. runtime.go owns structured I/O, hook/control correlation,
bounded native queues, interrupt/drain and exact-child cleanup. adapter.go
streams output, matches completed messages to MCP calls, releases finalized
results and owns the warm native conversation. context.go matches canonical
history and selects a native checkpoint or readable-history recovery.
The official CLI can emit several completed assistant records under one API
message ID. They are fragments of one assistant message, not separately billable
responses. The adapter preserves all actual records, including unknown fields,
signed thinking and redacted blocks, in their original order. It waits for API
message_stop before yielding tools, and checks completed text against streamed
text. It does not inspect or verify opaque thinking or signatures.
Usage counters progress under that shared API ID. The adapter takes each counter's maximum over API start, completed records and message-delta updates, then assigns those counts once to the finalized assistant message. Counters reset for the next API message. Input includes uncached, cache-read and cache-write portions; cache fields remain subset details. Native result-level totals are not added again. This follows OpenCode's per-ID progression rather than charging only the first fragment or summing repeated snapshots. The Haiku integration observes completed-record counts below the final API output count.
Every closed API message gets its own private capture and usage. A private-only
message can close without invented readable text. If another API message starts,
the earlier message closes with assistant_boundary; a tool yield or final
result closes it with done. The daemon atomically saves that turn and its
capture using the existing native-thinking transaction. An unfinished successor
cannot overwrite an earlier committed capture.
Claude's owned PreToolUse hook supplies the exact tool-use ID and registration
name. The shared proxy consumes that pair for the next MCP call. The adapter
checks it against completed tool blocks and arguments before dispatch. It waits
for the first held handler, not all serialized handlers. That wait stays in the
normal event loop so native EOF and failure results terminate it promptly, without
host dispatch. The next finalized EzAgent request supplies every result for the
yielded batch and may also contain user steers. The adapter matches results by
exact pending ID independently of those steers. It queues the new user text in
source order through Claude's structured priority: "next" input before releasing
held responses, following OpenCode's continuation path. Each result still travels
once through its original MCP exchange. Equal arguments with separate native IDs
remain separate calls.
For a changed catalog, the proxy publishes a list-change notification and the adapter waits for rediscovery. While a batch is pending, replacement occurs when the final old handler is held, before releasing its result. This keeps later serialized handlers associated with their original calls. Additions, removals and schema updates do not restart a healthy conversation. Focused real Haiku coverage exercises all three changes while an old result is held.
Continuation and private storage
The existing loaded-leaf owner retains the bridge and native process through idle. The next request confirms generated output against saved content and source-turn associations. It sends only new user input or releases the exact held result, never a second copy of the saved assistant answer.
The daemon's external owner also records the effective FiletypeGate decision for each media MIME type in its installed history. These are booleans, not a second history or attachment store. A policy change for existing media retires that owner before a new completion reaches the bridge. The replacement uses the normal canonical-history recovery, with disabled-media warnings or native blocks from the new gate. This also covers a finalized result whose old native MCP handler was still held. Historical tools are not executed again. New MIME types and equivalent gate settings do not invalidate the existing prefix; the adapter's strict equality check is unchanged.
claude_code.thinking.v1 uses the existing per-turn proprietary row. Its payload
is a one-element array containing version 1, ordered actual native records, and
a SHA-256 prefix_digest over normalized canonical messages through that turn.
The digest excludes runtime source/output IDs and historical provider provenance.
It normalizes argument JSON and checks history association only; it does not
validate signatures or thinking.
Native transcript UUIDs and session IDs remain inside the actual records.
No checkpoint index, transcript mirror or hidden turn metadata exists.
A brand-new conversation uses plain ordered user input and emits no recovery notice. Static system/developer text remains in the appended system prompt. Only existing history receives readable-history framing.
On cold recovery the adapter seeds a private transcript and starts an independent
native fork. A matching capture supplies the actual native assistant body. If it
cannot be replayed, the adapter restores public text and finalized tool history
without substituting readable Anthropic thinking. It includes
<previous_thoughts> for reasoning not identified as Anthropic-origin, and never
dispatches historical calls. Native rows remain saved for other eligible branches.
No generation, accepted input or uncertain tool delivery is automatically replayed. Cancellation interrupts and drains to a result or five-second deadline, then closes and reaps the exact group, with a two-second close grace. The outer local/remote process owner allows eight seconds for this Claude cleanup. Completed native-only data does not change the public client/addon JSONL contract.
Setup and tests
The offline native-two-file daemon acceptance uses the existing fake Claude
native fixture with the production bridge, standard isolated daemon fixture and
shipped builtin buffer. It checks a single two-call response, serial reads of
two real files, both persisted finalized results on the immediate next provider
request and a final answer containing both file contents. It also covers one
read and cancellation while the batch is pending. The opt-in
test-native-two-file-live recipe uses the same wire checks with an exact native
model selection. See commands and evidence.
Install and sign into both native applications through their official apps first.
EzAgent reuses that login, never installs the apps, copies credentials or prompts
for an API key. Normal use stays in EzAgent. Exceptional reauthentication may
require the official app. Claude setup assumes claude on PATH and keeps manual
model entry because discovery is advisory and non-inference.
The native child uses private XDG roots and a temporary workspace, with one
intentional exception: state/claude links to the parent's effective native
application directory. The launcher preserves the original effective XDG state
root in EZ_AGENT_PROVIDER_STATE_HOME; direct launches use their effective XDG
root, falling back to $HOME/.local/state when needed. Root/application aliases
are followed. HOME retains the official login, and the linked native state is
shared with the official app, not isolated transcript storage. Native sessions
follow Claude Code's own cleanup defaults; the bridge
does not extend retention or create another retention store. It removes its
temporary workspace on close without scanning native history or purging an
unrelated project. Live fixtures stop owned children and use
claude purge only for their exact temporary projects.
Tests describe offline fixtures and opt-in Haiku checks. No native recordings or credential files are collected by those fixtures.
Claude attachments
internal/providermedia holds the canonical
Anthropic image/PDF block mapping shared with the direct Anthropic provider.
The bridge consumes the normal FiletypeGate projection. It shares syntax and
metadata validation, not another provider's ceilings. Claude image projection
uses the documented 10,000,000-byte base64-data maximum; direct Anthropic's
original acceptance behavior and Muse's own limits/projection are unchanged.
No Claude image-count or per-PDF byte ceiling is invented. Actual encoded
updates and native writes retain their existing transport bounds, without
measuring installed history as a new update. No additional media store or
file/URL resolver exists.
Claude input remains structured through fresh prompts, warm suffixes and queued user steers. Filename/MIME labels stay beside their native blocks. User steers have an explicit native human origin; Claude 2.1.322 otherwise drops PDF blocks when folding an unstamped queued command into an active turn. Recovery history has role labels and original finalized tool IDs before the associated real media. Checkpoint restoration does not resend media from the captured prefix.
Finalized tool images use MCP image content. For PDF results, the adapter binds
native document blocks to the correlated tool ID before releasing its MCP response.
The owned PostToolUse callback consumes that exact replacement once through
hookSpecificOutput.updatedMCPToolOutput. Foreign IDs/names and duplicate callbacks
fail. This is the supported OpenCode mapping, validated with real Haiku tool PDFs.
The replacement never travels as an unrelated user message. On Claude 2.1.322,
MCP error results do not call PostToolUse and do not expose image/PDF data to the
model. That path forwards the finalized typed result/error flag with an explicit
informational limitation notice, without storing an orphaned replacement or
replaying a tool. Canonical media remains available for readable recovery.
Same-name PDF resources include their part index for distinct identity. Limits
and supported formats are listed in the Claude command guide.