test_mcp_stdio_session.py
python
sha256:4defb0407ee7fe26b1addb8df5cf3d31dae4ebf1ab92eeca1c05348b9d4c8458
merge: integrate R1 into the publishable #114 line (private…
Opus 5.5
minor
⚠ breaking
12 days ago
| 1 | """TDD — musehub#210: stdio transport's session focus not honored. |
| 2 | |
| 3 | ``musehub_set_context`` writes to ``session.repo_focus``, and the dispatcher |
| 4 | injects that focus into the next call's arguments when ``owner``/``slug`` |
| 5 | are omitted (see ``_handle_tools_call`` in ``musehub/mcp/dispatcher.py``). |
| 6 | That mechanism itself was never broken. The bug was entirely in |
| 7 | ``musehub/mcp/stdio_server.py``: every ``handle_request()`` call passed |
| 8 | ``session=None`` (the default) — no ``MCPSession`` was ever created for |
| 9 | the stdio transport at all, unlike the Streamable HTTP transport, which |
| 10 | creates one right after a successful ``initialize`` and threads it through |
| 11 | via the ``Mcp-Session-Id`` header on every subsequent request. |
| 12 | |
| 13 | These tests exercise ``stdio_server._run()`` end-to-end against fake |
| 14 | stdin/stdout pipes — the real regression surface — reproducing the |
| 15 | ticket's exact repro sequence (initialize -> musehub_set_context -> |
| 16 | musehub_read_context with no args, single process, sequential requests). |
| 17 | """ |
| 18 | from __future__ import annotations |
| 19 | |
| 20 | import asyncio |
| 21 | import json |
| 22 | from unittest.mock import AsyncMock, MagicMock, patch |
| 23 | |
| 24 | import pytest |
| 25 | |
| 26 | |
| 27 | @pytest.fixture |
| 28 | def allow_repo_gate(): |
| 29 | """Routing-only tests: stub the dispatcher's repo authorization gate. |
| 30 | |
| 31 | Repo read/write authorization is covered by tests/test_security_r1_*.py. |
| 32 | """ |
| 33 | with patch("musehub.mcp.dispatcher._repo_gate_error", AsyncMock(return_value=None)): |
| 34 | yield |
| 35 | |
| 36 | |
| 37 | class _FakeWriteTransport(asyncio.WriteTransport): |
| 38 | """Records every line written to stdout instead of touching a real pipe.""" |
| 39 | |
| 40 | def __init__(self) -> None: |
| 41 | self.written: list[bytes] = [] |
| 42 | |
| 43 | def write(self, data: bytes) -> None: |
| 44 | self.written.append(data) |
| 45 | |
| 46 | def lines(self) -> list[dict]: |
| 47 | return [json.loads(b.decode("utf-8")) for b in self.written] |
| 48 | |
| 49 | |
| 50 | async def _run_stdio_with_lines(lines: list[dict]) -> list[dict]: |
| 51 | """Feed *lines* through stdio_server._run() and return the parsed responses. |
| 52 | |
| 53 | Patches the real stdin/stdout pipe connections with an in-memory |
| 54 | StreamReader and a fake write transport, and patches ``init_db`` so the |
| 55 | test doesn't need a real database. |
| 56 | """ |
| 57 | from musehub.mcp import stdio_server |
| 58 | |
| 59 | reader = asyncio.StreamReader() |
| 60 | for line in lines: |
| 61 | reader.feed_data((json.dumps(line) + "\n").encode("utf-8")) |
| 62 | reader.feed_eof() |
| 63 | |
| 64 | fake_transport = _FakeWriteTransport() |
| 65 | |
| 66 | async def _fake_connect_read_pipe(protocol_factory, pipe): |
| 67 | protocol = protocol_factory() |
| 68 | protocol.connection_made(MagicMock()) |
| 69 | return MagicMock(), protocol |
| 70 | |
| 71 | async def _fake_connect_write_pipe(protocol_factory, pipe): |
| 72 | return fake_transport, protocol_factory() |
| 73 | |
| 74 | loop = asyncio.get_event_loop() |
| 75 | with ( |
| 76 | patch.object(loop, "connect_read_pipe", side_effect=_fake_connect_read_pipe), |
| 77 | patch.object(loop, "connect_write_pipe", side_effect=_fake_connect_write_pipe), |
| 78 | patch("musehub.db.init_db", new_callable=AsyncMock), |
| 79 | ): |
| 80 | # _run() builds its own StreamReader internally; feed ours in its |
| 81 | # place by patching asyncio.StreamReader to return our pre-fed one. |
| 82 | with patch("asyncio.StreamReader", return_value=reader): |
| 83 | await stdio_server._run() |
| 84 | |
| 85 | return fake_transport.lines() |
| 86 | |
| 87 | |
| 88 | @pytest.mark.asyncio |
| 89 | class TestStdioSessionPersistence: |
| 90 | async def test_set_context_then_read_context_resolves_focused_repo(self, allow_repo_gate: None) -> None: |
| 91 | """The ticket's exact repro: initialize, musehub_set_context, then |
| 92 | musehub_read_context with NO args in the same stdio process. Must |
| 93 | resolve to the focused repo, not an empty-string repository lookup.""" |
| 94 | mock_resolve = AsyncMock(return_value=("repo-123", None)) |
| 95 | mock_read_context = AsyncMock(return_value=MagicMock(ok=True, data={"repo_id": "repo-123"})) |
| 96 | |
| 97 | with ( |
| 98 | patch("musehub.mcp.dispatcher._resolve_repo_id", mock_resolve), |
| 99 | patch( |
| 100 | "musehub.services.musehub_mcp_executor.execute_read_context", |
| 101 | mock_read_context, |
| 102 | ), |
| 103 | ): |
| 104 | responses = await _run_stdio_with_lines([ |
| 105 | {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-11-25"}}, |
| 106 | { |
| 107 | "jsonrpc": "2.0", "id": 2, "method": "tools/call", |
| 108 | "params": {"name": "musehub_set_context", "arguments": {"owner": "gabriel", "slug": "build-with-muse"}}, |
| 109 | }, |
| 110 | { |
| 111 | "jsonrpc": "2.0", "id": 3, "method": "tools/call", |
| 112 | "params": {"name": "musehub_read_context", "arguments": {}}, |
| 113 | }, |
| 114 | ]) |
| 115 | |
| 116 | assert len(responses) == 3 |
| 117 | # musehub_set_context succeeded. |
| 118 | set_context_resp = responses[1] |
| 119 | assert set_context_resp["result"]["isError"] is False |
| 120 | |
| 121 | # musehub_read_context must have been called with the focused repo_id |
| 122 | # resolved from session.repo_focus -- NOT an empty-string lookup. |
| 123 | read_context_resp = responses[2] |
| 124 | assert read_context_resp["result"]["isError"] is False |
| 125 | mock_read_context.assert_awaited_once() |
| 126 | assert mock_read_context.await_args.args[0] == "repo-123" |
| 127 | |
| 128 | # The owner/slug resolution for the focused repo must have been |
| 129 | # triggered by the SESSION injection, not by explicit arguments on |
| 130 | # call 3 (call 3's arguments were empty). |
| 131 | resolved_calls = [c for c in mock_resolve.await_args_list if c.args == ("gabriel", "build-with-muse")] |
| 132 | assert len(resolved_calls) >= 1 |
| 133 | |
| 134 | async def test_session_is_reused_not_recreated_per_message(self, allow_repo_gate: None) -> None: |
| 135 | """A second initialize mid-stream is a distinct scenario; absent |
| 136 | that, the same MCPSession object must back every call after the |
| 137 | first initialize -- confirmed by set_context's write surviving to |
| 138 | the read_context call three messages later.""" |
| 139 | mock_resolve = AsyncMock(return_value=("repo-456", None)) |
| 140 | mock_read_context = AsyncMock(return_value=MagicMock(ok=True, data={})) |
| 141 | |
| 142 | with ( |
| 143 | patch("musehub.mcp.dispatcher._resolve_repo_id", mock_resolve), |
| 144 | patch( |
| 145 | "musehub.services.musehub_mcp_executor.execute_read_context", |
| 146 | mock_read_context, |
| 147 | ), |
| 148 | ): |
| 149 | responses = await _run_stdio_with_lines([ |
| 150 | {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, |
| 151 | { |
| 152 | "jsonrpc": "2.0", "id": 2, "method": "tools/call", |
| 153 | "params": {"name": "musehub_set_context", "arguments": {"owner": "acme", "slug": "widgets"}}, |
| 154 | }, |
| 155 | {"jsonrpc": "2.0", "id": 3, "method": "tools/list"}, |
| 156 | { |
| 157 | "jsonrpc": "2.0", "id": 4, "method": "tools/call", |
| 158 | "params": {"name": "musehub_read_context", "arguments": {}}, |
| 159 | }, |
| 160 | ]) |
| 161 | |
| 162 | assert len(responses) == 4 |
| 163 | mock_read_context.assert_awaited_once() |
| 164 | assert mock_read_context.await_args.args[0] == "repo-456" |
File History
3 commits
sha256:4defb0407ee7fe26b1addb8df5cf3d31dae4ebf1ab92eeca1c05348b9d4c8458
merge: integrate R1 into the publishable #114 line (private…
Opus 5.5
minor
⚠
12 days ago
sha256:83227647a82e1733a20b0b6d225df3d153769630d3c710d255e0c1b8aab8ae61
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Opus 5.5
minor
⚠
13 days ago
sha256:64298d820f83e03ad4a1d3dae5a5fe2e57d124c1ebd0d56e99d93e69b595dccc
fix: stdio MCP transport never created a session, breaking …
Sonnet 5
minor
⚠
25 days ago