claude_mcp
# claude_mcp
`claude_mcp` is a local, stdio-only Model Context Protocol server that gives
Codex a controlled Claude Opus 5 collaborator through the installed Claude Code
CLI and the user's Claude subscription. Opus can inspect an allowed workspace,
plan or review work without editing, or take a separately annotated write-capable
task that can edit files and run focused tests.
Codex remains the orchestrator and final authority. This bridge does not call the
Anthropic API directly, accept an Anthropic API key, scrape a terminal, create
commits, or run a resident Claude session.
## Collaboration model
The intended workflow is writer–verifier separation:
```text
User
-> Codex (GPT-5.6-sol, orchestrator)
-> claude_mcp over MCP stdio
-> claude -p --model claude-opus-5
-> controlled access to one validated workspace
-> structured Opus report + trusted bridge observations
-> Codex inspects the real diff, reruns important checks, and answers the user
```
Useful patterns include:
- Codex implements a substantial change, then starts a fresh Opus review.
- Opus implements a bounded change, then Codex inspects the actual diff and
independently verifies it.
- A read-only planning session is resumed into implementation in the same
canonical workspace.
- Final independent review normally uses a fresh session rather than resuming
the authoring session.
Only one operation may use a workspace at a time. Calls for different workspaces
may run concurrently up to the configured global limit. Do not ask both models
to write the same workspace concurrently, and skip Opus for trivial mechanical
work.
## Why `claude -p`
Claude Code's non-interactive print mode provides an argument-vector interface,
explicit tools and permission mode, structured JSON output, session IDs, and a
normal subprocess lifecycle. That is substantially more auditable than PTY,
tmux, terminal-control-sequence, or interactive-TUI scraping. The bridge uses
`asyncio.create_subprocess_exec` with no shell and supplies all task content as
JSON on stdin.
## Public MCP tools
Version 0.1 exposes exactly three tools:
- `opus_status`: free local readiness diagnostics. It runs `claude --version`
and `claude auth status`, but never a model completion.
- `opus_consult`: read-only `plan`, `review`, `diagnose`, or `design` work using
only `Read,Glob,Grep`. Those tools are explicitly allowed in both CLI arguments
and the per-call settings policy. Scrubbed Claude Code sessions use the effective
`default` permission mode directly, avoiding a misleading forced-mode warning.
Any observed workspace change is returned as a policy violation.
- `opus_execute`: destructive, non-idempotent `implement`, `fix`, `refactor`,
`test`, or `document` work using `Read,Glob,Grep,Edit,Write,Bash`. Git is
required by default.
Both collaboration tools return the validated Opus report separately from
bridge-observed process, session, policy, and workspace metadata. Claude's own
`files_changed` claim is advisory; the bridge's pre/post manifest is independent.
Full source diffs are not returned because Codex already has local workspace
access and should inspect them directly.
The public tools use reliable turn ceilings: 24 for read-only consultation and
64 for execution. These are maxima, not quotas, so Claude stops earlier when the
task is complete. If Claude exhausts a ceiling, the bridge reports
`error_max_turns` as a process failure with the selected ceiling and safe
remediation; it does not mislabel the result as a non-Opus fallback or a broken
structured-output contract.
## Requirements
- Python 3.11 or newer
- [`uv`](https://docs.astral.sh/uv/)
- Git
- macOS, Linux, or WSL2 (not native Windows)
- Claude Code at or above the configured minimum, currently `2.1.224`
- Native Claude Code sandbox dependencies. On Linux and WSL2 this normally means
`bubblewrap` (`bwrap`) and `socat`; macOS uses Seatbelt.
- A Claude subscription login through Claude Code, or a deliberately supplied
`CLAUDE_CODE_OAUTH_TOKEN`
The bridge fails closed when the native sandbox, required security settings,
supported CLI version, or allowed workspace roots are missing. Write-capable
execution also requires a successful authentication status probe unless the
operator deliberately supplied `CLAUDE_CODE_OAUTH_TOKEN`; in that case the actual
bounded request validates the token. Because some Claude Code releases can report
a stale status for a usable stored login, read-only consultation also lets the
bounded model request make the final authentication determination and returns its
redacted failure reason.
## Installation
```bash
git clone git@github.com:catid/claude_mcp.git
cd claude_mcp
uv sync --all-groups
```
Verify the installed entry point without sending a model request by configuring
the server in Codex and calling `opus_status`.
## Authentication
Use the normal Claude Code subscription login:
```bash
claude auth login
claude auth status
```
`CLAUDE_CODE_OAUTH_TOKEN` is preserved if the operator deliberately supplies it.
Version 0.1 does not support API-key billing or Bedrock, Vertex, Foundry, custom
gateways, profiles, or alternate endpoints.
Before every diagnostic and task process, the bridge copies the parent
environment and removes variables that could switch authentication, provider,
endpoint, organization, profile, or model. This includes `ANTHROPIC_*`,
`CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, and
`CLAUDE_CODE_USE_FOUNDRY`, plus selected cloud credentials. Interpreter/loader
injection variables such as `NODE_OPTIONS`, `PYTHONPATH`, and `LD_PRELOAD`, all
`GIT_*` variables, proxy and custom-CA variables, and `CLAUDE_CONFIG_DIR` are
also removed. It forces
`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1` so Bash children do not inherit Anthropic or
cloud credentials. `opus_status` reports detected override and dangerous
environment **names**, never values. Ordinary requirements such as `HOME`,
`PATH`, `SHELL`, `TMPDIR`, and locale are retained. Version 0.1 intentionally
does not inherit corporate proxies; explicit opt-in proxy support is future work.
Current Claude Code may create known zero-byte scrub stubs and append matching
`.git/info/exclude` blocks. The bridge records pre-existing state, removes only
new zero-byte stubs, and atomically restores only exact scrub-mode append blocks;
pre-existing or model-written content is preserved.
## Configuration
Set at least `CLAUDE_MCP_ALLOWED_ROOTS` in the MCP server environment. Paths are
separated with `os.pathsep` (`:` on POSIX) and are resolved canonically at server
startup.
| Variable | Default | Meaning |
| --- | ---: | --- |
| `CLAUDE_MCP_CLAUDE_BINARY` | `claude` | Claude Code executable |
| `CLAUDE_MCP_MODEL` | `claude-opus-5` | Required Opus 5 model |
| `CLAUDE_MCP_ALLOWED_ROOTS` | required for task calls | Allowed workspace roots |
| `CLAUDE_MCP_TIMEOUT_SECONDS` | `7200` | Total completion timeout |
| `CLAUDE_MCP_KILL_GRACE_SECONDS` | `10` | SIGTERM grace before SIGKILL |
| `CLAUDE_MCP_MAX_INPUT_CHARS` | `500000` | Maximum serialized task payload |
| `CLAUDE_MCP_MAX_OUTPUT_BYTES` | `16777216` | Maximum Claude stdout |
| `CLAUDE_MCP_MAX_STDERR_BYTES` | `1048576` | Maximum captured stderr |
| `CLAUDE_MCP_MAX_CONCURRENT` | `2` | Concurrent distinct workspaces |
| `CLAUDE_MCP_HEARTBEAT_SECONDS` | `30` | MCP heartbeat interval |
| `CLAUDE_MCP_REQUIRE_GIT_FOR_WRITES` | `true` | Require Git for execution |
| `CLAUDE_MCP_EXECUTE_PERMISSION_MODE` | `auto` | Claude execute permission mode |
| `CLAUDE_MCP_MIN_CLAUDE_VERSION` | `2.1.224` | Minimum supported CLI |
| `CLAUDE_MCP_STATE_DIR` | XDG state default | Session registry and lock state |
All values are validated. `bypassPermissions` and plan mode are not accepted as
execute modes.
### Codex MCP configuration
Add this to `~/.codex/config.toml`, using absolute paths:
```toml
[mcp_servers.opus_collaborator]
command = "/absolute/path/to/claude_mcp/.venv/bin/claude-mcp"
enabled = true
required = false
startup_timeout_sec = 20
tool_timeout_sec = 7500
default_tools_approval_mode = "approve"
[mcp_servers.opus_collaborator.env]
CLAUDE_MCP_ALLOWED_ROOTS = "/absolute/path/to/repositories"
CLAUDE_MCP_MODEL = "claude-opus-5"
CLAUDE_MCP_REQUIRE_GIT_FOR_WRITES = "true"
```
Codex clients share this MCP configuration. Run `codex mcp list` to inspect
configured servers, or use `/mcp` in the Codex terminal UI to confirm that
`opus_collaborator` loaded and advertises exactly three tools. See the current
[Codex MCP documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
for client configuration and approval-mode details.
## Usage patterns
### Fresh architecture plan
Call `opus_consult` without a session ID:
```json
{
"workspace_path": "/repos/service",
"task": "Design the new durable job scheduler",
"mode": "design",
"focus": "crash recovery, idempotency, and migration",
"effort": "high"
}
```
### Resume a plan into implementation
Pass the returned session ID to `opus_execute` for the same canonical workspace:
```json
{
"workspace_path": "/repos/service",
"task": "Implement the approved scheduler design",
"mode": "implement",
"session_id": "00000000-0000-4000-8000-000000000000",
"acceptance_criteria": [
"Existing jobs migrate without data loss",
"Focused unit and recovery tests pass"
]
}
```
The shown UUID is illustrative; use the actual bridge-returned value.
### Codex implementation, fresh Opus review
After Codex writes a substantial change, call `opus_consult` with `mode: "review"`
and omit `session_id`. Ask for concrete, evidenced findings. Codex should evaluate
each finding against the repository rather than accepting it automatically.
### Opus implementation, Codex verification
Delegate a bounded change with `opus_execute`, then have Codex inspect `git diff`,
the bridge's `observed_changed_paths`, pre-existing dirty work, and important
tests. The bridge never commits or pushes the result.
### Recommended Codex instruction
```text
Use the Opus collaborator proactively for substantial architecture, unfamiliar
repositories, difficult bugs, multi-file changes, algorithms, concurrency,
security-sensitive work, and independent review. Skip it for trivial mechanical
edits. Delegate a complementary role, never let both agents write the workspace
at once, inspect the actual diff after Opus writes, and use a fresh session for
final independent review unless continuity is specifically valuable.
```
## Security model
Workspace paths are hostile input. The bridge expands `~`, performs strict
canonical resolution, rejects files and missing paths, checks path-aware allowed
root containment, detects the Git top level, and rejects symlink, traversal,
sibling-prefix, and Git-root escapes. Execution requires Git by default but does
not require a clean tree; pre-existing tracked, staged, untracked, deleted, and
renamed work is preserved as context.
Every operation acquires, in order, a per-canonical-workspace async lock, a
global async semaphore, and a process-safe file lock whose filename is a SHA-256
digest. This prevents duplicate calls for one workspace from consuming global
capacity needed by another workspace. Sessions are canonical UUIDs stored in an
atomic, mode-`0600` registry
inside a mode-`0700` state directory. A session is bound to one canonical
workspace and one Opus model. A plan may resume into execution, but cross-
workspace and cross-model resumes fail.
Successful output must prove Opus 5 through a validated authoritative model field
or protocol-conformant positive Opus usage that exceeds aggregate Haiku auxiliary
usage. Both `modelUsage` spellings are audited when present; malformed,
conflicting, or unexpected model entries fail closed, and no fallback model is
configured.
Before and after a call, the bridge independently captures Git HEAD/branch,
NUL-safe porcelain status, tracked/staged/untracked/deleted/renamed paths, diff
statistics, and a content state fingerprint. The returned snapshot explicitly
notes that Git-ignored paths and `.git` internals are not observed; Codex must
inspect those separately when they matter. Non-Git consultations receive a
directory manifest with explicit entry and content-hash limits; beyond the hash
budget, bounded first/last content samples plus size/mtime/ctime metadata remain
observation evidence.
Filenames with spaces, tabs, quotes, and newlines are supported. A failed or
timed-out process still gets a post-operation observation when possible.
Claude starts in its own process session. Timeout, cancellation, output overflow,
or shutdown sends SIGTERM to the full process group, waits the configured grace
period, sends SIGKILL if needed, reaps the process, stops heartbeats, cleans
owner-only temporary prompt/settings files outside the repository, and releases
all locks. The bridge never retries a completion automatically; an ambiguous
failure may already have changed files and consumed subscription usage.
Every model call uses `--safe-mode`, `--strict-mcp-config`, `--no-chrome`, no Web
tools, a mandatory fail-closed native sandbox, an empty strict network allowlist,
no local binding or Unix sockets, secret-path denies, and dangerous Git-command
denies. Unsandboxed retry is disabled. Admin-managed Claude Code policy still
applies and can affect the effective policy; inspect organization policy when
`opus_status` or Claude Code reports a managed-setting conflict.
Important limitations:
- Workspace source and submitted task context are sent to Anthropic through the
locally authenticated Claude Code process and consume subscription usage.
- `opus_execute` is deliberately write-capable and should be approval-gated by
the MCP client.
- Native sandboxing is a strong boundary, not magic. Repository-contained
secrets remain sensitive even when common secret paths are denied.
- Claude Code may persist normal local session transcripts in its own state. The
bridge does not copy or expose transcript contents.
- Network access from Claude tools is denied by default. The model request itself
necessarily reaches Anthropic through Claude Code.
- Common commit, push, reset, clean, restore, rebase, merge, and history-rewrite
commands are denied by pattern; HEAD and workspace changes are independently
observed. These are layered controls, not a substitute for Codex inspecting
the actual diff and trusted manifest.
## Troubleshooting
- **CLI too old:** `opus_status` reports the parsed and minimum versions. Run
`claude update`, then verify `claude --version`.
- **Authentication unavailable:** run `claude auth login`, `claude auth status`,
and a new `claude -p` call. A nonzero or malformed status fails execution
preflight unless the operator deliberately supplied `CLAUDE_CODE_OAUTH_TOKEN`.
Read-only consultation may still attempt its bounded call and reports the
redacted Claude authentication error if that request also fails. `opus_status`
reports whether the deliberate-token execution exception is active.
- **API key overrides subscription:** unset `ANTHROPIC_API_KEY` and related
provider variables. Task processes strip them regardless; status reports names.
- **Workspace outside allowed roots:** add the complete canonical Git root's
parent to `CLAUDE_MCP_ALLOWED_ROOTS`. Allowing only a nested subdirectory is
rejected when the Git root would escape.
- **Native sandbox unavailable:** install `bwrap` and `socat` on Linux/WSL2, or
use a supported macOS host. The bridge runs a real namespace-isolation probe,
not just an executable check, and never falls back to unsandboxed Bash. Ubuntu
24.04 may additionally require an administrator-provided AppArmor profile for
`/usr/bin/bwrap` with `userns,` permission; prefer the distribution's
purpose-built bwrap profile when available rather than disabling the global
user-namespace restriction.
- **Session/workspace mismatch:** omit `session_id` to start fresh in the new
workspace. Sessions cannot move between repositories.
- **Timeout after possible edits:** do not blindly call again. Inspect status,
actual files, Git diff, tests, and the error's pre/post metadata first.
- **Malformed Claude result:** update Claude Code if necessary and inspect the
workspace. Locally invalid structured output is never trusted and execution is
never automatically retried.
- **Corrupt session registry:** stop bridge processes, preserve the registry for
diagnosis, and move it aside only after deciding that resumable sessions are
no longer needed. Corruption is not silently discarded.
## Development
The test suite is fully offline. `tests/fixtures/fake_claude.py` emulates Claude
diagnostics, structured completions, mutations, malformed output, limits,
timeouts, and process descendants. No test requires Anthropic credentials,
network access, subscription usage, or a real Claude invocation.
```bash
uv sync --all-groups
uv run ruff check .
uv run ruff format --check .
uv run pytest
uv build
```
`tests/test_protocol.py` launches the installed `claude-mcp` entry point and
performs a real stdio MCP initialize/list/call sequence against the fake CLI.
## Version 0.1 scope
Version 0.1 uses direct, synchronous access to one validated workspace per call.
It intentionally has no PTY/TUI scraping, tmux integration, resident background
agent, remote MCP transport, direct Anthropic API path, alternate provider,
automatic worktree, automatic Git operation, arbitrary child MCP server, or
background job that outlives an MCP call.
Possible later work includes opt-in isolated Git worktrees and richer progress
streaming. Those features should preserve the writer–verifier and fail-closed
security invariants established here.
TDQS
Scored across 3 tools
The three tools map onto a clear read-only / non-editing / editing split: opus_status inspects configuration, opus_consult plans and reviews without writes, and opus_execute delegates with write access. opus_consult and opus_execute could still be momentarily confused since they both invoke a model session, but the descriptions explicitly distinguish edit vs. no-edit behavior.
All three tools follow the same opus_<verb> pattern, with concise verbs (status, consult, execute) that consistently describe the action. No mixing of conventions or casing.
Three tools is minimal but each serves a distinct role in the delegate-to-Opus workflow, so nothing is redundant. It sits at the thin edge of the acceptable range, with no lifecycle tooling (cancel, resume, list sessions) to round it out.
Configuration check, planning/review, and execution are covered, but the surface has notable gaps: no way to list or resume sessions, cancel or abort a long run, or retrieve results of a previously delegated task. Agents must work around these lifecycle omissions.