Skip to content

feat(mcp): add tools to deliver input to, wait on, and close agent sessions - #422

Merged
forketyfork merged 9 commits into
mainfrom
feat/mcp-agent-control
Nov 4, 2026
Merged

forketyfork merged 9 commits into
mainfrom
feat/mcp-agent-control

Conversation

@forketyfork

@forketyfork forketyfork commented Nov 4, 2026 •

Copy link
Copy Markdown
Owner

TLDR

External tools can now control AI agents that run in Architect terminals. A tool can send a message to an agent, wait until the agent finishes its turn, and close the terminal. Before this change, a tool could only open a terminal.

Issue

architect-mcp exposed only spawn_session. An orchestrator that runs interactive Claude Code or Codex agents in Architect terminals (for example Mu, which today starts one claude -p / codex exec process per chat message) had no way to:

  • deliver a message to an idle agent (wake it up) without polling or a custom harness integration;
  • know when the agent's turn is over, or whether the agent waits for a human;
  • close a terminal it started.

Building and testing this against real agents also exposed three existing bugs:

  • The notification listener read right after accept() and dropped the connection when the hook client had not written yet. The hooks ignore send errors, so done / awaiting_approval notifications could be lost without any sign.
  • spawn_session types its command into the new shell, often while the terminal is still in canonical mode, where macOS keeps only 1024 bytes per line. Longer commands could be silently dropped (a 1195-byte command never ran).
  • app/control.zig declared tests that no test binary collected.

Solution

  • New MCP tools next to spawn_session: list_sessions, send_input, wait_for_session, terminate_session. They are generic, with no knowledge of any orchestrator.
  • Instance-scoped sessions: session ids restart at 0 in every Architect app, so a session is addressed by (instance_id, session_id). Each app generates an instance_id (pid plus a random 64-bit value) at startup, publishes it in its discovery file, and returns it from every tool. send_input, wait_for_session, and terminate_session require instance_id; architect-mcp routes them only to that instance and fails with the new error instance_not_found when it is not running (stale file, clean shutdown, or no app at all), never falling back to another app. The app also rejects a request that names a different instance. spawn_session and list_sessions take an optional instance_id and otherwise use the newest instance.
  • Agent state (app/agent_state.zig): each session has unknown | working | awaiting_approval | idle | exited plus an app-wide state_seq. Agent hooks drive it (ready, start, done, awaiting_approval). send_input sets working in the same main-thread step as the write, so delivery does not depend on any agent's hook. With require_idle, the check and the write are atomic. Claude's idle-reminder notification is ignored while the agent is idle. Unsubmitted drafts (submit: false) do not change the state. Within a frame, sessions are reconciled, then hook notifications applied, then control requests run, so require_idle sees every signal that arrived before it.
  • Tile follows the agent state: a hook signal the agent state ignores (for example ready during a mid-turn compaction) leaves the tile unchanged; the idle reminder keeps its existing attention highlight while the state stays idle. A submitted delivery marks the tile running.
  • Blocking wait without main-loop cost: the control listener parks wait_for_session connections in its poll(2) set and answers them from the board when it changes, the deadline passes, or the client goes away. A pending wait never wakes the frame loop (measured: same CPU as fully idle).
  • Startup: architect hook claude now also installs SessionStart → ready (only moves unknown → idle) and UserPromptSubmit → start. Agents without a ready hook start with their first message on the command line.
  • Termination reuses the tile-close despawn path. It runs after the frame's UI actions so grid compaction cannot invalidate queued UI slot indices.
  • Control protocol is now {"op","arguments"} → {"ok","result"}, validated by the same parser in the app and in architect-mcp.
  • Input safety: text is encoded like a user paste. Without bracketed paste only one line (no CR or LF) of at most 1023 bytes is accepted, in both submit modes, so a draft cannot submit itself and canonical-mode line limits cannot drop input.
  • Shutdown: the control request queue is closed under its lock at shutdown, so a request still being received is refused with app_not_running instead of blocking the listener while the runtime joins it. Parked waits survive a client that half-closes its socket after sending the request.
  • Bug fixes: the notify listener reads with a deadline until newline/EOF; spawn_session rejects commands over 1023 bytes with an explicit error; control.zig tests are registered.

Per-conversation context stays on the orchestrator side: one Architect session per (agent, conversation), started with the agent's own session id (claude --session-id/--resume, codex resume).

