333 lines
14 KiB
Python
333 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only IMAP MCP server for a delegated grommunio mailbox."""
|
|
|
|
import base64
|
|
import email
|
|
import hashlib
|
|
import html
|
|
import imaplib
|
|
import json
|
|
import os
|
|
import re
|
|
import socket
|
|
import ssl
|
|
import stat
|
|
import sys
|
|
from email.header import decode_header, make_header
|
|
from email.policy import default
|
|
|
|
HOST = os.environ.get("MAIL_IMAP_HOST", "mail.your-domain.com")
|
|
PORT = int(os.environ.get("MAIL_IMAP_PORT", "993"))
|
|
TARGET = os.environ.get("MAIL_TARGET_MAILBOX", "[email protected]")
|
|
CREDENTIALS_FILE = os.environ.get("MAIL_CREDENTIALS_FILE", "/home/node/.openclaw/mcp/.mail-credentials")
|
|
CERT_SHA256 = re.sub(r"[^A-Fa-f0-9]", "", os.environ.get("MAIL_CERT_SHA256", "")).upper()
|
|
MAX_MESSAGE_BYTES = 131072
|
|
|
|
|
|
def read_credentials():
|
|
try:
|
|
info = os.stat(CREDENTIALS_FILE)
|
|
except OSError as exc:
|
|
raise RuntimeError("Mail-Credential-Datei ist nicht lesbar.") from exc
|
|
if stat.S_IMODE(info.st_mode) & 0o077:
|
|
raise RuntimeError(f"Mail-Credential-Datei ist nicht restriktiv (Modus {oct(stat.S_IMODE(info.st_mode))}).")
|
|
if info.st_uid != 1000:
|
|
raise RuntimeError(f"Mail-Credential-Datei gehoert uid {info.st_uid}, erwartet 1000.")
|
|
with open(CREDENTIALS_FILE, encoding="utf-8") as handle:
|
|
lines = handle.read().splitlines()
|
|
if len(lines) != 2 or not lines[0] or not lines[1]:
|
|
raise RuntimeError("Mail-Credential-Datei muss genau Benutzername und Kennwort enthalten.")
|
|
return lines[0], lines[1]
|
|
|
|
|
|
def tls_context():
|
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
context.check_hostname = False
|
|
context.verify_mode = ssl.CERT_NONE
|
|
return context
|
|
|
|
|
|
def verify_certificate():
|
|
if not CERT_SHA256:
|
|
raise RuntimeError("Kein SHA-256-Fingerprint fuer das IMAP-Zertifikat konfiguriert.")
|
|
context = tls_context()
|
|
with socket.create_connection((HOST, PORT), timeout=15) as raw:
|
|
with context.wrap_socket(raw, server_hostname=HOST) as tls:
|
|
actual = hashlib.sha256(tls.getpeercert(binary_form=True)).hexdigest().upper()
|
|
if actual != CERT_SHA256:
|
|
raise RuntimeError("IMAP-Zertifikat stimmt nicht mit dem konfigurierten Fingerprint ueberein.")
|
|
|
|
|
|
class Mailbox:
|
|
def __enter__(self):
|
|
verify_certificate()
|
|
username, password = read_credentials()
|
|
self.client = imaplib.IMAP4_SSL(HOST, PORT, ssl_context=tls_context(), timeout=20)
|
|
self.client.login(f"{username}!{TARGET}", password)
|
|
return self.client
|
|
|
|
def __exit__(self, *_args):
|
|
try:
|
|
self.client.logout()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def decode_text(value):
|
|
if not value:
|
|
return ""
|
|
try:
|
|
return str(make_header(decode_header(value)))
|
|
except Exception:
|
|
return str(value)
|
|
|
|
|
|
def decode_modified_utf7(value):
|
|
result = []
|
|
index = 0
|
|
for match in re.finditer(r"&([^-]*)-", value):
|
|
result.append(value[index:match.start()])
|
|
token = match.group(1)
|
|
if not token:
|
|
result.append("&")
|
|
else:
|
|
padded = token.replace(",", "/") + "=" * ((4 - len(token) % 4) % 4)
|
|
result.append(base64.b64decode(padded).decode("utf-16-be"))
|
|
index = match.end()
|
|
result.append(value[index:])
|
|
return "".join(result)
|
|
|
|
|
|
def encode_modified_utf7(value):
|
|
chunks = []
|
|
pending = []
|
|
|
|
def flush():
|
|
if pending:
|
|
raw = "".join(pending).encode("utf-16-be")
|
|
chunks.append("&" + base64.b64encode(raw).decode("ascii").rstrip("=").replace("/", ",") + "-")
|
|
pending.clear()
|
|
|
|
for character in value:
|
|
code = ord(character)
|
|
if 0x20 <= code <= 0x7E:
|
|
flush()
|
|
chunks.append("&-" if character == "&" else character)
|
|
else:
|
|
pending.append(character)
|
|
flush()
|
|
return "".join(chunks)
|
|
|
|
|
|
def quote_mailbox(folder):
|
|
folder = str(folder or "INBOX").strip()
|
|
if not folder or "\r" in folder or "\n" in folder:
|
|
raise RuntimeError("Ungueltiger Mailordner.")
|
|
return encode_modified_utf7(folder)
|
|
|
|
|
|
def select_readonly(client, folder):
|
|
status, data = client.select(quote_mailbox(folder), readonly=True)
|
|
if status != "OK":
|
|
raise RuntimeError(f"Mailordner nicht lesbar: {folder}")
|
|
return int(data[0] or 0)
|
|
|
|
|
|
def list_folders_raw(client):
|
|
status, rows = client.list()
|
|
if status != "OK":
|
|
raise RuntimeError("Mailordner konnten nicht gelesen werden.")
|
|
folders = []
|
|
for row in rows or []:
|
|
line = row.decode("utf-8", "replace")
|
|
match = re.search(r'("(?:[^"\\]|\\.)*"|\S+)$', line)
|
|
if not match:
|
|
continue
|
|
raw = match.group(1)
|
|
if raw.startswith('"'):
|
|
raw = raw[1:-1].replace('\\"', '"').replace('\\\\', '\\')
|
|
folders.append(decode_modified_utf7(raw))
|
|
return folders
|
|
|
|
|
|
def parse_header(payload):
|
|
message = email.message_from_bytes(payload, policy=default)
|
|
return {
|
|
"date": decode_text(message.get("Date")),
|
|
"from": decode_text(message.get("From")),
|
|
"to": decode_text(message.get("To")),
|
|
"cc": decode_text(message.get("Cc")),
|
|
"subject": decode_text(message.get("Subject")) or "(ohne Betreff)",
|
|
"message_id": decode_text(message.get("Message-ID")),
|
|
}
|
|
|
|
|
|
def message_rows(client, uids):
|
|
rows = []
|
|
fields = "BODY.PEEK[HEADER.FIELDS (DATE FROM TO CC SUBJECT MESSAGE-ID)] FLAGS RFC822.SIZE INTERNALDATE"
|
|
for uid in uids:
|
|
status, data = client.uid("FETCH", uid, f"({fields})")
|
|
if status != "OK" or not data or not isinstance(data[0], tuple):
|
|
continue
|
|
metadata, payload = data[0]
|
|
item = parse_header(payload)
|
|
item["uid"] = uid.decode("ascii", "replace") if isinstance(uid, bytes) else str(uid)
|
|
meta = metadata.decode("utf-8", "replace")
|
|
item["unread"] = "\\Seen" not in meta
|
|
size = re.search(r"RFC822\.SIZE (\d+)", meta)
|
|
item["size_bytes"] = int(size.group(1)) if size else None
|
|
rows.append(item)
|
|
return rows
|
|
|
|
|
|
def status_tool(_args):
|
|
with Mailbox() as client:
|
|
folders = list_folders_raw(client)
|
|
status, data = client.status("INBOX", "(MESSAGES UNSEEN UIDNEXT)")
|
|
summary = data[0].decode("utf-8", "replace") if status == "OK" and data else "unbekannt"
|
|
return f"## Grommunio Mail\n\n- Server: {HOST}:{PORT} (IMAPS, Zertifikat gepinnt)\n- Zielpostfach: {TARGET}\n- Zugriff: read-only via IMAP EXAMINE/BODY.PEEK\n- Ordner: {len(folders)}\n- INBOX: {summary}"
|
|
|
|
|
|
def folders_tool(_args):
|
|
with Mailbox() as client:
|
|
folders = list_folders_raw(client)
|
|
return "## Mailordner\n\n" + "\n".join(f"- {folder}" for folder in folders)
|
|
|
|
|
|
def list_messages_tool(args):
|
|
folder = str(args.get("folder", "INBOX"))
|
|
limit = max(1, min(int(args.get("limit", 20)), 100))
|
|
unread_only = bool(args.get("unread_only", False))
|
|
with Mailbox() as client:
|
|
total = select_readonly(client, folder)
|
|
status, data = client.uid("SEARCH", None, "UNSEEN" if unread_only else "ALL")
|
|
if status != "OK":
|
|
raise RuntimeError("Nachrichtenliste konnte nicht gelesen werden.")
|
|
uids = list(reversed((data[0] or b"").split()))[:limit]
|
|
rows = message_rows(client, uids)
|
|
return json.dumps({"mailbox": TARGET, "folder": folder, "total": total, "returned": len(rows), "messages": rows}, ensure_ascii=False, indent=2)
|
|
|
|
|
|
def search_messages_tool(args):
|
|
folder = str(args.get("folder", "INBOX"))
|
|
query = str(args.get("query", "")).strip()
|
|
limit = max(1, min(int(args.get("limit", 20)), 100))
|
|
if not query or len(query) > 200 or "\r" in query or "\n" in query:
|
|
raise RuntimeError("Suchtext fehlt oder ist ungueltig.")
|
|
if not query.isascii():
|
|
raise RuntimeError("Die IMAP-Suche unterstuetzt auf diesem Server nur ASCII-Suchtext.")
|
|
escaped = query.replace("\\", "\\\\").replace('"', '\\"')
|
|
with Mailbox() as client:
|
|
select_readonly(client, folder)
|
|
status, data = client.uid("SEARCH", None, f'TEXT "{escaped}"')
|
|
if status != "OK":
|
|
raise RuntimeError("Nachrichtensuche ist fehlgeschlagen.")
|
|
uids = list(reversed((data[0] or b"").split()))[:limit]
|
|
rows = message_rows(client, uids)
|
|
return json.dumps({"mailbox": TARGET, "folder": folder, "query": query, "returned": len(rows), "messages": rows}, ensure_ascii=False, indent=2)
|
|
|
|
|
|
def extract_body(message):
|
|
plain = []
|
|
rich = []
|
|
parts = message.walk() if message.is_multipart() else [message]
|
|
for part in parts:
|
|
if part.get_content_disposition() == "attachment":
|
|
continue
|
|
content_type = part.get_content_type()
|
|
if content_type not in ("text/plain", "text/html"):
|
|
continue
|
|
try:
|
|
content = part.get_content()
|
|
except Exception:
|
|
raw = part.get_payload(decode=True) or b""
|
|
content = raw.decode(part.get_content_charset() or "utf-8", "replace")
|
|
if content_type == "text/plain":
|
|
plain.append(str(content))
|
|
else:
|
|
rich.append(re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", str(content)))).strip())
|
|
return "\n\n".join(plain or rich).strip()
|
|
|
|
|
|
def read_message_tool(args):
|
|
folder = str(args.get("folder", "INBOX"))
|
|
uid = str(args.get("uid", "")).strip()
|
|
if not uid.isdigit():
|
|
raise RuntimeError("Eine numerische IMAP-UID ist erforderlich.")
|
|
with Mailbox() as client:
|
|
select_readonly(client, folder)
|
|
status, data = client.uid("FETCH", uid, f"(BODY.PEEK[]<0.{MAX_MESSAGE_BYTES}> FLAGS RFC822.SIZE)")
|
|
if status != "OK" or not data or not isinstance(data[0], tuple):
|
|
raise RuntimeError("Nachricht wurde nicht gefunden.")
|
|
metadata, payload = data[0]
|
|
message = email.message_from_bytes(payload, policy=default)
|
|
headers = parse_header(payload)
|
|
body = extract_body(message)
|
|
attachments = [decode_text(part.get_filename()) for part in message.walk() if part.get_content_disposition() == "attachment"]
|
|
result = {"mailbox": TARGET, "folder": folder, "uid": uid, **headers, "body": body[:60000], "attachments": attachments, "truncated": len(payload) >= MAX_MESSAGE_BYTES}
|
|
return json.dumps(result, ensure_ascii=False, indent=2)
|
|
|
|
|
|
TOOLS = [
|
|
{"name": "mail_status", "description": "Prueft den read-only IMAP-Zugriff auf Pascals delegiertes grommunio-Postfach.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
|
|
{"name": "mail_list_folders", "description": "Listet die Ordner in Pascals delegiertem Postfach. Lesend.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
|
|
{"name": "mail_list_messages", "description": "Listet die neuesten Nachrichten eines Mailordners ohne sie als gelesen zu markieren.", "inputSchema": {"type": "object", "properties": {"folder": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}, "unread_only": {"type": "boolean"}}, "additionalProperties": False}},
|
|
{"name": "mail_search_messages", "description": "Durchsucht Nachrichten eines Mailordners nach ASCII-Text, ohne den Postfachzustand zu veraendern.", "inputSchema": {"type": "object", "properties": {"folder": {"type": "string"}, "query": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}}, "required": ["query"], "additionalProperties": False}},
|
|
{"name": "mail_read_message", "description": "Liest eine Nachricht anhand von Ordner und IMAP-UID mit BODY.PEEK, ohne sie als gelesen zu markieren.", "inputSchema": {"type": "object", "properties": {"folder": {"type": "string"}, "uid": {"type": "string"}}, "required": ["uid"], "additionalProperties": False}},
|
|
]
|
|
|
|
DISPATCH = {
|
|
"mail_status": status_tool,
|
|
"mail_list_folders": folders_tool,
|
|
"mail_list_messages": list_messages_tool,
|
|
"mail_search_messages": search_messages_tool,
|
|
"mail_read_message": read_message_tool,
|
|
}
|
|
|
|
|
|
def send(message):
|
|
sys.stdout.write(json.dumps(message, ensure_ascii=True, separators=(",", ":")) + "\n")
|
|
sys.stdout.flush()
|
|
|
|
|
|
def handle(message):
|
|
request_id = message.get("id")
|
|
method = message.get("method")
|
|
params = message.get("params") or {}
|
|
if method == "notifications/initialized" or (request_id is None and method):
|
|
return
|
|
if method == "initialize":
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"protocolVersion": params.get("protocolVersion", "2024-11-05"), "capabilities": {"tools": {}}, "serverInfo": {"name": "grommunio-mail", "version": "1.0.0"}}})
|
|
elif method == "ping":
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {}})
|
|
elif method == "tools/list":
|
|
tools = []
|
|
for tool in TOOLS:
|
|
item = dict(tool)
|
|
item["annotations"] = {"title": tool["name"].replace("_", " "), "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True}
|
|
tools.append(item)
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"tools": tools}})
|
|
elif method == "tools/call":
|
|
name = params.get("name")
|
|
function = DISPATCH.get(name)
|
|
if not function:
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": f"Unbekanntes Mail-Werkzeug: {name}"}], "isError": True}})
|
|
return
|
|
try:
|
|
text = function(params.get("arguments") or {})
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": text}], "isError": False}})
|
|
except Exception as exc:
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": f"Mail-Fehler: {exc}"}], "isError": True}})
|
|
else:
|
|
send({"jsonrpc": "2.0", "id": request_id, "error": {"code": -32601, "message": "Method not found"}})
|
|
|
|
|
|
for line in sys.stdin:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
try:
|
|
handle(json.loads(line))
|
|
except json.JSONDecodeError:
|
|
send({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
|