Skip to content

Commit 778d95d

Browse files
authored
Merge pull request #7 from simurg79/fix/per-mode-mcp-server-restrictions-review
fix: honor per-mode MCP allowlist for access_mcp_resource and prevent debounced flush from clobbering concurrent mode edits
2 parents 1036aa4 + 1a5018b commit 778d95d

6 files changed

Lines changed: 205 additions & 28 deletions

File tree

‎src/core/prompts/tools/__tests__/filter-tools-for-mode.spec.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,61 @@ describe("filterNativeToolsForMode - disabledTools", () => {
8989
expect(resultNames).not.toContain("edit")
9090
})
9191
})
92+
93+
describe("filterNativeToolsForMode - access_mcp_resource allowlist", () => {
94+
const nativeTools: OpenAI.Chat.ChatCompletionTool[] = [makeTool("read_file"), makeTool("access_mcp_resource")]
95+
96+
// Minimal McpHub stub exposing only getServers(), which is all the resource
97+
// availability check uses.
98+
function makeMcpHub(servers: Array<{ name: string; resources?: unknown[] }>): any {
99+
return {
100+
getServers: () => servers,
101+
}
102+
}
103+
104+
it("keeps access_mcp_resource when an allowed server has resources", () => {
105+
const mcpHub = makeMcpHub([{ name: "allowed-server", resources: [{ uri: "res://x" }] }])
106+
107+
const result = filterNativeToolsForMode(nativeTools, "code", undefined, undefined, undefined, {}, mcpHub, [
108+
"allowed-server",
109+
])
110+
111+
const resultNames = result.map((t) => (t as any).function.name)
112+
expect(resultNames).toContain("access_mcp_resource")
113+
})
114+
115+
it("removes access_mcp_resource when only a disallowed server has resources", () => {
116+
// The server with resources is NOT in the allowlist, so the restricted
117+
// mode must not retain access_mcp_resource.
118+
const mcpHub = makeMcpHub([
119+
{ name: "allowed-server", resources: [] },
120+
{ name: "blocked-server", resources: [{ uri: "res://secret" }] },
121+
])
122+
123+
const result = filterNativeToolsForMode(nativeTools, "code", undefined, undefined, undefined, {}, mcpHub, [
124+
"allowed-server",
125+
])
126+
127+
const resultNames = result.map((t) => (t as any).function.name)
128+
expect(resultNames).not.toContain("access_mcp_resource")
129+
expect(resultNames).toContain("read_file")
130+
})
131+
132+
it("considers all servers when no allowlist is provided (unrestricted mode)", () => {
133+
const mcpHub = makeMcpHub([{ name: "any-server", resources: [{ uri: "res://y" }] }])
134+
135+
const result = filterNativeToolsForMode(nativeTools, "code", undefined, undefined, undefined, {}, mcpHub)
136+
137+
const resultNames = result.map((t) => (t as any).function.name)
138+
expect(resultNames).toContain("access_mcp_resource")
139+
})
140+
141+
it("removes access_mcp_resource when the allowlist is empty", () => {
142+
const mcpHub = makeMcpHub([{ name: "some-server", resources: [{ uri: "res://z" }] }])
143+
144+
const result = filterNativeToolsForMode(nativeTools, "code", undefined, undefined, undefined, {}, mcpHub, [])
145+
146+
const resultNames = result.map((t) => (t as any).function.name)
147+
expect(resultNames).not.toContain("access_mcp_resource")
148+
})
149+
})

