Skip to content

Commit ea67c9b

Browse files
test(harness): a stub xtiles MCP server, and WD-4 to pin it (Layer 2)
Makes 'a connector named xtiles is attached' REAL for the transcript acceptance tests without a network, an account or an OAuth flow: a stdio server named xtiles exposing the three write tools the prompts select between (create_tasks, create_tiles_from_markdown_in_my_planner, create_view_from_markdown), appending every call to a JSON artefact. Deliberately dumb — no validation, no state, no response fidelity beyond the one thing the prompts check (the planner-tile tool returns a URL). Anything smarter would be a second xTiles implementation for tests to accidentally depend on. Two teeth worth naming. The stub REFUSES to run without a call-log path: a stub that ran unlogged would pass WD-5's silence checks vacuously, the exact positive-control trap (D4) this suite exists to avoid. And 'reaches no network' is enforced two ways — stdio transport by construction, plus an AST scan that goes red if a network-capable import creeps in. WD-4 drives the real handshake with the official SDK client: server name 'xtiles' (the name IS the skill's gate), exactly the three tools, every call logged in order, appends never overwrites. Mutation-verified: making _log_call silently drop a call turns both log tests red.
1 parent 3f1b951 commit ea67c9b

2 files changed

Lines changed: 242 additions & 0 deletions

