Claude Flow treats memory as the backbone and MCP tools as the hands. You get concurrent agents that coordinate cleanly, keep context tight, and ship durable artifacts without dragging long text through prompts. It feels like an ops layer for intelligence.
The stack is simple. Claude Code as the client. Claude Flow as the MCP server. SQLite memory at .swarm/memory.db for state, events, patterns, workflow checkpoints, and consensus. Artifacts hold the big payloads. Manifests in memory link everything with ids, tags, and checksums.
Coordination is explicit. Agents write hints to a shared blackboard, gate risky steps behind consensus, and record every transition as an event. Hooks inject minimal context before tools run and persist verified outcomes after. Small bundles in, durable facts out.
Planning keeps runs stable. Use GOAP to sequence actions with clear preconditions. Use OODA to shorten loops.
Observe metrics, orient with patterns, decide through votes, act with orchestration. Topology adapts from hierarchical to mesh when parallelism rises.
Long horizon work becomes repeatable. Sessions resume, workflows checkpoint, and telemetry trims context as load grows. The result is a pragmatic way to scale judgment, not just tokens. Start small, wire hooks, enforce namespaces, and let swarms do the heavy lifting.
Title: Architecting swarms that think before they act Body: “I am running multi‑agent swarms on Claude Flow where memory is the API.
Agents coordinate through a shared blackboard, checkpoint long horizon workflows, and gate releases with consensus.
MCP tools wire Claude Code to orchestration and analytics, while Artifacts keep the heavy payloads out of the prompt and in a durable manifest. This is how we scale judgment, not just tokens.” References: Claude Flow memory and MCP, Claude Artifacts. (GitHub)
Claude Flow combines a hive‑mind swarm architecture, a SQLite memory system at .swarm/memory.db, and an MCP tool suite to coordinate many agents in parallel while keeping context compact, durable, and auditable. It integrates natively with Claude Code hooks and the Model Context Protocol. (GitHub)
What you get
- Concurrent agents that coordinate via shared state, events, and consensus records
- Memory that persists sessions, workflows, and patterns across runs
- MCP tools that expose orchestration, analytics, and system utilities to Claude Code
- Hookable pre and post stages for context injection, verification, and cleanup (GitHub)
- Swarm and Hive‑Mind modes: quick ad‑hoc swarms vs persistent multi‑agent projects with resume and long horizon memory. The README clarifies when to choose each. (GitHub)
- Memory schema: 12 tables including
shared_state,events,workflow_state,patterns,consensus_state, andperformance_metricsfor coordination, audit, checkpoints, learning, and telemetry. (GitHub) - 87 MCP tools: orchestration, memory, topology optimization, performance reporting, and more under the
mcp__claude-flow__*namespace. (GitHub) - Hooks in Claude Code:
PreToolUse,PostToolUse,SessionStart,SessionEndfor deterministic context engineering and compliance controls. (Claude Docs) - Artifacts: large outputs live as Claude Artifacts; Flow stores manifests in memory so agents reference by id instead of rehydrating long text. (Anthropic)
- Performance upgrades: session forking, hook matchers, and an in‑process MCP server that reduce latency in the latest alphas. (GitHub)
Claude Code ──(MCP client)──> Claude Flow MCP tools
| |
| hooks + policies | orchestration API
v v
pre/post scripts <── events ──> memory.db (SQLite)
^ ├─ shared_state (blackboard)
| ├─ events (audit)
| ├─ workflow_state(checkpoints)
artifacts panel ├─ consensus_state(votes)
└─ performance_metrics(telemetry)
- Blackboard pattern: agents write hints to
shared_stateand append actions toevents. - Consensus gating: critical transitions record votes in
consensus_state. - Resilience:
workflow_stateandsessionsrestore long‑lived work. - Observability:
performance_metricsandswarm_statusguide concurrency and context size. (GitHub)
npm install -g @anthropic-ai/claude-code
npx claude-flow@alpha init --force
npx claude-flow@alpha --helpThe init seeds .claude/settings.json, MCP wiring, and memory structures. Use hive-mind for persistent work or swarm for quick jobs. (GitHub)
claude mcp add claude-flow -- npx claude-flow@alpha mcp start
claude mcp listClaude Code natively supports MCP servers and discovery. (Claude Docs)
npx claude-flow@alpha memory stats
# Hooks live in .claude/settings.json and support PreToolUse, PostToolUse, SessionStart, SessionEndHook fields and events are documented in Claude Code. (Claude Docs)
# Ad‑hoc swarm and resume later with hive‑mind
npx claude-flow@alpha swarm "build a REST API"
npx claude-flow@alpha hive-mind statusThe README includes the swarm vs hive‑mind decision table. (GitHub)
Build a small bundle from prior artifacts and events, then inject it before tools run.
// Claude Code conversation calling MCP
const hits = await mcp__claude-flow__memory_usage({
action: "search", namespace: "artifacts", query: "auth service"
})
const artifactIds = (hits?.items||[]).slice(0,5).map(x => x.key.replace("artifact:",""))
const bundle = { summary: "RBAC auth context", rules:["prefer small diffs"], artifactIds }Use this bundle in PreToolUse to bound input. (GitHub)
Persist decisions and checkpoints after tools run.
await mcp__claude-flow__memory_usage({
action: "store",
key: "pattern:auth:validation",
value: JSON.stringify({ regexes:["email","password"], confidence:0.9 }),
namespace: "patterns"
})
await mcp__claude-flow__memory_usage({
action: "store",
key: "workflow:auth:v1",
value: JSON.stringify({ step:"tests_passed", sha:"abc123" }),
namespace: "workflow_state"
})Tables patterns and workflow_state support learning and resumability. (GitHub)
Create or edit in an Artifact, store a manifest in artifacts namespace with checksum and tags, then reference by id across agents. (Anthropic)
await mcp__claude-flow__swarm_init({ topology:"hierarchical", maxAgents:8 })
await Promise.all([
mcp__claude-flow__agent_spawn({ type:"coordinator", name:"Lead" }),
mcp__claude-flow__agent_spawn({ type:"researcher", name:"Analyst" }),
mcp__claude-flow__agent_spawn({ type:"coder", name:"Impl" }),
mcp__claude-flow__agent_spawn({ type:"tester", name:"QA" })
])
await mcp__claude-flow__task_orchestrate({
task:"Design → Scaffold → Tests", strategy:"adaptive", priority:"high"
})Swarm tools and parameters are documented in the MCP Tools reference. (GitHub)
await mcp__claude-flow__memory_usage({
action: "store", key:"coord/hints",
value: JSON.stringify({ next:"PRD then routes then tests" }),
namespace: "shared", ttl: 1800
})shared_state and events are the blackboard and audit trail. (GitHub)
await mcp__claude-flow__memory_usage({
action:"store", key:"consensus:auth_api:v3",
value: JSON.stringify({ decision:"merge", votes:["Lead","Impl","QA"] }),
namespace:"consensus"
})consensus_state records versions, proposers, and acceptors. (GitHub)
await mcp__claude-flow__performance_report({ format:"summary", timeframe:"24h" })
await mcp__claude-flow__topology_optimize({})Use telemetry to trim bundles, rebalance agents, or change topology. (GitHub)
- Session forking to spawn many agents fast.
- Hook matchers to run only the smallest necessary hooks.
- In‑process MCP for near zero IPC overhead on local tools. The README details speedups from these features. Enable WAL mode if you see SQLite lock contention. (GitHub)
Hot path checklist
- Keep PreToolUse bundles under a few kilobytes and top‑5 artifacts only
- Use TTL on
sharedhints and sweep expired keys in maintenance jobs - Batch writes in transactions during heavy phases
- Emit
eventsfor every state transition to make replays deterministic (GitHub)
- Swarm: quick tasks, minimal setup.
- Hive‑Mind: persistent sessions, resume capability, project namespaces. The README includes a decision table for both modes and commands for resume. (GitHub)
Long horizon pattern
- Checkpoint each stage to
workflow_state - Summarize and persist on
SessionEnd - On
SessionStart, rehydrate from session id, then curate a minimal bundle for the next stage. (GitHub)
GOAP: express goals, actions, and preconditions, then let a planner sequence actions. Claude Flow exposes a Goal Module and A* planning in its docs. (GitHub)
OODA: Observe, Orient, Decide, Act. Map to Flow like this:
- Observe: query
events,performance_metrics, and recent artifacts - Orient: reduce to a bundle and compare to
patterns - Decide: write a candidate record into
consensus_stateand gate on votes - Act:
task_orchestrateand record anevent
For background on GOAP and OODA, see Orkin’s FEAR paper and standard OODA references. (GameDevs)
Tables that matter most
memory_storefor KV with namespaces and TTLshared_stateandeventsfor coordinationpatternsfor reusable rules and tacticsworkflow_stateandsessionsfor crash‑safe resumesconsensus_statefor approvals and quorum checkpoints (GitHub)
Maintenance
- Enable WAL for concurrent reads then run periodic
optimize,reindex, andVACUUM. The wiki shows WAL PRAGMA and optimization snippets. (GitHub)
Safety
- Do not store raw secrets in memory. Prefer references to a vault and mask values in hooks.
- Use namespaces:
artifacts,shared,patterns,events,consensus,metrics. (GitHub)
- Generate or open an Artifact in Claude
- Store a manifest in
artifactsnamespace withid,kind,tags,sha256 - Agents reference the manifest id rather than copying large text Artifacts live in a dedicated panel and are built to hold substantial content. (Anthropic)
Manifest example
await mcp__claude-flow__memory_usage({
action:"store",
key:"artifact:prd-auth-v3",
value: JSON.stringify({
kind:"doc", path:"/docs/prd-auth-v3.md", sha256:"...", tags:["auth","prd"]
}),
namespace:"artifacts"
})(GitHub)
Project hooks in .claude/settings.json:
PreToolUse: assemble context bundle, deny risky commands, enforce TTL rulesPostToolUse: persist decisions toevents, learnpatterns, checkpointworkflow_stateSessionStartandSessionEnd: resume and summarize
Hook configuration and examples are in Claude Code docs. (Claude Docs)
// 1) Start and staff swarm
await mcp__claude-flow__swarm_init({ topology:"mesh", maxAgents:10 })
const [lead, impl, qa] = await Promise.all([
mcp__claude-flow__agent_spawn({ type:"coordinator", name:"Lead" }),
mcp__claude-flow__agent_spawn({ type:"coder", name:"Impl" }),
mcp__claude-flow__agent_spawn({ type:"tester", name:"QA" })
])
// 2) PreToolUse hook builds small bundle from artifacts
// 3) Publish hints to shared blackboard
await mcp__claude-flow__memory_usage({
action:"store", key:"coord/current", value:"PRD → routes → tests",
namespace:"shared", ttl:1800
})
// 4) Orchestrate parallel tasks
await mcp__claude-flow__task_orchestrate({
task:"Design routes, implement handlers, write tests",
strategy:"parallel", priority:"high"
})
// 5) Gate release behind consensus vote
await mcp__claude-flow__memory_usage({
action:"store", key:"consensus:release:v3",
value: JSON.stringify({ decision:"approve", votes:["Lead","Impl","QA"] }),
namespace:"consensus"
})
// 6) PostToolUse: record outcome, learn pattern, checkpoint
await mcp__claude-flow__memory_usage({
action:"store", key:"events:last",
value: JSON.stringify({ task:"auth", status:"complete" }), namespace:"events"
})
await mcp__claude-flow__memory_usage({
action:"store", key:"pattern:scaffold:auth",
value: JSON.stringify({ steps:["routes","handlers","tests"], confidence:0.92 }),
namespace:"patterns"
})
await mcp__claude-flow__memory_usage({
action:"store", key:"workflow:auth:v3",
value: JSON.stringify({ step:"done", sha:"abc123" }), namespace:"workflow_state"
})All tool names and parameters are from the MCP Tools wiki. (GitHub)
- Rolling checkpoints: write compact diffs into
workflow_stateafter each stage - Session resume: use
hive-mind resumeto continue exactly where you left off - Periodic groom: sweep expired
sharedkeys, archive coldeventsto files, and runoptimize - Weekly verification: run evaluators and write results to
performance_metricsthen prune patterns with low confidence (GitHub)
Design 1: Coordinator with bounded context
- Coordinator reads only a top‑K bundle and delegates specialized sub‑tasks
- Sub‑agents attach micro‑summaries to
eventsand updatepatterns - Coordinator composes a final Artifact and requests consensus before merge (GitHub)
Design 2: Adaptive topology
- Start hierarchical for clarity
- Switch to mesh under high parallelism using
topology_optimize - Fall back to ring or star if lock contention appears in memory (GitHub)
Pitfalls
- Oversized context slows everything. Use bundles and artifacts.
- Namespace collisions create confusing reads. Adopt a naming policy and a deny‑list in hooks.
- Cleartext secrets in SQLite. Use a secret manager and store only references. (GitHub)
- Live ops:
performance_report,agent_metrics,swarm_status - Bench:
swarm-benchincluding SWE‑bench integration for reproducible evals in CI - Track P50 and P99 memory ops, session resume success rate, and consensus latency. (GitHub)
Namespace policy
artifacts: manifests only, TTL=0
shared: coordination hints, TTL=1800
patterns: reusable tactics, TTL=604800
events: audit trail, TTL=2592000
workflow_state: checkpoints, TTL=0
consensus: approvals and votes, TTL=604800
Aligns with defined tables and usage. (GitHub)
Hook skeleton
{
"hooks": {
"PreToolUse": [{
"command": "node",
"args": ["scripts/build_bundle.js"],
"alwaysRun": true
}],
"PostToolUse": [{
"command": "node",
"args": ["scripts/persist_outcomes.js"],
"alwaysRun": true
}],
"SessionStart": [{"command": "node","args":["scripts/session_start.js"]}],
"SessionEnd": [{"command": "node","args":["scripts/session_end.js"]}]
}
}Hook event names and configuration are per Claude Code docs. (Claude Docs)
GOAP micro‑domain
const goals = [{ id:"ship_auth", cost:1 }]
const actions = [
{ id:"write_prd", pre:[], add:["prd_ready"] },
{ id:"scaffold_routes", pre:["prd_ready"], add:["routes_ready"] },
{ id:"write_tests", pre:["routes_ready"], add:["tests_ready"] },
{ id:"merge", pre:["tests_ready"], add:["shipped"] }
]Use the Goal Module for initialization and planning. (GitHub)
OODA mapping
Observe: query events + metrics
Orient: build bundle + lookup patterns
Decide: write consensus_state entry and wait for quorum
Act: orchestrate task and record event
Background references on OODA provided. (Wikipedia)
- Use Claude Code managed policy settings to control tool access and MCP servers at enterprise scope. (TechRadar)
- Keep
.swarm/and.hive-mind/restricted and encrypted at the OS level. - Treat
credentialsnamespace as references only. - Enforce TTLs and retention in hooks. Audit with
eventsand scheduled exports. (GitHub)
# Choose a mode
npx claude-flow@alpha swarm "build REST API"
npx claude-flow@alpha hive-mind spawn "auth-system" --namespace auth
# Memory inspection
npx claude-flow@alpha memory stats
npx claude-flow@alpha memory list
npx claude-flow@alpha memory query "auth*"
# Orchestration and scaling
mcp__claude-flow__swarm_init({ topology:"mesh", maxAgents:12 })
mcp__claude-flow__topology_optimize({})
# Performance
mcp__claude-flow__performance_report({ format:"summary", timeframe:"24h" })Commands and tools come from the README and MCP Tools reference. (GitHub)
- Init, add MCP, and run
memory stats - Spawn 3 agents, store a
sharedhint, runtask_orchestrate - Write a
consensus:*key and verify gate logic in hooks - Create an Artifact and persist a manifest in
artifacts - Run
performance_reportand shrink the bundle until P99 drops below target (GitHub)
- Adopt artifact‑first outputs with manifest memory
- Keep context small and state durable
- Use consensus gates for deployments
- Treat telemetry as input to reduce context and rebalance concurrency (Anthropic)
Score 1‑5
- Context bundle size and hit rate
- Session resume success
- Consensus latency on critical merges
- P50 and P99 tool latency with in‑process MCP
- Pattern reuse rate and defect escape rate
Run weekly, track in performance_metrics, prune low‑value patterns, and adjust topology. (GitHub)
- Claude Flow repository: features, swarm vs hive‑mind, session forking, hook matchers, in‑process MCP, quick start commands. (GitHub)
- Memory System wiki:
.swarm/memory.db, 12‑table schema, usage, performance tips. (GitHub) - MCP Tools wiki: tool names, parameters, examples, performance reporting, topology optimization. (GitHub)
- Claude Code docs: MCP integration and hook events with configuration examples. (Claude Docs)
- Artifacts: product overview and usage guidance. (Anthropic)
- Model Context Protocol: protocol standard and client tutorial. (Model Context Protocol)
- GOAP and OODA: Orkin’s FEAR planning paper and OODA references. (GameDevs)