-
Notifications
You must be signed in to change notification settings - Fork 75
ug mcp add: native OAuth (direct HTTP) for Claude Code + Cursor, else generic proxy #560
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
sunishsheth2009
merged 5 commits into
databricks:main
from
sunishsheth2009:mcp-claude-code-http
Sep 14, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
53df397
ug mcp add: register connection-backed MCP services as direct HTTP fo…
sunishsheth2009 ecfd864
Extend direct-HTTP MCP OAuth to Cursor
sunishsheth2009 ba63929
mcp: drop redundant always_load guard from direct-HTTP dispatch
sunishsheth2009 2b9ea8e
Address review: probe fails closed + cache dir creation
sunishsheth2009 44fcb0c
Fix ruff format in test_mcp_oauth
sunishsheth2009 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| """Discovery of the OAuth client used for direct-HTTP MCP registration. | ||
|
|
||
| A connection-backed AI Gateway MCP service (e.g. ``system.ai.github``) needs a | ||
| per-user connection login before its tools can be called. When a coding agent | ||
| registers the service as a **direct HTTP** MCP server, the agent itself drives | ||
| that login via OAuth against the workspace ``/oidc`` — and `/oidc` has no dynamic | ||
| client registration, so the agent must present a **pre-registered public client**. | ||
|
|
||
| ``claude-code`` is that published client for Claude Code: it has the loopback | ||
| ``/callback`` redirect Claude Code uses registered (``databricks-cli`` does not, | ||
| so Claude's direct-HTTP OAuth is rejected against it). Where a workspace has | ||
| ``claude-code``, ucode registers these services as direct HTTP so ``/mcp`` shows | ||
| "needs authentication" and Authenticate drives the login natively. Not every | ||
| workspace has it yet, so we probe — and cache the answer per workspace. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import time | ||
| import urllib.error | ||
| import urllib.request | ||
| from urllib.parse import urlencode | ||
|
|
||
| from ucode.config_io import APP_DIR, read_json_safe, write_json_file | ||
|
|
||
| # Published public OAuth client Claude Code authenticates with. Any loopback | ||
| # callback port works — `/oidc` strips the port when matching loopback redirects | ||
| # (RFC 8252 §8.4) — but the redirect *path* (`/callback`) must be registered, | ||
| # which this client has and `databricks-cli` does not. | ||
| CLAUDE_CODE_OAUTH_CLIENT_ID = "claude-code" | ||
| MCP_OAUTH_CALLBACK_PORT = 3118 | ||
|
|
||
| # Published public OAuth client Cursor authenticates with for OAuth MCP servers. | ||
| # Cursor's `mcp.json` accepts a pre-registered `auth.CLIENT_ID` (no dynamic client | ||
| # registration, which `/oidc` lacks) and drives the login to Cursor's fixed loopback | ||
| # redirect `http://localhost:8787/callback`. `/oidc` matches loopback redirects by | ||
| # path (RFC 8252 §8.4), so the registered `/callback` path is what matters — the | ||
| # same requirement `claude-code` satisfies. | ||
| CURSOR_OAUTH_CLIENT_ID = "cursor-desktop" | ||
|
|
||
| # Published apps rarely appear/disappear, so a per-workspace probe result is good | ||
| # for a while; delete the cache file to force a re-probe. | ||
| _CACHE_PATH = APP_DIR / "oauth_client_cache.json" | ||
| _CACHE_TTL_SECONDS = 7 * 24 * 3600 | ||
|
|
||
|
|
||
| def _probe_oauth_client(workspace: str, client_id: str) -> bool | None: | ||
| """Whether ``client_id`` is a registered OAuth app on the workspace's ``/oidc``: | ||
| ``True`` (registered), ``False`` (not registered), or ``None`` (inconclusive). | ||
|
|
||
| Back-channel and unauthenticated: POST a throwaway ``authorization_code`` grant | ||
| to ``/oidc/v1/token``. An **unknown** client fails client authentication (HTTP | ||
| 401 ``invalid_client`` -> ``False``); a **known** client gets past that to a | ||
| grant error (HTTP 400 ``invalid_request`` — "Invalid authorization code" -> | ||
| ``True``); the dummy code always fails, harmlessly. Any other outcome — a | ||
| transient 429/5xx, a 404/redirect, a network error, or an unexpected 2xx — is | ||
| **inconclusive** (``None``): we must not read "not 401" as "registered", or an | ||
| incident/rate-limit would flip every workspace to the direct-HTTP path. This is | ||
| the only user-level check available — the authorize endpoint redirects to SSO | ||
| before validating the client, and the published-app API needs account-admin.""" | ||
| body = urlencode( | ||
| { | ||
| "grant_type": "authorization_code", | ||
| "code": "ucode-probe-not-a-real-code", | ||
| "redirect_uri": f"http://localhost:{MCP_OAUTH_CALLBACK_PORT}/callback", | ||
| "client_id": client_id, | ||
| # `/oidc` rejects a code_verifier shorter than 43 chars *before* it | ||
| # validates the client, so pad past that to reach the client check. | ||
| "code_verifier": "u" * 43, | ||
| } | ||
| ).encode("ascii") | ||
| request = urllib.request.Request( | ||
|
sunishsheth2009 marked this conversation as resolved.
|
||
| f"{workspace.rstrip('/')}/oidc/v1/token", | ||
| data=body, | ||
| method="POST", | ||
| headers={"Content-Type": "application/x-www-form-urlencoded"}, | ||
| ) | ||
| try: | ||
| urllib.request.urlopen(request, timeout=10) # noqa: S310 - fixed https workspace URL | ||
| return None # a 2xx for a dummy code is unexpected; don't conclude either way | ||
| except urllib.error.HTTPError as exc: | ||
| if exc.code == 401: | ||
| return False # invalid_client => the app is not registered | ||
| if exc.code == 400: | ||
| return True # known client, rejected only on the dummy code => registered | ||
| return None # 429/5xx/404/redirect/etc => inconclusive | ||
| except OSError: | ||
| return None # network failure => inconclusive | ||
|
|
||
|
|
||
| def _read_cache() -> dict: | ||
| return read_json_safe(_CACHE_PATH) | ||
|
|
||
|
|
||
| def _write_cache(cache: dict) -> None: | ||
| # write_json_file creates APP_DIR if missing (like every other APP_DIR writer); | ||
| # best-effort — a write failure just means we re-probe next time. | ||
| try: | ||
| write_json_file(_CACHE_PATH, cache) | ||
| except OSError: | ||
| pass | ||
|
|
||
|
|
||
| def oauth_client_available(workspace: str, client_id: str) -> bool: | ||
| """Whether the workspace has ``client_id`` as a registered OAuth app, cached | ||
| per (workspace, client_id). | ||
|
|
||
| Cached in ``APP_DIR`` with a weekly TTL so ``ug mcp add`` doesn't probe every | ||
| run. Negative results are cached too (workspaces that don't have it yet).""" | ||
| ws = workspace.rstrip("/") | ||
| cache = _read_cache() | ||
| entry = cache.get(ws, {}).get(client_id) | ||
| if entry and (time.time() - entry.get("checked_at", 0)) < _CACHE_TTL_SECONDS: | ||
| return bool(entry.get("available")) | ||
| available = _probe_oauth_client(ws, client_id) | ||
| if available is None: | ||
| # Inconclusive probe (transient status / network error): fall back to the | ||
| # stdio proxy and do NOT cache, so a transient failure isn't sticky for the | ||
| # TTL — we re-probe on the next run. | ||
| return False | ||
| cache.setdefault(ws, {})[client_id] = { | ||
| "available": available, | ||
| "checked_at": time.time(), | ||
| } | ||
| _write_cache(cache) | ||
| return available | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "CLAUDE_CODE_OAUTH_CLIENT_ID", | ||
| "CURSOR_OAUTH_CLIENT_ID", | ||
| "MCP_OAUTH_CALLBACK_PORT", | ||
| "oauth_client_available", | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.