mcp_dashboard_oauth.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """Dashboard-mediated callback bridge for MCP OAuth: the SDK still does discovery, DCR, PKCE, state
  2. validation and token exchange; this only moves the two human/browser callbacks from a loopback
  3. listener into the already-authenticated dashboard session."""
  4. from __future__ import annotations
  5. import asyncio
  6. import contextvars
  7. import logging
  8. import secrets
  9. import threading
  10. import time
  11. from contextlib import contextmanager
  12. from dataclasses import dataclass, field
  13. from typing import Iterator
  14. from urllib.parse import parse_qs, urlparse
  15. logger = logging.getLogger(__name__)
  16. @contextmanager
  17. def contextvar_set(var: contextvars.ContextVar, value) -> Iterator[None]:
  18. """Set *var* to *value* for the block, restoring the previous value after."""
  19. token = var.set(value)
  20. try:
  21. yield
  22. finally:
  23. var.reset(token)
  24. def exception_message(exc: BaseException) -> str:
  25. """``str(exc)``, or the type name when it is empty (bare ``TimeoutError()``/``RuntimeError()``)
  26. so ``mark_error`` never records a blank cause."""
  27. return str(exc) or type(exc).__name__
  28. @dataclass
  29. class DashboardOAuthFlow:
  30. flow_id: str
  31. server_name: str
  32. profile: str | None
  33. hermes_home: str
  34. redirect_uri: str
  35. reconnect_live: bool = False
  36. created_at: float = field(default_factory=time.time)
  37. status: str = "starting"
  38. authorization_url: str | None = None
  39. error: str | None = None
  40. tools: list[dict] = field(default_factory=list)
  41. discovery_error: str = ""
  42. # The user abandoned this flow: terminal for good, never re-minted (see publish_authorization_url).
  43. cancelled: bool = field(default=False, init=False)
  44. expected_state: str | None = field(default=None, init=False)
  45. _callback: tuple[str, str | None, str | None] | None = field(default=None, init=False, repr=False)
  46. _callback_error: str | None = field(default=None, init=False, repr=False)
  47. _authorization_ready: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
  48. _callback_ready: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
  49. _worker_done: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
  50. _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
  51. async def publish_authorization_url(self, url: str) -> None:
  52. """Record the SDK's authorization URL (with its ``state``) for the dashboard to show.
  53. A flow whose EARLIER attempt already ended is re-minted here instead of raising: the MCP server
  54. task inherits this handle for the whole life of the task, so ``RuntimeError: OAuth flow already
  55. ended`` escaped the SDK's auth flow on every retry and parked the server ("failed initial
  56. connection after 3 attempts") with no way back short of restarting Hermes (#114739). A flow the
  57. user CANCELLED stays terminal — the retrying worker must not reopen what they abandoned.
  58. """
  59. state = parse_qs(urlparse(url).query).get("state", [None])[0]
  60. if not state:
  61. raise ValueError("OAuth authorization URL did not include state")
  62. with self._lock:
  63. if self.cancelled:
  64. raise RuntimeError("OAuth flow already ended: cancelled by user")
  65. if self.status in {"approved", "error"}:
  66. self._reopen_ended_attempt()
  67. self.expected_state = state
  68. self.authorization_url = url
  69. self.status = "authorization_required"
  70. self._authorization_ready.set()
  71. def _reopen_ended_attempt(self) -> None:
  72. """Reset an ended attempt so the next authorization URL mints a fresh state (caller holds
  73. ``self._lock``). The ended attempt's URL, state and spent authorization code are dropped —
  74. replaying them would hand the SDK a code the provider already burned."""
  75. logger.info("MCP OAuth: dashboard flow %s for '%s' ended (%s); re-minting for the next attempt",
  76. self.flow_id, self.server_name, self.status)
  77. self.authorization_url = None
  78. self.expected_state = None
  79. self._callback = None
  80. self._callback_error = None
  81. self._callback_ready.clear()
  82. self.error = None
  83. self.status = "starting"
  84. async def wait_for_authorization_url(self, timeout: float = 30.0) -> str:
  85. if not await asyncio.to_thread(self._authorization_ready.wait, timeout):
  86. raise TimeoutError("Timed out waiting for MCP authorization URL")
  87. if not self.authorization_url:
  88. raise RuntimeError(self.error or "MCP OAuth flow ended before authorization")
  89. return self.authorization_url
  90. def deliver_callback(
  91. self, *, code: str | None, state: str | None, error: str | None, iss: str | None = None
  92. ) -> None:
  93. """Hand the browser redirect to the waiting flow; ``state`` must match exactly.
  94. ``iss`` (RFC 9207) is carried through — see ``tools.mcp_oauth._parse_redirect_query``.
  95. """
  96. with self._lock:
  97. if self._callback_ready.is_set():
  98. raise ValueError("OAuth callback already received")
  99. if self.expected_state is None or state is None or not secrets.compare_digest(self.expected_state, state):
  100. raise ValueError("OAuth callback state mismatch")
  101. if error:
  102. self._callback_error = error
  103. elif code:
  104. self._callback = (code, state, iss)
  105. else:
  106. self._callback_error = "OAuth callback did not include code or error"
  107. self._callback_ready.set()
  108. async def wait_for_callback(self, timeout: float = 300.0) -> tuple[str, str | None, str | None]:
  109. if not await asyncio.to_thread(self._callback_ready.wait, timeout):
  110. raise TimeoutError("Timed out waiting for MCP OAuth callback")
  111. if self._callback_error:
  112. raise RuntimeError(f"OAuth authorization failed: {self._callback_error}")
  113. if self._callback is None:
  114. raise RuntimeError(
  115. f"MCP OAuth flow for '{self.server_name}' ended without an authorization code "
  116. f"(status={self.status}, error={self.error!r})")
  117. return self._callback
  118. def mark_approved(self) -> None:
  119. with self._lock:
  120. if self.status == "error":
  121. raise RuntimeError("OAuth flow already ended")
  122. self.status = "approved"
  123. self.error = None
  124. def mark_error(self, error: str, *, cancelled: bool = False) -> None:
  125. """Fail the flow with *error*; the first reason wins. Waking the callback waiter makes the
  126. worker fail too, and its follow-on ``mark_error`` must not clobber the cause the user needs.
  127. ``cancelled`` marks a user cancellation, which ``publish_authorization_url`` refuses to re-mint
  128. (unlike an ordinary failure, which a retry may reopen). It is recorded even when the flow has
  129. already ended: the user's "no" outranks the recorded cause and keeps the handle terminal.
  130. """
  131. with self._lock:
  132. self.cancelled = self.cancelled or cancelled
  133. if self.status in {"approved", "error"}:
  134. return
  135. self.status = "error"
  136. self.error = error or "MCP OAuth flow failed before the callback was received (empty error message)"
  137. # The SDK's callback waiter reads _callback_error, not error — without
  138. # this copy, a failure marked before any browser redirect (worker
  139. # crash, authorization-URL timeout, user cancel) wakes the waiter
  140. # with no callback and no error, surfacing as the generic
  141. # "did not include an authorization code" RuntimeError while the
  142. # real cause stays unread. Guarded so a late mark_error cannot
  143. # override an already delivered callback.
  144. if self._callback is None and self._callback_error is None:
  145. self._callback_error = self.error
  146. self._authorization_ready.set()
  147. self._callback_ready.set()
  148. def snapshot(self) -> dict:
  149. with self._lock:
  150. return {"flow_id": self.flow_id, "server_name": self.server_name, "status": self.status,
  151. "authorization_url": self.authorization_url, "error": self.error}
  152. def mark_worker_done(self) -> None:
  153. self._worker_done.set()
  154. @property
  155. def worker_done(self) -> bool:
  156. return self._worker_done.is_set()
  157. _current_dashboard_flow: contextvars.ContextVar[DashboardOAuthFlow | None] = contextvars.ContextVar("mcp_dashboard_oauth_flow", default=None)
  158. def dashboard_oauth_flow(flow: DashboardOAuthFlow):
  159. """Make *flow* the active dashboard OAuth flow for the block (ContextVar-scoped)."""
  160. return contextvar_set(_current_dashboard_flow, flow)
  161. def get_dashboard_oauth_flow() -> DashboardOAuthFlow | None:
  162. return _current_dashboard_flow.get()