π OpenHands: AI-Driven Development
Preserve encrypted MCP credentials for agent conversations (#1426)
Graham Neubig17334f41c195
diff --git a/__tests__/hooks/mutation/use-update-mcp-server.test.ts b/__tests__/hooks/mutation/use-update-mcp-server.test.tsnew file mode 100644index 0000000000..18782a6244--- /dev/null+++ b/__tests__/hooks/mutation/use-update-mcp-server.test.ts@@ -0,0 +1,103 @@+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { describe, expect, it, vi, beforeEach } from "vitest";+import React from "react";+import SettingsService, {+ type SettingsApiResponse,+} from "#/api/settings-service/settings-service.api";+import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";++const useSettingsMock = vi.fn();+vi.mock("#/hooks/query/use-settings", () => ({+ useSettings: () => useSettingsMock(),+}));++import { useUpdateMcpServer } from "#/hooks/mutation/use-update-mcp-server";++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ function Wrapper({ children }: { children: React.ReactNode }) {+ return React.createElement(+ QueryClientProvider,+ { client: queryClient },+ children,+ );+ }+ return Wrapper;+};++describe("useUpdateMcpServer - stdio credential preservation", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ });++ it("saves the encrypted stdio env, not the redacted placeholder, when a stdio server is renamed", async () => {+ // The redacted settings the editor reads from still carry the original name+ // ("old-name") and redacted env. The user renames to "new-name" and leaves+ // the secret env value as "<redacted>".+ useSettingsMock.mockReturnValue({+ data: {+ agent_settings: {+ mcp_config: {+ mcpServers: {+ "old-name": {+ command: "npx",+ env: { API_KEY: REDACTED_MCP_SECRET_VALUE },+ },+ },+ },+ },+ },+ });++ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: {+ mcp_config: {+ mcpServers: {+ "old-name": {+ command: "npx",+ env: { API_KEY: "gAAAAA-encrypted-api-key" },+ },+ },+ },+ },+ } as unknown as SettingsApiResponse);++ const { result } = renderHook(() => useUpdateMcpServer(), {+ wrapper: createWrapper(),+ });++ await result.current.mutateAsync({+ serverId: "stdio-0",+ server: {+ id: "stdio-0",+ type: "stdio",+ name: "new-name",+ command: "npx",+ env: { API_KEY: REDACTED_MCP_SECRET_VALUE },+ },+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(SettingsService.saveSettings).toHaveBeenCalledTimes(1);+ const savedDiff = vi.mocked(SettingsService.saveSettings).mock.calls[0][0]+ .agent_settings_diff as Record<string, unknown> | undefined;+ const savedSdkConfig = savedDiff?.mcp_config;+ expect(savedSdkConfig).toMatchObject({+ mcpServers: {+ "new-name": {+ command: "npx",+ env: { API_KEY: "gAAAAA-encrypted-api-key" },+ },+ },+ });+ // The literal placeholder must never round-trip into the saved config.+ expect(JSON.stringify(savedSdkConfig)).not.toContain(+ REDACTED_MCP_SECRET_VALUE,+ );+ });+});diff --git a/src/api/agent-server-adapter.test.ts b/src/api/agent-server-adapter.test.tsnew file mode 100644index 0000000000..a44c8dba31--- /dev/null+++ b/src/api/agent-server-adapter.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from "vitest";+import { DEFAULT_SETTINGS } from "#/services/settings";+import type { Settings } from "#/types/settings";+import { buildStartConversationRequest } from "./agent-server-adapter";++const encryptedValue = "gAAAAAencrypted-mcp-header";++function makeSettings(agentSettings: Settings["agent_settings"]): Settings {+ return {+ ...DEFAULT_SETTINGS,+ agent_settings: agentSettings,+ conversation_settings: {+ confirmation_mode: false,+ security_analyzer: null,+ max_iterations: 20,+ },+ };+}++describe("buildStartConversationRequest", () => {+ it("marks OpenHands start requests as encrypted when MCP headers are encrypted", () => {+ const agentSettings = {+ agent_kind: "openhands",+ llm: {+ model: "litellm_proxy/openai/gpt-5.5",+ api_key: "gAAAAAencrypted-llm-api-key",+ },+ mcp_config: {+ mcpServers: {+ linear: {+ url: "https://mcp.linear.app/mcp",+ transport: "http",+ headers: {+ Authorization: encryptedValue,+ },+ },+ },+ },+ };+ const settings = makeSettings(agentSettings);++ const payload = buildStartConversationRequest({+ settings,+ encryptedAgentSettings: agentSettings,+ encryptedConversationSettings: settings.conversation_settings!,+ secretsEncrypted: true,+ });++ expect(payload.agent_settings.agent_kind).toBe("openhands");+ expect(payload.agent_settings.mcp_config).toEqual(agentSettings.mcp_config);+ expect(payload.secrets_encrypted).toBe(true);+ });++ it("marks ACP start requests as encrypted when MCP headers are encrypted", () => {+ const agentSettings = {+ agent_kind: "acp",+ acp_server: "codex",+ acp_command: ["codex-acp"],+ acp_model: "gpt-5.5/medium",+ mcp_config: {+ mcpServers: {+ linear: {+ url: "https://mcp.linear.app/mcp",+ transport: "http",+ headers: {+ Authorization: encryptedValue,+ },+ },+ },+ },+ };+ const settings = makeSettings(agentSettings);++ const payload = buildStartConversationRequest({+ settings,+ encryptedAgentSettings: agentSettings,+ encryptedConversationSettings: settings.conversation_settings!,+ secretsEncrypted: true,+ });++ expect(payload.agent_settings.agent_kind).toBe("acp");+ expect(payload.agent_settings.mcp_config).toEqual(agentSettings.mcp_config);+ expect(payload.secrets_encrypted).toBe(true);+ });++ it("keeps ACP start requests unencrypted when no encrypted MCP values are present", () => {+ const agentSettings = {+ agent_kind: "acp",+ acp_server: "codex",+ acp_command: ["codex-acp"],+ acp_model: "gpt-5.5/medium",+ mcp_config: {+ mcpServers: {+ publicDocs: {+ url: "https://docs.example.com/mcp",+ transport: "http",+ },+ },+ },+ };+ const settings = makeSettings(agentSettings);++ const payload = buildStartConversationRequest({+ settings,+ encryptedAgentSettings: agentSettings,+ encryptedConversationSettings: settings.conversation_settings!,+ secretsEncrypted: true,+ });++ expect(payload.agent_settings.agent_kind).toBe("acp");+ expect(payload.secrets_encrypted).toBeUndefined();+ });+});diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.tsindex 37b78915ea..22fcefdcc7 100644--- a/src/api/agent-server-adapter.ts+++ b/src/api/agent-server-adapter.ts@@ -409,6 +409,8 @@ type ConversationSettingsPayload = SettingsRecord & {export const ACP_SERVER_TAG_KEY = "acpserver";+const FERNET_TOKEN_PREFIX = "gAAAAA";+const CONVERSATION_SETTINGS_METADATA_KEYS = new Set(["schema_version","agent_settings",@@ -435,6 +437,28 @@ function normalizeSecretString(value: unknown): string | undefined {return trimmed.length > 0 ? trimmed : undefined;}+function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function hasEncryptedMcpSecrets(mcpConfig: unknown): boolean {+ if (!isPlainRecord(mcpConfig) || !isPlainRecord(mcpConfig.mcpServers)) {+ return false;+ }++ return Object.values(mcpConfig.mcpServers).some((server) => {+ if (!isPlainRecord(server)) return false;+ return ["env", "headers"].some((key) => {+ const values = server[key];+ if (!isPlainRecord(values)) return false;+ return Object.values(values).some(+ (value) =>+ typeof value === "string" && value.startsWith(FERNET_TOKEN_PREFIX),+ );+ });+ });+}+function getConversationConfirmationPolicy(conversationSettings: SettingsRecord,) {@@ -900,14 +924,16 @@ export function buildStartConversationRequest(payload.tags = { [ACP_SERVER_TAG_KEY]: acpServerTag };}- // ``secrets_encrypted`` makes the agent-server run every request secret through- // ``cipher.decrypt()`` at conversation start. Suppress it for ACP: an ACP agent- // carries no encrypted payload (no LLM api_key, and credentials ride as- // LookupSecrets whose values are fetched at resolution time, not decrypted), so- // there is nothing to decrypt. Claiming otherwise hard-fails ("cipher not- // configured") on a backend without ``OH_SECRET_KEY`` (e.g. a fresh ACP- // container). Non-ACP conversations still need it for their encrypted LLM key.- if (options.secretsEncrypted && !acpMode) {+ // ``secrets_encrypted`` makes the agent-server decrypt request secrets at+ // conversation start. Non-ACP conversations need it for encrypted LLM keys.+ // ACP normally carries provider credentials as LookupSecrets, so avoid+ // forcing a cipher on fresh ACP-only backends. The exception is MCP:+ // encrypted settings round-trip mcp_config.env/headers as Fernet tokens,+ // and ACP forwards that mcp_config directly to the subprocess.+ if (+ options.secretsEncrypted &&+ (!acpMode || hasEncryptedMcpSecrets(agentSettings.mcp_config))+ ) {payload.secrets_encrypted = true;}diff --git a/src/api/mcp-service/mcp-redacted-credentials.test.ts b/src/api/mcp-service/mcp-redacted-credentials.test.tsnew file mode 100644index 0000000000..888d970cf3--- /dev/null+++ b/src/api/mcp-service/mcp-redacted-credentials.test.ts@@ -0,0 +1,128 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import SettingsService, {+ type SettingsApiResponse,+} from "#/api/settings-service/settings-service.api";+import { substituteRedactedMcpCredentials } from "./mcp-redacted-credentials";+import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";++describe("substituteRedactedMcpCredentials", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("preserves encrypted stdio env when the server is renamed", async () => {+ // Regression: renaming a stdio server left a redacted env value unchanged,+ // so the lookup by the new display name missed the stored entry and the+ // literal "<redacted>" placeholder overwrote the stored encrypted secret.+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: {+ mcp_config: {+ mcpServers: {+ "old-name": {+ command: "npx",+ env: { API_KEY: "gAAAAA-encrypted-api-key" },+ },+ },+ },+ },+ } as unknown as SettingsApiResponse);++ const result = await substituteRedactedMcpCredentials({+ id: "stdio-0",+ type: "stdio",+ name: "new-name",+ command: "npx",+ env: { API_KEY: REDACTED_MCP_SECRET_VALUE },+ });++ expect(result.env).toEqual({ API_KEY: "gAAAAA-encrypted-api-key" });+ expect(result.name).toBe("new-name");+ });++ it("does not restore another server's secret when renamed onto an existing name", async () => {+ // Renaming "alpha" onto "beta"'s name must still resolve alpha's stored+ // entry by position, not beta's entry (which the name match would return).+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: {+ mcp_config: {+ mcpServers: {+ alpha: { command: "npx", env: { TOKEN: "gAAAAA-alpha-token" } },+ beta: { command: "npx", env: { TOKEN: "gAAAAA-beta-token" } },+ },+ },+ },+ } as unknown as SettingsApiResponse);++ const result = await substituteRedactedMcpCredentials({+ id: "stdio-0",+ type: "stdio",+ name: "beta",+ command: "npx",+ env: { TOKEN: REDACTED_MCP_SECRET_VALUE },+ });++ expect(result.env).toEqual({ TOKEN: "gAAAAA-alpha-token" });+ });++ it("leaves typed (non-redacted) env values untouched", async () => {+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: {+ mcp_config: {+ mcpServers: {+ "my-server": {+ command: "npx",+ env: { API_KEY: "gAAAAA-encrypted", REGION: "us-east-1" },+ },+ },+ },+ },+ } as unknown as SettingsApiResponse);++ const result = await substituteRedactedMcpCredentials({+ id: "stdio-0",+ type: "stdio",+ name: "my-server",+ command: "npx",+ env: {+ API_KEY: REDACTED_MCP_SECRET_VALUE,+ REGION: "eu-west-1",+ },+ });++ expect(result.env).toEqual({+ API_KEY: "gAAAAA-encrypted",+ REGION: "eu-west-1",+ });+ });++ it("returns the server unchanged when no env value is redacted", async () => {+ const server = {+ id: "stdio-0",+ type: "stdio" as const,+ name: "my-server",+ command: "npx",+ env: { API_KEY: "plaintext" },+ };++ const result = await substituteRedactedMcpCredentials(server);++ expect(result).toBe(server);+ expect(SettingsService.fetchSettingsFromApi).not.toHaveBeenCalled();+ });++ it("keeps the placeholder when the stored stdio entry is missing", async () => {+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: { mcp_config: { mcpServers: {} } },+ } as unknown as SettingsApiResponse);++ const result = await substituteRedactedMcpCredentials({+ id: "stdio-0",+ type: "stdio",+ name: "new-name",+ command: "npx",+ env: { API_KEY: REDACTED_MCP_SECRET_VALUE },+ });++ expect(result.env).toEqual({ API_KEY: REDACTED_MCP_SECRET_VALUE });+ });+});diff --git a/src/api/mcp-service/mcp-redacted-credentials.ts b/src/api/mcp-service/mcp-redacted-credentials.tsnew file mode 100644index 0000000000..f0f31bd8bc--- /dev/null+++ b/src/api/mcp-service/mcp-redacted-credentials.ts@@ -0,0 +1,148 @@+import SettingsService from "#/api/settings-service/settings-service.api";+import type { MCPServerConfig } from "#/types/mcp-server";+import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";++type StoredMcpServer = {+ url?: unknown;+ transport?: unknown;+ env?: unknown;+ headers?: unknown;+};++type StoredMcpServers = Record<string, StoredMcpServer>;++const isRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === "object" && !Array.isArray(value);++const stringRecord = (value: unknown): Record<string, string> | undefined => {+ if (!isRecord(value)) return undefined;+ const entries = Object.entries(value).filter(+ (entry): entry is [string, string] => typeof entry[1] === "string",+ );+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+};++const hasRedactedValue = (values: Record<string, string> | undefined) =>+ !!values &&+ Object.values(values).some((value) => value === REDACTED_MCP_SECRET_VALUE);++const remoteTransportMatches = (+ type: MCPServerConfig["type"],+ transport: unknown,+) => {+ if (type === "sse") return transport === "sse";+ if (type === "shttp") {+ return (+ transport === undefined ||+ transport === "http" ||+ transport === "shttp" ||+ transport === "streamable-http"+ );+ }+ return false;+};++// The editor assigns each stdio server an id of the form ``stdio-<i>`` matching+// its position in ``parseMcpConfig``'s stdio array. That position is stable+// across a rename because ``parseMcpConfig`` collects stdio entries (those+// without a ``url``) in ``Object.entries`` order, identical for the redacted+// and encrypted settings. Resolve the original stored entry by position so a+// renamed stdio server still finds its stored encrypted env, instead of+// looking it up by the new (no-longer-matching) display name.+const stdioIndexFromId = (id: string | undefined): number | undefined => {+ if (!id) return undefined;+ const match = /^stdio-(\d+)$/.exec(id);+ return match ? Number.parseInt(match[1], 10) : undefined;+};++const findStoredStdioByIndex = (+ id: string | undefined,+ storedServers: StoredMcpServers,+): StoredMcpServer | undefined => {+ const index = stdioIndexFromId(id);+ if (index === undefined) return undefined;+ const stdioEntries = Object.entries(storedServers).filter(+ ([, stored]) => !stored.url,+ );+ return stdioEntries[index]?.[1];+};++const findStoredServer = (+ server: MCPServerConfig,+ storedServers: StoredMcpServers,+): StoredMcpServer | undefined => {+ if (server.type === "stdio") {+ // Prefer the positional id: a rename changes the display name (the stored+ // dict key), and a rename onto an existing name would otherwise restore the+ // wrong server's secrets. Fall back to a name match only when no id-based+ // position is available (e.g. configs built without an editor-assigned id).+ return (+ findStoredStdioByIndex(server.id, storedServers) ??+ (server.name ? storedServers[server.name] : undefined)+ );+ }++ if (server.name && storedServers[server.name]) {+ return storedServers[server.name];+ }++ return Object.values(storedServers).find(+ (stored) =>+ stored.url === server.url &&+ remoteTransportMatches(server.type, stored.transport),+ );+};++async function fetchEncryptedStoredServer(+ server: MCPServerConfig,+): Promise<StoredMcpServer | undefined> {+ const response = await SettingsService.fetchSettingsFromApi("encrypted");+ const mcpConfig = response.agent_settings?.mcp_config;+ if (!isRecord(mcpConfig) || !isRecord(mcpConfig.mcpServers)) {+ return undefined;+ }+ return findStoredServer(server, mcpConfig.mcpServers as StoredMcpServers);+}++/**+ * The MCP editor sees redacted settings (`<redacted>`). When the user leaves+ * a secret unchanged, replace that placeholder with the stored encrypted+ * env/header value so tests and saves round-trip the real credential without+ * exposing plaintext in the browser.+ */+export async function substituteRedactedMcpCredentials(+ server: MCPServerConfig,+): Promise<MCPServerConfig> {+ const redactedStdioEnv =+ server.type === "stdio" && hasRedactedValue(server.env);+ const redactedRemoteApiKey =+ (server.type === "sse" || server.type === "shttp") &&+ server.api_key === REDACTED_MCP_SECRET_VALUE;++ if (!redactedStdioEnv && !redactedRemoteApiKey) return server;++ try {+ const stored = await fetchEncryptedStoredServer(server);+ if (!stored) return server;++ if (redactedStdioEnv) {+ const storedEnv = stringRecord(stored.env) ?? {};+ const env = Object.fromEntries(+ Object.entries(server.env ?? {}).map(([key, value]) => [+ key,+ value === REDACTED_MCP_SECRET_VALUE &&+ typeof storedEnv[key] === "string"+ ? storedEnv[key]+ : value,+ ]),+ );+ return { ...server, env };+ }++ const headers = stringRecord(stored.headers);+ if (!headers) return server;+ return { ...server, api_key: undefined, headers };+ } catch {+ return server;+ }+}diff --git a/src/api/mcp-service/mcp-service.api.test.ts b/src/api/mcp-service/mcp-service.api.test.tsnew file mode 100644index 0000000000..85200530b8--- /dev/null+++ b/src/api/mcp-service/mcp-service.api.test.ts@@ -0,0 +1,85 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { MCPClient } from "@openhands/typescript-client/clients";+import {+ setActiveSelection,+ setRegisteredBackends,+} from "../backend-registry/active-store";+import SettingsService from "../settings-service/settings-service.api";+import McpService from "./mcp-service.api";++vi.mock("@openhands/typescript-client/clients", () => ({+ MCPClient: vi.fn(),+}));++const testServer = vi.fn();+const close = vi.fn();++const encryptedAuthorization = "gAAAAAencrypted-authorization-header";++describe("McpService.testServer", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ setRegisteredBackends([+ {+ id: "local",+ name: "Local",+ host: "http://127.0.0.1:8001",+ apiKey: "session-key",+ kind: "local",+ },+ ]);+ setActiveSelection({ backendId: "local", orgId: null });+ vi.mocked(MCPClient).mockImplementation(function MockMCPClient() {+ return {+ testServer,+ close,+ } as unknown as MCPClient;+ } as unknown as typeof MCPClient);+ testServer.mockResolvedValue({ ok: true, tools: [] });+ });++ it("tests stored remote MCP credentials as encrypted headers, not redacted api_key text", async () => {+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ llm_api_key_is_set: false,+ conversation_settings: {},+ agent_settings: {+ mcp_config: {+ mcpServers: {+ linear: {+ url: "https://mcp.linear.app/mcp",+ transport: "http",+ headers: {+ Authorization: encryptedAuthorization,+ },+ },+ },+ },+ },+ });++ await McpService.testServer({+ id: "shttp-0",+ type: "shttp",+ name: "linear",+ url: "https://mcp.linear.app/mcp",+ api_key: "<redacted>",+ });++ expect(SettingsService.fetchSettingsFromApi).toHaveBeenCalledWith(+ "encrypted",+ );+ expect(testServer).toHaveBeenCalledTimes(1);+ expect(testServer.mock.calls[0][0]).toMatchObject({+ name: "linear",+ server: {+ type: "shttp",+ url: "https://mcp.linear.app/mcp",+ headers: {+ Authorization: encryptedAuthorization,+ },+ },+ });+ expect(testServer.mock.calls[0][0].server).not.toHaveProperty("api_key");+ expect(close).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/api/mcp-service/mcp-service.api.ts b/src/api/mcp-service/mcp-service.api.tsindex 3e19ed578d..a5434bf314 100644--- a/src/api/mcp-service/mcp-service.api.ts+++ b/src/api/mcp-service/mcp-service.api.ts@@ -5,16 +5,12 @@ import type {} from "@openhands/typescript-client";import { getAgentServerClientOptions } from "../agent-server-client-options";import { getActiveBackend } from "../backend-registry/active-store";-import SettingsService from "#/api/settings-service/settings-service.api";import { getCredentialValidationForServer } from "#/utils/mcp-credential-validation";import type {ExtendedMCPTestResponse,MCPServerConfig,} from "#/types/mcp-server";--// Placeholder the settings API substitutes for secret env values when-// settings are fetched without X-Expose-Secrets (the MCP page's mode).-const REDACTED_ENV_VALUE = "<redacted>";+import { substituteRedactedMcpCredentials } from "./mcp-redacted-credentials";function toMcpServerSpec(server: MCPServerConfig): MCPServerSpec {if (server.type === "stdio") {@@ -29,45 +25,10 @@ function toMcpServerSpec(server: MCPServerConfig): MCPServerSpec {return {type: server.type,url: server.url!,+ ...(server.headers &&+ Object.keys(server.headers).length > 0 && { headers: server.headers }),...(server.api_key ? { api_key: server.api_key } : {}),- };-}--/**- * The MCP page reads settings with redacted secrets, so an env value the- * user left unchanged in the edit form is the literal `<redacted>`- * placeholder β testing with it would exercise garbage credentials. Swap- * each placeholder for the stored value in encrypted form (the agent- * server decrypts it before spawning), so "Test connection" exercises the- * real stored credentials. Falls back to the placeholder when encrypted- * settings are unavailable (e.g. no cipher configured) β the credential- * check then fails honestly instead of crashing the test flow.- */-async function substituteRedactedEnv(- server: MCPServerConfig,-): Promise<MCPServerConfig> {- if (server.type !== "stdio" || !server.name || !server.env) return server;- const values = Object.values(server.env);- if (!values.some((value) => value === REDACTED_ENV_VALUE)) return server;-- try {- const response = await SettingsService.fetchSettingsFromApi("encrypted");- const mcpConfig = response.agent_settings?.mcp_config as- | { mcpServers?: Record<string, { env?: Record<string, string> }> }- | undefined;- const storedEnv = mcpConfig?.mcpServers?.[server.name]?.env ?? {};- const env = Object.fromEntries(- Object.entries(server.env).map(([key, value]) => [- key,- value === REDACTED_ENV_VALUE && typeof storedEnv[key] === "string"- ? storedEnv[key]- : value,- ]),- );- return { ...server, env };- } catch {- return server;- }+ } as MCPServerSpec;}class McpService {@@ -88,7 +49,9 @@ class McpService {return { ok: true, tools: [] };}const validation = getCredentialValidationForServer(server);- const serverSpec = toMcpServerSpec(await substituteRedactedEnv(server));+ const serverSpec = toMcpServerSpec(+ await substituteRedactedMcpCredentials(server),+ );const { host, apiKey } = getAgentServerClientOptions();const client = new MCPClient({ host, ...(apiKey ? { apiKey } : {}) });try {diff --git a/src/hooks/mutation/use-update-mcp-server.ts b/src/hooks/mutation/use-update-mcp-server.tsindex d8ec2234bb..30ba780c0e 100644--- a/src/hooks/mutation/use-update-mcp-server.ts+++ b/src/hooks/mutation/use-update-mcp-server.ts@@ -7,21 +7,10 @@ import {MCPSSEServer,MCPStdioServer,} from "#/types/settings";+import { MCPServerConfig } from "#/types/mcp-server";import { parseMcpConfig, toSdkMcpConfig } from "#/utils/mcp-config";import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";--type MCPServerType = "sse" | "stdio" | "shttp";--interface MCPServerConfig {- type: MCPServerType;- name?: string;- url?: string;- api_key?: string;- timeout?: number;- command?: string;- args?: string[];- env?: Record<string, string>;-}+import { substituteRedactedMcpCredentials } from "#/api/mcp-service/mcp-redacted-credentials";export function useUpdateMcpServer() {const queryClient = useQueryClient();@@ -44,30 +33,35 @@ export function useUpdateMcpServer() {stdio_servers: [...currentConfig.stdio_servers],shttp_servers: [...currentConfig.shttp_servers],};+ const serverToSave = await substituteRedactedMcpCredentials(server);const [serverType, indexStr] = serverId.split("-");const index = parseInt(indexStr, 10);if (serverType === "sse") {const sseServer: MCPSSEServer = {- ...(server.name && { name: server.name }),- url: server.url!,- ...(server.api_key && { api_key: server.api_key }),+ ...(serverToSave.name && { name: serverToSave.name }),+ url: serverToSave.url!,+ ...(serverToSave.api_key && { api_key: serverToSave.api_key }),+ ...(serverToSave.headers && { headers: serverToSave.headers }),};newConfig.sse_servers[index] = sseServer;} else if (serverType === "stdio") {const stdioServer: MCPStdioServer = {- name: server.name!,- command: server.command!,- ...(server.args && { args: server.args }),- ...(server.env && { env: server.env }),+ name: serverToSave.name!,+ command: serverToSave.command!,+ ...(serverToSave.args && { args: serverToSave.args }),+ ...(serverToSave.env && { env: serverToSave.env }),};newConfig.stdio_servers[index] = stdioServer;} else if (serverType === "shttp") {const shttpServer: MCPSHTTPServer = {- ...(server.name && { name: server.name }),- url: server.url!,- ...(server.api_key && { api_key: server.api_key }),- ...(server.timeout !== undefined && { timeout: server.timeout }),+ ...(serverToSave.name && { name: serverToSave.name }),+ url: serverToSave.url!,+ ...(serverToSave.api_key && { api_key: serverToSave.api_key }),+ ...(serverToSave.headers && { headers: serverToSave.headers }),+ ...(serverToSave.timeout !== undefined && {+ timeout: serverToSave.timeout,+ }),};newConfig.shttp_servers[index] = shttpServer;}diff --git a/src/types/mcp-server.ts b/src/types/mcp-server.tsindex 8b58b71c3b..98f4a1ad7d 100644--- a/src/types/mcp-server.ts+++ b/src/types/mcp-server.ts@@ -13,6 +13,7 @@ export interface MCPServerConfig {name?: string;url?: string;api_key?: string;+ headers?: Record<string, string>;timeout?: number;command?: string;args?: string[];diff --git a/src/types/settings.ts b/src/types/settings.tsindex 31ee2f7afe..8f4cc7b804 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -18,6 +18,7 @@ export type MCPSSEServer = {name?: string;url: string;api_key?: string;+ headers?: Record<string, string>;};export type MCPStdioServer = {@@ -31,6 +32,7 @@ export type MCPSHTTPServer = {name?: string;url: string;api_key?: string;+ headers?: Record<string, string>;timeout?: number;};diff --git a/src/utils/mcp-config.ts b/src/utils/mcp-config.tsindex cc8f8d4d97..cb1bcab0d7 100644--- a/src/utils/mcp-config.ts+++ b/src/utils/mcp-config.ts@@ -12,6 +12,8 @@ const EMPTY_MCP_CONFIG: MCPConfig = {shttp_servers: [],};+export const REDACTED_MCP_SECRET_VALUE = "<redacted>";+const LINEAR_DEPRECATED_SSE_URL = "https://mcp.linear.app/sse";const LINEAR_SHTTP_URL = "https://mcp.linear.app/mcp";@@ -87,6 +89,19 @@ function getAuthorizationHeaders(apiKey: string | undefined) {};}+function getRemoteCredentialFields(entry: {+ api_key?: string;+ headers?: Record<string, string>;+}): Partial<SdkMcpServerConfig> {+ if (entry.api_key && entry.api_key !== REDACTED_MCP_SECRET_VALUE) {+ return getAuthorizationHeaders(entry.api_key);+ }+ if (entry.headers && Object.keys(entry.headers).length > 0) {+ return { headers: entry.headers };+ }+ return {};+}+/*** Parse an SDK mcp_config value ({ mcpServers: { ... } }) and convert it* to the frontend MCPConfig format used by UI components.@@ -206,7 +221,7 @@ export function toSdkMcpConfig(config: MCPConfig): SdkMcpConfig | null {} else {name = entry.name;server.url = entry.url;- Object.assign(server, getAuthorizationHeaders(entry.api_key));+ Object.assign(server, getRemoteCredentialFields(entry));}server.transport = "sse";mcpServers[reserve(name || "sse")] = server;@@ -220,7 +235,7 @@ export function toSdkMcpConfig(config: MCPConfig): SdkMcpConfig | null {} else {name = entry.name;server.url = entry.url;- Object.assign(server, getAuthorizationHeaders(entry.api_key));+ Object.assign(server, getRemoteCredentialFields(entry));if (entry.timeout != null) server.timeout = entry.timeout;}mcpServers[reserve(name || "shttp")] = server;diff --git a/src/utils/mcp-installed-servers.ts b/src/utils/mcp-installed-servers.tsindex d1465fcc56..93c29966f1 100644--- a/src/utils/mcp-installed-servers.ts+++ b/src/utils/mcp-installed-servers.ts@@ -9,6 +9,7 @@ export function flattenMcpConfig(config: MCPConfig): MCPServerConfig[] {name: typeof server === "object" ? server.name : undefined,url: typeof server === "string" ? server : server.url,api_key: typeof server === "object" ? server.api_key : undefined,+ headers: typeof server === "object" ? server.headers : undefined,})),...config.stdio_servers.map((server, index) => ({id: `stdio-${index}`,@@ -24,6 +25,7 @@ export function flattenMcpConfig(config: MCPConfig): MCPServerConfig[] {name: typeof server === "object" ? server.name : undefined,url: typeof server === "string" ? server : server.url,api_key: typeof server === "object" ? server.api_key : undefined,+ headers: typeof server === "object" ? server.headers : undefined,timeout: typeof server === "object" ? server.timeout : undefined,})),];