Metadata-Version: 2.4
Name: claude-mcp-swarm
Version: 0.1.0
Summary: Parallel Claude Code MCP server with live task monitoring, batch wait, worktree isolation, and MCP Tasks support
Author: TKasperczyk
License: MIT
Project-URL: Homepage, https://github.com/TKasperczyk/claude-mcp-swarm
Project-URL: Repository, https://github.com/TKasperczyk/claude-mcp-swarm
Project-URL: Issues, https://github.com/TKasperczyk/claude-mcp-swarm/issues
Keywords: mcp,claude,claude-code,anthropic,async,parallel,swarm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: mcp-swarm-core<0.3,>=0.2.0
Dynamic: license-file

# claude-mcp-swarm

An MCP server that wraps Anthropic's Claude Code CLI (`claude`) with **true parallel execution**, **live task monitoring**, **git worktree isolation**, and **MCP Tasks** support. Powered by stdlib-only [`mcp-swarm-core`](https://github.com/TKasperczyk/mcp-swarm-core) (zero third-party runtime dependencies).

## Why?

Run multiple Claude Code (`claude -p`) agents concurrently from Codex, Antigravity, Claude Code, or any MCP client without serial queueing, with live visibility into tool calls, token usage, structured output, tool errors, permission denials, and isolated `HEAD`-based git worktrees.

**Key features:**

- **True parallel fan-out** - each task runs as an independent `claude -p --output-format=stream-json --verbose` subprocess
- **Worktree isolation** - `worktree: true` creates an isolated `HEAD`-based git worktree (`claude-swarm/<id>`) per task so parallel runs never edit past each other
- **Batch wait & MCP Tasks** - supports both explicit fan-out (`claude_async` + `claude_wait`) and the official MCP 2026-07-28 Tasks extension (`io.modelcontextprotocol/tasks`)
- **Live JSONL streaming status** - parses `system`, `assistant`, `user`, and terminal `result` NDJSON events incrementally for live tool counts, last tool call, token usage, tool errors, and permission denials
- **Non-interactive `claude -p` flag support** - `--model`, `--fallback-model`, `--effort`, `--permission-mode`, `--dangerously-skip-permissions`, `--tools`, `--allowed-tools`, `--disallowed-tools`, `--add-dir`, `--agent`, `--agents`, `--system-prompt`, `--append-system-prompt`, `--json-schema`, `--settings`, `--setting-sources`, `--mcp-config`, `--strict-mcp-config`, `--max-turns`, `--max-budget-usd`, `--disable-slash-commands`, `--no-session-persistence`, `--bare`, `--resume`, and `--fork-session`
- **Safe stdin transport** - prompts are sent via UTF-8 stdin and all value options use `--flag=value` syntax, avoiding OS argv length limits, leading-`-` option injection, Commander.js variadic greediness, and Windows shell quoting issues

## MCP Protocol Support

- **Stateless MCP `2026-07-28`** - supports `server/discover`, per-request `_meta["io.modelcontextprotocol/protocolVersion"]` and `_meta["io.modelcontextprotocol/clientCapabilities"]`, `resultType` discriminators, and unsupported-version rejection (`-32022`).
- **Official Tasks extension (`io.modelcontextprotocol/tasks`)** - when a client advertises `io.modelcontextprotocol/tasks`, `claude` and `claude_reply` immediately return a `CreateTaskResult` (`resultType: "task"`) with a 128-bit `taskId`. Clients poll `tasks/get` and cancel via `tasks/cancel` per SEP-2663.
- **Backward-compatible stateful MCP (`2024-11-05` through `2025-11-25`)** - supports `initialize` negotiation, top-level server `instructions`, `ping`, tool `annotations`, `outputSchema` + `structuredContent`, accurate `isError` flags, enriched `notifications/progress`, and JSON-RPC 2.0 §4.1 silent handling of unknown notifications.

## Tools

