Skip to content

Commit 6eca4bb

Browse files
committed
fix(core): resolve MCP tool __ FQN validation discrepancy inside subagents
1 parent 45a4a70 commit 6eca4bb

6 files changed

Lines changed: 132 additions & 64 deletions

File tree

packages/core/src/agents/agentLoader.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,11 @@ const localAgentSchema = z
107107
display_name: z.string().optional(),
108108
tools: z
109109
.array(
110-
z.string().refine((val) => isValidToolName(val), {
111-
message: 'Invalid tool name',
112-
}),
110+
z
111+
.string()
112+
.refine((val) => isValidToolName(val, { allowWildcards: true }), {
113+
message: 'Invalid tool name',
114+
}),
113115
)
114116
.optional(),
115117
model: z.string().optional(),

packages/core/src/agents/local-executor.ts

Lines changed: 55 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,13 @@ import {
1717
type Schema,
1818
} from '@google/genai';
1919
import { ToolRegistry } from '../tools/tool-registry.js';
20-
import { DiscoveredMCPTool } from '../tools/mcp-tool.js';
20+
import { type AnyDeclarativeTool } from '../tools/tools.js';
21+
import {
22+
DiscoveredMCPTool,
23+
isMcpToolName,
24+
parseMcpToolName,
25+
MCP_TOOL_PREFIX,
26+
} from '../tools/mcp-tool.js';
2127
import { CompressionStatus } from '../core/turn.js';
2228
import { type ToolCallRequestInfo } from '../scheduler/types.js';
2329
import { type Message } from '../confirmation-bus/types.js';
@@ -146,28 +152,62 @@ export class LocalAgentExecutor<TOutput extends z.ZodTypeAny> {
146152
context.config.getAgentRegistry().getAllAgentNames(),
147153
);
148154

