Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🐡 fix: Bound Tool Approval Admission Work (#17387)

lia-by-librechat[bot]532214c02255
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index 7f5799e2f2..34d9ae1d64 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -2301,6 +2301,55 @@ describe('AgentClient - startup telemetry', () => {
jest.restoreAllMocks();
});
+ it.each([false, true])(
+ 'bounds ordinary-chat admission before provider startup (legacy=%s)',
+ async (legacy) => {
+ const createRunBefore = mockCreateRun.mock.calls.length;
+ const name = 'q' + '_mcp_z'.repeat(legacy ? 4000 : 80);
+ const tool_options = Object.fromEntries(
+ Array.from({ length: legacy ? 1 : 100 }, (_, i) => [
+ `${i}_${name}`,
+ { approval_mode: 'ask' },
+ ]),
+ );
+ const client = new AgentClient({
+ req: {
+ user: { id: 'user-123' },
+ body: {},
+ config: {
+ endpoints: {
+ [EModelEndpoint.agents]: { toolApproval: { enabled: true, mode: 'bypass' } },
+ },
+ },
+ },
+ res: {},
+ agent: {
+ id: 'agent-123',
+ endpoint: EModelEndpoint.openAI,
+ provider: EModelEndpoint.openAI,
+ model_parameters: { model: 'gpt-4' },
+ tools: [],
+ lazySubagentConfigs: [{ id: 'child', tools: ['other_mcp_unknown'], tool_options }],
+ },
+ endpointTokenConfig: {},
+ eventHandlers: {},
+ contentParts: [],
+ collectedUsage: [],
+ artifactPromises: [],
+ });
+ client.conversationId = 'bounded-approval-admission';
+ client.responseMessageId = 'bounded-response';
+ client.parentMessageId = 'bounded-parent';
+
+ await client.chatCompletion({ payload: [] });
+
+ expect(mockCreateRun).toHaveBeenCalledTimes(createRunBefore);
+ expect(client.contentParts).toEqual(
+ expect.arrayContaining([expect.objectContaining({ type: ContentTypes.ERROR })]),
+ );
+ },
+ );
+
it('refuses scheduled pause-capable runs before provider startup without Redis', async () => {
mockIsHITLEnabled.mockReturnValue(false);
const createRunBefore = mockCreateRun.mock.calls.length;
diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.js
index df3e6e3685..25cd3d9cb3 100644
--- a/api/server/controllers/agents/v1.spec.js
+++ b/api/server/controllers/agents/v1.spec.js
@@ -220,6 +220,70 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
};
});
+ describe('tool_options HTTP validation', () => {
+ test.each([
+ ['key length', { ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' } }],
+ [
+ 'entry count',
+ Object.fromEntries(
+ Array.from({ length: 1025 }, (_, i) => [`${i}`, { approval_mode: 'ask' }]),
+ ),
+ ],
+ [
+ 'key bytes',
+ Object.fromEntries(
+ Array.from({ length: 129 }, (_, i) => [
+ `${i}`.padEnd(256, 'é'),
+ { approval_mode: 'ask' },
+ ]),
+ ),
+ ],
+ ])(
+ 'rejects excess %s over POST and PATCH without changing persisted data',
+ async (_label, tool_options) => {
+ const existing = await Agent.create({
+ id: `agent_${uuidv4()}`,
+ name: 'Unchanged',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: mockReq.user.id,
+ tool_options: { web_search: { approval_mode: 'ask' } },
+ });
+ const before = await Agent.findById(existing._id).lean();
+ const app = express();
+ app.use(express.json({ limit: '3mb' }));
+ app.use((req, _res, next) => {
+ req.user = mockReq.user;
+ req.config = {};
+ next();
+ });
+ app.post('/api/agents', createAgentHandler);
+ app.patch('/api/agents/:id', updateAgentHandler);
+
+ for (const response of [
+ await request(app).post('/api/agents').send({
+ name: 'Rejected',
+ provider: 'openai',
+ model: 'gpt-4',
+ tools: [],
+ tool_options,
+ }),
+ await request(app)
+ .patch(`/api/agents/${existing.id}`)
+ .send({ name: 'Rejected', tool_options }),
+ ]) {
+ expect(response.status).toBe(400);
+ expect(response.body).toMatchObject({
+ error: 'Invalid request data',
+ details: [expect.objectContaining({ path: ['tool_options'] })],
+ });
+ }
+ expect(await Agent.countDocuments()).toBe(1);
+ expect(await Agent.findById(existing._id).lean()).toEqual(before);
+ },
+ );
+ });
+
describe('inference input boundary', () => {
test.each(['modelKwargs', 'configuration', 'fallbacks', 'apiKey', 'callbacks'])(
'rejects %s on creation without persisting or disclosing its value',
diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js
index bc354fbb6d..bd6bba4768 100644
--- a/api/server/services/Endpoints/agents/initialize.spec.js
+++ b/api/server/services/Endpoints/agents/initialize.spec.js
@@ -735,6 +735,47 @@ describe('initializeClient — processAgent ACL gate', () => {
expect(capturedToolExecuteOptions.backgroundCompletionResultMaxChars).toBe(4096);
});
+ it('never swallows an option-limit failure from runtime classification', async () => {
+ loadAgentTools.mockImplementationOnce(({ agent }) =>
+ jest.requireActual('@librechat/api').buildToolClassification({
+ userId: testUser._id.toString(),
+ agentId: agent.id,
+ agentToolOptions: {
+ db_query_mcp_db: { approval_mode: 'ask' },
+ ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' },
+ },
+ loadedTools: [
+ {
+ name: 'query_mcp_db',
+ mcp: true,
+ mcpRawServerName: 'db',
+ mcpServerToolName: 'db_query',
+ },
+ ],
+ }),
+ );
+ mockInitializeAgent.mockImplementationOnce(async ({ req, res, loadTools, agent }) => {
+ await loadTools({
+ req,
+ res,
+ tools: ['query_mcp_db'],
+ model: agent.model,
+ agentId: agent.id,
+ provider: agent.provider,
+ });
+ return makePrimaryConfig([]);
+ });
+ await expect(
+ initializeClient({
+ req: makeReq(),
+ res: {},
+ signal: new AbortController().signal,
+ endpointOption: makeEndpointOption(),
+ }),
+ ).rejects.toMatchObject({ code: 'AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED' });
+ expect(agentClientArgs).toBeUndefined();
+ });
+
it('propagates an expected-MCP-tools failure from the runtime tool loader', async () => {
const toolError = Object.assign(new Error('Expected MCP tools are unavailable'), {
code: 'AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE',
@@ -1599,6 +1640,35 @@ describe('initializeClient — subagent loading', () => {
).rejects.toBe(toolError);
});
+ it('does not omit a lazy child when persisted option validation fails', async () => {
+ const child = await createAgent({
+ id: SUBAGENT_ID,
+ name: 'Oversized child',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: testUser._id,
+ tools: [],
+ tool_options: { ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' } },
+ });
+ await grantView(child);
+ mockInitializeAgent.mockResolvedValue(
+ makePrimaryConfig({
+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },
+ }),
+ );
+ const req = makeSubagentReq();
+ req.config.endpoints.agents.capabilities.push('tools');
+ await expect(
+ initializeClient({
+ req,
+ res: {},
+ signal: new AbortController().signal,
+ endpointOption: makeEndpointOption(),
+ }),
+ ).rejects.toMatchObject({ code: 'AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED' });
+ expect(agentClientArgs).toBeUndefined();
+ });
+
it('defers pure-subagent resource recovery until the descriptor is selected', async () => {
const subAgent = await createAgent({
id: SUBAGENT_ID,
diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.ts
index 04582d5fc8..b3111ecd4e 100644
--- a/packages/api/src/agents/__tests__/initialize.test.ts
+++ b/packages/api/src/agents/__tests__/initialize.test.ts
@@ -141,6 +141,7 @@ jest.mock('../../middleware/modelBoundContent', () => {
import { initializeAgent } from '../initialize';
import { primeResources } from '../resources';
import { isFatalAgentInitializationError } from '../errors';
+import { canAgentGraphPause } from '../hitl/admission';
const realUtils = jest.requireActual<typeof import('~/utils')>('~/utils');
@@ -4207,6 +4208,42 @@ describe('initializeAgent — execute_code capability expansion', () => {
},
);
+ it.each([
+ { ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' as const } },
+ Object.fromEntries(
+ Array.from({ length: 1025 }, (_, i) => [`${i}`, { approval_mode: 'ask' as const }]),
+ ),
+ Object.fromEntries(
+ Array.from({ length: 129 }, (_, i) => [
+ `${i}`.padEnd(256, 'é'),
+ { approval_mode: 'ask' as const },
+ ]),
+ ),
+ ])(
+ 'rejects legacy option-limit violations before loading tools or priming resources',
+ async (tool_options) => {
+ const { agent, req, res, loadTools, db } = createMocks();
+ agent.tool_options = tool_options;
+ const primeCalls = jest.mocked(primeResources).mock.calls.length;
+ await expect(
+ initializeAgent(
+ {
+ req,
+ res,
+ agent,
+ loadTools,
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ allowedProviders: new Set([Providers.OPENAI]),
+ isInitialAgent: true,
+ },
+ db,
+ ),
+ ).rejects.toMatchObject({ code: 'AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED' });
+ expect(loadTools).not.toHaveBeenCalled();
+ expect(primeResources).toHaveBeenCalledTimes(primeCalls);
+ },
+ );
+
it('rejects a stateful environment excluded by deployment policy', async () => {
const { agent, req, res, loadTools, db } = createMocks();
agent.tools = ['execute_code'];
@@ -5284,6 +5321,43 @@ describe('initializeAgent — run-scoped MCP tool definitions', () => {
);
});
+ it('keeps valid authored limits through symbol-only server normalization and chat admission', async () => {
+ const { agent, req, res, loadTools, db } = createMocks({
+ structuredTools: [{ name: 'web_search' }],
+ loadedToolDefinitions: [{ name: 'web_search' }],
+ });
+ const names = Array.from({ length: 1023 }, (_, i) => `${`${i}`.padEnd(58, 'q')}_mcp_!`);
+ agent.tools = ['web_search'];
+ agent.tool_options = Object.fromEntries([
+ ...names.map((name) => [name, { approval_mode: 'ask' as const }]),
+ ['web_search', { approval_mode: 'ask' as const }],
+ ]);
+ req.config!.mcpConfig = { '!': { type: 'stdio', command: 'node', args: [] } };
+ db.getAccessibleMcpServerNames = jest.fn().mockResolvedValue(['!']);
+ const result = await initializeAgent(
+ {
+ req,
+ res,
+ agent,
+ loadTools,
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ allowedProviders: new Set([Providers.OPENAI]),
+ isInitialAgent: true,
+ },
+ db,
+ );
+ expect(loadTools).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tool_options: expect.objectContaining({
+ [names[0].replace(/!$/, 'server_33')]: { approval_mode: 'ask' },
+ }),
+ }),
+ );
+ expect(
+ canAgentGraphPause({ policy: { enabled: true, mode: 'bypass' }, agents: [result] }),
+ ).toBe(true);
+ });
+
it('threads the normalized MCP request body into tool discovery', async () => {
const { agent, req, res, loadTools, db } = createMocks();
agent.tools = ['custom_tool'];
diff --git a/packages/api/src/agents/errors.spec.ts b/packages/api/src/agents/errors.spec.ts
index 3726c154f9..fa7e80d620 100644
--- a/packages/api/src/agents/errors.spec.ts
+++ b/packages/api/src/agents/errors.spec.ts
@@ -22,9 +22,22 @@ import {
import { MCPAuthenticationRejectedError, MCPAuthenticationRefreshError } from '~/mcp/errors';
import { createTerminalRunErrorObserver } from './failures/terminal';
import { OboTokenResolutionError } from '~/mcp/oauth/obo';
+import { assertToolOptionsWithinLimits } from './options';
import { OpenIDReauthRequiredError } from '~/utils/oidc';
describe('isFatalAgentInitializationError', () => {
+ it('never downgrades a persisted option-limit violation to optional-tool fallback', () => {
+ let error;
+ try {
+ assertToolOptionsWithinLimits({ ['q' + '_mcp_z'.repeat(4000)]: {} });
+ } catch (caught) {
+ error = caught;
+ }
+ expect(error).toBeInstanceOf(RangeError);
+ expect(isFatalAgentInitializationError(error)).toBe(true);
+ expect(isFatalAgentInitializationError(error, { allowExpectedMCPFallback: true })).toBe(true);
+ });
+
it.each([
new OpenIDReauthRequiredError('Please sign in again'),
new MCPAuthenticationRejectedError('private-mcp', false),
diff --git a/packages/api/src/agents/errors.ts b/packages/api/src/agents/errors.ts
index f82c42df72..8cb3633161 100644
--- a/packages/api/src/agents/errors.ts
+++ b/packages/api/src/agents/errors.ts
@@ -6,6 +6,7 @@ import {
} from 'librechat-data-provider';
import { ScheduledMCPPolicyError } from '~/schedules/authorization/policy';
import { MCPErrorCodes, isMCPInitializationError } from '~/mcp/errors';
+import { AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED } from './options';
import { OboTokenResolutionError } from '~/mcp/oauth/obo';
export const AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE = 'AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE';
@@ -14,6 +15,7 @@ export const AGENT_ATTACHMENT_LIMIT_EXCEEDED = 'AGENT_ATTACHMENT_LIMIT_EXCEEDED'
const FATAL_AGENT_INITIALIZATION_CODES = new Set(
[
AGENT_ATTACHMENT_LIMIT_EXCEEDED,
+ AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED,
ErrorTypes.RESOURCE_RECOVERY_REQUIRED,
ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED,
ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,
diff --git a/packages/api/src/agents/hitl/admission.spec.ts b/packages/api/src/agents/hitl/admission.spec.ts
index c7fa3b54f1..460181c5d2 100644
--- a/packages/api/src/agents/hitl/admission.spec.ts
+++ b/packages/api/src/agents/hitl/admission.spec.ts
@@ -1,6 +1,7 @@
import { Constants } from 'librechat-data-provider';
import { createToolPolicyHook } from '@librechat/agents';
import type { AgentToolOptions } from 'librechat-data-provider';
+import type { GenericTool } from '@librechat/agents';
import type { PluginHookSource } from '~/agents/hooks/source';
import type { ToolApprovalAdmissionAgent } from './admission';
import type { ToolApprovalHook } from './hooks';
@@ -9,8 +10,12 @@ import {
canAgentGraphPause,
copyToolApprovalAdmissionMetadata,
} from './admission';
+import { buildToolClassification, aliasMCPToolOptions } from '~/tools/classification';
+import { MAX_TOOL_OPTION_ENTRIES, MAX_TOOL_OPTION_KEY_BYTES } from '../options';
import { loadToolDefinitions } from '~/tools/definitions';
+import { normalizeAgentToolKeys } from '~/mcp/utils';
import { formatMCPServerTools } from '~/mcp/tools';
+import { agentUpdateSchema } from '../validation';
import { mapToolApprovalPolicy } from './policy';
const askHook: ToolApprovalHook = async () => ({ decision: 'ask' });
@@ -1374,3 +1379,307 @@ test('long mixed-case upstream prefixes use actual literal matcher spellings wit
}),
).toBe(false);
});
+
+describe('bounded approval admission', () => {
+ const policy = { enabled: true, mode: 'bypass' as const };
+ const oversized = { ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' as const } };
+
+ test.each(['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const)(
+ '%s skips unrelated options for an explicitly empty surface',
+ (placement) => {
+ const stringify = jest.spyOn(JSON, 'stringify');
+ expect(
+ canAgentGraphPause({
+ policy,
+ agents: [{ [placement]: [{ tools: [], tool_options: oversized }] }],
+ }),
+ ).toBe(false);
+ expect(stringify).not.toHaveBeenCalled();
+ },
+ );
+
+ test.each([undefined, ['other_mcp_unknown'], ['mcp_all_mcp_unknown']])(
+ 'rejects oversized legacy options before expansion with tools=%j',
+ (tools) => {
+ const stringify = jest.spyOn(JSON, 'stringify');
+ expect(() =>
+ canAgentGraphPause({
+ policy,
+ agents: [{ lazySubagentConfigs: [{ tools, tool_options: oversized }] }],
+ }),
+ ).toThrow(RangeError);
+ expect(stringify).not.toHaveBeenCalled();
+ },
+ );
+
+ test('rejects oversized legacy records before normalizing or copying metadata', () => {
+ for (const tool_options of [
+ oversized,
+ Object.fromEntries(
+ Array.from({ length: MAX_TOOL_OPTION_ENTRIES + 1 }, (_, i) => [
+ `${i}`,
+ { approval_mode: 'ask' as const },
+ ]),
+ ),
+ Object.fromEntries(
+ Array.from({ length: 129 }, (_, i) => [
+ `${i}`.padEnd(256, 'é'),
+ { approval_mode: 'ask' as const },
+ ]),
+ ),
+ ]) {
+ expect(() => copyToolApprovalAdmissionMetadata({}, { tools: [], tool_options })).toThrow(
+ RangeError,
+ );
+ expect(() =>
+ canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [{ tool_options }] }] }),
+ ).toThrow(RangeError);
+ }
+ });
+
+ test.each([
+ { definitionsOnly: false, count: 513, nameLength: 0 },
+ { definitionsOnly: true, count: 513, nameLength: 0 },
+ { definitionsOnly: false, count: 64, nameLength: 512 },
+ { definitionsOnly: true, count: 64, nameLength: 512 },
+ ])(
+ 'applies authoring limits before aliases (definitionsOnly=$definitionsOnly count=$count nameLength=$nameLength)',
+ async ({ definitionsOnly, count, nameLength }) => {
+ const names = Array.from({ length: count }, (_, i) => `read_${i}`.padEnd(nameLength, 'x'));
+ const tool_options = agentUpdateSchema.parse({
+ tool_options: Object.fromEntries(
+ names.map((name) => [`db_${name}_mcp_db`, { approval_mode: 'ask' }]),
+ ),
+ }).tool_options!;
+ const result = await buildToolClassification({
+ userId: 'user',
+ agentId: 'child',
+ definitionsOnly,
+ agentToolOptions: tool_options,
+ loadedTools: names.map((name) => ({
+ name: `${name}_mcp_db`,
+ mcp: true,
+ mcpRawServerName: 'db',
+ mcpServerToolName: `db_${name}`,
+ mcpJsonSchema: { type: 'object', properties: {} },
+ })) as unknown as GenericTool[],
+ });
+ expect(Object.keys(tool_options)).toHaveLength(count * 2);
+ const agent = {
+ tools: ['mcp_all_mcp_db'],
+ tool_options,
+ toolRegistry: result.toolRegistry,
+ toolDefinitions: result.toolDefinitions,
+ mcpToolAliases: result.mcpToolAliases,
+ };
+ expect(canAgentGraphPause({ policy, agents: [agent] })).toBe(true);
+ expect(canAgentGraphPause({ policy: { ...policy, deny: ['*'] }, agents: [agent] })).toBe(
+ false,
+ );
+ const projected = copyToolApprovalAdmissionMetadata({ id: 'child' }, agent);
+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [projected] }] })).toBe(
+ true,
+ );
+ // Provenance belongs to the trusted enrichment, not arbitrary over-limit records.
+ expect(() =>
+ canAgentGraphPause({
+ policy,
+ agents: [{ ...agent, tool_options: { ...tool_options } }],
+ }),
+ ).toThrow(RangeError);
+ },
+ );
+
+ test.each([
+ { count: 1023, keyLength: 64, selected: 'web_search' },
+ { count: 1023, keyLength: 64, selected: 'mcp' },
+ { count: 1, keyLength: 1024, selected: 'mcp' },
+ ])(
+ 'retains authored limits and normalized review entries (count=$count keyLength=$keyLength selected=$selected)',
+ ({ count, keyLength, selected }) => {
+ const names = Array.from(
+ { length: count },
+ (_, i) => `${`${i}`.padEnd(keyLength - 6, 'q')}_mcp_!`,
+ );
+ const tool_options = agentUpdateSchema.parse({
+ tool_options: Object.fromEntries([
+ ...names.map((name) => [name, { approval_mode: 'ask' }]),
+ ['web_search', { approval_mode: 'ask' }],
+ ]),
+ }).tool_options!;
+ const normalized = normalizeAgentToolKeys({
+ tools: [selected === 'mcp' ? names[0] : selected],
+ toolOptions: tool_options,
+ rawServerNames: ['!'],
+ });
+ const name = normalized.tools![0];
+ expect(normalized.toolOptions![name]?.approval_mode).toBe('ask');
+ // Re-submitting generated keys is still an untrusted write and must meet authoring limits.
+ expect(agentUpdateSchema.safeParse({ tool_options: normalized.toolOptions }).success).toBe(
+ false,
+ );
+ const agent = { tools: normalized.tools, tool_options: normalized.toolOptions };
+ expect(canAgentGraphPause({ policy, agents: [agent] })).toBe(true);
+ const projected = copyToolApprovalAdmissionMetadata({ id: 'child' }, agent, {
+ rawMcpServerNames: ['!'],
+ });
+ const copied = copyToolApprovalAdmissionMetadata({ id: 'child' }, projected);
+ for (const descriptor of [projected, copied]) {
+ expect(
+ canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] }),
+ ).toBe(true);
+ expect(
+ canAgentGraphPause({
+ policy: { ...policy, deny: ['*'] },
+ agents: [{ lazySubagentConfigs: [descriptor] }],
+ }),
+ ).toBe(false);
+ }
+ expect(() =>
+ canAgentGraphPause({
+ policy,
+ agents: [{ ...agent, tool_options: { ...normalized.toolOptions } }],
+ }),
+ ).toThrow(RangeError);
+ expect(Object.keys(tool_options)).toEqual([...names, 'web_search']);
+ },
+ );
+
+ test('keeps effective entries and source limits across aliasing, normalization, and projection', () => {
+ const names = Array.from({ length: 513 }, (_, i) => `read_${i}`);
+ const options = agentUpdateSchema.parse({
+ tool_options: {
+ ...Object.fromEntries(names.map((name) => [`db_${name}_mcp_db`, { approval_mode: 'ask' }])),
+ query_mcp_server_33: { approval_mode: 'allow' },
+ 'query_mcp_!': { approval_mode: 'ask' },
+ },
+ }).tool_options!;
+ const aliases = names.map((name) => ({
+ name: `${name}_mcp_db`,
+ aliasName: `db_${name}_mcp_db`,
+ }));
+ aliasMCPToolOptions(aliases, options);
+ expect(Object.keys(options).length).toBeGreaterThan(MAX_TOOL_OPTION_ENTRIES);
+ const normalized = normalizeAgentToolKeys({
+ tools: ['read_0_mcp_db'],
+ toolOptions: options,
+ rawServerNames: ['!', 'db'],
+ });
+ expect(normalized.toolOptions!.query_mcp_server_33.approval_mode).toBe('allow');
+ const source = {
+ tools: normalized.tools,
+ tool_options: normalized.toolOptions,
+ mcpToolAliases: aliases,
+ };
+ const descriptor = copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {
+ rawMcpServerNames: ['!', 'db'],
+ });
+ expect(canAgentGraphPause({ policy, agents: [source] })).toBe(true);
+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(
+ true,
+ );
+ for (const tools of [['query_mcp_server_33'], ['query_mcp_!']]) {
+ const current = copyToolApprovalAdmissionMetadata(
+ { id: 'child' },
+ { ...source, tools },
+ { rawMcpServerNames: ['!', 'db'] },
+ );
+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [current] }] })).toBe(
+ false,
+ );
+ }
+ });
+
+ test('normalization cannot make oversized authored options trusted', () => {
+ for (const toolOptions of [
+ oversized,
+ Object.fromEntries(
+ Array.from({ length: MAX_TOOL_OPTION_ENTRIES + 1 }, (_, i) => [
+ `query_${i}_mcp_!`,
+ { approval_mode: 'ask' as const },
+ ]),
+ ),
+ Object.fromEntries(
+ Array.from({ length: 129 }, (_, i) => [
+ `${i}`.padEnd(256, 'é') + '_mcp_!',
+ { approval_mode: 'ask' as const },
+ ]),
+ ),
+ ]) {
+ expect(() =>
+ normalizeAgentToolKeys({ tools: [], toolOptions, rawServerNames: ['!'] }),
+ ).toThrow(RangeError);
+ }
+ });
+
+ test('rejects oversized persisted options before any runtime alias is added', () => {
+ for (const tool_options of [
+ { query_mcp_db: { approval_mode: 'ask' as const }, ...oversized },
+ Object.fromEntries(
+ Array.from({ length: MAX_TOOL_OPTION_ENTRIES + 1 }, (_, i) => [
+ `query_${i}_mcp_db`,
+ { approval_mode: 'ask' as const },
+ ]),
+ ),
+ ]) {
+ const before = { ...tool_options };
+ const aliasName = Object.keys(tool_options)[0];
+ expect(() => aliasMCPToolOptions([{ name: 'new_mcp_db', aliasName }], tool_options)).toThrow(
+ RangeError,
+ );
+ expect(tool_options).toEqual(before);
+ }
+ });
+
+ test('bounds aggregate serialized expansion for otherwise valid delimiter-rich keys', () => {
+ const key = 'q' + '_mcp_z'.repeat(80);
+ const tool_options = Object.fromEntries(
+ Array.from({ length: 100 }, (_, i) => [`${i}_${key}`, { approval_mode: 'ask' as const }]),
+ );
+ expect(
+ Object.keys(tool_options).reduce((sum, name) => sum + Buffer.byteLength(name), 0),
+ ).toBeLessThan(MAX_TOOL_OPTION_KEY_BYTES);
+ const stringify = JSON.stringify;
+ let serializedBytes = 0;
+ jest.spyOn(JSON, 'stringify').mockImplementation((value) => {
+ const result = stringify(value);
+ serializedBytes += result?.length ?? 0;
+ return result;
+ });
+ const descriptor = copyToolApprovalAdmissionMetadata(
+ {},
+ { tools: ['other_mcp_unknown'], tool_options },
+ );
+ expect(() =>
+ canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] }),
+ ).toThrow('safety work limit');
+ expect(serializedBytes).toBeGreaterThan(0);
+ expect(serializedBytes).toBeLessThan(2 * 1024 * 1024);
+ });
+
+ test('shares the expansion budget across lazy children, not per option or agent', () => {
+ const name = 'q' + '_mcp_z'.repeat(80);
+ const child = {
+ tools: ['other_mcp_unknown'],
+ tool_options: { [name]: { approval_mode: 'ask' as const } },
+ };
+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [child] }] })).toBe(false);
+ expect(() =>
+ canAgentGraphPause({
+ policy,
+ agents: [{ lazySubagentConfigs: Array.from({ length: 40 }, () => ({ ...child })) }],
+ }),
+ ).toThrow('safety work limit');
+ });
+
+ test('bounds delimiter expansion in unresolved hook spellings too', () => {
+ const name = 'q' + '_mcp_z'.repeat(4000);
+ expect(() =>
+ canAgentGraphPause({
+ policy,
+ agents: [{ lazySubagentConfigs: [{}] }],
+ resolvedProgrammaticHooks: [{ hook: askHook, toolNames: [name] }],
+ }),
+ ).toThrow('safety work limit');
+ });
+});
diff --git a/packages/api/src/agents/hitl/admission.ts b/packages/api/src/agents/hitl/admission.ts
index 0b7aa9e2fb..7fc714f995 100644
--- a/packages/api/src/agents/hitl/admission.ts
+++ b/packages/api/src/agents/hitl/admission.ts
@@ -19,6 +19,11 @@ import {
isToolBlockedByApprovalPolicy,
healToolApprovalPolicy,
} from './policy';
+import {
+ assertToolOptionsWithinLimits,
+ retainToolOptionsLimits,
+ ToolOptionsLimitError,
+} from '../options';
import { selectSkillPrimesForTurn, unionPrimeAllowedTools } from '~/agents/skills';
import { isMCPAllPlaceholder, normalizeAgentToolKeys } from '~/mcp/utils';
import { ASK_USER_QUESTION_TOOL_NAME } from './askUserQuestionTool';
@@ -58,6 +63,21 @@ type AdmissionSurface = Pick<
> & { readonly rawMcpServerNames?: readonly string[] };
const admissionSurfaces = new WeakMap<object, AdmissionSurface>();
+// Charge full-name work before allocating aliases, across every lazy surface in one admission.
+const MAX_ADMISSION_NAME_WORK = 1024 * 1024;
+type AdmissionWork = (name: string, copies?: number) => void;
+
+function createAdmissionWork(): AdmissionWork {
+ let remaining = MAX_ADMISSION_NAME_WORK;
+ return (name, copies = 1) => {
+ const work = Math.max(1, name.length) * copies;
+ if (work > remaining) {
+ throw new ToolOptionsLimitError('Tool approval admission exceeds the safety work limit');
+ }
+ remaining -= work;
+ };
+}
+
function readAdmissionSurface(
agent: ToolApprovalAdmissionAgent,
): ToolApprovalAdmissionAgent & AdmissionSurface {
@@ -78,6 +98,7 @@ export function copyToolApprovalAdmissionMetadata<T extends object>(
context: AdmissionProjectionContext = {},
): T {
const surface = readAdmissionSurface(source);
+ assertToolOptionsWithinLimits(surface.tool_options);
const selectedTools: string[] | undefined = surface.tools == null ? undefined : [];
for (const tool of surface.tools ?? []) {
const name = typeof tool === 'string' ? tool : tool.name;
@@ -105,19 +126,21 @@ export function copyToolApprovalAdmissionMetadata<T extends object>(
toolOptions: surface.tool_options,
rawServerNames: context.rawMcpServerNames ?? surface.rawMcpServerNames ?? [],
});
+ const projectedOptions =
+ normalized.toolOptions &&
+ Object.fromEntries(
+ Object.entries(normalized.toolOptions)
+ .filter(
+ ([name]) =>
+ context.toolsAvailable !== false ||
+ isActionTool(name) ||
+ !name.includes(Constants.mcp_delimiter),
+ )
+ .map(([name, option]) => [name, { approval_mode: option.approval_mode }]),
+ );
+ if (projectedOptions) retainToolOptionsLimits(projectedOptions, normalized.toolOptions);
admissionSurfaces.set(target, {
- tool_options:
- normalized.toolOptions &&
- Object.fromEntries(
- Object.entries(normalized.toolOptions)
- .filter(
- ([name]) =>
- context.toolsAvailable !== false ||
- isActionTool(name) ||
- !name.includes(Constants.mcp_delimiter),
- )
- .map(([name, option]) => [name, { approval_mode: option.approval_mode }]),
- ),
+ tool_options: projectedOptions,
tools: normalized.tools,
rawMcpServerNames: context.rawMcpServerNames?.slice() ?? surface.rawMcpServerNames,
toolRegistry: surface.toolRegistry,
@@ -151,12 +174,18 @@ function literalHookNames(matcher?: string): string[] | undefined {
}
/** Possible catalog spellings are admission hints, never authorization aliases. */
-function unresolvedHookSpellings(name: string, rawServerNames: readonly string[]): string[] {
+function unresolvedHookSpellings(
+ name: string,
+ rawServerNames: readonly string[],
+ consume: AdmissionWork,
+): string[] {
+ consume(name, 1 + rawServerNames.length);
if (isActionTool(name) || isMCPAllPlaceholder(name)) return [name];
const aliases = buildServerNameAliases(rawServerNames);
const known = [...rawServerNames, ...aliases.keys()];
const spellings = new Set([name]);
const add = (tool: string, server: string): void => {
+ consume(name);
const raw = rawServerNames.includes(server) ? server : (aliases.get(server) ?? server);
const normalized = normalizeServerName(raw);
const suffixes =
@@ -169,9 +198,12 @@ function unresolvedHookSpellings(name: string, rawServerNames: readonly string[]
const legacy = `${prefix}_${stripped}`;
if (stripServerNamePrefix(legacy, normalized) === stripped) tools.add(legacy);
}
- for (const suffix of suffixes)
- for (const candidate of tools)
+ for (const suffix of suffixes) {
+ for (const candidate of tools) {
+ consume(name);
spellings.add(`${candidate}${Constants.mcp_delimiter}${suffix}`);
+ }
+ }
};
const [tool, server] = splitMCPToolKey(name, known);
if (server != null && known.includes(server)) add(tool, server);
@@ -191,6 +223,7 @@ function createUnresolvedReviewMatcher(
options: AgentToolOptions,
policy: TToolApprovalPolicy | undefined,
toolNames: ReadonlySet<string>,
+ consume: AdmissionWork,
rawServerNames: readonly string[] = [],
): (name?: string) => boolean {
const wildcardServers: string[] = [];
@@ -216,11 +249,13 @@ function createUnresolvedReviewMatcher(
directNames.has(server) ? server : (serverAliases.get(server) ?? server);
const key = (server: string, tool: string) => JSON.stringify([resolveServer(server), tool]);
const visitParts = (name: string, visit: (tool: string, server: string) => boolean): boolean => {
+ consume(name, 1 + knownNames.length);
const [tool, server] = splitMCPToolKey(name, knownNames);
if (server && knownNameSet.has(server)) return visit(tool, server);
// Without catalog knowledge either half may contain the delimiter. Keep possible boundaries.
let delimiter = name.indexOf(Constants.mcp_delimiter);
while (delimiter >= 0) {
+ consume(name);
const suffix = name.slice(delimiter + Constants.mcp_delimiter.length);
if (suffix && visit(name.slice(0, delimiter), suffix)) return true;
delimiter = name.indexOf(Constants.mcp_delimiter, delimiter + Constants.mcp_delimiter.length);
@@ -239,6 +274,7 @@ function createUnresolvedReviewMatcher(
const reviewServers = new Set<string>();
let unknownCanAsk = false;
for (const [name, option] of Object.entries(options)) {
+ consume(name);
if (
option.approval_mode == null ||
option.approval_mode === 'allow' ||
@@ -348,6 +384,7 @@ export function canAgentGraphPause({
return asksUserQuestion;
}
+ const consume = createAdmissionWork();
const approvalGraph = collectApprovalAgents(agents);
const toolOwners = new Map<string, Set<string | undefined>>();
const reviewGatedTools = new Set<string>();
@@ -371,13 +408,21 @@ export function canAgentGraphPause({
const reachable = new Set<string>();
for (const tool of surface.tools ?? []) {
const name = typeof tool === 'string' ? tool : tool.name;
- if (name) reachable.add(name);
+ if (name) {
+ consume(name);
+ reachable.add(name);
+ }
}
for (const name of surface.toolRegistry?.keys() ?? []) reachable.add(name);
for (const definition of surface.toolDefinitions ?? []) {
if (definition.name) reachable.add(definition.name);
}
- const options = { ...surface.tool_options };
+ // A closed empty surface cannot review a tool, regardless of unrelated persisted options.
+ const sourceOptions =
+ surface.tools != null && reachable.size === 0 ? undefined : surface.tool_options;
+ assertToolOptionsWithinLimits(sourceOptions);
+ const options = { ...sourceOptions };
+ retainToolOptionsLimits(options, sourceOptions);
aliasMCPToolOptions(surface.mcpToolAliases ?? [], options);
for (const name of reachable) {
addToolName(name, agent.id);
@@ -386,6 +431,7 @@ export function canAgentGraphPause({
}
if (
!unresolvedModeCanAsk &&
+ (surface.tools == null || reachable.size > 0) &&
approvalGraph.lazyAgents.has(agent) &&
surface.toolRegistry == null &&
surface.toolDefinitions == null
@@ -394,6 +440,7 @@ export function canAgentGraphPause({
options,
buildEffectiveToolApprovalPolicy(policy, surface.mcpToolAliases ?? [], toolApprovalAllows),
reachable,
+ consume,
surface.rawMcpServerNames,
);
unresolvedModeCanAsk = surface.tools == null ? canAsk() : [...reachable].some(canAsk);
@@ -444,7 +491,7 @@ export function canAgentGraphPause({
const spellings = (name: string): string[] => {
let names = cache.get(name);
if (!names) {
- names = knownCatalog ? [name] : unresolvedHookSpellings(name, rawNames);
+ names = knownCatalog ? [name] : unresolvedHookSpellings(name, rawNames, consume);
cache.set(name, names);
}
return names;
diff --git a/packages/api/src/agents/hitl/controller.spec.ts b/packages/api/src/agents/hitl/controller.spec.ts
index ef6dcc8a92..e35b062b32 100644
--- a/packages/api/src/agents/hitl/controller.spec.ts
+++ b/packages/api/src/agents/hitl/controller.spec.ts
@@ -271,3 +271,61 @@ test('agent-wide and inaccessible resets do not load MCP catalogs', async () =>
expect(f.getMCPServerConfigs).not.toHaveBeenCalled();
expect(f.getMCPServerTools).not.toHaveBeenCalled();
});
+
+test.each([
+ { approval_mode: 'chat' as const, count: 513, nameLength: 0 },
+ { approval_mode: 'always' as const, count: 513, nameLength: 0 },
+ { approval_mode: 'chat' as const, count: 64, nameLength: 512 },
+ { approval_mode: 'always' as const, count: 64, nameLength: 512 },
+])(
+ 'targeted reset preserves persisted limits through normalization ($approval_mode count=$count nameLength=$nameLength)',
+ async ({ approval_mode, count, nameLength }) => {
+ const f = fixture({ id: 'viewer-a' });
+ const agent = {
+ id: 'agent-a',
+ tool_options: Object.fromEntries(
+ Array.from({ length: count }, (_, i) => [
+ `db_ops_${i === 0 ? 'read_0' : `read_${i}`.padEnd(nameLength, 'x')}_mcp_db ops`,
+ { approval_mode },
+ ]),
+ ),
+ };
+ const saved = JSON.stringify(agent);
+ f.getAgent.mockResolvedValue(agent);
+ f.getMCPServerConfigs.mockResolvedValue({
+ 'db ops': { type: 'streamable-http', url: 'https://mcp.example.test/mcp' },
+ });
+ f.getMCPServerTools.mockResolvedValue(
+ formatMCPServerTools('db ops', [{ name: 'db_ops_read_0' }]),
+ );
+ await request(f.app)
+ .post('/reset')
+ .send({ agentId: 'agent-a', toolName: 'read_0_mcp_db_ops' })
+ .expect(200, { reset: true });
+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith(
+ 'viewer-a',
+ 'agent-a',
+ 'read_0_mcp_db_ops',
+ );
+ expect(JSON.stringify(agent)).toBe(saved);
+ },
+);
+
+test('targeted reset rejects oversized legacy options without blocking agent-wide revocation', async () => {
+ const f = fixture({ id: 'viewer-a' });
+ const name = 'q' + '_mcp_z'.repeat(4000);
+ f.getAgent.mockResolvedValue({
+ id: 'agent-a',
+ tool_options: {
+ db_query_mcp_db: { approval_mode: 'always' },
+ [name]: { approval_mode: 'ask' },
+ },
+ });
+ f.getMCPServerTools.mockResolvedValue(formatMCPServerTools('db', [{ name: 'db_query' }]));
+ const response = await request(f.app).post('/reset').send(reset).expect(503);
+ expect(response.body).toEqual({ code: 'APPROVAL_RESET_FAILED' });
+ expect(JSON.stringify(response.body)).not.toContain(name);
+ expect(f.storage.resetToolApprovalGrants).not.toHaveBeenCalled();
+ await request(f.app).post('/reset').send({ agentId: 'agent-a' }).expect(200, { reset: true });
+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith('viewer-a', 'agent-a', undefined);
+});
diff --git a/packages/api/src/agents/hitl/controller.ts b/packages/api/src/agents/hitl/controller.ts
index 02198c073a..eb8a5b64a3 100644
--- a/packages/api/src/agents/hitl/controller.ts
+++ b/packages/api/src/agents/hitl/controller.ts
@@ -13,6 +13,7 @@ import type { HasCapabilityFn } from '~/middleware/capabilities';
import type { MCPServerTools } from '~/tools/definitions';
import type { ParsedServerConfig } from '~/mcp/types';
import { collectMCPToolAliases, aliasMCPToolOptions } from '~/tools/classification';
+import { retainToolOptionsLimits } from '../options';
const resetSchema = z
.object({ agentId: z.string().min(1).max(256), toolName: z.string().min(1).max(256).optional() })
@@ -113,6 +114,7 @@ export function createResetToolApprovalController({
: (aliases.find(({ aliasName }) => aliasName === requested)?.name ?? toolName);
// Match the editor's unsaved migration. Explicit current options win.
options = { ...options };
+ retainToolOptionsLimits(options, agent.tool_options);
for (const [name, value] of Object.entries(agent.tool_options ?? {})) {
const [part, parsed] = splitMCPToolKey(name, boundaries);
if (parsed !== serverName && serverAliases.get(parsed ?? '') !== serverName) continue;
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index c0f13b696a..2cf21a8c00 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -141,6 +141,7 @@ import { createRequestAgentExecutionContext } from './runtime';
import { resolveTurnDeliveryRouting } from './files/delivery';
import { filterFilesByEndpointRuntimeConfig } from '~/files';
import { isFatalAgentInitializationError } from './errors';
+import { assertToolOptionsWithinLimits } from './options';
import { hasActiveFilePolicy } from '../protection/files';
import { resolveAgentCodeExecution } from '~/code/agent';
import { hasActiveFileFieldPolicy } from '~/protection';
@@ -1241,6 +1242,7 @@ export async function initializeAgent(
}
const shouldUseChatProjectContext =
useChatProjectContext ?? params.req?.chatProjectContextEnabled === true;
+ assertToolOptionsWithinLimits(suppliedAgent.tool_options);
const inputAgent = restoreAgentInferenceInput(suppliedAgent);
const agent = shouldUseChatProjectContext ? { ...inputAgent } : inputAgent;
const { user, appConfig } = runtime;
diff --git a/packages/api/src/agents/management.spec.ts b/packages/api/src/agents/management.spec.ts
index bb6535b982..c740073948 100644
--- a/packages/api/src/agents/management.spec.ts
+++ b/packages/api/src/agents/management.spec.ts
@@ -39,6 +39,33 @@ const persistedAgent = {
};
describe('Agent Management contract', () => {
+ it.each([
+ { ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' as const } },
+ Object.fromEntries(
+ Array.from({ length: 1025 }, (_, i) => [`${i}`, { approval_mode: 'ask' as const }]),
+ ),
+ Object.fromEntries(
+ Array.from({ length: 129 }, (_, i) => [
+ `${i}`.padEnd(256, 'é'),
+ { approval_mode: 'ask' as const },
+ ]),
+ ),
+ ])('preserves over-limit legacy options in responses while rejecting writes', (tool_options) => {
+ const response = projectAgentManagementResponse({ ...persistedAgent, tool_options });
+ expect(response.tool_options).toEqual(tool_options);
+ const page = projectAgentManagementListResponse({
+ data: [{ ...persistedAgent, tool_options }],
+ has_more: false,
+ after: null,
+ });
+ expect(page.data[0].tool_options).toEqual(tool_options);
+ expect(
+ agentManagementCreateSchema.safeParse({ provider: 'openAI', model: 'gpt-5', tool_options })
+ .success,
+ ).toBe(false);
+ expect(agentManagementUpdateSchema.safeParse({ tool_options }).success).toBe(false);
+ });
+
it('preserves repository instruction mode through API updates and response projection', () => {
for (const mode of ['prefer', 'defer', 'off'] as const) {
expect(agentManagementUpdateSchema.parse({ repositoryInstructions: mode })).toEqual({
diff --git a/packages/api/src/agents/management.ts b/packages/api/src/agents/management.ts
index d7275ca809..1c51e313fd 100644
--- a/packages/api/src/agents/management.ts
+++ b/packages/api/src/agents/management.ts
@@ -4,7 +4,7 @@ import type {
AgentSubagentGraphEdge,
AgentSubagentsConfig,
} from 'librechat-data-provider';
-import { agentCreateSchema, agentUpdateSchema } from './validation';
+import { agentCreateSchema, agentUpdateSchema, toolOptionsSchema } from './validation';
const MAX_LIST_LIMIT = 100;
const DEFAULT_LIST_LIMIT = 20;
@@ -194,6 +194,8 @@ export const agentManagementResponseSchema: z.ZodType<AgentManagementResponse> =
createdAt: timestampSchema,
updatedAt: timestampSchema,
subagents: agentManagementSubagentsResponseSchema,
+ // Legacy records remain readable; write and execution ceilings are enforced separately.
+ tool_options: z.record(z.string(), toolOptionsSchema).optional(),
})
.strict();
diff --git a/packages/api/src/agents/options.ts b/packages/api/src/agents/options.ts
new file mode 100644
index 0000000000..01d43e4f6b
--- /dev/null
+++ b/packages/api/src/agents/options.ts
@@ -0,0 +1,64 @@
+import type { AgentToolOptions } from 'librechat-data-provider';
+
+// Security ceilings, not tunable quotas: legacy reads and authoring must share the same bounds.
+export const MAX_TOOL_OPTION_KEY_LENGTH = 1024;
+export const MAX_TOOL_OPTION_ENTRIES = 1024;
+export const MAX_TOOL_OPTION_KEY_BYTES = 64 * 1024;
+
+export const AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED = 'AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED';
+
+export class ToolOptionsLimitError extends RangeError {
+ readonly code: string = AGENT_TOOL_OPTIONS_LIMIT_EXCEEDED;
+
+ constructor(message: string) {
+ super(message);
+ this.name = 'ToolOptionsLimitError';
+ }
+}
+
+export function getToolOptionsLimitError(options?: object): string | undefined {
+ let count = 0;
+ let bytes = 0;
+ for (const name in options) {
+ if (!Object.prototype.hasOwnProperty.call(options, name)) continue;
+ if (name.length > MAX_TOOL_OPTION_KEY_LENGTH) {
+ return 'Tool option key exceeds the safety length limit';
+ }
+ if (++count > MAX_TOOL_OPTION_ENTRIES) {
+ return 'Tool options exceed the safety entry limit';
+ }
+ bytes += Buffer.byteLength(name, 'utf8');
+ if (bytes > MAX_TOOL_OPTION_KEY_BYTES) {
+ return 'Tool option keys exceed the safety byte limit';
+ }
+ }
+ return undefined;
+}
+
+export function assertToolOptionsWithinLimits(options?: AgentToolOptions): void {
+ const error = getToolOptionsLimitError(getPersistedToolOptions(options));
+ if (error) throw new ToolOptionsLimitError(error);
+}
+
+const persistedToolOptions = new WeakMap<AgentToolOptions, AgentToolOptions>();
+
+/** This view is for safety accounting, never runtime approval matching. */
+export function getPersistedToolOptions(options?: AgentToolOptions): AgentToolOptions | undefined {
+ return options && (persistedToolOptions.get(options) ?? options);
+}
+
+/** Capture the bounded persisted view before runtime keys are transformed. */
+export function capturePersistedToolOptions(options: AgentToolOptions): AgentToolOptions {
+ let persisted = persistedToolOptions.get(options);
+ if (!persisted) {
+ assertToolOptionsWithinLimits(options);
+ persisted = { ...options };
+ persistedToolOptions.set(options, persisted);
+ }
+ return persisted;
+}
+
+/** Trusted copies and rewrites retain limits without replacing their effective entries. */
+export function retainToolOptionsLimits(target: AgentToolOptions, source?: AgentToolOptions): void {
+ if (source) persistedToolOptions.set(target, capturePersistedToolOptions(source));
+}
diff --git a/packages/api/src/agents/reads.spec.ts b/packages/api/src/agents/reads.spec.ts
index cc6e6d4fe7..90ed014a36 100644
--- a/packages/api/src/agents/reads.spec.ts
+++ b/packages/api/src/agents/reads.spec.ts
@@ -185,6 +185,34 @@ describe('Agent list access', () => {
});
describe('Agent Management read handlers', () => {
+ it('keeps legacy oversized approval options readable in GET and list responses', async () => {
+ const legacy = {
+ ...agent,
+ tool_options: { ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' as const } },
+ };
+ const deps = makeDeps({
+ getAgentWithVersionCount: jest.fn().mockResolvedValue(legacy),
+ getAgentManagementListByAccess: jest
+ .fn()
+ .mockResolvedValue({ data: [legacy], has_more: false, after: null }),
+ });
+ const handlers = createAgentManagementReadHandlers(deps);
+ const getResponse = makeResponse();
+ await handlers.get(makeRequest({ params: { id: agent.id } }), getResponse);
+ expect(getResponse.status).toHaveBeenCalledWith(200);
+ expect(getResponse.json).toHaveBeenCalledWith(
+ expect.objectContaining({ tool_options: legacy.tool_options }),
+ );
+ const listResponse = makeResponse();
+ await handlers.list(makeRequest(), listResponse);
+ expect(listResponse.status).toHaveBeenCalledWith(200);
+ expect(listResponse.json).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: [expect.objectContaining({ tool_options: legacy.tool_options })],
+ }),
+ );
+ });
+
it('lists only ACL-discovered records in the authenticated tenant', async () => {
const deps = makeDeps();
const response = makeResponse();
diff --git a/packages/api/src/agents/updates.spec.ts b/packages/api/src/agents/updates.spec.ts
index f7815c008c..db36b1b5c6 100644
--- a/packages/api/src/agents/updates.spec.ts
+++ b/packages/api/src/agents/updates.spec.ts
@@ -78,6 +78,26 @@ function makeDeps(overrides: Partial<AgentManagementUpdateDeps> = {}): AgentMana
}
describe('Agent Management update handler', () => {
+ it('returns success for an unrelated update without truncating legacy oversized options', async () => {
+ const tool_options = { ['q' + '_mcp_z'.repeat(4000)]: { approval_mode: 'ask' as const } };
+ const stored = { ...existingAgent, tool_options };
+ const deps = makeDeps({
+ getAgentWithVersionCount: jest.fn().mockResolvedValue(stored),
+ updateAgent: jest.fn(async (req: Request, res: Response) => {
+ stored.name = req.body.name;
+ return res.json(stored);
+ }),
+ });
+ const response = makeResponse();
+ await createAgentManagementUpdateHandler(deps)(makeRequest(), response);
+ expect(stored.name).toBe(updatedAgent.name);
+ expect(response.status).toHaveBeenCalledWith(200);
+ expect(response.json).toHaveBeenCalledWith(
+ expect.objectContaining({ name: updatedAgent.name, tool_options }),
+ );
+ expect(stored.tool_options).toEqual(tool_options);
+ });
+
it('delegates a partial update and returns the management projection', async () => {
const deps = makeDeps();
const request = makeRequest();
diff --git a/packages/api/src/agents/validation.spec.ts b/packages/api/src/agents/validation.spec.ts
index 26cbd87ea9..025a6541d7 100644
--- a/packages/api/src/agents/validation.spec.ts
+++ b/packages/api/src/agents/validation.spec.ts
@@ -15,6 +15,12 @@ import {
validateAgentModel,
} from './validation';
+import {
+ MAX_TOOL_OPTION_KEY_LENGTH,
+ MAX_TOOL_OPTION_ENTRIES,
+ MAX_TOOL_OPTION_KEY_BYTES,
+} from './options';
+
const validGroupId = '507f1f77bcf86cd799439011';
const validPromptId = '507f191e810c19729de860ea';
@@ -627,3 +633,40 @@ describe('validateAgentModel', () => {
expect(logViolation).toHaveBeenCalledTimes(1);
});
});
+
+describe('agent tool-option safety limits', () => {
+ const base = { provider: 'openAI', model: 'gpt-4o-mini', tools: [] };
+ const options = (names: string[]) =>
+ Object.fromEntries(names.map((name) => [name, { approval_mode: 'ask' as const }]));
+
+ test.each([
+ ['delimiter-rich key', options(['q' + '_mcp_z'.repeat(4000)])],
+ [
+ 'too many entries',
+ options(Array.from({ length: MAX_TOOL_OPTION_ENTRIES + 1 }, (_, i) => `${i}`)),
+ ],
+ ['aggregate bytes', options(Array.from({ length: 129 }, (_, i) => `${i}`.padEnd(256, 'é')))],
+ ])('rejects %s on both create and update', (_label, tool_options) => {
+ for (const result of [
+ agentCreateSchema.safeParse({ ...base, tool_options }),
+ agentUpdateSchema.safeParse({ tool_options }),
+ ]) {
+ expect(result.success).toBe(false);
+ if (!result.success) expect(result.error.issues[0].path).toEqual(['tool_options']);
+ }
+ });
+
+ test('accepts the inclusive key, entry and aggregate-byte boundaries', () => {
+ for (const tool_options of [
+ options(['x'.repeat(MAX_TOOL_OPTION_KEY_LENGTH)]),
+ options(
+ Array.from({ length: MAX_TOOL_OPTION_ENTRIES }, (_, i) =>
+ `${i}`.padStart(MAX_TOOL_OPTION_KEY_BYTES / MAX_TOOL_OPTION_ENTRIES, 'x'),
+ ),
+ ),
+ ]) {
+ expect(agentCreateSchema.parse({ ...base, tool_options }).tool_options).toEqual(tool_options);
+ expect(agentUpdateSchema.parse({ tool_options }).tool_options).toEqual(tool_options);
+ }
+ });
+});
diff --git a/packages/api/src/agents/validation.ts b/packages/api/src/agents/validation.ts
index cde6c1fb98..fbe4aeb83c 100644
--- a/packages/api/src/agents/validation.ts
+++ b/packages/api/src/agents/validation.ts
@@ -21,6 +21,7 @@ import type {
AgentInstructionsPrompt,
} from 'librechat-data-provider';
import type { Request, Response } from 'express';
+import { getToolOptionsLimitError } from './options';
/**
* Permissive Request alias used by {@link validateAgentModel}. Accepts either
@@ -174,8 +175,14 @@ export const toolOptionsSchema: z.ZodObject<
/** Agent tool options - map of tool_id to tool options */
export const agentToolOptionsSchema: z.ZodOptional<
- z.ZodRecord<z.ZodString, typeof toolOptionsSchema>
-> = z.record(z.string(), toolOptionsSchema).optional();
+ z.ZodEffects<z.ZodRecord<z.ZodString, typeof toolOptionsSchema>>
+> = z
+ .record(z.string(), toolOptionsSchema)
+ .superRefine((options, ctx) => {
+ const message = getToolOptionsLimitError(options);
+ if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, message });
+ })
+ .optional();
/**
* Subagent spawning configuration for an agent. `agent_ids` and `graphs` are
@@ -525,35 +532,7 @@ export const agentBaseSchema: z.ZodObject<
recursion_limit: z.ZodOptional<z.ZodNumber>;
conversation_starters: z.ZodOptional<z.ZodArray<z.ZodString, 'many'>>;
tool_resources: typeof agentToolResourcesSchema;
- tool_options: z.ZodOptional<
- z.ZodRecord<
- z.ZodString,
- z.ZodObject<
- {
- defer_loading: z.ZodOptional<z.ZodBoolean>;
- allowed_callers: z.ZodOptional<
- z.ZodArray<z.ZodEnum<['direct', 'code_execution']>, 'many'>
- >;
- run_in_background: z.ZodOptional<z.ZodBoolean>;
- describe_intent: z.ZodOptional<z.ZodBoolean>;
- },
- 'strip',
- z.ZodTypeAny,
- {
- defer_loading?: boolean | undefined;
- allowed_callers?: ('direct' | 'code_execution')[] | undefined;
- run_in_background?: boolean | undefined;
- describe_intent?: boolean | undefined;
- },
- {
- defer_loading?: boolean | undefined;
- allowed_callers?: ('direct' | 'code_execution')[] | undefined;
- run_in_background?: boolean | undefined;
- describe_intent?: boolean | undefined;
- }
- >
- >
- >;
+ tool_options: typeof agentToolOptionsSchema;
subagents: typeof agentSubagentsSchema;
support_contact: z.ZodOptional<
z.ZodObject<
@@ -708,35 +687,7 @@ export const agentCreateSchema: z.ZodObject<
recursion_limit: z.ZodOptional<z.ZodNumber>;
conversation_starters: z.ZodOptional<z.ZodArray<z.ZodString, 'many'>>;
tool_resources: typeof agentToolResourcesSchema;
- tool_options: z.ZodOptional<
- z.ZodRecord<
- z.ZodString,
- z.ZodObject<
- {
- defer_loading: z.ZodOptional<z.ZodBoolean>;
- allowed_callers: z.ZodOptional<
- z.ZodArray<z.ZodEnum<['direct', 'code_execution']>, 'many'>
- >;
- run_in_background: z.ZodOptional<z.ZodBoolean>;
- describe_intent: z.ZodOptional<z.ZodBoolean>;
- },
- 'strip',
- z.ZodTypeAny,
- {
- defer_loading?: boolean | undefined;
- allowed_callers?: ('direct' | 'code_execution')[] | undefined;
- run_in_background?: boolean | undefined;
- describe_intent?: boolean | undefined;
- },
- {
- defer_loading?: boolean | undefined;
- allowed_callers?: ('direct' | 'code_execution')[] | undefined;
- run_in_background?: boolean | undefined;
- describe_intent?: boolean | undefined;
- }
- >
- >
- >;
+ tool_options: typeof agentToolOptionsSchema;
subagents: typeof agentSubagentsSchema;
support_contact: z.ZodOptional<
z.ZodObject<
@@ -847,35 +798,7 @@ export const agentUpdateSchema: z.ZodObject<
recursion_limit: z.ZodOptional<z.ZodNumber>;
conversation_starters: z.ZodOptional<z.ZodArray<z.ZodString, 'many'>>;
tool_resources: typeof agentToolResourcesSchema;
- tool_options: z.ZodOptional<
- z.ZodRecord<
- z.ZodString,
- z.ZodObject<
- {
- defer_loading: z.ZodOptional<z.ZodBoolean>;
- allowed_callers: z.ZodOptional<
- z.ZodArray<z.ZodEnum<['direct', 'code_execution']>, 'many'>
- >;
- run_in_background: z.ZodOptional<z.ZodBoolean>;
- describe_intent: z.ZodOptional<z.ZodBoolean>;
- },
- 'strip',
- z.ZodTypeAny,
- {
- defer_loading?: boolean | undefined;
- allowed_callers?: ('direct' | 'code_execution')[] | undefined;
- run_in_background?: boolean | undefined;
- describe_intent?: boolean | undefined;
- },
- {
- defer_loading?: boolean | undefined;
- allowed_callers?: ('direct' | 'code_execution')[] | undefined;
- run_in_background?: boolean | undefined;
- describe_intent?: boolean | undefined;
- }
- >
- >
- >;
+ tool_options: typeof agentToolOptionsSchema;
subagents: typeof agentSubagentsSchema;
support_contact: z.ZodOptional<
z.ZodObject<
diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.ts
index 845f6a0096..c05aab9f35 100644
--- a/packages/api/src/mcp/utils.ts
+++ b/packages/api/src/mcp/utils.ts
@@ -10,6 +10,7 @@ import {
import type { AgentToolOptions, MCPOptions } from 'librechat-data-provider';
import type { ParsedServerConfig } from '~/mcp/types';
import type { RequestBody } from '~/types';
+import { capturePersistedToolOptions, retainToolOptionsLimits } from '~/agents/options';
import { isApiKeyHeaderOverridden, isGeneratedUserApiKeyVariable } from './headers';
import { isDirectOpenIDBearerRecoveryEnabled } from '~/mcp/openid';
import { ALLOWED_BODY_FIELDS, isPluginSourced } from '~/utils/env';
@@ -162,6 +163,7 @@ export function normalizeAgentToolKeys(params: {
let optionsChanged = false;
let nextOptions: AgentToolOptions | undefined;
if (toolOptions) {
+ capturePersistedToolOptions(toolOptions);
nextOptions = {};
for (const [key, options] of Object.entries(toolOptions)) {
const rewritten = rewriteKey(key);
@@ -178,6 +180,7 @@ export function normalizeAgentToolKeys(params: {
}
}
+ if (optionsChanged && nextOptions) retainToolOptionsLimits(nextOptions, toolOptions);
return {
tools: toolsChanged ? nextTools : tools,
toolOptions: optionsChanged ? nextOptions : toolOptions,
diff --git a/packages/api/src/tools/classification.ts b/packages/api/src/tools/classification.ts
index b06b609dfb..6f9439a35c 100644
--- a/packages/api/src/tools/classification.ts
+++ b/packages/api/src/tools/classification.ts
@@ -35,6 +35,7 @@ import type { CodeCapabilityConfigLoader } from '~/code/capabilities';
import { supportsProgrammaticCodeExecution } from '~/code/capabilities';
import { createContextProgrammaticBashTool } from '~/code/command';
import { sanitizeGeminiSchema } from '~/mcp/zod';
+import { capturePersistedToolOptions } from '~/agents/options';
export type { LCTool, LCToolRegistry, AllowedCaller, JsonSchemaType };
@@ -121,6 +122,7 @@ export function aliasMCPToolOptions(
}
for (const { name, aliasName } of aliases) {
if (agentToolOptions[name] == null && agentToolOptions[aliasName] != null) {
+ capturePersistedToolOptions(agentToolOptions);
agentToolOptions[name] = agentToolOptions[aliasName];
}
}