Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/cli/src/commands/mcp/approve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
MCP_APPROVALS_FILENAME,
} from '../../config/mcpApprovals.js';
import { loadProjectMcpServers } from '../../config/mcpJson.js';
import { setProjectMcpLiteralSource } from '../../config/mcpServers.js';

describe('qwen mcp approve / reject', () => {
let dir: string;
Expand Down Expand Up @@ -68,7 +69,10 @@ describe('qwen mcp approve / reject', () => {

const stateOf = (name: string) => {
resetMcpApprovalsForTesting();
const { servers } = loadProjectMcpServers(dir);
const { servers, literalServers } = loadProjectMcpServers(dir);
// Re-register the literal source the way assembly would, so the hash
// binding sees the pre-expansion config (#11499).
setProjectMcpLiteralSource(dir, literalServers);
return loadMcpApprovals().getState(dir, name, servers[name]!);
};

Expand Down
109 changes: 109 additions & 0 deletions packages/cli/src/config/mcpApprovals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import {
resetMcpApprovalsForTesting,
MCP_APPROVALS_FILENAME,
} from './mcpApprovals.js';
import {
resetProjectMcpLiteralSourceForTesting,
setProjectMcpLiteralSource,
} from './mcpServers.js';

describe('mcpApprovals (hash-bound approval store)', () => {
let dir: string;
Expand Down Expand Up @@ -629,4 +633,109 @@ describe('mcpApprovals (hash-bound approval store)', () => {
).toEqual([]);
});
});

describe('project `.mcp.json` approval binding (issue #11499)', () => {
// Approval hashes for project servers bind to the pre-expansion literal
// config, so rotating the secret behind a ${VAR} placeholder must NOT
// re-prompt; editing the file must.
const savedToken = process.env['MY_MCP_TOKEN'];

beforeEach(() => {
process.env['MY_MCP_TOKEN'] = 'tok-v1';
resetProjectMcpLiteralSourceForTesting();
});

afterEach(() => {
if (savedToken === undefined) {
delete process.env['MY_MCP_TOKEN'];
} else {
process.env['MY_MCP_TOKEN'] = savedToken;
}
resetProjectMcpLiteralSourceForTesting();
});

const expandedServer = (): MCPServerConfig =>
({
httpUrl: 'https://example.test/mcp',
headers: { Authorization: 'Bearer tok-v1' },
scope: 'project',
}) as unknown as MCPServerConfig;

const literalServer = (): MCPServerConfig =>
({
httpUrl: 'https://example.test/mcp',
headers: { Authorization: 'Bearer ${MY_MCP_TOKEN}' },
scope: 'project',
}) as unknown as MCPServerConfig;

/** Registers the literal source exactly as assembly from a real dir would. */
const registerLiteral = (literal: MCPServerConfig) => {
setProjectMcpLiteralSource(projectRoot, { gated: literal });
};

it('keeps an approval stable when the env value behind the placeholder rotates', async () => {
registerLiteral(literalServer());
const approvals = loadMcpApprovals();
await approvals.setState(
projectRoot,
'gated',
expandedServer(),
'approved',
);
expect(approvals.getState(projectRoot, 'gated', expandedServer())).toBe(
'approved',
);

// Token rotates — the resolved config changes, the file did not.
const rotated: MCPServerConfig = {
...expandedServer(),
headers: { Authorization: 'Bearer tok-v2' },
};
expect(approvals.getState(projectRoot, 'gated', rotated)).toBe(
'approved',
);
});

it('re-prompts when the literal `.mcp.json` entry is edited', async () => {
registerLiteral(literalServer());
const approvals = loadMcpApprovals();
await approvals.setState(
projectRoot,
'gated',
expandedServer(),
'approved',
);

// Same placeholder position, different URL — a real file edit.
const editedLiteral: MCPServerConfig = {
...literalServer(),
httpUrl: 'https://v2.example.test/mcp',
};
const editedExpanded: MCPServerConfig = {
...expandedServer(),
httpUrl: 'https://v2.example.test/mcp',
};
registerLiteral(editedLiteral);
expect(approvals.getState(projectRoot, 'gated', editedExpanded)).toBe(
'pending',
);
});

it('binds to the live config when no literal source is registered (settings-scope parity)', async () => {
// No literal source ⇒ the live config is the binding, exactly as for
// workspace-scoped servers today.
const approvals = loadMcpApprovals();
await approvals.setState(
projectRoot,
'gated',
expandedServer(),
'approved',
);
const rotated: MCPServerConfig = {
...expandedServer(),
headers: { Authorization: 'Bearer tok-v2' },
};
expect(approvals.getState(projectRoot, 'gated', rotated)).toBe('pending');
});
});
});
29 changes: 27 additions & 2 deletions packages/cli/src/config/mcpApprovals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,31 @@ import {
} from '@qwen-code/qwen-code-core';
import stripJsonComments from 'strip-json-comments';
import { writeStderrLine } from '../utils/stdioHelpers.js';
import { getProjectMcpLiteralSource } from './mcpServers.js';

export const MCP_APPROVALS_FILENAME = 'mcpApprovals.json';

/**
* The canonical config hash for approval binding. Project `.mcp.json`
* servers are loaded with env-var placeholders already resolved (#11499),
* so hashing the live config would bind the approval to the secret's
* *value*: rotating a token or a teammate cloning the repo with their own
* token would flip an approved server back to `pending` although the file
* never changed. #4615's intent is that *editing the file* re-triggers
* approval — so a project server binds to the hash of its pre-expansion
* literal config when that is available, and to the live config otherwise
* (settings-sourced servers are resolved upstream and keep the existing
* binding).
*/
function approvalConfigHash(
projectRoot: string,
serverName: string,
config: MCPServerConfig,
): string {
const literal = getProjectMcpLiteralSource(projectRoot)?.[serverName];
return hashMcpServerConfig(literal ?? config);
}

/**
* The user's persisted decision for one project-scoped MCP server. A decision is
* bound to `hash` — the canonical hash of the exact config the user reviewed. If
Expand Down Expand Up @@ -175,7 +197,7 @@ export class LoadedMcpApprovals {
if (!record) {
return 'pending';
}
if (record.hash !== hashMcpServerConfig(config)) {
if (record.hash !== approvalConfigHash(projectRoot, serverName, config)) {
return 'pending';
}
return record.status;
Expand All @@ -196,7 +218,10 @@ export class LoadedMcpApprovals {
? existing
: Object.create(null);
Object.defineProperty(project, serverName, {
value: { hash: hashMcpServerConfig(config), status },
value: {
hash: approvalConfigHash(projectRoot, serverName, config),
status,
},
enumerable: true,
configurable: true,
writable: true,
Expand Down
141 changes: 141 additions & 0 deletions packages/cli/src/config/mcpJson.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,145 @@ describe('loadProjectMcpServers', () => {
expect(servers['good']).toMatchObject({ command: 'ok', scope: 'project' });
expect(errors).toHaveLength(2);
});

describe('env-var expansion (#11499)', () => {
const savedToken = process.env['MY_MCP_TOKEN'];
const savedHostName = process.env['HOST_NAME'];
const savedHome = process.env['QWEN_HOME'];
let homeDir: string;

beforeEach(() => {
process.env['MY_MCP_TOKEN'] = 'tok-from-process-env';
process.env['HOST_NAME'] = 'example.test';
homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcpjson-home-'));
process.env['QWEN_HOME'] = homeDir;
});

afterEach(() => {
for (const [key, saved] of [
['MY_MCP_TOKEN', savedToken],
['HOST_NAME', savedHostName],
['QWEN_HOME', savedHome],
] as const) {
if (saved === undefined) {
delete process.env[key];
} else {
process.env[key] = saved;
}
}
fs.rmSync(homeDir, { recursive: true, force: true });
});

it('resolves $VAR and ${VAR} in headers, env, url and command/args', () => {
write(
JSON.stringify({
mcpServers: {
http: {
httpUrl: 'https://${HOST_NAME}/mcp',
headers: { Authorization: 'Bearer ${MY_MCP_TOKEN}' },
},
stdio: {
command: 'node',
args: ['--flag', '$MY_MCP_TOKEN'],
env: { TOKEN: '$MY_MCP_TOKEN' },
},
},
}),
);
const { servers, errors } = loadProjectMcpServers(dir);
expect(errors).toEqual([]);
expect(servers['http']).toMatchObject({
httpUrl: 'https://example.test/mcp',
headers: { Authorization: 'Bearer tok-from-process-env' },
scope: 'project',
});
expect(servers['stdio']).toMatchObject({
command: 'node',
args: ['--flag', 'tok-from-process-env'],
env: { TOKEN: 'tok-from-process-env' },
});
});
it('falls back to the home ~/.qwen/.env for vars not in process.env', () => {
delete process.env['MY_MCP_TOKEN'];
fs.writeFileSync(
path.join(homeDir, '.env'),
'MY_MCP_TOKEN=tok-from-home-env\n',
);
write(
JSON.stringify({
mcpServers: {
http: {
httpUrl: 'https://example.test/mcp',
headers: { Authorization: 'Bearer ${MY_MCP_TOKEN}' },
},
},
}),
);
const { servers, errors } = loadProjectMcpServers(dir);
expect(errors).toEqual([]);
expect(servers['http']).toMatchObject({
headers: { Authorization: 'Bearer tok-from-home-env' },
});
});

it('keeps an unresolved placeholder literal rather than erroring', () => {
delete process.env['MY_MCP_TOKEN'];
write(
JSON.stringify({
mcpServers: {
http: {
httpUrl: 'https://example.test/mcp',
headers: { Authorization: 'Bearer ${MY_MCP_TOKEN}' },
},
},
}),
);
const { servers, errors } = loadProjectMcpServers(dir);
expect(errors).toEqual([]);
expect(servers['http']).toMatchObject({
headers: { Authorization: 'Bearer ${MY_MCP_TOKEN}' },
});
});

it('reports the pre-expansion literal configs alongside the resolved ones', () => {
write(
JSON.stringify({
mcpServers: {
http: {
httpUrl: 'https://example.test/mcp',
headers: { Authorization: 'Bearer ${MY_MCP_TOKEN}' },
},
},
}),
);
const { servers, literalServers } = loadProjectMcpServers(dir);
expect(servers['http']).toMatchObject({
headers: { Authorization: 'Bearer tok-from-process-env' },
});
expect(literalServers['http']).toMatchObject({
httpUrl: 'https://example.test/mcp',
headers: { Authorization: 'Bearer ${MY_MCP_TOKEN}' },
scope: 'project',
});
});

it('expands after Claude transport normalization (httpUrl carries the placeholder)', () => {
write(
JSON.stringify({
mcpServers: {
claudeHttp: {
type: 'http',
url: 'https://example.test/${MY_MCP_TOKEN}/mcp',
},
},
}),
);
const { servers, errors } = loadProjectMcpServers(dir);
expect(errors).toEqual([]);
expect(servers['claudeHttp']).toMatchObject({
httpUrl: 'https://example.test/tok-from-process-env/mcp',
scope: 'project',
});
});
});
});
Loading
Loading