Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: fix OAuth sign-in for MCP servers like Notion (#10167)

Nilayfce1a9f0cb20
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index 01f5a839b76..edf0bcc7561 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -258,15 +258,44 @@ def _oauth_store():
return _oauth_token_store
+def _strip_client_id_under_basic_auth(auth) -> None:
+ """The SDK leaves client_id in the body under Basic auth; strict servers (Notion) read
+ that as two auth methods -- RFC 6749 2.3 -- and 401. Safe to drop: 3.2.1 makes client_id
+ a MAY once authenticated, and an unauthenticated client sends no header, so it keeps it."""
+ context = getattr(auth, "context", None)
+ prepare = getattr(context, "prepare_token_auth", None)
+ if prepare is None:
+ logger.warning("MCP OAuth: prepare_token_auth missing; client_id fixup skipped")
+ return
+
+ def prepare_token_auth(data, headers = None):
+ data, headers = prepare(data, headers)
+ if "Authorization" in headers:
+ data = {k: v for k, v in data.items() if k != "client_id"}
+ return data, headers
+
+ try:
+ context.prepare_token_auth = prepare_token_auth
+ except Exception as exc: # noqa: BLE001
+ # The SDK reach-in must never break OAuth: without it only strict servers fail, as before.
+ logger.warning("MCP OAuth: client_id fixup could not be applied: %s", exc)
+
+
+def _oauth(url: str):
+ from fastmcp.client.auth import OAuth
+
+ auth = OAuth(mcp_url = url, token_storage = _oauth_store())
+ _strip_client_id_under_basic_auth(auth)
+ return auth
+
+
async def clear_oauth_tokens_async(url: str) -> None:
"""Drop any persisted OAuth tokens for ``url``. fastmcp keys tokens by MCP
URL, so on server delete / URL change / OAuth disable we must clear them, else
re-registering the same URL reuses the old account's token. Best-effort: store
/ OAuth failures must not 500 the delete / update route."""
try:
- from fastmcp.client.auth import OAuth
- auth = OAuth(mcp_url = url, token_storage = _oauth_store())
- await auth.token_storage_adapter.clear()
+ await _oauth(url).token_storage_adapter.clear()
except Exception as exc: # noqa: BLE001
logger.warning("Failed to clear OAuth tokens for %s: %s", url, exc)
@@ -448,10 +477,7 @@ def _client(
from fastmcp.client.transports import SSETransport, StreamableHttpTransport
from fastmcp.mcp_config import infer_transport_type_from_url
- auth = None
- if use_oauth:
- from fastmcp.client.auth import OAuth
- auth = OAuth(mcp_url = url, token_storage = _oauth_store())
+ auth = _oauth(url) if use_oauth else None
transport_cls = (
SSETransport if infer_transport_type_from_url(url) == "sse" else StreamableHttpTransport
diff --git a/studio/backend/tests/test_mcp_oauth_basic_auth.py b/studio/backend/tests/test_mcp_oauth_basic_auth.py
new file mode 100644
index 00000000000..78b06adfa46
--- /dev/null
+++ b/studio/backend/tests/test_mcp_oauth_basic_auth.py
@@ -0,0 +1,102 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Under client_secret_basic the token request must not also carry client_id."""
+
+import asyncio
+import base64
+import types
+from urllib.parse import parse_qs
+
+from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
+
+from core.inference import mcp_client
+
+URL = "https://mcp.notion.com/mcp"
+CLIENT_ID = "test-client-id"
+CLIENT_SECRET = "test-client-secret"
+
+
+def _auth(tmp_path, monkeypatch, auth_method):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(mcp_client, "_oauth_token_store", None)
+ auth = mcp_client._oauth(URL)
+ auth.context.client_info = OAuthClientInformationFull(
+ client_id = CLIENT_ID,
+ client_secret = CLIENT_SECRET,
+ token_endpoint_auth_method = auth_method,
+ redirect_uris = auth.context.client_metadata.redirect_uris,
+ )
+ return auth
+
+
+def _form(request):
+ return {k: v[0] for k, v in parse_qs(request.content.decode()).items()}
+
+
+def _basic_header():
+ return "Basic " + base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
+
+
+def test_basic_auth_omits_client_id_from_body(tmp_path, monkeypatch):
+ auth = _auth(tmp_path, monkeypatch, "client_secret_basic")
+ request = asyncio.run(auth._exchange_token_authorization_code("auth-code", "verifier"))
+ form = _form(request)
+
+ assert "client_id" not in form
+ assert "client_secret" not in form
+ assert request.headers["Authorization"] == _basic_header()
+ assert form["grant_type"] == "authorization_code"
+ assert form["code"] == "auth-code"
+ assert form["code_verifier"] == "verifier"
+
+
+def test_post_auth_keeps_client_id_in_body(tmp_path, monkeypatch):
+ auth = _auth(tmp_path, monkeypatch, "client_secret_post")
+ request = asyncio.run(auth._exchange_token_authorization_code("auth-code", "verifier"))
+ form = _form(request)
+
+ assert form["client_id"] == CLIENT_ID
+ assert form["client_secret"] == CLIENT_SECRET
+ assert "Authorization" not in request.headers
+
+
+def test_basic_auth_omits_client_id_from_refresh(tmp_path, monkeypatch):
+ auth = _auth(tmp_path, monkeypatch, "client_secret_basic")
+ auth.context.current_tokens = OAuthToken(access_token = "at", refresh_token = "rt")
+ request = asyncio.run(auth._refresh_token())
+ form = _form(request)
+
+ assert "client_id" not in form
+ assert form["grant_type"] == "refresh_token"
+ assert form["refresh_token"] == "rt"
+ assert request.headers["Authorization"] == _basic_header()
+
+
+def test_public_client_keeps_client_id_in_body(tmp_path, monkeypatch):
+ """A public client authenticates with client_id alone, so stripping it would break it."""
+ auth = _auth(tmp_path, monkeypatch, "none")
+ auth.context.client_info.client_secret = None
+ request = asyncio.run(auth._exchange_token_authorization_code("auth-code", "verifier"))
+ form = _form(request)
+
+ assert form["client_id"] == CLIENT_ID
+ assert "Authorization" not in request.headers
+
+
+def test_unpatchable_context_does_not_break_oauth():
+ """If a future SDK makes the context unwritable, callers still get a working provider."""
+
+ class Frozen:
+ def prepare_token_auth(
+ self,
+ data,
+ headers = None,
+ ):
+ return data, headers or {}
+
+ def __setattr__(self, name, value):
+ raise AttributeError("frozen")
+
+ auth = types.SimpleNamespace(context = Frozen())
+ mcp_client._strip_client_id_under_basic_auth(auth)