File tree

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
"""A stub ``xtiles`` MCP server — Layer 2 of the acceptance harness.
2+
3+
Its only job is to make "an ``xtiles`` connector is attached" REAL for the
4+
transcript acceptance tests (WD-5/WD-6) without a network, an account or an
5+
OAuth flow: a harness pointed at this server sees a server named ``xtiles``
6+
exposing the three write tools the prompts select between, and every call is
7+
appended to a JSON file the test reads afterwards.
8+
9+
Deliberately dumb. No validation, no state, no fidelity to xTiles' real
10+
responses beyond the one thing the prompts check for (the planner-tile tool
11+
returns a URL). Anything smarter would be a second implementation of xTiles
12+
for tests to accidentally depend on.
13+
14+
NO NETWORK — enforced, not aspirational: the transport is stdio, and this
15+
module must import nothing that can open a socket. WD-4 scans this file's
16+
imports; adding ``socket``, ``http``, ``urllib.request``, ``requests`` or
17+
similar here turns that test red.
18+
19+
Environment:
20+
XTILES_STUB_CALL_LOG Path of the JSON call log (required). Each call is
21+
appended as {"tool": ..., "arguments": {...}}.
22+
"""
23+
24+
from __future__ import annotations
25+
26+
import json
27+
import os
28+
import sys
29+
from pathlib import Path
30+
31+
from mcp.server.fastmcp import FastMCP
32+
33+
mcp = FastMCP("xtiles")
34+
35+
36+
def _log_path() -> Path:
37+
raw = os.environ.get("XTILES_STUB_CALL_LOG", "").strip()
38+
if not raw:
39+
print("XTILES_STUB_CALL_LOG is not set; refusing to run unlogged", file=sys.stderr)
40+
raise SystemExit(2)
41+
return Path(raw)
42+
43+
44+
def _log_call(tool: str, arguments: dict) -> None:
45+
"""Append one call. Read-modify-write is fine: one server, one client."""
46+
path = _log_path()
47+
calls = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else []
48+
calls.append({"tool": tool, "arguments": arguments})
49+
path.write_text(json.dumps(calls, indent=2), encoding="utf-8")
50+
51+
52+
@mcp.tool()
53+
def xtiles_create_tasks(tasks: list[dict], projectId: str = "") -> dict: # noqa: N803 — xTiles' own casing
54+
"""Create one or more tasks (stub: logs and returns fake ids)."""
55+
_log_call("xtiles_create_tasks", {"tasks": tasks, "projectId": projectId})
56+
return {"tasks": [{"id": f"stub-task-{i}"} for i, _ in enumerate(tasks)]}
57+
58+
59+
@mcp.tool()
60+
def xtiles_create_tiles_from_markdown_in_my_planner(period: str, date: str, markdown: str) -> dict:
61+
"""Append tiles to the personal planner (stub: logs and returns fake URLs)."""
62+
_log_call(
63+
"xtiles_create_tiles_from_markdown_in_my_planner",
64+
{"period": period, "date": date, "markdown": markdown},
65+
)
66+
return {
67+
"view_id": "stub-view-planner",
68+
"tiles": [{"id": "stub-tile-1", "resource_url": "https://xtiles.app/stub-view-planner"}],
69+
"parent_resource_url": "https://xtiles.app/stub-view-planner",
70+
}
71+
72+
73+
@mcp.tool()
74+
def xtiles_create_view_from_markdown(projectId: str, markdown: str) -> dict: # noqa: N803
75+
"""Create a new page in a project (stub: logs and returns a fake URL)."""
76+
_log_call("xtiles_create_view_from_markdown", {"projectId": projectId, "markdown": markdown})
77+
return {
78+
"view_id": "stub-view-page",
79+
"resource_url": "https://xtiles.app/stub-view-page",
80+
}
81+
82+
83+
if __name__ == "__main__":
84+
_log_path() # fail before the handshake when unconfigured, not on first call
85+
mcp.run() # stdio transport — the default, and the point
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
"""WD-4 — the stub ``xtiles`` MCP server speaks MCP, logs every call, no network.
2+
3+
The stub's one job is to make "a connector named ``xtiles`` is attached" real
4+
for the transcript acceptance tests. So the properties pinned here are exactly
5+
the ones those tests lean on: the server completes a real stdio handshake
6+
under the name ``xtiles``, exposes the three write tools the prompts select
7+
between, appends every call to the JSON artefact, and cannot reach a network.
8+
9+
Red when: a call is unlogged, a tool disappears, the server name drifts, or a
10+
network-capable import creeps into the stub.
11+
"""
12+
13+
from __future__ import annotations
14+
15+
import ast
16+
import json
17+
import sys
18+
from pathlib import Path
19+
20+
import pytest
21+
22+
pytest.importorskip("mcp")
23+
24+
from mcp import ClientSession, StdioServerParameters
25+
from mcp.client.stdio import stdio_client
26+
27+
STUB = Path(__file__).parent / "_xtiles_stub_server.py"
28+
29+
EXPECTED_TOOLS = {
30+
"xtiles_create_tasks",
31+
"xtiles_create_tiles_from_markdown_in_my_planner",
32+
"xtiles_create_view_from_markdown",
33+
}
34+
35+
#: Modules that can open a connection. The stub's transport is stdio and its
36+
#: whole value is being offline; one of these appearing in it is the defect.
37+
_NETWORK_MODULES = {
38+
"socket",
39+
"ssl",
40+
"http",
41+
"urllib",
42+
"urllib3",
43+
"requests",
44+
"httpx",
45+
"aiohttp",
46+
"websockets",
47+
}
48+
49+
50+
def _server_params(tmp_path: Path) -> tuple[StdioServerParameters, Path]:
51+
log = tmp_path / "stub-calls.json"
52+
params = StdioServerParameters(
53+
command=sys.executable,
54+
args=[str(STUB)],
55+
env={"XTILES_STUB_CALL_LOG": str(log)},
56+
)
57+
return params, log
58+
59+
60+
@pytest.mark.asyncio
61+
async def test_handshake_tools_and_call_log(tmp_path: Path) -> None:
62+
"""initialize → tools/list → one call per tool → every call in the artefact."""
63+
params, log = _server_params(tmp_path)
64+
65+
async with (
66+
stdio_client(params) as (read, write),
67+
ClientSession(read, write) as session,
68+
):
69+
init = await session.initialize()
70+
# The NAME is the gate: the wind-down skill's second half is "an MCP
71+
# server named `xtiles` is connected", so a drifted name here would
72+
# make the whole harness test a connector the skill cannot see.
73+
assert init.serverInfo.name == "xtiles"
74+
75+
tools = {t.name for t in (await session.list_tools()).tools}
76+
assert tools == EXPECTED_TOOLS
77+
78+
task_call = await session.call_tool(
79+
"xtiles_create_tasks",
80+
{"tasks": [{"title": "Study: decorators"}]},
81+
)
82+
assert not task_call.isError
83+
84+
tile_call = await session.call_tool(
85+
"xtiles_create_tiles_from_markdown_in_my_planner",
86+
{"period": "day", "date": "2026-09-04", "markdown": "### Study: decorators"},
87+
)
88+
assert not tile_call.isError
89+
# The one bit of response fidelity the prompts depend on: the planner
90+
# tile is the shape that returns a URL.
91+
assert "resource_url" in tile_call.content[0].text
92+
93+
page_call = await session.call_tool(
94+
"xtiles_create_view_from_markdown",
95+
{"projectId": "stub-project", "markdown": "## LR — page"},
96+
)
97+
assert not page_call.isError
98+
99+
calls = json.loads(log.read_text(encoding="utf-8"))
100+
assert [c["tool"] for c in calls] == [
101+
"xtiles_create_tasks",
102+
"xtiles_create_tiles_from_markdown_in_my_planner",
103+
"xtiles_create_view_from_markdown",
104+
], "a call was dropped from the log, or logged out of order"
105+
assert calls[0]["arguments"]["tasks"] == [{"title": "Study: decorators"}]
106+
assert calls[1]["arguments"]["markdown"] == "### Study: decorators"
107+
108+
109+
@pytest.mark.asyncio
110+
async def test_every_call_is_appended_not_overwritten(tmp_path: Path) -> None:
111+
"""Two calls to the SAME tool → two log entries. A log that keeps only the
112+
last call would grade a multi-write transcript as a single write."""
113+
params, log = _server_params(tmp_path)
114+
115+
async with (
116+
stdio_client(params) as (read, write),
117+
ClientSession(read, write) as session,
118+
):
119+
await session.initialize()
120+
for title in ("first", "second"):
121+
await session.call_tool("xtiles_create_tasks", {"tasks": [{"title": title}]})
122+
123+
calls = json.loads(log.read_text(encoding="utf-8"))
124+
assert len(calls) == 2
125+
assert calls[0]["arguments"]["tasks"][0]["title"] == "first"
126+
assert calls[1]["arguments"]["tasks"][0]["title"] == "second"
127+
128+
129+
def test_unconfigured_stub_refuses_to_run() -> None:
130+
"""No log path → exit before the handshake. A stub that ran unlogged would
131+
pass WD-5's silence checks vacuously — the exact trap (D4) this suite is
132+
built to avoid."""
133+
import subprocess
134+
135+
result = subprocess.run(
136+
[sys.executable, str(STUB)],
137+
capture_output=True,
138+
text=True,
139+
env={"PATH": "/usr/bin:/bin"},
140+
timeout=30,
141+
)
142+
assert result.returncode == 2
143+
assert "XTILES_STUB_CALL_LOG" in result.stderr
144+
145+
146+
def test_the_stub_imports_nothing_that_can_open_a_socket() -> None:
147+
"""Structural half of "reaches no network": stdio transport by
148+
construction, plus no network-capable import in the stub itself."""
149+
tree = ast.parse(STUB.read_text(encoding="utf-8"))
150+
imported: set[str] = set()
151+
for node in ast.walk(tree):
152+
if isinstance(node, ast.Import):
153+
imported.update(alias.name.split(".")[0] for alias in node.names)
154+
elif isinstance(node, ast.ImportFrom) and node.module:
155+
imported.add(node.module.split(".")[0])
156+
offenders = imported & _NETWORK_MODULES
157+
assert not offenders, f"the stub imports network-capable modules: {sorted(offenders)}"

0 commit comments

Comments
 (0)