Skip to content

Commit 74703b6

Browse files
author
Bertan Ari
committed
feat(modes): add per-mode allowed MCP servers (allowlist)
Adds optional `allowedMcpServers: string[]` to ModeConfig. When defined, only listed MCP servers' schemas are injected into the system prompt and exposed as native tools, preventing context bloat in specialized modes. - Schema: packages/types ModeConfig + schemas/roomodes.json - Prompt: filter mcpHub.getServers() by allowlist in system.ts and native-tools/mcp_server.ts; wired via core/task/build-tools.ts - UI: new McpServerRestriction.tsx editor (cachedState + 150ms debounce, per AGENTS.md SettingsView pattern), integrated into ModesView for both edit and create flows - Tests: schema, system-prompt filtering, native-tool filtering, component behavior; vitest config + toolkit mock updates Ports upstream RooCodeInc/Roo-Code#12004 (fix from simurg79/Roo-Code#1).
1 parent f673043 commit 74703b6

13 files changed

Lines changed: 896 additions & 38 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { modeConfigSchema } from "../mode.js"
2+
3+
describe("modeConfigSchema allowedMcpServers", () => {
4+
const baseModeConfig = {
5+
slug: "test-mode",
6+
name: "Test Mode",
7+
roleDefinition: "A test mode",
8+
groups: ["read" as const],
9+
}
10+
11+
it("should accept valid allowedMcpServers array of strings", () => {
12+
const result = modeConfigSchema.safeParse({
13+
...baseModeConfig,
14+
allowedMcpServers: ["server1", "server2"],
15+
})
16+
expect(result.success).toBe(true)
17+
if (result.success) {
18+
expect(result.data.allowedMcpServers).toEqual(["server1", "server2"])
19+
}
20+
})
21+
22+
it("should accept missing/undefined allowedMcpServers", () => {
23+
const result = modeConfigSchema.safeParse(baseModeConfig)
24+
expect(result.success).toBe(true)
25+
if (result.success) {
26+
expect(result.data.allowedMcpServers).toBeUndefined()
27+
}
28+
})
29+
30+
it("should accept empty allowedMcpServers array", () => {
31+
const result = modeConfigSchema.safeParse({
32+
...baseModeConfig,
33+
allowedMcpServers: [],
34+
})
35+
expect(result.success).toBe(true)
36+
if (result.success) {
37+
expect(result.data.allowedMcpServers).toEqual([])
38+
}
39+
})
40+
41+
it("should reject non-string array items", () => {
42+
const result = modeConfigSchema.safeParse({
43+
...baseModeConfig,
44+
allowedMcpServers: [123, 456],
45+
})
46+
expect(result.success).toBe(false)
47+
})
48+
49+
it("should reject non-array value", () => {
50+
const result = modeConfigSchema.safeParse({
51+
...baseModeConfig,
52+
allowedMcpServers: "server1",
53+
})
54+
expect(result.success).toBe(false)
55+
})
56+
})

‎packages/types/src/mode.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ export const modeConfigSchema = z.object({
102102
customInstructions: z.string().optional(),
103103
groups: groupEntryArraySchema,
104104
source: z.enum(["global", "project"]).optional(),
105+
allowedMcpServers: z.array(z.string()).optional(),
105106
})
106107

107108
export type ModeConfig = z.infer<typeof modeConfigSchema>

‎schemas/roomodes.json‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,13 @@
8080
"required": ["relativePath"],
8181
"additionalProperties": false
8282
}
83+
},
84+
"allowedMcpServers": {
85+
"type": "array",
86+
"items": {
87+
"type": "string"
88+
},
89+
"description": "Optional list of MCP server names to include. When omitted, all servers are available. When set, only the listed servers are injected."
8390
}
8491
},
8592
"required": ["slug", "name", "roleDefinition", "groups"],

‎src/core/prompts/__tests__/system-prompt.spec.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,70 @@ describe("SYSTEM_PROMPT", () => {
575575
expect(prompt).toContain("OBJECTIVE")
576576
})
577577

