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:
1 parent
7c01e7be53
commit
75185ef2ba
41 files changed
+8834
-324
No files matched your search
@@ -4,6 +4,7 @@ __pycache__/
|
|||||||
tokens.json
|
tokens.json
|
||||||
config.json
|
config.json
|
||||||
.active_tokens.json
|
.active_tokens.json
|
||||||
|
service_tokens.json
|
||||||
*.before-*
|
*.before-*
|
||||||
.token_audit.log
|
.token_audit.log
|
||||||
*.bak-*
|
*.bak-*
|
||||||
|
|||||||
@@ -0,0 +1,209 @@
|
|||||||
|
# mcp-home
|
||||||
|
|
||||||
|
Self-hosted MCP (Model Context Protocol) servers for the OpenClaw assistants (mycroft/jarvis). Provides access to personal data services via HTTP endpoints with OAuth (client_credentials).
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
8 independent MCP servers, each on its own port, bound to 0.0.0.0:
|
||||||
|
|
||||||
|
- **Mail** (Port 5100) — searches IMAP backup Maildirs, reads attachments, creates drafts
|
||||||
|
- **Calendar** (Port 5101) — CalDAV against Baikal (Produktiv; Radicale-Fallback nur fuer Test-User mcptest) (events + tasks/reminders, travel time, geocoding, alarms)
|
||||||
|
- **Contacts** (Port 5102) — CardDAV against Baikal (Produktiv; Radicale-Fallback nur fuer Test-User mcptest) (contacts + photos)
|
||||||
|
- **Files** (Port 5103) — WebDAV against oCIS (full CRUD, images inline, documents as blobs)
|
||||||
|
- **Notes** (Port 5104) — Joplin Data API (notes + attachments)
|
||||||
|
- **OpenWearables** (Port 5105) — read-only Wearable-Daten (Sleep, Activity, Workouts, Timeseries) aus Open Wearables (`/opt/openwearables`), nur eigene Daten (s. u.)
|
||||||
|
- **Ghostfolio** (Port 5120) — Portfolio-Tracker via Ghostfolio-REST-API (Port 3333); read+write (Konten, Activities, Performance, Dividenden)
|
||||||
|
- **ActualBudget** (Port 5121) — Haushaltsbudget; read+write via Node-Sidecar `/opt/actualbudget-mcp/sidecar` (systemd `actualbudget-sidecar`, 127.0.0.1:5106) auf ActualBudget-Server (Port 5006)
|
||||||
|
|
||||||
|
Zugriff intern (Standard): Die OpenClaw-Container (mycroft/jarvis) erreichen die Server
|
||||||
|
ueber das Docker-Gateway `172.26.0.1:<port>/mcp` (openclaw-net). Die URLs stehen in den
|
||||||
|
Container-Configs `/mnt/ssd/openclaw/<agent>/data/openclaw.json` (mcp.servers.*.url).
|
||||||
|
|
||||||
|
Zugriff oeffentlich (seit 2026-09-18): notes, calendar, mail, contacts, files, openwearables,
|
||||||
|
ghostfolio und owamail sind zusaetzlich unter `https://<name>.mcp.slohmaier.de/mcp`
|
||||||
|
erreichbar (nginx -> 127.0.0.1:<port>, Let's-Encrypt-SAN, Rate-Limit auf /authorize+/token).
|
||||||
|
OpenClaw nutzt fuer diese die oeffentlichen URLs (bewusste Abweichung von der Regel "lokale
|
||||||
|
Routen", damit die Config bei einem Umzug unveraendert bleibt). Weitere Server bei Bedarf nach
|
||||||
|
demselben Muster (vhost + Cert-SAN).
|
||||||
|
Details: README.md, Abschnitt "Oeffentliche Endpunkte".
|
||||||
|
|
||||||
|
Auth fuer oeffentliche Clients: OAuth (claude.ai) ODER nicht-ablaufende Service-Tokens
|
||||||
|
(`service_tokens.json`, Verwaltung `./mint-service-token.sh`); common.py prueft Service-Tokens
|
||||||
|
vor den OAuth-Access-Tokens. Zukunfts-Option OAuth/DCR (ChatGPT) siehe README.md.
|
||||||
|
|
||||||
|
Firewall: iptables raw-PREROUTING blockt die Ports 5100-5105,5120,5121 fuer alle Quellen
|
||||||
|
ausserhalb `172.26.0.0/16` (openclaw-net). nginx erreicht die Ports via 127.0.0.1 (ACCEPT-Regel).
|
||||||
|
Regel in `/etc/iptables/rules.v4` (netfilter-persistent).
|
||||||
|
|
||||||
|
### OpenWearables (Port 5105)
|
||||||
|
|
||||||
|
Server: `/opt/mcp-servers/openwearables/server.py`, Config `/opt/mcp-servers/openwearables/config.json`
|
||||||
|
(chmod 600, enthaelt den gemeinsamen OpenWearables-API-Key und das User-ID-Mapping).
|
||||||
|
|
||||||
|
Tools: `get_users`, `get_sleep_summary`, `get_activity_summary`, `get_workout_events`, `get_timeseries`.
|
||||||
|
Alle read-only, gegen die interne Open-Wearables-API (`http://127.0.0.1:8000`), NIE ueber Cloudflare.
|
||||||
|
|
||||||
|
**User-Trennung (wichtig):** Der OpenWearables-API-Key ist GLOBAL (nicht pro User gescoped). Die
|
||||||
|
Trennung passiert im Server: `config.json` mappt den OAuth-User (`stefan`/`kati`) auf die jeweilige
|
||||||
|
OpenWearables-User-UUID (`user_id_map`). Die OpenWearables-User-ID wird IMMER aus dem Login des
|
||||||
|
Clients bestimmt, nie aus Tool-Argumenten. mycroft sieht also nur Stefans Daten, jarvis nur Katis.
|
||||||
|
|
||||||
|
- MCP-Server in openclaw.json: `openwearables` -> `http://172.26.0.1:5105/mcp`
|
||||||
|
- systemd: `mcp-openwearables.service`
|
||||||
|
|
||||||
|
All servers share `common.py` for OAuth + user resolution.
|
||||||
|
|
||||||
|
## Auth Flow
|
||||||
|
|
||||||
|
claude.ai uses OAuth 2.0 **Authorization Code + PKCE**. client_credentials is also supported (used by tests).
|
||||||
|
|
||||||
|
1. claude.ai discovers `/.well-known/oauth-authorization-server`
|
||||||
|
2. `GET /authorize` → auto-approves valid client_id, redirects with code
|
||||||
|
3. `POST /token` (authorization_code + code_verifier, optional client_secret) → access_token
|
||||||
|
4. `Authorization: Bearer <token>` on MCP requests
|
||||||
|
|
||||||
|
Access tokens are stored in a shared file `.active_tokens.json` so all 5 services validate tokens issued by any service. client_secret is verified at token exchange when provided.
|
||||||
|
|
||||||
|
## User Separation
|
||||||
|
|
||||||
|
`tokens.json` (not in git, chmod 600) maps client_id (`stefan`, `kati`, `test`) → secret. `USER_ALIASES` in `common.py` maps `test` → `stefan`. Each user sees only their own data; shared CalDAV calendars are visible to both.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
- `tokens.json` — OAuth client_id/secret per user (gitignored)
|
||||||
|
- `config.json` — all backend credentials (Baikal + Radicale, oCIS, Joplin, IMAP), gitignored. See `config.json.example`.
|
||||||
|
- `.active_tokens.json` — runtime OAuth tokens (gitignored)
|
||||||
|
|
||||||
|
## Backends
|
||||||
|
|
||||||
|
- **Mail**: reads Maildirs under `/mnt/ssd/Backup/{stefan,kati}/imap/`. Drafts via IMAP APPEND (1blu / Gmail).
|
||||||
|
- **Calendar/Contacts**: Baikal CalDAV/CardDAV on `https://baikal.slohmaier.de` (Produktiv, seit 2026-09-11). Basen:
|
||||||
|
`dav.php/calendars/<user>/` und `dav.php/addressbooks/<user>/`; Baikal liefert hrefs pfad-absolut (`/dav.php/...`) und
|
||||||
|
calendar-data/address-data mit Namespace-Prefix `cal:`/`card:` — der Parser ist Namespace-agnostisch
|
||||||
|
(`(?:[a-zA-Z][a-zA-Z0-9_]*):calendar-data|address-data`). sabre inbox/outbox werden herausgefiltert.
|
||||||
|
Backend-Auswahl pro User ueber `_serve(user)`: User in `baikal_users` (stefan/kati = mycroft/jarvis) → Baikal;
|
||||||
|
andere (Test-User `mcptest`) → Radicale-Fallback `http://127.0.0.1:5232` (Radicale laeuft weiter fuer Tests,
|
||||||
|
mirror-first bis Geraete-Umstellung abgeschlossen). Radicale-URL/Creds/Pfade bleiben in `config.json`
|
||||||
|
(`radicale_url`, `radicale_users`, `radicale_calendar_paths`, `radicale_addressbook_paths`).
|
||||||
|
- **Files**: oCIS WebDAV on `127.0.0.1:9200/remote.php/dav/files/<user>/`. oCIS username may differ from MCP user (mapping in config).
|
||||||
|
- **Notes**: Joplin **Data API** via joplin-cli sync clients on `127.0.0.1:41184` (stefan) / `41185` (kati). See `/opt/joplin-mcp/README.md`. NOT the Joplin Server sync API (that has no clean REST/search).
|
||||||
|
- **Ghostfolio**: Ghostfolio-REST-API on `127.0.0.1:3333` (JWT-Token `/opt/ghostfolio/migration/.auth-token`). Read+write.
|
||||||
|
- **ActualBudget**: Node-Sidecar (`/opt/actualbudget-mcp/sidecar`, systemd `actualbudget-sidecar`) on `127.0.0.1:5106` (RPC), der `@actual-app/api` kapselt und den ActualBudget-Server (Port 5006) anspricht.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
- `common.py` — OAuth (authorize/token/metadata), Bearer middleware, user resolution (contextvars), config loader
|
||||||
|
- `mail/server.py` — Maildir reader; tools: list_accounts, list_folders, search_mail, read_mail (lists attachments), read_attachment, create_draft
|
||||||
|
- `calendar/server.py` — CalDAV REPORT + vobject; events/tasks CRUD, travel time, geocoding, reminders. Timed events/tasks werden mit TZID=Europe/Berlin (pytz) geschrieben (naive Eingaben lokalisiert, Offsets/Z konvertiert; Bugfix 2026-09-30, vorher floating -> Baikal las +2h). Delete/Update loesen den echten Ressourcenpfad per UID auf (`_find_href`), da der Dateiname nicht die UID sein muss (Importe wie medatixx).
|
||||||
|
- `contacts/server.py` — CardDAV; search/get/create, contact photos
|
||||||
|
- `files/server.py` — WebDAV; list/read/write/delete/move/search, images + documents
|
||||||
|
- `notes/server.py` — Joplin Data API; list/search/read/create notes, list_note_resources, read_resource, add/update/delete_attachment
|
||||||
|
- `ghostfolio/server.py` — Ghostfolio-REST-API; portfolio_details, get_performance, get_dividends, list_accounts, create_account, import_activities, list_activities, delete_activity. Schreib-Tools stoessen automatisch `update-report.sh` an -> accessible-dashboard-Report wird sofort neu gebaut (Details im ghostfolio/README)
|
||||||
|
- `actualbudget/server.py` — Node-Sidecar-RPC; budgets/accounts/transactions/categories/budget/payees CRUD + aql_query
|
||||||
|
- `tests/` — Schichten: `test_smoke.py` (NIGHTLY via `mcp-tests.timer`, nur up+Auth+1 Read/Connector), `test_edge.py`+`test_stress.py`+`test_all.py` (ON-DEMAND via `run_full_tests.sh`). Doku `tests/MCPTEST.md`
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```
|
||||||
|
pip install mcp[cli] httpx vobject python-dateutil pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
Python 3.12+, venv at `./venv/`. joplin-cli (npm global) for Notes backend.
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
Each server is a systemd unit `mcp-<name>.service` (uvicorn), bound to 0.0.0.0. Zugriff intern via openclaw-net (172.26.0.1:<port>/mcp); einzelne Server zusaetzlich oeffentlich via nginx/TLS (notes/calendar, s. o.). Joplin: `joplin-cli-{stefan,kati}.service` + `joplin-sync.timer` (15 min).
|
||||||
|
|
||||||
|
## Content Types (returning binary)
|
||||||
|
|
||||||
|
- Text → `TextContent`
|
||||||
|
- Images (jpg/png/gif/webp) → `ImageContent` (base64 inline)
|
||||||
|
- PDFs → server-seitig zu Text extrahiert bzw. gescannte Seiten als PNG+OCR gerendert (`pdfutil.py`). claude.ai nimmt KEINE PDF/Dokument-Blobs aus Tool-Results nativ entgegen (nur Text + Bild). Andere Binaerdateien → `EmbeddedResource`/`BlobResourceContents` (Blob; wird von claude.ai nicht als Dokument verarbeitet)
|
||||||
|
|
||||||
|
## Robustheit / Limits
|
||||||
|
|
||||||
|
Alle Such-/List-Tools sind gegen grosse Datenmengen abgesichert (single-threaded Server darf nicht haengen): Mail per-Mail try/except + `DEADLINE_S`/`MAX_SCAN`; Files `search_files` `SEARCH_DEADLINE_S`/`SEARCH_MAX_DIRS`; Calendar/Contacts `PARSE_DEADLINE_S` + `MAX_RESULTS`-Output-Cap. Details + Messwerte: `tests/MCPTEST.md`.
|
||||||
|
|
||||||
|
## Adding a New Service
|
||||||
|
|
||||||
|
1. `<name>/server.py` with `FastMCP` instance + `create_app()` (copy mail/server.py pattern)
|
||||||
|
2. Import `get_current_user`, `OAUTH_ROUTES`, `BearerAuthMiddleware`, `load_config` from `common.py`
|
||||||
|
3. systemd unit `mcp-<name>.service` (bind 0.0.0.0) + iptables-Regel fuer den Port (nur openclaw-net 172.26.0.0/16) + URL in den Container-Configs eintragen
|
||||||
|
4. systemd unit `mcp-<name>.service`
|
||||||
|
5. Backend creds in `config.json`
|
||||||
|
6. Tests: Smoke-Read in `test_smoke.py` + Edge in `test_edge.py` + Stress in `test_stress.py` (Funktional in `test_all.py`); Dashboard + dieses File aktualisieren
|
||||||
|
|
||||||
|
## Tool Design Guidelines
|
||||||
|
|
||||||
|
- Docstring is the first thing Claude sees — make it actionable ("Call this first", "Use the UID from search results")
|
||||||
|
- `Annotated[str, Field(description="...")]` with example values for every parameter
|
||||||
|
- Mark optional params ("Leave empty for all")
|
||||||
|
- Reference other tools ("Use read_attachment with the index from read_mail")
|
||||||
|
- Return structured text, not JSON
|
||||||
|
- Include IDs/keys in output so Claude can chain to detail tools
|
||||||
|
|
||||||
|
## Test-/Dev-User mcptest
|
||||||
|
|
||||||
|
Die Test-Suite laeuft auf einem isolierten `mcptest`-User (NICHT Stefans Daten):
|
||||||
|
`USER_ALIASES = {"test": "mcptest"}`. Eigene Backends: Radicale-User mcptest (Calendar/Contacts laufen ueber den
|
||||||
|
Radicale-Fallback in `_serve(user)`, da es keinen Baikal-mcptest gibt), oCIS-User
|
||||||
|
mcptest, lokales Joplin-Profil (:41186, `joplin-cli-mcptest.service`), Test-Maildir
|
||||||
|
`tests/testdata/maildir/`. Dient auch als Dev-Sandbox. Vollstaendige Doku + Provisioning:
|
||||||
|
`tests/MCPTEST.md`. Creds: `/root/.mcptest-creds` (600) + `config.json`.
|
||||||
|
|
||||||
|
## User nova (stefan@slohmaier.com, fuer OpenClaw-Agent Nova)
|
||||||
|
|
||||||
|
Nova (Agent im mycroft-Gateway) braucht Business-Mails statt Stefans privater .de-Mails.
|
||||||
|
Dafuer:
|
||||||
|
- tokens.json: User `nova` mit eigenem Client-Secret (token).
|
||||||
|
- config.json mail_roots.nova -> `/mnt/ssd/Backup/stefan/nova-imap` (Symlink auf das
|
||||||
|
.com-Maildir d370128_0-stefanlohmaier). Nova sieht damit NUR das .com-Postfach.
|
||||||
|
- Im mycroft-Gateway gibt es einen zusaetzlichen MCP-Server `mail-com` (Bearer des nova-
|
||||||
|
Users) auf demselben Port 5100. Nova nutzt mail-com, Mycroft nutzt `mail` (.de).
|
||||||
|
- Zugriffstoken fuer nova per `mcp-token-refresh`-Mechanik oder manuell:
|
||||||
|
POST /token client_credentials mit client_id=nova + secret aus tokens.json.
|
||||||
|
|
||||||
|
## Calendar: Namens-Aufloesung (exakt vor Teilstring)
|
||||||
|
|
||||||
|
Seit 2026-08-20 loest `_match_cols` Kalender-/Listen-Namen bei allen
|
||||||
|
Schreib-/Loesch-Operationen (create_event, create_task, delete_event,
|
||||||
|
delete_task) so auf: exakter Namens-Treffer zuerst, sonst Teilstring.
|
||||||
|
Grund: Die Shared-Kalender "Kati Stefan" (beschreibbar) und "Kati Stefan
|
||||||
|
JaSi" (read-only, Google-Sync) kollidierten bei Teilstring-Match — ein PUT
|
||||||
|
auf "Kati Stefan" traf sonst den read-only JaSi-Kalender (HTTP 403), obwohl
|
||||||
|
der User (kati/stefan) Schreibrechte auf den richtigen Kalender hat.
|
||||||
|
|
||||||
|
## Calendar: Loeschen
|
||||||
|
|
||||||
|
Der Calendar-MCP hat seit 2026-08-13 `delete_event` und `delete_task` (Loeschen per UID).
|
||||||
|
UID kommt aus `get_events` / `get_tasks`. Loeschung direkt via CalDAV an das aktive Backend (Baikal fuer stefan/kati,
|
||||||
|
Radicale-Fallback fuer mcptest).
|
||||||
|
|
||||||
|
## Mail-Drafts mit Anhang
|
||||||
|
|
||||||
|
`create_draft` unterstuetzt seit 2026-08-13 Anhaenge ueber Base64:
|
||||||
|
- `attachment_filenames` (Liste), `attachment_contents` (Liste, Base64-kodierte Bytes),
|
||||||
|
optional `attachment_mimetypes` (Liste; sonst application/octet-stream).
|
||||||
|
- Der Agent erzeugt einen mehrteiligen (multipart) Draft im IMAP-Drafts-Ordner.
|
||||||
|
- Test ok: "Entwurf erstellt mit 1 Anhang/Anhaengen".
|
||||||
|
|
||||||
|
## Notes: Anhaenge (Attachments)
|
||||||
|
|
||||||
|
Der Notes-MCP kann seit 2026-09-16 Anhaenge an Notizen anlegen, aendern und
|
||||||
|
loeschen (vorher nur lesen: `list_note_resources` / `read_resource`):
|
||||||
|
|
||||||
|
- `add_attachment(note_id, filename, content_base64, mime?, title?)` — laedt die
|
||||||
|
Datei via `POST /resources` hoch (multipart/form-data: Datei im Feld `data`,
|
||||||
|
Properties als JSON im Feld `props`) und haengt `[title](:/resourceId)` ans
|
||||||
|
Ende des Notiz-Bodys an (bei Bildern `![...]`, damit es inline rendert).
|
||||||
|
Max 25 MB; Inhalt Base64 (data-URL-Prefix und Zeilenumbrueche erlaubt).
|
||||||
|
- `update_attachment(resource_id, content_base64?, filename?, mime?, title?)` —
|
||||||
|
ersetzt den Datei-Inhalt (`PUT /resources/:id`, multipart) und/oder aendert
|
||||||
|
Titel/MIME (JSON-PUT, wenn kein Inhalt uebergeben wird).
|
||||||
|
- `delete_attachment(resource_id, note_id?, remove_links?)` — loescht das
|
||||||
|
Resource endgueltig (Joplin hat fuer Resources keinen Papierkorb) und entfernt
|
||||||
|
die Markdown-/HTML-Referenzen aus dem Notiz-Body. `note_id` angeben, damit der
|
||||||
|
Link sicher bereinigt wird: Joplins Endpoint `/resources/:id/notes` ist
|
||||||
|
unzuverlaessig (Link-Tabelle kann leer bleiben, dann bliebe der Link verwaist).
|
||||||
|
- MIME wird aus der Dateiendung geraten, wenn nicht uebergeben.
|
||||||
|
- Getestet in `tests/test_all.py::TestNotes::test_attachment_crud` (mcptest).
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
# mcp-home
|
|
||||||
|
|
||||||
Self-hosted MCP (Model Context Protocol) servers for Claude. Provides access to personal data services via remote HTTP endpoints with OAuth (Authorization Code + PKCE, and client_credentials).
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
5 independent MCP servers, each on its own subdomain + port:
|
|
||||||
|
|
||||||
- **Mail** (`mail.mcp.home.slohmaier.de`, Port 5100) — searches IMAP backup Maildirs, reads attachments, creates drafts
|
|
||||||
- **Calendar** (`calendar.mcp.home.slohmaier.de`, Port 5101) — CalDAV against Radicale (events + tasks/reminders, travel time, geocoding, alarms)
|
|
||||||
- **Contacts** (`contacts.mcp.home.slohmaier.de`, Port 5102) — CardDAV against Radicale (contacts + photos)
|
|
||||||
- **Files** (`files.mcp.home.slohmaier.de`, Port 5103) — WebDAV against oCIS (full CRUD, images inline, documents as blobs)
|
|
||||||
- **Notes** (`notes.mcp.home.slohmaier.de`, Port 5104) — Joplin Data API (notes + attachments)
|
|
||||||
|
|
||||||
Each subdomain is its own nginx vhost proxying to the local port. All servers share `common.py` for OAuth + user resolution.
|
|
||||||
|
|
||||||
## Auth Flow
|
|
||||||
|
|
||||||
claude.ai uses OAuth 2.0 **Authorization Code + PKCE**. client_credentials is also supported (used by tests).
|
|
||||||
|
|
||||||
1. claude.ai discovers `/.well-known/oauth-authorization-server`
|
|
||||||
2. `GET /authorize` → auto-approves valid client_id, redirects with code
|
|
||||||
3. `POST /token` (authorization_code + code_verifier, optional client_secret) → access_token
|
|
||||||
4. `Authorization: Bearer <token>` on MCP requests
|
|
||||||
|
|
||||||
Access tokens are stored in a shared file `.active_tokens.json` so all 5 services validate tokens issued by any service. client_secret is verified at token exchange when provided.
|
|
||||||
|
|
||||||
## User Separation
|
|
||||||
|
|
||||||
`tokens.json` (not in git, chmod 600) maps client_id (`stefan`, `kati`, `test`) → secret. `USER_ALIASES` in `common.py` maps `test` → `stefan`. Each user sees only their own data; shared CalDAV calendars are visible to both.
|
|
||||||
|
|
||||||
## Config
|
|
||||||
|
|
||||||
- `tokens.json` — OAuth client_id/secret per user (gitignored)
|
|
||||||
- `config.json` — all backend credentials (Radicale, oCIS, Joplin, IMAP), gitignored. See `config.json.example`.
|
|
||||||
- `.active_tokens.json` — runtime OAuth tokens (gitignored)
|
|
||||||
|
|
||||||
## Backends
|
|
||||||
|
|
||||||
- **Mail**: reads Maildirs under `/mnt/ssd/Backup/{stefan,kati}/imap/`. Drafts via IMAP APPEND (1blu / Gmail).
|
|
||||||
- **Calendar/Contacts**: Radicale CalDAV/CardDAV on `127.0.0.1:5232`. Note: Radicale uses default `DAV:` namespace (no `d:` prefix) and `CR:` for CardDAV — regex must match both.
|
|
||||||
- **Files**: oCIS WebDAV on `127.0.0.1:9200/remote.php/dav/files/<user>/`. oCIS username may differ from MCP user (mapping in config).
|
|
||||||
- **Notes**: Joplin **Data API** via joplin-cli sync clients on `127.0.0.1:41184` (stefan) / `41185` (kati). See `/opt/joplin-mcp/README.md`. NOT the Joplin Server sync API (that has no clean REST/search).
|
|
||||||
|
|
||||||
## Files
|
|
||||||
|
|
||||||
- `common.py` — OAuth (authorize/token/metadata), Bearer middleware, user resolution (contextvars), config loader
|
|
||||||
- `mail/server.py` — Maildir reader; tools: list_accounts, list_folders, search_mail, read_mail (lists attachments), read_attachment, create_draft
|
|
||||||
- `calendar/server.py` — CalDAV REPORT + vobject; events/tasks CRUD, travel time, geocoding, reminders
|
|
||||||
- `contacts/server.py` — CardDAV; search/get/create, contact photos
|
|
||||||
- `files/server.py` — WebDAV; list/read/write/delete/move/search, images + documents
|
|
||||||
- `notes/server.py` — Joplin Data API; list/search/read/create notes, list_note_resources, read_resource
|
|
||||||
- `tests/` — Schichten: `test_smoke.py` (NIGHTLY via `mcp-tests.timer`, nur up+Auth+1 Read/Connector), `test_edge.py`+`test_stress.py`+`test_all.py` (ON-DEMAND via `run_full_tests.sh`). Doku `tests/MCPTEST.md`
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
```
|
|
||||||
pip install mcp[cli] httpx vobject python-dateutil pytest
|
|
||||||
```
|
|
||||||
|
|
||||||
Python 3.12+, venv at `./venv/`. joplin-cli (npm global) for Notes backend.
|
|
||||||
|
|
||||||
## Deployment
|
|
||||||
|
|
||||||
Each server is a systemd unit `mcp-<name>.service` (uvicorn). Each subdomain is an nginx vhost with rate-limited `/authorize` + `/token`. TLS via Certbot (shared cert on mail.mcp...). Joplin: `joplin-cli-{stefan,kati}.service` + `joplin-sync.timer` (15 min).
|
|
||||||
|
|
||||||
## Content Types (returning binary)
|
|
||||||
|
|
||||||
- Text → `TextContent`
|
|
||||||
- Images (jpg/png/gif/webp) → `ImageContent` (base64 inline)
|
|
||||||
- PDFs → server-seitig zu Text extrahiert bzw. gescannte Seiten als PNG+OCR gerendert (`pdfutil.py`). claude.ai nimmt KEINE PDF/Dokument-Blobs aus Tool-Results nativ entgegen (nur Text + Bild). Andere Binaerdateien → `EmbeddedResource`/`BlobResourceContents` (Blob; wird von claude.ai nicht als Dokument verarbeitet)
|
|
||||||
|
|
||||||
## Robustheit / Limits
|
|
||||||
|
|
||||||
Alle Such-/List-Tools sind gegen grosse Datenmengen abgesichert (single-threaded Server darf nicht haengen): Mail per-Mail try/except + `DEADLINE_S`/`MAX_SCAN`; Files `search_files` `SEARCH_DEADLINE_S`/`SEARCH_MAX_DIRS`; Calendar/Contacts `PARSE_DEADLINE_S` + `MAX_RESULTS`-Output-Cap. Details + Messwerte: `tests/MCPTEST.md`.
|
|
||||||
|
|
||||||
## Adding a New Service
|
|
||||||
|
|
||||||
1. `<name>/server.py` with `FastMCP` instance + `create_app()` (copy mail/server.py pattern)
|
|
||||||
2. Import `get_current_user`, `OAUTH_ROUTES`, `BearerAuthMiddleware`, `load_config` from `common.py`
|
|
||||||
3. nginx vhost `<name>.mcp.home.slohmaier.de` + Certbot
|
|
||||||
4. systemd unit `mcp-<name>.service`
|
|
||||||
5. Backend creds in `config.json`
|
|
||||||
6. Tests: Smoke-Read in `test_smoke.py` + Edge in `test_edge.py` + Stress in `test_stress.py` (Funktional in `test_all.py`); Dashboard + dieses File aktualisieren
|
|
||||||
|
|
||||||
## Tool Design Guidelines
|
|
||||||
|
|
||||||
- Docstring is the first thing Claude sees — make it actionable ("Call this first", "Use the UID from search results")
|
|
||||||
- `Annotated[str, Field(description="...")]` with example values for every parameter
|
|
||||||
- Mark optional params ("Leave empty for all")
|
|
||||||
- Reference other tools ("Use read_attachment with the index from read_mail")
|
|
||||||
- Return structured text, not JSON
|
|
||||||
- Include IDs/keys in output so Claude can chain to detail tools
|
|
||||||
|
|
||||||
## Test-/Dev-User mcptest
|
|
||||||
|
|
||||||
Die Test-Suite laeuft auf einem isolierten `mcptest`-User (NICHT Stefans Daten):
|
|
||||||
`USER_ALIASES = {"test": "mcptest"}`. Eigene Backends: Radicale-User mcptest, oCIS-User
|
|
||||||
mcptest, lokales Joplin-Profil (:41186, `joplin-cli-mcptest.service`), Test-Maildir
|
|
||||||
`tests/testdata/maildir/`. Dient auch als Dev-Sandbox. Vollstaendige Doku + Provisioning:
|
|
||||||
`tests/MCPTEST.md`. Creds: `/root/.mcptest-creds` (600) + `config.json`.
|
|
||||||
@@ -1,14 +1,72 @@
|
|||||||
# mcp-home
|
|
||||||
|
|
||||||
Self-hosted [MCP](https://modelcontextprotocol.io) servers for Claude. Gives Claude access to your email, calendar, contacts, files, and notes — all running on your own hardware, behind OAuth.
|
Self-hosted [MCP](https://modelcontextprotocol.io) servers for Claude. Gives Claude access to your email, calendar, contacts, files, and notes — all running on your own hardware, behind OAuth.
|
||||||
|
|
||||||
## Services & Tools
|
## Services & Tools
|
||||||
|
|
||||||
- **Mail** — `list_accounts`, `list_folders`, `search_mail` (full text), `read_mail` (lists attachments), `read_attachment` (image/PDF/text), `create_draft`
|
- **Mail** — `list_accounts`, `list_folders`, `search_mail` (full text), `read_mail` (lists attachments), `read_attachment` (image/PDF/text), `download_attachment` (Anhang als Datei ins Agent-Workspace), `create_draft`
|
||||||
|
- **download_attachment (2026-09-04):** schreibt den Anhang (account/folder/key aus search_mail, Index aus read_mail) als echte Datei ins Workspace des Agenten (mycroft/jarvis) und gibt den Container-Pfad zurueck. Zielverzeichnis pro User in `config.json` unter `mail_attachment_dirs` (host + container Pfad; mycroft: `/mnt/ssd/openclaw/mycroft/data/workspace/mail-attachments` -> `/home/node/.openclaw/workspace/mail-attachments`). UID 1000 (stefan/node) identisch, keine Permissions-Probleme. Kollisionen bekommen Suffix ` (1)`. Sinn: Der Agent kann den Anhang mit seinen Datei-/Shell-Tools weiterverarbeiten, nicht nur inline ansehen.
|
||||||
|
- **read_mail/read_attachment/download_attachment Key-Fix (2026-09-09):** Der FTS-Index speichert den vollen Maildir-Dateinamen inkl. Dovecot-Flags-Suffix (`...:2,T`), waehrend Python `mailbox.Maildir` als Key nur den Teil vor `:2,` nutzt. Dadurch schlug `read_mail` mit "Message not found" fehl, obwohl `search_mail` die Mail fand (betrifft alle Clients: OpenClaw + Hermes). Fix in `server.py`: `_norm_key(key)` schneidet das `:2,...`-Suffix ab und wird in `read_mail`, `read_attachment`, `download_attachment` angewandt. Backup: `server.py.bak-maileade-20260909`.
|
||||||
|
- **Nova .com voll in Betrieb (2026-09-10):** `imap_passwords.nova` + `IMAP_ACCOUNTS['nova']` (imap.1blu.de, user `d370128_0-stefanlohmaier`) ergaenzt. Verifiziert per Bearer per User: `stefan` sieht nur `d370128_0-slohmaier` (.de), `nova` nur `d370128_0-stefanlohmaier` (.com), `kati` nur `akpolke@gmail.com`. Real-Login gegen imap.1blu.de ok. Backups: `config.json.bak-novacom-20260910-110015`, `server.py.bak-novacom-20260910-*`.
|
||||||
|
- **create_draft Gmail-Quoting-Fix (2026-09-11):** `create_draft` fuer Katis Gmail-Account schlug mit `IMAP-Fehler: APPEND command error: BAD [b'Could not parse command']` fehl. Ursache: Python-imaplib quotet den Ordnernamen bei `append()`/`select()` mit Literal-Syntax ({n}) NICHT; Gmail bricht bei Ordnernamen mit Sonderzeichen ab (Drafts-Ordner `[Google Mail]/Entw&APw-rfe` enthaelt `&` und `[]`). Fix: Helper `_imap_quote_folder()` in `server.py`, der Ordnernamen mit Sonderzeichen (` &[]\\"`) in doppelte Anführungszeichen setzt und beim `append` anwendet. 1blu-Accounts (stefan/nova, `Drafts`) bleiben unquotiert. Verifiziert: echter APPEND an Gmail-Drafts mit gequotetem Namen -> OK, Test-Draft danach wieder geloescht. Backup: `server.py.bak-20260911-095326`.
|
||||||
|
- **Account-Isolierung pro Agent (2026-09-09):** `server.py` filtert die sichtbaren Mail-Accounts je User via Config `mail_account_allow` (config.json): `stefan` (mycroft/.de) -> nur `d370128_0-slohmaier`; `nova` (.com) -> nur `d370128_0-stefanlohmaier`. `_discover_accounts` wendet den Filter fuer alle Tools an (list/search/read/attachment). Fuer nova liegt der .com-Account als Symlink in `/mnt/ssd/Backup/stefan/nova-imap/`; `index_maildirs.py`/`_discover_folders` nutzen `os.walk(..., followlinks=True)`, damit Volltext-Index und Ordner-Scan den Symlink durchlaufen. Config-Backup: `config.json.bak-20260909`.
|
||||||
|
- **Volltextindex (2026-09-03):** `search_mail` nutzt einen SQLite-FTS5-Index statt des
|
||||||
|
Maildir-Vollscans (der bei Katis Gmail-Archiv, 16 GB / ~30k Mails, das Gateway-Request-Timeout
|
||||||
|
sprengte). Index-DBs: `/var/lib/mail-index/<user>.sqlite` (stefan, kati, nova, mcptest);
|
||||||
|
Build/Update: `/opt/mcp-servers/mail/index_maildirs.py`, getaktet via `mail-index.timer`
|
||||||
|
(alle 5 Min, versetzt zum mail-backup.timer). Such-Strategie: FTS5-Prefix-Treffer auf
|
||||||
|
sender/to/subject/body; E-Mail-Adressen (mit @) ueber LIKE. Erst-Build bereit, wenn
|
||||||
|
`<user>.ready` existiert; ohne ready faellt `search_mail` auf den alten Scan zurueck.
|
||||||
|
- **Ungelesene Mails im Maildir-`new/` (2026-09-26):** mbsync legt Gmail-Mails ohne
|
||||||
|
`\Seen`-Flag in `<folder>/new/` ab (nicht `cur/`). Index und `_discover_folders` sahen
|
||||||
|
aber nur `cur/` -> jede ungelesene Mail war fuer `search_mail` unsichtbar (kati 762,
|
||||||
|
stefan 577, nova 960 zusaetzliche Mails; neueste zuerst betroffen). Fix:
|
||||||
|
`mailindex.py::update_user` walkt jetzt `cur` **und** `new`; `server.py::_discover_folders`
|
||||||
|
akzeptiert Ordner mit `cur` oder `new`. `_parse_file`/`_norm_key` waren bereits
|
||||||
|
pfad-korrekt, `read_mail` funktionierte (Maildir vereint new+cur). Verifiziert per
|
||||||
|
MCP-Call als kati (`search_mail`/`read_mail` auf eine neue `new/`-Mail), Index-Neuaufbau
|
||||||
|
korrekt, `test_smoke.py` gruen und `test_all.py`+`test_edge.py` 96 passed. Backups:
|
||||||
|
`mailindex.py.bak-newdir-*`, `server.py.bak-newdir-*`, `kati.sqlite.bak-newdir-*`.
|
||||||
- **Calendar + Tasks** — `list_calendars`, `get_events`, `search_events`, `list_task_lists`, `get_tasks`, `create_event` (travel time + geocoding + reminders), `create_task`
|
- **Calendar + Tasks** — `list_calendars`, `get_events`, `search_events`, `list_task_lists`, `get_tasks`, `create_event` (travel time + geocoding + reminders), `create_task`
|
||||||
|
- **Zeitzonen-Fix (2026-09-30):** Timed-Events/Tasks wurden ohne TZID (floating) geschrieben; Baikal las sie als UTC, in der CalDAV-Suite +2h verschoben. Jetzt: naive Eingaben werden als `Europe/Berlin` lokalisiert (pytz), explizite Offsets/`Z` konvertiert. Betroffen waren alle per MCP angelegten Timed-Termine; per Einmal-Skript (alle stefan/kati-Kalender) auf TZID umgeschrieben. Anzeige normalisiert aware Zeiten nach Berlin. `delete_event`/`update_event`/`delete_task`/`update_task` loesen den echten Ressourcenpfad per UID auf (`_find_href`), da der `.ics`-Dateiname bei Importen (medatixx) nicht die UID ist (Delete lief sonst ins Leere, Update erzeugte Duplikate).
|
||||||
- **Contacts** — `search_contacts`, `get_contact` (with photo), `create_contact`, `set_contact_photo`
|
- **Contacts** — `search_contacts`, `get_contact` (with photo), `create_contact`, `set_contact_photo`
|
||||||
- **Files** — `list_files`, `read_file` (image/document/text), `file_info`, `search_files`, `write_file`, `create_folder`, `delete_file`, `move_file`
|
- **Files** — `list_files`, `read_file` (image/document/text), `file_info`, `search_files`, `write_file`, `create_folder`, `delete_file`, `move_file`
|
||||||
|
- **URL-Pfad-Encoding-Fix (2026-09-11):** `_dav()` setzte User-Pfade roh in die WebDAV-URL. httpx encodiert Leerzeichen/Umlaute automatisch, aber `#` (wurde Fragment) und `?` (wurde Query-Start) im Dateinamen zerlegten die URL; ein literales `%` erzeugte Ambiguitaet mit bereits-encodierten `%XX`-Sequenzen (oCIS liefert hrefs wie `Entw%C3%BCrfe` zurueck). Fix: `_enc_path()` in `server.py` encodiert `#`->`%23`, `?`->`%3F` und `%` nur ausserhalb gueltiger `%XX`-Folgen (roundtrip-sicher). Anwendung zentral in `_dav()` -> wirkt auf alle 7 Datei-Tools. Verifiziert ueber mcptest-Account (Dateien mit `#`/`%`/`?`/Umlaut/Leerzeichen anlegen/lesen/loeschen) + neuer Edge-Test `test_url_special_chars_roundtrip`. Backup: `files/server.py.bak-20260911-113635`.
|
||||||
- **Notes** — `list_notebooks`, `list_notes`, `search_notes`, `read_note`, `create_note`, `list_note_resources`, `read_resource` (attachments)
|
- **Notes** — `list_notebooks`, `list_notes`, `search_notes`, `read_note`, `create_note`, `list_note_resources`, `read_resource` (attachments)
|
||||||
|
- **Ghostfolio** — `portfolio_details`, `get_performance`, `get_dividends`, `list_accounts`, `create_account`, `import_activities`, `list_activities`, `delete_activity` (Portfolio-Tracker)
|
||||||
|
- **Kaltstart-Latenz (2026-09-11):** Der erste MCP-Call nach laengerer Inaktivitaet kann 6-26 s dauern (Ghostfolio laedt dann historische Wechselkurse ueber `ExchangeRateDataService`, z.B. AUDEUR ab 2023, von externen Quellen). Warm sind Calls 0.6-1 s. Kein Bug -- der naechtliche Smoke-Test (05:00) lief in diesem Kaltfenster und ueberschritt das 60-s-Timeout. Test-Timeout fuer ghostfolio auf 180 s erhoeht (test_smoke.py).
|
||||||
|
|
||||||
|
## owamail (BBS-Postfach, Port 5131)
|
||||||
|
|
||||||
|
Separater MCP-Server fuer Katis BBS-Arbeitsmail (Exchange 2019, S25-EXCHANGE,
|
||||||
|
https://bbsbex.bbsb.org/owa/). Tools: `login`, `list_folders`, `search_mail`,
|
||||||
|
`read_mail`, `download_attachments` (Anhaenge via GetFileAttachment ins
|
||||||
|
jarvis-Workspace owa-attachments), `create_draft` (Entwurf im Drafts-Ordner,
|
||||||
|
KEIN Senden).
|
||||||
|
|
||||||
|
- **Implementierung (2026-09-11):** Nutzt den klassischen OWA-Formular-Login
|
||||||
|
(POST /owa/auth.owa, Sperrschutz: GENAU EIN Login-Versuch, kein Retry -- Katis
|
||||||
|
Arbeitspasswort darf nie durch Auto-Wiederholungen gesperrt werden) und die interne
|
||||||
|
OWA-JSON-API: POST /owa/service.svc?action=<Action>&EP=1&ID=-1&AC=1 mit Action-Header,
|
||||||
|
X-OWA-CANARY und Exchange-JSON-Payloads. API-Muster aus
|
||||||
|
https://github.com/nhype/owa-exchange-mcp (MIT, Referenz unter
|
||||||
|
/opt/mcp-servers/owamail/vendor/exchange_mcp/). Systemd `mcp-owamail` (Port 5131).
|
||||||
|
EWS-Basic-Auth ist serverseitig deaktiviert (401), IMAP/POP3-Ports sind von aussen zu --
|
||||||
|
daher nur ueber die OWA-API. Nicht mit dem mail-Server (5100, Gmail/1blu) verwechseln.
|
||||||
|
Zugriff: Katis Bearer (client_id `kati`) im jarvis-openclaw.json unter `mcp.servers.owamail`
|
||||||
|
(http://172.26.0.1:5131/mcp). Nur User `kati`/`mcptest` duerfen die Tools (ALLOWED_USERS),
|
||||||
|
andere Bearer werden abgewiesen.
|
||||||
|
- **Sicherheit:** Credentials in /opt/mcp-servers/owamail/auth.txt (chmod 600). Der Server
|
||||||
|
bindet nur an localhost; Zugriff ueber Bearer-Auth (OAuth client_credentials).
|
||||||
|
- **Gemeinsamer Client (2026-09-16):** Login/API-Transport liegt in
|
||||||
|
`owamail/owa_client.py` (Klasse `OWAClient`, Modul-Instanz `client`). `server.py`
|
||||||
|
importiert daraus; der Kalender-Fetcher `/opt/owa-kati-calendar/owa_fetch.py`
|
||||||
|
nutzt denselben Client (Einweg-Sync Katis Arbeitskalender -> Baikal "Arbeit",
|
||||||
|
stuendlich). Aenderungen am Client betreffen beide -> `mcp-owamail.service` neu starten.
|
||||||
|
- **Vollständige Mail-Abdeckung (2026-09-11):** `search_mail` unterstuetzt Offset-Paging
|
||||||
|
(`offset`/`limit`, zeigt "Ordner hat N Mails; mehr vorhanden (Offset X)") -- damit erreicht
|
||||||
|
Jarvis auch die aeltesten Mails eines Ordners (Inbox: ~3700+ bis 2023, Archiv: bis 2024).
|
||||||
|
Zusaetzlich `scan_all=true` mit Suchbegriff: blaettert automatisch durch bis 2000 Mails und
|
||||||
|
findet alte Treffer (z.B. Betriebsrats-Newsletter 2025), ohne manuelles Paging.
|
||||||
|
|
||||||
## Setup
|
## Setup
|
||||||
|
|
||||||
@@ -21,6 +79,8 @@ cp config.json.example config.json # set backend credentials
|
|||||||
|
|
||||||
Notes needs joplin-cli sync clients exposing the Data API (see `/opt/joplin-mcp/`).
|
Notes needs joplin-cli sync clients exposing the Data API (see `/opt/joplin-mcp/`).
|
||||||
|
|
||||||
|
Ghostfolio braucht das JWT-Token in `/opt/ghostfolio/migration/.auth-token`.
|
||||||
|
|
||||||
## Usage with claude.ai
|
## Usage with claude.ai
|
||||||
|
|
||||||
Settings → Integrations → Custom MCP Server:
|
Settings → Integrations → Custom MCP Server:
|
||||||
@@ -39,6 +99,93 @@ venv/bin/python -m pytest tests/test_all.py -v
|
|||||||
|
|
||||||
54 integration tests (OAuth, all tools, CRUD in isolated test collections). Run daily via `mcp-tests.timer`.
|
54 integration tests (OAuth, all tools, CRUD in isolated test collections). Run daily via `mcp-tests.timer`.
|
||||||
|
|
||||||
|
## Fix 2026-09-06: actualbudget-Test aus Smoke entfernt
|
||||||
|
|
||||||
|
Der Smoke-Test (`test_smoke.py`) und `SERVERS` in `test_all.py` referenzierten einen
|
||||||
|
`actualbudget`-MCP-Server auf Port 5121, der nie existiert (kein Verzeichnis, keine
|
||||||
|
systemd-Unit, kein Prozess — verworfen). Folge: der
|
||||||
|
naechtliche `mcp-tests.timer` schlug jede Nacht mit 2 failed auf (aktualbudget-read +
|
||||||
|
server_up), was die urgent-NTFY "MCP Smoke-Tests fehlgeschlagen" ausloeste. actualbudget
|
||||||
|
aus `SERVERS` und `test_actualbudget_read` entfernt -> Smoke laeuft wieder gruen
|
||||||
|
(12 passed). Backups: `tests/test_all.py.bak-20260906`, `tests/test_smoke.py.bak-20260906`.
|
||||||
|
|
||||||
|
## Oeffentliche Endpunkte (2026-09-18)
|
||||||
|
|
||||||
|
Oeffentlich erreichbar (nginx -> 127.0.0.1:<port>, Let's-Encrypt-SAN, Rate-Limit
|
||||||
|
`mcp_auth` auf `/authorize` und `/token`):
|
||||||
|
|
||||||
|
- https://notes.mcp.slohmaier.de/mcp (Notes, 5104)
|
||||||
|
- https://calendar.mcp.slohmaier.de/mcp (Calendar, 5101)
|
||||||
|
- https://mail.mcp.slohmaier.de/mcp (Mail, 5100; deckt auch den nova/.com-Bearer ab)
|
||||||
|
- https://contacts.mcp.slohmaier.de/mcp (Contacts, 5102)
|
||||||
|
- https://files.mcp.slohmaier.de/mcp (Files, 5103)
|
||||||
|
- https://openwearables.mcp.slohmaier.de/mcp (OpenWearables, 5105)
|
||||||
|
- https://owamail.mcp.slohmaier.de/mcp (OWA Mail, 5131; nur kati/mcptest)
|
||||||
|
|
||||||
|
- DNS: Wildcard `*.mcp.slohmaier.de` (1blu) -> home.slohmaier.de -> poloschwabing.home64.de
|
||||||
|
- Cert: zentrales `akpo.slohmaier.de` (SAN-Liste, HTTP-01 webroot). Neue Hosts dort ergaenzen:
|
||||||
|
`certbot certonly --webroot -w /var/www/html --cert-name akpo.slohmaier.de --expand -d <alle> -d <neu>`
|
||||||
|
- nginx: `/etc/nginx/sites-available/<name>.mcp.slohmaier.de` (Symlink in sites-enabled)
|
||||||
|
- iptables unveraendert: nginx erreicht die Ports via 127.0.0.1 (ACCEPT-Regel), kein direkter Port.
|
||||||
|
- **Ghostfolio-MCP (5120) am 2026-09-18 entfernt** (0 Tool-Calls in 7 Tagen; vhost deaktiviert,
|
||||||
|
unit disabled). Portfolio weiter ueber die REST-API `https://portfolio.slohmaier.de`.
|
||||||
|
|
||||||
|
### Auth: OAuth + nicht-ablaufende Service-Tokens
|
||||||
|
|
||||||
|
1. OAuth 2.0 Authorization Code + PKCE (claude.ai), client_id/secret aus `tokens.json`.
|
||||||
|
2. Service-Tokens fuer Maschinen-Clients (opencode, Skripte), die einen statischen
|
||||||
|
`Authorization: Bearer`-Header setzen. Ablage: `service_tokens.json`
|
||||||
|
(`{"<token>": {"user": "stefan", "label": "opencode-polo"}}`), chmod 600.
|
||||||
|
`common.py` prueft Service-Tokens in `_resolve_access_token()` vor den OAuth-Access-Tokens
|
||||||
|
(konstanter Vergleich via `secrets.compare_digest`), sie laufen nie ab. Widerruf = `rm`.
|
||||||
|
Verwaltung: `./mint-service-token.sh add <user> <label> | rm <label> | list`.
|
||||||
|
|
||||||
|
### Raw-Endpunkte (Rohdateien/Binaer, token-geschuetzt)
|
||||||
|
|
||||||
|
Fuer beliebige Binaerdateien/-groessen (ersetzen Direkt-Mounts/rclone). Auth ueber dieselbe
|
||||||
|
`BearerAuthMiddleware` (Service-Token oder OAuth), kein anonymer Zugriff:
|
||||||
|
|
||||||
|
- files: `GET /raw?path=<ocis>` (Download, gestreamt) und `PUT /raw?path=<ocis>` (Upload, Body = Rohbytes)
|
||||||
|
- mail: `GET /raw?account=&folder=&key=&index=` (roher Anhang, Content-Disposition)
|
||||||
|
- notes: `GET /raw?resource_id=<id>` (roher Resource); Upload/Ersetzen: `PUT /raw?note_id=<id>&filename=<name>` (neue Resource anlegen + in Notiz verlinken) bzw. `PUT /raw?resource_id=<id>` (vorhandene ersetzen)
|
||||||
|
- contacts: `GET /raw?uid=<uid>` (Kontaktfoto roh) und `PUT /raw?uid=<uid>[&type=jpeg|png|gif]` (Foto aus Rohbytes setzen/ersetzen)
|
||||||
|
|
||||||
|
Beispiel Download: `curl -H "Authorization: Bearer $TOKEN" "https://files.mcp.slohmaier.de/raw?path=/x.pdf" -o /tmp/x.pdf`
|
||||||
|
Beispiel Upload: `curl -X PUT -H "Authorization: Bearer $TOKEN" --data-binary @/tmp/x.pdf "https://files.mcp.slohmaier.de/raw?path=/Ziel/x.pdf"`
|
||||||
|
|
||||||
|
Limits: nginx `client_max_body_size 5g` (Uploads), notes `MAX_ATTACHMENT_BYTES` 2GB. Downloads gestreamt (kein Body-Limit).
|
||||||
|
|
||||||
|
### OpenClaw (mycroft/jarvis)
|
||||||
|
|
||||||
|
Alle MCP-Server (notes, calendar, mail, contacts, files, openwearables, owamail) in `/mnt/ssd/openclaw/<agent>/data/openclaw.json` zeigen seit 2026-09-18 auf die
|
||||||
|
oeffentlichen URLs; Bearer ist ein nicht-ablaufendes Service-Token (`${MCP_BEARER}`, Labels
|
||||||
|
openclaw-mycroft/jarvis/nova). ghostfolio wurde entfernt. Bewusste Abweichung von der
|
||||||
|
AGENTS-Regel "lokale Routen", damit die Config bei einem Umzug (z. B. nach Odin) unveraendert
|
||||||
|
bleibt. Verifiziert: beide Container erreichen alle oeffentlichen Endpunkte mit HTTP 200.
|
||||||
|
|
||||||
|
### Monitoring
|
||||||
|
|
||||||
|
Der naechtliche Smoke (`mcp-tests.timer` 05:00) prueft die oeffentliche Route mit
|
||||||
|
`tests/test_public_smoke.py`: pro Server ohne Token 401, mit Service-Token (Label
|
||||||
|
`smoketest`) initialize + tools/list ueber `https://<name>.mcp.slohmaier.de/mcp`.
|
||||||
|
Faengt DNS-, vhost-, TLS-/Cert- und Auth-Ausfaelle ab (der interne Smoke testet nur
|
||||||
|
`127.0.0.1:<port>`).
|
||||||
|
|
||||||
|
### Zukunfts-Option: OAuth/DCR fuer ChatGPT & spec-konforme Clients
|
||||||
|
|
||||||
|
Service-Tokens funktionieren nur bei Clients, die einen eigenen Header setzen koennen
|
||||||
|
(opencode, OpenAI-Responses-API ueber das `authorization`-Feld, Cursor, mcp-remote usw.).
|
||||||
|
Die ChatGPT-App-Connectoren und strikt spec-konforme OAuth-Clients koennen das nicht; sie
|
||||||
|
brauchen OAuth mit Dynamic Client Registration. Dafuer waeren noetig:
|
||||||
|
|
||||||
|
- `registration_endpoint` (POST /register, RFC 7591) im AS-Metadata (`common.py`)
|
||||||
|
- `/.well-known/oauth-protected-resource` (RFC 9728) + passendes `WWW-Authenticate`
|
||||||
|
- Redirect-Allowlist in `oauth_authorize()` ueber claude.ai hinaus erweitern (ChatGPT-Callback)
|
||||||
|
- Consent-Schritt (aktuell Auto-Approve)
|
||||||
|
- Audience-/`resource`-Pruefung (RFC 8707)
|
||||||
|
|
||||||
|
Service-Tokens koennen parallel bestehen bleiben (Bearer-Middleware akzeptiert beides).
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT
|
MIT
|
||||||
+248
-60
@@ -1,10 +1,10 @@
|
|||||||
"""MCP Calendar + Tasks Server — reads and writes calendars and tasks via CalDAV."""
|
"""MCP Calendar + Tasks Server — reads and writes calendars and tasks via CalDAV."""
|
||||||
|
|
||||||
import os, sys, re, contextlib, uuid
|
import os, sys, re, contextlib, uuid, html
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
import httpx, vobject
|
import httpx, vobject, pytz
|
||||||
import time
|
import time
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
from mcp.server.fastmcp import FastMCP
|
from mcp.server.fastmcp import FastMCP
|
||||||
@@ -16,32 +16,54 @@ from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
|||||||
|
|
||||||
from common import load_config as _lc
|
from common import load_config as _lc
|
||||||
_cfg = _lc()
|
_cfg = _lc()
|
||||||
RADICALE = _cfg['radicale_url']
|
BAIKAL_URL = _cfg['baikal_url'] # https://baikal.slohmaier.de (Produktiv)
|
||||||
CREDS = {u: (d['username'], d['password']) for u, d in _cfg['radicale_users'].items()}
|
BAIKAL_CREDS = {u: (d['username'], d['password']) for u, d in _cfg['baikal_users'].items()}
|
||||||
CAL_PATHS = _cfg['calendar_paths']
|
CAL_PATHS = _cfg['calendar_paths'] # Baikal-Basen (aktiv)
|
||||||
|
|
||||||
|
# Alle Zeitangaben sind lokale Wanduhrzeit in Europe/Berlin. Naive Eintraege werden
|
||||||
|
# damit als TZID=Europe/Berlin geschrieben (statt floating), explizite Offsets/Z
|
||||||
|
# werden nach Berlin konvertiert. Ohne TZID liest Baikal floating-Zeiten als UTC
|
||||||
|
# (+2h Verschiebung, Bugfix 2026-09-30).
|
||||||
|
BERLIN = pytz.timezone('Europe/Berlin')
|
||||||
|
|
||||||
|
|
||||||
|
def _local(dt):
|
||||||
|
"""Naive -> Europe/Berlin lokalisieren; aware -> nach Europe/Berlin konvertieren."""
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
return BERLIN.localize(dt)
|
||||||
|
return dt.astimezone(BERLIN)
|
||||||
|
|
||||||
mcp = FastMCP("Calendar", stateless_http=True,
|
mcp = FastMCP("Calendar", stateless_http=True,
|
||||||
transport_security={"enable_dns_rebinding_protection": False})
|
transport_security={"enable_dns_rebinding_protection": False})
|
||||||
|
|
||||||
|
|
||||||
def _auth(user):
|
def _auth(user):
|
||||||
c = CREDS.get(user)
|
c = BAIKAL_CREDS.get(user)
|
||||||
return httpx.BasicAuth(c[0], c[1]) if c else None
|
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, CAL_PATHS.get(user, [])
|
||||||
|
|
||||||
def _propfind(url, auth, depth=1):
|
def _propfind(url, auth, depth=1):
|
||||||
body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:cs="urn:ietf:params:xml:ns:caldav"><d:prop><d:resourcetype/><d:displayname/><cs:supported-calendar-component-set/></d:prop></d:propfind>'
|
body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:cs="urn:ietf:params:xml:ns:caldav"><d:prop><d:resourcetype/><d:displayname/><cs:supported-calendar-component-set/></d:prop></d:propfind>'
|
||||||
return httpx.request("PROPFIND", url, content=body, auth=auth, headers={"Depth": str(depth), "Content-Type": "application/xml"}, timeout=30).text
|
return httpx.request("PROPFIND", url, content=body, auth=auth, headers={"Depth": str(depth), "Content-Type": "application/xml"}, timeout=30).text
|
||||||
|
|
||||||
def _discover(user, comp):
|
def _discover(user, comp):
|
||||||
auth = _auth(user)
|
auth = _auth(user)
|
||||||
|
url, bases = _serve(user)
|
||||||
cols = []
|
cols = []
|
||||||
for base in CAL_PATHS.get(user, []):
|
for base in bases:
|
||||||
xml = _propfind(RADICALE + base, auth)
|
xml = _propfind(url + base, auth)
|
||||||
for m in re.finditer(r'<(?:d:)?href>([^<]+)</(?:d:)?href>', xml):
|
for m in re.finditer(r'<(?:d:)?href>([^<]+)</(?:d:)?href>', xml):
|
||||||
href = m.group(1)
|
href = m.group(1)
|
||||||
if href.rstrip("/") == base.rstrip("/"): continue
|
if href.rstrip("/") == base.rstrip("/"): continue
|
||||||
|
# sabre system-collections herausfiltern
|
||||||
|
if "/inbox/" in href or "/outbox/" in href: continue
|
||||||
block = xml[m.start():xml.find("</response>", m.end())]
|
block = xml[m.start():xml.find("</response>", m.end())]
|
||||||
# Radicale returns <C:calendar/> or <CR:addressbook/> as resourcetype
|
# Baikal/res.report returns cal:calendar / card:addressbook as resourcetype
|
||||||
# Match calendar collections (both VEVENT and VTODO live in calendars)
|
# Match calendar collections (both VEVENT and VTODO live in calendars)
|
||||||
is_calendar = "calendar" in block.lower() and "addressbook" not in block.lower()
|
is_calendar = "calendar" in block.lower() and "addressbook" not in block.lower()
|
||||||
if comp in ("VEVENT", "VTODO") and not is_calendar:
|
if comp in ("VEVENT", "VTODO") and not is_calendar:
|
||||||
@@ -50,14 +72,42 @@ def _discover(user, comp):
|
|||||||
cols.append({"name": nm.group(1) if nm else href.split("/")[-2], "href": href})
|
cols.append({"name": nm.group(1) if nm else href.split("/")[-2], "href": href})
|
||||||
return cols
|
return cols
|
||||||
|
|
||||||
def _report(href, auth, start, end):
|
def _match_cols(cols, name):
|
||||||
body = f'<?xml version="1.0"?><c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><d:getetag/><c:calendar-data/></d:prop><c:filter><c:comp-filter name="VCALENDAR"><c:comp-filter name="VEVENT"><c:time-range start="{start}" end="{end}"/></c:comp-filter></c:comp-filter></c:filter></c:calendar-query>'
|
"""Priorisiere exakten Namens-Treffer, sonst Teilstring-Treffer."""
|
||||||
return httpx.request("REPORT", RADICALE + href, content=body, auth=auth, headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=30).text
|
q = name.lower()
|
||||||
|
exact = [c for c in cols if c["name"].lower() == q]
|
||||||
|
if exact:
|
||||||
|
return exact
|
||||||
|
return [c for c in cols if q in c["name"].lower()]
|
||||||
|
|
||||||
def _report_tasks(href, auth, inc=False):
|
def _report(user, href, start, end):
|
||||||
|
url, _ = _serve(user)
|
||||||
|
body = f'<?xml version="1.0"?><c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><d:getetag/><c:calendar-data/></d:prop><c:filter><c:comp-filter name="VCALENDAR"><c:comp-filter name="VEVENT"><c:time-range start="{start}" end="{end}"/></c:comp-filter></c:comp-filter></c:filter></c:calendar-query>'
|
||||||
|
return httpx.request("REPORT", url + href, content=body, auth=_auth(user), headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=30).text
|
||||||
|
|
||||||
|
def _report_tasks(user, href, inc=False):
|
||||||
|
url, _ = _serve(user)
|
||||||
filt = '<c:comp-filter name="VTODO"/>' if inc else '<c:comp-filter name="VTODO"><c:prop-filter name="STATUS"><c:text-match negate-condition="yes">COMPLETED</c:text-match></c:prop-filter></c:comp-filter>'
|
filt = '<c:comp-filter name="VTODO"/>' if inc else '<c:comp-filter name="VTODO"><c:prop-filter name="STATUS"><c:text-match negate-condition="yes">COMPLETED</c:text-match></c:prop-filter></c:comp-filter>'
|
||||||
body = f'<?xml version="1.0"?><c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><d:getetag/><c:calendar-data/></d:prop><c:filter><c:comp-filter name="VCALENDAR">{filt}</c:comp-filter></c:filter></c:calendar-query>'
|
body = f'<?xml version="1.0"?><c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><d:getetag/><c:calendar-data/></d:prop><c:filter><c:comp-filter name="VCALENDAR">{filt}</c:comp-filter></c:filter></c:calendar-query>'
|
||||||
return httpx.request("REPORT", RADICALE + href, content=body, auth=auth, headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=30).text
|
return httpx.request("REPORT", url + href, content=body, auth=_auth(user), headers={"Depth": "1", "Content-Type": "application/xml"}, timeout=30).text
|
||||||
|
|
||||||
|
|
||||||
|
def _find_href(user, cols, uid, tasks=False):
|
||||||
|
"""Echten CalDAV-Ressourcenpfad zu einer UID finden.
|
||||||
|
|
||||||
|
Der Dateiname ist NICHT immer die UID (Importe, z.B. medatixx, nutzen fremde
|
||||||
|
Dateinamen). Ohne diese Aufloesung treffen Delete/Update den falschen Pfad
|
||||||
|
(Delete laeuft ins Leere bzw. Update erzeugt ein Duplikat)."""
|
||||||
|
import html as _html
|
||||||
|
pat = re.compile(rf'^UID:{re.escape(uid)}\s*$', re.MULTILINE | re.IGNORECASE)
|
||||||
|
for col in cols:
|
||||||
|
xml = _report_tasks(user, col["href"], inc=True) if tasks else _report(user, col["href"], "20000101T000000Z", "21000101T000000Z")
|
||||||
|
for resp in re.findall(r'<(?:d:)?response>(.*?)</(?:d:)?response>', xml, re.DOTALL):
|
||||||
|
hr = re.search(r'<(?:d:)?href>([^<]+)</(?:d:)?href>', resp)
|
||||||
|
cd = re.search(r'<(?:[a-zA-Z][a-zA-Z0-9_]*):calendar-data[^>]*>(.*?)</(?:[a-zA-Z][a-zA-Z0-9_]*):calendar-data>', resp, re.DOTALL)
|
||||||
|
if hr and cd and pat.search(_html.unescape(cd.group(1))):
|
||||||
|
return hr.group(1)
|
||||||
|
return None
|
||||||
|
|
||||||
PARSE_DEADLINE_S = 12 # Wall-Clock-Limit fuer client-seitiges vobject-Parsen
|
PARSE_DEADLINE_S = 12 # Wall-Clock-Limit fuer client-seitiges vobject-Parsen
|
||||||
MAX_RESULTS = 300 # Output-Cap (sonst Token-Explosion bei tausenden Items)
|
MAX_RESULTS = 300 # Output-Cap (sonst Token-Explosion bei tausenden Items)
|
||||||
@@ -65,22 +115,29 @@ MAX_RESULTS = 300 # Output-Cap (sonst Token-Explosion bei tausenden Items)
|
|||||||
|
|
||||||
def _parse(xml, comp="VEVENT", t0=None, cap=None):
|
def _parse(xml, comp="VEVENT", t0=None, cap=None):
|
||||||
objs = []
|
objs = []
|
||||||
for m in re.finditer(r'<(?:c|C):calendar-data[^>]*>(.*?)</(?:c|C):calendar-data>', xml, re.DOTALL):
|
for m in re.finditer(r'<(?:[a-zA-Z][a-zA-Z0-9_]*):calendar-data[^>]*>(.*?)</(?:[a-zA-Z][a-zA-Z0-9_]*):calendar-data>', xml, re.DOTALL):
|
||||||
if cap is not None and len(objs) >= cap: break
|
if cap is not None and len(objs) >= cap: break
|
||||||
if t0 is not None and (time.monotonic() - t0) > PARSE_DEADLINE_S: break
|
if t0 is not None and (time.monotonic() - t0) > PARSE_DEADLINE_S: break
|
||||||
raw = m.group(1).replace("<","<").replace(">",">").replace("&","&")
|
raw = html.unescape(m.group(1))
|
||||||
try:
|
try:
|
||||||
for c in vobject.readOne(raw).components():
|
for c in vobject.readOne(raw).components():
|
||||||
if c.name == comp: objs.append(c)
|
if c.name == comp: objs.append(c)
|
||||||
except: pass
|
except: pass
|
||||||
return objs
|
return objs
|
||||||
|
|
||||||
|
def _fmt_dt(v):
|
||||||
|
"""Datetime einheitlich in Europe/Berlin darstellen (naive = lokale Wanduhrzeit)."""
|
||||||
|
if isinstance(v, datetime):
|
||||||
|
return _local(v).isoformat()
|
||||||
|
return v.isoformat() if hasattr(v, 'isoformat') else str(v)
|
||||||
|
|
||||||
|
|
||||||
def _fmt_ev(ev, cal=""):
|
def _fmt_ev(ev, cal=""):
|
||||||
s = getattr(ev, 'dtstart', None)
|
s = getattr(ev, 'dtstart', None)
|
||||||
e = getattr(ev, 'dtend', None)
|
e = getattr(ev, 'dtend', None)
|
||||||
summary = str(ev.summary.value) if hasattr(ev, 'summary') else '(kein Titel)'
|
summary = str(ev.summary.value) if hasattr(ev, 'summary') else '(kein Titel)'
|
||||||
start = s.value.isoformat() if s and hasattr(s.value, 'isoformat') else str(s.value) if s else '?'
|
start = _fmt_dt(s.value) if s else '?'
|
||||||
end_s = e.value.isoformat() if e and hasattr(e.value, 'isoformat') else ''
|
end_s = _fmt_dt(e.value) if e else ''
|
||||||
loc = str(ev.location.value) if hasattr(ev, 'location') and ev.location.value else ''
|
loc = str(ev.location.value) if hasattr(ev, 'location') and ev.location.value else ''
|
||||||
desc = str(ev.description.value)[:300] if hasattr(ev, 'description') and ev.description.value else ''
|
desc = str(ev.description.value)[:300] if hasattr(ev, 'description') and ev.description.value else ''
|
||||||
uid = str(ev.uid.value) if hasattr(ev, 'uid') else ''
|
uid = str(ev.uid.value) if hasattr(ev, 'uid') else ''
|
||||||
@@ -99,6 +156,15 @@ def _fmt_ev(ev, cal=""):
|
|||||||
if status: parts.append(f" Status: {status}")
|
if status: parts.append(f" Status: {status}")
|
||||||
if attendees: parts.append(f" Teilnehmer: {', '.join(attendees[:8])}")
|
if attendees: parts.append(f" Teilnehmer: {', '.join(attendees[:8])}")
|
||||||
if rrule: parts.append(f" Wiederholung: {rrule}")
|
if rrule: parts.append(f" Wiederholung: {rrule}")
|
||||||
|
travel_parts = []
|
||||||
|
if hasattr(ev, 'x_apple_travel_duration') and ev.x_apple_travel_duration.value:
|
||||||
|
travel_parts.append(f"Fahrzeit {ev.x_apple_travel_duration.value}")
|
||||||
|
if hasattr(ev, 'x_apple_travel_mode') and ev.x_apple_travel_mode.value:
|
||||||
|
travel_parts.append(f"Verkehrsmittel {ev.x_apple_travel_mode.value}")
|
||||||
|
if hasattr(ev, 'x_apple_travel_advisory_behavior') and ev.x_apple_travel_advisory_behavior.value:
|
||||||
|
travel_parts.append("Reisezeit aus Route")
|
||||||
|
if travel_parts:
|
||||||
|
parts.append(" " + ", ".join(travel_parts))
|
||||||
parts.append(f" UID: {uid}")
|
parts.append(f" UID: {uid}")
|
||||||
return "\n".join(parts)
|
return "\n".join(parts)
|
||||||
|
|
||||||
@@ -143,7 +209,7 @@ def get_events(
|
|||||||
t0 = time.monotonic()
|
t0 = time.monotonic()
|
||||||
results = []
|
results = []
|
||||||
for cal in cals:
|
for cal in cals:
|
||||||
for ev in _parse(_report(cal["href"], _auth(user), s, e), "VEVENT", t0=t0, cap=MAX_RESULTS - len(results)):
|
for ev in _parse(_report(user, cal["href"], s, e), "VEVENT", t0=t0, cap=MAX_RESULTS - len(results)):
|
||||||
results.append(_fmt_ev(ev, cal["name"]))
|
results.append(_fmt_ev(ev, cal["name"]))
|
||||||
if len(results) >= MAX_RESULTS or (time.monotonic() - t0) > PARSE_DEADLINE_S: break
|
if len(results) >= MAX_RESULTS or (time.monotonic() - t0) > PARSE_DEADLINE_S: break
|
||||||
out = "\n\n".join(results) if results else "Keine Termine in diesem Zeitraum"
|
out = "\n\n".join(results) if results else "Keine Termine in diesem Zeitraum"
|
||||||
@@ -170,7 +236,7 @@ def search_events(
|
|||||||
results = []
|
results = []
|
||||||
truncated = False
|
truncated = False
|
||||||
for cal in _discover(user, "VEVENT"):
|
for cal in _discover(user, "VEVENT"):
|
||||||
for ev in _parse(_report(cal["href"], _auth(user), s, e), "VEVENT", t0=t0):
|
for ev in _parse(_report(user, cal["href"], s, e), "VEVENT", t0=t0):
|
||||||
txt = f"{ev.summary.value if hasattr(ev,'summary') else ''} {ev.description.value if hasattr(ev,'description') else ''} {ev.location.value if hasattr(ev,'location') else ''}".lower()
|
txt = f"{ev.summary.value if hasattr(ev,'summary') else ''} {ev.description.value if hasattr(ev,'description') else ''} {ev.location.value if hasattr(ev,'location') else ''}".lower()
|
||||||
if q in txt:
|
if q in txt:
|
||||||
results.append(_fmt_ev(ev, cal["name"]))
|
results.append(_fmt_ev(ev, cal["name"]))
|
||||||
@@ -204,7 +270,7 @@ def get_tasks(
|
|||||||
t0 = time.monotonic()
|
t0 = time.monotonic()
|
||||||
results = []
|
results = []
|
||||||
for lst in lists:
|
for lst in lists:
|
||||||
for t in _parse(_report_tasks(lst["href"], _auth(user), include_completed), "VTODO", t0=t0, cap=MAX_RESULTS - len(results)):
|
for t in _parse(_report_tasks(user, lst["href"], include_completed), "VTODO", t0=t0, cap=MAX_RESULTS - len(results)):
|
||||||
results.append(_fmt_task(t, lst["name"]))
|
results.append(_fmt_task(t, lst["name"]))
|
||||||
if len(results) >= MAX_RESULTS or (time.monotonic() - t0) > PARSE_DEADLINE_S: break
|
if len(results) >= MAX_RESULTS or (time.monotonic() - t0) > PARSE_DEADLINE_S: break
|
||||||
out = "\n\n".join(results) if results else "Keine Aufgaben"
|
out = "\n\n".join(results) if results else "Keine Aufgaben"
|
||||||
@@ -227,34 +293,19 @@ def _geocode(address):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@mcp.tool()
|
TRAVEL_MODES = ("walking", "driving", "transit", "biking")
|
||||||
def create_event(
|
|
||||||
calendar: Annotated[str, Field(description="Calendar name, e.g. 'Stefan', 'Arbeit', 'Familie'")],
|
|
||||||
title: Annotated[str, Field(description="Event title")],
|
def _build_vevent_fields(ev, title, start, end, location, description, allday,
|
||||||
start: Annotated[str, Field(description="Start: YYYY-MM-DD for all-day, or YYYY-MM-DDTHH:MM for timed events, e.g. '2026-06-15T14:00'")],
|
travel_minutes, travel_mode, travel_advisory, reminder_minutes):
|
||||||
end: Annotated[str, Field(description="End: YYYY-MM-DD for all-day, or YYYY-MM-DDTHH:MM, e.g. '2026-06-15T15:30'")],
|
"""Setzt VEVENT-Felder auf ein vobject-Element (wiederverwendet von create/update)."""
|
||||||
location: Annotated[str, Field(description="Location or address, e.g. 'Marienplatz 1, Muenchen'. Gets geocoded for map display.")] = "",
|
|
||||||
description: Annotated[str, Field(description="Event description or notes")] = "",
|
|
||||||
allday: Annotated[bool, Field(description="True for all-day events (then use YYYY-MM-DD for start/end)")] = False,
|
|
||||||
travel_minutes: Annotated[int, Field(description="Travel time in minutes shown before the event on iPhone (0=none, e.g. 30 for 30 min commute)")] = 0,
|
|
||||||
reminder_minutes: Annotated[int, Field(description="Reminder alert X minutes before the event (0=none, e.g. 15, 30, 60)")] = 0,
|
|
||||||
) -> str:
|
|
||||||
"""Create a new calendar event. For all-day events, end date is exclusive (June 15 only → start=2026-06-15, end=2026-06-16). Location is geocoded for map pins. Travel time shows as block before the event on iPhone."""
|
|
||||||
user = get_current_user()
|
|
||||||
if not user: return "Error: not authenticated"
|
|
||||||
cals = [c for c in _discover(user, "VEVENT") if calendar.lower() in c["name"].lower()]
|
|
||||||
if not cals: return f"Kalender '{calendar}' nicht gefunden"
|
|
||||||
uid = str(uuid.uuid4())
|
|
||||||
cal = vobject.iCalendar()
|
|
||||||
ev = cal.add("vevent")
|
|
||||||
ev.add("uid").value = uid
|
|
||||||
ev.add("summary").value = title
|
ev.add("summary").value = title
|
||||||
if allday:
|
if allday:
|
||||||
ev.add("dtstart").value = datetime.strptime(start, "%Y-%m-%d").date()
|
ev.add("dtstart").value = datetime.strptime(start, "%Y-%m-%d").date()
|
||||||
ev.add("dtend").value = datetime.strptime(end, "%Y-%m-%d").date()
|
ev.add("dtend").value = datetime.strptime(end, "%Y-%m-%d").date()
|
||||||
else:
|
else:
|
||||||
ev.add("dtstart").value = datetime.fromisoformat(start)
|
ev.add("dtstart").value = _local(datetime.fromisoformat(start))
|
||||||
ev.add("dtend").value = datetime.fromisoformat(end)
|
ev.add("dtend").value = _local(datetime.fromisoformat(end))
|
||||||
if location:
|
if location:
|
||||||
ev.add("location").value = location
|
ev.add("location").value = location
|
||||||
geo = _geocode(location)
|
geo = _geocode(location)
|
||||||
@@ -266,25 +317,126 @@ def create_event(
|
|||||||
loc_prop.params["X-APPLE-RADIUS"] = ["70"]
|
loc_prop.params["X-APPLE-RADIUS"] = ["70"]
|
||||||
loc_prop.params["X-APPLE-REFERENCEFRAME"] = ["1"]
|
loc_prop.params["X-APPLE-REFERENCEFRAME"] = ["1"]
|
||||||
loc_prop.params["X-TITLE"] = [location]
|
loc_prop.params["X-TITLE"] = [location]
|
||||||
|
if travel_advisory:
|
||||||
|
# Apple Kalender berechnet die Reise-Erinnerung dann selbst aus der Route.
|
||||||
|
ev.add("x-apple-travel-advisory-behavior").value = "AUTOMATIC"
|
||||||
if description:
|
if description:
|
||||||
ev.add("description").value = description
|
ev.add("description").value = description
|
||||||
if travel_minutes > 0:
|
if travel_minutes > 0:
|
||||||
tp = ev.add("x-apple-travel-duration")
|
tp = ev.add("x-apple-travel-duration")
|
||||||
tp.value = f"PT{travel_minutes}M"
|
tp.value = f"PT{travel_minutes}M"
|
||||||
tp.params["VALUE"] = ["DURATION"]
|
tp.params["VALUE"] = ["DURATION"]
|
||||||
|
if travel_mode and travel_mode in TRAVEL_MODES:
|
||||||
|
md = ev.add("x-apple-travel-mode")
|
||||||
|
md.value = travel_mode.upper()
|
||||||
if reminder_minutes > 0:
|
if reminder_minutes > 0:
|
||||||
alarm = ev.add("valarm")
|
alarm = ev.add("valarm")
|
||||||
alarm.add("action").value = "DISPLAY"
|
alarm.add("action").value = "DISPLAY"
|
||||||
alarm.add("description").value = title
|
alarm.add("description").value = title
|
||||||
alarm.add("trigger").value = timedelta(minutes=-reminder_minutes)
|
alarm.add("trigger").value = timedelta(minutes=-reminder_minutes)
|
||||||
ev.add("dtstamp").value = datetime.utcnow()
|
ev.add("dtstamp").value = datetime.utcnow()
|
||||||
r = httpx.put(RADICALE + cals[0]["href"] + uid + ".ics", content=cal.serialize(), auth=_auth(user), headers={"Content-Type": "text/calendar"}, timeout=15)
|
|
||||||
|
|
||||||
|
def _write_event(user, cals, title, start, end, location, description, allday,
|
||||||
|
travel_minutes, travel_mode, travel_advisory, reminder_minutes,
|
||||||
|
uid=None, verb="Termin erstellt"):
|
||||||
|
cal = vobject.iCalendar()
|
||||||
|
ev = cal.add("vevent")
|
||||||
|
if uid:
|
||||||
|
target = _find_href(user, cals, uid) or (cals[0]["href"] + uid + ".ics")
|
||||||
|
else:
|
||||||
|
uid = str(uuid.uuid4())
|
||||||
|
target = cals[0]["href"] + uid + ".ics"
|
||||||
|
ev.add("uid").value = uid
|
||||||
|
_build_vevent_fields(ev, title, start, end, location, description, allday,
|
||||||
|
travel_minutes, travel_mode, travel_advisory, reminder_minutes)
|
||||||
|
r = httpx.put(_serve(user)[0] + target,
|
||||||
|
content=cal.serialize(), auth=_auth(user),
|
||||||
|
headers={"Content-Type": "text/calendar"}, timeout=15)
|
||||||
extras = []
|
extras = []
|
||||||
if location and _geocode(location): extras.append("mit Karte")
|
if location and _geocode(location): extras.append("mit Karte")
|
||||||
if travel_minutes: extras.append(f"{travel_minutes} Min. Fahrzeit")
|
if travel_minutes: extras.append(f"{travel_minutes} Min. Fahrzeit")
|
||||||
|
if travel_mode: extras.append(f"Verkehrsmittel {travel_mode}")
|
||||||
|
if travel_advisory: extras.append("Reisezeit aus Route")
|
||||||
if reminder_minutes: extras.append(f"Erinnerung {reminder_minutes} Min. vorher")
|
if reminder_minutes: extras.append(f"Erinnerung {reminder_minutes} Min. vorher")
|
||||||
extra_str = f" ({', '.join(extras)})" if extras else ""
|
extra_str = f" ({', '.join(extras)})" if extras else ""
|
||||||
return f"Termin erstellt: {title} am {start}{extra_str}" if r.status_code in (201, 204) else f"Fehler: HTTP {r.status_code}"
|
if r.status_code in (201, 204):
|
||||||
|
return f"{verb}: {title} am {start}{extra_str}"
|
||||||
|
if r.status_code in (200,) and uid:
|
||||||
|
return f"{verb}: {title} am {start}{extra_str}"
|
||||||
|
return f"Fehler: HTTP {r.status_code}"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def create_event(
|
||||||
|
calendar: Annotated[str, Field(description="Calendar name, e.g. 'Stefan', 'Arbeit', 'Familie'")],
|
||||||
|
title: Annotated[str, Field(description="Event title")],
|
||||||
|
start: Annotated[str, Field(description="Start: YYYY-MM-DD for all-day, or YYYY-MM-DDTHH:MM for timed events, e.g. '2026-06-15T14:00'. Lokale Zeit Europe/Berlin; explizite Offsets/Z werden konvertiert.")],
|
||||||
|
end: Annotated[str, Field(description="End: YYYY-MM-DD for all-day, or YYYY-MM-DDTHH:MM, e.g. '2026-06-15T15:30'. Lokale Zeit Europe/Berlin.")],
|
||||||
|
location: Annotated[str, Field(description="Location/Ziel als Text oder POI, e.g. 'Marienplatz 1, Muenchen'. Gets geocoded for map / POI.")] = "",
|
||||||
|
description: Annotated[str, Field(description="Event description or notes")] = "",
|
||||||
|
allday: Annotated[bool, Field(description="True for all-day events (then use YYYY-MM-DD for start/end)")] = False,
|
||||||
|
travel_minutes: Annotated[int, Field(description="Feste Reisezeit in Minuten vor dem Termin (0=none). Apple nutzt ihn als Anzeige-Block vor dem Event.")] = 0,
|
||||||
|
travel_mode: Annotated[str, Field(description="Optional. Verkehrsmittel fuer die Reise: walking, driving, transit, biking. Leer lassen, wenn nicht relevant.")] = "",
|
||||||
|
travel_advisory: Annotated[bool, Field(description="True: Apple Kalender berechnet die Reise-Erinnerungszeit selbst dynamisch aus der aktuellen Route anhand des Ziels (location). Empfohlen fuer Termine mit Zieladresse.")] = False,
|
||||||
|
reminder_minutes: Annotated[int, Field(description="Reminder alert X minutes before the event (0=none, e.g. 15, 30, 60)")] = 0,
|
||||||
|
) -> str:
|
||||||
|
"""Create a new calendar event. For all-day events, end date is exclusive (June 15 only → start=2026-06-15, end=2026-06-16). Timed events werden als Europe/Berlin (TZID) gespeichert. Location/Ziel wird geocoded (POI/Karte). Mit travel_advisory=true + Ziel berechnet Apple die Reise-Erinnerung dynamisch aus der Route."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
cals = _match_cols(_discover(user, "VEVENT"), calendar)
|
||||||
|
if not cals: return f"Kalender '{calendar}' nicht gefunden"
|
||||||
|
return _write_event(user, cals, title, start, end, location, description, allday,
|
||||||
|
travel_minutes, travel_mode, travel_advisory, reminder_minutes,
|
||||||
|
verb="Termin erstellt")
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def update_event(
|
||||||
|
calendar: Annotated[str, Field(description="Calendar name, e.g. 'Stefan', 'Arbeit', 'Familie'. Partial match.")],
|
||||||
|
uid: Annotated[str, Field(description="UID of the event to update (from get_events / search_events output).")],
|
||||||
|
title: Annotated[str, Field(description="Event title")],
|
||||||
|
start: Annotated[str, Field(description="Start: YYYY-MM-DD for all-day, or YYYY-MM-DDTHH:MM")],
|
||||||
|
end: Annotated[str, Field(description="End: YYYY-MM-DD for all-day, or YYYY-MM-DDTHH:MM")],
|
||||||
|
location: Annotated[str, Field(description="Location/Ziel als Text oder POI. Gets geocoded.")] = "",
|
||||||
|
description: Annotated[str, Field(description="Event description or notes")] = "",
|
||||||
|
allday: Annotated[bool, Field(description="True for all-day events")] = False,
|
||||||
|
travel_minutes: Annotated[int, Field(description="Feste Reisezeit in Minuten vor dem Termin (0=none)")] = 0,
|
||||||
|
travel_mode: Annotated[str, Field(description="Optional. Verkehrsmittel: walking, driving, transit, biking.")] = "",
|
||||||
|
travel_advisory: Annotated[bool, Field(description="True: Apple berechnet die Reise-Erinnerungszeit dynamisch aus der Route anhand des Ziels.")] = False,
|
||||||
|
reminder_minutes: Annotated[int, Field(description="Reminder alert X minutes before the event (0=none)")] = 0,
|
||||||
|
) -> str:
|
||||||
|
"""Update an existing calendar event (full overwrite of its fields). All optional fields default to clearing the previous value."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
cals = _match_cols(_discover(user, "VEVENT"), calendar)
|
||||||
|
if not cals: return f"Kalender '{calendar}' nicht gefunden"
|
||||||
|
return _write_event(user, cals, title, start, end, location, description, allday,
|
||||||
|
travel_minutes, travel_mode, travel_advisory, reminder_minutes,
|
||||||
|
uid=uid, verb="Termin aktualisiert")
|
||||||
|
|
||||||
|
|
||||||
|
def _write_task(user, lists, title, due, priority, description, uid=None, verb="Aufgabe erstellt"):
|
||||||
|
cal = vobject.iCalendar()
|
||||||
|
todo = cal.add("vtodo")
|
||||||
|
if uid:
|
||||||
|
target = _find_href(user, lists, uid, tasks=True) or (lists[0]["href"] + uid + ".ics")
|
||||||
|
else:
|
||||||
|
uid = str(uuid.uuid4())
|
||||||
|
target = lists[0]["href"] + uid + ".ics"
|
||||||
|
todo.add("uid").value = uid
|
||||||
|
todo.add("summary").value = title
|
||||||
|
todo.add("status").value = "NEEDS-ACTION"
|
||||||
|
if due: todo.add("due").value = _local(datetime.fromisoformat(due)) if "T" in due else datetime.strptime(due, "%Y-%m-%d").date()
|
||||||
|
if priority: todo.add("priority").value = str(priority)
|
||||||
|
if description: todo.add("description").value = description
|
||||||
|
todo.add("dtstamp").value = datetime.utcnow()
|
||||||
|
r = httpx.put(_serve(user)[0] + target, content=cal.serialize(), auth=_auth(user), headers={"Content-Type": "text/calendar"}, timeout=15)
|
||||||
|
if r.status_code in (201, 204):
|
||||||
|
return f"{verb}: {title}"
|
||||||
|
if r.status_code in (200,):
|
||||||
|
return f"{verb}: {title}"
|
||||||
|
return f"Fehler: HTTP {r.status_code}"
|
||||||
|
|
||||||
|
|
||||||
@mcp.tool()
|
@mcp.tool()
|
||||||
@@ -298,20 +450,56 @@ def create_task(
|
|||||||
"""Create a new task/reminder in the specified list."""
|
"""Create a new task/reminder in the specified list."""
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user: return "Error: not authenticated"
|
if not user: return "Error: not authenticated"
|
||||||
lists = [l for l in _discover(user, "VTODO") if task_list.lower() in l["name"].lower()]
|
lists = _match_cols(_discover(user, "VTODO"), task_list)
|
||||||
if not lists: return f"Liste '{task_list}' nicht gefunden"
|
if not lists: return f"Liste '{task_list}' nicht gefunden"
|
||||||
uid = str(uuid.uuid4())
|
return _write_task(user, lists, title, due, priority, description, verb="Aufgabe erstellt")
|
||||||
cal = vobject.iCalendar()
|
|
||||||
todo = cal.add("vtodo")
|
|
||||||
todo.add("uid").value = uid
|
@mcp.tool()
|
||||||
todo.add("summary").value = title
|
def update_task(
|
||||||
todo.add("status").value = "NEEDS-ACTION"
|
task_list: Annotated[str, Field(description="Task list name, e.g. 'Erinnerungen', 'Langzeiterinnerungen'. Partial match.")],
|
||||||
if due: todo.add("due").value = datetime.fromisoformat(due) if "T" in due else datetime.strptime(due, "%Y-%m-%d").date()
|
uid: Annotated[str, Field(description="UID of the task to update (from get_tasks output).")],
|
||||||
if priority: todo.add("priority").value = str(priority)
|
title: Annotated[str, Field(description="Task title")],
|
||||||
if description: todo.add("description").value = description
|
due: Annotated[str, Field(description="Due date: YYYY-MM-DD or YYYY-MM-DDTHH:MM. Leave empty for no due date.")] = "",
|
||||||
todo.add("dtstamp").value = datetime.utcnow()
|
priority: Annotated[int, Field(description="Priority 1-9 (1=highest, 9=lowest, 0=none)")] = 0,
|
||||||
r = httpx.put(RADICALE + lists[0]["href"] + uid + ".ics", content=cal.serialize(), auth=_auth(user), headers={"Content-Type": "text/calendar"}, timeout=15)
|
description: Annotated[str, Field(description="Task notes")] = "",
|
||||||
return f"Aufgabe erstellt: {title}" if r.status_code in (201, 204) else f"Fehler: HTTP {r.status_code}"
|
) -> str:
|
||||||
|
"""Update an existing task/reminder (full overwrite of its fields) in the specified list."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
lists = _match_cols(_discover(user, "VTODO"), task_list)
|
||||||
|
if not lists: return f"Liste '{task_list}' nicht gefunden"
|
||||||
|
return _write_task(user, lists, title, due, priority, description, uid=uid, verb="Aufgabe aktualisiert")
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def delete_event(
|
||||||
|
calendar: Annotated[str, Field(description="Calendar name from list_calendars, e.g. 'Stefan', 'Arbeit', 'Familie'. Use partial match.")],
|
||||||
|
uid: Annotated[str, Field(description="UID of the event to delete (from get_events / search_events output).")],
|
||||||
|
) -> str:
|
||||||
|
"""Delete an existing calendar event by its UID. Get the UID via get_events or search_events first."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
cals = _match_cols(_discover(user, "VEVENT"), calendar)
|
||||||
|
if not cals: return f"Kalender '{calendar}' nicht gefunden"
|
||||||
|
href = _find_href(user, cals, uid) or (cals[0]["href"] + uid + ".ics")
|
||||||
|
r = httpx.request("DELETE", _serve(user)[0] + href, auth=_auth(user), timeout=15)
|
||||||
|
return f"Termin geloescht (UID {uid})" if r.status_code in (200, 204, 404) else f"Fehler: HTTP {r.status_code}"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def delete_task(
|
||||||
|
task_list: Annotated[str, Field(description="Task list name, e.g. 'Erinnerungen', 'Langzeiterinnerungen'. Use partial match.")],
|
||||||
|
uid: Annotated[str, Field(description="UID of the task to delete (from get_tasks output).")],
|
||||||
|
) -> str:
|
||||||
|
"""Delete an existing task/reminder by its UID. Get the UID via get_tasks first."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
lists = _match_cols(_discover(user, "VTODO"), task_list)
|
||||||
|
if not lists: return f"Liste '{task_list}' nicht gefunden"
|
||||||
|
href = _find_href(user, lists, uid, tasks=True) or (lists[0]["href"] + uid + ".ics")
|
||||||
|
r = httpx.request("DELETE", _serve(user)[0] + href, auth=_auth(user), timeout=15)
|
||||||
|
return f"Aufgabe geloescht (UID {uid})" if r.status_code in (200, 204, 404) else f"Fehler: HTTP {r.status_code}"
|
||||||
|
|
||||||
|
|
||||||
def create_app():
|
def create_app():
|
||||||
@@ -329,4 +517,4 @@ def create_app():
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(create_app(), host="127.0.0.1", port=5101)
|
uvicorn.run(create_app(), host="0.0.0.0", port=5101)
|
||||||
@@ -4,6 +4,12 @@ Supports OAuth 2.0 Authorization Code flow with PKCE (for claude.ai):
|
|||||||
1. GET /authorize → auto-approves if client_id+client_secret valid, redirects with code
|
1. GET /authorize → auto-approves if client_id+client_secret valid, redirects with code
|
||||||
2. POST /token grant_type=authorization_code → exchanges code for access_token
|
2. POST /token grant_type=authorization_code → exchanges code for access_token
|
||||||
3. Bearer access_token on MCP requests
|
3. Bearer access_token on MCP requests
|
||||||
|
|
||||||
|
Zusaetzlich nicht-ablaufende Service-Tokens (service_tokens.json) fuer
|
||||||
|
Maschinen-Clients (opencode, OpenClaw), die einen statischen Authorization-
|
||||||
|
Bearer-Header setzen. Format: {"<token>": {"user": "stefan", "label": "opencode-polo"}}.
|
||||||
|
Ein Service-Token wird in _resolve_access_token() vor den OAuth-Access-Tokens
|
||||||
|
geprueft und laeuft nie ab; Widerruf durch Entfernen aus der Datei.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -23,7 +29,7 @@ from starlette.middleware.base import BaseHTTPMiddleware
|
|||||||
BASE_DIR = os.path.dirname(__file__)
|
BASE_DIR = os.path.dirname(__file__)
|
||||||
TOKENS_FILE = os.path.join(BASE_DIR, "tokens.json")
|
TOKENS_FILE = os.path.join(BASE_DIR, "tokens.json")
|
||||||
CONFIG_FILE = os.path.join(BASE_DIR, "config.json")
|
CONFIG_FILE = os.path.join(BASE_DIR, "config.json")
|
||||||
VALID_USERS = ["stefan", "kati", "test"]
|
VALID_USERS = ["stefan", "kati", "test", "nova"]
|
||||||
|
|
||||||
_config_cache = None
|
_config_cache = None
|
||||||
|
|
||||||
@@ -37,6 +43,7 @@ def load_config():
|
|||||||
_tokens_cache = None
|
_tokens_cache = None
|
||||||
_current_user: contextvars.ContextVar[str | None] = contextvars.ContextVar("current_user", default=None)
|
_current_user: contextvars.ContextVar[str | None] = contextvars.ContextVar("current_user", default=None)
|
||||||
_TOKEN_STORE = os.path.join(BASE_DIR, ".active_tokens.json")
|
_TOKEN_STORE = os.path.join(BASE_DIR, ".active_tokens.json")
|
||||||
|
_SERVICE_TOKENS_FILE = os.path.join(BASE_DIR, "service_tokens.json")
|
||||||
_auth_codes: dict[str, dict] = {}
|
_auth_codes: dict[str, dict] = {}
|
||||||
|
|
||||||
|
|
||||||
@@ -53,6 +60,15 @@ def _save_access_tokens(tokens):
|
|||||||
json.dump(tokens, f)
|
json.dump(tokens, f)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_service_tokens():
|
||||||
|
try:
|
||||||
|
with open(_SERVICE_TOKENS_FILE) as f:
|
||||||
|
data = json.load(f)
|
||||||
|
except (FileNotFoundError, json.JSONDecodeError):
|
||||||
|
return {}
|
||||||
|
return data if isinstance(data, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
def _load_tokens():
|
def _load_tokens():
|
||||||
global _tokens_cache
|
global _tokens_cache
|
||||||
if _tokens_cache is None:
|
if _tokens_cache is None:
|
||||||
@@ -81,6 +97,10 @@ def _resolve_client(client_id, client_secret):
|
|||||||
|
|
||||||
|
|
||||||
def _resolve_access_token(token):
|
def _resolve_access_token(token):
|
||||||
|
# Nicht-ablaufende Service-Tokens zuerst (konstanter Vergleich).
|
||||||
|
for stored, info in _load_service_tokens().items():
|
||||||
|
if secrets.compare_digest(stored, token):
|
||||||
|
return info.get("user") if isinstance(info, dict) else info
|
||||||
tokens = _load_access_tokens()
|
tokens = _load_access_tokens()
|
||||||
info = tokens.get(token)
|
info = tokens.get(token)
|
||||||
if not info:
|
if not info:
|
||||||
|
|||||||
+38
-1
@@ -1,4 +1,15 @@
|
|||||||
{
|
{
|
||||||
|
"baikal_url": "https://baikal.slohmaier.de",
|
||||||
|
"baikal_users": {
|
||||||
|
"stefan": {
|
||||||
|
"username": "stefan",
|
||||||
|
"password": "CHANGE_ME"
|
||||||
|
},
|
||||||
|
"kati": {
|
||||||
|
"username": "kati",
|
||||||
|
"password": "CHANGE_ME"
|
||||||
|
}
|
||||||
|
},
|
||||||
"radicale_url": "http://127.0.0.1:5232",
|
"radicale_url": "http://127.0.0.1:5232",
|
||||||
"radicale_users": {
|
"radicale_users": {
|
||||||
"stefan": {
|
"stefan": {
|
||||||
@@ -8,6 +19,10 @@
|
|||||||
"kati": {
|
"kati": {
|
||||||
"username": "kati",
|
"username": "kati",
|
||||||
"password": "CHANGE_ME"
|
"password": "CHANGE_ME"
|
||||||
|
},
|
||||||
|
"mcptest": {
|
||||||
|
"username": "mcptest",
|
||||||
|
"password": "CHANGE_ME"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"ocis_url": "http://127.0.0.1:9200",
|
"ocis_url": "http://127.0.0.1:9200",
|
||||||
@@ -31,6 +46,22 @@
|
|||||||
"kati": "/mnt/ssd/Backup/kati/imap"
|
"kati": "/mnt/ssd/Backup/kati/imap"
|
||||||
},
|
},
|
||||||
"calendar_paths": {
|
"calendar_paths": {
|
||||||
|
"stefan": [
|
||||||
|
"/dav.php/calendars/stefan/"
|
||||||
|
],
|
||||||
|
"kati": [
|
||||||
|
"/dav.php/calendars/kati/"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"addressbook_paths": {
|
||||||
|
"stefan": [
|
||||||
|
"/dav.php/addressbooks/stefan/"
|
||||||
|
],
|
||||||
|
"kati": [
|
||||||
|
"/dav.php/addressbooks/kati/"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"radicale_calendar_paths": {
|
||||||
"stefan": [
|
"stefan": [
|
||||||
"/stefan/",
|
"/stefan/",
|
||||||
"/shared/"
|
"/shared/"
|
||||||
@@ -38,14 +69,20 @@
|
|||||||
"kati": [
|
"kati": [
|
||||||
"/kati/",
|
"/kati/",
|
||||||
"/shared/"
|
"/shared/"
|
||||||
|
],
|
||||||
|
"mcptest": [
|
||||||
|
"/mcptest/"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"addressbook_paths": {
|
"radicale_addressbook_paths": {
|
||||||
"stefan": [
|
"stefan": [
|
||||||
"/stefan/"
|
"/stefan/"
|
||||||
],
|
],
|
||||||
"kati": [
|
"kati": [
|
||||||
"/kati/"
|
"/kati/"
|
||||||
|
],
|
||||||
|
"mcptest": [
|
||||||
|
"/mcptest/"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"joplin_data_api": {
|
"joplin_data_api": {
|
||||||
|
|||||||
+148
-18
@@ -1,6 +1,7 @@
|
|||||||
"""MCP Contacts Server — reads and writes contacts via CardDAV."""
|
"""MCP Contacts Server — reads and writes contacts via CardDAV."""
|
||||||
|
|
||||||
import os, sys, re, contextlib, uuid, base64
|
import os, sys, re, contextlib, uuid, base64
|
||||||
|
import html
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
import httpx, vobject
|
import httpx, vobject
|
||||||
@@ -9,30 +10,41 @@ from pydantic import Field
|
|||||||
from mcp.server.fastmcp import FastMCP
|
from mcp.server.fastmcp import FastMCP
|
||||||
from mcp.types import TextContent, ImageContent
|
from mcp.types import TextContent, ImageContent
|
||||||
from starlette.applications import Starlette
|
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__)))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
||||||
|
|
||||||
from common import load_config as _lc
|
from common import load_config as _lc
|
||||||
_cfg = _lc()
|
_cfg = _lc()
|
||||||
RADICALE = _cfg['radicale_url']
|
BAIKAL_URL = _cfg['baikal_url'] # https://baikal.slohmaier.de (Produktiv)
|
||||||
CREDS = {u: (d['username'], d['password']) for u, d in _cfg['radicale_users'].items()}
|
BAIKAL_CREDS = {u: (d['username'], d['password']) for u, d in _cfg['baikal_users'].items()}
|
||||||
AB_PATHS = _cfg['addressbook_paths']
|
AB_PATHS = _cfg['addressbook_paths'] # Baikal-Basen (aktiv)
|
||||||
|
|
||||||
mcp = FastMCP("Contacts", stateless_http=True,
|
mcp = FastMCP("Contacts", stateless_http=True,
|
||||||
transport_security={"enable_dns_rebinding_protection": False})
|
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):
|
def _discover_ab(user):
|
||||||
books = []
|
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>'
|
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):
|
for m in re.finditer(r'<(?:d:)?href>([^<]+)</(?:d:)?href>', r.text):
|
||||||
href = m.group(1)
|
href = m.group(1)
|
||||||
if href.rstrip("/") == base.rstrip("/"): continue
|
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())]
|
block = r.text[m.start():r.text.find("</response>", m.end())]
|
||||||
if "addressbook" not in block.lower(): continue
|
if "addressbook" not in block.lower(): continue
|
||||||
nm = re.search(r'<(?:d:)?displayname>([^<]*)</(?:d:)?displayname>', block)
|
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
|
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>'
|
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 = []
|
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
|
if t0 is not None and (time.monotonic() - t0) > PARSE_DEADLINE_S: break
|
||||||
raw = m.group(1).replace("<","<").replace(">",">").replace("&","&")
|
raw = html.unescape(m.group(1))
|
||||||
try: contacts.append(vobject.readOne(raw))
|
try: contacts.append(vobject.readOne(raw))
|
||||||
except: pass
|
except: pass
|
||||||
return contacts
|
return contacts
|
||||||
@@ -107,7 +120,7 @@ def search_contacts(
|
|||||||
results = []
|
results = []
|
||||||
truncated = False
|
truncated = False
|
||||||
for book in _discover_ab(user):
|
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()
|
txt = " ".join(str(getattr(c, a, None) or '') for a in ['fn','email','tel','org','note','nickname']).lower()
|
||||||
if q in txt:
|
if q in txt:
|
||||||
results.append(_brief(c))
|
results.append(_brief(c))
|
||||||
@@ -145,7 +158,7 @@ def get_contact(
|
|||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user: return [TextContent(type="text", text="Error: not authenticated")]
|
if not user: return [TextContent(type="text", text="Error: not authenticated")]
|
||||||
for book in _discover_ab(user):
|
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:
|
if hasattr(c, 'uid') and str(c.uid.value) == uid:
|
||||||
result = [TextContent(type="text", text=_full(c))]
|
result = [TextContent(type="text", text=_full(c))]
|
||||||
b64, mime = _get_photo_data(c)
|
b64, mime = _get_photo_data(c)
|
||||||
@@ -178,10 +191,70 @@ def create_contact(
|
|||||||
if phone: card.add("tel").value = phone
|
if phone: card.add("tel").value = phone
|
||||||
if organization: card.add("org").value = [organization]
|
if organization: card.add("org").value = [organization]
|
||||||
if note: card.add("note").value = note
|
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}"
|
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()
|
@mcp.tool()
|
||||||
def set_contact_photo(
|
def set_contact_photo(
|
||||||
uid: Annotated[str, Field(description="Contact UID from search_contacts or get_contact results")],
|
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"
|
if not user: return "Error: not authenticated"
|
||||||
auth = _auth(user)
|
auth = _auth(user)
|
||||||
for book in _discover_ab(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, 'uid') and str(c.uid.value) == uid:
|
||||||
if hasattr(c, 'photo'):
|
if hasattr(c, 'photo'):
|
||||||
c.remove(c.photo)
|
c.remove(c.photo)
|
||||||
@@ -202,13 +275,68 @@ def set_contact_photo(
|
|||||||
photo.params["ENCODING"] = ["b"]
|
photo.params["ENCODING"] = ["b"]
|
||||||
photo.params["TYPE"] = [image_type.upper()]
|
photo.params["TYPE"] = [image_type.upper()]
|
||||||
href = book["href"] + uid + ".vcf"
|
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):
|
if r.status_code in (200, 201, 204):
|
||||||
return f"Foto gesetzt fuer {c.fn.value if hasattr(c, 'fn') else uid}"
|
return f"Foto gesetzt fuer {c.fn.value if hasattr(c, 'fn') else uid}"
|
||||||
return f"Fehler: HTTP {r.status_code}"
|
return f"Fehler: HTTP {r.status_code}"
|
||||||
return f"Kontakt nicht gefunden: {uid}"
|
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():
|
def create_app():
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
mcp_app = mcp.streamable_http_app()
|
mcp_app = mcp.streamable_http_app()
|
||||||
@@ -217,11 +345,13 @@ def create_app():
|
|||||||
async with contextlib.AsyncExitStack() as stack:
|
async with contextlib.AsyncExitStack() as stack:
|
||||||
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
||||||
yield
|
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 = Starlette(routes=routes, lifespan=lifespan)
|
||||||
app.add_middleware(BearerAuthMiddleware)
|
app.add_middleware(BearerAuthMiddleware)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(create_app(), host="127.0.0.1", port=5102)
|
uvicorn.run(create_app(), host="0.0.0.0", port=5102)
|
||||||
+81
-5
@@ -1,6 +1,6 @@
|
|||||||
"""MCP Files Server — browse and read files via WebDAV/oCIS."""
|
"""MCP Files Server — browse and read files via WebDAV/oCIS."""
|
||||||
|
|
||||||
import os, sys, contextlib, base64, io
|
import os, sys, contextlib, base64, io, re
|
||||||
from xml.etree import ElementTree as ET
|
from xml.etree import ElementTree as ET
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
@@ -10,7 +10,8 @@ from pydantic import Field
|
|||||||
from mcp.server.fastmcp import FastMCP
|
from mcp.server.fastmcp import FastMCP
|
||||||
from mcp.types import TextContent, ImageContent, EmbeddedResource, BlobResourceContents
|
from mcp.types import TextContent, ImageContent, EmbeddedResource, BlobResourceContents
|
||||||
from starlette.applications import Starlette
|
from starlette.applications import Starlette
|
||||||
from starlette.routing import Mount
|
from starlette.routing import Mount, Route
|
||||||
|
from starlette.responses import Response, StreamingResponse
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
||||||
@@ -30,7 +31,27 @@ def _ocis_user(u):
|
|||||||
return c[0] if c else u
|
return c[0] if c else u
|
||||||
|
|
||||||
def _auth(u): c = OCIS_CREDS.get(u); return httpx.BasicAuth(c[0], c[1]) if c else None
|
def _auth(u): c = OCIS_CREDS.get(u); return httpx.BasicAuth(c[0], c[1]) if c else None
|
||||||
def _dav(u, p=""): return f"{OCIS}/remote.php/dav/files/{_ocis_user(u)}/{p.lstrip('/')}"
|
|
||||||
|
# Regex fuer bereits korrekt encodierte %XX-Sequenzen (Roundtrip-sicher):
|
||||||
|
# ein rohes '%', das NICHT vor 2 Hex-Ziffern steht, ist ein literales Prozentzeichen.
|
||||||
|
_ENC_SAFE_RE = re.compile(r"%(?![0-9A-Fa-f]{2})")
|
||||||
|
|
||||||
|
|
||||||
|
def _enc_path(p: str) -> str:
|
||||||
|
"""Bereite einen WebDAV-Pfad fuer die URL auf (roundtrip-sicher).
|
||||||
|
|
||||||
|
httpx encodiert Leerzeichen/Umlaute automatisch, aber '#', '?' und ein
|
||||||
|
literales '%' wuerden roh in der URL bleiben ('#' -> Fragment, '?' ->
|
||||||
|
Query-Start, '%' -> kaputte/mehrdeutige Pfade). oCIS liefert hrefs bereits
|
||||||
|
encodiert ('%20', '%C3%BC') zurueck; ein naives quote() wuerde das doppelt
|
||||||
|
encodieren. Deshalb: nur '#'/'?' und Prozent-Zeichen ausserhalb gueltiger
|
||||||
|
%XX-Sequenzen ersetzen, den Rest httpx ueberlassen.
|
||||||
|
"""
|
||||||
|
p = p.replace("#", "%23").replace("?", "%3F")
|
||||||
|
return _ENC_SAFE_RE.sub("%25", p)
|
||||||
|
|
||||||
|
|
||||||
|
def _dav(u, p=""): return f"{OCIS}/remote.php/dav/files/{_ocis_user(u)}/{_enc_path(p.lstrip('/'))}"
|
||||||
|
|
||||||
def _propfind(user, path="", depth=1):
|
def _propfind(user, path="", depth=1):
|
||||||
body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:displayname/><d:getcontentlength/><d:getlastmodified/><d:getcontenttype/></d:prop></d:propfind>'
|
body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:displayname/><d:getcontentlength/><d:getlastmodified/><d:getcontenttype/></d:prop></d:propfind>'
|
||||||
@@ -264,6 +285,59 @@ def move_file(
|
|||||||
return f"Fehler: HTTP {r.status_code}"
|
return f"Fehler: HTTP {r.status_code}"
|
||||||
|
|
||||||
|
|
||||||
|
async def raw_file(request):
|
||||||
|
"""Roher Datei-Transfer (beliebige Binaerdateien, jede Groesse).
|
||||||
|
|
||||||
|
GET /raw?path=<ocis> -> Datei herunterladen (gestreamt)
|
||||||
|
PUT /raw?path=<ocis> -> Datei hochladen (Body = Rohbytes)
|
||||||
|
Token-geschuetzt ueber BearerAuthMiddleware.
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return Response("unauthorized", status_code=401)
|
||||||
|
path = request.query_params.get("path", "")
|
||||||
|
if not path:
|
||||||
|
return Response("missing path", status_code=400)
|
||||||
|
url = _dav(user, path)
|
||||||
|
|
||||||
|
if request.method == "GET":
|
||||||
|
client = httpx.AsyncClient(auth=_auth(user), timeout=httpx.Timeout(300.0, connect=10.0))
|
||||||
|
try:
|
||||||
|
req = client.build_request("GET", url)
|
||||||
|
r = await client.send(req, stream=True)
|
||||||
|
except Exception as e:
|
||||||
|
await client.aclose()
|
||||||
|
return Response(f"Fehler: {e}", status_code=502)
|
||||||
|
if r.status_code >= 400:
|
||||||
|
await r.aclose(); await client.aclose()
|
||||||
|
return Response(f"HTTP {r.status_code}", status_code=r.status_code)
|
||||||
|
ct = r.headers.get("content-type", _guess_mime(path, None))
|
||||||
|
|
||||||
|
async def body():
|
||||||
|
try:
|
||||||
|
async for chunk in r.aiter_bytes():
|
||||||
|
yield chunk
|
||||||
|
finally:
|
||||||
|
await r.aclose(); await client.aclose()
|
||||||
|
|
||||||
|
return StreamingResponse(body(), media_type=ct)
|
||||||
|
|
||||||
|
# PUT (Upload) -- Body puffern, damit Content-Length gesetzt wird (oCIS
|
||||||
|
# akzeptiert kein chunked PUT ohne Laenge).
|
||||||
|
ct = request.headers.get("content-type") or _guess_mime(path, None)
|
||||||
|
body = await request.body()
|
||||||
|
client = httpx.AsyncClient(auth=_auth(user), timeout=httpx.Timeout(600.0, connect=10.0))
|
||||||
|
try:
|
||||||
|
r = await client.put(url, content=body, headers={"Content-Type": ct})
|
||||||
|
except Exception as e:
|
||||||
|
await client.aclose()
|
||||||
|
return Response(f"Fehler: {e}", status_code=502)
|
||||||
|
await client.aclose()
|
||||||
|
if r.status_code in (200, 201, 204):
|
||||||
|
return Response("ok", status_code=200)
|
||||||
|
return Response(f"HTTP {r.status_code}", status_code=r.status_code)
|
||||||
|
|
||||||
|
|
||||||
def create_app():
|
def create_app():
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
mcp_app = mcp.streamable_http_app()
|
mcp_app = mcp.streamable_http_app()
|
||||||
@@ -272,11 +346,13 @@ def create_app():
|
|||||||
async with contextlib.AsyncExitStack() as stack:
|
async with contextlib.AsyncExitStack() as stack:
|
||||||
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
||||||
yield
|
yield
|
||||||
routes = list(OAUTH_ROUTES) + [Mount("/", app=mcp_app)]
|
routes = list(OAUTH_ROUTES) + [
|
||||||
|
Route("/raw", raw_file, methods=["GET", "PUT"]),
|
||||||
|
] + [Mount("/", app=mcp_app)]
|
||||||
app = Starlette(routes=routes, lifespan=lifespan)
|
app = Starlette(routes=routes, lifespan=lifespan)
|
||||||
app.add_middleware(BearerAuthMiddleware)
|
app.add_middleware(BearerAuthMiddleware)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(create_app(), host="127.0.0.1", port=5103)
|
uvicorn.run(create_app(), host="0.0.0.0", port=5103)
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
"""MCP Ghostfolio Server — steuert das Portfolio komplett (read + write).
|
||||||
|
|
||||||
|
Wrappt die Ghostfolio-REST-API (Container auf 127.0.0.1:3333) ueber ein
|
||||||
|
JWT-Token aus /opt/ghostfolio/migration/.auth-token. Dieser MCP-Server
|
||||||
|
exponieret die Tools Docker-intern ans openclaw-net.
|
||||||
|
|
||||||
|
Tools: Portfolio-Uebersicht (Konten, Bestaende, Performance, Dividenden),
|
||||||
|
Konten (list/create/update/delete), Activities/Transaktionen (import,
|
||||||
|
list, delete), Balance-Setze.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
import contextlib
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from pydantic import Field
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
from starlette.applications import Starlette
|
||||||
|
from starlette.routing import Mount
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
||||||
|
|
||||||
|
API_BASE = os.environ.get("GF_API_BASE", "http://127.0.0.1:3333")
|
||||||
|
AUTH_TOKEN_FILE = "/opt/ghostfolio/migration/.auth-token"
|
||||||
|
|
||||||
|
mcp = FastMCP("Ghostfolio", stateless_http=True,
|
||||||
|
transport_security={"enable_dns_rebinding_protection": False})
|
||||||
|
|
||||||
|
|
||||||
|
def _token():
|
||||||
|
with open(AUTH_TOKEN_FILE) as f:
|
||||||
|
return f.read().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _api(method: str, path: str, body=None):
|
||||||
|
url = API_BASE + path
|
||||||
|
headers = {
|
||||||
|
"Authorization": "Bearer " + _token(),
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
data = json.dumps(body).encode() if body is not None else None
|
||||||
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||||
|
raw = resp.read()
|
||||||
|
if not raw:
|
||||||
|
return {}
|
||||||
|
return json.loads(raw.decode())
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return {"error": f"HTTP {e.code} bei {method} {path}: {e.read().decode()[:400]}"}
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": f"Ghostfolio nicht erreichbar: {e}"}
|
||||||
|
|
||||||
|
|
||||||
|
REPORT_SCRIPT = "/opt/ghostfolio/report/update-report.sh"
|
||||||
|
|
||||||
|
|
||||||
|
def _trigger_report():
|
||||||
|
"""Stoesst den Status-Report fuer das accessible dashboard neu an.
|
||||||
|
|
||||||
|
Laueft asynchron (subprocess), damit das Tool sofort antwortet. Laueft als
|
||||||
|
root ueber sudo, da der Zielordner /opt/accessible-dashboard/public/portfolio
|
||||||
|
gitea-runner gehoert und stefan dorthin nicht direkt schreiben kann.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
subprocess.Popen(
|
||||||
|
["/usr/bin/sudo", "/opt/ghostfolio/report/update-report.sh"],
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
start_new_session=True,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Report-Trigger fehlgeschlagen: {e}", file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Portfolio Uebersicht (read) ---
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def portfolio_details() -> str:
|
||||||
|
"""Get the full portfolio overview: accounts, holdings, summary. Call this first."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
r = _api("GET", "/api/v1/portfolio/details")
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
summary = r.get("summary", {})
|
||||||
|
lines = [
|
||||||
|
f"Gesamtvermoegen: {summary.get('totalValue', '?')} {summary.get('currency', '')}",
|
||||||
|
f"Konten: {summary.get('totalAccounts', '?')} | Holdings: {summary.get('totalHoldings', '?')}",
|
||||||
|
f"Cash: {summary.get('cash', '?')} | Angelegt: {summary.get('totalInvestment', '?')}",
|
||||||
|
f"Performance: {summary.get('totalPerformance', '?')} ({summary.get('totalPerformancePercentage', '?')}%)",
|
||||||
|
]
|
||||||
|
lines.append("")
|
||||||
|
lines.append("Konten:")
|
||||||
|
for acc_id, a in r.get("accounts", {}).items():
|
||||||
|
lines.append(f" {a.get('name')} (id: {acc_id}) | Wert: {a.get('valueInBaseCurrency', '?')} {a.get('currency', '')}")
|
||||||
|
lines.append("")
|
||||||
|
lines.append("Bestaende (Top nach Wert):")
|
||||||
|
for sym, h in sorted(r.get("holdings", {}).items(), key=lambda x: -x[1].get("valueInBaseCurrency", 0)):
|
||||||
|
lines.append(f" {sym}: {h.get('name', '')} | Wert: {h.get('valueInBaseCurrency', '?')} | Anzahl: {h.get('quantity', '?')} | Perf: {h.get('grossPerformancePercent', '?')}%")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_performance(
|
||||||
|
range: Annotated[str, Field(description="Zeitraum: 1d, 1w, 1m, 3m, ytd, 1y, 5y, max")] = "max",
|
||||||
|
) -> str:
|
||||||
|
"""Get portfolio performance for a time range (net/gross performance, totals)."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
r = _api("GET", f"/api/v2/portfolio/performance?range={range}")
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
p = r.get("performance", {})
|
||||||
|
return (f"Zeitraum {range}:\n"
|
||||||
|
f"Netto-Performance: {p.get('netPerformance', '?')} ({p.get('netPerformancePercentage', '?')}%)\n"
|
||||||
|
f"Brutto-Performance: {p.get('grossPerformance', '?')} ({p.get('grossPerformancePercentage', '?')}%)\n"
|
||||||
|
f"Investiert: {p.get('totalInvestment', '?')} | Wertzuwachs: {p.get('totalValue', '?')}")
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_dividends(
|
||||||
|
range: Annotated[str, Field(description="Zeitraum: ytd, 1y, 5y, max")] = "ytd",
|
||||||
|
) -> str:
|
||||||
|
"""Get dividend income for a time range."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
r = _api("GET", f"/api/v1/portfolio/dividends?range={range}")
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
total = sum(d.get("investment", 0) for d in r.get("dividends", []))
|
||||||
|
lines = [f"Dividenden ({range}): Gesamt {total}"]
|
||||||
|
for d in r.get("dividends", []):
|
||||||
|
lines.append(f" {d.get('date', '')}: {d.get('symbol', '')} | {d.get('investment', 0)}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def list_accounts() -> str:
|
||||||
|
"""List all accounts with their balances."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
r = _api("GET", "/api/v1/account")
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
data = r.get("accounts", r) if isinstance(r, dict) else r
|
||||||
|
if isinstance(data, dict):
|
||||||
|
lines = [f" {a.get('name')} (id: {a.get('id')}) | {a.get('currency', '')} | {a.get('comment', '')}"
|
||||||
|
for a in data.values()]
|
||||||
|
else:
|
||||||
|
lines = [f" {a.get('name')} (id: {a.get('id')}) | {a.get('currency', '')} | {a.get('comment', '')}"
|
||||||
|
for a in data]
|
||||||
|
return "\n".join(lines) if lines else "Keine Konten"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def create_account(
|
||||||
|
name: Annotated[str, Field(description="Kontoname, z.B. 'Girokonto'")],
|
||||||
|
currency: Annotated[str, Field(description="Waehrung, z.B. 'EUR'")] = "EUR",
|
||||||
|
comment: Annotated[str, Field(description="Kommentar/Beschreibung")] = "",
|
||||||
|
) -> str:
|
||||||
|
"""Create a new account/depot. Returns the account ID."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
body = {"name": name, "currency": currency, "balance": 0, "platformId": None}
|
||||||
|
if comment:
|
||||||
|
body["comment"] = comment
|
||||||
|
r = _api("POST", "/api/v1/account", body)
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
_trigger_report()
|
||||||
|
return f"Konto angelegt: {r.get('id')}"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def import_activities(
|
||||||
|
payload: Annotated[str, Field(description="JSON-Payload mit accounts, activities, optional assetProfiles (Ghostfolio-Importformat)")],
|
||||||
|
) -> str:
|
||||||
|
"""Import activities (BUY/SELL/DIVIDEND etc.) in Ghostfolio-Importformat. Advanced use; see Ghostfolio docs for the schema."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
try:
|
||||||
|
body = json.loads(payload)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
return f"Ungueltiges JSON: {e}"
|
||||||
|
r = _api("POST", "/api/v1/import", body)
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
_trigger_report()
|
||||||
|
return f"Import abgeschlossen: {len(r.get('activities', []))} Activities"
|
||||||
|
|
||||||
|
|
||||||
|
# --- Activities ---
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def list_activities(
|
||||||
|
account_id: Annotated[str, Field(description="Konto-ID. Leer fuer alle.")] = "",
|
||||||
|
limit: Annotated[int, Field(description="Maximale Anzahl")] = 50,
|
||||||
|
) -> str:
|
||||||
|
"""List recent activities (transactions) across the portfolio or a single account."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
q = f"?take={limit}"
|
||||||
|
if account_id:
|
||||||
|
q += f"&accounts={account_id}"
|
||||||
|
r = _api("GET", f"/api/v1/activities{q}")
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
items = r.get("activities", [])
|
||||||
|
lines = [f"{len(items)} Activities"]
|
||||||
|
for a in items[:limit]:
|
||||||
|
lines.append(f" {a.get('date', '')[:10]} | {a.get('type', '')} | {a.get('symbol', '')} | qty {a.get('quantity', '')} | Preis {a.get('unitPrice', '')} | {a.get('comment', '')} | id: {a.get('id')}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def delete_activity(
|
||||||
|
id: Annotated[str, Field(description="Activity-ID aus list_activities")],
|
||||||
|
) -> str:
|
||||||
|
"""Delete a single activity/transaction."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
r = _api("DELETE", f"/api/v1/activities/{id}")
|
||||||
|
if "error" in r:
|
||||||
|
return r["error"]
|
||||||
|
_trigger_report()
|
||||||
|
return f"Activity {id} geloescht"
|
||||||
|
|
||||||
|
|
||||||
|
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) + [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=5120)
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Inkrementeller Maildir-Index-Update fuer alle User (stefan, kati).
|
||||||
|
|
||||||
|
Aufruf: python3 index_maildirs.py # inkrementell, alle User
|
||||||
|
python3 index_maildirs.py --full # erzwingt Reindex (fuer Tests)
|
||||||
|
python3 index_maildirs.py --user kati # nur ein User
|
||||||
|
|
||||||
|
Wird vom systemd-Timer mail-index.timer nach jedem mail-backup-Sync aufgerufen.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, BASE_DIR)
|
||||||
|
sys.path.insert(0, os.path.join(BASE_DIR, "mail"))
|
||||||
|
from common import load_config as _lc # noqa: E402
|
||||||
|
from mail.mailindex import update_user, connect, _SCHEMA # noqa: E402
|
||||||
|
|
||||||
|
LOG_FILE = "/var/log/mail-index.log"
|
||||||
|
|
||||||
|
|
||||||
|
def log(msg):
|
||||||
|
line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}"
|
||||||
|
print(line, flush=True)
|
||||||
|
try:
|
||||||
|
with open(LOG_FILE, "a") as f:
|
||||||
|
f.write(line + "\n")
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = [a for a in sys.argv[1:]]
|
||||||
|
full = "--full" in args
|
||||||
|
only_user = None
|
||||||
|
if "--user" in args:
|
||||||
|
only_user = args[args.index("--user") + 1]
|
||||||
|
|
||||||
|
cfg = _lc()
|
||||||
|
roots = cfg.get("mail_roots", {})
|
||||||
|
if only_user:
|
||||||
|
roots = {only_user: roots.get(only_user)}
|
||||||
|
|
||||||
|
for user, root in sorted(roots.items()):
|
||||||
|
if not root or not os.path.isdir(root):
|
||||||
|
log(f"SKIP {user}: root fehlt ({root})")
|
||||||
|
continue
|
||||||
|
t0 = time.monotonic()
|
||||||
|
if full:
|
||||||
|
# Reindex: DB zuruecksetzen, dann komplett neu
|
||||||
|
con = connect(user)
|
||||||
|
con.executescript("DROP TABLE IF EXISTS messages_fts; DROP TABLE IF EXISTS messages;")
|
||||||
|
con.executescript(_SCHEMA)
|
||||||
|
con.commit()
|
||||||
|
con.close()
|
||||||
|
log(f"REINDEX {user}: Tabellen neu erstellt")
|
||||||
|
added, updated, removed = update_user(user, root, log=log)
|
||||||
|
dur = time.monotonic() - t0
|
||||||
|
# Erst-Build abgeschlossen → Suche darf den Index nutzen
|
||||||
|
from mail.mailindex import _ready_path
|
||||||
|
with open(_ready_path(user), "w") as f:
|
||||||
|
f.write(time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||||
|
log(f"OK {user}: added={added} updated={updated} removed={removed} ({dur:.1f}s)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,377 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Maildir-Volltextindex (SQLite FTS5) fuer den MCP-Mail-Server.
|
||||||
|
|
||||||
|
Hintergrund: search_mail scannte bei jeder Anfrage das komplette Maildir
|
||||||
|
(Roh-Byte-Vorfilter ueber alle Dateien). Bei Katis Gmail-Archiv (16 GB,
|
||||||
|
~30k Mails) dauerte das laenger als das Gateway-Request-Timeout → "Request
|
||||||
|
timed out". Dieser Index macht Suchen zu FTS5-SQL-Queries (Millisekunden).
|
||||||
|
|
||||||
|
Design:
|
||||||
|
- Eine SQLite-DB pro User unter /var/lib/mail-index/<user>.sqlite
|
||||||
|
- Tabelle messages (Stammdaten + body) + virtuelle Tabelle messages_fts
|
||||||
|
(FTS5, content='messages', mit Trigger-Sync via externem Content)
|
||||||
|
- Inkrementell: Datei-Pfad + mtime + size in messages; beim Update nur
|
||||||
|
neue/geaenderte Dateien neu einlesen, entfernte loeschen
|
||||||
|
- Such-Strategie: FTS5-MATCH mit Prefix-Termen; Fallback auf LIKE ueber
|
||||||
|
sender/to/subject (deckt Substrings und E-Mail-Adressen ab), zuletzt
|
||||||
|
LIKE ueber body
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import html as htmlmod
|
||||||
|
from email import policy
|
||||||
|
from email.parser import BytesParser
|
||||||
|
from email.utils import parsedate_to_datetime
|
||||||
|
|
||||||
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, BASE_DIR)
|
||||||
|
from common import load_config as _lc # noqa: E402
|
||||||
|
|
||||||
|
INDEX_DIR = "/var/lib/mail-index"
|
||||||
|
_SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
path TEXT UNIQUE NOT NULL,
|
||||||
|
account TEXT NOT NULL,
|
||||||
|
folder TEXT NOT NULL,
|
||||||
|
key TEXT NOT NULL,
|
||||||
|
mtime REAL NOT NULL,
|
||||||
|
size INTEGER NOT NULL,
|
||||||
|
date_ts INTEGER DEFAULT 0,
|
||||||
|
sent_from TEXT DEFAULT '',
|
||||||
|
sent_to TEXT DEFAULT '',
|
||||||
|
subject TEXT DEFAULT '',
|
||||||
|
body TEXT DEFAULT ''
|
||||||
|
);
|
||||||
|
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
|
||||||
|
sent_from, sent_to, subject, body,
|
||||||
|
content='messages', content_rowid='id',
|
||||||
|
tokenize='unicode61'
|
||||||
|
);
|
||||||
|
CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
|
||||||
|
INSERT INTO messages_fts(rowid, sent_from, sent_to, subject, body)
|
||||||
|
VALUES (new.id, new.sent_from, new.sent_to, new.subject, new.body);
|
||||||
|
END;
|
||||||
|
CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
|
||||||
|
INSERT INTO messages_fts(messages_fts, rowid, sent_from, sent_to, subject, body)
|
||||||
|
VALUES ('delete', old.id, old.sent_from, old.sent_to, old.subject, old.body);
|
||||||
|
END;
|
||||||
|
CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE ON messages BEGIN
|
||||||
|
INSERT INTO messages_fts(messages_fts, rowid, sent_from, sent_to, subject, body)
|
||||||
|
VALUES ('delete', old.id, old.sent_from, old.sent_to, old.subject, old.body);
|
||||||
|
INSERT INTO messages_fts(rowid, sent_from, sent_to, subject, body)
|
||||||
|
VALUES (new.id, new.sent_from, new.sent_to, new.subject, new.body);
|
||||||
|
END;
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _term_list(query):
|
||||||
|
"""Nicht-alphanumerische Zeichen als Trenner; Lowercase."""
|
||||||
|
return [t for t in re.split(r"[^0-9A-Za-z_]+", query.lower()) if t]
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_hdr(raw):
|
||||||
|
from email.header import decode_header
|
||||||
|
if not raw:
|
||||||
|
return ""
|
||||||
|
parts = decode_header(str(raw))
|
||||||
|
out = []
|
||||||
|
for data, charset in parts:
|
||||||
|
if isinstance(data, bytes):
|
||||||
|
for cs in (charset, "utf-8", "latin-1"):
|
||||||
|
if not cs:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
out.append(data.decode(cs, errors="replace"))
|
||||||
|
break
|
||||||
|
except (LookupError, TypeError):
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
out.append(data.decode("latin-1", errors="replace"))
|
||||||
|
else:
|
||||||
|
out.append(str(data))
|
||||||
|
return " ".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_textparts(msg):
|
||||||
|
"""Text-Bodies sammeln: text/plain bevorzugt, sonst text/html (ohne Tags)."""
|
||||||
|
plains, htmls = [], []
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
ct = part.get_content_type()
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if not payload:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
text = payload.decode(part.get_content_charset() or "utf-8", errors="replace")
|
||||||
|
except (LookupError, TypeError):
|
||||||
|
text = payload.decode("latin-1", errors="replace")
|
||||||
|
if ct == "text/plain":
|
||||||
|
plains.append(text)
|
||||||
|
elif ct == "text/html":
|
||||||
|
htmls.append(text)
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload:
|
||||||
|
try:
|
||||||
|
plains.append(payload.decode(msg.get_content_charset() or "utf-8", errors="replace"))
|
||||||
|
except (LookupError, TypeError):
|
||||||
|
plains.append(payload.decode("latin-1", errors="replace"))
|
||||||
|
if plains:
|
||||||
|
return "\n".join(plains)
|
||||||
|
if htmls:
|
||||||
|
out = []
|
||||||
|
for h in htmls:
|
||||||
|
h = re.sub(r"<style.*?</style>", " ", h, flags=re.S | re.I)
|
||||||
|
h = re.sub(r"<script.*?</script>", " ", h, flags=re.S | re.I)
|
||||||
|
h = re.sub(r"<[^>]+>", " ", h)
|
||||||
|
out.append(htmlmod.unescape(h))
|
||||||
|
return "\n".join(out)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_file(path, root):
|
||||||
|
"""Mail-Datei einlesen → (account, folder, key, date_ts, sender, to, subject, body).
|
||||||
|
|
||||||
|
Pfadform unter root: <account>/<folder>/cur/<key>
|
||||||
|
"""
|
||||||
|
rel = os.path.relpath(path, root)
|
||||||
|
parts = rel.split(os.sep)
|
||||||
|
# erwartet: [account, folder, "cur", key] — aber Ordner koennen verschachtelt sein
|
||||||
|
key = parts[-1]
|
||||||
|
folder = os.sep.join(parts[1:-2]) if len(parts) > 3 else parts[-3]
|
||||||
|
account = parts[0]
|
||||||
|
try:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
raw = f.read()
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
msg = BytesParser(policy=policy.default).parsebytes(raw)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
date_str = str(msg.get("Date", ""))
|
||||||
|
date_ts = 0
|
||||||
|
if date_str:
|
||||||
|
try:
|
||||||
|
dt = parsedate_to_datetime(date_str)
|
||||||
|
if dt:
|
||||||
|
date_ts = int(dt.timestamp())
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
sender = _decode_hdr(msg.get("From", ""))
|
||||||
|
to = _decode_hdr(msg.get("To", ""))
|
||||||
|
subject = _decode_hdr(msg.get("Subject", ""))
|
||||||
|
body = _extract_textparts(msg)
|
||||||
|
return account, folder, key, date_ts, sender, to, subject, body
|
||||||
|
|
||||||
|
|
||||||
|
def index_db_path(user):
|
||||||
|
return os.path.join(INDEX_DIR, f"{user}.sqlite")
|
||||||
|
|
||||||
|
|
||||||
|
def _ready_path(user):
|
||||||
|
"""Marker: Erst-Build abgeschlossen → Suche darf den Index nutzen."""
|
||||||
|
return os.path.join(INDEX_DIR, f"{user}.ready")
|
||||||
|
|
||||||
|
|
||||||
|
def connect(user, create=True):
|
||||||
|
os.makedirs(INDEX_DIR, exist_ok=True)
|
||||||
|
db = index_db_path(user)
|
||||||
|
con = sqlite3.connect(db, timeout=30)
|
||||||
|
con.execute("PRAGMA journal_mode=WAL")
|
||||||
|
con.execute("PRAGMA synchronous=NORMAL")
|
||||||
|
if create:
|
||||||
|
con.executescript(_SCHEMA)
|
||||||
|
return con
|
||||||
|
|
||||||
|
|
||||||
|
def update_user(user, root, log=print):
|
||||||
|
"""Inkrementeller Index-Update fuer einen User-Maildir-Root.
|
||||||
|
|
||||||
|
Gibt (added, updated, removed) zurueck.
|
||||||
|
"""
|
||||||
|
if not os.path.isdir(root):
|
||||||
|
log(f" [{user}] Root fehlt: {root}")
|
||||||
|
return 0, 0, 0
|
||||||
|
con = connect(user)
|
||||||
|
try:
|
||||||
|
seen = set()
|
||||||
|
added = updated = removed = 0
|
||||||
|
# cur/ + new/-Dateien aller Ordner einsammeln (followlinks: erlaubt Account-Symlinks wie nova->.com).
|
||||||
|
# new/ = ungelesene Mails (mbsync legt \Unseen dort ab); ohne new/ fehlten sie im Index.
|
||||||
|
for dirpath, dirnames, filenames in os.walk(root, followlinks=True):
|
||||||
|
if os.path.basename(dirpath) not in ("cur", "new"):
|
||||||
|
continue
|
||||||
|
for fn in filenames:
|
||||||
|
path = os.path.join(dirpath, fn)
|
||||||
|
try:
|
||||||
|
st = os.stat(path)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
mtime, size = st.st_mtime, st.st_size
|
||||||
|
seen.add(path)
|
||||||
|
row = con.execute(
|
||||||
|
"SELECT id FROM messages WHERE path=?", (path,)
|
||||||
|
).fetchone()
|
||||||
|
if row:
|
||||||
|
cur = con.execute(
|
||||||
|
"SELECT mtime, size FROM messages WHERE id=?", (row[0],)
|
||||||
|
).fetchone()
|
||||||
|
if cur and abs(cur[0] - mtime) < 0.001 and cur[1] == size:
|
||||||
|
continue # unveraendert
|
||||||
|
updated += 1
|
||||||
|
elif size == 0:
|
||||||
|
continue # leere Datei beim Sync noch nicht fertig
|
||||||
|
else:
|
||||||
|
added += 1
|
||||||
|
parsed = _parse_file(path, root)
|
||||||
|
if not parsed:
|
||||||
|
con.execute("DELETE FROM messages WHERE path=?", (path,))
|
||||||
|
continue
|
||||||
|
account, folder, key, date_ts, sender, to, subject, body = parsed
|
||||||
|
con.execute(
|
||||||
|
"""INSERT INTO messages
|
||||||
|
(path, account, folder, key, mtime, size, date_ts,
|
||||||
|
sent_from, sent_to, subject, body)
|
||||||
|
VALUES (?,?,?,?,?,?,?,?,?,?,?)
|
||||||
|
ON CONFLICT(path) DO UPDATE SET
|
||||||
|
account=excluded.account, folder=excluded.folder,
|
||||||
|
key=excluded.key, mtime=excluded.mtime, size=excluded.size,
|
||||||
|
date_ts=excluded.date_ts, sent_from=excluded.sent_from,
|
||||||
|
sent_to=excluded.sent_to, subject=excluded.subject,
|
||||||
|
body=excluded.body""",
|
||||||
|
(path, account, folder, key, mtime, size, date_ts,
|
||||||
|
sender, to, subject, body),
|
||||||
|
)
|
||||||
|
# in DB, aber Datei weg → loeschen
|
||||||
|
for (path,) in con.execute("SELECT path FROM messages").fetchall():
|
||||||
|
if path not in seen:
|
||||||
|
con.execute("DELETE FROM messages WHERE path=?", (path,))
|
||||||
|
removed += 1
|
||||||
|
con.commit()
|
||||||
|
return added, updated, removed
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _fts_query(query):
|
||||||
|
"""FTS5-MATCH-String: alle Terme als Praefix-OR innerhalb eines Terms
|
||||||
|
(ADDED-Optimierung: mehrere Woerter muessen ALLE vorkommen → AND)."""
|
||||||
|
terms = _term_list(query)
|
||||||
|
if not terms:
|
||||||
|
return None
|
||||||
|
# jedes Wort als Prefix-Term: "term"* — escapen von Anführungszeichen
|
||||||
|
parts = []
|
||||||
|
for t in terms:
|
||||||
|
t = t.replace('"', "")
|
||||||
|
parts.append(f'"{t}"*')
|
||||||
|
return " AND ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def search(user, query, account="", folder="", limit=20, log=print):
|
||||||
|
"""Volltextsuche im Index. Liefert Liste von Dicts
|
||||||
|
{account, folder, key, date, sender, to, subject} — gleiches Format
|
||||||
|
wie der alte Vollscan, damit search_mail unveraendert weitermacht.
|
||||||
|
"""
|
||||||
|
db = index_db_path(user)
|
||||||
|
if not os.path.exists(db) or not os.path.exists(_ready_path(user)):
|
||||||
|
return None # Index noch nicht (vollstaendig) gebaut → Fallback im Server
|
||||||
|
con = connect(user, create=False)
|
||||||
|
try:
|
||||||
|
term_like = f"%{query.lower()}%"
|
||||||
|
base = "SELECT account, folder, key, date_ts, sent_from, sent_to, subject FROM messages"
|
||||||
|
where_clauses = []
|
||||||
|
params = []
|
||||||
|
# E-Mail-Adressen: FTS5 zerlegt sie in Einzelwoerter mit zu striktem
|
||||||
|
# AND → direkt ueber den LIKE-Pfad (exakt auf sender/to/subject).
|
||||||
|
has_email = "@" in query
|
||||||
|
if not has_email:
|
||||||
|
fts = _fts_query(query)
|
||||||
|
if fts:
|
||||||
|
where_clauses.append("id IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ?)")
|
||||||
|
params.append(fts)
|
||||||
|
if account:
|
||||||
|
where_clauses.append("account=?")
|
||||||
|
params.append(account)
|
||||||
|
if folder:
|
||||||
|
where_clauses.append("folder LIKE ?")
|
||||||
|
params.append(f"%{folder}%")
|
||||||
|
out = []
|
||||||
|
if where_clauses:
|
||||||
|
where_sql = " WHERE " + " AND ".join(where_clauses)
|
||||||
|
rows = con.execute(
|
||||||
|
f"{base}{where_sql} ORDER BY date_ts DESC, id DESC LIMIT ?",
|
||||||
|
params + [limit],
|
||||||
|
).fetchall()
|
||||||
|
for account_, folder_, key_, date_ts, sender, to, subject in rows:
|
||||||
|
out.append({
|
||||||
|
"account": account_, "folder": folder_, "key": key_,
|
||||||
|
"date": _fmt_date(date_ts), "sender": sender, "to": to,
|
||||||
|
"subject": subject,
|
||||||
|
})
|
||||||
|
# Fallback: LIKE-Suche (deckt Substrings + E-Mail-Adressen ab)
|
||||||
|
if not out:
|
||||||
|
cols = ["sent_from LIKE ?", "sent_to LIKE ?", "subject LIKE ?"]
|
||||||
|
all_p = [term_like] * len(cols)
|
||||||
|
extra_where = []
|
||||||
|
if account:
|
||||||
|
extra_where.append("account=?")
|
||||||
|
all_p.append(account)
|
||||||
|
if folder:
|
||||||
|
extra_where.append("folder LIKE ?")
|
||||||
|
all_p.append(f"%{folder}%")
|
||||||
|
sql = f"{base} WHERE ({' OR '.join(cols)})"
|
||||||
|
if extra_where:
|
||||||
|
sql += " AND " + " AND ".join(extra_where)
|
||||||
|
sql += " ORDER BY date_ts DESC, id DESC LIMIT ?"
|
||||||
|
all_p.append(limit)
|
||||||
|
rows2 = con.execute(sql, all_p).fetchall()
|
||||||
|
for account_, folder_, key_, date_ts, sender, to, subject in rows2:
|
||||||
|
out.append({
|
||||||
|
"account": account_, "folder": folder_, "key": key_,
|
||||||
|
"date": _fmt_date(date_ts), "sender": sender, "to": to,
|
||||||
|
"subject": subject,
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_date(ts):
|
||||||
|
if not ts:
|
||||||
|
return ""
|
||||||
|
return time.strftime("%a, %d %b %Y %H:%M:%S %z", time.localtime(ts))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# CLI: python3 mailindex.py <user> --update|--search "<query>" [limit]
|
||||||
|
import argparse
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("user")
|
||||||
|
ap.add_argument("--update", action="store_true", help="inkrementeller Update")
|
||||||
|
ap.add_argument("--search", nargs="?", default=None)
|
||||||
|
ap.add_argument("--limit", type=int, default=10)
|
||||||
|
args = ap.parse_args()
|
||||||
|
cfg = _lc()
|
||||||
|
root = cfg["mail_roots"].get(args.user)
|
||||||
|
if args.update:
|
||||||
|
if not root:
|
||||||
|
print(f"kein root fuer {args.user}")
|
||||||
|
sys.exit(1)
|
||||||
|
a, u, r = update_user(args.user, root)
|
||||||
|
print(f"[{args.user}] added={a} updated={u} removed={r}")
|
||||||
|
elif args.search:
|
||||||
|
res = search(args.user, args.search, limit=args.limit)
|
||||||
|
if res is None:
|
||||||
|
print("kein index")
|
||||||
|
elif not res:
|
||||||
|
print("keine treffer")
|
||||||
|
else:
|
||||||
|
for r in res:
|
||||||
|
print(f"[{r['date']}] {r['sender']} -> {r['to']}\n {r['subject']}\n {r['account']}/{r['folder']}/{r['key']}")
|
||||||
|
else:
|
||||||
|
ap.print_help()
|
||||||
+203
-15
@@ -12,6 +12,9 @@ import time
|
|||||||
import ctypes
|
import ctypes
|
||||||
from email.header import decode_header
|
from email.header import decode_header
|
||||||
from email.mime.text import MIMEText
|
from email.mime.text import MIMEText
|
||||||
|
from email.mime.multipart import MIMEMultipart
|
||||||
|
from email.mime.base import MIMEBase
|
||||||
|
from email import encoders
|
||||||
from email.utils import formatdate, parsedate_to_datetime
|
from email.utils import formatdate, parsedate_to_datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
@@ -20,7 +23,8 @@ from pydantic import Field
|
|||||||
from mcp.server.fastmcp import FastMCP
|
from mcp.server.fastmcp import FastMCP
|
||||||
from mcp.types import TextContent, ImageContent, EmbeddedResource, BlobResourceContents
|
from mcp.types import TextContent, ImageContent, EmbeddedResource, BlobResourceContents
|
||||||
from starlette.applications import Starlette
|
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__)))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
||||||
@@ -46,6 +50,13 @@ IMAP_ACCOUNTS = {
|
|||||||
"drafts_folder": "[Google Mail]/Entw&APw-rfe",
|
"drafts_folder": "[Google Mail]/Entw&APw-rfe",
|
||||||
"from_addr": "akpolke@gmail.com",
|
"from_addr": "akpolke@gmail.com",
|
||||||
},
|
},
|
||||||
|
"nova": {
|
||||||
|
"host": "imap.1blu.de",
|
||||||
|
"user": "d370128_0-stefanlohmaier",
|
||||||
|
"password": _cfg["imap_passwords"]["nova"],
|
||||||
|
"drafts_folder": "Drafts",
|
||||||
|
"from_addr": "stefan@slohmaier.com",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
mcp = FastMCP("Mail", stateless_http=True,
|
mcp = FastMCP("Mail", stateless_http=True,
|
||||||
@@ -148,15 +159,20 @@ def _discover_accounts(user):
|
|||||||
root = MAIL_ROOTS.get(user)
|
root = MAIL_ROOTS.get(user)
|
||||||
if not root or not os.path.isdir(root):
|
if not root or not os.path.isdir(root):
|
||||||
return {}
|
return {}
|
||||||
return {a: os.path.join(root, a) for a in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, a))}
|
allow = _cfg.get("mail_account_allow", {}).get(user)
|
||||||
|
accounts = {a: os.path.join(root, a) for a in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, a))}
|
||||||
|
if not allow:
|
||||||
|
return accounts
|
||||||
|
return {a: p for a, p in accounts.items() if a in allow}
|
||||||
|
|
||||||
|
|
||||||
def _discover_folders(acct_path):
|
def _discover_folders(acct_path):
|
||||||
folders = []
|
folders = []
|
||||||
for entry in sorted(Path(acct_path).rglob("cur")):
|
for dirpath, dirnames, _ in os.walk(acct_path, followlinks=True):
|
||||||
rel = str(entry.parent.relative_to(acct_path))
|
if "cur" in dirnames or "new" in dirnames:
|
||||||
if rel != "." and rel not in folders:
|
rel = os.path.relpath(dirpath, acct_path)
|
||||||
folders.append(rel)
|
if rel != "." and rel not in folders:
|
||||||
|
folders.append(rel)
|
||||||
if "INBOX" in folders:
|
if "INBOX" in folders:
|
||||||
folders.remove("INBOX")
|
folders.remove("INBOX")
|
||||||
folders.insert(0, "INBOX")
|
folders.insert(0, "INBOX")
|
||||||
@@ -176,6 +192,30 @@ MAX_SCAN = 2000 # Obergrenze gesammelter Treffer (Speicher-Schutz bei breiten Q
|
|||||||
DEADLINE_S = 120 # Wall-Clock-Limit: Server heilt sich selbst, nie wieder endloser Haenger
|
DEADLINE_S = 120 # Wall-Clock-Limit: Server heilt sich selbst, nie wieder endloser Haenger
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_key(key: str) -> str:
|
||||||
|
"""Normalize an index key to the Python-mailbox key (strip Dovecot ':2,<flags>'
|
||||||
|
suffix). FTS index stores the full file name (...:2,T), while mailbox.Maildir
|
||||||
|
keys drop the flags suffix; md.get() would otherwise miss every message."""
|
||||||
|
if key and ":" in key:
|
||||||
|
return key.split(":", 1)[0]
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def _imap_quote_folder(folder: str) -> str:
|
||||||
|
"""Quote an IMAP mailbox name for commands that take a bare atom.
|
||||||
|
|
||||||
|
imaplib unterdrueckt das Quoting bei append()/select() mit Literal-Syntax
|
||||||
|
({n}), daher bricht Gmail bei Ordnernamen mit Sonderzeichen (z.B.
|
||||||
|
'[Google Mail]/Entw&APw-rfe' mit '&') mit 'BAD Could not parse command' ab.
|
||||||
|
Nur wenn der Name Zeichen enthaelt, die ein Atom stoeren, in Quotes setzen.
|
||||||
|
"""
|
||||||
|
if not folder:
|
||||||
|
return folder
|
||||||
|
if any(c in folder for c in ' &[]\\"'):
|
||||||
|
return '"' + folder.replace('"', '\\"') + '"'
|
||||||
|
return folder
|
||||||
|
|
||||||
|
|
||||||
def _iter_messages(md):
|
def _iter_messages(md):
|
||||||
"""Yield (key, msg); ueberspringt unparsbare Mails statt die Suche zu killen."""
|
"""Yield (key, msg); ueberspringt unparsbare Mails statt die Suche zu killen."""
|
||||||
try:
|
try:
|
||||||
@@ -236,10 +276,23 @@ def search_mail(
|
|||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return "Error: not authenticated"
|
return "Error: not authenticated"
|
||||||
|
|
||||||
|
# FTS5-Index (schnell); Fallback auf Vollscan wenn noch kein Index gebaut wurde.
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
import mailindex
|
||||||
|
t0 = time.monotonic()
|
||||||
|
hits = mailindex.search(user, query, account=account, folder=folder, limit=limit)
|
||||||
|
if hits is not None:
|
||||||
|
if not hits:
|
||||||
|
return "No results found"
|
||||||
|
lines = [f"[{h['date']}] {h['sender']} -> {h['to']}\n Subject: {h['subject']}\n Account: {h['account']}, Folder: {h['folder']}, Key: {h['key']}"
|
||||||
|
for h in hits]
|
||||||
|
return "\n\n".join(lines)
|
||||||
|
|
||||||
|
# Fallback: klassischer Maildir-Scan (nur solange der Index fehlt)
|
||||||
query_lower = query.lower()
|
query_lower = query.lower()
|
||||||
matches = []
|
matches = []
|
||||||
truncated = False
|
truncated = False
|
||||||
t0 = time.monotonic()
|
|
||||||
for acct_name, acct_path in _discover_accounts(user).items():
|
for acct_name, acct_path in _discover_accounts(user).items():
|
||||||
if account and account not in acct_name:
|
if account and account not in acct_name:
|
||||||
continue
|
continue
|
||||||
@@ -318,7 +371,7 @@ def read_mail(
|
|||||||
md = _open_folder(acct_path, folder)
|
md = _open_folder(acct_path, folder)
|
||||||
if not md:
|
if not md:
|
||||||
return f"Folder not found: {folder}"
|
return f"Folder not found: {folder}"
|
||||||
msg = md.get(key)
|
msg = md.get(_norm_key(key))
|
||||||
if not msg:
|
if not msg:
|
||||||
return f"Message not found: {key}"
|
return f"Message not found: {key}"
|
||||||
out = (
|
out = (
|
||||||
@@ -355,7 +408,7 @@ def read_attachment(
|
|||||||
md = _open_folder(acct_path, folder)
|
md = _open_folder(acct_path, folder)
|
||||||
if not md:
|
if not md:
|
||||||
return [TextContent(type="text", text=f"Folder not found: {folder}")]
|
return [TextContent(type="text", text=f"Folder not found: {folder}")]
|
||||||
msg = md.get(key)
|
msg = md.get(_norm_key(key))
|
||||||
if not msg:
|
if not msg:
|
||||||
return [TextContent(type="text", text=f"Message not found: {key}")]
|
return [TextContent(type="text", text=f"Message not found: {key}")]
|
||||||
attachments = _get_attachments(msg)
|
attachments = _get_attachments(msg)
|
||||||
@@ -377,6 +430,81 @@ def read_attachment(
|
|||||||
blob=base64.b64encode(payload).decode(), mimeType=mime))]
|
blob=base64.b64encode(payload).decode(), mimeType=mime))]
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_filename(name):
|
||||||
|
"""Safe filename: keep letters/digits/._-, no path separators."""
|
||||||
|
import re
|
||||||
|
base = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("._")
|
||||||
|
return base[:160] or "attachment.bin"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def download_attachment(
|
||||||
|
account: Annotated[str, Field(description="Account name from search results")],
|
||||||
|
folder: Annotated[str, Field(description="Folder name from search results")],
|
||||||
|
key: Annotated[str, Field(description="Message key from search results")],
|
||||||
|
attachment_index: Annotated[int, Field(description="Attachment number from the read_mail attachment list (1-based)")],
|
||||||
|
) -> str:
|
||||||
|
"""Download an email attachment as a file into the agent workspace and return the file path. Use the attachment index from read_mail; the returned path is directly readable by the agent inside the container. Falls back to listing matching files if the message key is not found literally."""
|
||||||
|
_trim_memory()
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return "Error: not authenticated"
|
||||||
|
acct_path = _discover_accounts(user).get(account)
|
||||||
|
if not acct_path:
|
||||||
|
return f"Account not found: {account}"
|
||||||
|
md = _open_folder(acct_path, folder)
|
||||||
|
if not md:
|
||||||
|
return f"Folder not found: {folder}"
|
||||||
|
msg = md.get(_norm_key(key))
|
||||||
|
if not msg:
|
||||||
|
# Fallback: Key waechst manchmal (Maildir-Read), suche erste passende Nachricht
|
||||||
|
found = None
|
||||||
|
try:
|
||||||
|
for k in list(md.keys()):
|
||||||
|
if k.startswith(key):
|
||||||
|
found = k
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if found:
|
||||||
|
msg = md.get(found)
|
||||||
|
if not msg:
|
||||||
|
return f"Message not found: {key}"
|
||||||
|
attachments = _get_attachments(msg)
|
||||||
|
att = next((a for a in attachments if a["index"] == attachment_index), None)
|
||||||
|
if not att:
|
||||||
|
return f"Anhang {attachment_index} nicht gefunden. {len(attachments)} Anhaenge vorhanden."
|
||||||
|
dirs = _cfg.get("mail_attachment_dirs", {})
|
||||||
|
d = dirs.get(user)
|
||||||
|
if not d:
|
||||||
|
return f"Kein Download-Verzeichnis fuer User {user} konfiguriert"
|
||||||
|
host_dir = os.path.expanduser(d["host"])
|
||||||
|
container_dir = os.path.expanduser(d["container"])
|
||||||
|
try:
|
||||||
|
os.makedirs(host_dir, exist_ok=True)
|
||||||
|
except Exception as e:
|
||||||
|
return f"Fehler beim Anlegen des Zielverzeichnisses: {e}"
|
||||||
|
filename = _sanitize_filename(att["filename"])
|
||||||
|
dest_host = os.path.join(host_dir, filename)
|
||||||
|
# Kollision aufloesen: (1), (2), ...
|
||||||
|
base, ext = os.path.splitext(dest_host)
|
||||||
|
n = 1
|
||||||
|
while os.path.exists(dest_host):
|
||||||
|
dest_host = f"{base} ({n}){ext}"
|
||||||
|
n += 1
|
||||||
|
if n > 100:
|
||||||
|
return f"Zu viele gleichnamige Dateien in {host_dir}"
|
||||||
|
try:
|
||||||
|
with open(dest_host, "wb") as fh:
|
||||||
|
fh.write(att["payload"])
|
||||||
|
except Exception as e:
|
||||||
|
return f"Fehler beim Schreiben: {e}"
|
||||||
|
dest_container = os.path.join(container_dir, os.path.basename(dest_host))
|
||||||
|
return (f"Anhang heruntergeladen: {dest_container}\n"
|
||||||
|
f"Datei: {att['filename']} ({att['mime']}, {att['size']:,} bytes)\n"
|
||||||
|
f"Gespeichert als: {dest_container}")
|
||||||
|
|
||||||
|
|
||||||
@mcp.tool()
|
@mcp.tool()
|
||||||
def create_draft(
|
def create_draft(
|
||||||
to: Annotated[str, Field(description="Recipient email address, e.g. 'max@example.com'")],
|
to: Annotated[str, Field(description="Recipient email address, e.g. 'max@example.com'")],
|
||||||
@@ -384,14 +512,22 @@ def create_draft(
|
|||||||
body: Annotated[str, Field(description="Email body text (plain text)")],
|
body: Annotated[str, Field(description="Email body text (plain text)")],
|
||||||
cc: Annotated[str, Field(description="CC recipients, comma-separated")] = "",
|
cc: Annotated[str, Field(description="CC recipients, comma-separated")] = "",
|
||||||
account: Annotated[str, Field(description="Which account to create the draft in. Leave empty for default account.")] = "",
|
account: Annotated[str, Field(description="Which account to create the draft in. Leave empty for default account.")] = "",
|
||||||
|
attachment_filenames: Annotated[list, Field(description="List of attachment file names, e.g. ['angebot.pdf']. Optional. Must match attachment_contents order.")] = None,
|
||||||
|
attachment_contents: Annotated[list, Field(description="List of attachment contents as Base64-encoded strings. Optional. Must match attachment_filenames order.")] = None,
|
||||||
|
attachment_mimetypes: Annotated[list, Field(description="List of attachment MIME types, e.g. ['application/pdf']. Optional. If omitted, guessed from file extension.")] = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Create an email draft in the Drafts folder. The draft can then be reviewed and sent from Roundcube or phone. Does NOT send the email."""
|
"""Create an email draft in the Drafts folder, optionally with attachments. Attachments are passed as Base64 content (attachment_contents) with matching filenames. The draft can then be reviewed and sent from Roundcube or phone. Does NOT send the email."""
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user: return "Error: not authenticated"
|
if not user: return "Error: not authenticated"
|
||||||
acct = IMAP_ACCOUNTS.get(user)
|
acct = IMAP_ACCOUNTS.get(user)
|
||||||
if not acct: return f"Kein IMAP-Account fuer {user} konfiguriert"
|
if not acct: return f"Kein IMAP-Account fuer {user} konfiguriert"
|
||||||
|
|
||||||
msg = MIMEText(body, "plain", "utf-8")
|
has_attachments = (attachment_filenames and attachment_contents) and len(attachment_filenames) == len(attachment_contents)
|
||||||
|
if has_attachments:
|
||||||
|
msg = MIMEMultipart()
|
||||||
|
else:
|
||||||
|
msg = MIMEText(body, "plain", "utf-8")
|
||||||
|
|
||||||
msg["From"] = acct["from_addr"]
|
msg["From"] = acct["from_addr"]
|
||||||
msg["To"] = to
|
msg["To"] = to
|
||||||
if cc:
|
if cc:
|
||||||
@@ -400,18 +536,68 @@ def create_draft(
|
|||||||
msg["Date"] = formatdate(localtime=True)
|
msg["Date"] = formatdate(localtime=True)
|
||||||
msg["X-Mailer"] = "MCP Mail Server"
|
msg["X-Mailer"] = "MCP Mail Server"
|
||||||
|
|
||||||
|
if has_attachments:
|
||||||
|
msg.attach(MIMEText(body, "plain", "utf-8"))
|
||||||
|
for i, fname in enumerate(attachment_filenames):
|
||||||
|
try:
|
||||||
|
content = base64.b64decode(attachment_contents[i])
|
||||||
|
except Exception as e:
|
||||||
|
return f"Fehler: Anhang '{fname}' nicht als gueltiges Base64 decodierbar: {e}"
|
||||||
|
mime = attachment_mimetypes[i] if (attachment_mimetypes and i < len(attachment_mimetypes)) else "application/octet-stream"
|
||||||
|
part = MIMEBase(*mime.split("/", 1))
|
||||||
|
part.set_payload(content)
|
||||||
|
encoders.encode_base64(part)
|
||||||
|
part.add_header("Content-Disposition", "attachment", filename=fname)
|
||||||
|
msg.attach(part)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
imap = imaplib.IMAP4_SSL(acct["host"])
|
imap = imaplib.IMAP4_SSL(acct["host"])
|
||||||
imap.login(acct["user"], acct["password"])
|
imap.login(acct["user"], acct["password"])
|
||||||
status, _ = imap.append(acct["drafts_folder"], "\\Draft", None, msg.as_bytes())
|
status, _ = imap.append(_imap_quote_folder(acct["drafts_folder"]), "\\Draft", None, msg.as_bytes())
|
||||||
imap.logout()
|
imap.logout()
|
||||||
if status == "OK":
|
if status == "OK":
|
||||||
return f"Entwurf erstellt: An {to}, Betreff \"{subject}\". Oeffne Roundcube oder die Mail-App um ihn zu senden."
|
n_att = len(attachment_filenames) if has_attachments else 0
|
||||||
|
att_str = f" mit {n_att} Anhang/Anhaengen" if n_att else ""
|
||||||
|
return f"Entwurf erstellt{att_str}: An {to}, Betreff \"{subject}\". Oeffne Roundcube oder die Mail-App um ihn zu senden."
|
||||||
return f"Fehler beim Erstellen des Entwurfs: {status}"
|
return f"Fehler beim Erstellen des Entwurfs: {status}"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"IMAP-Fehler: {e}"
|
return f"IMAP-Fehler: {e}"
|
||||||
|
|
||||||
|
|
||||||
|
async def raw_mail(request):
|
||||||
|
"""Roher Anhang-Download (beliebige Binaerdateien).
|
||||||
|
|
||||||
|
GET /raw?account=&folder=&key=&index= -> Anhang als Rohbytes.
|
||||||
|
Token-geschuetzt ueber BearerAuthMiddleware.
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return Response("unauthorized", status_code=401)
|
||||||
|
q = request.query_params
|
||||||
|
account = q.get("account", "")
|
||||||
|
folder = q.get("folder", "")
|
||||||
|
key = q.get("key", "")
|
||||||
|
try:
|
||||||
|
index = int(q.get("index", "0"))
|
||||||
|
except ValueError:
|
||||||
|
return Response("invalid index", status_code=400)
|
||||||
|
acct_path = _discover_accounts(user).get(account)
|
||||||
|
if not acct_path:
|
||||||
|
return Response(f"Account not found: {account}", status_code=404)
|
||||||
|
md = _open_folder(acct_path, folder)
|
||||||
|
if not md:
|
||||||
|
return Response(f"Folder not found: {folder}", status_code=404)
|
||||||
|
msg = md.get(_norm_key(key))
|
||||||
|
if not msg:
|
||||||
|
return Response(f"Message not found: {key}", status_code=404)
|
||||||
|
att = next((a for a in _get_attachments(msg) if a["index"] == index), None)
|
||||||
|
if not att:
|
||||||
|
return Response(f"Anhang {index} nicht gefunden", status_code=404)
|
||||||
|
fn = _sanitize_filename(att["filename"])
|
||||||
|
return Response(att["payload"], media_type=att["mime"],
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="{fn}"'})
|
||||||
|
|
||||||
|
|
||||||
def create_app():
|
def create_app():
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
mcp_app = mcp.streamable_http_app()
|
mcp_app = mcp.streamable_http_app()
|
||||||
@@ -422,7 +608,9 @@ def create_app():
|
|||||||
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
||||||
yield
|
yield
|
||||||
|
|
||||||
routes = list(OAUTH_ROUTES) + [Mount("/", app=mcp_app)]
|
routes = list(OAUTH_ROUTES) + [
|
||||||
|
Route("/raw", raw_mail, methods=["GET"]),
|
||||||
|
] + [Mount("/", app=mcp_app)]
|
||||||
app = Starlette(routes=routes, lifespan=lifespan)
|
app = Starlette(routes=routes, lifespan=lifespan)
|
||||||
app.add_middleware(BearerAuthMiddleware)
|
app.add_middleware(BearerAuthMiddleware)
|
||||||
return app
|
return app
|
||||||
@@ -430,4 +618,4 @@ def create_app():
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(create_app(), host="127.0.0.1", port=5100)
|
uvicorn.run(create_app(), host="0.0.0.0", port=5100)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Verwaltet nicht-ablaufende MCP-Service-Tokens (service_tokens.json).
|
||||||
|
#
|
||||||
|
# mint-service-token.sh add <user> <label> -> erzeugt Token, gibt ihn aus
|
||||||
|
# mint-service-token.sh rm <label> -> entfernt Token(s) mit Label
|
||||||
|
# mint-service-token.sh list -> listet Labels/User (Token gekuerzt)
|
||||||
|
#
|
||||||
|
# Service-Tokens werden von common.py als Authorization: Bearer akzeptiert und
|
||||||
|
# laufen nie ab. Widerruf = aus der Datei entfernen (rm). Datei chmod 600.
|
||||||
|
set -euo pipefail
|
||||||
|
DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
FILE="$DIR/service_tokens.json"
|
||||||
|
umask 077
|
||||||
|
[ -f "$FILE" ] || printf '{}\n' > "$FILE"
|
||||||
|
chmod 600 "$FILE"
|
||||||
|
|
||||||
|
python3 - "$FILE" "$@" <<'PY'
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
|
||||||
|
path = sys.argv[1]
|
||||||
|
cmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||||
|
rest = sys.argv[3:]
|
||||||
|
|
||||||
|
with open(path) as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
if cmd == "add":
|
||||||
|
if len(rest) < 2:
|
||||||
|
sys.exit("Usage: mint-service-token.sh add <user> <label>")
|
||||||
|
user, label = rest[0], rest[1]
|
||||||
|
token = secrets.token_urlsafe(48)
|
||||||
|
data[token] = {"user": user, "label": label}
|
||||||
|
with open(path, "w") as f:
|
||||||
|
json.dump(data, f, indent=2)
|
||||||
|
print(token)
|
||||||
|
elif cmd == "rm":
|
||||||
|
if not rest:
|
||||||
|
sys.exit("Usage: mint-service-token.sh rm <label>")
|
||||||
|
label = rest[0]
|
||||||
|
data = {k: v for k, v in data.items() if v.get("label") != label}
|
||||||
|
with open(path, "w") as f:
|
||||||
|
json.dump(data, f, indent=2)
|
||||||
|
elif cmd == "list":
|
||||||
|
for k, v in data.items():
|
||||||
|
print(f"{v.get('label', '?')}\t{v.get('user', '?')}\t{k[:6]}...")
|
||||||
|
else:
|
||||||
|
sys.exit("Usage: mint-service-token.sh add|rm|list ...")
|
||||||
|
PY
|
||||||
+257
-6
@@ -1,6 +1,6 @@
|
|||||||
"""MCP Notes Server — reads/writes Joplin notes via Joplin CLI Data API."""
|
"""MCP Notes Server — reads/writes Joplin notes via Joplin CLI Data API."""
|
||||||
|
|
||||||
import os, sys, contextlib, base64
|
import os, sys, contextlib, base64, json, mimetypes
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -8,7 +8,8 @@ from pydantic import Field
|
|||||||
from mcp.server.fastmcp import FastMCP
|
from mcp.server.fastmcp import FastMCP
|
||||||
from mcp.types import TextContent, ImageContent, EmbeddedResource, BlobResourceContents
|
from mcp.types import TextContent, ImageContent, EmbeddedResource, BlobResourceContents
|
||||||
from starlette.applications import Starlette
|
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__)))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware, load_config
|
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware, load_config
|
||||||
@@ -48,7 +49,7 @@ def _post(user, path, json_data):
|
|||||||
if not api:
|
if not api:
|
||||||
return None, "Kein Joplin-Zugang"
|
return None, "Kein Joplin-Zugang"
|
||||||
try:
|
try:
|
||||||
r = httpx.post(f"{api['url']}{path}?token={api['token']}", json=json_data, timeout=30)
|
r = httpx.post(f"{api['url']}{path}", params={"token": api["token"]}, json=json_data, timeout=30)
|
||||||
if r.status_code >= 400:
|
if r.status_code >= 400:
|
||||||
return None, f"Joplin HTTP {r.status_code}"
|
return None, f"Joplin HTTP {r.status_code}"
|
||||||
return r.json(), None
|
return r.json(), None
|
||||||
@@ -69,7 +70,7 @@ def _put(user, path, json_data):
|
|||||||
if not api:
|
if not api:
|
||||||
return None, "Kein Joplin-Zugang"
|
return None, "Kein Joplin-Zugang"
|
||||||
try:
|
try:
|
||||||
r = httpx.put(f"{api['url']}{path}?token={api['token']}", json=json_data, timeout=30)
|
r = httpx.put(f"{api['url']}{path}", params={"token": api["token"]}, json=json_data, timeout=30)
|
||||||
if r.status_code >= 400:
|
if r.status_code >= 400:
|
||||||
return None, f"Joplin HTTP {r.status_code}"
|
return None, f"Joplin HTTP {r.status_code}"
|
||||||
return r.json(), None
|
return r.json(), None
|
||||||
@@ -112,6 +113,62 @@ def _all_items(user, path, params=None):
|
|||||||
return items, None
|
return items, None
|
||||||
|
|
||||||
|
|
||||||
|
MAX_ATTACHMENT_BYTES = 2 * 1024 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_base64(content_base64):
|
||||||
|
s = re.sub(r"\s+", "", content_base64 or "")
|
||||||
|
if s.startswith("data:") and "," in s:
|
||||||
|
s = s.split(",", 1)[1]
|
||||||
|
try:
|
||||||
|
return base64.b64decode(s, validate=True), None
|
||||||
|
except Exception as e:
|
||||||
|
return None, f"Ungueltiges Base64: {e}"
|
||||||
|
|
||||||
|
|
||||||
|
def _guess_mime(filename, mime):
|
||||||
|
if mime:
|
||||||
|
return mime
|
||||||
|
return mimetypes.guess_type(filename or "")[0] or "application/octet-stream"
|
||||||
|
|
||||||
|
|
||||||
|
def _resource_link(title, mime, resource_id):
|
||||||
|
label = (title or "Anhang").replace("[", "(").replace("]", ")")
|
||||||
|
if (mime or "").startswith("image/"):
|
||||||
|
return f""
|
||||||
|
return f"[{label}](:/{resource_id})"
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_resource_refs(body, resource_id):
|
||||||
|
"""Remove Markdown/HTML links pointing at :/resourceId from a note body."""
|
||||||
|
rid = re.escape(resource_id)
|
||||||
|
body = re.sub(r"!?\[[^\]]*\]\(:/" + rid + r'(?:\s+"[^"]*")?\)', "", body)
|
||||||
|
body = re.sub(r"<[^>]*:/" + rid + r"[^>]*>", "", body)
|
||||||
|
body = re.sub(r"\n{3,}", "\n\n", body).strip()
|
||||||
|
return body + ("\n" if body else "")
|
||||||
|
|
||||||
|
|
||||||
|
def _upload_resource(user, path, filename, content, mime, props, method="post"):
|
||||||
|
"""Create (POST) or replace content (PUT) of a Joplin resource via multipart/form-data.
|
||||||
|
|
||||||
|
Joplin expects the file in the 'data' field and the properties as JSON in the
|
||||||
|
'props' field (see Data API docs, POST/PUT /resources)."""
|
||||||
|
api = _api(user)
|
||||||
|
if not api:
|
||||||
|
return None, "Kein Joplin-Zugang"
|
||||||
|
files = {"data": (filename or "attachment.bin", content, mime or "application/octet-stream")}
|
||||||
|
data = {"props": json.dumps(props or {})}
|
||||||
|
try:
|
||||||
|
fn = httpx.post if method == "post" else httpx.put
|
||||||
|
r = fn(f"{api['url']}{path}", params={"token": api["token"]},
|
||||||
|
files=files, data=data, timeout=120)
|
||||||
|
if r.status_code >= 400:
|
||||||
|
return None, f"Joplin HTTP {r.status_code}: {r.text[:200]}"
|
||||||
|
return r.json(), None
|
||||||
|
except Exception as e:
|
||||||
|
return None, str(e)
|
||||||
|
|
||||||
|
|
||||||
@mcp.tool()
|
@mcp.tool()
|
||||||
def list_notebooks() -> str:
|
def list_notebooks() -> str:
|
||||||
"""List all Joplin notebooks (folders). Call this first to see notebook names and IDs."""
|
"""List all Joplin notebooks (folders). Call this first to see notebook names and IDs."""
|
||||||
@@ -224,6 +281,116 @@ def read_resource(
|
|||||||
uri=uri, blob=base64.b64encode(content).decode(), mimeType=mime))]
|
uri=uri, blob=base64.b64encode(content).decode(), mimeType=mime))]
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def add_attachment(
|
||||||
|
note_id: Annotated[str, Field(description="Note ID from list_notes or search_notes")],
|
||||||
|
filename: Annotated[str, Field(description="File name incl. extension, e.g. 'angebot.pdf' or 'foto.jpg'. Used as resource title and to guess the MIME type.")],
|
||||||
|
content_base64: Annotated[str, Field(description="File content as a Base64 string (raw bytes). A 'data:...;base64,' prefix and line breaks are accepted.")],
|
||||||
|
mime: Annotated[str, Field(description="MIME type, e.g. 'application/pdf'. Leave empty to guess it from the filename.")] = "",
|
||||||
|
title: Annotated[str, Field(description="Title shown for the attachment in Joplin. Leave empty to use the filename.")] = "",
|
||||||
|
) -> str:
|
||||||
|
"""Add an attachment (image, PDF, any file) to a note. Uploads the file as a Joplin resource and appends a Markdown link at the end of the note body. Max 25 MB."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
if not _valid_id(note_id): return "Fehler: ungueltige note_id (erwartet 32 Hex-Zeichen)"
|
||||||
|
if not filename: return "Fehler: filename erforderlich"
|
||||||
|
content, err = _decode_base64(content_base64)
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
if not content: return "Fehler: content_base64 ist leer"
|
||||||
|
if len(content) > MAX_ATTACHMENT_BYTES:
|
||||||
|
return f"Fehler: Anhang zu gross ({len(content):,} bytes, max {MAX_ATTACHMENT_BYTES:,})"
|
||||||
|
mime = _guess_mime(filename, mime)
|
||||||
|
props = {"title": title or filename, "mime": mime}
|
||||||
|
res, err = _upload_resource(user, "/resources", filename, content, mime, props, method="post")
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
rid = res.get("id", "")
|
||||||
|
r, err = _get(user, f"/notes/{note_id}", {"fields": "id,title,body"})
|
||||||
|
if err: return f"Anhang hochgeladen (resource id: {rid}), aber Notiz-Lesen fehlgeschlagen: {err}"
|
||||||
|
note = r.json()
|
||||||
|
new_body = (note.get("body", "") or "").rstrip() + "\n\n" + _resource_link(props["title"], mime, rid) + "\n"
|
||||||
|
_, err = _put(user, f"/notes/{note_id}", {"body": new_body})
|
||||||
|
if err: return f"Anhang hochgeladen (resource id: {rid}), aber Verlinkung fehlgeschlagen: {err}"
|
||||||
|
return f"Anhang hinzugefuegt: {props['title']} ({mime}, {len(content):,} bytes), resource id: {rid}, verlinkt in Notiz: {note.get('title','?')}"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def update_attachment(
|
||||||
|
resource_id: Annotated[str, Field(description="Attachment/resource ID from list_note_resources")],
|
||||||
|
content_base64: Annotated[str, Field(description="New file content as a Base64 string. Leave empty to keep the current content (then only title/mime change).")] = "",
|
||||||
|
filename: Annotated[str, Field(description="New file name, only used together with content_base64.")] = "",
|
||||||
|
mime: Annotated[str, Field(description="New MIME type. Leave empty to keep the current one.")] = "",
|
||||||
|
title: Annotated[str, Field(description="New title shown in Joplin. Leave empty to keep the current one.")] = "",
|
||||||
|
) -> str:
|
||||||
|
"""Edit an attachment: replace its file content and/or change its title and MIME type. Only the given fields are changed. Get resource_id from list_note_resources."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
if not _valid_id(resource_id): return "Fehler: ungueltige resource_id (erwartet 32 Hex-Zeichen)"
|
||||||
|
if not content_base64 and not title and not mime:
|
||||||
|
return "Nichts zu aendern: content_base64, title oder mime angeben"
|
||||||
|
rmeta, err = _get(user, f"/resources/{resource_id}", {"fields": "id,title,mime,filename"})
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
meta = rmeta.json()
|
||||||
|
new_title = title or meta.get("title", "") or "attachment"
|
||||||
|
new_mime = mime or meta.get("mime", "")
|
||||||
|
if content_base64:
|
||||||
|
content, err = _decode_base64(content_base64)
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
if not content: return "Fehler: content_base64 ist leer"
|
||||||
|
if len(content) > MAX_ATTACHMENT_BYTES:
|
||||||
|
return f"Fehler: Anhang zu gross ({len(content):,} bytes, max {MAX_ATTACHMENT_BYTES:,})"
|
||||||
|
fn = filename or meta.get("filename") or new_title
|
||||||
|
new_mime = _guess_mime(fn, new_mime)
|
||||||
|
props = {"title": new_title, "mime": new_mime}
|
||||||
|
res, err = _upload_resource(user, f"/resources/{resource_id}", fn, content, new_mime, props, method="put")
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
return f"Anhang-Inhalt ersetzt: {new_title} ({new_mime}, {len(content):,} bytes), resource id: {resource_id}"
|
||||||
|
payload = {}
|
||||||
|
if title: payload["title"] = title
|
||||||
|
if mime: payload["mime"] = mime
|
||||||
|
d, err = _put(user, f"/resources/{resource_id}", payload)
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
return f"Anhang aktualisiert ({', '.join(sorted(payload))}): {d.get('title', new_title)} (resource id: {resource_id})"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def delete_attachment(
|
||||||
|
resource_id: Annotated[str, Field(description="Attachment/resource ID from list_note_resources")],
|
||||||
|
note_id: Annotated[str, Field(description="Note ID whose body also references the attachment. Recommended: only then is the Markdown link reliably removed. Leave empty to try all notes that Joplin reports for the resource.")] = "",
|
||||||
|
remove_links: Annotated[bool, Field(description="True (default): also remove the Markdown links to the attachment from the note body. False: keep the (then broken) links.")] = True,
|
||||||
|
) -> str:
|
||||||
|
"""Delete an attachment permanently (Joplin has no trash for resources) and remove its links from the note body. Get resource_id from list_note_resources."""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user: return "Error: not authenticated"
|
||||||
|
if not _valid_id(resource_id): return "Fehler: ungueltige resource_id (erwartet 32 Hex-Zeichen)"
|
||||||
|
if note_id and not _valid_id(note_id): return "Fehler: ungueltige note_id (erwartet 32 Hex-Zeichen)"
|
||||||
|
rmeta, err = _get(user, f"/resources/{resource_id}", {"fields": "id,title"})
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
rtitle = rmeta.json().get("title", resource_id)
|
||||||
|
cleaned = []
|
||||||
|
if remove_links:
|
||||||
|
notes, err = _all_items(user, f"/resources/{resource_id}/notes", {"fields": "id,title"})
|
||||||
|
if err: return f"Fehler: {err}"
|
||||||
|
if note_id:
|
||||||
|
notes = [n for n in notes if n["id"] == note_id] or [{"id": note_id}]
|
||||||
|
for n in notes:
|
||||||
|
r, err = _get(user, f"/notes/{n['id']}", {"fields": "id,title,body"})
|
||||||
|
if err: continue
|
||||||
|
d = r.json()
|
||||||
|
body = d.get("body", "") or ""
|
||||||
|
if f":/{resource_id}" in body:
|
||||||
|
_, err = _put(user, f"/notes/{n['id']}", {"body": _strip_resource_refs(body, resource_id)})
|
||||||
|
if not err:
|
||||||
|
cleaned.append(d.get("title", n["id"]))
|
||||||
|
_, err = _delete(user, f"/resources/{resource_id}")
|
||||||
|
if err: return f"Fehler beim Loeschen: {err}"
|
||||||
|
msg = f"Anhang geloescht (nicht wiederherstellbar): {rtitle} (resource id: {resource_id})"
|
||||||
|
if cleaned:
|
||||||
|
msg += f", Referenz entfernt aus: {', '.join(cleaned)}"
|
||||||
|
elif not note_id:
|
||||||
|
msg += ". Hinweis: keine verlinkte Notiz gefunden (Joplins Link-Tabelle kann leer sein) — note_id angeben, um den Link sicher zu entfernen"
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
@mcp.tool()
|
@mcp.tool()
|
||||||
def create_note(
|
def create_note(
|
||||||
notebook: Annotated[str, Field(description="Notebook name or ID where the note is created")],
|
notebook: Annotated[str, Field(description="Notebook name or ID where the note is created")],
|
||||||
@@ -298,6 +465,88 @@ def delete_note(
|
|||||||
return f"Notiz in den Papierkorb verschoben: {note_title} (in Joplin wiederherstellbar)"
|
return f"Notiz in den Papierkorb verschoben: {note_title} (in Joplin wiederherstellbar)"
|
||||||
|
|
||||||
|
|
||||||
|
async def raw_resource(request):
|
||||||
|
"""Roher Resource-Transfer (beliebige Binaerdateien).
|
||||||
|
|
||||||
|
GET /raw?resource_id=<id> -> Resource als Rohbytes
|
||||||
|
PUT /raw?resource_id=<id>[&filename=&mime=&title=] -> vorhandene Resource ersetzen
|
||||||
|
PUT /raw?note_id=<id>&filename=<name>[&mime=&title=] -> neue Resource anlegen + in Notiz verlinken
|
||||||
|
Token-geschuetzt ueber BearerAuthMiddleware.
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return Response("unauthorized", status_code=401)
|
||||||
|
q = request.query_params
|
||||||
|
|
||||||
|
if request.method == "GET":
|
||||||
|
rid = q.get("resource_id", "")
|
||||||
|
if not _valid_id(rid):
|
||||||
|
return Response("invalid resource_id", status_code=400)
|
||||||
|
rmeta, err = _get(user, f"/resources/{rid}", {"fields": "id,title,mime"})
|
||||||
|
if err:
|
||||||
|
return Response(f"Fehler: {err}", status_code=404)
|
||||||
|
meta = rmeta.json()
|
||||||
|
mime = meta.get("mime", "application/octet-stream")
|
||||||
|
title = meta.get("title", "attachment")
|
||||||
|
rfile, err = _get(user, f"/resources/{rid}/file")
|
||||||
|
if err:
|
||||||
|
return Response(f"Fehler: {err}", status_code=404)
|
||||||
|
return Response(rfile.content, media_type=mime,
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="{title}"'})
|
||||||
|
|
||||||
|
# PUT (Upload / Ersetzen)
|
||||||
|
content = await request.body()
|
||||||
|
if not content:
|
||||||
|
return Response("leerer Body", status_code=400)
|
||||||
|
if len(content) > MAX_ATTACHMENT_BYTES:
|
||||||
|
return Response(f"zu gross ({len(content):,} > {MAX_ATTACHMENT_BYTES:,})", status_code=413)
|
||||||
|
rid = q.get("resource_id", "")
|
||||||
|
note_id = q.get("note_id", "")
|
||||||
|
filename = q.get("filename", "")
|
||||||
|
mime = q.get("mime", "")
|
||||||
|
title = q.get("title", "")
|
||||||
|
|
||||||
|
if rid:
|
||||||
|
if not _valid_id(rid):
|
||||||
|
return Response("invalid resource_id", status_code=400)
|
||||||
|
rmeta, err = _get(user, f"/resources/{rid}", {"fields": "id,title,mime,filename"})
|
||||||
|
if err:
|
||||||
|
return Response(f"Fehler: {err}", status_code=404)
|
||||||
|
meta = rmeta.json()
|
||||||
|
fn = filename or meta.get("filename") or meta.get("title") or "attachment.bin"
|
||||||
|
new_mime = _guess_mime(fn, mime or meta.get("mime", ""))
|
||||||
|
new_title = title or meta.get("title") or fn
|
||||||
|
props = {"title": new_title, "mime": new_mime}
|
||||||
|
res, err = _upload_resource(user, f"/resources/{rid}", fn, content, new_mime, props, method="put")
|
||||||
|
if err:
|
||||||
|
return Response(f"Fehler: {err}", status_code=502)
|
||||||
|
return Response(f"ok resource {rid} ersetzt ({len(content):,} bytes)", status_code=200)
|
||||||
|
|
||||||
|
if note_id:
|
||||||
|
if not _valid_id(note_id):
|
||||||
|
return Response("invalid note_id", status_code=400)
|
||||||
|
if not filename:
|
||||||
|
return Response("filename erforderlich", status_code=400)
|
||||||
|
new_mime = _guess_mime(filename, mime)
|
||||||
|
new_title = title or filename
|
||||||
|
props = {"title": new_title, "mime": new_mime}
|
||||||
|
res, err = _upload_resource(user, "/resources", filename, content, new_mime, props, method="post")
|
||||||
|
if err:
|
||||||
|
return Response(f"Fehler: {err}", status_code=502)
|
||||||
|
new_rid = res.get("id", "")
|
||||||
|
r, err = _get(user, f"/notes/{note_id}", {"fields": "id,title,body"})
|
||||||
|
if err:
|
||||||
|
return Response(f"Anhang angelegt ({new_rid}), Notiz-Lesen fehlgeschlagen: {err}", status_code=200)
|
||||||
|
note = r.json()
|
||||||
|
new_body = (note.get("body", "") or "").rstrip() + "\n\n" + _resource_link(new_title, new_mime, new_rid) + "\n"
|
||||||
|
_, err = _put(user, f"/notes/{note_id}", {"body": new_body})
|
||||||
|
if err:
|
||||||
|
return Response(f"Anhang angelegt ({new_rid}), Verlinkung fehlgeschlagen: {err}", status_code=200)
|
||||||
|
return Response(f"ok resource {new_rid} angelegt + verlinkt", status_code=200)
|
||||||
|
|
||||||
|
return Response("resource_id oder note_id erforderlich", status_code=400)
|
||||||
|
|
||||||
|
|
||||||
def create_app():
|
def create_app():
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
mcp_app = mcp.streamable_http_app()
|
mcp_app = mcp.streamable_http_app()
|
||||||
@@ -306,11 +555,13 @@ def create_app():
|
|||||||
async with contextlib.AsyncExitStack() as stack:
|
async with contextlib.AsyncExitStack() as stack:
|
||||||
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
||||||
yield
|
yield
|
||||||
routes = list(OAUTH_ROUTES) + [Mount("/", app=mcp_app)]
|
routes = list(OAUTH_ROUTES) + [
|
||||||
|
Route("/raw", raw_resource, methods=["GET", "PUT"]),
|
||||||
|
] + [Mount("/", app=mcp_app)]
|
||||||
app = Starlette(routes=routes, lifespan=lifespan)
|
app = Starlette(routes=routes, lifespan=lifespan)
|
||||||
app.add_middleware(BearerAuthMiddleware)
|
app.add_middleware(BearerAuthMiddleware)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(create_app(), host="127.0.0.1", port=5104)
|
uvicorn.run(create_app(), host="0.0.0.0", port=5104)
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
"""MCP OpenWearables Server — read-only Abfrage der eigenen Wearable-Daten.
|
||||||
|
|
||||||
|
User-Trennung ueber das gemeinsame OAuth (common.get_current_user()):
|
||||||
|
- mycroft sendet MCP_BEARER (client_id=stefan) -> OpenWearables-User Stefan
|
||||||
|
- jarvis sendet MCP_BEARER (client_id=kati) -> OpenWearables-User Kati
|
||||||
|
|
||||||
|
Der OpenWearables-API-Key ist GLOBAL (nicht pro User gescoped). Die eigentliche
|
||||||
|
User-Trennung passiert HIER: die OpenWearables-User-ID wird IMMER aus dem Login
|
||||||
|
des Clients bestimmt und nie aus einem Tool-Argument uebernommen. Dadurch kann
|
||||||
|
ein Agent die Daten des anderen nicht ansprechen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from contextlib import AsyncExitStack, asynccontextmanager
|
||||||
|
from datetime import date, timedelta
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
from starlette.applications import Starlette
|
||||||
|
from starlette.routing import Mount
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
from common import OAUTH_ROUTES, BearerAuthMiddleware, get_current_user
|
||||||
|
|
||||||
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
with open(os.path.join(BASE_DIR, "config.json")) as f:
|
||||||
|
_cfg = json.load(f)
|
||||||
|
|
||||||
|
API_URL = _cfg["open_wearables_api_url"].rstrip("/")
|
||||||
|
API_KEY = _cfg["open_wearables_api_key"]
|
||||||
|
# Map local/openclaw user -> OpenWearables user UUID.
|
||||||
|
USER_ID_MAP = _cfg["user_id_map"]
|
||||||
|
|
||||||
|
|
||||||
|
class OpenWearablesError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user() -> str:
|
||||||
|
"""OpenWearables-User-ID des aktuell eingeloggten Clients."""
|
||||||
|
owner = get_current_user()
|
||||||
|
uid = USER_ID_MAP.get(owner or "")
|
||||||
|
if not uid:
|
||||||
|
raise OpenWearablesError(
|
||||||
|
"Zugriff verweigert: dieser Account hat keinen OpenWearables-User"
|
||||||
|
)
|
||||||
|
return uid
|
||||||
|
|
||||||
|
|
||||||
|
def _range(start: str, end: str) -> tuple[str, str]:
|
||||||
|
if start and end:
|
||||||
|
return start, end
|
||||||
|
e = date.today()
|
||||||
|
s = e - timedelta(days=14)
|
||||||
|
return s.isoformat(), e.isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def _request(path: str, params: dict | None = None) -> dict:
|
||||||
|
"""Blockierender API-Aufruf (MCP-Tools sind sync)."""
|
||||||
|
url = f"{API_URL}{path}"
|
||||||
|
try:
|
||||||
|
with httpx.Client(timeout=30) as client:
|
||||||
|
r = client.get(
|
||||||
|
url,
|
||||||
|
params=params,
|
||||||
|
headers={
|
||||||
|
"X-Open-Wearables-API-Key": API_KEY,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if r.status_code == 401:
|
||||||
|
raise OpenWearablesError("ungueltiger OpenWearables-API-Key")
|
||||||
|
if r.status_code == 404:
|
||||||
|
raise OpenWearablesError(f"nicht gefunden: {path}")
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
except OpenWearablesError:
|
||||||
|
raise
|
||||||
|
except httpx.HTTPError as ex:
|
||||||
|
raise OpenWearablesError(f"OpenWearables-API-Fehler: {ex}") from ex
|
||||||
|
|
||||||
|
|
||||||
|
mcp = FastMCP(
|
||||||
|
"OpenWearables",
|
||||||
|
stateless_http=True,
|
||||||
|
transport_security={"enable_dns_rebinding_protection": False},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_users() -> dict:
|
||||||
|
"""Discover OpenWearables users accessible to the current client.
|
||||||
|
|
||||||
|
Liefert NUR den eigenen Eintrag des eingeloggten Clients (stefan oder kati),
|
||||||
|
nie fremde User. Rueckgabe enthaelt OpenWearables user_id, email und Sync-Status.
|
||||||
|
"""
|
||||||
|
owner = get_current_user()
|
||||||
|
if not owner:
|
||||||
|
return {"error": "not authenticated"}
|
||||||
|
uid = USER_ID_MAP.get(owner)
|
||||||
|
if not uid:
|
||||||
|
return {"error": f"account '{owner}' hat keinen OpenWearables-User"}
|
||||||
|
try:
|
||||||
|
u = _request(f"/api/v1/users/{uid}")
|
||||||
|
except OpenWearablesError as e:
|
||||||
|
return {"error": str(e)}
|
||||||
|
return {
|
||||||
|
"users": [{
|
||||||
|
"id": u.get("id"),
|
||||||
|
"first_name": u.get("first_name"),
|
||||||
|
"last_name": u.get("last_name"),
|
||||||
|
"email": u.get("email"),
|
||||||
|
"external_user_id": u.get("external_user_id"),
|
||||||
|
"last_synced_at": u.get("last_synced_at"),
|
||||||
|
"last_synced_provider": u.get("last_synced_provider"),
|
||||||
|
"has_active_connection": u.get("has_active_connection"),
|
||||||
|
}],
|
||||||
|
"total": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_sleep_summary(start_date: str = "", end_date: str = "") -> dict:
|
||||||
|
"""Tages-Sleep-Summaries innerhalb eines Datumsbereichs (YYYY-MM-DD).
|
||||||
|
|
||||||
|
Liefert pro Nacht start_datetime, end_datetime und duration. Ohne Datums-
|
||||||
|
angabe werden die letzten 14 Tage genommen.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
s, e = _range(start_date, end_date)
|
||||||
|
return _request(
|
||||||
|
f"/api/v1/users/{_require_user()}/summaries/sleep",
|
||||||
|
{"start_date": s, "end_date": e, "limit": 100},
|
||||||
|
)
|
||||||
|
except OpenWearablesError as err:
|
||||||
|
return _err(err)
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_activity_summary(start_date: str = "", end_date: str = "") -> dict:
|
||||||
|
"""Tages-Aktivitaets-Summaries innerhalb eines Datumsbereichs.
|
||||||
|
|
||||||
|
Werte u.a.: steps, calories, heart rate, distance, Intensity Minutes.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
s, e = _range(start_date, end_date)
|
||||||
|
return _request(
|
||||||
|
f"/api/v1/users/{_require_user()}/summaries/activity",
|
||||||
|
{"start_date": s, "end_date": e, "limit": 100},
|
||||||
|
)
|
||||||
|
except OpenWearablesError as ex:
|
||||||
|
return {"error": str(ex)}
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_workout_events(start_date: str = "", end_date: str = "") -> dict:
|
||||||
|
"""Workout-Sessions innerhalb eines Datumsbereichs (YYYY-MM-DD).
|
||||||
|
|
||||||
|
Liefert sessions mit typ, duration, distance, calories. Default letzte 14 Tage.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
s, e = _range(start_date, end_date)
|
||||||
|
return _request(
|
||||||
|
f"/api/v1/users/{_require_user()}/events/workouts",
|
||||||
|
{"start_date": s, "end_date": e, "limit": 100},
|
||||||
|
)
|
||||||
|
except OpenWearablesError as ex:
|
||||||
|
return {"error": str(ex)}
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_timeseries(
|
||||||
|
types: list[str],
|
||||||
|
start_time: str = "",
|
||||||
|
end_time: str = "",
|
||||||
|
resolution: str = "raw",
|
||||||
|
) -> dict:
|
||||||
|
"""Granulare Zeitreihen-Samples (heart_rate, weight, SpO2, HRV, blood_glucose, ...).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
types: Liste an series type codes, z.B. ["heart_rate","oxygen_saturation"]
|
||||||
|
start_time/end_time: ISO-8601; ohne Angabe werden die letzten 24h genommen
|
||||||
|
resolution: raw|1min|5min|15min|1hour
|
||||||
|
"""
|
||||||
|
if not (start_time and end_time):
|
||||||
|
end = date.today()
|
||||||
|
start = end - timedelta(days=1)
|
||||||
|
start_time = f"{start.isoformat()}T00:00:00Z"
|
||||||
|
end_time = f"{end.isoformat()}T23:59:59Z"
|
||||||
|
joined = ",".join(types) if isinstance(types, list) else str(types)
|
||||||
|
try:
|
||||||
|
return _request(
|
||||||
|
f"/api/v1/users/{_require_user()}/timeseries",
|
||||||
|
{
|
||||||
|
"start_time": start_time,
|
||||||
|
"end_time": end_time,
|
||||||
|
"types": joined,
|
||||||
|
"resolution": resolution,
|
||||||
|
"limit": 100,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
except OpenWearablesError as ex:
|
||||||
|
return {"error": str(ex)}
|
||||||
|
|
||||||
|
|
||||||
|
def create_app():
|
||||||
|
mcp_app = mcp.streamable_http_app()
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app):
|
||||||
|
async with AsyncExitStack() as stack:
|
||||||
|
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
||||||
|
yield
|
||||||
|
|
||||||
|
routes = list(OAUTH_ROUTES) + [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=5105)
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
"""Shared OWA (Exchange) JSON-API client for the BBS mailbox (Kati).
|
||||||
|
|
||||||
|
Used by the mail MCP server (server.py) and by the calendar fetcher
|
||||||
|
(/opt/owa-kati-calendar/owa_fetch.py).
|
||||||
|
|
||||||
|
Exchange 2019 (S25-EXCHANGE) with classic OWA form login under
|
||||||
|
https://bbsbex.bbsb.org/owa/. EWS basic auth is disabled (401), so access
|
||||||
|
goes through the OWA form flow with an HTTP session and the internal
|
||||||
|
OWA JSON API (/owa/service.svc?action=...).
|
||||||
|
|
||||||
|
HARTE REGEL (lockout protection): exactly ONE login attempt per process.
|
||||||
|
On any login failure the caller aborts immediately, no retry, so Kati's work
|
||||||
|
password is never locked by automatic repetitions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
OWA_BASE = os.environ.get("OWA_BASE", "https://bbsbex.bbsb.org/owa").rstrip("/")
|
||||||
|
AUTH_FILE = os.environ.get(
|
||||||
|
"OWA_AUTH_FILE", "/opt/mcp-servers/owamail/auth.txt"
|
||||||
|
)
|
||||||
|
LOGIN_URL = OWA_BASE + "/auth.owa"
|
||||||
|
SERVICE_URL = OWA_BASE + "/service.svc"
|
||||||
|
SESSION_MAX_AGE_S = 600 # 10 min, then a fresh login
|
||||||
|
|
||||||
|
|
||||||
|
class OWASessionError(Exception):
|
||||||
|
"""Session expired / login failed."""
|
||||||
|
|
||||||
|
|
||||||
|
_DISTINGUISHED = {
|
||||||
|
"msgfolderroot", "inbox", "sentitems", "drafts", "deleteditems",
|
||||||
|
"junkemail", "outbox", "calendar", "contacts", "tasks", "notes",
|
||||||
|
"journal", "searchfolders",
|
||||||
|
}
|
||||||
|
|
||||||
|
_FOLDER_ALIASES = {
|
||||||
|
"posteingang": "inbox",
|
||||||
|
"inbox": "inbox",
|
||||||
|
"gesendet": "sentitems",
|
||||||
|
"sent": "sentitems",
|
||||||
|
"gesendete objekte": "sentitems",
|
||||||
|
"entwürfe": "drafts",
|
||||||
|
"entwuerfe": "drafts",
|
||||||
|
"drafts": "drafts",
|
||||||
|
"gelöschte objekte": "deleteditems",
|
||||||
|
"geloeschte objekte": "deleteditems",
|
||||||
|
"papierkorb": "deleteditems",
|
||||||
|
"deleted": "deleteditems",
|
||||||
|
"junk": "junkemail",
|
||||||
|
"spam": "junkemail",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def load_creds(auth_file: str = AUTH_FILE):
|
||||||
|
with open(auth_file) as f:
|
||||||
|
data = {}
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if "=" in line and not line.startswith("#"):
|
||||||
|
k, v = line.split("=", 1)
|
||||||
|
data[k.strip()] = v.strip()
|
||||||
|
return data.get("BBS_USER", ""), data.get("BBS_PASSWORD", "")
|
||||||
|
|
||||||
|
|
||||||
|
def new_session() -> requests.Session:
|
||||||
|
s = requests.Session()
|
||||||
|
s.headers.update({
|
||||||
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36",
|
||||||
|
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||||
|
})
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
class OWAClient:
|
||||||
|
"""OWA JSON-API client with a single-process session cache."""
|
||||||
|
|
||||||
|
def __init__(self, base: str = OWA_BASE, auth_file: str = AUTH_FILE,
|
||||||
|
session_max_age: int = SESSION_MAX_AGE_S):
|
||||||
|
self.base = base.rstrip("/")
|
||||||
|
self.auth_file = auth_file
|
||||||
|
self.session_max_age = session_max_age
|
||||||
|
self._session = None
|
||||||
|
self._session_ts = 0.0
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Login (lockout protection: EXACTLY ONE attempt)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def login(self) -> str:
|
||||||
|
"""Exactly ONE login attempt. Aborts immediately on failure, no retry."""
|
||||||
|
user, password = load_creds(self.auth_file)
|
||||||
|
if not user or not password:
|
||||||
|
return f"Fehler: BBS-Credentials fehlen in {self.auth_file}"
|
||||||
|
|
||||||
|
s = new_session()
|
||||||
|
login_url = self.base + "/auth.owa"
|
||||||
|
try:
|
||||||
|
r = s.get(login_url, timeout=30)
|
||||||
|
r.raise_for_status()
|
||||||
|
fields = {
|
||||||
|
"destination": self.base,
|
||||||
|
"flags": "4",
|
||||||
|
"forcedownlevel": "0",
|
||||||
|
"isUtf8": "1",
|
||||||
|
"username": user,
|
||||||
|
"password": password,
|
||||||
|
"passwordText": "",
|
||||||
|
}
|
||||||
|
r2 = s.post(login_url, data=fields, allow_redirects=True, timeout=30)
|
||||||
|
cookie_names = [c.name for c in s.cookies]
|
||||||
|
# Exchange 2019 sets X-OWA-CANARY + X-BackEndCookie on success,
|
||||||
|
# not an 'OWASession' cookie. These two are the success criterion.
|
||||||
|
has_session_cookie = (
|
||||||
|
"X-OWA-CANARY" in cookie_names and "X-BackEndCookie" in cookie_names
|
||||||
|
)
|
||||||
|
if has_session_cookie:
|
||||||
|
self._session = s
|
||||||
|
self._session_ts = time.time()
|
||||||
|
return "LOGIN_OK"
|
||||||
|
if r2.status_code == 200 and "logon.aspx" in r2.url:
|
||||||
|
return ("LOGIN_FEHLGESCHLAGEN: OWA-Login abgelehnt (falsche "
|
||||||
|
"Zugangsdaten oder Konto gesperrt). Kein Retry.")
|
||||||
|
return (
|
||||||
|
"LOGIN_FEHLGESCHLAGEN: Keine OWA-Session gesetzt "
|
||||||
|
f"(Status {r2.status_code}, Cookies: {cookie_names}). Kein Retry."
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
return f"LOGIN_FEHLGESCHLAGEN: {e}"
|
||||||
|
|
||||||
|
def ensure_session(self) -> str:
|
||||||
|
if self._session is None:
|
||||||
|
return self.login()
|
||||||
|
if time.time() - self._session_ts > self.session_max_age:
|
||||||
|
self._session = None
|
||||||
|
return self.login()
|
||||||
|
return "LOGIN_OK"
|
||||||
|
|
||||||
|
def session(self) -> requests.Session:
|
||||||
|
res = self.ensure_session()
|
||||||
|
if res != "LOGIN_OK":
|
||||||
|
raise OWASessionError(res)
|
||||||
|
return self._session
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# OWA JSON-API
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def header(server_version: str = "Exchange2013") -> dict:
|
||||||
|
return {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": server_version,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_canary(sess: requests.Session) -> str:
|
||||||
|
for c in sess.cookies:
|
||||||
|
if c.name == "X-OWA-CANARY" and c.value:
|
||||||
|
return c.value
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def api(self, action: str, payload: dict, *, timeout: int = 30) -> dict:
|
||||||
|
"""POST to the OWA JSON API. Raises OWASessionError on session expiry."""
|
||||||
|
s = self.session()
|
||||||
|
canary = self.get_canary(s)
|
||||||
|
url = f"{self.base}/service.svc?action={action}&EP=1&ID=-1&AC=1"
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
"Action": action,
|
||||||
|
"X-OWA-CANARY": canary,
|
||||||
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
r = s.post(url, json=payload, headers=headers, timeout=timeout)
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
raise OWASessionError(f"Request fehlgeschlagen: {e}")
|
||||||
|
|
||||||
|
new_canary = self.get_canary(s)
|
||||||
|
if new_canary:
|
||||||
|
s.cookies.set("X-OWA-CANARY", new_canary)
|
||||||
|
|
||||||
|
if r.status_code in (401, 440):
|
||||||
|
raise OWASessionError(f"Session abgelaufen (HTTP {r.status_code})")
|
||||||
|
if "text/html" in r.headers.get("Content-Type", ""):
|
||||||
|
raise OWASessionError(
|
||||||
|
f"Session abgelaufen oder ungueltige Action (HTML, HTTP {r.status_code})"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return r.json()
|
||||||
|
except ValueError:
|
||||||
|
raise OWASessionError(f"Unerwartete Antwort (HTTP {r.status_code})")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def items(data: dict) -> list:
|
||||||
|
try:
|
||||||
|
return data["Body"]["ResponseMessages"]["Items"]
|
||||||
|
except (KeyError, TypeError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
def resolve_folder_id(self, name: str):
|
||||||
|
"""Folder name (de/en) -> real numeric Exchange FolderId."""
|
||||||
|
alias = _FOLDER_ALIASES.get(name.strip().lower(), name.strip().lower())
|
||||||
|
if alias in _DISTINGUISHED:
|
||||||
|
payload = {
|
||||||
|
"__type": "GetFolderJsonRequest:#Exchange",
|
||||||
|
"Header": self.header(),
|
||||||
|
"Body": {
|
||||||
|
"__type": "GetFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "IdOnly",
|
||||||
|
},
|
||||||
|
"FolderIds": [
|
||||||
|
{"__type": "DistinguishedFolderId:#Exchange", "Id": alias}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = self.api("GetFolder", payload)
|
||||||
|
for msg in self.items(data):
|
||||||
|
if "Folders" in msg:
|
||||||
|
for f in msg["Folders"]:
|
||||||
|
fid = f.get("FolderId", {}).get("Id")
|
||||||
|
if fid:
|
||||||
|
return fid
|
||||||
|
payload = {
|
||||||
|
"__type": "FindFolderJsonRequest:#Exchange",
|
||||||
|
"Header": self.header(),
|
||||||
|
"Body": {
|
||||||
|
"__type": "FindFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "Default",
|
||||||
|
},
|
||||||
|
"ParentFolderIds": [
|
||||||
|
{"__type": "DistinguishedFolderId:#Exchange", "Id": "msgfolderroot"}
|
||||||
|
],
|
||||||
|
"Traversal": "Shallow",
|
||||||
|
"Paging": {
|
||||||
|
"__type": "IndexedPageView:#Exchange",
|
||||||
|
"BasePoint": "Beginning",
|
||||||
|
"Offset": 0,
|
||||||
|
"MaxEntriesReturned": 200,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = self.api("FindFolder", payload)
|
||||||
|
for msg in self.items(data):
|
||||||
|
if "RootFolder" in msg and "Folders" in msg["RootFolder"]:
|
||||||
|
for f in msg["RootFolder"]["Folders"]:
|
||||||
|
if f.get("DisplayName", "").lower() == name.strip().lower():
|
||||||
|
return f.get("FolderId", {}).get("Id")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def download_file(self, attachment_id: str, timeout: int = 60):
|
||||||
|
"""Download an attachment via GetFileAttachment. Returns (bytes, filename, content_type)."""
|
||||||
|
s = self.session()
|
||||||
|
canary = self.get_canary(s)
|
||||||
|
url = (
|
||||||
|
f"{self.base}/service.svc/s/GetFileAttachment"
|
||||||
|
f"?id={urllib.parse.quote(attachment_id)}&X-OWA-CANARY={urllib.parse.quote(canary)}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
resp = s.get(url, timeout=timeout)
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
raise OWASessionError(f"Download fehlgeschlagen: {e}")
|
||||||
|
if resp.status_code in (401, 440):
|
||||||
|
raise OWASessionError(f"Session abgelaufen (HTTP {resp.status_code})")
|
||||||
|
if "text/html" in resp.headers.get("Content-Type", ""):
|
||||||
|
raise OWASessionError("Session abgelaufen (HTML-Antwort beim Download)")
|
||||||
|
|
||||||
|
filename = "attachment"
|
||||||
|
cd = resp.headers.get("Content-Disposition", "")
|
||||||
|
if cd:
|
||||||
|
m = re.search(r'filename\*=(?:UTF-8\'\'|utf-8\'\')(.+?)(?:;|$)', cd)
|
||||||
|
if m:
|
||||||
|
filename = urllib.parse.unquote(m.group(1).strip())
|
||||||
|
else:
|
||||||
|
m = re.search(r'filename="?([^";]+)"?', cd)
|
||||||
|
if m:
|
||||||
|
filename = urllib.parse.unquote(m.group(1).strip())
|
||||||
|
content_type = resp.headers.get("Content-Type", "application/octet-stream")
|
||||||
|
if ";" in content_type:
|
||||||
|
content_type = content_type.split(";", 1)[0].strip()
|
||||||
|
return resp.content, filename, content_type
|
||||||
|
|
||||||
|
|
||||||
|
# Default client for single-process consumers (mail MCP server).
|
||||||
|
client = OWAClient()
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
"""MCP OWA Mail Server — Zugriff auf die BBS-Arbeits-Mail (Kati) ueber die OWA-JSON-API.
|
||||||
|
|
||||||
|
Exchange 2019 (S25-EXCHANGE) mit klassischem OWA-Formular-Login unter
|
||||||
|
https://bbsbex.bbsb.org/owa/. EWS-Basic-Auth ist serverseitig deaktiviert
|
||||||
|
(401), daher Zugriff ueber den OWA-Formular-Flow mit HTTP-Session und die
|
||||||
|
interne OWA-JSON-API (/owa/service.svc?action=...).
|
||||||
|
|
||||||
|
HARTE REGEL (Sperrschutz): Genau EIN Login-Versuch pro Sitzung. Bei jedem
|
||||||
|
Login-Fehlschlag wird SOFORT abgebrochen und kein Retry unternommen, damit
|
||||||
|
Katis Arbeitspasswort nie durch automatische Wiederholungen gesperrt wird.
|
||||||
|
|
||||||
|
Tools: login (Einmal-Versuch), list_folders, search_mail, read_mail,
|
||||||
|
create_draft (Entwurf im Drafts-Ordner, KEIN Senden).
|
||||||
|
|
||||||
|
API-Muster aus https://github.com/nhype/owa-exchange-mcp (MIT, 2026):
|
||||||
|
POST /owa/service.svc?action=<Action>&EP=1&ID=-1&AC=1
|
||||||
|
mit Action-Header, X-OWA-CANARY und JSON-Payload im Exchange-JSON-Schema.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import contextlib
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from pydantic import Field
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
from starlette.applications import Starlette
|
||||||
|
from starlette.routing import Mount
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
||||||
|
from utils import html_to_text
|
||||||
|
from owa_client import OWASessionError, client as _owa
|
||||||
|
|
||||||
|
# Transport/Login lebt im gemeinsamen Modul (auch vom Kalender-Fetcher genutzt).
|
||||||
|
_api = _owa.api
|
||||||
|
_items = _owa.items
|
||||||
|
_header = _owa.header
|
||||||
|
_resolve_folder_id = _owa.resolve_folder_id
|
||||||
|
_owa_login = _owa.login
|
||||||
|
_get_session = _owa.session
|
||||||
|
_download_file = _owa.download_file
|
||||||
|
|
||||||
|
# Nur Katis Arbeitsmail: erlaubte Bearer-User. `mcptest` fuer lokale Tests.
|
||||||
|
ALLOWED_USERS = {"kati", "mcptest"}
|
||||||
|
|
||||||
|
|
||||||
|
def _check_user():
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return None, "Error: not authenticated"
|
||||||
|
if user not in ALLOWED_USERS:
|
||||||
|
return None, "Zugriff verweigert: owamail ist nur fuer Katis Arbeitsmail (kati)."
|
||||||
|
return user, None
|
||||||
|
|
||||||
|
mcp = FastMCP("OWAMail", stateless_http=True,
|
||||||
|
transport_security={"enable_dns_rebinding_protection": False})
|
||||||
|
|
||||||
|
|
||||||
|
def _recipients(emails: str) -> list:
|
||||||
|
out = []
|
||||||
|
for addr in emails.split(","):
|
||||||
|
addr = addr.strip()
|
||||||
|
if addr:
|
||||||
|
out.append({
|
||||||
|
"Name": addr,
|
||||||
|
"EmailAddress": addr,
|
||||||
|
"RoutingType": "SMTP",
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _sender_of(item: dict) -> str:
|
||||||
|
mb = item.get("From", {}).get("Mailbox", {})
|
||||||
|
if not mb:
|
||||||
|
mb = item.get("Sender", {}).get("Mailbox", {})
|
||||||
|
if not mb:
|
||||||
|
mb = item.get("Organizer", {}).get("Mailbox", {})
|
||||||
|
name = str(mb.get("Name", "") or "")
|
||||||
|
addr = str(mb.get("EmailAddress", "") or "")
|
||||||
|
return f"{name} <{addr}>" if name else addr
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Tools
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def login() -> str:
|
||||||
|
"""Log in to the BBS OWA mailbox. Exactly ONE login attempt; aborts on failure (no retry)."""
|
||||||
|
user, err = _check_user()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
return _owa_login()
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def list_folders() -> str:
|
||||||
|
"""List the top-level folders of the BBS mailbox with unread counts."""
|
||||||
|
user, err = _check_user()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
try:
|
||||||
|
payload = {
|
||||||
|
"__type": "FindFolderJsonRequest:#Exchange",
|
||||||
|
"Header": _header(),
|
||||||
|
"Body": {
|
||||||
|
"__type": "FindFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "Default",
|
||||||
|
},
|
||||||
|
"ParentFolderIds": [
|
||||||
|
{"__type": "DistinguishedFolderId:#Exchange", "Id": "msgfolderroot"}
|
||||||
|
],
|
||||||
|
"Traversal": "Shallow",
|
||||||
|
"Paging": {
|
||||||
|
"__type": "IndexedPageView:#Exchange",
|
||||||
|
"BasePoint": "Beginning",
|
||||||
|
"Offset": 0,
|
||||||
|
"MaxEntriesReturned": 200,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = _api("FindFolder", payload)
|
||||||
|
except OWASessionError as e:
|
||||||
|
return f"Fehler: {e}"
|
||||||
|
folders = []
|
||||||
|
for msg in _items(data):
|
||||||
|
if "RootFolder" in msg and "Folders" in msg["RootFolder"]:
|
||||||
|
for f in msg["RootFolder"]["Folders"]:
|
||||||
|
folders.append(
|
||||||
|
f"{f.get('DisplayName', '?')} "
|
||||||
|
f"(id: {f.get('FolderId', {}).get('Id', '')}, "
|
||||||
|
f"gesamt: {f.get('TotalCount', 0)}, ungelesen: {f.get('UnreadCount', 0)})"
|
||||||
|
)
|
||||||
|
return "\n".join(folders) if folders else "Keine Ordner gefunden"
|
||||||
|
|
||||||
|
|
||||||
|
def _find_items(fid, limit=50, offset=0):
|
||||||
|
"""Ein FindItem-Aufruf. Gibt (items, total, includes_last)."""
|
||||||
|
payload = {
|
||||||
|
"__type": "FindItemJsonRequest:#Exchange",
|
||||||
|
"Header": _header(),
|
||||||
|
"Body": {
|
||||||
|
"__type": "FindItemRequest:#Exchange",
|
||||||
|
"ItemShape": {
|
||||||
|
"__type": "ItemResponseShape:#Exchange",
|
||||||
|
"BaseShape": "AllProperties",
|
||||||
|
},
|
||||||
|
"ParentFolderIds": [
|
||||||
|
{"__type": "FolderId:#Exchange", "Id": fid}
|
||||||
|
],
|
||||||
|
"Traversal": "Shallow",
|
||||||
|
"Paging": {
|
||||||
|
"__type": "IndexedPageView:#Exchange",
|
||||||
|
"BasePoint": "Beginning",
|
||||||
|
"Offset": offset,
|
||||||
|
"MaxEntriesReturned": limit,
|
||||||
|
},
|
||||||
|
"SortOrder": [
|
||||||
|
{
|
||||||
|
"__type": "SortResults:#Exchange",
|
||||||
|
"Order": "Descending",
|
||||||
|
"Path": {
|
||||||
|
"__type": "PropertyUri:#Exchange",
|
||||||
|
"FieldURI": "DateTimeReceived",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = _api("FindItem", payload)
|
||||||
|
items = []
|
||||||
|
total = 0
|
||||||
|
includes_last = True
|
||||||
|
for msg in _items(data):
|
||||||
|
rf = msg.get("RootFolder") or {}
|
||||||
|
items = rf.get("Items") or []
|
||||||
|
total = rf.get("TotalItemsInView", 0) or 0
|
||||||
|
if total < 0:
|
||||||
|
total = 0 # Exchange liefert -1 wenn unbekannt
|
||||||
|
includes_last = rf.get("IncludesLastItemInRange", True)
|
||||||
|
break
|
||||||
|
return items, total, includes_last
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_item(it):
|
||||||
|
subj = str(it.get("Subject", "") or "")
|
||||||
|
snd = str(_sender_of(it) or "")
|
||||||
|
return (
|
||||||
|
f"[{it.get('DateTimeReceived', it.get('DateTimeSent', ''))}] "
|
||||||
|
f"Von: {snd} | Betreff: {subj} | id: {it.get('ItemId', {}).get('Id', '')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def search_mail(
|
||||||
|
query: Annotated[str, Field(description="Suchbegriff (Betreff/Absender)")] = "",
|
||||||
|
folder: Annotated[str, Field(description="Ordner, z.B. 'Inbox', 'Entwuerfe'. Leer fuer Posteingang.")] = "Inbox",
|
||||||
|
limit: Annotated[int, Field(description="Max. Ergebnisse pro Seite (max 50)")] = 10,
|
||||||
|
offset: Annotated[int, Field(description="Start-Index (fuer Paging; 0 = neueste)")] = 0,
|
||||||
|
scan_all: Annotated[bool, Field(description="True = alle Seiten durchblaettern bis der Suchbegriff gefunden ist (bis max 500 Mails). False = nur die aktuelle Seite.")] = False,
|
||||||
|
) -> str:
|
||||||
|
"""Search the BBS mailbox for emails (subject/sender match).
|
||||||
|
|
||||||
|
Mit scan_all=True und einem Suchbegriff werden auch alte Mails gefunden
|
||||||
|
(blättert durch den ganzen Ordner, nicht nur die ersten 50). Ohne Query
|
||||||
|
liefert der Aufruf eine Seite (limit/offset) mit Gesamtzahl und
|
||||||
|
Blätter-Hinweis.
|
||||||
|
"""
|
||||||
|
user, err = _check_user()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
limit = max(1, min(limit, 50))
|
||||||
|
offset = max(0, offset)
|
||||||
|
q = query.strip().lower()
|
||||||
|
try:
|
||||||
|
fid = _resolve_folder_id(folder)
|
||||||
|
if not fid:
|
||||||
|
return f"Ordner '{folder}' nicht gefunden"
|
||||||
|
|
||||||
|
if scan_all and q:
|
||||||
|
# Alle Seiten durchblaettern (deckelt bei MAX_SCAN), Treffer sammeln
|
||||||
|
results = []
|
||||||
|
off = 0
|
||||||
|
page = 50
|
||||||
|
seen = 0
|
||||||
|
max_scan = 2000
|
||||||
|
limit_reached = False
|
||||||
|
while off < max_scan:
|
||||||
|
items, total, includes_last = _find_items(fid, page, off)
|
||||||
|
for it in items:
|
||||||
|
if not isinstance(it, dict):
|
||||||
|
continue
|
||||||
|
seen += 1
|
||||||
|
subj = str(it.get("Subject", "") or "")
|
||||||
|
snd = str(_sender_of(it) or "")
|
||||||
|
if q in subj.lower() or q in snd.lower():
|
||||||
|
results.append(it)
|
||||||
|
if not items or includes_last:
|
||||||
|
break
|
||||||
|
off += len(items)
|
||||||
|
else:
|
||||||
|
limit_reached = True
|
||||||
|
lines = [_fmt_item(it) for it in results[:limit]]
|
||||||
|
if results:
|
||||||
|
head = f"{len(results)} Treffer in {seen} geprueften Mails"
|
||||||
|
elif limit_reached:
|
||||||
|
head = f"Keine Treffer in den ersten {seen} Mails (Ordner groesser; mit folder= und offset= gezielt weiterblaettern)"
|
||||||
|
else:
|
||||||
|
head = f"Keine Treffer (durchsucht: {seen} Mails)"
|
||||||
|
body = "\n".join(lines)
|
||||||
|
return head + (f"\n{body}" if body else "")
|
||||||
|
else:
|
||||||
|
# Eine Seite
|
||||||
|
items, total, includes_last = _find_items(fid, limit, offset)
|
||||||
|
lines = []
|
||||||
|
for it in items:
|
||||||
|
if not isinstance(it, dict):
|
||||||
|
continue
|
||||||
|
subj = str(it.get("Subject", "") or "")
|
||||||
|
snd = str(_sender_of(it) or "")
|
||||||
|
if q and q not in subj.lower() and q not in snd.lower():
|
||||||
|
continue
|
||||||
|
lines.append(_fmt_item(it))
|
||||||
|
more = "" if includes_last else f" | mehr vorhanden (Offset {offset+limit} fuer die naechste Seite)"
|
||||||
|
head = f"Ordner hat {total} Mails; zeige {len(lines)} (Offset {offset}){more}"
|
||||||
|
body = "\n".join(lines)
|
||||||
|
return head + (f"\n{body}" if body else "")
|
||||||
|
except OWASessionError as e:
|
||||||
|
return f"Fehler: {e}"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def read_mail(
|
||||||
|
item_id: Annotated[str, Field(description="Mail-ID aus search_mail")],
|
||||||
|
) -> str:
|
||||||
|
"""Read a full email (body, recipients, attachments) by item ID."""
|
||||||
|
user, err = _check_user()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
try:
|
||||||
|
payload = {
|
||||||
|
"__type": "GetItemJsonRequest:#Exchange",
|
||||||
|
"Header": _header("V2017_08_18"),
|
||||||
|
"Body": {
|
||||||
|
"__type": "GetItemRequest:#Exchange",
|
||||||
|
"ItemShape": {
|
||||||
|
"__type": "ItemResponseShape:#Exchange",
|
||||||
|
"BaseShape": "AllProperties",
|
||||||
|
"BodyType": "HTML",
|
||||||
|
},
|
||||||
|
"ItemIds": [{"__type": "ItemId:#Exchange", "Id": item_id}],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = _api("GetItem", payload)
|
||||||
|
except OWASessionError as e:
|
||||||
|
return f"Fehler: {e}"
|
||||||
|
for msg in _items(data):
|
||||||
|
if "Items" not in msg or not msg["Items"]:
|
||||||
|
continue
|
||||||
|
for it in msg["Items"]:
|
||||||
|
body_val = it.get("Body", {}).get("Value", "")
|
||||||
|
body_type = it.get("Body", {}).get("BodyType", "Text")
|
||||||
|
body = html_to_text(body_val) if body_type == "HTML" else body_val
|
||||||
|
to_list = ", ".join(
|
||||||
|
r.get("EmailAddress", "") for r in it.get("ToRecipients", [])
|
||||||
|
)
|
||||||
|
cc_list = ", ".join(
|
||||||
|
r.get("EmailAddress", "") for r in it.get("CcRecipients", [])
|
||||||
|
)
|
||||||
|
atts = ", ".join(
|
||||||
|
f"{a.get('Name', '?')} [id={a.get('AttachmentId', {}).get('Id', '')}]"
|
||||||
|
for a in it.get("Attachments", [])
|
||||||
|
) or "keine"
|
||||||
|
return (
|
||||||
|
f"Von: {_sender_of(it)}\n"
|
||||||
|
f"An: {to_list}\n"
|
||||||
|
f"Cc: {cc_list or '-'}\n"
|
||||||
|
f"Betreff: {it.get('Subject', '')}\n"
|
||||||
|
f"Datum: {it.get('DateTimeSent', it.get('DateTimeReceived', ''))}\n"
|
||||||
|
f"Anhaenge: {atts}\n\n"
|
||||||
|
f"{body}"
|
||||||
|
)
|
||||||
|
return "Mail nicht gefunden"
|
||||||
|
|
||||||
|
|
||||||
|
def _attachment_ids(item_id: str):
|
||||||
|
"""Holt die Anhaenge (Name + AttachmentId) einer Mail via GetItem."""
|
||||||
|
payload = {
|
||||||
|
"__type": "GetItemJsonRequest:#Exchange",
|
||||||
|
"Header": _header("V2017_08_18"),
|
||||||
|
"Body": {
|
||||||
|
"__type": "GetItemRequest:#Exchange",
|
||||||
|
"ItemShape": {
|
||||||
|
"__type": "ItemResponseShape:#Exchange",
|
||||||
|
"BaseShape": "AllProperties",
|
||||||
|
"BodyType": "HTML",
|
||||||
|
},
|
||||||
|
"ItemIds": [{"__type": "ItemId:#Exchange", "Id": item_id}],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = _api("GetItem", payload)
|
||||||
|
for msg in _items(data):
|
||||||
|
if "Items" not in msg or not msg["Items"]:
|
||||||
|
continue
|
||||||
|
for it in msg["Items"]:
|
||||||
|
if not isinstance(it, dict):
|
||||||
|
continue
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": a.get("Name", "attachment"),
|
||||||
|
"attachment_id": a.get("AttachmentId", {}).get("Id", ""),
|
||||||
|
}
|
||||||
|
for a in it.get("Attachments", [])
|
||||||
|
if a.get("AttachmentId", {}).get("Id")
|
||||||
|
]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def download_attachments(
|
||||||
|
item_id: Annotated[str, Field(description="Mail-ID aus search_mail")],
|
||||||
|
target_dir: Annotated[str, Field(description="Zielverzeichnis (Host-Pfad), z.B. /mnt/ssd/LongTermStorage/openclaw-docker-20260919/ssd-openclaw/jarvis/data/workspace/owa-attachments")] = "/mnt/ssd/LongTermStorage/openclaw-docker-20260919/ssd-openclaw/jarvis/data/workspace/owa-attachments",
|
||||||
|
) -> str:
|
||||||
|
"""Download all attachments of an email to a directory on the host."""
|
||||||
|
user, err = _check_user()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
try:
|
||||||
|
atts = _attachment_ids(item_id)
|
||||||
|
if not atts:
|
||||||
|
return "Keine Anhaenge in dieser Mail."
|
||||||
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
saved = []
|
||||||
|
for a in atts:
|
||||||
|
try:
|
||||||
|
content, fname, ctype = _download_file(a["attachment_id"])
|
||||||
|
fname = os.path.basename(fname) or a["name"]
|
||||||
|
path = os.path.join(target_dir, fname)
|
||||||
|
with open(path, "wb") as f:
|
||||||
|
f.write(content)
|
||||||
|
saved.append(f"{fname} ({len(content)} bytes)")
|
||||||
|
except OWASessionError as e:
|
||||||
|
return f"Fehler: {e}"
|
||||||
|
return "Heruntergeladen:\n" + "\n".join(saved) if saved else "Keine Anhaenge"
|
||||||
|
except OWASessionError as e:
|
||||||
|
return f"Fehler: {e}"
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def create_draft(
|
||||||
|
to: Annotated[str, Field(description="Empfaenger (E-Mail)")],
|
||||||
|
subject: Annotated[str, Field(description="Betreff")],
|
||||||
|
body: Annotated[str, Field(description="Mailtext")],
|
||||||
|
cc: Annotated[str, Field(description="CC (kommagetrennt, optional)")] = "",
|
||||||
|
bcc: Annotated[str, Field(description="BCC (kommagetrennt, optional)")] = "",
|
||||||
|
) -> str:
|
||||||
|
"""Create an email draft in the BBS mailbox Drafts folder. Does NOT send."""
|
||||||
|
user, err = _check_user()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
try:
|
||||||
|
to_rcpts = _recipients(to)
|
||||||
|
if not to_rcpts:
|
||||||
|
return "Fehler: Mindestens ein Empfaenger erforderlich"
|
||||||
|
message = {
|
||||||
|
"__type": "Message:#Exchange",
|
||||||
|
"Subject": subject,
|
||||||
|
"Body": {
|
||||||
|
"__type": "BodyContentType:#Exchange",
|
||||||
|
"BodyType": "Text",
|
||||||
|
"Value": body,
|
||||||
|
},
|
||||||
|
"ToRecipients": to_rcpts,
|
||||||
|
}
|
||||||
|
if cc:
|
||||||
|
message["CcRecipients"] = _recipients(cc)
|
||||||
|
if bcc:
|
||||||
|
message["BccRecipients"] = _recipients(bcc)
|
||||||
|
payload = {
|
||||||
|
"__type": "CreateItemJsonRequest:#Exchange",
|
||||||
|
"Header": _header("V2017_08_18"),
|
||||||
|
"Body": {
|
||||||
|
"__type": "CreateItemRequest:#Exchange",
|
||||||
|
"Items": [message],
|
||||||
|
"MessageDisposition": "SaveOnly",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = _api("CreateItem", payload)
|
||||||
|
except OWASessionError as e:
|
||||||
|
return f"Fehler: {e}"
|
||||||
|
for msg in _items(data):
|
||||||
|
if msg.get("ResponseClass") == "Error":
|
||||||
|
return f"Fehler: {msg.get('MessageText', 'Entwurf fehlgeschlagen')}"
|
||||||
|
return f"Entwurf erstellt (An {to}, Betreff '{subject}'). Liegt im Drafts-Ordner, wurde NICHT gesendet."
|
||||||
|
|
||||||
|
|
||||||
|
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) + [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=5131)
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""Shared utility functions for the Exchange MCP server.
|
||||||
|
|
||||||
|
Extracts duplicated helpers from the standalone scripts:
|
||||||
|
html_to_text, date/time formatting and parsing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import html
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
def html_to_text(html_content: str) -> str:
|
||||||
|
"""Convert HTML to plain text.
|
||||||
|
|
||||||
|
Strips scripts, styles, converts <br>/<p>/<div> to newlines,
|
||||||
|
removes remaining tags, and unescapes HTML entities.
|
||||||
|
"""
|
||||||
|
if not html_content:
|
||||||
|
return ""
|
||||||
|
text = re.sub(
|
||||||
|
r"<script[^>]*>.*?</script>", "", html_content, flags=re.DOTALL | re.IGNORECASE
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE
|
||||||
|
)
|
||||||
|
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"<p[^>]*>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"</p>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"<div[^>]*>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"<[^>]+>", "", text)
|
||||||
|
text = html.unescape(text)
|
||||||
|
text = re.sub(r"\n\s*\n", "\n\n", text)
|
||||||
|
text = re.sub(r"[ \t]+", " ", text)
|
||||||
|
return text.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def extract_links_from_html(html_content: str) -> list[dict]:
|
||||||
|
"""Extract hyperlinks from HTML content.
|
||||||
|
|
||||||
|
Finds <a href="...">text</a> patterns, excludes mailto:, cid:,
|
||||||
|
javascript:, and fragment-only (#) links. Deduplicates by URL.
|
||||||
|
|
||||||
|
Returns list of {url, text} dicts.
|
||||||
|
"""
|
||||||
|
if not html_content:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Match <a ...href="URL"...>text</a>
|
||||||
|
pattern = re.compile(
|
||||||
|
r'<a\s[^>]*href=["\']([^"\']+)["\'][^>]*>(.*?)</a>',
|
||||||
|
re.DOTALL | re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
seen: set[str] = set()
|
||||||
|
links: list[dict] = []
|
||||||
|
|
||||||
|
for url_raw, text_raw in pattern.findall(html_content):
|
||||||
|
url = html.unescape(url_raw).strip()
|
||||||
|
|
||||||
|
# Skip non-http links
|
||||||
|
if url.startswith(("mailto:", "cid:", "javascript:")) or url == "#":
|
||||||
|
continue
|
||||||
|
# Skip fragment-only links
|
||||||
|
if url.startswith("#"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if url in seen:
|
||||||
|
continue
|
||||||
|
seen.add(url)
|
||||||
|
|
||||||
|
# Clean link text: strip tags and whitespace
|
||||||
|
text = re.sub(r"<[^>]+>", "", text_raw)
|
||||||
|
text = html.unescape(text).strip()
|
||||||
|
|
||||||
|
links.append({"url": url, "text": text})
|
||||||
|
|
||||||
|
return links
|
||||||
|
|
||||||
|
|
||||||
|
def format_datetime(dt_str: str) -> str:
|
||||||
|
"""Format an ISO datetime string as 'YYYY-MM-DD HH:MM'.
|
||||||
|
|
||||||
|
Strips timezone suffixes (Z, +offset) for cleaner display.
|
||||||
|
"""
|
||||||
|
if not dt_str:
|
||||||
|
return ""
|
||||||
|
if "T" in dt_str:
|
||||||
|
date_part, time_part = dt_str.split("T", 1)
|
||||||
|
time_part = time_part.split("Z")[0].split("+")[0]
|
||||||
|
return f"{date_part} {time_part[:5]}"
|
||||||
|
return dt_str
|
||||||
|
|
||||||
|
|
||||||
|
def format_date(dt_str: str) -> str:
|
||||||
|
"""Extract the date portion from an ISO datetime string."""
|
||||||
|
if not dt_str:
|
||||||
|
return ""
|
||||||
|
if "T" in dt_str:
|
||||||
|
return dt_str.split("T")[0]
|
||||||
|
return dt_str
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date(date_str: str) -> datetime:
|
||||||
|
"""Parse a date string in common formats.
|
||||||
|
|
||||||
|
Supports: YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, MM/DD/YYYY.
|
||||||
|
"""
|
||||||
|
formats = ["%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%m/%d/%Y"]
|
||||||
|
for fmt in formats:
|
||||||
|
try:
|
||||||
|
return datetime.strptime(date_str, fmt)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
raise ValueError(f"Could not parse date: {date_str}")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_iso_datetime(dt_str: str) -> datetime:
|
||||||
|
"""Parse an ISO datetime string to a naive datetime.
|
||||||
|
|
||||||
|
Handles both 'YYYY-MM-DDTHH:MM:SS' and 'YYYY-MM-DD' formats,
|
||||||
|
stripping any timezone suffix.
|
||||||
|
"""
|
||||||
|
if "T" in dt_str:
|
||||||
|
clean = dt_str.split("Z")[0].split("+")[0]
|
||||||
|
return datetime.strptime(clean, "%Y-%m-%dT%H:%M:%S")
|
||||||
|
return datetime.strptime(dt_str, "%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
|
def format_attendee(name: str, email: str) -> str:
|
||||||
|
"""Format an attendee as 'Name <email>' or just the email."""
|
||||||
|
if name and email and not email.startswith("/O="):
|
||||||
|
return f"{name} <{email}>"
|
||||||
|
return name or email or ""
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
"""Exchange MCP Server - access OWA email, calendar, directory via MCP."""
|
||||||
Vendored
+194
@@ -0,0 +1,194 @@
|
|||||||
|
"""Shared login logic for Exchange MCP.
|
||||||
|
|
||||||
|
Reuses crypto functions from login.py and provides an async Playwright-based
|
||||||
|
login function for use by the MCP login tool.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
|
||||||
|
# Ensure login.py (project root) is importable regardless of cwd
|
||||||
|
_project_root = str(Path(__file__).resolve().parent.parent)
|
||||||
|
if _project_root not in sys.path:
|
||||||
|
sys.path.insert(0, _project_root)
|
||||||
|
|
||||||
|
from login import CREDS_FILE, SALT_FILE, get_key, encrypt_credentials, decrypt_credentials
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Cookie encryption (same master password / salt as credentials)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def encrypt_cookie_file(cookies_str: str, master_password: str, cookie_file: Path) -> None:
|
||||||
|
"""Encrypt session cookies and write to disk."""
|
||||||
|
if not SALT_FILE.exists():
|
||||||
|
raise FileNotFoundError("Salt file not found. Set up credentials first.")
|
||||||
|
salt = SALT_FILE.read_bytes()
|
||||||
|
key = get_key(master_password, salt)
|
||||||
|
f = Fernet(key)
|
||||||
|
cookie_file.write_bytes(f.encrypt(cookies_str.encode()))
|
||||||
|
os.chmod(cookie_file, 0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_cookie_file(master_password: str, cookie_file: Path) -> str | None:
|
||||||
|
"""Decrypt session cookies from disk. Returns None on failure."""
|
||||||
|
if not cookie_file.exists() or not SALT_FILE.exists():
|
||||||
|
return None
|
||||||
|
salt = SALT_FILE.read_bytes()
|
||||||
|
key = get_key(master_password, salt)
|
||||||
|
f = Fernet(key)
|
||||||
|
try:
|
||||||
|
return f.decrypt(cookie_file.read_bytes()).decode()
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Async browser login
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def perform_login(
|
||||||
|
username: str,
|
||||||
|
password: str,
|
||||||
|
owa_url: str,
|
||||||
|
progress_callback=None,
|
||||||
|
) -> dict:
|
||||||
|
"""Authenticate to OWA via browser-based SSO + 2FA.
|
||||||
|
|
||||||
|
Mirrors login.py's login() but uses playwright.async_api so it can
|
||||||
|
run inside the MCP server's event loop.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
username: Email address.
|
||||||
|
password: Account password.
|
||||||
|
owa_url: Base OWA URL (e.g. https://owa.example.com).
|
||||||
|
progress_callback: Optional async callable for status updates.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{"success": True, "cookies": "name=val\\n..."} on success,
|
||||||
|
{"success": False, "error": "..."} on failure.
|
||||||
|
"""
|
||||||
|
from playwright.async_api import async_playwright
|
||||||
|
|
||||||
|
owa_host = owa_url.replace("https://", "").replace("http://", "").rstrip("/")
|
||||||
|
|
||||||
|
async def _info(msg: str):
|
||||||
|
if progress_callback:
|
||||||
|
await progress_callback(msg)
|
||||||
|
|
||||||
|
await _info(f"Logging in as {username}...")
|
||||||
|
|
||||||
|
async with async_playwright() as p:
|
||||||
|
browser = await p.chromium.launch(headless=True)
|
||||||
|
context = await browser.new_context()
|
||||||
|
page = await context.new_page()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Step 1: Navigate to OWA (redirects to SSO)
|
||||||
|
await page.goto(f"{owa_url}/owa/", wait_until="networkidle")
|
||||||
|
|
||||||
|
# Step 2: Fill credentials and submit
|
||||||
|
await page.fill('input[name="username"]', username)
|
||||||
|
await page.fill('input[name="password"]', password)
|
||||||
|
try:
|
||||||
|
btn = page.locator(
|
||||||
|
'button:has-text("Continue"), button:has-text("Продолжить")'
|
||||||
|
).first
|
||||||
|
await btn.click(timeout=5000)
|
||||||
|
except Exception:
|
||||||
|
await page.press('input[name="password"]', "Enter")
|
||||||
|
await page.wait_for_load_state("networkidle")
|
||||||
|
|
||||||
|
await _info("Credentials submitted, selecting 2FA method...")
|
||||||
|
|
||||||
|
# Step 3: Click 2FA authenticator button (skip nav/menu buttons)
|
||||||
|
try:
|
||||||
|
# Look for a heading that indicates the 2FA choice screen
|
||||||
|
await page.wait_for_selector(
|
||||||
|
'h1:has-text("Choose"), h1:has-text("Выберите")',
|
||||||
|
timeout=10000,
|
||||||
|
)
|
||||||
|
# Pick the first button inside the choices container (after the heading),
|
||||||
|
# skipping nav/menu chrome buttons.
|
||||||
|
auth_btn = page.locator("h1 ~ div button").first
|
||||||
|
await auth_btn.click(timeout=5000)
|
||||||
|
await page.wait_for_load_state("networkidle")
|
||||||
|
except Exception as e:
|
||||||
|
await _info(f"Could not find 2FA button: {e}")
|
||||||
|
|
||||||
|
# Step 4: Wait for mobile approval
|
||||||
|
await _info("Waiting for mobile approval... Check your 2FA app!")
|
||||||
|
success = False
|
||||||
|
last_url = ""
|
||||||
|
|
||||||
|
for i in range(90):
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
url = page.url
|
||||||
|
|
||||||
|
if url != last_url:
|
||||||
|
await _info(f"URL changed: {url[:80]}...")
|
||||||
|
last_url = url
|
||||||
|
|
||||||
|
if owa_host in url and "ofam" not in url and "adfs" not in url:
|
||||||
|
await _info("OWA detected! Waiting for page to load...")
|
||||||
|
await page.wait_for_load_state("load", timeout=15000)
|
||||||
|
success = True
|
||||||
|
break
|
||||||
|
|
||||||
|
try:
|
||||||
|
if (
|
||||||
|
await page.locator(
|
||||||
|
'[aria-label*="Outlook"], [aria-label*="Почта"]'
|
||||||
|
).count()
|
||||||
|
> 0
|
||||||
|
):
|
||||||
|
await _info("OWA elements detected!")
|
||||||
|
success = True
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if i > 0 and i % 15 == 0:
|
||||||
|
await _info(f"Still waiting... ({i}s)")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
err_str = str(e).lower()
|
||||||
|
if any(
|
||||||
|
kw in err_str
|
||||||
|
for kw in ("navigation", "destroyed", "target closed")
|
||||||
|
):
|
||||||
|
await _info("Navigation in progress...")
|
||||||
|
try:
|
||||||
|
await page.wait_for_load_state("load", timeout=15000)
|
||||||
|
url = page.url
|
||||||
|
if owa_host in url and "ofam" not in url:
|
||||||
|
success = True
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
await _info(f"Error: {e}")
|
||||||
|
|
||||||
|
if success:
|
||||||
|
cookies = await context.cookies()
|
||||||
|
cookies_str = "\n".join(
|
||||||
|
f"{c['name']}={c['value']}" for c in cookies
|
||||||
|
)
|
||||||
|
await _info("Login successful.")
|
||||||
|
return {"success": True, "cookies": cookies_str}
|
||||||
|
else:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": "2FA approval not received within 90 seconds.",
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {"success": False, "error": str(e)}
|
||||||
|
finally:
|
||||||
|
await browser.close()
|
||||||
+109
@@ -0,0 +1,109 @@
|
|||||||
|
"""Return type definitions for MCP tools.
|
||||||
|
|
||||||
|
Uses TypedDict for lightweight structured return types without
|
||||||
|
requiring Pydantic at the model layer.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import TypedDict
|
||||||
|
|
||||||
|
|
||||||
|
class Email(TypedDict, total=False):
|
||||||
|
"""An email message."""
|
||||||
|
subject: str
|
||||||
|
sender: str
|
||||||
|
sender_name: str
|
||||||
|
date: str
|
||||||
|
is_read: bool
|
||||||
|
has_attachments: bool
|
||||||
|
has_links: bool
|
||||||
|
item_id: str
|
||||||
|
size: int
|
||||||
|
is_meeting: bool
|
||||||
|
item_type: str
|
||||||
|
to: list[str]
|
||||||
|
cc: list[str]
|
||||||
|
body: str
|
||||||
|
body_type: str
|
||||||
|
attachments: list[dict]
|
||||||
|
# Meeting-specific fields
|
||||||
|
location: str
|
||||||
|
start: str
|
||||||
|
end: str
|
||||||
|
attendees_required: list[str]
|
||||||
|
attendees_optional: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarEvent(TypedDict, total=False):
|
||||||
|
"""A calendar event / meeting."""
|
||||||
|
subject: str
|
||||||
|
start: str
|
||||||
|
end: str
|
||||||
|
location: str
|
||||||
|
is_all_day: bool
|
||||||
|
is_cancelled: bool
|
||||||
|
is_meeting: bool
|
||||||
|
is_recurring: bool
|
||||||
|
organizer: str
|
||||||
|
organizer_email: str
|
||||||
|
my_response: str
|
||||||
|
item_id: str
|
||||||
|
body: str
|
||||||
|
attendees_required: list[str]
|
||||||
|
attendees_optional: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class Person(TypedDict, total=False):
|
||||||
|
"""A person from the Exchange directory."""
|
||||||
|
name: str
|
||||||
|
email: str
|
||||||
|
mailbox_type: str
|
||||||
|
first_name: str
|
||||||
|
last_name: str
|
||||||
|
job_title: str
|
||||||
|
department: str
|
||||||
|
company: str
|
||||||
|
office: str
|
||||||
|
alias: str
|
||||||
|
manager: str
|
||||||
|
manager_email: str
|
||||||
|
phones: dict[str, str]
|
||||||
|
address: str
|
||||||
|
direct_reports: list[dict[str, str]]
|
||||||
|
|
||||||
|
|
||||||
|
class Folder(TypedDict, total=False):
|
||||||
|
"""A mail folder."""
|
||||||
|
name: str
|
||||||
|
id: str
|
||||||
|
total_count: int
|
||||||
|
unread_count: int
|
||||||
|
child_folder_count: int
|
||||||
|
|
||||||
|
|
||||||
|
class FreeSlot(TypedDict):
|
||||||
|
"""A free time slot."""
|
||||||
|
date: str
|
||||||
|
start: str
|
||||||
|
end: str
|
||||||
|
duration_minutes: int
|
||||||
|
|
||||||
|
|
||||||
|
class Availability(TypedDict, total=False):
|
||||||
|
"""Availability data for a single attendee."""
|
||||||
|
email: str
|
||||||
|
busy_slots: int
|
||||||
|
free_slots: int
|
||||||
|
merged_freebusy: str
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingResult(TypedDict, total=False):
|
||||||
|
"""Result of creating/updating a meeting."""
|
||||||
|
success: bool
|
||||||
|
subject: str
|
||||||
|
date: str
|
||||||
|
start_time: str
|
||||||
|
end_time: str
|
||||||
|
location: str
|
||||||
|
required_attendees: list[str]
|
||||||
|
optional_attendees: list[str]
|
||||||
|
error: str
|
||||||
+493
@@ -0,0 +1,493 @@
|
|||||||
|
"""Centralized OWA HTTP client for Exchange API.
|
||||||
|
|
||||||
|
Extracts and unifies the duplicated request/cookie/session patterns
|
||||||
|
from all standalone scripts into a single reusable client.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import requests
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
class SessionExpiredError(Exception):
|
||||||
|
"""Raised when the OWA session has expired (HTTP 401/440 or HTML redirect)."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Map common folder names (English + Russian) to OWA distinguished folder IDs
|
||||||
|
DISTINGUISHED_FOLDERS = {
|
||||||
|
"inbox": "inbox",
|
||||||
|
"входящие": "inbox",
|
||||||
|
"sent": "sentitems",
|
||||||
|
"отправленные": "sentitems",
|
||||||
|
"drafts": "drafts",
|
||||||
|
"черновики": "drafts",
|
||||||
|
"deleted": "deleteditems",
|
||||||
|
"удаленные": "deleteditems",
|
||||||
|
"junk": "junkemail",
|
||||||
|
"нежелательная почта": "junkemail",
|
||||||
|
"outbox": "outbox",
|
||||||
|
"исходящие": "outbox",
|
||||||
|
"calendar": "calendar",
|
||||||
|
"календарь": "calendar",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class OWAClient:
|
||||||
|
"""HTTP client for OWA (Outlook Web Access) JSON API.
|
||||||
|
|
||||||
|
Handles cookie loading, CSRF token extraction, request construction,
|
||||||
|
session expiry detection, and automatic cookie reload on first failure.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
cookie_file: str | None = None,
|
||||||
|
owa_url: str | None = None,
|
||||||
|
):
|
||||||
|
self.cookie_file = Path(
|
||||||
|
cookie_file
|
||||||
|
or os.environ.get("EXCHANGE_COOKIE_FILE", "")
|
||||||
|
or str(Path(__file__).parent.parent / "session-cookies.txt")
|
||||||
|
)
|
||||||
|
self.owa_url = (
|
||||||
|
owa_url
|
||||||
|
or os.environ.get("EXCHANGE_OWA_URL", "")
|
||||||
|
).rstrip("/")
|
||||||
|
if not self.owa_url:
|
||||||
|
raise ValueError(
|
||||||
|
"OWA URL not configured. Set the EXCHANGE_OWA_URL environment variable."
|
||||||
|
)
|
||||||
|
self._cookies: dict[str, str] = {}
|
||||||
|
self._canary: str = ""
|
||||||
|
self._session = requests.Session()
|
||||||
|
self._loaded = False
|
||||||
|
self.user_email: str = ""
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Cookie / session helpers
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _load_cookies(self) -> None:
|
||||||
|
"""Read session-cookies.txt (name=value per line) and extract X-OWA-CANARY."""
|
||||||
|
if not self.cookie_file.exists():
|
||||||
|
raise SessionExpiredError(
|
||||||
|
f"Cookie file not found: {self.cookie_file}. Call the login tool first."
|
||||||
|
)
|
||||||
|
|
||||||
|
raw = self.cookie_file.read_text().strip()
|
||||||
|
|
||||||
|
# Detect encrypted cookie file (Fernet tokens start with gAAAAA)
|
||||||
|
if raw.startswith("gAAAAA"):
|
||||||
|
raise SessionExpiredError(
|
||||||
|
"Cookie file is encrypted. Call the login tool to decrypt and restore the session."
|
||||||
|
)
|
||||||
|
|
||||||
|
cookies: dict[str, str] = {}
|
||||||
|
for line in raw.split("\n"):
|
||||||
|
if "=" in line:
|
||||||
|
name, value = line.split("=", 1)
|
||||||
|
cookies[name] = value
|
||||||
|
|
||||||
|
if not cookies:
|
||||||
|
raise SessionExpiredError("Cookie file is empty. Call the login tool first.")
|
||||||
|
|
||||||
|
self._cookies = cookies
|
||||||
|
self._canary = cookies.get("X-OWA-CANARY", "")
|
||||||
|
self._session = requests.Session()
|
||||||
|
self._session.cookies.update(cookies)
|
||||||
|
self._loaded = True
|
||||||
|
|
||||||
|
def _ensure_loaded(self) -> None:
|
||||||
|
"""Load cookies on first use."""
|
||||||
|
if not self._loaded:
|
||||||
|
self._load_cookies()
|
||||||
|
|
||||||
|
def reload_cookies(self) -> None:
|
||||||
|
"""Force-reload cookies from disk (e.g. after re-login).
|
||||||
|
|
||||||
|
Preserves the existing in-memory session if reloading fails
|
||||||
|
(e.g. cookie file is encrypted or missing).
|
||||||
|
"""
|
||||||
|
old_cookies = self._cookies
|
||||||
|
old_canary = self._canary
|
||||||
|
old_session = self._session
|
||||||
|
old_loaded = self._loaded
|
||||||
|
try:
|
||||||
|
self._loaded = False
|
||||||
|
self._load_cookies()
|
||||||
|
except SessionExpiredError:
|
||||||
|
# Restore previous state to avoid corrupting a valid in-memory session
|
||||||
|
self._cookies = old_cookies
|
||||||
|
self._canary = old_canary
|
||||||
|
self._session = old_session
|
||||||
|
self._loaded = old_loaded
|
||||||
|
raise
|
||||||
|
|
||||||
|
def load_cookies_from_string(self, cookies_str: str) -> None:
|
||||||
|
"""Load cookies from a decrypted name=value string (one per line).
|
||||||
|
|
||||||
|
Used by the login tool to inject cookies directly into memory
|
||||||
|
without writing plaintext to disk.
|
||||||
|
"""
|
||||||
|
cookies: dict[str, str] = {}
|
||||||
|
for line in cookies_str.strip().split("\n"):
|
||||||
|
if "=" in line:
|
||||||
|
name, value = line.split("=", 1)
|
||||||
|
cookies[name] = value
|
||||||
|
|
||||||
|
if not cookies:
|
||||||
|
raise SessionExpiredError("No cookies in provided data.")
|
||||||
|
|
||||||
|
self._cookies = cookies
|
||||||
|
self._canary = cookies.get("X-OWA-CANARY", "")
|
||||||
|
self._session = requests.Session()
|
||||||
|
self._session.cookies.update(cookies)
|
||||||
|
self._loaded = True
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Core request method
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def request(self, action: str, payload: dict, *, timeout: int = 30) -> dict:
|
||||||
|
"""POST to /owa/service.svc?action={action}&EP=1&ID=-1&AC=1.
|
||||||
|
|
||||||
|
On session expiry (401, 440, or text/html response), reloads cookies
|
||||||
|
once and retries. If that also fails, raises SessionExpiredError.
|
||||||
|
|
||||||
|
Returns the parsed JSON response dict.
|
||||||
|
"""
|
||||||
|
self._ensure_loaded()
|
||||||
|
|
||||||
|
for attempt in range(2):
|
||||||
|
try:
|
||||||
|
data = self._do_request(action, payload, timeout=timeout)
|
||||||
|
return data
|
||||||
|
except SessionExpiredError:
|
||||||
|
if attempt == 0:
|
||||||
|
# Try reloading cookies (user may have re-logged in)
|
||||||
|
try:
|
||||||
|
self.reload_cookies()
|
||||||
|
except SessionExpiredError:
|
||||||
|
pass # Keep in-memory state, retry anyway
|
||||||
|
else:
|
||||||
|
raise
|
||||||
|
|
||||||
|
# Should not reach here, but just in case
|
||||||
|
raise SessionExpiredError("Session expired. Run login.py to login again.")
|
||||||
|
|
||||||
|
def _do_request(self, action: str, payload: dict, *, timeout: int = 30) -> dict:
|
||||||
|
"""Execute a single OWA API request (no retry)."""
|
||||||
|
url = f"{self.owa_url}/owa/service.svc?action={action}&EP=1&ID=-1&AC=1"
|
||||||
|
|
||||||
|
# Prefer our explicitly-tracked canary (updated on every response)
|
||||||
|
# over the session cookie jar, which can hold stale domain-less entries.
|
||||||
|
canary = self._canary or self._session.cookies.get("X-OWA-CANARY")
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
"Action": action,
|
||||||
|
"X-OWA-CANARY": canary,
|
||||||
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = self._session.post(url, json=payload, headers=headers, timeout=timeout)
|
||||||
|
except requests.exceptions.RequestException as exc:
|
||||||
|
raise SessionExpiredError(f"Request failed: {exc}") from exc
|
||||||
|
|
||||||
|
# Keep cached canary in sync if OWA rotated it
|
||||||
|
new_canary = resp.cookies.get("X-OWA-CANARY")
|
||||||
|
if new_canary:
|
||||||
|
self._canary = new_canary
|
||||||
|
self._session.cookies.set("X-OWA-CANARY", new_canary)
|
||||||
|
|
||||||
|
# Detect session expiry
|
||||||
|
if resp.status_code in (401, 440):
|
||||||
|
raise SessionExpiredError("Session expired (HTTP {}).".format(resp.status_code))
|
||||||
|
|
||||||
|
if "text/html" in resp.headers.get("Content-Type", ""):
|
||||||
|
# Extract a snippet from HTML for diagnostics (login redirects vs API errors)
|
||||||
|
body_snippet = resp.text[:300] if resp.text else ""
|
||||||
|
raise SessionExpiredError(
|
||||||
|
f"Session expired or invalid action (HTML response, HTTP {resp.status_code}). "
|
||||||
|
f"Snippet: {body_snippet}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Parse JSON
|
||||||
|
try:
|
||||||
|
return resp.json()
|
||||||
|
except (ValueError, requests.exceptions.JSONDecodeError) as exc:
|
||||||
|
raise SessionExpiredError(
|
||||||
|
f"Unexpected response (HTTP {resp.status_code}). "
|
||||||
|
"Session may have expired."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
def request_header_payload(
|
||||||
|
self, action: str, payload: dict, *, timeout: int = 30
|
||||||
|
) -> dict:
|
||||||
|
"""POST with payload in x-owa-urlpostdata header (empty body).
|
||||||
|
|
||||||
|
Some OWA actions (CreateFolder, DeleteFolder, RenameFolder, etc.)
|
||||||
|
require the JSON payload to be sent as a URL-encoded string in the
|
||||||
|
``x-owa-urlpostdata`` header instead of the POST body. This method
|
||||||
|
handles that pattern with the same retry logic as ``request()``.
|
||||||
|
"""
|
||||||
|
self._ensure_loaded()
|
||||||
|
|
||||||
|
for attempt in range(2):
|
||||||
|
try:
|
||||||
|
return self._do_request_header_payload(
|
||||||
|
action, payload, timeout=timeout
|
||||||
|
)
|
||||||
|
except SessionExpiredError:
|
||||||
|
if attempt == 0:
|
||||||
|
try:
|
||||||
|
self.reload_cookies()
|
||||||
|
except SessionExpiredError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise
|
||||||
|
|
||||||
|
raise SessionExpiredError("Session expired. Run login.py to login again.")
|
||||||
|
|
||||||
|
def _do_request_header_payload(
|
||||||
|
self, action: str, payload: dict, *, timeout: int = 30
|
||||||
|
) -> dict:
|
||||||
|
"""Execute a single OWA API request with payload in header."""
|
||||||
|
import json as _json
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
url = f"{self.owa_url}/owa/service.svc?action={action}&EP=1&ID=-1&AC=1"
|
||||||
|
canary = self._canary or self._session.cookies.get("X-OWA-CANARY")
|
||||||
|
|
||||||
|
url_post_data = quote(_json.dumps(payload, separators=(",", ":")))
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json; charset=UTF-8",
|
||||||
|
"Action": action,
|
||||||
|
"X-OWA-CANARY": canary,
|
||||||
|
"X-OWA-UrlPostData": url_post_data,
|
||||||
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = self._session.post(url, headers=headers, timeout=timeout)
|
||||||
|
except requests.exceptions.RequestException as exc:
|
||||||
|
raise SessionExpiredError(f"Request failed: {exc}") from exc
|
||||||
|
|
||||||
|
new_canary = resp.cookies.get("X-OWA-CANARY")
|
||||||
|
if new_canary:
|
||||||
|
self._canary = new_canary
|
||||||
|
self._session.cookies.set("X-OWA-CANARY", new_canary)
|
||||||
|
|
||||||
|
if resp.status_code in (401, 440):
|
||||||
|
raise SessionExpiredError(
|
||||||
|
"Session expired (HTTP {}).".format(resp.status_code)
|
||||||
|
)
|
||||||
|
|
||||||
|
if "text/html" in resp.headers.get("Content-Type", ""):
|
||||||
|
body_snippet = resp.text[:300] if resp.text else ""
|
||||||
|
raise SessionExpiredError(
|
||||||
|
f"Session expired or invalid action (HTML response, HTTP {resp.status_code}). "
|
||||||
|
f"Snippet: {body_snippet}"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return resp.json()
|
||||||
|
except (ValueError, requests.exceptions.JSONDecodeError) as exc:
|
||||||
|
raise SessionExpiredError(
|
||||||
|
f"Unexpected response (HTTP {resp.status_code}). "
|
||||||
|
"Session may have expired."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# File download (attachments)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def download_file(
|
||||||
|
self, attachment_id: str, *, timeout: int = 60
|
||||||
|
) -> tuple[bytes, str, str]:
|
||||||
|
"""Download a file attachment by its AttachmentId.
|
||||||
|
|
||||||
|
Uses the OWA GetFileAttachment endpoint (direct GET).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(content_bytes, filename, content_type)
|
||||||
|
"""
|
||||||
|
self._ensure_loaded()
|
||||||
|
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
canary = self._canary or self._session.cookies.get("X-OWA-CANARY")
|
||||||
|
url = (
|
||||||
|
f"{self.owa_url}/owa/service.svc/s/GetFileAttachment"
|
||||||
|
f"?id={quote(attachment_id)}&X-OWA-CANARY={quote(canary)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = self._session.get(url, timeout=timeout)
|
||||||
|
except requests.exceptions.RequestException as exc:
|
||||||
|
raise SessionExpiredError(f"Download failed: {exc}") from exc
|
||||||
|
|
||||||
|
if resp.status_code in (401, 440):
|
||||||
|
raise SessionExpiredError(
|
||||||
|
f"Session expired (HTTP {resp.status_code})."
|
||||||
|
)
|
||||||
|
|
||||||
|
if "text/html" in resp.headers.get("Content-Type", ""):
|
||||||
|
raise SessionExpiredError(
|
||||||
|
"Session expired (HTML response on attachment download)."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Parse filename from Content-Disposition header
|
||||||
|
filename = "attachment"
|
||||||
|
cd = resp.headers.get("Content-Disposition", "")
|
||||||
|
if cd:
|
||||||
|
import re as _re
|
||||||
|
from urllib.parse import unquote
|
||||||
|
|
||||||
|
# Try filename*= (RFC 5987) first, then filename=
|
||||||
|
match = _re.search(r"filename\*=(?:UTF-8''|utf-8'')(.+?)(?:;|$)", cd)
|
||||||
|
if match:
|
||||||
|
filename = unquote(match.group(1).strip())
|
||||||
|
else:
|
||||||
|
match = _re.search(r'filename="?([^";]+)"?', cd)
|
||||||
|
if match:
|
||||||
|
filename = unquote(match.group(1).strip())
|
||||||
|
|
||||||
|
content_type = resp.headers.get("Content-Type", "application/octet-stream")
|
||||||
|
|
||||||
|
return resp.content, filename, content_type
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Convenience: extract response items
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def extract_items(data: dict) -> list[dict]:
|
||||||
|
"""Extract Items from standard OWA response envelope.
|
||||||
|
|
||||||
|
Response shape: data["Body"]["ResponseMessages"]["Items"]
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return data["Body"]["ResponseMessages"]["Items"]
|
||||||
|
except (KeyError, TypeError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Folder helpers
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def get_folder_id(self, folder_name: str) -> str | None:
|
||||||
|
"""Resolve a folder name to its Exchange folder ID.
|
||||||
|
|
||||||
|
Supports distinguished folder names (inbox, sentitems, drafts, etc.)
|
||||||
|
in both English and Russian, plus custom folder names looked up
|
||||||
|
via FindFolder on msgfolderroot.
|
||||||
|
"""
|
||||||
|
folder_lower = folder_name.lower()
|
||||||
|
|
||||||
|
# Check distinguished folders first
|
||||||
|
distinguished_id = DISTINGUISHED_FOLDERS.get(folder_lower)
|
||||||
|
if distinguished_id:
|
||||||
|
payload = {
|
||||||
|
"__type": "GetFolderJsonRequest:#Exchange",
|
||||||
|
"Header": {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
},
|
||||||
|
"Body": {
|
||||||
|
"__type": "GetFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "IdOnly",
|
||||||
|
},
|
||||||
|
"FolderIds": [
|
||||||
|
{
|
||||||
|
"__type": "DistinguishedFolderId:#Exchange",
|
||||||
|
"Id": distinguished_id,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = self.request("GetFolder", payload)
|
||||||
|
for msg in self.extract_items(data):
|
||||||
|
if "Folders" in msg:
|
||||||
|
for f in msg["Folders"]:
|
||||||
|
fid = f.get("FolderId", {}).get("Id")
|
||||||
|
if fid:
|
||||||
|
return fid
|
||||||
|
|
||||||
|
# Fall back to searching custom folders by name
|
||||||
|
payload = {
|
||||||
|
"__type": "FindFolderJsonRequest:#Exchange",
|
||||||
|
"Header": {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
},
|
||||||
|
"Body": {
|
||||||
|
"__type": "FindFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "Default",
|
||||||
|
},
|
||||||
|
"ParentFolderIds": [
|
||||||
|
{
|
||||||
|
"__type": "DistinguishedFolderId:#Exchange",
|
||||||
|
"Id": "msgfolderroot",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"Traversal": "Shallow",
|
||||||
|
"Paging": {
|
||||||
|
"__type": "IndexedPageView:#Exchange",
|
||||||
|
"BasePoint": "Beginning",
|
||||||
|
"Offset": 0,
|
||||||
|
"MaxEntriesReturned": 200,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = self.request("FindFolder", payload)
|
||||||
|
for msg in self.extract_items(data):
|
||||||
|
if "RootFolder" in msg and "Folders" in msg["RootFolder"]:
|
||||||
|
for f in msg["RootFolder"]["Folders"]:
|
||||||
|
if f.get("DisplayName", "").lower() == folder_lower:
|
||||||
|
return f.get("FolderId", {}).get("Id")
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# ResolveNames (directory search / attendee resolution)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def resolve_names(
|
||||||
|
self, query: str, *, full_contact: bool = True
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Call ResolveNames to search the directory.
|
||||||
|
|
||||||
|
Returns the list of Resolution dicts from the API, each containing
|
||||||
|
Mailbox and optionally Contact data.
|
||||||
|
"""
|
||||||
|
payload = {
|
||||||
|
"__type": "ResolveNamesJsonRequest:#Exchange",
|
||||||
|
"Header": {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
},
|
||||||
|
"Body": {
|
||||||
|
"__type": "ResolveNamesRequest:#Exchange",
|
||||||
|
"UnresolvedEntry": query,
|
||||||
|
"ReturnFullContactData": full_contact,
|
||||||
|
"SearchScope": "ActiveDirectoryContacts",
|
||||||
|
"ContactDataShape": "AllProperties" if full_contact else "Default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = self.request("ResolveNames", payload)
|
||||||
|
for msg in self.extract_items(data):
|
||||||
|
if "ResolutionSet" in msg and "Resolutions" in msg["ResolutionSet"]:
|
||||||
|
return msg["ResolutionSet"]["Resolutions"]
|
||||||
|
|
||||||
|
return []
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
"""Exchange MCP Server.
|
||||||
|
|
||||||
|
Exposes OWA email, calendar, directory, and availability tools via MCP.
|
||||||
|
Uses FastMCP with a lifespan context manager to share a single OWAClient
|
||||||
|
instance across all tool invocations.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
|
||||||
|
from exchange_mcp.owa_client import OWAClient
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AppContext:
|
||||||
|
"""Shared application state available to all tools via lifespan context."""
|
||||||
|
client: OWAClient
|
||||||
|
pending_login: asyncio.Task | None = field(default=None, repr=False)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
|
||||||
|
"""Initialize the OWA client on startup, available for the server lifetime."""
|
||||||
|
client = OWAClient()
|
||||||
|
# Try to pre-load cookies; tolerate missing file so the server can start
|
||||||
|
# without an active session (the `login` tool will authenticate first).
|
||||||
|
try:
|
||||||
|
client._ensure_loaded()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
yield AppContext(client=client)
|
||||||
|
finally:
|
||||||
|
# No persistent connections to clean up (requests is sync + per-call)
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Create the MCP server instance
|
||||||
|
mcp = FastMCP("exchange", lifespan=app_lifespan)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Import tool modules so their @mcp.tool() decorators register tools.
|
||||||
|
# Each module imports `mcp` from this file and decorates its functions.
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
import exchange_mcp.tools.email # noqa: E402, F401
|
||||||
|
import exchange_mcp.tools.calendar # noqa: E402, F401
|
||||||
|
import exchange_mcp.tools.people # noqa: E402, F401
|
||||||
|
import exchange_mcp.tools.folders # noqa: E402, F401
|
||||||
|
import exchange_mcp.tools.availability # noqa: E402, F401
|
||||||
|
import exchange_mcp.tools.analytics # noqa: E402, F401
|
||||||
|
import exchange_mcp.tools.auth # noqa: E402, F401
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Entry point: run the MCP server over stdio."""
|
||||||
|
mcp.run()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""MCP tool modules for Exchange."""
|
||||||
+421
@@ -0,0 +1,421 @@
|
|||||||
|
"""Analytics tools for the Exchange MCP server.
|
||||||
|
|
||||||
|
Provides meeting statistics and connection matrix analysis
|
||||||
|
using GetUserAvailability and GetItem APIs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from collections import Counter, defaultdict
|
||||||
|
from datetime import datetime, timedelta, date
|
||||||
|
|
||||||
|
from mcp.server.fastmcp import Context
|
||||||
|
|
||||||
|
from exchange_mcp.server import mcp, AppContext
|
||||||
|
from exchange_mcp.owa_client import OWAClient
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client(ctx: Context) -> OWAClient:
|
||||||
|
"""Extract the OWAClient from the MCP lifespan context."""
|
||||||
|
app_ctx: AppContext = ctx.request_context.lifespan_context
|
||||||
|
return app_ctx.client
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Internal: resolve names to emails
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _resolve_to_email(client: OWAClient, name: str) -> tuple[str, str]:
|
||||||
|
"""Resolve a name/email to (display_name, email). Returns ('','') on failure."""
|
||||||
|
resolutions = client.resolve_names(name)
|
||||||
|
if resolutions:
|
||||||
|
mb = resolutions[0].get("Mailbox", {})
|
||||||
|
return mb.get("Name", name), mb.get("EmailAddress", "")
|
||||||
|
return "", ""
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Internal: query GetUserAvailability in chunks
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _get_availability_events(
|
||||||
|
client: OWAClient,
|
||||||
|
emails: list[str],
|
||||||
|
start: date,
|
||||||
|
end: date,
|
||||||
|
batch_size: int = 5,
|
||||||
|
chunk_days: int = 14,
|
||||||
|
) -> dict[str, list[dict]]:
|
||||||
|
"""Query GetUserAvailability for multiple people across a date range.
|
||||||
|
|
||||||
|
Returns dict mapping email -> list of calendar event dicts with
|
||||||
|
keys: subject, start_date, busy_type.
|
||||||
|
"""
|
||||||
|
results: dict[str, list[dict]] = {email: [] for email in emails}
|
||||||
|
|
||||||
|
# Batch people
|
||||||
|
email_batches = [emails[i:i+batch_size] for i in range(0, len(emails), batch_size)]
|
||||||
|
|
||||||
|
for batch in email_batches:
|
||||||
|
current = start
|
||||||
|
while current < end:
|
||||||
|
chunk_end = min(current + timedelta(days=chunk_days), end)
|
||||||
|
|
||||||
|
mailbox_data = [{
|
||||||
|
'__type': 'MailboxData:#Exchange',
|
||||||
|
'Email': {
|
||||||
|
'__type': 'EmailAddress:#Exchange',
|
||||||
|
'Address': email,
|
||||||
|
},
|
||||||
|
'AttendeeType': 'Required',
|
||||||
|
} for email in batch]
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
'__type': 'GetUserAvailabilityJsonRequest:#Exchange',
|
||||||
|
'Header': {
|
||||||
|
'__type': 'JsonRequestHeaders:#Exchange',
|
||||||
|
'RequestServerVersion': 'Exchange2013',
|
||||||
|
'TimeZoneContext': {
|
||||||
|
'__type': 'TimeZoneContext:#Exchange',
|
||||||
|
'TimeZoneDefinition': {
|
||||||
|
'__type': 'TimeZoneDefinitionType:#Exchange',
|
||||||
|
'Id': 'Russian Standard Time',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Body': {
|
||||||
|
'__type': 'GetUserAvailabilityRequest:#Exchange',
|
||||||
|
'MailboxDataArray': mailbox_data,
|
||||||
|
'FreeBusyViewOptions': {
|
||||||
|
'__type': 'FreeBusyViewOptions:#Exchange',
|
||||||
|
'TimeWindow': {
|
||||||
|
'__type': 'Duration:#Exchange',
|
||||||
|
'StartTime': f'{current}T00:00:00',
|
||||||
|
'EndTime': f'{chunk_end}T00:00:00',
|
||||||
|
},
|
||||||
|
'MergedFreeBusyIntervalInMinutes': 30,
|
||||||
|
'RequestedView': 'DetailedMerged',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request('GetUserAvailability', payload)
|
||||||
|
body = data.get('Body', {})
|
||||||
|
for i, fb_resp in enumerate(body.get('FreeBusyResponseArray', [])):
|
||||||
|
if i >= len(batch):
|
||||||
|
break
|
||||||
|
email = batch[i]
|
||||||
|
fb_view = fb_resp.get('FreeBusyView', {})
|
||||||
|
cal_events = fb_view.get('CalendarEventArray', {})
|
||||||
|
if isinstance(cal_events, dict):
|
||||||
|
items = cal_events.get('Items', [])
|
||||||
|
elif isinstance(cal_events, list):
|
||||||
|
items = cal_events
|
||||||
|
else:
|
||||||
|
items = []
|
||||||
|
for event in items:
|
||||||
|
s = event.get('StartTime', '')
|
||||||
|
bt = event.get('BusyType', '')
|
||||||
|
if s and bt != 'Free':
|
||||||
|
details = event.get('CalendarEventDetails', {})
|
||||||
|
subject = details.get('Subject', '') if details else ''
|
||||||
|
results[email].append({
|
||||||
|
'subject': subject,
|
||||||
|
'start_date': s[:10],
|
||||||
|
'busy_type': bt,
|
||||||
|
})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
current = chunk_end
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Tool: get_meeting_stats
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_meeting_stats(
|
||||||
|
people: str,
|
||||||
|
start_date: str,
|
||||||
|
end_date: str,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Get meeting count statistics for one or more people over a date range.
|
||||||
|
|
||||||
|
Uses GetUserAvailability to count calendar events (including
|
||||||
|
expanded recurring instances) for each person.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
people: Comma-separated names or email addresses to analyze.
|
||||||
|
start_date: Start date in YYYY-MM-DD format.
|
||||||
|
end_date: End date in YYYY-MM-DD format.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with per-person stats sorted by meeting count:
|
||||||
|
total_meetings, meetings_per_workday, days_with_meetings.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
try:
|
||||||
|
sd = datetime.strptime(start_date, '%Y-%m-%d').date()
|
||||||
|
ed = datetime.strptime(end_date, '%Y-%m-%d').date()
|
||||||
|
except ValueError as e:
|
||||||
|
return json.dumps({"error": f"Invalid date format: {e}"})
|
||||||
|
|
||||||
|
# Resolve names
|
||||||
|
name_list = [n.strip() for n in people.split(',') if n.strip()]
|
||||||
|
if not name_list:
|
||||||
|
return json.dumps({"error": "No people specified."})
|
||||||
|
|
||||||
|
resolved = [] # (display_name, email)
|
||||||
|
for name in name_list:
|
||||||
|
display, email = _resolve_to_email(client, name)
|
||||||
|
if email:
|
||||||
|
resolved.append((display, email))
|
||||||
|
else:
|
||||||
|
resolved.append((name, ""))
|
||||||
|
|
||||||
|
emails = [email for _, email in resolved if email]
|
||||||
|
if not emails:
|
||||||
|
return json.dumps({"error": "Could not resolve any names to email addresses."})
|
||||||
|
|
||||||
|
# Query availability
|
||||||
|
avail = _get_availability_events(client, emails, sd, ed)
|
||||||
|
|
||||||
|
# Count working days
|
||||||
|
workdays = 0
|
||||||
|
d = sd
|
||||||
|
while d < ed:
|
||||||
|
if d.weekday() < 5:
|
||||||
|
workdays += 1
|
||||||
|
d += timedelta(days=1)
|
||||||
|
workdays = max(workdays, 1)
|
||||||
|
|
||||||
|
# Build stats
|
||||||
|
stats = []
|
||||||
|
for display, email in resolved:
|
||||||
|
if not email or email not in avail:
|
||||||
|
stats.append({
|
||||||
|
"name": display,
|
||||||
|
"email": email or "not_found",
|
||||||
|
"total_meetings": 0,
|
||||||
|
"meetings_per_workday": 0,
|
||||||
|
"days_with_meetings": 0,
|
||||||
|
"workdays": workdays,
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
|
||||||
|
events = avail[email]
|
||||||
|
total = len(events)
|
||||||
|
unique_days = len(set(ev['start_date'] for ev in events))
|
||||||
|
avg = round(total / workdays, 1)
|
||||||
|
|
||||||
|
stats.append({
|
||||||
|
"name": display,
|
||||||
|
"email": email,
|
||||||
|
"total_meetings": total,
|
||||||
|
"meetings_per_workday": avg,
|
||||||
|
"days_with_meetings": unique_days,
|
||||||
|
"workdays": workdays,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sort by total descending
|
||||||
|
stats.sort(key=lambda x: x["total_meetings"], reverse=True)
|
||||||
|
|
||||||
|
return json.dumps({
|
||||||
|
"period": {"start": start_date, "end": end_date, "workdays": workdays},
|
||||||
|
"stats": stats,
|
||||||
|
}, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Tool: get_meeting_contacts
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_meeting_contacts(
|
||||||
|
start_date: str,
|
||||||
|
end_date: str,
|
||||||
|
top_n: int = 30,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Build a connection matrix: who you meet with most often.
|
||||||
|
|
||||||
|
Analyzes your calendar over a date range, accounting for recurring
|
||||||
|
meetings. For each contact found in your meetings, returns the
|
||||||
|
weighted count of shared meetings.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
start_date: Start date in YYYY-MM-DD format.
|
||||||
|
end_date: End date in YYYY-MM-DD format.
|
||||||
|
top_n: Number of top contacts to return. Default 30.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with total_meetings, unique_contacts, and a ranked
|
||||||
|
contacts array of {name, email, meetings} objects.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
try:
|
||||||
|
sd = datetime.strptime(start_date, '%Y-%m-%d').date()
|
||||||
|
ed = datetime.strptime(end_date, '%Y-%m-%d').date()
|
||||||
|
except ValueError as e:
|
||||||
|
return json.dumps({"error": f"Invalid date format: {e}"})
|
||||||
|
|
||||||
|
# Step 1: Get own expanded events via GetUserAvailability
|
||||||
|
# to count subject occurrences (handles recurring meetings)
|
||||||
|
own_email = client.user_email.lower() if client.user_email else ""
|
||||||
|
if not own_email:
|
||||||
|
return json.dumps({"error": "User email not available. Call the login tool first."})
|
||||||
|
|
||||||
|
folder_id = client.get_folder_id("calendar")
|
||||||
|
if not folder_id:
|
||||||
|
return json.dumps({"error": "Could not find calendar folder."})
|
||||||
|
|
||||||
|
# Get expanded event subjects with occurrence counts
|
||||||
|
avail_result = _get_availability_events(client, [client.user_email], sd, ed)
|
||||||
|
expanded_events = avail_result.get(client.user_email, [])
|
||||||
|
|
||||||
|
subject_counts = Counter(ev['subject'] for ev in expanded_events)
|
||||||
|
total_expanded = len(expanded_events)
|
||||||
|
|
||||||
|
# Step 2: Find master calendar items for each unique subject
|
||||||
|
# Scan entire calendar (descending) to match subjects
|
||||||
|
subject_to_id: dict[str, str] = {}
|
||||||
|
offset = 0
|
||||||
|
|
||||||
|
while len(subject_to_id) < len(subject_counts):
|
||||||
|
payload = {
|
||||||
|
'__type': 'FindItemJsonRequest:#Exchange',
|
||||||
|
'Header': {
|
||||||
|
'__type': 'JsonRequestHeaders:#Exchange',
|
||||||
|
'RequestServerVersion': 'Exchange2013',
|
||||||
|
},
|
||||||
|
'Body': {
|
||||||
|
'__type': 'FindItemRequest:#Exchange',
|
||||||
|
'ItemShape': {
|
||||||
|
'__type': 'ItemResponseShape:#Exchange',
|
||||||
|
'BaseShape': 'Default',
|
||||||
|
},
|
||||||
|
'ParentFolderIds': [
|
||||||
|
{'__type': 'FolderId:#Exchange', 'Id': folder_id}
|
||||||
|
],
|
||||||
|
'Traversal': 'Shallow',
|
||||||
|
'Paging': {
|
||||||
|
'__type': 'IndexedPageView:#Exchange',
|
||||||
|
'BasePoint': 'Beginning',
|
||||||
|
'Offset': offset,
|
||||||
|
'MaxEntriesReturned': 200,
|
||||||
|
},
|
||||||
|
'SortOrder': [{
|
||||||
|
'__type': 'SortResults:#Exchange',
|
||||||
|
'Order': 'Descending',
|
||||||
|
'Path': {
|
||||||
|
'__type': 'PropertyUri:#Exchange',
|
||||||
|
'FieldURI': 'Start',
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = client.request('FindItem', payload)
|
||||||
|
items = client.extract_items(data)
|
||||||
|
if not items:
|
||||||
|
break
|
||||||
|
folder_items = items[0].get('RootFolder', {}).get('Items', [])
|
||||||
|
is_last = items[0].get('RootFolder', {}).get('IncludesLastItemInRange', True)
|
||||||
|
if not folder_items:
|
||||||
|
break
|
||||||
|
|
||||||
|
for item in folder_items:
|
||||||
|
subj = item.get('Subject', '')
|
||||||
|
if subj and subj in subject_counts and subj not in subject_to_id:
|
||||||
|
subject_to_id[subj] = item.get('ItemId', {}).get('Id', '')
|
||||||
|
|
||||||
|
if is_last:
|
||||||
|
break
|
||||||
|
offset += 200
|
||||||
|
if offset > 3000:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Step 3: GetItem for each master to get attendees
|
||||||
|
unique_ids = list(set(subject_to_id.values()))
|
||||||
|
id_to_attendees: dict[str, set] = {}
|
||||||
|
|
||||||
|
for bi in range(0, len(unique_ids), 10):
|
||||||
|
batch = unique_ids[bi:bi+10]
|
||||||
|
item_id_list = [{"__type": "ItemId:#Exchange", "Id": iid} for iid in batch]
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "GetItemJsonRequest:#Exchange",
|
||||||
|
"Header": {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
},
|
||||||
|
"Body": {
|
||||||
|
"__type": "GetItemRequest:#Exchange",
|
||||||
|
"ItemShape": {
|
||||||
|
"__type": "ItemResponseShape:#Exchange",
|
||||||
|
"BaseShape": "AllProperties",
|
||||||
|
},
|
||||||
|
"ItemIds": item_id_list,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request("GetItem", payload)
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if "Items" not in msg:
|
||||||
|
continue
|
||||||
|
for item in msg["Items"]:
|
||||||
|
item_id = item.get("ItemId", {}).get("Id", "")
|
||||||
|
attendees = set()
|
||||||
|
|
||||||
|
for att_list in [item.get("RequiredAttendees", []) or [],
|
||||||
|
item.get("OptionalAttendees", []) or []]:
|
||||||
|
for a in att_list:
|
||||||
|
mailbox = a.get("Mailbox", {})
|
||||||
|
name = mailbox.get("Name", "")
|
||||||
|
addr = mailbox.get("EmailAddress", "")
|
||||||
|
if not name or not addr or addr.startswith("/O="):
|
||||||
|
continue
|
||||||
|
attendees.add((name, addr.lower()))
|
||||||
|
|
||||||
|
organizer = item.get("Organizer", {}).get("Mailbox", {})
|
||||||
|
if organizer:
|
||||||
|
org_addr = organizer.get("EmailAddress", "")
|
||||||
|
org_name = organizer.get("Name", "")
|
||||||
|
if org_addr and not org_addr.startswith("/O="):
|
||||||
|
attendees.add((org_name, org_addr.lower()))
|
||||||
|
|
||||||
|
id_to_attendees[item_id] = attendees
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Step 4: Build weighted contacts, excluding self
|
||||||
|
contacts = Counter()
|
||||||
|
for subject, item_id in subject_to_id.items():
|
||||||
|
weight = subject_counts.get(subject, 1)
|
||||||
|
attendees = id_to_attendees.get(item_id, set())
|
||||||
|
for name, email in attendees:
|
||||||
|
if own_email and email == own_email:
|
||||||
|
continue
|
||||||
|
contacts[(name, email)] += weight
|
||||||
|
|
||||||
|
result_contacts = []
|
||||||
|
for (name, email), count in contacts.most_common(top_n):
|
||||||
|
result_contacts.append({
|
||||||
|
"name": name,
|
||||||
|
"email": email,
|
||||||
|
"meetings": count,
|
||||||
|
})
|
||||||
|
|
||||||
|
return json.dumps({
|
||||||
|
"period": {"start": start_date, "end": end_date},
|
||||||
|
"total_meetings": total_expanded,
|
||||||
|
"unique_contacts": len(contacts),
|
||||||
|
"contacts": result_contacts,
|
||||||
|
}, ensure_ascii=False)
|
||||||
+201
@@ -0,0 +1,201 @@
|
|||||||
|
"""Authentication tool for the Exchange MCP server.
|
||||||
|
|
||||||
|
Provides a `login` tool that handles credential setup, browser-based SSO
|
||||||
|
login, and 2FA — all from within the MCP session. Session cookies are
|
||||||
|
encrypted at rest with the master password.
|
||||||
|
|
||||||
|
The login flow is non-blocking for 2FA:
|
||||||
|
1. First call starts browser login in the background and returns immediately
|
||||||
|
with instructions to approve 2FA on the mobile app.
|
||||||
|
2. Second call checks the background task result and loads cookies on success.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
|
||||||
|
from mcp.server.fastmcp import Context
|
||||||
|
|
||||||
|
from exchange_mcp.server import mcp, AppContext
|
||||||
|
from exchange_mcp.owa_client import OWAClient
|
||||||
|
|
||||||
|
|
||||||
|
def _get_app_ctx(ctx: Context) -> AppContext:
|
||||||
|
"""Extract the AppContext from the MCP lifespan context."""
|
||||||
|
return ctx.request_context.lifespan_context
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client(ctx: Context) -> OWAClient:
|
||||||
|
"""Extract the OWAClient from the MCP lifespan context."""
|
||||||
|
return _get_app_ctx(ctx).client
|
||||||
|
|
||||||
|
|
||||||
|
def _session_is_valid(client: OWAClient) -> bool:
|
||||||
|
"""Quick check: can we reach the inbox?"""
|
||||||
|
try:
|
||||||
|
client._ensure_loaded()
|
||||||
|
payload = {
|
||||||
|
"__type": "GetFolderJsonRequest:#Exchange",
|
||||||
|
"Header": {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
},
|
||||||
|
"Body": {
|
||||||
|
"__type": "GetFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "IdOnly",
|
||||||
|
},
|
||||||
|
"FolderIds": [
|
||||||
|
{
|
||||||
|
"__type": "DistinguishedFolderId:#Exchange",
|
||||||
|
"Id": "inbox",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
data = client.request("GetFolder", payload)
|
||||||
|
items = client.extract_items(data)
|
||||||
|
return bool(items)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def login(
|
||||||
|
master_password: str,
|
||||||
|
username: str = "",
|
||||||
|
password: str = "",
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Authenticate to Exchange OWA (handles credential setup and 2FA login).
|
||||||
|
|
||||||
|
Call this tool when the session has expired or before first use.
|
||||||
|
It performs browser-based SSO login with 2FA mobile push approval.
|
||||||
|
Session cookies are encrypted at rest with the master password.
|
||||||
|
|
||||||
|
**Two-call 2FA flow**: The first call starts the browser login in the
|
||||||
|
background and returns immediately asking you to tell the user to approve
|
||||||
|
2FA on their phone. Call login again with the same master_password after
|
||||||
|
the user approves — the second call picks up the result.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
master_password: Decrypts stored credentials (and cookies), or encrypts
|
||||||
|
new ones if username/password are also provided.
|
||||||
|
username: Email address. Provide together with password for first-time
|
||||||
|
credential setup (replaces `login.py --setup`).
|
||||||
|
password: Account password. Required together with username for setup.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON result with success status and any error details.
|
||||||
|
"""
|
||||||
|
app_ctx = _get_app_ctx(ctx)
|
||||||
|
client = app_ctx.client
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# If a background login task exists, check its status first
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
if app_ctx.pending_login is not None:
|
||||||
|
task = app_ctx.pending_login
|
||||||
|
|
||||||
|
if not task.done():
|
||||||
|
return json.dumps({
|
||||||
|
"status": "awaiting_2fa",
|
||||||
|
"message": "Still waiting for 2FA approval. Please approve the login in your authenticator app, then call login again.",
|
||||||
|
})
|
||||||
|
|
||||||
|
# Task finished — harvest result and clear
|
||||||
|
app_ctx.pending_login = None
|
||||||
|
try:
|
||||||
|
result = task.result()
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"success": False, "error": f"Background login failed: {e}"})
|
||||||
|
|
||||||
|
if result.get("success"):
|
||||||
|
from exchange_mcp.auth import encrypt_cookie_file
|
||||||
|
|
||||||
|
cookies_str = result.pop("cookies")
|
||||||
|
try:
|
||||||
|
encrypt_cookie_file(cookies_str, master_password, client.cookie_file)
|
||||||
|
client.load_cookies_from_string(cookies_str)
|
||||||
|
if _session_is_valid(client):
|
||||||
|
return json.dumps({"success": True, "message": "Logged in and session verified. Cookies encrypted."})
|
||||||
|
else:
|
||||||
|
return json.dumps({"success": True, "message": "Cookies saved but session verification failed. Try again."})
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"success": True, "message": f"Login succeeded but cookie handling failed: {e}"})
|
||||||
|
else:
|
||||||
|
return json.dumps(result)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# No pending task — normal login flow
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
# 1. Check if already authenticated (cookies already in memory)
|
||||||
|
if _session_is_valid(client):
|
||||||
|
return json.dumps({"success": True, "message": "Session is already active."})
|
||||||
|
|
||||||
|
# 2. Verify playwright is available
|
||||||
|
try:
|
||||||
|
import playwright # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
return json.dumps({
|
||||||
|
"success": False,
|
||||||
|
"error": "playwright is not installed. Run: pip install playwright && playwright install chromium",
|
||||||
|
})
|
||||||
|
|
||||||
|
# 3. Resolve credentials
|
||||||
|
from exchange_mcp.auth import (
|
||||||
|
encrypt_credentials,
|
||||||
|
decrypt_credentials,
|
||||||
|
CREDS_FILE,
|
||||||
|
decrypt_cookie_file,
|
||||||
|
encrypt_cookie_file,
|
||||||
|
perform_login,
|
||||||
|
)
|
||||||
|
|
||||||
|
if username and password:
|
||||||
|
# First-time setup: encrypt and save credentials
|
||||||
|
encrypt_credentials(username, password, master_password)
|
||||||
|
else:
|
||||||
|
# Decrypt existing credentials
|
||||||
|
if not CREDS_FILE.exists():
|
||||||
|
return json.dumps({
|
||||||
|
"success": False,
|
||||||
|
"error": "No stored credentials found. Provide username and password for first-time setup.",
|
||||||
|
})
|
||||||
|
username, password = decrypt_credentials(master_password)
|
||||||
|
if not username:
|
||||||
|
return json.dumps({
|
||||||
|
"success": False,
|
||||||
|
"error": "Invalid master password — could not decrypt credentials.",
|
||||||
|
})
|
||||||
|
|
||||||
|
# Store user email on the client for availability queries
|
||||||
|
client.user_email = username
|
||||||
|
|
||||||
|
# 4. Try restoring session from encrypted cookies on disk
|
||||||
|
cookies_str = decrypt_cookie_file(master_password, client.cookie_file)
|
||||||
|
if cookies_str:
|
||||||
|
try:
|
||||||
|
client.load_cookies_from_string(cookies_str)
|
||||||
|
if _session_is_valid(client):
|
||||||
|
return json.dumps({
|
||||||
|
"success": True,
|
||||||
|
"message": "Session restored from encrypted cookies.",
|
||||||
|
})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 5. Start browser login in background (non-blocking for 2FA)
|
||||||
|
app_ctx.pending_login = asyncio.create_task(
|
||||||
|
perform_login(
|
||||||
|
username=username,
|
||||||
|
password=password,
|
||||||
|
owa_url=client.owa_url,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return json.dumps({
|
||||||
|
"status": "awaiting_2fa",
|
||||||
|
"message": "Please approve the login in your 2FA authenticator app, then call login again with the same master_password.",
|
||||||
|
})
|
||||||
+593
@@ -0,0 +1,593 @@
|
|||||||
|
"""Availability / free-time tools for the Exchange MCP server.
|
||||||
|
|
||||||
|
Ports find-free-time.py and find-meeting-time.py logic into MCP tools
|
||||||
|
using OWAClient.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from mcp.server.fastmcp import Context
|
||||||
|
|
||||||
|
from exchange_mcp.server import mcp, AppContext
|
||||||
|
from exchange_mcp.owa_client import OWAClient
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client(ctx: Context) -> OWAClient:
|
||||||
|
"""Extract the OWAClient from the MCP lifespan context."""
|
||||||
|
app_ctx: AppContext = ctx.request_context.lifespan_context
|
||||||
|
return app_ctx.client
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Pure helper functions (preserved from find-meeting-time.py)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _parse_freebusy_string(
|
||||||
|
freebusy_str: str, start_time: datetime, interval_minutes: int = 30
|
||||||
|
) -> list[tuple]:
|
||||||
|
"""Parse the MergedFreeBusy string.
|
||||||
|
|
||||||
|
Each character represents a time slot:
|
||||||
|
0 = Free, 1 = Tentative, 2 = Busy, 3 = Out of Office, 4 = Working Elsewhere
|
||||||
|
"""
|
||||||
|
busy_periods = []
|
||||||
|
current_time = start_time
|
||||||
|
|
||||||
|
for char in freebusy_str:
|
||||||
|
next_time = current_time + timedelta(minutes=interval_minutes)
|
||||||
|
if char in ['1', '2', '3', '4']: # Not free
|
||||||
|
busy_periods.append((current_time, next_time, char))
|
||||||
|
current_time = next_time
|
||||||
|
|
||||||
|
return busy_periods
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_busy_periods(all_busy: list) -> list[tuple]:
|
||||||
|
"""Merge overlapping busy periods."""
|
||||||
|
if not all_busy:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Sort by start time
|
||||||
|
sorted_busy = sorted(all_busy, key=lambda x: x[0])
|
||||||
|
merged = [(sorted_busy[0][0], sorted_busy[0][1])]
|
||||||
|
|
||||||
|
for start, end, *_ in sorted_busy[1:]:
|
||||||
|
if start <= merged[-1][1]:
|
||||||
|
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
|
||||||
|
else:
|
||||||
|
merged.append((start, end))
|
||||||
|
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
|
def _find_free_slots(
|
||||||
|
busy_periods: list, date, start_hour: int, end_hour: int, duration_minutes: int
|
||||||
|
) -> list[tuple]:
|
||||||
|
"""Find free slots on a given date within working hours."""
|
||||||
|
day_start = datetime.combine(date, datetime.min.time().replace(hour=start_hour))
|
||||||
|
day_end = datetime.combine(date, datetime.min.time().replace(hour=end_hour))
|
||||||
|
|
||||||
|
# Filter busy periods to this day
|
||||||
|
day_busy = []
|
||||||
|
for period in busy_periods:
|
||||||
|
start, end = period[0], period[1]
|
||||||
|
if end.date() < date or start.date() > date:
|
||||||
|
continue
|
||||||
|
start = max(start, day_start)
|
||||||
|
end = min(end, day_end)
|
||||||
|
if start < end:
|
||||||
|
day_busy.append((start, end))
|
||||||
|
|
||||||
|
# Merge overlapping
|
||||||
|
merged = _merge_busy_periods([(s, e) for s, e in day_busy])
|
||||||
|
|
||||||
|
# Find gaps
|
||||||
|
free_slots = []
|
||||||
|
current = day_start
|
||||||
|
|
||||||
|
for busy_start, busy_end in merged:
|
||||||
|
if current < busy_start:
|
||||||
|
gap_duration = (busy_start - current).total_seconds() / 60
|
||||||
|
if gap_duration >= duration_minutes:
|
||||||
|
free_slots.append((current, busy_start))
|
||||||
|
current = max(current, busy_end)
|
||||||
|
|
||||||
|
# Check for time after last meeting
|
||||||
|
if current < day_end:
|
||||||
|
gap_duration = (day_end - current).total_seconds() / 60
|
||||||
|
if gap_duration >= duration_minutes:
|
||||||
|
free_slots.append((current, day_end))
|
||||||
|
|
||||||
|
return free_slots
|
||||||
|
|
||||||
|
|
||||||
|
def _format_time(dt: datetime) -> str:
|
||||||
|
"""Format datetime as HH:MM."""
|
||||||
|
return dt.strftime('%H:%M')
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Helper: get busy events via GetUserAvailability (includes recurring)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _get_availability_events(
|
||||||
|
client: OWAClient, email: str, start_date, end_date
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Get busy events via GetUserAvailability (expands recurring events)."""
|
||||||
|
payload = {
|
||||||
|
'__type': 'GetUserAvailabilityJsonRequest:#Exchange',
|
||||||
|
'Header': {
|
||||||
|
'__type': 'JsonRequestHeaders:#Exchange',
|
||||||
|
'RequestServerVersion': 'Exchange2013',
|
||||||
|
'TimeZoneContext': {
|
||||||
|
'__type': 'TimeZoneContext:#Exchange',
|
||||||
|
'TimeZoneDefinition': {
|
||||||
|
'__type': 'TimeZoneDefinitionType:#Exchange',
|
||||||
|
'Id': 'Russian Standard Time',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Body': {
|
||||||
|
'__type': 'GetUserAvailabilityRequest:#Exchange',
|
||||||
|
'MailboxDataArray': [{
|
||||||
|
'__type': 'MailboxData:#Exchange',
|
||||||
|
'Email': {'__type': 'EmailAddress:#Exchange', 'Address': email},
|
||||||
|
'AttendeeType': 'Required',
|
||||||
|
}],
|
||||||
|
'FreeBusyViewOptions': {
|
||||||
|
'__type': 'FreeBusyViewOptions:#Exchange',
|
||||||
|
'TimeWindow': {
|
||||||
|
'__type': 'Duration:#Exchange',
|
||||||
|
'StartTime': f'{start_date}T00:00:00',
|
||||||
|
'EndTime': f'{end_date + timedelta(days=1)}T00:00:00',
|
||||||
|
},
|
||||||
|
'MergedFreeBusyIntervalInMinutes': 30,
|
||||||
|
'RequestedView': 'DetailedMerged',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = client.request('GetUserAvailability', payload)
|
||||||
|
body = data.get('Body', {})
|
||||||
|
|
||||||
|
events = []
|
||||||
|
for fb_resp in body.get('FreeBusyResponseArray', []):
|
||||||
|
fb_view = fb_resp.get('FreeBusyView', {})
|
||||||
|
cal_events = fb_view.get('CalendarEventArray', {})
|
||||||
|
items = (
|
||||||
|
cal_events.get('Items', [])
|
||||||
|
if isinstance(cal_events, dict)
|
||||||
|
else (cal_events if isinstance(cal_events, list) else [])
|
||||||
|
)
|
||||||
|
for event in items:
|
||||||
|
bt = event.get('BusyType', '')
|
||||||
|
if bt in ('Free', 'NoData'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
start_str = event.get('StartTime', '')
|
||||||
|
end_str = event.get('EndTime', '')
|
||||||
|
if not start_str or not end_str:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
start = datetime.fromisoformat(start_str.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||||
|
end = datetime.fromisoformat(end_str.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||||
|
events.append({'start': start, 'end': end, 'status': bt})
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
continue
|
||||||
|
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Helper: get calendar folder ID
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _get_calendar_folder_id(client: OWAClient) -> str | None:
|
||||||
|
"""Get the calendar folder ID via GetFolder."""
|
||||||
|
payload = {
|
||||||
|
'__type': 'GetFolderJsonRequest:#Exchange',
|
||||||
|
'Header': {
|
||||||
|
'__type': 'JsonRequestHeaders:#Exchange',
|
||||||
|
'RequestServerVersion': 'Exchange2013',
|
||||||
|
},
|
||||||
|
'Body': {
|
||||||
|
'__type': 'GetFolderRequest:#Exchange',
|
||||||
|
'FolderShape': {
|
||||||
|
'__type': 'FolderResponseShape:#Exchange',
|
||||||
|
'BaseShape': 'IdOnly',
|
||||||
|
},
|
||||||
|
'FolderIds': [
|
||||||
|
{'__type': 'DistinguishedFolderId:#Exchange', 'Id': 'calendar'}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = client.request("GetFolder", payload)
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if "Folders" in msg:
|
||||||
|
for f in msg["Folders"]:
|
||||||
|
fid = f.get("FolderId", {}).get("Id")
|
||||||
|
if fid:
|
||||||
|
return fid
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Helper: get own calendar events (from find-free-time.py)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _get_calendar_events(
|
||||||
|
client: OWAClient, folder_id: str, start_date, end_date
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Get calendar events within a date range. Returns list of busy period dicts."""
|
||||||
|
events = []
|
||||||
|
offset = 0
|
||||||
|
batch_size = 100
|
||||||
|
|
||||||
|
while True:
|
||||||
|
payload = {
|
||||||
|
'__type': 'FindItemJsonRequest:#Exchange',
|
||||||
|
'Header': {
|
||||||
|
'__type': 'JsonRequestHeaders:#Exchange',
|
||||||
|
'RequestServerVersion': 'Exchange2013',
|
||||||
|
},
|
||||||
|
'Body': {
|
||||||
|
'__type': 'FindItemRequest:#Exchange',
|
||||||
|
'ItemShape': {
|
||||||
|
'__type': 'ItemResponseShape:#Exchange',
|
||||||
|
'BaseShape': 'AllProperties',
|
||||||
|
},
|
||||||
|
'ParentFolderIds': [
|
||||||
|
{'__type': 'FolderId:#Exchange', 'Id': folder_id}
|
||||||
|
],
|
||||||
|
'Traversal': 'Shallow',
|
||||||
|
'Paging': {
|
||||||
|
'__type': 'IndexedPageView:#Exchange',
|
||||||
|
'BasePoint': 'Beginning',
|
||||||
|
'Offset': offset,
|
||||||
|
'MaxEntriesReturned': batch_size,
|
||||||
|
},
|
||||||
|
'SortOrder': [
|
||||||
|
{
|
||||||
|
'__type': 'SortResults:#Exchange',
|
||||||
|
'Order': 'Ascending',
|
||||||
|
'Path': {
|
||||||
|
'__type': 'PropertyUri:#Exchange',
|
||||||
|
'FieldURI': 'Start',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = client.request("FindItem", payload)
|
||||||
|
items = client.extract_items(data)
|
||||||
|
|
||||||
|
if not items:
|
||||||
|
break
|
||||||
|
|
||||||
|
folder_items = items[0].get('RootFolder', {}).get('Items', [])
|
||||||
|
if not folder_items:
|
||||||
|
break
|
||||||
|
|
||||||
|
for item in folder_items:
|
||||||
|
# Skip cancelled events
|
||||||
|
if item.get('IsCancelled'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Skip free/tentative slots
|
||||||
|
fbt = item.get('FreeBusyType', 'Busy')
|
||||||
|
if fbt in ['Free', 'NoData']:
|
||||||
|
continue
|
||||||
|
|
||||||
|
start_str = item.get('Start', '')
|
||||||
|
end_str = item.get('End', '')
|
||||||
|
|
||||||
|
if not start_str or not end_str:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
start = datetime.fromisoformat(start_str.replace('Z', '+00:00'))
|
||||||
|
end = datetime.fromisoformat(end_str.replace('Z', '+00:00'))
|
||||||
|
|
||||||
|
# Convert to naive datetime for comparison
|
||||||
|
start = start.replace(tzinfo=None)
|
||||||
|
end = end.replace(tzinfo=None)
|
||||||
|
|
||||||
|
# Filter by date range
|
||||||
|
if end.date() < start_date or start.date() > end_date:
|
||||||
|
continue
|
||||||
|
|
||||||
|
events.append({
|
||||||
|
'start': start,
|
||||||
|
'end': end,
|
||||||
|
'subject': item.get('Subject', ''),
|
||||||
|
'status': fbt,
|
||||||
|
})
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Check if there are more items
|
||||||
|
is_last = items[0].get('RootFolder', {}).get('IncludesLastItemInRange', True)
|
||||||
|
if is_last:
|
||||||
|
break
|
||||||
|
|
||||||
|
offset += batch_size
|
||||||
|
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Tool: find_free_time
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def find_free_time(
|
||||||
|
start_date: str,
|
||||||
|
end_date: str = "",
|
||||||
|
duration_minutes: int = 30,
|
||||||
|
start_hour: int = 9,
|
||||||
|
end_hour: int = 18,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Find free time slots in your own calendar.
|
||||||
|
|
||||||
|
Analyzes your calendar events and returns available time slots
|
||||||
|
within working hours for each weekday in the range.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
start_date: Start date in YYYY-MM-DD format.
|
||||||
|
end_date: End date in YYYY-MM-DD format. Defaults to start_date
|
||||||
|
if not provided (single-day search).
|
||||||
|
duration_minutes: Minimum slot duration in minutes. Default 30.
|
||||||
|
start_hour: Working day start hour (0-23). Default 9.
|
||||||
|
end_hour: Working day end hour (0-23). Default 18.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with free_slots keyed by date, each containing an
|
||||||
|
array of {start, end, duration_minutes} objects.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
try:
|
||||||
|
sd = datetime.strptime(start_date, '%Y-%m-%d').date()
|
||||||
|
ed = datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else sd
|
||||||
|
except ValueError as e:
|
||||||
|
return json.dumps({"error": f"Invalid date format: {e}"})
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Use GetUserAvailability for accurate recurring event expansion
|
||||||
|
if client.user_email:
|
||||||
|
all_busy = _get_availability_events(client, client.user_email, sd, ed)
|
||||||
|
else:
|
||||||
|
# Fallback to FindItem (misses recurring event occurrences)
|
||||||
|
folder_id = _get_calendar_folder_id(client)
|
||||||
|
if not folder_id:
|
||||||
|
return json.dumps({"error": "Could not find calendar folder. Session may have expired."})
|
||||||
|
all_busy = _get_calendar_events(client, folder_id, sd, ed)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
# Convert event dicts to (start, end) tuples for _find_free_slots
|
||||||
|
busy_periods = [(ev['start'], ev['end']) for ev in all_busy]
|
||||||
|
|
||||||
|
result = {}
|
||||||
|
current_date = sd
|
||||||
|
while current_date <= ed:
|
||||||
|
# Skip weekends
|
||||||
|
if current_date.weekday() < 5:
|
||||||
|
free = _find_free_slots(
|
||||||
|
busy_periods, current_date,
|
||||||
|
start_hour, end_hour, duration_minutes,
|
||||||
|
)
|
||||||
|
if free:
|
||||||
|
result[str(current_date)] = [
|
||||||
|
{
|
||||||
|
"start": _format_time(s),
|
||||||
|
"end": _format_time(e),
|
||||||
|
"duration_minutes": int((e - s).total_seconds() / 60),
|
||||||
|
}
|
||||||
|
for s, e in free
|
||||||
|
]
|
||||||
|
current_date += timedelta(days=1)
|
||||||
|
|
||||||
|
return json.dumps({"free_slots": result}, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Tool: find_meeting_time
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def find_meeting_time(
|
||||||
|
emails: str,
|
||||||
|
start_date: str,
|
||||||
|
end_date: str = "",
|
||||||
|
duration_minutes: int = 30,
|
||||||
|
start_hour: int = 9,
|
||||||
|
end_hour: int = 18,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Find meeting times that work for multiple people.
|
||||||
|
|
||||||
|
Uses the OWA GetUserAvailability API to check cross-mailbox
|
||||||
|
availability and find common free slots for all attendees.
|
||||||
|
Supports multi-day ranges — searches each weekday in the range.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
emails: Comma-separated email addresses or names of attendees.
|
||||||
|
start_date: Start date in YYYY-MM-DD format.
|
||||||
|
end_date: End date in YYYY-MM-DD format. Defaults to start_date
|
||||||
|
if not provided (single-day search).
|
||||||
|
duration_minutes: Minimum slot duration in minutes. Default 30.
|
||||||
|
start_hour: Working day start hour (0-23). Default 9.
|
||||||
|
end_hour: Working day end hour (0-23). Default 18.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with attendee info and free_slots keyed by date,
|
||||||
|
each containing an array of {start, end, duration_minutes}.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
raw_list = [e.strip() for e in emails.split(',') if e.strip()]
|
||||||
|
if not raw_list:
|
||||||
|
return json.dumps({"error": "No email addresses provided."})
|
||||||
|
|
||||||
|
try:
|
||||||
|
sd = datetime.strptime(start_date, '%Y-%m-%d').date()
|
||||||
|
ed = datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else sd
|
||||||
|
except ValueError as e:
|
||||||
|
return json.dumps({"error": f"Invalid date format: {e}"})
|
||||||
|
|
||||||
|
# Resolve names to email addresses via ResolveNames
|
||||||
|
email_list = []
|
||||||
|
resolve_errors = []
|
||||||
|
for entry in raw_list:
|
||||||
|
if '@' in entry:
|
||||||
|
email_list.append(entry)
|
||||||
|
else:
|
||||||
|
resolutions = client.resolve_names(entry, full_contact=False)
|
||||||
|
if resolutions:
|
||||||
|
addr = resolutions[0].get('Mailbox', {}).get('EmailAddress', '')
|
||||||
|
if addr:
|
||||||
|
email_list.append(addr)
|
||||||
|
else:
|
||||||
|
resolve_errors.append(entry)
|
||||||
|
else:
|
||||||
|
resolve_errors.append(entry)
|
||||||
|
|
||||||
|
if not email_list:
|
||||||
|
return json.dumps({"error": f"Could not resolve any names to email addresses: {resolve_errors}"})
|
||||||
|
|
||||||
|
# Build mailbox data (reused for each day chunk)
|
||||||
|
mailbox_data = []
|
||||||
|
for email in email_list:
|
||||||
|
mailbox_data.append({
|
||||||
|
'__type': 'MailboxData:#Exchange',
|
||||||
|
'Email': {
|
||||||
|
'__type': 'EmailAddress:#Exchange',
|
||||||
|
'Address': email,
|
||||||
|
},
|
||||||
|
'AttendeeType': 'Required',
|
||||||
|
})
|
||||||
|
|
||||||
|
# Query the full date range at once (API handles multi-day windows)
|
||||||
|
payload = {
|
||||||
|
'__type': 'GetUserAvailabilityJsonRequest:#Exchange',
|
||||||
|
'Header': {
|
||||||
|
'__type': 'JsonRequestHeaders:#Exchange',
|
||||||
|
'RequestServerVersion': 'Exchange2013',
|
||||||
|
'TimeZoneContext': {
|
||||||
|
'__type': 'TimeZoneContext:#Exchange',
|
||||||
|
'TimeZoneDefinition': {
|
||||||
|
'__type': 'TimeZoneDefinitionType:#Exchange',
|
||||||
|
'Id': 'Russian Standard Time',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Body': {
|
||||||
|
'__type': 'GetUserAvailabilityRequest:#Exchange',
|
||||||
|
'MailboxDataArray': mailbox_data,
|
||||||
|
'FreeBusyViewOptions': {
|
||||||
|
'__type': 'FreeBusyViewOptions:#Exchange',
|
||||||
|
'TimeWindow': {
|
||||||
|
'__type': 'Duration:#Exchange',
|
||||||
|
'StartTime': f'{sd}T00:00:00',
|
||||||
|
'EndTime': f'{ed + timedelta(days=1)}T00:00:00',
|
||||||
|
},
|
||||||
|
'MergedFreeBusyIntervalInMinutes': 30,
|
||||||
|
'RequestedView': 'DetailedMerged',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request("GetUserAvailability", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
body = data.get('Body', {})
|
||||||
|
if 'ErrorCode' in body:
|
||||||
|
return json.dumps({"error": body.get('FaultMessage', 'Unknown error')})
|
||||||
|
|
||||||
|
# Parse availability responses
|
||||||
|
all_busy = []
|
||||||
|
attendee_info = []
|
||||||
|
freebusy_responses = body.get('FreeBusyResponseArray', [])
|
||||||
|
|
||||||
|
for i, fb_resp in enumerate(freebusy_responses):
|
||||||
|
fb_view = fb_resp.get('FreeBusyView', {})
|
||||||
|
merged_fb = fb_view.get('MergedFreeBusy', '')
|
||||||
|
email = email_list[i] if i < len(email_list) else f"Person {i+1}"
|
||||||
|
|
||||||
|
if merged_fb:
|
||||||
|
start_time = datetime.combine(sd, datetime.min.time())
|
||||||
|
busy_periods = _parse_freebusy_string(merged_fb, start_time)
|
||||||
|
|
||||||
|
busy_count = sum(1 for c in merged_fb if c != '0')
|
||||||
|
free_count = sum(1 for c in merged_fb if c == '0')
|
||||||
|
attendee_info.append({
|
||||||
|
"email": email,
|
||||||
|
"busy_slots": busy_count,
|
||||||
|
"free_slots": free_count,
|
||||||
|
})
|
||||||
|
|
||||||
|
all_busy.extend(busy_periods)
|
||||||
|
else:
|
||||||
|
# Fallback: parse CalendarEventArray
|
||||||
|
cal_events_raw = fb_view.get('CalendarEventArray', {})
|
||||||
|
cal_events = cal_events_raw.get('Items', []) if isinstance(cal_events_raw, dict) else (cal_events_raw if isinstance(cal_events_raw, list) else [])
|
||||||
|
if cal_events:
|
||||||
|
attendee_info.append({
|
||||||
|
"email": email,
|
||||||
|
"calendar_events": len(cal_events),
|
||||||
|
})
|
||||||
|
for event in cal_events:
|
||||||
|
start_str = event.get('StartTime', '')
|
||||||
|
end_str = event.get('EndTime', '')
|
||||||
|
if start_str and end_str:
|
||||||
|
try:
|
||||||
|
start = datetime.fromisoformat(start_str.replace('Z', '+00:00'))
|
||||||
|
end = datetime.fromisoformat(end_str.replace('Z', '+00:00'))
|
||||||
|
all_busy.append((start, end))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
attendee_info.append({
|
||||||
|
"email": email,
|
||||||
|
"status": "no_data",
|
||||||
|
})
|
||||||
|
|
||||||
|
merged_busy = _merge_busy_periods(all_busy)
|
||||||
|
|
||||||
|
# Find free slots for each weekday in range
|
||||||
|
free_by_date = {}
|
||||||
|
current_date = sd
|
||||||
|
while current_date <= ed:
|
||||||
|
if current_date.weekday() < 5: # Skip weekends
|
||||||
|
free = _find_free_slots(
|
||||||
|
merged_busy, current_date,
|
||||||
|
start_hour, end_hour, duration_minutes,
|
||||||
|
)
|
||||||
|
if free:
|
||||||
|
free_by_date[str(current_date)] = [
|
||||||
|
{
|
||||||
|
"start": _format_time(s),
|
||||||
|
"end": _format_time(e),
|
||||||
|
"duration_minutes": int((e - s).total_seconds() / 60),
|
||||||
|
}
|
||||||
|
for s, e in free
|
||||||
|
]
|
||||||
|
current_date += timedelta(days=1)
|
||||||
|
|
||||||
|
result = {
|
||||||
|
"period": {"start": str(sd), "end": str(ed)},
|
||||||
|
"attendees": attendee_info,
|
||||||
|
"free_slots": free_by_date,
|
||||||
|
}
|
||||||
|
|
||||||
|
if resolve_errors:
|
||||||
|
result["unresolved"] = resolve_errors
|
||||||
|
|
||||||
|
return json.dumps(result, ensure_ascii=False)
|
||||||
+1318
File diff suppressed because it is too large.
Load diff
+1033
File diff suppressed because it is too large.
Load diff
+430
@@ -0,0 +1,430 @@
|
|||||||
|
"""Folder tools for the Exchange MCP server.
|
||||||
|
|
||||||
|
Ports the get-folders.py logic into an MCP tool using OWAClient.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from mcp.server.fastmcp import Context
|
||||||
|
|
||||||
|
from exchange_mcp.server import mcp, AppContext
|
||||||
|
from exchange_mcp.owa_client import OWAClient
|
||||||
|
|
||||||
|
|
||||||
|
_DISTINGUISHED_NAMES = {
|
||||||
|
"msgfolderroot", "inbox", "sentitems", "drafts", "deleteditems",
|
||||||
|
"junkemail", "outbox", "calendar", "contacts", "tasks", "notes",
|
||||||
|
"journal", "searchfolders",
|
||||||
|
}
|
||||||
|
|
||||||
|
_HEADER_TZ = {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
"TimeZoneContext": {
|
||||||
|
"__type": "TimeZoneContext:#Exchange",
|
||||||
|
"TimeZoneDefinition": {
|
||||||
|
"__type": "TimeZoneDefinitionType:#Exchange",
|
||||||
|
"Id": "Russian Standard Time",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client(ctx: Context) -> OWAClient:
|
||||||
|
"""Extract the OWAClient from the MCP lifespan context."""
|
||||||
|
app_ctx: AppContext = ctx.request_context.lifespan_context
|
||||||
|
return app_ctx.client
|
||||||
|
|
||||||
|
|
||||||
|
def _folder_id_dict(folder_id: str) -> dict:
|
||||||
|
"""Build a typed FolderId or DistinguishedFolderId dict."""
|
||||||
|
if folder_id.lower() in _DISTINGUISHED_NAMES:
|
||||||
|
return {"__type": "DistinguishedFolderId:#Exchange", "Id": folder_id}
|
||||||
|
return {"__type": "FolderId:#Exchange", "Id": folder_id}
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def check_session(ctx: Context = None) -> str:
|
||||||
|
"""Check whether the current OWA session is authenticated.
|
||||||
|
|
||||||
|
Makes a lightweight GetFolder call on the inbox. Returns session
|
||||||
|
status, the mailbox display name, and cookie file path.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with authenticated (bool), mailbox name, and details.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "GetFolderJsonRequest:#Exchange",
|
||||||
|
"Header": {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
},
|
||||||
|
"Body": {
|
||||||
|
"__type": "GetFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "Default",
|
||||||
|
},
|
||||||
|
"FolderIds": [
|
||||||
|
{"__type": "DistinguishedFolderId:#Exchange", "Id": "inbox"}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request("GetFolder", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({
|
||||||
|
"authenticated": False,
|
||||||
|
"error": str(e),
|
||||||
|
"cookie_file": str(client.cookie_file),
|
||||||
|
})
|
||||||
|
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if "Folders" in msg:
|
||||||
|
folder = msg["Folders"][0]
|
||||||
|
return json.dumps({
|
||||||
|
"authenticated": True,
|
||||||
|
"mailbox": folder.get("DisplayName", ""),
|
||||||
|
"unread": folder.get("UnreadCount", 0),
|
||||||
|
"cookie_file": str(client.cookie_file),
|
||||||
|
})
|
||||||
|
|
||||||
|
return json.dumps({
|
||||||
|
"authenticated": False,
|
||||||
|
"error": "Unexpected response",
|
||||||
|
"cookie_file": str(client.cookie_file),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_folders(
|
||||||
|
parent_folder_id: str = "msgfolderroot",
|
||||||
|
recursive: bool = False,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""List mail folders from the Exchange mailbox.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
parent_folder_id: Parent folder to list children of.
|
||||||
|
Defaults to "msgfolderroot" (top-level). Can be a
|
||||||
|
distinguished folder name or a raw folder ID.
|
||||||
|
recursive: If True, traverse all subfolders recursively (Deep).
|
||||||
|
If False, only list immediate children (Shallow).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON array of folder objects with: name, id, total_count,
|
||||||
|
unread_count, child_folder_count.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
traversal = "Deep" if recursive else "Shallow"
|
||||||
|
|
||||||
|
# Determine parent folder id type
|
||||||
|
# Distinguished folder names are short lowercase strings
|
||||||
|
parent_folder = _folder_id_dict(parent_folder_id)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "FindFolderJsonRequest:#Exchange",
|
||||||
|
"Header": {
|
||||||
|
"__type": "JsonRequestHeaders:#Exchange",
|
||||||
|
"RequestServerVersion": "Exchange2013",
|
||||||
|
},
|
||||||
|
"Body": {
|
||||||
|
"__type": "FindFolderRequest:#Exchange",
|
||||||
|
"FolderShape": {
|
||||||
|
"__type": "FolderResponseShape:#Exchange",
|
||||||
|
"BaseShape": "Default",
|
||||||
|
},
|
||||||
|
"ParentFolderIds": [parent_folder],
|
||||||
|
"Traversal": traversal,
|
||||||
|
"Paging": {
|
||||||
|
"__type": "IndexedPageView:#Exchange",
|
||||||
|
"BasePoint": "Beginning",
|
||||||
|
"Offset": 0,
|
||||||
|
"MaxEntriesReturned": 200,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request("FindFolder", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
folders = []
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if "RootFolder" in msg and "Folders" in msg["RootFolder"]:
|
||||||
|
for f in msg["RootFolder"]["Folders"]:
|
||||||
|
folders.append({
|
||||||
|
"name": f.get("DisplayName", "Unknown"),
|
||||||
|
"id": f.get("FolderId", {}).get("Id", ""),
|
||||||
|
"total_count": f.get("TotalCount", 0),
|
||||||
|
"unread_count": f.get("UnreadCount", 0),
|
||||||
|
"child_folder_count": f.get("ChildFolderCount", 0),
|
||||||
|
})
|
||||||
|
|
||||||
|
return json.dumps(folders, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def create_folder(
|
||||||
|
name: str,
|
||||||
|
parent_folder_id: str = "msgfolderroot",
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Create a new mail folder.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name: Display name for the new folder.
|
||||||
|
parent_folder_id: Parent folder to create under.
|
||||||
|
Defaults to "msgfolderroot" (top-level). Can be a
|
||||||
|
distinguished folder name or a raw folder ID.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with the created folder's id and name.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "CreateFolderJsonRequest:#Exchange",
|
||||||
|
"Header": _HEADER_TZ,
|
||||||
|
"Body": {
|
||||||
|
"__type": "CreateFolderRequest:#Exchange",
|
||||||
|
"ParentFolderId": {
|
||||||
|
"__type": "TargetFolderId:#Exchange",
|
||||||
|
"BaseFolderId": _folder_id_dict(parent_folder_id),
|
||||||
|
},
|
||||||
|
"Folders": [
|
||||||
|
{
|
||||||
|
"__type": "Folder:#Exchange",
|
||||||
|
"DisplayName": name,
|
||||||
|
"FolderClass": "IPF.Note",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request_header_payload("CreateFolder", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if "Folders" in msg:
|
||||||
|
folder = msg["Folders"][0]
|
||||||
|
return json.dumps({
|
||||||
|
"success": True,
|
||||||
|
"name": name,
|
||||||
|
"id": folder.get("FolderId", {}).get("Id", ""),
|
||||||
|
})
|
||||||
|
|
||||||
|
return json.dumps({"error": "Unexpected response", "raw": str(data)})
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def rename_folder(
|
||||||
|
folder_id: str,
|
||||||
|
new_name: str,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Rename an existing mail folder.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
folder_id: The Exchange folder ID to rename (from get_folders).
|
||||||
|
new_name: New display name for the folder.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with success status and new folder id.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "UpdateFolderJsonRequest:#Exchange",
|
||||||
|
"Header": _HEADER_TZ,
|
||||||
|
"Body": {
|
||||||
|
"__type": "UpdateFolderRequest:#Exchange",
|
||||||
|
"FolderChanges": [
|
||||||
|
{
|
||||||
|
"__type": "FolderChange:#Exchange",
|
||||||
|
"FolderId": {
|
||||||
|
"__type": "FolderId:#Exchange",
|
||||||
|
"Id": folder_id,
|
||||||
|
},
|
||||||
|
"Updates": [
|
||||||
|
{
|
||||||
|
"__type": "SetFolderField:#Exchange",
|
||||||
|
"Path": {
|
||||||
|
"__type": "PropertyUri:#Exchange",
|
||||||
|
"FieldURI": "FolderDisplayName",
|
||||||
|
},
|
||||||
|
"Folder": {
|
||||||
|
"__type": "Folder:#Exchange",
|
||||||
|
"DisplayName": new_name,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request_header_payload("UpdateFolder", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if "Folders" in msg:
|
||||||
|
folder = msg["Folders"][0]
|
||||||
|
return json.dumps({
|
||||||
|
"success": True,
|
||||||
|
"new_name": new_name,
|
||||||
|
"id": folder.get("FolderId", {}).get("Id", ""),
|
||||||
|
})
|
||||||
|
|
||||||
|
return json.dumps({"error": "Unexpected response", "raw": str(data)})
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def empty_folder(
|
||||||
|
folder_id: str,
|
||||||
|
delete_sub_folders: bool = False,
|
||||||
|
permanent: bool = False,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Empty all items from a mail folder.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
folder_id: The Exchange folder ID to empty (from get_folders).
|
||||||
|
delete_sub_folders: If True, also delete sub-folders. Default False.
|
||||||
|
permanent: If True, permanently delete items (HardDelete).
|
||||||
|
Otherwise move to Deleted Items. Default False.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with success status.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
delete_type = "HardDelete" if permanent else "MoveToDeletedItems"
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "EmptyFolderJsonRequest:#Exchange",
|
||||||
|
"Header": _HEADER_TZ,
|
||||||
|
"Body": {
|
||||||
|
"__type": "EmptyFolderRequest:#Exchange",
|
||||||
|
"FolderIds": [
|
||||||
|
{"__type": "FolderId:#Exchange", "Id": folder_id}
|
||||||
|
],
|
||||||
|
"DeleteType": delete_type,
|
||||||
|
"DeleteSubFolders": delete_sub_folders,
|
||||||
|
"SuppressReadReceipt": True,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request_header_payload("EmptyFolder", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if msg.get("ResponseClass") == "Success":
|
||||||
|
return json.dumps({"success": True, "folder_id": folder_id})
|
||||||
|
|
||||||
|
return json.dumps({"error": "Unexpected response", "raw": str(data)})
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def delete_folder(
|
||||||
|
folder_id: str,
|
||||||
|
permanent: bool = False,
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Delete a mail folder.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
folder_id: The Exchange folder ID to delete (from get_folders).
|
||||||
|
permanent: If True, permanently delete (HardDelete).
|
||||||
|
Otherwise move to Deleted Items. Default False.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with success status.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
delete_type = "HardDelete" if permanent else "MoveToDeletedItems"
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "DeleteFolderJsonRequest:#Exchange",
|
||||||
|
"Header": _HEADER_TZ,
|
||||||
|
"Body": {
|
||||||
|
"__type": "DeleteFolderRequest:#Exchange",
|
||||||
|
"FolderIds": [
|
||||||
|
{"__type": "FolderId:#Exchange", "Id": folder_id}
|
||||||
|
],
|
||||||
|
"DeleteType": delete_type,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request_header_payload("DeleteFolder", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if msg.get("ResponseClass") == "Success":
|
||||||
|
return json.dumps({"success": True, "folder_id": folder_id})
|
||||||
|
|
||||||
|
return json.dumps({"error": "Unexpected response", "raw": str(data)})
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def move_folder(
|
||||||
|
folder_id: str,
|
||||||
|
target_parent_folder_id: str = "msgfolderroot",
|
||||||
|
ctx: Context = None,
|
||||||
|
) -> str:
|
||||||
|
"""Move a mail folder to a different parent folder.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
folder_id: The Exchange folder ID to move (from get_folders).
|
||||||
|
target_parent_folder_id: Destination parent folder.
|
||||||
|
Defaults to "msgfolderroot" (top-level). Can be a
|
||||||
|
distinguished folder name or a raw folder ID.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON object with success status and new folder ID.
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"__type": "MoveFolderJsonRequest:#Exchange",
|
||||||
|
"Header": _HEADER_TZ,
|
||||||
|
"Body": {
|
||||||
|
"__type": "MoveFolderRequest:#Exchange",
|
||||||
|
"FolderIds": [
|
||||||
|
{"__type": "FolderId:#Exchange", "Id": folder_id}
|
||||||
|
],
|
||||||
|
"ToFolderId": {
|
||||||
|
"__type": "TargetFolderId:#Exchange",
|
||||||
|
"BaseFolderId": _folder_id_dict(target_parent_folder_id),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = client.request_header_payload("MoveFolder", payload)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
for msg in client.extract_items(data):
|
||||||
|
if "Folders" in msg:
|
||||||
|
folder = msg["Folders"][0]
|
||||||
|
return json.dumps({
|
||||||
|
"success": True,
|
||||||
|
"folder_id": folder.get("FolderId", {}).get("Id", ""),
|
||||||
|
})
|
||||||
|
|
||||||
|
return json.dumps({"error": "Unexpected response", "raw": str(data)})
|
||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
"""People / directory search tools for the Exchange MCP server.
|
||||||
|
|
||||||
|
Ports the find-person.py logic into an MCP tool using OWAClient.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from mcp.server.fastmcp import Context
|
||||||
|
|
||||||
|
from exchange_mcp.server import mcp, AppContext
|
||||||
|
from exchange_mcp.owa_client import OWAClient
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client(ctx: Context) -> OWAClient:
|
||||||
|
"""Extract the OWAClient from the MCP lifespan context."""
|
||||||
|
app_ctx: AppContext = ctx.request_context.lifespan_context
|
||||||
|
return app_ctx.client
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_person(resolution: dict) -> dict:
|
||||||
|
"""Parse person data from a ResolveNames resolution entry.
|
||||||
|
|
||||||
|
Preserves the exact logic from find-person.py parse_person().
|
||||||
|
"""
|
||||||
|
mailbox = resolution.get("Mailbox", {})
|
||||||
|
contact = resolution.get("Contact", {})
|
||||||
|
|
||||||
|
person = {
|
||||||
|
"name": mailbox.get("Name", contact.get("DisplayName", "")),
|
||||||
|
"email": mailbox.get("EmailAddress", ""),
|
||||||
|
"type": mailbox.get("MailboxType", ""),
|
||||||
|
"first_name": contact.get("GivenName", ""),
|
||||||
|
"last_name": contact.get("Surname", ""),
|
||||||
|
"job_title": contact.get("JobTitle", ""),
|
||||||
|
"department": contact.get("Department", ""),
|
||||||
|
"company": contact.get("CompanyName", ""),
|
||||||
|
"office": contact.get("OfficeLocation", ""),
|
||||||
|
"manager": "",
|
||||||
|
"manager_email": "",
|
||||||
|
"phones": {},
|
||||||
|
"address": {},
|
||||||
|
"direct_reports": [],
|
||||||
|
"alias": contact.get("Alias", ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
# Phone numbers
|
||||||
|
for phone in contact.get("PhoneNumbers", []):
|
||||||
|
key = phone.get("Key", "")
|
||||||
|
number = phone.get("PhoneNumber", "")
|
||||||
|
if number:
|
||||||
|
person["phones"][key] = number
|
||||||
|
|
||||||
|
# Physical address
|
||||||
|
for addr in contact.get("PhysicalAddresses", []):
|
||||||
|
if addr.get("Key") == "Business":
|
||||||
|
parts = []
|
||||||
|
if addr.get("Street"):
|
||||||
|
parts.append(addr["Street"])
|
||||||
|
if addr.get("City"):
|
||||||
|
parts.append(addr["City"])
|
||||||
|
if addr.get("PostalCode"):
|
||||||
|
parts.append(addr["PostalCode"])
|
||||||
|
if addr.get("CountryOrRegion"):
|
||||||
|
parts.append(addr["CountryOrRegion"])
|
||||||
|
if parts:
|
||||||
|
person["address"] = {
|
||||||
|
"street": addr.get("Street", ""),
|
||||||
|
"city": addr.get("City", ""),
|
||||||
|
"postal_code": addr.get("PostalCode", ""),
|
||||||
|
"country": addr.get("CountryOrRegion", ""),
|
||||||
|
"full": ", ".join(parts),
|
||||||
|
}
|
||||||
|
|
||||||
|
# Manager
|
||||||
|
manager_data = contact.get("ManagerMailbox", {}).get("Mailbox", {})
|
||||||
|
if manager_data:
|
||||||
|
person["manager"] = manager_data.get("Name", "")
|
||||||
|
person["manager_email"] = manager_data.get("EmailAddress", "")
|
||||||
|
elif contact.get("Manager"):
|
||||||
|
person["manager"] = contact.get("Manager", "")
|
||||||
|
|
||||||
|
# Direct reports
|
||||||
|
for report in contact.get("DirectReports", []):
|
||||||
|
person["direct_reports"].append({
|
||||||
|
"name": report.get("Name", ""),
|
||||||
|
"email": report.get("EmailAddress", ""),
|
||||||
|
})
|
||||||
|
|
||||||
|
return person
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def find_person(query: str, ctx: Context) -> str:
|
||||||
|
"""Search for people in the corporate directory.
|
||||||
|
|
||||||
|
Looks up employees by name, email, department, or keyword using the
|
||||||
|
Exchange ResolveNames API against Active Directory.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
query: Name, email address, or keyword to search for.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON array of matching people with contact details (name, email,
|
||||||
|
job_title, department, company, office, phones, address, manager,
|
||||||
|
direct_reports, alias).
|
||||||
|
"""
|
||||||
|
client = _get_client(ctx)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resolutions = client.resolve_names(query)
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)})
|
||||||
|
|
||||||
|
if not resolutions:
|
||||||
|
return json.dumps([])
|
||||||
|
|
||||||
|
people = [_parse_person(r) for r in resolutions]
|
||||||
|
return json.dumps(people, ensure_ascii=False)
|
||||||
Vendored
+133
@@ -0,0 +1,133 @@
|
|||||||
|
"""Shared utility functions for the Exchange MCP server.
|
||||||
|
|
||||||
|
Extracts duplicated helpers from the standalone scripts:
|
||||||
|
html_to_text, date/time formatting and parsing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import html
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
def html_to_text(html_content: str) -> str:
|
||||||
|
"""Convert HTML to plain text.
|
||||||
|
|
||||||
|
Strips scripts, styles, converts <br>/<p>/<div> to newlines,
|
||||||
|
removes remaining tags, and unescapes HTML entities.
|
||||||
|
"""
|
||||||
|
if not html_content:
|
||||||
|
return ""
|
||||||
|
text = re.sub(
|
||||||
|
r"<script[^>]*>.*?</script>", "", html_content, flags=re.DOTALL | re.IGNORECASE
|
||||||
|
)
|
||||||
|
text = re.sub(
|
||||||
|
r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE
|
||||||
|
)
|
||||||
|
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"<p[^>]*>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"</p>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"<div[^>]*>", "\n", text, flags=re.IGNORECASE)
|
||||||
|
text = re.sub(r"<[^>]+>", "", text)
|
||||||
|
text = html.unescape(text)
|
||||||
|
text = re.sub(r"\n\s*\n", "\n\n", text)
|
||||||
|
text = re.sub(r"[ \t]+", " ", text)
|
||||||
|
return text.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def extract_links_from_html(html_content: str) -> list[dict]:
|
||||||
|
"""Extract hyperlinks from HTML content.
|
||||||
|
|
||||||
|
Finds <a href="...">text</a> patterns, excludes mailto:, cid:,
|
||||||
|
javascript:, and fragment-only (#) links. Deduplicates by URL.
|
||||||
|
|
||||||
|
Returns list of {url, text} dicts.
|
||||||
|
"""
|
||||||
|
if not html_content:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Match <a ...href="URL"...>text</a>
|
||||||
|
pattern = re.compile(
|
||||||
|
r'<a\s[^>]*href=["\']([^"\']+)["\'][^>]*>(.*?)</a>',
|
||||||
|
re.DOTALL | re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
seen: set[str] = set()
|
||||||
|
links: list[dict] = []
|
||||||
|
|
||||||
|
for url_raw, text_raw in pattern.findall(html_content):
|
||||||
|
url = html.unescape(url_raw).strip()
|
||||||
|
|
||||||
|
# Skip non-http links
|
||||||
|
if url.startswith(("mailto:", "cid:", "javascript:")) or url == "#":
|
||||||
|
continue
|
||||||
|
# Skip fragment-only links
|
||||||
|
if url.startswith("#"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if url in seen:
|
||||||
|
continue
|
||||||
|
seen.add(url)
|
||||||
|
|
||||||
|
# Clean link text: strip tags and whitespace
|
||||||
|
text = re.sub(r"<[^>]+>", "", text_raw)
|
||||||
|
text = html.unescape(text).strip()
|
||||||
|
|
||||||
|
links.append({"url": url, "text": text})
|
||||||
|
|
||||||
|
return links
|
||||||
|
|
||||||
|
|
||||||
|
def format_datetime(dt_str: str) -> str:
|
||||||
|
"""Format an ISO datetime string as 'YYYY-MM-DD HH:MM'.
|
||||||
|
|
||||||
|
Strips timezone suffixes (Z, +offset) for cleaner display.
|
||||||
|
"""
|
||||||
|
if not dt_str:
|
||||||
|
return ""
|
||||||
|
if "T" in dt_str:
|
||||||
|
date_part, time_part = dt_str.split("T", 1)
|
||||||
|
time_part = time_part.split("Z")[0].split("+")[0]
|
||||||
|
return f"{date_part} {time_part[:5]}"
|
||||||
|
return dt_str
|
||||||
|
|
||||||
|
|
||||||
|
def format_date(dt_str: str) -> str:
|
||||||
|
"""Extract the date portion from an ISO datetime string."""
|
||||||
|
if not dt_str:
|
||||||
|
return ""
|
||||||
|
if "T" in dt_str:
|
||||||
|
return dt_str.split("T")[0]
|
||||||
|
return dt_str
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date(date_str: str) -> datetime:
|
||||||
|
"""Parse a date string in common formats.
|
||||||
|
|
||||||
|
Supports: YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, MM/DD/YYYY.
|
||||||
|
"""
|
||||||
|
formats = ["%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%m/%d/%Y"]
|
||||||
|
for fmt in formats:
|
||||||
|
try:
|
||||||
|
return datetime.strptime(date_str, fmt)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
raise ValueError(f"Could not parse date: {date_str}")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_iso_datetime(dt_str: str) -> datetime:
|
||||||
|
"""Parse an ISO datetime string to a naive datetime.
|
||||||
|
|
||||||
|
Handles both 'YYYY-MM-DDTHH:MM:SS' and 'YYYY-MM-DD' formats,
|
||||||
|
stripping any timezone suffix.
|
||||||
|
"""
|
||||||
|
if "T" in dt_str:
|
||||||
|
clean = dt_str.split("Z")[0].split("+")[0]
|
||||||
|
return datetime.strptime(clean, "%Y-%m-%dT%H:%M:%S")
|
||||||
|
return datetime.strptime(dt_str, "%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
|
def format_attendee(name: str, email: str) -> str:
|
||||||
|
"""Format an attendee as 'Name <email>' or just the email."""
|
||||||
|
if name and email and not email.startswith("/O="):
|
||||||
|
return f"{name} <{email}>"
|
||||||
|
return name or email or ""
|
||||||
+53
-14
@@ -12,9 +12,10 @@ Alle Server lesen pro User aus `config.json`.
|
|||||||
|
|
||||||
## Backends pro Dienst
|
## Backends pro Dienst
|
||||||
|
|
||||||
- **Calendar/Contacts (Radicale):** User `mcptest` (htpasswd `/opt/radicale/config/htpasswd`,
|
- **Calendar/Contacts (Baikal auf 1blu):** User `mcptest` (Baikal-auth via digesta1).
|
||||||
bcrypt). Collections `/mcptest/calendar-test/` (VEVENT+VTODO) und `/mcptest/contacts-test/`
|
Collections im calendar-home `/dav.php/calendars/mcptest/`: `calendar-test` (VEVENT+VTODO)
|
||||||
(VADDRESSBOOK, Test-Kontakt "Max Mustermann"). `calendar_paths/addressbook_paths[mcptest]=["/mcptest/"]`.
|
und `calendar-test-second` (VEVENT). Addressbook `/dav.php/addressbooks/mcptest/contacts-test`
|
||||||
|
(VADDRESSBOOK). `calendar_paths/addressbook_paths[mcptest]=["/dav.php/calendars|addressbooks/mcptest/"]`.
|
||||||
- **Files (oCIS):** kompletter User `mcptest` (angelegt via Graph-API `POST /graph/v1.0/users`
|
- **Files (oCIS):** kompletter User `mcptest` (angelegt via Graph-API `POST /graph/v1.0/users`
|
||||||
als admin). `ocis_users[mcptest]`. Tests legen `/.mcp-tests` selbst an + raeumen auf.
|
als admin). `ocis_users[mcptest]`. Tests legen `/.mcp-tests` selbst an + raeumen auf.
|
||||||
- **Notes (Joplin):** lokales joplin-cli-Profil `/mnt/ssd/joplin-mcp/profiles/mcptest`
|
- **Notes (Joplin):** lokales joplin-cli-Profil `/mnt/ssd/joplin-mcp/profiles/mcptest`
|
||||||
@@ -26,8 +27,9 @@ Alle Server lesen pro User aus `config.json`.
|
|||||||
|
|
||||||
## Credentials
|
## Credentials
|
||||||
|
|
||||||
- Klartext-Backup: `/root/.mcptest-creds` (chmod 600).
|
- Klartext-Backup: `/root/.mcptest-creds` (chmod 600). Baikal-mcptest-Passwort zusaetzlich
|
||||||
- Aktiv genutzt: `config.json` (gitignored) — radicale/ocis Passwoerter, joplin Token.
|
unter `~/1bluapps/.secrets-mcptest/` (mcptest-baikal.password + .digesta1, chmod 600).
|
||||||
|
- Aktiv genutzt: `config.json` (gitignored) — baikal/ocis Passwoerter, joplin Token. Radicale-Keys sind entfernt.
|
||||||
- oCIS-Admin (fuer User-Anlage): `/mnt/ssd/ocis/auth.txt`.
|
- oCIS-Admin (fuer User-Anlage): `/mnt/ssd/ocis/auth.txt`.
|
||||||
|
|
||||||
## Tests laufen lassen
|
## Tests laufen lassen
|
||||||
@@ -38,23 +40,47 @@ Alle Server lesen pro User aus `config.json`.
|
|||||||
sudo /opt/mcp-servers/tests/run_tests.sh
|
sudo /opt/mcp-servers/tests/run_tests.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Testablauf und Selbstreinigung (Kalender/Kontakte)
|
||||||
|
|
||||||
|
- **Smoke (taeglich, read-only):** prueft, dass BEIDE Test-Kalender (calendar-test +
|
||||||
|
calendar-test-second) in `list_calendars` sichtbar sind. Kein Schreiben.
|
||||||
|
- **Full CRUD (`test_all.py`, on-demand):** erzeugt Events/Tasks/Kontakte via MCP
|
||||||
|
(`create_event` mit vollen Feldern inkl. Apple-Reise, `create_task`, `create_contact`),
|
||||||
|
aendert sie via `update_event`/`update_task`/`update_contact` (alle Felder, beide Kalender)
|
||||||
|
und **loescht am Ende alles wieder via `delete_event`/`delete_task`/`delete_contact`**
|
||||||
|
(try/finally je Testmethode). Nach dem Lauf ist der mcptest-Account wieder LEER
|
||||||
|
(Collections vorhanden, keine Objekte). Nur MCP-Methoden, kein direkter DAV-Zugriff.
|
||||||
|
|
||||||
|
## Neue MCP-Tools (Calendar/Contacts)
|
||||||
|
|
||||||
|
- `update_event(uid, ...)` — Feld-Overwrite wie `create_event`, auf bestehender UID.
|
||||||
|
- `update_task(uid, ...)` — wie `create_task` auf bestehender UID.
|
||||||
|
- `update_contact(uid, ...)` — wie `create_contact` auf bestehender UID.
|
||||||
|
- `delete_contact(uid)` — loescht Kontakt per UID.
|
||||||
|
- `create_event`/`update_event` unterstuetzen zusaetzlich `travel_mode`
|
||||||
|
(walking/driving/transit/biking) und `travel_advisory` (true = Apple berechnet die
|
||||||
|
Reise-Erinnerung dynamisch aus der Route via `X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC`).
|
||||||
|
- Bugfix: `_parse`/`_get_contacts` dekodieren jetzt XML-Entities per `html.unescape`
|
||||||
|
(zuvor brachen `"`-Werte wie `X-TITLE` das vobject-Roundtrip-Parsing).
|
||||||
|
|
||||||
## Als Dev-Sandbox nutzen
|
## Als Dev-Sandbox nutzen
|
||||||
|
|
||||||
- Direkt gegen die Backends: Radicale `http://127.0.0.1:5232/mcptest/` (User mcptest),
|
- Direkt gegen die Backends: Baikal `https://baikal.slohmaier.de/dav.php/calendars|addressbooks/mcptest/`
|
||||||
Joplin Data API `http://127.0.0.1:41186` (Token aus config.json), Maildir s.o.
|
(User mcptest), Joplin Data API `http://127.0.0.1:41186` (Token aus config.json), Maildir s.o.
|
||||||
- Ueber die MCP-Server: mit dem `test`-OAuth-Client verbinden -> trifft automatisch mcptest.
|
- Ueber die MCP-Server: mit dem `test`-OAuth-Client verbinden -> trifft automatisch mcptest.
|
||||||
- Testdaten zuruecksetzen: Collections/Notebooks neu seeden (siehe Provisioning unten).
|
- Testdaten zuruecksetzen: Collections/Notebooks neu seeden (siehe Provisioning unten).
|
||||||
|
|
||||||
## Provisioning (Recreate)
|
## Provisioning (Recreate)
|
||||||
|
|
||||||
1. Radicale: `htpasswd -bB /opt/radicale/config/htpasswd mcptest <pw>`; dann MKCALENDAR
|
1. Baikal (MySQL auf 1blu, `~/1bluapps/mysql-baikal`): principal `principals/mcptest`,
|
||||||
`/mcptest/calendar-test/` + extended-MKCOL `/mcptest/contacts-test/`.
|
user mit `digesta1`=md5-hex("mcptest:BaikalDAV:<pw>"), zwei Kalender (`calendar-test` VEVENT+VTODO,
|
||||||
|
`calendar-test-second` VEVENT) + `calendarinstances` (access=1) + `addressbooks` `contacts-test`.
|
||||||
2. oCIS: `POST /graph/v1.0/users` als admin (onPremisesSamAccountName=mcptest, passwordProfile).
|
2. oCIS: `POST /graph/v1.0/users` als admin (onPremisesSamAccountName=mcptest, passwordProfile).
|
||||||
3. Joplin: Profil anlegen (`joplin --profile DIR config api.token ...; sync.target 0`),
|
3. Joplin: Profil anlegen (`joplin --profile DIR config api.token ...; sync.target 0`),
|
||||||
`api.port=41186` in settings.json, `joplin-cli-mcptest.service` (Kopie von -stefan),
|
`api.port=41186` in settings.json, `joplin-cli-mcptest.service` (Kopie von -stefan),
|
||||||
Notebooks/Notizen via Data API seeden.
|
Notebooks/Notizen via Data API seeden.
|
||||||
4. Mail: `tests/testdata/maildir/` (im Repo) — Maildir-Konten mit cur/-Nachrichten.
|
4. Mail: `tests/testdata/maildir/` (im Repo) — Maildir-Konten mit cur/-Nachrichten.
|
||||||
5. `config.json`: mcptest in radicale_users, ocis_users, joplin_data_api, mail_roots,
|
5. `config.json`: mcptest in baikal_users, ocis_users, joplin_data_api, mail_roots,
|
||||||
calendar_paths, addressbook_paths.
|
calendar_paths, addressbook_paths.
|
||||||
6. `common.py`: `USER_ALIASES = {"test": "mcptest"}`.
|
6. `common.py`: `USER_ALIASES = {"test": "mcptest"}`.
|
||||||
|
|
||||||
@@ -111,8 +137,21 @@ Runtime-Deps: `pymupdf`, `pytesseract` + System `tesseract-ocr`/`-deu` (s. `requ
|
|||||||
Drei Schichten, NUR Smoke laeuft naechtlich:
|
Drei Schichten, NUR Smoke laeuft naechtlich:
|
||||||
|
|
||||||
- **Smoke** (`test_smoke.py`, Marker `smoke`): NIGHTLY via `mcp-tests.timer` (05:00) ->
|
- **Smoke** (`test_smoke.py`, Marker `smoke`): NIGHTLY via `mcp-tests.timer` (05:00) ->
|
||||||
`run_tests.sh` -> `pytest test_smoke.py`. Pro Connector: Server up + OAuth + tools/list +
|
`run_tests.sh` -> `pytest test_smoke.py test_public_smoke.py test_search_smoke.py`. Pro Connector: Server up +
|
||||||
EIN read-only Call. Schnell (~0.5s), schreibt keine Testdaten. Faengt Totalausfaelle ab.
|
OAuth + tools/list + EIN read-only Call. Schnell (~0.5s), schreibt keine Testdaten. Faengt
|
||||||
|
Totalausfaelle ab.
|
||||||
|
- **Public-Smoke** (`test_public_smoke.py`, Marker `smoke`): NIGHTLY im selben Lauf. Prueft die
|
||||||
|
oeffentliche Route (DNS, nginx-vhost, TLS/Cert-SAN, Bearer) fuer alle 9 Server ueber
|
||||||
|
`https://<name>.mcp.slohmaier.de/mcp`: ohne Token -> 401, mit Token -> initialize (serverInfo)
|
||||||
|
+ tools/list. Nutzt das nicht-ablaufende Service-Token mit Label `smoketest` (User mcptest)
|
||||||
|
aus `service_tokens.json`; keine `/token`-Aufrufe, damit das nginx-Rate-Limit `mcp_auth`
|
||||||
|
(10/min) unberuehrt bleibt. Read-only, kein Datenzugriff.
|
||||||
|
- **SearXNG-Smoke** (`test_search_smoke.py`, Marker `smoke`): NIGHTLY im selben Lauf.
|
||||||
|
Prueft die interne SearXNG-Instanz ueber die lokale Host-Route `127.0.0.1:8888`
|
||||||
|
(`/search?q=...&format=json`, kein Token noetig, Token-Gate nur in nginx). Assert:
|
||||||
|
HTTP 200 + `results` ist eine Liste. Bewusst kein "nicht leer", da geratelimitete
|
||||||
|
Engines ein bekannter Degraded-Zustand sind. Ersetzt den frueheren searxng-Eintrag
|
||||||
|
im Dashboard-service-check (2026-09-17).
|
||||||
- **Edge** (`test_edge.py`, Marker `edge`): ON-DEMAND. Boese/ungewoehnliche Eingaben pro
|
- **Edge** (`test_edge.py`, Marker `edge`): ON-DEMAND. Boese/ungewoehnliche Eingaben pro
|
||||||
Connector: Unicode/Emoji-Roundtrips, Sonderzeichen, riesige Limits/Bodies, kaputte
|
Connector: Unicode/Emoji-Roundtrips, Sonderzeichen, riesige Limits/Bodies, kaputte
|
||||||
Datumsangaben, **Path-Traversal-Block** (Files). Muss graceful sein, nichts leaken/crashen.
|
Datumsangaben, **Path-Traversal-Block** (Files). Muss graceful sein, nichts leaken/crashen.
|
||||||
@@ -155,13 +194,13 @@ Frage: verkraften die Connector "viel durchwuehlen" wie der Mail-Vollscan?
|
|||||||
den single-threaded Server blockiert. **Fix:** `SEARCH_DEADLINE_S=20` + `SEARCH_MAX_DIRS=400`
|
den single-threaded Server blockiert. **Fix:** `SEARCH_DEADLINE_S=20` + `SEARCH_MAX_DIRS=400`
|
||||||
+ Truncation-Hinweis ("Begriff praezisieren / 'path' enger"). Worst-Case jetzt ~20s gekappt.
|
+ Truncation-Hinweis ("Begriff praezisieren / 'path' enger"). Worst-Case jetzt ~20s gekappt.
|
||||||
Langfristig besser: oCIS server-seitige Suche (Graph/REPORT) statt Client-Rekursion.
|
Langfristig besser: oCIS server-seitige Suche (Graph/REPORT) statt Client-Rekursion.
|
||||||
- **Calendar (Radicale):** `get_events` ist server-seitig zeitgefiltert (gut). ABER bei
|
- **Calendar:** `get_events` ist server-seitig zeitgefiltert (gut). ABER bei
|
||||||
~6000 Test-Events gemessen: `search_events` 6-8s (vobject parst ALLE Events im ~15-Mon-
|
~6000 Test-Events gemessen: `search_events` 6-8s (vobject parst ALLE Events im ~15-Mon-
|
||||||
Fenster client-seitig), `get_events` lieferte **10939 Zeilen** (KEIN Result-Limit -> Token-
|
Fenster client-seitig), `get_events` lieferte **10939 Zeilen** (KEIN Result-Limit -> Token-
|
||||||
Explosion). Real schon 5s bei 29 Kalendern. **Fix:** `_parse` mit `PARSE_DEADLINE_S=12` +
|
Explosion). Real schon 5s bei 29 Kalendern. **Fix:** `_parse` mit `PARSE_DEADLINE_S=12` +
|
||||||
`get_events`/`get_tasks` Output-Cap `MAX_RESULTS=300` + Hinweise; `search_events` Top-30 +
|
`get_events`/`get_tasks` Output-Cap `MAX_RESULTS=300` + Hinweise; `search_events` Top-30 +
|
||||||
Deadline. Danach get_events 1501 statt 10939 Zeilen.
|
Deadline. Danach get_events 1501 statt 10939 Zeilen.
|
||||||
- **Contacts (Radicale):** `search_contacts` parst ALLE vCards client-seitig (real 0.2s, wenige
|
- **Contacts:** `search_contacts` parst ALLE vCards client-seitig (real 0.2s, wenige
|
||||||
Kontakte; skaliert linear). **Fix:** `PARSE_DEADLINE_S=12` in `_get_contacts` + Hinweis.
|
Kontakte; skaliert linear). **Fix:** `PARSE_DEADLINE_S=12` in `_get_contacts` + Hinweis.
|
||||||
- Rest-Kosten = CalDAV/CardDAV-REPORT-Transfer selbst (kein Server-Result-Limit im Protokoll);
|
- Rest-Kosten = CalDAV/CardDAV-REPORT-Transfer selbst (kein Server-Result-Limit im Protokoll);
|
||||||
in der Praxis durch Datumsbereich/Begriff eingrenzbar. Langfristig: server-seitige Suche.
|
in der Praxis durch Datumsbereich/Begriff eingrenzbar. Langfristig: server-seitige Suche.
|
||||||
+5
-3
@@ -1,7 +1,9 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# MCP Smoke-Tests — laeuft taeglich via systemd timer (mcp-tests.timer 05:00).
|
# MCP Smoke-Tests — laeuft taeglich via systemd timer (mcp-tests.timer 05:00).
|
||||||
# NUR Smoke (Server up + Auth + 1 Read/Connector). Stress/Edge/Funktional laufen
|
# NUR Smoke (Server up + Auth + 1 Read/Connector) plus SearXNG-Smoke
|
||||||
# NICHT naechtlich -> on-demand via run_full_tests.sh.
|
# (test_search_smoke.py, lokale Route 127.0.0.1:8888) plus oeffentlicher Smoke
|
||||||
|
# (test_public_smoke.py, Route/TLS/Bearer ueber https://<name>.mcp.slohmaier.de).
|
||||||
|
# Stress/Edge/Funktional laufen NICHT naechtlich -> on-demand via run_full_tests.sh.
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
|
|
||||||
LOG="/var/log/mcp-tests.log"
|
LOG="/var/log/mcp-tests.log"
|
||||||
@@ -10,7 +12,7 @@ VENV="/opt/mcp-servers/venv/bin"
|
|||||||
|
|
||||||
echo "[$(date)] MCP Smoke-Tests gestartet" | tee -a "$LOG"
|
echo "[$(date)] MCP Smoke-Tests gestartet" | tee -a "$LOG"
|
||||||
|
|
||||||
OUTPUT=$(cd /opt/mcp-servers/tests && $VENV/python -m pytest test_smoke.py -v --tb=short 2>&1)
|
OUTPUT=$(cd /opt/mcp-servers/tests && $VENV/python -m pytest test_smoke.py test_public_smoke.py test_search_smoke.py -v --tb=short 2>&1)
|
||||||
EXIT=$?
|
EXIT=$?
|
||||||
|
|
||||||
echo "$OUTPUT" | tee -a "$LOG"
|
echo "$OUTPUT" | tee -a "$LOG"
|
||||||
|
|||||||
+219
-97
@@ -13,6 +13,7 @@ Run: /opt/mcp-servers/venv/bin/python -m pytest /opt/mcp-servers/tests/test_all.
|
|||||||
import json
|
import json
|
||||||
import hashlib
|
import hashlib
|
||||||
import base64
|
import base64
|
||||||
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import time
|
import time
|
||||||
|
|
||||||
@@ -59,11 +60,11 @@ def get_token_pkce(port):
|
|||||||
return r2.json()["access_token"]
|
return r2.json()["access_token"]
|
||||||
|
|
||||||
|
|
||||||
def mcp_call(port, token, method, params=None):
|
def mcp_call(port, token, method, params=None, timeout=60):
|
||||||
r = httpx.post(f"http://127.0.0.1:{port}/mcp",
|
r = httpx.post(f"http://127.0.0.1:{port}/mcp",
|
||||||
json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}},
|
json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}},
|
||||||
headers={"Authorization": f"Bearer {token}", "Accept": "application/json, text/event-stream"},
|
headers={"Authorization": f"Bearer {token}", "Accept": "application/json, text/event-stream"},
|
||||||
timeout=60)
|
timeout=timeout)
|
||||||
assert r.status_code == 200, f"MCP {r.status_code}: {r.text[:200]}"
|
assert r.status_code == 200, f"MCP {r.status_code}: {r.text[:200]}"
|
||||||
for line in r.text.split("\n"):
|
for line in r.text.split("\n"):
|
||||||
if line.startswith("data: "):
|
if line.startswith("data: "):
|
||||||
@@ -71,8 +72,8 @@ def mcp_call(port, token, method, params=None):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def tool_call(port, token, tool_name, arguments=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 {}})
|
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}"
|
assert result and "error" not in result, f"Error: {result}"
|
||||||
content = result["result"]["content"]
|
content = result["result"]["content"]
|
||||||
assert len(content) > 0
|
assert len(content) > 0
|
||||||
@@ -229,125 +230,203 @@ class TestMail:
|
|||||||
|
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# Calendar Tests (CRUD on calendar-test)
|
# 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:
|
class TestCalendar:
|
||||||
PORT = SERVERS["calendar"]
|
PORT = SERVERS["calendar"]
|
||||||
TEST_CAL = "calendar-test"
|
CAL1 = "calendar-test"
|
||||||
|
CAL2 = "calendar-test-second"
|
||||||
|
|
||||||
def test_list_calendars(self):
|
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")
|
text = tool_call(self.PORT, get_token(self.PORT), "list_calendars")
|
||||||
assert "calendar-test" in text or "MCP Test" in text
|
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(self):
|
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")
|
text = tool_call(self.PORT, get_token(self.PORT), "list_task_lists")
|
||||||
assert len(text) > 0
|
assert self.CAL1 in text or self.CAL2 in text, f"Keine Task-Liste sichtbar: {text[:200]}"
|
||||||
|
|
||||||
def test_create_and_find_event(self):
|
def test_create_update_delete_event_full_fields(self):
|
||||||
token = get_token(self.PORT)
|
token = get_token(self.PORT)
|
||||||
tag = f"mcptest-{int(time.time())}"
|
tag = f"McpFeldtest-{int(time.time())}"
|
||||||
# Create
|
created = []
|
||||||
result = tool_call(self.PORT, token, "create_event", {
|
try:
|
||||||
"calendar": self.TEST_CAL,
|
r = tool_call(self.PORT, token, "create_event", {
|
||||||
"title": f"Test Event {tag}",
|
"calendar": self.CAL1, "title": tag,
|
||||||
"start": "2026-12-25T10:00",
|
"start": "2026-12-25T10:00", "end": "2026-12-25T11:00",
|
||||||
"end": "2026-12-25T11:00",
|
"location": "Marienplatz 1, Muenchen", "description": "Export Test Beschreibung",
|
||||||
"location": "Testort",
|
"travel_minutes": 30, "travel_mode": "driving",
|
||||||
"description": "Automatischer Test",
|
"travel_advisory": True, "reminder_minutes": 15,
|
||||||
})
|
})
|
||||||
assert "erstellt" in result.lower() or "created" in result.lower(), f"Create failed: {result}"
|
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))
|
||||||
|
|
||||||
# Search
|
tag2 = f"{tag}-GEANDERT"
|
||||||
found = tool_call(self.PORT, token, "search_events", {"query": tag})
|
r = tool_call(self.PORT, token, "update_event", {
|
||||||
assert tag in found, f"Event not found after create: {found[:200]}"
|
"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_create_and_find_task(self):
|
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)
|
token = get_token(self.PORT)
|
||||||
tag = f"mcptask-{int(time.time())}"
|
tag = f"McpTz-{int(time.time())}"
|
||||||
result = tool_call(self.PORT, token, "create_task", {
|
created = []
|
||||||
"task_list": self.TEST_CAL,
|
try:
|
||||||
"title": f"Test Task {tag}",
|
r = tool_call(self.PORT, token, "create_event", {
|
||||||
"due": "2026-12-31",
|
"calendar": self.CAL1, "title": tag,
|
||||||
"priority": 5,
|
"start": "2026-12-25T17:30", "end": "2026-12-25T19:15",
|
||||||
})
|
})
|
||||||
assert "erstellt" in result.lower() or "created" in result.lower(), f"Create failed: {result}"
|
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
|
||||||
|
|
||||||
tasks = tool_call(self.PORT, token, "get_tasks", {"task_list": self.TEST_CAL, "include_completed": True})
|
def test_create_event_second_calendar(self):
|
||||||
assert tag in tasks, f"Task not found: {tasks[:200]}"
|
"""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_get_events_date_range(self):
|
def test_create_update_delete_task(self):
|
||||||
text = tool_call(self.PORT, get_token(self.PORT), "get_events", {
|
"""Aufgabe in calendar-test (VTODO) anlegen, aendern, loeschen."""
|
||||||
"calendar": "calendar-test", "date_from": "2026-06-01", "date_to": "2026-06-30",
|
token = get_token(self.PORT)
|
||||||
})
|
tag = f"McpAufgabe-{int(time.time())}"
|
||||||
assert "Wann:" in text or "Keine Termine" in text
|
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
|
||||||
|
|
||||||
# ============================================================
|
|
||||||
# Contacts Tests (CRUD on contacts-test)
|
|
||||||
# ============================================================
|
|
||||||
|
|
||||||
class TestContacts:
|
class TestContacts:
|
||||||
PORT = SERVERS["contacts"]
|
PORT = SERVERS["contacts"]
|
||||||
|
|
||||||
def test_search_real_contacts(self):
|
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})
|
text = tool_call(self.PORT, get_token(self.PORT), "search_contacts", {"query": "Mustermann", "limit": 3})
|
||||||
assert "Mustermann" in text
|
assert isinstance(text, str), f"search_contacts Kaputt: {text}"
|
||||||
|
|
||||||
def test_search_empty(self):
|
def test_create_update_delete_contact(self):
|
||||||
text = tool_call(self.PORT, get_token(self.PORT), "search_contacts", {"query": "xyzzy_nobody_99"})
|
|
||||||
assert "Keine Kontakte" in text
|
|
||||||
|
|
||||||
def test_create_search_contact(self):
|
|
||||||
token = get_token(self.PORT)
|
token = get_token(self.PORT)
|
||||||
tag = f"McpTest-{int(time.time())}"
|
tag = f"McpKontakt-{int(time.time())}"
|
||||||
result = tool_call(self.PORT, token, "create_contact", {
|
created = []
|
||||||
"name": f"{tag} Mustermann",
|
try:
|
||||||
"email": f"{tag.lower()}@example.com",
|
r = tool_call(self.PORT, token, "create_contact", {
|
||||||
"phone": "+49 170 0000000",
|
"name": f"{tag} Mustermann", "email": "max@example.com",
|
||||||
"organization": "MCP Tests GmbH",
|
"phone": "+49 170 0000000", "organization": "MCP Tests GmbH", "note": "Automatisch erstellt",
|
||||||
"note": "Automatisch erstellt",
|
})
|
||||||
})
|
assert "erstellt" in r.lower() or "created" in r.lower(), f"create_contact failed: {r}"
|
||||||
assert "erstellt" in result.lower() or "created" in result.lower(), f"Create failed: {result}"
|
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)
|
||||||
|
|
||||||
found = tool_call(self.PORT, token, "search_contacts", {"query": tag})
|
tag2 = f"{tag}-GEANDERT"
|
||||||
assert tag in found, f"Contact not found: {found[:200]}"
|
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
|
||||||
|
|
||||||
def test_get_contact_details(self):
|
|
||||||
token = get_token(self.PORT)
|
|
||||||
search = tool_call(self.PORT, token, "search_contacts", {"query": "Mustermann", "limit": 1})
|
|
||||||
if "Keine" in search:
|
|
||||||
pytest.skip("No contacts")
|
|
||||||
uid = [l for l in search.split("\n") if "UID:" in l][0].split("UID: ")[1].strip()
|
|
||||||
# get_contact returns list content, first element is text
|
|
||||||
result = mcp_call(self.PORT, token, "tools/call", {"name": "get_contact", "arguments": {"uid": uid}})
|
|
||||||
text = result["result"]["content"][0]["text"]
|
|
||||||
assert "Mustermann" in text
|
|
||||||
assert "UID:" in text
|
|
||||||
|
|
||||||
def test_set_and_read_photo(self):
|
|
||||||
# Foto setzen + zuruecklesen (get_contact liefert dann ImageContent)
|
|
||||||
token = get_token(self.PORT)
|
|
||||||
tag = f"PhotoTest{int(time.time())}"
|
|
||||||
tool_call(self.PORT, token, "create_contact", {"name": f"{tag} Bildmann", "email": f"{tag.lower()}@example.com"})
|
|
||||||
search = tool_call(self.PORT, token, "search_contacts", {"query": tag, "limit": 1})
|
|
||||||
uid = [l for l in search.split("\n") if "UID:" in l][0].split("UID:")[1].strip()
|
|
||||||
# 1x1 PNG
|
|
||||||
png_b64 = ("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwC"
|
|
||||||
"AAAAC0lEQVR42mNk+M8AAAMCAYAAAS+ZkAAAAABJRU5ErkJggg==")
|
|
||||||
res = tool_call(self.PORT, token, "set_contact_photo",
|
|
||||||
{"uid": uid, "image_base64": png_b64, "image_type": "png"})
|
|
||||||
assert "esetzt" in res.lower() or "set" in res.lower()
|
|
||||||
content = mcp_call(self.PORT, token, "tools/call",
|
|
||||||
{"name": "get_contact", "arguments": {"uid": uid}})["result"]["content"]
|
|
||||||
imgs = [c for c in content if c.get("type") == "image"]
|
|
||||||
assert imgs, f"Kein Bild in get_contact: {[c.get('type') for c in content]}"
|
|
||||||
assert imgs[0].get("mimeType", "").startswith("image/")
|
|
||||||
|
|
||||||
|
|
||||||
# ============================================================
|
|
||||||
# Files Tests (CRUD on /mcp-tests/)
|
|
||||||
# ============================================================
|
|
||||||
|
|
||||||
class TestFiles:
|
class TestFiles:
|
||||||
PORT = SERVERS["files"]
|
PORT = SERVERS["files"]
|
||||||
@@ -497,6 +576,49 @@ class TestNotes:
|
|||||||
result = tool_call(self.PORT, token, "delete_note", {"note_id": note_id, "permanent": True})
|
result = tool_call(self.PORT, token, "delete_note", {"note_id": note_id, "permanent": True})
|
||||||
assert "ENDGUELTIG" in result, f"Delete failed: {result}"
|
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)
|
# File Type Tests (read_file auf vorbereiteten /testdata-Dateien)
|
||||||
|
|||||||
@@ -154,6 +154,21 @@ class TestFilesEdge:
|
|||||||
assert "404" in text or "gefunden" in text.lower() or "not found" in text.lower()
|
assert "404" in text or "gefunden" in text.lower() or "not found" in text.lower()
|
||||||
_alive(self.PORT)
|
_alive(self.PORT)
|
||||||
|
|
||||||
|
def test_url_special_chars_roundtrip(self):
|
||||||
|
# '#', '%' und '?' im Dateinamen duerfen die URL nicht zerlegen
|
||||||
|
# (Fix 2026-09-11: _enc_path() in files/server.py).
|
||||||
|
token = get_token(self.PORT)
|
||||||
|
tag = str(int(time.time()))
|
||||||
|
for fname in [f"edge{tag}#hash.txt", f"edge{tag}100%.txt", f"edge{tag}was?so.txt"]:
|
||||||
|
path = f"{self.DIR}/{fname}"
|
||||||
|
w = tool_call(self.PORT, token, "write_file", {"path": path, "content": "special"})
|
||||||
|
assert "geschrieben" in w, f"write fehlgeschlagen: {w}"
|
||||||
|
r = tool_call(self.PORT, token, "read_file", {"path": path})
|
||||||
|
assert "special" in r, f"read fehlgeschlagen: {r}"
|
||||||
|
d = tool_call(self.PORT, token, "delete_file", {"path": path})
|
||||||
|
assert "Geloescht" in d, f"delete fehlgeschlagen: {d}"
|
||||||
|
_alive(self.PORT)
|
||||||
|
|
||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# Notes
|
# Notes
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression (2026-09-26): ungelesene Mails im Maildir `new/` muessen indexiert
|
||||||
|
werden. mbsync legt Gmail-Mails ohne \\Seen in <folder>/new/ ab; der Index scannte
|
||||||
|
frueher nur cur/ und jarvis sah diese Mails nicht.
|
||||||
|
|
||||||
|
Lauf: /opt/mcp-servers/venv/bin/python -m pytest test_mail_newdir.py -q
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, BASE)
|
||||||
|
sys.path.insert(0, os.path.join(BASE, "mail"))
|
||||||
|
|
||||||
|
from mail import mailindex # noqa: E402
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.edge
|
||||||
|
|
||||||
|
MSG = (
|
||||||
|
"From: sender@example.com\r\n"
|
||||||
|
"To: rcpt@example.com\r\n"
|
||||||
|
"Subject: Newdir Regression {tag}\r\n"
|
||||||
|
"Date: Sat, 26 Sep 2026 13:58:32 +0200\r\n"
|
||||||
|
"Content-Type: text/plain; charset=utf-8\r\n"
|
||||||
|
"\r\n"
|
||||||
|
"unique-body-token-{tag}\r\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _write_mail(path):
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(MSG.format(tag=os.path.basename(path).split(":")[0]))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def newdir_index(tmp_path):
|
||||||
|
user = "newdir_test"
|
||||||
|
root = tmp_path / "maildir"
|
||||||
|
for sub, tag in (("cur", "curtoken"), ("new", "newtoken")):
|
||||||
|
d = root / "acct" / "INBOX" / sub
|
||||||
|
d.mkdir(parents=True)
|
||||||
|
_write_mail(str(d / f"1700000000.{tag}.polo,S:2,S"))
|
||||||
|
mailindex.update_user(user, str(root), log=lambda *a: None)
|
||||||
|
with open(mailindex._ready_path(user), "w") as fh:
|
||||||
|
fh.write("test")
|
||||||
|
yield user
|
||||||
|
for p in (mailindex.index_db_path(user), mailindex._ready_path(user)):
|
||||||
|
try:
|
||||||
|
os.remove(p)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_dir_is_indexed(newdir_index):
|
||||||
|
hits = mailindex.search(newdir_index, "newtoken", limit=5)
|
||||||
|
assert hits is not None, "Index nicht nutzbar"
|
||||||
|
assert hits, "Mail aus new/ wurde nicht indexiert"
|
||||||
|
assert hits[0]["folder"] == "INBOX"
|
||||||
|
|
||||||
|
|
||||||
|
def test_cur_dir_still_indexed(newdir_index):
|
||||||
|
hits = mailindex.search(newdir_index, "curtoken", limit=5)
|
||||||
|
assert hits, "Mail aus cur/ wurde nicht indexiert"
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Oeffentlicher MCP-Smoke-Test — NIGHTLY.
|
||||||
|
|
||||||
|
Prueft die oeffentliche Route (DNS, nginx-vhost, TLS/Cert-SAN, Bearer-Auth)
|
||||||
|
fuer alle oeffentlichen MCP-Server: https://<name>.mcp.slohmaier.de/mcp.
|
||||||
|
|
||||||
|
Nutzt ein dediziertes, nicht-ablaufendes Service-Token (Label `smoketest`,
|
||||||
|
User mcptest) aus /opt/mcp-servers/service_tokens.json. Dadurch entstehen
|
||||||
|
keine /token-Aufrufe und das nginx-Rate-Limit `mcp_auth` (10/min) wird nicht
|
||||||
|
belastet. Read-only: initialize + tools/list, kein Datenzugriff.
|
||||||
|
|
||||||
|
Lauf: /opt/mcp-servers/venv/bin/python -m pytest test_public_smoke.py -q
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
PUBLIC_HOSTS = {
|
||||||
|
"notes": "notes.mcp.slohmaier.de",
|
||||||
|
"calendar": "calendar.mcp.slohmaier.de",
|
||||||
|
"mail": "mail.mcp.slohmaier.de",
|
||||||
|
"contacts": "contacts.mcp.slohmaier.de",
|
||||||
|
"files": "files.mcp.slohmaier.de",
|
||||||
|
"openwearables": "openwearables.mcp.slohmaier.de",
|
||||||
|
"owamail": "owamail.mcp.slohmaier.de",
|
||||||
|
}
|
||||||
|
|
||||||
|
SERVICE_TOKENS = "/opt/mcp-servers/service_tokens.json"
|
||||||
|
INIT = {
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 1,
|
||||||
|
"method": "initialize",
|
||||||
|
"params": {
|
||||||
|
"protocolVersion": "2025-06-18",
|
||||||
|
"capabilities": {},
|
||||||
|
"clientInfo": {"name": "public-smoke", "version": "1"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.smoke
|
||||||
|
|
||||||
|
|
||||||
|
def _token():
|
||||||
|
with open(SERVICE_TOKENS) as f:
|
||||||
|
data = json.load(f)
|
||||||
|
for tok, info in data.items():
|
||||||
|
if isinstance(info, dict) and info.get("label") == "smoketest":
|
||||||
|
return tok
|
||||||
|
pytest.skip("kein Service-Token mit Label 'smoketest' in service_tokens.json")
|
||||||
|
|
||||||
|
|
||||||
|
def _headers(token=None, session=None):
|
||||||
|
h = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "application/json, text/event-stream",
|
||||||
|
}
|
||||||
|
if token:
|
||||||
|
h["Authorization"] = f"Bearer {token}"
|
||||||
|
if session:
|
||||||
|
h["mcp-session-id"] = session
|
||||||
|
return h
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonrpc(resp):
|
||||||
|
for line in resp.text.split("\n"):
|
||||||
|
if line.startswith("data: "):
|
||||||
|
return json.loads(line[6:])
|
||||||
|
try:
|
||||||
|
return resp.json()
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("svc,host", list(PUBLIC_HOSTS.items()))
|
||||||
|
def test_public_requires_auth(svc, host):
|
||||||
|
"""Ohne Bearer muss die oeffentliche Route 401 liefern (Route/TLS erreichbar)."""
|
||||||
|
r = httpx.post(f"https://{host}/mcp", json=INIT, headers=_headers(), timeout=30)
|
||||||
|
assert r.status_code == 401, f"{svc}: erwartet 401 ohne Token, bekam {r.status_code}"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("svc,host", list(PUBLIC_HOSTS.items()))
|
||||||
|
def test_public_initialize_and_tools(svc, host):
|
||||||
|
"""initialize + tools/list ueber die oeffentliche URL mit Service-Token."""
|
||||||
|
token = _token()
|
||||||
|
r = httpx.post(f"https://{host}/mcp", json=INIT, headers=_headers(token), timeout=30)
|
||||||
|
assert r.status_code == 200, f"{svc}: initialize HTTP {r.status_code}: {r.text[:200]}"
|
||||||
|
res = _jsonrpc(r)
|
||||||
|
assert res and res.get("result", {}).get("serverInfo"), f"{svc}: kein serverInfo"
|
||||||
|
session = r.headers.get("mcp-session-id")
|
||||||
|
|
||||||
|
# initialized-Notification (Server, die sie verlangen); Fehler ignorieren.
|
||||||
|
if session:
|
||||||
|
httpx.post(
|
||||||
|
f"https://{host}/mcp",
|
||||||
|
json={"jsonrpc": "2.0", "method": "notifications/initialized"},
|
||||||
|
headers=_headers(token, session),
|
||||||
|
timeout=30,
|
||||||
|
)
|
||||||
|
|
||||||
|
r2 = httpx.post(
|
||||||
|
f"https://{host}/mcp",
|
||||||
|
json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
|
||||||
|
headers=_headers(token, session),
|
||||||
|
timeout=30,
|
||||||
|
)
|
||||||
|
assert r2.status_code == 200, f"{svc}: tools/list HTTP {r2.status_code}: {r2.text[:200]}"
|
||||||
|
res2 = _jsonrpc(r2)
|
||||||
|
assert res2 and res2.get("result", {}).get("tools"), f"{svc}: tools/list leer"
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""SearXNG Smoke-Test — NIGHTLY.
|
||||||
|
|
||||||
|
Minimal, schnell, read-only. Prueft die interne SearXNG-Instanz auf Erreichbarkeit
|
||||||
|
und JSON-Antwort. Genutzt wird die lokale Host-Route 127.0.0.1:8888 (kein Token
|
||||||
|
noetig, das Token-Gate sitzt nur in nginx/oeffentlich); damit bleibt der Test ohne
|
||||||
|
Secret. Faengt Totalausfaelle (Container down, API kaputt) ueber Nacht ab.
|
||||||
|
|
||||||
|
Bewusst KEIN "results nicht leer"-Assert: geratelimitete Upstream-Engines liefern
|
||||||
|
leere results (bekannter Degraded-Zustand, siehe /opt/searxng/README.md), das ist
|
||||||
|
kein Ausfall.
|
||||||
|
|
||||||
|
Lauf: /opt/mcp-servers/venv/bin/python -m pytest test_search_smoke.py -q
|
||||||
|
"""
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.smoke
|
||||||
|
|
||||||
|
BASE = "http://127.0.0.1:8888"
|
||||||
|
|
||||||
|
|
||||||
|
def test_searxng_json_alive():
|
||||||
|
"""SearXNG erreichbar und liefert eine JSON-Antwort mit results-Liste."""
|
||||||
|
r = httpx.get(f"{BASE}/search", params={"q": "polo smoke", "format": "json"}, timeout=30)
|
||||||
|
assert r.status_code == 200, f"SearXNG HTTP {r.status_code}"
|
||||||
|
data = r.json()
|
||||||
|
assert isinstance(data.get("results"), list), "SearXNG JSON ohne results-Liste"
|
||||||
+6
-1
@@ -32,8 +32,12 @@ def test_mail_read():
|
|||||||
|
|
||||||
|
|
||||||
def test_calendar_read():
|
def test_calendar_read():
|
||||||
|
"""Beide Test-Kalender des mcptest-Backends muessen sichtbar sein (read-only)."""
|
||||||
text = tool_call(SERVERS["calendar"], get_token(SERVERS["calendar"]), "list_calendars")
|
text = tool_call(SERVERS["calendar"], get_token(SERVERS["calendar"]), "list_calendars")
|
||||||
assert "calendar-test" in text or "MCP Test" in text
|
missing = [c for c in ("calendar-test", "calendar-test-second") if c not in text]
|
||||||
|
assert not missing, (
|
||||||
|
f"mcptest-Backend unvollstaendig: Kalender {missing} fehlen in list_calendars. "
|
||||||
|
f"Pruefe Baikal (baikal.slohmaier.de, User mcptest) und config.json.")
|
||||||
|
|
||||||
|
|
||||||
def test_contacts_read():
|
def test_contacts_read():
|
||||||
@@ -51,3 +55,4 @@ def test_files_read():
|
|||||||
def test_notes_read():
|
def test_notes_read():
|
||||||
text = tool_call(SERVERS["notes"], get_token(SERVERS["notes"]), "list_notebooks")
|
text = tool_call(SERVERS["notes"], get_token(SERVERS["notes"]), "list_notebooks")
|
||||||
assert "id:" in text
|
assert "id:" in text
|
||||||
|
|
||||||
Reference in new issue
Block a user