#!/usr/bin/env python3 """STRATO DNS MCP for a single configured zone (CNAME and TXT records). Read tools are always available. Changes are two-step: ``strato_preview_change`` resolves the exact change against the current zone and issues a short-lived ticket; ``strato_apply_change`` writes it only with that ticket, ``confirm=true`` and ``STRATO_WRITE_ENABLED=true``, and only if the zone did not change meanwhile. """ from __future__ import annotations import json import os import secrets import socket import threading import time from typing import Any from mcp.server.fastmcp import FastMCP from mcp.server.fastmcp.exceptions import ToolError from strato_client import RECORD_TYPES, ChangePlan, StratoClient, StratoConfig, StratoError APPROVAL_TTL_SECONDS = 600 mcp = FastMCP( "strato-dns", instructions=( "Read and manage CNAME and TXT records of the configured STRATO DNS zone. " "Every change needs strato_preview_change first, then explicit user approval, " "then strato_apply_change with the ticket. Writes also require " "STRATO_WRITE_ENABLED=true." ), host=os.environ.get("MCP_HOST", "127.0.0.1"), port=int(os.environ.get("PORT", "8000")), stateless_http=True, ) _client_lock = threading.Lock() _client: StratoClient | None = None _client_config: StratoConfig | None = None _approvals: dict[str, tuple[float, str, ChangePlan]] = {} def _json(value: object) -> str: return json.dumps(value, ensure_ascii=False, separators=(",", ":")) def _get_client() -> tuple[StratoConfig, StratoClient]: """One client per process so the STRATO session is reused instead of a new login per call.""" global _client, _client_config config = StratoConfig.from_env() with _client_lock: if _client is None or _client_config != config: _client, _client_config = StratoClient(config), config return config, _client def _fail(exc: Exception) -> ToolError: return ToolError(str(exc) if isinstance(exc, StratoError) else f"{type(exc).__name__}: {exc}") def _record_view(record: Any) -> dict[str, str] | None: return record.as_dict() if record is not None else None def _change_args(action: str, record_type: str, prefix: str, value: str | None, new_prefix: str | None, old_value: str | None) -> dict[str, Any]: return { "action": action.strip().lower(), "record_type": record_type.strip().upper(), "prefix": prefix, "value": value, "new_prefix": new_prefix or None, "old_value": old_value or None, } def _plan(client: StratoClient, args: dict[str, Any]) -> ChangePlan: return client.plan( args["action"], args["record_type"], args["prefix"], args["value"], new_prefix=args["new_prefix"], old_value=args["old_value"], ) @mcp.tool() def strato_connection_status() -> str: """Log in and verify that the configured DNS zone can be read. Makes no change.""" try: config, client = _get_client() records = client.list_txt_and_cname_records() return _json({ "connected": True, "domain": config.domain, "record_count": len(records), "cname_count": sum(record.type == "CNAME" for record in records), "txt_count": sum(record.type == "TXT" for record in records), "write_enabled": config.write_enabled, }) except Exception as exc: raise _fail(exc) from None @mcp.tool() def strato_list_records(record_type: str = "", contains: str = "") -> str: """List CNAME and/or TXT records of the configured zone. Makes no change. record_type: CNAME, TXT or empty for both. contains: optional filter on prefix or value.""" try: config, client = _get_client() wanted = record_type.strip().upper() if wanted and wanted not in RECORD_TYPES: raise StratoError(f"record_type must be one of {', '.join(RECORD_TYPES)} or empty") needle = contains.strip().lower() records = [ r for r in client.list_txt_and_cname_records() if (not wanted or r.type == wanted) and (not needle or needle in r.prefix.lower() or needle in r.value.lower() or needle in r.as_dict().get("prefix_unicode", "").lower()) ] return _json({ "domain": config.domain, "count": len(records), "records": [record.as_dict() for record in records[:300]], "truncated": len(records) > 300, "write_enabled": config.write_enabled, }) except Exception as exc: raise _fail(exc) from None @mcp.tool() def strato_list_cnames() -> str: """List CNAME records of the configured zone. Makes no change.""" return strato_list_records("CNAME") @mcp.tool() def strato_preview_change( action: str, record_type: str, prefix: str, value: str | None = None, new_prefix: str | None = None, old_value: str | None = None, ) -> str: """Preview one DNS change and issue a 10-minute approval ticket. Makes no change. action: create, update or delete. record_type: CNAME or TXT. prefix: relative name (e.g. 'git' or '_acme-challenge.git') or full name in the zone. value: CNAME target or TXT text (create/update). new_prefix: rename on update. old_value: picks one TXT record when several share a prefix.""" try: config, client = _get_client() args = _change_args(action, record_type, prefix, value, new_prefix, old_value) plan = _plan(client, args) now = time.monotonic() for ticket, (expires, _, _) in list(_approvals.items()): if expires <= now: _approvals.pop(ticket, None) ticket = secrets.token_urlsafe(18) _approvals[ticket] = (now + APPROVAL_TTL_SECONDS, json.dumps(args, sort_keys=True), plan) return _json({ "action": "preview-only", "domain": config.domain, "change": plan.action, "record_type": plan.record_type, "before": _record_view(plan.before), "after": _record_view(plan.after), "zone_records_after": len(plan.records), "other_form_fields_resent_unchanged": list(plan.preserved_fields), "write_enabled": config.write_enabled, "approval_ticket": ticket, "approval_expires_in_seconds": APPROVAL_TTL_SECONDS, "next_step": ( "Show before/after to the user. Only after explicit approval call " "strato_apply_change with exactly the same arguments, confirm=true and this ticket." if config.write_enabled else "Writes are disabled (STRATO_WRITE_ENABLED is not true); this preview cannot be applied." ), }) except Exception as exc: raise _fail(exc) from None @mcp.tool() def strato_apply_change( action: str, record_type: str, prefix: str, approval_ticket: str, confirm: bool, value: str | None = None, new_prefix: str | None = None, old_value: str | None = None, ) -> str: """Apply exactly one previously previewed DNS change. WRITE. Needs the same arguments as the preview, its approval_ticket and confirm=true. Refused if the zone changed since the preview. Verified by reading the zone again.""" try: if confirm is not True: raise StratoError("confirm=true is required after the user approved the preview") config, client = _get_client() args = _change_args(action, record_type, prefix, value, new_prefix, old_value) approval = _approvals.pop(approval_ticket, None) if approval is None or approval[0] <= time.monotonic(): raise StratoError("Approval ticket is missing, expired or already used; preview again") if not secrets.compare_digest(approval[1], json.dumps(args, sort_keys=True)): raise StratoError("Arguments differ from the preview; preview again") result = client.apply(approval[2]) return _json({ "applied": True, "domain": config.domain, "change": result.action, "record_type": result.record_type, "before": _record_view(result.before), "after": _record_view(result.after), "hint": "DNS caches may take up to the record TTL to update; use strato_check_dns.", }) except Exception as exc: raise _fail(exc) from None @mcp.tool() def strato_check_dns(name: str) -> str: """Resolve a name with this server's DNS resolver and compare it with the STRATO zone. Shows whether a change is already visible. Makes no change.""" try: config, client = _get_client() host = name.strip().rstrip(".").lower() if not host: raise StratoError("name is required") if host != config.domain and not host.endswith("." + config.domain): host = f"{host}.{config.domain}" prefix = host[: -(len(config.domain) + 1)] if host != config.domain else "" expected = [r for r in client.list_cnames() if r.prefix.lower() == prefix] try: canonical, aliases, addresses = socket.gethostbyname_ex(host) resolved: dict[str, Any] = {"canonical_name": canonical, "aliases": aliases, "addresses": addresses} except OSError as exc: resolved = {"error": f"not resolvable: {exc.strerror or exc}"} target = expected[0].value.rstrip(".").lower() if expected else None matches: bool | None = None if target and "addresses" in resolved: names = [resolved["canonical_name"], *resolved["aliases"]] matches = any(n.rstrip(".").lower() == target for n in names) or _resolves_same( target, resolved["addresses"] ) elif target: matches = False return _json({ "name": host, "zone_cname_target": target, "resolver": resolved, "matches_zone": matches, "note": "Uses the MCP host's resolver; local DNS overrides or caches can differ from public DNS.", }) except Exception as exc: raise _fail(exc) from None def _resolves_same(target: str, addresses: list[str]) -> bool: try: return bool(set(socket.gethostbyname_ex(target)[2]) & set(addresses)) except OSError: return False if __name__ == "__main__": mcp.run(transport=os.environ.get("MCP_TRANSPORT", "streamable-http"))