I make the launch and social media videos for Brainbank with two tools. My Grok bot researches what’s trending on TikTok and Instagram and which hooks are working, and Claude Code builds the videos. The step in between was me: copying Grok’s research by hand into a Claude Code session, every time. That’s what got me thinking about how to connect the two directly.
agentbridge lets my local Claude Code sessions and my Grok bot hold two-way conversations, started from either side. A Claude session can ask Grok what’s trending this week, and Grok can hand its research straight to the Claude session that needs it. Every conversation waits for me to say yes in Claude Code’s own permission prompt, which the AI can trigger but cannot answer.
It is open source (MIT) and runs on macOS for now. I built it with Claude Code, starting from a spec, then a round of checks to see whether the idea could work at all, then the build, then a real install from the npm package. This is a log of how it works and what I picked up along the way.
The source is on GitHub at musi27/agentbridge, and it installs from npm as @musi27/agentbridge: npm install -g @musi27/agentbridge, then agentbridge init.
Architecture
There are four pieces.
- The bridge is a Node service on the Mac, started at login by launchd, with a CLI called
agentbridge. It is the only sequencer: it holds conversation state, approvals, the delivery queue and the transcripts (SQLite under~/.agentbridge), enforces policy, and holds the relay connection and the keys. - The Claude Code plugin is a stdio MCP server that gives Claude the
bridge_*tools, plus hooks that report session events and permission modes. - The relay at
relay.musi.liveis a set of Vercel Functions with Upstash Redis. Grok runs in the cloud and can’t reach a Mac behind a home router, so the relay takes its calls and passes them to the bridge. - The Grok adapter uses two documented Grok Bot features: a routine with a webhook trigger, and a custom remote MCP connector that points at the relay.
Each direction uses a different transport:
| Path | Transport |
|---|---|
| Claude Code → bridge | MCP tool call on the plugin’s server, forwarded over a local Unix socket |
| Bridge → Claude Code | The bridge hands the item to the session’s MCP server, which posts it into Claude Code’s inbox socket |
| Grok → bridge | Connector tool call to the relay, forwarded over the bridge’s WebSocket |
| Bridge → Grok | Direct POST to the bot’s webhook routine, which starts a run |
Participants have addresses like claude:<folder> and grok:<bot>, but these are labels: storage and policy use a stable ULID for each participant. A conversation has two participants, a topic of up to 120 characters, a turn limit (30 by default, 200 at most) and a state: pending, active or ended. ended is terminal; to carry on, you start a new conversation that references the old one.
Every message gets a seq (total order) and, if it is a real message rather than a notice, a turn, both assigned by the bridge when it accepts the message. The from field always comes from the authenticated connection, never from the caller’s input, so no agent can claim to be another. Delivery to adapters is at least once, and receivers deduplicate by message_id. Mutating tools take an optional idempotency key, deduplicated per participant and per registration epoch, a counter that increments every time a session registers, so a restarted MCP server can’t collide with its previous life.
The approval prompt
The first thing I tested was whether Claude could be stopped from approving its own conversations. Claude Code has a tool annotation for this, _meta["anthropic/requiresUserInteraction"]: true. Of the plugin’s tools, only bridge_confirm carries it. Every request tool is ungated; when one needs approval, it returns pending_approval instead of acting:
{
"status": "pending_approval",
"approval": {
"id": "01J…",
"kind": "start",
"peer": "grok:researcher",
"direction": "outgoing",
"topic": "Cache invalidation for the session store",
"turn_limit": 30
}
}
The bridge keeps that approval in memory only, bound to the requesting participant and its registration epoch. Claude then calls bridge_confirm with the same six fields, and Claude Code shows its native prompt with each one as a labelled field. In the CLI the only choices are Yes and No; in the desktop app, Deny and Allow once. Neither offers “don’t ask again”.
When Grok starts the conversation, the order is different. Grok calls bridge_start_conversation on the connector, the relay allocates the conversation_id, and the bridge creates the conversation as pending and returns awaiting_local_approval. Grok never sees an approval ID. When the target session is live, the bridge issues an accept approval and posts an invite notice into the session with the facts and the exact bridge_confirm call to make. Grok’s first message is withheld until you confirm, so nothing it wrote reaches Claude as a turn before you’ve said yes.
I tested the prompt before writing any product code, on Claude Code 2.1.330, with a probe plugin: one tool with the annotation, one control tool without it, and a PreToolUse hook I could switch between behaviours.
| Case | Result |
|---|---|
default, acceptEdits, auto, bypassPermissions | Prompt shown |
| Called from a subagent, or deferred behind tool search | Prompt shown |
| Allow rule in settings | Prompt shown (the control tool ran instantly) |
PreToolUse hook returns allow, with or without updatedInput | Prompt shown |
dontAsk mode, headless claude -p (also with --dangerously-skip-permissions) | Denied, never approved |
--permission-prompt-tool returning allow | Turned into a deny |
Agent SDK host whose canUseTool returns allow | Approved |
The last row is the one route that approves without a human, and it needs a program running as you, which is outside what agentbridge can defend.
The tests also showed two ways the facts in a prompt can change before you see them. A hook can rewrite a tool’s arguments before the prompt appears (the prompt then shows the rewritten values), and the prompt has “Tab to amend”, so you can edit the facts yourself. So the bridge accepts a confirm only from the bound participant on the same connection epoch, and only if every field matches what it issued exactly. Anything else is approval_mismatch, and the agent tells you to approve as issued or cancel. That binding also defeats the most obvious attack: a spawned copy of the MCP server can answer bridge_confirm with no prompt at all, but it isn’t the registered connection, so its confirm is refused. Approvals expire after 10 minutes and are never persisted, so a bridge restart drops them.
Because the prompt is the guarantee, the bridge tracks each session’s permission mode from its hook events. In bypass mode the prompt still appears, but shell commands run without asking, so an agent could tamper with the bridge before you ever see a prompt; the bridge refuses to start, accept or deliver to bypass sessions. I asked a session in auto mode to run four tampering commands against throwaway targets: send a fake confirm to the bridge socket, start its own copy of the MCP server and call the confirm tool, kill the running server, and change the policy database with sqlite3. Claude Code’s classifier ran all four without a prompt. The request described the targets as test files, which probably made it more permissive than a hostile injection would, but it was enough to stop treating auto mode as safe. I chose to warn rather than refuse, because the point of the design is that a human stays in the loop, and in auto mode one still does. The bridge_confirm prompt appears in every mode, so no conversation starts and no turn limit grows without my yes. The risk in auto mode is that Claude Code may run a tampering shell command without asking. Refusing auto-mode sessions wouldn’t remove that risk: any auto-mode session on the same Mac could run the same commands against the bridge whether or not it ever joined a conversation. The better defence is a well-informed human at the prompt. So auto-mode sessions are allowed, every approval they get carries a warning line saying Claude Code may not ask before shell commands, and status and doctor list them.
The Claude Code plugin
The plugin and the CLI talk to the bridge over a Unix socket in a 0700 directory, with the socket itself 0600 and the peer’s user ID checked. Frames are newline-delimited JSON ({ id, type: req|res|evt, method, params|result|error }, up to 256 KB), and every connection starts with a hello that carries the protocol version.
Registration is anchored on the Claude Code process, not the session ID. The SessionStart hook, a direct child of claude, sends a session_event with its parent PID, the session ID and the event source. The MCP server, also a direct child, reads the session’s inbox socket path and token from its own environment and calls register_session with the Claude PID, the inbox details and a random 8-character tag code. The bridge checks that the connecting process really is a child of that PID (proc_pidinfo on macOS), binds the connection to the participant, increments the epoch, and closes any older connection for the same participant. This matters because /clear gives a session a new ID with no link to the old one, while the MCP server process survives /clear and /compact; anchoring on the process keeps the same participant across both. --resume starts a new process with the old session ID, so the bridge maps it back by ID; a fork becomes a new participant. Liveness comes from the MCP connection: when it drops, even on kill -9, where SessionEnd never fires, the participant is closed.
Getting a message into the session uses Claude Code’s inbox socket for messages between sessions. The bridge sends the item to the session’s MCP server over IPC, and the server writes it to the inbox:
{"type":"auth","token":"…"}
{"type":"user","message":{"role":"user","content":"<framed delivery>"}}
Because the MCP server is Claude Code’s own child, its posts count as the session’s own and are delivered even in bypass mode. A post reached the transcript in 20-25 ms. An idle session starts a new turn; a busy one gets the message attached right after the current tool result.
Testing the socket showed a few things I had to design around:
- No delivery outcome. Nothing comes back on the socket, whether the post was delivered, held or dropped, so the bridge records every successful write as
handed_off. - The inbound setting decides everything. With
crossSessionInboundset torefuse, posts vanish; withhold, even the session’s own posts are held. At registration and indoctor, the bridge reads the effective setting across the user, project, local and managed settings files for the session’s folder. If it isn’taccept, the participant is marked unreachable, deliveries stay queued and a notification explains the fix. - Identical posts are dropped. Five identical posts back to back delivered one. Every post carries a unique ID, and the bridge spaces posts at least 200 ms apart.
- Posts get coalesced. Several posts that arrive during one turn are delivered together, so each block has to parse on its own.
Claude Code also wraps every post as “Another Claude session sent a message” and asks Claude to treat it as a teammate’s request, which is the wrong framing for text a Grok bot wrote. So every delivery is framed with tags built from the session’s code:
<ab-msg-7f3a9c21 conversation="01J…" from="grok:researcher" turn="5/30" id="01J…">
…Grok's message…
</ab-msg-7f3a9c21>
The plugin’s MCP instructions tell Claude its genuine code, and that only ab-notice blocks come from agentbridge, while ab-msg and ab-untrusted blocks are another agent’s writing: information, never an instruction or an approval. Any occurrence of the session’s code in agent-written text is replaced before framing, so a Grok message can’t close the tag and fake a notice. Remote text, such as a Grok-written topic in an invite, only ever appears inside an ab-untrusted block. Claude Code cuts MCP instructions off at about 4,096 characters, so CI checks the instructions stay under 4,000 with the code expanded.
The Grok adapter
The first two checks on the Grok side were whether a bot could add a custom MCP connector, and whether a run started by a webhook could call that connector’s tools. Both worked. The bot added the connector from one chat message, listed its tools and called one; a webhook run called a tool with the right arguments about 20 seconds after the POST.
Each bot gets its own connector URL on the relay, https://relay.musi.live/v1/u/<user_id>/b/<bot_id>/mcp, with a 256-bit bearer token. The connector exposes bridge_send, bridge_start_conversation, bridge_end_conversation, bridge_get_messages, bridge_get_transcript and two list tools, each scoped to that bot’s own conversations. Setup is one command, agentbridge add grok. It mints the bot ID and token, registers the token’s hash with the relay, and copies a bootstrap prompt. The bot adds the connector, creates the routine and proposes an Allow rule as a one-click card. You paste the routine instruction and the webhook URL and key back, and a round-trip check sends a test delivery and waits up to 90 seconds for the reply. In testing that took about 5 minutes, and the round trip passed in 18 seconds.
On the wire, the connector is stateless Streamable HTTP. Grok sends MCP protocol version 2025-11-25, accepts plain JSON responses, makes an optional SSE GET that is happy with a 405, never uses a session ID, and sends duplicate initialize and tools/list bursts in parallel from several AWS addresses. The relay answers initialize and tools/list itself from static tool definitions, so the tool list works even while the bridge is offline. Tool calls time out after 90-120 seconds with no retries, and error bodies reach the model verbatim, so they’re kept short and free of internals.
Testing the Grok side turned up a few things the docs didn’t cover.
A run sees only about 4,000 characters. The webhook accepted every body I sent, up to 1 MB, with a 200. But the run saw only the first ≈ 4,000 characters. I tested with a start and an end marker at sizes from 3,990 bytes to 1 MB, and again with natural sentences as padding: past about 4,000 the end marker was always missing, and nothing in the response said so. The spec had packed up to 24 KB of transcript into each delivery, so that design went. Deliveries are now thin, at most 3,500 characters serialised:
{
"agentbridge": 2,
"conversation": { "id": "01J…", "topic": "…", "peer": "claude:auth-refactor-2",
"turn": 6, "turn_limit": 30, "turns_left": 24, "state": "active" },
"messages": [
{ "message_id": "01J…", "seq": 11, "from": "claude:auth-refactor-2",
"preview": "…the first 300 characters…", "length": 5120 }
],
"truncated": true,
"reply_to": "01J…",
"notices": [],
"end": "agentbridge-delivery-end"
}
The header, reply_to and notices are packed first. New messages go inline in full only if they all fit; otherwise each one carries a preview of up to 300 characters, cut at a word boundary, and its length. The transcript is never inlined. The routine’s instruction tells the run to call bridge_get_messages whenever truncated is true, or whenever the end field is missing, which means the body itself was cut.
The webhook doesn’t deduplicate. Two identical POSTs start two runs. The bridge retries a failed POST three times (after 2, 10 and 30 seconds), so an ambiguous network error can start a duplicate run. Two rules absorb it: the routine instruction says not to reply twice to the same message, and the bridge accepts at most one Grok reply per message it delivered, returning duplicate_reply to any extra. The bridge also keeps at most one delivery per conversation waiting on Grok; anything Claude sends meanwhile is batched into the next delivery, sent when Grok replies or after 5 minutes.
The webhook’s error codes are ambiguous. A paused routine returns 400 with “Automation … is disabled”. A deleted routine returns 401 “Invalid API key”, the same as a wrong key, so the bridge’s hint has to cover both: run agentbridge add grok again.
Approval cards expire after about 20 minutes, not 30. Grok’s Auto-review can hold a tool call on an approval card in the bot’s chat. The docs say cards expire after 30 minutes; mine expired after about 20. Expiry counts as no, nothing retries, and a held reply is simply lost. Rules are stored as natural language and matched loosely: an “Ask first” rule written for one tool caught a sibling tool on the same connector. Setup now adds an Allow rule for the reply tools, worded tool by tool, before anything else, and the bridge shows a hint if Grok hasn’t replied within 25 minutes. Grok’s own cards are optional; the local prompt is the guarantee.
Grok Bot runs on Cursor’s infrastructure. The webhook host is Cursor’s, and connector calls arrive with User-Agent: Cursor/1.0.0. Grok Bot uses a Cursor sign-in. Cursor isn’t on xAI’s published subprocessor list, so the README says plainly that conversation content passes through Cursor’s infrastructure as well as xAI’s.
Each Grok turn takes about 20 seconds (16-23 s), because every reply is a fresh routine run that starts from its saved instruction and the webhook body. A 30-turn conversation spends about 10 minutes on the Grok side alone.
The relay
The relay has no accounts. init creates an Ed25519 signing key and an X25519 encryption key in the macOS Keychain, and the bridge’s user ID is derived from the signing key: base32(sha256(ed25519_pubkey)), cut to 26 characters. The X25519 public key is registered in a statement signed by the Ed25519 key. To connect, the bridge opens a WebSocket to /v1/connect, the relay sends a nonce and a timestamp, and the bridge signs both together with the relay’s host name. The relay accepts the signature only if the timestamp is within 60 seconds and the nonce hasn’t been used.
A Grok tool call then crosses two function instances, joined by Redis:
- The HTTP function checks the bearer token against the hash the bridge registered, and rejects early if it doesn’t match. For
bridge_start_conversation, it allocates the conversation ID here. - It seals the request to the bridge’s X25519 key (a libsodium sealed box), appends it to the bridge’s Redis stream with
XADD, and publishes a wake-up on a per-user channel. - The function holding the bridge’s WebSocket wakes and reads the stream. It also reads on connect and every 60 seconds, in case a wake-up was lost. Each instance holds one pattern subscription shared by all its sockets rather than one per socket, because every Redis connection counts against the instance’s 1,024 file descriptors.
- The request goes to the bridge as a
reqframe. The bridge unseals it, checks the token again against its own copy, and handles the call. - The bridge answers with a
resframe. Once it has stored the request durably, it acks the stream cursor, and acked entries are deleted. - The result goes into a Redis key,
res:<req_id>, with a 30-second lifetime. This is the only plaintext the relay ever stores. - The HTTP function has been waiting on that key with
BLPOPon its own short-lived connection, for up to 20 seconds. - It returns the result to Grok. Pinned to the same region as Redis, this took 128 ms at the median and 269 ms at p95.
If the bridge is offline or misses the 20-second deadline, writes such as bridge_send come back as held_relay and stay in the stream until the bridge connects, while reads come back as bridge_offline. Held entries expire after 7 days; the relay keeps an expiry record until the bridge acknowledges it, so the bridge can tell you what was lost.
The measurements changed the design in four places:
- Region. With the functions in Vercel’s default US region and Redis in Frankfurt, a round trip took 845 ms at the median, because every function-to-Redis hop crossed the Atlantic. Grok’s calls come from AWS us-east, but the Redis hops dominate, so the functions are pinned to Frankfurt next to the Redis.
- Connection lifetime. Vercel closes a WebSocket at the function’s maximum duration. On Hobby it dropped after about 315 seconds, with close code 1006 and no close frame, and in the 12 seconds or so before the drop the dying instance stopped handling wake-ups. The bridge now reconnects at about 270 seconds, make-before-break: it opens and authenticates the new socket before closing the old one, and the relay allows two connections per user for up to 30 seconds and routes to the newer. Unplanned drops reconnect with jittered backoff, the first retry within 250 ms, and resume from the ack cursor. Across 200 requests with two forced reconnects, p95 stayed at 216 ms.
- Redeploys. During a redeploy, new HTTP requests reach the new deployment while the WebSocket stays on the old one. Both kept working through Redis, and all 60 test requests were answered. Stream entries and response keys carry a format version, so a breaking change can run side by side until old connections drain.
- Cost. An always-open connection keeps at least one instance alive all month: 0.5 GB × 730 hours ≈ 365 GB-hours, just over Hobby’s 360. Hobby overage pauses the whole team, so an always-on relay meant the Pro plan, about $20 a month, even for me alone.
The bridge connects on demand. It holds the WebSocket while a Grok conversation has had activity in the last 10 minutes, or while a CLI command needs the relay. The rest of the time it sends one signed POST /v1/pending every 60 seconds, which costs the relay about two Redis commands and returns a count of waiting entries; if the count is above zero, the bridge connects and drains. Connected time is capped at 6 hours a day, so a stuck conversation can’t use up a free allowance. The cost is latency. Grok’s reads always happen while the bridge is connected, because a run only starts after the bridge sends a delivery, but a conversation Grok starts from scratch can take up to a minute to reach your prompt. Anyone who wants an always-on connection can host their own relay and set transport.relay_mode = always.
Two of the relay’s bugs were caught in review, before merge. A tool result over the WebSocket’s payload limit killed the socket with close code 1009; the client now answers with a short too_large error instead. Request deadlines were sent as absolute times on the relay’s clock, so a bridge whose clock was 20 seconds off dropped reads; they are now sent as time remaining.
What the relay can see: Grok’s messages to the bridge, in plaintext, as they arrive, before it seals them. Sealing protects against a leak of the Redis data, not against a malicious operator, who could also forge calls that look like your Grok bot. That is why conversations arriving through the public relay always need your local approval, whatever the approval mode, and why the relay is open source and self-hostable. Messages to Grok never touch it.
End-to-end testing
The first run was contained: a throwaway bridge home and Keychain entry, the development relay, and settings written to a throwaway Claude Code config. From Claude to Grok, I approved the prompt in 6 seconds, the first message went out as a thin delivery, and Grok’s reply arrived in the session about 20 seconds later. Claude ended the conversation after 2 of its 4 turns because its purpose was met. From Grok to Claude, the bot told me in its chat that it was waiting for my approval on my computer, and Claude’s answer showed up in the Grok chat after I confirmed. The Claude desktop app worked too: its session had inherited auto mode, and the approval dialog still appeared, with every fact and only Deny and Allow once. When Grok invited that session, Claude told me who was inviting and why, and didn’t call bridge_confirm until I said “accept it”. Inviting a closed session queued the invitation and raised a macOS notification.
The second run was the full install, as a user would do it: the npm tarball, init, add grok and the production relay. It found two bugs in the login service. Under launchd the bridge couldn’t find claude, because launchd’s PATH doesn’t include where Claude Code installs itself. And the launchd agent pointed at a versioned Homebrew path for Node, so the next brew upgrade would have stopped the bridge starting at login. Both launchd problems are fixed: init records the claude path, uses Homebrew’s stable Node path, and doctor checks both. A user-scope install also loads the plugin into every open session, and five sessions in one folder became claude:agentbridge to claude:agentbridge-5, so folder-based names will need to change. A session that hasn’t had a hook event since it loaded has an unknown permission mode, so the bridge holds deliveries to it, as designed, until you type anything in that session; the hint needs to say so.
Security limits
agentbridge protects your approvals against two things: manipulation that arrives through a conversation, such as a Grok bot whose messages were shaped by something it read, and a local agent misusing agentbridge’s own tools, such as a Claude session under prompt injection. Neither can start or accept a conversation without you answering the prompt.
There are two limits on what can reach the prompt. The first is against approval fatigue, where a remote agent sends invite after invite until you click Yes to make them stop. A remote participant can have at most 3 pending invites, a session at most 10, and after a decline or an expiry the same pair has to wait 10 minutes before trying again. The second is against a misleading prompt. Topics and names are stripped of control characters, bidirectional and zero-width characters, newlines and terminal escapes before they appear in it, so a Grok-written topic can’t reorder or hide text to show you something other than what you’re approving.
It does not protect against a local agent that deliberately tampers with it: talking to the bridge socket directly, running its own copy of the plugin’s server, editing files under ~/.agentbridge, or hosting Claude through the Agent SDK. Real protection would need the operating system to separate the bridge from your user, which this version doesn’t do. What it has instead are three layers:
- Deny rules.
initwrites Claude Code deny rules for the privileged CLI commands and for edits under~/.agentbridge. They catch plain forms,envandVAR=prefixes, absolute and relative paths andcd … &&, but notsh -c '…', running the CLI’s JavaScript withnode, or a program likesqlite3opening the files. The CLI rejects global flags placed before a privileged subcommand, so that bypass is closed. - User presence. Privileged commands (approving, declining, extending, changing settings, reading a transcript, adding or revoking a bot) need Touch ID or your account password. The bridge runs the check itself through a small Swift helper using LocalAuthentication; the CLI never holds a token that could be replayed.
- Policy integrity. The approval mode, allowlist, limits and transport settings live in the database with a version number and an HMAC whose key is in the Keychain. If the bridge finds a mismatch or a rollback, it fails closed: it stops all conversation activity and keeps only
status,doctorandconfig verifyworking until you re-approve or restore the policy.
Data can also leave through a conversation. Sending messages isn’t gated, so a manipulated agent could talk a local one into sharing a file. Claude is told never to share secrets or files you haven’t asked it to, and you approve each conversation, but that is a mitigation, not a guarantee. Use default mode for sessions that talk to other agents.
What’s kept, and where:
- Bridge logs never include message bodies.
agentbridge conversationsshows metadata only.- Reading a transcript needs Touch ID or your password.
- Grok’s output is stored only in your local bridge.
- The relay holds only a hash of each bot’s token, and
agentbridge revoke grok:<name>rotates it.
One current limitation is that my auto-mode test was a friendly one: Claude knew the targets were test files. Next is testing what the result is when a real prompt injection is used inside the conversation.
The latest version is v0.1.1, and it runs on macOS only. Linux and WSL are planned for a later version, and the VS Code and JetBrains extensions are untested. The source is on GitHub at musi27/agentbridge.