Something went wrong. Try again.
MCP based ACP agent
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Headless ACP client that drives one subagent subprocess.
The client-side half of the task system: pure ACP orchestration — spawna child crow agent, handshake, session/new, session/prompt,session/cancel, teardown. No sqlite, no tool knowledge: the MCP-side`task` tool owns state and lifecycle, this is the driver it uses.
Split rationale: ACP is the client<->agent contract, so the machinerythat talks to an agent lives in the client package; MCP is theagent<->tool contract, so the tool + state coupling lives in the mcppackage. The two couple through sqlite, never in-process."""
import asyncioimport contextlibimport osimport sysfrom pathlib import Pathfrom typing import Any
from acp import PROTOCOL_VERSION, RequestError, connect_to_agentfrom acp.interfaces import Clientfrom acp.schema import ( ClientCapabilities, HttpMcpServer, Implementation, McpServerStdio, PromptResponse, SseMcpServer,)
from crow_cli.acp_helpers import text_block
def _parse_mcp_servers(servers: list) -> list: """Parse wire JSON dicts into ACP server models BEFORE sending.
The SDK silently drops request list items that fail validation (e.g. a stdio server missing the required args/env lists) — the child would come up toolless with no error anywhere. Parsing item-by-item makes bad shapes loud, and fills the two required-but-emptyable stdio fields. """ out = [] for s in servers: if not isinstance(s, dict): out.append(s) # already a model continue kind = s.get("type") if kind == "http": out.append(HttpMcpServer.model_validate(s)) elif kind == "sse": out.append(SseMcpServer.model_validate(s)) else: out.append(McpServerStdio.model_validate({"args": [], "env": [], **s})) return out
def child_config() -> dict: """Config context for a spawned child agent, forwarded from THIS process's env.
The child loads its OWN config in its own process, so without these it resolves a different config dir — and a different database — than the caller that is about to read the child's transcript out of it.
Lives here, with the spawn it configures, because both spawners need it (the task tool and rlm) and neither may import the other: task's module registers MCP tools at import time, which a kernel-side tool must never do. """ kwargs: dict = {} if f := os.environ.get("CROW_CONFIG_FILE"): kwargs["config_file"] = Path(f) if d := os.environ.get("CROW_CONFIG_DIR"): kwargs["config_dir"] = Path(d) return kwargs
async def spawn_argv_process( argv: list[str], cwd: str, env: dict[str, str] | None = None,) -> asyncio.subprocess.Process: """Spawn ANY agent by argv — crow's own or a custom `agent_servers` entry.
``env`` is merged over this process's environment, not substituted for it: an entry's env is an overlay (a model, a token, a debug flag), and dropping PATH/HOME would break the child's own subprocesses. """ proc = await asyncio.create_subprocess_exec( *argv, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=cwd, env={**os.environ, **(env or {})}, ) if proc.stdin is None or proc.stdout is None: raise RuntimeError("agent subprocess does not expose stdio pipes") return proc
async def spawn_agent_process( cwd: str, config_dir: Path | None = None, model: str | None = None, config_file: Path | None = None,) -> asyncio.subprocess.Process: """Spawn a crow agent subprocess (frozen builds: the `acp` subcommand).
The child loads its OWN config in its own process — config dir/file are forwarded so the whole stack (db_uri, providers) routes the same. """ is_frozen = getattr(sys, "frozen", False) dir_args = ["--config-dir", str(config_dir)] if config_dir else [] if config_file: dir_args += ["--config-file", str(config_file)] model_args = ["--model", model] if model else [] if is_frozen: argv = [sys.executable, "acp", *dir_args, *model_args] else: argv = [sys.executable, "-m", "crow_cli.agent.main", *dir_args, *model_args] return await spawn_argv_process(argv, cwd)
class HeadlessClient(Client): """The client face shown to a subagent: swallow updates, no fs/pty.
The child's transcript is fully observable through the shared sqlite (query_session on its session id) — nothing needs forwarding, and terminal=False at handshake makes its terminal tool fall through to its own MCP supply. """
def __init__(self) -> None: self.updates: list[Any] = []
async def request_permission(self, *a: Any, **k: Any) -> Any: raise RequestError.method_not_found("session/request_permission")
async def session_update(self, session_id: str, update: Any, **k: Any) -> None: self.updates.append(update)
async def write_text_file(self, *a: Any, **k: Any) -> Any: raise RequestError.method_not_found("fs/write_text_file")
async def read_text_file(self, *a: Any, **k: Any) -> Any: raise RequestError.method_not_found("fs/read_text_file")
class SubagentDriver: """Drives ONE subagent over ACP: spawn -> handshake -> sessions."""
def __init__(self) -> None: self.proc: asyncio.subprocess.Process | None = None self.conn: Any = None self.client = HeadlessClient()
async def start( self, cwd: str, model: str | None = None, config_dir: Path | None = None, config_file: Path | None = None, ) -> None: self.proc = await spawn_agent_process( cwd, config_dir=config_dir, model=model, config_file=config_file ) self.conn = connect_to_agent( self.client, self.proc.stdin, self.proc.stdout, # session/fork is UNSTABLE — both ends opt in or the router # answers method_not_found. use_unstable_protocol=True, ) await self.conn.initialize( protocol_version=PROTOCOL_VERSION, # terminal=False: the child's terminal tool falls through to # its MCP supply (agent-owned execution), not to us. client_capabilities=ClientCapabilities(terminal=False), client_info=Implementation( name="crow-task", title="Crow Task", version="0.1.0" ), )
async def new_session(self, cwd: str, mcp_servers: list | None = None) -> str: ns = await self.conn.new_session( cwd=cwd, mcp_servers=_parse_mcp_servers(mcp_servers or []) ) return ns.session_id
async def load_session( self, session_id: str, cwd: str, mcp_servers: list | None = None ) -> None: """Re-attach to an existing session (re-prompt after its turn ended). The agent restores state from sqlite; no history is emitted back to us.""" await self.conn.load_session( cwd=cwd, session_id=session_id, mcp_servers=_parse_mcp_servers(mcp_servers or []), )
async def fork_session( self, session_id: str, cwd: str, mcp_servers: list | None = None, message_offset: int | None = None, rlm_depth: int | None = None, ) -> str: """session/fork (UNSTABLE): ``session_id``'s history under a NEW wire session id, which is the fork's own agent_id — so it is also the key the fork's transcript is stored under, and reading that transcript back needs no handshake.
``message_offset``/``rlm_depth`` are not in the schema: they ride the request ``_meta``, and the agent-side router flattens _meta into the handler's kwargs generically (no whitelist), so they arrive as the camelCase names the handler declares. ``start()`` already opts into the unstable protocol — without it the router answers method_not_found.
The client owns the fork's tool supply exactly as for new/load: an empty ``mcp_servers`` means ZERO tools, which is what an interrogation fork wants and what a delegate that only has to answer a question does not. """ meta: dict[str, Any] = {} if message_offset is not None: meta["messageOffset"] = message_offset if rlm_depth is not None: meta["rlmDepth"] = rlm_depth resp = await self.conn.fork_session( session_id=session_id, cwd=cwd, mcp_servers=_parse_mcp_servers(mcp_servers or []), **meta, ) return resp.session_id
async def prompt(self, session_id: str, text: str) -> PromptResponse: return await self.conn.prompt( session_id=session_id, prompt=[text_block(text)] )
async def cancel(self, session_id: str) -> None: await self.conn.cancel(session_id=session_id)
async def close(self) -> None: with contextlib.suppress(Exception): if self.conn is not None: await self.conn.close() if self.proc is not None and self.proc.returncode is None: with contextlib.suppress(Exception): self.proc.terminate() await asyncio.wait_for(self.proc.wait(), timeout=5) if self.proc.returncode is None: with contextlib.suppress(Exception): self.proc.kill()