|
| 1 | +"""Apply registry-resolved assets (#246) to the agent's runtime environment. |
| 2 | +
|
| 3 | +The orchestrator resolves a blueprint's ``registry://`` pins at the create-task |
| 4 | +boundary and threads a ``resolved_assets`` bundle into the invocation payload |
| 5 | +(see docs/design/REGISTRY.md §7/§8). This module is the agent-side consumer: |
| 6 | +it takes that bundle and applies each asset kind with the right mechanism. |
| 7 | +
|
| 8 | +MVP (this PR) wires ``mcp_server`` end-to-end — the resolved server config is |
| 9 | +merged into ``<repo_dir>/.mcp.json`` alongside whatever ``channel_mcp.py`` |
| 10 | +wrote, so the Claude Agent SDK (``setting_sources=["project"]``) picks it up at |
| 11 | +session start. ``cedar_policy_module`` and ``skill`` are stubs here; PR 3 fills |
| 12 | +them in (Cedar text appended to the PolicyEngine set; skill prompt fragments |
| 13 | +into the SDK setting sources). |
| 14 | +
|
| 15 | +Design note — parity with channel_mcp.py: both write ``.mcp.json`` by |
| 16 | +read-merge-write on the ``mcpServers`` map, never clobbering other servers. |
| 17 | +Registry assets and the channel MCP can therefore coexist in one file. |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import json |
| 23 | +import os |
| 24 | +from typing import Any |
| 25 | + |
| 26 | +from shell import log |
| 27 | + |
| 28 | +#: Key under which the resolved MCP server config lives in the descriptor |
| 29 | +#: (REGISTRY.md §3.3). The value is a ready-to-write ``mcpServers`` entry. |
| 30 | +_MCP_SERVER_CONFIG_KEY = "server_config" |
| 31 | + |
| 32 | + |
| 33 | +def _read_existing_mcp_config(path: str) -> dict[str, Any]: |
| 34 | + """Return the parsed .mcp.json at ``path``, or an empty dict if absent/invalid. |
| 35 | +
|
| 36 | + Mirrors ``channel_mcp._read_existing_mcp_config`` — malformed JSON is logged |
| 37 | + and treated as absent rather than crashing the agent on a broken file. |
| 38 | + """ |
| 39 | + if not os.path.isfile(path): |
| 40 | + return {} |
| 41 | + try: |
| 42 | + with open(path, encoding="utf-8") as f: |
| 43 | + parsed = json.load(f) |
| 44 | + if isinstance(parsed, dict): |
| 45 | + return parsed |
| 46 | + log("WARN", f"Ignoring non-object .mcp.json at {path} (got {type(parsed).__name__})") |
| 47 | + except (OSError, json.JSONDecodeError) as e: |
| 48 | + log("WARN", f"Failed to read existing .mcp.json at {path}: {type(e).__name__}: {e}") |
| 49 | + return {} |
| 50 | + |
| 51 | + |
| 52 | +def _mcp_server_key(asset: dict[str, Any]) -> str: |
| 53 | + """The ``mcpServers`` key an asset registers under. |
| 54 | +
|
| 55 | + Prefer the descriptor's ``tool_prefix`` stripped of the ``mcp__`` scaffolding |
| 56 | + (so tools surface consistently), falling back to ``namespace-name`` which is |
| 57 | + always present and unique per asset. |
| 58 | + """ |
| 59 | + namespace = asset.get("namespace", "") |
| 60 | + name = asset.get("name", "") |
| 61 | + return f"{namespace}-{name}".strip("-") or name or "registry-mcp" |
| 62 | + |
| 63 | + |
| 64 | +def apply_mcp_assets(repo_dir: str, resolved_mcp_servers: list[dict[str, Any]]) -> int: |
| 65 | + """Merge resolved MCP server assets into ``<repo_dir>/.mcp.json``. |
| 66 | +
|
| 67 | + Read-merge-write on the ``mcpServers`` map, preserving any channel MCP or |
| 68 | + repo-committed entries. Each asset's descriptor carries a ``server_config`` |
| 69 | + (the ``mcpServers`` entry value); assets missing it are skipped with a warn |
| 70 | + rather than writing a malformed entry. |
| 71 | +
|
| 72 | + Args: |
| 73 | + repo_dir: the cloned-repo working directory the SDK uses as ``cwd``. |
| 74 | + resolved_mcp_servers: the ``mcp_servers`` list from the resolved bundle; |
| 75 | + each item is a resolved-asset dict (kind/namespace/name/version/descriptor). |
| 76 | +
|
| 77 | + Returns: |
| 78 | + The number of MCP entries written (0 when nothing to apply, or on a |
| 79 | + write failure — logged). |
| 80 | + """ |
| 81 | + if not resolved_mcp_servers: |
| 82 | + return 0 |
| 83 | + if not repo_dir or not os.path.isdir(repo_dir): |
| 84 | + log("WARN", f"apply_mcp_assets: repo_dir missing or not a directory: {repo_dir!r}") |
| 85 | + return 0 |
| 86 | + |
| 87 | + mcp_path = os.path.join(repo_dir, ".mcp.json") |
| 88 | + config = _read_existing_mcp_config(mcp_path) |
| 89 | + servers = config.get("mcpServers") |
| 90 | + if not isinstance(servers, dict): |
| 91 | + servers = {} |
| 92 | + |
| 93 | + written = 0 |
| 94 | + for asset in resolved_mcp_servers: |
| 95 | + descriptor = asset.get("descriptor") or {} |
| 96 | + server_config = descriptor.get(_MCP_SERVER_CONFIG_KEY) |
| 97 | + if not isinstance(server_config, dict): |
| 98 | + log( |
| 99 | + "WARN", |
| 100 | + f"apply_mcp_assets: asset {asset.get('namespace')}/{asset.get('name')} " |
| 101 | + f"has no '{_MCP_SERVER_CONFIG_KEY}' in its descriptor; skipping", |
| 102 | + ) |
| 103 | + continue |
| 104 | + servers[_mcp_server_key(asset)] = server_config |
| 105 | + written += 1 |
| 106 | + |
| 107 | + if written == 0: |
| 108 | + return 0 |
| 109 | + |
| 110 | + config["mcpServers"] = servers |
| 111 | + try: |
| 112 | + with open(mcp_path, "w", encoding="utf-8") as f: |
| 113 | + json.dump(config, f, indent=2) |
| 114 | + f.write("\n") |
| 115 | + except OSError as e: |
| 116 | + log("ERROR", f"apply_mcp_assets: failed to write {mcp_path}: {e}") |
| 117 | + return 0 |
| 118 | + |
| 119 | + log("TASK", f"registry: merged {written} MCP server asset(s) into {mcp_path}") |
| 120 | + return written |
| 121 | + |
| 122 | + |
| 123 | +def apply_cedar_modules(resolved_cedar_modules: list[dict[str, Any]]) -> list[str]: |
| 124 | + """Return Cedar policy text for resolved cedar_policy_module assets. |
| 125 | +
|
| 126 | + STUB (PR 3): the resolver already returns these assets, but wiring the text |
| 127 | + into the PolicyEngine's policy set is deferred. Returns an empty list today |
| 128 | + so callers can unconditionally extend their policy list. |
| 129 | + """ |
| 130 | + if resolved_cedar_modules: |
| 131 | + log( |
| 132 | + "TASK", |
| 133 | + f"registry: {len(resolved_cedar_modules)} cedar_policy_module asset(s) " |
| 134 | + "resolved but not yet applied (PR 3)", |
| 135 | + ) |
| 136 | + return [] |
| 137 | + |
| 138 | + |
| 139 | +def apply_skills(repo_dir: str, resolved_skills: list[dict[str, Any]]) -> int: |
| 140 | + """Apply resolved skill assets to the SDK setting sources. |
| 141 | +
|
| 142 | + STUB (PR 3): returns 0 today. The resolver returns these assets; loading the |
| 143 | + prompt fragments into the SDK's setting_sources is deferred to PR 3. |
| 144 | + """ |
| 145 | + if resolved_skills: |
| 146 | + log( |
| 147 | + "TASK", |
| 148 | + f"registry: {len(resolved_skills)} skill asset(s) resolved but not yet applied (PR 3)", |
| 149 | + ) |
| 150 | + return 0 |
| 151 | + |
| 152 | + |
| 153 | +def apply_resolved_assets(repo_dir: str, resolved_assets: dict[str, list[dict]]) -> None: |
| 154 | + """Apply an entire resolved-asset bundle to the runtime. |
| 155 | +
|
| 156 | + Dispatches each kind to its loader. MVP applies MCP servers; cedar/skills are |
| 157 | + logged-only stubs (PR 3). Safe to call with an empty bundle (no-op). |
| 158 | + """ |
| 159 | + if not resolved_assets: |
| 160 | + return |
| 161 | + apply_mcp_assets(repo_dir, resolved_assets.get("mcp_servers") or []) |
| 162 | + apply_cedar_modules(resolved_assets.get("cedar_policy_modules") or []) |
| 163 | + apply_skills(repo_dir, resolved_assets.get("skills") or []) |
0 commit comments