| Tool | Description |
|------|-------------|
| `claude` | Synchronous execution (or native MCP Task when client supports `io.modelcontextprotocol/tasks`); returns text, `session_id`, token `usage`, optional `structured_output`, `tool_errors`, `permission_denials`, and structured failure details |
| `claude_async` | Launch a task, get a `task_id` immediately (fan-out). **Not** fire-and-forget: results come back only via `claude_wait`. Pass `session_id` to resume a session (with optional `fork_session: true`) |
| `claude_reply` | Continue a previous session via `claude --resume=<session_id>`. Automatically reuses the original session's working directory (including its worktree path) when `cwd` is omitted |
| `claude_status` | Live read-only peek: tools called, last tool call, permission mode, tool errors, token usage, and failure cause |
| `claude_wait` | Block until multiple tasks complete and return results or structured failure details |
| `claude_cancel` | Kill a running async task and its child process tree (preserves worktree for inspection); if already completed or failed, preserves and reports that outcome |
| `claude_models` | List available Claude Code model aliases/identifiers, resolved model IDs, and supported effort levels (queried live without starting a turn, persisting a session, or running hooks) |

## Installation

### PyPI

```bash
uvx --upgrade claude-mcp-swarm --model opus
```

### Local checkout (development)

```bash
uvx --from /path/to/claude-mcp-swarm --with /path/to/mcp-swarm-core claude-mcp-swarm --model opus
```

### Codex (`~/.codex/config.toml`)

```toml
[mcp_servers.claude-swarm]
command = "uvx"
args = ["--upgrade", "claude-mcp-swarm", "--model", "opus", "--dangerously-skip-permissions"]
```

### Unattended permissions & MCP isolation

- Pass `--dangerously-skip-permissions` or `--permission-mode bypassPermissions` / `acceptEdits` / `dontAsk` in server defaults (or per call) for unattended runs in trusted repos or sandboxes.
- If you want spawned Claude workers to skip loading your user MCP servers (faster startup and avoids recursive MCP server loading), pass `--strict-mcp-config` (optionally with `--mcp-config <file-or-json>`).

## Usage

### Parallel execution

```
1. Call claude_async(prompt="Audit module A", worktree=true)  ->  task_id: "a1b2c3d4"
2. Call claude_async(prompt="Audit module B", worktree=true)  ->  task_id: "e5f60718"
3. Call claude_wait(task_ids=["a1b2c3d4", "e5f60718"])
   -> blocks until all finish, returns all results
```

`claude_async` and `claude_wait` belong in the **same turn**: `task_id` is internal to this server and not tracked by legacy MCP clients. Short `timeout` values on `claude_wait` are raised to a floor (default `150s`, configurable via `CLAUDE_SWARM_MIN_WAIT`) so long waits cross the client's 2-minute auto-backgrounding threshold; already-finished tasks return immediately.

### Session continuity & worktree cwd preservation

- When `cwd` is omitted on `claude_reply` (or `claude_async(session_id=...)`), the server automatically reuses the original session's working directory (including its worktree path if it still exists; persisted on disk for async and worktree runs, and tracked in-process for non-worktree sync runs).
- Pass `fork_session: true` alongside `session_id` to branch a conversation into a new `session_id` without mutating the original transcript.
- Note that `no_session_persistence: true` disables writing session transcripts to disk, so those sessions cannot be resumed later.

### Structured output (`json_schema`)

Pass `json_schema` (JSON object or string) to forward `--json-schema` to Claude Code so it can emit validated JSON via its `StructuredOutput` tool. When `claude` returns `result.structured_output`, it is exposed on `structuredContent.structured_output`. Callers should still check that `structured_output` is present, because Claude CLI can exit 0 without it on short-circuited CLI commands or prose fallbacks.

### Credentials in config flags

Inline JSON passed via `--settings` or `--mcp-config` is redacted from the `claude-swarm:///config` resource, while file paths remain visible. Prefer file paths (e.g. `--mcp-config /path/to/mcp.json`) over inline tokens or `env` secrets so credentials are not passed on process command lines or stored in `.meta` files.

### Worktree isolation

> **Caveats:**
> - Because worktrees branch from `HEAD` (`git worktree add -b claude-swarm/<id> ... HEAD`), **uncommitted and untracked changes in your working tree are not included** in the worktree. Commit prerequisite edits first if the task needs them.
> - Expired worktrees (older than `CLAUDE_SWARM_TASK_MAX_AGE`, default 24 hours) are lazily removed on a subsequent task launch via `git worktree remove --force` and `git branch -D`. Merge or cherry-pick before expiry.

