webhook_mcp_events.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. """MCP Events deliveries on routes that ``tools/mcp_tool_events.py`` created (the route carries an
  2. ``mcp_event`` block). The endpoint-verification echo and the ``terminated`` / ``gap`` control
  3. envelopes are answered here without an agent run; an event occurrence continues through the normal
  4. route pipeline, keyed for idempotency by its ``eventId``. Signatures (Standard Webhooks, ``whsec_``)
  5. are already verified by the adapter before any of this runs."""
  6. import asyncio
  7. import json
  8. import logging
  9. from typing import Any, Optional
  10. logger = logging.getLogger(__name__)
  11. _MAX_CHALLENGE_CHARS = 512
  12. _MAX_NOTICE_DETAIL_CHARS = 200
  13. _MAX_EVENT_DATA_CHARS = 32_000
  14. def _json(body: dict, status: int = 200):
  15. from aiohttp import web # lazy: the adapter is only constructed when aiohttp is installed
  16. return web.json_response(body, status=status)
  17. def _mcp_event(route_config: dict) -> Optional[dict]:
  18. event = route_config.get("mcp_event")
  19. return event if isinstance(event, dict) else None
  20. def render_mcp_event_prompt(adapter, route_config: dict, payload: Any, event_type: str,
  21. route_name: str) -> Optional[str]:
  22. """The prompt for an occurrence on an MCP event route whose template uses ``{data}``; None otherwise.
  23. ``{data}`` takes the whole payload (up to ``_MAX_EVENT_DATA_CHARS``, with a note when cut) instead of
  24. the 2,000-character cap other placeholders get, and the JSON goes in after the rest of the template
  25. renders, so text inside the payload is never read as a placeholder."""
  26. if _mcp_event(route_config) is None or not isinstance(payload, dict):
  27. return None
  28. template = route_config.get("prompt")
  29. if not isinstance(template, str) or "{data}" not in template:
  30. return None
  31. data = json.dumps(payload.get("data"), indent=2, ensure_ascii=False)
  32. if len(data) > _MAX_EVENT_DATA_CHARS:
  33. data = (f"{data[:_MAX_EVENT_DATA_CHARS]}\n[truncated: the first {_MAX_EVENT_DATA_CHARS:,} of "
  34. f"{len(data):,} characters]")
  35. return data.join(adapter._render_prompt(part, payload, event_type, route_name) if part else ""
  36. for part in template.split("{data}"))
  37. def mcp_event_delivery_id(route_config: dict, payload: Any) -> Optional[str]:
  38. """``eventId`` is the sketch's dedup key (stable across retries and redeliveries), unlike the
  39. per-attempt ``webhook-id``."""
  40. if _mcp_event(route_config) is None or not isinstance(payload, dict):
  41. return None
  42. event_id = payload.get("eventId")
  43. return f"mcp-event:{event_id}" if isinstance(event_id, str) and event_id else None
  44. def _store_cursor(route_name: str, cursor: str) -> None:
  45. # Subscription state lives beside the route, never in it: an admitted run's reply is checked against
  46. # a digest of the route config, so a cursor written there would strand every run still in flight.
  47. from tools.mcp_tool_events import store_cursor
  48. store_cursor(route_name, cursor)
  49. def _remove_route(route_name: str) -> None:
  50. from hermes_cli.webhook import _mutate_subscriptions
  51. from tools.mcp_tool_events import drop_state
  52. _mutate_subscriptions(lambda subscriptions: subscriptions.pop(route_name, None))
  53. drop_state(route_name)
  54. async def _verification(adapter, route_name: str, route_config: dict, payload: dict, profile) -> Any:
  55. challenge = payload.get("challenge")
  56. if not isinstance(challenge, str) or not challenge or len(challenge) > _MAX_CHALLENGE_CHARS:
  57. return _json({"error": "Invalid verification challenge"}, status=400)
  58. logger.info("[webhook] MCP event route %s answered the server's verification challenge", route_name)
  59. return _json({"challenge": challenge})
  60. async def _terminated(adapter, route_name: str, route_config: dict, payload: dict, profile) -> Any:
  61. event = _mcp_event(route_config) or {}
  62. error = payload.get("error") if isinstance(payload.get("error"), dict) else {}
  63. await asyncio.to_thread(_remove_route, route_name)
  64. logger.warning("[webhook] MCP server '%s' ended event subscription %s (%s): %s", event.get("server"),
  65. route_name, event.get("name"), error)
  66. if route_config.get("deliver", "log") != "log":
  67. detail = str(error.get("message") or "no reason given")[:_MAX_NOTICE_DETAIL_CHARS]
  68. notice = (f"MCP server '{event.get('server')}' ended the subscription to '{event.get('name')}': "
  69. f"{detail} (code {error.get('code')}). Subscribe again to keep receiving these events.")
  70. await adapter._handle_deliver_only(notice, payload, route_config, route_name, "terminated",
  71. f"mcp-terminated:{route_name}", profile)
  72. return _json({"status": "terminated"})
  73. async def _gap(adapter, route_name: str, route_config: dict, payload: dict, profile) -> Any:
  74. cursor = payload.get("cursor")
  75. if isinstance(cursor, str) and cursor:
  76. await asyncio.to_thread(_store_cursor, route_name, cursor)
  77. logger.warning("[webhook] MCP event route %s: the server skipped events (gap); resuming from a fresh cursor",
  78. route_name)
  79. return _json({"status": "gap"})
  80. _CONTROL_HANDLERS = {"verification": _verification, "terminated": _terminated, "gap": _gap}
  81. async def handle_mcp_event_control(adapter, route_name: str, route_config: dict, payload: Any,
  82. profile) -> Any:
  83. """The response for a control envelope on an MCP event route; None lets the delivery continue
  84. as an event occurrence (whose replay cursor, when the server sends one, is remembered first)."""
  85. if _mcp_event(route_config) is None or not isinstance(payload, dict):
  86. return None
  87. kind = payload.get("type")
  88. handler = _CONTROL_HANDLERS.get(kind) if isinstance(kind, str) else None
  89. if handler is not None:
  90. return await handler(adapter, route_name, route_config, payload, profile)
  91. if "type" in payload:
  92. # The sketch: a body with a top-level ``type`` is a control envelope. Acknowledge one this client
  93. # does not know (a later revision's) so the server stops retrying it; it never starts a run.
  94. logger.info("[webhook] MCP event route %s: ignoring a control envelope of unknown type %r", route_name, kind)
  95. return _json({"status": "ignored", "type": kind if isinstance(kind, str) else None})
  96. cursor = payload.get("cursor")
  97. if isinstance(cursor, str) and cursor:
  98. await asyncio.to_thread(_store_cursor, route_name, cursor)
  99. return None