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: add ordered arguments to mcp server settings (#9943)

Etherl259a589fc1dc
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index ba1a95152b5..4aa93d7ea11 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -550,6 +550,21 @@ jobs:
mkdir -p logs/playwright_extra
python tests/studio/playwright_extra_ui.py
+ - name: MCP arguments end to end (Playwright)
+ if: matrix.shard == 'extra'
+ env:
+ BASE_URL: http://127.0.0.1:18894
+ STUDIO_OLD_PW: ${{ env.STUDIO_EXTRA_OLD_PW }}
+ STUDIO_NEW_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}
+ PW_ART_DIR: logs/playwright_mcp_arguments
+ STUDIO_UI_STRICT: '1'
+ run: |
+ mkdir -p logs/playwright_mcp_arguments
+ studio_home="${UNSLOTH_STUDIO_HOME:-$HOME/.unsloth/studio}"
+ export STUDIO_MCP_PYTHON="$studio_home/unsloth_studio/bin/python"
+ test -x "$STUDIO_MCP_PYTHON"
+ python tests/studio/playwright_mcp_arguments.py
+
- name: Per-chat settings persistence (Playwright)
if: matrix.shard == 'extra'
env:
@@ -819,6 +834,7 @@ jobs:
logs/playwright
logs/playwright-permissions-*
logs/playwright_extra
+ logs/playwright_mcp_arguments
logs/playwright_thread_settings
logs/playwright_fontscale
logs/playwright_update_banner
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index d8b36dfbcad..c8aedcd34fe 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -13,6 +13,7 @@ import os
import re
import shlex
import shutil
+import subprocess
import sys
import threading
import time
@@ -27,6 +28,8 @@ from loggers import get_logger
logger = get_logger(__name__)
MCP_TOOL_PREFIX = "mcp__"
+_WINDOWS_BATCH_ALWAYS_UNSAFE_ARGUMENT_CHARS = frozenset('%!"\r\n')
+_WINDOWS_BATCH_UNQUOTED_UNSAFE_ARGUMENT_CHARS = frozenset("&|<>^()")
# A failed probe isn't cached (a recovered server must come back), but it's
# recorded so a down server isn't re-probed -- and the chat send re-hung for
@@ -72,7 +75,10 @@ def _split_windows_command_line(address: str) -> list[str]:
backslashes = 0
i += 1
continue
- if ch.isspace() and not in_quotes:
+ # subprocess.list2cmdline() implements the MS C runtime grammar: only
+ # space and tab delimit arguments. Other Unicode/control whitespace is
+ # ordinary argument data and must not be split here.
+ if ch in (" ", "\t") and not in_quotes:
if backslashes:
current.extend("\\" * backslashes)
arg_started = True
@@ -82,7 +88,7 @@ def _split_windows_command_line(address: str) -> list[str]:
current = []
arg_started = False
i += 1
- while i < len(address) and address[i].isspace():
+ while i < len(address) and address[i] in (" ", "\t"):
i += 1
continue
if backslashes:
@@ -121,11 +127,20 @@ def join_stdio_command(parts: list[str]) -> str:
one string in the url field. Windows uses list2cmdline so spaced/backslash
paths round-trip through the posix=False quote-strip; posix uses shlex."""
if sys.platform == "win32":
- import subprocess
return subprocess.list2cmdline(parts)
return shlex.join(parts)
+def _windows_batch_argument_is_unsafe(argument: str) -> bool:
+ if _WINDOWS_BATCH_ALWAYS_UNSAFE_ARGUMENT_CHARS.intersection(argument):
+ return True
+ serialized = subprocess.list2cmdline([argument])
+ is_quoted = serialized.startswith('"') and serialized.endswith('"')
+ return not is_quoted and bool(
+ _WINDOWS_BATCH_UNQUOTED_UNSAFE_ARGUMENT_CHARS.intersection(argument)
+ )
+
+
def _stdio_log_id(url: str) -> str:
"""A non-secret label for logs. stdio commands can embed credentials in argv
(e.g. ``npx server --token sk-...``), so never log the raw command; use the
@@ -309,6 +324,13 @@ def _stdio_env(headers: Optional[dict], command: Optional[str] = None) -> Option
"""Process env for a stdio server: its own vars, plus the managed Node bin dir
on PATH so ``npx ...`` servers spawn on hosts with no usable system Node."""
env = dict(headers or {})
+ for key, value in env.items():
+ if not isinstance(key, str) or not isinstance(value, str):
+ raise ValueError("stdio environment names and values must be strings")
+ if "\x00" in key or "\x00" in value:
+ raise ValueError("stdio environment must not contain NUL characters")
+ if "=" in key:
+ raise ValueError("stdio environment variable names must not contain '='")
key = _path_key(env)
base = env.get(key)
if isinstance(base, str) and not base:
@@ -335,14 +357,54 @@ def _stdio_argv(parts: list, env: Optional[dict]) -> list:
"""argv with argv[0] resolved against the child's PATH. Windows resolves the
command against the parent environment before ``env`` applies, so a managed-only
``npx`` has to be handed over as a full path."""
- path = (env or {}).get(_path_key(env or {}))
+ path_key = _path_key(env or {})
+ explicit_path = env is not None and path_key in env
+ path = (env or {}).get(path_key)
if not isinstance(path, str):
path = os.environ.get("PATH", "")
try:
resolved = shutil.which(parts[0], path = path)
except OSError:
resolved = None
- return [resolved or parts[0], *parts[1:]]
+ if _IS_WINDOWS and resolved is None and explicit_path and not os.path.dirname(parts[0]):
+ raise ValueError(f"Cannot find {parts[0]!r} on the MCP server's configured PATH")
+ executable = resolved or parts[0]
+ if _IS_WINDOWS:
+ suffix = os.path.splitext(executable)[1].lower()
+ if suffix in {".cmd", ".bat"} and _launcher_name(executable) in {"npm", "npx"}:
+ launcher_dir = os.path.dirname(executable)
+ cli = os.path.join(
+ launcher_dir,
+ "node_modules",
+ "npm",
+ "bin",
+ f"{_launcher_name(executable)}-cli.js",
+ )
+ sibling_node = os.path.join(launcher_dir, "node.exe")
+ try:
+ node = (
+ sibling_node
+ if os.path.isfile(sibling_node)
+ else shutil.which("node", path = path)
+ )
+ cli_exists = os.path.isfile(cli)
+ except OSError:
+ node = None
+ cli_exists = False
+ if node and cli_exists:
+ # bypass cmd.exe so shell metacharacters remain literal argv.
+ return [node, cli, *parts[1:]]
+ raise ValueError(
+ f"Cannot launch {executable!r} without its Node executable and npm CLI script"
+ )
+ if suffix in {".cmd", ".bat"} and any(
+ _windows_batch_argument_is_unsafe(argument) for argument in parts[1:]
+ ):
+ raise ValueError(
+ "Windows batch launchers cannot safely preserve these MCP command arguments; "
+ "invoke the executable directly, or use node.exe with the JavaScript entry point"
+ )
+ return [executable, *parts[1:]]
def _client(
diff --git a/studio/backend/core/inference/mcp_config_import.py b/studio/backend/core/inference/mcp_config_import.py
index 534ed84c1de..f1bf086d9d3 100644
--- a/studio/backend/core/inference/mcp_config_import.py
+++ b/studio/backend/core/inference/mcp_config_import.py
@@ -97,7 +97,7 @@ def _parse_entry(name: str, spec: object) -> tuple[Optional[ParsedMcpEntry], Opt
return None, f"{label}: import cannot preserve {', '.join(unsupported)}."
if spec.get("oauth") is not None:
return None, f"{label}: 'oauth' is only supported for remote servers."
- args = spec.get("args") or []
+ args = spec["args"] if "args" in spec else []
if not isinstance(args, list) or not all(isinstance(a, _SCALAR) for a in args):
return None, f"{label}: 'args' must be a list of strings."
env = spec.get("env")
diff --git a/studio/backend/models/mcp_servers.py b/studio/backend/models/mcp_servers.py
index 606c2423bfd..354356164ae 100644
--- a/studio/backend/models/mcp_servers.py
+++ b/studio/backend/models/mcp_servers.py
@@ -3,7 +3,7 @@
from typing import Optional
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, StrictStr
class McpServerCreate(BaseModel):
@@ -40,6 +40,19 @@ class McpServerTestRequest(BaseModel):
use_oauth: bool = False
+class McpStdioDecodeRequest(BaseModel):
+ url: StrictStr
+
+
+class McpStdioCommand(BaseModel):
+ command: StrictStr
+ arguments: list[StrictStr] = Field(default_factory = list)
+
+
+class McpStdioEncodeResponse(BaseModel):
+ url: str
+
+
class McpServerProbeResult(BaseModel):
ok: bool
tool_count: int = 0
diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.py
index d1c2c6b526a..5b9117ed96b 100644
--- a/studio/backend/routes/mcp_servers.py
+++ b/studio/backend/routes/mcp_servers.py
@@ -3,6 +3,7 @@
import asyncio
import json
+import sys
import uuid
from typing import Annotated
from urllib.parse import urlparse
@@ -23,6 +24,7 @@ from core.inference.mcp_client import (
close_stdio_sessions,
invalidate_tool_cache,
is_stdio,
+ join_stdio_command,
list_tools_async,
parse_server_headers,
parse_stdio_command,
@@ -41,6 +43,9 @@ from models.mcp_servers import (
McpServerResponse,
McpServerTestRequest,
McpServerUpdate,
+ McpStdioCommand,
+ McpStdioDecodeRequest,
+ McpStdioEncodeResponse,
)
from storage import mcp_servers_db
from utils.utils import safe_curated_detail, log_and_http_error
@@ -63,34 +68,49 @@ def _looks_like_command(value: str) -> bool:
return any(ch.isspace() for ch in value)
+def _normalize_stdio_command(url: str) -> str:
+ raw = url or ""
+ trimmed = raw.strip()
+ if not trimmed:
+ raise HTTPException(status_code = 400, detail = "command must not be empty")
+ # Leading whitespace is executable-field padding. At the other end, only
+ # space/tab delimit arguments on Windows. POSIX quoting protects whitespace.
+ normalized = raw.lstrip().rstrip(" \t") if sys.platform == "win32" else trimmed
+ try:
+ parts = parse_stdio_command(normalized)
+ except ValueError as exc:
+ raise log_and_http_error(
+ exc,
+ 400,
+ "Invalid command. Check quoting and try again.",
+ event = "mcp_servers.invalid_command",
+ log = logger,
+ )
+ if not parts or not parts[0].strip():
+ raise HTTPException(status_code = 400, detail = "command must not be empty")
+ if any("\x00" in part for part in parts):
+ raise HTTPException(
+ status_code = 400,
+ detail = "command and arguments must not contain NUL characters",
+ )
+ if "://" in parts[0]:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Enter an http(s):// URL, or a local command whose "
+ "first token is an executable (not a URL).",
+ )
+ return normalized
+
+
def _validate_url(url: str) -> str:
- trimmed = (url or "").strip()
+ raw = url or ""
+ trimmed = raw.strip()
if not trimmed:
raise HTTPException(status_code = 400, detail = "url must not be empty")
- # When stdio is enabled, a non-HTTP value is a local command (reuses this
- # field so stdio servers ride existing CRUD/storage).
+ # Non-HTTP values reuse the URL field for local commands. Syntax validation
+ # is policy-free, but persistence and execution stay behind the stdio gate.
if stdio_mcp_enabled() and is_stdio(trimmed):
- try:
- parts = parse_stdio_command(trimmed)
- except ValueError as exc:
- raise log_and_http_error(
- exc,
- 400,
- "Invalid command. Check quoting and try again.",
- event = "mcp_servers.invalid_command",
- log = logger,
- )
- if not parts or not parts[0].strip():
- raise HTTPException(status_code = 400, detail = "command must not be empty")
- if "://" in parts[0]:
- # A URL-scheme first token is a mistyped URL, not a command. Reject
- # cleanly instead of exec-ing it (mirrors the frontend check).
- raise HTTPException(
- status_code = 400,
- detail = "Enter an http(s):// URL, or a local command whose "
- "first token is an executable (not a URL).",
- )
- return trimmed
+ return _normalize_stdio_command(raw)
parsed = urlparse(trimmed)
if parsed.scheme not in ("http", "https"):
if _looks_like_command(trimmed):
@@ -114,7 +134,18 @@ def _normalize_headers(headers: dict[str, str] | None) -> dict[str, str] | None:
for raw_key, value in headers.items():
key = str(raw_key).strip()
if key:
- out[key] = str(value)
+ normalized_value = str(value)
+ if "\x00" in key or "\x00" in normalized_value:
+ raise HTTPException(
+ status_code = 400,
+ detail = "headers and environment variables must not contain NUL characters",
+ )
+ if "=" in key:
+ raise HTTPException(
+ status_code = 400,
+ detail = "header and environment variable names must not contain '='",
+ )
+ out[key] = normalized_value
return out or None
@@ -131,6 +162,40 @@ def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerRes
)
[email protected]("/stdio/decode", response_model = McpStdioCommand)
+def decode_stdio_command(
+ payload: McpStdioDecodeRequest,
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: ViaApiKey = False,
+):
+ require_ui_session_for_local_commands(via_api_key)
+ if not is_stdio(payload.url.strip()):
+ raise HTTPException(status_code = 400, detail = "HTTP(S) MCP servers do not have arguments")
+ url = _normalize_stdio_command(payload.url)
+ parts = parse_stdio_command(url)
+ return McpStdioCommand(command = parts[0], arguments = parts[1:])
+
+
[email protected]("/stdio/encode", response_model = McpStdioEncodeResponse)
+def encode_stdio_command(
+ payload: McpStdioCommand,
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: ViaApiKey = False,
+):
+ require_ui_session_for_local_commands(via_api_key)
+ command = payload.command.strip()
+ if not command:
+ raise HTTPException(status_code = 400, detail = "command must not be empty")
+ if "://" in command:
+ raise HTTPException(
+ status_code = 400,
+ detail = "command must be a local executable, not a URL",
+ )
+ url = join_stdio_command([command, *payload.arguments])
+ _normalize_stdio_command(url)
+ return McpStdioEncodeResponse(url = url)
+
+
# FastAPI offloads sync reads; mutations stay on-loop to preserve atomic sequences.
@router.get("/", response_model = list[McpServerResponse])
def list_mcp_servers(
@@ -353,13 +418,13 @@ async def import_mcp_servers(
# http entries and reports the stdio ones.
if is_stdio(url):
require_ui_session_for_local_commands(via_api_key)
+ headers = _normalize_headers(entry.headers)
except HTTPException as exc:
errors.append(f"{entry.display_name}: {exc.detail}")
continue
if url in seen_urls:
skipped.append(entry.display_name)
continue
- headers = _normalize_headers(entry.headers)
server_id = uuid.uuid4().hex[:16]
mcp_servers_db.create_server(
id = server_id,
@@ -390,12 +455,13 @@ async def test_mcp_server(
if is_stdio(url):
require_ui_session_for_local_commands(via_api_key)
headers = _normalize_headers(payload.headers)
+ use_oauth = payload.use_oauth and not is_stdio(url)
try:
tools = await list_tools_async(
url = url,
headers = headers,
- timeout = probe_timeout(url, payload.use_oauth),
- use_oauth = payload.use_oauth,
+ timeout = probe_timeout(url, use_oauth),
+ use_oauth = use_oauth,
)
except Exception as exc: # noqa: BLE001
logger.error(
diff --git a/studio/backend/tests/fixtures/mcp_argument_echo_server.py b/studio/backend/tests/fixtures/mcp_argument_echo_server.py
new file mode 100644
index 00000000000..6440c155849
--- /dev/null
+++ b/studio/backend/tests/fixtures/mcp_argument_echo_server.py
@@ -0,0 +1,39 @@
+# 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 json
+import os
+import sys
+
+from fastmcp import FastMCP
+
+
+launch_log = os.environ.get("UNSLOTH_MCP_ARGUMENT_LOG")
+if launch_log:
+ with open(launch_log, "a", encoding = "utf-8") as log:
+ log.write(
+ json.dumps(
+ {
+ "arguments": sys.argv[1:],
+ "marker": os.environ.get("UNSLOTH_MCP_ARGUMENT_MARKER"),
+ }
+ )
+ + "\n"
+ )
+
+
+server = FastMCP("argument echo")
+
+
+def launch_state() -> str:
+ return json.dumps(
+ {
+ "arguments": sys.argv[1:],
+ "marker": os.environ.get("UNSLOTH_MCP_ARGUMENT_MARKER"),
+ }
+ )
+
+
+if __name__ == "__main__":
+ server.run(transport = "stdio", show_banner = False)
diff --git a/studio/backend/tests/test_mcp_config_import.py b/studio/backend/tests/test_mcp_config_import.py
index 4082733490f..30365d3025d 100644
--- a/studio/backend/tests/test_mcp_config_import.py
+++ b/studio/backend/tests/test_mcp_config_import.py
@@ -41,6 +41,16 @@ def _disable(monkeypatch):
["uvx", "some-server", "--flag"],
["/usr/local/bin/my-server"],
["mcp-server-sqlite"],
+ [
+ "python",
+ "--url",
+ "https://example.com/value",
+ "a b",
+ "O'Reilly",
+ 'say "hello"',
+ "trailing\\",
+ "",
+ ],
],
)
def test_join_parse_roundtrip_posix(monkeypatch, parts):
@@ -79,6 +89,15 @@ def test_join_parse_roundtrip_posix(monkeypatch, parts):
["node", "'draft'"],
["node", "'open", "close'"],
["node", ""],
+ [
+ "python",
+ "--url",
+ "https://example.com/value",
+ "a b",
+ 'say "hello"',
+ "C:\\path with spaces\\trailing\\",
+ "",
+ ],
],
)
def test_join_parse_roundtrip_win32(monkeypatch, parts):
@@ -87,6 +106,24 @@ def test_join_parse_roundtrip_win32(monkeypatch, parts):
assert mcp_client.parse_stdio_command(joined) == parts
+ "value",
+ [
+ pytest.param("a\u00a0b", id = "nbsp"),
+ pytest.param("a\nb", id = "newline"),
+ pytest.param("a\rb", id = "carriage-return"),
+ pytest.param("a\vb", id = "vertical-tab"),
+ pytest.param("a\fb", id = "form-feed"),
+ pytest.param("a\u2003b", id = "em-space"),
+ ],
+)
+def test_join_parse_roundtrip_win32_preserves_non_delimiter_whitespace(monkeypatch, value):
+ monkeypatch.setattr(sys, "platform", "win32")
+ parts = ["python", "--value", value, 'say "hello"', "a b", ""]
+ joined = mcp_client.join_stdio_command(parts)
+ assert mcp_client.parse_stdio_command(joined) == parts
+
+
def test_parse_rejects_manual_single_quoted_windows_executable(monkeypatch):
monkeypatch.setattr(sys, "platform", "win32")
command = "'C:\\Program Files\\node\\node.exe' server.js"
@@ -134,6 +171,14 @@ def test_parse_stdio_entry():
assert mcp_client.parse_stdio_command(entry.url) == ["npx", "-y", "server", "/tmp"]
[email protected]("args", [None, "", 0, False, {}])
+def test_parse_rejects_explicit_non_list_args(args):
+ entries, errors = parse_mcp_config({"mcpServers": {"bad": {"command": "python", "args": args}}})
+
+ assert entries == []
+ assert errors == ["bad: 'args' must be a list of strings."]
+
+
def test_parse_remote_entry():
cfg = {
"mcpServers": {
diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.py
index 3895d844dea..f0beeee284a 100644
--- a/studio/backend/tests/test_mcp_servers.py
+++ b/studio/backend/tests/test_mcp_servers.py
@@ -1,8 +1,11 @@
# 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 json
+
import pytest
from fastapi import HTTPException
+from pydantic import ValidationError
from storage import mcp_servers_db
@@ -74,6 +77,17 @@ def test_validate_url_accepts_http_and_https():
assert _validate_url("http://example.com/mcp") == "http://example.com/mcp"
assert _validate_url("https://example.com/mcp") == "https://example.com/mcp"
assert _validate_url(" https://example.com/mcp ") == "https://example.com/mcp"
+ assert _validate_url("\n https://example.com/mcp \u2003") == "https://example.com/mcp"
+
+
+def test_validate_url_stdio_keeps_posix_outer_normalization(monkeypatch):
+ import sys
+
+ import routes.mcp_servers as routes_mcp
+
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ assert routes_mcp._validate_url("\n python --flag \u2003") == "python --flag"
@pytest.mark.parametrize("bad", ["", " ", "ftp://x", "http://", "noscheme.com"])
@@ -84,6 +98,322 @@ def test_validate_url_rejects_bad(bad):
assert exc.value.status_code == 400
+def test_stdio_command_codec_roundtrip_preserves_order_empty_and_url_argument(monkeypatch):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpStdioCommand, McpStdioDecodeRequest
+
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ payload = McpStdioCommand(
+ command = "python",
+ arguments = ["-m", "mod", "--name", "a b", "", "https://example.com/value"],
+ )
+ encoded = routes_mcp.encode_stdio_command(payload, current_subject = "u")
+ decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = encoded.url), current_subject = "u"
+ )
+
+ assert decoded.command == payload.command
+ assert decoded.arguments == payload.arguments
+ assert McpStdioCommand(command = "python").arguments == []
+
+
+def test_stdio_command_codec_strips_only_executable_outer_padding(monkeypatch):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpStdioCommand, McpStdioDecodeRequest
+
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ arguments = [" keep outer spaces ", "\nkeep control whitespace\n", ""]
+ encoded = routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = " python ", arguments = arguments), current_subject = "u"
+ )
+ decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = encoded.url), current_subject = "u"
+ )
+
+ assert decoded.command == "python"
+ assert decoded.arguments == arguments
+
+
+ "final_argument",
+ [
+ pytest.param("\n", id = "newline"),
+ pytest.param("\r", id = "carriage-return"),
+ pytest.param("\v", id = "vertical-tab"),
+ pytest.param("\f", id = "form-feed"),
+ pytest.param("\u00a0", id = "nbsp"),
+ pytest.param("\u2003", id = "em-space"),
+ ],
+)
+def test_stdio_command_codec_windows_preserves_final_whitespace_argument_end_to_end(
+ tmp_path, monkeypatch, final_argument
+):
+ import asyncio
+ import sys
+
+ import fastmcp
+ from fastmcp.client import transports
+
+ from core.inference import mcp_client
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import (
+ McpServerCreate,
+ McpServerTestRequest,
+ McpServerUpdate,
+ McpStdioCommand,
+ McpStdioDecodeRequest,
+ )
+
+ _reset_db(tmp_path, monkeypatch)
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ monkeypatch.setattr(mcp_client, "stdio_mcp_enabled", lambda: True)
+ monkeypatch.setattr(routes_mcp, "close_stdio_sessions", lambda *args: None)
+
+ probed_urls: list[str] = []
+
+ async def capture_probe(**kwargs):
+ probed_urls.append(kwargs["url"])
+ return []
+
+ monkeypatch.setattr(routes_mcp, "list_tools_async", capture_probe)
+
+ encoded = routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = "python", arguments = [final_argument]),
+ current_subject = "u",
+ )
+ decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = encoded.url), current_subject = "u"
+ )
+
+ assert encoded.url.endswith(final_argument)
+ assert decoded.arguments == [final_argument]
+
+ probe = asyncio.run(
+ routes_mcp.test_mcp_server(McpServerTestRequest(url = encoded.url), current_subject = "u")
+ )
+ assert probe.ok is True
+ assert probed_urls == [encoded.url]
+
+ created = asyncio.run(
+ routes_mcp.create_mcp_server(
+ McpServerCreate(display_name = "created", url = encoded.url),
+ current_subject = "u",
+ )
+ )
+ assert created.url == encoded.url
+ assert mcp_servers_db.get_server(created.id)["url"] == encoded.url
+ created_decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = created.url), current_subject = "u"
+ )
+ assert created_decoded.arguments == [final_argument]
+
+ seed = asyncio.run(
+ routes_mcp.create_mcp_server(
+ McpServerCreate(display_name = "updated", url = "python seed"),
+ current_subject = "u",
+ )
+ )
+ updated = asyncio.run(
+ routes_mcp.update_mcp_server(
+ seed.id,
+ McpServerUpdate(url = encoded.url),
+ current_subject = "u",
+ )
+ )
+ assert updated.url == encoded.url
+ assert mcp_servers_db.get_server(seed.id)["url"] == encoded.url
+ updated_decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = updated.url), current_subject = "u"
+ )
+ assert updated_decoded.arguments == [final_argument]
+
+ captured_transport = {}
+
+ class CapturingStdioTransport:
+ def __init__(self, **kwargs):
+ captured_transport.update(kwargs)
+
+ monkeypatch.setattr(fastmcp, "Client", lambda transport: transport)
+ monkeypatch.setattr(transports, "StdioTransport", CapturingStdioTransport)
+ monkeypatch.setattr(mcp_client, "_stdio_argv", lambda parts, env: parts)
+ mcp_client._client(updated.url, None)
+ assert captured_transport["command"] == "python"
+ assert captured_transport["args"] == [final_argument]
+ assert captured_transport["keep_alive"] is False
+
+
+def test_stdio_command_codec_is_stateless_and_never_probes(monkeypatch):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpStdioCommand, McpStdioDecodeRequest
+
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+
+ def _never(*args, **kwargs):
+ raise AssertionError("codec must not access storage or transport")
+
+ monkeypatch.setattr(routes_mcp, "list_tools_async", _never)
+ monkeypatch.setattr(mcp_servers_db, "list_servers", _never)
+ monkeypatch.setattr(mcp_servers_db, "create_server", _never)
+ encoded = routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = "python", arguments = ["-m", "mod"]),
+ current_subject = "u",
+ )
+ decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = encoded.url), current_subject = "u"
+ )
+ assert (decoded.command, decoded.arguments) == ("python", ["-m", "mod"])
+
+
+def test_stdio_command_codec_remains_available_when_execution_is_disabled(monkeypatch):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpStdioCommand, McpStdioDecodeRequest
+
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: False)
+ encoded = routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = "python", arguments = ["a b", ""]),
+ current_subject = "u",
+ )
+ decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = encoded.url), current_subject = "u"
+ )
+
+ assert (decoded.command, decoded.arguments) == ("python", ["a b", ""])
+
+
+ ("operation", "detail"),
+ [
+ ("blank", "command must not be empty"),
+ ("url", "local executable"),
+ ("http_arguments", "local executable"),
+ ("remote_decode", "do not have arguments"),
+ ("malformed_decode", "Invalid command"),
+ ],
+)
+def test_stdio_command_codec_rejects_invalid_input_before_probe(monkeypatch, operation, detail):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpStdioCommand, McpStdioDecodeRequest
+
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+
+ async def _never(**kwargs):
+ raise AssertionError("invalid codec input must not be probed")
+
+ monkeypatch.setattr(routes_mcp, "list_tools_async", _never)
+ with pytest.raises(HTTPException) as exc:
+ if operation == "blank":
+ routes_mcp.encode_stdio_command(McpStdioCommand(command = " "), current_subject = "u")
+ elif operation in {"url", "http_arguments"}:
+ arguments = ["--flag"] if operation == "http_arguments" else []
+ routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = " https://example.com/mcp ", arguments = arguments),
+ current_subject = "u",
+ )
+ elif operation == "remote_decode":
+ routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = "https://example.com/mcp"), current_subject = "u"
+ )
+ else:
+ routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = 'python "unterminated'), current_subject = "u"
+ )
+ assert exc.value.status_code == 400
+ assert detail in str(exc.value.detail)
+
+
[email protected]("bad", [1, True, None, {"value": "x"}])
+def test_stdio_command_codec_rejects_non_string_arguments(bad):
+ from models.mcp_servers import McpStdioCommand
+ with pytest.raises(ValidationError):
+ McpStdioCommand.model_validate({"command": "python", "arguments": [bad]})
+
+
+ "payload",
+ [
+ pytest.param({"command": "py\u0000thon", "arguments": []}, id = "command"),
+ pytest.param({"command": "python", "arguments": ["a\u0000b"]}, id = "argument"),
+ ],
+)
+def test_stdio_command_codec_rejects_json_nul(payload, monkeypatch):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpStdioCommand
+
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ command = McpStdioCommand.model_validate_json(json.dumps(payload))
+
+ with pytest.raises(HTTPException) as exc:
+ routes_mcp.encode_stdio_command(command, current_subject = "u")
+
+ assert exc.value.status_code == 400
+ assert "NUL" in str(exc.value.detail)
+
+
+def test_stdio_raw_nul_is_rejected_before_route_side_effects(tmp_path, monkeypatch):
+ import asyncio
+
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import (
+ McpServerCreate,
+ McpServerImportRequest,
+ McpServerTestRequest,
+ McpServerUpdate,
+ McpStdioDecodeRequest,
+ )
+
+ _reset_db(tmp_path, monkeypatch)
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ raw = "python a\x00b"
+ side_effects: list[str] = []
+
+ async def unexpected_probe(**kwargs):
+ side_effects.append("probe")
+ return []
+
+ monkeypatch.setattr(routes_mcp, "list_tools_async", unexpected_probe)
+ monkeypatch.setattr(
+ routes_mcp, "invalidate_tool_cache", lambda *args: side_effects.append("invalidate")
+ )
+ monkeypatch.setattr(
+ routes_mcp, "close_stdio_sessions", lambda *args: side_effects.append("close")
+ )
+
+ with pytest.raises(HTTPException):
+ routes_mcp.decode_stdio_command(McpStdioDecodeRequest(url = raw), current_subject = "u")
+ with pytest.raises(HTTPException):
+ asyncio.run(
+ routes_mcp.create_mcp_server(
+ McpServerCreate(display_name = "bad", url = raw), current_subject = "u"
+ )
+ )
+ assert mcp_servers_db.list_servers() == []
+
+ mcp_servers_db.create_server(id = "seed", display_name = "seed", url = "python ok")
+ with pytest.raises(HTTPException):
+ asyncio.run(
+ routes_mcp.update_mcp_server("seed", McpServerUpdate(url = raw), current_subject = "u")
+ )
+ assert mcp_servers_db.get_server("seed")["url"] == "python ok"
+
+ with pytest.raises(HTTPException):
+ asyncio.run(routes_mcp.test_mcp_server(McpServerTestRequest(url = raw), current_subject = "u"))
+
+ imported = asyncio.run(
+ routes_mcp.import_mcp_servers(
+ McpServerImportRequest(
+ config = {"mcpServers": {"bad": {"command": "python", "args": ["a\x00b"]}}}
+ ),
+ current_subject = "u",
+ )
+ )
+ assert imported.created == []
+ assert len(imported.errors) == 1
+ assert "NUL" in imported.errors[0]
+ assert [row["id"] for row in mcp_servers_db.list_servers()] == ["seed"]
+ assert side_effects == []
+
+
def test_normalize_headers():
from routes.mcp_servers import _normalize_headers
@@ -94,6 +424,80 @@ def test_normalize_headers():
assert _normalize_headers({" ": "x"}) is None
+ "headers",
+ [
+ pytest.param({"BAD\x00NAME": "value"}, id = "nul-name"),
+ pytest.param({"NAME": "bad\x00value"}, id = "nul-value"),
+ pytest.param({"BAD=NAME": "value"}, id = "equals-name"),
+ ],
+)
+def test_invalid_headers_and_environment_are_rejected_before_side_effects(
+ headers, tmp_path, monkeypatch
+):
+ import asyncio
+
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import (
+ McpServerCreate,
+ McpServerImportRequest,
+ McpServerTestRequest,
+ McpServerUpdate,
+ )
+
+ _reset_db(tmp_path, monkeypatch)
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ probes: list[str] = []
+
+ async def unexpected_probe(**kwargs):
+ probes.append("probe")
+ return []
+
+ monkeypatch.setattr(routes_mcp, "list_tools_async", unexpected_probe)
+ with pytest.raises(HTTPException):
+ asyncio.run(
+ routes_mcp.create_mcp_server(
+ McpServerCreate(display_name = "bad", url = "python server.py", headers = headers),
+ current_subject = "u",
+ )
+ )
+ assert mcp_servers_db.list_servers() == []
+
+ mcp_servers_db.create_server(id = "seed", display_name = "seed", url = "python server.py")
+ with pytest.raises(HTTPException):
+ asyncio.run(
+ routes_mcp.update_mcp_server(
+ "seed", McpServerUpdate(headers = headers), current_subject = "u"
+ )
+ )
+ assert mcp_servers_db.get_server("seed")["headers_json"] is None
+
+ with pytest.raises(HTTPException):
+ asyncio.run(
+ routes_mcp.test_mcp_server(
+ McpServerTestRequest(url = "python server.py", headers = headers),
+ current_subject = "u",
+ )
+ )
+
+ imported = asyncio.run(
+ routes_mcp.import_mcp_servers(
+ McpServerImportRequest(
+ config = {
+ "mcpServers": {
+ "bad": {"command": "python", "args": ["server.py"], "env": headers}
+ }
+ }
+ ),
+ current_subject = "u",
+ )
+ )
+ assert imported.created == []
+ assert len(imported.errors) == 1
+ assert [row["id"] for row in mcp_servers_db.list_servers()] == ["seed"]
+ assert probes == []
+
+
def test_changes_from_payload_tristate_headers():
from routes.mcp_servers import _changes_from_payload
from models.mcp_servers import McpServerUpdate
@@ -943,6 +1347,66 @@ def test_update_stdio_command_change_closes_session(tmp_path, monkeypatch):
assert len(closed) == 1
+def test_stdio_arguments_update_preserves_untouched_bytes_then_invalidates_once(
+ tmp_path, monkeypatch
+):
+ import asyncio
+ import json
+
+ from core.inference import mcp_client
+ from models.mcp_servers import McpServerUpdate, McpStdioCommand
+ import routes.mcp_servers as routes_mcp
+
+ _reset_db(tmp_path, monkeypatch)
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ invalidated: list[str] = []
+ closed: list[tuple] = []
+ monkeypatch.setattr(routes_mcp, "invalidate_tool_cache", invalidated.append)
+ monkeypatch.setattr(routes_mcp, "close_stdio_sessions", lambda *args: closed.append(args))
+ cached = _one_tool()
+ monkeypatch.setattr(mcp_client, "_tool_cache", {"s1": cached})
+
+ original_url = "python -m mod"
+ env = {"API_KEY": "secret"}
+ mcp_servers_db.create_server(
+ id = "s1",
+ display_name = "A",
+ url = original_url,
+ headers_json = json.dumps(env),
+ is_enabled = True,
+ )
+ asyncio.run(
+ routes_mcp.update_mcp_server(
+ "s1",
+ McpServerUpdate(display_name = "B", url = original_url, headers = env),
+ current_subject = "u",
+ )
+ )
+ assert mcp_servers_db.get_server("s1")["url"] == original_url
+ assert mcp_client.get_cached_tools("s1") == cached
+ assert invalidated == []
+ assert closed == []
+
+ encoded = routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = "python", arguments = ["-m", "mod", "--name", "a b", ""]),
+ current_subject = "u",
+ )
+ asyncio.run(
+ routes_mcp.update_mcp_server("s1", McpServerUpdate(url = encoded.url), current_subject = "u")
+ )
+ assert mcp_servers_db.get_server("s1")["url"] == encoded.url
+ assert mcp_client.parse_stdio_command(encoded.url) == [
+ "python",
+ "-m",
+ "mod",
+ "--name",
+ "a b",
+ "",
+ ]
+ assert invalidated == ["s1"]
+ assert closed == [(original_url, env)]
+
+
def test_update_disable_evicts_tool_cache(tmp_path, monkeypatch):
"""Disabling a server must drop its cached tools, not leave them unread."""
import asyncio
diff --git a/studio/backend/tests/test_mcp_stdio_api_key_gate.py b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
index fb247820cf3..d5ac9e39652 100644
--- a/studio/backend/tests/test_mcp_stdio_api_key_gate.py
+++ b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
@@ -59,6 +59,36 @@ def no_probe(monkeypatch):
STDIO_CMD = "/bin/sh -c id"
+# ── stdio form codec: command material is UI-session-only ──────────
+
+
[email protected]("operation", ["encode", "decode"])
+def test_stdio_command_codec_refuses_api_key_before_work(
+ monkeypatch, stdio_on, no_probe, operation
+):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpStdioCommand, McpStdioDecodeRequest
+
+ def _never(*args, **kwargs):
+ raise AssertionError("refused codec request must not access storage")
+
+ monkeypatch.setattr(mcp_servers_db, "list_servers", _never)
+ with pytest.raises(HTTPException) as exc:
+ if operation == "encode":
+ routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = "python", arguments = ["--token", "secret"]),
+ current_subject = "api-key-user",
+ via_api_key = True,
+ )
+ else:
+ routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = "python --token secret"),
+ current_subject = "api-key-user",
+ via_api_key = True,
+ )
+ assert exc.value.status_code == 403
+
+
# ── /test: an unstored, caller-supplied command ─────────────────────
@@ -370,6 +400,8 @@ def test_default_is_ui_session_so_direct_calls_are_unaffected():
"refresh_mcp_server_tools",
"import_mcp_servers",
"test_mcp_server",
+ "decode_stdio_command",
+ "encode_stdio_command",
):
param = inspect.signature(getattr(routes_mcp, name)).parameters["via_api_key"]
assert param.default is False, name
diff --git a/studio/backend/tests/test_mcp_stdio_improvements.py b/studio/backend/tests/test_mcp_stdio_improvements.py
index 745c2cc447c..0bcd109fb2b 100644
--- a/studio/backend/tests/test_mcp_stdio_improvements.py
+++ b/studio/backend/tests/test_mcp_stdio_improvements.py
@@ -46,6 +46,39 @@ def test_client_builds_stdio_when_enabled_without_spawning(monkeypatch):
assert client is not None
+def test_client_builds_stdio_with_encoded_arguments_without_shell(monkeypatch):
+ import fastmcp
+ from fastmcp.client import transports
+ from models.mcp_servers import McpStdioCommand
+ import routes.mcp_servers as routes_mcp
+
+ _enable(monkeypatch)
+ captured = {}
+
+ class CapturingStdioTransport:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ monkeypatch.setattr(fastmcp, "Client", lambda transport: transport)
+ monkeypatch.setattr(transports, "StdioTransport", CapturingStdioTransport)
+ monkeypatch.setattr(mcp_client, "_stdio_argv", lambda parts, env: parts)
+
+ encoded = routes_mcp.encode_stdio_command(
+ McpStdioCommand(
+ command = " python ",
+ arguments = ["-m", "mod", "--name", "a b", "", " keep padding "],
+ ),
+ current_subject = "u",
+ )
+ mcp_client._client(encoded.url, {"API_KEY": "secret"})
+
+ assert captured["command"] == "python"
+ assert captured["args"] == ["-m", "mod", "--name", "a b", "", " keep padding "]
+ assert captured["env"]["API_KEY"] == "secret"
+ assert captured["keep_alive"] is False
+ assert set(captured) == {"command", "args", "env", "keep_alive"}
+
+
def test_client_http_unaffected_by_gate(monkeypatch):
_disable(monkeypatch)
assert mcp_client._client("https://example.com/mcp", None) is not None
@@ -85,6 +118,30 @@ def test_create_keeps_oauth_for_http(tmp_path, monkeypatch):
assert resp.use_oauth is True
+def test_connection_test_forces_oauth_off_for_stdio(monkeypatch):
+ import routes.mcp_servers as routes_mcp
+ from models.mcp_servers import McpServerTestRequest
+
+ _enable(monkeypatch)
+ captured = {}
+
+ async def capture_probe(**kwargs):
+ captured.update(kwargs)
+ return []
+
+ monkeypatch.setattr(routes_mcp, "list_tools_async", capture_probe)
+ result = asyncio.run(
+ routes_mcp.test_mcp_server(
+ McpServerTestRequest(url = "python server.py", use_oauth = True),
+ current_subject = "u",
+ )
+ )
+
+ assert result.ok is True
+ assert captured["use_oauth"] is False
+ assert captured["timeout"] == mcp_client.probe_timeout("python server.py", False)
+
+
def test_update_url_to_stdio_clears_oauth(tmp_path, monkeypatch):
import routes.mcp_servers as routes_mcp
from models.mcp_servers import McpServerUpdate
diff --git a/studio/backend/tests/test_mcp_stdio_node_path.py b/studio/backend/tests/test_mcp_stdio_node_path.py
index 2fda2409148..921dd0ef341 100644
--- a/studio/backend/tests/test_mcp_stdio_node_path.py
+++ b/studio/backend/tests/test_mcp_stdio_node_path.py
@@ -9,6 +9,7 @@ Run from studio/backend: python -m pytest tests/test_mcp_stdio_node_path.py -q
import os
import shutil
import sys
+from pathlib import Path
import pytest
@@ -104,9 +105,23 @@ def test_stdio_env_is_none_without_managed_node_or_vars(tmp_path, monkeypatch):
assert mcp_client._stdio_env(None) is None
+ "environment",
+ [
+ pytest.param({"BAD\x00NAME": "value"}, id = "nul-name"),
+ pytest.param({"NAME": "bad\x00value"}, id = "nul-value"),
+ pytest.param({"BAD=NAME": "value"}, id = "equals-name"),
+ ],
+)
+def test_stdio_env_rejects_invalid_legacy_values(environment):
+ with pytest.raises(ValueError):
+ mcp_client._stdio_env(environment, "python")
+
+
def test_client_passes_node_path_to_transport(managed_node, monkeypatch):
monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")
monkeypatch.setenv("PATH", "/usr/bin")
+ _make_executable(managed_node, "npx")
client = mcp_client._client("npx -y @modelcontextprotocol/server-filesystem /tmp", None)
assert client.transport.env["PATH"].split(os.pathsep)[0] == str(managed_node)
@@ -115,23 +130,39 @@ def _make_executable(bin_dir, name):
"""A stub the platform's own PATH lookup will accept (.cmd via PATHEXT on Windows)."""
path = bin_dir / (f"{name}.cmd" if os.name == "nt" else name)
path.write_text("")
- if os.name != "nt":
+ if os.name == "nt" and name in ("npm", "npx"):
+ (bin_dir / "node.exe").write_text("")
+ cli = bin_dir / "node_modules" / "npm" / "bin" / f"{name}-cli.js"
+ cli.parent.mkdir(parents = True, exist_ok = True)
+ cli.write_text("")
+ elif os.name != "nt":
path.chmod(0o755)
return path
+def _expected_node_launcher_argv(launcher, arguments):
+ if os.name != "nt":
+ return [str(launcher), *arguments]
+ bin_dir = launcher.parent
+ cli = bin_dir / "node_modules" / "npm" / "bin" / f"{launcher.stem}-cli.js"
+ return [str(bin_dir / "node.exe"), str(cli), *arguments]
+
+
def test_stdio_argv_resolves_managed_npx(managed_node):
npx = _make_executable(managed_node, "npx")
env = mcp_client._stdio_env(None)
argv = mcp_client._stdio_argv(["npx", "-y", "pkg"], env)
- assert os.path.samefile(argv[0], npx)
- assert argv[1:] == ["-y", "pkg"]
+ assert argv == _expected_node_launcher_argv(npx, ["-y", "pkg"])
def test_stdio_argv_keeps_unresolvable_command(managed_node):
- argv = mcp_client._stdio_argv(
- ["definitely-not-on-path-9304", "-y"], mcp_client._stdio_env(None)
- )
+ parts = ["definitely-not-on-path-9304", "-y"]
+ env = mcp_client._stdio_env(None)
+ if os.name == "nt":
+ with pytest.raises(ValueError, match = "configured PATH"):
+ mcp_client._stdio_argv(parts, env)
+ return
+ argv = mcp_client._stdio_argv(parts, env)
assert argv == ["definitely-not-on-path-9304", "-y"]
@@ -143,7 +174,101 @@ def test_stdio_argv_prefers_child_path_over_parent(managed_node, monkeypatch, tm
monkeypatch.setenv("PATH", str(bare))
assert shutil.which("npx") is None
argv = mcp_client._stdio_argv(["npx"], mcp_client._stdio_env(None))
- assert os.path.samefile(argv[0], npx)
+ assert argv == _expected_node_launcher_argv(npx, [])
+
+
[email protected]("launcher", ["npm", "npx"])
+def test_windows_stdio_argv_bypasses_batch_launcher(launcher, monkeypatch, tmp_path):
+ bin_dir = tmp_path / "node"
+ cli = bin_dir / "node_modules" / "npm" / "bin" / f"{launcher}-cli.js"
+ cli.parent.mkdir(parents = True)
+ cli.write_text("")
+ node = bin_dir / "node.exe"
+ node.write_text("")
+ batch = bin_dir / f"{launcher}.cmd"
+ batch.write_text("")
+ monkeypatch.setattr(mcp_client, "_IS_WINDOWS", True)
+ monkeypatch.setattr(
+ mcp_client.shutil,
+ "which",
+ lambda command, path = None: str(batch) if command == launcher else str(node),
+ )
+ arguments = ["%TOKEN%", "a&b", "x|y", 'say "hello"', "a b", ""]
+
+ argv = mcp_client._stdio_argv([launcher, *arguments], {"PATH": str(bin_dir)})
+
+ assert argv == [str(node), str(cli), *arguments]
+
+
+def test_windows_stdio_argv_rejects_batch_when_cli_is_unknown(monkeypatch, tmp_path):
+ batch = tmp_path / "custom" / "npx.cmd"
+ batch.parent.mkdir()
+ batch.write_text("")
+ monkeypatch.setattr(mcp_client, "_IS_WINDOWS", True)
+ monkeypatch.setattr(mcp_client.shutil, "which", lambda command, path = None: str(batch))
+
+ with pytest.raises(ValueError, match = "npm CLI script"):
+ mcp_client._stdio_argv(["npx", "package"], {"PATH": str(tmp_path)})
+
+
[email protected]("argument", ["%TOKEN%", "a&b", "x|y", 'say "hello"', "(group)"])
+def test_windows_stdio_argv_rejects_unsafe_batch_arguments(argument, monkeypatch, tmp_path):
+ batch = tmp_path / "mcp-server-example.cmd"
+ batch.write_text("")
+ monkeypatch.setattr(mcp_client, "_IS_WINDOWS", True)
+ monkeypatch.setattr(mcp_client.shutil, "which", lambda command, path = None: str(batch))
+
+ with pytest.raises(ValueError, match = "cannot safely preserve these MCP command arguments"):
+ mcp_client._stdio_argv(
+ ["mcp-server-example", argument],
+ {"PATH": str(tmp_path)},
+ )
+
+
+def test_windows_stdio_argv_keeps_safe_batch_arguments(monkeypatch, tmp_path):
+ batch = tmp_path / "mcp-server-example.cmd"
+ batch.write_text("")
+ monkeypatch.setattr(mcp_client, "_IS_WINDOWS", True)
+ monkeypatch.setattr(mcp_client.shutil, "which", lambda command, path = None: str(batch))
+ arguments = [
+ "--port",
+ "3000",
+ r"C:\Users\me\data",
+ r"C:\Program Files (x86)\mcp data",
+ "a & b",
+ "",
+ ]
+
+ assert mcp_client._stdio_argv(["mcp-server-example", *arguments], {"PATH": str(tmp_path)}) == [
+ str(batch),
+ *arguments,
+ ]
+
+
+def test_windows_stdio_argv_keeps_argument_free_batch(monkeypatch, tmp_path):
+ batch = tmp_path / "mcp-server-example.cmd"
+ batch.write_text("")
+ monkeypatch.setattr(mcp_client, "_IS_WINDOWS", True)
+ monkeypatch.setattr(mcp_client.shutil, "which", lambda command, path = None: str(batch))
+
+ assert mcp_client._stdio_argv(["mcp-server-example"], {"PATH": str(tmp_path)}) == [str(batch)]
+
+
[email protected](os.name != "nt", reason = "requires an installed Windows Node runtime")
[email protected]("launcher", ["npm", "npx"])
+def test_windows_installed_node_launcher_avoids_cmd_shell(launcher):
+ resolved = shutil.which(launcher)
+ if resolved is None:
+ pytest.skip(f"{launcher} is not installed")
+ assert Path(resolved).suffix.lower() in (".cmd", ".bat")
+ arguments = ["%TOKEN%", "a&b", "x|y", 'say "hello"', "a b", ""]
+
+ argv = mcp_client._stdio_argv([launcher, *arguments], {"PATH": os.environ.get("PATH", "")})
+
+ assert Path(argv[0]).name.lower() == "node.exe"
+ assert Path(argv[1]).name.lower() == f"{launcher}-cli.js"
+ assert Path(argv[1]).is_file()
+ assert argv[2:] == arguments
def test_client_spawns_managed_npx_by_full_path(managed_node, monkeypatch, tmp_path):
@@ -153,7 +278,10 @@ def test_client_spawns_managed_npx_by_full_path(managed_node, monkeypatch, tmp_p
monkeypatch.setenv("PATH", str(bare))
monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")
client = mcp_client._client("npx -y @modelcontextprotocol/server-filesystem /tmp", None)
- assert os.path.samefile(client.transport.command, npx)
+ expected = _expected_node_launcher_argv(
+ npx, ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
+ )
+ assert [client.transport.command, *client.transport.args] == expected
def test_runtime_free_dir_resolves_nothing(runtime_free_dir):
@@ -218,7 +346,11 @@ def test_explicit_empty_path_blocks_host_lookup(managed_node, monkeypatch, tmp_p
_make_executable(host, "hostcmd")
monkeypatch.setenv("PATH", str(host))
assert shutil.which("hostcmd") is not None
- assert mcp_client._stdio_argv(["hostcmd"], {"PATH": ""}) == ["hostcmd"]
+ if os.name == "nt":
+ with pytest.raises(ValueError, match = "configured PATH"):
+ mcp_client._stdio_argv(["hostcmd"], {"PATH": ""})
+ else:
+ assert mcp_client._stdio_argv(["hostcmd"], {"PATH": ""}) == ["hostcmd"]
def test_explicit_empty_path_still_allows_absolute_command(managed_node):
@@ -414,8 +546,9 @@ def test_windows_npx_sibling_runtime_is_the_one_validated(
checked = []
_patch_floors(
monkeypatch,
- lambda executable, path = None: checked.append(str(executable))
- or not str(executable).startswith(str(old)),
+ lambda executable, path = None: (
+ checked.append(str(executable)) or not str(executable).startswith(str(old))
+ ),
)
configured = f"{good}{os.pathsep}{old}"
result = node_runtime.path_with_managed_node(configured)
@@ -462,7 +595,8 @@ def test_windows_lowercase_empty_path_is_still_a_sandbox(managed_node, monkeypat
def test_windows_lowercase_path_blocks_host_lookup(managed_node, windows_env):
- assert mcp_client._stdio_argv(["npx"], {"Path": ""}) == ["npx"]
+ with pytest.raises(ValueError, match = "configured PATH"):
+ mcp_client._stdio_argv(["npx"], {"Path": ""})
def test_posix_treats_path_and_lowercase_path_as_distinct(managed_node, monkeypatch, posix_env):
diff --git a/studio/backend/tests/test_mcp_stdio_real_server.py b/studio/backend/tests/test_mcp_stdio_real_server.py
new file mode 100644
index 00000000000..2c253be26fb
--- /dev/null
+++ b/studio/backend/tests/test_mcp_stdio_real_server.py
@@ -0,0 +1,176 @@
+# 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 json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+from core.inference import mcp_client
+from models.mcp_servers import (
+ McpServerCreate,
+ McpServerImportRequest,
+ McpServerTestRequest,
+ McpServerUpdate,
+ McpStdioCommand,
+ McpStdioDecodeRequest,
+)
+from routes import mcp_servers as routes_mcp
+from storage import mcp_servers_db
+
+
+FIXTURE = Path(__file__).parent / "fixtures" / "mcp_argument_echo_server.py"
+
+
+def _reset_db(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")
+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)
+
+
+def _encode(arguments: list[str]) -> str:
+ return routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = sys.executable, arguments = [str(FIXTURE), *arguments]),
+ current_subject = "u",
+ ).url
+
+
+def _launched_state(url: str, environment: dict[str, str]) -> dict:
+ output = mcp_client.call_tool_sync(
+ url,
+ environment,
+ "launch_state",
+ {},
+ timeout = 20,
+ )
+ assert not output.startswith("Error:"), output
+ return json.loads(output)
+
+
+def test_stdio_arguments_survive_real_crud_import_probe_and_launch(tmp_path, monkeypatch):
+ _reset_db(tmp_path, monkeypatch)
+ original_arguments = [
+ "--flag",
+ "",
+ "a b",
+ 'quote"inside',
+ "single'quote",
+ "trailing\\",
+ "https://example.com/value?q=a%20b",
+ " keep outer spaces ",
+ ]
+ environment = {"UNSLOTH_MCP_ARGUMENT_MARKER": "create value"}
+ encoded = _encode(original_arguments)
+
+ probe = asyncio.run(
+ routes_mcp.test_mcp_server(
+ McpServerTestRequest(url = encoded, headers = environment),
+ current_subject = "u",
+ )
+ )
+ assert (probe.ok, probe.tool_count, probe.error) == (True, 1, None)
+
+ created = asyncio.run(
+ routes_mcp.create_mcp_server(
+ McpServerCreate(
+ display_name = "argument echo",
+ url = encoded,
+ headers = environment,
+ ),
+ current_subject = "u",
+ )
+ )
+ persisted = mcp_servers_db.get_server(created.id)
+ assert persisted["url"] == encoded
+ assert json.loads(persisted["headers_json"]) == environment
+
+ listed = routes_mcp.list_mcp_servers(current_subject = "u")
+ assert [row.id for row in listed] == [created.id]
+ decoded = routes_mcp.decode_stdio_command(
+ McpStdioDecodeRequest(url = listed[0].url), current_subject = "u"
+ )
+ assert decoded.command == sys.executable
+ assert decoded.arguments == [str(FIXTURE), *original_arguments]
+ assert _launched_state(persisted["url"], environment) == {
+ "arguments": original_arguments,
+ "marker": "create value",
+ }
+
+ edited_arguments = ["second", "", "first", "a&b", "x|y", "%TOKEN%"]
+ edited_environment = {"UNSLOTH_MCP_ARGUMENT_MARKER": "edited value"}
+ edited_url = _encode(edited_arguments)
+ updated = asyncio.run(
+ routes_mcp.update_mcp_server(
+ created.id,
+ McpServerUpdate(url = edited_url, headers = edited_environment),
+ current_subject = "u",
+ )
+ )
+ assert updated.url == edited_url
+ refreshed = asyncio.run(routes_mcp.refresh_mcp_server_tools(created.id, current_subject = "u"))
+ assert (refreshed.ok, refreshed.tool_count) == (True, 1)
+ assert _launched_state(updated.url, edited_environment) == {
+ "arguments": edited_arguments,
+ "marker": "edited value",
+ }
+
+ imported_arguments = ["imported", "", "with spaces", 'say "hello"']
+ imported = asyncio.run(
+ routes_mcp.import_mcp_servers(
+ McpServerImportRequest(
+ config = {
+ "mcpServers": {
+ "imported echo": {
+ "command": sys.executable,
+ "args": [str(FIXTURE), *imported_arguments],
+ "env": {"UNSLOTH_MCP_ARGUMENT_MARKER": "import value"},
+ }
+ }
+ }
+ ),
+ current_subject = "u",
+ )
+ )
+ assert imported.errors == []
+ assert imported.skipped == []
+ assert len(imported.created) == 1
+ imported_row = mcp_servers_db.get_server(imported.created[0].id)
+ assert _launched_state(
+ imported_row["url"],
+ mcp_client.parse_server_headers(imported_row),
+ ) == {
+ "arguments": imported_arguments,
+ "marker": "import value",
+ }
+
+
[email protected](os.name != "nt", reason = "requires Windows batch launch semantics")
+def test_safe_arguments_survive_a_real_windows_batch_launcher(tmp_path, monkeypatch):
+ _reset_db(tmp_path, monkeypatch)
+ launcher = tmp_path / "mcp-server-example.cmd"
+ launcher.write_text(
+ f'@echo off\r\n"{sys.executable}" "{FIXTURE}" %*\r\n',
+ encoding = "utf-8",
+ )
+ arguments = [
+ "--port",
+ "3000",
+ r"C:\Users\me\data",
+ r"C:\Program Files (x86)\mcp data",
+ "a & b",
+ "",
+ ]
+ url = routes_mcp.encode_stdio_command(
+ McpStdioCommand(command = str(launcher), arguments = arguments),
+ current_subject = "u",
+ ).url
+
+ assert _launched_state(url, {"UNSLOTH_MCP_ARGUMENT_MARKER": "batch"}) == {
+ "arguments": arguments,
+ "marker": "batch",
+ }
diff --git a/studio/frontend/src/features/chat/api/mcp-server-mutation-tracker.ts b/studio/frontend/src/features/chat/api/mcp-server-mutation-tracker.ts
new file mode 100644
index 00000000000..031f40e7c0f
--- /dev/null
+++ b/studio/frontend/src/features/chat/api/mcp-server-mutation-tracker.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+const pendingMcpServerMutations = new Set<Promise<void>>();
+const mutationSettlementListeners = new Set<(epoch: number) => void>();
+let mcpServerMutationEpoch = 0;
+
+export function getMcpServerMutationEpoch(): number {
+ return mcpServerMutationEpoch;
+}
+
+export function subscribeToMcpServerMutationSettlements(
+ listener: (epoch: number) => void,
+): () => void {
+ mutationSettlementListeners.add(listener);
+ return () => mutationSettlementListeners.delete(listener);
+}
+
+export function trackMcpServerMutation<T>(mutation: Promise<T>): Promise<T> {
+ // The returned operation keeps its original result/rejection for its caller.
+ // The internal settlement promise always fulfills so background waiters never
+ // create an additional unhandled rejection when a component unmounts.
+ mcpServerMutationEpoch += 1;
+ const settlement = mutation.then(
+ () => undefined,
+ () => undefined,
+ );
+ pendingMcpServerMutations.add(settlement);
+ void settlement.then(() => {
+ pendingMcpServerMutations.delete(settlement);
+ mcpServerMutationEpoch += 1;
+ const settledEpoch = mcpServerMutationEpoch;
+ for (const listener of [...mutationSettlementListeners]) {
+ try {
+ listener(settledEpoch);
+ } catch {
+ // Observers must not change caller promise semantics or block siblings.
+ }
+ }
+ });
+ return mutation;
+}
+
+export async function readMcpServerMutationSnapshot<T>(
+ read: () => Promise<T>,
+): Promise<T> {
+ // Settlement-driven consumers need the newest stable server snapshot even
+ // if an unrelated, older mutation is still pending. Retry only when a
+ // mutation starts or settles across the read itself.
+ while (true) {
+ const epochBeforeRead = mcpServerMutationEpoch;
+ try {
+ const result = await read();
+ if (mcpServerMutationEpoch === epochBeforeRead) return result;
+ } catch (error) {
+ if (mcpServerMutationEpoch === epochBeforeRead) throw error;
+ }
+ }
+}
+
+export async function waitForPendingMcpServerMutations(): Promise<void> {
+ // A mutation may begin while an earlier batch is settling. Re-snapshot until
+ // the module-level set is empty so an open-time refresh cannot miss it.
+ while (pendingMcpServerMutations.size > 0) {
+ await Promise.all([...pendingMcpServerMutations]);
+ }
+}
+
+export async function readAfterPendingMcpServerMutations<T>(
+ read: () => Promise<T>,
+): Promise<T> {
+ while (true) {
+ await waitForPendingMcpServerMutations();
+ const epochBeforeRead = mcpServerMutationEpoch;
+ let result: T;
+ try {
+ result = await read();
+ } catch (error) {
+ await waitForPendingMcpServerMutations();
+ if (mcpServerMutationEpoch !== epochBeforeRead) continue;
+ throw error;
+ }
+ await waitForPendingMcpServerMutations();
+ if (mcpServerMutationEpoch === epochBeforeRead) return result;
+ }
+}
diff --git a/studio/frontend/src/features/chat/api/mcp-servers-api.ts b/studio/frontend/src/features/chat/api/mcp-servers-api.ts
index 0dc0719da47..5d7ad240833 100644
--- a/studio/frontend/src/features/chat/api/mcp-servers-api.ts
+++ b/studio/frontend/src/features/chat/api/mcp-servers-api.ts
@@ -4,6 +4,13 @@
import { authFetch } from "@/features/auth";
import { formatFastApiDetail } from "@/lib/format-fastapi-error";
+import {
+ getMcpServerMutationEpoch,
+ readAfterPendingMcpServerMutations,
+ readMcpServerMutationSnapshot,
+ trackMcpServerMutation,
+} from "./mcp-server-mutation-tracker";
+
export interface McpServerConfig {
id: string;
display_name: string;
@@ -27,6 +34,17 @@ export interface McpServerImportResult {
errors: string[];
}
+export interface McpStdioCommand {
+ command: string;
+ arguments: string[];
+}
+
+let mcpServerListRequest: Promise<McpServerConfig[]> | null = null;
+let mcpServerSettlementListRequest: {
+ minimumEpoch: number;
+ promise: Promise<McpServerConfig[]>;
+} | null = null;
+
function parseErrorText(status: number, body: unknown): string {
if (body && typeof body === "object") {
const { detail, message } = body as { detail?: unknown; message?: unknown };
@@ -53,8 +71,56 @@ async function mcpRequest<T>(
return json as T;
}
-export function listMcpServers(): Promise<McpServerConfig[]> {
- return mcpRequest("/");
+export function listMcpServers({
+ waitForPendingMutations = true,
+ minimumMutationEpoch,
+}: {
+ waitForPendingMutations?: boolean;
+ minimumMutationEpoch?: number;
+} = {}): Promise<McpServerConfig[]> {
+ if (!waitForPendingMutations) {
+ const requestedEpoch = minimumMutationEpoch ?? getMcpServerMutationEpoch();
+ if (
+ mcpServerSettlementListRequest &&
+ mcpServerSettlementListRequest.minimumEpoch >= requestedEpoch
+ ) {
+ return mcpServerSettlementListRequest.promise;
+ }
+ const request = readMcpServerMutationSnapshot(() =>
+ mcpRequest<McpServerConfig[]>("/"),
+ );
+ const slot = { minimumEpoch: requestedEpoch, promise: request };
+ mcpServerSettlementListRequest = slot;
+ void request.then(
+ () => {
+ if (mcpServerSettlementListRequest === slot) {
+ mcpServerSettlementListRequest = null;
+ }
+ },
+ () => {
+ if (mcpServerSettlementListRequest === slot) {
+ mcpServerSettlementListRequest = null;
+ }
+ },
+ );
+ return request;
+ }
+
+ if (mcpServerListRequest) return mcpServerListRequest;
+
+ const request = readAfterPendingMcpServerMutations(() =>
+ mcpRequest<McpServerConfig[]>("/"),
+ );
+ mcpServerListRequest = request;
+ void request.then(
+ () => {
+ if (mcpServerListRequest === request) mcpServerListRequest = null;
+ },
+ () => {
+ if (mcpServerListRequest === request) mcpServerListRequest = null;
+ },
+ );
+ return request;
}
export function createMcpServer(payload: {
@@ -64,16 +130,18 @@ export function createMcpServer(payload: {
isEnabled?: boolean;
useOauth?: boolean;
}): Promise<McpServerConfig> {
- return mcpRequest("/", {
- method: "POST",
- body: {
- display_name: payload.displayName,
- url: payload.url,
- headers: payload.headers ?? null,
- is_enabled: payload.isEnabled ?? true,
- use_oauth: payload.useOauth ?? false,
- },
- });
+ return trackMcpServerMutation(
+ mcpRequest("/", {
+ method: "POST",
+ body: {
+ display_name: payload.displayName,
+ url: payload.url,
+ headers: payload.headers ?? null,
+ is_enabled: payload.isEnabled ?? true,
+ use_oauth: payload.useOauth ?? false,
+ },
+ }),
+ );
}
export function updateMcpServer(
@@ -88,16 +156,21 @@ export function updateMcpServer(
},
): Promise<McpServerConfig> {
const body: Record<string, unknown> = {};
- if (payload.displayName !== undefined) body.display_name = payload.displayName;
+ if (payload.displayName !== undefined)
+ body.display_name = payload.displayName;
if (payload.url !== undefined) body.url = payload.url;
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;
- return mcpRequest(`/${serverId}`, { method: "PUT", body });
+ return trackMcpServerMutation(
+ mcpRequest(`/${serverId}`, { method: "PUT", body }),
+ );
}
export function deleteMcpServer(serverId: string): Promise<void> {
- return mcpRequest(`/${serverId}`, { method: "DELETE" });
+ return trackMcpServerMutation(
+ mcpRequest(`/${serverId}`, { method: "DELETE" }),
+ );
}
export function refreshMcpServerTools(
@@ -121,11 +194,29 @@ export function testMcpServer(payload: {
});
}
+export function decodeMcpStdioCommand(url: string): Promise<McpStdioCommand> {
+ return mcpRequest("/stdio/decode", {
+ method: "POST",
+ body: { url },
+ });
+}
+
+export function encodeMcpStdioCommand(payload: McpStdioCommand): Promise<{
+ url: string;
+}> {
+ return mcpRequest("/stdio/encode", {
+ method: "POST",
+ body: payload,
+ });
+}
+
// Bulk-import servers from a standard mcpServers JSON config (Claude Desktop,
// Cursor, Cline, VS Code). The backend skips duplicates and reports per-entry
// errors instead of failing the whole batch.
export function importMcpServers(
config: unknown,
): Promise<McpServerImportResult> {
- return mcpRequest("/import", { method: "POST", body: { config } });
+ return trackMcpServerMutation(
+ mcpRequest("/import", { method: "POST", body: { config } }),
+ );
}
diff --git a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
index d51be01668e..8df2a6d432e 100644
--- a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
+++ b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
@@ -1,11 +1,21 @@
// 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 { type ChangeEvent, useCallback, useEffect, useRef, useState } from "react";
-import { toast } from "sonner";
-import { Delete02Icon, Edit03Icon, PlusSignIcon } from "@hugeicons/core-free-icons";
+import {
+ Delete02Icon,
+ Edit03Icon,
+ PlusSignIcon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { RefreshCwIcon, UploadIcon } from "lucide-react";
+import {
+ type ChangeEvent,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+import { toast } from "sonner";
import {
AlertDialog,
@@ -29,29 +39,47 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
+import { subscribeToMcpServerMutationSettlements } from "./api/mcp-server-mutation-tracker";
import {
type McpServerConfig,
createMcpServer,
+ decodeMcpStdioCommand,
deleteMcpServer,
+ encodeMcpStdioCommand,
importMcpServers,
listMcpServers,
refreshMcpServerTools,
testMcpServer,
updateMcpServer,
} from "./api/mcp-servers-api";
+import {
+ type McpStdioSnapshot,
+ createMcpStdioSnapshot,
+ resolveMcpStdioUrl,
+} from "./mcp-server-form";
type HeaderRow = { id: string; key: string; value: string };
+type ArgumentRow = { id: string; value: string };
+type FormTransport = "unknown" | "http" | "stdio";
type FormState = {
displayName: string;
url: string;
+ transport: FormTransport;
+ arguments: ArgumentRow[];
+ stdioSnapshot: McpStdioSnapshot | null;
headers: HeaderRow[];
+ credentialTransport: Exclude<FormTransport, "unknown"> | null;
useOauth: boolean;
};
const EMPTY_FORM: FormState = {
displayName: "",
url: "",
+ transport: "unknown",
+ arguments: [],
+ stdioSnapshot: null,
headers: [],
+ credentialTransport: null,
useOauth: false,
};
@@ -67,7 +95,17 @@ function headersFromObject(headers: Record<string, string>): HeaderRow[] {
}));
}
-function headersToObject(rows: HeaderRow[]): Record<string, string> | undefined {
+function argumentsFromStrings(arguments_: readonly string[]): ArgumentRow[] {
+ return arguments_.map((value) => ({ id: newRowId(), value }));
+}
+
+function argumentsToStrings(rows: readonly ArgumentRow[]): string[] {
+ return rows.map((row) => row.value);
+}
+
+function headersToObject(
+ rows: HeaderRow[],
+): Record<string, string> | undefined {
const out: Record<string, string> = {};
for (const row of rows) {
const key = row.key.trim();
@@ -84,6 +122,51 @@ function isHttpAddress(value: string): boolean {
return trimmed.startsWith("http://") || trimmed.startsWith("https://");
}
+function transportFromAddress(
+ value: string,
+ credentialTransport: FormState["credentialTransport"] = null,
+): FormTransport {
+ const trimmed = value.trim().toLowerCase();
+ if (!trimmed) {
+ return "unknown";
+ }
+ if (isHttpAddress(value)) {
+ return "http";
+ }
+ if (
+ credentialTransport === "http" &&
+ ("http://".startsWith(trimmed) || "https://".startsWith(trimmed))
+ ) {
+ return "unknown";
+ }
+ return "stdio";
+}
+
+function formWithAddress(
+ form: FormState,
+ url: string,
+ preservePartialHttp: boolean,
+): FormState {
+ const transport = transportFromAddress(
+ url,
+ preservePartialHttp ? form.credentialTransport : null,
+ );
+ const nextCredentialTransport =
+ transport === "unknown" ? form.credentialTransport : transport;
+ const transportChanged =
+ transport !== "unknown" &&
+ form.credentialTransport !== null &&
+ form.credentialTransport !== transport;
+ return {
+ ...form,
+ url,
+ transport,
+ headers: transportChanged ? [] : form.headers,
+ credentialTransport: nextCredentialTransport,
+ useOauth: transport === "stdio" ? false : form.useOauth,
+ };
+}
+
function isValidAddress(value: string): boolean {
const trimmed = value.trim();
if (!trimmed) return false;
@@ -95,28 +178,90 @@ function isValidAddress(value: string): boolean {
return false;
}
}
- // Otherwise it's a local command (stdio); the backend gates whether those
- // are allowed. Reject only when the command itself is a URL; "://" is fine
- // inside an argument (e.g. a DB connection string passed to the server).
- return !trimmed.split(/\s+/)[0].includes("://");
+ // The backend owns stdio parsing and validation. In particular, the browser
+ // must not split an executable or duplicate platform-specific quoting rules.
+ return true;
+}
+
+function ArgumentsEditor({
+ rows,
+ onChange,
+ disabled,
+}: {
+ rows: ArgumentRow[];
+ onChange: (rows: ArgumentRow[]) => void;
+ disabled: boolean;
+}) {
+ const update = (id: string, value: string) =>
+ onChange(rows.map((row) => (row.id === id ? { ...row, value } : row)));
+ const add = () => onChange([...rows, { id: newRowId(), value: "" }]);
+ const remove = (id: string) => onChange(rows.filter((row) => row.id !== id));
+
+ return (
+ <div className="grid gap-2">
+ <div className="flex items-center justify-between">
+ <Label className="text-sm">Arguments</Label>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={add}
+ disabled={disabled}
+ >
+ <HugeiconsIcon icon={PlusSignIcon} size={14} />
+ Add argument
+ </Button>
+ </div>
+ {rows.length === 0 ? (
+ <div className="text-xs text-muted-foreground">
+ Optional. Each row is one argument; row order is preserved.
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {rows.map((row, index) => (
+ <div key={row.id} className="flex items-center gap-2">
+ <Input
+ data-reload-snapshot-sensitive={true}
+ value={row.value}
+ disabled={disabled}
+ aria-label={`Argument ${index + 1}`}
+ placeholder={index === 0 ? "e.g. -y" : undefined}
+ onChange={(event) => update(row.id, event.target.value)}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => remove(row.id)}
+ disabled={disabled}
+ aria-label={`Remove argument ${index + 1}`}
+ >
+ <HugeiconsIcon icon={Delete02Icon} size={14} />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
}
function HeadersEditor({
rows,
onChange,
stdio,
+ disabled,
}: {
rows: HeaderRow[];
onChange: (rows: HeaderRow[]) => void;
// stdio servers reuse this editor for environment variables instead of headers.
stdio: boolean;
+ disabled: boolean;
}) {
const update = (id: string, patch: Partial<HeaderRow>) =>
onChange(rows.map((row) => (row.id === id ? { ...row, ...patch } : row)));
- const add = () =>
- onChange([...rows, { id: newRowId(), key: "", value: "" }]);
- const remove = (id: string) =>
- onChange(rows.filter((row) => row.id !== id));
+ const add = () => onChange([...rows, { id: newRowId(), key: "", value: "" }]);
+ const remove = (id: string) => onChange(rows.filter((row) => row.id !== id));
const copy = stdio
? {
@@ -138,7 +283,13 @@ function HeadersEditor({
<>
<div className="flex items-center justify-between">
<Label className="text-sm">{copy.label}</Label>
- <Button type="button" variant="ghost" size="sm" onClick={add}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={add}
+ disabled={disabled}
+ >
<HugeiconsIcon icon={PlusSignIcon} size={14} />
{copy.add}
</Button>
@@ -149,8 +300,8 @@ function HeadersEditor({
"Optional. Environment variables passed to the server process."
) : (
<>
- Optional. Add an <code>Authorization</code> header here for servers
- that require auth.
+ Optional. Add an <code>Authorization</code> header here for
+ servers that require auth.
</>
)}
</div>
@@ -160,12 +311,14 @@ function HeadersEditor({
<div key={row.id} className="flex items-center gap-2">
<Input
value={row.key}
+ disabled={disabled}
placeholder={copy.keyPlaceholder}
onChange={(e) => update(row.id, { key: e.target.value })}
/>
<Input
- data-reload-snapshot-sensitive
+ data-reload-snapshot-sensitive={true}
value={row.value}
+ disabled={disabled}
placeholder={copy.valuePlaceholder}
onChange={(e) => update(row.id, { value: e.target.value })}
/>
@@ -174,6 +327,7 @@ function HeadersEditor({
variant="ghost"
size="icon"
onClick={() => remove(row.id)}
+ disabled={disabled}
aria-label={copy.remove}
>
<HugeiconsIcon icon={Delete02Icon} size={14} />
@@ -206,68 +360,276 @@ export function ChatMcpServersDialog({
const [form, setForm] = useState<FormState>(EMPTY_FORM);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
+ const [codecPending, setCodecPending] = useState(false);
+ const [decodingCommand, setDecodingCommand] = useState(false);
+ const [codecError, setCodecError] = useState<string | null>(null);
const [importing, setImporting] = useState(false);
- const [refreshingId, setRefreshingId] = useState<string | null>(null);
- const [confirmingDelete, setConfirmingDelete] = useState<McpServerConfig | null>(
- null,
+ const [refreshingIds, setRefreshingIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
);
+ const [togglingIds, setTogglingIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const [busyIds, setBusyIds] = useState<ReadonlySet<string>>(() => new Set());
+ const [confirmingDelete, setConfirmingDelete] =
+ useState<McpServerConfig | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
+ const formGenerationRef = useRef(0);
+ const actionGenerationRef = useRef(0);
+ const importGenerationRef = useRef(0);
+ const activeEditIdRef = useRef<string | null>(null);
+ const listRefreshGenerationRef = useRef(0);
+ const openRef = useRef(open);
+ const refreshingIdsRef = useRef(new Set<string>());
+ const togglingIdsRef = useRef(new Set<string>());
+ const busyIdsRef = useRef(new Set<string>());
+ const importingRef = useRef(false);
+ openRef.current = open;
- const refresh = useCallback(async () => {
- setLoading(true);
- try {
- const rows = await listMcpServers();
- setServers(rows);
- } catch (err) {
- toast.error("Failed to load MCP servers", {
- description: err instanceof Error ? err.message : String(err),
- });
- } finally {
- setLoading(false);
- }
+ useEffect(() => {
+ return () => {
+ formGenerationRef.current += 1;
+ actionGenerationRef.current += 1;
+ activeEditIdRef.current = null;
+ openRef.current = false;
+ };
}, []);
+ const refresh = useCallback(
+ async (waitForPendingMutations = true, minimumMutationEpoch = 0) => {
+ const generation = listRefreshGenerationRef.current + 1;
+ listRefreshGenerationRef.current = generation;
+ setLoading(true);
+ try {
+ const rows = await listMcpServers({
+ waitForPendingMutations,
+ minimumMutationEpoch,
+ });
+ if (listRefreshGenerationRef.current !== generation || !openRef.current)
+ return;
+ setServers((current) =>
+ rows.map((row) => {
+ if (!togglingIdsRef.current.has(row.id)) return row;
+ const optimistic = current.find(
+ (candidate) => candidate.id === row.id,
+ );
+ return optimistic
+ ? { ...row, is_enabled: optimistic.is_enabled }
+ : row;
+ }),
+ );
+ } catch (err) {
+ if (listRefreshGenerationRef.current !== generation || !openRef.current)
+ return;
+ toast.error("Failed to load MCP servers", {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ if (listRefreshGenerationRef.current === generation && openRef.current)
+ setLoading(false);
+ }
+ },
+ [],
+ );
+
useEffect(() => {
- if (!open) return;
- refresh();
- // Reset to the list on each open, else a stale create/edit view persists.
- setView({ kind: "list" });
- setForm(EMPTY_FORM);
+ if (!open) {
+ listRefreshGenerationRef.current += 1;
+ return;
+ }
+ const unsubscribe = subscribeToMcpServerMutationSettlements((epoch) => {
+ void refresh(false, epoch);
+ });
+ return () => {
+ unsubscribe();
+ listRefreshGenerationRef.current += 1;
+ };
+ }, [open, refresh]);
+
+ useEffect(() => {
+ formGenerationRef.current += 1;
+ actionGenerationRef.current += 1;
+ activeEditIdRef.current = null;
+ let cancelled = false;
+ queueMicrotask(() => {
+ if (cancelled) return;
+ setSaving(false);
+ setTesting(false);
+ setCodecPending(false);
+ setDecodingCommand(false);
+ setCodecError(null);
+ setImporting(importingRef.current);
+ setConfirmingDelete(null);
+ setRefreshingIds(new Set(refreshingIdsRef.current));
+ setTogglingIds(new Set(togglingIdsRef.current));
+ setBusyIds(new Set(busyIdsRef.current));
+ if (!open) return;
+ void refresh();
+ // Reset to the list on each open, else a stale create/edit view persists.
+ setView({ kind: "list" });
+ setForm(EMPTY_FORM);
+ });
+ return () => {
+ cancelled = true;
+ };
}, [open, refresh]);
function startCreate() {
+ formGenerationRef.current += 1;
+ activeEditIdRef.current = null;
+ setSaving(false);
+ setTesting(false);
+ setCodecPending(false);
+ setDecodingCommand(false);
+ setCodecError(null);
setView({ kind: "create" });
setForm(EMPTY_FORM);
}
- function startEdit(server: McpServerConfig) {
+ async function startEdit(server: McpServerConfig) {
+ const generation = formGenerationRef.current + 1;
+ formGenerationRef.current = generation;
+ activeEditIdRef.current = server.id;
+ setSaving(false);
+ setTesting(false);
+ setCodecError(null);
setView({ kind: "edit", id: server.id });
- setForm({
+ const baseForm: FormState = {
displayName: server.display_name,
url: server.url,
+ transport: isHttpAddress(server.url) ? "http" : "stdio",
+ arguments: [],
+ stdioSnapshot: null,
headers: headersFromObject(server.headers ?? {}),
+ credentialTransport: isHttpAddress(server.url) ? "http" : "stdio",
useOauth: server.use_oauth ?? false,
- });
+ };
+
+ if (isHttpAddress(server.url)) {
+ setCodecPending(false);
+ setDecodingCommand(false);
+ setForm(baseForm);
+ return;
+ }
+
+ setCodecPending(true);
+ setDecodingCommand(true);
+ setForm(baseForm);
+ try {
+ const decoded = await decodeMcpStdioCommand(server.url);
+ if (
+ formGenerationRef.current !== generation ||
+ activeEditIdRef.current !== server.id
+ ) {
+ return;
+ }
+ setForm({
+ ...baseForm,
+ url: decoded.command,
+ arguments: argumentsFromStrings(decoded.arguments ?? []),
+ stdioSnapshot: createMcpStdioSnapshot(
+ server.url,
+ decoded.command,
+ decoded.arguments ?? [],
+ ),
+ useOauth: false,
+ });
+ } catch (err) {
+ if (
+ formGenerationRef.current !== generation ||
+ activeEditIdRef.current !== server.id
+ ) {
+ return;
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ setCodecError(message);
+ toast.error("Failed to read local command", { description: message });
+ } finally {
+ if (
+ formGenerationRef.current === generation &&
+ activeEditIdRef.current === server.id
+ ) {
+ setCodecPending(false);
+ setDecodingCommand(false);
+ }
+ }
}
function cancelForm() {
+ formGenerationRef.current += 1;
+ activeEditIdRef.current = null;
+ setSaving(false);
+ setTesting(false);
+ setCodecPending(false);
+ setDecodingCommand(false);
+ setCodecError(null);
setView({ kind: "list" });
setForm(EMPTY_FORM);
}
+ function handleOpenChange(next: boolean) {
+ // once crud starts, dismissal must wait for the authoritative refresh
+ if (!next && ((saving && !codecPending) || busyIdsRef.current.size > 0))
+ return;
+ if (!next) {
+ formGenerationRef.current += 1;
+ actionGenerationRef.current += 1;
+ activeEditIdRef.current = null;
+ setSaving(false);
+ setTesting(false);
+ setCodecPending(false);
+ setDecodingCommand(false);
+ setCodecError(null);
+ setConfirmingDelete(null);
+ }
+ onOpenChange(next);
+ }
+
+ async function encodeStdioForGeneration(
+ generation: number,
+ command: string,
+ arguments_: string[],
+ ): Promise<string | null> {
+ setCodecPending(true);
+ try {
+ const encoded = await encodeMcpStdioCommand({
+ command,
+ arguments: arguments_,
+ });
+ if (formGenerationRef.current !== generation) return null;
+ return encoded.url;
+ } finally {
+ if (formGenerationRef.current === generation) setCodecPending(false);
+ }
+ }
+
async function testConnection() {
- const trimmedUrl = form.url.trim();
- if (!isValidAddress(trimmedUrl)) {
+ if (!form.url.trim() || form.transport === "unknown") {
toast.error("Enter an http(s):// URL or a local command first");
return;
}
+ const stdio = form.transport === "stdio";
+ if (!stdio && !isValidAddress(form.url)) {
+ toast.error("Enter an http(s):// URL or a local command first");
+ return;
+ }
+ const generation = formGenerationRef.current;
setTesting(true);
try {
+ const url = stdio
+ ? await encodeStdioForGeneration(
+ generation,
+ form.url,
+ argumentsToStrings(form.arguments),
+ )
+ : form.url.trim();
+ if (url === null || formGenerationRef.current !== generation) return;
const result = await testMcpServer({
- url: trimmedUrl,
+ url,
headers: headersToObject(form.headers),
- useOauth: form.useOauth,
+ useOauth: stdio ? false : form.useOauth,
});
+ if (formGenerationRef.current !== generation) return;
if (result.ok) {
toast.success(
`Connected (${result.tool_count} tool${result.tool_count === 1 ? "" : "s"})`,
@@ -278,74 +640,111 @@ export function ChatMcpServersDialog({
});
}
} catch (err) {
+ if (formGenerationRef.current !== generation) return;
toast.error("Connection test failed", {
description: err instanceof Error ? err.message : String(err),
});
} finally {
- setTesting(false);
+ if (formGenerationRef.current === generation) setTesting(false);
}
}
async function submitForm() {
const trimmedName = form.displayName.trim();
- const trimmedUrl = form.url.trim();
if (!trimmedName) {
toast.error("Display name is required");
return;
}
- if (!trimmedUrl) {
+ if (!form.url.trim() || form.transport === "unknown") {
toast.error("URL or command is required");
return;
}
- if (!isValidAddress(trimmedUrl)) {
+ const stdio = form.transport === "stdio";
+ if (!stdio && !isValidAddress(form.url)) {
toast.error("Enter an http(s):// URL or a local command");
return;
}
+ const generation = formGenerationRef.current;
setSaving(true);
try {
const headers = headersToObject(form.headers);
+ let url: string | undefined;
+ if (stdio) {
+ const decision = resolveMcpStdioUrl(
+ form.url,
+ argumentsToStrings(form.arguments),
+ form.stdioSnapshot,
+ );
+ if (decision.kind === "reuse") {
+ url = view.kind === "edit" ? undefined : decision.url;
+ } else {
+ const encodedUrl = await encodeStdioForGeneration(
+ generation,
+ decision.command,
+ decision.arguments,
+ );
+ if (encodedUrl === null) return;
+ url = encodedUrl;
+ }
+ } else {
+ url = form.url.trim();
+ }
+ if (formGenerationRef.current !== generation) return;
if (view.kind === "edit") {
await updateMcpServer(view.id, {
displayName: trimmedName,
- url: trimmedUrl,
+ url,
headers: headers ?? null,
- useOauth: form.useOauth,
+ useOauth: stdio ? false : form.useOauth,
});
+ if (formGenerationRef.current !== generation) return;
toast.success("MCP server updated");
} else {
+ if (url === undefined) return;
await createMcpServer({
displayName: trimmedName,
- url: trimmedUrl,
+ url,
headers: headers,
- useOauth: form.useOauth,
+ useOauth: stdio ? false : form.useOauth,
});
+ if (formGenerationRef.current !== generation) return;
toast.success("MCP server added");
}
+ if (formGenerationRef.current !== generation) return;
cancelForm();
- await refresh();
} catch (err) {
+ if (formGenerationRef.current !== generation) return;
toast.error("Save failed", {
description: err instanceof Error ? err.message : String(err),
});
} finally {
- setSaving(false);
+ if (formGenerationRef.current === generation) setSaving(false);
}
}
async function onImportFile(e: ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
e.target.value = ""; // let the user re-pick the same file later
- if (!file) return;
- let config: unknown;
- try {
- config = JSON.parse(await file.text());
- } catch {
- toast.error("Invalid JSON file");
- return;
- }
+ if (!file || importingRef.current) return;
+ const generation = actionGenerationRef.current;
+ const importGeneration = importGenerationRef.current + 1;
+ importGenerationRef.current = importGeneration;
+ importingRef.current = true;
setImporting(true);
try {
+ let config: unknown;
+ try {
+ config = JSON.parse(await file.text());
+ } catch {
+ if (actionGenerationRef.current === generation && openRef.current)
+ toast.error("Invalid JSON file");
+ return;
+ }
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
const result = await importMcpServers(config);
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
const parts = [`${result.created.length} added`];
if (result.skipped.length) parts.push(`${result.skipped.length} skipped`);
if (result.errors.length) {
@@ -365,28 +764,49 @@ export function ChatMcpServersDialog({
} else {
toast.success(summary);
}
- await refresh();
} catch (err) {
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
toast.error("Import failed", {
description: err instanceof Error ? err.message : String(err),
});
} finally {
- setImporting(false);
+ if (importGenerationRef.current === importGeneration) {
+ importingRef.current = false;
+ if (openRef.current) setImporting(false);
+ }
}
}
async function removeServer(server: McpServerConfig) {
+ if (busyIdsRef.current.has(server.id)) return;
+ const generation = actionGenerationRef.current;
+ busyIdsRef.current.add(server.id);
+ setBusyIds(new Set(busyIdsRef.current));
try {
await deleteMcpServer(server.id);
- await refresh();
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
+ setServers((rows) => rows.filter((row) => row.id !== server.id));
} catch (err) {
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
toast.error("Delete failed", {
description: err instanceof Error ? err.message : String(err),
});
+ } finally {
+ busyIdsRef.current.delete(server.id);
+ if (openRef.current) setBusyIds(new Set(busyIdsRef.current));
}
}
async function toggleEnabled(server: McpServerConfig, next: boolean) {
+ if (busyIdsRef.current.has(server.id)) return;
+ const generation = actionGenerationRef.current;
+ busyIdsRef.current.add(server.id);
+ togglingIdsRef.current.add(server.id);
+ setBusyIds(new Set(busyIdsRef.current));
+ setTogglingIds(new Set(togglingIdsRef.current));
// Optimistic update so the switch doesn't snap back during the round-trip.
setServers((rows) =>
rows.map((row) =>
@@ -396,6 +816,8 @@ export function ChatMcpServersDialog({
try {
await updateMcpServer(server.id, { isEnabled: next });
} catch (err) {
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
setServers((rows) =>
rows.map((row) =>
row.id === server.id ? { ...row, is_enabled: !next } : row,
@@ -404,13 +826,27 @@ export function ChatMcpServersDialog({
toast.error("Update failed", {
description: err instanceof Error ? err.message : String(err),
});
+ } finally {
+ busyIdsRef.current.delete(server.id);
+ togglingIdsRef.current.delete(server.id);
+ if (openRef.current) {
+ setBusyIds(new Set(busyIdsRef.current));
+ setTogglingIds(new Set(togglingIdsRef.current));
+ }
}
}
async function refreshTools(server: McpServerConfig) {
- setRefreshingId(server.id);
+ if (busyIdsRef.current.has(server.id)) return;
+ const generation = actionGenerationRef.current;
+ busyIdsRef.current.add(server.id);
+ refreshingIdsRef.current.add(server.id);
+ setBusyIds(new Set(busyIdsRef.current));
+ setRefreshingIds(new Set(refreshingIdsRef.current));
try {
const result = await refreshMcpServerTools(server.id);
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
if (result.ok) {
toast.success(
`Refreshed "${server.display_name}" (${result.tool_count} tool${result.tool_count === 1 ? "" : "s"})`,
@@ -421,22 +857,33 @@ export function ChatMcpServersDialog({
});
}
} catch (err) {
+ if (actionGenerationRef.current !== generation || !openRef.current)
+ return;
toast.error("Refresh failed", {
description: err instanceof Error ? err.message : String(err),
});
} finally {
- setRefreshingId(null);
+ busyIdsRef.current.delete(server.id);
+ refreshingIdsRef.current.delete(server.id);
+ if (openRef.current) {
+ setBusyIds(new Set(busyIdsRef.current));
+ setRefreshingIds(new Set(refreshingIdsRef.current));
+ }
}
}
const showForm = view.kind !== "list";
+ const formPending = importing || codecPending || testing || saving;
// A local stdio command uses env vars, not headers or OAuth.
- const addressIsCommand =
- form.url.trim() !== "" && !isHttpAddress(form.url);
+ const addressIsCommand = form.transport === "stdio";
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-w-2xl">
+ <Dialog open={open} onOpenChange={handleOpenChange}>
+ <DialogContent
+ className="max-w-2xl"
+ showCloseButton={!(saving && !codecPending) && busyIds.size === 0}
+ aria-busy={decodingCommand}
+ >
<DialogHeader>
<DialogTitle>MCP Servers</DialogTitle>
<DialogDescription>
@@ -449,6 +896,7 @@ export function ChatMcpServersDialog({
accept="application/json,.json"
className="hidden"
onChange={onImportFile}
+ disabled={importing || formPending}
/>
{showForm ? (
@@ -464,7 +912,7 @@ export function ChatMcpServersDialog({
variant="outline"
className="shrink-0"
onClick={() => fileInputRef.current?.click()}
- disabled={importing}
+ disabled={importing || formPending}
title="Import servers from a mcpServers JSON config (Claude Desktop, Cursor, VS Code…)"
>
{importing ? <Spinner /> : <UploadIcon size={14} />}
@@ -477,6 +925,7 @@ export function ChatMcpServersDialog({
<Input
id="mcp-display-name"
value={form.displayName}
+ disabled={formPending}
onChange={(e) =>
setForm((prev) => ({ ...prev, displayName: e.target.value }))
}
@@ -484,22 +933,95 @@ export function ChatMcpServersDialog({
/>
</div>
<div className="grid gap-2">
- <Label htmlFor="mcp-url">URL or command</Label>
+ <Label htmlFor="mcp-url">
+ {addressIsCommand
+ ? "Executable"
+ : form.transport === "http"
+ ? "URL"
+ : "URL or executable"}
+ </Label>
<Input
id="mcp-url"
value={form.url}
- onChange={(e) =>
- setForm((prev) => ({ ...prev, url: e.target.value }))
+ disabled={formPending}
+ onChange={(e) => {
+ const url = e.target.value;
+ setCodecError(null);
+ setForm((prev) => formWithAddress(prev, url, true));
+ }}
+ onBlur={() => {
+ setForm((prev) =>
+ prev.transport === "unknown" && prev.url.trim()
+ ? formWithAddress(prev, prev.url, false)
+ : prev,
+ );
+ }}
+ placeholder={
+ addressIsCommand
+ ? "e.g. npx"
+ : form.transport === "http"
+ ? "https://example.com/mcp"
+ : "https://example.com/mcp or npx"
}
- placeholder="https://example.com/mcp or npx -y @modelcontextprotocol/server-filesystem /tmp"
/>
<span className="text-xs text-muted-foreground">
- An http(s) URL for a remote server, or a local command to run an
- stdio server (local installs only).
+ {addressIsCommand
+ ? "The executable for a local stdio server. Add each local argument in an Arguments row below."
+ : form.transport === "http"
+ ? "An http(s) URL for a remote server."
+ : "An http(s) URL for a remote server, or an executable for local stdio. Add local arguments in the Arguments rows."}
</span>
+ {decodingCommand && (
+ <span
+ role="status"
+ aria-live="polite"
+ className="flex items-center gap-2 text-xs text-muted-foreground"
+ >
+ <Spinner />
+ Reading local command…
+ </span>
+ )}
</div>
- {!addressIsCommand && (
+ {addressIsCommand && (
+ <ArgumentsEditor
+ rows={form.arguments}
+ disabled={formPending}
+ onChange={(arguments_) =>
+ setForm((prev) => ({ ...prev, arguments: arguments_ }))
+ }
+ />
+ )}
+
+ {codecError && (
+ <div className="flex items-center justify-between gap-3">
+ <div
+ role="alert"
+ aria-live="assertive"
+ className="text-sm text-destructive"
+ >
+ {codecError}
+ </div>
+ {view.kind === "edit" && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={formPending}
+ onClick={() => {
+ const server = servers.find(
+ (candidate) => candidate.id === view.id,
+ );
+ if (server) void startEdit(server);
+ }}
+ >
+ Retry
+ </Button>
+ )}
+ </div>
+ )}
+
+ {form.transport === "http" && (
<div className="flex items-start justify-between gap-3">
<div className="flex flex-col gap-0.5">
<Label className="text-sm" htmlFor="mcp-oauth">
@@ -514,6 +1036,7 @@ export function ChatMcpServersDialog({
<Switch
id="mcp-oauth"
checked={form.useOauth}
+ disabled={formPending}
onCheckedChange={(useOauth) =>
setForm((prev) => ({ ...prev, useOauth }))
}
@@ -521,11 +1044,16 @@ export function ChatMcpServersDialog({
</div>
)}
- <HeadersEditor
- rows={form.headers}
- onChange={(headers) => setForm((prev) => ({ ...prev, headers }))}
- stdio={addressIsCommand}
- />
+ {form.transport !== "unknown" && (
+ <HeadersEditor
+ rows={form.headers}
+ onChange={(headers) =>
+ setForm((prev) => ({ ...prev, headers }))
+ }
+ stdio={addressIsCommand}
+ disabled={formPending}
+ />
+ )}
<div className="flex items-center justify-between gap-2 pt-2">
<Button
@@ -533,16 +1061,32 @@ export function ChatMcpServersDialog({
variant="outline"
size="sm"
onClick={testConnection}
- disabled={testing || saving || !form.url.trim()}
+ disabled={
+ formPending ||
+ codecError !== null ||
+ form.transport === "unknown" ||
+ !form.url.trim()
+ }
>
{testing ? <Spinner /> : null}
Test connection
</Button>
<div className="flex gap-2">
- <Button variant="ghost" onClick={cancelForm} disabled={saving}>
+ <Button
+ variant="ghost"
+ onClick={cancelForm}
+ disabled={saving && !codecPending}
+ >
Cancel
</Button>
- <Button onClick={submitForm} disabled={saving}>
+ <Button
+ onClick={submitForm}
+ disabled={
+ formPending ||
+ codecError !== null ||
+ form.transport === "unknown"
+ }
+ >
{saving ? <Spinner /> : null}
{view.kind === "edit" ? "Save changes" : "Add server"}
</Button>
@@ -562,7 +1106,7 @@ export function ChatMcpServersDialog({
{importing ? <Spinner /> : <UploadIcon size={14} />}
Import config
</Button>
- <Button size="sm" onClick={startCreate}>
+ <Button size="sm" onClick={startCreate} disabled={importing}>
<HugeiconsIcon icon={PlusSignIcon} size={14} />
Add server
</Button>
@@ -595,6 +1139,7 @@ export function ChatMcpServersDialog({
checked={server.is_enabled}
onCheckedChange={(next) => toggleEnabled(server, next)}
aria-label="Enable server"
+ disabled={importing || busyIds.has(server.id)}
/>
<Button
type="button"
@@ -603,9 +1148,9 @@ export function ChatMcpServersDialog({
onClick={() => refreshTools(server)}
aria-label="Refresh tools"
title="Refresh tools from this server"
- disabled={refreshingId === server.id}
+ disabled={importing || busyIds.has(server.id)}
>
- {refreshingId === server.id ? (
+ {refreshingIds.has(server.id) ? (
<Spinner />
) : (
<RefreshCwIcon size={14} />
@@ -615,8 +1160,9 @@ export function ChatMcpServersDialog({
type="button"
variant="ghost"
size="icon"
- onClick={() => startEdit(server)}
+ onClick={() => void startEdit(server)}
aria-label="Edit server"
+ disabled={importing || busyIds.has(server.id)}
>
<HugeiconsIcon icon={Edit03Icon} size={14} />
</Button>
@@ -626,6 +1172,7 @@ export function ChatMcpServersDialog({
size="icon"
onClick={() => setConfirmingDelete(server)}
aria-label="Delete server"
+ disabled={importing || busyIds.has(server.id)}
>
<HugeiconsIcon icon={Delete02Icon} size={14} />
</Button>
@@ -638,7 +1185,7 @@ export function ChatMcpServersDialog({
)}
</DialogContent>
<AlertDialog
- open={confirmingDelete !== null}
+ open={open && confirmingDelete !== null}
onOpenChange={(next) => {
if (!next) setConfirmingDelete(null);
}}
diff --git a/studio/frontend/src/features/chat/mcp-composer-button.tsx b/studio/frontend/src/features/chat/mcp-composer-button.tsx
index 951c35019c8..1fd89b5503b 100644
--- a/studio/frontend/src/features/chat/mcp-composer-button.tsx
+++ b/studio/frontend/src/features/chat/mcp-composer-button.tsx
@@ -5,7 +5,7 @@ import { Tick02Icon } from "@/lib/tick-icon";
import { McpServerIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { XIcon } from "lucide-react";
-import { type FC, useCallback, useEffect, useState } from "react";
+import { type FC, useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import {
@@ -23,6 +23,7 @@ import {
} from "@/components/ui/tooltip";
import { useShortcut } from "@/features/settings";
+import { subscribeToMcpServerMutationSettlements } from "./api/mcp-server-mutation-tracker";
import {
type McpServerConfig,
createMcpServer,
@@ -30,9 +31,9 @@ import {
updateMcpServer,
} from "./api/mcp-servers-api";
import { ChatMcpServersDialog } from "./chat-mcp-servers-dialog";
+import { useChatActive } from "./runtime-provider";
import { useChatRuntimeStore } from "./stores/chat-runtime-store";
import { useMcpServersDialogStore } from "./stores/mcp-servers-dialog-store";
-import { useChatActive } from "./runtime-provider";
// Matches the Thinking pill chevron so the affordance reads the same.
const ArrowDownStandardIcon: FC<{ className?: string }> = ({ className }) => (
@@ -109,27 +110,78 @@ export function McpComposerButton({
const dialogOpen = useMcpServersDialogStore((s) => s.open);
const setDialogOpen = useMcpServersDialogStore((s) => s.setOpen);
const [menuOpen, setMenuOpen] = useState(false);
- const [pendingUrl, setPendingUrl] = useState<string | null>(null);
+ const [serversLoaded, setServersLoaded] = useState(false);
+ const [pendingUrls, setPendingUrls] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const pendingUrlsRef = useRef(new Set<string>());
const [hintKey, setHintKey] = useState<string | null>(null);
+ const listRefreshGenerationRef = useRef(0);
+ const hasLoadedServerSnapshotRef = useRef(false);
// Grey out only when a loaded model lacks tool support; with no model yet,
// MCP can still be pre-selected, like the other composer tools.
const usable = !modelLoaded || supportsTools;
- const refresh = useCallback(async () => {
- try {
- const rows = await listMcpServers();
- setServers(rows);
- } catch {
- // Keep prior state if the list call fails.
- }
+ const refresh = useCallback(
+ async (waitForPendingMutations = true, minimumMutationEpoch = 0) => {
+ const generation = listRefreshGenerationRef.current + 1;
+ listRefreshGenerationRef.current = generation;
+ setServersLoaded(false);
+ try {
+ const rows = await listMcpServers({
+ waitForPendingMutations,
+ minimumMutationEpoch,
+ });
+ if (listRefreshGenerationRef.current !== generation) return;
+ setServers(rows);
+ hasLoadedServerSnapshotRef.current = true;
+ setServersLoaded(true);
+ } catch {
+ if (
+ listRefreshGenerationRef.current === generation &&
+ hasLoadedServerSnapshotRef.current
+ ) {
+ setServersLoaded(true);
+ }
+ }
+ },
+ [],
+ );
+
+ const applyServer = useCallback((server: McpServerConfig) => {
+ setServers((current) => {
+ const index = current.findIndex(
+ (candidate) => candidate.id === server.id,
+ );
+ if (index === -1) return [...current, server];
+ return current.map((candidate) =>
+ candidate.id === server.id ? server : candidate,
+ );
+ });
}, []);
+ useEffect(() => {
+ const unsubscribe = subscribeToMcpServerMutationSettlements((epoch) => {
+ void refresh(false, epoch);
+ });
+ return () => {
+ unsubscribe();
+ listRefreshGenerationRef.current += 1;
+ };
+ }, [refresh]);
+
// Load the server list on mount, and again when the dialog closes: it can
// be opened from the chord as well as from this menu.
useEffect(() => {
if (dialogOpen) return;
- void refresh();
+ let cancelled = false;
+ queueMicrotask(() => {
+ if (!cancelled) void refresh();
+ });
+ return () => {
+ cancelled = true;
+ };
}, [refresh, dialogOpen]);
const enabledUrls = new Set(
@@ -150,35 +202,42 @@ export function McpComposerButton({
disablesWebSearch?: boolean;
}) {
const norm = normalizeMcpUrl(args.url);
- if (pendingUrl === norm) return; // guard rapid double-clicks
- setPendingUrl(norm);
+ if (pendingUrlsRef.current.has(norm)) return; // guard rapid double-clicks
+ pendingUrlsRef.current.add(norm);
+ setPendingUrls(new Set(pendingUrlsRef.current));
try {
if (args.checked) {
// Reuse the already-loaded row, else create one.
if (args.existing) {
if (!args.existing.is_enabled) {
- await updateMcpServer(args.existing.id, { isEnabled: true });
+ applyServer(
+ await updateMcpServer(args.existing.id, { isEnabled: true }),
+ );
}
} else {
- await createMcpServer({
- displayName: args.displayName,
- url: args.url,
- isEnabled: true,
- });
+ applyServer(
+ await createMcpServer({
+ displayName: args.displayName,
+ url: args.url,
+ isEnabled: true,
+ }),
+ );
}
setMcpEnabledForChat(true);
// Search servers turn off the built-in Web Search to avoid overlap.
if (args.disablesWebSearch) setToolsEnabled(false);
} else if (args.existing) {
- await updateMcpServer(args.existing.id, { isEnabled: false });
+ applyServer(
+ await updateMcpServer(args.existing.id, { isEnabled: false }),
+ );
}
- await refresh();
} catch (err) {
toast.error("Failed to update MCP server", {
description: err instanceof Error ? err.message : String(err),
});
} finally {
- setPendingUrl(null);
+ pendingUrlsRef.current.delete(norm);
+ setPendingUrls(new Set(pendingUrlsRef.current));
}
}
@@ -197,7 +256,7 @@ export function McpComposerButton({
}) => (
<DropdownMenuItem
key={opts.key}
- disabled={pendingUrl === normalizeMcpUrl(opts.url)}
+ disabled={!serversLoaded || pendingUrls.has(normalizeMcpUrl(opts.url))}
onSelect={(e) => {
e.preventDefault();
void toggleServer({
@@ -263,11 +322,13 @@ export function McpComposerButton({
aria-label="Turn off MCP"
tabIndex={-1}
onPointerDown={(e) => {
- if (e.currentTarget.closest('[data-pill-compact="true"]')) return;
+ if (e.currentTarget.closest('[data-pill-compact="true"]'))
+ return;
e.stopPropagation();
}}
onClick={(e) => {
- if (e.currentTarget.closest('[data-pill-compact="true"]')) return;
+ if (e.currentTarget.closest('[data-pill-compact="true"]'))
+ return;
e.stopPropagation();
setMcpEnabledForChat(false);
}}
diff --git a/studio/frontend/src/features/chat/mcp-server-form.ts b/studio/frontend/src/features/chat/mcp-server-form.ts
new file mode 100644
index 00000000000..5ac374651da
--- /dev/null
+++ b/studio/frontend/src/features/chat/mcp-server-form.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export interface McpStdioSnapshot {
+ originalUrl: string;
+ command: string;
+ arguments: string[];
+}
+
+export type McpStdioUrlDecision =
+ | { kind: "reuse"; url: string }
+ | { kind: "encode"; command: string; arguments: string[] };
+
+export function createMcpStdioSnapshot(
+ originalUrl: string,
+ command: string,
+ arguments_: readonly string[] = [],
+): McpStdioSnapshot {
+ return {
+ originalUrl,
+ command,
+ arguments: [...arguments_],
+ };
+}
+
+function sameArguments(left: readonly string[], right: readonly string[]) {
+ return (
+ left.length === right.length &&
+ left.every((argument, index) => argument === right[index])
+ );
+}
+
+export function resolveMcpStdioUrl(
+ command: string,
+ arguments_: readonly string[],
+ snapshot: McpStdioSnapshot | null,
+): McpStdioUrlDecision {
+ if (
+ snapshot !== null &&
+ command === snapshot.command &&
+ sameArguments(arguments_, snapshot.arguments)
+ ) {
+ return { kind: "reuse", url: snapshot.originalUrl };
+ }
+
+ return { kind: "encode", command, arguments: [...arguments_] };
+}
diff --git a/studio/frontend/tests/mcp-server-arguments.test.ts b/studio/frontend/tests/mcp-server-arguments.test.ts
new file mode 100644
index 00000000000..3fc20f02044
--- /dev/null
+++ b/studio/frontend/tests/mcp-server-arguments.test.ts
@@ -0,0 +1,829 @@
+// 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 assert from "node:assert/strict";
+import { readdirSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import {
+ createMcpStdioSnapshot,
+ resolveMcpStdioUrl,
+} from "../src/features/chat/mcp-server-form.ts";
+import {
+ readAfterPendingMcpServerMutations,
+ readMcpServerMutationSnapshot,
+ subscribeToMcpServerMutationSettlements,
+ trackMcpServerMutation,
+ waitForPendingMcpServerMutations,
+} from "../src/features/chat/api/mcp-server-mutation-tracker.ts";
+
+function deferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+function sourceBetween(source: string, start: string, end: string): string {
+ const startIndex = source.indexOf(start);
+ const endIndex = source.indexOf(end, startIndex + start.length);
+ assert.notEqual(startIndex, -1, `missing source marker: ${start}`);
+ assert.notEqual(endIndex, -1, `missing source marker: ${end}`);
+ return source.slice(startIndex, endIndex);
+}
+
+function typescriptFilesUnder(directory: string): string[] {
+ const files: string[] = [];
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ files.push(...typescriptFilesUnder(path));
+ } else if (/\.[cm]?tsx?$/.test(entry.name)) {
+ files.push(path);
+ }
+ }
+ return files;
+}
+
+test("an unchanged stdio form reuses the exact original URL", () => {
+ const originalUrl = `python -m mod --name "a b" ''`;
+ const snapshot = createMcpStdioSnapshot(originalUrl, "python", [
+ "-m",
+ "mod",
+ "--name",
+ "a b",
+ "",
+ ]);
+
+ assert.deepEqual(
+ resolveMcpStdioUrl("python", ["-m", "mod", "--name", "a b", ""], snapshot),
+ { kind: "reuse", url: originalUrl },
+ );
+});
+
+test("missing legacy arguments default to an empty ordered list", () => {
+ const snapshot = createMcpStdioSnapshot("python", "python");
+ assert.deepEqual(snapshot.arguments, []);
+ assert.deepEqual(resolveMcpStdioUrl("python", [], snapshot), {
+ kind: "reuse",
+ url: "python",
+ });
+});
+
+test("command, order, value, and intentional empty argument changes require encoding", () => {
+ const snapshot = createMcpStdioSnapshot("python -m mod", "python", [
+ "-m",
+ "mod",
+ ]);
+
+ for (const [command, arguments_] of [
+ ["python3", ["-m", "mod"]],
+ ["python", ["mod", "-m"]],
+ ["python", ["-m", "other"]],
+ ["python", ["-m", "mod", ""]],
+ ] as const) {
+ assert.deepEqual(resolveMcpStdioUrl(command, arguments_, snapshot), {
+ kind: "encode",
+ command,
+ arguments: [...arguments_],
+ });
+ }
+});
+
+test("the helper never parses, splits, joins, trims, or quotes commands", () => {
+ const helper = readFileSync(
+ new URL("../src/features/chat/mcp-server-form.ts", import.meta.url),
+ "utf8",
+ );
+ assert.doesNotMatch(helper, /\.(?:split|join|trim)\s*\(/);
+ assert.doesNotMatch(helper, /JSON\.stringify|replace\s*\(/);
+});
+
+test("the dialog wires backend codec calls, stale guards, and a stdio-only editor", () => {
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const api = readFileSync(
+ new URL("../src/features/chat/api/mcp-servers-api.ts", import.meta.url),
+ "utf8",
+ );
+
+ assert.match(api, /mcpRequest\("\/stdio\/decode"/);
+ assert.match(api, /mcpRequest\("\/stdio\/encode"/);
+ assert.match(dialog, /await decodeMcpStdioCommand\(server\.url\)/);
+ assert.match(dialog, /await encodeMcpStdioCommand\(\{/);
+ assert.match(dialog, /formGenerationRef\.current !== generation/);
+ assert.match(dialog, /activeEditIdRef\.current !== server\.id/);
+ assert.match(
+ dialog,
+ /function handleOpenChange[\s\S]*formGenerationRef\.current \+= 1;[\s\S]*onOpenChange\(next\)/,
+ );
+ assert.match(dialog, /addressIsCommand && \(\s*<ArgumentsEditor/);
+ assert.match(dialog, /const addressIsCommand = form\.transport === "stdio"/);
+ assert.match(
+ dialog,
+ /function formWithAddress[\s\S]*transportFromAddress\([\s\S]*preservePartialHttp \? form\.credentialTransport : null[\s\S]*headers: transportChanged \? \[\] : form\.headers/,
+ );
+ assert.match(
+ dialog,
+ /queueMicrotask\(\(\) => \{\s*if \(cancelled\) return;[\s\S]*setView\(\{ kind: "list" \}\)/,
+ );
+ assert.match(
+ dialog,
+ /function ArgumentsEditor[\s\S]*\{ id: newRowId\(\), value: "" \}/,
+ );
+ assert.match(
+ dialog,
+ /form\.transport === "http" && \([\s\S]*Use OAuth sign-in/,
+ );
+ assert.match(dialog, /const decision = resolveMcpStdioUrl\(/);
+ assert.match(
+ dialog,
+ /decision\.kind === "reuse"[\s\S]*url = view\.kind === "edit" \? undefined : decision\.url/,
+ );
+ assert.match(
+ dialog,
+ /const url = stdio\s*\? await encodeStdioForGeneration\([\s\S]*testMcpServer\(\{\s*url,/,
+ );
+ assert.match(dialog, /return rows\.map\(\(row\) => row\.value\)/);
+ assert.match(
+ dialog,
+ /function ArgumentsEditor[\s\S]*data-reload-snapshot-sensitive/,
+ );
+ assert.match(api, /export function testMcpServer[\s\S]*body: \{\s*url:/);
+ assert.doesNotMatch(
+ dialog,
+ /npx -y @modelcontextprotocol\/server-filesystem \/tmp/,
+ );
+ assert.match(dialog, /URL or executable/);
+ assert.match(dialog, /https:\/\/example\.com\/mcp or npx/);
+ assert.match(dialog, /Add local arguments in the Arguments rows/);
+ assert.match(
+ dialog,
+ /setForm\(\(prev\) => formWithAddress\(prev, url, true\)\)/,
+ );
+ assert.doesNotMatch(dialog, /form\.url\.(?:split|join)\s*\(/);
+ assert.doesNotMatch(dialog, /form\.arguments[^;\n]*\.join\s*\(/);
+});
+
+test("every mutable MCP form editor is locked for the full pending interval", () => {
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const argumentsEditor = sourceBetween(
+ dialog,
+ "function ArgumentsEditor",
+ "function HeadersEditor",
+ );
+ const headersEditor = sourceBetween(
+ dialog,
+ "function HeadersEditor",
+ "export interface ChatMcpServersDialogProps",
+ );
+
+ assert.equal(
+ argumentsEditor.match(/disabled=\{disabled\}/g)?.length,
+ 3,
+ "argument add, input, and remove must all be locked",
+ );
+ assert.equal(
+ headersEditor.match(/disabled=\{disabled\}/g)?.length,
+ 4,
+ "header/env add, key, value, and remove must all be locked",
+ );
+ assert.match(
+ dialog,
+ /const formPending = importing \|\| codecPending \|\| testing \|\| saving/,
+ );
+ assert.match(
+ dialog,
+ /id="mcp-display-name"[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,
+ );
+ assert.match(
+ dialog,
+ /id="mcp-url"[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,
+ );
+ assert.match(
+ dialog,
+ /<ArgumentsEditor[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,
+ );
+ assert.match(
+ dialog,
+ /id="mcp-oauth"[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,
+ );
+ assert.match(
+ dialog,
+ /<HeadersEditor[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,
+ );
+});
+
+test("a decode error is announced and executable edits unlock manual recovery", () => {
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+
+ assert.match(
+ dialog,
+ /id="mcp-url"[\s\S]*?onChange=\{\(e\) => \{[\s\S]*?setCodecError\(null\)[\s\S]*?formWithAddress/,
+ );
+ assert.match(
+ dialog,
+ /role="alert"\s*aria-live="assertive"[\s\S]*?\{codecError\}/,
+ );
+ assert.match(
+ dialog,
+ /aria-busy=\{decodingCommand\}[\s\S]*role="status"\s*aria-live="polite"[\s\S]*Reading local command…/,
+ );
+ assert.match(
+ dialog,
+ /codecError && \([\s\S]*view\.kind === "edit"[\s\S]*void startEdit\(server\)[\s\S]*Retry/,
+ );
+ assert.match(
+ dialog,
+ /disabled=\{\s*formPending \|\|\s*codecError !== null \|\|\s*form\.transport === "unknown" \|\|\s*!form\.url\.trim\(\)/,
+ );
+});
+
+test("dialog actions and reconciliation stop when the dialog closes", () => {
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+
+ assert.match(
+ dialog,
+ /useEffect\(\(\) => \{\s*if \(!open\) \{[\s\S]*subscribeToMcpServerMutationSettlements/,
+ );
+ assert.match(
+ dialog,
+ /actionGenerationRef\.current !== generation \|\| !openRef\.current/,
+ );
+ assert.match(dialog, /open=\{open && confirmingDelete !== null\}/);
+ assert.match(
+ dialog,
+ /<Button size="sm" onClick=\{startCreate\} disabled=\{importing\}>/,
+ );
+});
+
+test("pending MCP actions remain keyed to their own server", () => {
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const composer = readFileSync(
+ new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),
+ "utf8",
+ );
+
+ assert.match(composer, /pendingUrlsRef = useRef\(new Set<string>\(\)\)/);
+ assert.match(
+ composer,
+ /pendingUrlsRef\.current\.delete\(norm\);\s*setPendingUrls\(new Set\(pendingUrlsRef\.current\)\)/,
+ );
+ assert.match(dialog, /refreshingIdsRef = useRef\(new Set<string>\(\)\)/);
+ assert.match(dialog, /togglingIdsRef = useRef\(new Set<string>\(\)\)/);
+ assert.match(
+ dialog,
+ /if \(!togglingIdsRef\.current\.has\(row\.id\)\) return row;[\s\S]*is_enabled: optimistic\.is_enabled/,
+ );
+});
+
+test("dialog closure is blocked while a CRUD mutation is in flight", () => {
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const closeHandler = sourceBetween(
+ dialog,
+ "function handleOpenChange",
+ "async function encodeStdioForGeneration",
+ );
+
+ assert.match(
+ closeHandler,
+ /if \(!next && \(\(saving && !codecPending\) \|\| busyIdsRef\.current\.size > 0\)\)[\s\S]*return;[\s\S]*if \(!next\) \{[\s\S]*formGenerationRef\.current \+= 1;/,
+ "the in-flight mutation guard must run before close invalidates the form generation",
+ );
+ assert.match(
+ dialog,
+ /<DialogContent[\s\S]*?showCloseButton=\{!\(saving && !codecPending\) && busyIds\.size === 0\}[\s\S]*?>/,
+ "the built-in close control must disappear during the same mutation window",
+ );
+ assert.match(
+ dialog,
+ /onClick=\{cancelForm\}[\s\S]*?disabled=\{saving && !codecPending\}/,
+ "the visible Cancel action must use the same mutation boundary",
+ );
+ assert.match(
+ dialog,
+ /async function encodeStdioForGeneration[\s\S]*setCodecPending\(true\);[\s\S]*await encodeMcpStdioCommand/,
+ "codec encoding remains distinguishable so it can still be cancelled before CRUD starts",
+ );
+});
+
+test("composer applies mutation responses before releasing each preset", () => {
+ const composer = readFileSync(
+ new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),
+ "utf8",
+ );
+
+ assert.match(
+ composer,
+ /const applyServer = useCallback[\s\S]*setServers\(\(current\)[\s\S]*candidate\.id === server\.id/,
+ );
+ assert.match(
+ composer,
+ /applyServer\(\s*await createMcpServer\([\s\S]*pendingUrlsRef\.current\.delete\(norm\)/,
+ );
+ assert.match(
+ composer,
+ /applyServer\(\s*await updateMcpServer\([\s\S]*pendingUrlsRef\.current\.delete\(norm\)/,
+ );
+ assert.match(
+ composer,
+ /const \[serversLoaded, setServersLoaded\] = useState\(false\)[\s\S]*const hasLoadedServerSnapshotRef = useRef\(false\);[\s\S]*setServersLoaded\(false\);[\s\S]*setServers\(rows\);\s*hasLoadedServerSnapshotRef\.current = true;\s*setServersLoaded\(true\)/,
+ );
+ assert.match(
+ composer,
+ /catch \{\s*if \(\s*listRefreshGenerationRef\.current === generation &&\s*hasLoadedServerSnapshotRef\.current\s*\) \{\s*setServersLoaded\(true\);/,
+ );
+ assert.match(
+ composer,
+ /disabled=\{\s*!serversLoaded \|\| pendingUrls\.has\(normalizeMcpUrl\(opts\.url\)\)/,
+ );
+});
+
+test("full unmount invalidates cancellable stdio encode continuations", async () => {
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const refsAndCleanup = sourceBetween(
+ dialog,
+ "const formGenerationRef = useRef(0)",
+ "const refresh = useCallback",
+ );
+ const openLifecycle = sourceBetween(
+ dialog,
+ "useEffect(() => {\n formGenerationRef.current += 1;",
+ "function startCreate",
+ );
+ const encode = sourceBetween(
+ dialog,
+ "async function encodeStdioForGeneration",
+ "async function testConnection",
+ );
+ const testContinuation = sourceBetween(
+ dialog,
+ "async function testConnection",
+ "async function submitForm",
+ );
+ const crudContinuation = sourceBetween(
+ dialog,
+ "async function submitForm",
+ "async function onImportFile",
+ );
+
+ assert.match(
+ refsAndCleanup,
+ /useEffect\(\(\) => \{\s*return \(\) => \{\s*formGenerationRef\.current \+= 1;\s*actionGenerationRef\.current \+= 1;\s*activeEditIdRef\.current = null;[\s\S]*\};\s*\}, \[\]\)/,
+ "the component mount lifetime must invalidate the form identity on teardown",
+ );
+ assert.match(
+ openLifecycle,
+ /queueMicrotask\(\(\) => \{\s*if \(cancelled\) return;[\s\S]*setCodecPending\(false\);\s*setDecodingCommand\(false\);[\s\S]*setConfirmingDelete\(null\);[\s\S]*if \(!open\) return;/,
+ "route teardown must clear transient form state before a later reopen",
+ );
+ assert.match(
+ encode,
+ /await encodeMcpStdioCommand\([\s\S]*formGenerationRef\.current !== generation\) return null/,
+ );
+ assert.match(
+ testContinuation,
+ /await encodeStdioForGeneration\([\s\S]*if \(url === null \|\| formGenerationRef\.current !== generation\) return;[\s\S]*testMcpServer\(/,
+ );
+ assert.match(
+ crudContinuation,
+ /await encodeStdioForGeneration\([\s\S]*if \(encodedUrl === null\) return;[\s\S]*if \(formGenerationRef\.current !== generation\) return;[\s\S]*(?:updateMcpServer|createMcpServer)\(/,
+ );
+ assert.match(
+ crudContinuation,
+ /await updateMcpServer\([\s\S]*if \(formGenerationRef\.current !== generation\) return;\s*toast\.success\("MCP server updated"\)/,
+ "an unmounted edit must not emit a stale success toast",
+ );
+ assert.match(
+ crudContinuation,
+ /await createMcpServer\([\s\S]*if \(formGenerationRef\.current !== generation\) return;\s*toast\.success\("MCP server added"\)/,
+ "an unmounted create must not emit a stale success toast",
+ );
+
+ const generation = { current: 7 };
+ const activeEditId = { current: "server-1" as string | null };
+ const encoded = deferred<string>();
+ let testCalls = 0;
+ let createCalls = 0;
+ let updateCalls = 0;
+ let staleUiEffects = 0;
+
+ async function continueAfterEncode(kind: "test" | "create" | "update") {
+ const capturedGeneration = generation.current;
+ await encoded.promise;
+ if (generation.current !== capturedGeneration) return;
+ if (kind === "test") testCalls += 1;
+ if (kind === "create") createCalls += 1;
+ if (kind === "update") updateCalls += 1;
+ staleUiEffects += 1;
+ }
+
+ const continuations = [
+ continueAfterEncode("test"),
+ continueAfterEncode("create"),
+ continueAfterEncode("update"),
+ ];
+ generation.current += 1;
+ activeEditId.current = null;
+ encoded.resolve("encoded command");
+ await Promise.all(continuations);
+
+ assert.equal(activeEditId.current, null);
+ assert.equal(testCalls, 0);
+ assert.equal(createCalls, 0);
+ assert.equal(updateCalls, 0);
+ assert.equal(staleUiEffects, 0);
+});
+
+test("open-time reconciliation waits for every mutation across component lifetimes", async () => {
+ const first = deferred<void>();
+ const second = deferred<void>();
+ const batchNotified = deferred<void>();
+ let notificationCount = 0;
+ const unsubscribe = subscribeToMcpServerMutationSettlements(() => {
+ notificationCount += 1;
+ batchNotified.resolve();
+ });
+ trackMcpServerMutation(first.promise);
+
+ let reconciled = false;
+ const reconciliation = waitForPendingMcpServerMutations().then(() => {
+ reconciled = true;
+ });
+ await Promise.resolve();
+ assert.equal(
+ reconciled,
+ false,
+ "the first pending mutation must hold refresh",
+ );
+
+ // Simulate another API mutation starting after the opening component has
+ // already captured and begun waiting on the first batch.
+ trackMcpServerMutation(second.promise);
+ first.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ assert.equal(
+ reconciled,
+ false,
+ "a mutation added during settlement must also hold refresh",
+ );
+
+ second.resolve();
+ await reconciliation;
+ await batchNotified.promise;
+ unsubscribe();
+ assert.equal(reconciled, true);
+ assert.equal(
+ notificationCount,
+ 2,
+ "each settled mutation publishes its epoch",
+ );
+});
+
+test("a settled successor can reconcile while an older mutation remains pending", async () => {
+ const first = deferred<void>();
+ const second = deferred<void>();
+ let authoritativeRows = ["old"];
+ const snapshots: string[][] = [];
+ const successorVisible = deferred<void>();
+ const predecessorVisible = deferred<void>();
+
+ const unsubscribe = subscribeToMcpServerMutationSettlements(() => {
+ void readMcpServerMutationSnapshot(async () => [...authoritativeRows]).then(
+ (rows) => {
+ snapshots.push(rows);
+ if (rows.includes("successor")) successorVisible.resolve();
+ if (rows.includes("predecessor")) predecessorVisible.resolve();
+ },
+ );
+ });
+
+ trackMcpServerMutation(first.promise);
+ trackMcpServerMutation(second.promise);
+ authoritativeRows = ["old", "successor"];
+ second.resolve();
+ await successorVisible.promise;
+ assert.deepEqual(snapshots.at(-1), ["old", "successor"]);
+
+ authoritativeRows = ["old", "successor", "predecessor"];
+ first.resolve();
+ await predecessorVisible.promise;
+ await waitForPendingMcpServerMutations();
+ unsubscribe();
+ assert.deepEqual(snapshots.at(-1), ["old", "successor", "predecessor"]);
+});
+
+test("failed mutations settle waiters without leaking a tracker rejection", async () => {
+ const mutation = deferred<void>();
+ const tracked = trackMcpServerMutation(mutation.promise);
+ assert.equal(tracked, mutation.promise);
+ const expectedFailure = assert.rejects(tracked, /save failed/);
+ const reconciliation = waitForPendingMcpServerMutations();
+
+ mutation.reject(new Error("save failed"));
+ await expectedFailure;
+ await reconciliation;
+ await waitForPendingMcpServerMutations();
+});
+
+test("settlement refreshes a mounted background consumer after another consumer mutates", async () => {
+ let authoritativeRows = ["old"];
+ let backgroundRows = await readAfterPendingMcpServerMutations(async () => [
+ ...authoritativeRows,
+ ]);
+ let foregroundRows = [...backgroundRows];
+ const backgroundUpdated = deferred<void>();
+ let notificationCount = 0;
+ let notifiedEpoch = 0;
+
+ const unsubscribe = subscribeToMcpServerMutationSettlements((epoch) => {
+ notificationCount += 1;
+ notifiedEpoch = epoch;
+ void readAfterPendingMcpServerMutations(async () => [
+ ...authoritativeRows,
+ ]).then((rows) => {
+ backgroundRows = rows;
+ backgroundUpdated.resolve();
+ });
+ });
+
+ const mutation = deferred<string>();
+ const tracked = trackMcpServerMutation(mutation.promise);
+ assert.equal(tracked, mutation.promise);
+ authoritativeRows = ["new"];
+ mutation.resolve("saved");
+
+ assert.equal(await tracked, "saved");
+ foregroundRows = await readAfterPendingMcpServerMutations(async () => [
+ ...authoritativeRows,
+ ]);
+ await backgroundUpdated.promise;
+ unsubscribe();
+
+ assert.deepEqual(foregroundRows, ["new"]);
+ assert.deepEqual(backgroundRows, ["new"]);
+ assert.equal(notificationCount, 1);
+ assert.ok(
+ notifiedEpoch >= 2,
+ "registration and settlement both advance epoch",
+ );
+});
+
+test("a list read retries when a mutation starts after its pre-read drain", async () => {
+ let authoritativeRows = ["old"];
+ let readCount = 0;
+ const firstReadStarted = deferred<void>();
+ const firstReadResult = deferred<string[]>();
+
+ const stableRead = readAfterPendingMcpServerMutations(async () => {
+ readCount += 1;
+ if (readCount === 1) {
+ firstReadStarted.resolve();
+ return firstReadResult.promise;
+ }
+ return [...authoritativeRows];
+ });
+
+ await firstReadStarted.promise;
+ const mutation = deferred<void>();
+ const tracked = trackMcpServerMutation(mutation.promise);
+ firstReadResult.resolve(["old"]);
+ authoritativeRows = ["new"];
+ mutation.resolve();
+
+ await tracked;
+ assert.deepEqual(await stableRead, ["new"]);
+ assert.equal(readCount, 2, "the overlapping old read must be retried once");
+});
+
+test("a rejected overlapping list read retries after settlement subscribers join it", async () => {
+ let authoritativeRows = ["old"];
+ let readCount = 0;
+ let listRequest: Promise<string[]> | null = null;
+ const firstReadStarted = deferred<void>();
+ const firstReadResult = deferred<string[]>();
+
+ function listRows(): Promise<string[]> {
+ if (listRequest) return listRequest;
+ const request = readAfterPendingMcpServerMutations(async () => {
+ readCount += 1;
+ if (readCount === 1) {
+ firstReadStarted.resolve();
+ return firstReadResult.promise;
+ }
+ return [...authoritativeRows];
+ });
+ listRequest = request;
+ void request.then(
+ () => {
+ if (listRequest === request) listRequest = null;
+ },
+ () => {
+ if (listRequest === request) listRequest = null;
+ },
+ );
+ return request;
+ }
+
+ const originalRequest = listRows();
+ await firstReadStarted.promise;
+
+ const subscriberJoined = deferred<void>();
+ let subscriberRequest: Promise<string[]> | null = null;
+ let notificationCount = 0;
+ const unsubscribe = subscribeToMcpServerMutationSettlements(() => {
+ notificationCount += 1;
+ subscriberRequest = listRows();
+ subscriberJoined.resolve();
+ });
+
+ const mutation = deferred<void>();
+ const tracked = trackMcpServerMutation(mutation.promise);
+ authoritativeRows = ["new"];
+ mutation.resolve();
+ await tracked;
+ await subscriberJoined.promise;
+
+ assert.equal(
+ subscriberRequest,
+ originalRequest,
+ "the settlement subscriber must initially join the in-flight GET",
+ );
+ firstReadResult.reject(new Error("transient list failure"));
+
+ assert.deepEqual(await originalRequest, ["new"]);
+ assert.deepEqual(await subscriberRequest, ["new"]);
+ unsubscribe();
+ assert.equal(notificationCount, 1);
+ assert.equal(readCount, 2, "the failed overlapping GET gets one fresh retry");
+});
+
+test("a list rejection without an epoch change preserves the original error", async () => {
+ const expected = new Error("unrelated list failure");
+ let readCount = 0;
+ await assert.rejects(
+ readAfterPendingMcpServerMutations(async () => {
+ readCount += 1;
+ throw expected;
+ }),
+ (error) => error === expected,
+ );
+ assert.equal(readCount, 1, "an unrelated failure must not be retried");
+});
+
+test("every list consumer uses the shared pending-mutation read barrier", () => {
+ const chatRoot = fileURLToPath(
+ new URL("../src/features/chat/", import.meta.url),
+ );
+ const dialog = readFileSync(
+ new URL(
+ "../src/features/chat/chat-mcp-servers-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const api = readFileSync(
+ new URL("../src/features/chat/api/mcp-servers-api.ts", import.meta.url),
+ "utf8",
+ );
+ const composer = readFileSync(
+ new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),
+ "utf8",
+ );
+ const listApi = sourceBetween(
+ api,
+ "export function listMcpServers",
+ "export function createMcpServer",
+ );
+ const dialogRefresh = sourceBetween(
+ dialog,
+ "const refresh = useCallback",
+ "useEffect(() =>",
+ );
+ const composerRefresh = sourceBetween(
+ composer,
+ "const refresh = useCallback",
+ "// Load the server list on mount",
+ );
+
+ const listOccurrences = typescriptFilesUnder(chatRoot)
+ .flatMap((file) => {
+ const count =
+ readFileSync(file, "utf8").match(/\blistMcpServers\s*\(/g)?.length ?? 0;
+ return Array.from({ length: count }, () =>
+ relative(chatRoot, file).replaceAll("\\", "/"),
+ );
+ })
+ .sort();
+
+ assert.deepEqual(listOccurrences, [
+ "api/mcp-servers-api.ts",
+ "chat-mcp-servers-dialog.tsx",
+ "mcp-composer-button.tsx",
+ ]);
+
+ assert.equal(
+ api.match(/return trackMcpServerMutation\(/g)?.length,
+ 4,
+ "create, update, delete, and import must register at the API boundary",
+ );
+ assert.match(
+ listApi,
+ /readAfterPendingMcpServerMutations\(\(\) =>[\s\S]*mcpRequest<McpServerConfig\[\]>\("\/"\)/,
+ "the shared query boundary must retry reads that overlap tracked mutations",
+ );
+ assert.match(
+ listApi,
+ /readMcpServerMutationSnapshot\(\(\) =>[\s\S]*mcpRequest<McpServerConfig\[\]>\("\/"\)/,
+ "settlement refreshes must not wait on unrelated older mutations",
+ );
+ assert.match(
+ listApi,
+ /minimumMutationEpoch \?\? getMcpServerMutationEpoch\(\)[\s\S]*mcpServerSettlementListRequest\.minimumEpoch >= requestedEpoch/,
+ "a newer settlement must replace a snapshot cached for an older epoch",
+ );
+ assert.match(
+ listApi,
+ /const slot = \{ minimumEpoch: requestedEpoch, promise: request \}[\s\S]*mcpServerSettlementListRequest === slot/,
+ "an older completion must not clear the successor epoch slot",
+ );
+ assert.match(
+ listApi,
+ /if \(mcpServerListRequest\) return mcpServerListRequest/,
+ );
+ assert.match(
+ dialogRefresh,
+ /await listMcpServers\(\{\s*waitForPendingMutations,\s*minimumMutationEpoch,\s*\}\)/,
+ );
+ assert.match(
+ composerRefresh,
+ /await listMcpServers\(\{\s*waitForPendingMutations,\s*minimumMutationEpoch,\s*\}\)/,
+ );
+ assert.match(
+ dialog,
+ /subscribeToMcpServerMutationSettlements\(\(epoch\) => \{\s*void refresh\(false, epoch\)/,
+ );
+ assert.match(
+ composer,
+ /subscribeToMcpServerMutationSettlements\(\(epoch\) => \{\s*void refresh\(false, epoch\)/,
+ );
+ assert.match(
+ dialogRefresh,
+ /listRefreshGenerationRef\.current !== generation/,
+ );
+ assert.match(
+ composerRefresh,
+ /listRefreshGenerationRef\.current !== generation/,
+ );
+ assert.doesNotMatch(dialog, /waitForPendingMcpServerMutations/);
+ assert.doesNotMatch(composer, /waitForPendingMcpServerMutations/);
+ assert.doesNotMatch(dialog, /await refresh\(\)/);
+ assert.doesNotMatch(composer, /await refresh\(\)/);
+});
diff --git a/tests/studio/playwright_mcp_arguments.py b/tests/studio/playwright_mcp_arguments.py
new file mode 100644
index 00000000000..3309238b508
--- /dev/null
+++ b/tests/studio/playwright_mcp_arguments.py
@@ -0,0 +1,490 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import sys
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+from playwright.sync_api import expect, sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ chromium_launch_args,
+ install_view_transition_killer,
+ install_wall_clock_watchdog,
+ wait_for_health,
+)
+
+
+BASE = os.environ["BASE_URL"].rstrip("/")
+OLD = os.environ["STUDIO_OLD_PW"]
+NEW = os.environ["STUDIO_NEW_PW"]
+ART = Path(os.environ.get("PW_ART_DIR", "logs/playwright-mcp-arguments"))
+BROWSER = os.environ.get("STUDIO_PLAYWRIGHT_BROWSER", "chromium").lower()
+CHANNEL = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL") or None
+WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "420"))
+SOURCE_FIXTURE = (
+ Path(__file__).resolve().parents[2]
+ / "studio"
+ / "backend"
+ / "tests"
+ / "fixtures"
+ / "mcp_argument_echo_server.py"
+)
+MCP_PYTHON = os.environ.get("STUDIO_MCP_PYTHON", sys.executable)
+
+
+def info(message: str) -> None:
+ print(f"[mcp-ui] {message}", flush = True)
+
+
+def api(
+ path: str,
+ payload: dict | None = None,
+ token: str | None = None,
+ method: str = "POST",
+) -> dict | list:
+ request = urllib.request.Request(
+ BASE + path,
+ data = json.dumps(payload).encode() if payload is not None else None,
+ headers = {
+ "Content-Type": "application/json",
+ **({"Authorization": f"Bearer {token}"} if token else {}),
+ },
+ method = method,
+ )
+ with urllib.request.urlopen(request, timeout = 30) as response:
+ body = response.read()
+ return json.loads(body) if body else {}
+
+
+def authenticate() -> dict:
+ try:
+ session = api("/api/auth/login", {"username": "unsloth", "password": NEW})
+ if not session.get("must_change_password"):
+ return session
+ except urllib.error.HTTPError:
+ pass
+ initial = api("/api/auth/login", {"username": "unsloth", "password": OLD})
+ try:
+ api(
+ "/api/auth/change-password",
+ {"current_password": OLD, "new_password": NEW},
+ initial["access_token"],
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code not in (400, 401, 403):
+ raise
+ return api("/api/auth/login", {"username": "unsloth", "password": NEW})
+
+
+def remove_prior_test_servers(token: str) -> None:
+ servers = api("/api/mcp/servers/", token = token, method = "GET")
+ assert isinstance(servers, list)
+ for server in servers:
+ if server.get("display_name") not in (
+ "Playwright argument echo",
+ "Playwright imported echo",
+ "Unsloth Docs",
+ ):
+ continue
+ api(
+ f"/api/mcp/servers/{server['id']}",
+ token = token,
+ method = "DELETE",
+ )
+
+
+def open_dialog(page):
+ page.get_by_role("button", name = "MCP servers").click()
+ page.get_by_role("menuitem", name = "Manage MCP servers").press("Enter")
+ dialog = page.get_by_role("dialog", name = "MCP Servers")
+ expect(dialog).to_be_visible()
+ return dialog
+
+
+def row_for(dialog, name: str):
+ row = dialog.locator("li").filter(has_text = name)
+ expect(row).to_have_count(1)
+ return row
+
+
+def fill_arguments(dialog, arguments: list[str]) -> None:
+ for index, argument in enumerate(arguments, start = 1):
+ dialog.get_by_role("button", name = "Add argument").click()
+ dialog.get_by_role("textbox", name = f"Argument {index}", exact = True).fill(argument)
+
+
+def fill_environment(dialog, values: dict[str, str]) -> None:
+ for key, value in values.items():
+ dialog.get_by_role("button", name = "Add variable").click()
+ keys = dialog.get_by_placeholder("Variable name")
+ vals = dialog.get_by_placeholder("Variable value")
+ keys.nth(keys.count() - 1).fill(key)
+ vals.nth(vals.count() - 1).fill(value)
+
+
+def assert_arguments(dialog, expected: list[str]) -> None:
+ inputs = dialog.locator('[aria-label^="Argument "]')
+ expect(inputs).to_have_count(len(expected))
+ for index, value in enumerate(expected):
+ expect(inputs.nth(index)).to_have_value(value)
+
+
+def screenshot(dialog, name: str) -> None:
+ dialog.screenshot(path = str(ART / f"{name}-{BROWSER}.png"))
+
+
+def delay_real_response(seconds: float):
+ def handler(route):
+ response = route.fetch()
+ time.sleep(seconds)
+ route.fulfill(response = response)
+
+ return handler
+
+
+def hold_next_request(page, pattern: str) -> list:
+ held: list = []
+ page.route(pattern, lambda route: held.append(route), times = 1)
+ return held
+
+
+def release_request(page, held: list) -> None:
+ page.wait_for_timeout(50)
+ assert len(held) == 1
+ held[0].continue_()
+
+
+def run(page, launch_log: Path, fixture: Path) -> None:
+ page.goto(BASE + "/hub", wait_until = "domcontentloaded")
+ page.goto(BASE + "/chat", wait_until = "domcontentloaded")
+ page.wait_for_timeout(1000)
+ if page.url.startswith(BASE + "/login") or page.url.startswith(BASE + "/change-password"):
+ raise AssertionError(f"not authenticated: {page.url}")
+
+ dialog = open_dialog(page)
+ dialog.get_by_role("button", name = "Add server").click()
+ dialog.locator("#mcp-display-name").fill("Playwright argument echo")
+ dialog.locator("#mcp-url").fill(MCP_PYTHON)
+ arguments = [
+ str(fixture),
+ "--flag",
+ "",
+ "a b",
+ 'quote"inside',
+ "single'quote",
+ "trailing\\",
+ "https://example.com/value?q=a%20b",
+ " keep outer spaces ",
+ ]
+ fill_arguments(dialog, arguments)
+ environment = {
+ "UNSLOTH_MCP_ARGUMENT_MARKER": "playwright create",
+ "UNSLOTH_MCP_ARGUMENT_LOG": str(launch_log),
+ }
+ fill_environment(dialog, environment)
+ screenshot(dialog, "fixed-create-filled")
+
+ dialog.get_by_role("button", name = "Test connection").click()
+ expect(page.get_by_text("Connected (1 tool)")).to_be_visible(timeout = 30_000)
+ dialog.get_by_role("button", name = "Add server").click()
+ row = row_for(dialog, "Playwright argument echo")
+ expect(row).to_contain_text("--flag")
+
+ page.route("**/api/mcp/servers/stdio/decode", delay_real_response(1.5))
+ row.get_by_role("button", name = "Edit server").click(no_wait_after = True)
+ loading = dialog.get_by_text("Reading local command…", exact = True)
+ expect(loading).to_be_visible()
+ screenshot(dialog, "fixed-edit-loading")
+ page.unroute("**/api/mcp/servers/stdio/decode")
+ expect(loading).to_be_hidden(timeout = 10_000)
+ assert_arguments(dialog, arguments)
+ screenshot(dialog, "fixed-edit-hydrated")
+
+ dialog.get_by_role("button", name = "Cancel").click()
+ dialog.get_by_role("button", name = "Close").click()
+ page.reload(wait_until = "domcontentloaded")
+ page.wait_for_timeout(500)
+ dialog = open_dialog(page)
+ row = row_for(dialog, "Playwright argument echo")
+ row.get_by_role("button", name = "Edit server").click()
+ assert_arguments(dialog, arguments)
+
+ edited = [str(fixture), "second", "", "first", "a&b", "x|y", "%TOKEN%"]
+ inputs = dialog.locator('[aria-label^="Argument "]')
+ while inputs.count() > len(edited):
+ dialog.get_by_role("button", name = f"Remove argument {inputs.count()}").click()
+ for index, value in enumerate(edited):
+ dialog.get_by_role("textbox", name = f"Argument {index + 1}", exact = True).fill(value)
+ dialog.get_by_placeholder("Variable value").first.fill("playwright edited")
+ dialog.get_by_role("button", name = "Save changes").click()
+ expect(page.get_by_text("MCP server updated")).to_be_visible()
+ row = row_for(dialog, "Playwright argument echo")
+ row.get_by_role("button", name = "Edit server").click()
+ assert_arguments(dialog, edited)
+ screenshot(dialog, "fixed-edit-persisted")
+
+ dialog.get_by_role("button", name = "Cancel").click()
+ row = row_for(dialog, "Playwright argument echo")
+ launches_before_refresh = len(launch_log.read_text(encoding = "utf-8").splitlines())
+ held_refresh = hold_next_request(page, "**/api/mcp/servers/*/refresh")
+ row.get_by_role("button", name = "Refresh tools").click(no_wait_after = True)
+ expect(row.get_by_role("switch", name = "Enable server")).to_be_disabled()
+ expect(row.get_by_role("button", name = "Refresh tools")).to_be_disabled()
+ expect(row.get_by_role("button", name = "Edit server")).to_be_disabled()
+ expect(row.get_by_role("button", name = "Delete server")).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Close")).to_have_count(0)
+ screenshot(dialog, "fixed-row-busy")
+ release_request(page, held_refresh)
+ expect(page.get_by_text('Refreshed "Playwright argument echo" (1 tool)')).to_be_visible(
+ timeout = 30_000
+ )
+ launches_after_refresh = len(launch_log.read_text(encoding = "utf-8").splitlines())
+ assert launches_after_refresh == launches_before_refresh + 1
+
+ imported = {
+ "mcpServers": {
+ "Playwright imported echo": {
+ "command": MCP_PYTHON,
+ "args": [str(fixture), "imported", "", "with spaces", 'say "hello"'],
+ "env": {
+ "UNSLOTH_MCP_ARGUMENT_MARKER": "playwright import",
+ "UNSLOTH_MCP_ARGUMENT_LOG": str(launch_log),
+ },
+ }
+ }
+ }
+ held_import = hold_next_request(page, "**/api/mcp/servers/import")
+ dialog.locator('input[type="file"]').set_input_files(
+ {
+ "name": "mcp-config.json",
+ "mimeType": "application/json",
+ "buffer": json.dumps(imported).encode(),
+ }
+ )
+ expect(dialog.get_by_role("button", name = "Import")).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Add server")).to_be_disabled()
+ dialog.get_by_role("button", name = "Close").click()
+ composer = page.get_by_role("button", name = "MCP servers")
+ composer.click()
+ expect(page.get_by_role("menuitem", name = "Unsloth Docs")).to_be_disabled()
+ page.get_by_role("menu").screenshot(
+ path = str(ART / f"fixed-composer-import-reconciliation-busy-{BROWSER}.png")
+ )
+ page.keyboard.press("Escape")
+ dialog = open_dialog(page)
+ expect(dialog.get_by_role("button", name = "Import")).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Add server")).to_be_disabled()
+ screenshot(dialog, "fixed-import-reopened-busy")
+ release_request(page, held_import)
+ expect(dialog.get_by_role("button", name = "Import")).to_be_enabled(timeout = 10_000)
+ imported_row = row_for(dialog, "Playwright imported echo")
+ imported_row.get_by_role("button", name = "Edit server").click()
+ assert_arguments(dialog, [str(fixture), "imported", "", "with spaces", 'say "hello"'])
+ dialog.get_by_role("button", name = "Test connection").click()
+ expect(page.get_by_text("Connected (1 tool)")).to_be_visible(timeout = 30_000)
+ dialog.get_by_role("button", name = "Cancel").click()
+ imported_row = row_for(dialog, "Playwright imported echo")
+ imported_row.get_by_role("button", name = "Refresh tools").click()
+ expect(page.get_by_text('Refreshed "Playwright imported echo" (1 tool)')).to_be_visible(
+ timeout = 30_000
+ )
+
+ row = row_for(dialog, "Playwright argument echo")
+ page.route(
+ "**/api/mcp/servers/stdio/decode",
+ lambda route: route.fulfill(
+ status = 500,
+ content_type = "application/json",
+ body = json.dumps({"detail": "forced decode failure"}),
+ ),
+ times = 1,
+ )
+ row.get_by_role("button", name = "Edit server").click()
+ expect(dialog.get_by_role("alert")).to_contain_text("forced decode failure")
+ expect(dialog.locator("#mcp-url")).not_to_have_value("")
+ screenshot(dialog, "fixed-edit-error")
+ dialog.get_by_role("button", name = "Retry").click()
+ assert_arguments(dialog, edited)
+
+ expect(dialog.get_by_placeholder("Variable name")).to_have_count(2)
+ dialog.locator("#mcp-url").fill("https://example.com/mcp")
+ expect(dialog.get_by_text("Custom headers", exact = True)).to_be_visible()
+ expect(dialog.get_by_placeholder("Header name")).to_have_count(0)
+ dialog.get_by_role("button", name = "Add header").click()
+ dialog.get_by_placeholder("Header name").fill("Authorization")
+ dialog.get_by_placeholder("Header value").fill("Bearer remote-secret")
+ oauth = dialog.get_by_role("switch", name = "Use OAuth sign-in")
+ oauth.click()
+ expect(oauth).to_be_checked()
+ address = dialog.locator("#mcp-url")
+ address.fill("")
+ address.press_sequentially("https://example.org/mcp")
+ expect(dialog.get_by_placeholder("Header name")).to_have_count(1)
+ expect(dialog.get_by_placeholder("Header name")).to_have_value("Authorization")
+ expect(oauth).to_be_checked()
+ screenshot(dialog, "fixed-http-typing-preserves-credentials")
+ address.fill("https:/")
+ expect(dialog.get_by_role("button", name = "Save changes")).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Test connection")).to_be_disabled()
+ screenshot(dialog, "fixed-partial-http-save-disabled")
+ address.fill("http")
+ expect(dialog.get_by_role("button", name = "Save changes")).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Test connection")).to_be_disabled()
+ screenshot(dialog, "fixed-ambiguous-http-save-disabled")
+ address.blur()
+ expect(dialog.get_by_text("Environment variables", exact = True)).to_be_visible()
+ expect(dialog.get_by_placeholder("Variable name")).to_have_count(0)
+ expect(dialog.get_by_role("switch", name = "Use OAuth sign-in")).to_have_count(0)
+ screenshot(dialog, "fixed-ambiguous-http-command-clears-credentials")
+ dialog.locator("#mcp-url").fill(MCP_PYTHON)
+ expect(dialog.get_by_text("Environment variables", exact = True)).to_be_visible()
+ expect(dialog.get_by_placeholder("Variable name")).to_have_count(0)
+ screenshot(dialog, "fixed-transport-credentials-cleared")
+ dialog.get_by_role("button", name = "Cancel").click()
+
+ dialog.get_by_role("button", name = "Close").click()
+ composer = page.get_by_role("button", name = "MCP servers")
+ expect(composer).to_be_visible()
+ composer.click()
+ preset = page.get_by_role("menuitem", name = "Unsloth Docs")
+ expect(preset).to_be_enabled()
+ page.wait_for_timeout(250)
+ held_list: list = []
+
+ def hold_first_list(route):
+ if route.request.method == "GET" and not held_list:
+ held_list.append(route)
+ else:
+ route.continue_()
+
+ writes = []
+ page.on(
+ "request",
+ lambda request: (
+ writes.append(request.method)
+ if "/api/mcp/servers/" in request.url and request.method in ("POST", "PUT")
+ else None
+ ),
+ )
+ page.route("**/api/mcp/servers/", hold_first_list)
+ preset.click()
+ expect(preset).to_be_disabled(timeout = 10_000)
+ deadline = time.monotonic() + 10
+ while (not held_list or writes.count("POST") != 1) and time.monotonic() < deadline:
+ page.wait_for_timeout(50)
+ assert held_list and writes.count("POST") == 1
+ page.get_by_role("menu").screenshot(
+ path = str(ART / f"fixed-composer-preset-waits-for-refresh-{BROWSER}.png")
+ )
+ release_request(page, held_list)
+ page.unroute("**/api/mcp/servers/", hold_first_list)
+ expect(preset).to_be_enabled(timeout = 10_000)
+ preset.click()
+ page.wait_for_timeout(500)
+ assert writes.count("POST") == 1
+ assert writes.count("PUT") == 1
+ failed_list = []
+
+ def fail_next_list(route):
+ if route.request.method == "GET" and not failed_list:
+ failed_list.append(route.request.url)
+ route.fulfill(status = 503, json = {"detail": "temporary list failure"})
+ else:
+ route.continue_()
+
+ page.route("**/api/mcp/servers/", fail_next_list)
+ preset.click()
+ deadline = time.monotonic() + 10
+ while (not failed_list or writes.count("PUT") != 2) and time.monotonic() < deadline:
+ page.wait_for_timeout(50)
+ assert failed_list and writes.count("PUT") == 2
+ expect(preset).to_be_enabled()
+ page.get_by_role("menu").screenshot(
+ path = str(ART / f"fixed-composer-recovers-after-refresh-error-{BROWSER}.png")
+ )
+ page.unroute("**/api/mcp/servers/", fail_next_list)
+ page.get_by_role("menuitem", name = "Manage MCP servers").press("Enter")
+ dialog = page.get_by_role("dialog", name = "MCP Servers")
+ expect(dialog).to_be_visible()
+ expect(dialog.locator("li").filter(has_text = "Unsloth Docs")).to_have_count(1)
+ screenshot(dialog, "fixed-composer-preset-no-duplicate")
+
+ row = row_for(dialog, "Playwright argument echo")
+ row.get_by_role("button", name = "Delete server").click()
+ expect(page.get_by_role("alertdialog", name = "Delete MCP server")).to_be_visible()
+ page.goto(BASE + "/hub", wait_until = "domcontentloaded")
+ expect(page).to_have_url(BASE + "/hub")
+ expect(page.get_by_role("alertdialog", name = "Delete MCP server")).to_have_count(0)
+ page.screenshot(path = str(ART / f"fixed-delete-route-closed-{BROWSER}.png"))
+
+ records = [json.loads(line) for line in launch_log.read_text(encoding = "utf-8").splitlines()]
+ expected_runs = [record for record in records if record["marker"] == "playwright edited"]
+ assert expected_runs
+ assert all(record["arguments"] == edited[1:] for record in expected_runs)
+ imported_runs = [record for record in records if record["marker"] == "playwright import"]
+ assert imported_runs
+ assert all(
+ record["arguments"] == ["imported", "", "with spaces", 'say "hello"']
+ for record in imported_runs
+ )
+
+
+def main() -> int:
+ ART.mkdir(parents = True, exist_ok = True)
+ fixture_dir = ART / "fixture directory with spaces"
+ fixture_dir.mkdir(parents = True, exist_ok = True)
+ fixture = fixture_dir / SOURCE_FIXTURE.name
+ shutil.copyfile(SOURCE_FIXTURE, fixture)
+ launch_log = ART / "argument launches.jsonl"
+ launch_log.unlink(missing_ok = True)
+ wait_for_health(BASE, timeout = 60, info = info)
+ session = authenticate()
+ remove_prior_test_servers(session["access_token"])
+ seed_js = (
+ "(() => {"
+ f"localStorage.setItem('unsloth_auth_token', {json.dumps(session['access_token'])});"
+ f"localStorage.setItem('unsloth_refresh_token', {json.dumps(session.get('refresh_token', ''))});"
+ "localStorage.setItem('unsloth_chat_mcp_enabled', 'true');"
+ "})();"
+ )
+ install_wall_clock_watchdog(WALL_TIMEOUT_S, label = "mcp-arguments", info = info)
+ with sync_playwright() as playwright:
+ if BROWSER not in ("chromium", "firefox", "webkit"):
+ raise AssertionError(f"unsupported browser: {BROWSER}")
+ browser_type = getattr(playwright, BROWSER)
+ launch_kwargs: dict = {"headless": True}
+ if BROWSER == "chromium":
+ launch_kwargs["args"] = chromium_launch_args()
+ if CHANNEL:
+ launch_kwargs["channel"] = CHANNEL
+ browser = browser_type.launch(**launch_kwargs)
+ context = browser.new_context(
+ viewport = {"width": 1280, "height": 900},
+ reduced_motion = "reduce",
+ )
+ install_view_transition_killer(context)
+ context.add_init_script(seed_js)
+ page = context.new_page()
+ page.set_default_timeout(15_000)
+ try:
+ run(page, launch_log, fixture)
+ finally:
+ page.screenshot(path = str(ART / f"fixed-final-{BROWSER}.png"), full_page = True)
+ context.close()
+ browser.close()
+ remove_prior_test_servers(session["access_token"])
+ info("PASS real stdio create, edit, import, probe, persistence, reconnect, and launch")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/test_playwright_suites_run_in_ci.py b/tests/studio/test_playwright_suites_run_in_ci.py
index b2995377085..cfd8e67b2b9 100644
--- a/tests/studio/test_playwright_suites_run_in_ci.py
+++ b/tests/studio/test_playwright_suites_run_in_ci.py
@@ -163,6 +163,22 @@ def test_every_playwright_driver_is_invoked_by_ci():
)
+def test_mcp_argument_driver_launches_the_managed_studio_python():
+ document = yaml.safe_load(
+ (REPO / ".github" / "workflows" / "studio-ui-smoke.yml").read_text(encoding = "utf-8")
+ )
+ steps = document["jobs"]["ui-smoke"]["steps"]
+ run = next(
+ str(step["run"])
+ for step in steps
+ if step.get("name") == "MCP arguments end to end (Playwright)"
+ )
+ driver = (REPO / "tests" / "studio" / "playwright_mcp_arguments.py").read_text(encoding = "utf-8")
+
+ assert 'export STUDIO_MCP_PYTHON="$studio_home/unsloth_studio/bin/python"' in run
+ assert 'os.environ.get("STUDIO_MCP_PYTHON", sys.executable)' in driver
+
+
def test_the_exemptions_are_still_exempt_and_still_exist():
"""An exemption that outlives its file, or its reason, quietly shrinks the check."""
names = {driver.name for driver in DRIVERS}