diff --git a/adapters/foundations_mcp.py b/adapters/foundations_mcp.py new file mode 100644 index 0000000..8135c84 --- /dev/null +++ b/adapters/foundations_mcp.py @@ -0,0 +1,147 @@ +import copy +import json + +from jsonschema import Draft202012Validator +from referencing import Registry + +from poodo_core import ContractError +from .mcp_stdio_server import McpServer +from .wire import WireFailure + +COMBINATORS = ("allOf", "anyOf", "oneOf") +OPTIONS = tuple(f"option-{i}" for i in range(1, 21)) +NEXT_PHASE = {"pontificate": "observe", "orchestrate": "observe", "observe": "orient", "orient": "decide"} +ADMITTED = ("completed", "tool_error") +META_KEY = "cstack/poodo" + + +def _no_external_schema(uri): + raise WireFailure("External schema resolution is forbidden") + + +def tool_name(domain_id, operation): + return f"{domain_id.removeprefix('foundation_')}.{operation}" + + +def _merged(values): + distinct = [] + for value in values: + if value not in distinct: + distinct.append(value) + return distinct[0] if len(distinct) == 1 else {"anyOf": distinct} + + +def advertised_schema(schema): + if not any(key in schema for key in COMBINATORS): + return copy.deepcopy(schema) + projected = {key: copy.deepcopy(value) for key, value in schema.items() if key not in COMBINATORS} + branches = [b for key in ("oneOf", "anyOf") for b in schema.get(key, ()) if type(b) is dict] + if branches and "properties" not in projected: + names = list(dict.fromkeys(name for b in branches for name in b.get("properties", {}))) + projected["properties"] = {name: copy.deepcopy(_merged([b["properties"][name] for b in branches + if name in b.get("properties", {})])) + for name in names} + shared = set.intersection(*(set(b.get("required", ())) for b in branches)) + projected["required"] = [name for name in branches[0].get("required", ()) if name in shared] + if all(b.get("additionalProperties") is False for b in branches): + projected["additionalProperties"] = False + projected["type"] = "object" + return projected + + +def _tool(domain_id, entry): + name = tool_name(domain_id, entry["name"]) + return {"name": name, "title": name, "description": entry["description"], + "inputSchema": advertised_schema(entry["inputSchema"]), + "annotations": {"title": name, "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, + "openWorldHint": False}} + + +def _refused(payload, poodo=None): + result = {"content": [{"type": "text", "text": json.dumps(payload, sort_keys=True)}], + "structuredContent": payload, "isError": True} + if poodo is not None: + result["_meta"] = {META_KEY: poodo} + return result + + +class FoundationsMcpServer(McpServer): + INSTRUCTIONS = ("Read-only tools of the Foundations this host pinned. Each call is decided and recorded by POODO " + "under this bot's AOR. A result is the Foundation's own structuredContent, with its receipt, " + "Evidence and boundary, unchanged: CHECK values are not approved, and an observation is not an " + "engineering, safety or compliance determination.") + + def __init__(self, session, inventories, *, name="cstack-foundations"): + super().__init__(session, name=name) + registry = Registry(retrieve=_no_external_schema) + classes = session.classes + self._routes, self._goals, tools = {}, {}, [] + for domain_id, inventory in inventories.items(): + if classes.get(domain_id, "deny") == "deny": + continue + for entry in inventory: + Draft202012Validator.check_schema(entry["inputSchema"]) + tool = _tool(domain_id, entry) + self._routes[tool["name"]] = (domain_id, entry["name"], + Draft202012Validator(entry["inputSchema"], registry=registry)) + tools.append(tool) + self._tools = tuple(tools) + self._by_name = {tool["name"]: tool for tool in self._tools} + + def _call(self, tool, arguments): + domain, operation, validator = self._routes[tool["name"]] + problem = next(iter(sorted(validator.iter_errors(arguments), key=lambda e: list(map(str, e.absolute_path)))), + None) + if problem is not None: + return _refused({"error": "Arguments do not match the pinned input schema", + "path": [str(p) for p in problem.absolute_path], "detail": problem.message[:300]}) + poodo = {"bot": self._session.bot.slug, "domain": domain, "operation": operation, + "ledger": self._session.ledger_label} + try: + poodo.update(self._decide(domain, operation, arguments)) + ran = self._session.execute(domain, poodo["decision_id"]) + except (ContractError, ValueError, TypeError) as error: + return _refused({"error": str(error) or type(error).__name__}, poodo) + if ran["status"] != "executed": + return _refused({"error": ran["status"], "dispatched": False}, poodo) + outcome = ran["outcome"] + poodo.update({key: outcome[key] for key in ("attempt_id", "execution_status", "execution_certainty", + "assessment", "source_manifest_sha256", "inventory_sha256")}) + raw = outcome["raw_result"] + if outcome["execution_status"] not in ADMITTED or type(raw) is not dict: + return _refused({"error": "No Foundation result was admitted", + "execution_status": outcome["execution_status"], + "execution_certainty": outcome["execution_certainty"], + "assessment": outcome["assessment"], "limitations": outcome["limitations"]}, poodo) + content = raw["structuredContent"] + result = {"content": [{"type": "text", "text": json.dumps(content, sort_keys=True)}], + "isError": raw["isError"], "_meta": {META_KEY: poodo}} + if type(content) is dict: + result["structuredContent"] = content + return result + + def _decide(self, domain, operation, arguments): + goal = self._goals.get(domain) + if goal is None: + snapshot = self._session.start_goal( + domain, f"Answer read-only {domain} tool calls from the Foundations MCP server.", + ["Each call returns the pinned Foundation's receipt unchanged, or a stated refusal."], + exclusions=["No CHECK value is approved and no determination or control action is made."]) + goal = self._goals[domain] = {"goal_id": snapshot["contract"]["goal_id"], "phase": snapshot["phase"]} + goal_id = goal["goal_id"] + while goal["phase"] != "decide": + step = NEXT_PHASE[goal["phase"]] + snapshot = self._session.advance( + domain, goal_id, step, f"Host-authored checkpoint for {tool_name(domain, operation)}.", + research_references=[f"{domain} pinned tool inventory: {operation}"] if step == "orient" else [], + option_ids=list(OPTIONS) if step == "decide" else []) + goal["phase"] = snapshot["phase"] + record = self._session.decide( + domain, goal_id, operation, arguments, + f"The pinned {domain} tool {operation} returns a receipt bound to these arguments, with its Evidence.", + "Only the supplied arguments against the pinned Foundation; nothing is approved or determined.", + "A tool error, refusal or unknown outcome is reported as such, with no automatic retry.") + goal["phase"] = self._session.advance(domain, goal_id, "orchestrate", + "Host-authored checkpoint: run the precommitted call.")["phase"] + return {"goal_id": goal_id, "decision_id": record["decision_id"], "request_sha256": record["request_sha256"], + "approval_required": record["approval_required"]} diff --git a/adapters/mcp_stdio_server.py b/adapters/mcp_stdio_server.py index 5e593ce..5d7892a 100644 --- a/adapters/mcp_stdio_server.py +++ b/adapters/mcp_stdio_server.py @@ -115,6 +115,9 @@ def _check_arguments(tool, arguments): class McpServer: + INSTRUCTIONS = ("POODO tools for one bot's AOR on this device. Effects outside the AOR are refused by the host; " + "ask-class effects wait for the owner through the approval channel.") + def __init__(self, session, *, name="cstack"): self._session, self._name, self._ready = session, name, False domains = getattr(session, "classes", None) # an AorSession reports every registered domain, denied included @@ -139,8 +142,7 @@ def handle(self, message): self._ready = True return _result(ident, {"protocolVersion": version, "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": self._name, "version": "0.1.0"}, - "instructions": "POODO tools for one bot's AOR on this device. Effects outside " - "the AOR are refused by the host; ask-class effects wait for the owner through the approval channel."}) + "instructions": self.INSTRUCTIONS}) if method == "ping": return _result(ident, {}) if not self._ready: diff --git a/bootstrap.py b/bootstrap.py index 5c1d47b..c7c1f38 100644 --- a/bootstrap.py +++ b/bootstrap.py @@ -390,8 +390,23 @@ def _witnessed_config(state_root, bot_slug, hostname): return node, writer["writer"], paths +def registered_foundations(domain_ids=None): + if domain_ids is None: + return tuple(DOMAINS.values()) + if not domain_ids or len(set(domain_ids)) != len(domain_ids): + raise ContractError("Choose at least one Foundation, each once") + unknown = [domain_id for domain_id in domain_ids if domain_id not in DOMAINS] + if unknown: + raise ContractError(f"Foundation {unknown[0]} is not registered on this host") + return tuple(DOMAINS[domain_id] for domain_id in domain_ids) + + +def foundation_inventories(domain_ids): + return {d.domain_id: d.capability(d.source_root).inventory() for d in registered_foundations(domain_ids)} + + def build_aor_session(bot_slug, *, state_root, hostname, fleet_path=DEFAULT_FLEET, clock=None, enforce=None, - fleet_mail=None): + fleet_mail=None, foundations=None): """Trusted HOST configuration only (ADR 003): one bot's AOR on this device, for the MCP driving adapter. The bot slug comes from the host's launch command, never from a request. Foundations are pure @@ -401,6 +416,7 @@ def build_aor_session(bot_slug, *, state_root, hostname, fleet_path=DEFAULT_FLEE and anchor. A lifetime store claim refuses a second live session for the same bot and domain. enforce defaults to the host's LEDGER_ENFORCE=1 (ADR 004: off unless the owner turns it on). fleet_mail is a host-owned FleetMailConfig; None (the default) disables mail. + foundations, when given, is the host's subset of registered domain ids; the session opens only those. """ import os import time @@ -408,6 +424,7 @@ def build_aor_session(bot_slug, *, state_root, hostname, fleet_path=DEFAULT_FLEE from adapters.aor_session import AorSession, LedgerStoreClaim, SessionApprovalReader from adapters.approval_store import ApprovalReader + selected = registered_foundations(foundations) state_root = Path(state_root) state_root.mkdir(parents=True, exist_ok=True, mode=0o700) fleet = load_fleet(fleet_path) @@ -447,7 +464,7 @@ def make_core(domain, grants, anchors): raise return core, ledger, claim - domains = {d.domain_id: (d.tool_names, "read") for d in DOMAINS.values()} + domains = {d.domain_id: (d.tool_names, "read") for d in selected} session = AorSession(fleet=fleet, bot_slug=bot_slug, hostname=hostname, state_dir=state_root, domains=domains, make_core=make_core, ledger_label="witnessed" if witnessed else MEMORY_LEDGER, shields_file=state_root / "SHIELDS_UP") diff --git a/contracts/ADAPTERS.json b/contracts/ADAPTERS.json index 9daae73..ffc6514 100644 --- a/contracts/ADAPTERS.json +++ b/contracts/ADAPTERS.json @@ -43,6 +43,34 @@ "strategic_dependency_adr": null, "notes": "Per-AOR MCP stdio launcher; fixes bot, device, fleet and state at host startup, marks the server process and closes the session on exit." }, + { + "adapter_id": "foundations-mcp-server", + "lane": "HMIFace", + "port": "none", + "port_reason": "Driving side: MCP tools call the host AOR session API, which drives each Foundation core; no core port protocol.", + "vendor": "cstack (in-repo), legacy MCP stdio JSON-RPC", + "kind": "python_module", + "path": "adapters/foundations_mcp.py", + "fake": null, + "fake_reason": "Tests drive it in process and through its launcher over the real pinned bridges; no named HMIFace replaceability fake is registered.", + "status": "hard_wired", + "strategic_dependency_adr": null, + "notes": "Read-only . MCP tools for the host-chosen pinned Foundations; schemas from the pinned inventories; each call is a POODO decision in the bot's AOR session; the Foundation's structuredContent is returned unchanged." + }, + { + "adapter_id": "foundations-mcp-launcher", + "lane": "HMIFace", + "port": "none", + "port_reason": "Host composition entry point: builds an AOR session limited to the chosen Foundations and serves MCP directly; no core port protocol.", + "vendor": "cstack (in-repo), Tailscale CLI for device identity", + "kind": "python_module", + "path": "tools/foundations_mcp.py", + "fake": null, + "fake_reason": "Launcher tests use host-supplied fixture configuration; no named HMIFace replaceability fake is registered.", + "status": "hard_wired", + "strategic_dependency_adr": null, + "notes": "Per-AOR Foundations MCP stdio launcher; the bot, device, fleet, state and exposed Foundations are fixed at host startup." + }, { "adapter_id": "aor-session", "lane": "HMIFace", diff --git a/contracts/INTERFACES.md b/contracts/INTERFACES.md index 760aa44..56fee25 100644 --- a/contracts/INTERFACES.md +++ b/contracts/INTERFACES.md @@ -73,6 +73,8 @@ The adapter validates the outputSchema, the tool identity, the false proof and a MCP is an application protocol with transport bindings. Any later adapter must state its tested revision and demonstrate actual client interoperability. Current 2026-07-28 uses per-request metadata and server/discover; legacy 2025-11-25 uses initialize/initialized. A legacy SDK does not prove current-revision support. +`tools/foundations_mcp.py` serves the host-chosen pinned Foundations as read-only MCP tools for one bot's AOR, through that AOR session's goals and decisions; see `docs/icd/icd-foundations.md`. + `adapters/mcp_stdio_client.py` is an MCP client CapabilityPort with tested revision **2025-11-25** only. It is not 2026-07-28. The host fixes: - the server argv, cwd and env allowlist; - per tool, a read/write/execute effect class and a sha256 pin of the whole reviewed tools/list entry (`tool_sha256`), including title, icons, execution and `_meta`; diff --git a/docs/architecture/architecture.md b/docs/architecture/architecture.md index fafe6da..8b6d965 100644 --- a/docs/architecture/architecture.md +++ b/docs/architecture/architecture.md @@ -82,11 +82,13 @@ Each component lists the requirements allocated to it. `python -B tools/check_tr | SDD-C22 | Reasoning snapshot | `reasoning/poodo/`, `TODELETE/reasoning/poodo/` | Mirrored POODO skill subset and archived retired paths | CS-REQ-019 | | SDD-C23 | Operator tools without tests | `tools/agent_profiles.py`, `tools/generate_aors.py`, `tools/measure_foundation_routes.py`, `tools/measure_routes_pyodide.mjs`, `tools/tty_approve.py`, `tools/fuzz_ports.py`, `tools/spawncount.py`, `tools/gen_release_docs.py` | Generators, measurement, release-record and test-support scripts; no CS-REQ requirement. `tools/spawncount.py` and `tools/fuzz_ports.py` are used by tests | Infrastructure | | SDD-C24 | Examples and placeholders | `examples/`, `products/`, `workshop/`, `cstack.config.example.json` | Example documents and configuration; empty component areas | Infrastructure | +| SDD-C31 | Foundations MCP server | `adapters/foundations_mcp.py`, `tools/foundations_mcp.py` | Host-launched MCP server exposing the chosen pinned Foundations' tools to one bot, each call decided and executed through its AOR session | CS-REQ-091 | ```mermaid flowchart LR CLI[SDD-C9 CLI] --> BOOT[SDD-C1 bootstrap] MCP[SDD-C15 MCP server] --> AOR[SDD-C14 AOR session] + FMCP[SDD-C31 Foundations MCP] --> AOR AOR --> BOOT BOOT --> CORE[SDD-C2 control core] CORE --> AD[SDD-C5/C6/C7 adapters] diff --git a/docs/icd/icd-foundations.md b/docs/icd/icd-foundations.md index 3656024..f375e06 100644 --- a/docs/icd/icd-foundations.md +++ b/docs/icd/icd-foundations.md @@ -64,6 +64,30 @@ Template, Refrigeration, Robotics and Film adapters use `BridgeProfile` and `Pin Adapter pins live in `adapters/template_stdio.py`, `adapters/refrigeration_stdio.py`, `adapters/robotics_stdio.py` and `adapters/film_stdio.py`; sources and manifest builders live under their respective `foundations/` directories. Changes require matched source, inventory, schema and conformance review. +## Foundations MCP interface + +`tools/foundations_mcp.py` starts an agent-facing MCP stdio server, `adapters/foundations_mcp.py`, for one bot's AOR on one device. It is a driving adapter: it calls the AOR session's public goal, advance, decide and execute operations and never a Foundation bridge directly. The bridges above stay non-MCP. + +| Property | Controlled value / rule | +|---|---| +| Launch | `python -B tools/foundations_mcp.py --aor --foundation [--foundation ...] [--state-root DIR] [--fleet FILE]`; `` is a registered domain id with or without the `foundation_` prefix | +| Who chooses the Foundations | The host's launch arguments only. An unregistered name, a runtime such as `cstack_forge`, a repeat or an empty choice stops the launch. No request can add one | +| Framing and lifecycle | As the Cstack MCP server (CS-REQ-052): newline-delimited JSON-RPC 2.0, `initialize`, 1 MiB frames, strict parsing, protocol revisions 2025-11-25, 2025-06-18 and 2024-11-05 | +| Tool names | `.`, for example `refrigeration.saturation_pressure`, `math.exact_scalar`. Clients that allow only `[A-Za-z0-9_-]` may rewrite the dot | +| Tools listed | Each tool of each chosen Foundation whose effect class for this bot and device is `allow` or `ask`. A `deny` domain lists nothing | +| Input schema | The pinned inventory's `inputSchema`, unchanged as a JSON value, except that a top-level `allOf`, `oneOf` or `anyOf` is projected into one object schema (branch properties merged, `anyOf` where branches differ, required names common to all branches). The server always validates against the exact pinned schema. Today this applies to `math.exact_scalar` and `robotics.mechanism_check` | +| Description and annotations | The pinned description; `readOnlyHint` and `idempotentHint` true, `destructiveHint` and `openWorldHint` false | +| Authority | The AOR session's read-only ToolFace grant for that domain (the Foundation's fixed tools, 32 goal ids, 64 calls per session), checked against `contracts/ADAPTERS.json` | + +Each call: + +1. Refuses arguments that fail the exact pinned input schema as a tool error, with no POODO event. +2. Keeps one standing goal per Foundation and walks it to Decide with host-authored checkpoints (the tool's inventory entry as the research reference and 20 fixed option ids). These satisfy the structural gates; they are not research. +3. Precommits the exact arguments with host-written expected observation, success boundary and failure meaning, advances to Orchestrate and executes through the pinned adapter, which verifies the manifest, the live inventory and, for the shared adapter, the receipt input digest. +4. Returns the Foundation's `isError` and `structuredContent` exactly as admitted, and the same JSON as text. Engine results that are not objects are returned as text only, because MCP requires `structuredContent` to be an object. `_meta["cstack/poodo"]` carries the bot, domain, goal, decision, request digest, attempt, execution status and certainty, assessment, source and inventory digests and the ledger label. + +A core refusal, an approval still pending, an exhausted budget or an outcome the adapter did not admit (tampered source, out-of-profile numbers, protocol failure) is a tool error with the reason and, where a decision exists, the POODO record. Nothing is retried. CHECK values, the receipt boundary and the evidence ceiling are passed through, never rewritten. The ledger is witnessed only when the state root has an ADR 004 `ledger.json`; otherwise it is memory and is lost when the server stops. With a witnessed ledger, this server and `tools/cstack_mcp.py` cannot both hold the same bot and domain at once. + ## Interface change acceptance Record old/new manifests, catalog identities, operation/schema differences and changed evidence semantics. Run adapter and domain conformance suites plus the root suite against the candidate. Incompatible upstream extractions require explicit migration design; a familiar repository name is not compatibility evidence. Keep an unmodified baseline available for comparison and rollback. @@ -114,7 +138,7 @@ stops the run before dispatch with no action/outcome, preserving earlier history ## Requirements addressed -CS-REQ-003 to CS-REQ-008 and CS-REQ-015 (Math adapter); CS-REQ-064 (Film, Refrigeration, Robotics and Template adapters); CS-REQ-065 (Engine adapter); CS-REQ-009 to CS-REQ-011 (process executor); CS-REQ-017 and CS-REQ-018 (local CLI approval). The tool and field tables generated from `schemas/` are in the [data dictionary](../data/data-dictionary.md). See the [verification matrix](../verification/verification-matrix.md) for the tests. +CS-REQ-003 to CS-REQ-008 and CS-REQ-015 (Math adapter); CS-REQ-064 (Film, Refrigeration, Robotics and Template adapters); CS-REQ-065 (Engine adapter); CS-REQ-009 to CS-REQ-011 (process executor); CS-REQ-017 and CS-REQ-018 (local CLI approval); CS-REQ-091 (Foundations MCP server). The tool and field tables generated from `schemas/` are in the [data dictionary](../data/data-dictionary.md). See the [verification matrix](../verification/verification-matrix.md) for the tests. ## Change history diff --git a/docs/requirements/requirements.md b/docs/requirements/requirements.md index 604e464..c30fc85 100644 --- a/docs/requirements/requirements.md +++ b/docs/requirements/requirements.md @@ -649,6 +649,16 @@ The MCP stdio client shall take its descriptor and effects from the host, treat - Verification: T. The TypeScript SDK interop test skips without that SDK. - Status: Baselined +### CS-REQ-091 — Foundations MCP server + +The Foundations MCP server shall list, as `.`, only the tools of the Foundations the host named at launch that the bot's AOR does not deny, each with its input schema from the pinned tool inventory (a top-level `allOf`, `oneOf` or `anyOf` projected into one object schema). It shall refuse an unknown tool as invalid params and refuse arguments that fail the exact pinned input schema before any decision. It shall run every other call through the bot's AOR session as a POODO goal, decision and execution on a read-only ToolFace grant and the pinned adapter, return the Foundation's `structuredContent` unchanged with the POODO record in `_meta`, and report a refused, tampered, unadmitted, pending or over-budget call as a tool error. A launch naming an unregistered Foundation or a runtime shall fail. + +- Rationale: agents need domain truth as tools, without bypassing source pins, authority, the ledger or the evidence ceiling. +- Derivation: `adapters/foundations_mcp.py`; `tools/foundations_mcp.py`; `bootstrap.py` +- Allocated to: SDD-C31 +- Verification: T. No test drives it from a real MCP client; one session allows 64 calls per Foundation. +- Status: Baselined + ### CS-REQ-054 — Fleet mail Fleet mail shall stamp the sender so input cannot override it, accept only fleet slugs, all-bots or host extras as recipients, refuse over-long strings, control and look-alike characters, mentions and cross-repository references, enforce send, all-bots and per-thread reply allowances with refusals recorded once per window, refuse writes while shields are up, record message number and digest but never the body, verify signatures against the roster and show forgeries as unverified, keep fleet mail out of the approval path, run `gh` with a fixed argument shape, fixed environment, stdin-only message text, deadline and output bounds, and keep the MCP mail tools off by default. The send-budget file shall be private, refuse an emptied state, and never let several processes pass the limit. diff --git a/docs/verification/verification-matrix.md b/docs/verification/verification-matrix.md index 1be2ee1..5597285 100644 --- a/docs/verification/verification-matrix.md +++ b/docs/verification/verification-matrix.md @@ -84,6 +84,7 @@ The matrix does not embed pass counts. A mapped test shows the requirement is ex | CS-REQ-051 | T | `tests/test_e2e_agent_ledger.py` | Verdict stream and anchor checks | [STR-baseline](reports/STR-baseline.md) | | CS-REQ-052 | T | `tests/test_mcp_driving_adapter.py`; `tests/test_mcp_conformance.py` | Golden tool list; malformed input keeps serving | [STR-baseline](reports/STR-baseline.md) | | CS-REQ-053 | T | `tests/test_mcp_stdio_client.py` | `test_interop_with_official_typescript_sdk_server` skips unless `CSTACK_MCP_SDK_ESM` and `node` are present; a skip is not interop evidence | [STR-baseline](reports/STR-baseline.md) | +| CS-REQ-091 | T | `tests/test_foundations_mcp.py` | Every vendored Foundation called once over the real pinned bridges; tampered manifest; stdio launcher | Not yet in a recorded run | | CS-REQ-054 | T | `tests/test_fleet_mail.py`; `tests/test_fleet_mail_budget.py` | Uses a fake `gh`; no network | [STR-baseline](reports/STR-baseline.md) | | CS-REQ-055 | T | `tests/test_relay_outbox.py` | Several processes, torn tails | [STR-baseline](reports/STR-baseline.md) | | CS-REQ-056 | T | `tests/test_scheduled_approvals.py` | SQLite and witnessed node logs | [STR-baseline](reports/STR-baseline.md) | diff --git a/tests/test_foundations_mcp.py b/tests/test_foundations_mcp.py new file mode 100644 index 0000000..4da54b6 --- /dev/null +++ b/tests/test_foundations_mcp.py @@ -0,0 +1,215 @@ +import dataclasses +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import bootstrap +from adapters.foundation_stdio import arguments_sha256 +from adapters.foundations_mcp import COMBINATORS, META_KEY, FoundationsMcpServer, tool_name +from bootstrap import DOMAINS, build_aor_session, foundation_inventories +from poodo_core import ContractError +from tests.aor_fixtures import R717_20F, write_fleet +from tests.helpers import request + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / "tools/foundations_mcp.py" +MATH_CASE = json.loads((ROOT / "examples/tool-cases.json").read_text())[0] +REPRESENTATIVE = { + "foundation_math": (MATH_CASE["operation"], MATH_CASE["arguments"]), + "foundation_template": ("echo_observation", {"observation": "synthetic reading 7"}), + "foundation_engine": ("validate_scene_output", {"output": {"toneMapping": "agx", "exposure": 1.25}}), + "foundation_refrigeration": ("saturation_pressure", R717_20F), + "foundation_robotics": ("scale_timing", {"height_mm": 6000}), + "foundation_film": ("audio_gate", {"integrated_lufs": -16200, "true_peak_dbtp": -1500, "voice_over_bed_db": 13500, + "cuts": 10, "cuts_with_hit": 9, "heard": ["Speech", "Music"], + "line_wer": [{"line": "b1-1", "wer_permille": 20}]}), +} +DIGEST_BOUND = set(REPRESENTATIVE) - {"foundation_engine", "foundation_math"} + + +class Host: + def __init__(self, foundations=None, **fleet): + self.directory = tempfile.TemporaryDirectory() + root = Path(self.directory.name) + self.foundations = list(DOMAINS) if foundations is None else foundations + self.session = build_aor_session("alpha", state_root=root / "state", hostname="testbox", + fleet_path=write_fleet(root, **fleet), foundations=self.foundations) + self.server = FoundationsMcpServer(self.session, foundation_inventories(self.foundations)) + self.next_id = 0 + self.rpc("initialize", {"protocolVersion": "2025-11-25"}) + + def rpc(self, method, params=None): + self.next_id += 1 + return self.server.handle({"jsonrpc": "2.0", "id": self.next_id, "method": method, + **({} if params is None else {"params": params})}) + + def call(self, name, arguments): + return self.rpc("tools/call", {"name": name, "arguments": arguments}) + + def events(self, domain): + return self.session.ledger(domain, 50)["events"] + + def close(self): + self.session.close() + self.directory.cleanup() + + +def direct(domain, operation, arguments): + d = DOMAINS[domain] + outcome = d.capability(d.source_root).invoke(request(operation, arguments, domain), "attempt-direct") + return outcome.to_dict()["raw_result"] + + +class FoundationsMcpTests(unittest.TestCase): + def setUp(self): + self.host = Host() + self.addCleanup(self.host.close) + + def test_list_names_every_exposed_tool_with_its_pinned_schema(self): + tools = self.host.rpc("tools/list")["result"]["tools"] + inventories = foundation_inventories(list(DOMAINS)) + self.assertEqual([t["name"] for t in tools], + [tool_name(d, entry["name"]) for d, inventory in inventories.items() for entry in inventory]) + pinned = {tool_name(d, e["name"]): e for d, inventory in inventories.items() for e in inventory} + for tool in tools: + entry = pinned[tool["name"]] + self.assertEqual(tool["description"], entry["description"]) + self.assertEqual(tool["annotations"]["readOnlyHint"], True) + self.assertEqual(tool["annotations"]["destructiveHint"], False) + self.assertEqual(tool["inputSchema"]["type"], "object") + self.assertFalse(set(tool["inputSchema"]) & set(COMBINATORS)) + if not set(entry["inputSchema"]) & set(COMBINATORS): + self.assertEqual(tool["inputSchema"], entry["inputSchema"]) + self.assertIn("refrigeration.saturation_pressure", pinned) + + def test_each_foundation_answers_its_representative_tool_with_its_receipt_unchanged(self): + for domain, (operation, arguments) in REPRESENTATIVE.items(): + if domain not in DOMAINS: + continue + with self.subTest(domain=domain): + result = self.host.call(tool_name(domain, operation), arguments)["result"] + poodo = result["_meta"][META_KEY] + self.assertEqual((result["isError"], poodo["execution_status"], poodo["execution_certainty"]), + (False, "completed", "responded")) + expected = direct(domain, operation, arguments) + self.assertEqual(result["structuredContent"], expected["structuredContent"]) + self.assertEqual(json.loads(result["content"][0]["text"]), expected["structuredContent"]) + content = result["structuredContent"] + if domain in DIGEST_BOUND: + self.assertEqual(content["receipt"]["input_sha256"], arguments_sha256(arguments)) + if domain != "foundation_engine": + self.assertEqual((content["formal_proof"], content["runtime_goal_acceptance"]), (False, False)) + kinds = [(e["kind"], e["data"].get("decision_id") or e["data"].get("outcome", {}).get("decision_id")) + for e in self.host.events(domain)] + self.assertIn(("outcome", poodo["decision_id"]), kinds) + + def test_unknown_tool_is_invalid_params(self): + for name in ("refrigeration.shell", "saturation_pressure", "cstack_forge.run", "aor", None): + with self.subTest(name=name): + self.assertEqual(self.host.call(name, {})["error"]["code"], -32602) + self.assertEqual(self.host.rpc("tools/call", {"name": "template.echo_observation", + "arguments": ["x"]})["error"]["code"], -32602) + + def test_malformed_input_never_reaches_the_core(self): + before = len(self.host.events("foundation_template")) + for arguments in ({}, {"observation": "x", "extra": 1}, {"observation": 7}, {"observation": ""}): + with self.subTest(arguments=arguments): + result = self.host.call("template.echo_observation", arguments)["result"] + self.assertTrue(result["isError"]) + self.assertEqual(result["structuredContent"]["error"], "Arguments do not match the pinned input schema") + self.assertNotIn("_meta", result) + self.assertEqual(len(self.host.events("foundation_template")), before) + + @unittest.skipUnless("foundation_refrigeration" in DOMAINS, "Refrigeration is absent") + def test_out_of_profile_number_is_refused_before_dispatch(self): + arguments = {"fluid": "R717", "temperature": {"value": 1e-7, "unit": "degC"}} + result = self.host.call("refrigeration.saturation_pressure", arguments)["result"] + poodo = result["_meta"][META_KEY] + self.assertTrue(result["isError"]) + self.assertEqual((poodo["execution_status"], poodo["execution_certainty"]), ("resource_rejected", "not_dispatched")) + + +class HostConfigurationTests(unittest.TestCase): + def test_host_chooses_the_foundations(self): + host = Host(["foundation_template"]) + self.addCleanup(host.close) + self.assertEqual(list(host.session.classes), ["foundation_template"]) + names = [t["name"] for t in host.rpc("tools/list")["result"]["tools"]] + self.assertEqual(names, ["template.echo_observation"]) + self.assertEqual(host.call("math.exact_scalar", MATH_CASE["arguments"])["error"]["code"], -32602) + + def test_unknown_runtime_empty_or_repeated_choices_are_refused(self): + for choice in (["foundation_nope"], ["cstack_forge"], [], ["foundation_template", "foundation_template"]): + with self.subTest(choice=choice), self.assertRaises(ContractError): + bootstrap.registered_foundations(choice) + + def test_denied_domain_lists_nothing(self): + host = Host(["foundation_template"], alpha_read="deny") + self.addCleanup(host.close) + self.assertEqual(host.rpc("tools/list")["result"]["tools"], []) + + def test_ask_class_waits_for_the_owner(self): + host = Host(["foundation_template"], owner="beta", guest_read="ask") + self.addCleanup(host.close) + result = host.call("template.echo_observation", {"observation": "synthetic"})["result"] + self.assertTrue(result["isError"]) + self.assertEqual(result["structuredContent"], {"error": "approval_pending", "dispatched": False}) + self.assertTrue(result["_meta"][META_KEY]["approval_required"]) + + def test_tampered_manifest_is_refused(self): + with tempfile.TemporaryDirectory() as directory: + copy = Path(directory) / "template" + shutil.copytree(DOMAINS["foundation_template"].source_root, copy) + listed = next(iter(json.loads((copy / "SOURCE-MANIFEST.json").read_text())["files"])) + with open(copy / listed, "ab") as handle: + handle.write(b"\n") + tampered = dataclasses.replace(DOMAINS["foundation_template"], source_root=copy) + with mock.patch.dict(bootstrap.DOMAINS, {"foundation_template": tampered}): + host = Host(["foundation_template"]) + self.addCleanup(host.close) + result = host.call("template.echo_observation", {"observation": "synthetic"})["result"] + poodo = result["_meta"][META_KEY] + self.assertTrue(result["isError"]) + self.assertEqual((poodo["execution_status"], poodo["assessment"], poodo["execution_certainty"]), + ("unavailable", "source_identity_unavailable", "not_dispatched")) + self.assertNotIn("receipt", result["structuredContent"]) + + +class LauncherTests(unittest.TestCase): + def run_server(self, frames, *foundations): + with tempfile.TemporaryDirectory() as directory: + argv = [sys.executable, "-B", str(TOOL), "--aor", "alpha", "--state-root", str(Path(directory) / "state"), + "--device", "testbox", "--fleet", str(write_fleet(directory))] + for name in foundations: + argv += ["--foundation", name] + return subprocess.run(argv, cwd=ROOT, input="".join(json.dumps(f) + "\n" for f in frames), + capture_output=True, text=True, timeout=120) + + def test_stdio_lists_and_calls_the_chosen_foundation(self): + frames = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-11-25"}}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "template.echo_observation", "arguments": {"observation": "synthetic"}}}] + done = self.run_server(frames, "template") + self.assertEqual(done.returncode, 0, done.stderr) + replies = [json.loads(line) for line in done.stdout.splitlines()] + self.assertEqual(replies[0]["result"]["serverInfo"]["name"], "cstack-foundations-alpha") + self.assertEqual([t["name"] for t in replies[1]["result"]["tools"]], ["template.echo_observation"]) + content = replies[2]["result"]["structuredContent"] + self.assertEqual(content["receipt"]["result"], {"observation": "synthetic"}) + self.assertEqual(content["receipt"]["evidence"][0]["evidence"]["status"], "CHECK") + + def test_unregistered_foundation_refuses_to_start(self): + done = self.run_server([], "nope") + self.assertNotEqual(done.returncode, 0) + self.assertIn("foundation_nope is not registered", done.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/foundations_mcp.py b/tools/foundations_mcp.py new file mode 100644 index 0000000..fb5052b --- /dev/null +++ b/tools/foundations_mcp.py @@ -0,0 +1,38 @@ +import argparse +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from adapters.foundations_mcp import FoundationsMcpServer # noqa: E402 +from bootstrap import DEFAULT_FLEET, build_aor_session, foundation_inventories # noqa: E402 +from tools.cstack_mcp import MCP_MARKER, tailnet_hostname # noqa: E402 + + +def domain_id(name): + return name if name.startswith("foundation_") else f"foundation_{name}" + + +def main(argv=None): + parser = argparse.ArgumentParser(description="Serve the host's pinned Foundations as read-only MCP tools for " + "one bot's AOR on this device.") + parser.add_argument("--aor", required=True, help="bot slug from the fleet registry") + parser.add_argument("--foundation", action="append", required=True, metavar="NAME", + help="registered Foundation to expose, such as refrigeration; repeatable") + parser.add_argument("--state-root", type=Path, default=Path.home() / ".local/state/cstack") + parser.add_argument("--device", help="override the tailnet device name (tests only)") + parser.add_argument("--fleet", type=Path, default=DEFAULT_FLEET, help="host-owned AOR registry") + args = parser.parse_args(argv) + foundations = [domain_id(name) for name in args.foundation] + os.environ[MCP_MARKER] = "1" + inventories = foundation_inventories(foundations) + session = build_aor_session(args.aor, state_root=args.state_root, hostname=args.device or tailnet_hostname(), + fleet_path=args.fleet, foundations=foundations) + try: + FoundationsMcpServer(session, inventories, name=f"cstack-foundations-{args.aor}").serve() + finally: + session.close() + + +if __name__ == "__main__": + main()