|
16 | 16 |
|
17 | 17 | import asyncio |
18 | 18 | import json |
| 19 | +import socket |
| 20 | +import time |
19 | 21 | from unittest.mock import MagicMock |
20 | 22 |
|
21 | | -from dimos.agents.mcp.mcp_server import handle_request |
| 23 | +import requests |
| 24 | + |
| 25 | +from dimos.agents.mcp.mcp_server import McpServer, handle_request |
22 | 26 | from dimos.core.module import SkillInfo |
23 | 27 |
|
24 | 28 |
|
@@ -111,3 +115,56 @@ def test_mcp_module_initialize_and_unknown() -> None: |
111 | 115 |
|
112 | 116 | response = asyncio.run(handle_request({"method": "unknown/method", "id": 2}, [], {})) |
113 | 117 | assert response["error"]["code"] == -32601 |
| 118 | + |
| 119 | + |
| 120 | +def _free_port() -> int: |
| 121 | + with socket.socket() as s: |
| 122 | + s.bind(("", 0)) |
| 123 | + return s.getsockname()[1] |
| 124 | + |
| 125 | + |
| 126 | +def test_mcp_server_lifecycle() -> None: |
| 127 | + """Start a real McpServer, hit the HTTP endpoint, then stop it. |
| 128 | +
|
| 129 | + This exercises the AsyncModuleThread event loop integration that the |
| 130 | + unit tests above do not cover. |
| 131 | + """ |
| 132 | + port = _free_port() |
| 133 | + |
| 134 | + server = McpServer() |
| 135 | + server._start_server(port=port) |
| 136 | + url = f"http://127.0.0.1:{port}/mcp" |
| 137 | + |
| 138 | + # Wait for the server to be ready |
| 139 | + for _ in range(40): |
| 140 | + try: |
| 141 | + resp = requests.post( |
| 142 | + url, |
| 143 | + json={"jsonrpc": "2.0", "method": "initialize", "id": 1}, |
| 144 | + timeout=0.5, |
| 145 | + ) |
| 146 | + if resp.status_code == 200: |
| 147 | + break |
| 148 | + except requests.ConnectionError: |
| 149 | + time.sleep(0.1) |
| 150 | + else: |
| 151 | + server.stop() |
| 152 | + raise AssertionError("McpServer did not become ready") |
| 153 | + |
| 154 | + # Verify it responds |
| 155 | + data = resp.json() |
| 156 | + assert data["result"]["serverInfo"]["name"] == "dimensional" |
| 157 | + |
| 158 | + # Stop and verify it shuts down |
| 159 | + server.stop() |
| 160 | + time.sleep(0.3) |
| 161 | + |
| 162 | + with socket.socket() as s: |
| 163 | + # Port should be released after stop |
| 164 | + try: |
| 165 | + s.connect(("127.0.0.1", port)) |
| 166 | + s.close() |
| 167 | + # If we could connect, the server is still up — that's a bug |
| 168 | + raise AssertionError("McpServer still listening after stop()") |
| 169 | + except ConnectionRefusedError: |
| 170 | + pass # expected — server is down |
0 commit comments