#!/usr/bin/env python3 """MCP Server Integration Tests. Uses a 'test' OAuth client (maps to dedicated mcptest backends). Creates, reads, updates, and deletes test data in dedicated test collections: - Radicale: calendar-test, contacts-test - oCIS: /mcp-tests/ - Mail: read-only (no test mailbox) Run: /opt/mcp-servers/venv/bin/python -m pytest /opt/mcp-servers/tests/test_all.py -v """ import json import hashlib import base64 import re import secrets import time import httpx import pytest SERVERS = { "mail": 5100, "calendar": 5101, "contacts": 5102, "files": 5103, "notes": 5104, } with open("/opt/mcp-servers/tokens.json") as f: TEST_SECRET = json.load(f)["test"]["token"] _tokens = {} def get_token(port): if port not in _tokens: r = httpx.post(f"http://127.0.0.1:{port}/token", data={ "grant_type": "client_credentials", "client_id": "test", "client_secret": TEST_SECRET, }, timeout=10) assert r.status_code == 200, f"Token failed: {r.text}" _tokens[port] = r.json()["access_token"] return _tokens[port] def get_token_pkce(port): verifier = secrets.token_urlsafe(32) challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() r = httpx.get(f"http://127.0.0.1:{port}/authorize", params={ "response_type": "code", "client_id": "test", "redirect_uri": "https://claude.ai/api/mcp/auth_callback", "code_challenge": challenge, "code_challenge_method": "S256", }, follow_redirects=False, timeout=10) assert r.status_code == 302 code = r.headers["location"].split("code=")[1].split("&")[0] r2 = httpx.post(f"http://127.0.0.1:{port}/token", data={ "grant_type": "authorization_code", "code": code, "client_id": "test", "client_secret": TEST_SECRET, "code_verifier": verifier, }, timeout=10) assert r2.status_code == 200 return r2.json()["access_token"] def mcp_call(port, token, method, params=None, timeout=60): r = httpx.post(f"http://127.0.0.1:{port}/mcp", json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}}, headers={"Authorization": f"Bearer {token}", "Accept": "application/json, text/event-stream"}, timeout=timeout) assert r.status_code == 200, f"MCP {r.status_code}: {r.text[:200]}" for line in r.text.split("\n"): if line.startswith("data: "): return json.loads(line[6:]) return None def tool_call(port, token, tool_name, arguments=None, timeout=60): result = mcp_call(port, token, "tools/call", {"name": tool_name, "arguments": arguments or {}}, timeout=timeout) assert result and "error" not in result, f"Error: {result}" content = result["result"]["content"] assert len(content) > 0 return content[0].get("text", "") # ============================================================ # OAuth Tests (all servers) # ============================================================ class TestOAuth: @pytest.mark.parametrize("svc,port", SERVERS.items()) def test_metadata(self, svc, port): r = httpx.get(f"http://127.0.0.1:{port}/.well-known/oauth-authorization-server", timeout=10) assert r.status_code == 200 d = r.json() assert "authorization_endpoint" in d assert "token_endpoint" in d @pytest.mark.parametrize("svc,port", SERVERS.items()) def test_client_credentials(self, svc, port): assert len(get_token(port)) > 20 @pytest.mark.parametrize("svc,port", SERVERS.items()) def test_pkce_flow(self, svc, port): assert len(get_token_pkce(port)) > 20 @pytest.mark.parametrize("svc,port", SERVERS.items()) def test_invalid_secret_rejected(self, svc, port): r = httpx.post(f"http://127.0.0.1:{port}/token", data={ "grant_type": "client_credentials", "client_id": "test", "client_secret": "WRONG", }, timeout=10) assert r.status_code == 401 @pytest.mark.parametrize("svc,port", SERVERS.items()) def test_no_auth_rejected(self, svc, port): r = httpx.post(f"http://127.0.0.1:{port}/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}, headers={"Accept": "application/json, text/event-stream"}, timeout=10) assert r.status_code == 401 @pytest.mark.parametrize("svc,port", SERVERS.items()) def test_tools_list(self, svc, port): result = mcp_call(port, get_token(port), "tools/list") tools = result["result"]["tools"] assert len(tools) > 0 for t in tools: assert "name" in t assert "description" in t # ============================================================ # Mail Tests (read-only) # ============================================================ class TestMail: PORT = SERVERS["mail"] def test_list_accounts(self): text = tool_call(self.PORT, get_token(self.PORT), "list_accounts") assert "mcp-test-mail" in text def test_list_folders(self): text = tool_call(self.PORT, get_token(self.PORT), "list_folders", {"account": "mcp-test-mail"}) assert "INBOX" in text def test_search_finds_something(self): text = tool_call(self.PORT, get_token(self.PORT), "search_mail", {"query": "stefan", "limit": 2}) assert "Subject:" in text def test_search_empty_result(self): text = tool_call(self.PORT, get_token(self.PORT), "search_mail", {"query": "xyzzy_nonexistent_99", "limit": 1, "account": "mcp-test-empty"}) assert "No results" in text def test_search_finds_old_mail(self): # Uralte Mail (2009) muss gefunden werden -> vollstaendiger Scan, kein Crash davor text = tool_call(self.PORT, get_token(self.PORT), "search_mail", {"query": "URALTMAIL2009", "limit": 5, "account": "mcp-test-mail"}) assert "No results" not in text assert "2009" in text def test_search_survives_bad_charset(self): # Mail mit charset x-unknown darf die Suche NICHT killen und muss findbar sein text = tool_call(self.PORT, get_token(self.PORT), "search_mail", {"query": "XUNKNOWNTOKEN", "limit": 5, "account": "mcp-test-mail"}) assert "No results" not in text assert "Subject:" in text def test_search_survives_bad_header(self): # Kaputter encoded-word-Header darf decode_hdr nicht crashen text = tool_call(self.PORT, get_token(self.PORT), "search_mail", {"query": "BADHEADERTOKEN", "limit": 5, "account": "mcp-test-mail"}) assert "No results" not in text def test_search_broad_no_crash(self): # Breite Suche scannt ueber die Edge-Mails hinweg ohne Fehler text = tool_call(self.PORT, get_token(self.PORT), "search_mail", {"query": "mcptest", "limit": 50, "account": "mcp-test-mail"}) assert "Error" not in text assert text.count("Subject:") >= 2 def test_read_mail(self): # First search to get a key text = tool_call(self.PORT, get_token(self.PORT), "search_mail", {"query": "stefan", "limit": 1, "account": "mcp-test-mail"}) if "No results" in text: pytest.skip("No mails found") # Parse account, folder, key from result for line in text.split("\n"): if "Account:" in line: parts = line.strip().split(", ") account = parts[0].split(": ")[1] folder = parts[1].split(": ")[1] key = parts[2].split(": ")[1] break body = tool_call(self.PORT, get_token(self.PORT), "read_mail", {"account": account, "folder": folder, "key": key}) assert "From:" in body assert "Subject:" in body def test_attachment_listing_and_fetch(self): token = get_token(self.PORT) # Find a mail with an attachment by scanning Rechnung search results text = tool_call(self.PORT, token, "search_mail", {"query": "Rechnung", "limit": 10, "account": "mcp-test-mail"}) if "No results" in text: pytest.skip("No mails found") # Read each result, look for one with attachments found_att = None for block in text.split("\n\n"): acc = fld = k = None for line in block.split("\n"): if "Account:" in line: parts = line.strip().split(", ") acc = parts[0].split(": ")[1] fld = parts[1].split(": ")[1] k = parts[2].split(": ")[1] if not k: continue body = tool_call(self.PORT, token, "read_mail", {"account": acc, "folder": fld, "key": k}) if "Anhaenge" in body: found_att = (acc, fld, k) break if not found_att: pytest.skip("No mail with attachment found") acc, fld, k = found_att result = mcp_call(self.PORT, token, "tools/call", { "name": "read_attachment", "arguments": {"account": acc, "folder": fld, "key": k, "attachment_index": 1}, }) content = result["result"]["content"][0] assert content["type"] in ("image", "resource", "text") # ============================================================ # Calendar Tests (CRUD on calendar-test + calendar-test-second) # Baikal mcptest-Backend. Nur MCP-Methoden, kein direkter DAV-Zugriff. # Selbstreinigend: alle erzeugten Events/Tasks werden am Ende geloescht. # ============================================================ import re as _re def _extract_uids(text): """Alle UIDs (uuid-Format) aus einem MCP-Textauszug extrahieren.""" return _re.findall(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", text) class TestCalendar: PORT = SERVERS["calendar"] CAL1 = "calendar-test" CAL2 = "calendar-test-second" def test_list_calendars_both(self): """Beide Test-Kalender muessen sichtbar sein (klares Fehlerbild, wenn Backend fehlt).""" text = tool_call(self.PORT, get_token(self.PORT), "list_calendars") missing = [c for c in (self.CAL1, self.CAL2) if c not in text] assert not missing, ( f"mcptest-Backend unvollstaendig: Kalender {missing} nicht in list_calendars. " f"Pruefe Baikal (baikal.slohmaier.de, User mcptest) und config.json.") def test_list_task_lists_contains(self): """calendar-test ist auch Task-Liste (VEVENT+VTODO).""" text = tool_call(self.PORT, get_token(self.PORT), "list_task_lists") assert self.CAL1 in text or self.CAL2 in text, f"Keine Task-Liste sichtbar: {text[:200]}" def test_create_update_delete_event_full_fields(self): token = get_token(self.PORT) tag = f"McpFeldtest-{int(time.time())}" created = [] try: r = tool_call(self.PORT, token, "create_event", { "calendar": self.CAL1, "title": tag, "start": "2026-12-25T10:00", "end": "2026-12-25T11:00", "location": "Marienplatz 1, Muenchen", "description": "Export Test Beschreibung", "travel_minutes": 30, "travel_mode": "driving", "travel_advisory": True, "reminder_minutes": 15, }) assert "erstellt" in r.lower() or "created" in r.lower(), f"create_event failed: {r}" found = tool_call(self.PORT, token, "search_events", {"query": tag, "date_from": "2026-12-01", "date_to": "2026-12-31"}) assert tag in found, f"Event nach Create nicht auffindbar: {found[:300]}" uids = _extract_uids(found) assert uids, f"Keine UID im Create-Ergebnis: {found[:300]}" uid = uids[0] created.append((self.CAL1, uid)) tag2 = f"{tag}-GEANDERT" r = tool_call(self.PORT, token, "update_event", { "calendar": self.CAL1, "uid": uid, "title": tag2, "start": "2026-12-26T14:30", "end": "2026-12-26T15:30", "location": "Hauptbahnhof Muenchen", "description": "Neue Beschreibung nach Update", "travel_minutes": 45, "travel_mode": "transit", "travel_advisory": True, "reminder_minutes": 30, }) assert "aktualisiert" in r.lower() or "updated" in r.lower(), f"update_event failed: {r}" found2 = tool_call(self.PORT, token, "search_events", {"query": tag2, "date_from": "2026-12-01", "date_to": "2027-01-31"}) assert tag2 in found2, f"Event nach Update nicht auffindbar: {found2[:300]}" assert "Hauptbahnhof" in found2, f"Ort nach Update fehlt: {found2[:300]}" assert "Verkehrsmittel" in found2, f"travel_mode nach Update nicht angezeigt: {found2[:300]}" finally: for cal, uid in created: try: tool_call(self.PORT, token, "delete_event", {"calendar": cal, "uid": uid}) except Exception: pass def test_event_timezone_tzid(self): """Timed events muessen mit TZID (Europe/Berlin) gespeichert werden, nicht floating. Regression 2026-09-30: floating DTSTART wurde von Baikal als UTC gelesen (+2h).""" token = get_token(self.PORT) tag = f"McpTz-{int(time.time())}" created = [] try: r = tool_call(self.PORT, token, "create_event", { "calendar": self.CAL1, "title": tag, "start": "2026-12-25T17:30", "end": "2026-12-25T19:15", }) assert "erstellt" in r.lower() or "created" in r.lower(), f"create_event failed: {r}" found = tool_call(self.PORT, token, "search_events", {"query": tag, "date_from": "2026-12-01", "date_to": "2026-12-31"}) uids = _extract_uids(found) assert uids, f"Keine UID: {found[:300]}" created.append((self.CAL1, uids[0])) assert re.search(r"T17:30:00[+-]0[12]:00", found), ( f"Event ohne Berlin-Offset (floating?) gespeichert: {found[:300]}") finally: for cal, uid in created: try: tool_call(self.PORT, token, "delete_event", {"calendar": cal, "uid": uid}) except Exception: pass def test_create_event_second_calendar(self): """Event in zweitem Kalender anlegen (Wechsel/Mehrfach-Test).""" token = get_token(self.PORT) tag = f"McpZweiter-{int(time.time())}" created = [] try: r = tool_call(self.PORT, token, "create_event", { "calendar": self.CAL2, "title": tag, "start": "2027-01-15T09:00", "end": "2027-01-15T10:00", "location": "Marienplatz", "description": "Zweiter Kalender Test", }) assert "erstellt" in r.lower() or "created" in r.lower(), f"create_event(second) failed: {r}" found = tool_call(self.PORT, token, "search_events", {"query": tag, "date_from": "2027-01-01", "date_to": "2027-02-01"}) uids = _extract_uids(found) assert uids, f"Event in zweitem Kalender nicht auffindbar: {found[:300]}" created.append((self.CAL2, uids[0])) finally: for cal, uid in created: try: tool_call(self.PORT, token, "delete_event", {"calendar": cal, "uid": uid}) except Exception: pass def test_create_update_delete_task(self): """Aufgabe in calendar-test (VTODO) anlegen, aendern, loeschen.""" token = get_token(self.PORT) tag = f"McpAufgabe-{int(time.time())}" created = [] try: r = tool_call(self.PORT, token, "create_task", { "task_list": self.CAL1, "title": tag, "due": "2026-12-31", "priority": 5, "description": "Testbeschreibung", }) assert "erstellt" in r.lower() or "created" in r.lower(), f"create_task failed: {r}" tasks = tool_call(self.PORT, token, "get_tasks", {"task_list": self.CAL1, "include_completed": True}) assert tag in tasks, f"Task nach Create nicht auffindbar: {tasks[:300]}" uids = _extract_uids(tasks) assert uids, f"Keine UID bei Task: {tasks[:300]}" uid = uids[0] created.append(uid) tag2 = f"{tag}-GEANDERT" r = tool_call(self.PORT, token, "update_task", { "task_list": self.CAL1, "uid": uid, "title": tag2, "due": "2026-12-30", "priority": 8, "description": "Update Notiz", }) assert "aktualisiert" in r.lower() or "updated" in r.lower(), f"update_task failed: {r}" tasks2 = tool_call(self.PORT, token, "get_tasks", {"task_list": self.CAL1, "include_completed": True}) assert tag2 in tasks2, f"Task nach Update nicht auffindbar: {tasks2[:300]}" assert "Update Notiz" in tasks2, f"Task-Beschreibung nach Update fehlt: {tasks2[:300]}" finally: for uid in created: try: tool_call(self.PORT, token, "delete_task", {"task_list": self.CAL1, "uid": uid}) except Exception: pass class TestContacts: PORT = SERVERS["contacts"] def test_search_contacts_read(self): """Read-only Smoke auf das Adressbuch (leer ok).""" text = tool_call(self.PORT, get_token(self.PORT), "search_contacts", {"query": "Mustermann", "limit": 3}) assert isinstance(text, str), f"search_contacts Kaputt: {text}" def test_create_update_delete_contact(self): token = get_token(self.PORT) tag = f"McpKontakt-{int(time.time())}" created = [] try: r = tool_call(self.PORT, token, "create_contact", { "name": f"{tag} Mustermann", "email": "max@example.com", "phone": "+49 170 0000000", "organization": "MCP Tests GmbH", "note": "Automatisch erstellt", }) assert "erstellt" in r.lower() or "created" in r.lower(), f"create_contact failed: {r}" found = tool_call(self.PORT, token, "search_contacts", {"query": tag, "limit": 5}) assert tag in found, f"Kontakt nach Create nicht auffindbar: {found[:300]}" uids = _extract_uids(found) assert uids, f"Keine UID bei Kontakt: {found[:300]}" uid = uids[0] created.append(uid) tag2 = f"{tag}-GEANDERT" r = tool_call(self.PORT, token, "update_contact", { "uid": uid, "name": f"{tag2} Mustermann", "email": "neu@example.org", "phone": "+49 171 999999", "organization": "Andere Firma", "note": "Update-Notiz", }) assert "aktualisiert" in r.lower() or "updated" in r.lower(), f"update_contact failed: {r}" found2 = tool_call(self.PORT, token, "search_contacts", {"query": tag2, "limit": 5}) assert tag2 in found2, f"Kontakt nach Update nicht auffindbar: {found2[:300]}" assert "Andere Firma" in found2, f"Organisation nach Update fehlt: {found2[:300]}" finally: for uid in created: try: tool_call(self.PORT, token, "delete_contact", {"uid": uid}) except Exception: pass class TestFiles: PORT = SERVERS["files"] TEST_DIR = "/.mcp-tests" @pytest.fixture(autouse=True, scope="class") def ensure_test_dir(self): """Create test dir at start, delete at end. Isolated from real data.""" token = get_token(self.PORT) tool_call(self.PORT, token, "create_folder", {"path": self.TEST_DIR}) yield tool_call(self.PORT, token, "delete_file", {"path": self.TEST_DIR}) def test_list_root(self): text = tool_call(self.PORT, get_token(self.PORT), "list_files", {"path": "/"}) assert "DIR" in text def test_file_info_root(self): text = tool_call(self.PORT, get_token(self.PORT), "file_info", {"path": "/"}) assert "Verzeichnis" in text or "Directory" in text def test_write_read_delete_file(self): token = get_token(self.PORT) tag = f"test-{int(time.time())}" path = f"{self.TEST_DIR}/{tag}.txt" result = tool_call(self.PORT, token, "write_file", { "path": path, "content": f"Hello MCP Test {tag}\nZeile 2", }) assert "geschrieben" in result.lower() or "written" in result.lower(), f"Write failed: {result}" read_result = mcp_call(self.PORT, token, "tools/call", {"name": "read_file", "arguments": {"path": path}}) text = read_result["result"]["content"][0]["text"] assert tag in text info = tool_call(self.PORT, token, "file_info", {"path": path}) assert "bytes" in info.lower() del_result = tool_call(self.PORT, token, "delete_file", {"path": path}) assert "eloescht" in del_result.lower() or "deleted" in del_result.lower() info2 = tool_call(self.PORT, token, "file_info", {"path": path}) assert "404" in info2 or "Nicht gefunden" in info2 or "Not found" in info2 def test_create_delete_folder(self): token = get_token(self.PORT) tag = f"testdir-{int(time.time())}" path = f"{self.TEST_DIR}/{tag}" result = tool_call(self.PORT, token, "create_folder", {"path": path}) assert "erstellt" in result.lower() or "created" in result.lower() listing = tool_call(self.PORT, token, "list_files", {"path": self.TEST_DIR}) assert tag in listing tool_call(self.PORT, token, "delete_file", {"path": path}) def test_move_file(self): token = get_token(self.PORT) tag = f"move-{int(time.time())}" src = f"{self.TEST_DIR}/{tag}-src.txt" dst = f"{self.TEST_DIR}/{tag}-dst.txt" tool_call(self.PORT, token, "write_file", {"path": src, "content": "move test"}) result = tool_call(self.PORT, token, "move_file", {"source": src, "destination": dst}) assert "erschoben" in result.lower() or "moved" in result.lower() read = mcp_call(self.PORT, token, "tools/call", {"name": "read_file", "arguments": {"path": dst}}) assert "move test" in read["result"]["content"][0]["text"] tool_call(self.PORT, token, "delete_file", {"path": dst}) def test_search_files(self): token = get_token(self.PORT) tag = f"search-{int(time.time())}" path = f"{self.TEST_DIR}/{tag}.md" tool_call(self.PORT, token, "write_file", {"path": path, "content": "searchable"}) result = tool_call(self.PORT, token, "search_files", {"query": tag, "path": self.TEST_DIR}) assert tag in result tool_call(self.PORT, token, "delete_file", {"path": path}) # ============================================================ # Notes Tests (Joplin Data API) # ============================================================ class TestNotes: PORT = SERVERS["notes"] TEST_NOTEBOOK = "Inbox" def test_list_notebooks(self): text = tool_call(self.PORT, get_token(self.PORT), "list_notebooks") assert "id:" in text and "Keine" not in text def test_list_notes(self): text = tool_call(self.PORT, get_token(self.PORT), "list_notes", {"limit": 5}) assert "id:" in text or "Keine Notizen" in text def test_create_search_read_note(self): token = get_token(self.PORT) tag = f"mcptest-{int(time.time())}" # Create result = tool_call(self.PORT, token, "create_note", { "notebook": self.TEST_NOTEBOOK, "title": f"Test Note {tag}", "body": f"Automatischer Test {tag}\n\nInhalt.", }) assert "erstellt" in result.lower(), f"Create failed: {result}" note_id = result.split("id: ")[1].rstrip(")").strip() # Read back (search FTS index may lag, so verify via read) body = tool_call(self.PORT, token, "read_note", {"note_id": note_id}) assert tag in body, f"Note content mismatch: {body[:200]}" # Verify it appears in the notebook listing listing = tool_call(self.PORT, token, "list_notes", {"notebook": self.TEST_NOTEBOOK}) assert note_id in listing or f"Test Note {tag}" in listing def test_update_delete_note(self): """Voller CRUD-Zyklus: create -> update (title+body) -> read verify -> delete permanent.""" token = get_token(self.PORT) tag = f"mcptest-upd-{int(time.time())}" result = tool_call(self.PORT, token, "create_note", { "notebook": self.TEST_NOTEBOOK, "title": f"Upd Note {tag}", "body": "vorher", }) assert "erstellt" in result.lower(), f"Create failed: {result}" note_id = result.split("id: ")[1].rstrip(")").strip() # Update title + body result = tool_call(self.PORT, token, "update_note", { "note_id": note_id, "title": f"Upd Note {tag} NEU", "body": f"NACHHER {tag}", }) assert "aktualisiert" in result.lower(), f"Update failed: {result}" body = tool_call(self.PORT, token, "read_note", {"note_id": note_id}) assert f"NACHHER {tag}" in body and "NEU" in body, f"Update not applied: {body[:200]}" # Leerer Update-Aufruf gibt klare Meldung statt Fehler result = tool_call(self.PORT, token, "update_note", {"note_id": note_id}) assert "Nichts zu aendern" in result # Permanent loeschen (Testdaten nicht liegen lassen) result = tool_call(self.PORT, token, "delete_note", {"note_id": note_id, "permanent": True}) assert "ENDGUELTIG" in result, f"Delete failed: {result}" def test_attachment_crud(self): """Anhang-Zyklus: add -> list -> read -> update (Inhalt+Props) -> delete (inkl. Link-Cleanup).""" token = get_token(self.PORT) tag = f"mcptest-att-{int(time.time())}" result = tool_call(self.PORT, token, "create_note", { "notebook": self.TEST_NOTEBOOK, "title": f"Att {tag}", "body": "anfang", }) assert "erstellt" in result.lower(), f"Create failed: {result}" note_id = result.split("id: ")[1].rstrip(")").strip() content = base64.b64encode(f"Hallo {tag}\n".encode()).decode() res = tool_call(self.PORT, token, "add_attachment", { "note_id": note_id, "filename": f"{tag}.txt", "content_base64": content, }) assert "hinzugefuegt" in res.lower(), f"Add failed: {res}" rid = res.split("resource id: ")[1].split(",")[0].strip() listing = tool_call(self.PORT, token, "list_note_resources", {"note_id": note_id}) assert rid in listing and f"{tag}.txt" in listing, f"Listing mismatch: {listing}" body = tool_call(self.PORT, token, "read_note", {"note_id": note_id}) assert f":/{rid}" in body, f"Link missing in body: {body}" text = tool_call(self.PORT, token, "read_resource", {"resource_id": rid}) assert tag in text, f"Content mismatch: {text}" new_content = base64.b64encode(f"Neu {tag}\n".encode()).decode() upd = tool_call(self.PORT, token, "update_attachment", { "resource_id": rid, "content_base64": new_content, "title": f"{tag}-neu.txt", }) assert "ersetzt" in upd.lower(), f"Content update failed: {upd}" text = tool_call(self.PORT, token, "read_resource", {"resource_id": rid}) assert f"Neu {tag}" in text, f"Content update not applied: {text}" upd2 = tool_call(self.PORT, token, "update_attachment", {"resource_id": rid, "mime": "text/plain"}) assert "aktualisiert" in upd2.lower(), f"Props update failed: {upd2}" dele = tool_call(self.PORT, token, "delete_attachment", {"resource_id": rid, "note_id": note_id}) assert "geloescht" in dele.lower(), f"Delete failed: {dele}" assert f":/{rid}" not in tool_call(self.PORT, token, "read_note", {"note_id": note_id}) tool_call(self.PORT, token, "delete_note", {"note_id": note_id, "permanent": True}) # ============================================================ # File Type Tests (read_file auf vorbereiteten /testdata-Dateien) # ============================================================ class TestFileTypes: """Liest die mcptest-Testdaten verschiedener Typen und prueft den Content-Typ.""" PORT = SERVERS["files"] CASES = [ ("testdata/images/photo.jpg", {"image"}), ("testdata/images/screenshot.png", {"image"}), ("testdata/images/logo.svg", {"image"}), ("testdata/text/notes.txt", {"text"}), ("testdata/text/readme.md", {"text"}), ("testdata/text/data.csv", {"text"}), ("testdata/documents/document.pdf", {"text"}), # Text-PDF -> extrahiert ("testdata/documents/scanned.pdf", {"image"}), # Scan-PDF -> als Bild gerendert ("testdata/documents/report.docx", {"text"}), ("testdata/documents/budget.xlsx", {"text"}), ("testdata/documents/slides.pptx", {"text"}), ("testdata/audio/tone.mp3", {"resource"}), ("testdata/video/clip.mp4", {"resource"}), ("testdata/archives/archive.zip", {"resource"}), ] @pytest.mark.parametrize("path,expected", CASES) def test_read_file_type(self, path, expected): token = get_token(self.PORT) result = mcp_call(self.PORT, token, "tools/call", {"name": "read_file", "arguments": {"path": path}}) types = {c["type"] for c in result["result"]["content"]} assert types & expected, f"{path}: erwartet eins von {expected}, bekam {types}" # ============================================================ # File Edge Cases (leere/grosse/verschluesselte/Sonderzeichen-Dateien) # ============================================================ class TestFileEdgeCases: PORT = SERVERS["files"] def _read(self, path): token = get_token(self.PORT) r = mcp_call(self.PORT, token, "tools/call", {"name": "read_file", "arguments": {"path": path}}) return r["result"]["content"] def test_empty_text_file(self): c = self._read("testdata/edge/empty.txt") assert c and c[0]["type"] == "text" def test_zero_byte_binary(self): c = self._read("testdata/edge/leer.bin") assert c # kein Crash def test_umlaut_space_paren_filename(self): c = self._read("testdata/edge/Ärger Übersicht (Größe).txt") assert c[0]["type"] == "text" and "Umlauten" in c[0]["text"] def test_unicode_emoji_rtl_content(self): c = self._read("testdata/edge/unicode.txt") assert "😀" in c[0]["text"] and "مرحبا" in c[0]["text"] def test_no_extension(self): c = self._read("testdata/edge/README_NOEXT") assert c and c[0]["type"] in ("text", "resource") def test_encrypted_pdf_graceful(self): c = self._read("testdata/edge/geschuetzt.pdf") assert c and c[0]["type"] in ("text", "resource") # kein Crash def test_password_protected_zip(self): c = self._read("testdata/edge/geheim.zip") assert any(x["type"] == "resource" for x in c) def test_oversized_file_rejected(self): c = self._read("testdata/edge/riesig.dat") assert c[0]["type"] == "text" and "zu gross" in c[0]["text"]