Something went wrong. Try again.
MCP based ACP agent
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279"""The `agent_servers` registry: what a CLIENT launches, and how it speaks.
Config-driven, client-side, and the reason every client canboth launch somebody else's agent without a code change:
agent_servers: crow-cli: command: uv args: ["--project", "~/.agents/crow/src/crow-cli", "run", "crow-cli", "acp"] something-else: command: ~/src/other-agent/run.sh
Every entry is a command, honored exactly as written — crow never substitutesits own agent for a configured one. Crow's own agent exists only as thefallback when nothing is configured (:func:`crow_agent_server`).
``protocol`` is an optional override, not something an entry owes you. WhichCLIENT drives it — :mod:`crow_cli.client` for v1, :mod:`crow_cli.client2` forv2 — is settled by the ``initialize`` handshake: the client sends the latestversion it speaks and the agent answers with the one it chose, so the agentsays what it is and nothing has to be told in advance(:mod:`crow_cli.discover`). Declaring ``protocol`` skips that round trip, whichis why crow's own entries do. Guessing from the argv instead would be aheuristic that fails on the first agent whose path happens to contain ``acp2``,and a config field that disagrees with the agent is a hang with no error oneither side. A client that speaks only one protocol refuses an entry declaredfor the other rather than launching it and failing the handshake.
``mcpServers`` is the other client-owned half: the tools this agent is handedat ``session/new``. Absent means the client's global ``mcpServers`` supply,which is what every session gets today. Present, it REPLACES that supply forthis agent only — which is how a v2 agent gets crow-mcp2 (whose ``execute``returns the terminal envelope) without changing what the v1 sessions on thesame box are handed. Both shapes are the same mapping the global key uses, soan entry can be copied between them.
This module knows nothing about either wire protocol: it turns config into anargv, an environment and an optional protocol override — the whole of what aclient needs to spawn an agent by name."""
from __future__ import annotations
import loggingfrom dataclasses import dataclass, fieldfrom typing import Any, Optional
from crow_cli.cli.source import spawn_argv
logger = logging.getLogger(__name__)
#: ACP v1 — :mod:`crow_cli.client`, ``crow-cli acp``.V1 = "acp"
#: ACP v2 — :mod:`crow_cli.client2`, ``crow-cli acp2``.V2 = "acp2"
#: What an entry's ``protocol`` override may say. Order is the order they are#: listed in an error message. Absent is not a third value: it means "ask the#: agent", which is :mod:`crow_cli.discover`'s job.PROTOCOLS = (V1, V2)
#: The identity crow's own agent is listed under, when a client lists the#: registry plus the fallback. A domain, matching the store's convention.CROW_IDENTITY = "crow-ai.dev"
class AgentServerError(Exception): """An `agent_servers` entry is missing or malformed."""
@dataclass(frozen=True)class AgentServer: """One launchable agent: an argv, an environment, and maybe a protocol.
``argv`` is what a client spawns and ``launch`` is what a human reads; the list is the truth and the string is decoration, because a shell-quoted round trip is how an argv with a space in it gets lost. """
name: str command: str args: tuple[str, ...] = () env: dict[str, str] = field(default_factory=dict) #: An override, not a requirement. ``None`` means the client asks the agent #: at ``initialize`` which version it speaks; a value here skips the round #: trip for an entry that already knows. protocol: Optional[str] = None display_name: str = "" mcp_servers: Optional[dict[str, Any]] = None builtin: bool = False
@property def argv(self) -> list[str]: """The spawn: command then args, exactly as configured.""" return [self.command, *self.args]
@property def title(self) -> str: """What a client shows: the configured display name, else the key.""" return self.display_name or self.name
@property def launch(self) -> str: """The argv as one line, for help text and error messages.""" return " ".join(self.argv)
def parse_agent_server(name: str, spec: Any) -> AgentServer: """Validate one `agent_servers` entry.
Raises: AgentServerError: the entry is not a mapping, has no command, or says something untrue about its args, env, protocol or mcpServers. """ if not isinstance(spec, dict): raise AgentServerError(f"agent_servers.{name!r} must be a mapping.")
kind = spec.get("type", "custom") if kind != "custom": raise AgentServerError( f"agent_servers {name!r}: unknown type {kind!r}; an agent server " "is a command (type 'custom' or none at all)." )
command = spec.get("command") if not command: raise AgentServerError(f"agent_servers {name!r}: requires a 'command'.") args = spec.get("args") or [] if not isinstance(args, list): raise AgentServerError(f"agent_servers {name!r}: 'args' must be a list.") env = spec.get("env") or {} if not isinstance(env, dict): raise AgentServerError(f"agent_servers {name!r}: 'env' must be a mapping.")
protocol = spec.get("protocol") if protocol is not None and protocol not in PROTOCOLS: raise AgentServerError( f"agent_servers {name!r}: unknown protocol {protocol!r}; expected " f"one of {', '.join(PROTOCOLS)}." )
servers = spec.get("mcpServers") if servers is not None and not isinstance(servers, dict): raise AgentServerError( f"agent_servers {name!r}: 'mcpServers' must be a mapping of name to " "server, shaped like the global mcpServers key." )
return AgentServer( name=name, command=str(command), args=tuple(str(a) for a in args), env={str(k): str(v) for k, v in env.items()}, protocol=protocol, display_name=str(spec["name"]) if spec.get("name") else "", mcp_servers=servers, )
def resolve_agent_server(name: str, agent_servers: dict[str, Any]) -> AgentServer: """Resolve a configured name into an :class:`AgentServer`.
The entry is honored exactly as written: its command, args and env ARE the launch. Crow never substitutes its own agent for a configured one — that is what ``-a NAME`` means.
Raises: AgentServerError: the name is not configured, or its entry is invalid. """ if name not in agent_servers: known = ", ".join(agent_servers) or "none configured" raise AgentServerError( f"No agent_servers entry named {name!r}. Configured: {known}." ) return parse_agent_server(name, agent_servers[name] or {})
def parse_agent_servers(agent_servers: dict[str, Any]) -> dict[str, AgentServer]: """Every launchable entry, in config order (the top one is the default).
An entry that fails to resolve is logged and skipped rather than raised: one broken entry must not take down the client that lists them. """ servers: dict[str, AgentServer] = {} for name in agent_servers or {}: try: servers[name] = parse_agent_server(name, agent_servers[name] or {}) except AgentServerError as error: logger.warning("agent_servers %r: %s", name, error) return servers
def crow_agent_server( protocol: str = V1, config_dir: Any = None, config_file: Any = None,) -> AgentServer: """Crow's own agent, for whichever protocol the client speaks.
The fallback when nothing is configured: always the code that is actually running (see :func:`crow_cli.cli.source.spawn_argv`). Pointing at a source checkout is an ``agent_servers`` entry the user writes instead.
No ``--model`` here on purpose. Model choice is the CLIENT's job: it goes over ``session/set_config_option`` once the session exists, which is the one path that works for every agent — crow's own and any custom entry alike. Baking it into this argv would make ``-m`` work for one agent and silently vanish for the others. """ flags: list[str] = [] if config_dir is not None: flags += ["--config-dir", str(config_dir)] if config_file is not None: flags += ["--config-file", str(config_file)] argv, _kind = spawn_argv(flags, protocol) return AgentServer( name=CROW_IDENTITY, command=argv[0], args=tuple(argv[1:]), protocol=protocol, display_name="Crow", builtin=True, )
def default_agent_server( agent_servers: dict[str, Any], fallback_protocol: str = V1, config_dir: Any = None, config_file: Any = None,) -> AgentServer: """The agent a client launches when nobody named one.
The TOP config entry, which is the rule bare ``crow-cli`` already uses, so one config orders both surfaces. Crow's own agent when the registry is empty — and then ``fallback_protocol`` decides which of crow's entry points a client gets, because there is no entry left to declare it: a v2 client asks for ``acp2``, a v1 client for ``acp``. """ top = next(iter(parse_agent_servers(agent_servers).values()), None) if top is not None: return top return crow_agent_server(fallback_protocol, config_dir, config_file)
def select_agent_server( name: Optional[str], agent_servers: dict[str, Any], fallback_protocol: str = V1, config_dir: Any = None, config_file: Any = None,) -> AgentServer: """The agent a client launches: ``-a NAME``, else the default.
Raises: AgentServerError: NAME is not configured, or its entry is invalid. An unknown name is an error rather than a fallback, because silently launching a different agent than the one asked for is the kind of wrong answer nobody notices. """ if name: return resolve_agent_server(name, agent_servers) return default_agent_server( agent_servers, fallback_protocol, config_dir, config_file )
def tool_supply(server: AgentServer, config_mcp_servers: dict[str, Any]) -> dict[str, Any]: """The mcpServers map a client hands this agent at ``session/new``.
The entry's own supply when it declares one, else the client's global one. The client owns tool supply either way — the agent never reads config for this, so what is returned here is exactly what the session gets. """ if server.mcp_servers is not None: return server.mcp_servers return config_mcp_servers or {}