578+
describe("allowedMcpServers filtering in system prompt", () => {
579+
it("should exclude MCP capability text when allowedMcpServers is empty array", async () => {
580+
mockMcpHub = createMockMcpHub(true)
581+
582+
const customModes: ModeConfig[] = [
583+
{
584+
slug: "filtered-mode",
585+
name: "Filtered Mode",
586+
roleDefinition: "A filtered mode",
587+
groups: ["read", "mcp"] as const,
588+
allowedMcpServers: [],
589+
},
590+
]
591+
592+
const prompt = await SYSTEM_PROMPT(
593+
mockContext,
594+
"/test/path",
595+
false,
596+
mockMcpHub, // mcpHub with servers
597+
undefined, // diffStrategy
598+
"filtered-mode", // mode
599+
undefined, // customModePrompts
600+
customModes, // customModes
601+
undefined, // globalCustomInstructions
602+
experiments,
603+
undefined, // language
604+
undefined, // rooIgnoreInstructions
605+
)
606+
607+
expect(prompt).not.toContain("MCP servers")
608+
})
609+
610+
it("should include MCP capability text when allowedMcpServers matches connected servers", async () => {
611+
mockMcpHub = createMockMcpHub(true) // has "test-server"
612+
613+
const customModes: ModeConfig[] = [
614+
{
615+
slug: "mcp-mode",
616+
name: "MCP Mode",
617+
roleDefinition: "A mode with MCP",
618+
groups: ["read", "mcp"] as const,
619+
allowedMcpServers: ["test-server"],
620+
},
621+
]
622+
623+
const prompt = await SYSTEM_PROMPT(
624+
mockContext,
625+
"/test/path",
626+
false,
627+
mockMcpHub,
628+
undefined,
629+
"mcp-mode",
630+
undefined,
631+
customModes,
632+
undefined,
633+
experiments,
634+
undefined,
635+
undefined,
636+
)
637+
638+
expect(prompt).toContain("MCP servers")
639+
})
640+
})
641+
578642
afterAll(() => {
579643
vi.restoreAllMocks()
580644
})

‎src/core/prompts/system.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,15 @@ async function generatePrompt(
6666

6767
// Check if MCP functionality should be included
6868
const hasMcpGroup = modeConfig.groups.some((groupEntry) => getGroupName(groupEntry) === "mcp")
69-
const hasMcpServers = mcpHub && mcpHub.getServers().length > 0
69+
const allowedMcpServers = modeConfig.allowedMcpServers
70+
71+
let hasMcpServers = false
72+
if (mcpHub) {
73+
const servers = allowedMcpServers
74+
? mcpHub.getServers().filter((s) => new Set(allowedMcpServers).has(s.name))
75+
: mcpHub.getServers()
76+
hasMcpServers = servers.length > 0
77+
}
7078
const shouldIncludeMcp = hasMcpGroup && hasMcpServers
7179

7280
const codeIndexManager = CodeIndexManager.getInstance(context, cwd)

‎src/core/prompts/tools/native-tools/__tests__/mcp_server.spec.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,53 @@ describe("getMcpServerTools", () => {
197197
})
198198
expect(getFunction(result[0]).parameters).not.toHaveProperty("required")
199199
})
200+
describe("allowedServers filtering", () => {
201+
it("should return all tools when allowedServers is undefined", () => {
202+
const server1 = createMockServer("server1", [createMockTool("tool1")])
203+
const server2 = createMockServer("server2", [createMockTool("tool2")])
204+
const mockHub = createMockMcpHub([server1, server2])
205+
206+
const result = getMcpServerTools(mockHub as McpHub, undefined)
207+
208+
expect(result).toHaveLength(2)
209+
const toolNames = result.map((t) => getFunction(t).name)
210+
expect(toolNames).toContain("mcp--server1--tool1")
211+
expect(toolNames).toContain("mcp--server2--tool2")
212+
})
213+
214+
it("should return only tools from allowed servers when allowedServers is provided", () => {
215+
const server1 = createMockServer("server1", [createMockTool("tool1")])
216+
const server2 = createMockServer("server2", [createMockTool("tool2")])
217+
const server3 = createMockServer("server3", [createMockTool("tool3")])
218+
const mockHub = createMockMcpHub([server1, server2, server3])
219+
220+
const result = getMcpServerTools(mockHub as McpHub, ["server1", "server3"])
221+
222+
expect(result).toHaveLength(2)
223+
const toolNames = result.map((t) => getFunction(t).name)
224+
expect(toolNames).toContain("mcp--server1--tool1")
225+
expect(toolNames).toContain("mcp--server3--tool3")
226+
expect(toolNames).not.toContain("mcp--server2--tool2")
227+
})
228+
229+
it("should return empty array when allowedServers is empty array", () => {
230+
const server1 = createMockServer("server1", [createMockTool("tool1")])
231+
const server2 = createMockServer("server2", [createMockTool("tool2")])
232+
const mockHub = createMockMcpHub([server1, server2])
233+
234+
const result = getMcpServerTools(mockHub as McpHub, [])
235+
236+
expect(result).toEqual([])
237+
})
238+
239+
it("should ignore server names in allowedServers not found in hub", () => {
240+
const server1 = createMockServer("server1", [createMockTool("tool1")])
241+
const mockHub = createMockMcpHub([server1])
242+
243+
const result = getMcpServerTools(mockHub as McpHub, ["server1", "nonexistent-server"])
244+
245+
expect(result).toHaveLength(1)
246+
expect(getFunction(result[0]).name).toBe("mcp--server1--tool1")
247+
})
248+
})
200249
})