‎src/core/prompts/tools/filter-tools-for-mode.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,9 @@ export function applyModelToolCustomization(
220220
* @param codeIndexManager - Code index manager for codebase_search feature check
221221
* @param settings - Additional settings for tool filtering (includes modelInfo for model-specific customization)
222222
* @param mcpHub - MCP hub for checking available resources
223+
* @param allowedMcpServers - Optional allowlist of MCP server names for the current mode. When
224+
* provided, the resource-availability check only considers servers in this list, so a mode that
225+
* restricts MCP servers cannot retain `access_mcp_resource` based on resources from disallowed servers.
223226
* @returns Filtered array of tools allowed for the mode
224227
*/
225228
export function filterNativeToolsForMode(
@@ -230,6 +233,7 @@ export function filterNativeToolsForMode(
230233
codeIndexManager?: CodeIndexManager,
231234
settings?: Record<string, any>,
232235
mcpHub?: McpHub,
236+
allowedMcpServers?: string[],
233237
): OpenAI.Chat.ChatCompletionTool[] {
234238
// Get mode configuration and all tools for this mode
235239
const modeSlug = mode ?? defaultModeSlug
@@ -301,8 +305,10 @@ export function filterNativeToolsForMode(
301305
}
302306
}
303307

304-
// Conditionally exclude access_mcp_resource if MCP is not enabled or there are no resources
305-
if (!mcpHub || !hasAnyMcpResources(mcpHub)) {
308+
// Conditionally exclude access_mcp_resource if MCP is not enabled or there are no resources.
309+
// When the mode restricts MCP servers via allowedMcpServers, only resources from allowed
310+
// servers count — otherwise a restricted mode could still read resources from disallowed servers.
311+
if (!mcpHub || !hasAnyMcpResources(mcpHub, allowedMcpServers)) {
306312
allowedToolNames.delete("access_mcp_resource")
307313
}
308314

@@ -330,10 +336,18 @@ export function filterNativeToolsForMode(
330336
}
331337

332338
/**
333-
* Helper function to check if any MCP server has resources available
339+
* Helper function to check if any MCP server has resources available.
340+
*
341+
* When `allowedServers` is provided, only servers whose name is in the allowlist are considered.
342+
* This keeps the `access_mcp_resource` availability check consistent with the mode's MCP server
343+
* allowlist so a restricted mode cannot retain the tool based on resources from disallowed servers.
334344
*/
335-
function hasAnyMcpResources(mcpHub: McpHub): boolean {
336-
const servers = mcpHub.getServers()
345+
function hasAnyMcpResources(mcpHub: McpHub, allowedServers?: string[]): boolean {
346+
let servers = mcpHub.getServers()
347+
if (allowedServers) {
348+
const allowSet = new Set(allowedServers)
349+
servers = servers.filter((server) => allowSet.has(server.name))
350+
}
337351
return servers.some((server) => server.resources && server.resources.length > 0)
338352
}
339353

‎src/core/task/build-tools.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,13 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO
114114
supportsImages,
115115
})
116116

117-
// Filter native tools based on mode restrictions.
117+
// Resolve mode config to get allowedMcpServers for MCP server filtering.
118+
const modeConfig = getModeBySlug(mode ?? defaultModeSlug, customModes)
119+
const allowedMcpServers = modeConfig?.allowedMcpServers
120+
121+
// Filter native tools based on mode restrictions. The allowlist is forwarded so the
122+
// access_mcp_resource availability check only considers resources from allowed servers;
123+
// otherwise a restricted mode could still read resources from disallowed servers.
118124
const filteredNativeTools = filterNativeToolsForMode(
119125
nativeTools,
120126
mode,
@@ -123,12 +129,9 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO
123129
codeIndexManager,
124130
filterSettings,
125131
mcpHub,
132+
allowedMcpServers,
126133
)
127134

128-
// Resolve mode config to get allowedMcpServers for MCP server filtering.
129-
const modeConfig = getModeBySlug(mode ?? defaultModeSlug, customModes)
130-
const allowedMcpServers = modeConfig?.allowedMcpServers
131-
132135
// Filter MCP tools based on mode restrictions.
133136
const mcpTools = getMcpServerTools(mcpHub, allowedMcpServers)
134137
const filteredMcpTools = filterMcpToolsForMode(mcpTools, mode, customModes, experiments)

‎webview-ui/src/__mocks__/@vscode/webview-ui-toolkit/react.tsx‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import React from "react"
22

33
export const VSCodeCheckbox = ({ children, onChange, checked, "data-testid": dataTestId, ...props }: any) => (
4-
<label data-testid={dataTestId}>
5-
<input type="checkbox" checked={checked} onChange={(e: any) => onChange?.(e)} {...props} />
4+
<label>
5+
<input
6+
type="checkbox"
7+
data-testid={dataTestId}
8+
checked={checked}
9+
onChange={(e: any) => onChange?.(e)}
10+
{...props}
11+
/>
612
{children}
713
</label>
814
)
@@ -52,3 +58,31 @@ export const VSCodeTextField = ({ value, onInput, "data-testid": dataTestId, chi
5258
{children}
5359
</div>
5460
)
61+
62+
export const VSCodeButton = ({ children, onClick, "data-testid": dataTestId, ...props }: any) => (
63+
<button data-testid={dataTestId} onClick={onClick} {...props}>
64+
{children}
65+
</button>
66+
)
67+
68+
export const VSCodeBadge = ({ children, ...props }: any) => <span {...props}>{children}</span>
69+
70+
export const VSCodeProgressRing = (props: any) => <div role="progressbar" {...props} />
71+
72+
export const VSCodeDropdown = ({ children, value, onChange, "data-testid": dataTestId, ...props }: any) => (
73+
<select data-testid={dataTestId} value={value} onChange={(e: any) => onChange?.(e)} {...props}>
74+
{children}
75+
</select>
76+
)
77+
78+
export const VSCodeOption = ({ children, value, ...props }: any) => (
79+
<option value={value} {...props}>
80+
{children}
81+
</option>
82+
)
83+
84+
export const VSCodePanels = ({ children, ...props }: any) => <div {...props}>{children}</div>
85+
86+
export const VSCodePanelTab = ({ children, ...props }: any) => <div {...props}>{children}</div>
87+
88+
export const VSCodePanelView = ({ children, ...props }: any) => <div {...props}>{children}</div>

‎webview-ui/src/components/modes/McpServerRestriction.tsx‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,18 @@ const McpServerRestriction: React.FC<McpServerRestrictionProps> = ({ customMode,
6161
// Reseed-on-mode-switch is keyed on slug; track the last slug we saw.
6262
const lastSlugRef = useRef(customMode.slug)
6363

64+
// Always hold the latest `customMode` and `onCommit` so the debounced flush
65+
// merges `allowedMcpServers` into the freshest mode snapshot instead of the
66+
// stale one captured when the timeout was scheduled. Without this, an edit to
67+
// another field of the same mode within the 150 ms debounce window would be
68+
// clobbered when this flush spreads an outdated `customMode`.
69+
const latestCustomModeRef = useRef(customMode)
70+
const latestOnCommitRef = useRef(onCommit)
71+
useEffect(() => {
72+
latestCustomModeRef.current = customMode
73+
latestOnCommitRef.current = onCommit
74+
})
75+
6476
// Reseed when the user switches to a different mode.
6577
useEffect(() => {
6678
if (lastSlugRef.current !== customMode.slug) {
@@ -98,10 +110,13 @@ const McpServerRestriction: React.FC<McpServerRestrictionProps> = ({ customMode,
98110
}
99111
const handle = setTimeout(() => {
100112
lastFlushedRef.current = cachedAllowedMcpServers
101-
onCommit(customMode.slug, {
102-
...customMode,
113+
// Merge into the freshest mode snapshot (via refs) so a concurrent edit to
114+
// another field within the debounce window is not clobbered by a stale spread.
115+
const latestCustomMode = latestCustomModeRef.current
116+
latestOnCommitRef.current(latestCustomMode.slug, {
117+
...latestCustomMode,
103118
allowedMcpServers: cachedAllowedMcpServers,
104-
source: customMode.source || "global",
119+
source: latestCustomMode.source || "global",
105120
})
106121
}, 150)
107122
return () => clearTimeout(handle)

‎webview-ui/src/components/modes/__tests__/McpServerRestriction.spec.tsx‎

Lines changed: 66 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,9 @@ describe("MCP Server Restriction UI", () => {
138138
expect(screen.getByTestId("restrict-mcp-servers-toggle")).toBeInTheDocument()
139139
})
140140

141-
const toggleLabel = screen.getByTestId("restrict-mcp-servers-toggle")
142-
const checkbox = toggleLabel.querySelector("input[type='checkbox']") as HTMLInputElement
141+
// The toolkit mock forwards `data-testid` to the inner
142+
// <input type="checkbox">, so getByTestId resolves to the checkbox input directly.
143+
const checkbox = screen.getByTestId("restrict-mcp-servers-toggle") as HTMLInputElement
143144
fireEvent.click(checkbox)
144145

145146
await waitFor(() => {
@@ -165,8 +166,8 @@ describe("MCP Server Restriction UI", () => {
165166
expect(screen.getByTestId("restrict-mcp-servers-toggle")).toBeInTheDocument()
166167
})
167168

168-
const toggleLabel = screen.getByTestId("restrict-mcp-servers-toggle")
169-
const checkbox = toggleLabel.querySelector("input[type='checkbox']") as HTMLInputElement
169+
// data-testid is forwarded to the inner checkbox input by the toolkit mock.
170+
const checkbox = screen.getByTestId("restrict-mcp-servers-toggle") as HTMLInputElement
170171
fireEvent.click(checkbox)
171172

172173
await waitFor(() => {
@@ -222,17 +223,16 @@ describe("McpServerRestriction subcomponent — flicker regressions", () => {
222223
const onCommit = vitest.fn()
223224
render(<McpServerRestriction customMode={baseCustomMode} mcpServers={mcpServers} onCommit={onCommit} />)
224225

225-
const toggleLabel = screen.getByTestId("restrict-mcp-servers-toggle")
226-
const checkbox = toggleLabel.querySelector("input[type='checkbox']") as HTMLInputElement
226+
// The toolkit mock forwards `data-testid` to the inner checkbox input,
227+
// so getByTestId resolves to the <input type="checkbox"> directly.
228+
const checkbox = screen.getByTestId("restrict-mcp-servers-toggle") as HTMLInputElement
227229
expect(checkbox.checked).toBe(false)
228230
expect(screen.queryByTestId("mcp-server-list")).not.toBeInTheDocument()
229231

230232
fireEvent.click(checkbox)
231233

232234
// Synchronous post-click assertions — no advanceTimers, no host echo.
233-
const checkboxAfter = screen
234-
.getByTestId("restrict-mcp-servers-toggle")
235-
.querySelector("input[type='checkbox']") as HTMLInputElement
235+
const checkboxAfter = screen.getByTestId("restrict-mcp-servers-toggle") as HTMLInputElement
236236
expect(checkboxAfter.checked).toBe(true)
237237
expect(screen.getByTestId("mcp-server-list")).toBeInTheDocument()
238238
// Debounced flush has not fired yet.
@@ -314,10 +314,10 @@ describe("McpServerRestriction subcomponent — flicker regressions", () => {
314314
const initialCommits = onRender.mock.calls.length
315315
expect(initialCommits).toBeGreaterThan(0)
316316

317-
// (a) Click — exactly 1 additional commit.
318-
const serverCheckbox = screen
319-
.getByTestId("mcp-server-checkbox-server-a")
320-
.querySelector("input[type='checkbox']") as HTMLInputElement
317+
// (a) Click — exactly 1 additional commit. The toolkit mock forwards
318+
// `data-testid` to the inner checkbox input, so getByTestId resolves
319+
// to the <input type="checkbox"> directly.
320+
const serverCheckbox = screen.getByTestId("mcp-server-checkbox-server-a") as HTMLInputElement
321321
fireEvent.click(serverCheckbox)
322322
const afterClickCommits = onRender.mock.calls.length
323323
expect(afterClickCommits - initialCommits).toBe(1)
@@ -340,4 +340,57 @@ describe("McpServerRestriction subcomponent — flicker regressions", () => {
340340
vitest.useRealTimers()
341341
}
342342
})
343+
344+
/**
345+
* Test 4 — Concurrent-edit safety: the debounced flush must not clobber a
346+
* newer edit to another field of the same mode made within the 150 ms
347+
* window.
348+
*
349+
* Repro: the user toggles a per-server checkbox (schedules the debounced
350+
* flush), then within the debounce window another field of the same mode
351+
* (e.g. `name`) changes — the parent re-renders the component with an
352+
* updated `customMode`. Before the fix, the flush spread the STALE
353+
* `customMode` captured when the timeout was scheduled, sending the old
354+
* `name` back to the host and clobbering the newer value.
355+
*
356+
* After the fix, the flush merges `allowedMcpServers` into the freshest
357+
* `customMode` (via a ref), so the committed snapshot carries the updated
358+
* `name`.
359+
*/
360+
it("Test 4: debounced flush merges into the latest customMode, not the stale snapshot", () => {
361+
vitest.useFakeTimers()
362+
try {
363+
const onCommit = vitest.fn()
364+
const customMode = { ...baseCustomMode, name: "Old Name", allowedMcpServers: [] as string[] }
365+
366+
const { rerender } = render(
367+
<McpServerRestriction customMode={customMode} mcpServers={mcpServers} onCommit={onCommit} />,
368+
)
369+
370+
// User edits the allowlist (schedules the debounced flush). The toolkit
371+
// mock forwards `data-testid` to the inner checkbox input, so getByTestId
372+
// resolves to the <input type="checkbox"> directly.
373+
const serverCheckbox = screen.getByTestId("mcp-server-checkbox-server-a") as HTMLInputElement
374+
fireEvent.click(serverCheckbox)
375+
expect(onCommit).not.toHaveBeenCalled() // debounce hasn't fired yet
376+
377+
// Within the debounce window, another field of the same mode changes.
378+
const updatedCustomMode = { ...customMode, name: "New Name" }
379+
rerender(
380+
<McpServerRestriction customMode={updatedCustomMode} mcpServers={mcpServers} onCommit={onCommit} />,
381+
)
382+
383+
// Let the 150 ms debounce fire.
384+
vitest.advanceTimersByTime(200)
385+
386+
expect(onCommit).toHaveBeenCalledTimes(1)
387+
const [, committedConfig] = onCommit.mock.calls[0]
388+
// The newer field value must be preserved (not clobbered by the stale snapshot).
389+
expect(committedConfig.name).toBe("New Name")
390+
// And the user's allowlist edit must still be present.
391+
expect(committedConfig.allowedMcpServers).toEqual(["server-a"])
392+
} finally {
393+
vitest.useRealTimers()
394+
}
395+
})
343396
})

0 commit comments

Comments
 (0)