fix(setup): honor Mastra Code's MCP disable flag (#15126)

* fix(setup): report Mastra Code's MASTRACODE_DISABLE_MCP switch

Mastra Code reads MASTRACODE_DISABLE_MCP at startup and stops loading every
MCP source. REA's client table has no such fact, so doctor kept reporting
~/.mastracode/mcp.json as aligned while Mastra started no server, and setup
rewrote a registration the running client ignores.

readClientPolicyBlock now answers for mastracode through a small module of
its own. The value is truthy only for 1/true/yes/on, case-insensitively
and after trimming, matching Mastra Code's isTruthyEnv. Doctor, setup's
inspect/configure and mcp add pass the launcher environment they already
resolve, so a supplied environment decides the outcome instead of the host
process.env.

The documented load order also lists the project .mcp.json, which this
change does not read yet; #15038 stays open for that half.

Tests: mastracodePolicySources (13, new) covers the value table;
mastracodeDisabledRegistration (2, new) covers status, setup refusal and
an unchanged file; geminiPolicySources (4) and setupPolicySnapshot (7)
still pass. check:fast is green across 3328 files. The CLI boundary suite
mcpAddClientPolicy needs a compiled dist/cli-runtime and was not run.

Refs #15038

(cherry picked from commit 4e5ea523f4a4c3040c7d172758558fb6a0241966)

* fix(setup): enforce the Mastra flag for project MCP registration

* style(test): format Mastra MCP regression

* test(doctor): prove the Mastra disable policy gates a valid launcher

---------

Co-authored-by: 2SinceJuly <202121119+2SinceJuly@users.noreply.github.com>
This commit is contained in:
morlutoand2SinceJuly authored and GitHub committed 2026-11-29 20:17:58 +00:00
1 parent 4170a4ce40
commit a3be3f429a
11 files changed
+275 -3

No files matched your search

@@ -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
@@ -404,6 +404,7 @@ export const readClientRegistrationInspections = async (
parsed,
undefined,
options.resources,
options.environment ?? process.env,
);
if (!policy.ok) {
if (
+4
View File
@@ -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<NodeJS.ProcessEnv> = process.env,
): Promise<Result<string | undefined, ClientConfigurationFileError>> => {
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;
+20
View File
@@ -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<NodeJS.ProcessEnv>,
): 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<NodeJS.ProcessEnv>,
): 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;
+4
View File
@@ -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<NodeJS.ProcessEnv> = process.env,
): Promise<readonly McpClientRegistrationOutcome[]> => {
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<NodeJS.ProcessEnv> = process.env,
): Promise<
Result<McpClientRegistrationReceipt, McpClientRegistrationFailure>
> => {
@@ -180,6 +183,7 @@ export const registerMcpClient = async (
client,
launcher,
platform,
launcherEnvironment,
);
if (!preparation.ok) return retainFailure(preparation.error);
const prepared = preparation.value;
@@ -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<NodeJS.ProcessEnv> = 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)
+17 -2
View File
@@ -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 {
+1
View File
@@ -319,6 +319,7 @@ const executeRegistration = async (
signal,
resources,
platform,
environment,
),
};
})
@@ -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"] } },
});
},
);
@@ -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");
});
@@ -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 });
});