Coverage for src/romfarmer/intent/mcp.py: 45%
38 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""``python -m romfarmer.intent.mcp`` — the intent agent's MCP server.
3A SEPARATE entry point from ``romfarmer.mcp_server`` (41 tools, including
4``farmhand_remote_exec``). This one exposes exactly the five read-only
5intent tools. The one-way door is enforced by the tool surface not
6existing: no execute, no config write, no shell. ``TOOL_SCHEMAS`` is
7importable without the ``mcp`` package so the equality test always runs.
8"""
10from __future__ import annotations
12import asyncio
13import json
14import logging
15from typing import Any
17from romfarmer.intent.tools import INTENT_TOOL_NAMES, IntentTools
19SERVER_NAME = "romfarmer-intent"
20SERVER_VERSION = "0.1.0"
21logger = logging.getLogger(__name__)
23SPEC_GRAMMAR = (
24 "Spec YAML grammar (spec_version 2): "
25 "intent:{text,authored_by,authored_at,inventory_digest,capability_digest,allocation_note} (provenance, not hashed); "
26 "target:{frontend,device,storage_bytes,reserve_bytes}; "
27 "platforms:[{platform, sources:[{root,subpath,recursive}] (root = alias from capabilities.platform_sources — never an absolute path), "
28 "dat:{retool_1g1r:bool, source?, file?}, extraction? (omit → platform intrinsic), compression? (omit → frontend preferred), priority?, "
29 "passes:{dat_filter:bool, region:{preferred:[]} (must be empty under a Retool DAT), "
30 "rating:{scale:unit_interval, min:0–1, top_n?, unrated:keep|drop (REQUIRED with min)}, "
31 "curated_lists:{ref: curated/<name>@sha256:<hex>}, budget:{max_bytes, unrated_as:median|worst|best|<float>}, sample:{n,seed}}}]. "
32 "Start from capabilities.spec_template. Σ budget.max_bytes ≤ storage_bytes − reserve_bytes."
33)
34_SPEC_ARG = {"spec_yaml": {"type": "string", "description": "Spec YAML text. " + SPEC_GRAMMAR}}
36TOOL_SCHEMAS: list[dict[str, Any]] = [
37 {
38 "name": "inventory",
39 "description": "INVENTORY: catalog every platform in the spec (once per session; NAS-bound). "
40 "Returns per-platform units/files/bytes/dat_matched/rated and a top-level inventory_digest "
41 "(record it as intent.inventory_digest).",
42 "inputSchema": {"type": "object", "properties": _SPEC_ARG, "required": ["spec_yaml"]},
43 },
44 {
45 "name": "capabilities",
46 "description": "What a frontend × device can run: capability tier A/B/C/X, quality, accepted formats, folder names, reserve_bytes, capability_digest, platform_sources (the exact sources fragment per supported platform) and spec_template (a complete valid Spec skeleton to start from). Call this FIRST. Data — never guess.",
47 "inputSchema": {
48 "type": "object",
49 "properties": {
50 "frontend": {"type": "string", "description": "config/frontends/<name>.yaml"},
51 "device": {"type": "string", "description": "config/devices/<name>.yaml"},
52 },
53 "required": ["frontend"],
54 },
55 },
56 {
57 "name": "validate_spec",
58 "description": "Validate a Spec (loud rules) and RESOLVE every platform: chain, DAT, 1g1r lever, "
59 "rating/budget as the compiler will see them. No source scan. Pass previous_spec_yaml + "
60 "previous_headroom_p90 (or _p50) when revising: loosening while over budget is rejected.",
61 "inputSchema": {
62 "type": "object",
63 "properties": {
64 **_SPEC_ARG,
65 "previous_spec_yaml": {"type": "string"},
66 "previous_headroom_p50": {"type": "integer"},
67 "previous_headroom_p90": {
68 "type": "integer",
69 "description": "preferred: the binding headroom",
70 },
71 },
72 "required": ["spec_yaml"],
73 },
74 },
75 {
76 "name": "dry_run",
77 "description": "PLAN over cached catalogs → PlanSummary. Per platform: units in/out, bytes_est_p50/p90 "
78 "with p90_ratio and p90_source (telemetry|exact|family-factor), bytes_kept_at_rating (p50 bytes a "
79 "rating.min would keep; unrated units count at their budget rank), rating_quantiles, heaviest, "
80 "removed_by_pass, top_dropped. Global: fits (binds on aggregate p90), headroom_p50/p90. The compiler's "
81 "budget pass binds max_bytes at p50 — to fit at p90, set max_bytes ≤ target / p90_ratio. Moves zero bytes.",
82 "inputSchema": {
83 "type": "object",
84 "properties": {
85 **_SPEC_ARG,
86 "detail": {
87 "type": "array",
88 "items": {"type": "string"},
89 "description": "platforms to expand with heaviest/top_dropped/bytes_kept_at_rating "
90 "(~2 KB each); omit = all, [] = none",
91 },
92 },
93 "required": ["spec_yaml"],
94 },
95 },
96 {
97 "name": "write_curated_list",
98 "description": "Freeze a curated list into artifacts/curated/<name>/<sha256>.yaml and return the "
99 "curated/<name>@sha256:<hex> ref to put in the spec.",
100 "inputSchema": {
101 "type": "object",
102 "properties": {
103 "name": {"type": "string"},
104 "entries": {
105 "type": "array",
106 "items": {
107 "type": "object",
108 "properties": {
109 "canonical_name": {"type": "string"},
110 "action": {"type": "string", "enum": ["include", "exclude"]},
111 "reason": {"type": "string"},
112 },
113 "required": ["canonical_name"],
114 },
115 },
116 "generated_by": {"type": "string"},
117 "basis": {"type": "object"},
118 },
119 "required": ["name", "entries", "generated_by"],
120 },
121 },
122]
124assert {t["name"] for t in TOOL_SCHEMAS} == INTENT_TOOL_NAMES
127def build_server(tools: IntentTools) -> Any:
128 """Construct the MCP ``Server`` (requires the ``mcp`` package)."""
129 from mcp.server import Server
130 from mcp.types import TextContent, Tool
132 server = Server(SERVER_NAME)
134 @server.list_tools() # type: ignore[untyped-decorator]
135 async def list_tools() -> list[Tool]:
136 return [Tool(**schema) for schema in TOOL_SCHEMAS]
138 @server.call_tool() # type: ignore[untyped-decorator]
139 async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
140 result = tools.call(name, arguments or {})
141 return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
143 return server
146async def main() -> None:
147 from mcp.server.lowlevel.server import NotificationOptions
148 from mcp.server.models import InitializationOptions
149 from mcp.server.stdio import stdio_server
151 from romfarmer.core.paths import get_paths
153 tools = IntentTools(get_paths().workspace_root)
154 server = build_server(tools)
155 async with stdio_server() as (read_stream, write_stream):
156 await server.run(
157 read_stream,
158 write_stream,
159 InitializationOptions(
160 server_name=SERVER_NAME,
161 server_version=SERVER_VERSION,
162 capabilities=server.get_capabilities(
163 notification_options=NotificationOptions(), experimental_capabilities={}
164 ),
165 ),
166 )
169def run() -> None:
170 asyncio.run(main())
173if __name__ == "__main__":
174 run()