fix(calendar): TZID Europe/Berlin for timed events/tasks, resolve real resource href on delete/update, fix _report_tasks XML; sync deployed servers (owamail, openwearables, ghostfolio), docs and tests

This commit is contained in:
Stefan Lohmaier committed 2026-10-01 04:29:57 +02:00
1 parent 7c01e7be53
commit 75185ef2ba
41 files changed
+8834 -324

No files matched your search

+148 -18
View File
@@ -1,6 +1,7 @@
"""MCP Contacts Server — reads and writes contacts via CardDAV."""
import os, sys, re, contextlib, uuid, base64
import html
from typing import Annotated
import httpx, vobject
@@ -9,30 +10,41 @@ from pydantic import Field
from mcp.server.fastmcp import FastMCP
from mcp.types import TextContent, ImageContent
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.routing import Mount, Route
from starlette.responses import Response
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
from common import load_config as _lc
_cfg = _lc()
RADICALE = _cfg['radicale_url']
CREDS = {u: (d['username'], d['password']) for u, d in _cfg['radicale_users'].items()}
AB_PATHS = _cfg['addressbook_paths']
BAIKAL_URL = _cfg['baikal_url'] # https://baikal.slohmaier.de (Produktiv)
BAIKAL_CREDS = {u: (d['username'], d['password']) for u, d in _cfg['baikal_users'].items()}
AB_PATHS = _cfg['addressbook_paths'] # Baikal-Basen (aktiv)
mcp = FastMCP("Contacts", stateless_http=True,
transport_security={"enable_dns_rebinding_protection": False})
def _auth(u): c = CREDS.get(u); return httpx.BasicAuth(c[0], c[1]) if c else None
def _auth(u):
c = BAIKAL_CREDS.get(u)
return httpx.BasicAuth(c[0], c[1]) if c else None
def _serve(user):
"""Backend: Baikal fuer alle MCP-User (stefan/kati). Radicale ist entfernt (2026-09-11)."""
if user not in BAIKAL_CREDS:
raise ValueError(f'kein Baikal-Konto fuer User {user}')
return BAIKAL_URL, AB_PATHS.get(user, [])
def _discover_ab(user):
books = []
for base in AB_PATHS.get(user, []):
url, bases = _serve(user)
for base in bases:
body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:displayname/></d:prop></d:propfind>'
r = httpx.request("PROPFIND", RADICALE + base, content=body, auth=_auth(user), headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=30)
r = httpx.request("PROPFIND", url + base, content=body, auth=_auth(user), headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=30)
for m in re.finditer(r'<(?:d:)?href>([^<]+)</(?:d:)?href>', r.text):
href = m.group(1)
if href.rstrip("/") == base.rstrip("/"): continue
if "/inbox/" in href or "/outbox/" in href: continue
block = r.text[m.start():r.text.find("</response>", m.end())]
if "addressbook" not in block.lower(): continue
nm = re.search(r'<(?:d:)?displayname>([^<]*)</(?:d:)?displayname>', block)
@@ -42,13 +54,14 @@ def _discover_ab(user):
PARSE_DEADLINE_S = 12 # Wall-Clock-Limit fuer client-seitiges vobject-Parsen
def _get_contacts(href, auth, t0=None):
def _get_contacts(user, href, t0=None):
url, _ = _serve(user)
body = '<?xml version="1.0"?><c:addressbook-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav"><d:prop><d:getetag/><c:address-data/></d:prop></c:addressbook-query>'
r = httpx.request("REPORT", RADICALE + href, content=body, auth=auth, headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=60)
r = httpx.request("REPORT", url + href, content=body, auth=_auth(user), headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=60)
contacts = []
for m in re.finditer(r'<(?:c|CR):address-data[^>]*>(.*?)</(?:c|CR):address-data>', r.text, re.DOTALL):
for m in re.finditer(r'<(?:[a-zA-Z][a-zA-Z0-9_]*):address-data[^>]*>(.*?)</(?:[a-zA-Z][a-zA-Z0-9_]*):address-data>', r.text, re.DOTALL):
if t0 is not None and (time.monotonic() - t0) > PARSE_DEADLINE_S: break
raw = m.group(1).replace("&lt;","<").replace("&gt;",">").replace("&amp;","&")
raw = html.unescape(m.group(1))
try: contacts.append(vobject.readOne(raw))
except: pass
return contacts
@@ -107,7 +120,7 @@ def search_contacts(
results = []
truncated = False
for book in _discover_ab(user):
for c in _get_contacts(book["href"], _auth(user), t0=t0):
for c in _get_contacts(user, book["href"], t0=t0):
txt = " ".join(str(getattr(c, a, None) or '') for a in ['fn','email','tel','org','note','nickname']).lower()
if q in txt:
results.append(_brief(c))
@@ -145,7 +158,7 @@ def get_contact(
user = get_current_user()
if not user: return [TextContent(type="text", text="Error: not authenticated")]
for book in _discover_ab(user):
for c in _get_contacts(book["href"], _auth(user)):
for c in _get_contacts(user, book["href"]):
if hasattr(c, 'uid') and str(c.uid.value) == uid:
result = [TextContent(type="text", text=_full(c))]
b64, mime = _get_photo_data(c)
@@ -178,10 +191,70 @@ def create_contact(
if phone: card.add("tel").value = phone
if organization: card.add("org").value = [organization]
if note: card.add("note").value = note
r = httpx.put(RADICALE + books[0]["href"] + uid_val + ".vcf", content=card.serialize(), auth=_auth(user), headers={"Content-Type": "text/vcard"}, timeout=15)
r = httpx.put(_serve(user)[0] + books[0]["href"] + uid_val + ".vcf", content=card.serialize(), auth=_auth(user), headers={"Content-Type": "text/vcard"}, timeout=15)
return f"Kontakt erstellt: {name}" if r.status_code in (201, 204) else f"Fehler: HTTP {r.status_code}"
def _build_card_fields(card, name, email, phone, organization, note):
"""Setzt vCard-Felder auf ein vobject-Element (wiederverwendet von create/update)."""
card.add("fn").value = name
p = name.split(" ", 1)
card.add("n").value = vobject.vcard.Name(family=p[-1] if len(p)>1 else p[0],
given=p[0] if len(p)>1 else "")
if email: card.add("email").value = email
if phone: card.add("tel").value = phone
if organization: card.add("org").value = [organization]
if note: card.add("note").value = note
def _find_book_href(user, uid):
"""Findet (books[0], book['href']) fuer eine UID in einem der Adressbuecher."""
for book in _discover_ab(user):
for c in _get_contacts(user, book["href"]):
if hasattr(c, 'uid') and str(c.uid.value) == uid:
return book["href"]
return None
@mcp.tool()
def update_contact(
uid: Annotated[str, Field(description="Contact UID from search_contacts or get_contact results")],
name: Annotated[str, Field(description="Full name, e.g. 'Max Mustermann'")],
email: Annotated[str, Field(description="Email address")] = "",
phone: Annotated[str, Field(description="Phone number, e.g. '+49 171 1234567'")] = "",
organization: Annotated[str, Field(description="Company/organization name")] = "",
note: Annotated[str, Field(description="Notes about this contact")] = "",
) -> str:
"""Update an existing contact (full overwrite of name/email/phone/organization/note) by UID."""
user = get_current_user()
if not user: return "Error: not authenticated"
href = _find_book_href(user, uid)
if not href: return f"Kontakt nicht gefunden: {uid}"
card = vobject.vCard()
card.add("uid").value = uid
_build_card_fields(card, name, email, phone, organization, note)
r = httpx.put(_serve(user)[0] + href + uid + ".vcf", content=card.serialize(),
auth=_auth(user), headers={"Content-Type": "text/vcard"}, timeout=15)
if r.status_code in (200, 201, 204):
return f"Kontakt aktualisiert: {name}"
return f"Fehler: HTTP {r.status_code}"
@mcp.tool()
def delete_contact(
uid: Annotated[str, Field(description="Contact UID from search_contacts or get_contact results")],
) -> str:
"""Delete an existing contact by its UID."""
user = get_current_user()
if not user: return "Error: not authenticated"
href = _find_book_href(user, uid)
if not href: return f"Kontakt nicht gefunden: {uid}"
r = httpx.request("DELETE", _serve(user)[0] + href + uid + ".vcf", auth=_auth(user), timeout=15)
if r.status_code in (200, 204, 404):
return f"Kontakt geloescht (UID {uid})"
return f"Fehler: HTTP {r.status_code}"
@mcp.tool()
def set_contact_photo(
uid: Annotated[str, Field(description="Contact UID from search_contacts or get_contact results")],
@@ -193,7 +266,7 @@ def set_contact_photo(
if not user: return "Error: not authenticated"
auth = _auth(user)
for book in _discover_ab(user):
for c in _get_contacts(book["href"], auth):
for c in _get_contacts(user, book["href"]):
if hasattr(c, 'uid') and str(c.uid.value) == uid:
if hasattr(c, 'photo'):
c.remove(c.photo)
@@ -202,13 +275,68 @@ def set_contact_photo(
photo.params["ENCODING"] = ["b"]
photo.params["TYPE"] = [image_type.upper()]
href = book["href"] + uid + ".vcf"
r = httpx.put(RADICALE + href, content=c.serialize(), auth=auth, headers={"Content-Type": "text/vcard"}, timeout=15)
r = httpx.put(_serve(user)[0] + href, content=c.serialize(), auth=auth, headers={"Content-Type": "text/vcard"}, timeout=15)
if r.status_code in (200, 201, 204):
return f"Foto gesetzt fuer {c.fn.value if hasattr(c, 'fn') else uid}"
return f"Fehler: HTTP {r.status_code}"
return f"Kontakt nicht gefunden: {uid}"
async def raw_contact_photo(request):
"""Rohes Kontaktfoto (beliebige Bildformate).
GET /raw?uid=<uid> -> Foto als Rohbytes
PUT /raw?uid=<uid>[&type=jpeg|png] -> Foto aus Rohbytes setzen/ersetzen
Token-geschuetzt ueber BearerAuthMiddleware.
"""
user = get_current_user()
if not user:
return Response("unauthorized", status_code=401)
uid = request.query_params.get("uid", "")
if not uid:
return Response("missing uid", status_code=400)
if request.method == "GET":
for book in _discover_ab(user):
for c in _get_contacts(user, book["href"]):
if hasattr(c, 'uid') and str(c.uid.value) == uid:
b64, mime = _get_photo_data(c)
if not b64:
return Response("kein Foto", status_code=404)
return Response(base64.b64decode(b64), media_type=mime,
headers={"Content-Disposition": 'attachment; filename="contact.jpg"'})
return Response(f"Kontakt nicht gefunden: {uid}", status_code=404)
# PUT
content = await request.body()
if not content:
return Response("leerer Body", status_code=400)
ctype = (request.query_params.get("type") or request.headers.get("content-type", "") or "").lower()
if "png" in ctype:
image_type = "PNG"
elif "gif" in ctype:
image_type = "GIF"
else:
image_type = "JPEG"
auth = _auth(user)
for book in _discover_ab(user):
for c in _get_contacts(user, book["href"]):
if hasattr(c, 'uid') and str(c.uid.value) == uid:
if hasattr(c, 'photo'):
c.remove(c.photo)
photo = c.add("photo")
photo.value = content
photo.params["ENCODING"] = ["b"]
photo.params["TYPE"] = [image_type]
href = book["href"] + uid + ".vcf"
r = httpx.put(_serve(user)[0] + href, content=c.serialize(), auth=auth,
headers={"Content-Type": "text/vcard"}, timeout=15)
if r.status_code in (200, 201, 204):
return Response(f"ok Foto gesetzt fuer {uid} ({len(content):,} bytes)", status_code=200)
return Response(f"Fehler: HTTP {r.status_code}", status_code=r.status_code)
return Response(f"Kontakt nicht gefunden: {uid}", status_code=404)
def create_app():
from contextlib import asynccontextmanager
mcp_app = mcp.streamable_http_app()
@@ -217,11 +345,13 @@ def create_app():
async with contextlib.AsyncExitStack() as stack:
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
yield
routes = list(OAUTH_ROUTES) + [Mount("/", app=mcp_app)]
routes = list(OAUTH_ROUTES) + [
Route("/raw", raw_contact_photo, methods=["GET", "PUT"]),
] + [Mount("/", app=mcp_app)]
app = Starlette(routes=routes, lifespan=lifespan)
app.add_middleware(BearerAuthMiddleware)
return app
if __name__ == "__main__":
import uvicorn
uvicorn.run(create_app(), host="127.0.0.1", port=5102)
uvicorn.run(create_app(), host="0.0.0.0", port=5102)