#!/usr/bin/env python3 """Zwei erfundene MCP-Server plus Prüfungen gegen junction. Der Test startet zwei winzige MCP-Server (einer für Aufgaben, einer für Fähigkeiten), trägt sie in eine junction-Konfiguration ein und prüft dann über HTTP, was ein Agent tatsächlich sieht: 1. initialize antwortet mit Werkzeug-Fähigkeit 2. tools/list nennt beide Server und macht die Namen eindeutig 3. tools/call geht an den richtigen Server, mit dem unveränderten Werkzeugnamen 4. ein Werkzeug, das es nicht gibt, wird abgelehnt statt geraten 5. eine Meldung ohne id bekommt 202 und keine Antwort 6. ein Server, der nicht antwortet, macht die Liste nicht kaputt """ import json import os import socket import subprocess import sys import tempfile import threading import time import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer JUNCTION = os.environ.get("JUNCTION_BIN", "./junction") PORT = 18190 TOOLS = { "tasksd": [ {"name": "task_create", "description": "Aufgabe anlegen", "inputSchema": {"type": "object", "properties": {"goal": {"type": "string"}}}}, {"name": "task_list", "description": "Aufgaben zeigen", "inputSchema": {"type": "object", "properties": {}}}, ], "skilld": [ {"name": "skill_list", "description": "Fähigkeiten zeigen", "inputSchema": {"type": "object", "properties": {}}}, ], } PROMPTS = { "tasksd": [{"name": "summarize", "description": "Aufgaben zusammenfassen", "arguments": [{"name": "scope", "required": True}]}], "skilld": [{"name": "explain", "description": "Fähigkeit erklären", "arguments": [{"name": "skill", "required": True}]}], } RESOURCES = { "tasksd": [{"uri": "memory://tasks", "name": "Aufgaben", "mimeType": "text/plain"}], "skilld": [{"uri": "memory://skills", "name": "Fähigkeiten", "mimeType": "text/plain"}], } calls = [] # (server, tool, arguments) die tatsächlich ankamen prompt_calls = [] # (server, name, arguments) — der Name MUSS ohne Präfix ankommen resource_calls = [] # (server, uri) — die URI MUSS ohne Präfix ankommen def make_handler(which): class H(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass def _send(self, obj, code=200): body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_POST(self): n = int(self.headers.get("Content-Length") or 0) req = json.loads(self.rfile.read(n) or b"{}") method = req.get("method") if method == "initialize": return self._send({"jsonrpc": "2.0", "id": req.get("id"), "result": {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": which}}}) if method == "tools/list": return self._send({"jsonrpc": "2.0", "id": req.get("id"), "result": {"tools": TOOLS[which]}}) if method == "prompts/list": return self._send({"jsonrpc": "2.0", "id": req.get("id"), "result": {"prompts": PROMPTS[which]}}) if method == "prompts/get": p = req.get("params") or {} prompt_calls.append((which, p.get("name"), p.get("arguments"))) return self._send({"jsonrpc": "2.0", "id": req.get("id"), "result": {"description": f"{which}:{p.get('name')}", "messages": [{"role": "user", "content": {"type": "text", "text": "hi"}}]}}) if method == "resources/list": return self._send({"jsonrpc": "2.0", "id": req.get("id"), "result": {"resources": RESOURCES[which]}}) if method == "resources/read": p = req.get("params") or {} resource_calls.append((which, p.get("uri"))) return self._send({"jsonrpc": "2.0", "id": req.get("id"), "result": {"contents": [{"uri": p.get("uri"), "text": f"{which}:ok"}]}}) if method == "tools/call": p = req.get("params") or {} calls.append((which, p.get("name"), p.get("arguments"))) return self._send({"jsonrpc": "2.0", "id": req.get("id"), "result": {"content": [{"type": "text", "text": f"{which}:{p.get('name')}"}], "isError": False}}) return self._send({"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": -32601, "message": "no"}}) return H def post(url, payload, timeout=25, headers=None): data = json.dumps(payload).encode() hdrs = {"Content-Type": "application/json"} if headers: hdrs.update(headers) req = urllib.request.Request(url, data=data, method="POST", headers=hdrs) t0 = time.time() try: with urllib.request.urlopen(req, timeout=timeout) as r: body = r.read().decode() status = r.status except urllib.error.HTTPError as e: # 401 ist hier ein erwartetes Ergebnis, kein Absturz des Tests. body = e.read().decode() status = e.code return status, body if os.environ.get("MCP_VERBOSE"): print(" %-14s %5.1fs %s" % (payload.get("method"), time.time() - t0, body[:60])) return status, body def wait_port(port, timeout=30.0): """Wait for the listener instead of sleeping. Junction talks to its MCP servers while it starts; a fixed 1.2 s was enough on an idle box and too short under load, and the first POST then failed with "connection refused" -- the whole suite failed for a test that had simply looked too early. """ end = time.time() + timeout while time.time() < end: try: with socket.create_connection(("127.0.0.1", port), timeout=0.5): return True except OSError: time.sleep(0.05) return False def main(): servers = {} for name in TOOLS: srv = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(name)) threading.Thread(target=srv.serve_forever, daemon=True).start() servers[name] = srv ports = {n: s.server_address[1] for n, s in servers.items()} with tempfile.TemporaryDirectory() as tmp: conf = os.path.join(tmp, "junction.conf") with open(conf, "w") as f: f.write(f"""listen 127.0.0.1:{PORT} log_prefix jmcp mcp_cache_ttl 1 mcp tasksd url http://127.0.0.1:{ports['tasksd']}/mcp timeout 2 mcp skilld url http://127.0.0.1:{ports['skilld']}/mcp timeout 2 mcp tot url http://127.0.0.1:9/mcp timeout 1 mcp local cmd "python3 {os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mcp_stdio.py')}" mcp krumm cmd "exit 1" endpoint dummy {{ base http://127.0.0.1:9/v1 kind remote context 8000 priority 10 }} """) proc = subprocess.Popen([JUNCTION, "--config", conf], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if not wait_port(PORT): proc.kill() print("FAIL: junction did not listen on", PORT) sys.exit(1) base = f"http://127.0.0.1:{PORT}/mcp" failures = [] try: # 1. initialize st, body = post(base, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}) j = json.loads(body) if j.get("result", {}).get("serverInfo", {}).get("name") != "junction": failures.append(f"initialize: {body[:120]}") caps = j.get("result", {}).get("capabilities", {}) if "tools" not in caps: failures.append("initialize nennt keine Werkzeug-Fähigkeit") if "prompts" not in caps or "resources" not in caps: failures.append(f"initialize nennt Prompts/Ressourcen nicht: {sorted(caps)}") # 2. tools/list st, body = post(base, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) j = json.loads(body) names = [t["name"] for t in j["result"]["tools"]] want = {"tasksd__task_create", "tasksd__task_list", "skilld__skill_list"} # Teilmenge, nicht Gleichheit: der stdio-Server weiter unten liefert ein # eigenes Werkzeug dazu, und diese Prüfung handelt von den HTTP-Servern. if not want <= set(names): failures.append(f"tools/list: {names} statt {sorted(want)}") # Beschreibung muss erhalten sein for t in j["result"]["tools"]: if t["name"] == "tasksd__task_create" and not t.get("description"): failures.append("Beschreibung des Werkzeugs ging verloren") if t["name"] == "tasksd__task_create" and not t.get("inputSchema"): failures.append("Schema des Werkzeugs ging verloren") # 3. tools/call an den richtigen Server st, body = post(base, {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "skilld__skill_list", "arguments": {}}}) j = json.loads(body) txt = j["result"]["content"][0]["text"] if txt != "skilld:skill_list": failures.append(f"tools/call ging an den falschen Server: {txt!r}") if calls != [("skilld", "skill_list", {})]: failures.append(f"Server sah: {calls}") # Argumente müssen unverändert durchgehen st, body = post(base, {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "tasksd__task_create", "arguments": {"goal": "Test mit Ümlaut"}}}) if not calls or calls[-1] != ("tasksd", "task_create", {"goal": "Test mit Ümlaut"}): failures.append(f"Argumente verstümmelt: {calls[-1:] or 'kein Aufruf'}") # 4. unbekanntes Werkzeug wird abgelehnt st, body = post(base, {"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "gibtsnicht", "arguments": {}}}) j = json.loads(body) if "error" not in j: failures.append("unbekanntes Werkzeug wurde nicht abgelehnt") # 4b. Prompts: gebündelt, präfixt, beim Abruf wieder abgenommen st, body = post(base, {"jsonrpc": "2.0", "id": 11, "method": "prompts/list"}) j = json.loads(body) pnames = {p["name"] for p in j["result"]["prompts"]} if not {"skilld__explain", "tasksd__summarize"} <= pnames: failures.append(f"prompts/list: {sorted(pnames)}") st, body = post(base, {"jsonrpc": "2.0", "id": 12, "method": "prompts/get", "params": {"name": "tasksd__summarize", "arguments": {"scope": "heute"}}}) j = json.loads(body) if j.get("result", {}).get("description") != "tasksd:summarize": failures.append(f"prompts/get ging an den falschen Server: {body[:120]}") if prompt_calls != [("tasksd", "summarize", {"scope": "heute"})]: failures.append(f"Prompt-Name kam präfixt beim Server an: {prompt_calls}") # 4c. Ressourcen: URI präfixt in der Liste, ohne Präfix beim Lesen st, body = post(base, {"jsonrpc": "2.0", "id": 13, "method": "resources/list"}) j = json.loads(body) uris = {r["uri"] for r in j["result"]["resources"]} if not {"skilld__memory://skills", "tasksd__memory://tasks"} <= uris: failures.append(f"resources/list: {sorted(uris)}") st, body = post(base, {"jsonrpc": "2.0", "id": 14, "method": "resources/read", "params": {"uri": "skilld__memory://skills"}}) j = json.loads(body) if j.get("result", {}).get("contents", [{}])[0].get("text") != "skilld:ok": failures.append(f"resources/read ging an den falschen Server: {body[:120]}") if resource_calls != [("skilld", "memory://skills")]: failures.append(f"URI kam präfixt beim Server an: {resource_calls}") # 4d. Unbekanntes Präfix wird abgelehnt, nicht geraten st, body = post(base, {"jsonrpc": "2.0", "id": 15, "method": "prompts/get", "params": {"name": "niemand__x", "arguments": {}}}) if "error" not in json.loads(body): failures.append("unbekanntes Prompt-Präfix wurde nicht abgelehnt") # 4e. stdio-Upstream: eigener Prozess, JSON-Zeilen über stdin/stdout st, body = post(base, {"jsonrpc": "2.0", "id": 21, "method": "tools/list"}) j = json.loads(body) names = [t["name"] for t in j["result"]["tools"]] if "local__echo" not in names: failures.append(f"stdio-Server fehlt in der Werkzeugliste: {names}") if not any(n.startswith("tasksd__") for n in names): failures.append(f"ein kaputtes stdio-Kommando riss die HTTP-Server mit: {names}") st, body = post(base, {"jsonrpc": "2.0", "id": 22, "method": "tools/call", "params": {"name": "local__echo", "arguments": {"text": "hallo"}}}) j = json.loads(body) txt = j.get("result", {}).get("content", [{}])[0].get("text") if txt != "stdio:echo:hallo": failures.append(f"stdio tools/call: {txt!r} ({body[:120]})") # Prompts und Ressourcen kommen aus beiden Transporten zusammen st, body = post(base, {"jsonrpc": "2.0", "id": 23, "method": "prompts/list"}) j = json.loads(body) pn = sorted(p["name"] for p in j["result"]["prompts"]) if "local__hello" not in pn or "tasksd__summarize" not in pn: failures.append(f"prompts/list über beide Transporte: {pn}") st, body = post(base, {"jsonrpc": "2.0", "id": 24, "method": "resources/read", "params": {"uri": "local__localfile://note"}}) j = json.loads(body) if j.get("result", {}).get("contents", [{}])[0].get("text") != "stdio:note": failures.append(f"stdio resources/read: {body[:120]}") # 5. Meldung ohne id: 202, kein Inhalt st, body = post(base, {"jsonrpc": "2.0", "method": "notifications/initialized"}) if st != 202 or body: failures.append(f"Meldung ohne id: HTTP {st}, Körper {body[:60]!r}") # 6. Zugang: ohne Schlüssel nur lokal # Ein zweiter junction mit "mcp_auth all" verlangt den Schlüssel auch vom # Rechner selbst — anders wäre der Fall von außen nicht prüfbar. conf2 = os.path.join(tmp, "junction-auth.conf") with open(conf2, "w") as f: f.write(f"""listen 127.0.0.1:{PORT + 1} log_prefix jmcpauth mcp_cache_ttl 1 mcp tasksd url http://127.0.0.1:{ports['tasksd']}/mcp timeout 2 vkey "mcpclient" token_env VKEY_MCP allow "*" vkey "reader" token_env VKEY_READ allow "*" mcp_tools "tasksd__task_list" mcp_auth all endpoint dummy {{ base http://127.0.0.1:9/v1 kind remote context 8000 priority 10 }} """) env = dict(os.environ) env["VKEY_MCP"] = "mcp-test-key" env["VKEY_READ"] = "mcp-read-key" proc2 = subprocess.Popen([JUNCTION, "--config", conf2], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=env) try: if not wait_port(PORT + 1): failures.append("the auth instance did not listen") base2 = f"http://127.0.0.1:{PORT + 1}/mcp" st, body = post(base2, {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) if st == 401 and "mcp_key_required" in body: pass else: failures.append(f"ohne Schlüssel: HTTP {st}, {body[:80]!r}") st, body = post(base2, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, headers={"Authorization": "Bearer falsch"}) if st != 401: failures.append(f"falscher Schlüssel kam durch: HTTP {st}") st, body = post(base2, {"jsonrpc": "2.0", "id": 3, "method": "tools/list"}, headers={"Authorization": "Bearer mcp-test-key"}) try: names = [t["name"] for t in json.loads(body)["result"]["tools"]] except Exception: names = [] if st == 200 and any(n.startswith("tasksd__") for n in names): pass else: failures.append(f"mit Schlüssel: HTTP {st}, {body[:80]!r}") # Werkzeugbeschränkung: der Schlüssel darf nur, was in mcp_tools steht. st, body = post(base2, {"jsonrpc": "2.0", "id": 4, "method": "tools/list"}, headers={"Authorization": "Bearer mcp-test-key"}) alle = [t["name"] for t in json.loads(body)["result"]["tools"]] st, body = post(base2, {"jsonrpc": "2.0", "id": 5, "method": "tools/list"}, headers={"Authorization": "Bearer mcp-read-key"}) gefiltert = [t["name"] for t in json.loads(body)["result"]["tools"]] if gefiltert != ["tasksd__task_list"]: failures.append(f"Filterliste falsch: {gefiltert}") if len(alle) <= len(gefiltert): failures.append(f"Filter kürzte nicht: alle={alle} gefiltert={gefiltert}") # Der Aufruf muss genauso geprüft werden wie die Liste. st, body = post(base2, {"jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": {"name": "tasksd__task_create", "arguments": {"title": "x"}}}, headers={"Authorization": "Bearer mcp-read-key"}) if "-32601" not in body and "not permitted" not in body: failures.append(f"gesperrtes Werkzeug kam durch: {body[:100]!r}") st, body = post(base2, {"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "tasksd__task_list", "arguments": {}}}, headers={"Authorization": "Bearer mcp-read-key"}) if "not permitted" in body: failures.append(f"erlaubtes Werkzeug wurde gesperrt: {body[:100]!r}") finally: proc2.terminate() try: proc2.wait(timeout=5) except subprocess.TimeoutExpired: proc2.kill() # 7. toter Server darf die Liste nicht kaputt machen servers["tasksd"].shutdown() time.sleep(1.5) # Zwischenspeicher (ttl 1) ablaufen lassen st, body = post(base, {"jsonrpc": "2.0", "id": 6, "method": "tools/list"}) j = json.loads(body) names = [t["name"] for t in j["result"]["tools"]] if "skilld__skill_list" not in names: failures.append(f"toter Server riss die Liste mit: {names}") finally: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() for s in servers.values(): try: s.shutdown() except Exception: pass if failures: print("FAIL") for f in failures: print(" -", f) print("--- junction stderr ---") print((proc.stderr.read() or b"").decode()[-1500:]) sys.exit(1) print(f"PASS: 24 Prüfungen — initialize (Werkzeuge, Prompts, Ressourcen), " f"{len(want)} Werkzeuge gebündelt, Aufruf beim richtigen Server, " f"Argumente unverändert, unbekanntes Werkzeug abgelehnt, " f"Zugang ohne Schlüssel abgewiesen (401), falscher Schlüssel abgewiesen, " f"mit Schlüssel erlaubt, Werkzeugfilter je Schlüssel (Liste gekürzt), " f"gesperrtes Werkzeug abgewiesen (-32601), erlaubtes Werkzeug durchgelassen, " f"Prompts gebündelt und beim Abruf entpräfixt, " f"Ressourcen-URI beim Lesen entpräfixt, unbekanntes Präfix abgelehnt, " f"stdio-Server startet und antwortet, kaputtes stdio-Kommando reißt die " f"Liste nicht mit, beide Transporte in einer Liste, " f"toter Server übersprungen") if __name__ == "__main__": main()