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(tools): make TOOL_NAME_MAX_LENGTH=0 actually disable tool-name compression (#17530)

LiJiana6a2642008fd
diff --git a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
index 306709b0d28..d7db6fcf225 100644
--- a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
+++ b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
interface MockGlobalConfigOptions {
agentGatewayUrl?: string;
enableAgentGateway?: boolean;
+ toolNameMaxLengthEnv?: string;
}
const mockGlobalConfigDependencies = (
@@ -80,7 +81,7 @@ const mockGlobalConfigDependencies = (
}));
vi.doMock('@/envs/tools', () => ({
- toolsEnv: {},
+ toolsEnv: { TOOL_NAME_MAX_LENGTH: options.toolNameMaxLengthEnv },
}));
vi.doMock('@/libs/better-auth/utils/server', () => ({
@@ -196,4 +197,42 @@ describe('getServerGlobalConfig', () => {
enableGatewayMode: false,
});
});
+
+ // The client-driven chat path builds tool names in the browser, so `0`
+ // (tool-name compression off) only takes effect if the server ships the value
+ // with the global config.
+ it('should expose TOOL_NAME_MAX_LENGTH to the client, including 0', async () => {
+ await expect(loadServerConfig(false, { toolNameMaxLengthEnv: '0' })).resolves.toMatchObject({
+ toolNameMaxLength: 0,
+ });
+
+ await expect(loadServerConfig(false, { toolNameMaxLengthEnv: '30' })).resolves.toMatchObject({
+ toolNameMaxLength: 30,
+ });
+
+ await expect(loadServerConfig(false)).resolves.toMatchObject({
+ toolNameMaxLength: undefined,
+ });
+ });
+
+ // The value shipped to the client must be parsed exactly like the resolver
+ // parses `process.env` on the server — same env value, same tool names on both
+ // sides — and a typo must never take the whole global config down.
+ it('should parse TOOL_NAME_MAX_LENGTH like the resolver, falling back instead of throwing', async () => {
+ const cases: [string, number | undefined][] = [
+ ['64', 64],
+ ['1e2', 1], // parseInt semantics, not Number()
+ ['2048', 2048], // no upper bound
+ [' ', undefined], // not `0`
+ ['-5', undefined],
+ ['abc', undefined],
+ ['', undefined],
+ ];
+
+ for (const [raw, expected] of cases) {
+ await expect(loadServerConfig(false, { toolNameMaxLengthEnv: raw })).resolves.toMatchObject({
+ toolNameMaxLength: expected,
+ });
+ }
+ });
});
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index 856bf3104b1..637061741e8 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -1,4 +1,5 @@
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
+import { parseToolNameMaxLength } from '@lobechat/const/plugin';
import { ModelProvider } from 'model-bank';
import { composioEnv } from '@/config/composio';
@@ -139,6 +140,12 @@ export const getServerGlobalConfig = async () => {
telemetry: {
langfuse: langfuseEnv.ENABLE_LANGFUSE,
},
+ // The client-driven chat path generates tool names in the browser, so the
+ // server-only `TOOL_NAME_MAX_LENGTH` has to travel with the config for `0`
+ // (compression off) to have any effect outside gateway mode. Parsed with the
+ // resolver's own function so both sides read the raw value identically —
+ // unset/invalid stays `undefined`, i.e. the resolver's default 64.
+ toolNameMaxLength: parseToolNameMaxLength(toolsEnv.TOOL_NAME_MAX_LENGTH),
};
return config;
diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdx
index 41db97ba9e0..895426ea761 100644
--- a/docs/self-hosting/environment-variables/basic.mdx
+++ b/docs/self-hosting/environment-variables/basic.mdx
@@ -255,6 +255,14 @@ This environment variable allows administrators to customize the default image g
## Plugin Service
+### `TOOL_NAME_MAX_LENGTH`
+
+- Type: Optional
+- Description: The length at which a function-call tool name is compressed into an opaque `MD5HASH_…` name. OpenAI caps function names at 64 characters, but providers without that limit only pay the readability cost, so the threshold is configurable. Set it to `0` to disable length-based compression entirely and keep full, readable tool names. Names containing characters providers reject (non-ASCII, dots, spaces…) are still hashed regardless of this setting.
+- Default: `64`
+- Example: `0`
+- Note: an unset, invalid, or negative value falls back to the default.
+
### `PLUGINS_INDEX_URL`
- Type: Optional
diff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
index 6ff7c193d8b..74bf3279dc6 100644
--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
@@ -251,6 +251,14 @@ VISUAL_UNDERSTANDING_MODEL=gemini-2.5-flash
## 插件服务
+### `TOOL_NAME_MAX_LENGTH`
+
+- 类型:可选
+- 描述:函数调用工具名超过该长度后会被压缩为不可读的 `MD5HASH_…`。OpenAI 限制函数名不超过 64 字符,而没有该限制的模型只会白白损失可读性,因此该阈值可配置。设为 `0` 可完全关闭基于长度的压缩,保留完整可读的工具名。包含服务商不接受字符(非 ASCII、点、空格等)的名称仍会被哈希,不受该配置影响。
+- 默认值:`64`
+- 示例:`0`
+- 说明:未设置、非法或负数时回退为默认值。
+
### `PLUGINS_INDEX_URL`
- 类型:可选
diff --git a/packages/const/package.json b/packages/const/package.json
index 09641cd2827..cca88bc86bb 100644
--- a/packages/const/package.json
+++ b/packages/const/package.json
@@ -7,6 +7,7 @@
"./currency": "./src/currency.ts",
"./desktopGlobalShortcuts": "./src/desktopGlobalShortcuts.ts",
"./hotkeys": "./src/hotkeys.ts",
+ "./plugin": "./src/plugin.ts",
"./rbac": "./src/rbac.ts",
"./url": "./src/url.ts",
"./verify": "./src/verify.ts",
diff --git a/packages/const/src/plugin.ts b/packages/const/src/plugin.ts
index ff44ce5e00b..08f5129dc89 100644
--- a/packages/const/src/plugin.ts
+++ b/packages/const/src/plugin.ts
@@ -1,6 +1,28 @@
export const PLUGIN_SCHEMA_SEPARATOR = '____';
export const PLUGIN_SCHEMA_API_MD5_PREFIX = 'MD5HASH_';
+/**
+ * Canonical parse for a raw `TOOL_NAME_MAX_LENGTH` value — the length at which a
+ * function-call tool name is compressed into an opaque `MD5HASH_…` name, `0`
+ * turning that compression off.
+ *
+ * Returns `undefined` for unset / unparseable / negative input, meaning "not
+ * configured": callers fall back to the default rather than failing, because a
+ * typo in this var must never take a deployment down.
+ *
+ * Lives here, in a leaf module, because the var is read from two sides:
+ * `ToolNameResolver` reads `process.env` directly on the server, while the app
+ * ships the value to the browser with the global server config (the
+ * client-driven chat path generates tool names where `process.env` isn't
+ * visible). Parsing it with two different rule sets would let one env value mean
+ * two different things, and the same tool could get different names on each side.
+ */
+export const parseToolNameMaxLength = (raw: string | undefined): number | undefined => {
+ if (raw === undefined || raw === '') return undefined;
+ const parsed = Number.parseInt(raw, 10);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
+};
+
export const ARTIFACT_TAG = 'lobeArtifact';
export const ARTIFACT_THINKING_TAG = 'lobeThinking';
export const MENTION_TAG = 'mention';
diff --git a/packages/context-engine/package.json b/packages/context-engine/package.json
index 7ef8125751d..d6f37687f6e 100644
--- a/packages/context-engine/package.json
+++ b/packages/context-engine/package.json
@@ -18,6 +18,7 @@
"test:update": "vitest -u"
},
"dependencies": {
+ "@lobechat/const": "workspace:*",
"@lobechat/database": "workspace:*",
"@lobechat/prompts": "workspace:*",
"@lobechat/utils": "workspace:*",
diff --git a/packages/context-engine/src/engine/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.ts
index 93a3b29d6ca..a8c6b7b0556 100644
--- a/packages/context-engine/src/engine/tools/ToolNameResolver.ts
+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts
@@ -1,3 +1,4 @@
+import { parseToolNameMaxLength } from '@lobechat/const/plugin';
import { Md5 } from 'ts-md5';
import type { ChatToolPayload, MessageToolCall } from '@/types/index';
@@ -26,9 +27,7 @@ const DEFAULT_TOOL_NAME_MAX_LENGTH = 64;
const readEnvMaxLength = (): number => {
try {
const raw = typeof process === 'undefined' ? undefined : process.env?.TOOL_NAME_MAX_LENGTH;
- if (raw === undefined || raw === '') return DEFAULT_TOOL_NAME_MAX_LENGTH;
- const parsed = Number.parseInt(raw, 10);
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_TOOL_NAME_MAX_LENGTH;
+ return parseToolNameMaxLength(raw) ?? DEFAULT_TOOL_NAME_MAX_LENGTH;
} catch {
return DEFAULT_TOOL_NAME_MAX_LENGTH;
}
diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.ts
index 0d2d81e0f0a..a578122676d 100644
--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.ts
+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.ts
@@ -1,3 +1,4 @@
+import { parseToolNameMaxLength } from '@lobechat/const/plugin';
import { afterEach, describe, expect, it } from 'vitest';
import { getToolNameMaxLength, setToolNameMaxLength, ToolNameResolver } from '../ToolNameResolver';
@@ -66,6 +67,25 @@ describe('configurable tool-name max length', () => {
expect(getToolNameMaxLength()).toBe(64);
});
+ // Hosts that read the var through their own env layer (and ship it to the
+ // browser, where `process.env` isn't visible) must reuse this parse — the same
+ // env value has to mean the same thing wherever a name is generated.
+ it('parses raw env values leniently, never throwing on a typo', () => {
+ expect(parseToolNameMaxLength('0')).toBe(0);
+ expect(parseToolNameMaxLength('64')).toBe(64);
+ // No upper bound: an absurd value just means "never compress".
+ expect(parseToolNameMaxLength('2048')).toBe(2048);
+ // parseInt semantics, deliberately not `Number()` (which would give 100).
+ expect(parseToolNameMaxLength('1e2')).toBe(1);
+ // Unparseable / out-of-range input reads as "not configured" — the caller
+ // falls back to the default rather than failing.
+ expect(parseToolNameMaxLength(' ')).toBeUndefined();
+ expect(parseToolNameMaxLength('-5')).toBeUndefined();
+ expect(parseToolNameMaxLength('abc')).toBeUndefined();
+ expect(parseToolNameMaxLength('')).toBeUndefined();
+ expect(parseToolNameMaxLength(undefined)).toBeUndefined();
+ });
+
it('still roundtrips through resolve when compression is disabled', () => {
setToolNameMaxLength(0);
const toolName = resolver.generate(longIdentifier, longApiName, 'mcp');
diff --git a/packages/env/src/tools.ts b/packages/env/src/tools.ts
index 2c59913977d..f72b1c09760 100644
--- a/packages/env/src/tools.ts
+++ b/packages/env/src/tools.ts
@@ -16,6 +16,7 @@ export const getToolsConfig = () => {
JINA_USE_CN_DOMAINS: process.env.JINA_USE_CN_DOMAINS,
SEARCH_PROVIDERS: process.env.SEARCH_PROVIDERS,
SEARXNG_URL: process.env.SEARXNG_URL,
+ TOOL_NAME_MAX_LENGTH: process.env.TOOL_NAME_MAX_LENGTH,
VISUAL_UNDERSTANDING_MODEL: process.env.VISUAL_UNDERSTANDING_MODEL,
VISUAL_UNDERSTANDING_PROVIDER: process.env.VISUAL_UNDERSTANDING_PROVIDER,
},
@@ -27,6 +28,20 @@ export const getToolsConfig = () => {
JINA_USE_CN_DOMAINS: z.enum(['true', 'false']).optional(),
SEARCH_PROVIDERS: z.string().optional(),
SEARXNG_URL: z.string().url().optional(),
+ /**
+ * Length at which a function-call tool name is compressed to an opaque
+ * `MD5HASH_…` (OpenAI caps function names at 64). `0` disables
+ * length-based compression entirely, keeping full readable tool names for
+ * deployments whose models have no such limit. Defaults to 64.
+ *
+ * Deliberately kept as a raw string: `parseToolNameMaxLength`
+ * (`@lobechat/const/plugin`) owns the parse, because `ToolNameResolver`
+ * also reads this var straight from `process.env` on the server. Coercing
+ * it here with different rules would let one env value mean two different
+ * things — and would turn a typo into a thrown validation error that takes
+ * the whole server config down, instead of falling back to the default.
+ */
+ TOOL_NAME_MAX_LENGTH: z.string().optional(),
VISUAL_UNDERSTANDING_MODEL: z.string().optional(),
VISUAL_UNDERSTANDING_PROVIDER: z.string().optional(),
},
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 35b49c6b837..d70c2f3c019 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -115,6 +115,15 @@ export interface GlobalServerConfig {
telemetry: {
langfuse?: boolean;
};
+ /**
+ * `TOOL_NAME_MAX_LENGTH`: the length at which a function-call tool name gets
+ * compressed to an opaque `MD5HASH_…`, `0` disabling that compression.
+ * Exposed to the client because the client-driven chat path builds the tool
+ * payload in the browser, where the server env isn't visible — without this
+ * the var would only take effect in gateway (server-run) mode.
+ * Undefined means "not configured": the default (64) applies.
+ */
+ toolNameMaxLength?: number;
visualUnderstanding?: VisualUnderstandingConfig;
}
diff --git a/src/helpers/applyToolNameMaxLength.test.ts b/src/helpers/applyToolNameMaxLength.test.ts
new file mode 100644
index 00000000000..4735e202713
--- /dev/null
+++ b/src/helpers/applyToolNameMaxLength.test.ts
@@ -0,0 +1,43 @@
+import { getToolNameMaxLength, setToolNameMaxLength } from '@lobechat/context-engine';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { applyToolNameMaxLength } from './applyToolNameMaxLength';
+
+let mockStoreState: { serverConfig?: { toolNameMaxLength?: number } } | undefined;
+
+vi.mock('@/store/serverConfig', () => ({
+ getServerConfigStoreState: () => mockStoreState,
+}));
+
+afterEach(() => {
+ setToolNameMaxLength(undefined);
+ mockStoreState = undefined;
+});
+
+describe('applyToolNameMaxLength', () => {
+ it('applies the server-resolved value, including 0', () => {
+ mockStoreState = { serverConfig: { toolNameMaxLength: 0 } };
+ applyToolNameMaxLength();
+ expect(getToolNameMaxLength()).toBe(0);
+
+ mockStoreState = { serverConfig: { toolNameMaxLength: 30 } };
+ applyToolNameMaxLength();
+ expect(getToolNameMaxLength()).toBe(30);
+ });
+
+ it('falls back to the default when the deployment did not configure it', () => {
+ mockStoreState = { serverConfig: {} };
+ applyToolNameMaxLength();
+ expect(getToolNameMaxLength()).toBe(64);
+ });
+
+ it('leaves an applied value alone while the store does not exist yet', () => {
+ mockStoreState = { serverConfig: { toolNameMaxLength: 0 } };
+ applyToolNameMaxLength();
+
+ // No store (e.g. called outside the app shell) must not reset to 64.
+ mockStoreState = undefined;
+ applyToolNameMaxLength();
+ expect(getToolNameMaxLength()).toBe(0);
+ });
+});
diff --git a/src/helpers/applyToolNameMaxLength.ts b/src/helpers/applyToolNameMaxLength.ts
new file mode 100644
index 00000000000..0113a7e4977
--- /dev/null
+++ b/src/helpers/applyToolNameMaxLength.ts
@@ -0,0 +1,26 @@
+import { setToolNameMaxLength } from '@lobechat/context-engine';
+
+import { getServerConfigStoreState } from '@/store/serverConfig';
+
+/**
+ * Apply the deployment's `TOOL_NAME_MAX_LENGTH` before generating tool names.
+ *
+ * The var is a server env, but this app also generates tool names in the browser
+ * (the client-driven chat path builds the tool payload, and mention hydration
+ * writes tool names into the system prompt), where `process.env` isn't visible —
+ * so the resolved value travels with the global server config and is pushed into
+ * the context-engine module here, the client mirror of what the server does at
+ * `createServerToolsEngine`.
+ *
+ * Deliberately called from the sites that generate names rather than once at
+ * config load: the server config store is created on every page, including the
+ * lightweight auth / popup shells, and importing the context engine there would
+ * drag its whole module graph into those bundles.
+ *
+ * Idempotent. Does nothing until the store exists, so an already-applied value
+ * is never reset back to the default.
+ */
+export const applyToolNameMaxLength = () => {
+ const state = getServerConfigStoreState();
+ if (state) setToolNameMaxLength(state.serverConfig?.toolNameMaxLength);
+};
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index 8843ad23d83..b05f78f37a2 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -138,6 +138,12 @@ vi.mock('@/store/tool/selectors', () => ({
},
}));
+let mockServerConfig: { toolNameMaxLength?: number } = {};
+
+vi.mock('@/store/serverConfig', () => ({
+ getServerConfigStoreState: () => ({ serverConfig: mockServerConfig }),
+}));
+
let mockIsCanUseFC = true;
vi.mock('../isCanUseFC', () => ({
@@ -207,6 +213,54 @@ describe('toolEngineering', () => {
mockIsCanUseFC = true;
mockCurrentChatConfig = {};
mockImageOutputSupport = false;
+ mockServerConfig = {};
+ });
+
+ // `TOOL_NAME_MAX_LENGTH` is a server env, but this path generates tool names in
+ // the browser — the value has to arrive via the server config for `0` to
+ // actually turn the MD5 compression off here.
+ describe('tool name compression', () => {
+ const longNamedPlugin = {
+ api: [
+ {
+ description: 'Search documents',
+ name: 'searchDocumentsInWorkspace',
+ parameters: { properties: {}, required: [], type: 'object' },
+ },
+ ],
+ identifier: 'my-notion-mcp-connector-with-a-long-identifier',
+ meta: { avatar: '📓', title: 'Notion' },
+ type: 'default',
+ } as unknown as ToolManifest;
+
+ const generateLongToolName = () => {
+ mockInstalledPluginManifestList = () => [longNamedPlugin];
+ const toolsEngine = createToolsEngine();
+
+ return toolsEngine.generateTools({
+ model: 'gpt-4',
+ provider: 'openai',
+ toolIds: [longNamedPlugin.identifier],
+ })![0].function.name;
+ };
+
+ it('should compress names past the default 64 chars', () => {
+ expect(generateLongToolName()).toContain('MD5HASH_');
+ });
+
+ it('should keep the full name when the server config sets 0', () => {
+ mockServerConfig = { toolNameMaxLength: 0 };
+
+ expect(generateLongToolName()).toBe(
+ 'my-notion-mcp-connector-with-a-long-identifier____searchDocumentsInWorkspace',
+ );
+ });
+
+ it('should honour a custom threshold from the server config', () => {
+ mockServerConfig = { toolNameMaxLength: 200 };
+
+ expect(generateLongToolName()).not.toContain('MD5HASH_');
+ });
});
describe('createToolsEngine', () => {
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index dd75edeb2be..23b3dc4cac5 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -20,6 +20,7 @@ import {
} from '@lobechat/types';
import type { ConnectorToolPermission } from '@/database/schemas';
+import { applyToolNameMaxLength } from '@/helpers/applyToolNameMaxLength';
import { isToolAvailableInCurrentEnv } from '@/helpers/toolAvailability';
import { patchManifestWithPermissions } from '@/libs/mcp/patchManifestPermissions';
import { getAgentStoreState } from '@/store/agent';
@@ -115,6 +116,11 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
manifestContext,
} = config;
+ // Push the deployment's `TOOL_NAME_MAX_LENGTH` in before any tool name is
+ // generated — the client mirror of `createServerToolsEngine`. Without it a
+ // deployment setting `0` would still get `MD5HASH_…` names on this path.
+ applyToolNameMaxLength();
+
const toolStoreState = getToolStoreState();
// Get custom connector manifests (user-added MCP servers). Connectors take
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
index 0842c32de34..97e438ddb11 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
@@ -12,6 +12,7 @@ import isEqual from 'fast-deep-equal';
import { memo, useCallback, useMemo } from 'react';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
+import { applyToolNameMaxLength } from '@/helpers/applyToolNameMaxLength';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
@@ -118,6 +119,9 @@ const useMentionOptions = () => {
const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
const baseItems = useMemo<MentionListOption[]>(() => {
+ // Mention metadata carries generated tool names, so it has to honour the
+ // deployment's `TOOL_NAME_MAX_LENGTH` like the tools payload does.
+ applyToolNameMaxLength();
const state = useToolStore.getState();
return installedTools.map((tool) => {
@@ -182,6 +186,9 @@ const useMentionOptions = () => {
);
const mentionMarkdownWriter = useCallback((mention: any) => {
+ // These names are written into the system prompt — they must match the tool
+ // names the same deployment sends to the model.
+ applyToolNameMaxLength();
const metadata = (mention?.metadata || {}) as MentionMetadata;
const pluginId = metadata.pluginIdentifier || metadata.identifier;
const state = useToolStore.getState();