Something went wrong. Try again.
MCP based ACP agent
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450import asyncioimport contextlibimport jsonimport loggingimport osimport sysfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any
import typerfrom rich.console import Consolefrom rich.panel import Panelfrom rich.table import Tablefrom rich.text import Text
from crow_cli.agents import ( V2, AgentServer, AgentServerError, crow_agent_server, parse_agent_servers, select_agent_server, tool_supply,)from crow_cli.config import Config, apply_config_overridesfrom crow_cli.agent.main import main as agent_mainfrom crow_cli.agent.mcp_client import fastmcp_config_to_acp_serversfrom crow_cli.memory import build_agent_id, get_engine, get_max_agent_idxfrom crow_cli.agent.memory import MemoryClient, MemoryServiceErrorfrom crow_cli.agent.session import AgentSessionfrom crow_cli.cli.init_cmd import init_commandfrom crow_cli.cli.install import app as install_appfrom crow_cli.client.main import CrowClient, connect_client
if TYPE_CHECKING: # crow_cli.discover imports the v2 schema (~0.36s), and a run whose entry # declares its protocol must never pay that. The annotation is the only # thing here that needs the name. from crow_cli.discover import Connection
app = typer.Typer( name="crow-cli", help=( "Transparent CLI for the Crow agent — full observability into agent state.\n\n" "Talk to an agent with `crow-cli run \"prompt\"` and continue a session with " "`-s <session-id>`. Agents launch subagents with the `task` MCP tool; every " "session persists in the shared store, so you can attach to a subagent's " "session yourself with `run -s <session-id>` and read its thoughts via the " "query_session MCP tool. See `crow-cli run --help` for the full recipe." ),)
# Register command groupsapp.add_typer(install_app, name="install")
console = Console()# we need to work on a crow-cli init command to set up configuration# until then...client = CrowClient(console=console)
# ===========================================================================# ACP Agent@app.command("acp")def run_agentmain( config_dir: Path = typer.Option( None, "--config-dir", "-d", help="Configuration directory (default: ~/.agents/crow)", ), debug: bool = typer.Option( False, "--debug", help="Enable chunk-level JSONL logging for debugging", ), system_prompt_path: Path = typer.Option( None, "--system-prompt-path", "-p", help="Path to a Jinja2 system prompt template file", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML file with config values to override", ), model: str = typer.Option( None, "--model", "-m", help="Model to use (name from config.yaml models: section)", ), http: bool = typer.Option( False, "--http", help="Serve ACP over Streamable HTTP + WebSocket instead of stdio", ), host: str = typer.Option( "127.0.0.1", "--host", help="Bind address with --http (use 0.0.0.0 to expose)", ), port: int = typer.Option( 2769, "--port", help="Port with --http (default 2769)", ),): """Main entry point for the crow-cli agent.""" if config_dir is None: config_dir = Path.home() / ".agents" / "crow"
config = Config.load(config_dir=config_dir) config = apply_config_overrides(config, config_file)
if system_prompt_path: config.system_prompt_path = system_prompt_path
if debug: config.chunk_log = True
agent_main(config=config, model=model, http=http, host=host, port=port)
# ===========================================================================# ACP v2 Agent@app.command("acp2")def run_agent2( config_dir: Path = typer.Option( None, "--config-dir", "-d", help="Configuration directory (default: ~/.agents/crow)", ), debug: bool = typer.Option( False, "--debug", help="Enable chunk-level JSONL logging for debugging", ), system_prompt_path: Path = typer.Option( None, "--system-prompt-path", "-p", help="Path to a Jinja2 system prompt template file", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML file with config values to override", ), model: str = typer.Option( None, "--model", "-m", help="Model to use (name from config.yaml models: section)", ), no_default_tool: bool = typer.Option( False, "--no-default-tool", help="Do not merge config.yaml's mcpServers into sessions: the session's " "tools are exactly the ones the client sent in session/new", ), http: bool = typer.Option( False, "--http", help="Serve ACP v2 over Streamable HTTP + WebSocket instead of stdio", ), host: str = typer.Option( "127.0.0.1", "--host", help="Bind address with --http (use 0.0.0.0 to expose)", ), port: int = typer.Option( 2771, "--port", help="Port with --http (default 2771)", ),): """Entry point for the ACP v2 agent (``crow_cli.agent2``).
The v2 counterpart of ``crow-cli acp``, and the command a frozen build spawns when it needs a v2 subagent — :func:`crow_cli.client2.subagent. agent_argv` names it, so the two must not drift.
stdio by default; ``--http`` serves v2 over Streamable HTTP + WebSocket (same JSON-RPC lifecycle as ``crow-cli acp --http``) via an ``AgentProtocolRouter``. Each connection negotiates v2 and binds one ``CrowAgentV2``; sessions share the same store.
``--no-default-tool`` leaves config.yaml's ``mcpServers`` out of every session, so a session's tools are exactly the ones its client sent in ``session/new``. That is what makes an agent generic by construction rather than by prompt: a conductor whose only arm is the MCP server it was handed cannot reach for ``execute`` and go off script.
Lazy import, and startup is the reason. ``crow_cli.cli.main`` already costs ~1.15s to import; ``agent2.main`` pulls ``acp.experimental.v2.schema`` — six thousand lines of pydantic — for another ~0.36s. At module scope every invocation pays that, including ``crow-cli --help`` and ``crow-cli mcp2 --list-tools``. """ from crow_cli.agent2.main import main as agent2_main
if config_dir is None: config_dir = Path.home() / ".agents" / "crow"
config = Config.load(config_dir=config_dir) config = apply_config_overrides(config, config_file)
if system_prompt_path: config.system_prompt_path = system_prompt_path
if debug: config.chunk_log = True
if no_default_tool: config.no_default_tool = True
agent2_main(config=config, model=model, http=http, host=host, port=port)
@app.command("mcp")def run_mcp( transport: str = typer.Option( "stdio", "--transport", help="stdio = spawned child (default); http = streamable HTTP service", ), host: str = typer.Option("127.0.0.1", "--host", help="bind address for the HTTP transport"), port: int = typer.Option(2769, "--port", help="port for the HTTP transport"), include_tools: list[str] = typer.Option( None, "--include-tools", metavar="TOOLS", help="Allowlist of tools to serve, comma-separated and/or repeated. " "Defaults to ALL of them — exclude a tool by not listing it.", ), list_tools: bool = typer.Option( False, "--list-tools", help="Print the tool names --include-tools accepts and exit.", ),): """Serve Crow's MCP tools — stdio child (default) or streamable HTTP.
Spawn it several times with different --include-tools to get several servers out of this one codebase. """ # Lazy import: this module is cheap (it imports no tool group), but the # tools it registers are not — vision pulls opencv. register_tools() only # imports the modules that own the tools actually selected. from crow_cli.mcp import tool_names from crow_cli.mcp.server.main import ( ToolSelectionError, resolve_tool_selection, serve, )
if list_tools: for name in tool_names(): typer.echo(name) raise typer.Exit(0)
try: include = resolve_tool_selection(include_tools) except ToolSelectionError as exc: # Loud and on stderr: stdout is the JSON-RPC stream on stdio transport. typer.secho(f"crow-cli mcp: {exc}", fg="yellow", err=True) raise typer.Exit(2)
serve(transport, host, port, include_tools=include)
@app.command("mcp2")def run_mcp2( transport: str = typer.Option( "stdio", "--transport", help="stdio = spawned child (default); http = streamable HTTP service", ), host: str = typer.Option("127.0.0.1", "--host", help="bind address for the HTTP transport"), port: int = typer.Option(2770, "--port", help="port for the HTTP transport"), list_tools: bool = typer.Option( False, "--list-tools", help="Print the served tool names and exit.", ),): """Serve crow-mcp2 — the ACP v2 agent's MCP tools.
``execute`` and nothing else: the rest of the v1 surface is reached through subtools ambient in the kernel, so there is no --include-tools here. Spawn it as an agent2 session's MCP server, or run it over HTTP as one kernel host for many sessions. """ # Lazy, and the ORDER is the point. --list-tools answers from the registry # in crow_cli.mcp2, which imports nothing; crow_cli.mcp2.main pulls in # fastmcp and the server instance, and serve() then imports the execute # tool, which pulls jupyter_client and ipykernel. Importing the runner # before the branch would make the cheap question pay for all of it. from crow_cli.mcp2 import tool_names
if list_tools: for name in tool_names(): typer.echo(name) raise typer.Exit(0)
from crow_cli.mcp2.main import serve
try: serve(transport, host, port) except ValueError as exc: # Loud and on stderr, and an exit code: stdout is the JSON-RPC stream # on the stdio transport, and a traceback there is a protocol violation # the spawning client would see instead of an error at spawn time. typer.secho(f"crow-cli mcp2: {exc}", fg="yellow", err=True) raise typer.Exit(2)
@app.command("timers")def run_timers( config_dir: Path = typer.Option( None, "--config-dir", "-d", help="Configuration directory (default: ~/.agents/crow)", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML file with config values to override", ), concurrency: int = typer.Option( 1, "--concurrency", help="Worker processes. One is enough: a timer job is two sqlite " "statements and a publish, and a second consumer only makes two " "timers that fire together land in a less predictable order.", ), loglevel: str = typer.Option("INFO", "--loglevel", help="Celery log level"),): """Run the timer worker — the process that fires scheduled wakes.
A timer is an ordinary task row with kind="timer" and a celery job behind it. When the job fires it closes the row, lands the delivery in the owner's mailbox and publishes the wake, exactly like a subagent finishing — so an agent that is parked gets its turn back, and one that is not gets the message at the top of its next turn.
This worker is the only piece that has to be running for any of that to happen, and it needs the broker and nothing else: the database rides in each message. """ # Lazy import, for the reason `mcp` gives: celery, kombu and billiard are # a third of a second of import that no other subcommand wants to pay. from crow_cli.timers import run_worker
config = Config.load(config_dir=config_dir) config = apply_config_overrides(config, config_file) if not config.redis_url: # Loud and on stderr, and an exit code: a worker started against # celery's own amqp:// default does not fail, it retries forever. typer.secho( "crow-cli timers: redis_url is empty, so there is no broker to run " "against. Set redis_url in config.yaml or CROW_REDIS_URL.", fg="yellow", err=True, ) raise typer.Exit(2)
run_worker(config.redis_url, concurrency=concurrency, loglevel=loglevel)
@app.command("init")def run_init( config_dir: Path = typer.Option( None, "--config-dir", "-d", help="Configuration directory (default: ~/.agents/crow)", ), yes: bool = typer.Option( False, "--yes", "-y", help="Skip all confirmation prompts", ), no_source: bool = typer.Option( False, "--no-source", help=( "Skip cloning the source checkout into <config-dir>/src. Crow is " "source-first: the checkout is what a source-first spawn runs, so " "skipping it leaves you on the installed build." ), ),): """Initialize Crow configuration interactively.""" if config_dir is None: config_dir = Path.home() / ".agents" / "crow" init_command(config_dir=config_dir, yes=yes, source=not no_source)
@app.command("auth")def run_auth(): """ Declare authentication support for ACP Registry compliance.
This agent supports authentication and is registered in the ACP Registry. No actual authentication is required for FOSS deployments. """ console.print( Panel( "[green]✓ Authentication Support Declared[/green]\n\n" "This agent declares authentication support for ACP Registry compliance.\n" "No actual authentication is required for FOSS deployments.\n\n" "[dim]Agent is ready for use.[/dim]", title="[magenta]🪶 Crow[/magenta]", border_style="green", ) )
# ============================================================================# Session Inspection# ============================================================================
@app.command("inspect")def inspect_db( session_id: str | None = typer.Option( None, "--session", "-s", help="Session ID to inspect" ), messages: bool = typer.Option(False, "--messages", "-m", help="Show messages"), limit: int = typer.Option(20, "--limit", "-l", help="Limit number of rows"), json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"), include_forks: bool = typer.Option( False, "--include-forks", help="Fold fork agents into counts/listings (hidden by default)", ),): """Inspect Crow sessions — state, messages, etc.""" asyncio.run(_inspect_db(session_id, messages, limit, json_output, include_forks))
async def _inspect_db(session_id, messages, limit, json_output, include_forks=False): if session_id: # Use existing AgentSession methods to get the latest agent for this session max_idx = await AgentSession.get_max_agent_idx(session_id) if max_idx < 1: if json_output: print(json.dumps({"error": f"Session '{session_id}' not found"})) else: client._console.print(f"[red]Session '{session_id}' not found[/red]") raise SystemExit(1)
agent_id = build_agent_id(session_id, max_idx) session_obj = await AgentSession.load(agent_id)
session_data = { "agent_id": session_obj.agent_id, "session_id": session_obj.session_id, "cwd": session_obj.cwd, "model_identifier": session_obj.model_identifier, "agent_idx": session_obj.agent_idx, } if include_forks: # Fork ids never appear unless explicitly asked for. mc = MemoryClient() try: agents = await mc.list_agents(session_id) finally: await mc.close() session_data["forks"] = [a.agent_id for a in agents if a.fork_idx > 1]
msgs_data = [] if messages: for msg in session_obj.messages[:limit]: msgs_data.append({"role": msg["role"], "data": msg})
if json_output: output = {"session": session_data} if messages: output["messages"] = msgs_data print(json.dumps(output, indent=2, default=str)) else: table = Table(title=f"Session: {session_id}", show_header=False) table.add_column("Field", style="cyan") table.add_column("Value", style="green") for key, val in session_data.items(): table.add_row(key, str(val)) client._console.print(table)
if messages: msg_table = Table(title=f"Messages ({len(msgs_data)} shown)") msg_table.add_column("ID", style="dim") msg_table.add_column("Role", style="cyan") msg_table.add_column("Content Preview", style="white") for i, msg in enumerate(msgs_data): content = msg["data"].get("content", "") if isinstance(content, list): content = str(content) preview = content[:100] + "..." if len(content) > 100 else content msg_table.add_row(str(i), msg["role"], preview.replace("\n", " ")) client._console.print(msg_table) else: # List all sessions, most-recently-active first. try: sessions_list = await AgentSession.list_sessions( limit=limit, include_forks=include_forks ) except MemoryServiceError as e: if json_output: print(json.dumps({"error": f"memory error: {e.detail}"})) else: client._console.print(f"[red]memory error: {e.detail}[/red]") raise SystemExit(1)
if not sessions_list: if json_output: print(json.dumps({"sessions": []})) else: client._console.print("[yellow]No sessions found[/yellow]") raise SystemExit(0)
if json_output: print( json.dumps( {"sessions": [s.to_dict() for s in sessions_list]}, indent=2 ) ) else: table = Table(title="Crow Sessions") table.add_column("Session ID", style="cyan") table.add_column("Last active", style="dim") table.add_column("Model", style="green") table.add_column("Agents", style="magenta") table.add_column("Messages", style="yellow") for sess in sessions_list: table.add_row( sess.session_id, sess.last_activity[:19], sess.model_identifier or "", str(sess.agent_count), str(sess.message_count), ) client._console.print(table) client._console.print( f"\n[dim]Use --session <id> --messages to inspect a specific session[/dim]" )
# ============================================================================# Telemetry — the MCP query tools as CLI surfaces.# Same functions, two facades: the agent meets them as MCP tools# (list_sessions/query_memory/query_session), the human meets them here.# ============================================================================
def _telemetry_db_override(config_file: Path | None) -> None: """Point the memory store at the SAME db the rest of the CLI would use.
The store resolves CROW_DB_URI env -> config.yaml; --config-file must win here exactly like it does for `run` (e.g. dev overrides pointing at a fresh db). """ if config_file is None: return config = apply_config_overrides(Config.load(), config_file) os.environ["CROW_DB_URI"] = config.db_uri
def _print_telemetry(result: str, raw: bool) -> None: if raw: print(result) else: from rich.markdown import Markdown
console.print(Markdown(result))
def _content_mode(value: str): from crow_cli.mcp.memory.main import ContentMode
try: return ContentMode(value) except ValueError: choices = ", ".join(m.value for m in ContentMode) console.print(f"[red]Invalid --mode '{value}' (one of: {choices})[/red]") raise typer.Exit(1)
@app.command("list-sessions")def cli_list_sessions( limit: int = typer.Option(50, "--limit", "-l", help="Max sessions (cap 200)"), offset: int = typer.Option(0, "--offset", help="Pagination offset"), include_forks: bool = typer.Option( False, "--include-forks", help="Fold fork agents into the listing (hidden by default)", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML file with config values to override" ), raw: bool = typer.Option( False, "--raw", help="Print the raw markdown instead of rendering it" ),): """List agent sessions, most-recently-active first (who's working now).
Same implementation as the list_sessions MCP tool.""" _telemetry_db_override(config_file) from crow_cli.mcp.memory.main import list_sessions
result = asyncio.run( list_sessions(limit=limit, offset=offset, include_forks=include_forks) ) _print_telemetry(result, raw)
@app.command("query-memory")def cli_query_memory( query: str = typer.Argument(..., help="Search term"), mode: str = typer.Option( "conversation", "--mode", "-m", help="conversation | with_thinking | with_tools | full", ), limit: int = typer.Option(20, "--limit", "-l", help="Max matches (cap 200)"), offset: int = typer.Option(0, "--offset", help="Pagination offset"), include_forks: bool = typer.Option( False, "--include-forks", help="Include matches from fork agents' own rows (hidden by default)", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML file with config values to override" ), raw: bool = typer.Option( False, "--raw", help="Print the raw markdown instead of rendering it" ),): """Search conversation history ACROSS all sessions (BM25 discovery).
Same implementation as the query_memory MCP tool.""" _telemetry_db_override(config_file) from crow_cli.mcp.memory.main import query_memory
result = asyncio.run( query_memory( query=query, mode=_content_mode(mode), limit=limit, offset=offset, include_forks=include_forks, ) ) _print_telemetry(result, raw)
@app.command("query-session")def cli_query_session( session_id: str = typer.Argument(..., help="The session to read"), query: str = typer.Option(None, "--query", "-q", help="Search within the session"), agent_idx: int = typer.Option( None, "--agent-idx", help="Narrow to one agent (default: all agents)" ), mode: str = typer.Option( "conversation", "--mode", "-m", help="conversation | with_thinking | with_tools | full", ), order: str = typer.Option( "desc", "--order", help="desc = newest-first (default); asc = oldest-first" ), context: int = typer.Option( 0, "--context", "-C", help="Messages around each match (search only)" ), after: str = typer.Option(None, "--after", help="ISO datetime lower bound"), before: str = typer.Option(None, "--before", help="ISO datetime upper bound"), limit: int = typer.Option( None, "--limit", "-l", help="Max messages (browse default 1, search 20; cap 200)" ), offset: int = typer.Option(0, "--offset", help="Pagination offset into the past"), search_type: str = typer.Option( "semantic", "--search-type", help="semantic (BM25) | keyword | both" ), include_forks: bool = typer.Option( False, "--include-forks", help="Fold fork agents into the view (hidden by default)", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML file with config values to override" ), raw: bool = typer.Option( False, "--raw", help="Print the raw markdown instead of rendering it" ),): """Read or search one session's history across all its agents.
Browse (no --query) returns the tail by default; --query searches. Same implementation as the query_session MCP tool.""" _telemetry_db_override(config_file) from crow_cli.mcp.memory.main import SearchType, query_session
try: st = SearchType(search_type) except ValueError: choices = ", ".join(s.value for s in SearchType) console.print( f"[red]Invalid --search-type '{search_type}' (one of: {choices})[/red]" ) raise typer.Exit(1)
result = asyncio.run( query_session( session_id=session_id, query=query, agent_idx=agent_idx, mode=_content_mode(mode), order=order, context=context, after=after, before=before, limit=limit, offset=offset, search_type=st, include_forks=include_forks, ) ) _print_telemetry(result, raw)
# ============================================================================# Main Commands# ============================================================================
def _sampling_label(model) -> str: """One-line sampling summary for the models table: effort when set, else temperature plus whichever optional params are configured.""" if model.reasoning_effort: return model.reasoning_effort parts = [f"temp={model.temperature}"] for label, value in ( ("top_p", model.top_p), ("top_k", model.top_k), ("min_p", model.min_p), ("presence", model.presence_penalty), ("repeat", model.repetition_penalty), ): if value is not None: parts.append(f"{label}={value}") return " ".join(parts)
@app.command()def models( config_dir: Path = typer.Option( None, "--config-dir", "-d", help="Configuration directory (default: ~/.agents/crow)", ), json_out: bool = typer.Option( False, "--json", "-j", help="Machine-readable JSON output" ),): """List the models available from config.yaml (first one is the default).""" config = Config.load(config_dir=config_dir) rows = [ { "name": m.name, "provider": m.provider_name, "model_id": m.model_id, "modality": ",".join(m.modality), "sampling": _sampling_label(m), "fallbacks": list(m.fallbacks), "default": i == 0, } for i, m in enumerate(config.llm.models.values()) ] if json_out: print(json.dumps(rows, indent=2)) return if not rows: console.print("[yellow]No models configured.[/yellow]") return table = Table(title="Models") table.add_column("", justify="center") # default marker table.add_column("name", style="bold", overflow="fold") table.add_column("provider", overflow="fold") table.add_column("model_id", overflow="fold") table.add_column("modality", overflow="fold") table.add_column("sampling", overflow="fold") table.add_column("fallbacks", overflow="fold") for r in rows: table.add_row( "[green]*[/green]" if r["default"] else "", r["name"], r["provider"], r["model_id"], r["modality"], r["sampling"], ",".join(r["fallbacks"]), ) console.print(table) console.print("[dim]* = default (first in config.yaml); text,image = default (assume vision)[/dim]")
@app.command()def agents( config_dir: Path = typer.Option( None, "--config-dir", "-d", help="Configuration directory (default: ~/.agents/crow)", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML override file applied on top of the loaded config — the same " "one `run` takes, so an override can be listed before it is launched.", ), json_out: bool = typer.Option( False, "--json", "-j", help="Machine-readable JSON output" ),): """List the `agent_servers` entries `crow-cli run -a NAME` can drive.
The TOP entry is what a bare `run` launches — the same rule bare `crow-cli` follows — so config order decides the default. An entry's `protocol` picks the client: `acp` is the v1 client, `acp2` is client2. `auto` means the entry declared none and `run` asks the agent at `initialize`, which is what an entry that is not crow's own should do. With nothing configured, `run` falls back to crow's own v2 agent. """ config = Config.load(config_dir=config_dir) apply_config_overrides(config, config_file) servers = list(parse_agent_servers(config.agent_servers).values()) fallback = not servers if fallback: servers = [crow_agent_server(V2, config_dir=config_dir)] rows = [ { "name": s.name, "title": s.title, "protocol": s.protocol or "auto", "launch": s.launch, "tools": "global" if s.mcp_servers is None else ", ".join(s.mcp_servers), "builtin": s.builtin, "default": i == 0, } for i, s in enumerate(servers) ] if json_out: print(json.dumps({"fallback": fallback, "agents": rows}, indent=2)) return table = Table(title="Agent servers") table.add_column("", justify="center") # default marker table.add_column("name", style="bold", overflow="fold") table.add_column("protocol", overflow="fold") table.add_column("launch", overflow="fold") table.add_column("tools", overflow="fold") for r in rows: table.add_row( "[green]*[/green]" if r["default"] else "", r["name"], r["protocol"], r["launch"], r["tools"], ) console.print(table) if fallback: console.print( "[yellow]No agent_servers configured — `run` falls back to " "crow's own v2 agent.[/yellow]" ) else: console.print( "[dim]* = default (top entry in config.yaml agent_servers); " "tools 'global' = the client's mcpServers key; " "protocol 'auto' = asked at initialize[/dim]" )
@app.command()def run( prompt: str = typer.Argument( None, help="Prompt to send (optional in interactive mode; '-' reads stdin)" ), prompt_file: Path | None = typer.Option( None, "--prompt-file", "-f", help="Read the prompt from a file (useful for long subagent prompts)", ), interactive: bool = typer.Option( False, "--interactive", "-i", help="Run in interactive mode" ), session_id: str | None = typer.Option( None, "--session", "-s", help="Load existing session" ), fork: bool = typer.Option( False, "--fork", help="Spawn a FORK of -s/--session and run inside it (requires -s). " "The fork shares the source's history (no copying) and persists under " "its own three-part id, which is printed so you can continue it with -s.", ), fork_idx: int | None = typer.Option( None, "--fork-idx", help="Continue existing fork N of -s/--session (requires -s). " "Fork 1 is the trunk — plain -s already does that.", ), cwd: str = typer.Option(os.getcwd(), "--cwd", "-c", help="Working directory"), verbose: bool = typer.Option( False, "--verbose", "-v", help="Enable verbose logging" ), config_dir: Path = typer.Option( None, "--config-dir", "-d", help="Configuration directory (default: ~/.agents/crow)", ), config_file: Path = typer.Option( None, "--config-file", "-o", help="YAML override file applied on top of the loaded config (forwarded to the agent)", ), model: str | None = typer.Option( None, "--model", "-m", help="Model to use (name from config.yaml models:); overrides the session's saved model", ), agent_server: str | None = typer.Option( None, "--agent-server", "-a", help="Named `agent_servers` entry to drive (see `crow-cli agents`). Default: the " "TOP entry in config, or crow's own v2 agent when none is configured.", ), replay: bool = typer.Option( False, "--replay", help="Re-emit a resumed session's stored updates before prompting (acp2 agents " "only — a v1 `session/load` always replays).", ), json_out: bool = typer.Option( False, "--json", "-j", help="Machine-readable JSONL to stdout (one event per line; disables rich rendering)", ),): """ Run the Crow client — send a prompt to an agent (one-shot) or start a REPL.
MODES: default sends one prompt, prints the response, and exits; -i/--interactive starts a REPL loop.
MODELS: the agent uses the first model in config.yaml's models: section by default. Override with -m/--model <name> (see `crow-cli models`); the override also wins over a resumed session's saved model. The choice travels over the wire (session/set_config_option), not in the agent's argv, so it reaches any entry that publishes a `model` config option.
AGENTS: which agent runs is config, not code. `crow-cli agents` lists the `agent_servers` entries; -a/--agent-server NAME drives one, and a bare `run` drives the TOP entry (crow's own v2 agent when none is configured). Each entry declares its `protocol` — `acp` gets the v1 client, `acp2` gets client2 — and may carry its own `mcpServers` tool supply. An unknown NAME is an error, never a silent fallback to something else.
MACHINE OUTPUT: -j/--json emits JSONL to stdout — one event per line (session, thinking, message, tool_call, usage, result, error), rich rendering disabled. Pipe to a .jsonl file or jq. One-shot only.
PROMPT SOURCES: the prompt can be a positional argument, a file (--prompt-file/-f), or stdin (pass '-' as the prompt).
SUBAGENTS — agents launch subagents with the `task` MCP tool (bg-only: launch, re-prompt, cancel; completions land in the owner's mailbox). Every session persists in the shared sqlite store, so YOU can also launch a worker, keep talking to it by session id, attach to a subagent the task system spawned, and read any session's thoughts from any other agent. The loop:
1. Launch a worker (it gets a coolname session id):
crow-cli run "refactor the parser into its own module"
2. Continue that session with -s (give it a hellacious timeout if the prompt is big):
crow-cli run -s <session-id> "now add tests"
3. Send a long, pre-written prompt from a file or stdin:
crow-cli run -f brief.md -s <session-id> cat brief.md | crow-cli run -
4. From another agent, read what the worker did with the query_session MCP tool: query_session(session_id="<session-id>") — a bare call returns the worker's latest message.
That's the whole mechanism: launch or attach with `run`, read thoughts with query_session, verify artifacts on disk. No bespoke agent-to-agent protocol — just a shared database and a read query.
FORKS — branch a session's history without copying it:
1. Spawn a fork of a session and run inside it (the fork sees the whole trunk history; the trunk never sees the fork):
crow-cli run -s <session-id> --fork "what would you do differently?"
2. The fork persists under its own three-part id (printed on creation). Continue it like any session:
crow-cli run -s <session-id>-<agent-idx>-<fork-idx> "keep going"
3. Or continue fork N of a session directly:
crow-cli run -s <session-id> --fork-idx 2 "keep going"
Forks are hidden from the telemetry surfaces (inspect, query_session, query_memory, list_sessions) unless include_forks/--include-forks is set. """ if verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.WARNING)
if json_out and interactive: print(json.dumps({"type": "error", "error": "--json is one-shot only; not supported with --interactive"})) raise SystemExit(1)
# Resolve the prompt source: --prompt-file > stdin ('-') > positional arg. if prompt_file is not None: if prompt is not None: client._console.print( "[red]Error: provide a prompt OR --prompt-file, not both[/red]" ) raise SystemExit(1) if not prompt_file.exists(): client._console.print( f"[red]Error: prompt file not found: {prompt_file}[/red]" ) raise SystemExit(1) prompt = prompt_file.read_text() elif prompt == "-": prompt = sys.stdin.read()
# Validate arguments if fork and fork_idx is not None: client._console.print( "[red]Error: --fork and --fork-idx are mutually exclusive " "(spawn a fork OR continue one)[/red]" ) raise SystemExit(1) if (fork or fork_idx is not None) and not session_id: client._console.print( "[red]Error: --fork/--fork-idx require -s/--session (the fork source)[/red]" ) raise SystemExit(1)
if not interactive and prompt is None: client._console.print( "[red]Error: Either provide a prompt or use -i for interactive mode[/red]" ) client._console.print("\n[yellow]Examples:[/yellow]") client._console.print(" crow-cli run 'list the files'") client._console.print(" crow-cli run -i") client._console.print(" crow-cli run -s <session-id> -i") client._console.print(" crow-cli run -f prompt.md -s <session-id>") client._console.print(" cat prompt.md | crow-cli run -") raise SystemExit(1)
# The CLIENT owns which agent runs and what tools it gets, so config is # read here — after flag validation, which must be able to fail without a # config dir to read. config = Config.load(config_dir) apply_config_overrides(config, config_file) try: server = select_agent_server( agent_server, config.agent_servers, V2, config_dir, config_file ) except AgentServerError as e: client._console.print(f"[red]Error: {e}[/red]") raise SystemExit(1)
# -m is a config.yaml model NAME; the wire's `model` config option speaks # `provider:model_id`. Resolved here, before anything is spawned, so a typo # fails instead of quietly running on the config's first model. model_value = None if model: try: model_value = config.llm.option_value(model) except ValueError as e: client._console.print(f"[red]Error: {e}[/red]") raise SystemExit(1)
# --fork-idx names a fork by number; the wire speaks three-part ids, and # both clients need the same resolution, so it happens once, here. wire_session = session_id if session_id and fork_idx is not None: engine = get_engine(config.db_uri) max_agent = get_max_agent_idx(engine, session_id) wire_session = build_agent_id(session_id, max_agent, fork_idx)
if server.protocol is None: # The entry did not say, so the agent gets asked. One spawn, one # `initialize`, and the answer picks the client — a config field # asserting the same thing is a second source of truth whose only # talent is disagreeing with the first, silently. asyncio.run( _dispatch( server, config, prompt, interactive, wire_session, cwd, model_value, json_out, fork, replay, ) ) return
if server.protocol == V2: # Lazy on purpose: the v2 schema costs ~0.36s to import and a v1 run # never needs it. from crow_cli.client2.main import run_v2
asyncio.run( run_v2( server, config, console=client._console, prompt=prompt, interactive=interactive, session_id=wire_session, fork=fork, cwd=cwd, model=model_value, json_out=json_out, replay=replay, ) ) return
asyncio.run( _run_async( server, config, prompt, interactive, wire_session, cwd, model_value, json_out, fork=fork, ) )
def _emit_json(**event: Any) -> None: print(json.dumps(event), flush=True)
async def _dispatch( server: AgentServer, config: Config, prompt: str | None, interactive: bool, session_id: str | None, cwd: str, model: str | None, json_out: bool, fork: bool, replay: bool,) -> None: """Ask the agent which protocol it speaks, then drive it with that client.
This is the path an entry with no ``protocol`` takes, and it spawns once: the probe IS the connection, so the handshaked child is handed to whichever stack the answer selects instead of being spawned a second time by it.
An agent that cannot be asked — dead, silent, or speaking a version this client does not — is an error with the child's own last words on it, not a hang. That is the failure a declared ``protocol`` turns into a silent one. """ # Lazy on purpose, and only reachable from here: an entry that declares its # protocol never imports discovery, and so never imports the v2 schema. from crow_cli.discover import ProtocolError, agent_connection
workdir = cwd or os.getcwd() try: async with agent_connection(server, workdir) as conn: if conn.protocol == V2: from crow_cli.client2.main import run_v2
await run_v2( server, config, console=client._console, prompt=prompt, interactive=interactive, session_id=session_id, fork=fork, cwd=workdir, model=model, json_out=json_out, replay=replay, conn=conn, ) else: await _run_async( server, config, prompt, interactive, session_id, workdir, model, json_out, fork=fork, discovered=conn, ) except ProtocolError as e: client._console.print(f"[red]Error: {e}[/red]") raise SystemExit(1)
async def _run_async( server: AgentServer, config: Config, prompt: str | None, interactive: bool, session_id: str | None, cwd: str, model: str | None = None, json_out: bool = False, fork: bool = False, discovered: "Connection | None" = None,) -> None: """Async implementation of `run` for a v1 (``acp``) agent.
``server`` is already resolved and ``config`` already loaded: which agent runs and what tools it gets are the client's decisions and the caller made them, so this function only drives the wire. ``model`` is already the ``provider:model_id`` value the agent's option speaks, not a config name.
``discovered`` is a child :mod:`crow_cli.discover` already spawned and asked. Its streams are adopted instead of spawning a second process for the same agent, its handshake is not repeated, and its protocol — not the entry's, which declared none — is what gets announced. """ protocol = discovered.protocol if discovered is not None else server.protocol client._json_mode = json_out if not json_out: mode = ( "[green]Interactive[/green]" if interactive else "[yellow]Single-shot[/yellow]" ) client._console.print( Panel( "[bold]Crow ACP Client[/bold]\n\n" f"Agent: [cyan]{server.title}[/cyan] [dim]({protocol})[/dim]\n" f"Working directory: [cyan]{cwd}[/cyan]\n" f"Mode: {mode}\n" f"Session: {session_id or '[dim]New session[/dim]'}", title="[magenta]🪶 Crow[/magenta]", border_style="magenta", ) )
# The CLIENT owns tool supply: hand mcpServers to the agent in # new_session/load_session (config.yaml -> FastMCP dict -> ACP server # objects, the inverse of the agent's acp_to_fastmcp_config). The entry's # own mcpServers replaces the global map when it declares one; `crow-cli # mcp` rides along because it is an entry like any other. Empty or absent # = the session runs with zero tools. supply = tool_supply(server, config.mcp_servers) mcp_servers = fastmcp_config_to_acp_servers(supply) if not json_out: names = ", ".join(s.name for s in mcp_servers) client._console.print( f"[cyan]MCP servers: {names or '[dim]none — zero tools[/dim]'}[/cyan]" )
# Spawn the resolved argv, honored exactly as written — this is what makes # a custom `agent_servers` entry work, and why no crow flag is added here. # A discovered child is already spawned and handshaked: adopting it is the # whole point of a probe that IS the connection, since spawning again would # be a second cold start of the same agent. if discovered is not None: proc = discovered.proc else: proc = await client.spawn_agent(cwd, argv=server.argv, env=server.env)
try: # Connect conn = await connect_client( proc, client, initialized=bool(discovered and discovered.initialized) )
# Create, fork, or load session if fork: # session/fork (UNSTABLE): the fork shares the source's history # (prefix rows, never copied) and gets its own three-part wire id. if not json_out: client._console.print(f"[cyan]Forking session: {session_id}[/cyan]") forked = await conn.fork_session( session_id=session_id, cwd=cwd, mcp_servers=mcp_servers ) actual_session_id = forked.session_id if not json_out: client._console.print(f"[green]Fork created: {actual_session_id}[/green]") elif session_id: # `session_id` is already the wire id: `run` resolved --fork-idx to # a three-part id before dispatching, because the v2 client needs # the same answer and neither should own that translation. if not json_out: client._console.print(f"[cyan]Loading session: {session_id}[/cyan]") await conn.load_session( session_id=session_id, mcp_servers=mcp_servers, cwd=cwd ) actual_session_id = session_id else: if not json_out: client._console.print("[cyan]Creating new session...[/cyan]") session = await conn.new_session(mcp_servers=mcp_servers, cwd=cwd) actual_session_id = session.session_id if not json_out: client._console.print( f"[green]Session created: {actual_session_id}[/green]" ) if model: # Model choice is the CLIENT's job: it travels over the protocol, # not in the agent's argv, so it works for any agent that publishes # a `model` config option — including a custom `agent_servers` # entry, which is the first time -m has reached one. await conn.set_config_option( config_id="model", session_id=actual_session_id, value=model )
if json_out: _emit_json( type="session", session_id=actual_session_id, cwd=cwd, agent=server.name, protocol=protocol, mode="interactive" if interactive else "one_shot", model=model, )
# Run if interactive: await client.interactive_loop(conn, actual_session_id) else: await client.send_prompt(conn, actual_session_id, prompt) if json_out: client._flush_json() _emit_json(type="result", session_id=actual_session_id) else: client._console.print(f"\n[dim]Session: {actual_session_id}[/dim]") client._console.print( f'[dim]Use crow-cli run -s {actual_session_id} "<your—message>" to continue this conversation[/dim]' ) except Exception as e: # Surface the agent's stderr (e.g. a startup failure like an unknown # -m model) before re-raising. Wait briefly for the process to die so # the stderr read completes — the old .done() check raced the reader. stderr_output = b"" reader = getattr(proc, "_stderr_reader", None) if reader is None and discovered is not None: # A discovered child's stderr went to discovery's drainer, not to a # _stderr_reader task, so its deque is the only copy that exists. stderr_output = discovered.stderr_tail().encode() elif reader is not None: try: if proc.returncode is None: with contextlib.suppress(asyncio.TimeoutError): await asyncio.wait_for(proc.wait(), timeout=2) if proc.returncode is not None: stderr_output = await asyncio.wait_for( asyncio.shield(reader), timeout=3 ) except Exception: pass if stderr_output and stderr_output.strip(): text = stderr_output.decode(errors="replace") if json_out: _emit_json(type="error", error=text.strip()) else: client._console.print() client._console.print("[red]═══ Agent subprocess failed ═══[/red]") client._console.print() client._console.print(text) client._console.print( "[yellow]The agent subprocess exited with an error. " "The traceback above shows what went wrong.[/yellow]" ) raise e
finally: # Cleanup if proc.returncode is None: proc.terminate() with contextlib.suppress(ProcessLookupError): await proc.wait()
# ============================================================================# Entry Point# ============================================================================
def _print_version_and_exit(value: bool) -> None: if value: import crow_cli
typer.echo(f"crow-cli {crow_cli.__version__}") raise typer.Exit()
@app.callback(invoke_without_command=True)def global_callback( ctx: typer.Context, version: bool = typer.Option( False, "--version", "-V", help="Print the crow-cli version and exit.", is_eager=True, callback=_print_version_and_exit, ),): """Crow ACP Client - Transparent, observable agent client.
With no subcommand, prints this help: every capability is a subcommand. """ if ctx.invoked_subcommand is None: typer.echo(ctx.get_help()) raise typer.Exit()
def main(): app()
if __name__ == "__main__": main()