Context

  • Design, rejected alternatives, verification notes, and follow-ups: docs/superpowers/specs/2026-11-04-mcp-agent-control-design.md
  • Tool reference: docs/ai-integration.md
  • Verified end to end on a separate Architect instance with real Claude Code 2.1.318 (start via ready, two turns) and Codex 0.166.0 (first message on the command line, a second turn via send_input, session_busy on an early second send, terminate).
  • Breaking for mixed versions: an older running app answers a newer architect-mcp with invalid_request. Upgrade both together.
  • Breaking for orchestrators: send_input, wait_for_session, and terminate_session require the instance_id returned by spawn_session or list_sessions; store it with the session_id.
  • Review: the Copilot review threads on this PR and a local multi-angle review were addressed in follow-up commits (ordering, drafts, half-closed waits, CR input, shutdown queue race, instance identity, tile updates for ignored hooks).
  • Follow-ups (out of scope): graceful terminate, persisted labels for re-attach after an Architect restart, Codex/Gemini ready/start hooks (Codex 0.166 hooks need user review before they run).
  • Existing Claude setups must re-run architect hook claude to get the two new hooks.

Test plan

  • Run architect hook claude in an Architect terminal on a machine with existing hooks; confirm SessionStart and UserPromptSubmit entries are added once and existing hooks are kept.
  • In the GUI, spawn a session via architect-mcp and close it with terminate_session in both grid and full view; confirm the grid compacts and focus moves like closing the tile by hand.
  • Type a prompt by hand into a hooked Claude session; confirm the tile's status and attention behave as before (no new attention flash on startup).

The notification listener read right after accept() and closed the
connection on EWOULDBLOCK, so a hook client that had connected but not
yet written lost its notification. The hook clients swallow send errors,
so a lost done/awaiting_approval was silent. Read with a deadline until
newline or EOF instead.
…ssions

architect-mcp gains list_sessions, send_input, wait_for_session, and
terminate_session next to spawn_session, so an orchestrator can drive
interactive agents turn by turn without polling.

- app/agent_state.zig: hook-driven per-session agent state with an
  app-wide sequence number, read by the control listener
- app/control.zig: op/arguments wire format shared with architect-mcp;
  the listener parks wait_for_session connections and answers them from
  the agent-state board, so pending waits never wake the main loop
- app/agent_control.zig: main-thread list and send_input handlers;
  require_idle checks and writes atomically
- terminate_session reuses the tile-close despawn path, deferred until
  after the frame's UI actions
- control.zig tests now run in the exe test binary (they were not
  collected by any test binary before)

Design and rejected alternatives:
docs/superpowers/specs/2026-11-04-mcp-agent-control-design.md
…ompts

A new session stayed unknown until the agent's first Stop hook, so an
orchestrator could not deliver the first message after spawn_session.
Add a ready notification state: architect hook claude now installs
SessionStart -> ready, which moves only an unknown agent to idle (it
also fires on /clear and compaction, which must not override a later
state), and UserPromptSubmit -> start, so prompts a human types into
the tile mark the agent working.

The design doc records the chosen readiness signal and why treating
unknown as deliverable was rejected, and lists graceful terminate,
re-attach labels, and Codex/Gemini lifecycle hooks as follow-ups.
spawn_session types its command into the new shell, often while the
terminal is still in canonical mode, where macOS keeps at most 1024
bytes per line and drops the rest including the newline. A 1195-byte
command never ran while a 1495-byte one happened to arrive after zsh
switched to raw mode. Limit command to 1023 bytes with an explicit
error and point clients at a script.

Also add a test that a second require_idle send right after a delivery
is refused without any hook event, and record the real Claude Code and
Codex end-to-end results in the design doc.
@forketyfork
forketyfork marked this pull request as ready for review November 4, 2026 14:32
@forketyfork
forketyfork requested a balanced review from Copilot November 4, 2026 14:33

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Control requests run before queued hook notifications, allowing deliveries to busy agents and stale completion signals to falsely satisfy waits for a new turn.

7 open issues
What changed in this PR

Extends Architect’s MCP interface from session creation to turn-by-turn agent control, allowing external orchestrators to send input, wait for agent state changes, and close sessions.

Changes:

  • Adds four MCP tools, a shared control protocol, and hook-driven agent-state tracking with listener-managed waits.
  • Integrates input delivery and termination into the runtime, adds Claude lifecycle hooks, and fixes delayed notification reads.
  • Expands tests and their registration, limits startup command length, and documents the new tools and architecture.

