Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 147 additions & 0 deletions adapters/foundations_mcp.py
Original file line number Diff line number Diff line change
@@ -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"]}
6 changes: 4 additions & 2 deletions adapters/mcp_stdio_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
21 changes: 19 additions & 2 deletions bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -401,13 +416,15 @@ 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
from adapters.aor_registry import load_fleet
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)
Expand Down Expand Up @@ -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")
Expand Down
28 changes: 28 additions & 0 deletions contracts/ADAPTERS.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 <foundation>.<tool> 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",
Expand Down
2 changes: 2 additions & 0 deletions contracts/INTERFACES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
Expand Down
2 changes: 2 additions & 0 deletions docs/architecture/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading
Loading