🙌 OpenHands: AI-Driven Development
feat: scope an agent profile to specific MCP servers (#17289)
simonrosenberg2c5ce2fa2dca
diff --git a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsxindex 4af8be9cdb..d62f489027 100644--- a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx+++ b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx@@ -134,6 +134,7 @@ describe("AgentProfilesLocalView save mapping", () => {isDirty: true,buildAgentProfileFields: () => ({agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: true,}),credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },@@ -148,6 +149,7 @@ describe("AgentProfilesLocalView save mapping", () => {name: "my-oh",profile: {agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: true,llm_profile_ref: "default",},@@ -161,6 +163,7 @@ describe("AgentProfilesLocalView save mapping", () => {isDirty: true,buildAgentProfileFields: () => ({agent_kind: "acp",+ mcp_server_refs: null,acp_server: "claude-code",acp_model: "claude-opus-4-8",acp_command: null,@@ -178,6 +181,7 @@ describe("AgentProfilesLocalView save mapping", () => {name: "my-claude",profile: {agent_kind: "acp",+ mcp_server_refs: null,acp_server: "claude-code",acp_model: "claude-opus-4-8",acp_command: null,@@ -215,8 +219,11 @@ describe("AgentProfilesLocalView save mapping", () => {agentType: "openhands",isValid: true,isDirty: true,+ // The editor models `mcp_server_refs`, so it re-emits what it was seeded+ // with; `disabled_skills` it does not, and survives via the merge.buildAgentProfileFields: () => ({agent_kind: "openhands",+ mcp_server_refs: ["github"],enable_sub_agents: true,}),credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },@@ -240,6 +247,9 @@ describe("AgentProfilesLocalView save mapping", () => {enable_sub_agents: false,enable_switch_llm_tool: false,tool_concurrency_limit: 4,+ // Without this the picker opens on "all servers" and the save widens the+ // profile's scope back to every configured server.+ mcp_server_refs: ["github"],});await user.click(screen.getByTestId("save-agent-profile-btn"));@@ -292,6 +302,7 @@ describe("AgentProfilesLocalView save mapping", () => {isDirty: true,buildAgentProfileFields: () => ({agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: false,enable_switch_llm_tool: true,}),@@ -329,6 +340,7 @@ describe("AgentProfilesLocalView save mapping", () => {isDirty: true,buildAgentProfileFields: () => ({agent_kind: "acp",+ mcp_server_refs: null,acp_server: "claude-code",acp_model: "claude-opus-4-8",acp_command: null,@@ -350,6 +362,7 @@ describe("AgentProfilesLocalView save mapping", () => {name: "default",profile: {agent_kind: "acp",+ mcp_server_refs: null,acp_server: "claude-code",acp_model: "claude-opus-4-8",acp_command: null,@@ -380,6 +393,7 @@ describe("AgentProfilesLocalView save mapping", () => {isDirty: false,buildAgentProfileFields: () => ({agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: false,}),credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },@@ -418,6 +432,7 @@ describe("AgentProfilesLocalView save mapping", () => {isDirty: false,buildAgentProfileFields: () => ({agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: false,}),credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },@@ -438,6 +453,7 @@ describe("AgentProfilesLocalView save mapping", () => {isDirty: true,buildAgentProfileFields: () => ({agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: false,}),credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },diff --git a/__tests__/constants/profile-scope.test.ts b/__tests__/constants/profile-scope.test.tsnew file mode 100644index 0000000000..3741990c12--- /dev/null+++ b/__tests__/constants/profile-scope.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from "vitest";+import {+ readProfileMcpRefs,+ sameScopeSelection,+} from "#/constants/profile-scope";++describe("readProfileMcpRefs", () => {+ it("reads an absent field as the server default", () => {+ expect(readProfileMcpRefs(undefined)).toEqual({+ mode: "standard",+ selected: [],+ });+ expect(readProfileMcpRefs(null)).toEqual({+ mode: "standard",+ selected: [],+ });+ });++ it("reads an empty array as an explicit no-servers scope", () => {+ expect(readProfileMcpRefs([])).toEqual({ mode: "custom", selected: [] });+ });++ it("reads a list as the selection", () => {+ expect(readProfileMcpRefs(["github", "postgres"])).toEqual({+ mode: "custom",+ selected: ["github", "postgres"],+ });+ });++ it("drops non-string entries rather than failing the editor", () => {+ expect(readProfileMcpRefs(["github", 7, null])).toEqual({+ mode: "custom",+ selected: ["github"],+ });+ });+});++describe("sameScopeSelection", () => {+ it("ignores order, which the resolver does not use", () => {+ expect(+ sameScopeSelection(["github", "postgres"], ["postgres", "github"]),+ ).toBe(true);+ });++ it("ignores a repeated name, which the resolver collapses", () => {+ expect(sameScopeSelection(["github"], ["github", "github"])).toBe(true);+ });++ it("still sees an added or removed server", () => {+ expect(sameScopeSelection(["github"], ["github", "postgres"])).toBe(false);+ expect(sameScopeSelection(["github"], ["postgres"])).toBe(false);+ });++ it("treats an empty selection as equal only to another empty one", () => {+ expect(sameScopeSelection([], [])).toBe(true);+ expect(sameScopeSelection([], ["github"])).toBe(false);+ });+});diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsxindex 943029fd8d..9fbc0c959c 100644--- a/__tests__/routes/agent-settings.test.tsx+++ b/__tests__/routes/agent-settings.test.tsx@@ -3,7 +3,10 @@ import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { MemoryRouter } from "react-router";import { beforeEach, describe, expect, it, vi } from "vitest";-import { AgentSettingsScreen } from "#/routes/agent-settings";+import {+ AgentSettingsScreen,+ type AgentSettingsSaveControl,+} from "#/routes/agent-settings";import SettingsService from "#/api/settings-service/settings-service.api";import { SecretsService } from "#/api/secrets-service";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";@@ -1060,3 +1063,232 @@ describe("AgentSettingsScreen", () => {).toBeInTheDocument();});});++describe("AgentSettingsScreen — MCP server scope", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ });++ function seedWithMcp(mcpConfig: Record<string, unknown>) {+ // `useSettings` prefers `agent_settings.mcp_config` over the top-level+ // field, so seed it where the hook actually reads.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ agent_settings: {+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,+ agent_kind: "openhands",+ mcp_config: mcpConfig,+ },+ } as never),+ );+ }++ const TWO_SERVERS = {+ github: { url: "https://mcp.example/github", transport: "shttp" },+ postgres: { url: "https://mcp.example/pg", transport: "shttp" },+ };++ it("lists configured servers read-only and persists null by default", async () => {+ seedWithMcp(TWO_SERVERS);+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ mcp_server_refs: null,+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ const github = screen.getByTestId("agent-settings-mcp-github");+ expect(github).toBeChecked();+ expect(github).toBeDisabled();+ expect(control!.buildAgentProfileFields()).toMatchObject({+ mcp_server_refs: null,+ });+ });++ it("seeds from a stored scope and persists the selection", async () => {+ seedWithMcp(TWO_SERVERS);+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ mcp_server_refs: ["github"],+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ expect(screen.getByTestId("agent-settings-mcp-github")).toBeChecked();+ expect(screen.getByTestId("agent-settings-mcp-postgres")).not.toBeChecked();+ expect(control!.buildAgentProfileFields()).toMatchObject({+ mcp_server_refs: ["github"],+ });+ });++ it("seeds a switch to custom with every configured server", async () => {+ // Turning the control on should narrow from the default rather than cut+ // the agent off from every server at once.+ seedWithMcp(TWO_SERVERS);+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ mcp_server_refs: null,+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ const user = userEvent.setup();+ const combo = screen.getByTestId("agent-settings-mcp-mode");+ combo.focus();+ await user.keyboard("{ArrowDown}");+ await user.click(+ await screen.findByRole("option", {+ name: "SETTINGS$AGENT_PROFILE_MCP_CHOOSE",+ }),+ );++ await waitFor(() => {+ expect(control!.buildAgentProfileFields()).toMatchObject({+ mcp_server_refs: ["github", "postgres"],+ });+ });+ expect(screen.getByTestId("agent-settings-mcp-github")).toBeChecked();+ expect(screen.getByTestId("agent-settings-mcp-postgres")).toBeChecked();+ });++ it("warns about a ref whose server is gone, which would fail the launch", async () => {+ seedWithMcp(TWO_SERVERS);+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ mcp_server_refs: ["github", "deleted-server"],+ },+ });+ await screen.findByTestId("agent-settings-screen");++ expect(+ screen.getByTestId("agent-settings-mcp-deleted-server"),+ ).toBeChecked();+ expect(+ screen.getByTestId("agent-settings-mcp-dangling"),+ ).toBeInTheDocument();+ });++ it("scopes an ACP profile too, since the field lives on the profile base", async () => {+ seedWithMcp(TWO_SERVERS);+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "acp",+ acp_server: "claude-code",+ mcp_server_refs: ["github"],+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");++ expect(screen.getByTestId("agent-settings-mcp-github")).toBeChecked();+ expect(control!.buildAgentProfileFields()).toMatchObject({+ agent_kind: "acp",+ mcp_server_refs: ["github"],+ });+ });++ it("explains the empty state when no server is configured", async () => {+ seedWithMcp({});+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ },+ });+ await screen.findByTestId("agent-settings-screen");+ expect(+ screen.queryByTestId("agent-settings-mcp-list"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByText("SETTINGS$AGENT_PROFILE_MCP_NONE"),+ ).toBeInTheDocument();+ });++ it("is hidden outside the profile editor", async () => {+ // The global page saves `agent_settings`, which carries the resolved+ // `mcp_config`, not refs.+ seedWithMcp(TWO_SERVERS);+ renderAgentSettingsScreen({});+ await screen.findByTestId("agent-settings-screen");+ expect(+ screen.queryByTestId("agent-settings-mcp-mode"),+ ).not.toBeInTheDocument();+ });+});++describe("AgentSettingsScreen — MCP scope dirty tracking", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ agent_settings: {+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,+ agent_kind: "openhands",+ mcp_config: {+ github: { url: "https://mcp.example/github", transport: "shttp" },+ postgres: { url: "https://mcp.example/pg", transport: "shttp" },+ },+ },+ } as never),+ );+ });++ async function dirtyForStoredRefs(refs: string[]) {+ let control: AgentSettingsSaveControl | null = null;+ renderAgentSettingsScreen({+ embedded: true,+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ mcp_server_refs: refs,+ },+ onSaveControlChange: (next) => {+ control = next;+ },+ });+ await screen.findByTestId("agent-settings-screen");+ await screen.findByTestId("agent-settings-mcp-list");+ return () => control!.isDirty;+ }++ it("is clean on load when the stored order matches the config order", async () => {+ const isDirty = await dirtyForStoredRefs(["github", "postgres"]);+ await waitFor(() => expect(isDirty()).toBe(false));+ });++ it("is clean on load when the stored order differs from the config order", async () => {+ const isDirty = await dirtyForStoredRefs(["postgres", "github"]);+ await waitFor(() => expect(isDirty()).toBe(false));+ });+});diff --git a/__tests__/routes/build-agent-profile-fields.test.ts b/__tests__/routes/build-agent-profile-fields.test.tsindex fcfba98b6b..e35a3f63be 100644--- a/__tests__/routes/build-agent-profile-fields.test.ts+++ b/__tests__/routes/build-agent-profile-fields.test.ts@@ -14,6 +14,8 @@ const baseAcp = {switchLlmToolSupportedOnProfile: true,toolConcurrencyField: undefined,toolConcurrency: "",+ mcpMode: "standard" as const,+ selectedMcpServers: [],};const switchLlmToolField: SettingsFieldSchema = {@@ -48,6 +50,7 @@ describe("buildAgentProfileFields — ACP", () => {const fields = buildAgentProfileFields(baseAcp);expect(fields).toEqual({agent_kind: "acp",+ mcp_server_refs: null,acp_server: "claude-code",acp_model: "claude-opus-4-8",acp_command: null,@@ -104,11 +107,14 @@ describe("buildAgentProfileFields — OpenHands", () => {switchLlmToolSupportedOnProfile: true,toolConcurrencyField: undefined,toolConcurrency: "",+ mcpMode: "standard" as const,+ selectedMcpServers: [],};it("passes through enable_sub_agents and omits concurrency when the field is absent", () => {expect(buildAgentProfileFields(baseOh)).toEqual({agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: true,});});@@ -197,3 +203,56 @@ describe("buildAgentProfileFields — OpenHands", () => {).toThrow();});});++describe("buildAgentProfileFields — mcp_server_refs", () => {+ const baseOh = {+ isAcp: false,+ selectedPreset: "custom",+ isDefaultProviderCommand: false,+ commandTokens: [],+ acpModel: "",+ subAgentsEnabled: false,+ switchLlmToolField: undefined,+ switchLlmToolEnabled: false,+ switchLlmToolSupportedOnProfile: true,+ toolConcurrencyField: undefined,+ toolConcurrency: "",+ mcpMode: "standard" as const,+ selectedMcpServers: [],+ };++ it("emits null in standard mode, so the profile inherits every server", () => {+ expect(buildAgentProfileFields(baseOh).mcp_server_refs).toBeNull();+ expect(+ buildAgentProfileFields({ ...baseOh, isAcp: true }).mcp_server_refs,+ ).toBeNull();+ });++ it("emits the selection in custom mode", () => {+ const selected = ["fetch", "playwright"];+ expect(+ buildAgentProfileFields({+ ...baseOh,+ mcpMode: "custom",+ selectedMcpServers: selected,+ }).mcp_server_refs,+ ).toEqual(selected);+ });++ it("distinguishes an empty selection from standard — [] means no servers", () => {+ expect(+ buildAgentProfileFields({ ...baseOh, mcpMode: "custom" }).mcp_server_refs,+ ).toEqual([]);+ });++ it("rides both variants, since the field lives on the profile base", () => {+ const acp = buildAgentProfileFields({+ ...baseOh,+ isAcp: true,+ mcpMode: "custom",+ selectedMcpServers: ["fetch"],+ });+ expect(acp.agent_kind).toBe("acp");+ expect(acp.mcp_server_refs).toEqual(["fetch"]);+ });+});diff --git a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsxindex 519d8ca4f7..c0f305acf6 100644--- a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx+++ b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx@@ -44,6 +44,7 @@ function toAgentSettingsOverride(if (profile.agent_kind === "acp") {return {agent_kind: "acp",+ mcp_server_refs: profile.mcp_server_refs ?? null,acp_server: profile.acp_server,acp_command: profile.acp_command ? parseCommand(profile.acp_command) : [],acp_args: profile.acp_args ?? [],@@ -59,6 +60,7 @@ function toAgentSettingsOverride(true;return {agent_kind: "openhands",+ mcp_server_refs: profile.mcp_server_refs ?? null,enable_sub_agents: profile.enable_sub_agents,enable_switch_llm_tool: switchLlmToolEnabled,tool_concurrency_limit: profile.tool_concurrency_limit,diff --git a/src/components/features/settings/agent-profiles/profile-scope-list.tsx b/src/components/features/settings/agent-profiles/profile-scope-list.tsxnew file mode 100644index 0000000000..b1a6605d8a--- /dev/null+++ b/src/components/features/settings/agent-profiles/profile-scope-list.tsx@@ -0,0 +1,53 @@+import { SettingsSwitch } from "#/components/features/settings/settings-switch";+import { Typography } from "#/ui/typography";++export interface ProfileScopeItem {+ name: string;+ description?: string | null;+}++interface ProfileScopeListProps {+ /** Prefix: the list is `<testId>-list`, each row `<testId>-<name>`. */+ testId: string;+ items: ProfileScopeItem[];+ selected: string[];+ isDisabled?: boolean;+ onToggle: (name: string, checked: boolean) => void;+}++/**+ * Per-item toggles for a profile scope field such as `mcp_server_refs`.+ *+ * Rows are keyed by the wire name — the same identifier the API takes — so an+ * entry this build has no description for is still legible and selectable.+ */+export function ProfileScopeList({+ testId,+ items,+ selected,+ isDisabled = false,+ onToggle,+}: ProfileScopeListProps) {+ return (+ <ul data-testid={`${testId}-list`} className="flex flex-col gap-2.5">+ {items.map(({ name, description }) => (+ <li key={name} className="flex flex-col gap-0.5">+ <SettingsSwitch+ testId={`${testId}-${name}`}+ name={`${testId}-${name}`}+ isToggled={selected.includes(name)}+ isDisabled={isDisabled}+ onToggle={(checked) => onToggle(name, checked)}+ >+ <span className="font-mono">{name}</span>+ </SettingsSwitch>+ {description ? (+ <Typography.Text className="text-xs text-tertiary-alt pl-11">+ {description}+ </Typography.Text>+ ) : null}+ </li>+ ))}+ </ul>+ );+}diff --git a/src/constants/profile-scope.ts b/src/constants/profile-scope.tsnew file mode 100644index 0000000000..d9a5aaeb47--- /dev/null+++ b/src/constants/profile-scope.ts@@ -0,0 +1,33 @@+/** Picker state for a profile's scope fields: server default, or an explicit list. */+export type ProfileScopeMode = "standard" | "custom";++/**+ * Read a stored profile's `mcp_server_refs` into picker state.+ *+ * Tri-state on the wire: `null`/absent = every configured server, an array =+ * only those keys (`[]` = none).+ */+export function readProfileMcpRefs(value: unknown): {+ mode: ProfileScopeMode;+ selected: string[];+} {+ if (!Array.isArray(value)) return { mode: "standard", selected: [] };+ return {+ mode: "custom",+ selected: value.filter((name): name is string => typeof name === "string"),+ };+}++/**+ * Whether two scope selections name the same servers.+ *+ * Compared as a set: the resolver de-duplicates refs and uses them as an+ * allow-list, so neither order nor a repeat changes what the agent gets. The+ * editor emits catalog order while a stored profile keeps whatever order it was+ * written in, so an order-sensitive check reports a profile dirty on open.+ */+export function sameScopeSelection(a: string[], b: string[]): boolean {+ const normalize = (names: string[]) =>+ [...new Set(names)].sort().join("\u0000");+ return normalize(a) === normalize(b);+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex a405d73355..6b479e4e7d 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -5473,6 +5473,125 @@"uk": "ACP (зовнішній підпроцес)","ca": "ACP (subprocés extern)"},+ "SETTINGS$AGENT_PROFILE_MCP": {+ "en": "MCP servers",+ "ja": "MCPサーバー",+ "zh-CN": "MCP 服务器",+ "zh-TW": "MCP 伺服器",+ "ko-KR": "MCP 서버",+ "no": "MCP-servere",+ "it": "Server MCP",+ "pt": "Servidores MCP",+ "es": "Servidores MCP",+ "ar": "خوادم MCP",+ "fr": "Serveurs MCP",+ "tr": "MCP sunucuları",+ "de": "MCP-Server",+ "uk": "Сервери MCP",+ "ca": "Servidors MCP"+ },+ "SETTINGS$AGENT_PROFILE_MCP_ALL": {+ "en": "All servers",+ "ja": "すべてのサーバー",+ "zh-CN": "全部服务器",+ "zh-TW": "全部伺服器",+ "ko-KR": "모든 서버",+ "no": "Alle servere",+ "it": "Tutti i server",+ "pt": "Todos os servidores",+ "es": "Todos los servidores",+ "ar": "كل الخوادم",+ "fr": "Tous les serveurs",+ "tr": "Tüm sunucular",+ "de": "Alle Server",+ "uk": "Усі сервери",+ "ca": "Tots els servidors"+ },+ "SETTINGS$AGENT_PROFILE_MCP_CHOOSE": {+ "en": "Choose servers",+ "ja": "サーバーを選択",+ "zh-CN": "自选服务器",+ "zh-TW": "自選伺服器",+ "ko-KR": "서버 선택",+ "no": "Velg servere",+ "it": "Scegli i server",+ "pt": "Escolher servidores",+ "es": "Elegir servidores",+ "ar": "اختيار الخوادم",+ "fr": "Choisir les serveurs",+ "tr": "Sunucuları seçin",+ "de": "Server auswählen",+ "uk": "Вибрати сервери",+ "ca": "Tria els servidors"+ },+ "SETTINGS$AGENT_PROFILE_MCP_ALL_HINT": {+ "en": "This agent can use every MCP server you have configured, including any that can make changes.",+ "ja": "このエージェントは、設定済みのすべてのMCPサーバーを使用できます。変更を加えられるサーバーも含まれます。",+ "zh-CN": "该代理可以使用你配置的所有 MCP 服务器,其中也包括能够进行修改的服务器。",+ "zh-TW": "該代理可以使用你設定的所有 MCP 伺服器,其中也包括能夠進行修改的伺服器。",+ "ko-KR": "이 에이전트는 구성된 모든 MCP 서버를 사용할 수 있으며, 여기에는 변경을 수행할 수 있는 서버도 포함됩니다.",+ "no": "Denne agenten kan bruke alle MCP-serverne du har satt opp, inkludert dem som kan gjøre endringer.",+ "it": "Questo agente può usare tutti i server MCP che hai configurato, compresi quelli in grado di apportare modifiche.",+ "pt": "Este agente pode usar todos os servidores MCP que você configurou, incluindo os que podem fazer alterações.",+ "es": "Este agente puede usar todos los servidores MCP que has configurado, incluidos los que pueden hacer cambios.",+ "ar": "يمكن لهذا الوكيل استخدام جميع خوادم MCP التي أعددتها، بما فيها تلك القادرة على إجراء تغييرات.",+ "fr": "Cet agent peut utiliser tous les serveurs MCP que vous avez configurés, y compris ceux capables d'apporter des modifications.",+ "tr": "Bu aracı, yapılandırdığınız tüm MCP sunucularını kullanabilir; bunlara değişiklik yapabilenler de dahildir.",+ "de": "Dieser Agent kann alle von Ihnen konfigurierten MCP-Server verwenden, auch solche, die Änderungen vornehmen können.",+ "uk": "Цей агент може використовувати всі налаштовані вами сервери MCP, зокрема ті, що здатні вносити зміни.",+ "ca": "Aquest agent pot fer servir tots els servidors MCP que has configurat, inclosos els que poden fer canvis."+ },+ "SETTINGS$AGENT_PROFILE_MCP_CHOOSE_HINT": {+ "en": "This agent can use only the servers you select. Every other MCP server stays hidden from it.",+ "ja": "このエージェントは選択したサーバーのみを使用できます。ほかのMCPサーバーは表示されません。",+ "zh-CN": "该代理只能使用你选择的服务器。其他 MCP 服务器对它不可见。",+ "zh-TW": "該代理只能使用你選擇的伺服器。其他 MCP 伺服器對它不可見。",+ "ko-KR": "이 에이전트는 선택한 서버만 사용할 수 있습니다. 다른 MCP 서버는 표시되지 않습니다.",+ "no": "Denne agenten kan bare bruke serverne du velger. Alle andre MCP-servere forblir skjult for den.",+ "it": "Questo agente può usare solo i server che selezioni. Tutti gli altri server MCP restano nascosti.",+ "pt": "Este agente pode usar apenas os servidores que você selecionar. Todos os outros servidores MCP permanecem ocultos para ele.",+ "es": "Este agente solo puede usar los servidores que selecciones. Los demás servidores MCP permanecen ocultos para él.",+ "ar": "لا يمكن لهذا الوكيل استخدام سوى الخوادم التي تحددها. وتظل خوادم MCP الأخرى محجوبة عنه.",+ "fr": "Cet agent ne peut utiliser que les serveurs que vous sélectionnez. Tous les autres serveurs MCP lui restent masqués.",+ "tr": "Bu aracı yalnızca seçtiğiniz sunucuları kullanabilir. Diğer tüm MCP sunucuları ona gizli kalır.",+ "de": "Dieser Agent kann nur die von Ihnen ausgewählten Server verwenden. Alle anderen MCP-Server bleiben für ihn verborgen.",+ "uk": "Цей агент може використовувати лише вибрані вами сервери. Усі інші сервери MCP залишаються прихованими від нього.",+ "ca": "Aquest agent només pot fer servir els servidors que seleccionis. La resta de servidors MCP li queden ocults."+ },+ "SETTINGS$AGENT_PROFILE_MCP_NONE": {+ "en": "You have not configured any MCP servers yet.",+ "ja": "MCPサーバーはまだ設定されていません。",+ "zh-CN": "你还没有配置任何 MCP 服务器。",+ "zh-TW": "你還沒有設定任何 MCP 伺服器。",+ "ko-KR": "아직 구성된 MCP 서버가 없습니다.",+ "no": "Du har ikke satt opp noen MCP-servere ennå.",+ "it": "Non hai ancora configurato alcun server MCP.",+ "pt": "Você ainda não configurou nenhum servidor MCP.",+ "es": "Aún no has configurado ningún servidor MCP.",+ "ar": "لم تُعِدّ أي خوادم MCP بعد.",+ "fr": "Vous n'avez encore configuré aucun serveur MCP.",+ "tr": "Henüz MCP sunucusu yapılandırmadınız.",+ "de": "Sie haben noch keine MCP-Server konfiguriert.",+ "uk": "Ви ще не налаштували жодного сервера MCP.",+ "ca": "Encara no has configurat cap servidor MCP."+ },+ "SETTINGS$AGENT_PROFILE_MCP_DANGLING": {+ "en": "{{names}} is no longer configured. Saving with it selected will stop this agent from starting — clear it or re-add the server.",+ "ja": "{{names}} は現在設定されていません。選択したまま保存すると、このエージェントは起動できなくなります。選択を解除するか、サーバーを再追加してください。",+ "zh-CN": "{{names}} 已不再配置。保持选中并保存会导致该代理无法启动——请取消选择或重新添加该服务器。",+ "zh-TW": "{{names}} 已不再設定。保持選取並儲存會導致該代理無法啟動——請取消選取或重新新增該伺服器。",+ "ko-KR": "{{names}}이(가) 더 이상 구성되어 있지 않습니다. 선택한 채로 저장하면 이 에이전트가 시작되지 않습니다. 선택을 해제하거나 서버를 다시 추가하세요.",+ "no": "{{names}} er ikke lenger satt opp. Lagrer du med den valgt, vil ikke denne agenten starte – fjern valget eller legg til serveren på nytt.",+ "it": "{{names}} non è più configurato. Salvando con questa selezione l'agente non si avvierà: deselezionalo o aggiungi di nuovo il server.",+ "pt": "{{names}} não está mais configurado. Salvar com ele selecionado impedirá que este agente inicie — desmarque-o ou adicione o servidor novamente.",+ "es": "{{names}} ya no está configurado. Guardar con esta selección impedirá que este agente se inicie: desmárcalo o vuelve a añadir el servidor.",+ "ar": "لم يعد {{names}} مُعدًّا. سيؤدي الحفظ مع تحديده إلى منع هذا الوكيل من العمل — ألغِ تحديده أو أضِف الخادم من جديد.",+ "fr": "{{names}} n'est plus configuré. Enregistrer en le laissant sélectionné empêchera cet agent de démarrer : désélectionnez-le ou rajoutez le serveur.",+ "tr": "{{names}} artık yapılandırılmış değil. Seçili bırakarak kaydederseniz bu aracı başlatılamaz — seçimi kaldırın veya sunucuyu yeniden ekleyin.",+ "de": "{{names}} ist nicht mehr konfiguriert. Ein Speichern mit dieser Auswahl verhindert den Start dieses Agenten – heben Sie die Auswahl auf oder fügen Sie den Server erneut hinzu.",+ "uk": "{{names}} більше не налаштовано. Якщо зберегти з цим вибором, агент не запуститься — зніміть позначку або додайте сервер знову.",+ "ca": "{{names}} ja no està configurat. Desar amb aquesta selecció impedirà que aquest agent s'iniciï: desmarca'l o torna a afegir el servidor."+ },"SETTINGS$AGENT_PRESET": {"en": "Preset","ja": "プリセット",diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsxindex dcd502ae39..e13ff841da 100644--- a/src/routes/agent-settings.tsx+++ b/src/routes/agent-settings.tsx@@ -12,6 +12,7 @@ import { SchemaField } from "#/components/features/settings/sdk-settings/schema-import { AcpCredentialsSection } from "#/components/features/settings/acp-credentials-section";import { useAcpCredentialForm } from "#/hooks/use-acp-credential-form";import { BrandButton } from "#/components/features/settings/brand-button";+import { ProfileScopeList } from "#/components/features/settings/agent-profiles/profile-scope-list";import { Typography } from "#/ui/typography";import { I18nKey } from "#/i18n/declaration";import { formControlSwitchDescriptionClassName } from "#/utils/form-control-classes";@@ -39,6 +40,13 @@ import {type ACPProviderConfig,} from "#/constants/acp-providers";import { parseCommand, formatCommand } from "#/utils/acp-command";+import {+ readProfileMcpRefs,+ sameScopeSelection,+ type ProfileScopeMode,+} from "#/constants/profile-scope";+import { flattenMcpConfig } from "#/utils/mcp-installed-servers";+import { parseMcpConfig } from "#/utils/mcp-config";import { agentProfileSupportsSwitchLlmTool } from "#/api/agent-profiles-service/profile-field-support";export const handle = { hideTitle: true };@@ -55,6 +63,7 @@ type AgentSettingsSnapshot = {const ENABLE_SUB_AGENTS_FIELD_KEY = "enable_sub_agents";const ENABLE_SWITCH_LLM_TOOL_FIELD_KEY = "enable_switch_llm_tool";const TOOL_CONCURRENCY_FIELD_KEY = "tool_concurrency_limit";+const MCP_SERVER_REFS_KEY = "mcp_server_refs";const COMMAND_PLACEHOLDER_FALLBACK = "npx -y <package-name>";const ACP_CUSTOM_MODEL_KEY = "__custom_model__";const EMPTY_AGENT_SETTINGS_SNAPSHOT: AgentSettingsSnapshot = {@@ -121,12 +130,14 @@ function isKnownAcpModel(export type AgentProfileFieldsDraft =| {agent_kind: "openhands";+ mcp_server_refs: string[] | null;enable_sub_agents: boolean;enable_switch_llm_tool?: boolean;tool_concurrency_limit?: number;}| {agent_kind: "acp";+ mcp_server_refs: string[] | null;acp_server: string;acp_model: string | null;acp_command: string | null;@@ -154,6 +165,8 @@ export interface AgentProfileFieldsInput {switchLlmToolSupportedOnProfile: boolean;toolConcurrencyField?: SettingsFieldSchema;toolConcurrency: string | boolean;+ mcpMode: ProfileScopeMode;+ selectedMcpServers: string[];}/**@@ -189,12 +202,20 @@ export function buildAgentProfileFields(switchLlmToolSupportedOnProfile,toolConcurrencyField,toolConcurrency,+ mcpMode,+ selectedMcpServers,} = input;+ // A base-model field, so it rides both variants. No version gate: it has+ // existed since agent profiles shipped, below the supported floor.+ const mcpRefs = {+ mcp_server_refs: mcpMode === "custom" ? selectedMcpServers : null,+ };if (isAcp) {const isBuiltinDefault =isDefaultProviderCommand && selectedPreset !== ACP_CUSTOM_PRESET_KEY;return {agent_kind: "acp",+ ...mcpRefs,acp_server: selectedPreset,acp_model: acpModel.trim() || null,acp_command: isBuiltinDefault@@ -206,6 +227,7 @@ export function buildAgentProfileFields(const fields: Extract<AgentProfileFieldsDraft, { agent_kind: "openhands" }> ={agent_kind: "openhands",+ ...mcpRefs,enable_sub_agents: subAgentsEnabled,};if (switchLlmToolField && switchLlmToolSupportedOnProfile) {@@ -348,6 +370,65 @@ export function AgentSettingsScreen({initialToolConcurrency,);+ // --- MCP servers (both variants; a base-model field) ---+ // Only the profile editor shows this: the global agent-settings page saves+ // ``agent_settings``, which has no refs — it carries the resolved+ // ``mcp_config`` itself.+ const showProfileScopeFields = embedded;+ const initialMcpRefs = React.useMemo(+ () => readProfileMcpRefs(agentSettingsSource?.[MCP_SERVER_REFS_KEY]),+ [agentSettingsSource],+ );+ const [mcpMode, setMcpMode] = useState<ProfileScopeMode>(initialMcpRefs.mode);+ const [selectedMcpServers, setSelectedMcpServers] = useState<string[]>(+ initialMcpRefs.selected,+ );+ const configuredMcpNames = React.useMemo(+ () =>+ flattenMcpConfig(+ settings?.mcp_config ??+ parseMcpConfig(settings?.agent_settings?.mcp_config),+ )+ // `name` is optional on the shared type; flattenMcpConfig always sets+ // it from the config key, so narrow rather than assert.+ .filter(+ (server): server is typeof server & { name: string } =>+ typeof server.name === "string",+ )+ .map((server) => ({ name: server.name, description: server.type })),+ [settings],+ );+ const mcpCatalog = React.useMemo(() => {+ const configured = configuredMcpNames;+ // A stored ref whose server is gone rides along so the user can clear it:+ // a dangling ref fails the launch (422 locally; on cloud the never-brick+ // handler swallows it and silently falls back to unscoped settings).+ const known = new Set(configured.map(({ name }) => name));+ return [+ ...configured,+ ...initialMcpRefs.selected+ .filter((name) => !known.has(name))+ .map((name) => ({ name, description: null as string | null })),+ ];+ }, [configuredMcpNames, initialMcpRefs]);+ const orderedSelectedMcpServers = React.useMemo(+ () =>+ mcpCatalog+ .map(({ name }) => name)+ .filter((name) => selectedMcpServers.includes(name)),+ [mcpCatalog, selectedMcpServers],+ );+ const danglingMcpRefs = React.useMemo(+ () =>+ mcpMode === "custom"+ ? orderedSelectedMcpServers.filter(+ (name) =>+ !configuredMcpNames.some((server) => server.name === name),+ )+ : [],+ [mcpMode, orderedSelectedMcpServers, configuredMcpNames],+ );+// --- ACP path ---const [agentType, setAgentType] = useState<AgentType>("openhands");const [commandText, setCommandText] = useState("");@@ -448,12 +529,19 @@ export function AgentSettingsScreen({setToolConcurrency(initialToolConcurrency);}, [initialToolConcurrency]);+ // Sync the MCP scope when settings reload+ useEffect(() => {+ setMcpMode(initialMcpRefs.mode);+ setSelectedMcpServers(initialMcpRefs.selected);+ }, [initialMcpRefs]);+// --- Embedded (Agent-profile editor) save control ---// Ref-backed so the exposed builder/credential fns read the freshest state at// call time without re-emitting the control on every keystroke (mirrors// ``sdk-section-page``). The body is (re)assigned during render below.const buildFieldsRef = useRef<() => AgentProfileFieldsDraft>(() => ({agent_kind: "openhands",+ mcp_server_refs: null,enable_sub_agents: false,}));const stableBuildFields = useCallback(() => buildFieldsRef.current(), []);@@ -469,8 +557,14 @@ export function AgentSettingsScreen({// the emit effect can depend on them; the full ACP derivation lives after it.const acpCommandEmpty =agentType === "acp" && parseCommand(commandText).length === 0;+ // `mcp_server_refs` lives on the profile base, so it is dirty-tracked for both+ // variants rather than inside the kind-specific branch below.+ const mcpScopeDirty =+ mcpMode !== initialMcpRefs.mode ||+ !sameScopeSelection(orderedSelectedMcpServers, initialMcpRefs.selected);const settingsDirty =agentType !== loadedSnapshot.agentType ||+ mcpScopeDirty ||(agentType === "acp"? commandText !== loadedSnapshot.commandText ||acpModel !== loadedSnapshot.acpModel ||@@ -543,6 +637,8 @@ export function AgentSettingsScreen({switchLlmToolSupportedOnProfile,toolConcurrencyField,toolConcurrency,+ mcpMode,+ selectedMcpServers: orderedSelectedMcpServers,});const isSavingAny = isSaving || acpCredentialForm.isSaving;@@ -795,6 +891,84 @@ export function AgentSettingsScreen({/>) : null}+ {showProfileScopeFields ? (+ <div className="flex flex-col gap-2.5">+ <Typography.Text className="text-sm">+ {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP)}+ </Typography.Text>+ <SettingsDropdownInput+ testId="agent-settings-mcp-mode"+ name="agent-mcp-mode"+ label=""+ items={[+ {+ key: "standard",+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL),+ },+ {+ key: "custom",+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE),+ },+ ]}+ selectedKey={mcpMode}+ isDisabled={isSavingAny}+ onSelectionChange={(key) => {+ if (!key) return;+ const mode = key as ProfileScopeMode;+ setMcpMode(mode);+ // Seed a first switch to custom from the default — every+ // configured server — so turning the control on narrows from what+ // the agent had rather than cutting it off from all of them.+ if (mode === "custom" && selectedMcpServers.length === 0) {+ setSelectedMcpServers(+ configuredMcpNames.map(({ name }) => name),+ );+ }+ }}+ />+ {mcpCatalog.length > 0 ? (+ <ProfileScopeList+ testId="agent-settings-mcp"+ items={mcpCatalog}+ selected={+ mcpMode === "custom"+ ? orderedSelectedMcpServers+ : mcpCatalog.map(({ name }) => name)+ }+ isDisabled={isSavingAny || mcpMode === "standard"}+ onToggle={(name, checked) =>+ setSelectedMcpServers((prev) =>+ checked+ ? [...prev, name]+ : prev.filter((entry) => entry !== name),+ )+ }+ />+ ) : (+ <Typography.Text className="text-xs text-tertiary-alt">+ {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_NONE)}+ </Typography.Text>+ )}+ {danglingMcpRefs.length > 0 ? (+ <Typography.Text+ testId="agent-settings-mcp-dangling"+ className="text-xs text-danger"+ >+ {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_DANGLING, {+ names: danglingMcpRefs.join(", "),+ })}+ </Typography.Text>+ ) : null}+ <Typography.Text className="text-xs text-tertiary-alt">+ {t(+ mcpMode === "custom"+ ? I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE_HINT+ : I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL_HINT,+ )}+ </Typography.Text>+ </div>+ ) : null}+{isAcp && (<><SettingsDropdownInput