swarm-mcp
Manages container lifecycle, resource scheduling, and networking for each agent, ensuring isolation and enabling GPU and resource semaphores.
Allows Claude agents to access Google Workspace services (Gmail, Drive, Calendar) via MCP, enabling email handling, file operations, and event management.
Allows Claude agents to access and interact with a Logseq knowledge graph via MCP, enabling reading, writing, and querying of pages and blocks.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@swarm-mcp run 3 code reviews in parallel and reduce them"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
swarm-mcp
Orchestrate parallel Claude agent workloads via Docker containers.
swarm-mcp is an MCP server that lets your Claude session spawn other Claude agents — each in an isolated Docker container — and compose their results using functional combinators. Instead of one agent doing everything, you describe the work as run, par, map, chain, reduce, and pipeline calls, and swarm-mcp handles container lifecycle, resource scheduling, and result plumbing. The agent outputs are lazy refs (metadata on the wire, text on disk) so you never blow up the MCP protocol with megabytes of agent output.
Why swarm-mcp?
True Docker isolation per agent. Every agent gets its own container with its own filesystem, network policy, memory limit, and CPU quota. No shared state leaks between agents. A rogue
rm -rf /in one container doesn't touch anything else.Lazy refs (metadata on the wire, text on disk). Combinators return refs — small JSON objects with metadata (cost, duration, exit code, provenance hash). The actual text stays on disk in
/tmp/swarm-mcp/{run_id}/{agent_id}/result.json. Callunwrapwhen you actually need the content. This keeps the MCP protocol fast and prevents context window bloat.Data-driven pipelines. The
pipelinetool interprets a JSON definition — steps withon_failhandlers,conditionguards,retry_ifloops, andnextjumps. The pipeline definition is data: store it in git, version it, resume it from any step, generate it programmatically. The interpreter handles container lifecycle, budget tracking, and inter-step state via a shared/shared/directory.GPU and resource semaphores. Named resource pools (
gpu,database,api, anything) are semaphores with configurable capacity. Agents queue for resources before execution. A single GPU doesn't get double-booked; a rate-limited API doesn't get hammered.Natural language type contracts with validation. Types are markdown files that describe what an agent should produce. The
validatetool spawns a validator agent that checks the output against the type definition.filterkeeps only results that pass.retryre-runs until the output validates. Types reference each other with[type-name]syntax.Agents can use your MCP servers. Set
mcps: ["database-mcp"]in a sandbox spec and the agent gets access to your local knowledge base, Logseq graph, Google Workspace, or any other MCP server configured in your Claude settings. Data paths are mounted into the container at the same host path; network MCPs need no extra config. See the MCP Access guide.Full artifact tracing. Every container runs a PostToolUse hook that logs MCP tool calls and file writes to
artifacts.jsonl.inspectgenerates a post-mortem debug report from any ref.unwrapextracts output to a file you canRead()orGrep. Every ref carries a provenance hash and parent chain.
Related MCP server: Orchestrator MCP Server
Architecture
flowchart TB
Claude["Claude Code<br/>(your session)"] -- "MCP" --> Server["swarm-mcp server<br/>run · par · map · chain · pipeline"]
Server --> Pools["Semaphore + Resource Pools<br/>SWARM_MAX_CONCURRENT · SWARM_RESOURCE_gpu"]
Pools --> Docker["Docker API"]
Docker --> C0["Container 0<br/>claude --model sonnet"]
Docker --> C1["Container 1<br/>claude --model opus"]
Docker --> CN["Container N<br/>claude --model haiku"]
C0 & C1 & CN --> Out[" /tmp/swarm-mcp/{run}/{agent}/<br/>result.json · stream.jsonl · artifacts.jsonl"]
Out -- "unwrap()" --> Text["output.md"]Ref flow
flowchart LR
A["run('Review code')"] --> R["ref: a1b2c3/agent-0<br/>exit_code: 0 · cost: $0.03<br/><i>metadata only — no text yet</i>"]
R -- "unwrap()" --> F["/tmp/.../output.md"]
R -- "inspect()" --> D["inspect.md<br/>debug report"]
R -- "reduce([r1,r2,r3])" --> S["synthesis ref"]Combinator composition
flowchart LR
P["par(3 tasks)"] --> R3["3 refs"]
R3 --> Re["reduce('Synthesise')"] --> Final["1 ref"] --> U["unwrap → text"]
M["map(template, 5 inputs)"] --> R5["5 refs"]
R5 --> Fi["filter('code-review')"] --> V["valid refs only"]Installation
Prerequisites
Docker — containers are the execution substrate
Claude Code CLI — with OAuth configured (
claude login)uv — Python package manager
Install
# Run directly
uvx mcp-swarm
# Or install as a tool
uv tool install mcp-swarmConfigure Claude Code
Add to your Claude settings (~/.claude.json or project .claude.json):
{
"mcpServers": {
"swarm": {
"command": "uvx",
"args": ["mcp-swarm"]
}
}
}Build the Docker image
The agent containers need a Docker image with Claude CLI and uv baked in. Clone the repo and build:
git clone https://github.com/stiege/swarm-mcp
cd swarm-mcp
docker build -t swarm-agent .The Dockerfile installs Claude Code CLI and uv from their official sources during the build — no binaries to copy. The image is based on Ubuntu 24.04 with git, Python 3, and jq. It auto-builds on first use if missing, but pre-building avoids the startup delay.
Quick Start
1. Single agent — code review
Use run to review this file:
run(
prompt: "Review the error handling in /workspace/src/api/auth.py. Flag any unhandled exceptions, missing input validation, or security issues. Be specific — line numbers and fix suggestions.",
model: "sonnet",
mounts: '[{"host_path": "/home/me/myproject", "container_path": "/workspace", "readonly": true}]',
tools: "Read,Glob,Grep"
)Returns a ref with metadata. Use unwrap on the ref to read the full review.
2. Parallel research — three topics at once
Use par to research these topics in parallel:
par(
tasks: '[
{"prompt": "Research the current state of WebTransport API browser support. What works, what doesn'\''t, what'\''s coming.", "model": "sonnet"},
{"prompt": "Research QUIC protocol performance characteristics vs TCP for real-time applications. Include benchmarks if available.", "model": "sonnet"},
{"prompt": "Research existing open-source WebTransport server implementations. Compare features, maturity, language.", "model": "sonnet"}
]',
max_concurrency: 3
)Three containers spin up simultaneously. Each gets its own network, filesystem, and execution context. Results come back as an array of refs with a summary showing succeeded/failed counts.
3. Pipeline — write, test, fix loop
Use pipeline to implement and test a feature:
pipeline(
definition: '{
"name": "implement-and-test",
"steps": [
{
"id": "implement",
"prompt": "Implement a rate limiter middleware for Express.js. Use a sliding window algorithm. Write to /shared/rate-limiter.js",
"model": "sonnet",
"tools": "Read,Write,Bash"
},
{
"id": "test",
"prompt": "Write tests for /shared/rate-limiter.js using Jest. Run them. Report pass/fail.",
"model": "sonnet",
"tools": "Read,Write,Bash",
"on_fail": "fix"
},
{
"id": "fix",
"prompt": "Fix the failing tests. Read the error output and fix either the implementation or the tests.",
"model": "sonnet",
"tools": "Read,Write,Bash",
"condition": "prev.error",
"next": "test",
"max_retries": 3
}
]
}'
)The pipeline writes code in step 1, tests it in step 2, and if tests fail, loops through the fix step up to 3 times. All steps share the /shared/ directory for file passing.
Combinators Reference
Execution
Combinator | Pattern | Use when |
| 1 prompt → 1 ref | Single agent task. The fundamental unit. |
| N prompts → N refs | Independent tasks that can run simultaneously. |
| 1 template + N inputs → N refs | Same operation applied to many inputs (fan-out). |
| N prompts → 1 final ref (sequential) | Each step needs the previous step's output as context. |
| N refs + synthesis prompt → 1 ref | Combine multiple results into a single synthesis. |
| map + reduce in one call | Fan-out then synthesize — no manual plumbing. |
Control Flow
Combinator | Pattern | Use when |
| N refs + type → valid refs | Keep only results that match a declared type. |
| N prompts → 1 winner ref | Multiple strategies, take the first success. |
| 1 prompt + max_attempts → 1 ref | Flaky task that may need multiple tries. Optionally validates against a type. |
| 1 ref + check → ref or error | Enforce constraints (validated, budget, classification, encrypted, exists) before passing downstream. |
| JSON definition → execution trace | Multi-step workflow with conditions, retries, on_fail handlers, and budget/deadline tracking. |
Observation
Tool | Pattern | Use when |
| ref → file path | You need the actual text content. Writes to |
| ref → debug report | Post-mortem on a failed or slow agent. Shows tool calls, stream log, artifacts. |
Security
Tool | Pattern | Use when |
| ref → encrypted ref + key_id | Protect sensitive output at rest. Metadata stays readable; text is Fernet-encrypted on disk. |
| encrypted ref + key_id → file path | Decrypt with the right key. Writes plaintext to |
| ref + level → classified ref | Tag data sensitivity (public/internal/confidential/restricted). Controls which MCPs can access. |
Types
Tool | Pattern | Use when |
| → list of types | See what types are defined. |
| name → markdown content | Read a type definition, with [references] resolved. |
| artifact + type → VALID/PARTIAL/INVALID | Check if an agent's output matches a declared type. |
Configuration
Tool | Pattern | Use when |
| name + JSON → saved | Create a reusable sandbox configuration. |
| → list of specs | See saved sandboxes. |
| file path → ref | Bring an external file/directory into the ref system. |
| project dir → registered resources | Register a project's pipelines/, sandboxes/, types/ directories. |
Sandbox Configuration
A sandbox spec defines the environment for an agent container. Use inline on any combinator, or save with save_sandbox_spec for reuse.
Field | Type | Default | Description |
| string |
| Claude model: |
| list[string] |
| Allowed Claude tools |
| list[string] |
| MCP servers to attach (by name from host |
| string |
| System prompt injected via |
| string |
| Written to workspace |
| dict |
| JSON schema for structured output ( |
| string |
| Effort level: |
| float |
| USD budget cap for the agent |
| string |
| Natural language type describing agent input |
| string |
| Natural language type describing expected output |
| list[dict] |
| Volume mounts: |
| string |
| Container working directory |
| dict |
| Files to inject: |
| bool |
| Network access (needed for Anthropic API) |
| string |
| Docker memory limit (e.g. |
| float |
| Docker CPU limit (e.g. |
| bool |
| Pass |
| list[string] |
| Named resource pools to acquire (e.g. |
| int |
| Max execution time in seconds (30 min default) |
| dict |
| Environment variables: |
Complete example
{
"model": "sonnet",
"tools": ["Read", "Write", "Glob", "Grep", "Bash"],
"system_prompt": "You are a senior backend engineer. Write production-quality Go code.",
"claude_md": "# Project\nThis is a Go microservice using chi router and pgx for Postgres.",
"mounts": [
{"host_path": "/home/me/myservice", "container_path": "/workspace", "readonly": false}
],
"mcps": ["database-mcp"],
"memory": "4g",
"cpus": 2.0,
"timeout": 600,
"effort": "high",
"env_vars": {"GOPATH": "/home/ubuntu/go"},
"output_type": "[go-module]"
}Save it:
save_sandbox_spec(name: "go-backend", spec: '<the JSON above>')Then use it anywhere:
run(prompt: "Add pagination to the /users endpoint", sandbox: "go-backend")
par(tasks: '[{"prompt": "...", "sandbox": "go-backend"}, ...]')Pipelines
A pipeline definition is a program expressed as data. The pipeline tool is the interpreter. You describe what should happen — steps, control flow, error handling — and the interpreter evaluates it, managing shared state and resource budgets.
The key property: the definition is a JSON value you can store, version, share, resume, and generate. It does nothing on its own. The interpreter handles all effects: spawning containers, tracking costs, enforcing deadlines, and routing control flow.
Complete pipeline example
{
"name": "research-and-report",
"budget": 2.00,
"deadline_seconds": 1800,
"classification": "internal",
"steps": [
{
"id": "gather",
"prompt": "Research the top 5 Rust web frameworks by GitHub stars. For each, note: name, stars, last commit date, key features. Write a JSON summary to /shared/frameworks.json",
"model": "sonnet",
"tools": "Read,Write,Bash"
},
{
"id": "benchmark",
"prompt": "Read /shared/frameworks.json. For each framework, find or estimate request throughput benchmarks. Write results to /shared/benchmarks.json",
"model": "sonnet",
"tools": "Read,Write,Bash"
},
{
"id": "draft",
"prompt": "Read /shared/frameworks.json and /shared/benchmarks.json. Write a comparative analysis report to /shared/report.md. Include a recommendation.",
"model": "opus",
"tools": "Read,Write",
"on_fail": "fix-draft"
},
{
"id": "fix-draft",
"prompt": "The report draft failed. Read the error, fix the issues, and rewrite /shared/report.md",
"model": "sonnet",
"tools": "Read,Write",
"condition": "prev.error",
"next": "review",
"max_retries": 2
},
{
"id": "review",
"prompt": "Read /shared/report.md. Check for factual accuracy, missing data, and unclear recommendations. Write feedback to /shared/review.md. If the report is good, just write 'APPROVED'.",
"model": "opus",
"tools": "Read,Write",
"retry_if": {"draft": "NEEDS_REVISION"}
}
]
}Step fields
Field | Type | Description |
| string | Step identifier (used by |
| string | The task prompt. Previous step's output is appended as context automatically. |
| string | dict | Step ID to jump to on failure, or |
| dict |
|
| string | Step ID to jump to after success (instead of next sequential step). |
| string |
|
| int | Max times this step can be entered via |
| dict |
|
+ any sandbox field |
|
Pipeline-level fields
Field | Type | Description |
| string | Pipeline name (optional). |
| string | Default sandbox spec applied to all steps. |
| float | Total USD budget. Pipeline stops if exceeded. |
| int | Wall-clock deadline. Pipeline stops if exceeded. |
| string | Default data classification for the run. |
| dict | Inline governor specs keyed by name. Per-project, version-controlled alongside the pipeline. |
Pipeline status
The pipeline tool returns a status field: "done" (all steps completed) or "broken" (last result had an error, or a governor returned broken). A broken_reason field is included when applicable. Broken pipelines can be inspected via pipeline_status.
The /shared/ directory
Every step in a pipeline gets /shared/ mounted read-write. This is the inter-step communication channel. Step 1 writes /shared/data.json, step 2 reads it. No ref passing needed — just files.
Resuming
pipeline(definition: "research-and-report", resume: "a1b2c3d4e5f6")
pipeline(definition: "research-and-report", resume: "a1b2c3d4e5f6/benchmark")resume: "run_id"— reuses the shared directory from a previous run, starts from step 0.resume: "run_id/step_id"— skips to the named step, previous artifacts available in/shared/.
Governors
Governors are LLM-powered control-flow hooks evaluated at pipeline trigger points (on_fail, on_success). They replace hardcoded fallback logic with natural language policy — a Claude model reads the live pipeline state and decides what happens next.
Unlike the stamp layer (stamps.py — provenance, cost, classification, encryption), governors are about control flow.
Continuation algebra
Every governor returns one of five actions:
Action | Effect |
| Proceed to the next step normally |
| Jump to a named step ( |
| Stop the pipeline cleanly (status: |
| Stop and mark pipeline as broken with a |
| Deep-merge patch the pipeline definition, then continue |
The context dict is free-form, accumulates across the pipeline, and is written to /shared/governor-context.json after each evaluation so steps can read it.
Inline pipeline governors
Define governors directly in the pipeline JSON — version-controlled alongside the pipeline, no global registration needed:
{
"name": "train-loop",
"governors": {
"TrainingFailure": {
"description": "Governs QLoRA train step failures",
"model": "claude-haiku-4-5-20251001",
"spec": "You govern the train step of a QLoRA fine-tuning pipeline. OOM errors → broken. NaN/loss divergence → broken. Transient errors (disk, timeout) → jump to the step before train to retry data preparation. Inspect exit_code and error output."
},
"QualityGate": {
"description": "Decides whether the current model iteration is good enough",
"model": "claude-haiku-4-5-20251001",
"spec": "You govern the evaluation step. If the pass rate is 5/5, return halt (we're done). If 3-4/5, jump to the training step for another iteration. If 0-2/5, return broken — the model is not converging."
}
},
"steps": [
{"id": "train", "prompt": "...", "on_fail": {"governor": "TrainingFailure"}},
{"id": "evaluate", "prompt": "...", "on_success": {"governor": "QualityGate"}}
]
}Global fallback: ~/.claude/governors/ (managed by save_governor_spec / list_governor_specs). Inline definitions take priority over global ones.
The patch_pipeline action
A governor can surgically modify the running pipeline definition. This uses JSON Merge Patch (RFC 7396) — null values delete keys, objects recurse, scalars/arrays replace:
{
"action": "patch_pipeline",
"pipeline_patch": {
"steps": [
{"id": "train", "prompt": "Run training with --batch-size 4 instead of 8"}
]
},
"context": {"adjusted_batch_size": true},
"reason": "Detected instability in loss curve — reducing batch size"
}governor_context
The context dict from each governor continuation is merged into a running governor_context that persists across the entire pipeline. Written to /shared/governor-context.json so steps can read it. Use it to pass structured observations between governors (e.g., iteration count, last loss value, retry history).
Type System
Types are natural language specifications stored as markdown files in a types/ directory. They describe what something is, what it should contain, and how to verify it.
Defining a type
Create types/code-review.md:
A code review document that covers:
1. **Summary** — one paragraph describing what the code does
2. **Issues** — numbered list of problems found, each with:
- Severity (critical / warning / nit)
- File and line number
- Description of the problem
- Suggested fix
3. **Security** — specific section for security concerns (XSS, injection, auth)
4. **Testing** — assessment of test coverage and suggestions
## Verification
- Has a Summary section
- Has at least one numbered issue with severity, location, and fix
- Has a Security section (even if "no issues found")
- Has a Testing sectionUsing types
Set input_type or output_type on any combinator to inject type context into the agent's prompt:
run(
prompt: "Review the auth module",
output_type: "code-review",
mounts: '[{"host_path": "/home/me/project", "container_path": "/workspace", "readonly": true}]'
)Validating
validate(artifact: '{"ref": "a1b2c3/agent-0"}', declared_type: "code-review")Returns VALID, PARTIAL, or INVALID with per-criterion results.
Type references
Types can reference other types with [type-name] syntax:
# types/api-server.md
A REST API server that includes:
- Route handlers with input validation
- Error handling middleware
- [test-suite] with integration tests
- [dockerfile] for containerized deploymentReferences are resolved recursively (up to depth 3). Each referenced type is inlined once; subsequent references become "(see above)".
Registering types
wrap_project(project_dir: "/home/me/myproject")This registers myproject/types/, myproject/sandboxes/, and myproject/pipelines/ as search paths. Types in the project take priority over global types in ~/.claude/types/.
Resource Pools & GPU
GPU access
run(
prompt: "Fine-tune the sentiment classifier on the new dataset",
gpu: true,
mounts: '[{"host_path": "/data/models", "container_path": "/models", "readonly": false}]'
)Setting gpu: true does two things:
Passes
--gpus allto the Docker containerAcquires the
"gpu"resource pool (capacity 1 by default)
If another agent is using the GPU, this one queues until the resource is free.
Named resource pools
Any string in the resources array becomes a semaphore. Configure capacity with environment variables:
# One GPU at a time (default)
export SWARM_RESOURCE_gpu=1
# Up to 3 concurrent database connections
export SWARM_RESOURCE_database=3
# Rate-limit external API access to 5 concurrent agents
export SWARM_RESOURCE_api=5Use in a run call:
run(
prompt: "Query the production database for user analytics",
resources: '["database"]',
mcps: '["database-mcp"]'
)Queue semantics
Resource acquisition uses a separate timeout (SWARM_QUEUE_TIMEOUT, default 1 hour) from execution timeout. An agent waiting 10 minutes for a GPU still gets its full execution time once the GPU is available. The global concurrency limit (SWARM_MAX_CONCURRENT) is acquired first, then named resources.
Observability
unwrap — extract text to file
unwrap(ref: "a1b2c3/agent-0")Writes the agent's full text output to /tmp/swarm-mcp/a1b2c3/agent-0/output.md and returns the path and size. Use Read() to view it. This is how you go from a lazy ref to actual content.
inspect — post-mortem debug
inspect(ref: "a1b2c3/agent-0")Generates a debug report at inspect.md containing:
Result metadata (exit code, error, duration, cost)
Output text (first 2000 chars)
Stream log summary (tool calls made, thinking steps)
Artifacts logged by the PostToolUse hook
Files in the output directory
Artifact tracing
Every agent container runs a PostToolUse hook (hooks/log-artifacts.sh) that captures MCP tool calls and file writes to /output/artifacts.jsonl. Each entry records:
{
"timestamp": "2025-01-15T10:30:00Z",
"tool": "Write",
"tool_use_id": "toolu_abc123",
"input": {"file_path": "/workspace/src/main.py", "content": "..."},
"response": {"success": true}
}This gives you a complete audit trail of what every agent did inside its container.
Encrypted refs
The encrypt / decrypt flow protects sensitive outputs at rest:
run(prompt: "Extract PII from the uploaded documents")
│
▼
encrypt(ref: "a1b2c3/agent-0")
│
▼
{ "ref": "a1b2c3/agent-0", ◄── metadata visible
"key_id": "f9e8d7c6b5a4", ◄── needed to decrypt
"encrypted": { ◄── text is Fernet-encrypted on disk
"key_id": "f9e8d7c6b5a4",
"algorithm": "fernet"
}}
│
├── unwrap() ──► ERROR: "Ref is encrypted. Use decrypt tool."
│
└── decrypt(ref: "a1b2c3/agent-0", key_id: "f9e8d7c6b5a4") ──► output.mdThe key is stored in /tmp/swarm-mcp/.keys/ with 0600 permissions. Only processes with the key_id can access the plaintext. The ciphertext stays in result.json — decrypt writes the plaintext to a separate output.md without replacing the encrypted copy.
Classification flow
classify(ref: "a1b2c3/agent-0", level: "confidential", denied_mcps: '["whatsapp", "slack"]')
│
▼
guard(ref: '<classified ref>', check: "classification", value: '["slack"]')
│
▼
ERROR: "MCP 'slack' denied for classification 'confidential'"Classification levels: public (0) → internal (1) → confidential (2) → restricted (3). Use guard with the "classification" check to enforce data flow policies before passing refs to downstream agents with MCP access.
On-Disk Layout
Every agent execution produces a directory under /tmp/swarm-mcp/:
/tmp/swarm-mcp/
└── a1b2c3d4e5f6/ ← run_id
├── agent-0/ ← agent_id
│ ├── result.json ← full output + metadata
│ ├── stream.jsonl ← raw stream-json from claude
│ ├── artifacts.jsonl ← PostToolUse hook log
│ ├── output.md ← created by unwrap()
│ ├── inspect.md ← created by inspect()
│ ├── prompt.txt ← the prompt sent to the agent
│ ├── home/ ← staged HOME dir mounted into container
│ │ ├── .claude/ ← claude config + settings + hooks
│ │ └── .claude.json ← oauth + mcp config
│ └── workspace/ ← mounted as /workspace in container
│ └── CLAUDE.md ← injected from sandbox spec
├── agent-1/
│ └── ...
└── shared/ ← pipeline shared directory (/shared/ in containers)
├── data.json
└── report.mdEnvironment Variables
Variable | Default | Description |
|
| Maximum agents running simultaneously across all combinators. |
|
| Seconds an agent will wait in the queue for an execution slot or resource pool. |
|
| Capacity of a named resource pool. e.g. |
| unset | Project root containing |
Contributing
See CONTRIBUTING.md.
License
MIT
Available Tools
33 toolsbeamA
Sample N candidates in parallel, score each, commit to the top-1.
The simplest search combinator: proposes width candidates via par,
scores each with a cheap haiku evaluator, and returns the highest-scoring
ref. Losing candidates are preserved on the winner's search.alternatives
field (unless keep_losers is false). This is self-consistency /
majority-vote with arbitrary scoring — the same shape as the governor
beam search, but applied to arbitrary agent output.
Evaluator forms:
score:<criterion>— direct haiku call, returns a float in [0, 1] plus a reason string. Use for rubric-style scoring.validate:<type>— runs the type validator; VALID=1.0, PARTIAL=0.5, INVALID=0.0. Use when the acceptance criterion is a registered type.
Budget semantics: a hard cap on total proposer spend. If exceeded, the
winner's search stamp records prune_reason="budget exhausted" but the
result is still returned — best-effort rather than abort. Evaluator cost
is not counted against budget for phase 1; evaluators are already
constrained to haiku.
Anti-pattern: the Tree Search paper flags evaluator-as-expensive-as-proposer as a non-starter. This combinator hardcodes haiku for scoring — if you need a stronger evaluator, lift that logic into a governor instead.
Args:
prompt: Task prompt sent to every candidate agent.
width: Number of parallel candidates (default: 3).
evaluator: Scoring directive. Must start with score: or validate:.
sandbox: Named sandbox spec or inline JSON for candidate agents.
model: Candidate agent model (default: sonnet — the proposer).
timeout: Per-candidate timeout in seconds.
mcps: JSON array of MCP server names attached to candidates.
keep_losers: Preserve losing candidates on winner search stamp
(default: true — useful for inspection + future step-lookahead).
budget: Total USD cap on proposer cost. Best-so-far semantics on breach.
max_concurrency: Upper bound on concurrent candidate agents.
Returns:
JSON with run_id, winner ref (search-stamped), scores, and
total_cost. If all candidates scored 0, error is populated.
Inputs: prompt (required), width, evaluator, sandbox, +6 more. Returns: result
chainA
Run agents sequentially as a pipeline. Each stage receives the prior stage's output as context.
Args: stages: JSON array of stage objects. Each supports all sandbox fields (prompt, model, tools, sandbox, system_prompt, etc.).
Inputs: stages (required). Returns: result
classifyA
Set the classification level on a ref. Controls which MCPs can access the data.
Use for data sensitivity enforcement — e.g. mark original legal documents as 'confidential' (no WhatsApp MCP), mark synthetic outputs as 'public'.
Args: ref: A ref string or JSON object. level: Classification level: public, internal, confidential, restricted. allowed_mcps: JSON array of MCP names allowed to access this ref. denied_mcps: JSON array of MCP names denied access.
Inputs: ref (required), level (required), allowed_mcps, denied_mcps. Returns: result
decryptA
Decrypt an encrypted ref's text. Writes the plaintext to output.md and returns the path.
You need the key_id that was returned when the ref was encrypted.
Args: ref: A ref string like "run_id/agent_id", or a JSON object with a "ref" field. key_id: The key ID returned by the encrypt tool.
Inputs: ref (required), key_id (required). Returns: result
encryptA
Encrypt a ref's text payload. Returns the ref with a key_id — only callers with the key can decrypt.
The ref metadata (provenance, classification, etc.) stays visible; only the text content is encrypted. Pass the key_id to specific agents or features that should be able to read the content.
Args: ref: A ref string like "run_id/agent_id", or a JSON object with a "ref" field.
Inputs: ref (required). Returns: result
filterA
Filter refs by type validation — keep only results that match the declared type.
Runs validate on each ref in parallel. Returns only refs with VALID verdict. This is the type-gated composition primitive: ensures only correct results flow downstream.
Args: refs: JSON array of ref objects: [{"ref": "run_id/agent_id"}, ...]. declared_type: Type name or description to validate against. model: Model for the validator agents (default: sonnet). timeout: Timeout per validation (default: 120).
Inputs: refs (required), declared_type (required), model, timeout. Returns: result
get_type_definitionA
Get a type definition by name, optionally resolving [references] to other types.
Args: name: Type name (e.g. "mcp-server", "tarball", "code-review"). resolve_refs: Whether to inline [referenced] types (default: true).
Inputs: name (required), resolve_refs. Returns: result
guardA
Check a monadic condition on a ref. Returns the ref if the guard passes, error if not.
Use to enforce constraints before passing refs to downstream combinators.
Args: ref: A ref string or JSON object. check: The guard to check — one of: "validated", "budget", "classification", "encrypted", "exists". value: Required for some checks — e.g. the type name for "validated", the classification level for "classification".
Inputs: ref (required), check (required), value. Returns: result
huntA
Run multiple (fetch → map → score) hunt strategies in parallel and merge.
Each strategy is an independent (fetch, plan, score) triple with its own seed prompt or explicit seeds, plan template, and rubric. Strategies run concurrently; a failure in one does not halt the others. All scored refs across all strategies are merged into a single globally-ranked leaderboard so you can see which strategy produced the highest-yield finding.
This is the compound combinator that makes "run all the hunt framings at once" tractable — rather than sequentially trying one hunt shape at a time, you parallelise across framings (problem-driven, gap-in-field, broken-claims, tool-landscape, connection) and let the scoring sort them.
Strategy dict fields:
name(required) — short label used for tagging and per-strategy reporting in the leaderboard.seeds(optional) — pre-supplied list of seed strings (each becomes a map input). Exactly one ofseedsorfetcher_promptmust be set.fetcher_prompt(optional) — prompt sent to a singleruncall that must emit a JSON array of seed strings (or a JSON object with aseedskey). The agent runs with network enabled.planner_template(required) — prompt template for the map step. Use{input}as the placeholder for each seed.rubric(required) — evaluator directive for the score step. Any form accepted by_evaluate_node:validate:<type>,score:<criterion>, orexec:<cmd>.top_k(optional, default 3) — how many winners this strategy contributes to the unified leaderboard.model_planner(optional, default "haiku") — model for the map step.model_fetcher(optional, default "haiku") — model for the fetch step.timeout(optional) — per-agent timeout in seconds.
Args: strategies: JSON array of strategy dicts (or a Python list). max_parallel_strategies: Upper bound on strategies running at once (default: 5). Each strategy internally parallelises its map step. top_k_global: Size of the unified leaderboard across all strategies (default: 10).
Returns:
JSON with run_id, strategies (per-strategy summary including
name, error-if-any, total_cost, winner_ref, best_score), and
leaderboard (globally-ranked list tagged by strategy). The full
per-ref scoring trace lives at strategy_details[i].ranked.
Inputs: strategies (required), max_parallel_strategies, top_k_global. Returns: result
inspectA
Inspect an agent's full execution state — partial output, stream log, files produced.
Use after a timeout, crash, or unexpected result to understand what happened. Writes a human-readable debug report to output_dir/inspect.md.
Args: ref: A ref string like "run_id/agent_id".
Inputs: ref (required). Returns: result
iterateA
Iteratively refine an agent's output until an evaluator is satisfied.
Runs the agent up to max_iterations times. Each iteration sees the
prior attempts' outputs, scores, and issues injected into its prompt, so
the agent can correct the specific shortcomings the evaluator called out
on the last pass. Halts when any of these become true:
Evaluator score >=
success_threshold(success).patienceiterations pass with no improvement to the best score.Total agent cost exceeds
max_budget(best-so-far).Wall-time exceeds
max_wall_timeseconds (best-so-far).max_iterationsreached (best-so-far).
Evaluator forms (pass exactly one of target_type or evaluator):
target_type="some-type"— shorthand forevaluator="validate:some-type". LLM validator against a registered type. Best for text artifacts whose correctness is a matter of shape and content.evaluator="validate:<type>"— explicit form of the above.evaluator="exec:<shell cmd>"— ground-truth executor. The agent's output is written to a tempfile and the command runs with$ARTIFACTset to the path (and{artifact}substituted in the template). Exit 0 scores 1.0; non-zero scores 0.0 with stderr parsed into issues. Use for artifacts with compile/build/test semantics (docker build,pytest, etc.) — this is the only way to get ground-truth feedback.evaluator="score:<criterion>"— ad-hoc LLM rubric scoring via haiku.
Args:
prompt: Base task description sent to the agent on iteration 1; on
subsequent iterations it is augmented with a "Prior attempts"
section summarising previous outputs, scores, and issues.
target_type: Shorthand for evaluator="validate:<target_type>". Also
injects the type as output_type context on the agent prompt.
evaluator: Full evaluator directive (validate:, exec:, or
score:). Takes precedence over target_type if both given.
max_iterations: Hard cap on iteration count (default: 10).
success_threshold: Score at or above which we declare success
(default: 0.9). Must be in [0.0, 1.0].
patience: Halt if patience consecutive iterations fail to improve
on the best score so far (default: 3).
max_budget: Optional USD cap on total agent (proposer) cost. Evaluator
cost is not counted. Halts best-so-far on breach.
max_wall_time: Optional wall-time cap in seconds. Halts best-so-far
on breach.
sandbox: Named sandbox spec or inline JSON for the agent.
model: Agent (proposer) model (default: sonnet).
timeout: Per-iteration agent timeout in seconds.
mcps: JSON array of MCP server names attached to the agent.
Returns:
JSON with run_id, iterations, halted_because,
best_iteration, best_ref (validated-stamped), best_score,
total_cost, and the full attempts trace with per-iteration
ref / score / issues / cost.
Inputs: prompt (required), target_type, evaluator, max_iterations, +8 more. Returns: result
list_governor_specsA
List all registered LLM-governed governors.
Returns each governor's name, description, model, and a preview of its spec.
Inputs: no named parameters. Returns: result
list_pipelinesA
List recent pipeline runs and their current status.
Scans /tmp/swarm-mcp/ for pipeline-status.json files and returns a summary of all known runs, sorted by last_updated descending. Also annotates which runs have live threads in the current process.
Inputs: no named parameters. Returns: result
list_sandbox_specsA
List all saved sandbox specs from ~/.claude/sandboxes/.
Inputs: no named parameters. Returns: result
list_type_registryA
List all registered types from ~/.claude/types/.
Inputs: no named parameters. Returns: result
mapA
Apply a prompt template to each input in parallel. Use {input} as the placeholder.
Args: prompt_template: Prompt template with {input} placeholder(s). inputs: JSON array of input strings: ["input1", "input2", ...]. sandbox: Named sandbox spec or inline JSON. network: Whether containers have network access (default: true — needed for API calls). tools: Comma-separated list of allowed Claude tools. model: Claude model to use (default: sonnet). timeout: Max execution time per agent in seconds (default: 120). max_concurrency: Max agents running simultaneously (default: 5). system_prompt: System prompt injected via --system-prompt. claude_md: Project instructions written to workspace CLAUDE.md. output_schema: JSON schema string for structured output. mcps: JSON array of MCP server names to attach. effort: Effort level: low, medium, high, max.
Inputs: prompt_template (required), inputs (required), sandbox, network, +9 more. Returns: result
map_reduceA
Map a prompt over inputs in parallel, then reduce results into one — all in a single call. Fan-out then synthesise: map produces N results, reduce consumes them, no manual plumbing.
Args: prompt_template: Prompt template with {input} placeholder(s). inputs: JSON array of input strings: ["input1", "input2", ...]. synthesis_prompt: Instructions for how to synthesise the map results. sandbox: Named sandbox spec or inline JSON (used for map agents). network: Whether containers have network access (default: true — needed for API calls). tools: Comma-separated list of allowed Claude tools for map agents. model: Claude model for map agents (default: sonnet). reduce_model: Claude model for the reduce agent (default: same as model). timeout: Max execution time per agent in seconds (default: 120). max_concurrency: Max map agents running simultaneously (default: 5). system_prompt: System prompt for map agents. reduce_system_prompt: System prompt for the reduce agent. output_schema: JSON schema for structured reduce output. mcps: JSON array of MCP server names for map agents. effort: Effort level for map agents.
Inputs: prompt_template (required), inputs (required), synthesis_prompt (required), sandbox, +11 more. Returns: result
parA
Run multiple Claude agents in parallel. Each task can have its own config.
Args: tasks: JSON array of task objects. Each supports all sandbox fields (prompt, model, tools, sandbox, system_prompt, claude_md, output_schema, mcps, effort, etc.). max_concurrency: Max agents running simultaneously (default: 5).
Inputs: tasks (required), max_concurrency. Returns: result
pipelineA
Launch a pipeline in the background and return immediately.
The pipeline runs asynchronously in a daemon thread. Use pipeline_status(run_id) to poll progress, and pipeline_kill(run_id) to stop it.
The definition is a JSON object or a pipeline name (loaded from registered project pipelines/ directories or ~/.claude/pipelines/).
Pipeline format: { "name": "optional-name", "sandbox": "optional-default-sandbox", "steps": [ {"id": "step-0", "prompt": "...", "model": "sonnet", "sandbox": "...", ...}, {"id": "test", "prompt": "Run tests", "tools": "Bash", "on_fail": "fix"}, {"id": "fix", "prompt": "Fix failing tests", "tools": "Read,Edit,Bash", "condition": "prev.error", "next": "test", "max_retries": 3} ] }
Step fields: prompt (required), plus any sandbox fields (model, tools, system_prompt, etc.). Control flow: on_fail (step id to jump to on error, or {"governor": "name"} for LLM-governed recovery — see save_governor_spec), on_success ({"governor": "name"} for LLM-governed continuation), next (jump after success), condition ("prev.error" = only run if previous failed), max_retries, retry_if ({target_step: keyword} — jump if output contains keyword). Any unhandled failure terminates the pipeline with status="broken".
Args: definition: Pipeline name (loaded from ~/.claude/pipelines/.json) or inline JSON definition. resume: Resume a previous run. Format: "run_id" or "run_id/step_id". Reuses the shared directory from the previous run. If step_id is given, skips to that step. If only run_id, resumes from the step that failed.
Inputs: definition (required), resume. Returns: result
pipeline_artifactsA
List artifacts produced by a pipeline run.
Without step_id: lists the /shared/ directory contents (inter-step files) plus a summary of each step's output directory.
With step_id: lists that specific step's output directory in detail, including file sizes. Use unwrap(ref) or Read() to view file contents.
Args: run_id: The pipeline run ID. step_id: Optional step ID to inspect. If omitted, lists shared/ and all steps.
Inputs: run_id (required), step_id. Returns: result
pipeline_killA
Kill a running pipeline and all its Docker containers.
Sets the pipeline's stop event (so the loop exits cleanly after the current step) and immediately kills all Docker containers associated with the run.
Args: run_id: The pipeline run ID to kill.
Inputs: run_id (required). Returns: result
pipeline_statusA
Return the current status of a running or completed pipeline.
Reads /tmp/swarm-mcp/<run_id>/pipeline-status.json and returns its contents. The status file is written after each step completes.
Args: run_id: The pipeline run ID returned by the pipeline() tool.
Inputs: run_id (required). Returns: result
raceA
Run multiple approaches in parallel, return the first to succeed.
All tasks start simultaneously. As soon as one completes without error, its ref is returned. Remaining tasks are abandoned (their containers are killed). Use for speculative execution or when multiple strategies might work.
Args: tasks: JSON array of task objects (same format as par). max_concurrency: Max agents running simultaneously (default: 5).
Inputs: tasks (required), max_concurrency. Returns: result
reduceA
Synthesise multiple results into one. Accepts plain strings or structured AgentResult objects (auto-extracts .text fields), so you can pipe par/map output directly without manual unwrapping.
Args: results: JSON array — either plain strings ["text1", "text2"] or AgentResult objects [{"text": "...", ...}]. synthesis_prompt: Instructions for how to synthesise the results. sandbox: Named sandbox spec or inline JSON. network: Whether the container has network access (default: true — needed for API calls). tools: Comma-separated list of allowed Claude tools. model: Claude model to use (default: sonnet). timeout: Max execution time in seconds (default: 120). mcps: JSON array of MCP server names to attach to the reducer agent. system_prompt: System prompt for the reducer agent.
Inputs: results (required), synthesis_prompt (required), sandbox, network, +5 more. Returns: result
retryA
Run a single agent with automatic retries on failure.
If declared_type is set, retries until the output validates as that type (not just until exit code 0). Each attempt receives the prior error as context.
Args: prompt: The task prompt. max_attempts: Maximum number of attempts (default: 3). sandbox: Named sandbox spec or inline JSON. model: Claude model (default: sonnet). timeout: Timeout per attempt (default: 120). declared_type: If set, validates output and retries if not VALID. mcps: JSON array of MCP server names to attach.
Inputs: prompt (required), max_attempts, sandbox, model, +3 more. Returns: result
runA
Run a single Claude agent in a Docker container. Returns the agent's text output and metadata.
Args: prompt: The task prompt for the agent. sandbox: Named sandbox spec (from ~/.claude/sandboxes/) or inline JSON. Overrides below are merged on top. network: Whether the container has network access (default: true — needed for API calls). tools: Comma-separated list of allowed Claude tools (default: Read,Write,Glob,Grep,Bash). mounts: JSON array of mount specs: [{"host_path": "...", "container_path": "...", "readonly": true}]. model: Claude model to use (default: sonnet). Options: haiku, sonnet, opus. timeout: Max execution time in seconds (default: 120). system_prompt: System prompt injected via --system-prompt (role, persona, instructions). claude_md: Project instructions written to workspace CLAUDE.md. output_schema: JSON schema string for structured output (--json-schema). mcps: JSON array of MCP server names to attach: ["database-mcp", "whatsapp"]. effort: Effort level: low, medium, high, max. max_budget: Explicit USD budget cap. env_vars: JSON object of environment variables: {"KEY": "value"}. input_files: JSON object of files to inject: {"/path": "content"}. memory: Docker memory limit (e.g. "2g"). cpus: Docker CPU limit (e.g. 2.0). gpu: Pass --gpus all to Docker for GPU access (default: false). Acquires the "gpu" resource pool (capacity 1). resources: JSON array of named resource pools to acquire before execution (e.g. '["gpu", "database"]'). Agents wait for all resources. Configure capacity via SWARM_RESOURCE_= env vars. input_type: Natural language type describing what the agent receives (e.g. "research notes", "[code-review]"). output_type: Natural language type describing what the agent must produce (e.g. "[mcp-server] with [test-suite]").
Inputs: prompt (required), sandbox, network, tools, +17 more. Returns: result
save_governor_specA
Register an LLM-governed governor for use in pipeline control flow.
Governors are evaluated at trigger points (on_fail, on_success) to decide the continuation. The spec is a natural language description of what the governor should decide. The governor LLM returns one of:
next — proceed normally
jump(target) — jump to a named step
halt — stop the pipeline cleanly
broken(reason) — stop and write broken status (visible via pipeline_status)
patch_pipeline — deep-merge patch the pipeline definition and continue
Each continuation also carries a free-form context dict that accumulates
across the pipeline and is written to /shared/governor-context.json, plus a
confidence score in [0.0, 1.0].
Reference a governor in a pipeline step: "on_fail": {"governor": "Failure"} "on_success": {"governor": "Validation"}
Args:
name: Unique governor name used to reference it from pipeline steps.
spec: Natural language description telling the LLM what to decide.
description: One-line summary shown in list_governor_specs.
model: Claude model for evaluation (default: haiku).
beam_width: Self-consistency beam width. When >1 the harness samples the
governor N times in parallel and commits to the confidence-weighted
majority decision. Losing candidates are preserved on the winner's
alternatives field for inspection. Default 1 (no beam).
Inputs: name (required), spec (required), description, model, +1 more. Returns: result
save_sandbox_specA
Save a reusable sandbox spec to ~/.claude/sandboxes/.json.
Args: name: Name for the sandbox spec (e.g. "web-researcher", "code-reviewer"). spec: JSON object with sandbox fields: model, tools, mcps, system_prompt, claude_md, output_schema, effort, max_budget, mounts, workdir, input_files, network, memory, cpus, timeout, env_vars.
Inputs: name (required), spec (required). Returns: result
score_listA
Score and rank a list of existing refs against an evaluator.
This is the missing piece for "generate N candidates, then pick the best"
pipelines where the N candidates already exist as refs from an upstream
combinator (map, par, etc.) — beam is the wrong shape because
it fans out width-N proposers of the same prompt, whereas score_list
takes N different outputs and ranks them.
The key infrastructure point: refs are resolved to their artifact text
server-side, so callers do not need to pipe full artifact text
through tool parameters. This clears the ~4KB param-size wall you would
otherwise hit scoring 6+ medium-length artifacts through map.
Evaluator forms are the same as iterate / beam:
validate:<type>— LLM validator against a registered typescore:<criterion>— ad-hoc haiku rubricexec:<shell-cmd>— ground-truth shell command (exit code scoring)
Each ref is tagged with a search stamp carrying its score and
beam_rank. Refs outside the top-k are marked pruned=True
with a reason pointing at the beam cut. top_k=0 means return all
without pruning.
Args:
refs: JSON array of refs — either ["run_id/agent_id", ...] or
[{"ref": "run_id/agent_id"}, ...]. Both forms are accepted.
evaluator: Scoring directive (validate:<type>, score:<criterion>,
or exec:<cmd>).
top_k: How many top-scoring refs to surface as winners. 0 means
rank-only, no pruning stamp applied.
max_concurrency: Upper bound on parallel evaluator calls (default: 5).
Returns:
JSON with run_id, evaluator, total, top_k,
winners (list of winning ref strings), and ranked (the full
per-ref trace: rank, ref, score, verdict, issues, reason).
Inputs: refs (required), evaluator (required), top_k, max_concurrency. Returns: result
unwrapA
Unwrap an agent result ref — writes the full text to a file and returns the path.
All combinators return refs (metadata without text). Use unwrap to extract the text when you need it. The text is written to a .md file alongside the result, so you can Read() it, Grep it, or pass it to other tools without bloating the MCP protocol.
Args: ref: A ref string like "run_id/agent_id", or a JSON object with a "ref" field.
Inputs: ref (required). Returns: result
validateA
Validate an artifact against a declared type. Runs a type-checker agent that inspects the artifact and reports VALID/PARTIAL/INVALID with per-criterion results.
Use this after a pipeline step to verify the output matches expectations. If validation fails, you know which agent to blame and can retry.
Args: artifact: Description of what to validate — e.g. the agent's output text, a file path, or a ref {"ref": "run_id/agent_id"}. declared_type: The type to validate against — either a type name (e.g. "mcp-server") or inline natural language description. sandbox: Named sandbox spec or inline JSON for the validator agent. model: Model for the validator (default: sonnet — needs to be good at analysis). timeout: Timeout for the validation agent.
Inputs: artifact (required), declared_type (required), sandbox, model, +1 more. Returns: result
wrapA
Wrap a file or directory into the swarm ref system.
This is how you bring external objects INTO the monadic context. The wrapped file gets a ref that can be passed to any combinator.
Args: path: Absolute path to a file or directory on the host.
Inputs: path (required). Returns: result
wrap_projectA
Register a project directory's pipelines, sandboxes, and types with the swarm.
Looks for pipelines/, sandboxes/, types/ subdirectories and adds them to the search paths. After wrapping, named resources from the project are discoverable by all swarm tools (pipeline, run, validate, etc.).
Args: project_dir: Absolute path to a project root containing pipelines/, sandboxes/, and/or types/ directories.
Inputs: project_dir (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 33 tools
Most tools have distinct purposes, but there are some overlaps that could cause confusion, such as 'chain' vs 'pipeline' and 'map' vs 'map_reduce'. Descriptions help differentiate them, but an agent might struggle to pick the right one in some cases.
Names follow snake_case, but the pattern is inconsistent: some are verbs (run, validate, wrap), some are nouns (beam, chain, map), and some are abbreviations (par). This lack of a unified naming convention reduces predictability.
With 33 tools, the server is on the larger side. While each tool serves a specific purpose in a complex orchestration system, the count exceeds the typical 3-15 range, making it feel heavy but not extreme.
The tool set covers execution, evaluation, state management, type system, pipeline management, and governance comprehensively. Minor gaps exist, such as lack of a general run listing tool, but overall the surface is broad and well-rounded.
Maintenance
Related MCP Connectors
AI work orchestration for plans, tasks, teams, and coding-agent dispatch.
LLM Orchestration Agent (Langchain Anthropic)
Your AI Agent's Infrastructure Layer. Connect Claude, Copilot, Codex, or ChatGPT to 200+ managed open source services. Start databases, pipelines, and applications through natural language.
Hosted runtime for persistent agent teams, durable workflows, memory, schedules, and goals.
Related MCP Servers
- FlicenseBqualityNot gradedmaintenanceBridges Claude Code to a Cloud Orchestrator API, providing access to multi-AI consensus, web search, code execution sandboxes, long-term memory, knowledge graphs, deployment management, and 20+ integrated AI and developer tools.28-
- AlicenseNot gradedqualityCmaintenanceCoordinates up to 64 parallel expert agents for complex multi-agent orchestration and intelligent task routing within Claude Code. It enables users to analyze requests, manage hierarchical execution plans, and monitor active orchestration sessions.MIT
- FlicenseAqualityCmaintenanceAn MCP server that orchestrates parallel Claude agent sessions by decomposing natural-language tasks into contract-bound tenants with structured outputs and validation, all running over stdio.5-
- AlicenseNot gradedqualityAmaintenanceRun dynamic, multi-agent workflow scripts — agent(), parallel(), pipeline() — over real coding agents (Claude Code and OpenAI Codex), with deterministic journaling, resume, token budgets, and git-worktree isolation.7Apache 2.0