diff --git a/docs/getting-started/client-configuration.md b/docs/getting-started/client-configuration.md index b5c66ec3f3b..6936f710255 100644 --- a/docs/getting-started/client-configuration.md +++ b/docs/getting-started/client-configuration.md @@ -926,6 +926,11 @@ of these clients. Setup offers a client when its directory exists. | Zed | `zed` | `~/.config/zed/settings.json` on macOS, `%APPDATA%\Zed\settings.json` on Windows, `$XDG_CONFIG_HOME/zed/settings.json` on Linux | `context_servers` | | Amp | `amp` | `~/.config/amp/settings.json`, or `settings.jsonc` when that is the only one | `amp.mcpServers` | +Mastra Code skips all MCP sources when `MASTRACODE_DISABLE_MCP` is `1`, +`true`, `yes`, or `on`, ignoring case and surrounding whitespace. Run setup +or `rea mcp add` with the flag unset or false to prepare a registration the +client will load. + The Cline extension keeps a separate settings file in each editor that runs it. `cline_vscode_insiders`, `cline_vscodium`, `cline_cursor` and `cline_windsurf` manage the same file under that editor's user directory diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index 759b7b77c69..284804f6bee 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -404,6 +404,7 @@ export const readClientRegistrationInspections = async ( parsed, undefined, options.resources, + options.environment ?? process.env, ); if (!policy.ok) { if ( diff --git a/src/application/GeminiClientSettings.ts b/src/application/GeminiClientSettings.ts index 5872b93e32f..800052195c5 100644 --- a/src/application/GeminiClientSettings.ts +++ b/src/application/GeminiClientSettings.ts @@ -32,6 +32,7 @@ import { } from "./ClientConfigurationFiles.js"; import type { SetupClient } from "./SupportedClients.js"; import { readJunieLocationBlock } from "./JunieClientSettings.js"; +import { mastracodeMcpDisabledPolicy } from "./MastraCodeSettings.js"; import { errorMessage } from "../kernel/errorMessage.js"; type SettingsSource = { path: string; document: ClientConfigurationDocument }; @@ -140,6 +141,7 @@ export const readClientPolicyBlock = async ( userDocument: ClientConfigurationDocument | undefined, desiredRegistration?: unknown, resources?: ArtifactResourceScope, + launcherEnvironment: Readonly = process.env, ): Promise> => { if (client.claudeCodeManaged !== undefined) { const policy = await readClaudeCodeMcpPolicy( @@ -173,6 +175,8 @@ export const readClientPolicyBlock = async ( } if (client.junieSettings !== undefined) return readJunieLocationBlock(client.junieSettings, resources); + if (client.name === "mastracode") + return ok(mastracodeMcpDisabledPolicy(launcherEnvironment)); if (client.name !== "gemini_cli" || client.geminiSettings === undefined) return ok(undefined); const settings = client.geminiSettings; diff --git a/src/application/MastraCodeSettings.ts b/src/application/MastraCodeSettings.ts new file mode 100644 index 00000000000..d1c6e7057ad --- /dev/null +++ b/src/application/MastraCodeSettings.ts @@ -0,0 +1,20 @@ +export const MASTRACODE_DISABLE_MCP = "MASTRACODE_DISABLE_MCP"; + +// Mastra Code reads the switch with the same truthy set for its other +// MASTRACODE_DISABLE_* variables, so "0" and "false" leave MCP enabled. +const truthy = new Set(["1", "true", "yes", "on"]); + +export const mastracodeMcpDisabled = ( + environment: Readonly, +): boolean => { + const value = environment[MASTRACODE_DISABLE_MCP]?.trim().toLowerCase(); + return value !== undefined && truthy.has(value); +}; + +/** Why Mastra Code will start no MCP server despite the saved registration. */ +export const mastracodeMcpDisabledPolicy = ( + environment: Readonly, +): string | undefined => + mastracodeMcpDisabled(environment) + ? `${MASTRACODE_DISABLE_MCP} turns off every MCP source in Mastra Code, so this registration is not loaded in an environment that sets it. Unset ${MASTRACODE_DISABLE_MCP} or set it to 0, then restart Mastra Code.` + : undefined; diff --git a/src/application/McpClientRegistration.ts b/src/application/McpClientRegistration.ts index 9868fe9a078..cf05dc8c187 100644 --- a/src/application/McpClientRegistration.ts +++ b/src/application/McpClientRegistration.ts @@ -97,6 +97,7 @@ export const registerMcpClients = async ( resources: ArtifactResourceScope, /** The host the clients were resolved for; it decides document semantics. */ platform: NodeJS.Platform, + launcherEnvironment: Readonly = process.env, ): Promise => { const outcomes: McpClientRegistrationOutcome[] = []; let cancelled = false; @@ -116,6 +117,7 @@ export const registerMcpClients = async ( signal, resources, platform, + launcherEnvironment, ); outcomes.push({ ...labels, status: "completed", result }); cancelled = @@ -132,6 +134,7 @@ export const registerMcpClient = async ( signal: AbortSignal | undefined, resources: ArtifactResourceScope, platform: NodeJS.Platform, + launcherEnvironment: Readonly = process.env, ): Promise< Result > => { @@ -180,6 +183,7 @@ export const registerMcpClient = async ( client, launcher, platform, + launcherEnvironment, ); if (!preparation.ok) return retainFailure(preparation.error); const prepared = preparation.value; diff --git a/src/application/McpRegistrationConfiguration.ts b/src/application/McpRegistrationConfiguration.ts index d15330b69a5..a87d313dd0e 100644 --- a/src/application/McpRegistrationConfiguration.ts +++ b/src/application/McpRegistrationConfiguration.ts @@ -1,3 +1,4 @@ +import { mastracodeMcpDisabledPolicy } from "./MastraCodeSettings.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import type { ClientRegistrationCommand } from "../domain/clientRegistrationCommand.js"; import { errorMessage } from "../kernel/errorMessage.js"; @@ -72,14 +73,23 @@ const registrationDocumentFailure = ( /** * Merge REA's entry into one selected client document. `platform` is the host * the catalog resolved the client for; it decides the document's environment - * name rules. + * name rules. `launcherEnvironment` is the environment the client will start + * in, which decides client-level MCP switches such as Mastra Code's. */ export const prepareRegistration = async ( path: string, client: McpRegistrationClient, launcher: ClientRegistrationCommand, platform: NodeJS.Platform, + launcherEnvironment: Readonly = process.env, ) => { + if (client.id === "mastracode") { + const disabled = mastracodeMcpDisabledPolicy(launcherEnvironment); + if (disabled !== undefined) + return err( + new ConfigurationError(`${disabled} No settings were written.`), + ); + } const snapshot = await readRegularFileTextSnapshot(path, { symlinks: "reject", }).catch((cause: unknown) => { @@ -135,6 +145,8 @@ export const prepareRegistration = async ( client.setupClient, parsed, desired.value, + undefined, + launcherEnvironment, ); if (!policy.ok) return configurationLayerFailure(policy.error); if (policy.value !== undefined) diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index d0756d47671..843a641fc31 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -242,7 +242,13 @@ const configureClientDocument = async ( resolveProviderRequestBudget, ); if (!policyEntry.ok) return desiredReadbackFailure(policyEntry.error); - const policy = await readClientPolicyBlock(client, parsed, policyEntry.value); + const policy = await readClientPolicyBlock( + client, + parsed, + policyEntry.value, + undefined, + launcherEnvironment, + ); if (!policy.ok) { throwCleanupFailure(policy.error); return { status: "failed", reason: "readback" }; @@ -664,6 +670,7 @@ const readClientRefresh = async ( parsed, desired, resources, + launcherEnvironment, ); if (!policy.ok) { throwCleanupFailure(policy.error); @@ -979,6 +986,8 @@ const inspectClientDocument = async ( client, undefined, desired.value, + undefined, + launcherEnvironment, ); if (!policy.ok) { throwCleanupFailure(policy.error); @@ -1054,7 +1063,13 @@ const inspectClientDocument = async ( ); if (override !== undefined) return { status: "invalid", remediation: override }; - const policy = await readClientPolicyBlock(client, parsed, desired.value); + const policy = await readClientPolicyBlock( + client, + parsed, + desired.value, + undefined, + launcherEnvironment, + ); if (!policy.ok) { throwCleanupFailure(policy.error); return { diff --git a/src/cli/mcpRegistration.ts b/src/cli/mcpRegistration.ts index 5f940c6a013..f60fb9eff70 100644 --- a/src/cli/mcpRegistration.ts +++ b/src/cli/mcpRegistration.ts @@ -319,6 +319,7 @@ const executeRegistration = async ( signal, resources, platform, + environment, ), }; }) diff --git a/tests/boundary/cli/mcpAddClientPolicy.test.ts b/tests/boundary/cli/mcpAddClientPolicy.test.ts index 94341df8d81..b617271964b 100644 --- a/tests/boundary/cli/mcpAddClientPolicy.test.ts +++ b/tests/boundary/cli/mcpAddClientPolicy.test.ts @@ -238,3 +238,56 @@ const addOpenCodeProject = ( cwd, environment, }); + +cliTest.for(["global", "project"] as const)( + "mcp add respects the Mastra disable flag for the %s registration", + async (scope, { cli }) => { + const home = await createTestTempDirectory("rea-mastra-mcp-flag-"); + const project = join(home, "project"); + await mkdir(project); + const path = join( + scope === "global" ? home : project, + ".mastracode", + "mcp.json", + ); + const command = [ + "mcp", + "add", + "--agent", + "mastra", + "--command", + "rea mcp", + "--json", + ...(scope === "global" ? [] : ["--no-global"]), + ]; + const blocked = await cli.run({ + arguments: command, + cwd: project, + environment: await registrationEnvironment(home, { + MASTRACODE_DISABLE_MCP: " YES ", + }), + }); + expect(blocked.exitCode, blocked.stdout).toBe(1); + expect(mcpRegistrationReportSchema.parse(blocked.json)).toMatchObject({ + clients: [ + { + config_path: path, + status: "failed", + error: { reason: expect.stringContaining("MASTRACODE_DISABLE_MCP") }, + }, + ], + }); + await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" }); + const enabled = await cli.run({ + arguments: command, + cwd: project, + environment: await registrationEnvironment(home, { + MASTRACODE_DISABLE_MCP: "false", + }), + }); + expect(enabled.exitCode, enabled.stdout).toBe(0); + expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({ + mcpServers: { rea: { command: "rea", args: ["mcp"] } }, + }); + }, +); diff --git a/tests/boundary/filesystem/mastracodeDisabledRegistration.test.ts b/tests/boundary/filesystem/mastracodeDisabledRegistration.test.ts new file mode 100644 index 00000000000..22bd4a18a74 --- /dev/null +++ b/tests/boundary/filesystem/mastracodeDisabledRegistration.test.ts @@ -0,0 +1,84 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { expect, it } from "vitest"; + +import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js"; +import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const MASTRACODE_COMMAND = ["/opt/rea/bin/rea", "mcp"]; + +const fixture = async () => { + const home = await createTestTempDirectory("rea-mastracode-disable-"); + const configPath = join(home, ".mastracode", "mcp.json"); + await mkdir(dirname(configPath), { recursive: true }); + await writeFile(configPath, JSON.stringify({ mcpServers: {} })); + const [client] = supportedClients( + home, + process.platform, + {}, + {}, + "mastracode", + ); + if (client === undefined) throw new Error("Mastra Code is not a client row"); + return { home, client, configPath }; +}; + +it("reports the saved registration stale while MASTRACODE_DISABLE_MCP is set", async () => { + const { home, configPath } = await fixture(); + const [command, entrypoint, ...args] = currentClientRegistrationCommand(); + if (command === undefined || entrypoint === undefined) + throw new Error("Mastra Code needs the current launcher"); + await writeFile( + configPath, + JSON.stringify({ + mcpServers: { rea: { command, args: [entrypoint, ...args] } }, + }), + ); + const status = async (value: string) => + ( + await readClientRegistrationStatuses(home, entrypoint, { + platform: process.platform, + environment: { MASTRACODE_DISABLE_MCP: value }, + selectedClientIds: ["mastracode"], + scope: "user", + }) + ).find(({ client }) => client === "mastracode"); + expect(await status("0")).toMatchObject({ + command_identity: "owned", + state: "aligned", + }); + expect(await status("1")).toMatchObject({ + command_identity: "owned", + state: "stale", + remediation: expect.stringContaining("MASTRACODE_DISABLE_MCP"), + }); +}); + +it("refuses a setup repair the running Mastra Code would ignore", async () => { + const { client, configPath } = await fixture(); + const disabled = await configureClientConfiguration( + client, + {}, + MASTRACODE_COMMAND, + undefined, + process.platform, + { MASTRACODE_DISABLE_MCP: "true" }, + ); + expect(disabled).toMatchObject({ status: "failed", reason: "readback" }); + expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({ + mcpServers: {}, + }); + + const enabled = await configureClientConfiguration( + client, + {}, + MASTRACODE_COMMAND, + undefined, + process.platform, + {}, + ); + expect(enabled.status).toBe("configured"); +}); diff --git a/tests/boundary/filesystem/mastracodePolicySources.test.ts b/tests/boundary/filesystem/mastracodePolicySources.test.ts new file mode 100644 index 00000000000..a1388cdb296 --- /dev/null +++ b/tests/boundary/filesystem/mastracodePolicySources.test.ts @@ -0,0 +1,73 @@ +import { expect, it } from "vitest"; + +import { readClientPolicyBlock } from "../../../src/application/GeminiClientSettings.js"; +import type { SetupClient } from "../../../src/application/SupportedClients.js"; +import { supportedClientRegistrationProfile } from "../../fixtures/clientRegistrationProfile.js"; + +const mastracode = ( + configPath = "/home/alice/.mastracode/mcp.json", +): SetupClient => ({ + name: "mastracode", + registrationProfile: supportedClientRegistrationProfile("mastracode"), + configPath, + format: "json", +}); + +const registration = { url: "node /opt/rea/scripts/rea.mjs mcp" }; + +it.each(["1", "true", "TRUE", "yes", "on", " On "])( + "reports Mastra Code's MCP as disabled when MASTRACODE_DISABLE_MCP is %j", + async (value) => { + expect( + await readClientPolicyBlock( + mastracode(), + undefined, + registration, + undefined, + { MASTRACODE_DISABLE_MCP: value }, + ), + ).toMatchObject({ + ok: true, + value: expect.stringContaining("MASTRACODE_DISABLE_MCP"), + }); + }, +); + +it.each(["0", "false", "off", "no", ""])( + "leaves Mastra Code aligned when MASTRACODE_DISABLE_MCP is %j", + async (value) => { + expect( + await readClientPolicyBlock( + mastracode(), + undefined, + registration, + undefined, + { MASTRACODE_DISABLE_MCP: value }, + ), + ).toEqual({ ok: true, value: undefined }); + }, +); + +it("leaves Mastra Code aligned when MASTRACODE_DISABLE_MCP is unset", async () => { + expect( + await readClientPolicyBlock( + mastracode(), + undefined, + registration, + undefined, + {}, + ), + ).toEqual({ ok: true, value: undefined }); +}); + +it("does not let another client's disable switch affect Mastra Code", async () => { + expect( + await readClientPolicyBlock( + mastracode(), + undefined, + registration, + undefined, + { CLINE_DISABLE_MCP: "1" }, + ), + ).toEqual({ ok: true, value: undefined }); +});