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: only a UI session may define a local (stdio) MCP command (#8550)
Daniel Han7dfee7e6ee41
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.pyindex 768a15a836b..810509d2a19 100644--- a/studio/backend/auth/authentication.py+++ b/studio/backend/auth/authentication.py@@ -186,6 +186,21 @@ async def authenticated_via_api_key(return bool(credentials and credentials.credentials.startswith(API_KEY_PREFIX))+def require_ui_session_for_local_commands(via_api_key: bool) -> None:+ """Refuse an sk-unsloth API key that asks to define a local (stdio) MCP command.++ stdio MCP runs a command on this host as the backend user, outside the+ python/terminal sandbox, so only a UI session may choose what runs. API keys+ keep http(s) MCP, and stdio servers the owner already configured.+ """+ if via_api_key:+ raise HTTPException(+ status_code = status.HTTP_403_FORBIDDEN,+ detail = "Local (stdio) MCP servers can only be configured from the Unsloth UI, "+ "not with an API key. Use an http:// or https:// MCP server instead.",+ )++async def allow_ambient_hf_token(via_api_key: bool = Depends(authenticated_via_api_key)) -> bool:"""Whether a download this caller starts may fall back to the backend's own HF_TOKEN.diff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.pyindex 9770e88b7f5..3c2545bf19a 100644--- a/studio/backend/core/data_recipe/service.py+++ b/studio/backend/core/data_recipe/service.py@@ -166,6 +166,18 @@ def _validate_recipe_runtime_support(recipe: dict[str, Any], model_providers: liraise ValueError("Add a Provider connection block before running this recipe.")+def recipe_has_stdio_mcp(recipe: dict[str, Any]) -> bool:+ """True when the recipe asks for a local (stdio) MCP provider, i.e. a command+ this host would run. Routes gate on it to keep that behind a UI session."""+ providers = recipe.get("mcp_providers") or []+ if not isinstance(providers, list):+ return False+ return any(+ isinstance(provider, dict) and provider.get("provider_type") == "stdio"+ for provider in providers+ )++def build_mcp_providers(recipe: dict[str, Any]) -> list:from data_designer.config.mcp import LocalStdioMCPProvider, MCPProvider # pyright: ignore[reportMissingImports]diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.pyindex 7fdf0abadaa..8555914e36e 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -7,12 +7,16 @@ from __future__ import annotationsimport copyfrom datetime import datetime, timedelta, timezone-from typing import Any, Optional+from typing import Annotated, Any, Optionalfrom urllib.parse import urlparsefrom fastapi import APIRouter, Depends, HTTPException, Query, Request-from auth.authentication import get_current_credential+from auth.authentication import (+ authenticated_via_api_key,+ get_current_credential,+ require_ui_session_for_local_commands,+)from auth.storage import CredentialRotatedfrom fastapi.responses import JSONResponse, StreamingResponsefrom pydantic import ValidationError@@ -22,6 +26,7 @@ from core.data_recipe.huggingface import (publish_recipe_dataset,)from core.data_recipe.jobs import get_job_manager+from core.data_recipe.service import recipe_has_stdio_mcpfrom loggers import get_loggerfrom models.data_recipe import (JobCreateResponse,@@ -34,6 +39,10 @@ from utils.utils import safe_error_detail, safe_curated_detail, log_and_http_errlogger = get_logger(__name__)router = APIRouter()+# A stdio provider is a command this host would run, so only a UI session may+# supply one. Annotated, not a Depends default, so a direct call gets False.+ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]+def _resolve_local_v1_endpoint(request: Request) -> str:"""Return the loopback /v1 URL for the actual backend listen port.@@ -387,10 +396,13 @@ def create_job(payload: RecipePayload,request: Request,credential: tuple = Depends(get_current_credential),+ via_api_key: ViaApiKey = False,):recipe = payload.recipeif not recipe.get("columns"):raise HTTPException(status_code = 400, detail = "Recipe must include columns.")+ if recipe_has_stdio_mcp(recipe):+ require_ui_session_for_local_commands(via_api_key)run: dict[str, Any] = payload.run or {}run.pop("artifact_path", None)diff --git a/studio/backend/routes/data_recipe/mcp.py b/studio/backend/routes/data_recipe/mcp.pyindex 78a39877ccc..e5822d4e743 100644--- a/studio/backend/routes/data_recipe/mcp.py+++ b/studio/backend/routes/data_recipe/mcp.py@@ -6,10 +6,15 @@from __future__ import annotationsfrom collections import defaultdict+from typing import Annotated-from fastapi import APIRouter+from fastapi import APIRouter, Depends-from core.data_recipe.service import build_mcp_providers+from auth.authentication import (+ authenticated_via_api_key,+ require_ui_session_for_local_commands,+)+from core.data_recipe.service import build_mcp_providers, recipe_has_stdio_mcpfrom loggers import get_loggerfrom models.data_recipe import (McpToolsListRequest,@@ -21,9 +26,18 @@ from utils.utils import safe_error_detaillogger = get_logger(__name__)router = APIRouter()+# A stdio provider is a command this host would run, so only a UI session may+# supply one. Annotated, not a Depends default, so a direct call gets False.+ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]+@router.post("/mcp/tools", response_model = McpToolsListResponse)-def list_mcp_tools(payload: McpToolsListRequest) -> McpToolsListResponse:+def list_mcp_tools(+ payload: McpToolsListRequest, via_api_key: ViaApiKey = False+) -> McpToolsListResponse:+ # Caller-supplied and probed immediately, so gate before any is built.+ if recipe_has_stdio_mcp({"mcp_providers": payload.mcp_providers}):+ require_ui_session_for_local_commands(via_api_key)try:from data_designer.engine.mcp import io as mcp_ioexcept ImportError as exc:diff --git a/studio/backend/routes/data_recipe/validate.py b/studio/backend/routes/data_recipe/validate.pyindex ffe36ba69ee..09ed0d38e9b 100644--- a/studio/backend/routes/data_recipe/validate.py+++ b/studio/backend/routes/data_recipe/validate.py@@ -5,13 +5,18 @@from __future__ import annotations-from typing import Any+from typing import Annotated, Any-from fastapi import APIRouter+from fastapi import APIRouter, Depends+from auth.authentication import (+ authenticated_via_api_key,+ require_ui_session_for_local_commands,+)from core.data_recipe.service import (build_config_builder,create_data_designer,+ recipe_has_stdio_mcp,validate_recipe,)from loggers import get_logger@@ -21,6 +26,10 @@ from utils.utils import safe_error_detail, safe_curated_detail, log_and_http_errlogger = get_logger(__name__)router = APIRouter()+# A stdio provider is a command this host would run, so only a UI session may+# supply one. Annotated, not a Depends default, so a direct call gets False.+ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]+_GITHUB_VALIDATE_NOTE = ("Recipe shape is valid. GitHub access and rate limits are checked when the run starts.")@@ -132,13 +141,15 @@ def _patch_local_providers(recipe: dict[str, Any]) -> None:@router.post("/validate", response_model = ValidateResponse)-def validate(payload: RecipePayload) -> ValidateResponse:+def validate(payload: RecipePayload, via_api_key: ViaApiKey = False) -> ValidateResponse:recipe = payload.recipeif not recipe.get("columns"):return ValidateResponse(valid = False,errors = [ValidateError(message = "Recipe must include columns.")],)+ if recipe_has_stdio_mcp(recipe):+ require_ui_session_for_local_commands(via_api_key)_patch_local_providers(recipe)diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex dc018d163a0..eca2b9a72b0 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -4,12 +4,17 @@import asyncioimport jsonimport uuid+from typing import Annotatedfrom urllib.parse import urlparseimport structlogfrom fastapi import APIRouter, Depends, HTTPException-from auth.authentication import get_current_subject+from auth.authentication import (+ authenticated_via_api_key,+ get_current_subject,+ require_ui_session_for_local_commands,+)from core.inference.mcp_client import (TOOL_CACHE_INVALIDATING_FIELDS,cache_tools,@@ -41,6 +46,11 @@ logger = structlog.get_logger(__name__)router = APIRouter()+# Only a UI session may define a local command; API keys keep http(s) MCP.+# Annotated, not a Depends default: these routes are also called directly by the+# tests, where a Depends object is truthy and would read as "API key".+ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]+def _looks_like_command(value: str) -> bool:"""Whitespace is a one-way signal: a URL can't hold an unencoded space, so@@ -128,12 +138,16 @@ async def list_mcp_servers(current_subject: str = Depends(get_current_subject)):@router.post("/", response_model = McpServerResponse, status_code = 201)async def create_mcp_server(- payload: McpServerCreate, current_subject: str = Depends(get_current_subject)+ payload: McpServerCreate,+ current_subject: str = Depends(get_current_subject),+ via_api_key: ViaApiKey = False,):display_name = (payload.display_name or "").strip()if not display_name:raise HTTPException(status_code = 400, detail = "display_name must not be empty")url = _validate_url(payload.url)+ if is_stdio(url):+ require_ui_session_for_local_commands(via_api_key)headers = _normalize_headers(payload.headers)# 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.@@ -184,6 +198,7 @@ async def update_mcp_server(server_id: str,payload: McpServerUpdate,current_subject: str = Depends(get_current_subject),+ via_api_key: ViaApiKey = False,):old = mcp_servers_db.get_server(server_id)if not old:@@ -191,6 +206,11 @@ async def update_mcp_server(changes = _changes_from_payload(payload)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 env/name/enabled flag. Before every side effect, so a+ # refusal leaves the row, its OAuth tokens, cache and sessions untouched.+ if is_stdio(old["url"]) or is_stdio(changes.get("url", old["url"])):+ require_ui_session_for_local_commands(via_api_key)# headers == HTTP headers (remote) or env vars (stdio). On a transport-type# switch with no new headers, drop the old ones so env secrets aren't# re-sent as HTTP headers (or vice versa).@@ -207,6 +227,14 @@ async def update_mcp_server(("url" in changes and changes["url"] != old["url"]) or changes.get("use_oauth") is False):await clear_oauth_tokens_async(old["url"])+ # That await hands the loop to other requests, so re-read and re-gate+ # before writing: a UI conversion to stdio landing in the window would+ # otherwise let an API key's headers become the command's env.+ current = mcp_servers_db.get_server(server_id)+ if current is not None and (+ is_stdio(current["url"]) or is_stdio(changes.get("url", current["url"]))+ ):+ require_ui_session_for_local_commands(via_api_key)mcp_servers_db.update_server(server_id, changes)# A new endpoint/auth makes cached tools wrong and disabling makes them unreachable, so drop# them and let the next send re-probe; a rename leaves them valid. Live stdio sessions for the@@ -234,15 +262,21 @@ async def delete_mcp_server(server_id: str, current_subject: str = Depends(get_c@router.post("/{server_id}/refresh", response_model = McpServerProbeResult)async def refresh_mcp_server_tools(- server_id: str, current_subject: str = Depends(get_current_subject)+ server_id: str,+ current_subject: str = Depends(get_current_subject),+ via_api_key: ViaApiKey = False,):server = mcp_servers_db.get_server(server_id)if not server:raise HTTPException(status_code = 404, detail = "MCP server not found")# Refresh uses the stored address, so re-check the stdio gate here too: a# stdio row from a desktop DB must not spawn on a hosted/network host.- if is_stdio(server["url"]) and not stdio_mcp_enabled():- raise HTTPException(status_code = 400, detail = "stdio MCP servers are disabled on this host")+ if is_stdio(server["url"]):+ require_ui_session_for_local_commands(via_api_key)+ if not stdio_mcp_enabled():+ raise HTTPException(+ status_code = 400, detail = "stdio MCP servers are disabled on this host"+ )use_oauth = bool(server.get("use_oauth"))try:@@ -281,7 +315,9 @@ async def refresh_mcp_server_tools(@router.post("/import", response_model = McpServerImportResult)async def import_mcp_servers(- payload: McpServerImportRequest, current_subject: str = Depends(get_current_subject)+ payload: McpServerImportRequest,+ current_subject: str = Depends(get_current_subject),+ via_api_key: ViaApiKey = False,):"""Bulk-register servers from a standard mcpServers JSON config (issue#5936). Each entry rides the existing create path: _validate_url applies@@ -297,6 +333,10 @@ async def import_mcp_servers(for entry in entries:try:url = _validate_url(entry.url)+ # Per entry, so an API-key import of a mixed config still creates its+ # http entries and reports the stdio ones.+ if is_stdio(url):+ require_ui_session_for_local_commands(via_api_key)except HTTPException as exc:errors.append(f"{entry.display_name}: {exc.detail}")continue@@ -321,12 +361,18 @@ async def import_mcp_servers(@router.post("/test", response_model = McpServerProbeResult)async def test_mcp_server(- payload: McpServerTestRequest, current_subject: str = Depends(get_current_subject)+ payload: McpServerTestRequest,+ current_subject: str = Depends(get_current_subject),+ via_api_key: ViaApiKey = False,):# URL/header validation must surface as 400 like create/update so the# frontend's create-form pre-flight gets the same error semantics as the# save call. Only catch transport/timeout errors below.url = _validate_url(payload.url)+ # Caller-supplied and unstored, so the gate has to land before+ # list_tools_async -- after it the process has already started.+ if is_stdio(url):+ require_ui_session_for_local_commands(via_api_key)headers = _normalize_headers(payload.headers)try:tools = await list_tools_async(diff --git a/studio/backend/tests/test_mcp_stdio_api_key_gate.py b/studio/backend/tests/test_mcp_stdio_api_key_gate.pynew file mode 100644index 00000000000..888f8bd361e--- /dev/null+++ b/studio/backend/tests/test_mcp_stdio_api_key_gate.py@@ -0,0 +1,417 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""stdio MCP runs a local command as the backend user, outside the sandbox, and+sk-unsloth API keys authenticate the same routes the UI uses. So these pin that+only a UI session may define a command, and that http(s) MCP stays usable from an+API key. list_tools_async is stubbed to fail if called, so a gate placed after the+probe would not pass.+"""++import asyncio+import os++import pytest+from fastapi import HTTPException++from core.inference import mcp_client+from storage import mcp_servers_db+from utils import host_policy+++def _reset_db(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ mcp_client.invalidate_tool_cache()++[email protected](autouse = True)+def _isolate_stdio_env():+ """apply_stdio_mcp_loopback_default() mutates os.environ plus a module flag+ monkeypatch cannot roll back; snapshot and restore both."""+ saved = os.environ.get("UNSLOTH_STUDIO_ALLOW_STDIO_MCP")+ host_policy._reset_loopback_default_state()+ yield+ host_policy._reset_loopback_default_state()+ if saved is None:+ os.environ.pop("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", None)+ else:+ os.environ["UNSLOTH_STUDIO_ALLOW_STDIO_MCP"] = saved+++def stdio_on(monkeypatch):+ """The worst case for this gate: a host where stdio is allowed."""+ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")+++def no_probe(monkeypatch):+ """Fail loudly if a refused request still reached the transport."""+ import routes.mcp_servers as routes_mcp++ async def _never(**kwargs):+ raise AssertionError("the stdio command must not be probed")++ monkeypatch.setattr(routes_mcp, "list_tools_async", _never)+++STDIO_CMD = "/bin/sh -c id"+++# ── /test: an unstored, caller-supplied command ─────────────────────+++def test_test_endpoint_refuses_stdio_from_api_key(tmp_path, monkeypatch, stdio_on, no_probe):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerTestRequest++ _reset_db(tmp_path, monkeypatch)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ routes_mcp.test_mcp_server(+ McpServerTestRequest(url = STDIO_CMD),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert exc.value.status_code == 403+++def test_test_endpoint_allows_http_from_api_key(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerTestRequest++ _reset_db(tmp_path, monkeypatch)+ seen = {}++ async def _probe(**kwargs):+ seen.update(kwargs)+ return []++ monkeypatch.setattr(routes_mcp, "list_tools_async", _probe)+ res = asyncio.run(+ routes_mcp.test_mcp_server(+ McpServerTestRequest(url = "https://example.com/mcp"),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert res.ok is True+ assert seen["url"] == "https://example.com/mcp"+++# ── create / update ─────────────────────────────────────────────────+++def test_create_refuses_stdio_from_api_key_and_writes_nothing(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerCreate++ _reset_db(tmp_path, monkeypatch)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ routes_mcp.create_mcp_server(+ McpServerCreate(display_name = "Local", url = STDIO_CMD),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert exc.value.status_code == 403+ assert mcp_servers_db.list_servers() == []+++def test_create_allows_http_from_api_key(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerCreate++ _reset_db(tmp_path, monkeypatch)+ resp = asyncio.run(+ routes_mcp.create_mcp_server(+ McpServerCreate(display_name = "Remote", url = "https://example.com/mcp"),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert resp.url == "https://example.com/mcp"+++def test_update_refuses_http_to_stdio_conversion_from_api_key(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerUpdate++ _reset_db(tmp_path, monkeypatch)+ mcp_servers_db.create_server(id = "s1", display_name = "A", url = "https://a/mcp")+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ routes_mcp.update_mcp_server(+ "s1",+ McpServerUpdate(url = STDIO_CMD),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert exc.value.status_code == 403+ assert mcp_servers_db.get_server("s1")["url"] == "https://a/mcp"+++ "payload_kwargs",+ [+ {"display_name": "Renamed"},+ {"is_enabled": True},+ {"headers": {"SECRET": "x"}},+ ],+)+def test_update_refuses_any_edit_of_a_stdio_row_from_api_key(+ tmp_path, monkeypatch, stdio_on, payload_kwargs+):+ """Not just the address: the env vars, the name and the enabled flag all+ change what runs or how, so an API key may not touch a stdio row at all."""+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerUpdate++ _reset_db(tmp_path, monkeypatch)+ mcp_servers_db.create_server(id = "s1", display_name = "Local", url = STDIO_CMD)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ routes_mcp.update_mcp_server(+ "s1",+ McpServerUpdate(**payload_kwargs),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert exc.value.status_code == 403+ assert mcp_servers_db.get_server("s1")["display_name"] == "Local"+++def test_update_regates_after_the_oauth_clear_await(tmp_path, monkeypatch, stdio_on):+ """clear_oauth_tokens_async awaits, handing the loop to other requests. If+ the owner converts the row to stdio in that window, the write that follows+ must not land the API key's headers as the command's env."""+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerUpdate++ _reset_db(tmp_path, monkeypatch)+ mcp_servers_db.create_server(+ id = "s1", display_name = "Remote", url = "https://a/mcp", is_enabled = True, use_oauth = True+ )++ async def _clear_then_convert(url):+ await asyncio.sleep(0)+ mcp_servers_db.update_server("s1", {"url": STDIO_CMD, "use_oauth": False})++ monkeypatch.setattr(routes_mcp, "clear_oauth_tokens_async", _clear_then_convert)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ routes_mcp.update_mcp_server(+ "s1",+ McpServerUpdate(headers = {"LD_PRELOAD": "/tmp/evil.so"}, use_oauth = False),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert exc.value.status_code == 403+ assert mcp_servers_db.get_server("s1")["headers_json"] is None+++def test_update_allows_http_row_from_api_key(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerUpdate++ _reset_db(tmp_path, monkeypatch)+ mcp_servers_db.create_server(id = "s1", display_name = "A", url = "https://a/mcp")+ resp = asyncio.run(+ routes_mcp.update_mcp_server(+ "s1",+ McpServerUpdate(display_name = "B"),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert resp.display_name == "B"+++# ── refresh ─────────────────────────────────────────────────────────+++def test_refresh_refuses_stored_stdio_from_api_key(tmp_path, monkeypatch, stdio_on, no_probe):+ import routes.mcp_servers as routes_mcp++ _reset_db(tmp_path, monkeypatch)+ mcp_servers_db.create_server(id = "stdio1", display_name = "Local", url = STDIO_CMD, is_enabled = True)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ routes_mcp.refresh_mcp_server_tools(+ "stdio1", current_subject = "api-key-user", via_api_key = True+ )+ )+ assert exc.value.status_code == 403+++def test_refresh_allows_http_from_api_key(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp++ _reset_db(tmp_path, monkeypatch)+ mcp_servers_db.create_server(id = "s1", display_name = "A", url = "https://a/mcp")++ async def _probe(**kwargs):+ return []++ monkeypatch.setattr(routes_mcp, "list_tools_async", _probe)+ res = asyncio.run(+ routes_mcp.refresh_mcp_server_tools("s1", current_subject = "api-key-user", via_api_key = True)+ )+ assert res.ok is True+++# ── import: per-entry, so a mixed config still lands its http rows ──+++_MIXED_CONFIG = {+ "mcpServers": {+ "remote": {"url": "https://example.com/mcp"},+ "local": {"command": "/bin/sh", "args": ["-c", "id"]},+ }+}+++def test_import_from_api_key_keeps_http_and_reports_stdio(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerImportRequest++ _reset_db(tmp_path, monkeypatch)+ res = asyncio.run(+ routes_mcp.import_mcp_servers(+ McpServerImportRequest(config = _MIXED_CONFIG),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert [s.display_name for s in res.created] == ["remote"]+ assert any("local" in err for err in res.errors)+ assert [row["url"] for row in mcp_servers_db.list_servers()] == ["https://example.com/mcp"]++ # Re-importing the same config is idempotent: the http entry is now a skip,+ # the stdio entry is still an error, and no row is duplicated.+ again = asyncio.run(+ routes_mcp.import_mcp_servers(+ McpServerImportRequest(config = _MIXED_CONFIG),+ current_subject = "api-key-user",+ via_api_key = True,+ )+ )+ assert again.created == []+ assert again.skipped == ["remote"]+ assert any("local" in err for err in again.errors)+ assert len(mcp_servers_db.list_servers()) == 1+++# ── a UI session keeps every existing stdio behaviour ───────────────+++def test_ui_session_still_creates_and_imports_stdio(tmp_path, monkeypatch, stdio_on):+ import routes.mcp_servers as routes_mcp+ from models.mcp_servers import McpServerCreate, McpServerImportRequest, McpServerUpdate++ _reset_db(tmp_path, monkeypatch)+ # A command distinct from the one in _MIXED_CONFIG, so the import below is a+ # real create rather than the url-dedupe skip.+ own_cmd = "/bin/echo hello"+ created = asyncio.run(+ routes_mcp.create_mcp_server(+ McpServerCreate(display_name = "Local", url = own_cmd),+ current_subject = "owner",+ via_api_key = False,+ )+ )+ assert created.url == own_cmd+ renamed = asyncio.run(+ routes_mcp.update_mcp_server(+ created.id,+ McpServerUpdate(display_name = "Local FS"),+ current_subject = "owner",+ via_api_key = False,+ )+ )+ assert renamed.display_name == "Local FS"+ res = asyncio.run(+ routes_mcp.import_mcp_servers(+ McpServerImportRequest(config = _MIXED_CONFIG),+ current_subject = "owner",+ via_api_key = False,+ )+ )+ assert res.errors == []+ assert sorted(s.display_name for s in res.created) == ["local", "remote"]+++def test_default_is_ui_session_so_direct_calls_are_unaffected():+ """The dependency is Annotated with a plain False default; a bare+ `= Depends(...)` default would be a truthy object and 403 every direct+ call (the existing suites call these handlers directly)."""+ import inspect++ import routes.mcp_servers as routes_mcp++ for name in (+ "create_mcp_server",+ "update_mcp_server",+ "refresh_mcp_server_tools",+ "import_mcp_servers",+ "test_mcp_server",+ ):+ param = inspect.signature(getattr(routes_mcp, name)).parameters["via_api_key"]+ assert param.default is False, name+++# ── data recipe: the same primitive, same gate ──────────────────────+++_STDIO_PROVIDER = {+ "name": "local",+ "provider_type": "stdio",+ "command": "/bin/sh",+ "args": ["-c", "id"],+}+_HTTP_PROVIDER = {"name": "remote", "provider_type": "http", "url": "https://example.com/mcp"}+_STDIO_RECIPE = {"columns": [{"name": "a"}], "mcp_providers": [_STDIO_PROVIDER]}+++def test_recipe_has_stdio_mcp():+ from core.data_recipe.service import recipe_has_stdio_mcp++ assert recipe_has_stdio_mcp({"mcp_providers": [_STDIO_PROVIDER]}) is True+ assert recipe_has_stdio_mcp({"mcp_providers": [_HTTP_PROVIDER]}) is False+ assert recipe_has_stdio_mcp({}) is False+ assert recipe_has_stdio_mcp({"mcp_providers": "nonsense"}) is False+++def test_data_recipe_mcp_tools_refuses_stdio_from_api_key():+ from models.data_recipe import McpToolsListRequest+ from routes.data_recipe.mcp import list_mcp_tools++ with pytest.raises(HTTPException) as exc:+ list_mcp_tools(McpToolsListRequest(mcp_providers = [_STDIO_PROVIDER]), via_api_key = True)+ assert exc.value.status_code == 403+++def test_data_recipe_job_refuses_stdio_recipe_from_api_key():+ from models.data_recipe import RecipePayload+ from routes.data_recipe.jobs import create_job++ payload = RecipePayload(recipe = _STDIO_RECIPE)+ with pytest.raises(HTTPException) as exc:+ create_job(payload, request = None, credential = ("u", None), via_api_key = True)+ assert exc.value.status_code == 403+++def test_data_recipe_validate_refuses_stdio_recipe_from_api_key():+ from models.data_recipe import RecipePayload+ from routes.data_recipe.validate import validate++ payload = RecipePayload(recipe = _STDIO_RECIPE)+ with pytest.raises(HTTPException) as exc:+ validate(payload, via_api_key = True)+ assert exc.value.status_code == 403