|
| 1 | +"""Phase 9.0 — MCP server bridge serves the full triple: tools + resources + prompts. |
| 2 | +
|
| 3 | +Reuses the same subprocess-driven JSON-RPC test pattern as test_mcp_server.py. |
| 4 | +""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import json |
| 8 | +import os |
| 9 | +import socket |
| 10 | +import sys |
| 11 | +import threading |
| 12 | +import time |
| 13 | + |
| 14 | +import pytest |
| 15 | + |
| 16 | +try: |
| 17 | + import fastapi # noqa |
| 18 | + import uvicorn # noqa |
| 19 | + DEPS_AVAILABLE = True |
| 20 | +except ImportError: |
| 21 | + DEPS_AVAILABLE = False |
| 22 | + |
| 23 | +if DEPS_AVAILABLE: |
| 24 | + from zhub.server import create_app |
| 25 | +from zhub import publish |
| 26 | + |
| 27 | + |
| 28 | +def _free_port() -> int: |
| 29 | + with socket.socket() as s: |
| 30 | + s.bind(("", 0)) |
| 31 | + return s.getsockname()[1] |
| 32 | + |
| 33 | + |
| 34 | +@pytest.fixture(scope="module") |
| 35 | +def hub(): |
| 36 | + if not DEPS_AVAILABLE: |
| 37 | + pytest.skip("fastapi/uvicorn not installed") |
| 38 | + port = _free_port() |
| 39 | + app = create_app() |
| 40 | + |
| 41 | + def run(): |
| 42 | + config = uvicorn.Config(app, host="127.0.0.1", port=port, |
| 43 | + log_level="warning") |
| 44 | + asyncio.run(uvicorn.Server(config).serve()) |
| 45 | + |
| 46 | + threading.Thread(target=run, daemon=True).start() |
| 47 | + for _ in range(30): |
| 48 | + try: |
| 49 | + with socket.create_connection(("127.0.0.1", port), timeout=0.1): |
| 50 | + break |
| 51 | + except OSError: |
| 52 | + time.sleep(0.1) |
| 53 | + yield port |
| 54 | + |
| 55 | + |
| 56 | +async def _send_recv(proc, method: str, params: dict, req_id: int) -> dict: |
| 57 | + msg = {"jsonrpc": "2.0", "id": req_id, "method": method, "params": params} |
| 58 | + proc.stdin.write((json.dumps(msg) + "\n").encode()) |
| 59 | + await proc.stdin.drain() |
| 60 | + while True: |
| 61 | + line = await asyncio.wait_for(proc.stdout.readline(), timeout=10.0) |
| 62 | + if not line: |
| 63 | + raise AssertionError("mcp_server closed stdout") |
| 64 | + try: |
| 65 | + data = json.loads(line.decode()) |
| 66 | + except json.JSONDecodeError: |
| 67 | + continue |
| 68 | + if data.get("id") == req_id: |
| 69 | + return data |
| 70 | + |
| 71 | + |
| 72 | +async def _spawn_mcp(hub_http: str, ai: str, key: str): |
| 73 | + env = dict(os.environ) |
| 74 | + env["PYTHONUNBUFFERED"] = "1" |
| 75 | + return await asyncio.create_subprocess_exec( |
| 76 | + sys.executable, "-m", "zhub.mcp_server", |
| 77 | + "--hub", hub_http, "--ai", ai, "--key", key, |
| 78 | + stdin=asyncio.subprocess.PIPE, |
| 79 | + stdout=asyncio.subprocess.PIPE, |
| 80 | + stderr=asyncio.subprocess.PIPE, |
| 81 | + env=env, |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +@pytest.mark.asyncio |
| 86 | +async def test_initialize_advertises_all_three_surfaces(hub): |
| 87 | + hub_http = f"http://127.0.0.1:{hub}" |
| 88 | + pub = publish(name="mcp-init-bot", description="x", |
| 89 | + chat_handler=lambda m, o: "ok", |
| 90 | + hub_url=f"ws://127.0.0.1:{hub}") |
| 91 | + for _ in range(50): |
| 92 | + if pub.api_key: |
| 93 | + break |
| 94 | + await asyncio.sleep(0.1) |
| 95 | + |
| 96 | + proc = await _spawn_mcp(hub_http, pub.name, pub.api_key) |
| 97 | + try: |
| 98 | + r = await _send_recv(proc, "initialize", { |
| 99 | + "protocolVersion": "2024-11-05", "capabilities": {}, |
| 100 | + "clientInfo": {"name": "pytest", "version": "0"}, |
| 101 | + }, 1) |
| 102 | + caps = r["result"]["capabilities"] |
| 103 | + assert "tools" in caps |
| 104 | + assert "resources" in caps |
| 105 | + assert "prompts" in caps |
| 106 | + finally: |
| 107 | + proc.terminate() |
| 108 | + try: |
| 109 | + await asyncio.wait_for(proc.wait(), timeout=3.0) |
| 110 | + except asyncio.TimeoutError: |
| 111 | + proc.kill() |
| 112 | + await proc.wait() |
| 113 | + |
| 114 | + |
| 115 | +@pytest.mark.asyncio |
| 116 | +async def test_resources_list_and_read(hub): |
| 117 | + hub_http = f"http://127.0.0.1:{hub}" |
| 118 | + resources = [ |
| 119 | + { |
| 120 | + "uri": "zhub://res-bot/readme", |
| 121 | + "name": "readme", |
| 122 | + "description": "the project readme", |
| 123 | + "mimeType": "text/markdown", |
| 124 | + "content": "# Project\n\nHello.", |
| 125 | + }, |
| 126 | + { |
| 127 | + "uri": "zhub://res-bot/config", |
| 128 | + "name": "config", |
| 129 | + "mimeType": "application/json", |
| 130 | + "content": "{\"k\":1}", |
| 131 | + }, |
| 132 | + ] |
| 133 | + pub = publish(name="res-bot", description="r", |
| 134 | + chat_handler=lambda m, o: "ok", |
| 135 | + hub_url=f"ws://127.0.0.1:{hub}", |
| 136 | + resources=resources) |
| 137 | + for _ in range(50): |
| 138 | + if pub.api_key: |
| 139 | + break |
| 140 | + await asyncio.sleep(0.1) |
| 141 | + |
| 142 | + proc = await _spawn_mcp(hub_http, pub.name, pub.api_key) |
| 143 | + try: |
| 144 | + await _send_recv(proc, "initialize", { |
| 145 | + "protocolVersion": "2024-11-05", "capabilities": {}, |
| 146 | + "clientInfo": {"name": "pytest", "version": "0"}, |
| 147 | + }, 1) |
| 148 | + listed = await _send_recv(proc, "resources/list", {}, 2) |
| 149 | + items = listed["result"]["resources"] |
| 150 | + assert {x["uri"] for x in items} == { |
| 151 | + "zhub://res-bot/readme", "zhub://res-bot/config", |
| 152 | + } |
| 153 | + # Each must have name, no content (read separately) |
| 154 | + names = {x["name"] for x in items} |
| 155 | + assert names == {"readme", "config"} |
| 156 | + |
| 157 | + read = await _send_recv(proc, "resources/read", |
| 158 | + {"uri": "zhub://res-bot/readme"}, 3) |
| 159 | + contents = read["result"]["contents"] |
| 160 | + assert contents[0]["uri"] == "zhub://res-bot/readme" |
| 161 | + assert contents[0]["text"].startswith("# Project") |
| 162 | + assert contents[0]["mimeType"] == "text/markdown" |
| 163 | + |
| 164 | + bad = await _send_recv(proc, "resources/read", |
| 165 | + {"uri": "zhub://nope"}, 4) |
| 166 | + assert "error" in bad |
| 167 | + finally: |
| 168 | + proc.terminate() |
| 169 | + try: |
| 170 | + await asyncio.wait_for(proc.wait(), timeout=3.0) |
| 171 | + except asyncio.TimeoutError: |
| 172 | + proc.kill() |
| 173 | + await proc.wait() |
| 174 | + |
| 175 | + |
| 176 | +@pytest.mark.asyncio |
| 177 | +async def test_prompts_list_and_get_with_substitution(hub): |
| 178 | + hub_http = f"http://127.0.0.1:{hub}" |
| 179 | + prompts = [ |
| 180 | + { |
| 181 | + "name": "summarize", |
| 182 | + "description": "summarize text in 3 bullets", |
| 183 | + "arguments": [ |
| 184 | + {"name": "text", "required": True, |
| 185 | + "description": "the text to summarize"}, |
| 186 | + ], |
| 187 | + "messages": [ |
| 188 | + {"role": "user", |
| 189 | + "content": "Summarize this in 3 bullets:\n\n{text}"}, |
| 190 | + ], |
| 191 | + }, |
| 192 | + ] |
| 193 | + pub = publish(name="prompt-bot", description="p", |
| 194 | + chat_handler=lambda m, o: "ok", |
| 195 | + hub_url=f"ws://127.0.0.1:{hub}", |
| 196 | + prompts=prompts) |
| 197 | + for _ in range(50): |
| 198 | + if pub.api_key: |
| 199 | + break |
| 200 | + await asyncio.sleep(0.1) |
| 201 | + |
| 202 | + proc = await _spawn_mcp(hub_http, pub.name, pub.api_key) |
| 203 | + try: |
| 204 | + await _send_recv(proc, "initialize", { |
| 205 | + "protocolVersion": "2024-11-05", "capabilities": {}, |
| 206 | + "clientInfo": {"name": "pytest", "version": "0"}, |
| 207 | + }, 1) |
| 208 | + listed = await _send_recv(proc, "prompts/list", {}, 2) |
| 209 | + items = listed["result"]["prompts"] |
| 210 | + assert any(p["name"] == "summarize" for p in items) |
| 211 | + sumarize = next(p for p in items if p["name"] == "summarize") |
| 212 | + assert sumarize["arguments"][0]["name"] == "text" |
| 213 | + assert sumarize["arguments"][0]["required"] is True |
| 214 | + |
| 215 | + got = await _send_recv(proc, "prompts/get", |
| 216 | + {"name": "summarize", |
| 217 | + "arguments": {"text": "the rain in spain"}}, |
| 218 | + 3) |
| 219 | + msgs = got["result"]["messages"] |
| 220 | + assert msgs[0]["role"] == "user" |
| 221 | + # MCP message content shape: {type: "text", text: "..."} OR plain string |
| 222 | + content = msgs[0]["content"] |
| 223 | + text = content if isinstance(content, str) else content.get("text", "") |
| 224 | + assert "the rain in spain" in text |
| 225 | + |
| 226 | + # Missing required arg |
| 227 | + bad = await _send_recv(proc, "prompts/get", |
| 228 | + {"name": "summarize", "arguments": {}}, 4) |
| 229 | + assert "error" in bad |
| 230 | + |
| 231 | + # Unknown prompt |
| 232 | + nope = await _send_recv(proc, "prompts/get", |
| 233 | + {"name": "doesnt-exist", "arguments": {}}, 5) |
| 234 | + assert "error" in nope |
| 235 | + finally: |
| 236 | + proc.terminate() |
| 237 | + try: |
| 238 | + await asyncio.wait_for(proc.wait(), timeout=3.0) |
| 239 | + except asyncio.TimeoutError: |
| 240 | + proc.kill() |
| 241 | + await proc.wait() |
0 commit comments