pi-subagent
It turns the Pi CLI into a programmable, session-based coding sub-agent that MCP hosts can delegate work to and manage.
Delegate tasks to Pi sub-agents (
pi_delegate) with prompts, sessions, working directories, sync/async modes, timeouts, and constraints.Harvest results via long-polling
pi_statusto get run outcomes without blocking tool calls.Make scheduling decisions with
pi_plan, which evaluates the task and suggests whether/how to delegate, which mode to use, and how many sessions to fan out to.List and inspect sessions using
pi_session_listandpi_session_snapshotto see active/current sub-agent state.Fork sessions with
pi_session_forkto branch an existing session and try a different path.Abort runs with
pi_killto stop a delegated Pi process.Support async workflows for long-running delegations and avoid host tool-call timeouts.
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., "@pi-subagent Delegate implementing user authentication"
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.
pi-subagent
Turn the Pi CLI (
@earendil-works/pi-coding-agent) into a programmable coding sub-agent that any MCP host (ZCode, Claude Code, Cursor, …) can delegate tasks to, track sessions, and kill processes.
pi-subagent is a thin MCP server that wraps pi -p --mode json into 7 structured tools: delegate tasks, harvest results, make scheduling decisions, manage named sessions, and abort runs. Process-isolated, fully session-based, sync/async dual-mode.
Why
Pi is a minimal terminal coding agent. Rather than teaching Pi methodology, this project treats Pi as a delegatable worker: a host agent (ZCode / Claude Code) decides when to delegate, fires off a self-contained task, and harvests the result. One Pi process = one isolated sub-agent run.
Process isolation — each delegation spawns one
pi -pchild process. A Pi crash only affects that run.Fully session-based — every task binds to a named session (e.g.
feat-auth); subsequent calls auto-continue.Sync / async — defaults to
async(avoids host tool-call timeouts); harvest withpi_statuslong-poll.Schedulable —
pi_planis a pure 5-stage decision function (reject / capacity / reuse / modify / mode), fully unit-tested.Universal MCP — any standard MCP client can load it.
Related MCP server: pi-delegate-mcp
Architecture
┌─────────────────────────────────────────────────────────────┐
│ MCP Host (ZCode / Claude Code / Pi / Cursor …) │
└───────────────────────────┬─────────────────────────────────┘
│ MCP (JSON-RPC over stdio)
▼
┌─────────────────────────────────────────────────────────────┐
│ pi-subagent-server (Node/TS) │
│ ┌────────────┐ ┌──────────────┐ ┌────────────────────┐ │
│ │ Tool layer │ │ Session │ │ Pi runner │ │
│ │ (7 tools) │─▶│ registry │─▶│ (spawn pi -p) │ │
│ │ + plan() │ │ + persist │ │ parse agent_end │ │
│ └─────┬──────┘ │ + _snapshot │ │ + tool_execution │ │
│ │ └──────────────┘ └─────────┬──────────┘ │
│ │ ┌────────▼─────────┐ │
│ └───────────────────────────│ Run registry │ │
│ (kill) │ + process-table │ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│ child_process.spawn({ cwd })
▼
┌─────────────────────┐
│ pi CLI (0.77+) │
└─────────────────────┘Three layers with clear boundaries: Tool layer (MCP schema + plan() pure function) / Session registry (state + persistence + redaction) / Runner (spawn pi, parse NDJSON, process table).
Tools
Tool | Purpose |
| Decide: should-delegate, sync/async, how many sessions |
| Dispatch a task (default async; new sessions wait for handshake) |
| Harvest a run's result (long-poll) |
| List sessions (omit |
| Inspect one session |
| Branch a session to try another path |
| Abort a run |
| Create a multi-stage task (host writes |
| Dispatch a domain review of the plan (harvest via |
| Run one stage: sync (wait for outcome) or async (returns runId) |
| Harvest an async stage run; auto-judges and re-dispatches (max 3), else manual |
| List tasks (filter by taskId / status) |
Review loop: after
pi_task_plan, harvest withpi_status(runId). When the run finishes, the server detects it is a review run, parses_plan-reviewed.md, and storesplanVerdict/planReviewedPathon the task. Stage prompts automatically include the reviewed plan and the output files of passed dependency stages.
Async stages: pass
mode: "async"topi_task_stage_runto avoid blocking a tool call for the full run (recommended when the MCP host enforces a short tool timeout). Harvest withpi_task_stage_collect(taskId, stageId). Failed attempts re-dispatch under a fresh session name to avoid history contamination; after 3 failures the stage goesmanualwith a decision panel (retry_with_new_hintis supported viapromptHintOverride).
Restart recovery: re-running
pi_task_createwith the sametaskIdmerges instead of conflicting. Stages whose output file already exists and passes validation are markedpassedautomatically, so interrupted tasks resume without hand-editingtasks.json.
Session model
Each session has a human-readable name + Pi's UUID +
cwd+goal.First
pi_delegatecreates the session (goalrequired); later calls auto-continue.The registry persists to
~/.pi-subagent/registry.json(atomic write; on restart, interruptedrunningrecords are corrected toerror).Concurrency cap: 4 running runs; a single session is never run concurrently.
Tasks persist to
~/.pi-subagent/tasks.json(atomic write; running stages are corrected tofailed(interrupted_by_restart)on restart).
Install
git clone <this-repo> && cd pi-subagent
npm install
npm run build # required: emits dist/, the MCP entry pointPrerequisite: the pi CLI is installed (npm i -g @earendil-works/pi-coding-agent) and on PATH.
npm 10+ blocks install scripts by default. If
npm installprints1 package has install scripts not yet covered by allowScriptsforesbuild, runnpm install-scripts approve esbuild—tsx(used by the test suite) needs esbuild's native binary and will fail to start without it.
Configure an MCP host
Add to your MCP client config:
{
"mcpServers": {
"pi-subagent": {
"command": "node",
"args": ["/abs/path/to/pi-subagent/dist/server.js"]
}
}
}Use the compiled
dist/entry with plainnode, and always an absolute path. Do not configurenpx tsx src/server.ts: MCP hosts spawn the server with the host's working directory (the project being edited), not this repo. From therenpxcannot resolve the locally installedtsx, so it falls through to a registry download — on a slow or firewalled network that blows past the host's 30s handshake window and the server shows up asCONNECT_TIMEOUT. Runningdist/server.jsundernodeneeds no resolution step and starts in ~0.2s from any cwd.Re-run
npm run buildafter pulling changes, sincedist/is gitignored.
Optional env vars:
PI_SUBAGENT_REGISTRY— registry path (default~/.pi-subagent/registry.json)PI_BIN— override the pi executable (used by tests)
Test
npm test # full suite (140 tests)
npm run test:fast # dot reporterTests use a fake pi (test/fixtures/fake-pi.sh) and cover: async/sync, timeout, kill, session-create-failure, multi-waiter, progress cap, scheduling rules (table-driven + 100-iteration property tests), registry persistence, redaction, etc.
Project layout
src/
├── types.ts # all shared types + error codes
├── errors.ts # ToolError helpers
├── runner/ # parse.ts, argv.ts, spawn.ts, process-table.ts
├── registry/ # session.ts, run.ts, persist.ts, redact.ts
├── scheduler/ # keywords.ts, plan.ts (5-stage pure function)
├── tools/ # delegate, status, plan-tool, session, kill
└── server.ts # MCP entry (stdio)
skills/pi-subagent/ # SKILL.md + delegation-patterns (strategy layer)
test/ # fixtures/ + *.test.ts
docs/ # design.md (spec) + implementation-plan.mdDesign & process
This project went through collaborative design + 4 rounds of external review before implementation. The spec and plan are committed under docs/:
docs/design.md— full design spec (architecture, tool contracts, error handling, scheduler rules, testing strategy). Every contract is traceable to a review note (R1–R4).docs/implementation-plan.md— 19 TDD tasks (write failing test → implement → pass → commit).
Key design decisions, all backed by real probing of pi -p output and external review:
cwd≠ session storage —spawn({ cwd })controls the working dir; Pi's session files use their default location (doesn't pollute the project).async default + handshake — new sessions wait for Pi's
sessionevent before returning (with asessionStartTimeoutMs), so the host always gets a realpiSessionId.Multi-stage scheduler —
plan()is reject → capacity → reuse → modify → mode, where modifiers stack rather than first-match (a lesson from review round 1).Progress redaction — tool results are truncated + scrubbed for tokens/keys before being stored.
Status
Working implementation, 140 passing tests. Not yet published to npm — clone, npm install && npm run build, then point your MCP host at dist/server.js.
License
MIT
Available Tools
7 toolspi_delegateC
委派任务给 Pi 子代理(默认 async)
Inputs: prompt (required), session (required), cwd, goal, +4 more.
pi_killC
中止 run
Inputs: runId (required).
pi_planC
调度决策:该不该委派、sync/async、开几个 session
Inputs: cwd (required), task (required), fanout, estComplexity, +1 more.
pi_session_forkD
派生 session
Inputs: to (required), from (required).
pi_session_listA
列 session(不传 cwd 取全量,供 pi_plan 用)
Inputs: cwd.
pi_session_snapshotC
取 session 详情
Inputs: session (required).
pi_statusC
取 run 结果(long-poll)
Inputs: runId (required), waitTimeoutMs.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Each tool targets a distinct operation: delegation, kill, planning, session management, and status. No overlap in purpose.
All tools share the 'pi_' prefix, but the structure varies: some are verbs (pi_delegate, pi_kill), others are noun_verb (pi_session_fork). Overall readable and consistent prefix helps.
7 tools is appropriate for a subagent manager covering delegation, planning, session lifecycle, and status retrieval.
Core operations are covered, though missing explicit session creation or update tools. Forking may serve creation, and kill provides termination.
Related MCP Connectors
Start and manage Reason cloud coding agents, projects and sessions from any MCP client.
Remote MCP server exposing your Node Command fleet (files, shell, processes, browser) to AI hosts.
Hosted MCP server and Agent Skills for specs, engineering threads, and project memory.
Shared memory MCP server for Claude Code, Codex, Gemini CLI and Cursor. Cited, editable.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables MCP clients to spawn and control Codex CLI and Claude Code sessions on the host machine, with session management and filesystem access.4MIT
- AlicenseNot gradedqualityDmaintenanceDelegates bounded coding tasks from MCP clients to the Pi Coding Agent over stdio. Supports review, verification, implementation, and batch operations with long-running task polling.MIT
- FlicenseNot gradedqualityDmaintenanceEnables MCP hosts like Claude Code and Codex to spawn, manage, and interact with persistent, reusable Pi coding-agent sessions, supporting task dispatch, status checks, and session lifecycle control.7 npm-
- AlicenseBqualityBmaintenanceEnables any MCP host to delegate work to multiple coding-agent CLIs such as Codex, Claude Code, and Antigravity as subagents, preserving native sessions and supporting team-based supervision and agent-to-agent messaging.1711 npmApache 2.0