test_mcp.py
python
sha256:0a2400b8017d871bff9916bfa6d3898b74b0dcce7f8e4d6e842365133f21090a
fix(coord): a task claim is one conditional UPDATE — exactl…
Opus 5.5
minor
⚠ breaking
1 day ago
| 1 | """DOC_MCP — /muse/mcp contract (musehub#252, QA contract v2). |
| 2 | |
| 3 | Every claim on the page was checked on 2026-11-07 against musehub ``dev`` fe5bf55b (the real ``/mcp`` router, session, |
| 4 | context, elicitation and stdio modules) and Muse 0.2.1rc20. These tests keep the corrected page honest in both |
| 5 | directions, offline and database-free: the HTTP transport runs in-process on a bare FastAPI app with the database |
| 6 | dependencies stubbed (nothing reaches them before the checks under test), the stdio server runs as a subprocess |
| 7 | against an unreachable database, and the page is rendered by the shared fixture. Known product defects stay |
| 8 | documented as contract plus warning (#241 defect-preservation rule): each is a strict xfail pinned to the behaviour |
| 9 | the contract wants. |
| 10 | |
| 11 | * DOC_MCP_01/02/03 — CLI parse, anchors, URL scheme: the shared checkers (``test_doc_inf_*``). |
| 12 | * DOC_MCP_04 — counts and the V3 tool matrix equal the live registry. |
| 13 | * DOC_MCP_05 — launch: the documented stdio command answers ``initialize``; the Muse CLI has no launcher. |
| 14 | * DOC_MCP_06 — Streamable HTTP: sessions, origins, protocol versions, auth gates, error codes. |
| 15 | * DOC_MCP_07 — elicitation and SSE frames (the V1 sequence figure). |
| 16 | * DOC_MCP_08 — known defects (strict xfail, musehub#289–#295; #300 needs PostgreSQL, so its race is recorded in the QA transcript): |
| 17 | a session works on every worker (#289), while elicitation and push across workers stay best effort (strict xfail). |
| 18 | """ |
| 19 | |
| 20 | from __future__ import annotations |
| 21 | |
| 22 | import asyncio |
| 23 | import json |
| 24 | import os |
| 25 | import re |
| 26 | import subprocess |
| 27 | import sys |
| 28 | from collections.abc import Iterator |
| 29 | |
| 30 | import pytest |
| 31 | from fastapi import FastAPI |
| 32 | from fastapi.testclient import TestClient |
| 33 | |
| 34 | from tests.docs_contract import cli_check as cc |
| 35 | from tests.docs_contract import mcp_session_table |
| 36 | from tests.docs_contract import registry_check as rc |
| 37 | |
| 38 | PAGE = rc.phase_path("mcp") |
| 39 | HUB_ISSUES = "https://staging.musehub.ai/gabriel/musehub/issues/" |
| 40 | _TICKETS = {"335"} |
| 41 | XFAIL = dict(strict=True, raises=AssertionError) |
| 42 | |
| 43 | INIT = {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { |
| 44 | "protocolVersion": "2025-11-25", "capabilities": {"elicitation": {"form": {}, "url": {}}}, |
| 45 | "clientInfo": {"name": "doc-mcp", "version": "1"}}} |
| 46 | |
| 47 | |
| 48 | @pytest.fixture(scope="module") |
| 49 | def html(rendered: dict[str, str]) -> str: |
| 50 | return rendered[PAGE].replace("'", "'").replace(""", '"').replace(""", '"') |
| 51 | |
| 52 | |
| 53 | def _rows(html: str, table_id: str) -> list[dict[str, str]]: |
| 54 | table = html.split(f'id="{table_id}"', 1)[1].split("</table>", 1)[0] |
| 55 | return [dict(re.findall(r'data-([a-z-]+)="([^"]*)"', m)) for m in re.findall(r"<tr [^>]*data-[^>]*>", table)] |
| 56 | |
| 57 | |
| 58 | def _section(html: str, anchor: str) -> str: |
| 59 | return html.split(f'id="{anchor}"', 1)[1].split("</section>", 1)[0] |
| 60 | |
| 61 | |
| 62 | # ── In-process transport ──────────────────────────────────────────────────── |
| 63 | |
| 64 | |
| 65 | @pytest.fixture(scope="module") |
| 66 | def client() -> Iterator[TestClient]: |
| 67 | from musehub.api.routes import mcp as route |
| 68 | from musehub.auth.request_signing import optional_signed_request |
| 69 | from musehub.rate_limits import limiter |
| 70 | |
| 71 | app = FastAPI() |
| 72 | app.state.limiter = limiter |
| 73 | app.include_router(route.router) |
| 74 | app.dependency_overrides[optional_signed_request] = lambda: None # anonymous caller |
| 75 | with mcp_session_table.installed(), TestClient(app) as c: # the session table every worker shares, in memory (#289) |
| 76 | yield c |
| 77 | |
| 78 | |
| 79 | @pytest.fixture() |
| 80 | def sid(client: TestClient) -> str: |
| 81 | r = client.post("/mcp", json=INIT) |
| 82 | assert r.status_code == 200 |
| 83 | return r.headers["Mcp-Session-Id"] |
| 84 | |
| 85 | |
| 86 | def _call(client: TestClient, sid: str | None, payload: object, **headers: str): # type: ignore[no-untyped-def] |
| 87 | h = dict(headers) |
| 88 | if sid: |
| 89 | h["Mcp-Session-Id"] = sid |
| 90 | return client.post("/mcp", json=payload, headers=h) |
| 91 | |
| 92 | |
| 93 | # ── DOC_MCP_04: counts and the tool matrix come from the registry ────────── |
| 94 | |
| 95 | |
| 96 | class TestCatalogue: |
| 97 | def test_group_counts_equal_the_registry(self, html: str) -> None: |
| 98 | from musehub.mcp.tools import musehub as reg |
| 99 | |
| 100 | expected = {"read": reg.MUSEHUB_READ_TOOLS, "write": reg.MUSEHUB_WRITE_TOOLS, |
| 101 | "elicitation": reg.MUSEHUB_ELICITATION_TOOLS, "coord-read": reg.MUSEHUB_COORD_READ_TOOLS, |
| 102 | "coord-write": reg.MUSEHUB_COORD_WRITE_TOOLS, "workspace": reg.MUSEHUB_WORKSPACE_TOOLS} |
| 103 | rows = {r["group"]: r for r in _rows(html, "tool-groups")} |
| 104 | for key, tools in expected.items(): |
| 105 | assert int(rows[key]["count"]) == len(tools), key |
| 106 | names = [r["tool"] for r in _rows(html, f"mcp-tools-{key}")] |
| 107 | assert names == [t["name"] for t in tools], key |
| 108 | assert sum(len(t) for t in expected.values()) == len(reg.MUSEHUB_TOOLS) |
| 109 | |
| 110 | def test_matrix_auth_scope_and_hints_match_the_gates_and_tools_list(self, html: str) -> None: |
| 111 | from musehub.api.routes.mcp import _SSE_TOOL_NAMES |
| 112 | from musehub.mcp import scope_policy |
| 113 | from musehub.mcp.dispatcher import _handle_tools_list |
| 114 | from musehub.mcp.tools import MUSEHUB_WRITE_TOOL_NAMES |
| 115 | |
| 116 | listed = {t["name"]: t["annotations"] for t in _handle_tools_list()["tools"]} |
| 117 | rows = [r for g in ("read", "write", "elicitation", "coord-read", "coord-write", "workspace") |
| 118 | for r in _rows(html, f"mcp-tools-{g}")] |
| 119 | assert len(rows) == len(listed) |
| 120 | for r in rows: |
| 121 | name, ann = r["tool"], listed[r["tool"]] |
| 122 | assert r["auth"] == ("msign" if name in MUSEHUB_WRITE_TOOL_NAMES else "anonymous"), name |
| 123 | assert r["readonly"] == str(bool(ann.get("readOnlyHint"))).lower(), name |
| 124 | assert r["destructive"] == str(bool(ann.get("destructiveHint"))).lower(), name |
| 125 | assert r["sse"] == str(name in _SSE_TOOL_NAMES).lower(), name |
| 126 | if name in scope_policy.REQUIRED_SCOPE: |
| 127 | assert r["scope"] == scope_policy.REQUIRED_SCOPE[name], name |
| 128 | |
| 129 | def test_resource_and_prompt_counts(self, html: str) -> None: |
| 130 | from musehub.mcp.prompts import PROMPT_CATALOGUE |
| 131 | from musehub.mcp.resources import RESOURCE_TEMPLATES, STATIC_RESOURCES |
| 132 | |
| 133 | props = _rows_text(html, "server-properties") |
| 134 | assert f"{len(STATIC_RESOURCES)} static + {len(RESOURCE_TEMPLATES)} URI templates" in props["Resources"] |
| 135 | assert props["Prompts"].startswith(str(len(PROMPT_CATALOGUE))) |
| 136 | |
| 137 | def test_server_version_is_the_served_one(self, html: str) -> None: |
| 138 | from musehub.mcp.dispatcher import _SERVER_VERSION |
| 139 | |
| 140 | assert _rows_text(html, "server-properties")["Server version"].startswith(_SERVER_VERSION) |
| 141 | |
| 142 | def test_schema_example_is_the_registry_schema(self, html: str) -> None: |
| 143 | from musehub.mcp.tools import MCP_TOOLS |
| 144 | |
| 145 | block = _section(html, "tools").split("Input schema example", 1)[1].split("<pre>", 1)[1].split("</pre>", 1)[0] |
| 146 | shown = json.loads(block) |
| 147 | tool = next(t for t in MCP_TOOLS if t["name"] == "musehub_list_commits") |
| 148 | assert shown == {"name": tool["name"], "inputSchema": tool["inputSchema"]} |
| 149 | |
| 150 | |
| 151 | def _rows_text(html: str, table_id: str) -> dict[str, str]: |
| 152 | table = html.split(f'id="{table_id}"', 1)[1].split("</table>", 1)[0] |
| 153 | out = {} |
| 154 | for tr in re.findall(r"<tr>(.*?)</tr>", table, re.S): |
| 155 | cells = [re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", c)).strip() for c in re.findall(r"<td[^>]*>(.*?)</td>", tr, re.S)] |
| 156 | if len(cells) >= 2: |
| 157 | out[cells[0]] = cells[1] |
| 158 | return out |
| 159 | |
| 160 | |
| 161 | # ── DOC_MCP_05: the documented launch paths ───────────────────────────────── |
| 162 | |
| 163 | |
| 164 | class TestLaunch: |
| 165 | def test_the_muse_cli_has_no_mcp_launcher(self) -> None: |
| 166 | parser = cc.capture_parser() |
| 167 | assert cc.check_line(parser, cc.DocCommand("muse hub mcp", in_pre=True)).kind != "ok" |
| 168 | |
| 169 | def test_the_page_documents_no_launcher_command(self, html: str) -> None: |
| 170 | assert not [c.line for c in cc.extract_commands(html) if c.line.startswith("muse hub mcp")] |
| 171 | assert 'id="launch-not-available"' in html |
| 172 | |
| 173 | def test_documented_stdio_command_answers_initialize(self, tmp_path) -> None: # type: ignore[no-untyped-def] |
| 174 | assert "python -m musehub.mcp.stdio_server" in _section(_html_raw(), "transports") |
| 175 | # Runs from an empty directory (no .env) against an unreachable database; the import path is made absolute. |
| 176 | root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 177 | path = [root, *(os.path.abspath(p) for p in os.environ.get("PYTHONPATH", "").split(os.pathsep) if p)] |
| 178 | env = {**os.environ, "HOME": str(tmp_path), "PYTHONPATH": os.pathsep.join(path), |
| 179 | "DATABASE_URL": "postgresql+asyncpg://qa:[email protected]:9/none"} |
| 180 | lines = [json.dumps(INIT), json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})] |
| 181 | p = subprocess.run([sys.executable, "-m", "musehub.mcp.stdio_server"], input="\n".join(lines) + "\n", |
| 182 | capture_output=True, text=True, timeout=120, cwd=tmp_path, env=env) |
| 183 | out = [json.loads(line) for line in p.stdout.splitlines() if line.strip()] |
| 184 | assert len(out) == 2, p.stderr[-2000:] |
| 185 | assert out[0]["result"]["serverInfo"]["name"] == "musehub-mcp" |
| 186 | from musehub.mcp.tools import MCP_TOOLS |
| 187 | assert len(out[1]["result"]["tools"]) == len(MCP_TOOLS) |
| 188 | |
| 189 | |
| 190 | def _html_raw() -> str: |
| 191 | from tests.docs_contract.pages import render_all |
| 192 | return render_all()[PAGE] |
| 193 | |
| 194 | |
| 195 | # ── DOC_MCP_06: Streamable HTTP behaviour ─────────────────────────────────── |
| 196 | |
| 197 | |
| 198 | class TestTransport: |
| 199 | def test_initialize_result_and_session_header(self, client: TestClient, html: str) -> None: |
| 200 | r = client.post("/mcp", json=INIT) |
| 201 | res = r.json()["result"] |
| 202 | assert len(r.headers["Mcp-Session-Id"]) == 43 and "43-character" in html |
| 203 | assert res["protocolVersion"] == "2025-11-25" and res["serverInfo"]["name"] == "musehub-mcp" |
| 204 | caps = _section(html, "session").split("Server capabilities", 1)[1].split("<pre>", 1)[1].split("</pre>", 1)[0] |
| 205 | assert json.loads(re.sub(r"<[^>]+>", "", caps))["capabilities"] == res["capabilities"] |
| 206 | assert [line.split(" —")[0] for line in res["instructions"].splitlines() if line.startswith("STEP")] == \ |
| 207 | ["STEP 1", "STEP 2", "STEP 3", "STEP 4"] |
| 208 | |
| 209 | def test_session_properties(self, html: str) -> None: |
| 210 | from musehub.mcp import context, session |
| 211 | |
| 212 | assert session._SESSION_TTL_SECONDS == 15 * 60 and session._SSE_BUFFER_SIZE == 50 |
| 213 | assert context._ELICITATION_TIMEOUT_SECONDS == 300.0 |
| 214 | props = _rows_text(html, "session-properties") |
| 215 | assert props["Session TTL"].startswith("15 minutes") and "50 most recent" in props["Event buffer"] |
| 216 | assert "10,000" in props["Max sessions"] and "Retry-After: 5" in props["Max sessions"] |
| 217 | |
| 218 | def test_stateless_requests_and_unknown_sessions(self, client: TestClient) -> None: |
| 219 | assert _call(client, None, {"jsonrpc": "2.0", "id": 1, "method": "ping"}).status_code == 200 |
| 220 | r = _call(client, "nope", {"jsonrpc": "2.0", "id": 1, "method": "ping"}) |
| 221 | assert r.status_code == 404 and r.json()["error"]["code"] == -32600 |
| 222 | |
| 223 | @pytest.mark.parametrize(("origin", "status"), [("https://evil.example", 403), ("https://musehub.ai", 200), |
| 224 | ("http://localhost", 200), ("http://localhost:5173", 403)]) |
| 225 | def test_origins_match_exactly(self, client: TestClient, sid: str, origin: str, status: int) -> None: |
| 226 | assert _call(client, sid, {"jsonrpc": "2.0", "id": 1, "method": "ping"}, Origin=origin).status_code == status |
| 227 | |
| 228 | @pytest.mark.parametrize(("version", "status"), [("2025-11-25", 200), ("2025-03-26", 200), ("2024-11-05", 400)]) |
| 229 | def test_protocol_version_header(self, client: TestClient, sid: str, version: str, status: int) -> None: |
| 230 | r = _call(client, sid, {"jsonrpc": "2.0", "id": 1, "method": "ping"}, **{"MCP-Protocol-Version": version}) |
| 231 | assert r.status_code == status |
| 232 | |
| 233 | def test_msign_tool_without_signature(self, client: TestClient, sid: str, html: str) -> None: |
| 234 | call = {"jsonrpc": "2.0", "id": 4, "method": "tools/call", |
| 235 | "params": {"name": "musehub_list_collaborators", "arguments": {"owner": "o", "slug": "s"}}} |
| 236 | r = _call(client, sid, call) |
| 237 | assert r.status_code == 401 and r.json()["error"]["code"] == -32001 |
| 238 | assert r.headers["WWW-Authenticate"] == 'MSign realm="musehub"' |
| 239 | batch = _call(client, sid, [{**call, "params": {"name": "musehub_create_issue", "arguments": {"owner": "o", "slug": "s"}}}]) |
| 240 | entry = batch.json()[0]["result"] |
| 241 | assert batch.status_code == 200 and entry["isError"] is True |
| 242 | err = json.loads(entry["content"][0]["text"]) |
| 243 | assert err["error_code"] == "unauthenticated" and "requires authentication" in err["error_message"] |
| 244 | assert "musehub_list_collaborators" in _section(html, "auth") |
| 245 | |
| 246 | def test_get_and_delete(self, client: TestClient, sid: str) -> None: |
| 247 | assert client.get("/mcp", headers={"Mcp-Session-Id": sid}).status_code == 405 |
| 248 | assert client.get("/mcp", headers={"Accept": "text/event-stream"}).status_code == 400 |
| 249 | assert client.delete("/mcp", headers={"Mcp-Session-Id": sid}).status_code == 200 |
| 250 | assert client.delete("/mcp", headers={"Mcp-Session-Id": sid}).status_code == 404 |
| 251 | |
| 252 | def test_jsonrpc_error_codes(self, client: TestClient, sid: str, html: str) -> None: |
| 253 | def code(method: str) -> int: |
| 254 | return _call(client, sid, {"jsonrpc": "2.0", "id": 9, "method": method, "params": {}}).json()["error"]["code"] |
| 255 | |
| 256 | assert code("logging/setLevel") == -32000 and code("no/such") == -32601 |
| 257 | bad = client.post("/mcp", content=b"{x", headers={"Content-Type": "application/json", "Mcp-Session-Id": sid}) |
| 258 | assert bad.status_code == 400 and bad.json()["error"]["code"] == -32700 |
| 259 | stub = _call(client, sid, {"jsonrpc": "2.0", "id": 9, "method": "completions/complete"}).json()["result"] |
| 260 | assert stub == {"completion": {"values": [], "hasMore": False, "total": 0}} |
| 261 | codes = set(re.findall(r"<td><code>(-32\d{3})</code></td>", _section(html, "errors"))) |
| 262 | assert codes == {"-32700", "-32600", "-32601", "-32602", "-32603", "-32000", "-32001", "-32042"} |
| 263 | |
| 264 | def test_malformed_msign_header_is_rejected(self) -> None: |
| 265 | from musehub.api.routes import mcp as route |
| 266 | from musehub.db.database import get_db |
| 267 | from musehub.rate_limits import limiter |
| 268 | |
| 269 | app = FastAPI() |
| 270 | app.state.limiter = limiter |
| 271 | app.include_router(route.router) |
| 272 | app.dependency_overrides[get_db] = lambda: None # the header is refused before any lookup |
| 273 | with TestClient(app) as c: |
| 274 | r = c.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "ping"}, |
| 275 | headers={"Authorization": 'MSign handle="h" ts=1745280000 sig="abc"'}) |
| 276 | assert r.status_code == 401 and r.json() == {"detail": "Malformed MSign header."} |
| 277 | |
| 278 | def test_every_msign_example_carries_alg(self, html: str) -> None: |
| 279 | headers = re.findall(r"MSign handle=[^\n<]*", html) |
| 280 | assert headers and all('alg="ed25519"' in h for h in headers), headers |
| 281 | |
| 282 | def test_tool_error_codes_on_the_page_are_emitted(self, html: str) -> None: |
| 283 | import pathlib |
| 284 | |
| 285 | root = pathlib.Path(__file__).resolve().parents[2] / "musehub" |
| 286 | src = "".join(p.read_text() for p in [*root.joinpath("mcp").rglob("*.py"), root / "services/musehub_mcp_executor.py", |
| 287 | root / "services/musehub_coord_server.py"]) |
| 288 | emitted = set(re.findall(r'error_code="([a-z_]+)"', src)) |
| 289 | table = _section(html, "errors").split('id="tool-error-codes"', 1)[1].split("</table>", 1)[0] |
| 290 | documented = set(re.findall(r"<code>([a-z_]+)</code>", table)) |
| 291 | assert documented <= emitted, documented - emitted |
| 292 | |
| 293 | |
| 294 | # ── DOC_MCP_07: elicitation and SSE frames ───────────────────────────────── |
| 295 | |
| 296 | |
| 297 | def _run(coro): # type: ignore[no-untyped-def] |
| 298 | return asyncio.run(coro) |
| 299 | |
| 300 | |
| 301 | async def _review(action: str) -> tuple[str, dict, object]: |
| 302 | from types import SimpleNamespace |
| 303 | from unittest.mock import AsyncMock, patch |
| 304 | |
| 305 | from musehub.mcp import context, session |
| 306 | from musehub.mcp.write_tools import elicitation_tools |
| 307 | |
| 308 | sess = session.create_session("doc-mcp", {"elicitation": {"form": {}, "url": {}}}) |
| 309 | q: asyncio.Queue[str | None] = asyncio.Queue() |
| 310 | sess.sse_queues.append(q) |
| 311 | # The worked example reviews a proposal in a code repository: the form offers that domain's dimensions (musehub#313). |
| 312 | target = (SimpleNamespace(from_branch="feat", to_branch="main"), "code") |
| 313 | with patch.object(elicitation_tools, "_load_review_target", AsyncMock(return_value=target)): |
| 314 | task = asyncio.create_task(elicitation_tools.execute_review_proposal_interactive("r", "p", ctx=context.ToolCallContext("doc-mcp", sess))) |
| 315 | frame = await asyncio.wait_for(q.get(), 5) |
| 316 | payload = json.loads(frame.split("data: ", 1)[1]) |
| 317 | result: dict[str, object] = {"action": action} |
| 318 | if action == "accept": |
| 319 | result["content"] = {"dimension_focus": "structure", "review_depth": "thorough"} |
| 320 | session.resolve_elicitation(sess, payload["id"], result) |
| 321 | out = await asyncio.wait_for(task, 10) |
| 322 | session.delete_session(sess.session_id) |
| 323 | return frame, payload, out |
| 324 | |
| 325 | |
| 326 | class TestElicitation: |
| 327 | def test_form_frame_matches_the_worked_example(self, html: str) -> None: |
| 328 | frame, payload, _ = _run(_review("decline")) |
| 329 | assert re.match(r"id: [0-9a-f]+-\d+\ndata: ", frame) and frame.endswith("\n\n") |
| 330 | assert re.search(r"<pre>id: [0-9a-f]+-\d+\ndata: ", _section(html, "elicitation").split("Step 2", 1)[1]) |
| 331 | assert re.fullmatch(r"elicit-\d+-[0-9a-f]{8}", payload["id"]) |
| 332 | assert payload["method"] == "elicitation/create" and payload["params"]["mode"] == "form" |
| 333 | schema = payload["params"]["requestedSchema"] |
| 334 | example = _section(html, "elicitation").split("Step 2", 1)[1].split("</pre>", 1)[0] |
| 335 | for prop in ("dimension_focus", "review_depth"): |
| 336 | assert json.dumps(schema["properties"][prop]["enum"], separators=(",", ":")) in example, prop |
| 337 | assert schema["required"] == ["dimension_focus", "review_depth"] |
| 338 | assert '"required":["dimension_focus","review_depth"]' in example |
| 339 | |
| 340 | def test_worked_example_uses_a_dimension_the_form_accepts(self, html: str) -> None: |
| 341 | from musehub.mcp.elicitation import SCHEMAS |
| 342 | |
| 343 | enum = set(SCHEMAS["proposal_review_focus"]["properties"]["dimension_focus"]["enum"]) |
| 344 | section = _section(html, "elicitation") |
| 345 | request = re.findall(r'dimension_focus"</span>: <span class="tok-str">"([^"]+)"', section) |
| 346 | response = re.findall(r'focus_dimension\\": \\"([^"\\]+)', section) |
| 347 | assert request and response, "worked-example dimensions not found" |
| 348 | used = set(request) | set(response) |
| 349 | assert used <= enum, used - enum |
| 350 | |
| 351 | def test_decline_is_an_error_not_a_fallback(self, html: str) -> None: |
| 352 | _, _, out = _run(_review("decline")) |
| 353 | assert out.ok is False and out.error_code == "elicitation_declined" |
| 354 | assert "does not fall back" in html and '"elicitation_declined": true' not in html |
| 355 | |
| 356 | def test_accept_continues_into_the_review(self) -> None: |
| 357 | _, _, out = _run(_review("accept")) |
| 358 | assert out.error_code in ("db_unavailable", None) # past the form: the review itself needs the database |
| 359 | |
| 360 | def test_cancellation_is_keyed_by_request_id(self) -> None: |
| 361 | from musehub.mcp import context, dispatcher, session |
| 362 | |
| 363 | async def go() -> object: |
| 364 | sess = session.create_session("doc-mcp", {"elicitation": {}}) |
| 365 | q: asyncio.Queue[str | None] = asyncio.Queue() |
| 366 | sess.sse_queues.append(q) |
| 367 | task = asyncio.create_task(context.ToolCallContext("doc-mcp", sess).elicit_form({"type": "object"}, "m")) |
| 368 | rid = json.loads((await q.get()).split("data: ", 1)[1])["id"] |
| 369 | await dispatcher._dispatch("notifications/cancelled", {"requestId": rid}, user_id=None, session=sess) |
| 370 | return await asyncio.wait_for(task, 5) |
| 371 | |
| 372 | assert _run(go()) is None |
| 373 | |
| 374 | |
| 375 | # ── DOC_MCP_08: known defects (contract + warning) ────────────────────────── |
| 376 | |
| 377 | |
| 378 | async def _progress_frames(replay: bool) -> tuple[list[str], list[str]]: |
| 379 | """Three progress events, the first read live; then a reconnect, with the first event's ID if *replay*.""" |
| 380 | from musehub.mcp import context, session |
| 381 | |
| 382 | sess = session.create_session("doc-mcp", {}) |
| 383 | live: list[str] = [] |
| 384 | agen = session.register_sse_queue(sess) |
| 385 | reader = asyncio.create_task(agen.__anext__()) |
| 386 | await asyncio.sleep(0) |
| 387 | for i in range(3): |
| 388 | await context.ToolCallContext("doc-mcp", sess, progress_token="t").progress(i + 1, 3) |
| 389 | live.append(await asyncio.wait_for(reader, 2)) |
| 390 | await agen.aclose() |
| 391 | last_event_id = live[0].split("\n", 1)[0].removeprefix("id: ") if replay else None |
| 392 | replayed: list[str] = [] |
| 393 | agen = session.register_sse_queue(sess, last_event_id) |
| 394 | try: |
| 395 | while True: |
| 396 | replayed.append(await asyncio.wait_for(agen.__anext__(), 0.2)) |
| 397 | except (asyncio.TimeoutError, StopAsyncIteration): |
| 398 | pass |
| 399 | finally: |
| 400 | await agen.aclose() |
| 401 | session.delete_session(sess.session_id) |
| 402 | return live, replayed |
| 403 | |
| 404 | |
| 405 | class TestKnownDefects: |
| 406 | def test_every_known_issue_links_its_ticket(self, html: str) -> None: |
| 407 | linked = set(re.findall(rf"{re.escape(HUB_ISSUES)}(\d+)", html)) |
| 408 | assert _TICKETS <= linked, _TICKETS - linked |
| 409 | assert {r["ticket"] for r in _rows(html, "known-issues-table")} == _TICKETS |
| 410 | |
| 411 | def test_a_session_survives_a_request_on_another_worker(self, client: TestClient, sid: str, html: str) -> None: |
| 412 | from musehub.mcp import session |
| 413 | |
| 414 | saved = dict(session._SESSIONS) |
| 415 | session._SESSIONS.clear() # a second worker process starts with an empty store |
| 416 | try: |
| 417 | assert _call(client, sid, {"jsonrpc": "2.0", "id": 1, "method": "ping"}).status_code == 200 |
| 418 | session._SESSIONS.clear() |
| 419 | assert client.delete("/mcp", headers={"Mcp-Session-Id": sid}).status_code == 200 # ends it everywhere |
| 420 | finally: |
| 421 | session._SESSIONS.update(saved) |
| 422 | assert _call(client, sid, {"jsonrpc": "2.0", "id": 1, "method": "ping"}).status_code == 404 |
| 423 | props = _rows_text(html, "session-properties") |
| 424 | assert "every worker" in props["Where sessions live"] and 'id="session-affinity-warning"' not in html |
| 425 | |
| 426 | @pytest.mark.xfail(reason="musehub#335: elicitation is per worker; a reply on another worker finds no Future", **XFAIL) |
| 427 | def test_an_elicitation_reply_on_another_worker_reaches_the_tool(self, client: TestClient, sid: str, html: str) -> None: |
| 428 | from musehub.mcp import session |
| 429 | |
| 430 | assert 'data-ticket="335"' in html and "300-second timeout" in html |
| 431 | tool_worker = dict(session._SESSIONS) |
| 432 | fut = asyncio.new_event_loop().create_future() |
| 433 | tool_worker[sid].pending["elicit-x"] = fut # the tool waits on the worker that runs it |
| 434 | session._SESSIONS.clear() # the reply reaches another worker |
| 435 | try: |
| 436 | r = _call(client, sid, {"jsonrpc": "2.0", "id": "elicit-x", "result": {"action": "accept", "content": {}}}) |
| 437 | assert r.status_code == 202 and fut.done() |
| 438 | finally: |
| 439 | session._SESSIONS.clear() |
| 440 | session._SESSIONS.update(tool_worker) |
| 441 | tool_worker[sid].pending.pop("elicit-x", None) |
| 442 | |
| 443 | def test_a_reconnect_without_last_event_id_replays_nothing(self) -> None: |
| 444 | live, replayed = _run(_progress_frames(False)) |
| 445 | assert live[0].startswith("id: ") and replayed == [] |
| 446 | |
| 447 | def test_last_event_id_replays_later_events(self, html: str) -> None: |
| 448 | live, replayed = _run(_progress_frames(True)) |
| 449 | assert live[0].startswith("id: ") and len(replayed) == 2 |
| 450 | assert [f.split("\n", 1)[0] for f in replayed] == sorted({f.split("\n", 1)[0] for f in replayed}, key=lambda i: int(i.rsplit("-", 1)[1])) |
| 451 | assert 'id="sse-replay-warning"' not in html and "replays the buffered events after it" in html |
| 452 | |
| 453 | def test_elicitation_complete_resolves_a_url_elicitation(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 454 | from musehub.mcp import context, dispatcher, session |
| 455 | |
| 456 | monkeypatch.setattr(context, "_ELICITATION_TIMEOUT_SECONDS", 0.5) |
| 457 | |
| 458 | async def go() -> bool: |
| 459 | sess = session.create_session("doc-mcp", {"elicitation": {"url": {}}}) |
| 460 | q: asyncio.Queue[str | None] = asyncio.Queue() |
| 461 | sess.sse_queues.append(q) |
| 462 | task = asyncio.create_task(context.ToolCallContext("doc-mcp", sess).elicit_url("https://x.invalid/", "m", "e1")) |
| 463 | await q.get() |
| 464 | await dispatcher._dispatch("notifications/elicitation/complete", {"elicitationId": "e1"}, user_id=None, session=sess) |
| 465 | return await task |
| 466 | |
| 467 | assert _run(go()) is True |
| 468 | |
| 469 | @pytest.mark.parametrize("name", ["musehub_delete_repo", "musehub_delete_user_account", "musehub_transfer_repo_ownership"]) |
| 470 | def test_destructive_tools_are_annotated(self, name: str) -> None: |
| 471 | from musehub.mcp.dispatcher import _handle_tools_list |
| 472 | |
| 473 | assert {t["name"]: t["annotations"] for t in _handle_tools_list()["tools"]}[name]["destructiveHint"] is True |
| 474 | |
| 475 | def test_progress_echoes_the_request_token(self) -> None: |
| 476 | from musehub.mcp import session |
| 477 | from musehub.mcp.dispatcher import _handle_tools_call |
| 478 | |
| 479 | async def go() -> list[str]: |
| 480 | sess = session.create_session("doc-mcp", {}) |
| 481 | q: asyncio.Queue[str | None] = asyncio.Queue() |
| 482 | sess.sse_queues.append(q) |
| 483 | await _handle_tools_call({"name": "musehub_review_proposal_interactive", "_meta": {"progressToken": "p-1"}, |
| 484 | "arguments": {"repo_id": "", "proposal_id": "p", "dimension": "all", "depth": "quick"}}, |
| 485 | user_id="doc-mcp", session=sess) |
| 486 | frames = [] |
| 487 | while not q.empty(): |
| 488 | frames.append(q.get_nowait() or "") |
| 489 | return frames |
| 490 | |
| 491 | frames = _run(go()) |
| 492 | assert frames and all('"progressToken":"p-1"' in f for f in frames) |
| 493 | |
| 494 | def test_one_dimension_vocabulary(self) -> None: |
| 495 | from musehub.mcp.context import ToolCallContext |
| 496 | from musehub.mcp.elicitation import SCHEMAS |
| 497 | from musehub.mcp.write_tools.elicitation_tools import execute_review_proposal_interactive |
| 498 | |
| 499 | guide = _run(execute_review_proposal_interactive("r", "p", ctx=ToolCallContext("doc-mcp", None))).data |
| 500 | assert set(guide["dimension_options"]) == set(SCHEMAS["proposal_review_focus"]["properties"]["dimension_focus"]["enum"]) |
| 501 | |
| 502 | def test_gate_errors_carry_an_error_code(self, client: TestClient, sid: str) -> None: |
| 503 | call = {"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "musehub_create_issue", "arguments": {}}} |
| 504 | entry = _call(client, sid, [call]).json()[0]["result"] |
| 505 | assert "error_code" in json.loads(entry["content"][0]["text"]) |
| 506 | |
| 507 | |
| 508 | # ── Static page checks ─────────────────────────────────────────────────────── |
| 509 | |
| 510 | |
| 511 | class TestPage: |
| 512 | def test_superseded_claims_are_gone(self, html: str) -> None: |
| 513 | for needle in ("119", "45 read", "identity.toml</code> provides the signing key", "id: 58", "event: elicitation/create", |
| 514 | '"ok": true', "Read tools and all resource/prompt reads work without authentication", |
| 515 | "the hub's own origin", "always return HTTP 200", '"args": ["hub"'): |
| 516 | assert needle not in html, needle |
| 517 | |
| 518 | def test_every_sidebar_section_exists(self, html: str) -> None: |
| 519 | for anchor in ("overview", "transports", "launch", "connect", "session", "tools", "coordination", "elicitation", |
| 520 | "sse", "auth", "errors", "known-issues", "tool-catalogue-figure", "elicitation-sequence-figure"): |
| 521 | assert f'id="{anchor}"' in html, anchor |
| 522 | |
| 523 | def test_sequence_figure_steps(self, html: str) -> None: |
| 524 | fig = html.split('id="elicitation-sequence-figure"', 1)[1].split("</figure>", 1)[0] |
| 525 | assert re.findall(r'data-channel="([a-z]+)"', fig) == ["get", "post", "get", "post", "get", "stream"] |
| 526 | assert 'aria-labelledby="elicitation-sequence-figure-title"' in html |
| 527 | |
| 528 | def test_coordination_defaults(self, html: str) -> None: |
| 529 | import pathlib |
| 530 | |
| 531 | src = (pathlib.Path(__file__).resolve().parents[2] / "musehub/services/musehub_coord_server.py").read_text() |
| 532 | assert "else 300" in src and "else 50" in src |
| 533 | rows = _rows_text(html, "coord-defaults") |
| 534 | assert rows["Reservation TTL default"].startswith("300 s") and rows["Task priority default"] == "50" |
File History
19 commits
sha256:0a2400b8017d871bff9916bfa6d3898b74b0dcce7f8e4d6e842365133f21090a
fix(coord): a task claim is one conditional UPDATE — exactl…
Opus 5.5
minor
⚠
1 day ago
sha256:2b93e88316d2f32df15a9f877b0b6e5fae363de59bc428ce5709f86e230581d8
docs(mcp): the cross-worker elicitation/push known issue mo…
Opus 5.5
patch
1 day ago
sha256:e6c07a0f17d2b30516cfe406c094c493c3aeaf8ea72db9ca098d24013bcc3bb9
Merge branch 'task/wave-hub-mcp-289' into dev
Opus 5.5
minor
⚠
1 day ago
sha256:08c30c873257205e342a68f5d55803ff3c6dd6abd4747b5444c68e1da4b8da39
fix(mcp): bind sessions to their principal; honest cross-wo…
Opus 5.5
minor
⚠
1 day ago
sha256:5e59815d34816a1aa12717d0ac82362d6a9919e8b6e096e66ed49c47a028d76f
fix(mcp): share Streamable HTTP sessions across worker proc…
Opus 5.5
minor
⚠
1 day ago
sha256:299f7e61ed29513b71569e957cfd8ce55e2132041d220b1387ce0b43b12a3d92
Merge branch 'task/313-on-dev' into dev
Opus 5.5
minor
⚠
1 day ago
sha256:dc8a25669115527392507de6bb24bd7a06c109fdc1814cf7bed97ec10c835acb
fix(proposals): diff, compare, divergence and diff-summary …
Opus 5.5
minor
⚠
1 day ago
sha256:d7af2b937831db3288db5589530c6c2f8e90f0c2c4efbbeb5dd0577076168b29
fix(mcp): SSE event ids + Last-Event-ID replay (#290); per-…
Opus 5.5
minor
⚠
1 day ago
sha256:f19d5e4a89766fc91b926cdf801255e12dcd968041c0ece8adf6627760788d22
merge: next build — MCP (#291 #292 #295 #324), profiles/sit…
Opus 5.5
minor
⚠
1 day ago
sha256:87f4c4d976afad92db715748495c09600f4aafed5f924e6b4b1664aab5a86fad
merge: rc26 — MCP wave (#291 #292 #295 #324)
Opus 5.5
minor
⚠
1 day ago
sha256:8f71621a510dbf00c5cef4b4a877ab154ea8c4af406d0fe7f0319a368b954f64
fix(mcp): notifications/elicitation/complete resolves the U…
Opus 5.5
minor
⚠
2 days ago
sha256:e0601efe55c167c25a25964556649adc67857bd02e415016a026c852e1a535b2
fix(mcp): gate and dispatcher errors carry error_code/error…
Opus 5.5
minor
⚠
2 days ago
sha256:ff23c9c281bee839f187bbaf3d30de9e88d331e3c404ed45e2845954f04cad82
fix(mcp): tools/list sets all four hints from one registry …
Opus 5.5
minor
⚠
2 days ago
sha256:b020dfcaf95656a94e47604849662f7a93a3616a775fccbc69dae8a554afe46c
docs(mcp): use a valid dimension in the review worked examp…
Sonnet 5.5
patch
6 days ago
sha256:3d450cb7100e86b4c435cbfeb8d185f2b659827e9beb43ab1dcd32e6e31e955c
docs(mcp): drop the stale #294 known issue
Sonnet 5.5
patch
6 days ago
sha256:397179b78ae61f8f1422f89db39f61e7906688c7ed907a41fd687774e71b4494
docs(mcp): progress events echo the request's _meta.progres…
Opus 5.5
patch
6 days ago
sha256:7509cea23a330ac39d3db91391c88932011b9ba6e7f5a8615cb7889e27e426c1
fix(mcp): one dimension vocabulary for interactive proposal…
Opus 5.5
patch
6 days ago
sha256:75ea6757bc3427a326603f3b7a5eee006173366f3f331a75ef4b01997f747e83
fix(mcp): progress notifications carry the request's _meta.…
Opus 5.5
minor
⚠
6 days ago
sha256:417ffbc1d6761e3a4cd26ca5475d5a0b786ae8af936912b5ce31121e2e55c19a
docs(mcp): #252 MCP Tooling QA contract v2 — correct /muse/…
Opus 5.5
minor
⚠
9 days ago