Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: sanitize provider tool names (#14510)

YuTengjing38c92fa04a1f
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
index c347e8dfb66..1f19d7ae642 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -700,6 +700,60 @@ Document content here.
filteredToolCalls: 1,
});
});
+
+ it('should remove disabled tool calls after provider-safe name hashing', async () => {
+ const messages: UIChatMessage[] = [
+ {
+ content: 'Open the page',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ {
+ content: '',
+ createdAt: Date.now(),
+ id: 'msg-2',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'open_page',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: '@browser/use',
+ type: 'mcp',
+ },
+ ],
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ {
+ content: 'Opened the page.',
+ createdAt: Date.now(),
+ id: 'msg-3',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ];
+
+ const params = createBasicParams({
+ messages,
+ toolsConfig: {
+ disabledToolIdentifiers: ['@browser/use'],
+ tools: [],
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ expect(result.messages.some((m) => m.role === 'tool')).toBe(false);
+ expect(result.messages.some((m) => JSON.stringify(m).includes('MD5HASH_'))).toBe(false);
+ expect(result.metadata.disabledToolCallFilter).toEqual({
+ filteredAssistantMessages: 1,
+ filteredToolCalls: 1,
+ });
+ });
});
describe('Page Selections', () => {
diff --git a/packages/context-engine/src/engine/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.ts
index d71423d1414..c64f63bbc34 100644
--- a/packages/context-engine/src/engine/tools/ToolNameResolver.ts
+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts
@@ -7,6 +7,7 @@ import type { LobeChatPluginApi, LobeToolManifest } from './types';
// Tool naming constants
const PLUGIN_SCHEMA_SEPARATOR = '____';
const PLUGIN_SCHEMA_API_MD5_PREFIX = 'MD5HASH_';
+const TOOL_NAME_COMPONENT_PATTERN = /^[\w-]+$/;
/**
* Tool Name Resolver
@@ -21,6 +22,25 @@ export class ToolNameResolver {
return Md5.hashStr(name).toString().slice(0, 12);
}
+ private hashComponent(name: string): string {
+ return PLUGIN_SCHEMA_API_MD5_PREFIX + this.genHash(name);
+ }
+
+ /**
+ * Strict providers reject tool function names with non-ASCII characters,
+ * dots, slashes, spaces, or other punctuation. Hash invalid segments so the
+ * generated name stays provider-safe while `resolve()` can still recover the
+ * original value from the manifest.
+ *
+ * Example: `custom_mcp____中文API____mcp` is rejected, so the API segment
+ * becomes `MD5HASH_xxx` on the wire.
+ */
+ private normalizeComponent(name: string): string {
+ return name.length > 0 && !TOOL_NAME_COMPONENT_PATTERN.test(name)
+ ? this.hashComponent(name)
+ : name;
+ }
+
/**
* Generate tool calling name
* @param identifier - Plugin identifier
@@ -30,25 +50,29 @@ export class ToolNameResolver {
*/
generate(identifier: string, name: string, type: string = 'builtin'): string {
const pluginType =
- type && type !== 'builtin' && type !== 'default' ? `${PLUGIN_SCHEMA_SEPARATOR}${type}` : '';
+ type && type !== 'builtin' && type !== 'default'
+ ? `${PLUGIN_SCHEMA_SEPARATOR}${this.normalizeComponent(type)}`
+ : '';
+ let identifierName = this.normalizeComponent(identifier);
+ let apiName = this.normalizeComponent(name);
// Step 1: Try normal format
- let apiName = identifier + PLUGIN_SCHEMA_SEPARATOR + name + pluginType;
+ let toolName = identifierName + PLUGIN_SCHEMA_SEPARATOR + apiName + pluginType;
// OpenAI GPT function_call name can't be longer than 64 characters
// Step 2: If >= 64, hash the name part
- if (apiName.length >= 64) {
- const nameHash = PLUGIN_SCHEMA_API_MD5_PREFIX + this.genHash(name);
- apiName = identifier + PLUGIN_SCHEMA_SEPARATOR + nameHash + pluginType;
+ if (toolName.length >= 64) {
+ apiName = this.hashComponent(name);
+ toolName = identifierName + PLUGIN_SCHEMA_SEPARATOR + apiName + pluginType;
// Step 3: If still >= 64, also hash the identifier
- if (apiName.length >= 64) {
- const identifierHash = PLUGIN_SCHEMA_API_MD5_PREFIX + this.genHash(identifier);
- apiName = identifierHash + PLUGIN_SCHEMA_SEPARATOR + nameHash + pluginType;
+ if (toolName.length >= 64) {
+ identifierName = this.hashComponent(identifier);
+ toolName = identifierName + PLUGIN_SCHEMA_SEPARATOR + apiName + pluginType;
}
}
- return apiName;
+ return toolName;
}
/**
diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts
index d9e6902b2e4..d0be34a5340 100644
--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts
+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts
@@ -107,6 +107,30 @@ describe('ToolNameResolver', () => {
expect(result).toBe('plugin123____action456____type789');
});
+ it('should hash invalid api names so provider tool names stay valid', () => {
+ const result = resolver.generate('mcp-server', 'get.current/weather', 'mcp');
+
+ expect(result).toMatch(/^mcp-server____MD5HASH_[\da-f]+____mcp$/);
+ expect(result).toMatch(/^[\w-]+$/);
+ expect(result).not.toContain('get.current/weather');
+ });
+
+ it('should hash non-ASCII api names so provider tool names stay valid', () => {
+ const result = resolver.generate('custom_mcp_plugin', '中文API', 'mcp');
+
+ expect(result).toMatch(/^custom_mcp_plugin____MD5HASH_[\da-f]+____mcp$/);
+ expect(result).toMatch(/^[\w-]+$/);
+ expect(result).not.toContain('中文API');
+ });
+
+ it('should hash invalid identifiers so provider tool names stay valid', () => {
+ const result = resolver.generate('@browser/use', 'open_page', 'mcp');
+
+ expect(result).toMatch(/^MD5HASH_[\da-f]+____open_page____mcp$/);
+ expect(result).toMatch(/^[\w-]+$/);
+ expect(result).not.toContain('@browser/use');
+ });
+
it('should be consistent for same inputs', () => {
const result1 = resolver.generate('plugin', 'action', 'type');
const result2 = resolver.generate('plugin', 'action', 'type');
@@ -400,6 +424,76 @@ describe('ToolNameResolver', () => {
expect(result[0].apiName).toBe('MD5HASH_abc123def456');
});
+
+ it('should resolve apiName hashed because it contains provider-invalid characters', () => {
+ const identifier = 'mcp-server';
+ const apiName = 'get.current/weather';
+ const toolName = resolver.generate(identifier, apiName, 'mcp');
+
+ const result = resolver.resolve(
+ [
+ {
+ function: {
+ arguments: '{"location":"Shanghai"}',
+ name: toolName,
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ ],
+ {
+ [identifier]: {
+ api: [{ description: 'Get weather', name: apiName, parameters: {} }],
+ identifier,
+ meta: {},
+ type: 'mcp' as const,
+ },
+ },
+ );
+
+ expect(result[0]).toEqual({
+ apiName,
+ arguments: '{"location":"Shanghai"}',
+ id: 'call_1',
+ identifier,
+ type: 'mcp',
+ });
+ });
+
+ it('should resolve non-ASCII apiName hashed for provider-safe tool names', () => {
+ const identifier = 'custom_mcp_plugin';
+ const apiName = '中文API';
+ const toolName = resolver.generate(identifier, apiName, 'mcp');
+
+ const result = resolver.resolve(
+ [
+ {
+ function: {
+ arguments: '{"query":"最近工作压力好大"}',
+ name: toolName,
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ ],
+ {
+ [identifier]: {
+ api: [{ description: 'Chat with companion', name: apiName, parameters: {} }],
+ identifier,
+ meta: {},
+ type: 'mcp' as const,
+ },
+ },
+ );
+
+ expect(result[0]).toEqual({
+ apiName,
+ arguments: '{"query":"最近工作压力好大"}',
+ id: 'call_1',
+ identifier,
+ type: 'mcp',
+ });
+ });
});
describe('resolve - hashed identifier', () => {
@@ -464,6 +558,37 @@ describe('ToolNameResolver', () => {
expect(result[0].identifier).toBe('MD5HASH_abc123def456');
});
+
+ it('should resolve identifier hashed because it contains provider-invalid characters', () => {
+ const identifier = '@browser/use';
+ const apiName = 'open_page';
+ const toolName = resolver.generate(identifier, apiName, 'mcp');
+
+ const result = resolver.resolve(
+ [
+ {
+ function: {
+ arguments: '{}',
+ name: toolName,
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ ],
+ {
+ [identifier]: {
+ api: [{ description: 'Open page', name: apiName, parameters: {} }],
+ identifier,
+ meta: {},
+ type: 'mcp' as const,
+ },
+ },
+ );
+
+ expect(result[0].identifier).toBe(identifier);
+ expect(result[0].apiName).toBe(apiName);
+ expect(result[0].type).toBe('mcp');
+ });
});
describe('resolve - both identifier and apiName hashed', () => {
diff --git a/packages/context-engine/src/processors/DisabledToolCallFilter.ts b/packages/context-engine/src/processors/DisabledToolCallFilter.ts
index 004dcd27a82..3a821c13ecc 100644
--- a/packages/context-engine/src/processors/DisabledToolCallFilter.ts
+++ b/packages/context-engine/src/processors/DisabledToolCallFilter.ts
@@ -32,6 +32,20 @@ const isDisabledToolName = (name: string | undefined, disabledToolIdentifiers: S
return false;
};
+const getDisabledToolCallIds = (message: Message, disabledToolIdentifiers: Set<string>) => {
+ const ids = new Set<string>();
+
+ if (!Array.isArray(message.tools)) return ids;
+
+ for (const tool of message.tools) {
+ if (disabledToolIdentifiers.has(String(tool?.identifier ?? '')) && tool?.id) {
+ ids.add(String(tool.id));
+ }
+ }
+
+ return ids;
+};
+
/**
* Removes historical tool calls for tools that are not valid in the current runtime scope.
*
@@ -92,10 +106,13 @@ export class DisabledToolCallFilter extends BaseProcessor {
private filterAssistantMessage(message: Message, disabledToolIdentifiers: Set<string>): Message {
let nextMessage = message;
+ const disabledToolCallIds = getDisabledToolCallIds(message, disabledToolIdentifiers);
if (Array.isArray(message.tool_calls)) {
const toolCalls = message.tool_calls.filter(
- (toolCall) => !isDisabledToolName(toolCall?.function?.name, disabledToolIdentifiers),
+ (toolCall) =>
+ !disabledToolCallIds.has(String(toolCall?.id ?? '')) &&
+ !isDisabledToolName(toolCall?.function?.name, disabledToolIdentifiers),
);
if (toolCalls.length !== message.tool_calls.length) {