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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: support pre-registered MCP OAuth clients (#7665)
Ben Younes4504252f3ecf
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.pyindex 4ee6d74e154..cbe1ee89709 100644--- a/studio/backend/core/inference/mcp_client.py+++ b/studio/backend/core/inference/mcp_client.py@@ -392,10 +392,20 @@ def _strip_client_id_under_basic_auth(auth) -> None:logger.warning("MCP OAuth: client_id fixup could not be applied: %s", exc)-def _oauth(url: str):+def _oauth(+ url: str,+ oauth_client_id: Optional[str] = None,+ oauth_client_secret: Optional[str] = None,+):from fastmcp.client.auth import OAuth- auth = OAuth(mcp_url = url, token_storage = _oauth_store())+ # A pre-registered client skips Dynamic Client Registration (Google's MCP servers have no /register).+ auth = OAuth(+ mcp_url = url,+ token_storage = _oauth_store(),+ client_id = oauth_client_id,+ client_secret = oauth_client_secret,+ )_strip_client_id_under_basic_auth(auth)return auth@@ -578,6 +588,7 @@ def _client(url: str,headers: Optional[dict],use_oauth: bool = False,+ **oauth,):validate_mcp_address(url)from fastmcp import Client@@ -611,7 +622,7 @@ def _client(from fastmcp.client.transports import SSETransport, StreamableHttpTransportfrom fastmcp.mcp_config import infer_transport_type_from_url- auth = _oauth(url) if use_oauth else None+ auth = _oauth(url, **oauth) if use_oauth else Nonetransport_cls = (SSETransport if infer_transport_type_from_url(url) == "sse" else StreamableHttpTransport@@ -624,6 +635,16 @@ def _client(return Client(transport_cls(url = url, headers = headers or None, auth = auth, **kwargs))+def oauth_client_kwargs(row: dict) -> dict:+ # Empty unless configured, so test doubles of _client without these kwargs keep working.+ if not row.get("oauth_client_id"):+ return {}+ return {+ "oauth_client_id": row["oauth_client_id"],+ "oauth_client_secret": row.get("oauth_client_secret"),+ }++_SESSION_IDLE_TTL = 300.0_SESSION_REAP_INTERVAL = 30.0_STDIO_CONNECT_TIMEOUT = 60.0 # allows first-run `npx -y ...` package download@@ -1463,9 +1484,10 @@ async def list_tools_async(headers: Optional[dict] = None,timeout: float = 5.0,use_oauth: bool = False,+ **oauth,) -> list[dict]:async def _fetch() -> list[dict]:- async with _client(url, headers, use_oauth) as client:+ async with _client(url, headers, use_oauth, **oauth) as client:tools = await client.list_tools()return [t.model_dump(exclude_none = True) for t in tools]@@ -1508,7 +1530,9 @@ def serialize_mcp_server_mutation(handler):# MCP server fields whose change invalidates a server's discovered tools: the endpoint/auth used to probe it (url,# headers, oauth) or whether it's used at all (is_enabled). A rename does not. The update route's eviction and# get_enabled_mcp_tools' mid-probe guard both key off this so they can't drift.-TOOL_CACHE_INVALIDATING_FIELDS = frozenset({"url", "headers_json", "use_oauth", "is_enabled"})+TOOL_CACHE_INVALIDATING_FIELDS = frozenset(+ {"url", "headers_json", "use_oauth", "oauth_client_id", "oauth_client_secret", "is_enabled"}+)def get_cached_tools(server_id: str) -> Optional[list[dict]]:@@ -2114,6 +2138,7 @@ def call_tool_sync(scope: Optional[str] = None,config_check = None,ui_resource_uri: Optional[str] = None,+ **oauth,) -> str:"""Call one MCP tool and return its flattened text/image result. Never raises: every failure comesback as an "Error: ..." string for the model.@@ -2133,7 +2158,7 @@ def call_tool_sync("""async def _one_shot() -> Any:- async with _client(url, headers, use_oauth) as client:+ async with _client(url, headers, use_oauth, **oauth) as client:# Connecting (OAuth included) can outlast an edit or delete of the server row.if config_check is not None and not config_check():raise RuntimeError("MCP server was updated or removed while connecting")@@ -2213,6 +2238,7 @@ def _ui_request_sync(cancel_event = None,scope = None,config_check = None,+ **oauth,) -> Any:"""``dispatch(client)`` on the transport call_tool_sync would pick for this scope."""@@ -2220,7 +2246,7 @@ def _ui_request_sync(# As the session branch: an edit during discovery must not reach the old endpoint.if config_check is not None and not config_check():raise RuntimeError("MCP server was updated or removed during the call")- async with _client(url, headers, use_oauth) as client:+ async with _client(url, headers, use_oauth, **oauth) as client:return await dispatch(client)session_args = (url, headers, label, {}, timeout, cancel_event, scope, config_check, use_oauth)diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 0604a3217cc..76b6945013e 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -76,6 +76,7 @@ from core.inference.mcp_client import (is_studio_decisions,is_stdio,list_tools_async,+ oauth_client_kwargs,parse_server_headers,parse_stdio_command,probe_timeout,@@ -13698,6 +13699,7 @@ async def get_enabled_mcp_tools() -> list[dict]:headers = parse_server_headers(s),timeout = probe_timeout(s["url"], bool(s.get("use_oauth"))),use_oauth = bool(s.get("use_oauth")),+ **oauth_client_kwargs(s),)for s in uncached),@@ -14029,6 +14031,7 @@ def execute_tool(use_oauth = use_oauth,cancel_event = cancel_event,scope = mcp_scope,+ **oauth_client_kwargs(server),config_check = _config_current,ui_resource_uri = tool_ui_resource_uri(mcp_tool_definition(server_id, tool_name)),)diff --git a/studio/backend/models/mcp_servers.py b/studio/backend/models/mcp_servers.pyindex 98b95b2e1b0..17d457f8350 100644--- a/studio/backend/models/mcp_servers.py+++ b/studio/backend/models/mcp_servers.py@@ -20,6 +20,8 @@ class McpServerCreate(BaseModel):headers: Optional[dict[str, str]] = Noneis_enabled: bool = Trueuse_oauth: bool = False+ oauth_client_id: Optional[str] = None+ oauth_client_secret: Optional[str] = Noneimage_input_mappings: list[McpImageInputMapping] = Field(default_factory = list, max_length = 64)@@ -30,6 +32,8 @@ class McpServerUpdate(BaseModel):headers: Optional[dict[str, str]] = Noneis_enabled: Optional[bool] = Noneuse_oauth: Optional[bool] = None+ oauth_client_id: Optional[str] = None+ oauth_client_secret: Optional[str] = Noneimage_input_mappings: Optional[list[McpImageInputMapping]] = Field(None, max_length = 64)@@ -41,6 +45,8 @@ class McpServerResponse(BaseModel):headers: dict[str, str] = Field(default_factory = dict)is_enabled: bool = Trueuse_oauth: bool = False+ oauth_client_id: Optional[str] = None+ has_oauth_client_secret: bool = Falseimage_input_mappings: list[McpImageInputMapping] = Field(default_factory = list)# False when no mapping matches a cached tool schema any more; true while the tools are unknown.image_mappings_active: bool = False@@ -52,6 +58,10 @@ class McpServerTestRequest(BaseModel):url: strheaders: Optional[dict[str, str]] = Noneuse_oauth: bool = False+ oauth_client_id: Optional[str] = None+ oauth_client_secret: Optional[str] = None+ # Edit form: reuse this server's stored secret when the secret field is left blank.+ server_id: Optional[str] = Noneclass BlenderSettings(BaseModel):diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex 5ee07550721..597299a10a1 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -32,6 +32,7 @@ from core.inference.mcp_client import (is_stdio,join_stdio_command,list_tools_async,+ oauth_client_kwargs,parse_server_headers,parse_stdio_command,probe_timeout,@@ -176,6 +177,15 @@ def _image_mappings_active(row: dict) -> bool:)+def _oauth_client(+ client_id: str | None, client_secret: str | None+) -> tuple[str | None, str | None]:+ client_id = (client_id or "").strip() or None+ if client_secret and not client_id:+ raise HTTPException(status_code = 400, detail = "oauth_client_secret requires oauth_client_id")+ return client_id, client_secret or None++def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerResponse:return McpServerResponse(id = row["id"],@@ -185,6 +195,8 @@ def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerResheaders = (parse_server_headers(row) or {}) if include_headers else {},is_enabled = bool(row["is_enabled"]),use_oauth = bool(row.get("use_oauth")),+ oauth_client_id = row.get("oauth_client_id"),+ has_oauth_client_secret = bool(row.get("oauth_client_secret")),image_input_mappings = image_input_mappings(row),image_mappings_active = _image_mappings_active(row),created_at = row["created_at"],@@ -356,6 +368,11 @@ async def create_mcp_server(# OAuth is HTTP-only; force it off for stdio commands so a stale flag can't# push the probe onto the 305s OAuth timeout. Backend enforces this.use_oauth = payload.use_oauth and not is_stdio(url)+ client_id, client_secret = (+ _oauth_client(payload.oauth_client_id, payload.oauth_client_secret)+ if use_oauth+ else (None, None)+ )server_id = uuid.uuid4().hex[:16]mcp_servers_db.create_server(@@ -366,6 +383,8 @@ async def create_mcp_server(is_enabled = payload.is_enabled,use_oauth = use_oauth,image_input_mappings_json = _mappings_json(payload.image_input_mappings),+ oauth_client_id = client_id,+ oauth_client_secret = client_secret,)return _row_to_response(mcp_servers_db.get_server(server_id))@@ -398,9 +417,15 @@ def _changes_from_payload(payload: McpServerUpdate) -> dict:changes["use_oauth"] = payload.use_oauthif "image_input_mappings" in sent:changes["image_input_mappings_json"] = _mappings_json(payload.image_input_mappings)+ if "oauth_client_id" in sent:+ changes["oauth_client_id"] = (payload.oauth_client_id or "").strip() or None+ if "oauth_client_secret" in sent:+ changes["oauth_client_secret"] = payload.oauth_client_secret or None# stdio is OAuth-less: drop a stale OAuth flag when switching to a command.if "url" in changes and is_stdio(changes["url"]):changes["use_oauth"] = False+ if changes.get("use_oauth") is False:+ changes["oauth_client_id"] = changes["oauth_client_secret"] = Nonereturn changes@@ -424,6 +449,13 @@ async def update_mcp_server(status_code = 400,detail = "Use the managed integration setup to configure or enable this server.",)+ client_id = changes.get("oauth_client_id", old.get("oauth_client_id"))+ # A secret belongs to one client at one origin: a new client ID or URL drops it unless replaced.+ if "oauth_client_secret" not in changes and (+ client_id != old.get("oauth_client_id") or changes.get("url", old["url"]) != old["url"]+ ):+ changes["oauth_client_secret"] = None+ _oauth_client(client_id, changes.get("oauth_client_secret", old.get("oauth_client_secret")))if not changes:raise HTTPException(status_code = 400, detail = "No fields to update")# Both directions, so an API key can neither repoint an http row at a command nor edit a stdio row's@@ -439,9 +471,14 @@ async def update_mcp_server(and "headers_json" not in changes):changes["headers_json"] = None- # Clear persisted OAuth tokens when the URL changes or OAuth is disabled+ # Clear persisted OAuth tokens when the URL, the OAuth flag or the client changesif bool(old.get("use_oauth")) and (- ("url" in changes and changes["url"] != old["url"]) or changes.get("use_oauth") is False+ ("url" in changes and changes["url"] != old["url"])+ or changes.get("use_oauth") is False+ or any(+ changes.get(k, old.get(k)) != old.get(k)+ for k in ("oauth_client_id", "oauth_client_secret")+ )):await clear_oauth_tokens_async(old["url"])# That await hands the loop to other requests.@@ -533,6 +570,7 @@ async def refresh_mcp_server_tools(headers = parse_server_headers(server),timeout = probe_timeout(server["url"], use_oauth),use_oauth = use_oauth,+ **oauth_client_kwargs(server),)except Exception as exc: # noqa: BLE001 - surface transport+timeout errors to UIlogger.error(@@ -620,12 +658,22 @@ async def test_mcp_server(require_ui_session_for_local_commands(via_api_key)headers = _normalize_headers(payload.headers)use_oauth = payload.use_oauth and not is_stdio(url)+ client_id, client_secret = _oauth_client(payload.oauth_client_id, payload.oauth_client_secret)+ if use_oauth and payload.server_id and client_id and not client_secret:+ stored = mcp_servers_db.get_server(payload.server_id) or {}+ if stored.get("url") == url and stored.get("oauth_client_id") == client_id:+ client_secret = stored.get("oauth_client_secret")try:tools = await list_tools_async(url = url,headers = headers,timeout = probe_timeout(url, use_oauth),use_oauth = use_oauth,+ **oauth_client_kwargs(+ {"oauth_client_id": client_id, "oauth_client_secret": client_secret}+ if use_oauth+ else {}+ ),)except Exception as exc: # noqa: BLE001logger.error(@@ -681,6 +729,7 @@ async def _warm_tool_cache(server: dict) -> None:headers = parse_server_headers(server),timeout = probe_timeout(url, use_oauth),use_oauth = use_oauth,+ **oauth_client_kwargs(server),)except Exception: # noqa: BLE001 - a probe failure reads as "nothing declared"tools = None@@ -700,6 +749,7 @@ def _ui_call_kwargs(server_id: str, server: dict, thread_id, session_id) -> dict"headers": parse_server_headers(server),"timeout": _UI_TIMEOUT,"use_oauth": bool(server.get("use_oauth")),+ **oauth_client_kwargs(server),# execute_tool's key, so a widget reaches the chat's own stdio subprocess."scope": mcp_session_scope(session_id, thread_id),"config_check": lambda: _row_still_matches(server_id, server),diff --git a/studio/backend/storage/mcp_servers_db.py b/studio/backend/storage/mcp_servers_db.pyindex 484a35659d6..82168b7c4eb 100644--- a/studio/backend/storage/mcp_servers_db.py+++ b/studio/backend/storage/mcp_servers_db.py@@ -34,7 +34,13 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:cols = {r["name"] for r in conn.execute("PRAGMA table_info(mcp_servers)").fetchall()}if "use_oauth" not in cols:conn.execute("ALTER TABLE mcp_servers ADD COLUMN use_oauth INTEGER NOT NULL DEFAULT 0")- for column in ("builtin_id", "builtin_config_json", "image_input_mappings_json"):+ for column in (+ "builtin_id",+ "builtin_config_json",+ "image_input_mappings_json",+ "oauth_client_id",+ "oauth_client_secret",+ ):if column not in cols:conn.execute(f"ALTER TABLE mcp_servers ADD COLUMN {column} TEXT")conn.execute(@@ -75,6 +81,8 @@ def create_server(builtin_id: Optional[str] = None,builtin_config_json: Optional[str] = None,image_input_mappings_json: Optional[str] = None,+ oauth_client_id: Optional[str] = None,+ oauth_client_secret: Optional[str] = None,) -> None:from core.inference.mcp_client import validate_mcp_address@@ -87,8 +95,8 @@ def create_server(INSERT INTO mcp_servers(id, display_name, url, headers_json,is_enabled, use_oauth, created_at, updated_at, builtin_id, builtin_config_json,- image_input_mappings_json)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ image_input_mappings_json, oauth_client_id, oauth_client_secret)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(id,@@ -102,6 +110,8 @@ def create_server(builtin_id,builtin_config_json,image_input_mappings_json,+ oauth_client_id,+ oauth_client_secret,),)conn.commit()diff --git a/studio/backend/tests/test_mcp_preregistered_oauth.py b/studio/backend/tests/test_mcp_preregistered_oauth.pynew file mode 100644index 00000000000..e223c57e830--- /dev/null+++ b/studio/backend/tests/test_mcp_preregistered_oauth.py@@ -0,0 +1,164 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import asyncio+import sqlite3++import pytest+from fastapi import HTTPException+from core.inference import mcp_client+from models.mcp_servers import McpServerCreate, McpServerTestRequest, McpServerUpdate+from routes import mcp_servers as routes+from storage import mcp_servers_db++URL = "https://calendarmcp.googleapis.com/mcp/v1"+CREDS = {"oauth_client_id": "client-id", "oauth_client_secret": "client-secret"}+++def db(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())+ cleared, invalidated = [], []++ async def clear_tokens(url):+ cleared.append(url)++ monkeypatch.setattr(routes, "clear_oauth_tokens_async", clear_tokens)+ monkeypatch.setattr(routes, "invalidate_tool_cache", invalidated.append)+ mcp_servers_db.create_server(+ id = "cal", display_name = "Calendar", url = URL, use_oauth = True, **CREDS+ )+ return cleared, invalidated+++def _update(**fields):+ return asyncio.run(+ routes.update_mcp_server("cal", McpServerUpdate(**fields), current_subject = "u")+ )+++def test_real_fastmcp_oauth_gets_the_preregistered_client(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(mcp_client, "_oauth_token_store", None)+ auth = mcp_client._client(URL, None, use_oauth = True, **CREDS).transport.auth+ assert (auth._client_id, auth._client_secret) == ("client-id", "client-secret")+++def test_list_call_and_widget_paths_forward_the_client(monkeypatch):+ captured = []++ class FakeClient:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_):+ return None++ async def list_tools(self):+ return []++ async def call_tool(self, *_args, **_kwargs):+ return "ok"++ def fake_client(+ url,+ headers,+ use_oauth = False,+ **oauth,+ ):+ captured.append(oauth)+ return FakeClient()++ monkeypatch.setattr(mcp_client, "_client", fake_client)+ asyncio.run(mcp_client.list_tools_async(URL, use_oauth = True, **CREDS))+ mcp_client.call_tool_sync(URL, None, "t", {}, use_oauth = True, **CREDS)+ mcp_client._ui_request_sync(+ URL, None, "r", lambda c: c.list_tools(), timeout = 5, use_oauth = True, **CREDS+ )+ asyncio.run(mcp_client.list_tools_async(URL, use_oauth = True))+ assert captured == [CREDS, CREDS, CREDS, {}]+++def test_stored_client_reaches_chat_and_widget_paths(db):+ row = mcp_servers_db.get_server("cal")+ assert mcp_client.oauth_client_kwargs(row) == CREDS+ assert routes._ui_call_kwargs("cal", row, None, None)["oauth_client_secret"] == "client-secret"+++def test_responses_report_the_secret_without_returning_it(db):+ created = asyncio.run(+ routes.create_mcp_server(+ McpServerCreate(display_name = "Other", url = URL, use_oauth = True, **CREDS),+ current_subject = "u",+ )+ )+ assert created.oauth_client_id == "client-id"+ assert created.has_oauth_client_secret is True+ assert "client-secret" not in created.model_dump_json()+ with pytest.raises(HTTPException, match = "requires oauth_client_id"):+ routes._oauth_client(None, "orphan")+++ "fields",+ [+ {"oauth_client_id": "other-id"},+ {"url": "https://other.example/mcp"},+ {"oauth_client_secret": None},+ ],+)+def test_new_client_id_url_or_removed_secret_drops_secret_and_tokens(db, fields):+ cleared, invalidated = db+ _update(**fields)+ assert mcp_servers_db.get_server("cal")["oauth_client_secret"] is None+ assert cleared == [URL] and invalidated == ["cal"]+++def test_rename_resending_the_same_client_keeps_secret_and_tokens(db):+ cleared, invalidated = db+ _update(display_name = "Renamed", url = URL, use_oauth = True, oauth_client_id = "client-id")+ assert mcp_servers_db.get_server("cal")["oauth_client_secret"] == "client-secret"+ assert cleared == [] and invalidated == []+++def test_secret_rotation_keeps_stored_id_and_disabling_oauth_clears_both(db):+ _update(oauth_client_secret = "rotated")+ row = mcp_servers_db.get_server("cal")+ assert (row["oauth_client_id"], row["oauth_client_secret"]) == ("client-id", "rotated")+ _update(use_oauth = False, oauth_client_id = "client-id")+ row = mcp_servers_db.get_server("cal")+ assert (row["oauth_client_id"], row["oauth_client_secret"]) == (None, None)+++ "url, expected", [(URL, "client-secret"), ("https://attacker.example/mcp", None)]+)+def test_connection_test_reuses_stored_secret_only_for_the_same_url(db, monkeypatch, url, expected):+ captured = {}++ async def fake_list_tools(**kwargs):+ captured.update(kwargs)+ return []++ monkeypatch.setattr(routes, "list_tools_async", fake_list_tools)+ request = McpServerTestRequest(+ server_id = "cal", url = url, use_oauth = True, oauth_client_id = "client-id"+ )+ asyncio.run(routes.test_mcp_server(request, current_subject = "u"))+ assert captured["oauth_client_secret"] == expected+++def test_legacy_database_gains_the_oauth_columns(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())+ path = mcp_servers_db.studio_db_path()+ path.parent.mkdir(parents = True, exist_ok = True)+ with sqlite3.connect(path) as conn:+ conn.execute(+ "CREATE TABLE mcp_servers (id TEXT PRIMARY KEY, display_name TEXT NOT NULL,"+ " url TEXT NOT NULL, headers_json TEXT, is_enabled INTEGER NOT NULL DEFAULT 1,"+ " created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"+ )+ mcp_servers_db.create_server(id = "cal", display_name = "C", url = URL, use_oauth = True, **CREDS)+ assert mcp_client.oauth_client_kwargs(mcp_servers_db.get_server("cal")) == CREDSdiff --git a/studio/frontend/src/features/chat/api/mcp-servers-api.ts b/studio/frontend/src/features/chat/api/mcp-servers-api.tsindex becb4f1590f..ca89cb0874e 100644--- a/studio/frontend/src/features/chat/api/mcp-servers-api.ts+++ b/studio/frontend/src/features/chat/api/mcp-servers-api.ts@@ -25,6 +25,8 @@ export interface McpServerConfig {headers: Record<string, string>;is_enabled: boolean;use_oauth: boolean;+ oauth_client_id?: string | null;+ has_oauth_client_secret?: boolean;image_input_mappings?: McpImageInputMapping[];image_mappings_active?: boolean;created_at: string;@@ -186,6 +188,8 @@ export function createMcpServer(payload: {headers?: Record<string, string>;isEnabled?: boolean;useOauth?: boolean;+ oauthClientId?: string | null;+ oauthClientSecret?: string;imageInputMappings?: McpImageInputMapping[];}): Promise<McpServerConfig> {return trackMcpServerMutation(@@ -197,6 +201,8 @@ export function createMcpServer(payload: {headers: payload.headers ?? null,is_enabled: payload.isEnabled ?? true,use_oauth: payload.useOauth ?? false,+ oauth_client_id: payload.oauthClientId ?? null,+ oauth_client_secret: payload.oauthClientSecret ?? null,image_input_mappings: payload.imageInputMappings ?? [],},}),@@ -212,6 +218,9 @@ export function updateMcpServer(headers?: Record<string, string> | null;isEnabled?: boolean;useOauth?: boolean;+ oauthClientId?: string | null;+ /** omit to keep the stored secret */+ oauthClientSecret?: string;imageInputMappings?: McpImageInputMapping[];},): Promise<McpServerConfig> {@@ -222,6 +231,10 @@ export function updateMcpServer(if (payload.headers !== undefined) body.headers = payload.headers;if (payload.isEnabled !== undefined) body.is_enabled = payload.isEnabled;if (payload.useOauth !== undefined) body.use_oauth = payload.useOauth;+ if (payload.oauthClientId !== undefined)+ body.oauth_client_id = payload.oauthClientId;+ if (payload.oauthClientSecret !== undefined)+ body.oauth_client_secret = payload.oauthClientSecret;if (payload.imageInputMappings !== undefined)body.image_input_mappings = payload.imageInputMappings;return trackMcpServerMutation(@@ -251,6 +264,9 @@ export function testMcpServer(payload: {url: string;headers?: Record<string, string>;useOauth?: boolean;+ oauthClientId?: string | null;+ oauthClientSecret?: string;+ serverId?: string;}): Promise<McpServerProbeResult> {return mcpRequest("/test", {method: "POST",@@ -258,6 +274,9 @@ export function testMcpServer(payload: {url: payload.url,headers: payload.headers ?? null,use_oauth: payload.useOauth ?? false,+ oauth_client_id: payload.oauthClientId ?? null,+ oauth_client_secret: payload.oauthClientSecret ?? null,+ server_id: payload.serverId ?? null,},});}diff --git a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsxindex 14c9c4f35f1..0e8792dde79 100644--- a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx+++ b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx@@ -74,6 +74,8 @@ type FormState = {headers: HeaderRow[];credentialTransport: Exclude<FormTransport, "unknown"> | null;useOauth: boolean;+ oauthClientId: string;+ oauthClientSecret: string;imageInputMappings: McpImageInputMapping[];};@@ -96,6 +98,8 @@ const EMPTY_FORM: FormState = {headers: [],credentialTransport: null,useOauth: false,+ oauthClientId: "",+ oauthClientSecret: "",imageInputMappings: [],};@@ -183,6 +187,17 @@ function formWithAddress(};}+function oauthPayload(form: FormState, stdio: boolean) {+ if (stdio || !form.useOauth) return { useOauth: false };+ return {+ useOauth: true,+ oauthClientId: form.oauthClientId.trim() || null,+ ...(form.oauthClientSecret+ ? { oauthClientSecret: form.oauthClientSecret }+ : {}),+ };+}+function isValidAddress(value: string): boolean {const trimmed = value.trim();if (!trimmed) return false;@@ -503,6 +518,17 @@ export function ChatMcpServersDialog({setForm(EMPTY_FORM);}+ function oauthSecretPlaceholder(): string {+ const saved =+ view.kind === "edit" ? servers.find((s) => s.id === view.id) : undefined;+ if (!saved?.has_oauth_client_secret) return "Optional client secret";+ // The backend drops the stored secret when the client ID or URL changes.+ return form.url.trim() === saved.url &&+ form.oauthClientId.trim() === (saved.oauth_client_id ?? "")+ ? "Leave blank to keep the stored secret"+ : "Re-enter the secret: a new client ID or URL clears the stored one";+ }+async function startEdit(server: McpServerConfig) {const generation = formGenerationRef.current + 1;formGenerationRef.current = generation;@@ -520,6 +546,8 @@ export function ChatMcpServersDialog({headers: headersFromObject(server.headers ?? {}),credentialTransport: isHttpAddress(server.url) ? "http" : "stdio",useOauth: server.use_oauth ?? false,+ oauthClientId: server.oauth_client_id ?? "",+ oauthClientSecret: "",imageInputMappings: server.image_input_mappings ?? [],};@@ -649,7 +677,8 @@ export function ChatMcpServersDialog({const result = await testMcpServer({url,headers: headersToObject(form.headers),- useOauth: stdio ? false : form.useOauth,+ serverId: view.kind === "edit" ? view.id : undefined,+ ...oauthPayload(form, stdio),});if (formGenerationRef.current !== generation) return;if (result.ok) {@@ -717,7 +746,7 @@ export function ChatMcpServersDialog({displayName: trimmedName,url,headers: headers ?? null,- useOauth: stdio ? false : form.useOauth,+ ...oauthPayload(form, stdio),imageInputMappings: form.imageInputMappings,});if (formGenerationRef.current !== generation) return;@@ -728,7 +757,7 @@ export function ChatMcpServersDialog({displayName: trimmedName,url,headers: headers,- useOauth: stdio ? false : form.useOauth,+ ...oauthPayload(form, stdio),});if (formGenerationRef.current !== generation) return;toast.success("MCP server added");@@ -1067,6 +1096,43 @@ export function ChatMcpServersDialog({</div>)}+ {form.transport === "http" && form.useOauth && (+ <div className="grid gap-3 rounded-md border p-3">+ <div className="grid gap-2">+ <Label htmlFor="mcp-oauth-client-id">OAuth client ID</Label>+ <Input+ id="mcp-oauth-client-id"+ value={form.oauthClientId}+ onChange={(e) =>+ setForm((prev) => ({+ ...prev,+ oauthClientId: e.target.value,+ }))+ }+ placeholder="Optional pre-registered client ID"+ />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="mcp-oauth-client-secret">+ OAuth client secret+ </Label>+ <Input+ id="mcp-oauth-client-secret"+ type="password"+ autoComplete="new-password"+ value={form.oauthClientSecret}+ onChange={(e) =>+ setForm((prev) => ({+ ...prev,+ oauthClientSecret: e.target.value,+ }))+ }+ placeholder={oauthSecretPlaceholder()}+ />+ </div>+ </div>+ )}+<McpImageMappingskey={view.kind === "edit" ? view.id : "new"}serverId={view.kind === "edit" ? view.id : undefined}