mcp_oauth_device.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. """Explicit RFC 8628 MCP login, sharing SDK discovery, client auth and token storage.
  2. The SDK still owns runtime requests and refresh. Device authorization is only
  3. started by `hermes mcp login/reauth`, never a background reconnect.
  4. """
  5. from __future__ import annotations
  6. import asyncio
  7. import math
  8. import sys
  9. import time
  10. from mcp.shared.auth import OAuthMetadata
  11. from pydantic import AnyHttpUrl
  12. DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
  13. class DeviceOAuthMetadata(OAuthMetadata):
  14. # RFC 8414 makes authorization_endpoint optional for grants not using it.
  15. authorization_endpoint: AnyHttpUrl | None = None
  16. device_authorization_endpoint: AnyHttpUrl
  17. async def _discover(client, provider):
  18. from mcp.client.auth.exceptions import OAuthFlowError
  19. from mcp.client.auth.utils import (
  20. build_protected_resource_metadata_discovery_urls,
  21. extract_resource_metadata_from_www_auth,
  22. handle_protected_resource_response,
  23. )
  24. context = provider.context
  25. response = await client.get(context.server_url)
  26. challenge = extract_resource_metadata_from_www_auth(response)
  27. prm = None
  28. for url in build_protected_resource_metadata_discovery_urls(challenge, context.server_url):
  29. response = await client.get(url)
  30. prm = await handle_protected_resource_response(response)
  31. if prm:
  32. await provider._validate_resource_match(prm)
  33. context.protected_resource_metadata = prm
  34. break
  35. # RFC 9728 lets a resource advertise several authorization servers; a browser-only
  36. # server often comes first and the device-code one later, so try each in order.
  37. servers = [str(url) for url in prm.authorization_servers] if prm else [None]
  38. failures = []
  39. for auth_server_url in servers:
  40. try:
  41. metadata = await _device_metadata(client, context.server_url, auth_server_url)
  42. except (RuntimeError, OAuthFlowError, ValueError) as exc:
  43. failures.append((auth_server_url, exc))
  44. continue
  45. context.auth_server_url = auth_server_url
  46. context.oauth_metadata = metadata
  47. return
  48. if len(failures) == 1:
  49. raise failures[0][1]
  50. raise RuntimeError("No advertised authorization server supports device login: "
  51. + "; ".join(f"{url}: {exc}" for url, exc in failures))
  52. async def _device_metadata(client, server_url, auth_server_url):
  53. """Issuer-bound device metadata of one authorization server; raises when it is unusable."""
  54. from mcp.client.auth.utils import build_oauth_authorization_server_metadata_discovery_urls
  55. from tools.mcp_oauth_provider import metadata_issued_by_origin
  56. for url in build_oauth_authorization_server_metadata_discovery_urls(auth_server_url, server_url):
  57. response = await client.get(url)
  58. if response.status_code == 404:
  59. continue
  60. data = _payload(response, "OAuth metadata")
  61. if not data.get("device_authorization_endpoint"):
  62. raise RuntimeError("Server does not advertise device authorization; use --flow browser if supported")
  63. metadata = DeviceOAuthMetadata.model_validate(data)
  64. # The advertised identifier reaches here as str(AnyHttpUrl) with a trailing "/" (pydantic
  65. # normalizes a host-only URL to its root path) while the document issuer keeps the advertised
  66. # form, so the SDK's exact-string check (RFC 8414 §3.3) would reject Google's issuer
  67. # ("https://accounts.google.com" != "https://accounts.google.com/"). Compare both sides
  68. # root-slash-normalized, the same convention _metadata_issuer and the refresh-token issuer
  69. # binding already use; any other mismatch is still rejected.
  70. expected = auth_server_url.rstrip("/") if auth_server_url else auth_server_url
  71. if expected and not metadata_issued_by_origin(metadata, expected, response):
  72. if str(metadata.issuer).rstrip("/") != expected:
  73. from mcp.client.auth.exceptions import OAuthFlowError
  74. raise OAuthFlowError(f"Authorization server metadata issuer mismatch: {metadata.issuer} != {expected}")
  75. grants = metadata.grant_types_supported
  76. if grants is not None and DEVICE_GRANT not in grants:
  77. raise RuntimeError("Server does not advertise the device_code grant")
  78. return metadata
  79. raise RuntimeError("No OAuth authorization server metadata found")
  80. def _payload(response, label):
  81. try:
  82. data = response.json()
  83. except ValueError:
  84. raise RuntimeError(f"{label}: invalid JSON response") from None
  85. if not isinstance(data, dict):
  86. raise RuntimeError(f"{label}: expected a JSON object")
  87. if not 200 <= response.status_code < 300:
  88. # Descriptions and arbitrary error values may contain credentials.
  89. raise RuntimeError(f"{label} failed (HTTP {response.status_code})")
  90. return data
  91. async def _register(client, provider, cfg):
  92. from mcp.shared.auth import OAuthClientInformationFull
  93. from mcp.client.auth.oauth2 import OAuthRegistrationError, check_registration_usable
  94. context = provider.context
  95. metadata = context.client_metadata.model_dump(mode="json", exclude_none=True)
  96. metadata.update(grant_types=[DEVICE_GRANT, "refresh_token"], response_types=[])
  97. if cfg.get("client_id"):
  98. data = {**metadata, "client_id": cfg["client_id"]}
  99. if cfg.get("client_secret"):
  100. data["client_secret"] = cfg["client_secret"]
  101. else:
  102. endpoint = context.oauth_metadata.registration_endpoint
  103. if not endpoint:
  104. raise RuntimeError("Server has no registration endpoint; configure oauth.client_id (and client_secret if required)")
  105. response = await client.post(str(endpoint), json=metadata)
  106. data = _payload(response, "Client registration")
  107. # SEP-2352: bind the credentials to the identifier the SDK's runtime flow compares them against — the
  108. # advertised authorization server when the resource advertised one, else the metadata issuer (its Step 4
  109. # rule). For a path-scoped server whose document names its origin (#116233) the two differ, and a
  110. # binding to the document issuer would make the next 401 discard this client and its tokens.
  111. data["issuer"] = str(context.auth_server_url or context.oauth_metadata.issuer)
  112. context.client_info = OAuthClientInformationFull.model_validate(data)
  113. provider._coerce_client_secret_post()
  114. try:
  115. check_registration_usable(context.client_info)
  116. except OAuthRegistrationError:
  117. raise RuntimeError("Device OAuth client has unsupported or incomplete token endpoint authentication") from None
  118. def _positive_seconds(value, label):
  119. value = float(value)
  120. if not math.isfinite(value) or value <= 0:
  121. raise RuntimeError(f"Device authorization has invalid {label}")
  122. return value
  123. async def _authorize(client, provider, cfg):
  124. from tools.mcp_oauth_provider import google_offline_access_params
  125. from tools.mcp_tool import sdk_httpx
  126. context = provider.context
  127. resource = context.get_resource_url()
  128. data = {"client_id": context.client_info.client_id, "resource": resource}
  129. if context.client_metadata.scope:
  130. data["scope"] = context.client_metadata.scope
  131. data.update(google_offline_access_params(context))
  132. data, headers = context.prepare_token_auth(data, {})
  133. response = await client.post(str(context.oauth_metadata.device_authorization_endpoint), data=data, headers=headers)
  134. authorization = _payload(response, "Device authorization")
  135. for key in ("device_code", "user_code", "verification_uri"):
  136. if not isinstance(authorization.get(key), str) or not authorization[key]:
  137. raise RuntimeError(f"Device authorization is missing {key}")
  138. verification = AnyHttpUrl(authorization["verification_uri"])
  139. interval = _positive_seconds(authorization.get("interval", 5), "interval")
  140. deadline = time.monotonic() + min(_positive_seconds(authorization["expires_in"], "expires_in"),
  141. _positive_seconds(cfg.get("timeout", 300), "timeout"))
  142. print(f"\n MCP OAuth: open {verification} on any device.\n Code: {authorization['user_code']}\n"
  143. " Waiting for approval...\n", file=sys.stderr, flush=True)
  144. token_data = {"client_id": context.client_info.client_id, "device_code": authorization["device_code"],
  145. "grant_type": DEVICE_GRANT, "resource": resource}
  146. token_data, headers = context.prepare_token_auth(token_data, {})
  147. httpx = sdk_httpx()
  148. while True:
  149. remaining = deadline - time.monotonic()
  150. if remaining <= interval:
  151. raise RuntimeError("Device authorization expired before approval; run login again")
  152. await asyncio.sleep(interval)
  153. request = provider._prepare_token_request(httpx.Request("POST", str(context.oauth_metadata.token_endpoint),
  154. data=token_data, headers=headers))
  155. try:
  156. response = await asyncio.wait_for(client.send(request), timeout=deadline - time.monotonic())
  157. except (TimeoutError, httpx.TimeoutException):
  158. # RFC 8628 requires reducing polling frequency after connection timeouts.
  159. interval *= 2
  160. continue
  161. if 200 <= response.status_code < 300:
  162. from mcp.shared.auth import OAuthToken
  163. tokens = OAuthToken.model_validate(_payload(response, "Device token"))
  164. if not tokens.access_token:
  165. raise RuntimeError("Device token response has no access token")
  166. if tokens.scope is None:
  167. tokens.scope = context.client_metadata.scope
  168. return tokens
  169. try:
  170. error = response.json().get("error")
  171. except (ValueError, AttributeError):
  172. error = None
  173. if error == "authorization_pending":
  174. continue
  175. if error == "slow_down":
  176. interval += 5
  177. continue
  178. safe_error = error if error in {"access_denied", "expired_token"} else f"HTTP {response.status_code}"
  179. raise RuntimeError(f"Device authorization failed: {safe_error}")
  180. async def login_device(name, server_url, oauth_config):
  181. """Authorize then commit state in the active profile; failed grants preserve old state."""
  182. from tools.mcp_oauth import _build_client_metadata
  183. from tools.mcp_oauth_manager import HermesMCPOAuthProvider, get_manager
  184. from tools.mcp_oauth_provider import prepare_oauth_config
  185. from tools.mcp_tool import sdk_httpx
  186. cfg, storage = prepare_oauth_config(name, server_url, oauth_config)
  187. # Device flow never binds a callback socket or uses the hosted browser CIMD.
  188. cfg["_resolved_port"] = cfg.get("redirect_port", 8420)
  189. provider = HermesMCPOAuthProvider(server_url=server_url, server_name=name, storage=storage,
  190. client_metadata=_build_client_metadata(cfg),
  191. token_user_agent=cfg.get("user_agent"))
  192. httpx = sdk_httpx()
  193. try:
  194. async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
  195. await _discover(client, provider)
  196. await _register(client, provider, cfg)
  197. tokens = await _authorize(client, provider, cfg)
  198. except (ValueError, TypeError, KeyError):
  199. raise RuntimeError("Device OAuth response has invalid fields") from None
  200. except httpx.HTTPError:
  201. raise RuntimeError("Device OAuth network request failed") from None
  202. # Validate the entire grant before touching disk; reuse the existing scoped store.
  203. previous = storage.snapshot()
  204. try:
  205. await storage.set_client_info(provider.context.client_info)
  206. storage.save_oauth_metadata(provider.context.oauth_metadata)
  207. await storage.set_tokens(tokens)
  208. except OSError:
  209. storage.restore(previous)
  210. raise
  211. get_manager().evict(name)