feat: token-protected HTTP transport for the MCP server
wodify mcp --http HOST:PORT serves MCP streamable HTTP at /mcp, stdlib only. A bearer token of 32+ chars is mandatory and checked before the path; prime is not offered over HTTP; tool calls are serialized. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
This commit is contained in:
1 parent
7be931a712
commit
3909c35565
5 files changed
+324
-4
No files matched your search
@@ -301,3 +301,118 @@ def test_my_classes_reports_a_stale_session(tools, wire, monkeypatch):
|
||||
res = call(tools, "my_classes")
|
||||
assert res["isError"] is True
|
||||
assert "STALE" in res["content"][0]["text"] and "exit 4" in res["content"][0]["text"]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------ HTTP
|
||||
|
||||
TOKEN = "t" * 40
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def http(monkeypatch):
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
monkeypatch.setattr(mcpserver, "run_cli", lambda argv: (0, "ran " + " ".join(argv)))
|
||||
server = mcpserver.make_http_server("127.0.0.1", 0, TOKEN)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
base = f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
def request(method="POST", path="/mcp", body=None, token=TOKEN, raw=None):
|
||||
data = raw if raw is not None else (
|
||||
json.dumps(body).encode() if body is not None else None)
|
||||
req = urllib.request.Request(base + path, data=data, method=method)
|
||||
if token is not None:
|
||||
req.add_header("Authorization", f"Bearer {token}")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=5) as res:
|
||||
text = res.read().decode()
|
||||
return res.status, json.loads(text) if text else None
|
||||
except urllib.error.HTTPError as exc:
|
||||
text = exc.read().decode()
|
||||
return exc.code, json.loads(text) if text else None
|
||||
|
||||
request.port = server.server_address[1]
|
||||
yield request
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _rpc(method, params=None, msg_id=1):
|
||||
return {"jsonrpc": "2.0", "id": msg_id, "method": method, "params": params or {}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("token", [None, "", "wrong" * 10, TOKEN[:-1], TOKEN + "x"])
|
||||
def test_http_refuses_anything_without_the_exact_token(http, token):
|
||||
for method, path in (("POST", "/mcp"), ("GET", "/mcp"), ("GET", "/"),
|
||||
("POST", "/anything")):
|
||||
status, body = http(method, path, _rpc("tools/list") if method == "POST" else None,
|
||||
token=token)
|
||||
assert status == 401, (method, path)
|
||||
assert body == {"error": "unauthorized"}
|
||||
|
||||
|
||||
def test_http_serves_mcp_with_the_token(http):
|
||||
status, body = http(body=_rpc("initialize", {"protocolVersion": "2025-06-18"}))
|
||||
assert status == 200 and body["result"]["serverInfo"]["name"] == "wodify"
|
||||
|
||||
status, body = http(body={"jsonrpc": "2.0", "method": "notifications/initialized"})
|
||||
assert (status, body) == (202, None)
|
||||
|
||||
status, body = http(body=_rpc("tools/call", {"name": "my_classes", "arguments": {}}))
|
||||
assert status == 200
|
||||
assert body["result"]["content"][0]["text"] == "ran list mine"
|
||||
|
||||
|
||||
def test_http_does_not_offer_prime(http):
|
||||
_, body = http(body=_rpc("tools/list"))
|
||||
names = [t["name"] for t in body["result"]["tools"]]
|
||||
assert "prime" not in names and "my_classes" in names
|
||||
_, body = http(body=_rpc("tools/call", {"name": "prime"}))
|
||||
assert body["result"]["isError"] is True
|
||||
_, body = http(body=_rpc("initialize"))
|
||||
assert "not offered over HTTP" in body["result"]["instructions"]
|
||||
|
||||
|
||||
def test_http_only_answers_post_on_the_mcp_path(http):
|
||||
assert http("GET")[0] == 405
|
||||
assert http("DELETE")[0] == 405
|
||||
assert http("POST", "/other", _rpc("ping"))[0] == 404
|
||||
assert http("POST", "/mcp/", _rpc("ping"))[0] == 200
|
||||
|
||||
|
||||
def test_http_rejects_garbage_and_oversized_bodies(http):
|
||||
status, body = http(raw=b"not json")
|
||||
assert status == 400 and body["error"]["code"] == -32700
|
||||
|
||||
|
||||
def test_http_refuses_an_oversized_body_before_reading_it(http):
|
||||
"""Declared length alone is enough: the body is never read."""
|
||||
import socket
|
||||
port = http.port
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=5) as sock:
|
||||
sock.sendall((f"POST /mcp HTTP/1.1\r\nHost: x\r\n"
|
||||
f"Authorization: Bearer {TOKEN}\r\n"
|
||||
f"Content-Length: {mcpserver.MAX_BODY_BYTES + 1}\r\n\r\n").encode())
|
||||
assert sock.recv(64).startswith(b"HTTP/1.1 413")
|
||||
|
||||
|
||||
def test_http_will_not_start_without_a_real_token(monkeypatch, tmp_path):
|
||||
with pytest.raises(ValueError):
|
||||
mcpserver.make_http_server("127.0.0.1", 0, "short")
|
||||
|
||||
monkeypatch.delenv("WODIFY_MCP_TOKEN", raising=False)
|
||||
with pytest.raises(SystemExit, match="no MCP token"):
|
||||
mcpserver.load_token(str(tmp_path / "missing"))
|
||||
|
||||
weak = tmp_path / "weak"
|
||||
weak.write_text("hunter2\n")
|
||||
with pytest.raises(SystemExit, match="too short"):
|
||||
mcpserver.load_token(str(weak))
|
||||
|
||||
good = tmp_path / "good"
|
||||
good.write_text(TOKEN + "\n")
|
||||
assert mcpserver.load_token(str(good)) == TOKEN
|
||||
monkeypatch.setenv("WODIFY_MCP_TOKEN", "e" * 40)
|
||||
assert mcpserver.load_token(str(good)) == "e" * 40
|
||||
Reference in new issue
Block a user