Build, tests, and lint were not run in this review environment.

File Description
src/​shell.zig Installs Claude ready and start hooks.
src/​session/​notify.zig Waits for delayed notification data and recognizes ready signals.
src/​mcp/​main.zig Exposes all five control tools and their schemas.
src/​main.zig Registers control and agent-module tests.
src/​env.zig Exposes environment initialization for tests.
src/​app/​terminal_actions.zig Adds paste payloads with optional submission.
src/​app/​runtime.zig Handles control requests, hook updates, and deferred termination.
src/​app/​control.zig Implements shared validation, replies, and parked waits.
src/​app/​agent_state.zig Adds the agent-state board and sequence-based wait evaluation.
src/​app/​agent_control.zig Implements session listing, input delivery, and board reconciliation.
scripts/​perf/​spawn_session.py Uses the updated control request format.
scripts/​check-test-registry.sh Requires explicit registration of control tests.
scripts/​architect_notify.py Accepts the ready notification state.
README.md Introduces the expanded MCP capabilities.
docs/​superpowers/​specs/​2026-11-04-mcp-agent-control-design.md Records design decisions, verification notes, and follow-ups.
docs/​perf-debugging.md Updates the control-socket request example.
docs/​ARCHITECTURE.md Documents agent-state modules and control flows.
docs/​ai-integration.md Defines tool contracts and agent orchestration workflows.
CLAUDE.md Documents control-channel and notification-handling invariants.

Review effort: Balanced

Comment thread src/app/runtime.zig Resolved
Comment thread src/app/agent_control.zig Resolved
Comment thread src/app/control.zig Resolved
Comment thread src/app/runtime.zig Resolved
Comment thread src/app/runtime.zig Resolved
Comment thread src/app/terminal_actions.zig Resolved
Comment thread src/shell.zig Resolved
Copilot review of the PR found ordering and edge-case gaps:

- Control requests ran before the frame's hook notifications, so a
  require_idle delivery could ignore a queued start and an older done
  could overwrite the delivery. Reconcile sessions first, then apply
  hooks, then run control requests.
- An unsubmitted draft marked the agent working although no turn starts,
  leaving it busy forever. Only submitted deliveries change the state.
- A client that half-closes after its request was treated as gone. On
  macOS that is indistinguishable from a full close, so keep the wait
  parked and stop polling it; a vanished client shows up as a failed
  reply write.
- Submitted deliveries now mark the tile running and clear attention,
  like a start hook, for agents without one.
- Without bracketed paste a single line above 1023 bytes could be lost
  to the canonical-mode line limit; reject it as input_not_ready.
- architect hook claude reused the first group, inheriting a matcher
  such as SessionStart "resume". Install into an unfiltered group and
  only count unfiltered groups as installed.
…at shutdown

Review found two defects:

- Without bracketed paste only LF was rejected, but CR submits a line
  too, so an unsubmitted draft like "echo one\recho two" could run its
  first line at a shell prompt. Reject both CR and LF in either submit
  mode.
- The listener could queue a request after shutdown had already failed
  the queue (a request still being read when stop was set), then block
  forever on its completion while the runtime joined the thread. The
  queue now has a closed flag set under its lock by closeAndFail, and
  push refuses with app_not_running once it is set.
…oks off the tile

Review found two more defects:

- Session ids restart at 0 in every app, but architect-mcp resolved the
  newest discovery entry on every call, so opening a second Architect
  could route send_input or terminate_session for session 0 to an
  unrelated terminal. Each app now generates an instance_id (pid plus a
  random 64-bit value) at startup, publishes it in its discovery file,
  and returns it from every tool. send_input, wait_for_session, and
  terminate_session require it; the helper routes only to that instance
  and fails with instance_not_found instead of trying another, and the
  app rejects requests naming a different instance. spawn_session and
  list_sessions still default to the newest instance.
- Hook signals the agent board ignored still changed the tile, so a
  SessionStart during a mid-turn compaction showed the agent idle.
  applyHook now reports its outcome and the tile only follows accepted
  signals, except Claude's idle reminder, which keeps its existing
  attention highlight while the agent state stays idle.
…p is running

With no discovery file left (the only app shut down cleanly), a request
naming an instance returned app_not_running, while the same request
returned instance_not_found when the app left a stale file or another
instance was running. Targeted requests now fail with instance_not_found
in every case; untargeted spawn and list keep app_not_running.
@forketyfork
forketyfork merged commit 20138bd into main Nov 4, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants