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

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

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Exchange MCP Server - access OWA email, calendar, directory via MCP."""
+194
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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()
+1
View File
@@ -0,0 +1 @@
"""MCP tool modules for Exchange."""
+421
View File
@@ -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
View File
@@ -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
View File
@@ -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)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+430
View File
@@ -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
View File
@@ -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)
+133
View File
@@ -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 ""