polyagent-mcp
MCP server that lets any agent or MCP host delegate to headless Codex, Grok, and Claude CodeCLIs, with Cursor available as an opt-in fallback. Use the fleet for implementation, planning,and project exploration without burning the caller's context on raw worker output.
Worker tools take optional model and effort overrides, return a session_id, and supportfollow_up. Difficulty levels select a distinct default model across the three activesubscriptions.
Tools
The server exposes ten tools:
| Tool | Purpose |
|---|---|
delegate |
Run a task with full read/edit/shell access in cwd. Required level: 1=GPT-5.6 Luna max (codex), 2=Grok 4.5 high (grok), 3=GPT-5.6 Sol xhigh (codex), 4=Grok 4.6 high (grok), 5=Opus max (claude). Optionally accepts an agent persona by name or inline {prompt}. |
fast_delegate |
Same full read/edit/shell access as delegate, but with no level to pick: it routes to whichever CLI is currently the fastest and healthy. Optionally accepts an agent persona. |
explore |
Read-only exploration on Codex with gpt-5.6-luna. question alone → broad fan-out search returning file:line refs; question+files → answer about those files; neither → general project map. breadth: "thorough" sweeps wider. Locates, does not review. |
read_slice |
Surgical read-only read: returns ONLY the code relevant to want (exact lines with file:line) from the given files — the full file never enters your context. Use instead of reading large files whole. |
run_filtered |
Run a shell command through Codex/Luna with full access and get back ONLY the lines relevant to want — semantic filtering of huge build/test/log output. |
web_lookup |
Web/docs lookup through Codex/Luna with real web search enabled and a read-only filesystem. |
generate_image |
Generate or edit an image through Codex's built-in image tool and save it inside cwd. |
fan_out |
Run the SAME prompt across N engines/tiers in parallel isolated sandboxes and get back ONLY a compact digest — mode: "race" (default) returns the first success, mode: "consensus" compares every output through one cheap arbiter. |
follow_up |
Continue a prior session by session_id. |
bridge_stats |
Report calls and chars returned to context per tool (needs POLYAGENT_LOG). |
Worker tools accept cwd, model, and effort where applicable. delegate requires a level(1-5); fast_delegate has none and picks the fastest healthy engine. Explicit model/effortvalues override the selected tier.
When an engine runs out of quota
A call that fails because the engine's plan quota is exhausted does not silently retry onanother engine — spending the next subscription is your decision. The call fails with an actionableerror naming the engines still available (installed, enabled, and capable of what that tool needs)and how to switch: engine:"<x>" on the four auxiliary tools, the lowest still-usable level:<n>on delegate. Tools that pick the engine themselves (fast_delegate, fan_out) and follow_up(pinned to the resumed session's engine) report the quota without suggesting a parameter, andgenerate_image reports it against the two engines that have an image tool at all (codex, grok). A transient rate limit is reported separately and asks you to wait, since switchingengines would not help. Anything the classifier does not recognize — an expired login, for one —propagates as the raw CLI failure instead of being guessed at.
Requirements
- Node ≥ 18
bubblewrap(bwrap) installed — required, not recommended: the sandbox is mandatory and theserver refuses to start without it (sudo apt install bubblewrap). OnlyPOLYAGENT_SANDBOX=offwaives it, as an explicit operator choice.- Codex installed and authenticated for read tools and levels 1/3; Grok for levels 2/4; Claude Codefor level 5.
- Optional Cursor fallback: install
cursor-agentand setPOLYAGENT_ENABLE_CURSOR=1.
Install
Installing via an AI agent? Point it at
INSTALL.md— an agent-facing,copy-paste guide that detects the host and registers the bridge in Claude Code, Cursor,Codex, Grok, or any generic MCP host.
git clone https://github.com/JaimeJunr/cursor-mcp-bridge.git
cd cursor-mcp-bridge
npm install
npm run build
Register in an MCP host
Claude Code:
claude mcp add polyagent -s user -- node /abs/path/to/cursor-mcp-bridge/dist/index.js
Any host — add to its mcp.json:
{
"mcpServers": {
"polyagent": {
"command": "node",
"args": ["/abs/path/to/cursor-mcp-bridge/dist/index.js"]
}
}
}
Permissions (Claude Code): claude mcp add registers the server but does not granttool permission — without an allowlist every bridge call prompts for approval. Afterregistering, add either "mcp__polyagent__*" (full; also auto-approves mutating toolsdelegate/fast_delegate/run_filtered/follow_up) or a read-only subset(explore/read_slice/web_lookup/bridge_stats) underpermissions.allow in settings.json. Full options and trade-offs:INSTALL.md §3. Cursor/Codex/other hostshave their own approval settings — consult the host.
Configuration (env)
| Var | Default | Meaning |
|---|---|---|
POLYAGENT_CURSOR_BIN |
cursor-agent |
Path to the optional Cursor CLI fallback. |
POLYAGENT_GROK_BIN |
grok |
Path to the Grok CLI. |
POLYAGENT_CODEX_BIN |
codex |
Path to the Codex CLI. |
POLYAGENT_CLAUDE_BIN |
claude |
Path to the Claude Code CLI. |
POLYAGENT_ENABLE_CURSOR |
(off) | Set to 1/true to allow Cursor fallback when a tier's preferred CLI is missing. Otherwise the call fails with the missing CLI named. |
POLYAGENT_MODEL |
composer-2.5-fast |
Default model for the optional Cursor path. |
POLYAGENT_EXPLORE_MODEL |
gpt-5.6-luna |
Codex model for explore, read_slice, run_filtered, and web_lookup when neither the call nor the tool-specific _MODEL sets one. |
POLYAGENT_<TOOL>_ENGINE |
codex |
Per-tool engine for the four auxiliary tools — <TOOL> is EXPLORE, READ_SLICE, RUN_FILTERED, or WEB_LOOKUP. The call's own engine parameter beats it. Refused when the engine lacks what the tool needs: read-only (explore/read_slice/web_lookup, which outside codex comes from the sandbox) or web search (web_lookup, codex only). |
POLYAGENT_<TOOL>_MODEL |
(see above) | Per-tool model, same four names. The call's model beats it. With a non-codex engine and no model set anywhere, the engine's own default model is used. |
POLYAGENT_AGENT_PATHS |
(off) | Additional :-separated roots for named agent personas, searched before project/home .claude/agents and ~/.claude/plugins. |
POLYAGENT_SANDBOX |
bwrap |
Isolates every engine in a bubblewrap sandbox with an empty $HOME, preventing global config, MCP servers, hooks, and skills from loading. Only auth, required engine state, and toolchains are bound in. Set off/0 to disable explicitly — with the sandbox off, the read-only tools (explore, read_slice, web_lookup) accept only the codex engine. A missing bwrap is a startup error, never a silent downgrade. |
POLYAGENT_FORCE |
(off) | If 1/true, force-enable non-interactive approval for Cursor and Claude runs. |
POLYAGENT_TIMEOUT_MS |
1800000 (30 min) |
Per-call safety-net timeout (not a work budget). Execution tools (delegate/fast_delegate) also get a prompt note so the worker returns partial results before being killed. |
POLYAGENT_LOG |
(off) | Path to a JSONL file; when set, every call logs {tool, outChars} for bridge_stats. |
POLYAGENT_HOOK_MODE |
redirect |
Hook behavior: off (no-op), nudge (non-blocking additionalContext only), or redirect (deny once + name bridge tool for WebSearch/WebFetch and whole-file large Read; fail-open on retry). Grep/Glob/Bash/Edit/Write stay nudge-only. |
POLYAGENT_HOOK_MIN_LINES |
300 |
Line threshold above which the optional hook (below) redirects/nudges whole-file Read toward read_slice. |
Breaking change: env var rename
Every CURSOR_BRIDGE_* variable was renamed to POLYAGENT_* (same suffix), and CURSOR_BINbecame POLYAGENT_CURSOR_BIN. This is a clean cut: the old names are no longer read at all —setting one has zero effect (no fallback, no warning). Update your host config (mcp.json /settings.json "env" blocks) and any shell profile before upgrading.
| Old (removed) | New |
|---|---|
CURSOR_BIN |
POLYAGENT_CURSOR_BIN |
CURSOR_BRIDGE_AGENT_PATHS |
POLYAGENT_AGENT_PATHS |
CURSOR_BRIDGE_GROK_BIN |
POLYAGENT_GROK_BIN |
CURSOR_BRIDGE_CODEX_BIN |
POLYAGENT_CODEX_BIN |
CURSOR_BRIDGE_CLAUDE_BIN |
POLYAGENT_CLAUDE_BIN |
CURSOR_BRIDGE_MODEL |
POLYAGENT_MODEL |
CURSOR_BRIDGE_EXPLORE_MODEL |
POLYAGENT_EXPLORE_MODEL |
CURSOR_BRIDGE_IMAGE_MODEL |
POLYAGENT_IMAGE_MODEL |
CURSOR_BRIDGE_FORCE |
POLYAGENT_FORCE |
CURSOR_BRIDGE_ENABLE_CURSOR |
POLYAGENT_ENABLE_CURSOR |
CURSOR_BRIDGE_TIMEOUT_MS |
POLYAGENT_TIMEOUT_MS |
CURSOR_BRIDGE_DEBUG |
POLYAGENT_DEBUG |
CURSOR_BRIDGE_SANDBOX |
POLYAGENT_SANDBOX |
CURSOR_BRIDGE_SANDBOX_EXTRA |
POLYAGENT_SANDBOX_EXTRA |
CURSOR_BRIDGE_LOG |
POLYAGENT_LOG |
CURSOR_BRIDGE_HOOK_MODE |
POLYAGENT_HOOK_MODE |
CURSOR_BRIDGE_HOOK_MIN_LINES |
POLYAGENT_HOOK_MIN_LINES |
"cursor" survives only where it names the actual Cursor engine (POLYAGENT_CURSOR_BIN,POLYAGENT_ENABLE_CURSOR).
Security:
delegate,fast_delegate, andrun_filteredhave full access and auto-approvetheir work.explore,read_slice, andweb_lookupuse Codex's read-only sandbox. Named agentsare resolved on the host, reject path traversal, and are injected without mounting agentdirectories.
Make the agent actually use it
Registering the tools is not enough. Two structural forces push the agent back tonative tools: (1) the host rule "prefer the dedicated file/search tools", and (2) MCPtools used to be deferred — the agent had to run a tool-search to load their schemas,so always-loaded Read/Grep/WebSearch won by default. The server now publishesstartup instructions (routing boundary) and marks the five core tools with_meta: { "anthropic/alwaysLoad": true } (Claude Code ≥2.1.121) so their schemas loadeagerly; secondary tools stay deferred. Four fixes, strongest first:
1. Call-time hook (recommended). A PreToolUse hook that steers the agent towardthe bridge at the moment it reaches for a native tool — text in a config file loses underpressure, a call-time reminder does not. This repo ships one athooks/prefer-polyagent.mjs: it runs on node(already required) and only fires where it pays. Default mode is redirect(POLYAGENT_HOOK_MODE=redirect): for the two safe-to-block cases it returnspermissionDecision: "deny" once and names the bridge tool; other cases stay non-blockingnudges. Wire it into your host's settings (Claude Code settings.json):
Breaking change (US-007): The hook file was renamed from
hooks/prefer-cursor-bridge.mjstohooks/prefer-polyagent.mjs. Update any hostsettings.jsonentry that points to the old path.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Read|Grep|Glob|WebSearch|WebFetch|Bash|Edit|Write|MultiEdit",
"hooks": [
{ "type": "command", "command": "node /abs/path/to/cursor-mcp-bridge/hooks/prefer-polyagent.mjs", "timeout": 5 }
]
}
]
}
}
What it emits, and when — each fires at most once per session (deduplicated in a tmpfile keyed by session_id), because a repeated fire is worse than none: the agent learnsto ignore it and every fire costs tokens. Dedup keys are saved before emitting soredirect is one-shot and fail-open (a second identical call is allowed through).
Readwhole-file (no offset/limit) overPOLYAGENT_HOOK_MIN_LINESlines →redirect (default) or nudge towardread_slice(once per file). Partial reads are left alone.WebSearch/WebFetch→ redirect (default) or nudge towardweb_lookup(once).Grep/Glob→ emits the one-time preload reminder to run theToolSearchfor anystill-deferred bridge tools (nudge only — never redirected). The dedup collapses them to asingle fire.Bashwhose command writes an artifact (git commit/push,git worktree add,gh pr create,gh issue create,bkt pr create) → suggests offloading that grunt-work todelegate(once, nudge only). Read-only Bash (status/diff/log/checkout) is left alone — theorchestrator needs that state, and a mechanical filter (e.g. rtk) already trims the noise.Edit/Write/MultiEdit→ once per session, reminds that a self-contained task(feature, bugfix, mechanical multi-file change, build fix) can go whole todelegate(prompt, level)— the selected worker edits with full access — instead of the orchestrator implementingit on expensive tokens. It never blocks the edit (nudge only); the once-per-session dedup meansthe orchestrator still edits inline freely (the nudge repositions execution, it doesn't police every edit).- The first qualifying fire of the session (whichever tool triggers it) also carriesthat preload reminder, so secondary schemas get loaded even in a Read-only or web-only session.
- Redirect deny reasons end with a fail-open suffix: if the bridge tool isn't loaded yet, runToolSearch first; if the native tool is genuinely needed, call it again and it will be allowed(critical under headless
-pso the agent never hard-stalls).
Set POLYAGENT_HOOK_MODE=nudge for the old non-blocking behavior, or off to disable.To reset the dedup and see the fires again, start a new session (or deletepolyagent-nudged-<session_id>.json from your OS temp dir — os.tmpdir(),e.g. /tmp on Linux, not necessarily $TMPDIR).
Preloading at session start (SessionStart)
The PreToolUse preload above only fires when the agent uses the Grep/Read tool. Butunder pressure agents often reach for Bash grep instead, which matches no PreToolUsematcher — so the preload reminder never arrives. Wire the same hook for SessionStart toclose that hole: the preload reminder then lands in context before the first tool decision,regardless of how the agent searches.
{
"hooks": {
"SessionStart": [
{ "hooks": [{ "type": "command", "command": "node /abs/path/to/cursor-mcp-bridge/hooks/prefer-polyagent.mjs", "timeout": 5 }] }
]
}
}
On SessionStart the hook emits the ToolSearch preload as additionalContext and pre-markspreload as seen in the session's dedup file, so the PreToolUse piggyback never repeats it.
Reaching subagents too (SubagentStart)
The nudges above only steer the main loop. Spawned subagents never see them,so wire the same hook for SubagentStart as well:
{
"hooks": {
"SubagentStart": [
{
"hooks": [
{ "type": "command", "command": "node /abs/path/to/cursor-mcp-bridge/hooks/prefer-polyagent.mjs" }
]
}
]
}
}
On SubagentStart the hook injects a compact polyagent preference into everyspawned subagent via additionalContext (subagentStartContext(agent_type)).When agent_type is Explore it appends an extra line: that Explore run was spawned on theorchestrator's expensive model (Explore inherits the session model, capped at Opus), so it shouldroute all reading through explore/read_slice (which run on Codex Luna) andkeep the expensive shell to orchestration only.
Coexisting with context-mode. The bridge and context-mode use separate channels(context-mode may still do its own thing; this hook only emits
additionalContext),so they coexist cleanly — noupdatedInputrace, no delay, no import ofcontext-mode's routing.
2. Preload any still-deferred tools. The five core tools are already alwaysLoad onClaude Code ≥2.1.121. For secondary tools (or older hosts), tell the agent to load schemasonce per session. Add to your CLAUDE.md/AGENTS.md:
At the start of any session involving code reading/exploration, run tool-search once for
`read_slice, explore, run_filtered, web_lookup` (and any secondary bridge tools you need) so
their schemas are loaded if the host still defers them.
3. Reconcile the conflict in CLAUDE.md. State the precedence explicitly:
The host rule "prefer dedicated file/search tools" applies to the EDIT path (Edit needs the
file content → native Read). For PURE reading/locating/web (no edit), polyagent takes
precedence over native Read/Grep/Glob/WebSearch/WebFetch. Read a large file whole with native
Read ONLY when you are about to edit it.
4. Delegate execution, not just exploration. The bridge is not only for reading — delegateruns implementation work with full read/edit/shell access, so the orchestrator shouldn't burn itsown tokens on self-contained tasks. State this in CLAUDE.md so the agent routes doing, not justfinding, to the cheap worker:
You are the ORCHESTRATOR. delegate(prompt, level) is the DEFAULT for BOTH execution AND judgment.
`level` picks a distinct tier: 1=GPT-5.6 Luna max (codex), 2=Grok 4.5 high (grok), 3=GPT-5.6 Sol
xhigh (codex), 4=Grok 4.6 high (grok), 5=Opus max (claude). The worker has full read/edit/shell access
in cwd when you delegate. The constant win is context economy: the worker's raw output never enters
your context. Delegate it, then review the result; edit inline only for a quick one-off you're
already positioned for. Use fast_delegate(prompt) when the work is self-contained and you just want
the fastest healthy worker. Pass agent:"name" or agent:{prompt:"..."} when the worker
needs a specialized persona.
Develop
npm test # vitest — unit tests for model resolution / arg building
npm run dev # run from source via tsx
License
MIT