agent-bridge-mcp
Delegates local coding tasks to Ollama models, with model selection, system prompts, temperature, token limits, thinking mode, and timeouts; also supports OpenCode-backed local workspace modes.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
agent-bridge-mcp
One coding agent hands work to others. agent-bridge-mcp is an MCP server that lets a primary agent session delegate tasks to Codex CLI, Claude Code (claude -p), Antigravity (agy) and local models (Ollama, OpenCode). It adds guard rails to that delegation: one writer per folder, a timed-out worker is killed together with its child processes (on Windows), and a backend whose quota is known to be used up is refused before it starts.
How this was built. AI coding agents wrote almost all of the code in this repository, and other agents reviewed it. My part was to decide what the bridge should do, set the rules the agents work under, and accept or reject what came back. The field report covers the first three days of real use, including what failed.
Emirhan Bahçacı
Why it exists
Running several agent CLIs from one session goes wrong in a few repeatable ways:
Two agents edit the same folder at the same time.
A worker hangs, or exits and leaves child processes behind.
A task goes to a provider whose quota ran out an hour ago.
A worker ends with empty output and the caller treats that as success.
The bridge puts one tool surface in front of four backends and handles these cases in one place.
Related MCP server: Antigravity MCP Bridge
What it does
Delegation. Single calls (
delegate_codex,delegate_claude,delegate_antigravity,delegate_local_agent), parallel batches (run_parallel_agents) and background jobs (start_agent_job,check_agent_job).One writer per folder. A write-capable run takes a cross-process lock on its
cwd. A second writer is refused withCWD_BUSYon a direct call, and waits its turn inside a batch or a background job.Process control. On Windows, a timeout or a cancel ends the worker's whole process tree (job objects, with
taskkill /Tas fallback). If processes are still running after a worker exits, the result carries aLEFTOVER_PROCESSESwarning.Quota awareness.
bridge_budgetreads the 5-hour and weekly limits of Codex (throughcodex app-server), Antigravity (agy -p /quota) and a separately profiled Claude Code (claude -p /usage) without sending a prompt to a model, and ranks themspend,normal,unknown,saveorblocked. Ablockedbackend is refused withCOOLDOWNbefore any process starts. Local models have no quota and are not ranked.Failure classes. Every result carries an
errorclass such asEMPTY_OUTPUT,QUOTA_EXHAUSTED,AUTH_REQUIREDorTIMEOUT, so the caller can react without parsing prose. A read-only run that ends with no text is reported asEMPTY_OUTPUT. A write-capable run with no text keeps its status and gets a warning, because its result is the changed files.Containment. Workers cannot delegate onward (
AGENT_BRIDGE_MAX_DEPTH),allowed_commandsis checked against an allowlist, andprompt_filereads only from allowed folders and never from files on its credential deny-list.A record. Each delegation is logged with its duration, model, error class and a hash of the prompt (not the prompt text).
record_outcomestores whether the result was accepted, fixed or rejected, andbridge_statssummarizes the log.
Status and limits
New project: first version on 15 November 2026, current version
0.4.0.Developed and used on Windows 11 only. The code has POSIX branches (file locks use
fcntl), but they are not tested, and on POSIX a timeout or a cancel kills only the worker's main process, not its children.Quota reading depends on CLI behavior that can change:
agy -p /quota,claude -p /usageand the Codexapp-server. A quota reading older than 15 minutes counts asunknown, andunknowndoes not block a delegation.The unit tests replace the worker CLIs with fakes. Real CLI behavior is covered only by daily use; the field report shows how that went.
Some names come from my own setup. Workers are told not to call two MCP servers,
agent-bridgeandlocal-llm; the second is my local-model server, so change that name inserver.pyif yours differs. The model names inconfig.example.jsonare the ones I use.Two optional helpers are not part of this repository:
helpers/ensure_ollama.py, which starts Ollama on demand (without it, start Ollama yourself), and an OpenCode binary underbin/opencode.
Quick start
Requirements: Windows (see Status and limits), Python 3.10 or newer, the mcp Python package (mcp>=1.0.0, installed in step 1), and whichever worker CLIs or runtimes you want to use, each already logged in: Claude Code (claude), Codex CLI (codex), Antigravity (agy), Ollama and/or OpenCode (opencode or opencode-cli).
Clone the repository, install it and create your config file:
git clone https://github.com/parttimegod/agent-bridge-mcp
cd agent-bridge-mcp
pip install -e .
cp config.example.json config.jsonAdjust
config.jsonfor your environment (seeconfig.jsonSettings):Replace the model names with models your own subscriptions offer.
To delegate to Claude Code, point
claude_config_dirat a separate profile folder and log that profile in once (setCLAUDE_CONFIG_DIRto the folder and runclaude /login), or setclaude_allow_orchestrator_accounttotrue. Until thendelegate_claudereturnsWORKER_PROFILE_MISSING.For local models, pull a model in Ollama and set
default_local_modelto its tag.
Register the server in your MCP client. For Claude Code:
claude mcp add agent-bridge -- python /absolute/path/to/agent-bridge-mcp/server.pyFor clients that read a JSON file:
{
"mcpServers": {
"agent-bridge": {
"command": "python",
"args": ["/absolute/path/to/agent-bridge-mcp/server.py"]
}
}
}The installed agent-bridge-mcp entry point works in place of python server.py. Use the Python interpreter you installed into; with another one the server exits and asks for the mcp package.
Ask your agent to call
bridge_status, which lists the workers it found, then delegate a first read-only task. This example needs a logged-in Codex CLI. Arguments fordelegate_codex:
{
"prompt": "Read src/parser.py and list possible off-by-one errors. Max 150 words.",
"cwd": "/path/to/project",
"sandbox": "read-only",
"timeout_seconds": 300
}The result is a JSON object like this one (shortened, values are examples):
{"ok": true, "id": "3f9c2a71be", "agent": "codex", "model": "<model>", "mode": "read-only", "output": "...", "error": null, "duration_seconds": 131.2}The rest of this page is reference.
Tools
Tool | Purpose | Key parameters |
| Run a Codex CLI task |
|
| Run a task via |
|
| Run an Antigravity ( |
|
| Run a local Ollama or OpenCode task |
|
| Run heterogeneous tasks concurrently |
|
| Start a background task |
|
| Query background job status |
|
| Cancel a job and terminate its worker (the whole process tree on Windows) |
|
| List background jobs in the current server process | - |
| Read 5-hour and weekly usage limits |
|
| Report worker availability, cooldowns, budget levels, and notes |
|
| Summarize delegation logs |
|
| Record verdict ( |
|
| Set or clear cooldowns ( |
|
| Add a dated note under |
|
Modes and team=true
codex (
sandbox):read-only(default),workspace-write,danger-full-access(excluded from defaultallowed_modes).claude (
permission_mode):read(default; usesdontAskwithRead,Grep,Glob, plus command prefixes passed inallowed_commands),edit(acceptEdits; edits files, denies other commands),auto(runs commands approved by the safety classifier),manual,dontAsk,bypassPermissions(excluded from defaultallowed_modes). Aliases:plan->read,acceptEdits->edit,default->manual.antigravity (
mode):plan(default, read-only),accept-edits(write-capable),auto(excluded from defaultallowed_modes).local (
mode):fast(default, text-only Ollama/api/chat),workspace(OpenCode read-only;editandshelldenied),workspace-write(OpenCode witheditandshellallowed; requires an explicitcwd). In both workspace modes the total prompt, including the guard header and the rules, is capped at 24,000 characters.allowed_commandsrule (delegate_claude): Comma-separated list of command prefixes (up to 20 entries, at most 80 characters per entry). After splitting on commas and stripping whitespace, every entry must match^[A-Za-z0-9._/\\][A-Za-z0-9._/\\ =+@:-]*$(no wildcards such as*or?,%, quotes, parentheses, control characters, non-ASCII characters, or leading-). Any violation rejects the call withINVALID_ARGUMENTbefore spawning a process.prompt_filerule:prompt_filemust be an absolute path and is resolved (following symlinks) withstrict=False.Allowed root folders are: (a) the call's
cwd, only when explicitly passed by the caller and when its resolved path is not a filesystem root, not the user's home folder, and not an ancestor of the home folder; (b) theagent-bridgesubfolder inside the system temporary directory (<tempdir>/agent-bridge, not the entire system temporary directory); (c) each directory in configprompt_file_roots, subject to the same root/home/ancestor restriction ascwd.If the resolved path is not inside an allowed root, it is rejected with
ValueError("prompt_file is outside the allowed folders")(PROMPT_FILE_INVALID) before any existence, file-type, or size check.A case-insensitive deny-list is checked against both the given path and the resolved path: any path component starting with
.claude,.codex,.gemini,.ssh,.antigravity,.aws,.azure,.gnupg,.kube, or.docker; any file named.npmrc,.netrc,_netrc,.pypirc,.git-credentials, or.envrc; and any file whose name starts with.envor ends with.env. Blocked paths return the same"prompt_file is outside the allowed folders"message.The target must then be a regular file of at most 200,000 bytes and must decode strictly as UTF-8 (
"prompt_file must be valid UTF-8"on decode error).
team=true: Supported only bycodexandantigravity(INVALID_ARGUMENTfor other backends). Enables built-in sub-agents on the worker, using the configured lead and sub-agent models (codex_team_model/codex_team_worker_modelorantigravity_team_model/antigravity_team_worker_model, orantigravity_tierswhen quota data is available; passingmodeloverrides the lead model). Intended for tasks with at least three independent subtasks; token usage is roughly three times a single run.
Results and Error Classes
Every delegation returns a JSON object with these fields:
Field | Description |
| Success flag ( |
| Backend, model and mode the run used |
| Wall-clock time of the run |
| Error class name or |
| Worker response text (truncated above |
| Summary of changed files for write-capable runs and Antigravity runs |
| Non-fatal notices such as permission denials, no file changes, or worker-spawned sub-agents |
| Metadata such as |
| Normalized counters: |
| 10-character delegation identifier (matches |
Error classes (error):
EMPTY_PROMPT: Prompt is empty.PROMPT_FILE_INVALID:prompt_fileis not an absolute regular file, exceeds 200,000 bytes, is outside allowed roots, or targets a restricted directory or.envfile.UNKNOWN_AGENT: Unknown backend name.INVALID_TASK: Task object or field type is invalid.INVALID_ARGUMENT: Invalid argument value (for example, malformedallowed_commands, invalidown_usage, orteam=trueon an unsupported backend).RECURSION_LIMIT_REACHED: Current depth reachedAGENT_BRIDGE_MAX_DEPTH.INVALID_CWD:cwddirectory does not exist.CWD_REQUIRED:cwdis empty for a write-capable task.CWD_NOT_ALLOWED: Write-capablecwdpoints to the home directory, filesystem root, or inside.claude,.claude-pro,.codex, or.gemini.CWD_BUSY: Another active writer holds a lock on the same or an overlapping directory.LOCK_UNAVAILABLE: Could not open or acquire the lock file.INVALID_MODE: Mode is invalid for the selected backend.MODE_NOT_ALLOWED: Mode is not listed inallowed_modes.WORKER_PROFILE_MISSING: No separate Claude worker profile is configured andclaude_allow_orchestrator_accountis false.BINARY_NOT_FOUND: CLI binary (claude,codex, oragy) was not found.OPENCODE_NOT_FOUND:opencodeoropencode-clibinary was not found.PROMPT_TOO_LONG: Local workspace prompt exceeds 24,000 characters.SPAWN_FAILED: Subprocess failed to start.TIMEOUT: Execution timed out and the worker was killed (with its whole process tree on Windows).CANCELLED: Task or background job was cancelled.COOLDOWN: Target worker or model is in cooldown or its budget level isblocked.AUTH_REQUIRED: Session or API key is missing or invalid.QUOTA_EXHAUSTED: Rate or usage limit reached.BUDGET_EXHAUSTED:max_budget_usdlimit reached.MAX_TURNS: Claude worker reached its turn limit.EMPTY_OUTPUT: Read-only run completed with empty output.EMPTY_OUTPUT_TOKEN_LIMIT: Infastmode,max_tokenswas exhausted during thinking before producing content.OLLAMA_UNAVAILABLE: Ollama helper could not start or reach Ollama.OLLAMA_REQUEST_FAILED: Ollama/api/chatrequest failed.WORKER_ERROR: Unclassified worker failure.INTERNAL_ERROR: Unhandled exception inside the bridge.STATE_WRITE_FAILED:set_cooldownfailed to writecooldowns.json.INVALID_VERDICT: Invalidverdictpassed torecord_outcome.UNKNOWN_JOB_ID: Unknownjob_idpassed tocheck_agent_joborcancel_agent_job.
config.json Settings
The home directory is used for helpers/ensure_ollama.py lookup, bin/opencode lookup, and the fallback working directory when the current working directory is unavailable. It is resolved from environment variable AGENT_BRIDGE_HOME, then environment variable AI_CODING_ROOT (legacy alias), then home_dir in config.json (must be a string; relative paths are resolved against the server folder containing server.py), and finally the folder that contains server.py. A relative data_dir (from AGENT_BRIDGE_DATA_DIR or config.json) is also resolved against the server folder. A custom v2 OpenCode binary must have "opencode-cli" in its file name or have OPENCODE_FORCE_V2 set (OPENCODE_FORCE_V2=1).
Moving from an older private setup: Set home_dir in config.json or AGENT_BRIDGE_HOME in the environment when helpers or bin live outside the server folder.
Key | Default ( | Description |
|
| Base directory fallback (string; relative paths resolve against the server folder) used when |
|
| Directory for logs, locks, jobs, and state files (relative paths resolve against the server folder; overridden by |
|
| Explicit path to the |
|
| Additional root directories allowed for |
|
| Default model for |
|
| Default model for |
|
| Context length for Ollama and OpenCode (overridden by |
|
| Wait timeout in seconds for optional |
|
| Policy passed to |
|
| Rules file prepended to local workspace prompts |
|
| Markdown file used by |
|
| Separate |
|
| Allow Claude delegation using the orchestrator's own account when |
|
| Comma-separated |
|
| Value passed to |
|
| Default per-call |
|
| Default model for solo Codex runs |
|
| Default |
|
| Codex MCP policy ( |
|
| Extra |
|
| Lead model used for Codex when |
|
| Sub-agent model named in the Codex |
|
| Ordered fallback model list for Antigravity, skipping models in cooldown |
|
| Lead model used for Antigravity when |
|
| Sub-agent model named in the Antigravity |
|
| Tier model names selected by quota state in |
| Group prefix map | Maps Antigravity model name substrings to quota group keys |
| Per-agent lists | Permitted modes for each backend |
|
| In-process concurrency cap per backend |
|
| Fallback cooldown durations when no reset time is parsed |
|
| Character limit above which |
|
| Environment variable prefixes stripped from worker subprocesses |
| Threshold parameters | Pace and remaining-fraction thresholds used by |
Environment Variables
Name | Meaning |
| Path to |
| Home directory for |
| Legacy alias for |
| Directory for state, logs, locks, jobs, and truncated outputs (relative paths resolve against the server folder) |
| Default model for |
| Separate |
| Maximum allowed delegation recursion depth (default |
| Current delegation recursion depth (default |
| Base URL for the Ollama API server (default |
| Context window length ( |
| Explicit path to the |
| Explicit path to the |
| Explicit path to the |
| Explicit path to the |
| Explicit path to the v2 |
| Set to |
| Directory containing Codex |
| Preserved in the delegated Claude worker environment when present in the parent environment |
| Compared against the worker profile's |
| Windows application data folder used to locate npm Codex and |
| Windows local application data folder used to locate |
State Files and Cooldown
State and log data are stored in AGENT_BRIDGE_DATA_DIR, falling back to data_dir in config.json, or data/ inside the server folder containing server.py (relative data_dir values are always resolved against the server folder):
delegations.jsonl(rotates todelegations.1.jsonlabove 5 MB)cooldowns.jsonbudget_state.jsonquota_history.jsonljobs/(cleaned up after 7 days)locks/(per-directory write locks; stale locks from dead PIDs or older than 6 hours are removed)outputs/(full text for truncated outputs; cleaned up after 14 days)local-profile/(isolated profile directories for OpenCode local workspace runs)
worker_notes.md stores dated notes under ## <agent> headings (local, codex, antigravity, claude, general). When a run fails with QUOTA_EXHAUSTED or AUTH_REQUIRED, a cooldown entry is recorded until the parsed reset time or for cooldown_minutes. A successful run clears that key's cooldown. To clear a cooldown manually, call set_cooldown("<key>", 0), or set_cooldown("all", 0) to clear all keys.
Usage Budget
bridge_budget reads 5-hour and weekly limits for codex, antigravity, claude (only when a separate claude_config_dir is configured), and max (when own_usage JSON text is provided). It returns order (sorted from most available to most constrained) along with each department's level, until, why, and scored buckets.
Levels:
spend: sufficient weekly margin or nearing weekly reset with unused quota.normal: usage pace is within normal bounds.unknown: no fresh data (snapshots older than 15 minutes expire); does not block delegations.save: running ahead of pace or low 5-hour quota; attaches aBUDGET:warning to delegation results.blocked: quota is exhausted (<= 2%remaining or provider-blocked); delegations fail immediately withCOOLDOWNwithout spawning a worker process.
For Antigravity, budget.py maps quota groups to antigravity_tiers to pick strong/team_head, single, and team_worker models. Cached snapshots are reused for 120 seconds unless refresh=True is passed, and completed delegations trigger a background refresh for that backend. To view the budget table from the command line:
python budget.pySupported flags: --json, --refresh, and --own '<json>'.
Troubleshooting
AUTH_REQUIREDfrom the Claude worker: Log in to the worker profile: setCLAUDE_CONFIG_DIRto that profile folder, runclaude /login, then clear the cooldown withset_cooldown("claude", 0).Codex Windows sandbox triggers UAC prompts: Keep
features.network_proxy=falseincodex_extra_config; switching betweenread-onlyandworkspace-writewith the network proxy enabled triggers elevated Windows sandbox setup.Changes to
server.pydo not take effect: MCP clients loadserver.pywhen starting the server process; start a new MCP session or restart the client after editingserver.py.
Tests
Run the unit test suite from the repository root:
python -m unittest discover -s testsTool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Shared control plane for AI coding agents — tasks, memory, decisions, file locks. 12 tools.
Multiplayer for the coding agents your team already uses: shared tasks, decisions, skills and tools.
Command center for developers coordinating AI coding agents across projects.
The team layer for AI coding agents: shared contracts, collision alerts, E2EE sessions.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables users to delegate coding tasks in a chosen project to the official Codex and Claude CLI agents from within an existing chat, then convene a council of configured models to gather independent opinions and review the resulting files and test runs. It also manages multi-provider API connections, model catalogs, and per-task token, time, and cost limits.MIT
- AlicenseNot gradedqualityBmaintenanceEnables Codex or Claude Code to orchestrate persistent Antigravity CLI workers as independent implementers and testers within restricted workspace roots. It supports asynchronous task dispatch, progress polling, result inspection, follow-up messages, and cancellation with bounded, audited local event logging.5MIT
- AlicenseAqualityBmaintenanceEnables an AI agent to delegate self-contained tasks to other agent CLIs already installed and signed in on the same machine — Claude, Codex, Gemini, or a local Ollama model — using their existing subscriptions with no API keys. Supports synchronous single-call delegation plus background tasks that can be started and polled for longer-running work.431 npmMIT
- AlicenseBqualityCmaintenanceEnables AI agents to start, monitor, follow up on, stop, and collect results from headless Claude Code CLI sessions, with queuing, budgets, locks, and wake-up notifications.9MIT