357 lines
16 KiB
Python
357 lines
16 KiB
Python
"""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
|
|
import time
|
|
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, 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()
|
|
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 = 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 = []
|
|
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", 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)
|
|
books.append({"name": nm.group(1) if nm else href.split("/")[-2], "href": href})
|
|
return books
|
|
|
|
PARSE_DEADLINE_S = 12 # Wall-Clock-Limit fuer client-seitiges vobject-Parsen
|
|
|
|
|
|
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", url + href, content=body, auth=_auth(user), headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=60)
|
|
contacts = []
|
|
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 = html.unescape(m.group(1))
|
|
try: contacts.append(vobject.readOne(raw))
|
|
except: pass
|
|
return contacts
|
|
|
|
def _brief(c):
|
|
fn = str(c.fn.value) if hasattr(c, 'fn') else '?'
|
|
org = f" ({c.org.value[0]})" if hasattr(c, 'org') and c.org.value else ''
|
|
uid = str(c.uid.value) if hasattr(c, 'uid') else ''
|
|
parts = [f"{fn}{org}"]
|
|
for em in (c.email_list if hasattr(c, 'email_list') else ([c.email] if hasattr(c, 'email') else [])):
|
|
parts.append(f" Email: {em.value}")
|
|
for tel in (c.tel_list if hasattr(c, 'tel_list') else ([c.tel] if hasattr(c, 'tel') else [])):
|
|
parts.append(f" Tel: {tel.value}")
|
|
parts.append(f" UID: {uid}")
|
|
return "\n".join(parts)
|
|
|
|
def _full(c):
|
|
parts = [str(c.fn.value) if hasattr(c, 'fn') else '?']
|
|
if hasattr(c, 'n'):
|
|
n = c.n.value
|
|
if n.prefix: parts.append(f" Anrede: {n.prefix}")
|
|
parts.append(f" Vorname: {n.given}")
|
|
parts.append(f" Nachname: {n.family}")
|
|
if n.suffix: parts.append(f" Suffix: {n.suffix}")
|
|
if hasattr(c, 'nickname'): parts.append(f" Spitzname: {c.nickname.value}")
|
|
for em in (c.email_list if hasattr(c, 'email_list') else ([c.email] if hasattr(c, 'email') else [])):
|
|
typ = em.params.get("TYPE", [""])[0] if hasattr(em, 'params') and em.params else ""
|
|
parts.append(f" Email ({typ or 'sonstig'}): {em.value}")
|
|
for tel in (c.tel_list if hasattr(c, 'tel_list') else ([c.tel] if hasattr(c, 'tel') else [])):
|
|
typ = tel.params.get("TYPE", [""])[0] if hasattr(tel, 'params') and tel.params else ""
|
|
parts.append(f" Telefon ({typ or 'sonstig'}): {tel.value}")
|
|
for adr in (c.adr_list if hasattr(c, 'adr_list') else ([c.adr] if hasattr(c, 'adr') else [])):
|
|
a = adr.value
|
|
addr = ", ".join(filter(None, [a.street, a.city, a.region, a.code, a.country]))
|
|
if addr: parts.append(f" Adresse: {addr}")
|
|
if hasattr(c, 'org') and c.org.value: parts.append(f" Firma: {c.org.value[0]}")
|
|
if hasattr(c, 'title'): parts.append(f" Titel: {c.title.value}")
|
|
if hasattr(c, 'role'): parts.append(f" Rolle: {c.role.value}")
|
|
if hasattr(c, 'bday'): parts.append(f" Geburtstag: {c.bday.value}")
|
|
if hasattr(c, 'note') and c.note.value: parts.append(f" Notiz: {str(c.note.value)[:300]}")
|
|
if hasattr(c, 'url'): parts.append(f" URL: {c.url.value}")
|
|
if hasattr(c, 'uid'): parts.append(f" UID: {c.uid.value}")
|
|
return "\n".join(parts)
|
|
|
|
|
|
@mcp.tool()
|
|
def search_contacts(
|
|
query: Annotated[str, Field(description="Search term — matches name, email, phone, company, address, notes. Example: 'Lohmaier', 'BMW', '+49171'")],
|
|
limit: Annotated[int, Field(description="Maximum number of results")] = 30,
|
|
) -> str:
|
|
"""Search contacts by any field. Returns name, email, phone, and UID. Use get_contact with the UID for full details."""
|
|
user = get_current_user()
|
|
if not user: return "Error: not authenticated"
|
|
q = query.lower()
|
|
t0 = time.monotonic()
|
|
results = []
|
|
truncated = False
|
|
for book in _discover_ab(user):
|
|
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))
|
|
if len(results) >= limit: break
|
|
if len(results) >= limit: break
|
|
if (time.monotonic() - t0) > PARSE_DEADLINE_S:
|
|
truncated = True; break
|
|
out = "\n\n".join(results) if results else "Keine Kontakte gefunden"
|
|
if truncated:
|
|
out += "\n\n[Suche zeitbegrenzt — Begriff praezisieren]"
|
|
return out
|
|
|
|
|
|
def _get_photo_data(card):
|
|
if not hasattr(card, 'photo'):
|
|
return None, None
|
|
photo = card.photo
|
|
data = photo.value
|
|
if isinstance(data, str) and data.startswith("http"):
|
|
return None, None
|
|
if isinstance(data, bytes):
|
|
b64 = base64.b64encode(data).decode()
|
|
else:
|
|
b64 = data
|
|
ptype = (photo.params.get("TYPE", [""])[0] or "").lower() if hasattr(photo, 'params') and photo.params else ""
|
|
mime = {"jpeg": "image/jpeg", "png": "image/png", "gif": "image/gif"}.get(ptype, "image/jpeg")
|
|
return b64, mime
|
|
|
|
|
|
@mcp.tool()
|
|
def get_contact(
|
|
uid: Annotated[str, Field(description="Contact UID from search_contacts results")],
|
|
) -> list[TextContent | ImageContent]:
|
|
"""Get full details of a contact by UID: name, emails, phones, addresses, company, birthday, notes. Includes contact photo if available."""
|
|
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(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)
|
|
if b64 and mime:
|
|
result.append(ImageContent(type="image", data=b64, mimeType=mime))
|
|
return result
|
|
return [TextContent(type="text", text=f"Kontakt nicht gefunden: {uid}")]
|
|
|
|
|
|
@mcp.tool()
|
|
def create_contact(
|
|
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:
|
|
"""Create a new contact in the default addressbook."""
|
|
user = get_current_user()
|
|
if not user: return "Error: not authenticated"
|
|
books = _discover_ab(user)
|
|
if not books: return "Kein Adressbuch gefunden"
|
|
uid_val = str(uuid.uuid4())
|
|
card = vobject.vCard()
|
|
card.add("uid").value = uid_val
|
|
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
|
|
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")],
|
|
image_base64: Annotated[str, Field(description="Photo as base64-encoded JPEG or PNG data")],
|
|
image_type: Annotated[str, Field(description="Image format: 'jpeg' or 'png'")] = "jpeg",
|
|
) -> str:
|
|
"""Set or replace a contact's photo. Provide the image as base64-encoded data."""
|
|
user = get_current_user()
|
|
if not user: return "Error: not authenticated"
|
|
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 = base64.b64decode(image_base64)
|
|
photo.params["ENCODING"] = ["b"]
|
|
photo.params["TYPE"] = [image_type.upper()]
|
|
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 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()
|
|
@asynccontextmanager
|
|
async def lifespan(app):
|
|
async with contextlib.AsyncExitStack() as stack:
|
|
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
|
yield
|
|
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="0.0.0.0", port=5102) |