docs/internal/bridgemcp.md

Native bridges and shared MCP

Shared proxy

internal/bridgemcp owns the authenticated IPv4 loopback HTTP MCP server extracted from Muse. 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 HTTP 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 HTTP connections and callbacks. A successful write is not proof of remote consumption.

Adapter options preserve Muse's defaults:

  • Describe, DiagnosticLabel, Trace, Failure and BodyLimitMessage keep Muse-specific reminders and safe diagnostics outside the shared implementation.
  • NonReadOnlyTools adds readOnlyHint:false for Claude's serialized handlers.
  • AllowCatalogWhilePending allows catalog replacement without changing the held call's original identity. Muse continues to reject replacement while held.
  • NotifyToolListChanges enables the standard authenticated GET/SSE MCP stream, advertises listChanged, and sends notifications/tools/list_changed. AwaitCatalog waits for the native client to fetch the current revision.
  • MaxRequests defaults to Muse's 4,096 requests. A negative value removes the count ceiling, not replay detection or the 1,024-byte encoded ID limit.
  • Correlate consumes 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.

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 HTTP 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, normalizes argument JSON and checks history association only. It is not a signature or thinking validator. 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.

After a real process restart or a new leaf branch, the adapter requires the captured prefix to match, then uses --resume, --resume-session-at and --fork-session. Each restored writer gets an independent native fork. It never adopts a later unsaved native tail. A checkpoint ending in a tool request cannot restore the old HTTP exchange and is ineligible. If native initialization cannot restore a session before any new input was sent, the adapter may start a labeled readable-history handoff. It preserves ordinary reasoning in <previous_thoughts> and labels historical calls/results as records, not new execution requests. 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

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.