Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(mcp): make MCP writes a separate opt-in and validate renderer input
Davidjayan36dec5b8c529
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 4829225cb..1d9f5ef9d 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -4865,17 +4865,16 @@ export function registerIpcHandlers(// (Claude Code, Codex…). Built here because this is where the agent's own// dependencies live, but NOT started here: the headless CLI shares this// function and must never bind the port a running app is listening on.- // `main.ts` starts it. Its tools obey the same "Project edits" switch as the- // in-app agent, read on every call.- const mcpController = new McpController(- new McpSettingsStore(app.getPath("userData"), safeStorage),- {- host: new EditorDocumentHost(ipcMain),- editsAllowed: () => getAiEditionLlmConfig().getConfig()?.allowAgentEdits !== false,- cursor: agentCursorTelemetryReader,- version: app.getVersion(),- },- );+ // `main.ts` starts it. Its writes have their own switch, off by default and+ // read on every call — separate from the in-app agent's "Project edits", so+ // turning the server on grants a client read access and nothing more.+ const mcpSettings = new McpSettingsStore(app.getPath("userData"), safeStorage);+ const mcpController = new McpController(mcpSettings, {+ host: new EditorDocumentHost(ipcMain),+ editsAllowed: () => mcpSettings.getSettings().allowEdits,+ cursor: agentCursorTelemetryReader,+ version: app.getVersion(),+ });registerNativeBridgeHandlers({getPlatform: () => process.platform,diff --git a/electron/ipc/nativeBridge.mcp.test.ts b/electron/ipc/nativeBridge.mcp.test.tsnew file mode 100644index 000000000..59b477c93--- /dev/null+++ b/electron/ipc/nativeBridge.mcp.test.ts@@ -0,0 +1,82 @@+// The MCP settings actions take renderer input, so the bridge checks its types+// before anything reaches the settings store: a bad value is an INVALID_REQUEST,+// not an INTERNAL_ERROR thrown further in.++import { beforeEach, describe, expect, it, vi } from "vitest";+import type { NativeBridgeResponse } from "../../src/native/contracts";+import { type NativeBridgeContext, registerNativeBridgeHandlers } from "./nativeBridge";++const electron = vi.hoisted(() => ({ handle: vi.fn() }));+vi.mock("electron", () => ({+ app: { getAppPath: () => "", isPackaged: false },+ ipcMain: { handle: electron.handle, removeHandler: vi.fn() },+ shell: {},+}));+vi.mock("../native-bridge/services/compositorViewService", () => ({+ CompositorViewService: class {},+}));++const service = vi.hoisted(() => ({+ mcpSetEnabled: vi.fn(async () => ({ ok: "enabled" })),+ mcpSetPort: vi.fn(async () => ({ ok: "port" })),+ mcpSetAllowEdits: vi.fn(async () => ({ ok: "allowEdits" })),+}));+vi.mock("../native-bridge/services/aiEditionService", () => ({+ AiEditionService: class {+ mcpSetEnabled = service.mcpSetEnabled;+ mcpSetPort = service.mcpSetPort;+ mcpSetAllowEdits = service.mcpSetAllowEdits;+ },+}));++let invoke: (action: string, payload: unknown) => Promise<NativeBridgeResponse>;++beforeEach(() => {+ electron.handle.mockClear();+ for (const fn of Object.values(service)) fn.mockClear();+ registerNativeBridgeHandlers({+ getPlatform: () => "linux",+ getAiEditionDocuments: () => ({}),+ getAiEditionLlmConfig: () => ({}),+ } as unknown as NativeBridgeContext);+ const handler = electron.handle.mock.calls[0]?.[1] as (+ event: unknown,+ request: unknown,+ ) => Promise<NativeBridgeResponse>;+ invoke = (action, payload) =>+ handler({ sender: {} }, { domain: "aiEdition", action, payload, requestId: "r" });+});++function errorCode(response: NativeBridgeResponse): string | undefined {+ return response.ok ? undefined : response.error?.code;+}++describe("native bridge MCP settings", () => {+ it.each([80, 70000, 4.5, "47821", null])("rejects port %s as a bad request", async (port) => {+ expect(errorCode(await invoke("mcp.setPort", { port }))).toBe("INVALID_REQUEST");+ expect(service.mcpSetPort).not.toHaveBeenCalled();+ });++ it("passes a valid port on", async () => {+ const response = await invoke("mcp.setPort", { port: 47821 });+ expect(response.ok).toBe(true);+ expect(service.mcpSetPort).toHaveBeenCalledWith(47821);+ });++ it.each(["true", 1, undefined])("rejects enabled=%s as a bad request", async (enabled) => {+ expect(errorCode(await invoke("mcp.setEnabled", { enabled }))).toBe("INVALID_REQUEST");+ expect(service.mcpSetEnabled).not.toHaveBeenCalled();+ });++ it.each(["yes", 0, undefined])("rejects allowEdits=%s as a bad request", async (allowEdits) => {+ expect(errorCode(await invoke("mcp.setAllowEdits", { allowEdits }))).toBe("INVALID_REQUEST");+ expect(service.mcpSetAllowEdits).not.toHaveBeenCalled();+ });++ it("passes valid flags on", async () => {+ await invoke("mcp.setEnabled", { enabled: true });+ await invoke("mcp.setAllowEdits", { allowEdits: false });+ expect(service.mcpSetEnabled).toHaveBeenCalledWith(true);+ expect(service.mcpSetAllowEdits).toHaveBeenCalledWith(false);+ });+});diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.tsindex 9ba8c293b..452f42701 100644--- a/electron/ipc/nativeBridge.ts+++ b/electron/ipc/nativeBridge.ts@@ -13,6 +13,7 @@ import {import type { ChatEventSink } from "../ai-edition/chat-service";import type { DocumentService } from "../ai-edition/document-service";import { StylePresetError, type StylePresetService } from "../ai-edition/style-preset-service";+import { isValidMcpPort } from "../mcp/mcp-settings-store";import {type CursorTelemetryLoadResult,TelemetryCursorAdapter,@@ -578,16 +579,44 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {);case "mcp.getStatus":return createSuccessResponse(requestId, await aiEditionService.mcpGetStatus());+ // Renderer input: check the types here, so a bad value is reported as+ // the bad request it is rather than failing later as an internal error.case "mcp.setEnabled":+ if (typeof request.payload?.enabled !== "boolean") {+ return createErrorResponse(+ requestId,+ "INVALID_REQUEST",+ "Invalid MCP enabled flag.",+ );+ }return createSuccessResponse(requestId,await aiEditionService.mcpSetEnabled(request.payload.enabled),);case "mcp.setPort":+ if (!isValidMcpPort(request.payload?.port)) {+ return createErrorResponse(+ requestId,+ "INVALID_REQUEST",+ "MCP port must be a whole number between 1024 and 65535.",+ );+ }return createSuccessResponse(requestId,await aiEditionService.mcpSetPort(request.payload.port),);+ case "mcp.setAllowEdits":+ if (typeof request.payload?.allowEdits !== "boolean") {+ return createErrorResponse(+ requestId,+ "INVALID_REQUEST",+ "Invalid MCP edit permission.",+ );+ }+ return createSuccessResponse(+ requestId,+ await aiEditionService.mcpSetAllowEdits(request.payload.allowEdits),+ );case "mcp.regenerateToken":return createSuccessResponse(requestId, await aiEditionService.mcpRegenerateToken());case "chat.run": {diff --git a/electron/mcp/editor-document-host.test.ts b/electron/mcp/editor-document-host.test.tsindex 6071c34d9..5b11cd19a 100644--- a/electron/mcp/editor-document-host.test.ts+++ b/electron/mcp/editor-document-host.test.ts@@ -65,6 +65,18 @@ describe("EditorDocumentHost", () => {await expect(pending).resolves.toEqual({ document: { id: "d" }, revision: 3 });});+ it("treats a snapshot without a numeric revision as no snapshot", async () => {+ const { host, fromRenderer } = setup();+ const editor = new FakeWebContents();+ fromRenderer(editor, AI_EDITION_MCP_HOST_CHANNEL, true);+ // A missing revision would reach the apply guard as `undefined` and skip it.+ for (const revision of [undefined, "3", Number.NaN]) {+ const pending = host.snapshot();+ await answer(editor, fromRenderer, { document: { id: "d" }, revision });+ await expect(pending).resolves.toBeNull();+ }+ });+it("passes the apply verdict through", async () => {const { host, fromRenderer } = setup();const editor = new FakeWebContents();diff --git a/electron/mcp/editor-document-host.ts b/electron/mcp/editor-document-host.tsindex bce4a2d83..55d6d6156 100644--- a/electron/mcp/editor-document-host.ts+++ b/electron/mcp/editor-document-host.ts@@ -90,7 +90,12 @@ export class EditorDocumentHost implements McpDocumentHost {async snapshot(): Promise<AiEditionMcpHostSnapshot | null> {const result = await this.request({ op: "snapshot" });if (!result || result === TIMED_OUT || typeof result !== "object") return null;- return result as AiEditionMcpHostSnapshot;+ // The revision is the apply guard: one that is missing or not a number would+ // reach `applyAgentDocumentIfCurrent` as `undefined`, which skips the+ // stale-edit check entirely. Treat such a reply as no snapshot at all.+ const snapshot = result as Partial<AiEditionMcpHostSnapshot>;+ if (typeof snapshot.revision !== "number" || !Number.isFinite(snapshot.revision)) return null;+ return snapshot as AiEditionMcpHostSnapshot;}async apply(document: AxcutDocument, expectedRevision: number): Promise<McpApplyResult> {diff --git a/electron/mcp/mcp-controller.test.ts b/electron/mcp/mcp-controller.test.tsindex d7d0d426a..3a23bae09 100644--- a/electron/mcp/mcp-controller.test.ts+++ b/electron/mcp/mcp-controller.test.ts@@ -70,7 +70,19 @@ async function initializeStatus(url: string, token: string) {describe("McpSettingsStore", () => {it("is off by default, on the default port", () => {const store = new McpSettingsStore(dir, fakeCrypto);- expect(store.getSettings()).toEqual({ enabled: false, port: DEFAULT_MCP_PORT });+ expect(store.getSettings()).toEqual({+ enabled: false,+ port: DEFAULT_MCP_PORT,+ allowEdits: false,+ });+ });++ it("keeps MCP edits off unless they were turned on explicitly", async () => {+ expect(new McpSettingsStore(dir, fakeCrypto).getSettings().allowEdits).toBe(false);+ await new McpSettingsStore(dir, fakeCrypto).setSettings({ enabled: true });+ expect(new McpSettingsStore(dir, fakeCrypto).getSettings().allowEdits).toBe(false);+ await new McpSettingsStore(dir, fakeCrypto).setSettings({ allowEdits: true });+ expect(new McpSettingsStore(dir, fakeCrypto).getSettings().allowEdits).toBe(true);});it("keeps the token encrypted on disk and stable across instances", async () => {@@ -126,6 +138,19 @@ describe("McpController", () => {expect(status.error).toContain(String(port));});+ it("saves the edit permission without restarting the server", async () => {+ const store = new McpSettingsStore(dir, fakeCrypto);+ await store.setSettings({ port: await freePort() });+ controller = new McpController(store, deps);+ const on = await controller.setEnabled(true);+ expect(on.allowEdits).toBe(false);++ const allowed = await controller.setAllowEdits(true);+ expect(allowed.allowEdits).toBe(true);+ expect(allowed.token).toBe(on.token);+ expect(await initializeStatus(allowed.url, allowed.token ?? "")).toBe(200);+ });+it("locks out the old token once it is regenerated", async () => {const store = new McpSettingsStore(dir, fakeCrypto);await store.setSettings({ port: await freePort() });diff --git a/electron/mcp/mcp-controller.ts b/electron/mcp/mcp-controller.tsindex 5e424553d..49eb1e538 100644--- a/electron/mcp/mcp-controller.ts+++ b/electron/mcp/mcp-controller.ts@@ -66,7 +66,7 @@ export class McpController {async getStatus(): Promise<AiEditionMcpStatus> {await this.transition;- const { enabled, port } = this.store.getSettings();+ const { enabled, port, allowEdits } = this.store.getSettings();let token: string | null = null;if (enabled) {try {@@ -78,6 +78,7 @@ export class McpController {return {enabled,port,+ allowEdits,running: this.running !== null,url: `http://127.0.0.1:${port}${MCP_ENDPOINT_PATH}`,token,@@ -101,6 +102,12 @@ export class McpController {return this.getStatus();}+ /** No restart needed: the server reads it on every call. */+ async setAllowEdits(allowEdits: boolean): Promise<AiEditionMcpStatus> {+ await this.serially(() => this.store.setSettings({ allowEdits }));+ return this.getStatus();+ }+/** New token; the running server is restarted so the old one stops working at once. */async regenerateToken(): Promise<AiEditionMcpStatus> {await this.serially(async () => {diff --git a/electron/mcp/mcp-settings-store.ts b/electron/mcp/mcp-settings-store.tsindex 7c794d50c..4d8aaaa47 100644--- a/electron/mcp/mcp-settings-store.ts+++ b/electron/mcp/mcp-settings-store.ts@@ -16,6 +16,12 @@ export const DEFAULT_MCP_PORT = 47821;export interface McpSettings {enabled: boolean;port: number;+ /**+ * Whether MCP clients may run the tools that change the project. Off by+ * default and separate from the in-app agent's "Project edits": turning the+ * server on gives a client read access, and writing is a second decision.+ */+ allowEdits: boolean;}export interface McpTokenCrypto {@@ -49,9 +55,10 @@ export class McpSettingsStore {return {enabled: raw.enabled === true,port: isValidMcpPort(raw.port) ? raw.port : DEFAULT_MCP_PORT,+ allowEdits: raw.allowEdits === true,};} catch {- return { enabled: false, port: DEFAULT_MCP_PORT };+ return { enabled: false, port: DEFAULT_MCP_PORT, allowEdits: false };}}diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.tsindex fdcb2b565..579ba59a3 100644--- a/electron/native-bridge/services/aiEditionService.ts+++ b/electron/native-bridge/services/aiEditionService.ts@@ -292,6 +292,10 @@ export class AiEditionService {return this.mcp.setPort(port);}+ mcpSetAllowEdits(allowEdits: boolean): Promise<AiEditionMcpStatus> {+ return this.mcp.setAllowEdits(allowEdits);+ }+mcpRegenerateToken(): Promise<AiEditionMcpStatus> {return this.mcp.regenerateToken();}diff --git a/src/components/ai-edition/McpServerSettings.test.tsx b/src/components/ai-edition/McpServerSettings.test.tsxindex e14105a94..453a4961d 100644--- a/src/components/ai-edition/McpServerSettings.test.tsx+++ b/src/components/ai-edition/McpServerSettings.test.tsx@@ -8,10 +8,11 @@ import type { AiEditionMcpStatus } from "@/native/contracts";const TOKEN = "secret-token";const URL = "http://127.0.0.1:47821/mcp";-function status(enabled: boolean): AiEditionMcpStatus {+function status(enabled: boolean, allowEdits = false): AiEditionMcpStatus {return {enabled,port: 47821,+ allowEdits,running: enabled,url: URL,token: enabled ? TOKEN : null,@@ -23,6 +24,7 @@ const bridge = vi.hoisted(() => ({mcpGetStatus: vi.fn(),mcpSetEnabled: vi.fn(),mcpSetPort: vi.fn(),+ mcpSetAllowEdits: vi.fn(),mcpRegenerateToken: vi.fn(),}));@@ -66,6 +68,19 @@ describe("McpServerSettings", () => {expect(screen.queryByText(new RegExp(TOKEN))).not.toBeInTheDocument();});+ it("keeps MCP edits off until they are turned on", async () => {+ bridge.mcpGetStatus.mockResolvedValue(status(true));+ bridge.mcpSetAllowEdits.mockResolvedValue(status(true, true));+ renderSection();+ const toggle = await screen.findByTestId("mcp-edits-toggle");+ expect(toggle).toHaveAttribute("aria-pressed", "false");+ fireEvent.click(toggle);+ await waitFor(() => expect(bridge.mcpSetAllowEdits).toHaveBeenCalledWith(true));+ await waitFor(() =>+ expect(screen.getByTestId("mcp-edits-toggle")).toHaveAttribute("aria-pressed", "true"),+ );+ });+it("copies the real token into the Claude Code command", async () => {bridge.mcpGetStatus.mockResolvedValue(status(true));renderSection();diff --git a/src/components/ai-edition/McpServerSettings.tsx b/src/components/ai-edition/McpServerSettings.tsxindex f2c59b67d..785911bea 100644--- a/src/components/ai-edition/McpServerSettings.tsx+++ b/src/components/ai-edition/McpServerSettings.tsx@@ -126,30 +126,26 @@ export function McpServerSettings({ open }: { open: boolean }) {</div><p className={styles.hint}>{te("mcpServer.description")}</p>- <div className={styles.field}>- <label>{te("mcpServer.enableLabel")}</label>- <label- style={{- display: "flex",- alignItems: "center",- gap: 10,- font: "500 13px var(--font-body)",- color: "var(--fg-2)",- cursor: "pointer",- }}- >- <button- type="button"- data-testid="mcp-server-toggle"- className={`${styles.toggle} ${status.enabled ? styles.isOn : ""}`}- aria-pressed={status.enabled}- disabled={busy}- onClick={() => run(() => nativeBridgeClient.aiEdition.mcpSetEnabled(!status.enabled))}- />- {te("mcpServer.enable")}- </label>- <p className={styles.hint}>{te("mcpServer.editsHint")}</p>- </div>+ <ToggleField+ label={te("mcpServer.enableLabel")}+ text={te("mcpServer.enable")}+ testId="mcp-server-toggle"+ on={status.enabled}+ disabled={busy}+ onToggle={() => run(() => nativeBridgeClient.aiEdition.mcpSetEnabled(!status.enabled))}+ />++ <ToggleField+ label={te("mcpServer.editsLabel")}+ text={te("mcpServer.allowEdits")}+ hint={te("mcpServer.editsHint")}+ testId="mcp-edits-toggle"+ on={status.allowEdits}+ disabled={busy}+ onToggle={() =>+ run(() => nativeBridgeClient.aiEdition.mcpSetAllowEdits(!status.allowEdits))+ }+ /><div className={styles.field}><label>{te("mcpServer.portLabel")}</label>@@ -242,6 +238,52 @@ export function McpServerSettings({ open }: { open: boolean }) {);}+/** The panes' switch, not a system checkbox, inside its label so the text toggles it too. */+function ToggleField({+ label,+ text,+ hint,+ testId,+ on,+ disabled,+ onToggle,+}: {+ label: string;+ text: string;+ hint?: string;+ testId: string;+ on: boolean;+ disabled: boolean;+ onToggle: () => void;+}) {+ return (+ <div className={styles.field}>+ <label>{label}</label>+ <label+ style={{+ display: "flex",+ alignItems: "center",+ gap: 10,+ font: "500 13px var(--font-body)",+ color: "var(--fg-2)",+ cursor: "pointer",+ }}+ >+ <button+ type="button"+ data-testid={testId}+ className={`${styles.toggle} ${on ? styles.isOn : ""}`}+ aria-pressed={on}+ disabled={disabled}+ onClick={onToggle}+ />+ {text}+ </label>+ {hint ? <p className={styles.hint}>{hint}</p> : null}+ </div>+ );+}+function IconButton({label,onClick,diff --git a/src/components/ai-edition/ProviderSettings.test.tsx b/src/components/ai-edition/ProviderSettings.test.tsxindex 304efa183..88103e214 100644--- a/src/components/ai-edition/ProviderSettings.test.tsx+++ b/src/components/ai-edition/ProviderSettings.test.tsx@@ -35,6 +35,7 @@ vi.mock("@/native/client", () => ({Promise.resolve({enabled: false,port: 47821,+ allowEdits: false,running: false,url: "http://127.0.0.1:47821/mcp",token: null,diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.jsonindex 8eac6eb11..e93f6914b 100644--- a/src/i18n/locales/ar/editor.json+++ b/src/i18n/locales/ar/editor.json@@ -407,7 +407,9 @@"description": "اسمح لعملاء MCP الذين تشغّلهم بنفسك، مثل Claude Code أو Codex، باستخدام أدوات التحرير بالذكاء الاصطناعي على المشروع المفتوح في المحرر. يسجّلون الدخول بحساباتهم الخاصة، ولا يطّلع OpenScreen عليها أبدًا.","enableLabel": "الخادم","enable": "تفعيل خادم MCP",- "editsHint": "تخضع التعديلات لإعداد تعديلات المشروع نفسه الذي يخضع له الوكيل المدمج، ويمكن التراجع عن كل تعديل.",+ "editsLabel": "تعديلات المشروع",+ "allowEdits": "السماح لعملاء MCP بتعديل المشروع",+ "editsHint": "متوقف افتراضيًا: يمكن للعملاء قراءة المشروع، ويُرفض كل تعديل يحاولونه. عند تفعيله، يُحفظ كل تعديل فور تطبيقه ويمكن التراجع عنه.","statusRunning": "يعمل","statusOff": "متوقف","statusError": "لا يعمل",diff --git a/src/i18n/locales/cs/editor.json b/src/i18n/locales/cs/editor.jsonindex fb00fa683..ac242ff8d 100644--- a/src/i18n/locales/cs/editor.json+++ b/src/i18n/locales/cs/editor.json@@ -407,7 +407,9 @@"description": "Umožněte MCP klientům, které sami spouštíte, například Claude Code nebo Codex, používat nástroje pro úpravy s AI na projektu otevřeném v editoru. Přihlašují se vlastními účty; OpenScreen je nikdy nevidí.","enableLabel": "Server","enable": "Zapnout MCP server",- "editsHint": "Úpravy se řídí stejným nastavením Úpravy projektu jako vestavěný agent a každou lze vrátit zpět.",+ "editsLabel": "Úpravy projektu",+ "allowEdits": "Povolit MCP klientům úpravy projektu",+ "editsHint": "Ve výchozím stavu vypnuto: klienti mohou projekt číst a každá úprava, o kterou se pokusí, je odmítnuta. Po zapnutí se každá úprava hned uloží a lze ji vrátit zpět.","statusRunning": "Běží","statusOff": "Vypnuto","statusError": "Neběží",diff --git a/src/i18n/locales/de/editor.json b/src/i18n/locales/de/editor.jsonindex 9ac59fd1c..a292f3270 100644--- a/src/i18n/locales/de/editor.json+++ b/src/i18n/locales/de/editor.json@@ -407,7 +407,9 @@"description": "Erlaube MCP-Clients, die du selbst ausführst, etwa Claude Code oder Codex, die KI-Bearbeitungswerkzeuge für das im Editor geöffnete Projekt zu nutzen. Sie melden sich mit ihren eigenen Konten an; OpenScreen sieht diese nie.","enableLabel": "Server","enable": "MCP-Server aktivieren",- "editsHint": "Bearbeitungen folgen derselben Einstellung „Projektänderungen“ wie der integrierte Agent und lassen sich einzeln rückgängig machen.",+ "editsLabel": "Projektänderungen",+ "allowEdits": "MCP-Clients erlauben, das Projekt zu bearbeiten",+ "editsHint": "Standardmäßig aus: Clients können das Projekt lesen, jede versuchte Änderung wird abgelehnt. Wenn aktiviert, wird jede Änderung sofort gespeichert und lässt sich rückgängig machen.","statusRunning": "Läuft","statusOff": "Aus","statusError": "Läuft nicht",diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.jsonindex 94dd2cc91..52dbd2d35 100644--- a/src/i18n/locales/en/editor.json+++ b/src/i18n/locales/en/editor.json@@ -407,7 +407,9 @@"description": "Let MCP clients you run yourself, such as Claude Code or Codex, use the AI editing tools on the project open in the editor. They sign in with their own accounts; OpenScreen never sees them.","enableLabel": "Server","enable": "Enable MCP server",- "editsHint": "Edits follow the same Project edits setting as the built-in agent, and each one can be undone.",+ "editsLabel": "Project edits",+ "allowEdits": "Allow MCP clients to edit the project",+ "editsHint": "Off by default: clients can read the project, and every edit they try is refused. When on, each edit is saved as it lands and can be undone.","statusRunning": "Running","statusOff": "Off","statusError": "Not running",diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.jsonindex f486faffa..d3e01791c 100644--- a/src/i18n/locales/es/editor.json+++ b/src/i18n/locales/es/editor.json@@ -407,7 +407,9 @@"description": "Permite que los clientes MCP que ejecutas tú mismo, como Claude Code o Codex, usen las herramientas de edición con IA en el proyecto abierto en el editor. Inician sesión con sus propias cuentas; OpenScreen nunca las ve.","enableLabel": "Servidor","enable": "Activar servidor MCP",- "editsHint": "Las ediciones siguen el mismo ajuste de Ediciones del proyecto que el agente integrado, y cada una se puede deshacer.",+ "editsLabel": "Ediciones del proyecto",+ "allowEdits": "Permitir que los clientes MCP editen el proyecto",+ "editsHint": "Desactivado por defecto: los clientes pueden leer el proyecto y se rechaza cualquier edición que intenten. Si se activa, cada edición se guarda al aplicarse y se puede deshacer.","statusRunning": "En ejecución","statusOff": "Desactivado","statusError": "Sin ejecutar",diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.jsonindex 464317d1c..60bede225 100644--- a/src/i18n/locales/fr/editor.json+++ b/src/i18n/locales/fr/editor.json@@ -407,7 +407,9 @@"description": "Permettez aux clients MCP que vous lancez vous-même, comme Claude Code ou Codex, d’utiliser les outils d’édition IA sur le projet ouvert dans l’éditeur. Ils se connectent avec leurs propres comptes ; OpenScreen ne les voit jamais.","enableLabel": "Serveur","enable": "Activer le serveur MCP",- "editsHint": "Les modifications suivent le même réglage Modifications du projet que l’agent intégré, et chacune peut être annulée.",+ "editsLabel": "Modifications du projet",+ "allowEdits": "Autoriser les clients MCP à modifier le projet",+ "editsHint": "Désactivé par défaut : les clients peuvent lire le projet, et toute modification qu’ils tentent est refusée. Une fois activé, chaque modification est enregistrée dès qu’elle est appliquée et peut être annulée.","statusRunning": "En cours","statusOff": "Désactivé","statusError": "Arrêté",diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 69f34d7a4..bef5e48d6 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -407,7 +407,9 @@"description": "Consenti ai client MCP che esegui tu stesso, come Claude Code o Codex, di usare gli strumenti di modifica con IA sul progetto aperto nell’editor. Accedono con i propri account; OpenScreen non li vede mai.","enableLabel": "Server","enable": "Attiva server MCP",- "editsHint": "Le modifiche seguono la stessa impostazione Modifiche al progetto dell’agente integrato e ognuna può essere annullata.",+ "editsLabel": "Modifiche al progetto",+ "allowEdits": "Consenti ai client MCP di modificare il progetto",+ "editsHint": "Disattivato per impostazione predefinita: i client possono leggere il progetto e ogni modifica che tentano viene rifiutata. Se attivato, ogni modifica viene salvata subito e può essere annullata.","statusRunning": "In esecuzione","statusOff": "Disattivato","statusError": "Non in esecuzione",diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.jsonindex 035d3d8ba..b8322677a 100644--- a/src/i18n/locales/ja-JP/editor.json+++ b/src/i18n/locales/ja-JP/editor.json@@ -407,7 +407,9 @@"description": "Claude Code や Codex など、ご自身で実行する MCP クライアントが、エディターで開いているプロジェクトに AI 編集ツールを使えるようにします。クライアントは各自のアカウントでサインインし、OpenScreen がそれを見ることはありません。","enableLabel": "サーバー","enable": "MCP サーバーを有効にする",- "editsHint": "編集は内蔵エージェントと同じ「プロジェクトの編集」設定に従い、1 つずつ元に戻せます。",+ "editsLabel": "プロジェクトの編集",+ "allowEdits": "MCP クライアントによるプロジェクトの編集を許可",+ "editsHint": "既定ではオフです。クライアントはプロジェクトを読み取れますが、編集はすべて拒否されます。オンにすると、各編集は反映と同時に保存され、元に戻せます。","statusRunning": "実行中","statusOff": "オフ","statusError": "停止中",diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.jsonindex 60cc5ba2e..3dfd3a431 100644--- a/src/i18n/locales/ko-KR/editor.json+++ b/src/i18n/locales/ko-KR/editor.json@@ -407,7 +407,9 @@"description": "Claude Code나 Codex처럼 직접 실행하는 MCP 클라이언트가 편집기에 열린 프로젝트에서 AI 편집 도구를 사용할 수 있게 합니다. 클라이언트는 자체 계정으로 로그인하며, OpenScreen은 이를 절대 보지 않습니다.","enableLabel": "서버","enable": "MCP 서버 사용",- "editsHint": "편집은 내장 에이전트와 같은 '프로젝트 편집' 설정을 따르며, 각 편집은 실행 취소할 수 있습니다.",+ "editsLabel": "프로젝트 편집",+ "allowEdits": "MCP 클라이언트의 프로젝트 편집 허용",+ "editsHint": "기본값은 꺼짐입니다. 클라이언트는 프로젝트를 읽을 수 있지만 모든 편집 시도는 거부됩니다. 켜면 각 편집이 적용되는 즉시 저장되며 실행 취소할 수 있습니다.","statusRunning": "실행 중","statusOff": "꺼짐","statusError": "실행되지 않음",diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex 2a4f4ced5..d4c344ad9 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -407,7 +407,9 @@"description": "Permita que clientes MCP que você mesmo executa, como Claude Code ou Codex, usem as ferramentas de edição com IA no projeto aberto no editor. Eles entram com as próprias contas; o OpenScreen nunca as vê.","enableLabel": "Servidor","enable": "Ativar servidor MCP",- "editsHint": "As edições seguem a mesma configuração Edições do projeto que o agente integrado, e cada uma pode ser desfeita.",+ "editsLabel": "Edições do projeto",+ "allowEdits": "Permitir que clientes MCP editem o projeto",+ "editsHint": "Desligado por padrão: os clientes podem ler o projeto, e toda edição que tentarem é recusada. Quando ligado, cada edição é salva assim que aplicada e pode ser desfeita.","statusRunning": "Em execução","statusOff": "Desligado","statusError": "Parado",diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex 75053b196..35f0d0233 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -407,7 +407,9 @@"description": "Разрешите MCP-клиентам, которые вы запускаете сами, например Claude Code или Codex, использовать инструменты ИИ-редактирования для проекта, открытого в редакторе. Они входят со своими учётными записями; OpenScreen их никогда не видит.","enableLabel": "Сервер","enable": "Включить MCP-сервер",- "editsHint": "Правки подчиняются той же настройке «Правки проекта», что и встроенный агент, и каждую можно отменить.",+ "editsLabel": "Правки проекта",+ "allowEdits": "Разрешить MCP-клиентам редактировать проект",+ "editsHint": "По умолчанию выключено: клиенты могут читать проект, а любая их попытка правки отклоняется. Если включить, каждая правка сохраняется сразу и её можно отменить.","statusRunning": "Работает","statusOff": "Выключен","statusError": "Не работает",diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.jsonindex e86376f99..df1eb203f 100644--- a/src/i18n/locales/tr/editor.json+++ b/src/i18n/locales/tr/editor.json@@ -407,7 +407,9 @@"description": "Claude Code veya Codex gibi kendi çalıştırdığınız MCP istemcilerinin, düzenleyicide açık olan projede yapay zekâ düzenleme araçlarını kullanmasına izin verin. Kendi hesaplarıyla oturum açarlar; OpenScreen bunları hiçbir zaman görmez.","enableLabel": "Sunucu","enable": "MCP sunucusunu etkinleştir",- "editsHint": "Düzenlemeler, yerleşik ajanla aynı Proje düzenlemeleri ayarına uyar ve her biri geri alınabilir.",+ "editsLabel": "Proje düzenlemeleri",+ "allowEdits": "MCP istemcilerinin projeyi düzenlemesine izin ver",+ "editsHint": "Varsayılan olarak kapalı: istemciler projeyi okuyabilir, denedikleri her düzenleme reddedilir. Açıkken her düzenleme uygulandığı anda kaydedilir ve geri alınabilir.","statusRunning": "Çalışıyor","statusOff": "Kapalı","statusError": "Çalışmıyor",diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex 16b2b6b57..97e000f27 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -407,7 +407,9 @@"description": "Cho phép các ứng dụng khách MCP do bạn tự chạy, như Claude Code hoặc Codex, dùng công cụ chỉnh sửa bằng AI trên dự án đang mở trong trình chỉnh sửa. Chúng đăng nhập bằng tài khoản riêng; OpenScreen không bao giờ thấy các tài khoản đó.","enableLabel": "Máy chủ","enable": "Bật máy chủ MCP",- "editsHint": "Các chỉnh sửa tuân theo cùng cài đặt Chỉnh sửa dự án như tác tử tích hợp, và mỗi chỉnh sửa đều có thể hoàn tác.",+ "editsLabel": "Chỉnh sửa dự án",+ "allowEdits": "Cho phép ứng dụng khách MCP chỉnh sửa dự án",+ "editsHint": "Mặc định tắt: ứng dụng khách có thể đọc dự án, và mọi chỉnh sửa chúng thử đều bị từ chối. Khi bật, mỗi chỉnh sửa được lưu ngay khi áp dụng và có thể hoàn tác.","statusRunning": "Đang chạy","statusOff": "Tắt","statusError": "Không chạy",diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.jsonindex fa22333d5..e2be1ddc2 100644--- a/src/i18n/locales/zh-CN/editor.json+++ b/src/i18n/locales/zh-CN/editor.json@@ -407,7 +407,9 @@"description": "让你自己运行的 MCP 客户端(如 Claude Code 或 Codex)在编辑器中打开的项目上使用 AI 编辑工具。它们使用各自的账号登录,OpenScreen 永远不会看到这些账号。","enableLabel": "服务器","enable": "启用 MCP 服务器",- "editsHint": "编辑遵循与内置智能体相同的“项目编辑”设置,每次编辑都可撤销。",+ "editsLabel": "项目编辑",+ "allowEdits": "允许 MCP 客户端编辑项目",+ "editsHint": "默认关闭:客户端可以读取项目,但它们尝试的每次编辑都会被拒绝。开启后,每次编辑在生效时即保存,并且可以撤销。","statusRunning": "运行中","statusOff": "已关闭","statusError": "未运行",diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.jsonindex 5ded6701a..991a5d04f 100644--- a/src/i18n/locales/zh-TW/editor.json+++ b/src/i18n/locales/zh-TW/editor.json@@ -407,7 +407,9 @@"description": "讓你自行執行的 MCP 用戶端(例如 Claude Code 或 Codex)在編輯器中開啟的專案上使用 AI 編輯工具。它們使用各自的帳號登入,OpenScreen 永遠不會看到這些帳號。","enableLabel": "伺服器","enable": "啟用 MCP 伺服器",- "editsHint": "編輯遵循與內建代理相同的「專案編輯」設定,每次編輯都可復原。",+ "editsLabel": "專案編輯",+ "allowEdits": "允許 MCP 用戶端編輯專案",+ "editsHint": "預設關閉:用戶端可以讀取專案,但它們嘗試的每次編輯都會被拒絕。開啟後,每次編輯在生效時即儲存,並且可以復原。","statusRunning": "執行中","statusOff": "已關閉","statusError": "未執行",diff --git a/src/native/browserShim.ts b/src/native/browserShim.tsindex ec7bcec35..26ed3ca65 100644--- a/src/native/browserShim.ts+++ b/src/native/browserShim.ts@@ -462,10 +462,11 @@ function createShimBridgeClient() {if (taken) throw presetError("NAME_TAKEN", `A style preset named "${name}" already exists.`);};- const shimMcp = { enabled: false, port: 47821, token: "shim-token" };+ const shimMcp = { enabled: false, port: 47821, allowEdits: false, token: "shim-token" };const shimMcpStatus = () => ({enabled: shimMcp.enabled,port: shimMcp.port,+ allowEdits: shimMcp.allowEdits,running: false,url: `http://127.0.0.1:${shimMcp.port}/mcp`,token: shimMcp.enabled ? shimMcp.token : null,@@ -613,6 +614,10 @@ function createShimBridgeClient() {shimMcp.port = port;return Promise.resolve(shimMcpStatus());},+ mcpSetAllowEdits: (allowEdits: boolean) => {+ shimMcp.allowEdits = allowEdits;+ return Promise.resolve(shimMcpStatus());+ },mcpRegenerateToken: () => {shimMcp.token = `shim-token-${Date.now()}`;return Promise.resolve(shimMcpStatus());diff --git a/src/native/client.ts b/src/native/client.tsindex 30ef66288..53d09419b 100644--- a/src/native/client.ts+++ b/src/native/client.ts@@ -274,6 +274,12 @@ export const nativeBridgeClient = {action: "mcp.setPort",payload: { port },}),+ mcpSetAllowEdits: (allowEdits: boolean) =>+ requireNativeBridgeData<AiEditionMcpStatus>({+ domain: "aiEdition",+ action: "mcp.setAllowEdits",+ payload: { allowEdits },+ }),mcpRegenerateToken: () =>requireNativeBridgeData<AiEditionMcpStatus>({domain: "aiEdition",diff --git a/src/native/contracts.ts b/src/native/contracts.tsindex de840ef25..432a6ca69 100644--- a/src/native/contracts.ts+++ b/src/native/contracts.ts@@ -295,6 +295,8 @@ export interface AiEditionLlmProviderModelsResult {export interface AiEditionMcpStatus {enabled: boolean;port: number;+ /** Whether clients may run the tools that change the project. Off by default. */+ allowEdits: boolean;running: boolean;/** `http://127.0.0.1:<port>/mcp` — what a client is pointed at. */url: string;@@ -662,6 +664,12 @@ export type NativeBridgeRequest =payload: { port: number };requestId?: string;}+ | {+ domain: "aiEdition";+ action: "mcp.setAllowEdits";+ payload: { allowEdits: boolean };+ requestId?: string;+ }| {domain: "aiEdition";action: "mcp.regenerateToken";diff --git a/technical-documentation/architecture/mcp-server.md b/technical-documentation/architecture/mcp-server.mdindex 665e3cb7f..4d3ca2155 100644--- a/technical-documentation/architecture/mcp-server.md+++ b/technical-documentation/architecture/mcp-server.md@@ -7,9 +7,9 @@ OpenScreen can offer the in-app agent's tools to MCP clients the user runs thems| [`electron/mcp/openscreen-mcp-server.ts`](../../electron/mcp/openscreen-mcp-server.ts) | The MCP server and its local HTTP guard. Registers the tools, runs each call. || [`electron/mcp/editor-document-host.ts`](../../electron/mcp/editor-document-host.ts) | Main-process side of the live document: asks the editor window for a snapshot and hands edits back. || [`electron/mcp/mcp-controller.ts`](../../electron/mcp/mcp-controller.ts) | Lifecycle: start when enabled, restart on a port or token change, status for the settings UI. |-| [`electron/mcp/mcp-settings-store.ts`](../../electron/mcp/mcp-settings-store.ts) | `mcp-server.json` (enabled, port) and `mcp-token.enc` (bearer token, `safeStorage`). |+| [`electron/mcp/mcp-settings-store.ts`](../../electron/mcp/mcp-settings-store.ts) | `mcp-server.json` (enabled, port, allowEdits) and `mcp-token.enc` (bearer token, `safeStorage`). || [`src/lib/ai-edition/store/mcpDocumentHost.ts`](../../src/lib/ai-edition/store/mcpDocumentHost.ts) | Renderer side: answers snapshot / apply requests from the project store. Mounted by `NewEditorShell`. |-| [`src/components/ai-edition/McpServerSettings.tsx`](../../src/components/ai-edition/McpServerSettings.tsx) | The settings section: toggle, port, token, copyable `claude mcp add` / `codex mcp add` commands. |+| [`src/components/ai-edition/McpServerSettings.tsx`](../../src/components/ai-edition/McpServerSettings.tsx) | The settings section: server toggle, its own Project edits toggle, port, token, copyable `claude mcp add` / `codex mcp add` commands. |## One tool surface, two agents@@ -17,7 +17,7 @@ Nothing about the tools is reimplemented. The server registers `TOOL_ARG_SCHEMASSo a tool added to the agent appears over MCP with no further work, and the MCP test asserts the listed tools equal `OPENSCREEN_TOOL_NAMES`. What the server adds is MCP metadata only: `readOnlyHint` for the reads (`!isMutatingTool`) and `destructiveHint` for `replaceTimeline` and the three `remove*` tools.-The "Project edits" switch (`allowAgentEdits`) applies unchanged: it is read on every call and passed to the executor, which refuses writes when it is off, and the consent block of the system prompt is in the instructions.+**Writes are a second opt-in.** MCP clients have their own "Project edits" switch, `allowEdits` in `mcp-server.json`, **off by default** and independent of the in-app agent's `allowAgentEdits`. Turning the server on therefore grants read access only. The value is read on every call and passed to the executor as `editsAllowed`, the same gate the in-app agent's switch drives: while it is off every mutating tool is refused with the executor's consent message, and the consent block of the system prompt is in the instructions. It is independent because `allowAgentEdits` defaults to allowed and lives in the provider form, so a user with no provider configured could never have turned MCP writes off.## Where the document comes from@@ -57,4 +57,3 @@ codex mcp add openscreen --url http://127.0.0.1:47821/mcp --bearer-token-env-var- **Only what the agent can do.** The server exposes the agent's timeline tools. Recording, export, import and project management are not tools, for MCP or for the in-app agent.- **An open editor is required.** With no editor window, or no project loaded, every tool answers "No project is open".-- **The edits switch lives in the provider form.** `allowAgentEdits` is part of `LlmConfig`, so a user with no provider configured cannot turn edits off for MCP clients; it defaults to allowed.diff --git a/website/docs/ai-editing.md b/website/docs/ai-editing.mdindex 46cf26f5e..cf3399a66 100644--- a/website/docs/ai-editing.md+++ b/website/docs/ai-editing.md@@ -67,4 +67,4 @@ If you already use an AI coding agent such as Claude Code or Codex, it can drive2. Copy the **Claude Code** or **Codex** command shown there and run it in a terminal. The Claude Code command carries the access token. Codex reads it from the `OPENSCREEN_MCP_TOKEN` environment variable instead: set that in the shell you start Codex from.3. Keep a project open in the OpenScreen editor, then ask your agent for the edit.-The tools are the ones the built-in agent uses, and they act on the project open in the editor. Each edit is saved as it lands and undone with `Ctrl/Cmd + Z`. The **Project edits** switch applies to MCP clients too. **Regenerate** the token to disconnect every client set up with the old one.+The tools are the ones the built-in agent uses, and they act on the project open in the editor. MCP clients can only **read** the project until you also turn on **Project edits** in the MCP server section; this switch is separate from the built-in agent's, and it starts off. Once on, each edit is saved as it lands and undone with `Ctrl/Cmd + Z`. **Regenerate** the token to disconnect every client set up with the old one.