‎src/core/prompts/tools/native-tools/mcp_server.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,18 @@ import { normalizeToolSchema, type JsonSchema } from "../../../../utils/json-sch
1111
* @param mcpHub The McpHub instance containing connected servers.
1212
* @returns An array of OpenAI.Chat.ChatCompletionTool definitions.
1313
*/
14-
export function getMcpServerTools(mcpHub?: McpHub): OpenAI.Chat.ChatCompletionTool[] {
14+
export function getMcpServerTools(mcpHub?: McpHub, allowedServers?: string[]): OpenAI.Chat.ChatCompletionTool[] {
1515
if (!mcpHub) {
1616
return []
1717
}
1818

19-
const servers = mcpHub.getServers()
19+
let servers = mcpHub.getServers()
20+
21+
// Filter servers by allowlist if provided
22+
if (allowedServers) {
23+
const allowSet = new Set(allowedServers)
24+
servers = servers.filter((s) => allowSet.has(s.name))
25+
}
2026
const tools: OpenAI.Chat.ChatCompletionTool[] = []
2127
// Track seen tool names to prevent duplicates (e.g., when same server exists in both global and project configs)
2228
const seenToolNames = new Set<string>()

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { customToolRegistry, formatNative } from "@roo-code/core"
77

88
import type { ClineProvider } from "../webview/ClineProvider"
99
import { getRooDirectoriesForCwd } from "../../services/roo-config/index.js"
10+
import { getModeBySlug, defaultModeSlug } from "../../shared/modes"
1011

1112
import { getNativeTools, getMcpServerTools } from "../prompts/tools/native-tools"
1213
import {
@@ -124,8 +125,12 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO
124125
mcpHub,
125126
)
126127

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

131136
// Add custom tools if they are available and the experiment is enabled.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import React from "react"
2+
3+
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} />
6+
{children}
7+
</label>
8+
)
9+
10+
export const VSCodeRadioGroup = ({ children, ...props }: any) => <div {...props}>{children}</div>
11+
12+
export const VSCodeRadio = ({ children, value, ...props }: any) => (
13+
<label>
14+
<input type="radio" value={value} {...props} />
15+
{children}
16+
</label>
17+
)
18+
19+
export const VSCodeTextArea = ({ value, onChange, "data-testid": dataTestId, ...props }: any) => (
20+
<textarea
21+
data-testid={dataTestId}
22+
value={value ?? ""}
23+
onChange={(e: any) => onChange?.(e)}
24+
// Bridge: the real toolkit dispatches a CustomEvent("change") with the
25+
// new value carried on `event.detail.target.value`. Existing tests rely
26+
// on this. Forward such events to the React onChange handler so the
27+
// component sees the synthesized detail.
28+
ref={(el: HTMLTextAreaElement | null) => {
29+
if (!el) return
30+
if ((el as any).__vscodeChangeBridge) return
31+
;(el as any).__vscodeChangeBridge = true
32+
el.addEventListener("change", (e: Event) => {
33+
const ce = e as CustomEvent
34+
if (ce.detail && (ce.detail as any).target) {
35+
onChange?.(ce as unknown as React.ChangeEvent<HTMLTextAreaElement>)
36+
}
37+
})
38+
}}
39+
{...props}
40+
/>
41+
)
42+
43+
export const VSCodeLink = ({ children, href, ...props }: any) => (
44+
<a href={href} {...props}>
45+
{children}
46+
</a>
47+
)
48+
49+
export const VSCodeTextField = ({ value, onInput, "data-testid": dataTestId, children, ...props }: any) => (
50+
<div>
51+
<input data-testid={dataTestId} value={value} onInput={onInput} {...props} />
52+
{children}
53+
</div>
54+
)

0 commit comments

Comments
 (0)