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: turn on agent access (MCP) from Settings > API (#13167)

Etherl26de92cb7276
diff --git a/studio/frontend/src/features/settings/api/mcp-access.ts b/studio/frontend/src/features/settings/api/mcp-access.ts
new file mode 100644
index 00000000000..0921bbbf811
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/mcp-access.ts
@@ -0,0 +1,54 @@
+// 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 { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+
+const MCP_ACCESS_PATH = "/api/settings/mcp-access";
+
+export type McpAccessSettings = {
+ enabled: boolean;
+ /** UNSLOTH_STUDIO_ENABLE_MCP=1 forces this on and disables the switch */
+ forcedByEnv: boolean;
+ /** backend-reported URL used as the snippet fallback */
+ url: string;
+};
+
+type ApiMcpAccessSettings = {
+ enabled: boolean;
+ forced_by_env: boolean;
+ url: string;
+};
+
+export function mcpAccessFromApi(
+ settings: ApiMcpAccessSettings,
+): McpAccessSettings {
+ return {
+ enabled: settings.enabled,
+ forcedByEnv: settings.forced_by_env,
+ url: settings.url,
+ };
+}
+
+async function request(
+ fallback: string,
+ init?: RequestInit,
+): Promise<McpAccessSettings> {
+ const res = await authFetch(MCP_ACCESS_PATH, init);
+ if (!res.ok) {
+ throw new Error(await readFastApiError(res, fallback));
+ }
+ return mcpAccessFromApi(await res.json());
+}
+
+export function loadMcpAccess(): Promise<McpAccessSettings> {
+ return request("Failed to load agent access settings");
+}
+
+export function updateMcpAccess(enabled: boolean): Promise<McpAccessSettings> {
+ return request("Failed to update agent access settings", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled }),
+ });
+}
diff --git a/studio/frontend/src/features/settings/components/agent-command-block.tsx b/studio/frontend/src/features/settings/components/agent-command-block.tsx
new file mode 100644
index 00000000000..c5c22222e68
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/agent-command-block.tsx
@@ -0,0 +1,135 @@
+// 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 { useT } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import { Copy01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { ApiProviderLogo } from "../../chat/api-provider-logo";
+
+// bind feedback to the copied text so command changes cannot retain a stale tick.
+export function useCopyButton(text: string) {
+ const textVersion = useMemo(() => Symbol(text), [text]);
+ const [copiedVersion, setCopiedVersion] = useState<symbol | null>(null);
+ const timeoutRef = useRef<number | null>(null);
+ const currentVersionRef = useRef(textVersion);
+
+ useEffect(() => {
+ currentVersionRef.current = textVersion;
+ return () => {
+ if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current);
+ timeoutRef.current = null;
+ };
+ }, [textVersion]);
+
+ const copy = async () => {
+ const requestedText = text;
+ const requestedVersion = textVersion;
+ if (!(await copyToClipboard(requestedText))) return;
+ if (currentVersionRef.current !== requestedVersion) return;
+ setCopiedVersion(requestedVersion);
+ if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current);
+ timeoutRef.current = window.setTimeout(() => {
+ setCopiedVersion(null);
+ timeoutRef.current = null;
+ }, 1600);
+ };
+
+ const reset = () => {
+ if (timeoutRef.current !== null) {
+ window.clearTimeout(timeoutRef.current);
+ timeoutRef.current = null;
+ }
+ setCopiedVersion(null);
+ };
+
+ return { copied: copiedVersion === textVersion, copy, reset };
+}
+
+export function AgentIcon({
+ logo,
+ icon,
+ darkIcon,
+ color,
+ mark,
+}: {
+ logo?: string;
+ icon?: string;
+ darkIcon?: string;
+ color?: string;
+ mark?: string;
+}) {
+ if (logo) {
+ return (
+ <span className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded">
+ <ApiProviderLogo providerType={logo} className="size-5 rounded" />
+ </span>
+ );
+ }
+ if (icon) {
+ const iconSrc = `${import.meta.env.BASE_URL}agent-logos/${icon}`;
+ const darkIconSrc = darkIcon
+ ? `${import.meta.env.BASE_URL}agent-logos/${darkIcon}`
+ : null;
+ return (
+ <span className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded">
+ <img
+ src={iconSrc}
+ alt=""
+ aria-hidden={true}
+ className={cn("size-5 object-contain", darkIconSrc && "dark:hidden")}
+ />
+ {darkIconSrc ? (
+ <img
+ src={darkIconSrc}
+ alt=""
+ aria-hidden={true}
+ className="hidden size-5 object-contain dark:block"
+ />
+ ) : null}
+ </span>
+ );
+ }
+ return (
+ <span
+ aria-hidden={true}
+ style={{ backgroundColor: color }}
+ className="flex size-5 shrink-0 items-center justify-center rounded font-heading text-ui-10 font-semibold text-white"
+ >
+ {mark}
+ </span>
+ );
+}
+
+export function CommandBlock({ command }: { command: string }) {
+ const t = useT();
+ const { copied, copy } = useCopyButton(command);
+
+ return (
+ <div className="group relative overflow-hidden rounded-xl border border-border bg-muted/40 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.04*var(--contrast-wash-gain,1)))]">
+ <pre className="hover-scrollbar overflow-x-auto py-3 pr-11 pl-4 text-xs leading-relaxed text-foreground">
+ <code className="font-mono whitespace-pre">{command}</code>
+ </pre>
+ <button
+ type="button"
+ onClick={copy}
+ aria-label={
+ copied ? t("settings.agents.copied") : t("settings.agents.copy")
+ }
+ className="absolute top-2 right-2 flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon
+ icon={copied ? Tick02Icon : Copy01Icon}
+ className={cn("size-3.5", copied && "text-control-accent")}
+ strokeWidth={2}
+ />
+ </button>
+ <output className="sr-only" aria-live="polite">
+ {copied ? t("settings.agents.copied") : ""}
+ </output>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/coding-agent-list.ts b/studio/frontend/src/features/settings/components/coding-agent-list.ts
new file mode 100644
index 00000000000..3f657962c22
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/coding-agent-list.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// shared by Settings > Agents and Settings > API; kept data-only for Node.js tests.
+
+export const UNSLOTH_START_DOCS_URL =
+ "https://unsloth.ai/docs/integrations/unsloth-start";
+
+export type AgentDetails = {
+ id: string;
+ name: string;
+ docsUrl: string;
+ logo?: string;
+ icon?: string;
+ darkIcon?: string;
+ color?: string;
+ mark?: string;
+};
+
+// names stay untranslated; `settings.agents.intro` includes them for search.
+export const SUPPORTED_AGENTS: AgentDetails[] = [
+ {
+ id: "claude",
+ name: "Claude Code",
+ docsUrl: "https://unsloth.ai/docs/basics/claude-code",
+ logo: "anthropic",
+ },
+ {
+ id: "codex",
+ name: "OpenAI Codex",
+ docsUrl: "https://unsloth.ai/docs/basics/codex",
+ logo: "openai",
+ },
+ {
+ id: "hermes",
+ name: "Hermes Agent",
+ docsUrl: "https://unsloth.ai/docs/integrations/hermes-agent",
+ // hermes.png comes from the NousResearch/hermes-agent desktop assets.
+ icon: "hermes.png",
+ },
+ {
+ id: "openclaw",
+ name: "OpenClaw",
+ docsUrl: "https://unsloth.ai/docs/integrations/openclaw",
+ icon: "openclaw.svg",
+ },
+ {
+ id: "opencode",
+ name: "OpenCode",
+ docsUrl: "https://unsloth.ai/docs/integrations/opencode",
+ icon: "opencode-light.svg",
+ darkIcon: "opencode-dark.svg",
+ },
+ {
+ id: "dsh",
+ name: "DeepSeek Harness",
+ docsUrl: "https://github.com/deepseek-ai/deepseek-harness",
+ logo: "deepseek",
+ },
+ {
+ id: "vibe",
+ name: "Mistral Vibe",
+ docsUrl: "https://github.com/mistralai/mistral-vibe",
+ logo: "mistral",
+ },
+];
+
+export function detailsFor(agentId: string): AgentDetails {
+ return (
+ SUPPORTED_AGENTS.find((agent) => agent.id === agentId) ?? {
+ id: agentId,
+ name: agentId,
+ docsUrl: UNSLOTH_START_DOCS_URL,
+ color: "#64748B",
+ mark: agentId.slice(0, 2),
+ }
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/mcp-access-section.tsx b/studio/frontend/src/features/settings/components/mcp-access-section.tsx
new file mode 100644
index 00000000000..33986aca276
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/mcp-access-section.tsx
@@ -0,0 +1,268 @@
+// 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 {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { usePlatformStore } from "@/config/env";
+import { translate, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { McpServerIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ type ReactElement,
+ useEffect,
+ useState,
+ useSyncExternalStore,
+} from "react";
+import {
+ type McpAccessSettings,
+ loadMcpAccess,
+ updateMcpAccess,
+} from "../api/mcp-access";
+import {
+ type ExampleOs,
+ useSettingsPanelPrefsStore,
+} from "../stores/settings-panel-prefs-store";
+import { AgentIcon, CommandBlock } from "./agent-command-block";
+import { SUPPORTED_AGENTS, detailsFor } from "./coding-agent-list";
+import {
+ MCP_API_KEY_ENV,
+ MCP_SHELL_AGENT_IDS,
+ buildMcpSnippet,
+} from "./mcp-agent-snippet";
+import { SettingsRow } from "./settings-row";
+import {
+ readUseTunnelPref,
+ subscribeUseTunnelPref,
+} from "./tunnel-preference";
+
+const ENV_FORCE = "UNSLOTH_STUDIO_ENABLE_MCP";
+const OS_OPTIONS = [
+ { os: "unix", labelKey: "settings.apiKeys.osUnix" },
+ { os: "windows", labelKey: "settings.apiKeys.osWindows" },
+] as const;
+
+function errorMessage(error: unknown): string | null {
+ return error instanceof Error ? error.message : null;
+}
+
+export function McpAccessSection({
+ apiKey = null,
+}: {
+ /** newly created key inserted into snippets instead of the environment variable */
+ apiKey?: string | null;
+}): ReactElement | null {
+ const t = useT();
+ const [settings, setSettings] = useState<McpAccessSettings | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const deviceType = usePlatformStore((s) => s.deviceType);
+ const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
+ const serverUrl = usePlatformStore((s) => s.serverUrl);
+ const storedAgent = useSettingsPanelPrefsStore((s) => s.mcpAgent);
+ const storedOs = useSettingsPanelPrefsStore((s) => s.mcpOs);
+ const setStoredAgent = useSettingsPanelPrefsStore((s) => s.setMcpAgent);
+ const setStoredOs = useSettingsPanelPrefsStore((s) => s.setMcpOs);
+
+ const agent =
+ storedAgent && SUPPORTED_AGENTS.some((a) => a.id === storedAgent)
+ ? storedAgent
+ : SUPPORTED_AGENTS[0].id;
+ // an explicit pick wins, since the agent may run on another machine.
+ const os: ExampleOs =
+ storedOs ?? (deviceType === "windows" ? "windows" : "unix");
+
+ useEffect(() => {
+ let live = true;
+ loadMcpAccess().then(
+ (next) => live && setSettings(next),
+ (err) =>
+ live &&
+ setError(
+ errorMessage(err) ?? translate("settings.apiKeys.mcp.loadError"),
+ ),
+ );
+ return () => {
+ live = false;
+ };
+ }, []);
+
+ const apply = async (enabled: boolean) => {
+ setBusy(true);
+ setError(null);
+ try {
+ setSettings(await updateMcpAccess(enabled));
+ } catch (err) {
+ // resync because a rejected update may leave the server value unknown.
+ try {
+ setSettings(await loadMcpAccess());
+ } catch (refreshError) {
+ console.warn(
+ "Couldn't refresh agent access settings after a rejected change.",
+ refreshError,
+ );
+ }
+ setError(errorMessage(err) ?? t("settings.apiKeys.mcp.saveError"));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // subscribe to same-tab tunnel changes from the API examples.
+ const useTunnel = useSyncExternalStore(
+ subscribeUseTunnelPref,
+ readUseTunnelPref,
+ () => true,
+ );
+
+ if (!(settings || error)) {
+ return null;
+ }
+
+ // match the server address shown by the API examples.
+ const origin = typeof window !== "undefined" ? window.location.origin : "";
+ const base =
+ useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+ const snippet = settings?.enabled
+ ? (buildMcpSnippet(agent, base, os, apiKey) ??
+ buildMcpSnippet(agent, settings.url, os, apiKey))
+ : null;
+ const agentDetails = detailsFor(agent);
+
+ return (
+ <section
+ data-settings-label={t("settings.apiKeys.mcp.title")}
+ className="overflow-hidden rounded-lg border border-border/70"
+ >
+ <div className="flex items-start gap-3 bg-muted/30 p-4">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">
+ <HugeiconsIcon
+ icon={McpServerIcon}
+ className="size-4 text-foreground"
+ />
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <h2 className="settings-heading text-base font-semibold font-heading">
+ {t("settings.apiKeys.mcp.title")}
+ </h2>
+ <p className="text-xs text-muted-foreground leading-relaxed">
+ {t("settings.apiKeys.mcp.description")}
+ </p>
+ </div>
+ </div>
+
+ {error ? (
+ <p className="border-t border-border/60 px-4 py-2.5 text-xs leading-snug text-destructive">
+ {error}
+ </p>
+ ) : null}
+
+ {settings ? (
+ <div className="border-t border-border/60 px-4 py-1">
+ <SettingsRow
+ label={t("settings.apiKeys.mcp.enable")}
+ description={
+ settings.forcedByEnv
+ ? t("settings.apiKeys.mcp.lockedByEnv", { name: ENV_FORCE })
+ : t("settings.apiKeys.mcp.enableDescription")
+ }
+ >
+ <Switch
+ checked={settings.enabled}
+ disabled={busy || settings.forcedByEnv}
+ onCheckedChange={(on) => void apply(on)}
+ aria-label={t("settings.apiKeys.mcp.enable")}
+ />
+ </SettingsRow>
+
+ {snippet ? (
+ <>
+ <SettingsRow label={t("settings.apiKeys.mcp.agent")}>
+ <Select value={agent} onValueChange={setStoredAgent}>
+ <SelectTrigger
+ className="w-48"
+ aria-label={t("settings.apiKeys.mcp.agent")}
+ >
+ <SelectValue>
+ <span className="flex min-w-0 items-center gap-2">
+ <AgentIcon {...agentDetails} />
+ <span className="truncate">{agentDetails.name}</span>
+ </span>
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent align="end">
+ {SUPPORTED_AGENTS.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ <span className="flex min-w-0 items-center gap-2">
+ <AgentIcon {...option} />
+ <span className="truncate">{option.name}</span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+
+ <div className="flex min-w-0 flex-col gap-2 pb-3">
+ {MCP_SHELL_AGENT_IDS.has(agent) ? (
+ <fieldset className="flex min-w-0">
+ <legend className="sr-only">
+ {t("settings.agents.commandShell")}
+ </legend>
+ <div className="hub-tab-toggle inline-flex h-8 items-center rounded-full">
+ {OS_OPTIONS.map((option) => (
+ <button
+ key={option.os}
+ type="button"
+ onClick={() => setStoredOs(option.os)}
+ aria-pressed={os === option.os}
+ className={cn(
+ "inline-flex h-8 items-center rounded-full px-3.5 text-ui-12 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
+ os === option.os
+ ? "hub-tab-toggle-pill text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {t(option.labelKey)}
+ </button>
+ ))}
+ </div>
+ </fieldset>
+ ) : null}
+
+ {/* exclude commands containing a newly created key from reload snapshots. */}
+ <div
+ className="min-w-0"
+ data-reload-snapshot-sensitive={apiKey ? "" : undefined}
+ >
+ <CommandBlock command={snippet.text} />
+ </div>
+
+ {snippet.configPath ? (
+ <p className="text-xs leading-snug text-muted-foreground">
+ {t("settings.apiKeys.mcp.configFileHint", {
+ path: snippet.configPath,
+ })}
+ </p>
+ ) : null}
+ {snippet.readsKeyEnv ? (
+ <p className="text-xs leading-snug text-muted-foreground">
+ {t("settings.apiKeys.mcp.exportKeyHint", {
+ name: MCP_API_KEY_ENV,
+ })}
+ </p>
+ ) : null}
+ </div>
+ </>
+ ) : null}
+ </div>
+ ) : null}
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/mcp-agent-snippet.ts b/studio/frontend/src/features/settings/components/mcp-agent-snippet.ts
new file mode 100644
index 00000000000..1f315c577a2
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/mcp-agent-snippet.ts
@@ -0,0 +1,190 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// pure builders keep each agent's MCP setup format testable in Node.
+
+import { type AgentCommandOs, quoteShellArg } from "./agent-command.ts";
+
+export const MCP_SERVER_NAME = "unsloth-studio";
+export const MCP_API_KEY_ENV = "UNSLOTH_API_KEY";
+
+// only command-based agents need Unix and PowerShell variants.
+export const MCP_SHELL_AGENT_IDS: ReadonlySet<string> = new Set([
+ "claude",
+ "codex",
+]);
+
+export type McpSnippet = {
+ text: string;
+ /** set for agents configured by a file the user edits */
+ configPath: string | null;
+ /** the text reads UNSLOTH_API_KEY, so it has to be set before the agent starts */
+ readsKeyEnv: boolean;
+};
+
+/** `<origin>/mcp/` for any Studio base, or null when the base is not a URL. */
+export function mcpEndpointUrl(base: string | null | undefined): string | null {
+ if (!base) {
+ return null;
+ }
+ try {
+ const url = new URL(base);
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ return null;
+ }
+ // Studio answers the bare /mcp with a redirect that clients may not follow on a POST.
+ return `${url.origin}/mcp/`;
+ } catch {
+ return null;
+ }
+}
+
+// JSON strings are valid YAML double-quoted scalars and TOML basic strings.
+const quoted = (value: string): string => JSON.stringify(value);
+
+function claudeSnippet(
+ url: string,
+ os: AgentCommandOs,
+ apiKey: string | null,
+): string {
+ const command = `claude mcp add --transport http ${MCP_SERVER_NAME} ${quoteShellArg(url, os)}`;
+ if (apiKey) {
+ return `${command} --header ${quoteShellArg(`Authorization: Bearer ${apiKey}`, os)}`;
+ }
+ // In PowerShell $UNSLOTH_API_KEY is an unset shell variable, not the environment.
+ const envRef =
+ os === "windows" ? `$env:${MCP_API_KEY_ENV}` : `$${MCP_API_KEY_ENV}`;
+ return `${command} --header "Authorization: Bearer ${envRef}"`;
+}
+
+function codexSnippet(url: string, os: AgentCommandOs): string {
+ // Codex only takes the name of an environment variable, never the key itself.
+ return [
+ `codex mcp add ${MCP_SERVER_NAME} --url ${quoteShellArg(url, os)} --bearer-token-env-var ${MCP_API_KEY_ENV}`,
+ `# Optional, for long jobs, in ~/.codex/config.toml under [mcp_servers.${MCP_SERVER_NAME}]:`,
+ "# tool_timeout_sec = 300",
+ ].join("\n");
+}
+
+function opencodeSnippet(url: string, apiKey: string | null): string {
+ const config = {
+ mcp: {
+ [MCP_SERVER_NAME]: {
+ type: "remote",
+ url,
+ oauth: false,
+ headers: {
+ Authorization: `Bearer ${apiKey ?? `{env:${MCP_API_KEY_ENV}}`}`,
+ },
+ },
+ },
+ };
+ return JSON.stringify(config, null, 2);
+}
+
+function hermesSnippet(url: string, apiKey: string | null): string {
+ const token = apiKey ?? `\${${MCP_API_KEY_ENV}}`;
+ return [
+ "mcp_servers:",
+ " unsloth_studio:",
+ ` url: ${quoted(url)}`,
+ " headers:",
+ ` Authorization: ${quoted(`Bearer ${token}`)}`,
+ "# Then run /reload-mcp in Hermes",
+ ].join("\n");
+}
+
+function openclawSnippet(url: string, apiKey: string | null): string {
+ const config = {
+ mcp: {
+ servers: {
+ [MCP_SERVER_NAME]: {
+ url,
+ // url servers otherwise default to SSE.
+ transport: "streamable-http",
+ headers: {
+ Authorization: `Bearer ${apiKey ?? `\${${MCP_API_KEY_ENV}}`}`,
+ },
+ },
+ },
+ },
+ };
+ return JSON.stringify(config, null, 2);
+}
+
+function vibeSnippet(url: string): string {
+ // Vibe's static auth reads the key from a named variable only.
+ return [
+ "[[mcp_servers]]",
+ 'name = "unsloth_studio"',
+ 'transport = "streamable-http"',
+ `url = ${quoted(url)}`,
+ "",
+ "[mcp_servers.auth]",
+ 'type = "static"',
+ `api_key_env = "${MCP_API_KEY_ENV}"`,
+ 'api_key_header = "Authorization"',
+ 'api_key_format = "Bearer {token}"',
+ ].join("\n");
+}
+
+function dshSnippet(url: string, apiKey: string | null): string {
+ // dsh lacks ${VAR} substitution, so !!js evaluates the template.
+ const authorization = apiKey
+ ? quoted(`Bearer ${apiKey}`)
+ : `!!js '\`Bearer \${process.env.${MCP_API_KEY_ENV}}\`'`;
+ return [
+ "- insert:",
+ " - id: mcp-unsloth-studio",
+ " name: '@deepseek-ai/dsh-mcp-client'",
+ " config:",
+ ` serverName: ${MCP_SERVER_NAME}`,
+ " transport: streamable-http",
+ ` url: ${quoted(url)}`,
+ " headers:",
+ ` Authorization: ${authorization}`,
+ ].join("\n");
+}
+
+type Builder = (url: string, os: AgentCommandOs, key: string | null) => string;
+
+const BUILDERS = new Map<string, Builder>([
+ ["claude", claudeSnippet],
+ ["codex", codexSnippet],
+ ["opencode", (url, _os, apiKey) => opencodeSnippet(url, apiKey)],
+ ["hermes", (url, _os, apiKey) => hermesSnippet(url, apiKey)],
+ ["openclaw", (url, _os, apiKey) => openclawSnippet(url, apiKey)],
+ ["vibe", vibeSnippet],
+ ["dsh", (url, _os, apiKey) => dshSnippet(url, apiKey)],
+]);
+
+const CONFIG_PATHS: Record<string, string> = {
+ opencode: "~/.config/opencode/opencode.json",
+ hermes: "~/.hermes/config.yaml",
+ openclaw: "~/.openclaw/openclaw.json",
+ vibe: "~/.vibe/config.toml",
+ dsh: "~/.dsh/cordis.patch.yml",
+};
+
+// these read the key from UNSLOTH_API_KEY even when the caller passes one.
+const ENV_ONLY_AGENT_IDS: ReadonlySet<string> = new Set(["codex", "vibe"]);
+
+/** returns setup for a known agent and valid base URL, with a literal key only when provided. */
+export function buildMcpSnippet(
+ agentId: string,
+ base: string | null | undefined,
+ os: AgentCommandOs,
+ apiKey: string | null = null,
+): McpSnippet | null {
+ const url = mcpEndpointUrl(base);
+ const build = BUILDERS.get(agentId);
+ if (!(url && build)) {
+ return null;
+ }
+ const key = apiKey || null;
+ return {
+ text: build(url, os, key),
+ configPath: CONFIG_PATHS[agentId] ?? null,
+ readsKeyEnv: key === null || ENV_ONLY_AGENT_IDS.has(agentId),
+ };
+}
diff --git a/studio/frontend/src/features/settings/components/tunnel-preference.ts b/studio/frontend/src/features/settings/components/tunnel-preference.ts
new file mode 100644
index 00000000000..be7a66fd453
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/tunnel-preference.ts
@@ -0,0 +1,42 @@
+// 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 USE_TUNNEL_KEY = "unsloth_api_use_tunnel";
+
+let currentUseTunnelPref: boolean | null = null;
+const useTunnelListeners = new Set<() => void>();
+
+export function readUseTunnelPref(): boolean {
+ if (currentUseTunnelPref !== null) {
+ return currentUseTunnelPref;
+ }
+ if (typeof window === "undefined") {
+ return true;
+ }
+ try {
+ return window.localStorage.getItem(USE_TUNNEL_KEY) !== "false";
+ } catch {
+ return true;
+ }
+}
+
+export function subscribeUseTunnelPref(listener: () => void): () => void {
+ useTunnelListeners.add(listener);
+ return () => {
+ useTunnelListeners.delete(listener);
+ };
+}
+
+export function writeUseTunnelPref(value: boolean): void {
+ currentUseTunnelPref = value;
+ if (typeof window !== "undefined") {
+ try {
+ window.localStorage.setItem(USE_TUNNEL_KEY, value ? "true" : "false");
+ } catch {
+ // keep the in-memory value when persistent storage is unavailable.
+ }
+ }
+ for (const listener of useTunnelListeners) {
+ listener();
+ }
+}
diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsx
index f8f99f7d4c9..dbcfeaae6df 100644
--- a/studio/frontend/src/features/settings/components/usage-examples.tsx
+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx
@@ -56,6 +56,10 @@ import {
statusGgufVerdict,
} from "./agent-command";
import { keylessBaseEligible } from "./keyless-example-eligibility";
+import {
+ readUseTunnelPref,
+ writeUseTunnelPref,
+} from "./tunnel-preference";
type ExampleType =
| "curl"
@@ -376,34 +380,14 @@ function buildSnippets(
}
const KEY_PLACEHOLDER = "sk-unsloth-YOUR_KEY";
-// the openai sdks require some api_key, so name one rather than leave it blank
+// OpenAI SDKs require an api_key value even for keyless access.
const KEYLESS_KEY_PLACEHOLDER = "not-needed";
-const USE_TUNNEL_KEY = "unsloth_api_use_tunnel";
-// Slow retry while /v1 has nothing to name: a download or load moves no store state.
+// retry while /v1 has no model because downloads and loads do not update the store.
const CATALOG_RETRY_MS = 15000;
-// Slower beat once something is servable: an idle unload frees a model without
-// touching the store, so residency is never settled for good.
+// keep polling after a model appears because idle unloads do not update the store.
const CATALOG_IDLE_MS = 60000;
-function readUseTunnelPref(): boolean {
- if (typeof window === "undefined") return true;
- try {
- return window.localStorage.getItem(USE_TUNNEL_KEY) !== "false";
- } catch {
- return true;
- }
-}
-
-function writeUseTunnelPref(value: boolean): void {
- if (typeof window === "undefined") return;
- try {
- window.localStorage.setItem(USE_TUNNEL_KEY, value ? "true" : "false");
- } catch {
- // Non-fatal
- }
-}
-
-// A checkpoint can be an on-disk load path, which /v1 never advertises. Mirrors _looks_like_path.
+// match the backend path heuristic because /v1 never advertises on-disk checkpoints.
function looksLikePath(id: string): boolean {
return (
id.startsWith("/") ||
@@ -415,7 +399,7 @@ function looksLikePath(id: string): boolean {
);
}
-// The model the examples name: always an id /v1 resolves against, null when there is none.
+// return only model ids that /v1 can resolve, or null when none are available.
function useExampleModelName(keylessOnly: boolean): string | null {
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const ggufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 43aa88eede9..96944dbb30c 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -215,20 +215,19 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.apiKeys.description",
"settings.apiKeys.accessTokens",
"settings.apiKeys.decisionApi.title",
+ "settings.apiKeys.mcp.title",
],
- // The two cards label themselves in English in every locale, so keys naming them
- // would never match their own anchor. The header carries both entries instead.
+ // the English card labels cannot match localized keys, so the header carries both entries.
"remote-lan": ["settings.remoteLan.title", "settings.remoteLan.description"],
agents: [
- // Every key needs a rendered data-settings-label, or a hit has nothing to scroll to.
+ // every key needs a rendered data-settings-label as its scroll target.
"settings.agents.title",
"settings.agents.description",
"settings.agents.intro",
"settings.agents.agent",
"settings.agents.model",
"settings.agents.quantization",
- // subagent.title is deliberately absent: its label only mounts for the agents
- // that support subagents, so a hit would have nothing to scroll to otherwise.
+ // subagent.title has no stable scroll target because its label mounts conditionally.
"settings.agents.options.title",
"settings.agents.remote.title",
"settings.agents.passthrough.title",
@@ -378,11 +377,12 @@ const HUGGING_FACE_ONLY_ENTRIES: ReadonlySet<TranslationKey> = new Set([
"settings.general.hub.datasetsServer",
]);
-// Rows of a tab every account sees that render only for the owner (the OS sandbox sections).
+// owner-only rows on tabs visible to every account.
const OWNER_ONLY_ENTRIES: ReadonlySet<TranslationKey> = new Set([
"settings.sandbox.toolsSection",
"settings.sandbox.python",
"settings.sandbox.terminal",
+ "settings.apiKeys.mcp.title",
]);
export function renderedSearchEntries(
@@ -413,8 +413,7 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<
// the feature is named after was unreachable by search.
"settings.resources.storage.caches.label":
"settings.resources.storage.caches.keywords",
- // mlock, vram, ulimit and pin are in none of these labels, so search
- // missed the rows the feature is named after.
+ // match mlock, vram, ulimit, and pin even though the labels omit them.
"settings.resources.modelMemory.title":
"settings.resources.modelMemory.modelMemoryKeywords",
"settings.resources.modelMemory.keepResident":
@@ -422,10 +421,12 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<
"settings.resources.modelMemory.noRamReserve":
"settings.resources.modelMemory.modelMemoryKeywords",
"settings.chat.autoCompact": "settings.chat.autoCompactKeywords",
- // These rows are labelled with what they are, so the verbs people search for live here.
+ // match action verbs omitted from these descriptive labels.
"settings.chat.thinking.visibility": "settings.chat.visibilityKeywords",
"settings.chat.tools.visibility": "settings.chat.visibilityKeywords",
"settings.chat.tools.foldIntoThinking": "settings.chat.visibilityKeywords",
"settings.chat.autoScroll": "settings.chat.autoScrollKeywords",
"settings.chat.scrollToBottomButton": "settings.chat.scrollToBottomButtonKeywords",
+ // match protocol and agent names omitted from the title.
+ "settings.apiKeys.mcp.title": "settings.apiKeys.mcp.keywords",
};
diff --git a/studio/frontend/src/features/settings/stores/settings-panel-prefs-store.ts b/studio/frontend/src/features/settings/stores/settings-panel-prefs-store.ts
index 8cde7a0bae3..f64fb2bf32e 100644
--- a/studio/frontend/src/features/settings/stores/settings-panel-prefs-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-panel-prefs-store.ts
@@ -33,6 +33,12 @@ export interface SettingsPanelPrefsState {
setApiExampleOs: (os: ExampleOs) => void;
setApiExampleAgent: (agent: string | null) => void;
+ // null mcpOs follows the detected device type.
+ mcpAgent: string | null;
+ mcpOs: ExampleOs | null;
+ setMcpAgent: (agent: string) => void;
+ setMcpOs: (os: ExampleOs) => void;
+
resourcesLiveUpdates: boolean;
setResourcesLiveUpdates: (enabled: boolean) => void;
@@ -75,7 +81,7 @@ function sanitize(
(EXAMPLE_OS_VALUES as string[]).includes(raw.agentsOs)
? (raw.agentsOs as ExampleOs)
: null,
- // A quant with no model to scope it to can never be applied.
+ // a quant without its model scope cannot be applied.
agentsVariant: agentsVariantModel ? agentsVariant : null,
agentsVariantModel: agentsVariant ? agentsVariantModel : null,
apiExampleLang: text(raw.apiExampleLang),
@@ -85,6 +91,8 @@ function sanitize(
? (raw.apiExampleOs as ExampleOs)
: null,
apiExampleAgent: text(raw.apiExampleAgent),
+ mcpAgent: text(raw.mcpAgent),
+ mcpOs: EXAMPLE_OS_VALUES.find((os) => os === raw.mcpOs) ?? null,
resourcesLiveUpdates:
typeof raw.resourcesLiveUpdates === "boolean"
? raw.resourcesLiveUpdates
@@ -116,6 +124,11 @@ export const useSettingsPanelPrefsStore = create<SettingsPanelPrefsState>()(
setApiExampleOs: (apiExampleOs) => set({ apiExampleOs }),
setApiExampleAgent: (apiExampleAgent) => set({ apiExampleAgent }),
+ mcpAgent: null,
+ mcpOs: null,
+ setMcpAgent: (mcpAgent) => set({ mcpAgent }),
+ setMcpOs: (mcpOs) => set({ mcpOs }),
+
resourcesLiveUpdates: true,
setResourcesLiveUpdates: (resourcesLiveUpdates) =>
set({ resourcesLiveUpdates }),
@@ -125,10 +138,9 @@ export const useSettingsPanelPrefsStore = create<SettingsPanelPrefsState>()(
}),
{
name: SETTINGS_PANEL_PREFS_STORAGE_KEY,
- // Pinned so a later shape change has somewhere to migrate from.
+ // pinned so later shape changes can migrate from this version.
version: 1,
- // Older records share these field names, so the sanitiser is enough. A
- // newer one is dropped: it may reuse the names with different meaning.
+ // sanitize older records; drop newer versions that may reuse these field names.
migrate: (persisted, version) =>
(version < 1 ? persisted : {}) as SettingsPanelPrefsState,
merge: (persisted, current) => sanitize(persisted, current),
diff --git a/studio/frontend/src/features/settings/tabs/agents-tab.tsx b/studio/frontend/src/features/settings/tabs/agents-tab.tsx
index 291c1072dc3..9b929aa4524 100644
--- a/studio/frontend/src/features/settings/tabs/agents-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/agents-tab.tsx
@@ -46,13 +46,11 @@ import type { TranslationKey } from "@/i18n";
import { useT } from "@/i18n";
import { getApiBase, isTauri } from "@/lib/api-base";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
-import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import { ArrowUpRight01Icon, Copy01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { ApiProviderLogo } from "../../chat/api-provider-logo";
import { loadCodingAgents } from "../api/coding-agents";
import {
buildAgentShellCommands,
@@ -60,6 +58,17 @@ import {
normalizeHost,
quoteShellArg,
} from "../components/agent-command";
+import {
+ AgentIcon,
+ CommandBlock,
+ useCopyButton,
+} from "../components/agent-command-block";
+import {
+ type AgentDetails,
+ SUPPORTED_AGENTS,
+ UNSLOTH_START_DOCS_URL,
+ detailsFor,
+} from "../components/coding-agent-list";
import { SettingsSection } from "../components/settings-section";
import {
isChatGenerativeHubModel,
@@ -71,7 +80,7 @@ import {
useSettingsPanelPrefsStore,
} from "../stores/settings-panel-prefs-store";
-const DOCS_URL = "https://unsloth.ai/docs/integrations/unsloth-start";
+const DOCS_URL = UNSLOTH_START_DOCS_URL;
const FLAGS_DOCS_URL = `${DOCS_URL}#flags--options`;
const EXAMPLE_MODEL_REPO = "unsloth/Qwen3.8-27B-GGUF";
const EXAMPLE_MODEL_VARIANT = "UD-Q4_K_XL";
@@ -95,123 +104,13 @@ function canUseLocalAgentDetection(base: string): boolean {
return isTauri && isLoopbackBase(base);
}
-// bind feedback to the copied text so command changes cannot retain a stale tick.
-function useCopyButton(text: string) {
- const textVersion = useMemo(() => Symbol(text), [text]);
- const [copiedVersion, setCopiedVersion] = useState<symbol | null>(null);
- const timeoutRef = useRef<number | null>(null);
- const currentVersionRef = useRef(textVersion);
-
- useEffect(() => {
- currentVersionRef.current = textVersion;
- return () => {
- if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current);
- timeoutRef.current = null;
- };
- }, [textVersion]);
-
- const copy = async () => {
- const requestedText = text;
- const requestedVersion = textVersion;
- if (!(await copyToClipboard(requestedText))) return;
- if (currentVersionRef.current !== requestedVersion) return;
- setCopiedVersion(requestedVersion);
- if (timeoutRef.current !== null) window.clearTimeout(timeoutRef.current);
- timeoutRef.current = window.setTimeout(() => {
- setCopiedVersion(null);
- timeoutRef.current = null;
- }, 1600);
- };
-
- const reset = () => {
- if (timeoutRef.current !== null) {
- window.clearTimeout(timeoutRef.current);
- timeoutRef.current = null;
- }
- setCopiedVersion(null);
- };
-
- return { copied: copiedVersion === textVersion, copy, reset };
-}
-
-type AgentDetails = {
- id: string;
- name: string;
- docsUrl: string;
- logo?: string;
- icon?: string;
- darkIcon?: string;
- color?: string;
- mark?: string;
-};
-
type ParsedModel = {
repo: string;
variant: string | null;
};
-// Names are untranslated, so `settings.agents.intro` lists them all to keep them searchable.
-const SUPPORTED_AGENTS: AgentDetails[] = [
- {
- id: "claude",
- name: "Claude Code",
- docsUrl: "https://unsloth.ai/docs/basics/claude-code",
- logo: "anthropic",
- },
- {
- id: "codex",
- name: "OpenAI Codex",
- docsUrl: "https://unsloth.ai/docs/basics/codex",
- logo: "openai",
- },
- {
- id: "hermes",
- name: "Hermes Agent",
- docsUrl: "https://unsloth.ai/docs/integrations/hermes-agent",
- // hermes.png is the desktop app icon from NousResearch/hermes-agent (apps/desktop/assets/icon.png)
- icon: "hermes.png",
- },
- {
- id: "openclaw",
- name: "OpenClaw",
- docsUrl: "https://unsloth.ai/docs/integrations/openclaw",
- icon: "openclaw.svg",
- },
- {
- id: "opencode",
- name: "OpenCode",
- docsUrl: "https://unsloth.ai/docs/integrations/opencode",
- icon: "opencode-light.svg",
- darkIcon: "opencode-dark.svg",
- },
- {
- id: "dsh",
- name: "DeepSeek Harness",
- docsUrl: "https://github.com/deepseek-ai/deepseek-harness",
- logo: "deepseek",
- },
- {
- id: "vibe",
- name: "Mistral Vibe",
- docsUrl: "https://github.com/mistralai/mistral-vibe",
- logo: "mistral",
- },
-];
-
const FALLBACK_AGENT = SUPPORTED_AGENTS[0];
-function detailsFor(agentId: string): AgentDetails {
- return (
- SUPPORTED_AGENTS.find((agent) => agent.id === agentId) ?? {
- id: agentId,
- name: agentId,
- docsUrl: DOCS_URL,
- color: "#64748B",
- mark: agentId.slice(0, 2),
- }
- );
-}
-
function splitModelVariant(model: string): ParsedModel {
const value = model.trim();
if (
@@ -409,61 +308,6 @@ function activeGgufSelection(
};
}
-function AgentIcon({
- logo,
- icon,
- darkIcon,
- color,
- mark,
-}: {
- logo?: string;
- icon?: string;
- darkIcon?: string;
- color?: string;
- mark?: string;
-}) {
- if (logo) {
- return (
- <span className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded">
- <ApiProviderLogo providerType={logo} className="size-5 rounded" />
- </span>
- );
- }
- if (icon) {
- const iconSrc = `${import.meta.env.BASE_URL}agent-logos/${icon}`;
- const darkIconSrc = darkIcon
- ? `${import.meta.env.BASE_URL}agent-logos/${darkIcon}`
- : null;
- return (
- <span className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded">
- <img
- src={iconSrc}
- alt=""
- aria-hidden={true}
- className={cn("size-5 object-contain", darkIconSrc && "dark:hidden")}
- />
- {darkIconSrc ? (
- <img
- src={darkIconSrc}
- alt=""
- aria-hidden={true}
- className="hidden size-5 object-contain dark:block"
- />
- ) : null}
- </span>
- );
- }
- return (
- <span
- aria-hidden={true}
- style={{ backgroundColor: color }}
- className="flex size-5 shrink-0 items-center justify-center rounded font-heading text-ui-10 font-semibold text-white"
- >
- {mark}
- </span>
- );
-}
-
// Flag tokens are literal; only the descriptions are localized.
const OPTION_ROWS: { flag: string; descKey: TranslationKey }[] = [
{ flag: "--model, -m", descKey: "settings.agents.options.model" },
@@ -545,36 +389,6 @@ function CopyableCode({
);
}
-function CommandBlock({ command }: { command: string }) {
- const t = useT();
- const { copied, copy } = useCopyButton(command);
-
- return (
- <div className="group relative overflow-hidden rounded-xl border border-border bg-muted/40 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.04*var(--contrast-wash-gain,1)))]">
- <pre className="hover-scrollbar overflow-x-auto py-3 pr-11 pl-4 text-xs leading-relaxed text-foreground">
- <code className="font-mono whitespace-pre">{command}</code>
- </pre>
- <button
- type="button"
- onClick={copy}
- aria-label={
- copied ? t("settings.agents.copied") : t("settings.agents.copy")
- }
- className="absolute top-2 right-2 flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- >
- <HugeiconsIcon
- icon={copied ? Tick02Icon : Copy01Icon}
- className={cn("size-3.5", copied && "text-control-accent")}
- strokeWidth={2}
- />
- </button>
- <output className="sr-only" aria-live="polite">
- {copied ? t("settings.agents.copied") : ""}
- </output>
- </div>
- );
-}
-
function SubagentSection({
agent,
command,
diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
index df049cac83b..48f86546f65 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -25,6 +25,7 @@ import { DecisionApiSection } from "../components/decision-api-section";
import { KeyRevealCard } from "../components/key-reveal-card";
import { KeylessApiAccessSection } from "../components/keyless-api-access-section";
import { LanAccessSection } from "../components/lan-access-section";
+import { McpAccessSection } from "../components/mcp-access-section";
import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";
import { MonitorLink } from "../components/monitor-link";
import { RemoteAccessSection } from "../components/remote-access-section";
@@ -207,6 +208,8 @@ export function ApiKeysTab() {
{isOwner ? <DecisionApiSection /> : null}
+ {isOwner ? <McpAccessSection apiKey={revealed} /> : null}
+
<Dialog
open={revokeTarget !== null}
onOpenChange={(o) => !o && setRevokeTarget(null)}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 2b9c791be1f..2c7a0ca269e 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2888,6 +2888,19 @@ export const ar = {
addConnection: "لاستخدام نموذج قرارات مستضاف، أضف TypeSafe أو Liquid AI أو OpenRouter في الاتصالات.",
openConnections: "فتح الاتصالات",
},
+ mcp: {
+ title: "وصول الوكلاء (MCP)",
+ description: "اسمح لوكلاء البرمجة مثل Claude Code وCodex باستخدام Unsloth Studio عبر MCP. يسجّل الوكلاء الدخول بتوكن وصول من هذه الصفحة.",
+ enable: "السماح باتصالات الوكلاء",
+ enableDescription: "يخدم /mcp/ للطلبات التي تحمل توكن وصول من Unsloth Studio.",
+ lockedByEnv: "مضبوط بواسطة {name}.",
+ loadError: "تعذّر تحميل إعدادات وصول الوكلاء.",
+ saveError: "تعذّر حفظ إعداد وصول الوكلاء.",
+ agent: "الوكيل",
+ exportKeyHint: "اضبط {name} على توكن وصول من هذه الصفحة قبل تشغيل الوكيل.",
+ configFileHint: "أضف هذا إلى {path}.",
+ keywords: "mcp model context protocol agents claude codex tools وكلاء وكيل أدوات بروتوكول سياق النموذج",
+ },
usageNoModel:
"حمّل نموذجًا أو نزّله لعرض أمثلة قابلة للتشغيل. لا يوجد في هذا الخادم أي نموذج يمكن استخدامه في الأمثلة بعد.",
},
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 19b48168c4b..4801fb73da5 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2932,6 +2932,19 @@ export const de = {
addConnection: "Für ein gehostetes Entscheidungsmodell füge TypeSafe, Liquid AI oder OpenRouter unter Verbindungen hinzu.",
openConnections: "Verbindungen öffnen",
},
+ mcp: {
+ title: "Agentenzugriff (MCP)",
+ description: "Lass Coding-Agenten wie Claude Code und Codex Unsloth Studio über MCP nutzen. Agenten melden sich mit einem Zugriffstoken von dieser Seite an.",
+ enable: "Agentenverbindungen erlauben",
+ enableDescription: "Stellt /mcp/ für Anfragen mit einem Unsloth Studio-Zugriffstoken bereit.",
+ lockedByEnv: "Festgelegt durch {name}.",
+ loadError: "Die Einstellungen für den Agentenzugriff konnten nicht geladen werden.",
+ saveError: "Die Einstellung für den Agentenzugriff konnte nicht gespeichert werden.",
+ agent: "Agent",
+ exportKeyHint: "Setze {name} auf ein Zugriffstoken von dieser Seite, bevor du den Agenten startest.",
+ configFileHint: "Füge das zu {path} hinzu.",
+ keywords: "mcp model context protocol agents claude codex tools Agenten Agent Werkzeuge Tools Modellkontextprotokoll",
+ },
usageNoModel:
"Laden Sie ein Modell oder laden Sie eines herunter, um ausführbare Beispiele zu sehen. Dieser Server kennt noch kein Modell, das in den Beispielen verwendet werden könnte.",
},
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 6f3e4925b23..1cf6abbe447 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2923,6 +2923,19 @@ export const en = {
addConnection: "To use a hosted decision model, add TypeSafe, Liquid AI or OpenRouter in Connections.",
openConnections: "Open Connections",
},
+ mcp: {
+ title: "Agent access (MCP)",
+ description: "Let coding agents such as Claude Code and Codex use Unsloth Studio over MCP. Agents sign in with an access token from this page.",
+ enable: "Allow agent connections",
+ enableDescription: "Serves /mcp/ to requests that carry an Unsloth Studio access token.",
+ lockedByEnv: "Set by {name}.",
+ loadError: "Couldn't load agent access settings.",
+ saveError: "Couldn't save the agent access setting.",
+ agent: "Agent",
+ exportKeyHint: "Set {name} to an access token from this page before you start the agent.",
+ configFileHint: "Add this to {path}.",
+ keywords: "mcp model context protocol agents claude codex tools",
+ },
},
about: {
title: "About",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 84901d2ae68..81fc2f0bc04 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2925,6 +2925,19 @@ export const es = {
addConnection: "Para usar un modelo de decisiones alojado, añade TypeSafe, Liquid AI u OpenRouter en Conexiones.",
openConnections: "Abrir Conexiones",
},
+ mcp: {
+ title: "Acceso de agentes (MCP)",
+ description: "Permite que agentes de código como Claude Code y Codex usen Unsloth Studio mediante MCP. Los agentes inician sesión con un token de acceso de esta página.",
+ enable: "Permitir conexiones de agentes",
+ enableDescription: "Sirve /mcp/ a las solicitudes que llevan un token de acceso de Unsloth Studio.",
+ lockedByEnv: "Definido por {name}.",
+ loadError: "No se pudo cargar la configuración de acceso de agentes.",
+ saveError: "No se pudo guardar la configuración de acceso de agentes.",
+ agent: "Agente",
+ exportKeyHint: "Define {name} con un token de acceso de esta página antes de iniciar el agente.",
+ configFileHint: "Añade esto a {path}.",
+ keywords: "mcp model context protocol agents claude codex tools agentes agente herramientas protocolo de contexto de modelo",
+ },
usageNoModel:
"Carga o descarga un modelo para ver ejemplos ejecutables. Este servidor todavía no tiene ningún modelo que indicar.",
},
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 11b8f29fa6f..e4faa74604f 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2933,6 +2933,19 @@ export const fr = {
addConnection: "Pour utiliser un modèle de décision hébergé, ajoutez TypeSafe, Liquid AI ou OpenRouter dans Connexions.",
openConnections: "Ouvrir Connexions",
},
+ mcp: {
+ title: "Accès des agents (MCP)",
+ description: "Permettez aux agents de code comme Claude Code et Codex d’utiliser Unsloth Studio via MCP. Les agents se connectent avec un jeton d’accès de cette page.",
+ enable: "Autoriser les connexions des agents",
+ enableDescription: "Sert /mcp/ aux requêtes qui portent un jeton d’accès Unsloth Studio.",
+ lockedByEnv: "Défini par {name}.",
+ loadError: "Impossible de charger les paramètres d’accès des agents.",
+ saveError: "Impossible d’enregistrer le paramètre d’accès des agents.",
+ agent: "Agent",
+ exportKeyHint: "Définissez {name} sur un jeton d’accès de cette page avant de lancer l’agent.",
+ configFileHint: "Ajoutez ceci à {path}.",
+ keywords: "mcp model context protocol agents claude codex tools agents agent outils protocole de contexte de modèle",
+ },
usageNoModel:
"Chargez ou téléchargez un modèle pour voir des exemples exécutables. Aucun modèle n'est encore disponible sur ce serveur pour figurer dans les exemples.",
},
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 35ee6ca9193..7a064cbd752 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -3001,6 +3001,19 @@ export const he = {
"כדי להשתמש במודל החלטות מתארח, הוסף את TypeSafe,‏ Liquid AI או OpenRouter ב'חיבורים'.",
openConnections: "פתח את 'חיבורים'",
},
+ mcp: {
+ title: "גישת סוכנים (MCP)",
+ description: "אפשר לסוכני קוד כמו Claude Code ו-Codex להשתמש ב-Unsloth Studio דרך MCP. סוכנים מתחברים עם טוקן גישה מהדף הזה.",
+ enable: "אפשר חיבורי סוכנים",
+ enableDescription: "מגיש את /mcp/ לבקשות שנושאות טוקן גישה של Unsloth Studio.",
+ lockedByEnv: "נקבע על ידי {name}.",
+ loadError: "לא ניתן לטעון את הגדרות גישת הסוכנים.",
+ saveError: "לא ניתן לשמור את הגדרת גישת הסוכנים.",
+ agent: "סוכן",
+ exportKeyHint: "הגדר את {name} לטוקן גישה מהדף הזה לפני שתפעיל את הסוכן.",
+ configFileHint: "הוסף את זה ל-{path}.",
+ keywords: "mcp model context protocol agents claude codex tools סוכנים סוכן כלים פרוטוקול הקשר מודל",
+ },
},
about: {
title: "אודות",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 443bfbd9c8b..ffa63b420e2 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2894,6 +2894,19 @@ export const hi = {
addConnection: "होस्ट किया गया निर्णय मॉडल इस्तेमाल करने के लिए कनेक्शन में TypeSafe, Liquid AI या OpenRouter जोड़ें।",
openConnections: "कनेक्शन खोलें",
},
+ mcp: {
+ title: "एजेंट एक्सेस (MCP)",
+ description: "Claude Code और Codex जैसे कोडिंग एजेंट को MCP के ज़रिए Unsloth Studio इस्तेमाल करने दें। एजेंट इस पेज के एक्सेस टोकन से साइन इन करते हैं।",
+ enable: "एजेंट कनेक्शन की अनुमति दें",
+ enableDescription: "Unsloth Studio एक्सेस टोकन वाले अनुरोधों के लिए /mcp/ उपलब्ध कराता है।",
+ lockedByEnv: "{name} द्वारा सेट।",
+ loadError: "एजेंट एक्सेस सेटिंग्स लोड नहीं हो सकीं।",
+ saveError: "एजेंट एक्सेस सेटिंग सहेजी नहीं जा सकी।",
+ agent: "एजेंट",
+ exportKeyHint: "एजेंट शुरू करने से पहले {name} को इस पेज के किसी एक्सेस टोकन पर सेट करें।",
+ configFileHint: "इसे {path} में जोड़ें।",
+ keywords: "mcp model context protocol agents claude codex tools एजेंट टूल्स मॉडल कॉन्टेक्स्ट प्रोटोकॉल",
+ },
usageNoModel:
"चलाने योग्य उदाहरण देखने के लिए कोई मॉडल लोड या डाउनलोड करें। इस सर्वर के पास अभी बताने को कोई मॉडल नहीं है।",
},
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index e31ff20ea51..4dd87beee2e 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2891,6 +2891,19 @@ export const it = {
addConnection: "Per usare un modello decisionale ospitato, aggiungi TypeSafe, Liquid AI o OpenRouter in Connessioni.",
openConnections: "Apri Connessioni",
},
+ mcp: {
+ title: "Accesso degli agenti (MCP)",
+ description: "Consenti ad agenti di programmazione come Claude Code e Codex di usare Unsloth Studio tramite MCP. Gli agenti accedono con un token di accesso di questa pagina.",
+ enable: "Consenti connessioni degli agenti",
+ enableDescription: "Rende disponibile /mcp/ alle richieste che portano un token di accesso di Unsloth Studio.",
+ lockedByEnv: "Impostato da {name}.",
+ loadError: "Impossibile caricare le impostazioni di accesso degli agenti.",
+ saveError: "Impossibile salvare l’impostazione di accesso degli agenti.",
+ agent: "Agente",
+ exportKeyHint: "Imposta {name} su un token di accesso di questa pagina prima di avviare l’agente.",
+ configFileHint: "Aggiungi questo a {path}.",
+ keywords: "mcp model context protocol agents claude codex tools agenti agente strumenti protocollo di contesto del modello",
+ },
},
about: {
title: "Informazioni",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 41fc76b1244..e522f9eaba9 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2858,6 +2858,19 @@ export const ja = {
addConnection: "ホスト型の判定モデルを使うには、接続で TypeSafe、Liquid AI、OpenRouter のいずれかを追加してください。",
openConnections: "接続を開く",
},
+ mcp: {
+ title: "エージェントアクセス (MCP)",
+ description: "Claude Code や Codex などのコーディングエージェントが MCP 経由で Unsloth Studio を使えるようにします。エージェントはこのページのアクセストークンでサインインします。",
+ enable: "エージェントの接続を許可",
+ enableDescription: "Unsloth Studio のアクセストークンを持つリクエストに /mcp/ を提供します。",
+ lockedByEnv: "{name} で設定されています。",
+ loadError: "エージェントアクセスの設定を読み込めませんでした。",
+ saveError: "エージェントアクセスの設定を保存できませんでした。",
+ agent: "エージェント",
+ exportKeyHint: "エージェントを起動する前に、{name} にこのページのアクセストークンを設定してください。",
+ configFileHint: "これを {path} に追加してください。",
+ keywords: "mcp model context protocol agents claude codex tools エージェント ツール モデルコンテキストプロトコル",
+ },
usageNoModel:
"モデルを読み込むかダウンロードすると、実行できる例が表示されます。このサーバーにはまだ指定できるモデルがありません。",
},
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index a44788c7950..582e87fa084 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2878,6 +2878,19 @@ export const ko = {
addConnection: "호스팅된 판단 모델을 사용하려면 연결에서 TypeSafe, Liquid AI 또는 OpenRouter를 추가하세요.",
openConnections: "연결 열기",
},
+ mcp: {
+ title: "에이전트 액세스 (MCP)",
+ description: "Claude Code, Codex 같은 코딩 에이전트가 MCP로 Unsloth Studio를 사용하게 합니다. 에이전트는 이 페이지의 액세스 토큰으로 로그인합니다.",
+ enable: "에이전트 연결 허용",
+ enableDescription: "Unsloth Studio 액세스 토큰이 있는 요청에 /mcp/를 제공합니다.",
+ lockedByEnv: "{name}(으)로 설정됨.",
+ loadError: "에이전트 액세스 설정을 불러오지 못했습니다.",
+ saveError: "에이전트 액세스 설정을 저장하지 못했습니다.",
+ agent: "에이전트",
+ exportKeyHint: "에이전트를 시작하기 전에 {name}에 이 페이지의 액세스 토큰을 설정하세요.",
+ configFileHint: "이 내용을 {path}에 추가하세요.",
+ keywords: "mcp model context protocol agents claude codex tools 에이전트 도구 모델 컨텍스트 프로토콜",
+ },
usageNoModel:
"모델을 로드하거나 다운로드하면 실행 가능한 예제가 표시됩니다. 이 서버에는 아직 지정할 모델이 없습니다.",
},
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index ccdf44d0a87..e2601626995 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2904,6 +2904,19 @@ export const ptBR = {
addConnection: "Para usar um modelo de decisões hospedado, adicione TypeSafe, Liquid AI ou OpenRouter em Conexões.",
openConnections: "Abrir Conexões",
},
+ mcp: {
+ title: "Acesso de agentes (MCP)",
+ description: "Permita que agentes de código como Claude Code e Codex usem o Unsloth Studio via MCP. Os agentes entram com um token de acesso desta página.",
+ enable: "Permitir conexões de agentes",
+ enableDescription: "Atende /mcp/ para solicitações que trazem um token de acesso do Unsloth Studio.",
+ lockedByEnv: "Definido por {name}.",
+ loadError: "Não foi possível carregar as configurações de acesso de agentes.",
+ saveError: "Não foi possível salvar a configuração de acesso de agentes.",
+ agent: "Agente",
+ exportKeyHint: "Defina {name} com um token de acesso desta página antes de iniciar o agente.",
+ configFileHint: "Adicione isto a {path}.",
+ keywords: "mcp model context protocol agents claude codex tools agentes agente ferramentas protocolo de contexto de modelo",
+ },
usageNoModel:
"Carregue ou baixe um modelo para ver exemplos executáveis. Este servidor ainda não tem nenhum modelo para indicar.",
},
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 7ea6f50a12e..3359e7ffc62 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2899,6 +2899,19 @@ export const ru = {
addConnection: "Чтобы использовать облачную модель решений, добавьте TypeSafe, Liquid AI или OpenRouter в разделе «Подключения».",
openConnections: "Открыть подключения",
},
+ mcp: {
+ title: "Доступ агентов (MCP)",
+ description: "Разрешите агентам для программирования, таким как Claude Code и Codex, работать с Unsloth Studio через MCP. Агенты входят с токеном доступа с этой страницы.",
+ enable: "Разрешить подключения агентов",
+ enableDescription: "Обслуживает /mcp/ для запросов с токеном доступа Unsloth Studio.",
+ lockedByEnv: "Задано через {name}.",
+ loadError: "Не удалось загрузить настройки доступа агентов.",
+ saveError: "Не удалось сохранить настройку доступа агентов.",
+ agent: "Агент",
+ exportKeyHint: "Перед запуском агента задайте в {name} токен доступа с этой страницы.",
+ configFileHint: "Добавьте это в {path}.",
+ keywords: "mcp model context protocol agents claude codex tools агенты агент инструменты протокол контекста модели",
+ },
usageNoModel:
"Загрузите или скачайте модель, чтобы увидеть готовые к запуску примеры. На этом сервере пока нет модели, которую можно подставить в примеры.",
},
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index e3ba0784a0c..d8f09d8c148 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -3102,6 +3102,19 @@ export const sv = {
"Lägg till TypeSafe, Liquid AI eller OpenRouter under Anslutningar för att använda en värdbaserad beslutsmodell.",
openConnections: "Öppna Anslutningar",
},
+ mcp: {
+ title: "Agentåtkomst (MCP)",
+ description: "Låt kodagenter som Claude Code och Codex använda Unsloth Studio via MCP. Agenter loggar in med en åtkomsttoken från den här sidan.",
+ enable: "Tillåt agentanslutningar",
+ enableDescription: "Betjänar /mcp/ för förfrågningar som har en åtkomsttoken för Unsloth Studio.",
+ lockedByEnv: "Angiven av {name}.",
+ loadError: "Det gick inte att läsa in inställningarna för agentåtkomst.",
+ saveError: "Det gick inte att spara inställningen för agentåtkomst.",
+ agent: "Agent",
+ exportKeyHint: "Sätt {name} till en åtkomsttoken från den här sidan innan du startar agenten.",
+ configFileHint: "Lägg till det här i {path}.",
+ keywords: "mcp model context protocol agents claude codex tools agenter agent verktyg modellkontextprotokoll",
+ },
},
about: {
title: "Om",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 82ec7d4effb..ed151b39a36 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2837,6 +2837,19 @@ export const zhCN = {
addConnection: "要使用托管的决策模型,请在连接中添加 TypeSafe、Liquid AI 或 OpenRouter。",
openConnections: "打开连接",
},
+ mcp: {
+ title: "智能体访问 (MCP)",
+ description: "允许 Claude Code、Codex 等编程智能体通过 MCP 使用 Unsloth Studio。智能体使用本页的访问 token 登录。",
+ enable: "允许智能体连接",
+ enableDescription: "为携带 Unsloth Studio 访问 token 的请求提供 /mcp/。",
+ lockedByEnv: "由 {name} 设置。",
+ loadError: "无法加载智能体访问设置。",
+ saveError: "无法保存智能体访问设置。",
+ agent: "智能体",
+ exportKeyHint: "启动智能体前,请将 {name} 设置为本页的访问 token。",
+ configFileHint: "将此内容添加到 {path}。",
+ keywords: "mcp model context protocol agents claude codex tools 智能体 代理 工具 模型上下文协议",
+ },
usageNoModel:
"加载或下载一个模型后即可看到可运行的示例。此服务器目前还没有可指定的模型。",
},
diff --git a/studio/frontend/tests/agents-model-picker.test.ts b/studio/frontend/tests/agents-model-picker.test.ts
index 0d9e5a93a05..53373f08afe 100644
--- a/studio/frontend/tests/agents-model-picker.test.ts
+++ b/studio/frontend/tests/agents-model-picker.test.ts
@@ -10,6 +10,11 @@ import {
isClassifierOrRerankerHubModel,
isSpeechOnlyHubModel,
} from "../src/features/settings/lib/agent-hub-model.ts";
+import {
+ SUPPORTED_AGENTS,
+ UNSLOTH_START_DOCS_URL,
+ detailsFor,
+} from "../src/features/settings/components/coding-agent-list.ts";
import { en } from "../src/i18n/locales/en.ts";
const TAB = readFileSync(
@@ -180,3 +185,25 @@ test("an adopted resident model does not use a cached load ID", () => {
TAB.includes("const cachedLoadId = selectedModelIsActive\n ? null"),
);
});
+
+test("the shared agent list keeps the seven agents in order", () => {
+ assert.deepEqual(
+ SUPPORTED_AGENTS.map((agent) => agent.id),
+ ["claude", "codex", "hermes", "openclaw", "opencode", "dsh", "vibe"],
+ );
+ assert.equal(detailsFor("codex").name, "OpenAI Codex");
+ assert.deepEqual(detailsFor("pi"), {
+ id: "pi",
+ name: "pi",
+ docsUrl: UNSLOTH_START_DOCS_URL,
+ color: "#64748B",
+ mark: "pi",
+ });
+});
+
+test("the Agents tab uses the shared agent list and copy blocks", () => {
+ assert.match(TAB, /from "\.\.\/components\/coding-agent-list";/);
+ assert.match(TAB, /from "\.\.\/components\/agent-command-block";/);
+ assert.doesNotMatch(TAB, /const SUPPORTED_AGENTS/);
+ assert.doesNotMatch(TAB, /function (CommandBlock|useCopyButton)\(/);
+});
diff --git a/studio/frontend/tests/mcp-access-api.test.ts b/studio/frontend/tests/mcp-access-api.test.ts
new file mode 100644
index 00000000000..ef60abdd2a8
--- /dev/null
+++ b/studio/frontend/tests/mcp-access-api.test.ts
@@ -0,0 +1,93 @@
+// 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 test from "node:test";
+
+import type * as McpAccessApi from "../src/features/settings/api/mcp-access.ts";
+import * as formatFastApiError from "../src/lib/format-fastapi-error.ts";
+import { readSrc } from "./helpers/kit.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+const API = readSrc("features/settings/api/mcp-access.ts");
+
+function client(response: () => Response) {
+ const requests: { path: string; init?: RequestInit }[] = [];
+ const api = loadWithStubs<typeof McpAccessApi>(
+ new URL("../src/features/settings/api/mcp-access.ts", import.meta.url),
+ {
+ "@/features/auth": {
+ authFetch: async (path: string, init?: RequestInit) => {
+ requests.push({ path, init });
+ return response();
+ },
+ },
+ "@/lib/format-fastapi-error": formatFastApiError,
+ },
+ );
+ return { api, requests };
+}
+
+const BODY = {
+ enabled: true,
+ forced_by_env: false,
+ url: "http://127.0.0.1:8888/mcp/",
+};
+
+test("loading reads the owner settings route and maps it to camelCase", async () => {
+ for (const forced of [false, true]) {
+ const c = client(() => Response.json({ ...BODY, forced_by_env: forced }));
+ assert.deepEqual(await c.api.loadMcpAccess(), {
+ enabled: true,
+ forcedByEnv: forced,
+ url: "http://127.0.0.1:8888/mcp/",
+ });
+ assert.deepEqual(c.requests, [
+ { path: "/api/settings/mcp-access", init: undefined },
+ ]);
+ }
+});
+
+test("saving sends only the switch value", async () => {
+ const c = client(() => Response.json({ ...BODY, enabled: false }));
+ const saved = await c.api.updateMcpAccess(false);
+ assert.equal(saved.enabled, false);
+ assert.deepEqual(c.requests, [
+ {
+ path: "/api/settings/mcp-access",
+ init: {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled: false }),
+ },
+ },
+ ]);
+});
+
+test("a forced setting and an API-key caller surface the server's reason", async () => {
+ for (const [status, detail] of [
+ [409, "Set by UNSLOTH_STUDIO_ENABLE_MCP."],
+ [403, "Agent access (MCP) can only be changed from the Unsloth UI."],
+ ] as const) {
+ const c = client(() => Response.json({ detail }, { status }));
+ await assert.rejects(c.api.updateMcpAccess(true), (error: Error) => {
+ assert.equal(error.message, detail);
+ return true;
+ });
+ }
+});
+
+test("a body without a detail falls back to a status line", async () => {
+ const c = client(() => new Response("bad gateway", { status: 502 }));
+ await assert.rejects(
+ c.api.loadMcpAccess(),
+ /Failed to load agent access settings \(502\)/,
+ );
+});
+
+test("the client is built on authFetch and readFastApiError", () => {
+ assert.match(API, /import \{ authFetch \} from "@\/features\/auth";/);
+ assert.match(API, /readFastApiError\(res, /);
+ assert.match(API, /forcedByEnv: settings\.forced_by_env/);
+});
diff --git a/studio/frontend/tests/mcp-access-section.test.ts b/studio/frontend/tests/mcp-access-section.test.ts
new file mode 100644
index 00000000000..ae9eebde706
--- /dev/null
+++ b/studio/frontend/tests/mcp-access-section.test.ts
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// source assertions avoid the auth barrel, which cannot load in this test harness.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { ar } from "../src/i18n/locales/ar.ts";
+import { de } from "../src/i18n/locales/de.ts";
+import { en } from "../src/i18n/locales/en.ts";
+import { es } from "../src/i18n/locales/es.ts";
+import { fr } from "../src/i18n/locales/fr.ts";
+import { he } from "../src/i18n/locales/he.ts";
+import { hi } from "../src/i18n/locales/hi.ts";
+import { it } from "../src/i18n/locales/it.ts";
+import { ja } from "../src/i18n/locales/ja.ts";
+import { ko } from "../src/i18n/locales/ko.ts";
+import { ptBR } from "../src/i18n/locales/pt-br.ts";
+import { ru } from "../src/i18n/locales/ru.ts";
+import { sv } from "../src/i18n/locales/sv.ts";
+import { zhCN } from "../src/i18n/locales/zh-CN.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const SECTION = readSrc("features/settings/components/mcp-access-section.tsx");
+const API_TAB = readSrc("features/settings/tabs/api-keys-tab.tsx");
+const TUNNEL_PREF = readSrc(
+ "features/settings/components/tunnel-preference.ts",
+);
+
+const LOCALES = { ar, de, en, es, fr, he, hi, it, ja, ko, ptBR, ru, sv, zhCN };
+
+test("only the owner sees it, after the Decision API section, and settings search finds it", () => {
+ assert.match(
+ API_TAB,
+ /\{isOwner \? <DecisionApiSection \/> : null\}\s*\{isOwner \? <McpAccessSection apiKey=\{revealed\} \/> : null\}/,
+ );
+ assert.doesNotMatch(SECTION, /useIsAccountOwner/);
+ assert.match(
+ SECTION,
+ /data-settings-label=\{t\("settings.apiKeys.mcp.title"\)\}/,
+ );
+});
+
+test("the switch is the shared primitive and the environment locks it in text", () => {
+ assert.match(
+ SECTION,
+ /import \{ Switch \} from "@\/components\/ui\/switch";/,
+ );
+ assert.match(SECTION, /<SettingsRow/);
+ assert.match(SECTION, /disabled=\{busy \|\| settings\.forcedByEnv\}/);
+ assert.match(SECTION, /const ENV_FORCE = "UNSLOTH_STUDIO_ENABLE_MCP";/);
+ assert.match(
+ SECTION,
+ /forcedByEnv\s*\?\s*t\("settings.apiKeys.mcp.lockedByEnv", \{ name: ENV_FORCE \}\)/,
+ );
+ assert.equal(en.settings.apiKeys.mcp.lockedByEnv, "Set by {name}.");
+});
+
+test("a rejected change resyncs and shows the error inline, and a failed first load still renders the section", () => {
+ const apply = SECTION.slice(
+ SECTION.indexOf("const apply = async"),
+ SECTION.indexOf("if (!(settings || error))"),
+ );
+ assert.ok(
+ apply.indexOf("updateMcpAccess(enabled)") <
+ apply.lastIndexOf("loadMcpAccess()"),
+ );
+ assert.match(apply, /t\("settings.apiKeys.mcp.saveError"\)/);
+ assert.match(SECTION, /text-xs leading-snug text-destructive/);
+ assert.doesNotMatch(SECTION, /toast/);
+ assert.match(SECTION, /if \(!\(settings \|\| error\)\) \{\s*return null;/);
+ assert.ok(SECTION.indexOf("{error ? (") < SECTION.indexOf("{settings ? ("));
+ assert.match(SECTION, /translate\("settings.apiKeys.mcp.loadError"\)/);
+});
+
+test("no emerald and no unscaled lengths", () => {
+ assert.doesNotMatch(SECTION, /emerald/);
+ assert.doesNotMatch(SECTION, /-\[\d+(?:\.\d+)?(?:px|rem)\]/);
+});
+
+test("the copy stays plain in every locale", () => {
+ const keys = Object.keys(en.settings.apiKeys.mcp);
+ for (const [name, locale] of Object.entries(LOCALES)) {
+ const copy = (
+ locale.settings.apiKeys as unknown as {
+ mcp: Record<string, string>;
+ }
+ ).mcp;
+ assert.deepEqual(Object.keys(copy), keys, name);
+ for (const value of Object.values(copy)) {
+ assert.doesNotMatch(value, /[;—]/, `${name}: ${value}`);
+ }
+ }
+});
+
+test("the setup snippet shows only while on, targets the usage examples' address and names the variable and file", () => {
+ assert.match(SECTION, /const snippet = settings\?\.enabled\s*\?/);
+ assert.match(SECTION, /\{snippet \? \(/);
+ assert.match(SECTION, /<CommandBlock command=\{snippet\.text\} \/>/);
+ assert.match(SECTION, /buildMcpSnippet\(agent, settings\.url, os, apiKey\)/);
+ assert.match(
+ SECTION,
+ /useTunnel && cloudflareUrl\s*\?\s*cloudflareUrl\s*:\s*\(serverUrl \?\? origin\)/,
+ );
+ // tunnel preference changes must notify this section immediately.
+ assert.match(
+ SECTION,
+ /useSyncExternalStore\(\s*subscribeUseTunnelPref,\s*readUseTunnelPref,/,
+ );
+ assert.match(
+ TUNNEL_PREF,
+ /function writeUseTunnelPref[\s\S]*?for \(const listener of useTunnelListeners\) \{\s*listener\(\);/,
+ );
+ assert.match(
+ SECTION,
+ /snippet\.readsKeyEnv \? \([\s\S]*?t\("settings.apiKeys.mcp.exportKeyHint", \{\s*name: MCP_API_KEY_ENV,?\s*\}\)/,
+ );
+ assert.match(
+ SECTION,
+ /t\("settings.apiKeys.mcp.configFileHint", \{\s*path: snippet\.configPath,?\s*\}\)/,
+ );
+ assert.equal(
+ en.settings.apiKeys.mcp.exportKeyHint,
+ "Set {name} to an access token from this page before you start the agent.",
+ );
+});
+
+test("a key created on this page fills the snippet and is kept out of reload snapshots", () => {
+ assert.match(SECTION, /buildMcpSnippet\(agent, base, os, apiKey\)/);
+ assert.match(
+ SECTION,
+ /data-reload-snapshot-sensitive=\{apiKey \? "" : undefined\}\s*>\s*<CommandBlock command=\{snippet\.text\} \/>/,
+ );
+});
+
+test("the agent picker keeps the pill trigger and shared list, CLI agents get the shell choice, and both picks persist", () => {
+ const trigger = SECTION.slice(
+ SECTION.indexOf("<SelectTrigger"),
+ SECTION.indexOf("</SelectTrigger>"),
+ );
+ assert.ok(trigger.length > 0);
+ assert.doesNotMatch(trigger, /rounded-/);
+ assert.match(SECTION, /SUPPORTED_AGENTS\.map\(/);
+ assert.match(SECTION, /from "\.\/coding-agent-list";/);
+ assert.match(SECTION, /from "\.\/agent-command-block";/);
+ assert.match(SECTION, /MCP_SHELL_AGENT_IDS\.has\(agent\) \? \(\s*<fieldset/);
+ assert.match(SECTION, /className="hub-tab-toggle inline-flex/);
+ assert.match(SECTION, /aria-pressed=\{os === option\.os\}/);
+ assert.match(SECTION, /useSettingsPanelPrefsStore\(\(s\) => s\.mcpAgent\)/);
+ assert.match(SECTION, /useSettingsPanelPrefsStore\(\(s\) => s\.mcpOs\)/);
+ assert.match(SECTION, /onValueChange=\{setStoredAgent\}/);
+ assert.match(SECTION, /onClick=\{\(\) => setStoredOs\(option\.os\)\}/);
+});
diff --git a/studio/frontend/tests/mcp-agent-snippet.test.ts b/studio/frontend/tests/mcp-agent-snippet.test.ts
new file mode 100644
index 00000000000..fbca8985721
--- /dev/null
+++ b/studio/frontend/tests/mcp-agent-snippet.test.ts
@@ -0,0 +1,269 @@
+// 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 test from "node:test";
+
+import yaml from "js-yaml";
+
+import { SUPPORTED_AGENTS } from "../src/features/settings/components/coding-agent-list.ts";
+import {
+ MCP_SHELL_AGENT_IDS,
+ buildMcpSnippet,
+ mcpEndpointUrl,
+} from "../src/features/settings/components/mcp-agent-snippet.ts";
+
+const LOCAL = "http://127.0.0.1:8888";
+const TUNNEL = "https://shed-topic-remark-arguments.trycloudflare.com/";
+const LAN = "http://192.168.1.20:8888";
+const KEY = "sk-unsloth-0123456789abcdef0123456789abcdef";
+
+// dsh evaluates `!!js` scalars; the test only needs to read them back.
+const DSH_SCHEMA = yaml.DEFAULT_SCHEMA.extend([
+ new yaml.Type("tag:yaml.org,2002:js", {
+ kind: "scalar",
+ construct: (source: string) => ({ js: source }),
+ }),
+]);
+
+function snippet(
+ agent: string,
+ os: "unix" | "windows" = "unix",
+ key: string | null = null,
+ base: string = LOCAL,
+) {
+ const result = buildMcpSnippet(agent, base, os, key);
+ assert.ok(result, `${agent} has a snippet`);
+ return result;
+}
+
+test("every listed agent has a snippet and only the CLIs get an OS choice", () => {
+ for (const agent of SUPPORTED_AGENTS) {
+ assert.ok(buildMcpSnippet(agent.id, LOCAL, "unix"), agent.id);
+ }
+ assert.deepEqual([...MCP_SHELL_AGENT_IDS], ["claude", "codex"]);
+ assert.equal(buildMcpSnippet("pi", LOCAL, "unix"), null);
+});
+
+test("the endpoint is always the origin plus /mcp/", () => {
+ assert.equal(mcpEndpointUrl(LOCAL), "http://127.0.0.1:8888/mcp/");
+ assert.equal(
+ mcpEndpointUrl(TUNNEL),
+ "https://shed-topic-remark-arguments.trycloudflare.com/mcp/",
+ );
+ assert.equal(mcpEndpointUrl(LAN), "http://192.168.1.20:8888/mcp/");
+ assert.equal(
+ mcpEndpointUrl("http://127.0.0.1:8888/mcp"),
+ "http://127.0.0.1:8888/mcp/",
+ );
+ assert.equal(
+ mcpEndpointUrl("https://studio.example/some/path?x=1#y"),
+ "https://studio.example/mcp/",
+ );
+ assert.equal(mcpEndpointUrl(""), null);
+ assert.equal(mcpEndpointUrl("not a url"), null);
+ assert.equal(mcpEndpointUrl("file:///etc/passwd"), null);
+ assert.equal(buildMcpSnippet("claude", "not a url", "unix"), null);
+});
+
+test("Claude Code reads the key from the shell it runs in", () => {
+ assert.equal(
+ snippet("claude", "unix").text,
+ 'claude mcp add --transport http unsloth-studio http://127.0.0.1:8888/mcp/ --header "Authorization: Bearer $UNSLOTH_API_KEY"',
+ );
+ assert.equal(
+ snippet("claude", "windows").text,
+ 'claude mcp add --transport http unsloth-studio http://127.0.0.1:8888/mcp/ --header "Authorization: Bearer $env:UNSLOTH_API_KEY"',
+ );
+ assert.equal(snippet("claude").readsKeyEnv, true);
+});
+
+test("Claude Code quotes a real key for each shell", () => {
+ const unix = snippet("claude", "unix", KEY);
+ assert.equal(
+ unix.text,
+ `claude mcp add --transport http unsloth-studio http://127.0.0.1:8888/mcp/ --header 'Authorization: Bearer ${KEY}'`,
+ );
+ assert.equal(unix.readsKeyEnv, false);
+ assert.ok(
+ snippet("claude", "windows", KEY).text.endsWith(
+ `--header 'Authorization: Bearer ${KEY}'`,
+ ),
+ );
+ assert.ok(
+ snippet("claude", "unix", "it's").text.endsWith(
+ `--header 'Authorization: Bearer it'\\''s'`,
+ ),
+ );
+ assert.ok(
+ snippet("claude", "windows", "it's").text.endsWith(
+ `--header 'Authorization: Bearer it''s'`,
+ ),
+ );
+});
+
+test("Codex names the variable and offers a longer tool timeout", () => {
+ const text = snippet("codex").text;
+ assert.equal(
+ text.split("\n")[0],
+ "codex mcp add unsloth-studio --url http://127.0.0.1:8888/mcp/ --bearer-token-env-var UNSLOTH_API_KEY",
+ );
+ assert.match(text, /^# tool_timeout_sec = 300$/m);
+ assert.equal(snippet("codex", "windows").text, text);
+ // Codex cannot accept the key directly.
+ assert.equal(snippet("codex", "unix", KEY).text, text);
+ assert.equal(snippet("codex", "unix", KEY).readsKeyEnv, true);
+});
+
+test("OpenCode gets valid JSON with OAuth off and an env reference", () => {
+ const parsed = JSON.parse(snippet("opencode").text);
+ assert.deepEqual(parsed, {
+ mcp: {
+ "unsloth-studio": {
+ type: "remote",
+ url: "http://127.0.0.1:8888/mcp/",
+ oauth: false,
+ headers: { Authorization: "Bearer {env:UNSLOTH_API_KEY}" },
+ },
+ },
+ });
+ const withKey = JSON.parse(snippet("opencode", "unix", 'a"b').text);
+ assert.equal(
+ withKey.mcp["unsloth-studio"].headers.Authorization,
+ 'Bearer a"b',
+ );
+});
+
+test("OpenClaw gets valid JSON with the transport set explicitly", () => {
+ const parsed = JSON.parse(snippet("openclaw").text);
+ assert.deepEqual(parsed, {
+ mcp: {
+ servers: {
+ "unsloth-studio": {
+ url: "http://127.0.0.1:8888/mcp/",
+ transport: "streamable-http",
+ headers: { Authorization: "Bearer ${UNSLOTH_API_KEY}" },
+ },
+ },
+ },
+ });
+ assert.equal(
+ JSON.parse(snippet("openclaw", "unix", KEY).text).mcp.servers[
+ "unsloth-studio"
+ ].headers.Authorization,
+ `Bearer ${KEY}`,
+ );
+});
+
+test("Hermes gets YAML with ${UNSLOTH_API_KEY} and the reload step", () => {
+ const text = snippet("hermes").text;
+ assert.ok(text.includes('Authorization: "Bearer ${UNSLOTH_API_KEY}"'));
+ assert.match(text, /\/reload-mcp/);
+ assert.deepEqual(yaml.load(text), {
+ mcp_servers: {
+ unsloth_studio: {
+ url: "http://127.0.0.1:8888/mcp/",
+ headers: { Authorization: "Bearer ${UNSLOTH_API_KEY}" },
+ },
+ },
+ });
+ const tricky = 'k"e\\y';
+ assert.equal(
+ (
+ yaml.load(snippet("hermes", "unix", tricky).text) as {
+ mcp_servers: {
+ unsloth_studio: { headers: { Authorization: string } };
+ };
+ }
+ ).mcp_servers.unsloth_studio.headers.Authorization,
+ `Bearer ${tricky}`,
+ );
+});
+
+test("Mistral Vibe uses the static auth block", () => {
+ assert.equal(
+ snippet("vibe").text,
+ [
+ "[[mcp_servers]]",
+ 'name = "unsloth_studio"',
+ 'transport = "streamable-http"',
+ 'url = "http://127.0.0.1:8888/mcp/"',
+ "",
+ "[mcp_servers.auth]",
+ 'type = "static"',
+ 'api_key_env = "UNSLOTH_API_KEY"',
+ 'api_key_header = "Authorization"',
+ 'api_key_format = "Bearer {token}"',
+ ].join("\n"),
+ );
+ // Vibe rejects legacy top-level keys mixed with [auth].
+ const text = snippet("vibe").text;
+ assert.doesNotMatch(text, /^headers/m);
+ assert.ok(text.indexOf("api_key_env") > text.indexOf("[mcp_servers.auth]"));
+ assert.equal(snippet("vibe", "unix", KEY).text, snippet("vibe").text);
+});
+
+test("DeepSeek Harness evaluates the key with !!js, or takes a plain string", () => {
+ const text = snippet("dsh").text;
+ assert.ok(
+ text.includes(
+ "Authorization: !!js '`Bearer ${process.env.UNSLOTH_API_KEY}`'",
+ ),
+ );
+ assert.deepEqual(yaml.load(text, { schema: DSH_SCHEMA }), [
+ {
+ insert: [
+ {
+ id: "mcp-unsloth-studio",
+ name: "@deepseek-ai/dsh-mcp-client",
+ config: {
+ serverName: "unsloth-studio",
+ transport: "streamable-http",
+ url: "http://127.0.0.1:8888/mcp/",
+ headers: {
+ Authorization: {
+ js: "`Bearer ${process.env.UNSLOTH_API_KEY}`",
+ },
+ },
+ },
+ },
+ ],
+ },
+ ]);
+ const withKey = snippet("dsh", "unix", KEY).text;
+ assert.doesNotMatch(withKey, /!!js/);
+ assert.ok(withKey.includes(`Authorization: "Bearer ${KEY}"`));
+});
+
+test("no snippet carries a key unless one is passed", () => {
+ for (const agent of SUPPORTED_AGENTS) {
+ for (const os of ["unix", "windows"] as const) {
+ for (const base of [LOCAL, TUNNEL, LAN]) {
+ for (const key of [null, ""]) {
+ const result = snippet(agent.id, os, key, base);
+ assert.doesNotMatch(result.text, /sk-/, `${agent.id} ${os}`);
+ assert.equal(result.readsKeyEnv, true, `${agent.id} ${os}`);
+ assert.match(result.text, /UNSLOTH_API_KEY/);
+ assert.ok(
+ result.text.includes(mcpEndpointUrl(base) as string),
+ `${agent.id} ${os} ${base}`,
+ );
+ }
+ }
+ }
+ }
+});
+
+test("config-file agents say which file to edit", () => {
+ assert.equal(snippet("claude").configPath, null);
+ assert.equal(snippet("codex").configPath, null);
+ assert.equal(
+ snippet("opencode").configPath,
+ "~/.config/opencode/opencode.json",
+ );
+ assert.equal(snippet("hermes").configPath, "~/.hermes/config.yaml");
+ assert.equal(snippet("openclaw").configPath, "~/.openclaw/openclaw.json");
+ assert.equal(snippet("vibe").configPath, "~/.vibe/config.toml");
+ assert.equal(snippet("dsh").configPath, "~/.dsh/cordis.patch.yml");
+});
diff --git a/studio/frontend/tests/settings-panel-prefs.test.ts b/studio/frontend/tests/settings-panel-prefs.test.ts
index 86d0081d77d..918fc14b580 100644
--- a/studio/frontend/tests/settings-panel-prefs.test.ts
+++ b/studio/frontend/tests/settings-panel-prefs.test.ts
@@ -27,6 +27,8 @@ store.set(
apiExampleLang: "pythonTools",
apiExampleOs: "windows",
apiExampleAgent: "codex",
+ mcpAgent: "hermes",
+ mcpOs: "windows",
resourcesLiveUpdates: false,
fineTuneAction: "recipes",
},
@@ -46,6 +48,8 @@ test("a version 0 record hydrates every field", () => {
assert.equal(s.agentsOs, null);
assert.equal(s.agentsVariant, "UD-Q4_K_XL");
assert.equal(s.apiExampleOs, "windows");
+ assert.equal(s.mcpAgent, "hermes");
+ assert.equal(s.mcpOs, "windows");
assert.equal(s.resourcesLiveUpdates, false);
assert.equal(s.fineTuneAction, "recipes");
});
@@ -229,3 +233,23 @@ test("corrupt JSON does not break the store", async () => {
"function",
);
});
+
+test("the agent access (MCP) picks persist and reject unknown values", () => {
+ const s = useSettingsPanelPrefsStore.getState();
+ s.setMcpAgent("dsh");
+ s.setMcpOs("unix");
+ const raw = store.get(KEY);
+ assert.ok(raw);
+ const state = JSON.parse(raw as string).state;
+ assert.equal(state.mcpAgent, "dsh");
+ assert.equal(state.mcpOs, "unix");
+
+ const merged = useSettingsPanelPrefsStore.persist.getOptions().merge;
+ assert.ok(merged);
+ const out = merged(
+ { mcpAgent: 7, mcpOs: "fish" },
+ useSettingsPanelPrefsStore.getState(),
+ ) as { mcpAgent: unknown; mcpOs: unknown };
+ assert.equal(out.mcpAgent, null);
+ assert.equal(out.mcpOs, null);
+});
diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.ts
index 8e31194d656..bc7412102f1 100644
--- a/studio/frontend/tests/settings-search.test.ts
+++ b/studio/frontend/tests/settings-search.test.ts
@@ -122,3 +122,30 @@ test("the endpoint rows are searchable only while Hugging Face serves, as they r
assert.deepEqual(endpoint.map((key) => [huggingFace.includes(key), modelScope.includes(key)]), [[true, false], [true, false]]);
assert.ok(modelScope.includes("settings.general.hub.source"));
});
+
+const MCP_ENTRY = "settings.apiKeys.mcp.title";
+
+test("agent access (MCP) is found by the protocol and the agents' names, by the owner only", () => {
+ const index = createSettingsSearchIndex({
+ desktop: false,
+ closeToTray: false,
+ });
+ assert.ok(index["api-keys"].includes(MCP_ENTRY));
+ const keywordsKey = SETTINGS_SEARCH_KEYWORDS[MCP_ENTRY];
+ assert.equal(keywordsKey, "settings.apiKeys.mcp.keywords");
+ const haystack =
+ `${en.settings.apiKeys.mcp.title} ${en.settings.apiKeys.mcp.keywords}`.toLowerCase();
+ for (const term of ["mcp", "claude", "codex", "model context protocol"]) {
+ assert.ok(haystack.includes(term), `search matches "${term}"`);
+ }
+ assert.ok(
+ renderedSearchEntries(index, "api-keys", "huggingface", true).includes(
+ MCP_ENTRY,
+ ),
+ );
+ assert.ok(
+ !renderedSearchEntries(index, "api-keys", "huggingface", false).includes(
+ MCP_ENTRY,
+ ),
+ );
+});
diff --git a/studio/frontend/tests/tunnel-preference.test.ts b/studio/frontend/tests/tunnel-preference.test.ts
new file mode 100644
index 00000000000..9f3ee8abfc7
--- /dev/null
+++ b/studio/frontend/tests/tunnel-preference.test.ts
@@ -0,0 +1,45 @@
+// 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 test from "node:test";
+
+import {
+ readUseTunnelPref,
+ subscribeUseTunnelPref,
+ writeUseTunnelPref,
+} from "../src/features/settings/components/tunnel-preference.ts";
+
+test("a failed storage write still publishes the current tunnel choice", () => {
+ const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ let notifications = 0;
+ const unsubscribe = subscribeUseTunnelPref(() => {
+ notifications += 1;
+ });
+
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ localStorage: {
+ getItem: () => "true",
+ setItem: () => {
+ throw new Error("storage blocked");
+ },
+ },
+ },
+ });
+
+ try {
+ assert.equal(readUseTunnelPref(), true);
+ writeUseTunnelPref(false);
+ assert.equal(readUseTunnelPref(), false);
+ assert.equal(notifications, 1);
+ } finally {
+ unsubscribe();
+ if (previousWindow) {
+ Object.defineProperty(globalThis, "window", previousWindow);
+ } else {
+ Reflect.deleteProperty(globalThis, "window");
+ }
+ }
+});