149-
const registerToolByName = (toolName: string) => {
155+
const registerToolInstance = (tool: AnyDeclarativeTool) => {
150156
// Check if the tool is a subagent to prevent recursion.
151157
// We do not allow agents to call other agents.
152-
if (allAgentNames.has(toolName)) {
158+
if (allAgentNames.has(tool.name)) {
153159
debugLogger.warn(
154-
`[LocalAgentExecutor] Skipping subagent tool '${toolName}' for agent '${definition.name}' to prevent recursion.`,
160+
`[LocalAgentExecutor] Skipping subagent tool '${tool.name}' for agent '${definition.name}' to prevent recursion.`,
155161
);
156162
return;
157163
}
158164

165+
if (tool instanceof DiscoveredMCPTool) {
166+
// Subagents MUST use fully qualified names for MCP tools to ensure
167+
// unambiguous tool calls and to comply with policy requirements.
168+
// We automatically "upgrade" any MCP tool to its qualified version.
169+
agentToolRegistry.registerTool(tool.asFullyQualifiedTool());
170+
} else {
171+
agentToolRegistry.registerTool(tool);
172+
}
173+
};
174+
175+
const registerToolByName = (toolName: string) => {
176+
// Handle global wildcard
177+
if (toolName === '*') {
178+
for (const tool of parentToolRegistry.getAllTools()) {
179+
registerToolInstance(tool);
180+
}
181+
return;
182+
}
183+
184+
// Handle MCP wildcards
185+
if (isMcpToolName(toolName)) {
186+
if (toolName === `${MCP_TOOL_PREFIX}*`) {
187+
for (const tool of parentToolRegistry.getAllTools()) {
188+
if (tool instanceof DiscoveredMCPTool) {
189+
registerToolInstance(tool);
190+
}
191+
}
192+
return;
193+
}
194+
195+
const parsed = parseMcpToolName(toolName);
196+
if (parsed.serverName && parsed.toolName === '*') {
197+
for (const tool of parentToolRegistry.getToolsByServer(
198+
parsed.serverName,
199+
)) {
200+
registerToolInstance(tool);
201+
}
202+
return;
203+
}
204+
}
205+
159206
// If the tool is referenced by name, retrieve it from the parent
160207
// registry and register it with the agent's isolated registry.
161208
const tool = parentToolRegistry.getTool(toolName);
162209
if (tool) {
163-
if (tool instanceof DiscoveredMCPTool) {
164-
// Subagents MUST use fully qualified names for MCP tools to ensure
165-
// unambiguous tool calls and to comply with policy requirements.
166-
// We automatically "upgrade" any MCP tool to its qualified version.
167-
agentToolRegistry.registerTool(tool.asFullyQualifiedTool());
168-
} else {
169-
agentToolRegistry.registerTool(tool);
170-
}
210+
registerToolInstance(tool);
171211
}
172212
};
173213

@@ -1174,10 +1214,9 @@ export class LocalAgentExecutor<TOutput extends z.ZodTypeAny> {
11741214
const { toolConfig, outputConfig } = this.definition;
11751215

11761216
if (toolConfig) {
1177-
const toolNamesToLoad: string[] = [];
11781217
for (const toolRef of toolConfig.tools) {
11791218
if (typeof toolRef === 'string') {
1180-
toolNamesToLoad.push(toolRef);
1219+
// The names were already expanded and loaded into the registry during creation.
11811220
} else if (typeof toolRef === 'object' && 'schema' in toolRef) {
11821221
// Tool instance with an explicit schema property.
11831222
toolsList.push(toolRef.schema);
@@ -1186,10 +1225,8 @@ export class LocalAgentExecutor<TOutput extends z.ZodTypeAny> {
11861225
toolsList.push(toolRef);
11871226
}
11881227
}
1189-
// Add schemas from tools that were registered by name.
1190-
toolsList.push(
1191-
...this.toolRegistry.getFunctionDeclarationsFiltered(toolNamesToLoad),
1192-
);
1228+
// Add schemas from tools that were explicitly registered by name or wildcard.
1229+
toolsList.push(...this.toolRegistry.getFunctionDeclarations());
11931230
}
11941231

11951232
// Always inject complete_task.

packages/core/src/tools/mcp-tool.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ export function parseMcpToolName(name: string): {
5858
// Remove the prefix
5959
const withoutPrefix = name.slice(MCP_TOOL_PREFIX.length);
6060
// The first segment is the server name, the rest is the tool name
61+
// Must be strictly `server_tool` where neither are empty
6162
const match = withoutPrefix.match(/^([^_]+)_(.+)$/);
6263
if (match) {
6364
return {

packages/core/src/tools/tool-names.test.ts

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ vi.mock('./tool-names.js', async (importOriginal) => {
2525
...actual,
2626
TOOL_LEGACY_ALIASES: mockedAliases,
2727
isValidToolName: vi.fn().mockImplementation((name: string, options) => {
28-
if (mockedAliases[name]) return true;
28+
if (Object.prototype.hasOwnProperty.call(mockedAliases, name))
29+
return true;
2930
return actual.isValidToolName(name, options);
3031
}),
3132
getToolAliases: vi.fn().mockImplementation((name: string) => {
@@ -55,11 +56,9 @@ describe('tool-names', () => {
5556
expect(isValidToolName(`${DISCOVERED_TOOL_PREFIX}my_tool`)).toBe(true);
5657
});
5758

58-
it('should validate MCP tool names (server__tool)', () => {
59-
expect(isValidToolName('server__tool')).toBe(true);
60-
expect(isValidToolName('my-server__my-tool')).toBe(true);
61-
expect(isValidToolName('my.server__my:tool')).toBe(true);
62-
expect(isValidToolName('my-server...truncated__tool')).toBe(true);
59+
it('should validate modern MCP FQNs (mcp_server_tool)', () => {
60+
expect(isValidToolName('mcp_server_tool')).toBe(true);
61+
expect(isValidToolName('mcp_my-server_my-tool')).toBe(true);
6362
});
6463

6564
it('should validate legacy tool aliases', async () => {
@@ -69,28 +68,33 @@ describe('tool-names', () => {
6968
}
7069
});
7170

72-
it('should reject invalid tool names', () => {
73-
expect(isValidToolName('')).toBe(false);
74-
expect(isValidToolName('invalid-name')).toBe(false);
75-
expect(isValidToolName('server__')).toBe(false);
76-
expect(isValidToolName('__tool')).toBe(false);
77-
expect(isValidToolName('server__tool__extra')).toBe(false);
71+
it('should return false for invalid tool names', () => {
72+
expect(isValidToolName('invalid-tool-name')).toBe(false);
73+
expect(isValidToolName('mcp_server')).toBe(false);
74+
expect(isValidToolName('mcp__tool')).toBe(false);
75+
expect(isValidToolName('mcp_invalid server_tool')).toBe(false);
76+
expect(isValidToolName('mcp_server_invalid tool')).toBe(false);
77+
expect(isValidToolName('mcp_server_')).toBe(false);
7878
});
7979

8080
it('should handle wildcards when allowed', () => {
8181
// Default: not allowed
8282
expect(isValidToolName('*')).toBe(false);
83-
expect(isValidToolName('server__*')).toBe(false);
83+
expect(isValidToolName('mcp_*')).toBe(false);
84+
expect(isValidToolName('mcp_server_*')).toBe(false);
8485

8586
// Explicitly allowed
8687
expect(isValidToolName('*', { allowWildcards: true })).toBe(true);
87-
expect(isValidToolName('server__*', { allowWildcards: true })).toBe(true);
88+
expect(isValidToolName('mcp_*', { allowWildcards: true })).toBe(true);
89+
expect(isValidToolName('mcp_server_*', { allowWildcards: true })).toBe(
90+
true,
91+
);
8892

8993
// Invalid wildcards
90-
expect(isValidToolName('__*', { allowWildcards: true })).toBe(false);
91-
expect(isValidToolName('server__tool*', { allowWildcards: true })).toBe(
92-
false,
93-
);
94+
expect(isValidToolName('mcp__*', { allowWildcards: true })).toBe(false);
95+
expect(
96+
isValidToolName('mcp_server_tool*', { allowWildcards: true }),
97+
).toBe(false);
9498
});
9599
});
96100

packages/core/src/tools/tool-names.ts

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,12 @@ export const DISCOVERED_TOOL_PREFIX = 'discovered_tool_';
221221
/**
222222
* List of all built-in tool names.
223223
*/
224+
import {
225+
isMcpToolName,
226+
parseMcpToolName,
227+
MCP_TOOL_PREFIX,
228+
} from './mcp-tool.js';
229+
224230
export const ALL_BUILTIN_TOOL_NAMES = [
225231
GLOB_TOOL_NAME,
226232
WRITE_TODOS_TOOL_NAME,
@@ -290,25 +296,44 @@ export function isValidToolName(
290296
return true;
291297
}
292298

293-
// MCP tools (format: server__tool)
294-
if (name.includes('__')) {
295-
const parts = name.split('__');
296-
if (parts.length !== 2 || parts[0].length === 0 || parts[1].length === 0) {
299+
// Handle standard MCP FQNs (mcp_server_tool or wildcards mcp_*, mcp_server_*)
300+
if (isMcpToolName(name)) {
301+
// Global wildcard: mcp_*
302+
if (name === `${MCP_TOOL_PREFIX}*` && options.allowWildcards) {
303+
return true;
304+
}
305+
306+
// Explicitly reject names with empty server component (e.g. mcp__tool)
307+
if (name.startsWith(`${MCP_TOOL_PREFIX}_`)) {
297308
return false;
298309
}
299310

300-
const server = parts[0];
301-
const tool = parts[1];
311+
const parsed = parseMcpToolName(name);
312+
// Ensure that both components are populated. parseMcpToolName splits at the second _,
313+
// so `mcp__tool` has serverName="", toolName="tool"
314+
if (parsed.serverName && parsed.toolName) {
315+
// Basic slug validation for server and tool names.
316+
// We allow dots (.) and colons (:) as they are valid in function names and
317+
// used for truncation markers.
318+
const slugRegex = /^[a-z0-9_.:-]+$/i;
319+
320+
if (!slugRegex.test(parsed.serverName)) {
321+
return false;
322+
}
323+
324+
if (parsed.toolName === '*') {
325+
return options.allowWildcards === true;
326+
}
327+
328+
// A tool name consisting only of underscores is invalid.
329+
if (/^_*$/.test(parsed.toolName)) {
330+
return false;
331+
}
302332

303-
if (tool === '*') {
304-
return !!options.allowWildcards;
333+
return slugRegex.test(parsed.toolName);
305334
}
306335

307-
// Basic slug validation for server and tool names.
308-
// We allow dots (.) and colons (:) as they are valid in function names and
309-
// used for truncation markers.
310-
const slugRegex = /^[a-z0-9_.:-]+$/i;
311-
return slugRegex.test(server) && slugRegex.test(tool);
336+
return false;
312337
}
313338

314339
return false;

packages/core/src/tools/tool-registry.ts

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,17 @@ export class ToolRegistry {
594594
for (const name of toolNames) {
595595
const tool = this.getTool(name);
596596
if (tool) {
597-
declarations.push(tool.getSchema(modelId));
597+
let schema = tool.getSchema(modelId);
598+
599+
// Ensure the schema name matches the qualified name for MCP tools
600+
if (tool instanceof DiscoveredMCPTool) {
601+
schema = {
602+
...schema,
603+
name: tool.getFullyQualifiedName(),
604+
};
605+
}
606+
607+
declarations.push(schema);
598608
}
599609
}
600610
return declarations;
@@ -670,17 +680,6 @@ export class ToolRegistry {
670680
}
671681
}
672682

673-
if (!tool && name.includes('__')) {
674-
for (const t of this.allKnownTools.values()) {
675-
if (t instanceof DiscoveredMCPTool) {
676-
if (t.getFullyQualifiedName() === name) {
677-
tool = t;
678-
break;
679-
}
680-
}
681-
}
682-
}
683-
684683
if (tool && this.isActiveTool(tool)) {
685684
return tool;
686685
}

0 commit comments

Comments
 (0)