## Server flags

| Flag | Description |
|------|-------------|
| `--version` | Show version and exit |
| `--model MODEL` | Default model alias or full name (e.g. `opus`, `sonnet`, `haiku`, `fable`) |
| `--fallback-model MODEL` | Default fallback model(s), comma-separated |
| `--effort LEVEL` | Default reasoning effort (`low`, `medium`, `high`, `xhigh`, `max`) |
| `--permission-mode MODE` | Default permission mode (`acceptEdits`, `auto`, `bypassPermissions`, `manual`, `dontAsk`, `plan`) |
| `--dangerously-skip-permissions` | Bypass all permission checks by default |
| `--tools TOOLS` | Built-in tools to expose (`""` for none, `"default"`, or comma-separated names) |
| `--allowed-tools TOOL` | Tool rule to allow by default (repeatable) |
| `--disallowed-tools TOOL` | Tool rule to deny by default (repeatable) |
| `--add-dir DIR` | Additional directory Claude can access by default (repeatable) |
| `--agent NAME` | Default agent name |
| `--agents JSON_OR_PATH` | Default custom agents JSON object or file path |
| `--system-prompt TEXT` | Default system prompt override |
| `--append-system-prompt TEXT` | Default text appended to the system prompt |
| `--settings JSON_OR_PATH` | Default extra settings JSON object or file path |
| `--setting-sources SOURCES` | Comma-separated setting sources (`user,project,local`) |
| `--mcp-config JSON_OR_PATH` | Default MCP config file or JSON string (repeatable) |
| `--strict-mcp-config` | Only use MCP servers from `--mcp-config` by default |
| `--max-turns N` | Default maximum agentic turns per invocation |
| `--max-budget-usd AMOUNT` | Default maximum API budget in USD per invocation |
| `--disable-slash-commands` | Disable skills and slash commands by default |
| `--no-session-persistence` | Do not persist sessions to disk by default |
| `--bare` | Minimal headless mode (skip hooks, plugins, CLAUDE.md discovery, OAuth/keychain; API-key / provider auth only) |

Boolean server flags can be explicitly overridden to `false` on any individual tool call.

## MCP Resources

| URI | Description |
|-----|-------------|
| `claude-swarm:///server-info` | Version, capabilities, directories, CLI protocol contract |
| `claude-swarm:///config` | Current server-level CLI defaults |
| `claude-swarm:///models` | Available Claude Code model aliases, resolved IDs, and supported effort levels |
| `claude-swarm:///tasks` | All known tasks and their state, usage, tool errors, permission denials, and failure details |

## Environment variables

| Variable | Default | Description |
|----------|---------|-------------|
| `CLAUDE_SWARM_LOG` | `<user-runtime>/claude-swarm/claude_mcp_swarm.log` | Log file path |
| `CLAUDE_SWARM_LOG_LEVEL` | `WARNING` | Log level (`DEBUG`, `INFO`, `WARNING`, `ERROR`) |
| `CLAUDE_SWARM_TASK_DIR` | `<user-runtime>/claude-swarm/tasks` | Task output storage directory (owner-only `0700` when using default) |
| `CLAUDE_SWARM_WORKTREE_DIR` | `<user-cache>/claude-swarm/worktrees` | Worktree storage directory (owner-only `0700` when using default) |
| `CLAUDE_SWARM_TASK_MAX_AGE` | `86400` (24h) | Seconds after completion / last reply activity before task artifacts and worktrees are cleaned up |
| `CLAUDE_SWARM_MIN_WAIT` | `150` | Floor in seconds for `claude_wait` |
| `CLAUDE_SWARM_BIN` | _(auto)_ | Explicit path or command name for `claude` (auto-searches `PATH` and `~/.local/bin/claude`) |

## Requirements

- Python 3.8+
- Claude Code CLI (`claude`) installed and authenticated
- Only depends on stdlib-only [`mcp-swarm-core`](https://github.com/TKasperczyk/mcp-swarm-core) (no third-party packages)

## License

MIT
