Skip to content

Commit fd2a0fc

Browse files
author
Bertan Ari
committed
fix(modes): address PR review on per-mode MCP allowlist (backend)
- Filter MCP servers passed to the capabilities section so disallowed servers are not described in the system prompt (review: getCapabilitiesSection) - Hoist allow-list Set construction out of the server .filter() in system.ts - Add invocation-time MCP server guard (use_mcp_tool / access_mcp_resource) rejecting calls to servers not in the mode's allowedMcpServers, as a second defense layer beyond tool listing/filtering - Add unit tests for the invocation-time guard (mcpServerRestriction.spec.ts)
1 parent a8d424b commit fd2a0fc

6 files changed

Lines changed: 340 additions & 12 deletions

File tree

‎src/core/prompts/sections/capabilities.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,43 @@
11
import { McpHub } from "../../../services/mcp/McpHub"
22

3-
export function getCapabilitiesSection(cwd: string, mcpHub?: McpHub): string {
3+
/**
4+
* Builds the CAPABILITIES section of the system prompt.
5+
*
6+
* The MCP availability line is only emitted when at least one MCP server is actually
7+
* exposed to the current mode. When `allowedMcpServers` is provided, the hub's server
8+
* list is filtered by that allowlist BEFORE deciding whether to advertise MCP, so the
9+
* capability text matches the per-mode tool exposure:
10+
* - `undefined` allowlist → all connected servers count (backward compatible)
11+
* - empty `[]` allowlist → no servers count ⇒ MCP line omitted
12+
* - populated allowlist → only listed servers count
13+
*
14+
* @param cwd Current working directory used in the prompt text.
15+
* @param mcpHub Optional MCP hub. When omitted, the MCP line is never emitted.
16+
* @param allowedMcpServers Optional per-mode allowlist of MCP server names. When provided,
17+
* the hub's servers are filtered to this set before determining MCP availability.
18+
*/
19+
export function getCapabilitiesSection(cwd: string, mcpHub?: McpHub, allowedMcpServers?: string[]): string {
20+
// Determine whether any MCP server is actually available to the current mode.
21+
// Filtering the hub's servers by the allowlist (when provided) keeps the capability
22+
// text consistent with the tools that are exposed for the mode.
23+
let hasMcpServers = false
24+
if (mcpHub) {
25+
let servers = mcpHub.getServers()
26+
if (allowedMcpServers) {
27+
const allowSet = new Set(allowedMcpServers)
28+
servers = servers.filter((server) => allowSet.has(server.name))
29+
}
30+
hasMcpServers = servers.length > 0
31+
}
32+
433
return `====
534
635
CAPABILITIES
736
837
- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search, read and write files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
938
- When the user initially gives you a task, a recursive list of all filepaths in the current workspace directory ('${cwd}') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current workspace directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
1039
- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.${
11-
mcpHub
40+
hasMcpServers
1241
? `
1342
- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
1443
`

‎src/core/prompts/system.ts‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,13 @@ async function generatePrompt(
6868
const hasMcpGroup = modeConfig.groups.some((groupEntry) => getGroupName(groupEntry) === "mcp")
6969
const allowedMcpServers = modeConfig.allowedMcpServers
7070

71+
// Hoist the allowlist Set once (matches the sibling call sites, e.g. mcp_server.ts) instead
72+
// of constructing a new Set on every `.filter` iteration.
73+
const allowSet = allowedMcpServers ? new Set(allowedMcpServers) : undefined
74+
7175
let hasMcpServers = false
7276
if (mcpHub) {
73-
const servers = allowedMcpServers
74-
? mcpHub.getServers().filter((s) => new Set(allowedMcpServers).has(s.name))
75-
: mcpHub.getServers()
77+
const servers = allowSet ? mcpHub.getServers().filter((s) => allowSet.has(s.name)) : mcpHub.getServers()
7678
hasMcpServers = servers.length > 0
7779
}
7880
const shouldIncludeMcp = hasMcpGroup && hasMcpServers
@@ -99,13 +101,13 @@ ${getSharedToolUseSection()}${toolsCatalog}
99101
${getToolUseGuidelinesSection()}
100102
101103
${
102-
// `shouldIncludeMcp` already accounts for the mode's allowedMcpServers allowlist
103-
// (see hasMcpServers above), so a mode that restricts MCP servers down to none will
104-
// pass `undefined` here and omit the MCP capabilities line entirely. The capabilities
105-
// section only emits a generic MCP availability statement (it does not enumerate
106-
// individual servers), so forwarding the hub when at least one allowed server exists
107-
// is consistent with the per-mode tool exposure.
108-
getCapabilitiesSection(cwd, shouldIncludeMcp ? mcpHub : undefined)
104+
// Forward the hub only when the mode actually exposes the MCP group, and pass the per-mode
105+
// allowlist through so the capabilities section filters servers using the SAME convention as
106+
// the tool-listing layer (a single source of truth for which servers are visible). This keeps
107+
// the capability text consistent with the tools exposed in mixed cases (e.g. one allowed +
108+
// one disallowed server), preventing the section from advertising MCP based on a disallowed
109+
// server. `shouldIncludeMcp` is still used to short-circuit when no allowed server exists.
110+
getCapabilitiesSection(cwd, hasMcpGroup ? mcpHub : undefined, allowedMcpServers)
109111
}
110112
111113
${modesSection}

‎src/core/tools/UseMcpToolTool.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type { ToolUse } from "../../shared/tools"
77
import { toolNamesMatch } from "../../utils/mcp-name"
88

99
import { BaseTool, ToolCallbacks } from "./BaseTool"
10+
import { ensureMcpServerAllowed } from "./mcpServerRestriction"
1011

1112
interface UseMcpToolParams {
1213
server_name: string
@@ -44,6 +45,20 @@ export class UseMcpToolTool extends BaseTool<"use_mcp_tool"> {
4445
return
4546
}
4647

48+
// Execution-time defense: reject invocation of a server not permitted by the mode's
49+
// allowedMcpServers allowlist, even if the model referenced it from history. This runs
50+
// before approval/execution so a disallowed server can never be reached.
51+
const serverAllowed = await ensureMcpServerAllowed(
52+
task,
53+
"use_mcp_tool",
54+
serverName,
55+
pushToolResult,
56+
formatResponse.toolError,
57+
)
58+
if (!serverAllowed) {
59+
return
60+
}
61+
4762
// Use the resolved tool name (original name from the server) for MCP calls
4863
// This handles cases where models mangle hyphens to underscores
4964
const resolvedToolName = toolValidation.resolvedToolName ?? toolName
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
// npx vitest run core/tools/__tests__/mcpServerRestriction.spec.ts
2+
3+
import type { Task } from "../../task/Task"
4+
import { isMcpServerAllowed, getAllowedMcpServersForTask, ensureMcpServerAllowed } from "../mcpServerRestriction"
5+
6+
vi.mock("../../../shared/modes", async (importOriginal) => {
7+
const actual = await importOriginal<typeof import("../../../shared/modes")>()
8+
return {
9+
...actual,
10+
defaultModeSlug: "code",
11+
getModeBySlug: vi.fn(),
12+
}
13+
})
14+
15+
import { getModeBySlug } from "../../../shared/modes"
16+
17+
const toolError = (error: string) => `ERR:${error}`
18+
19+
function makeTask(state: any): Task {
20+
return {
21+
providerRef: {
22+
deref: () => ({
23+
getState: vi.fn().mockResolvedValue(state),
24+
}),
25+
},
26+
consecutiveMistakeCount: 0,
27+
didToolFailInCurrentTurn: false,
28+
recordToolError: vi.fn(),
29+
} as unknown as Task
30+
}
31+
32+
describe("isMcpServerAllowed", () => {
33+
it("allows all servers when allowlist is undefined (backward compatible)", () => {
34+
expect(isMcpServerAllowed("any-server", undefined)).toBe(true)
35+
})
36+
37+
it("rejects all servers when allowlist is empty", () => {
38+
expect(isMcpServerAllowed("any-server", [])).toBe(false)
39+
})
40+
41+
it("allows a server present in a populated allowlist", () => {
42+
expect(isMcpServerAllowed("allowed", ["allowed", "other"])).toBe(true)
43+
})
44+
45+
it("rejects a server absent from a populated allowlist", () => {
46+
expect(isMcpServerAllowed("disallowed", ["allowed", "other"])).toBe(false)
47+
})
48+
})
49+
50+
describe("getAllowedMcpServersForTask", () => {
51+
beforeEach(() => {
52+
vi.mocked(getModeBySlug).mockReset()
53+
})
54+
55+
it("returns the mode's allowedMcpServers when defined", async () => {
56+
vi.mocked(getModeBySlug).mockReturnValue({
57+
slug: "code",
58+
name: "Code",
59+
roleDefinition: "",
60+
groups: ["mcp"],
61+
allowedMcpServers: ["srv-a"],
62+
} as any)
63+
const task = makeTask({ mode: "code", customModes: [] })
64+
await expect(getAllowedMcpServersForTask(task)).resolves.toEqual(["srv-a"])
65+
})
66+
67+
it("returns undefined when the mode does not restrict servers", async () => {
68+
vi.mocked(getModeBySlug).mockReturnValue({
69+
slug: "code",
70+
name: "Code",
71+
roleDefinition: "",
72+
groups: ["mcp"],
73+
} as any)
74+
const task = makeTask({ mode: "code", customModes: [] })
75+
await expect(getAllowedMcpServersForTask(task)).resolves.toBeUndefined()
76+
})
77+
78+
it("returns undefined when the mode cannot be resolved", async () => {
79+
vi.mocked(getModeBySlug).mockReturnValue(undefined as any)
80+
const task = makeTask({ mode: "missing", customModes: [] })
81+
await expect(getAllowedMcpServersForTask(task)).resolves.toBeUndefined()
82+
})
83+
})
84+
85+
describe("ensureMcpServerAllowed", () => {
86+
beforeEach(() => {
87+
vi.mocked(getModeBySlug).mockReset()
88+
})
89+
90+
function mockModeAllowlist(allowedMcpServers?: string[]) {
91+
vi.mocked(getModeBySlug).mockReturnValue({
92+
slug: "code",
93+
name: "Code",
94+
roleDefinition: "",
95+
groups: ["mcp"],
96+
...(allowedMcpServers !== undefined ? { allowedMcpServers } : {}),
97+
} as any)
98+
}
99+
100+
it("allows invocation when allowlist is undefined (allows all)", async () => {
101+
mockModeAllowlist(undefined)
102+
const task = makeTask({ mode: "code", customModes: [] })
103+
const pushToolResult = vi.fn()
104+
105+
const result = await ensureMcpServerAllowed(task, "use_mcp_tool", "anything", pushToolResult, toolError)
106+
107+
expect(result).toBe(true)
108+
expect(pushToolResult).not.toHaveBeenCalled()
109+
expect(task.recordToolError).not.toHaveBeenCalled()
110+
})
111+
112+
it("allows invocation when server is in the populated allowlist", async () => {
113+
mockModeAllowlist(["allowed-server"])
114+
const task = makeTask({ mode: "code", customModes: [] })
115+
const pushToolResult = vi.fn()
116+
117+
const result = await ensureMcpServerAllowed(task, "use_mcp_tool", "allowed-server", pushToolResult, toolError)
118+
119+
expect(result).toBe(true)
120+
expect(pushToolResult).not.toHaveBeenCalled()
121+
})
122+
123+
it("rejects invocation when server is NOT in the populated allowlist", async () => {
124+
mockModeAllowlist(["allowed-server"])
125+
const task = makeTask({ mode: "code", customModes: [] })
126+
const pushToolResult = vi.fn()
127+
128+
const result = await ensureMcpServerAllowed(
129+
task,
130+
"use_mcp_tool",
131+
"disallowed-server",
132+
pushToolResult,
133+
toolError,
134+
)
135+
136+
expect(result).toBe(false)
137+
expect(task.consecutiveMistakeCount).toBe(1)
138+
expect(task.didToolFailInCurrentTurn).toBe(true)
139+
expect(task.recordToolError).toHaveBeenCalledWith("use_mcp_tool")
140+
expect(pushToolResult).toHaveBeenCalledTimes(1)
141+
const message = (pushToolResult as any).mock.calls[0][0] as string
142+
expect(message).toContain("disallowed-server")
143+
expect(message).toContain("not allowed")
144+
expect(message).toContain("allowed-server")
145+
})
146+
147+
it("rejects all invocations when allowlist is empty", async () => {
148+
mockModeAllowlist([])
149+
const task = makeTask({ mode: "code", customModes: [] })
150+
const pushToolResult = vi.fn()
151+
152+
const result = await ensureMcpServerAllowed(
153+
task,
154+
"access_mcp_resource",
155+
"any-server",
156+
pushToolResult,
157+
toolError,
158+
)
159+
160+
expect(result).toBe(false)
161+
expect(task.recordToolError).toHaveBeenCalledWith("access_mcp_resource")
162+
const message = (pushToolResult as any).mock.calls[0][0] as string
163+
expect(message).toContain("No MCP servers are allowed")
164+
})
165+
})

‎src/core/tools/accessMcpResourceTool.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { Task } from "../task/Task"
55
import { formatResponse } from "../prompts/responses"
66

77
import { BaseTool, ToolCallbacks } from "./BaseTool"
8+
import { ensureMcpServerAllowed } from "./mcpServerRestriction"
89

910
interface AccessMcpResourceParams {
1011
server_name: string
@@ -33,6 +34,19 @@ export class AccessMcpResourceTool extends BaseTool<"access_mcp_resource"> {
3334
return
3435
}
3536

37+
// Execution-time defense: reject access to a server not permitted by the mode's
38+
// allowedMcpServers allowlist, even if the model referenced it from history.
39+
const serverAllowed = await ensureMcpServerAllowed(
40+
task,
41+
"access_mcp_resource",
42+
server_name,
43+
pushToolResult,
44+
formatResponse.toolError,
45+
)
46+
if (!serverAllowed) {
47+
return
48+
}
49+
3650
task.consecutiveMistakeCount = 0
3751

3852
const completeMessage = JSON.stringify({

0 commit comments

Comments
 (0)