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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🫰 feat: Configure Tool Approval Modes Per Agent (#16707)
lia-by-librechat[bot]0e3c9088f6b7
diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex 8cc6943194..c702c35ca9 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -3268,6 +3268,33 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {);});+ it('carries only server-owned approval bindings through the claimed resume', async () => {+ const bindings = {+ tc1: {+ agentId: AGENT_ID,+ instanceName: 'query_mcp_db',+ toolName: 'query_mcp_db',+ binding: 'server-digest',+ scope: 'chat',+ },+ };+ mockGenerationJobManager.getJob.mockResolvedValue(+ makeToolApprovalJob({ metadata: { pendingAction: { toolApprovalBindings: bindings } } }),+ );+ await post(approveBody({ toolApprovalBindings: { tc1: { binding: 'forged' } } }));+ await settled;+ await flush();+ const client = await mockInitializeClient.mock.results[0].value.then((r) => r.client);+ expect(client.resumeCompletion).toHaveBeenCalledWith(+ expect.objectContaining({+ reviewedToolApprovals: {+ bindings,+ decisions: [{ tool_call_id: 'tc1', decision: 'approve' }],+ },+ }),+ );+ });+it('seeds the rebuilt client from the context meta captured at the pause', async () => {const contextMeta = {calibrationRatio: 1.25,diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex b2be1bfd56..7d0108bb2f 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -45,6 +45,8 @@ const {buildPendingAction,toClientPendingAction,captureCodeExecutionApprovalBinding,+ captureRunToolApprovalBindings,+ describeRememberedToolApprovals,computeAgentRequestFingerprint,computeLegacyAgentRequestFingerprint,getRunDiscoveredTools,@@ -4421,37 +4423,42 @@ class AgentClient extends BaseClient {)? captureCodeExecutionApprovalBinding(reachableAgents): undefined;- const pendingAction = buildPendingAction(interruptPayload, {- streamId,- conversationId: this.conversationId,- // runId mirrors the LangGraph checkpoint namespace when the SDK provides it- // (its documented meaning), falling back to the response message id.- runId: interrupt.checkpointNs ?? this.responseMessageId,- responseMessageId: this.responseMessageId,- interruptId: interrupt.interruptId,- // thread_id was bound to conversationId at run config (config.configurable);- // fall back to it when the SDK doesn't echo threadId on the interrupt.- threadId: interrupt.threadId ?? this.conversationId,- ttlMs: getApprovalTtlMs(checkpointerCfg),- // Bind the pause to the authoritative project identity/revision. The key is- // server-only and is checked before provider/tool startup on resume.- projectContextKey: getChatProjectContextKey(this.options.req?.chatProjectContext),- expiresAt: this.options.req?._agentEventBindingRetention?.expiredAt,- // Pin the graph-determining request fields so resume can't rebuild this paused- // run on a different agent/tool set (esp. ephemeral agents, whose agent_id is- // undefined so the id guard can't tell two configs apart).- // Keep the legacy digest in its established field so an old replica can- // resume pauses written during a rolling deploy; current replicas also- // enforce the stricter code-environment-aware digest below.- requestFingerprint: computeLegacyAgentRequestFingerprint(this.options.req?.body ?? {}),- requestFingerprintV2: computeAgentRequestFingerprint(this.options.req?.body ?? {}),- // Persist those same fields verbatim so the resume route can REPLAY them — a- // reload/cross-replica resume can't reconstruct the ephemeral config client-side,- // so the server restores it and rebuilds the same graph (and the fingerprint matches).- resumeContext,- codeExecutionBinding,- toolApprovalAliases: collectAllowAlwaysAliases(interruptPayload, getRunMCPToolAliases(run)),- });+ const toolApprovalBindings = captureRunToolApprovalBindings(run, interruptPayload);+ const pendingAction = buildPendingAction(+ describeRememberedToolApprovals(interruptPayload, toolApprovalBindings, run),+ {+ streamId,+ conversationId: this.conversationId,+ // runId mirrors the LangGraph checkpoint namespace when the SDK provides it+ // (its documented meaning), falling back to the response message id.+ runId: interrupt.checkpointNs ?? this.responseMessageId,+ responseMessageId: this.responseMessageId,+ interruptId: interrupt.interruptId,+ // thread_id was bound to conversationId at run config (config.configurable);+ // fall back to it when the SDK doesn't echo threadId on the interrupt.+ threadId: interrupt.threadId ?? this.conversationId,+ ttlMs: getApprovalTtlMs(checkpointerCfg),+ // Bind the pause to the authoritative project identity/revision. The key is+ // server-only and is checked before provider/tool startup on resume.+ projectContextKey: getChatProjectContextKey(this.options.req?.chatProjectContext),+ expiresAt: this.options.req?._agentEventBindingRetention?.expiredAt,+ // Pin the graph-determining request fields so resume can't rebuild this paused+ // run on a different agent/tool set (esp. ephemeral agents, whose agent_id is+ // undefined so the id guard can't tell two configs apart).+ // Keep the legacy digest in its established field so an old replica can+ // resume pauses written during a rolling deploy; current replicas also+ // enforce the stricter code-environment-aware digest below.+ requestFingerprint: computeLegacyAgentRequestFingerprint(this.options.req?.body ?? {}),+ requestFingerprintV2: computeAgentRequestFingerprint(this.options.req?.body ?? {}),+ // Persist those same fields verbatim so the resume route can REPLAY them — a+ // reload/cross-replica resume can't reconstruct the ephemeral config client-side,+ // so the server restores it and rebuilds the same graph (and the fingerprint matches).+ resumeContext,+ codeExecutionBinding,+ toolApprovalAliases: collectAllowAlwaysAliases(interruptPayload, getRunMCPToolAliases(run)),+ },+ );+ pendingAction.toolApprovalBindings = toolApprovalBindings;// Job-replacement guard: streamId == conversationId is reused per conversation, so a// newer request can replace this run's job. If this (older) run hits an interrupt@@ -5043,6 +5050,7 @@ class AgentClient extends BaseClient {// opts into the tool-approval wiring. Non-resumable callers (OpenAI-compat, Responses)// leave this off so an approval-gated tool can't pause where there's no resume path.hitlCapable: true,+ toolApprovalStorage: db,resolvedToolApprovalHooks,toolApprovalAllows: resolveRunToolApprovalAllows(agentsEConfig?.toolApproval,@@ -5407,6 +5415,7 @@ class AgentClient extends BaseClient {*/async resumeCompletion({resumeValue,+ reviewedToolApprovals,seedContent = [],runSteps = [],storedMessages = [],@@ -5846,6 +5855,8 @@ class AgentClient extends BaseClient {// The resumed run can pause AGAIN (another tool, a follow-up question), and this// controller owns that lifecycle, so it must keep the HITL wiring on the rebuilt run.hitlCapable: true,+ toolApprovalStorage: db,+ reviewedToolApprovals,resolvedToolApprovalHooks,toolApprovalAllows: resolveRunToolApprovalAllows(agentsEConfig?.toolApproval,diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.jsindex 2c9ec60c04..4784ca4964 100644--- a/api/server/controllers/agents/client.test.js+++ b/api/server/controllers/agents/client.test.js@@ -2290,6 +2290,14 @@ describe('AgentClient - startup telemetry', () => {});it.each([+ ...['ask', 'chat', 'always'].map((mode) => ({+ name: `a deselected MCP tool retaining ${mode} mode`,+ toolApproval: { enabled: true, mode: 'bypass', agentModes: true },+ tool_options: {+ deselected_mcp_db: { approval_mode: mode },+ read_file: { approval_mode: 'allow' },+ },+ })),{name: 'a bypass-only approval policy',toolApproval: { enabled: true, mode: 'bypass' },@@ -2300,6 +2308,44 @@ describe('AgentClient - startup telemetry', () => {toolApproval: { enabled: true, mode: 'bypass', ask: ['approval_probe'] },subagentAgentConfigs: undefined,},+ {+ name: 'dontAsk denied attached-code lazy graph member',+ toolApproval: { enabled: true, mode: 'dontAsk', allow: ['read_file'] },+ primaryTools: [{ name: 'read_file' }],+ subagentAgentConfigs: [+ {+ id: 'lazy-parent',+ subagentGraphMemberMetadata: [+ {+ id: 'attached-member',+ codeExecutionContext: { environmentType: 'attached' },+ skillAuthoringAvailable: true,+ },+ ],+ },+ ],+ },+ {+ name: 'dontAsk fallback-denied ask agent tool',+ toolApproval: { enabled: true, mode: 'dontAsk', allow: ['safe_mcp_db'] },+ primaryTools: [{ name: 'query_mcp_db' }, { name: 'safe_mcp_db' }],+ tool_options: { query_mcp_db: { approval_mode: 'ask' } },+ subagentAgentConfigs: undefined,+ },+ {+ name: 'dontAsk fallback-denied chat agent tool',+ toolApproval: { enabled: true, mode: 'dontAsk', allow: ['safe_mcp_db'] },+ primaryTools: [{ name: 'query_mcp_db' }, { name: 'safe_mcp_db' }],+ tool_options: { query_mcp_db: { approval_mode: 'chat' } },+ subagentAgentConfigs: undefined,+ },+ {+ name: 'dontAsk fallback-denied always agent tool',+ toolApproval: { enabled: true, mode: 'dontAsk', allow: ['safe_mcp_db'] },+ primaryTools: [{ name: 'query_mcp_db' }, { name: 'safe_mcp_db' }],+ tool_options: { query_mcp_db: { approval_mode: 'always' } },+ subagentAgentConfigs: undefined,+ },{name: 'ask_user_question denied by the approval policy',toolApproval: { enabled: true, deny: ['ask_*'] },@@ -2318,7 +2364,7 @@ describe('AgentClient - startup telemetry', () => {},])('does not reject scheduled runs for $name',- async ({ toolApproval, primaryTools, subagentAgentConfigs }) => {+ async ({ toolApproval, primaryTools, subagentAgentConfigs, tool_options }) => {mockDeleteAgentCheckpoint.mockReset().mockResolvedValue(undefined);const processStream = jest.fn().mockResolvedValue();mockCreateRun.mockResolvedValueOnce({@@ -2345,6 +2391,7 @@ describe('AgentClient - startup telemetry', () => {hide_sequential_outputs: false,tools: primaryTools ?? [{ name: 'read_file' }],subagentAgentConfigs,+ tool_options,},endpointTokenConfig: {},eventHandlers: {},@@ -2377,6 +2424,124 @@ describe('AgentClient - startup telemetry', () => {},);+ it.each([+ {+ name: 'selected review-gated tool',+ tools: [{ name: 'query_mcp_db' }],+ tool_options: { query_mcp_db: { approval_mode: 'ask' } },+ },+ {+ name: 'selected tool with verified legacy mode',+ tools: [{ name: 'query_mcp_db' }],+ tool_options: { db_query_mcp_db: { approval_mode: 'chat' } },+ mcpToolAliases: [{ name: 'query_mcp_db', aliasName: 'db_query_mcp_db' }],+ },+ {+ name: 'unresolved lazy review-gated child',+ tools: [{ name: 'read_file' }],+ lazySubagentConfigs: [+ { id: 'lazy-agent', tool_options: { query_mcp_db: { approval_mode: 'always' } } },+ ],+ },+ ])(+ 'rejects scheduled memory-store runs with a $name before provider execution',+ async (surface) => {+ const createRunBefore = mockCreateRun.mock.calls.length;+ const client = new AgentClient({+ req: {+ user: { id: 'user-123' },+ body: {},+ config: {+ endpoints: {+ [EModelEndpoint.agents]: {+ toolApproval: { enabled: true, mode: 'bypass', agentModes: true },+ },+ },+ },+ _isScheduledFire: true,+ _resumableStreamId: 'scheduled-agent-mode',+ },+ res: {},+ agent: {+ id: 'agent-123',+ endpoint: EModelEndpoint.openAI,+ provider: EModelEndpoint.openAI,+ model_parameters: { model: 'gpt-4' },+ ...surface,+ },+ endpointTokenConfig: {},+ eventHandlers: {},+ contentParts: [],+ collectedUsage: [],+ artifactPromises: [],+ });+ client.conversationId = 'scheduled-agent-mode';+ client.responseMessageId = 'scheduled-agent-mode-response';+ client.parentMessageId = 'scheduled-agent-mode-parent';+ await expect(client.chatCompletion({ payload: [] })).rejects.toMatchObject({+ code: 'SCHEDULED_HITL_REQUIRES_SHARED_STORE',+ });+ expect(mockCreateRun).toHaveBeenCalledTimes(createRunBefore);+ },+ );++ it.each(['db', 'Db', 'dB', 'DB'])(+ 'refuses unresolved %s legacy-hook schedules before provider startup under canonical dontAsk allow',+ async (prefix) => {+ mockIsHITLEnabled.mockReturnValue(true);+ const hook = jest.fn(async () => ({ decision: 'ask' }));+ const unregister = registerToolApprovalHook(() => hook, {+ matcher: `^${prefix}_query_mcp_db$`,+ });+ const createRunBefore = mockCreateRun.mock.calls.length;+ const client = new AgentClient({+ req: {+ user: { id: 'user-123' },+ body: {},+ config: {+ endpoints: {+ [EModelEndpoint.agents]: {+ toolApproval: {+ enabled: true,+ mode: 'dontAsk',+ allow: ['query_mcp_db', 'subagent'],+ },+ },+ },+ },+ _isScheduledFire: true,+ _resumableStreamId: 'scheduled-legacy-hook',+ },+ res: {},+ agent: {+ id: 'agent-123',+ endpoint: EModelEndpoint.openAI,+ provider: EModelEndpoint.openAI,+ model_parameters: { model: 'gpt-4' },+ tools: [{ name: 'subagent' }],+ lazySubagentConfigs: [{ id: 'lazy-child', tools: ['query_mcp_db'] }],+ },+ endpointTokenConfig: {},+ eventHandlers: {},+ contentParts: [],+ collectedUsage: [],+ artifactPromises: [],+ });+ client.conversationId = 'scheduled-legacy-hook';+ client.responseMessageId = 'scheduled-legacy-hook-response';+ client.parentMessageId = 'scheduled-legacy-hook-parent';+ try {+ await expect(client.chatCompletion({ payload: [] })).rejects.toMatchObject({+ code: 'SCHEDULED_HITL_REQUIRES_SHARED_STORE',+ });+ expect(mockCreateRun).toHaveBeenCalledTimes(createRunBefore);+ expect(hook).not.toHaveBeenCalled();+ } finally {+ unregister();+ }+ },+ );+it('uses request-scoped hook resolution when deciding whether a scheduled run can pause', async () => {mockIsHITLEnabled.mockReturnValue(true);registerToolApprovalHook((context) =>diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex d331920151..290d3ccea1 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -1986,6 +1986,10 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)const resumeClient = () =>client.resumeCompletion({resumeValue: mapped.resumeValue,+ reviewedToolApprovals: {+ bindings: pendingAction.toolApprovalBindings,+ decisions: req.body.decisions ?? [],+ },seedContent,runSteps: resumeState?.runSteps ?? [],storedMessages,@@ -2009,6 +2013,7 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)code: 'RUN_REPLACED',});}+await recordToolApprovalAllows({userId,conversationId,diff --git a/api/server/routes/agents/tools.js b/api/server/routes/agents/tools.jsindex 843e3a56f2..b0bcb5e4f7 100644--- a/api/server/routes/agents/tools.js+++ b/api/server/routes/agents/tools.js@@ -1,14 +1,40 @@const express = require('express');const {reportLocatorTraversalFailure,+ createResetToolApprovalController,createContentFilter,extractToolArgumentContent,} = require('@librechat/api');const { callTool, verifyToolAuth, getToolCalls } = require('~/server/controllers/tools');+const { ResourceType, PermissionBits } = require('librechat-data-provider');+const { checkPermission } = require('~/server/services/PermissionService');+const { hasCapability } = require('~/server/middleware/roles/capabilities');+const { resolveAllMcpConfigs } = require('~/server/services/MCP');+const { getMCPServerTools } = require('~/server/services/Config');const { getAvailableTools } = require('~/server/controllers/PluginController');const { toolCallLimiter } = require('~/server/middleware');+const approvalStorage = require('~/models');const router = express.Router();+router.post(+ '/approvals/reset',+ toolCallLimiter,+ createResetToolApprovalController({+ storage: approvalStorage,+ hasCapability,+ getMCPServerConfigs: resolveAllMcpConfigs,+ getMCPServerTools,+ getAgent: approvalStorage.getAgent,+ canAccessAgent: (agent, user) =>+ checkPermission({+ userId: user.id,+ role: user.role,+ resourceType: ResourceType.AGENT,+ resourceId: agent._id,+ requiredPermission: PermissionBits.VIEW,+ }),+ }),+);const filterToolArguments = createContentFilter({onTraversalFailure: reportLocatorTraversalFailure,getFilters: (req) => req.config?.filters,diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex eb66305571..904853685f 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -2,6 +2,7 @@ const { logger } = require('@librechat/data-schemas');const { createContentAggregator, GraphNodeKeys } = require('@librechat/agents');const {resolveSender,+ copyToolApprovalAdmissionMetadata,resolveRunConversation,resolveAdmittedCodeEnvironmentDecision,createConcurrencyLimiter,@@ -1179,30 +1180,38 @@ const initializeClientWithProvider = async ({codeExecutionAvailable: lazyCodeEnvAvailable,memoryAvailable,});- return {- id: agent.id,- name: agent.name,- description: agent.description,- provider: agent.provider,- model: agent.model,- model_parameters: { model: agent.model_parameters?.model },- recursion_limit: agent.recursion_limit,- memory_scope: agent.memory_scope,- memoryToolsRegistered:- memoryAvailable === true && agent.tools?.includes(Tools.memory) === true,- subagents: agent.subagents,- configId: getLazySubagentConfigId(agent),- codeEnvAvailable: lazyCodeEnvAvailable,- statefulCodeSessions,- statefulCodeEnvironment,- codeExecutionContext,- codeSessionKey: codeExecutionContext?.codeSessionKey,- includeReasoningHistory: getIncludeReasoningHistory(agent),- alwaysApplySkillPrimes,- historicalToolNames,- historicalMcpServerNames,- skillAuthoringAvailable: skillAuthoringAvailable === true,- };+ return copyToolApprovalAdmissionMetadata(+ {+ id: agent.id,+ name: agent.name,+ description: agent.description,+ provider: agent.provider,+ model: agent.model,+ model_parameters: { model: agent.model_parameters?.model },+ recursion_limit: agent.recursion_limit,+ memory_scope: agent.memory_scope,+ memoryToolsRegistered:+ memoryAvailable === true && agent.tools?.includes(Tools.memory) === true,+ subagents: agent.subagents,+ configId: getLazySubagentConfigId(agent),+ codeEnvAvailable: lazyCodeEnvAvailable,+ statefulCodeSessions,+ statefulCodeEnvironment,+ codeExecutionContext,+ codeSessionKey: codeExecutionContext?.codeSessionKey,+ includeReasoningHistory: getIncludeReasoningHistory(agent),+ alwaysApplySkillPrimes,+ historicalToolNames,+ historicalMcpServerNames,+ skillAuthoringAvailable: skillAuthoringAvailable === true,+ },+ agent,+ {+ skillPrimes: alwaysApplySkillPrimes,+ rawMcpServerNames: historicalMcpServerNames,+ toolsAvailable: enabledCapabilities.has(AgentCapabilities.tools),+ },+ );};const loadSubagentMetadata = async (agentId) => {@@ -1449,44 +1458,47 @@ const initializeClientWithProvider = async ({const lazyChildren = childDescriptors.filter((child) => child.configId);const eagerChildren = childDescriptors.filter((child) => !child.configId);const subagentGraphMemberMetadata = await loadGraphMemberCapabilityMetadata(metadata);- return {- id: metadata.id,- name: metadata.name,- description: metadata.description,- provider: metadata.provider,- model: metadata.model,- model_parameters: metadata.model_parameters,- recursion_limit: metadata.recursion_limit,- memory_scope: metadata.memory_scope,- memoryToolsRegistered: metadata.memoryToolsRegistered,- subagents: metadata.subagents,- configId: metadata.configId,- codeEnvAvailable: metadata.codeEnvAvailable,- statefulCodeSessions: metadata.statefulCodeSessions,- statefulCodeEnvironment: metadata.statefulCodeEnvironment,- codeExecutionContext: metadata.codeExecutionContext,- codeSessionKey: metadata.codeSessionKey,- includeReasoningHistory: metadata.includeReasoningHistory,- skillAuthoringAvailable: metadata.skillAuthoringAvailable,- alwaysApplySkillPrimes: metadata.alwaysApplySkillPrimes,- historicalToolNames: metadata.historicalToolNames,- historicalMcpServerNames: metadata.historicalMcpServerNames,- lazySubagentConfigs: lazyChildren,- subagentAgentConfigs: eagerChildren,- subagentGraphMemberMetadata,- resolve: async (context) =>- initializeLazySubagent({- agentId: metadata.id,- configId: metadata.configId,- context,- lazyChildren,- }).then(async (config) => {- config.subagentAgentConfigs = eagerChildren;- graphMemberConfigsById.set(config.id, config);- await resolveGraphSubagentsFor(config, context.signal);- return config;- }),- };+ return copyToolApprovalAdmissionMetadata(+ {+ id: metadata.id,+ name: metadata.name,+ description: metadata.description,+ provider: metadata.provider,+ model: metadata.model,+ model_parameters: metadata.model_parameters,+ recursion_limit: metadata.recursion_limit,+ memory_scope: metadata.memory_scope,+ memoryToolsRegistered: metadata.memoryToolsRegistered,+ subagents: metadata.subagents,+ configId: metadata.configId,+ codeEnvAvailable: metadata.codeEnvAvailable,+ statefulCodeSessions: metadata.statefulCodeSessions,+ statefulCodeEnvironment: metadata.statefulCodeEnvironment,+ codeExecutionContext: metadata.codeExecutionContext,+ codeSessionKey: metadata.codeSessionKey,+ includeReasoningHistory: metadata.includeReasoningHistory,+ skillAuthoringAvailable: metadata.skillAuthoringAvailable,+ alwaysApplySkillPrimes: metadata.alwaysApplySkillPrimes,+ historicalToolNames: metadata.historicalToolNames,+ historicalMcpServerNames: metadata.historicalMcpServerNames,+ lazySubagentConfigs: lazyChildren,+ subagentAgentConfigs: eagerChildren,+ subagentGraphMemberMetadata,+ resolve: async (context) =>+ initializeLazySubagent({+ agentId: metadata.id,+ configId: metadata.configId,+ context,+ lazyChildren,+ }).then(async (config) => {+ config.subagentAgentConfigs = eagerChildren;+ graphMemberConfigsById.set(config.id, config);+ await resolveGraphSubagentsFor(config, context.signal);+ return config;+ }),+ },+ metadata,+ );}),);return descriptors.filter(Boolean);diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex 8b2e8e9b0d..1771bf2fca 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -1438,6 +1438,456 @@ describe('initializeClient — subagent loading', () => {expect(agentClientArgs.agentConfigs.has(SUBAGENT_ID)).toBe(false);});+ it.each(['ask', 'chat', 'always', 'allow', undefined])(+ 'retains server-only lazy approval admission for %s without initializing the child',+ async (mode) => {+ const toolName = 'query_mcp_fixture';+ const child = await createAgent({+ id: SUBAGENT_ID,+ name: 'Review-capable child',+ provider: 'openai',+ model: 'gpt-4',+ author: new mongoose.Types.ObjectId(),+ tools: [toolName],+ tool_options: {+ [toolName]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ });+ 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 initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ const { canAgentGraphPause } = jest.requireActual('@librechat/api');+ const policy = { enabled: true, mode: 'bypass' };+ expect(canAgentGraphPause({ policy, agents: [agentClientArgs.agent] })).toBe(+ mode != null && mode !== 'allow',+ );+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: [toolName] },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, enabled: false },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(false);+ const descriptor = agentClientArgs.agent.lazySubagentConfigs[0];+ expect(descriptor).not.toHaveProperty('tool_options');+ expect(descriptor).not.toHaveProperty('tools');+ expect(JSON.stringify(descriptor)).not.toContain('approval_revision');+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ },+ );++ it.each([[[]], [['other_mcp_fixture']]])(+ 'does not let deselected lazy modes block admission with tools=%j',+ async (tools) => {+ const child = await createAgent({+ id: SUBAGENT_ID,+ name: 'Inactive review option',+ provider: 'openai',+ model: 'gpt-4',+ author: new mongoose.Types.ObjectId(),+ tools,+ tool_options: { query_mcp_fixture: { 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 initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ expect(+ jest.requireActual('@librechat/api').canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(false);+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ },+ );++ it.each([+ ['query_mcp_db', 'db_query_mcp_db', ['db'], true],+ ['query_mcp_DB', 'db_query_mcp_DB', ['DB'], true],+ ['query_mcp_db ops', 'db_ops_query_mcp_db_ops', ['db ops'], true],+ [`${Constants.mcp_all}${Constants.mcp_delimiter}db`, 'read_mcp_other', ['db', 'other'], false],+ [+ `${Constants.mcp_all}${Constants.mcp_delimiter}db`,+ 'read_mcp_other_mcp_db',+ ['db', 'other_mcp_db'],+ false,+ ],+ [+ `${Constants.mcp_all}${Constants.mcp_delimiter}db ops`,+ 'read_mcp_db_ops',+ ['db ops', 'other'],+ true,+ ],+ [+ `${Constants.mcp_all}${Constants.mcp_delimiter}Finance_mcp_EU`,+ 'get_mcp_version_mcp_Finance_mcp_EU',+ ['Finance_mcp_EU'],+ true,+ ],+ [+ `${Constants.mcp_all}${Constants.mcp_delimiter}db_ops`,+ 'read_mcp_db ops',+ ['db_ops', 'db ops'],+ false,+ ],+ ])(+ 'classifies real lazy spellings and wildcard scope before resolution: %s / %s',+ async (selected, option, servers, expected) => {+ const child = await createAgent({+ id: SUBAGENT_ID,+ name: 'Scoped review child',+ provider: 'openai',+ model: 'gpt-4',+ author: testUser._id,+ tools: [selected],+ tool_options: { [option]: { approval_mode: 'ask' } },+ });+ await grantView(child);+ mockGetAccessibleMcpServerNames.mockResolvedValue(servers);+ mockInitializeAgent.mockResolvedValue(+ makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ );+ const req = makeSubagentReq();+ req.config.endpoints.agents.capabilities.push('tools');+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ const descriptor = agentClientArgs.agent.lazySubagentConfigs[0];+ const { canAgentGraphPause } = jest.requireActual('@librechat/api');+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(expected);+ expect(descriptor).not.toHaveProperty('mcpToolAliases');+ expect(descriptor).not.toHaveProperty('tool_options');+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ },+ );++ it.each(['ask', 'chat', 'always'])(+ 'disabled MCP capability excludes real saved lazy selections before delegation: %s',+ async (mode) => {+ const child = await createAgent({+ id: SUBAGENT_ID,+ name: 'Disabled MCP child',+ provider: 'openai',+ model: 'gpt-4',+ author: testUser._id,+ tools: ['query_mcp_fixture'],+ tool_options: { query_mcp_fixture: { approval_mode: mode } },+ });+ await grantView(child);+ mockInitializeAgent.mockResolvedValue(+ makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ );+ const { canAgentGraphPause } = jest.requireActual('@librechat/api');+ for (const enabled of [false, true]) {+ const req = makeSubagentReq();++ if (enabled) req.config.endpoints.agents.capabilities.push('tools');+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(enabled);+ expect(agentClientArgs.agent.lazySubagentConfigs[0]).not.toHaveProperty('tool_options');+ }+ expect(mockInitializeAgent).toHaveBeenCalledTimes(2);+ },+ );++ it('requires durable approval for a real unresolved lazy legacy selection', async () => {+ const child = await createAgent({+ id: SUBAGENT_ID,+ name: 'Unresolved legacy selection',+ provider: 'openai',+ model: 'gpt-4',+ author: new mongoose.Types.ObjectId(),+ tools: ['fixture_query_mcp_fixture'],+ tool_options: { query_mcp_fixture: { approval_mode: 'chat' } },+ });+ 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 initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ expect(+ jest.requireActual('@librechat/api').canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(true);+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ expect(agentClientArgs.agent.lazySubagentConfigs[0]).not.toHaveProperty('mcpToolAliases');+ });++ it('retains review capability through nested lazy descriptors before delegation', async () => {+ const leafId = 'approval-lazy-leaf';+ await createViewableAgent(SUBAGENT_ID, {+ enabled: true,+ allowSelf: false,+ agent_ids: [leafId],+ });+ const leaf = await createAgent({+ id: leafId,+ name: 'Approval leaf',+ provider: 'openai',+ model: 'gpt-4',+ author: new mongoose.Types.ObjectId(),+ tools: ['query_mcp_fixture'],+ tool_options: { query_mcp_fixture: { approval_mode: 'chat' } },+ });+ await grantView(leaf);+ mockInitializeAgent.mockResolvedValue(+ makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ );+ const req = makeSubagentReq();+ req.config.endpoints.agents.capabilities.push('tools');+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ expect(+ jest.requireActual('@librechat/api').canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(true);+ expect(agentClientArgs.agent.lazySubagentConfigs[0].lazySubagentConfigs[0]).not.toHaveProperty(+ 'tool_options',+ );+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ });++ it('classifies unresolved lazy graph-member review modes before selecting the parent', async () => {+ const memberId = 'approval-lazy-graph-member';+ await createViewableAgent(SUBAGENT_ID, {+ enabled: true,+ allowSelf: false,+ graphs: [+ {+ type: 'review_team',+ name: 'Review team',+ agent_ids: [SUBAGENT_ID, memberId],+ edges: [{ from: SUBAGENT_ID, to: memberId, edgeType: 'direct' }],+ entry_agent_id: SUBAGENT_ID,+ result_agent_id: memberId,+ },+ ],+ });+ const member = await createAgent({+ id: memberId,+ name: 'Approval graph member',+ provider: 'openai',+ model: 'gpt-4',+ author: new mongoose.Types.ObjectId(),+ tools: [`${Constants.mcp_all}${Constants.mcp_delimiter}fixture`],+ tool_options: { query_mcp_fixture: { approval_mode: 'always' } },+ });+ await grantView(member);+ mockInitializeAgent.mockResolvedValue(+ makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ );+ const req = makeSubagentReq();+ req.config.endpoints.agents.capabilities.push('tools');+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ const metadata = agentClientArgs.agent.lazySubagentConfigs[0].subagentGraphMemberMetadata[0];+ expect(metadata.id).toBe(memberId);+ expect(metadata).not.toHaveProperty('tool_options');+ expect(+ jest.requireActual('@librechat/api').canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(true);+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['db_query_mcp_DB', 'query_mcp_DB', 'DB'],+ ['db_ops_query_mcp_db ops', 'query_mcp_db_ops', 'db ops'],+ ['db_ops_query_mcp_db_ops', 'query_mcp_db ops', 'db ops'],+ ])(+ 'classifies a real normalized lazy selection before resolution: %s',+ async (selected, current, raw) => {+ const child = await createAgent({+ id: SUBAGENT_ID,+ name: 'Normalized review selection',+ provider: 'openai',+ model: 'gpt-4',+ author: testUser._id,+ tools: [selected],+ tool_options: { [current]: { approval_mode: 'chat' } },+ });+ await grantView(child);+ mockGetAccessibleMcpServerNames.mockResolvedValue([raw]);+ mockInitializeAgent.mockResolvedValue(+ makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ );+ const req = makeSubagentReq();+ req.config.endpoints.agents.capabilities.push('tools');+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ expect(+ jest.requireActual('@librechat/api').canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(true);+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ expect(agentClientArgs.agent.lazySubagentConfigs[0]).not.toHaveProperty('mcpToolAliases');+ expect(agentClientArgs.agent.lazySubagentConfigs[0]).not.toHaveProperty('tool_options');+ },+ );++ it.each([+ 'active',+ 'disabled-skills',+ 'disabled-tools',+ 'agent-opt-out',+ 'inactive',+ 'out-of-scope',+ 'deselected',+ 'raw-key',+ ])('uses the real gated skill-only lazy surface for admission: %s', async (state) => {+ const current = 'query_mcp_db_ops';+ const { skill } = await createSkill({+ name: 'approval-skill',+ description: 'Adds a reviewed query.',+ body: '# Approval query\n',+ alwaysApply: true,+ frontmatter: { 'allowed-tools': [state === 'raw-key' ? 'db_ops_query_mcp_db ops' : current] },+ author: testUser._id,+ authorName: testUser.name,+ });+ await AclEntry.create({+ principalType: PrincipalType.USER,+ principalId: testUser._id,+ principalModel: PrincipalModel.USER,+ resourceType: ResourceType.SKILL,+ resourceId: skill._id,+ permBits: PermissionBits.VIEW,+ grantedBy: testUser._id,+ });+ const child = await createAgent({+ id: SUBAGENT_ID,+ name: 'Skill-only review selection',+ provider: 'openai',+ model: 'gpt-4',+ author: testUser._id,+ tools: [],+ skills_enabled: state !== 'agent-opt-out',+ skills: [+ state === 'out-of-scope' ? new mongoose.Types.ObjectId().toString() : skill._id.toString(),+ ],+ tool_options: {+ [state === 'deselected' ? 'other_mcp_db_ops' : current]: { approval_mode: 'ask' },+ },+ });+ await grantView(child);+ if (state === 'inactive')+ await User.updateOne(+ { _id: testUser._id },+ { $set: { skillStates: { [skill._id.toString()]: false } } },+ );+ mockGetAccessibleMcpServerNames.mockResolvedValue(['db ops']);+ mockInitializeAgent.mockResolvedValue(+ makePrimaryConfig({+ subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] },+ }),+ );+ const req = makeSubagentReq();+ if (state !== 'disabled-skills') req.config.endpoints.agents.capabilities.push('skills');+ if (state !== 'disabled-tools') req.config.endpoints.agents.capabilities.push('tools');+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ expect(+ jest.requireActual('@librechat/api').canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [agentClientArgs.agent],+ }),+ ).toBe(state === 'active' || state === 'raw-key');+ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ expect(agentClientArgs.agent.lazySubagentConfigs[0]).not.toHaveProperty('tools');+ expect(agentClientArgs.agent.lazySubagentConfigs[0]).not.toHaveProperty('tool_options');+ });+it('includes current always-apply Skill revisions in lazy descriptor metadata', async () => {const secondSubagentId = 'agent_subagent_skill_2';const { skill } = await createSkill({diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex 75b401a899..b2d0177074 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -3,6 +3,7 @@ const { logger, getTenantId } = require('@librechat/data-schemas');const { Providers, Constants: AgentConstants } = require('@librechat/agents');const {sendEvent,+ createMCPToolApprovalMetadata,PENDING_STALE_MS,MCPOAuthHandler,MCPTokenStorage,@@ -1238,6 +1239,7 @@ async function createMCPTool({currentToolName: matchedToolKey === strippedToolKey ? strippedToolName : undefined,serverName,serverConfig,+ customUserVars: userMCPAuthMap?.[`${Constants.mcp_prefix}${serverName}`],toolDefinition: toolEntry['function'],upstreamTokenProvider,upstreamTokenProviderResolver,@@ -1261,6 +1263,7 @@ function createToolInstance({currentToolName,serverName,serverConfig: capturedServerConfig,+ customUserVars: capturedCustomUserVars,toolDefinition,provider: capturedProvider,upstreamTokenProvider: capturedUpstreamTokenProvider = null,@@ -1483,6 +1486,17 @@ function createToolInstance({});toolInstance.mcp = true;toolInstance.mcpRawServerName = serverName;+ createMCPToolApprovalMetadata().bindInstance(toolInstance, {+ serverName,+ config: capturedServerConfig,+ user: capturedUser,+ body: capturedRequestBody,+ customUserVars: capturedCustomUserVars,+ currentToolName,+ upstreamName: serverToolName,+ parameters,+ description,+ });if (serverToolName !== toolName) {/** Upstream identity for stripped keys — lets the options aliasing in* `buildToolClassification` heal legacy `tool_options` spellings. */diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex 0900b35f5b..7320e0ec3d 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -2,6 +2,7 @@const mockGetTenantId = jest.fn();jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),logger: {debug: jest.fn(),error: jest.fn(),diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex bb7002a2c5..8b74236819 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -13,6 +13,7 @@ const {createAuthIdentityContext,selectMCPUpstreamTokenProvider,loadToolDefinitions,+ createMCPToolApprovalMetadata,GenerationJobManager,isActionDomainAllowed,buildWebSearchContext,@@ -1166,6 +1167,7 @@ async function loadToolDefinitionsWrapper({/** Name-preserving: the definitions loader resolves normalized-vs-raw* spellings itself (direct identity first, alias fallback), so this* closure must look up EXACTLY the name it is given. */+ const approvalMetadata = createMCPToolApprovalMetadata();const getOrFetchMCPServerTools = async (userId, serverName) => {const addPendingOAuthServer = async () => {const pendingOAuthStart = await getReplayablePendingMCPOAuthStart({@@ -1184,9 +1186,11 @@ async function loadToolDefinitionsWrapper({let serverConfig;try {- serverConfig =- configServers?.[serverName] ??- (await getMCPServersRegistry().getServerConfig(serverName, userId, configServers));+ serverConfig = await getMCPServersRegistry().getServerConfig(+ serverName,+ userId,+ configServers,+ );} catch {logger.warn('[Tool Definitions] MCP registry unavailable; skipping tool exposure for one server',@@ -1202,6 +1206,13 @@ async function loadToolDefinitionsWrapper({}const customUserVars = userMCPAuthMap?.[`${Constants.mcp_prefix}${serverName}`];+ approvalMetadata.capture({+ serverName,+ config: serverConfig,+ user: req.user,+ body: runtimeRequestBody,+ customUserVars,+ });const missingUserVars = getMissingCustomUserVars(serverConfig, customUserVars);if (missingUserVars.length > 0) {logger.warn('[Tool Definitions] Skipping one MCP server with missing user configuration', {@@ -1604,6 +1615,7 @@ async function loadToolDefinitionsWrapper({}}+ approvalMetadata.attach(toolDefinitions);return {toolRegistry,mcpAvailableTools,diff --git a/api/server/services/__tests__/MCP.spec.js b/api/server/services/__tests__/MCP.spec.jsindex 3cd0d8e3de..556cd3a5d2 100644--- a/api/server/services/__tests__/MCP.spec.js+++ b/api/server/services/__tests__/MCP.spec.js@@ -21,6 +21,7 @@ jest.mock('~/config', () => ({}));jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),getTenantId: jest.fn(() => 'tenant-1'),logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },}));diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.jsindex d851f4075a..52cf1798b7 100644--- a/api/server/services/__tests__/ToolService.spec.js+++ b/api/server/services/__tests__/ToolService.spec.js@@ -257,7 +257,7 @@ describe('ToolService - Action Capability Gating', () => {mockGetCachedTools.mockResolvedValue(null);mockGetUserMCPAuthMap.mockResolvedValue({});mockGetRoleByName.mockResolvedValue(buildRole());- mockGetServerConfig.mockResolvedValue(undefined);+ mockGetServerConfig.mockImplementation(async (name, _userId, candidates) => candidates?.[name]);mockFlowManager.getFlowState.mockResolvedValue(undefined);mockResolveConfigServers.mockResolvedValue({});mockResolveMcpServerNames.mockResolvedValue([]);@@ -2577,7 +2577,68 @@ describe('ToolService - Action Capability Gating', () => {expect(authDeltaEvent?.data.delta.expires_at).toBe(createdAt + PENDING_STALE_MS);});- it('should use request-scoped MCP config before falling back to the registry', async () => {+ it('approval binding follows the user-tier authority instead of a same-name config candidate', async () => {+ const { getToolApprovalBinding, buildMCPToolApprovalBinding, getToolApprovalAuthKind } =+ jest.requireActual('@librechat/api');+ const serverName = 'shared-server';+ const name = `query${Constants.mcp_delimiter}${serverName}`;+ const req = createMockReq([AgentCapabilities.tools]);+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig([AgentCapabilities.tools]));+ const candidate = {+ type: 'streamable-http',+ source: 'config',+ url: 'https://config.example.com/mcp',+ };+ const firstAuthority = {+ type: 'streamable-http',+ source: 'user',+ url: 'https://user.example.com/mcp',+ dbId: 'server-id',+ };+ mockResolveConfigServers.mockResolvedValue({ [serverName]: candidate });+ mockGetServerConfig.mockResolvedValue(firstAuthority);+ mockGetMCPServerTools.mockResolvedValue({+ [name]: { function: { name, parameters: { type: 'object' } } },+ });+ mockLoadToolDefinitions.mockImplementation(async (params, deps) => {+ await deps.getOrFetchMCPServerTools(params.userId, serverName);+ return {+ toolDefinitions: [{ name, serverName, parameters: { type: 'object' } }],+ toolRegistry: new Map(),+ hasDeferredTools: false,+ };+ });+ const first = await loadAgentTools({+ req,+ res: {},+ agent: { id: 'agent-a', tools: [name] },+ definitionsOnly: true,+ });+ expect(getToolApprovalAuthKind(first.toolDefinitions[0])).toBe('other');+ expect(getToolApprovalBinding(first.toolDefinitions[0])).toBe(+ buildMCPToolApprovalBinding(serverName, firstAuthority),+ );+ expect(getToolApprovalBinding(first.toolDefinitions[0])).not.toBe(+ buildMCPToolApprovalBinding(serverName, candidate),+ );+ mockGetServerConfig.mockResolvedValue({+ ...firstAuthority,+ url: 'https://new-user.example.com/mcp',+ requiresOAuth: true,+ });+ const second = await loadAgentTools({+ req,+ res: {},+ agent: { id: 'agent-a', tools: [name] },+ definitionsOnly: true,+ });+ expect(getToolApprovalAuthKind(second.toolDefinitions[0])).toBe('oauth');+ expect(getToolApprovalBinding(second.toolDefinitions[0])).not.toBe(+ getToolApprovalBinding(first.toolDefinitions[0]),+ );+ });++ it('resolves request-scoped MCP candidates through the effective registry', async () => {const serverName = 'config-server';const mcpTool = `search${Constants.mcp_delimiter}${serverName}`;const capabilities = [AgentCapabilities.tools];@@ -2592,6 +2653,9 @@ describe('ToolService - Action Capability Gating', () => {},},});+ mockGetServerConfig.mockImplementation(+ async (_name, _userId, candidates) => candidates[serverName],+ );mockGetUserMCPAuthMap.mockResolvedValue({[`${Constants.mcp_prefix}${serverName}`]: { TOKEN: 'secret' },});@@ -2621,7 +2685,11 @@ describe('ToolService - Action Capability Gating', () => {});expect(result.toolDefinitions).toEqual([mcpTool]);- expect(mockGetServerConfig).not.toHaveBeenCalled();+ expect(mockGetServerConfig).toHaveBeenCalledWith(+ serverName,+ req.user.id,+ expect.objectContaining({ [serverName]: expect.any(Object) }),+ );expect(mockGetMCPServerTools).toHaveBeenCalledWith(req.user.id,serverName,diff --git a/client/src/components/Agents/AgentDetailContent.tsx b/client/src/components/Agents/AgentDetailContent.tsxindex 001f7ab4bc..a09d177afa 100644--- a/client/src/components/Agents/AgentDetailContent.tsx+++ b/client/src/components/Agents/AgentDetailContent.tsx@@ -29,6 +29,7 @@ import { useMarketplaceHost } from './MarketplaceContext';import { useFavorites, useLocalize } from '~/hooks';import DescriptionWords from './DescriptionWords';import { cn, renderAgentAvatar } from '~/utils';+import ResetApprovals from './ResetApprovals';import AgentCategoryBadge from './Category';import CopyLink from './CopyLink';@@ -399,7 +400,7 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({onFocusCapture={handleActionFocusCapture}onBlurCapture={handleActionBlurCapture}>- <div className="grid grid-cols-2 gap-2 sm:flex sm:gap-2">+ <div className="flex items-center gap-2"><Buttonvariant="outline"aria-label={favoriteLabel}@@ -421,6 +422,7 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({<span className="truncate">{favoriteLabel}</span></Button><CopyLink url={shareUrl} disabled={actionsDisabled} />+ <ResetApprovals agentId={agent.id} disabled={actionsDisabled} /></div><ButtonclassName="w-full sm:w-auto"diff --git a/client/src/components/Agents/ResetApprovals.tsx b/client/src/components/Agents/ResetApprovals.tsxnew file mode 100644index 0000000000..1b3f366f25--- /dev/null+++ b/client/src/components/Agents/ResetApprovals.tsx@@ -0,0 +1,80 @@+import { useId, useState, useEffect } from 'react';+import { ShieldOff } from 'lucide-react';+import * as Ariakit from '@ariakit/react';+import { useMutation } from '@tanstack/react-query';+import { dataService, MutationKeys } from 'librechat-data-provider';+import { Button, DropdownPopup, TooltipAnchor, useToastContext } from '@librechat/client';+import { useGetAgentsConfig, useLocalize } from '~/hooks';++/** Personal consent is independent of permission to edit the shared agent. */+export default function ResetApprovals({+ agentId,+ disabled = false,+}: {+ agentId: string;+ disabled?: boolean;+}) {+ const localize = useLocalize();+ const { agentsConfig } = useGetAgentsConfig();+ const { showToast } = useToastContext();+ const menuId = useId();+ const [open, setOpen] = useState(false);+ const reset = useMutation(dataService.resetToolApprovalGrants, {+ mutationKey: [MutationKeys.resetToolApprovalGrants],+ onSuccess: () => {+ setOpen(false);+ showToast({ message: localize('com_ui_tool_approval_reset_success'), status: 'success' });+ },+ });+ useEffect(() => {+ if (!open) return;+ const dismiss = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ setOpen(false);+ }+ };+ document.addEventListener('keydown', dismiss);+ return () => document.removeEventListener('keydown', dismiss);+ }, [open]);+ if (agentsConfig?.toolApproval?.agentModes !== true) return null;+ const label = localize('com_ui_tool_approval_reset');+ return (+ <DropdownPopup+ menuId={menuId}+ isOpen={open}+ setIsOpen={setOpen}+ portal+ focusLoop+ unmountOnHide+ items={[+ {+ id: `${menuId}-reset`,+ label: localize(+ reset.isError ? 'com_ui_tool_approval_reset_error' : 'com_ui_tool_approval_reset',+ ),+ disabled: disabled || reset.isLoading,+ hideOnClick: false,+ onClick: () => {+ if (!disabled) reset.mutate({ agentId });+ },+ },+ ]}+ trigger={+ <TooltipAnchor+ description={label}+ render={+ <Ariakit.MenuButton+ aria-label={label}+ aria-expanded={open}+ disabled={disabled || reset.isLoading}+ render={<Button type="button" variant="outline" size="icon-sm" />}+ >+ <ShieldOff className="size-4" aria-hidden="true" />+ </Ariakit.MenuButton>+ }+ />+ }+ />+ );+}diff --git a/client/src/components/Agents/tests/Accessibility.spec.tsx b/client/src/components/Agents/tests/Accessibility.spec.tsxindex 904aa3156a..2e605bd9c9 100644--- a/client/src/components/Agents/tests/Accessibility.spec.tsx+++ b/client/src/components/Agents/tests/Accessibility.spec.tsx@@ -1,3 +1,4 @@+jest.mock('../ResetApprovals', () => () => null);import React from 'react';import * as t from 'librechat-data-provider';import { render, screen, fireEvent } from '@testing-library/react';diff --git a/client/src/components/Agents/tests/AgentDetailContent.spec.tsx b/client/src/components/Agents/tests/AgentDetailContent.spec.tsxindex c735ec5922..42d886fabb 100644--- a/client/src/components/Agents/tests/AgentDetailContent.spec.tsx+++ b/client/src/components/Agents/tests/AgentDetailContent.spec.tsx@@ -1,3 +1,4 @@+jest.mock('../ResetApprovals', () => () => null);import React from 'react';import { RecoilRoot } from 'recoil';import userEvent from '@testing-library/user-event';diff --git a/client/src/components/Agents/tests/AgentGrid.integration.spec.tsx b/client/src/components/Agents/tests/AgentGrid.integration.spec.tsxindex fac4309509..956e134462 100644--- a/client/src/components/Agents/tests/AgentGrid.integration.spec.tsx+++ b/client/src/components/Agents/tests/AgentGrid.integration.spec.tsx@@ -1,3 +1,4 @@+jest.mock('../ResetApprovals', () => () => null);import React, { useRef } from 'react';import userEvent from '@testing-library/user-event';import { dataService, QueryKeys } from 'librechat-data-provider';diff --git a/client/src/components/Agents/tests/ResetApprovals.spec.tsx b/client/src/components/Agents/tests/ResetApprovals.spec.tsxnew file mode 100644index 0000000000..28a8f0c1f3--- /dev/null+++ b/client/src/components/Agents/tests/ResetApprovals.spec.tsx@@ -0,0 +1,90 @@+import React from 'react';+import userEvent from '@testing-library/user-event';+import { render, screen, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import '@testing-library/jest-dom';+import ResetApprovals from '../ResetApprovals';++const mockReset = jest.fn();+const mockToast = jest.fn();+let mockEnabled = true;+jest.mock('librechat-data-provider', () => ({+ ...jest.requireActual('librechat-data-provider'),+ dataService: {+ ...jest.requireActual('librechat-data-provider').dataService,+ resetToolApprovalGrants: (params: { agentId: string; toolName?: string }) => mockReset(params),+ },+}));+jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useGetAgentsConfig: () => ({ agentsConfig: { toolApproval: { agentModes: mockEnabled } } }),+}));+jest.mock('@librechat/client', () => ({+ ...jest.requireActual('@librechat/client'),+ useToastContext: () => ({ showToast: mockToast }),+}));+const renderReset = (disabled = false) =>+ render(+ <QueryClientProvider+ client={+ new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ logger: { log: () => {}, warn: () => {}, error: () => {} },+ })+ }+ >+ <ResetApprovals agentId="shared-agent" disabled={disabled} />+ </QueryClientProvider>,+ );++beforeEach(() => {+ mockReset.mockReset().mockResolvedValue({ reset: true });+ mockToast.mockReset();+ mockEnabled = true;+});++test('a viewer needs only the shared agent ID to reset personal consent', async () => {+ renderReset();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'com_ui_tool_approval_reset' }));+ await user.click(screen.getByRole('menuitem', { name: 'com_ui_tool_approval_reset' }));+ await waitFor(() => expect(mockReset).toHaveBeenCalledWith({ agentId: 'shared-agent' }));+ await waitFor(() =>+ expect(mockToast).toHaveBeenCalledWith({+ message: 'com_ui_tool_approval_reset_success',+ status: 'success',+ }),+ );+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());+});++test('personal reset remains actionable after failure and supports retry', async () => {+ mockReset.mockRejectedValueOnce(new Error('temporary failure'));+ renderReset();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'com_ui_tool_approval_reset' }));+ await user.click(screen.getByRole('menuitem', { name: 'com_ui_tool_approval_reset' }));+ await user.click(+ await screen.findByRole('menuitem', { name: 'com_ui_tool_approval_reset_error' }),+ );+ await waitFor(() => expect(mockReset).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());+});++test('disabled access cannot mutate consent and Escape dismisses the menu', async () => {+ const view = renderReset(true);+ expect(screen.getByRole('button', { name: 'com_ui_tool_approval_reset' })).toBeDisabled();+ view.unmount();+ renderReset();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'com_ui_tool_approval_reset' }));+ await user.keyboard('{Escape}');+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());+ expect(mockReset).not.toHaveBeenCalled();+});++test('the existing opt-in flag hides the personal action when modes are unavailable', () => {+ mockEnabled = false;+ renderReset();+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+});diff --git a/client/src/components/Chat/Messages/Content/ToolApproval.tsx b/client/src/components/Chat/Messages/Content/ToolApproval.tsxindex 30e4aef15f..37cc67fe69 100644--- a/client/src/components/Chat/Messages/Content/ToolApproval.tsx+++ b/client/src/components/Chat/Messages/Content/ToolApproval.tsx@@ -100,6 +100,14 @@ export default function ToolApproval({const invalidJsonId = useId();const allowAlwaysHintId = useId();const { actionId, allowed_decisions: allowedDecisions, description } = approval;+ const rememberScope = approval.remember_scope;+ const rememberUnavailable = approval.remember_unavailable;+ const unavailableLabels: Record<NonNullable<typeof rememberUnavailable>, TranslationKeys> = {+ connection: 'com_ui_tool_approval_connection_unavailable',+ disabled: 'com_ui_tool_approval_remember_disabled',+ storage: 'com_ui_tool_approval_storage_unavailable',+ background: 'com_ui_tool_approval_background_unavailable',+ };const conversationId = useContext(ChatContext)?.conversation?.conversationId;const composerPresents = useComposerPresentsApproval(conversationId, actionId);const deferToComposer = surface === 'thread' && composerPresents;@@ -271,6 +279,20 @@ export default function ToolApproval({data-tool-call-id={toolCallId}>{descriptionNode}+ {rememberUnavailable && (+ <p className="text-text-warning text-xs" role="status">+ {localize(unavailableLabels[rememberUnavailable])}+ </p>+ )}+ {rememberScope && (+ <p className="text-text-secondary text-xs">+ {localize(+ rememberScope === 'chat'+ ? 'com_ui_tool_approval_remember_chat'+ : 'com_ui_tool_approval_remember_always',+ )}+ </p>+ )}<div className="flex flex-wrap gap-2">{allowedDecisions.map((decision) => {const Icon = DECISION_ICON[decision];diff --git a/client/src/components/Chat/approval/Review.tsx b/client/src/components/Chat/approval/Review.tsxindex 812aa2f0d4..71f9675721 100644--- a/client/src/components/Chat/approval/Review.tsx+++ b/client/src/components/Chat/approval/Review.tsx@@ -157,6 +157,8 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({approval={{actionId: pendingAction.actionId,allowed_decisions: config.allowed_decisions,+ remember_scope: config.remember_scope,+ remember_unavailable: config.remember_unavailable,description: preview.description,allow_always: config.allow_always === true,}}diff --git a/client/src/components/SidePanel/Agents/AgentPanel.tsx b/client/src/components/SidePanel/Agents/AgentPanel.tsxindex 78d064eb36..95223c5332 100644--- a/client/src/components/SidePanel/Agents/AgentPanel.tsx+++ b/client/src/components/SidePanel/Agents/AgentPanel.tsx@@ -38,6 +38,7 @@ import { useResourcePermissions } from '~/hooks/useResourcePermissions';import { useSelectAgent, useLocalize, useAuthContext } from '~/hooks';import { useAgentPanelContext } from '~/Providers/AgentPanelContext';import { resolveCapabilityTools } from './Tools/items/capabilities';+import ResetApprovals from '~/components/Agents/ResetApprovals';import AgentPanelSkeleton from './AgentPanelSkeleton';import AdvancedPanel from './Advanced/AdvancedPanel';import { Panel, isEphemeralAgent } from '~/common';@@ -851,6 +852,7 @@ export default function AgentPanel() {{localize('com_agents_not_available')}</h2><p className="text-text-secondary">{localize('com_agents_no_access')}</p>+ {agentQuery.data?.id && <ResetApprovals agentId={agentQuery.data.id} />}</div></div>)}diff --git a/client/src/components/SidePanel/Agents/ApprovalOption.tsx b/client/src/components/SidePanel/Agents/ApprovalOption.tsxnew file mode 100644index 0000000000..b9d05a5abc--- /dev/null+++ b/client/src/components/SidePanel/Agents/ApprovalOption.tsx@@ -0,0 +1,139 @@+import { useId, useState, useEffect } from 'react';+import * as Ariakit from '@ariakit/react';+import { useMutation } from '@tanstack/react-query';+import { dataService, MutationKeys } from 'librechat-data-provider';+import { Button, DropdownPopup, TooltipAnchor } from '@librechat/client';+import { Check, Shield, ShieldCheck, ShieldQuestion, MessageCircle, Minus } from 'lucide-react';+import type { AgentToolApprovalMode } from 'librechat-data-provider';+import type { TranslationKeys } from '~/hooks';+import { useLocalize } from '~/hooks';++const LABELS: Record<AgentToolApprovalMode | 'inherit' | 'mixed', TranslationKeys> = {+ inherit: 'com_ui_tool_approval_inherit',+ ask: 'com_ui_tool_approval_ask',+ allow: 'com_ui_tool_approval_allow',+ chat: 'com_ui_tool_approval_chat',+ always: 'com_ui_tool_approval_always',+ mixed: 'com_ui_tool_approval_mixed',+};++const MODES: Array<AgentToolApprovalMode | 'inherit'> = [+ 'inherit',+ 'ask',+ 'allow',+ 'chat',+ 'always',+];++export default function ApprovalOption({+ mode,+ onChange,+ bulk = false,+ disabled = false,+ constraint,+ agentId,+ toolName,+}: {+ mode?: AgentToolApprovalMode | 'mixed';+ onChange: (mode?: AgentToolApprovalMode) => void;+ bulk?: boolean;+ disabled?: boolean;+ constraint?: 'ask' | 'deny';+ agentId?: string;+ toolName?: string;+}) {+ const localize = useLocalize();+ const menuId = useId();+ const [open, setOpen] = useState(false);+ const reset = useMutation(dataService.resetToolApprovalGrants, {+ mutationKey: [MutationKeys.resetToolApprovalGrants],+ });+ useEffect(() => {+ if (!open) return;+ const dismiss = (event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ // OGDialog prevents the native Escape before Ariakit can dismiss its popup.+ event.preventDefault();+ setOpen(false);+ };+ document.addEventListener('keydown', dismiss);+ return () => document.removeEventListener('keydown', dismiss);+ }, [open]);+ const selected = mode ?? 'inherit';+ const items = MODES.map((value) => ({+ id: `${menuId}-${value}`,+ label: localize(LABELS[value]),+ ariaChecked: selected === value,+ disabled: constraint != null && value !== 'inherit' && value !== 'ask',+ icon: selected === value ? <Check className="size-4" aria-hidden="true" /> : undefined,+ onClick: () => onChange(value === 'inherit' ? undefined : value),+ }));+ const label = localize(bulk ? 'com_ui_tool_approval_bulk' : 'com_ui_tool_approval_mode');+ let tooltip = `${label}: ${localize(LABELS[selected])}`;+ if (constraint) {+ tooltip = localize(+ constraint === 'ask' ? 'com_ui_tool_approval_admin_ask' : 'com_ui_tool_approval_admin_deny',+ );+ }+ if (disabled) tooltip = localize('com_ui_tool_approval_disabled');+ const icons = {+ inherit: Shield,+ ask: ShieldQuestion,+ allow: ShieldCheck,+ chat: MessageCircle,+ always: ShieldCheck,+ mixed: Minus,+ };+ const Icon = constraint === 'ask' ? ShieldQuestion : icons[selected];++ return (+ <DropdownPopup+ menuId={menuId}+ isOpen={open}+ setIsOpen={setOpen}+ portal={true}+ focusLoop={true}+ unmountOnHide={true}+ items={[+ ...items,+ ...(agentId && toolName && (mode === 'chat' || mode === 'always')+ ? [+ {+ id: `${menuId}-reset`,+ label: localize(+ reset.isError ? 'com_ui_tool_approval_reset_error' : 'com_ui_tool_approval_reset',+ ),+ disabled: reset.isLoading,+ hideOnClick: false,+ onClick: () =>+ reset.mutate({ agentId, toolName }, { onSuccess: () => setOpen(false) }),+ },+ ]+ : []),+ ]}+ trigger={+ <TooltipAnchor+ description={tooltip}+ side="top"+ render={+ <Ariakit.MenuButton+ aria-label={tooltip}+ aria-expanded={open}+ disabled={disabled}+ accessibleWhenDisabled={true}+ render={+ <Button+ type="button"+ variant={mode != null || constraint != null ? 'outline' : 'section-action'}+ size={bulk ? 'icon-sm' : 'icon-xs'}+ />+ }+ >+ <Icon className="size-4" aria-hidden="true" />+ </Ariakit.MenuButton>+ }+ />+ }+ />+ );+}diff --git a/client/src/components/SidePanel/Agents/MCPToolItem.tsx b/client/src/components/SidePanel/Agents/MCPToolItem.tsxindex a496e9cfc5..ee9623af8a 100644--- a/client/src/components/SidePanel/Agents/MCPToolItem.tsx+++ b/client/src/components/SidePanel/Agents/MCPToolItem.tsx@@ -1,7 +1,8 @@import { useState } from 'react';import { Button } from '@librechat/client';import { Check, Clock, Code2, Captions, Info, Zap } from 'lucide-react';-import type { AgentToolType } from 'librechat-data-provider';+import type { AgentToolType, AgentToolApprovalMode } from 'librechat-data-provider';+import ApprovalOption from './ApprovalOption';import OptionToggle from './OptionToggle';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -26,6 +27,11 @@ interface MCPToolItemProps {onToggleProgrammatic: () => void;onToggleBackground: () => void;onToggleIntent: () => void;+ approvalConstraint?: 'ask' | 'deny';+ approvalAgentId?: string;+ approvalMode?: AgentToolApprovalMode;+ approvalsEnabled?: boolean;+ onApprovalModeChange?: (mode?: AgentToolApprovalMode) => void;}const iconButton = 'size-6 rounded-md';@@ -48,6 +54,11 @@ export default function MCPToolItem({programmaticToolsAvailable,backgroundToolsEnabled,toolIntentsEnabled,+ approvalMode,+ approvalConstraint,+ approvalAgentId,+ approvalsEnabled,+ onApprovalModeChange,}: MCPToolItemProps) {const localize = useLocalize();const [expanded, setExpanded] = useState(false);@@ -130,6 +141,16 @@ export default function MCPToolItem({onToggle={onToggleIntent}/>)}+ {onApprovalModeChange && (+ <ApprovalOption+ constraint={approvalConstraint}+ agentId={approvalAgentId}+ toolName={tool.tool_id}+ mode={approvalMode}+ onChange={onApprovalModeChange}+ disabled={!approvalsEnabled}+ />+ )}<Buttonvariant="ghost"size="icon"diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsxindex 1ee42046fa..2b8657f8e5 100644--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx@@ -97,6 +97,11 @@ jest.mock('~/hooks', () => ({}),}));+jest.mock('../../../ApprovalOption', () => ({+ __esModule: true,+ default: () => null,+}));+jest.mock('../../../MCPToolItem', () => ({__esModule: true,default: ({diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsxindex 31006dd325..6cf8115045 100644--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx@@ -4,6 +4,7 @@ import { useFormContext, useWatch } from 'react-hook-form';import { Button, Spinner, Checkbox, Skeleton } from '@librechat/client';import {AgentCapabilities,+ getToolApprovalConstraint,Constants,splitMCPToolKey,normalizeServerName,@@ -26,6 +27,7 @@ import { getStatusColor, getStatusTextKey } from '~/components/MCP/mcpServerUtilimport MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';import McpOAuthDialog from '~/components/MCP/McpOAuthDialog';+import ApprovalOption from '../../../ApprovalOption';import { useAgentPanelContext } from '~/Providers';import { getIconForItem } from '../../items/icons';import OptionToggle from '../../../OptionToggle';@@ -108,6 +110,7 @@ export default function McpSection({ item }: Props) {toggleProgrammaticAll,toggleBackgroundAll,toggleIntentAll,+ setToolApprovalMode,} = useMCPToolOptions();const serverName = item.server.serverName;@@ -228,6 +231,11 @@ export default function McpSection({ item }: Props) {* edit persists it.*/const formToolOptions = useWatch({ control, name: 'tool_options' });+ const approvalsEnabled = agentsConfig?.toolApproval?.agentModes === true;+ const approvalModes = new Set(+ tools.map((tool) => formToolOptions?.[tool.tool_id]?.approval_mode),+ );+ const bulkApprovalMode = approvalModes.size > 1 ? 'mixed' : approvalModes.values().next().value;useEffect(() => {if (!formToolOptions) {return;@@ -488,7 +496,7 @@ export default function McpSection({ item }: Props) {</div><div className="flex flex-col gap-2">- <div className="flex min-h-7 items-center justify-between">+ <div className="flex min-h-7 flex-wrap items-center justify-between gap-x-2 gap-y-1"><span className="text-text-secondary text-[11px] font-medium tracking-wide uppercase">{localize('com_ui_tools_mcp_tools_section')}</span>@@ -539,6 +547,19 @@ export default function McpSection({ item }: Props) {onToggle={() => toggleIntentAll(intentEligibleTools)}/>)}+ {hasTools && (+ <ApprovalOption+ bulk={true}+ mode={bulkApprovalMode}+ disabled={!approvalsEnabled}+ onChange={(mode) =>+ setToolApprovalMode(+ tools.map((tool) => tool.tool_id),+ mode,+ )+ }+ />+ )}{hasTools &&(deferredToolsEnabled ||programmaticToolsEnabled ||@@ -578,6 +599,14 @@ export default function McpSection({ item }: Props) {<MCPToolItemkey={tool.tool_id}tool={tool}+ approvalAgentId={getValues('id')}+ approvalConstraint={getToolApprovalConstraint(+ agentsConfig?.toolApproval,+ tool.tool_id,+ )}+ approvalMode={formToolOptions?.[tool.tool_id]?.approval_mode}+ approvalsEnabled={approvalsEnabled}+ onApprovalModeChange={(mode) => setToolApprovalMode([tool.tool_id], mode)}isSelected={selectedTools.includes(tool.tool_id)}isDeferred={deferredToolsEnabled && isToolDeferred(tool.tool_id)}isProgrammatic={programmaticToolsEnabled && isToolProgrammatic(tool.tool_id)}diff --git a/client/src/components/SidePanel/Agents/__tests__/ApprovalOption.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/ApprovalOption.spec.tsxnew file mode 100644index 0000000000..e21a6ebd36--- /dev/null+++ b/client/src/components/SidePanel/Agents/__tests__/ApprovalOption.spec.tsx@@ -0,0 +1,64 @@+import { fireEvent, screen, waitFor } from '@testing-library/react';+import { render } from 'test/layout-test-utils';+import ApprovalOption from '../ApprovalOption';++const mockReset = jest.fn(async (_params: { agentId: string; toolName: string }) => ({+ reset: true as const,+}));++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ resetToolApprovalGrants: (params: { agentId: string; toolName: string }) => mockReset(params),+ },+ };+});++jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));++test('opens the four modes and inheritance without changing tool selection', async () => {+ const onChange = jest.fn();+ render(<ApprovalOption mode="chat" onChange={onChange} />);+ fireEvent.click(screen.getByRole('button'));+ const item = await screen.findByRole('menuitemcheckbox', { name: 'com_ui_tool_approval_always' });+ fireEvent.click(item);+ expect(onChange).toHaveBeenCalledWith('always');+});++test('bulk menu reports mixed state and clears to inheritance', async () => {+ const onChange = jest.fn();+ render(<ApprovalOption bulk={true} mode="mixed" onChange={onChange} />);+ fireEvent.click(screen.getByRole('button'));+ fireEvent.click(+ await screen.findByRole('menuitemcheckbox', { name: 'com_ui_tool_approval_inherit' }),+ );+ await waitFor(() => expect(onChange).toHaveBeenCalledWith(undefined));+});++test('administrator-required approval disables automatic modes', async () => {+ render(<ApprovalOption constraint="ask" onChange={jest.fn()} />);+ fireEvent.click(screen.getByRole('button'));+ const allow = await screen.findByRole('menuitemcheckbox', { name: 'com_ui_tool_approval_allow' });+ expect(allow).toHaveAttribute('aria-disabled', 'true');+});++test('reset failures stay actionable and retry only the current user’s tool', async () => {+ mockReset.mockRejectedValueOnce(new Error('unavailable')).mockResolvedValueOnce({ reset: true });+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});+ render(+ <ApprovalOption mode="chat" agentId="agent-a" toolName="query_mcp_db" onChange={jest.fn()} />,+ );+ fireEvent.click(screen.getByRole('button'));+ fireEvent.click(await screen.findByRole('menuitem', { name: 'com_ui_tool_approval_reset' }));+ fireEvent.click(+ await screen.findByRole('menuitem', { name: 'com_ui_tool_approval_reset_error' }),+ );+ await waitFor(() => expect(mockReset).toHaveBeenCalledTimes(2));+ expect(mockReset).toHaveBeenLastCalledWith({ agentId: 'agent-a', toolName: 'query_mcp_db' });+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());+ mockReset.mockClear();+ consoleError.mockRestore();+});diff --git a/client/src/hooks/Agents/__tests__/approvalModes.spec.ts b/client/src/hooks/Agents/__tests__/approvalModes.spec.tsnew file mode 100644index 0000000000..2791e0b6e4--- /dev/null+++ b/client/src/hooks/Agents/__tests__/approvalModes.spec.ts@@ -0,0 +1,68 @@+import { validate as validateUUID } from 'uuid';+import type { AgentToolOptions } from 'librechat-data-provider';+import { withApprovalModes } from '../useMCPToolOptions';++test('bulk changes preserve other tool options and do not mutate the form snapshot', () => {+ const original: AgentToolOptions = { a: { defer_loading: true }, b: { run_in_background: true } };+ const updated = withApprovalModes(original, ['a', 'b'], 'chat');+ expect(original).toEqual({ a: { defer_loading: true }, b: { run_in_background: true } });+ expect(updated.a).toMatchObject({+ defer_loading: true,+ approval_mode: 'chat',+ approval_revision: expect.any(String),+ });+ expect(updated.b).toMatchObject({ run_in_background: true, approval_mode: 'chat' });+ expect(updated.a.approval_revision).not.toEqual(updated.b.approval_revision);+});++test('selecting the existing mode preserves its approval revision and form identity', () => {+ const original = withApprovalModes({}, ['a'], 'always');+ expect(withApprovalModes(original, ['a'], 'always')).toBe(original);+});++test('inheritance clears only the approval settings and drops empty entries', () => {+ const original: AgentToolOptions = withApprovalModes(+ { a: { defer_loading: true } },+ ['a', 'b'],+ 'ask',+ );+ expect(withApprovalModes(original, ['a', 'b'])).toEqual({ a: { defer_loading: true } });+});++for (const mode of ['chat', 'always'] as const) {+ test.each([undefined, '', 'invalid-revision'])(+ `${mode} repairs a missing or invalid revision when reselected (%s)`,+ (approval_revision) => {+ const options: AgentToolOptions = {+ a: { approval_mode: mode, approval_revision, defer_loading: true },+ };+ const repaired = withApprovalModes(options, ['a'], mode);+ expect(repaired).not.toBe(options);+ expect(repaired.a.approval_mode).toBe(mode);+ expect(repaired.a.defer_loading).toBe(true);+ expect(validateUUID(repaired.a.approval_revision!)).toBe(true);+ expect(options.a.approval_revision).toBe(approval_revision);+ expect(withApprovalModes(repaired, ['a'], mode)).toBe(repaired);+ },+ );++ test(`${mode} bulk selection repairs only missing revisions and preserves valid consent`, () => {+ const valid = withApprovalModes({}, ['a'], mode);+ const original: AgentToolOptions = {+ ...valid,+ b: { approval_mode: mode, describe_intent: true },+ };+ const repaired = withApprovalModes(original, ['a', 'b'], mode);+ expect(repaired.a).toBe(original.a);+ expect(repaired.b).toMatchObject({ approval_mode: mode, describe_intent: true });+ expect(validateUUID(repaired.b.approval_revision!)).toBe(true);+ expect(original.b.approval_revision).toBeUndefined();+ });+}++test('unchanged ask, allow and inherited modes do not generate unnecessary revisions', () => {+ for (const mode of ['ask', 'allow', undefined] as const) {+ const original: AgentToolOptions = { a: { approval_mode: mode, defer_loading: true } };+ expect(withApprovalModes(original, ['a'], mode)).toBe(original);+ }+});diff --git a/client/src/hooks/Agents/useMCPToolOptions.ts b/client/src/hooks/Agents/useMCPToolOptions.tsindex ee6a496f23..5d3bedc4a0 100644--- a/client/src/hooks/Agents/useMCPToolOptions.ts+++ b/client/src/hooks/Agents/useMCPToolOptions.ts@@ -1,6 +1,12 @@import { useCallback } from 'react';import { useFormContext, useWatch } from 'react-hook-form';-import type { AgentToolOptions, AllowedCaller, AgentToolType } from 'librechat-data-provider';+import { v4 as uuidv4, validate as validateUUID } from 'uuid';+import type {+ AgentToolOptions,+ AllowedCaller,+ AgentToolType,+ AgentToolApprovalMode,+} from 'librechat-data-provider';import type { UseFormGetValues, UseFormSetValue } from 'react-hook-form';import type { AgentForm } from '~/common';@@ -21,6 +27,7 @@ interface ToolOptionsFormContext {interface UseMCPToolOptionsReturn {formToolOptions: AgentToolOptions | undefined;+ setToolApprovalMode: (toolIds: readonly string[], mode?: AgentToolApprovalMode) => void;isToolDeferred: (toolId: string) => boolean;isToolProgrammatic: (toolId: string) => boolean;isToolBackground: (toolId: string) => boolean;@@ -144,6 +151,33 @@ function useBooleanToolOption(return { isSet, toggle, areAllSet, toggleAll };}+export function withApprovalModes(+ options: AgentToolOptions,+ toolIds: readonly string[],+ mode?: AgentToolApprovalMode,+): AgentToolOptions {+ let updated = options;+ for (const toolId of toolIds) {+ const current = options[toolId];+ const remembered = mode === 'chat' || mode === 'always';+ if (+ current?.approval_mode === mode &&+ (!remembered || validateUUID(current.approval_revision ?? ''))+ )+ continue;+ if (updated === options) updated = { ...options };+ const { approval_mode: _mode, approval_revision: _revision, ...rest } = options[toolId] ?? {};+ if (mode != null) {+ updated[toolId] = { ...rest, approval_mode: mode, approval_revision: uuidv4() };+ } else if (Object.keys(rest).length > 0) {+ updated[toolId] = rest;+ } else {+ delete updated[toolId];+ }+ }+ return updated;+}+export default function useMCPToolOptions(): UseMCPToolOptionsReturn {const { getValues, setValue, control } = useFormContext<AgentForm>();const formToolOptions = useWatch({ control, name: 'tool_options' });@@ -255,8 +289,18 @@ export default function useMCPToolOptions(): UseMCPToolOptionsReturn {[getValues, setValue, areAllToolsProgrammatic],);+ const setToolApprovalMode = useCallback(+ (toolIds: readonly string[], mode?: AgentToolApprovalMode) => {+ const options = getValues('tool_options') ?? {};+ const updated = withApprovalModes(options, toolIds, mode);+ if (updated !== options) setValue('tool_options', updated, { shouldDirty: true });+ },+ [getValues, setValue],+ );+return {formToolOptions,+ setToolApprovalMode,isToolDeferred: defer.isSet,isToolProgrammatic,isToolBackground: background.isSet,diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 63c48ddc59..ec9ffafbef 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -3339,5 +3339,25 @@"com_ui_code_checkout_isolated": "Isolated worktree","com_ui_code_checkout_isolated_info": "Created on the first workspace operation from the worker's Git snapshot. Uncommitted changes are not copied.","com_ui_code_checkout_source": "Registered checkout",- "com_ui_code_checkout_source_info": "Use the machine's registered checkout directly. Other chats may share these files."+ "com_ui_code_checkout_source_info": "Use the machine's registered checkout directly. Other chats may share these files.",+ "com_ui_tool_approval_mode": "Tool approval mode",+ "com_ui_tool_approval_bulk": "Approval mode for all listed tools",+ "com_ui_tool_approval_inherit": "Use inherited policy",+ "com_ui_tool_approval_ask": "Always ask",+ "com_ui_tool_approval_allow": "Always approve",+ "com_ui_tool_approval_chat": "Ask once per chat",+ "com_ui_tool_approval_always": "Ask once, then always approve",+ "com_ui_tool_approval_mixed": "Mixed approval modes",+ "com_ui_tool_approval_disabled": "An administrator must enable agent tool approval modes.",+ "com_ui_tool_approval_remember_chat": "Approving remembers this tool for this agent in this chat, including calls with different arguments. Administrator rules still apply.",+ "com_ui_tool_approval_remember_always": "Approving remembers this tool for you and this agent across chats, including calls with different arguments. Administrator rules still apply.",+ "com_ui_tool_approval_reset": "Reset my remembered approvals",+ "com_ui_tool_approval_reset_success": "Your remembered approvals were reset.",+ "com_ui_tool_approval_reset_error": "Could not reset remembered approvals. Please retry.",+ "com_ui_tool_approval_admin_ask": "Administrator policy requires approval.",+ "com_ui_tool_approval_admin_deny": "Administrator policy blocks this tool.",+ "com_ui_tool_approval_connection_unavailable": "Approval cannot be remembered for this connection. Each call requires review.",+ "com_ui_tool_approval_remember_disabled": "Remembered approvals are disabled. Each call requires review.",+ "com_ui_tool_approval_storage_unavailable": "Remembered approval is unavailable. This approval will apply only to this call.",+ "com_ui_tool_approval_background_unavailable": "Background launches cannot teach approval. Approve a successful foreground call to remember this tool."}diff --git a/client/src/utils/approval.ts b/client/src/utils/approval.tsindex ccd083257d..8bc73f50ee 100644--- a/client/src/utils/approval.ts+++ b/client/src/utils/approval.ts@@ -110,6 +110,8 @@ function tagApprovalOnPart(approval: {actionId,allowed_decisions: reviewConfig?.allowed_decisions ?? [],+ remember_scope: reviewConfig?.remember_scope,+ remember_unavailable: reviewConfig?.remember_unavailable,description: request.description,...(reviewConfig?.allow_always === true && { allow_always: true }),},diff --git a/docs/tool-approval-modes.md b/docs/tool-approval-modes.mdnew file mode 100644index 0000000000..d5ba80b7bb--- /dev/null+++ b/docs/tool-approval-modes.md@@ -0,0 +1,59 @@+# Agent tool approval modes++MCP tool rows expose a shield menu beside defer, programmatic, background and intent options.+The header menu changes all currently listed tools. Newly discovered tools inherit policy.+Selections belong to the agent, not the shared MCP server.++| Mode | Behavior |+| ----------------------------- | ---------------------------------------------------------------------------- |+| Inherited | No agent-specific rule. |+| Always ask | Review each call. |+| Always approve | No agent-specific prompt. Administrator requirements still win. |+| Ask once per chat | Remember a successful, manually approved call for this user, agent and chat. |+| Ask once, then always approve | Remember it for this user and agent across chats. |++Remembered approval covers different arguments. The approval view discloses that scope.+A grant-store outage at pause, resume, invocation or transport keeps a reviewed non-OAuth foreground call one-time, even after storage recovers. OAuth and unknown-auth calls still require verified account generations.+Reject, edit, respond, failed execution, detached launches and expired approvals do not create grants. Success can teach approval only after the execution target has been verified. A launch handle never teaches approval; pending-call ownership is retired at settlement.+A changed connection, active MCP OAuth credential generation, raw upstream tool, schema or mode revision requires fresh approval. Retained OAuth records are ignored when the executing connection uses API-key, direct-bearer or OBO authentication; active MCP OAuth account-change fences remain enforced. Authentication that depends on a runtime-resolved URL remains conservative until detection: manual review pins the stored OAuth generation instead of assuming non-OAuth. OAuth generation changes, including conservative refresh fences, may require another review; token bytes themselves are never consent identity. Review-only authority pins resolved routing and principal identity even when consent cannot be remembered. A manually reviewed non-rememberable connection executes only in the foreground; approving a background request does not authorize detached execution. Execution rechecks the loaded target and current grant before invocation. The approved OAuth generation is pinned to every transport send and recovery retry. Request-scoped, templated or+unresolved connections cannot retain approval. Reset in the tool menu revokes your grants+across chats. In-flight approvals cannot restore a revoked grant. Refresh and reconnect do not reset a chat.++## Activation++Upgrade every serving replica before enabling authoring:++```yaml+endpoints:+ agents:+ toolApproval:+ enabled: true+ mode: bypass+ agentModes: true+ grantLookupTimeoutMs: 3000+```++Explicit administrator deny/ask rules and hooks remain authoritative. Approval grants do not+supply missing permissions or credentials. Hosts without a supported approval responder block+calls requiring review. An inner/programmatic path that cannot evaluate the agent policy refuses+execution rather than treating an automatic mode as a bypass. Input/output scripts are not part of this feature.++## Compatibility and rollback++Existing agents inherit policy. Disabling `agentModes` disables authoring and remembered grants;+stored manual-review requirements remain enforced while endpoint approvals are enabled.+Older clients can drop these fields when editing agents. Do not enable authoring during a rolling+upgrade. Before downgrading the server, enforce affected tools through administrator ask/deny+rules and stop active runs. Do not downgrade into a bypass baseline that ignores agent requirements.++## Personal reset++Shared-agent viewers can reset their consent from agent details or the read-only agent panel. Reset does not require EDIT permission or reveal tool configuration. It changes no agent options. Agent-wide reset fences all tools, including unseen in-flight approvals. Stale completions cannot overwrite consent renewed after reset; the per-tool shield menu still supports targeted reset.++Reset accepts the same tenant-scoped `manage:agents` capability or VIEW ACL as normal agent access. It always resets the authenticated user’s consent.++Renewable OpenID/Graph credential placeholders are excluded from review authority in env, arguments, URLs, OAuth fields and headers. Surrounding routing and principal values remain bound. Persistence rechecks OAuth generation and atomically compares the captured consent binding, so stale completions cannot replace consent for a new account, connection, schema or approval revision.++Approval ownership is invocation-specific. A delayed background completion cannot retire a newer call with the same provider ID. Registry timestamps and inspection summaries do not change authority. Renewable placeholders introduced by environment or custom-variable substitution are masked before credential resolution, without changing normal transport resolution.++Scheduled-run pause admission checks each agent’s reachable tools and verified aliases. Options retained for deselected tools do not make an initialized run pause-capable. Unresolved lazy tool surfaces remain fail-closed.diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yamlindex 470cb7aa91..be32ca709e 100644--- a/e2e/config/librechat.e2e.yaml+++ b/e2e/config/librechat.e2e.yaml@@ -148,6 +148,7 @@ endpoints:# existing file-authoring, steering, background-tool, or MCP specs.toolApproval:enabled: true+ agentModes: truemode: bypass# The probe below is an `ask` rule and a hook match, so it is never offered# "Always allow"; the remembered-approval scenarios assert exactly that.diff --git a/e2e/specs/mock/tool-approval-modes.spec.ts b/e2e/specs/mock/tool-approval-modes.spec.tsnew file mode 100644index 0000000000..22c4b215b2--- /dev/null+++ b/e2e/specs/mock/tool-approval-modes.spec.ts@@ -0,0 +1,273 @@+import { expect, test } from '@playwright/test';+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';+import {+ getAccessToken,+ requestJson,+ fetchJson,+ sendMessage,+ messagesView,+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+} from './helpers';++for (const [theme, width] of [+ ['light', 1280],+ ['dark', 1280],+ ['dark', 390],+] as const) {+ test(`approval mode controls persist in ${theme} mode at ${width}px`, async ({+ page,+ }, testInfo) => {+ await page.setViewportSize({ width, height: 900 });+ await page.addInitScript((value) => localStorage.setItem('color-theme', value), theme);+ await page.goto(NEW_CHAT_PATH);+ const token = await getAccessToken(page);+ const name = uniqueAgentName('Approval modes');+ const agent = await requestJson<{ id: string }>(page, {+ path: '/api/agents',+ method: 'POST',+ token,+ body: {+ name,+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ tools: [+ 'sys__server__sys_mcp_e2e-memory',+ 'remember_fact_mcp_e2e-memory',+ 'recall_fact_mcp_e2e-memory',+ ],+ },+ });+ try {+ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name }).click();+ await expect(form.getByLabel('Agent name')).toHaveValue(name);+ await form.getByRole('button', { name: 'Configure', exact: true }).last().click();+ const dialog = page.getByTestId('item-dialog');+ await expect(dialog.getByText('Tools in this server')).toBeVisible();+ const row = dialog.getByRole('button', { name: 'remember_fact', exact: true }).locator('..');+ await row.getByRole('button', { name: /^Tool approval mode:/ }).click();+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible();+ for (const label of [+ 'Use inherited policy',+ 'Always ask',+ 'Always approve',+ 'Ask once per chat',+ 'Ask once, then always approve',+ ]) {+ await expect(+ menu.getByRole('menuitemcheckbox', { name: label, exact: true }),+ ).toBeVisible();+ }+ await menu.getByRole('menuitemcheckbox', { name: 'Ask once per chat', exact: true }).click();+ await expect(menu).toHaveCount(0);+ await expect(+ row.getByRole('button', { name: 'Tool approval mode: Ask once per chat', exact: true }),+ ).toBeVisible();+ await dialog+ .getByRole('button', { name: /Approval mode for all listed tools: Mixed/ })+ .click();+ await menu.getByRole('menuitemcheckbox', { name: 'Always ask', exact: true }).click();+ await expect(menu).toHaveCount(0);+ await expect(+ row.getByRole('button', { name: 'Tool approval mode: Always ask', exact: true }),+ ).toBeVisible();+ await row.getByRole('button', { name: /^Tool approval mode:/ }).focus();+ await page.keyboard.press('Enter');+ await expect(menu).toBeVisible();+ await menu.getByRole('menuitemcheckbox', { name: 'Ask once per chat', exact: true }).click();+ await expect(menu).toHaveCount(0);+ await row.getByRole('button', { name: /^Tool approval mode:/ }).click();+ await testInfo.attach('Approval menu', {+ body: await menu.screenshot(),+ contentType: 'image/png',+ });+ await page.keyboard.press('Escape');+ await expect(menu).toHaveCount(0);+ await dialog.getByRole('button', { name: 'Close', exact: true }).click();+ await expect(dialog).not.toBeVisible();+ await openAgentBuilder(page, { navigate: false });+ const [saved] = await Promise.all([+ page.waitForResponse(+ (response) =>+ response.request().method() === 'PATCH' &&+ response.url().includes(`/api/agents/${agent.id}`),+ ),+ form.getByRole('button', { name: 'Save', exact: true }).click(),+ ]);+ expect(saved.ok()).toBe(true);+ const body = await saved.json();+ expect(body.tool_options['remember_fact_mcp_e2e-memory'].approval_mode).toBe('chat');+ await page.reload();+ const reopened = await openAgentBuilder(page, { navigate: false });+ await reopened.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name }).click();+ await reopened.getByRole('button', { name: 'Configure', exact: true }).last().click();+ await expect(+ dialog.getByRole('button', { name: 'Tool approval mode: Ask once per chat', exact: true }),+ ).toBeVisible();+ await testInfo.attach('MCP tool approval controls', {+ body: await dialog.screenshot(),+ contentType: 'image/png',+ });+ const overflow = await dialog.evaluate(+ (element) => element.scrollWidth > element.clientWidth,+ );+ expect(overflow).toBe(false);+ } finally {+ await page.keyboard.press('Escape');+ await cleanupAgent(page, agent.id);+ }+ });+}++test('a real MCP batch learns approval only after review, then reuses it in the chat', async ({+ page,+}) => {+ test.setTimeout(60000);+ await page.goto(NEW_CHAT_PATH);+ const token = await getAccessToken(page);+ const name = uniqueAgentName('Learned approval');+ const toolName = 'remember_fact_mcp_e2e-memory';+ const agent = await requestJson<{ id: string }>(page, {+ path: '/api/agents',+ method: 'POST',+ token,+ body: {+ name,+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ tools: ['sys__server__sys_mcp_e2e-memory', toolName],+ tool_options: {+ [toolName]: {+ approval_mode: 'chat',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ },+ });+ try {+ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name }).click();+ await form.getByRole('button', { name: 'Select Agent' }).click();+ const first = `first-${Date.now()}`;+ expect((await sendMessage(page, `E2E_ACTIVITY_REPLY:${first}`)).ok()).toBe(true);+ const panel = page.locator('#pending-tool-approval-panel');+ await expect(panel).toBeVisible();+ await expect(panel.getByText(/Approving remembers this tool/).first()).toBeVisible();+ for (const approve of await panel.getByRole('button', { name: 'Approve', exact: true }).all())+ await approve.click();+ await panel.getByRole('button', { name: 'Continue', exact: true }).click();+ const conversationId = new URL(page.url()).pathname.split('/').pop()!;+ await expect+ .poll(+ async () =>+ JSON.stringify(+ await fetchJson<Array<{ content?: object[] }>>(+ page,+ `/api/messages/${conversationId}`,+ token,+ ),+ ),+ { timeout: 20000 },+ )+ .toContain(`E2E MCP memory noted: activity alpha ${first}`);+ await expect(+ messagesView(page).getByText('E2E mock reply: pong', { exact: true }),+ ).toBeVisible();+ await expect(panel).toHaveCount(0);+ const second = `second-${Date.now()}`;+ expect((await sendMessage(page, `E2E_ACTIVITY_REPLY:${second}`)).ok()).toBe(true);+ await expect(+ messagesView(page).getByText(`E2E activity reply done ${second}`, { exact: true }),+ ).toBeVisible({ timeout: 20000 });+ await expect(panel).toHaveCount(0);+ const completed = await fetchJson<+ Array<{ content?: Array<{ tool_call?: { output?: string } }> }>+ >(page, `/api/messages/${conversationId}`, token);+ expect(JSON.stringify(completed)).toContain(`E2E MCP memory noted: activity alpha ${second}`);+ } finally {+ await cleanupAgent(page, agent.id);+ }+});++test('a basic agent viewer can reset personal consent without loading authoring options', async ({+ page,+}) => {+ test.setTimeout(60000);+ await page.goto(NEW_CHAT_PATH);+ const token = await getAccessToken(page);+ const name = uniqueAgentName('Viewer consent reset');+ const agent = await requestJson<{ id: string }>(page, {+ path: '/api/agents',+ method: 'POST',+ token,+ body: {+ name,+ description: 'Personal consent reset',+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ tools: ['remember_fact_mcp_e2e-memory'],+ tool_options: {+ 'remember_fact_mcp_e2e-memory': {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ },+ });+ let basicReads = 0;+ await page.route(`**/api/agents/${agent.id}*`, async (route) => {+ if (route.request().method() !== 'GET') return route.continue();+ const response = await route.fetch();+ const body = await response.json();+ basicReads++;+ await route.fulfill({+ response,+ json: {+ id: body.id,+ _id: body._id,+ name: body.name,+ description: body.description,+ avatar: body.avatar,+ created_at: body.created_at,+ },+ });+ });+ try {+ await page.goto(`/agents/all?q=${encodeURIComponent(name)}`);+ await page.getByRole('button', { name, exact: true }).click();+ const dialog = page.getByRole('dialog');+ const reset = dialog.getByRole('button', {+ name: 'Reset my remembered approvals',+ exact: true,+ });+ await expect(reset).toBeEnabled();+ expect(basicReads).toBeGreaterThan(0);+ await expect(dialog.getByRole('button', { name: 'Configure', exact: true })).toHaveCount(0);+ await reset.click();+ await page.keyboard.press('Escape');+ await expect(page.getByRole('menu')).toHaveCount(0);+ await expect(dialog).toBeVisible();+ await reset.click();+ const [response] = await Promise.all([+ page.waitForResponse(+ (response) =>+ response.url().endsWith('/api/agents/tools/approvals/reset') &&+ response.request().method() === 'POST',+ ),+ page.getByRole('menuitem', { name: 'Reset my remembered approvals', exact: true }).click(),+ ]);+ expect(response.ok()).toBe(true);+ expect(response.request().postDataJSON()).toEqual({ agentId: agent.id });+ await expect(+ page.getByText('Your remembered approvals were reset.', { exact: true }),+ ).toBeVisible();+ await expect(page.getByRole('menu')).toHaveCount(0);+ } finally {+ await cleanupAgent(page, agent.id);+ }+});diff --git a/librechat.example.yaml b/librechat.example.yamlindex edf598e760..e930f56b6f 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -906,6 +906,11 @@ endpoints:# # "tool_intents" enables live model-written labels for native tools and opted-in MCP tools.# # (optional) Require user approval before matching tool calls. Disabled by default.# toolApproval:+ # # Opt in after all replicas have been upgraded. Agent tool rows then expose+ # # Always ask, Always approve, Ask once per chat, and Ask once then always approve.+ # # Explicit administrator ask/deny rules and hooks remain authoritative.+ # agentModes: false+ # grantLookupTimeoutMs: 3000# enabled: true# mode: default # default, dontAsk, or bypass# allow: ["mcp:trusted-server:read_*"]diff --git a/packages/api/openapi/agents.openapi.json b/packages/api/openapi/agents.openapi.jsonindex 1511c1ddd3..fb2b0e08e5 100644--- a/packages/api/openapi/agents.openapi.json+++ b/packages/api/openapi/agents.openapi.json@@ -2271,6 +2271,19 @@},"describe_intent": {"type": "boolean"+ },+ "approval_mode": {+ "type": "string",+ "enum": [+ "ask",+ "allow",+ "chat",+ "always"+ ]+ },+ "approval_revision": {+ "type": "string",+ "format": "uuid"}}}@@ -2718,6 +2731,19 @@},"describe_intent": {"type": "boolean"+ },+ "approval_mode": {+ "type": "string",+ "enum": [+ "ask",+ "allow",+ "chat",+ "always"+ ]+ },+ "approval_revision": {+ "type": "string",+ "format": "uuid"}}}@@ -3189,6 +3215,19 @@},"describe_intent": {"type": "boolean"+ },+ "approval_mode": {+ "type": "string",+ "enum": [+ "ask",+ "allow",+ "chat",+ "always"+ ]+ },+ "approval_revision": {+ "type": "string",+ "format": "uuid"}}}diff --git a/packages/api/src/agents/__tests__/run-summarization.test.ts b/packages/api/src/agents/__tests__/run-summarization.test.tsindex 9c5da0ce4b..6cc6a8c7f0 100644--- a/packages/api/src/agents/__tests__/run-summarization.test.ts+++ b/packages/api/src/agents/__tests__/run-summarization.test.ts@@ -4815,12 +4815,13 @@ describe('HITL wiring is gated on hitlCapable', () => {matchQuery: alias.name,})).decision;- expect(hooks.getMatchers('PreToolUse')).toHaveLength(1);+ const initialMatcherCount = hooks.getMatchers('PreToolUse').length;+ expect(initialMatcherCount).toBeGreaterThan(0);expect(await decisionForAlias()).toBe('allow');await (lazyConfig?.resolveAgentInputs as (context: never) => Promise<unknown>)({signal: new AbortController().signal,} as never);- expect(hooks.getMatchers('PreToolUse')).toHaveLength(1);+ expect(hooks.getMatchers('PreToolUse')).toHaveLength(initialMatcherCount);expect(await decisionForAlias()).toBe('deny');},);diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex e64f4d2b14..acc99c7257 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -111,6 +111,12 @@ import {WORKSPACE_EDIT_MAX_COUNT,WORKSPACE_WRITE_MAX_BYTES,} from '~/code/workspace';+import {+ noteToolApprovalDispatch,+ bindToolApprovalInvocation,+ finishToolApprovalDispatch,+ getToolApprovalExecutionScope,+} from '~/tools/approval';import {BACKGROUND_TASK_ABORT_GRACE_MS,BACKGROUND_TASK_SHUTDOWN_MESSAGE,@@ -5618,6 +5624,23 @@ function createSkillFilesHandoff(};}+function getToolFailureFeedback(content: ToolExecuteResult['content']): string {+ if (typeof content === 'string') return content;+ const messages: string[] = [];+ for (const part of content) {+ if (+ part != null &&+ typeof part === 'object' &&+ 'type' in part &&+ part.type === 'text' &&+ 'text' in part &&+ typeof part.text === 'string'+ )+ messages.push(part.text);+ }+ return messages.join('\n') || 'Tool execution failed.';+}+export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandler {const {scheduledMCPExecution,@@ -6476,6 +6499,13 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand);}};+ const approvalDispatch = {+ agentId,+ toolCallId: tc.id,+ executionScope: getToolApprovalExecutionScope(executionContext),+ background: true,+ };+ noteToolApprovalDispatch(approvalDispatch);let invokePromise: Promise<{ content?: unknown; artifact?: unknown }>;try {invokePromise = Promise.resolve(@@ -6498,7 +6528,10 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand}: {}),},- metadata,+ metadata: bindToolApprovalInvocation(+ { ...metadata, executingAgentId: agentId },+ approvalDispatch,+ ),} as Record<string, unknown>),) as Promise<{ content?: unknown; artifact?: unknown }>;} catch (error) {@@ -6507,6 +6540,9 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand* through the same terminal-evidence path as an async one. */invokePromise = Promise.reject(error);}+ invokePromise = invokePromise.finally(() =>+ finishToolApprovalDispatch(approvalDispatch),+ );const persistDetachedTerminal = async (input:| { status: 'succeeded'; result: unknown }@@ -7579,7 +7615,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandconst result = await tool.invoke(normalizedArgs, {toolCall: toolCallConfig,configurable: mergedConfigurable,- metadata,+ metadata: { ...metadata, executingAgentId: agentId },/** The run's cancellation signal. Without it a foreground* tool call keeps running after Stop: an MCP call never* sends `notifications/cancelled`, and every other@@ -7674,7 +7710,10 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandtoolCallId: tc.id,content: cleanedContent,artifact: result.artifact,- status: 'success' as const,+ status: result.status === 'error' ? ('error' as const) : ('success' as const),+ ...(result.status === 'error' && {+ errorMessage: getToolFailureFeedback(cleanedContent),+ }),};} catch (toolError) {if (toolError instanceof ContentFilterError) {diff --git a/packages/api/src/agents/hitl/admission.spec.ts b/packages/api/src/agents/hitl/admission.spec.tsindex 170654e25a..c7fa3b54f1 100644--- a/packages/api/src/agents/hitl/admission.spec.ts+++ b/packages/api/src/agents/hitl/admission.spec.ts@@ -1,7 +1,17 @@+import { Constants } from 'librechat-data-provider';+import { createToolPolicyHook } from '@librechat/agents';+import type { AgentToolOptions } from 'librechat-data-provider';import type { PluginHookSource } from '~/agents/hooks/source';import type { ToolApprovalAdmissionAgent } from './admission';import type { ToolApprovalHook } from './hooks';-import { agentRunUsesCheckpointer, canAgentGraphPause } from './admission';+import {+ agentRunUsesCheckpointer,+ canAgentGraphPause,+ copyToolApprovalAdmissionMetadata,+} from './admission';+import { loadToolDefinitions } from '~/tools/definitions';+import { formatMCPServerTools } from '~/mcp/tools';+import { mapToolApprovalPolicy } from './policy';const askHook: ToolApprovalHook = async () => ({ decision: 'ask' });@@ -161,3 +171,1206 @@ describe('agentRunUsesCheckpointer', () => {).toBe(false);});});++for (const mode of ['ask', 'chat', 'always'] as const) {+ test.each([+ { tools: ['selected_mcp_db'] },+ { tools: [{ name: 'selected_mcp_db' }] },+ { toolDefinitions: [{ name: 'selected_mcp_db' }] },+ { toolRegistry: new Map([['selected_mcp_db', {}]]) },+ ])(`${mode} options only affect reachable initialized tools (%#)`, (surface) => {+ const policy = { enabled: true, mode: 'bypass' as const };+ const options = {+ selected_mcp_db: { approval_mode: 'allow' as const },+ deselected_mcp_db: { approval_mode: mode },+ };+ expect(canAgentGraphPause({ policy, agents: [{ ...surface, tool_options: options }] })).toBe(+ false,+ );+ expect(+ canAgentGraphPause({+ policy,+ agents: [+ {+ ...surface,+ tool_options: {+ ...options,+ selected_mcp_db: { approval_mode: mode },+ },+ },+ ],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['selected_mcp_db'] },+ agents: [{ ...surface, tool_options: { selected_mcp_db: { approval_mode: mode } } }],+ }),+ ).toBe(false);+ });++ test(`${mode} inactive modes cannot borrow another agent's reachable tool`, () => {+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [+ {+ id: 'a',+ tools: ['other_mcp_db'],+ tool_options: { selected_mcp_db: { approval_mode: mode } },+ },+ {+ id: 'b',+ tools: ['selected_mcp_db'],+ tool_options: { selected_mcp_db: { approval_mode: 'allow' } },+ },+ ],+ }),+ ).toBe(false);+ });++ test(`${mode} follows verified aliases without changing saved options or overriding current entries`, () => {+ const policy = { enabled: true, mode: 'bypass' as const };+ const options = { db_query_mcp_db: { approval_mode: mode } };+ const agent = {+ tools: ['query_mcp_db'],+ tool_options: options,+ mcpToolAliases: [{ name: 'query_mcp_db', aliasName: 'db_query_mcp_db' }],+ };+ expect(canAgentGraphPause({ policy, agents: [agent] })).toBe(true);+ expect(Object.keys(options)).toEqual(['db_query_mcp_db']);+ expect(canAgentGraphPause({ policy, agents: [{ ...agent, mcpToolAliases: [] }] })).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents: [+ {+ ...agent,+ tool_options: {+ ...options,+ query_mcp_db: { approval_mode: 'allow' },+ },+ },+ ],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({ policy: { ...policy, deny: ['db_query_mcp_db'] }, agents: [agent] }),+ ).toBe(false);+ });++ test(`${mode} remains conservative for unresolved lazy tools but ignores known deselection`, () => {+ const policy = { enabled: true, mode: 'bypass' as const };+ const option = { query_mcp_db: { approval_mode: mode } };+ expect(+ canAgentGraphPause({+ policy,+ agents: [{ lazySubagentConfigs: [{ id: 'lazy', tool_options: option }] }],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy,+ agents: [+ {+ lazySubagentConfigs: [+ {+ id: 'lazy',+ tools: [`${Constants.mcp_all}${Constants.mcp_delimiter}db`],+ tool_options: option,+ },+ ],+ },+ ],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy,+ agents: [{ lazySubagentConfigs: [{ id: 'lazy', tools: [], tool_options: option }] }],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents: [+ { lazySubagentConfigs: [{ id: 'lazy', tools: ['other_mcp_db'], tool_options: option }] },+ ],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents: [+ { lazySubagentConfigs: [{ id: 'lazy', toolDefinitions: [], tool_options: option }] },+ ],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['query_mcp_db'] },+ agents: [{ lazySubagentConfigs: [{ tool_options: option }] }],+ }),+ ).toBe(false);+ });+}++test('disabled modes, inherited options, cycles and duplicate agent IDs preserve admission defaults', () => {+ const child: ToolApprovalAdmissionAgent = {+ id: 'same',+ tools: ['selected_mcp_db'],+ tool_options: { selected_mcp_db: { approval_mode: 'ask' } },+ };+ const parent: ToolApprovalAdmissionAgent = {+ id: 'same',+ tools: ['read_file'],+ subagentAgentConfigs: [child],+ };+ Object.assign(child, { subagentAgentConfigs: [parent] });+ expect(canAgentGraphPause({ policy: { enabled: true, mode: 'bypass' }, agents: [parent] })).toBe(+ true,+ );+ expect(canAgentGraphPause({ policy: { enabled: false, mode: 'bypass' }, agents: [parent] })).toBe(+ false,+ );+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [{ tools: ['read_file'], tool_options: { read_file: { defer_loading: true } } }],+ }),+ ).toBe(false);+});++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test(`${placement} preserves private approval metadata across multiple projections`, () => {+ const source: ToolApprovalAdmissionAgent = {+ id: 'child',+ tools: ['query_mcp_db'],+ tool_options: {+ query_mcp_db: { approval_mode: 'chat' as const, approval_revision: 'revision' },+ },+ };+ const metadata = copyToolApprovalAdmissionMetadata({ id: source.id, name: 'Child' }, source);+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: source.id, configId: 'private-config' },+ metadata,+ );+ source.tool_options!.query_mcp_db.approval_mode = 'allow';+ const agents = [{ [placement]: [descriptor] }];+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents })).toBe(true);+ expect(canAgentGraphPause({ policy: { ...policy, deny: ['query_mcp_db'] }, agents })).toBe(+ false,+ );+ expect(canAgentGraphPause({ policy: { ...policy, enabled: false }, agents })).toBe(false);+ expect(descriptor).not.toHaveProperty('tool_options');+ expect(descriptor).not.toHaveProperty('tools');+ expect(JSON.stringify(descriptor)).not.toContain('approval_');+ expect(Object.getOwnPropertySymbols(descriptor)).toEqual([]);+ });+}++test('private projections retain verified aliases and current-option precedence', () => {+ const source = {+ tools: ['query_mcp_db'],+ mcpToolAliases: [{ name: 'query_mcp_db', aliasName: 'db_query_mcp_db' }],+ tool_options: { db_query_mcp_db: { approval_mode: 'ask' as const } },+ };+ const descriptor = copyToolApprovalAdmissionMetadata({ id: 'child' }, source);+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ true,+ );+ const allow = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ {+ ...source,+ tool_options: {+ query_mcp_db: { approval_mode: 'allow' as const },+ db_query_mcp_db: { approval_mode: 'ask' as const },+ },+ },+ );+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [allow] }] })).toBe(false);+});++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each(['db', 'finance_mcp_eu'])(+ `${placement} cannot treat unresolved legacy selection as a closed catalog (%s)`,+ (server) => {+ const canonical = `query${Constants.mcp_delimiter}${server}`;+ const selected = `${server}_query${Constants.mcp_delimiter}${server}`;+ const source = {+ id: 'child',+ tools: [selected],+ tool_options: { [canonical]: { approval_mode: 'chat' as const } },+ };+ const descriptor = copyToolApprovalAdmissionMetadata({ id: 'child' }, source);+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [descriptor] }] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: [canonical] },+ agents: [{ [placement]: [descriptor] }],+ }),+ ).toBe(false);+ const collision = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { ...source, toolDefinitions: [{ name: selected }] },+ );+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [collision] }] })).toBe(false);+ const explicit = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ {+ ...source,+ tool_options: { ...source.tool_options, [selected]: { approval_mode: 'allow' as const } },+ },+ );+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [explicit] }] })).toBe(false);+ },+ );+}++const normalizedLazySelections = [+ { selected: 'db_query_mcp_DB', current: 'query_mcp_DB', raw: 'DB' },+ { selected: 'db_ops_query_mcp_db ops', current: 'query_mcp_db_ops', raw: 'db ops' },+ { selected: 'db_ops_query_mcp_db_ops', current: 'query_mcp_db ops', raw: 'db ops' },+ { selected: 'db_ops_query_mcp_db ops', current: 'query_mcp_db ops', raw: 'db ops' },+ {+ selected: 'finance_mcp_eu_get_mcp_version_mcp_Finance_mcp_EU',+ current: 'get_mcp_version_mcp_Finance_mcp_EU',+ raw: 'Finance_mcp_EU',+ },+];+for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each(normalizedLazySelections)(+ `${placement} predicts runtime normalization without proving an alias ($selected)`,+ ({ selected, current, raw }) => {+ const source = {+ tools: [selected],+ tool_options: { [current]: { approval_mode: 'chat' as const } },+ };+ const metadata = copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {+ rawMcpServerNames: [raw],+ });+ const descriptor = copyToolApprovalAdmissionMetadata({ id: 'child' }, metadata);+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [descriptor] }] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, enabled: false },+ agents: [{ [placement]: [descriptor] }],+ }),+ ).toBe(false);+ expect(descriptor).not.toHaveProperty('mcpToolAliases');+ expect(descriptor).not.toHaveProperty('tools');+ expect(source).toEqual({+ tools: [selected],+ tool_options: { [current]: { approval_mode: 'chat' } },+ });+ const closed = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { ...source, toolDefinitions: [{ name: selected }] },+ { rawMcpServerNames: [raw] },+ );+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [closed] }] })).toBe(false);+ },+ );+}++test('catalog-free stripping follows runtime reserved-name and classification protections', () => {+ for (const current of ['oauth', 'mcp_all', 'mcp_server', 'mcp_db', 'lc_transfer_to_child']) {+ const selected = `db_${current}_mcp_db`;+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: [selected], tool_options: { [`${current}_mcp_db`]: { approval_mode: 'ask' } } },+ );+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [{ lazySubagentConfigs: [descriptor] }],+ }),+ ).toBe(false);+ }+});++test('normalized current options win while explicit selected options and server deny remain authoritative', () => {+ const policy = { enabled: true, mode: 'bypass' as const };+ const contexts = { rawMcpServerNames: ['db ops'] };+ const scenarios: AgentToolOptions[] = [+ {+ query_mcp_db_ops: { approval_mode: 'allow' as const },+ 'query_mcp_db ops': { approval_mode: 'ask' as const },+ },+ {+ 'query_mcp_db ops': { approval_mode: 'ask' as const },+ query_mcp_db_ops: { approval_mode: 'allow' as const },+ },+ {+ query_mcp_db_ops: { approval_mode: 'ask' as const },+ db_ops_query_mcp_db_ops: { approval_mode: 'allow' as const },+ },+ ];+ for (const tool_options of scenarios) {+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: ['db_ops_query_mcp_db ops'], tool_options },+ contexts,+ );+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ false,+ );+ }+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: ['db_query_mcp_DB'], tool_options: { query_mcp_DB: { approval_mode: 'ask' } } },+ );+ for (const name of ['db_query_mcp_DB', 'query_mcp_DB']) {+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: [name] },+ agents: [{ lazySubagentConfigs: [descriptor] }],+ }),+ ).toBe(false);+ }+});++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each(['query_mcp_db_ops', 'db_ops_query_mcp_db ops'])(+ `${placement} includes resolved skill-only tools with empty saved selection (%s)`,+ (contributed) => {+ const skillPrimes = [{ name: 'analysis', allowedTools: [contributed, contributed] }];+ const source = {+ tools: [],+ tool_options: { query_mcp_db_ops: { approval_mode: 'ask' as const } },+ };+ const metadata = copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {+ skillPrimes,+ rawMcpServerNames: ['db ops'],+ toolsAvailable: true,+ });+ const descriptor = copyToolApprovalAdmissionMetadata({ id: 'child' }, metadata);+ skillPrimes[0].allowedTools.length = 0;+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [descriptor] }] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['query_mcp_db_ops'] },+ agents: [{ [placement]: [descriptor] }],+ }),+ ).toBe(false);+ expect(JSON.stringify(descriptor)).not.toContain('query');+ expect(Object.keys(source.tool_options)).toEqual(['query_mcp_db_ops']);+ },+ );+}++test('skill projection preserves absent surfaces, inactive/default modes, MCP capability gates and unrelated selections', () => {+ const policy = { enabled: true, mode: 'bypass' as const };+ for (const mode of ['ask', 'chat', 'always', 'allow', undefined] as const) {+ const source = { tools: [], tool_options: { query_mcp_db: { approval_mode: mode } } };+ const project = (allowedTools: string[], toolsAvailable = true) =>+ copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {+ skillPrimes: [{ name: 'analysis', allowedTools }],+ toolsAvailable,+ });+ for (const descriptor of [+ project([]),+ project(['other_mcp_db']),+ project(['query_mcp_db'], false),+ ]) {+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ false,+ );+ }+ expect(+ canAgentGraphPause({+ policy,+ agents: [{ lazySubagentConfigs: [project(['query_mcp_db'])] }],+ }),+ ).toBe(mode != null && mode !== 'allow');+ }+ const unresolved = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tool_options: { query_mcp_db: { approval_mode: 'ask' } } },+ );+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [unresolved] }] })).toBe(+ true,+ );+});++const inverseSelections = [+ { selected: 'query_mcp_db', option: 'db_query_mcp_db', server: 'db' },+ { selected: 'query_mcp_DB', option: 'db_query_mcp_DB', server: 'DB' },+ { selected: 'query_mcp_DB', option: 'DB_query_mcp_DB', server: 'DB' },+ { selected: 'query_mcp_db ops', option: 'db_ops_query_mcp_db_ops', server: 'db ops' },+ { selected: 'query_mcp_db_ops', option: 'DB_OPS_query_mcp_db ops', server: 'db ops' },+ {+ selected: 'get_mcp_version_mcp_Finance_mcp_EU',+ option: 'finance_mcp_eu_get_mcp_version_mcp_Finance_mcp_EU',+ server: 'Finance_mcp_EU',+ },+];+for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each(inverseSelections)(+ `${placement} considers inverse option spellings without assigning identity ($option)`,+ ({ selected, option, server }) => {+ const source = {+ tools: [selected],+ tool_options: { [option]: { approval_mode: 'chat' as const } },+ };+ const metadata = copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {+ rawMcpServerNames: [server],+ });+ const descriptor = copyToolApprovalAdmissionMetadata({ id: 'child' }, metadata);+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [descriptor] }] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, enabled: false },+ agents: [{ [placement]: [descriptor] }],+ }),+ ).toBe(false);+ expect(canAgentGraphPause({ policy, agents: [descriptor] })).toBe(false);+ expect(descriptor).not.toHaveProperty('mcpToolAliases');+ expect(JSON.stringify(descriptor)).not.toContain(option);+ expect(source.tool_options[option].approval_mode).toBe('chat');+ },+ );+}++test('selected keys, closed catalogs and administrator deny win over an inverse option hint', () => {+ const policy = { enabled: true, mode: 'bypass' as const };+ for (const entry of [{ approval_mode: 'allow' as const }, { defer_loading: true }]) {+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ {+ tools: ['query_mcp_db'],+ tool_options: { db_query_mcp_db: { approval_mode: 'ask' }, query_mcp_db: entry },+ },+ );+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ false,+ );+ }+ for (const name of ['query_mcp_db', 'db_query_mcp_db']) {+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: ['query_mcp_db'], tool_options: { db_query_mcp_db: { approval_mode: 'ask' } } },+ );+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: [name] },+ agents: [{ lazySubagentConfigs: [descriptor] }],+ }),+ ).toBe(false);+ }+ const closed = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ {+ tools: ['query_mcp_db'],+ toolDefinitions: [{ name: 'query_mcp_db' }],+ tool_options: { db_query_mcp_db: { approval_mode: 'ask' } },+ },+ );+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [closed] }] })).toBe(false);+});++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each(['db', 'db ops', 'Finance_mcp_EU'])(+ `${placement} wildcard modes are scoped to the exact selected server (%s)`,+ (server) => {+ const normalized = server.replace(/ /g, '_');+ const marker = `${Constants.mcp_all}${Constants.mcp_delimiter}${server}`;+ const project = (tool_options: AgentToolOptions) =>+ copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: [marker], tool_options },+ { rawMcpServerNames: [server, 'other', `other_mcp_${normalized}`] },+ );+ const policy = { enabled: true, mode: 'bypass' as const };+ for (const other of [+ 'read_mcp_other',+ `read_mcp_other_mcp_${normalized}`,+ `read_mcp_not${normalized}`,+ ]) {+ const descriptor = project({ [other]: { approval_mode: 'ask' } });+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [descriptor] }] })).toBe(false);+ }+ for (const suffix of [server, normalized]) {+ const name = `get_mcp_version_mcp_${suffix}`;+ const descriptor = project({ [name]: { approval_mode: 'always' } });+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [descriptor] }] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['get_mcp_version_mcp_*'] },+ agents: [{ [placement]: [descriptor] }],+ }),+ ).toBe(false);+ expect(descriptor).not.toHaveProperty('rawMcpServerNames');+ }+ },+ );+}++test('wildcards preserve raw direct-first collisions, distinct casing and genuinely unknown surfaces', () => {+ const marker = `${Constants.mcp_all}${Constants.mcp_delimiter}`;+ const policy = { enabled: true, mode: 'bypass' as const };+ const project = (+ tools: string[] | undefined,+ tool_options: AgentToolOptions,+ rawMcpServerNames: string[] = [],+ ) =>+ copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools, tool_options },+ { rawMcpServerNames },+ );+ for (const descriptor of [+ project([marker + 'db'], { read_mcp_DB: { approval_mode: 'ask' } }, ['db', 'DB']),+ project([marker + 'db_ops'], { 'read_mcp_db ops': { approval_mode: 'ask' } }, [+ 'db ops',+ 'db_ops',+ ]),+ project([marker + 'db'], { read_mcp_other: { approval_mode: 'allow' } }),+ project([], { read_mcp_other: { approval_mode: 'ask' } }),+ ])+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ false,+ );+ const unknown = project(undefined, { read_mcp_other: { approval_mode: 'ask' } });+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [unknown] }] })).toBe(true);+ const selected = project(+ [marker + 'db', marker + 'other'],+ { read_mcp_other: { approval_mode: 'ask' } },+ ['db', 'other'],+ );+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [selected] }] })).toBe(true);+});++test('a skill-contributed current selection retains inverse review options privately', () => {+ const source = {+ tools: [],+ tool_options: { db_query_mcp_db: { approval_mode: 'ask' as const } },+ };+ const descriptor = copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {+ skillPrimes: [{ name: 'analysis', allowedTools: ['query_mcp_db'] }],+ toolsAvailable: true,+ rawMcpServerNames: ['db'],+ });+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass' },+ agents: [{ lazySubagentConfigs: [descriptor] }],+ }),+ ).toBe(true);+ expect(source.tools).toEqual([]);+});++for (const tools of [['query_mcp_db'], [`${Constants.mcp_all}${Constants.mcp_delimiter}db`]]) {+ test.each(['ask', 'chat', 'always', 'allow', undefined] as const)(+ `unresolved admission matches actual stripped catalog loading for ${tools[0]} mode=%s`,+ async (mode) => {+ const option = 'db_query_mcp_db';+ const options: AgentToolOptions = { [option]: { approval_mode: mode } };+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools, tool_options: options },+ { rawMcpServerNames: ['db', 'other'] },+ );+ const catalog = formatMCPServerTools('db', [+ { name: 'db_query', inputSchema: { type: 'object', properties: {} } },+ ]);+ const result = await loadToolDefinitions(+ {+ userId: 'user',+ agentId: 'child',+ tools,+ toolOptions: { ...options },+ mcpServerNames: ['db', 'other'],+ rawServerNames: ['db', 'other'],+ },+ { getOrFetchMCPServerTools: async () => catalog, isBuiltInTool: () => false },+ );+ expect(result.mcpToolAliases).toContainEqual({ name: 'query_mcp_db', aliasName: option });+ const policy = { enabled: true, mode: 'bypass' as const };+ const actual = canAgentGraphPause({+ policy,+ agents: [+ {+ id: 'child',+ tool_options: options,+ toolDefinitions: result.toolDefinitions,+ mcpToolAliases: result.mcpToolAliases,+ },+ ],+ });+ expect(actual).toBe(mode != null && mode !== 'allow');+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ actual,+ );+ },+ );+}++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ for (const mode of ['ask', 'chat', 'always'] as const) {+ test.each([+ { tools: undefined, options: 'query_mcp_db' },+ { tools: ['query_mcp_db'], options: 'query_mcp_db' },+ { tools: ['query_mcp_db'], options: 'db_query_mcp_db' },+ { tools: ['db_query_mcp_db'], options: 'query_mcp_db' },+ { tools: [`${Constants.mcp_all}${Constants.mcp_delimiter}db`], options: 'query_mcp_db' },+ { tools: ['db_ops_query_mcp_db ops'], options: 'query_mcp_db_ops' },+ ])(+ `${placement} omits disabled saved MCP selections in ${mode}: $options / $tools`,+ ({ tools, options }) => {+ const source = { tools, tool_options: { [options]: { approval_mode: mode } } };+ const project = (toolsAvailable: boolean) => {+ const metadata = copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {+ toolsAvailable,+ rawMcpServerNames: ['db', 'db ops'],+ skillPrimes: [{ name: 'analysis', allowedTools: ['query_mcp_db'] }],+ });+ return copyToolApprovalAdmissionMetadata({ id: 'child' }, metadata);+ };+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [project(false)] }] })).toBe(+ false,+ );+ expect(canAgentGraphPause({ policy, agents: [{ [placement]: [project(true)] }] })).toBe(+ true,+ );+ expect(source.tool_options[options].approval_mode).toBe(mode);+ expect(project(false)).not.toHaveProperty('tool_options');+ },+ );+ }+}++test('disabled MCP capability preserves independently enabled non-MCP review and unknown surfaces', () => {+ const policy = { enabled: true, mode: 'bypass' as const };+ for (const tools of [undefined, ['query_mcp_db', 'read_file']]) {+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ {+ tools,+ tool_options: {+ query_mcp_db: { approval_mode: 'ask' },+ read_file: { approval_mode: 'chat' },+ },+ },+ {+ toolsAvailable: false,+ skillPrimes: [{ name: 'analysis', allowedTools: ['query_mcp_db', 'read_file'] }],+ },+ );+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ true,+ );+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['read_file'] },+ agents: [{ lazySubagentConfigs: [descriptor] }],+ }),+ ).toBe(false);+ }+});++test('MCP capability filtering keeps action-classified keys with MCP text under their independent gate', () => {+ const action = 'query_mcp_docs_action_service';+ const mcp = 'query_action_method_mcp_service';+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ {+ tools: [action, mcp],+ tool_options: { [action]: { approval_mode: 'ask' }, [mcp]: { approval_mode: 'chat' } },+ },+ { toolsAvailable: false },+ );+ const policy = { enabled: true, mode: 'bypass' as const };+ expect(canAgentGraphPause({ policy, agents: [{ lazySubagentConfigs: [descriptor] }] })).toBe(+ true,+ );+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: [action] },+ agents: [{ lazySubagentConfigs: [descriptor] }],+ }),+ ).toBe(false);+});++for (const mode of ['ask', 'chat', 'always'] as const) {+ test.each(['selected', 'inverse', 'legacy', 'wildcard', 'unknown'] as const)(+ `${mode} agent modes cannot override dontAsk fallback in %s admission`,+ async (surface) => {+ let tools: string[] | undefined = ['query_mcp_db'];+ let option = 'query_mcp_db';+ if (surface === 'inverse') option = 'db_query_mcp_db';+ if (surface === 'legacy') tools = ['db_query_mcp_db'];+ if (surface === 'wildcard') tools = [`${Constants.mcp_all}${Constants.mcp_delimiter}db`];+ if (surface === 'unknown') tools = undefined;+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools, tool_options: { [option]: { approval_mode: mode } } },+ { rawMcpServerNames: ['db'] },+ );+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: ['safe_mcp_other'] };+ const agents = [{ tools: ['safe_mcp_other'], lazySubagentConfigs: [descriptor] }];+ expect(canAgentGraphPause({ policy, agents })).toBe(false);+ const baseline = await createToolPolicyHook(mapToolApprovalPolicy(policy)!)(+ {+ hook_event_name: 'PreToolUse',+ runId: 'test',+ toolName: 'query_mcp_db',+ toolUseId: 'call',+ toolInput: {},+ },+ new AbortController().signal,+ );+ expect(baseline.decision).toBe('deny');+ for (const exception of ['allow', 'ask'] as const) {+ const allowed = { ...policy, [exception]: ['query*_mcp_db', 'db_query_mcp_db'] };+ expect(canAgentGraphPause({ policy: allowed, agents })).toBe(true);+ expect(canAgentGraphPause({ policy: { ...allowed, deny: ['*'] }, agents })).toBe(false);+ }+ },+ );+}++test('verified alias and conversation allows are evaluated before fallback-denied review modes', () => {+ const policy = {+ enabled: true,+ mode: 'dontAsk' as const,+ allowAlways: true,+ allow: ['safe_mcp_db'],+ };+ const agent = {+ tools: ['query_mcp_db', 'safe_mcp_db'],+ tool_options: { query_mcp_db: { approval_mode: 'chat' as const } },+ mcpToolAliases: [{ name: 'query_mcp_db', aliasName: 'db_query_mcp_db' }],+ };+ expect(canAgentGraphPause({ policy, agents: [agent] })).toBe(false);+ expect(+ canAgentGraphPause({ policy: { ...policy, allow: ['db_query_mcp_db'] }, agents: [agent] }),+ ).toBe(true);+ expect(+ canAgentGraphPause({ policy, agents: [agent], toolApprovalAllows: ['query_mcp_db'] }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['db_query_mcp_db'] },+ agents: [agent],+ toolApprovalAllows: ['query_mcp_db'],+ }),+ ).toBe(false);+});++test('unbounded lazy hook predictions intersect literal dontAsk exceptions and static denial', () => {+ const agents = [+ { id: 'root', tools: ['read_file'], subagentGraphMemberMetadata: [{ id: 'child' }] },+ ];+ const hook = {+ hook: askHook,+ matcher: '^(?:bash_tool|create_file)$',+ agentIds: new Set(['child']),+ };+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: ['read_file'] };+ expect(canAgentGraphPause({ policy, agents, resolvedProgrammaticHooks: [hook] })).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['read_file', 'bash_tool'] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['read_file', 'bash_tool'], deny: ['bash_tool'] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'dontAsk' },+ agents,+ resolvedProgrammaticHooks: [{ hook: askHook }],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['write_*'] },+ agents,+ resolvedProgrammaticHooks: [{ hook: askHook }],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['write_*'], deny: ['*'] },+ agents,+ resolvedProgrammaticHooks: [{ hook: askHook }],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ resolvedProgrammaticHooks: [{ ...hook, toolNames: ['bash_tool', 'create_file'] }],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['bash_*'] },+ agents,+ resolvedProgrammaticHooks: [{ ...hook, toolNames: ['bash_tool'] }],+ }),+ ).toBe(true);+});++test('lazy plugin prediction uses eligible literal exceptions instead of denied hook presence', () => {+ const agents = [{ tools: ['read_file'], subagentGraphMemberMetadata: [{ id: 'child' }] }];+ const source = pluginSource((names) => names == null || names.includes('bash_tool'));+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: ['read_file'] };+ expect(canAgentGraphPause({ policy, agents, pluginHookSource: source })).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['read_file', 'bash_tool'] },+ agents,+ pluginHookSource: source,+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['read_file', 'bash_tool'], deny: ['bash_tool'] },+ agents,+ pluginHookSource: source,+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'dontAsk' },+ agents,+ pluginHookSource: source,+ }),+ ).toBe(false);+});++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each([+ {+ selected: 'db_query_mcp_db',+ permitted: 'query_mcp_db',+ matched: 'db_query_mcp_db',+ server: 'db',+ },+ {+ selected: 'query_mcp_db',+ permitted: 'query_mcp_db',+ matched: 'db_query_mcp_db',+ server: 'db',+ },+ {+ selected: 'query_mcp_DB',+ permitted: 'query_mcp_DB',+ matched: 'db_query_mcp_DB',+ server: 'DB',+ },+ {+ selected: 'db_ops_query_mcp_db ops',+ permitted: 'query_mcp_db_ops',+ matched: 'db_ops_query_mcp_db_ops',+ server: 'db ops',+ },+ {+ selected: 'get_mcp_version_mcp_db',+ permitted: 'get_mcp_version_mcp_db',+ matched: 'db_get_mcp_version_mcp_db',+ server: 'db',+ },+ ])(+ `${placement} preserves possible lazy alias hook scope without assigning identity ($selected)`,+ ({ selected, permitted, matched, server }) => {+ const child = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: [selected] },+ { rawMcpServerNames: [server] },+ );+ const agents = [{ id: 'root', tools: ['subagent'], [placement]: [child] }];+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: [permitted, 'subagent'] };+ const hook = { hook: askHook, matcher: `^${matched}$`, agentIds: new Set(['child']) };+ expect(canAgentGraphPause({ policy, agents, resolvedProgrammaticHooks: [hook] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ resolvedProgrammaticHooks: [{ ...hook, toolNames: [matched] }],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ pluginHookSource: pluginSource((names) => names == null || names.includes(matched)),+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['*_mcp_*'] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['subagent'] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ resolvedProgrammaticHooks: [{ ...hook, agentIds: new Set(['other']) }],+ }),+ ).toBe(false);+ expect(child).not.toHaveProperty('mcpToolAliases');+ expect(child).not.toHaveProperty('tools');+ },+ );+}++test.each(['query_mcp_db', 'db_query_mcp_db', `${Constants.mcp_all}${Constants.mcp_delimiter}db`])(+ 'lazy hook admission matches the actual catalog alias for %s',+ async (selected) => {+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: ['query_mcp_db', 'subagent'] };+ const hook = { hook: askHook, matcher: '^db_query_mcp_db$', agentIds: new Set(['child']) };+ const catalog = formatMCPServerTools('db', [+ { name: 'db_query', inputSchema: { type: 'object', properties: {} } },+ ]);+ const loaded = await loadToolDefinitions(+ {+ userId: 'user',+ agentId: 'child',+ tools: [selected],+ rawServerNames: ['db'],+ mcpServerNames: ['db'],+ },+ { getOrFetchMCPServerTools: async () => catalog, isBuiltInTool: () => false },+ );+ const resolved = {+ id: 'child',+ toolDefinitions: loaded.toolDefinitions,+ mcpToolAliases: loaded.mcpToolAliases,+ };+ expect(+ canAgentGraphPause({ policy, agents: [resolved], resolvedProgrammaticHooks: [hook] }),+ ).toBe(true);+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: [selected] },+ { rawMcpServerNames: ['db'] },+ );+ expect(+ canAgentGraphPause({+ policy,+ agents: [{ tools: ['subagent'], lazySubagentConfigs: [descriptor] }],+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(true);+ },+);++test('lazy alias predictions preserve direct-name denial, closed catalogs and wildcard exact-server boundaries', () => {+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: ['query_mcp_db', 'subagent'] };+ const hook = { hook: askHook, matcher: '^db_query_mcp_db$', agentIds: new Set(['child']) };+ const lazy = (source: ToolApprovalAdmissionAgent) => [+ {+ tools: ['subagent'],+ lazySubagentConfigs: [+ copyToolApprovalAdmissionMetadata({ id: 'child' }, source, {+ rawMcpServerNames: ['db', 'other', 'other_mcp_db'],+ }),+ ],+ },+ ];+ expect(+ canAgentGraphPause({+ policy,+ agents: lazy({ tools: ['query_mcp_db'], toolDefinitions: [{ name: 'query_mcp_db' }] }),+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents: lazy({ tools: [`${Constants.mcp_all}${Constants.mcp_delimiter}other`] }),+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents: lazy({ tools: ['read_mcp_other'] }),+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['db_query_mcp_db'] },+ agents: lazy({ tools: ['db_query_mcp_db'] }),+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ const currentHook = { ...hook, matcher: '^query_mcp_db$' };+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['db_query_mcp_db'] },+ agents: lazy({ tools: ['query_mcp_db'] }),+ resolvedProgrammaticHooks: [currentHook],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({ policy, agents: lazy({ tools: [] }), resolvedProgrammaticHooks: [hook] }),+ ).toBe(false);+});++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each(['db', 'Db', 'dB', 'DB'])(+ `${placement} case-variant hook admission matches actual catalog stripping (%s)`,+ async (prefix) => {+ const policy = {+ enabled: true,+ mode: 'dontAsk' as const,+ allow: ['query_mcp_db', 'subagent'],+ };+ const upstream = `${prefix}_query`;+ const legacy = `${upstream}_mcp_db`;+ const hook = { hook: askHook, matcher: `^${legacy}$`, agentIds: new Set(['child']) };+ const catalog = formatMCPServerTools('db', [+ { name: upstream, inputSchema: { type: 'object', properties: {} } },+ ]);+ const loaded = await loadToolDefinitions(+ {+ userId: 'user',+ agentId: 'child',+ tools: ['query_mcp_db'],+ rawServerNames: ['db'],+ mcpServerNames: ['db'],+ },+ { getOrFetchMCPServerTools: async () => catalog, isBuiltInTool: () => false },+ );+ expect(loaded.mcpToolAliases).toContainEqual({ name: 'query_mcp_db', aliasName: legacy });+ const resolved = {+ id: 'child',+ toolDefinitions: loaded.toolDefinitions,+ mcpToolAliases: loaded.mcpToolAliases,+ };+ expect(+ canAgentGraphPause({ policy, agents: [resolved], resolvedProgrammaticHooks: [hook] }),+ ).toBe(true);+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: ['query_mcp_db'] },+ { rawMcpServerNames: ['db', 'DB'] },+ );+ const agents = [{ tools: ['subagent'], [placement]: [descriptor] }];+ expect(canAgentGraphPause({ policy, agents, resolvedProgrammaticHooks: [hook] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: [legacy] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ resolvedProgrammaticHooks: [{ ...hook, matcher: `^${upstream}_mcp_DB$` }],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { ...policy, allow: ['subagent'] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(descriptor).not.toHaveProperty('mcpToolAliases');+ expect(hook.hook).not.toHaveProperty('mock');+ },+ );+}++test('nonliteral case-variant hook matchers remain conservative only on eligible unresolved MCP selections', () => {+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: ['query_mcp_db', 'subagent'] };+ const hook = { hook: askHook, matcher: '^(?:D[Bb]_query_mcp_db)$', agentIds: new Set(['child']) };+ const agents = [+ {+ tools: ['subagent'],+ lazySubagentConfigs: [+ copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: ['query_mcp_db'] },+ { rawMcpServerNames: ['db'] },+ ),+ ],+ },+ ];+ expect(canAgentGraphPause({ policy, agents, resolvedProgrammaticHooks: [hook] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: ['*_mcp_*'] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({ policy, agents, resolvedProgrammaticHooks: [{ ...hook, matcher: '[' }] }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ resolvedProgrammaticHooks: [{ ...hook, toolNames: ['D_query_mcp_other'] }],+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ resolvedProgrammaticHooks: [{ ...hook, matcher: '^(?:DB_query_mcp_db|read_mcp_other)$' }],+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy,+ agents,+ pluginHookSource: pluginSource((names) => names == null || names.includes('dB_query_mcp_db')),+ }),+ ).toBe(true);+});++test('long mixed-case upstream prefixes use actual literal matcher spellings without exponential enumeration', () => {+ const server = 'long_server_name_with_many_letters';+ const legacy = 'LoNg_SeRvEr_NaMe_WiTh_MaNy_LeTtErS_query_mcp_' + server;+ const current = 'query_mcp_' + server;+ const descriptor = copyToolApprovalAdmissionMetadata(+ { id: 'child' },+ { tools: [current] },+ { rawMcpServerNames: [server] },+ );+ const agents = [{ tools: ['subagent'], lazySubagentConfigs: [descriptor] }];+ const policy = { enabled: true, mode: 'dontAsk' as const, allow: [current, 'subagent'] };+ const hook = { hook: askHook, matcher: `^${legacy}$`, agentIds: new Set(['child']) };+ expect(canAgentGraphPause({ policy, agents, resolvedProgrammaticHooks: [hook] })).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { ...policy, deny: [legacy] },+ agents,+ resolvedProgrammaticHooks: [hook],+ }),+ ).toBe(false);+});diff --git a/packages/api/src/agents/hitl/admission.ts b/packages/api/src/agents/hitl/admission.tsindex 3e8ea9612d..0b7aa9e2fb 100644--- a/packages/api/src/agents/hitl/admission.ts+++ b/packages/api/src/agents/hitl/admission.ts@@ -1,9 +1,28 @@+import {+ Constants,+ isActionTool,+ normalizeServerName,+ stripServerNamePrefix,+ splitMCPToolKey,+ buildServerNameAliases,+} from 'librechat-data-provider';import type { TToolApprovalPolicy } from 'librechat-data-provider';+import type { AgentToolOptions } from 'librechat-data-provider';import type { PluginHookSource } from '~/agents/hooks/source';import type { MCPToolAlias } from '~/tools/classification';+import type { SkillPrimeWithTools } from '~/agents/skills';import type { ResolvedToolApprovalHook } from './hooks';-import { isHITLEnabled, isToolApprovalPauseCapable, isToolDeniedByApprovalPolicy } from './policy';+import {+ isHITLEnabled,+ isToolApprovalPauseCapable,+ isToolDeniedByApprovalPolicy,+ isToolBlockedByApprovalPolicy,+ healToolApprovalPolicy,+} from './policy';+import { selectSkillPrimesForTurn, unionPrimeAllowedTools } from '~/agents/skills';+import { isMCPAllPlaceholder, normalizeAgentToolKeys } from '~/mcp/utils';import { ASK_USER_QUESTION_TOOL_NAME } from './askUserQuestionTool';+import { aliasMCPToolOptions } from '~/tools/classification';import { resolvedToolApprovalHooksCanMatch } from './hooks';import { buildEffectiveToolApprovalPolicy } from './allow';@@ -22,6 +41,7 @@ interface ApprovalSubagentGraph {export interface ToolApprovalAdmissionAgent {readonly id?: string;+ readonly tool_options?: AgentToolOptions;readonly tools?: readonly (string | ApprovalToolReference)[];readonly toolRegistry?: ApprovalToolRegistry;readonly toolDefinitions?: readonly ApprovalToolReference[];@@ -32,6 +52,81 @@ export interface ToolApprovalAdmissionAgent {readonly subagentGraphConfigs?: readonly ApprovalSubagentGraph[];}+type AdmissionSurface = Pick<+ ToolApprovalAdmissionAgent,+ 'tool_options' | 'tools' | 'toolRegistry' | 'toolDefinitions' | 'mcpToolAliases'+> & { readonly rawMcpServerNames?: readonly string[] };+const admissionSurfaces = new WeakMap<object, AdmissionSurface>();++function readAdmissionSurface(+ agent: ToolApprovalAdmissionAgent,+): ToolApprovalAdmissionAgent & AdmissionSurface {+ const captured = admissionSurfaces.get(agent);+ return captured ? { ...captured, ...agent } : agent;+}++interface AdmissionProjectionContext {+ readonly skillPrimes?: readonly SkillPrimeWithTools[];+ readonly rawMcpServerNames?: readonly string[];+ readonly toolsAvailable?: boolean;+}++/** Retain only admission data across server-only lazy projections. */+export function copyToolApprovalAdmissionMetadata<T extends object>(+ target: T,+ source: ToolApprovalAdmissionAgent,+ context: AdmissionProjectionContext = {},+): T {+ const surface = readAdmissionSurface(source);+ const selectedTools: string[] | undefined = surface.tools == null ? undefined : [];+ for (const tool of surface.tools ?? []) {+ const name = typeof tool === 'string' ? tool : tool.name;+ if (name) selectedTools!.push(name);+ }+ const { alwaysApplySkillPrimes } = selectSkillPrimesForTurn({+ manualSkillPrimes: [],+ alwaysApplySkillPrimes: context.skillPrimes ?? [],+ });+ const { extraToolNames } = unionPrimeAllowedTools({+ primes: alwaysApplySkillPrimes,+ agentToolNames: selectedTools ?? [],+ });+ const effectiveTools =+ selectedTools == null && extraToolNames.length === 0+ ? undefined+ : [...(selectedTools ?? []), ...extraToolNames];+ const normalized = normalizeAgentToolKeys({+ tools:+ context.toolsAvailable === false+ ? effectiveTools?.filter(+ (name) => isActionTool(name) || !name.includes(Constants.mcp_delimiter),+ )+ : effectiveTools,+ toolOptions: surface.tool_options,+ rawServerNames: context.rawMcpServerNames ?? surface.rawMcpServerNames ?? [],+ });+ 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 }]),+ ),+ tools: normalized.tools,+ rawMcpServerNames: context.rawMcpServerNames?.slice() ?? surface.rawMcpServerNames,+ toolRegistry: surface.toolRegistry,+ toolDefinitions: surface.toolDefinitions?.map(({ name }) => ({ name })),+ mcpToolAliases: surface.mcpToolAliases?.map((alias) => ({ ...alias })),+ });+ return target;+}+export interface ToolApprovalAdmissionInput {readonly policy: TToolApprovalPolicy | undefined;readonly agents: readonly (ToolApprovalAdmissionAgent | null | undefined)[];@@ -43,6 +138,145 @@ export interface ToolApprovalAdmissionInput {readonly toolApprovalAllows?: readonly string[];}+/** Exact trusted matchers provide case-preserving candidates; other regexes remain unresolved. */+function literalHookNames(matcher?: string): string[] | undefined {+ if (!matcher?.startsWith('^') || !matcher.endsWith('$')) return undefined;+ let pattern = matcher.slice(1, -1);+ if (pattern.startsWith('(?:') && pattern.endsWith(')')) pattern = pattern.slice(3, -1);+ else if (pattern.includes('|')) return undefined;+ const names = pattern.split('|');+ if (names.some((name) => !/^[A-Za-z0-9 _-]+$/.test(name.replace(/\\[.-]/g, '_'))))+ return undefined;+ return names.map((name) => name.replace(/\\([.-])/g, '$1'));+}++/** Possible catalog spellings are admission hints, never authorization aliases. */+function unresolvedHookSpellings(name: string, rawServerNames: readonly string[]): string[] {+ 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 => {+ const raw = rawServerNames.includes(server) ? server : (aliases.get(server) ?? server);+ const normalized = normalizeServerName(raw);+ const suffixes =+ aliases.get(normalized) == null || aliases.get(normalized) === raw+ ? new Set([server, raw, normalized])+ : new Set([server]);+ const stripped = stripServerNamePrefix(tool, normalized);+ const tools = new Set([tool, stripped]);+ for (const prefix of new Set([normalized, normalized.toLowerCase()])) {+ const legacy = `${prefix}_${stripped}`;+ if (stripServerNamePrefix(legacy, normalized) === stripped) tools.add(legacy);+ }+ for (const suffix of suffixes)+ for (const candidate of tools)+ spellings.add(`${candidate}${Constants.mcp_delimiter}${suffix}`);+ };+ const [tool, server] = splitMCPToolKey(name, known);+ if (server != null && known.includes(server)) add(tool, server);+ else {+ let delimiter = name.indexOf(Constants.mcp_delimiter);+ while (delimiter >= 0) {+ const suffix = name.slice(delimiter + Constants.mcp_delimiter.length);+ if (suffix) add(name.slice(0, delimiter), suffix);+ delimiter = name.indexOf(Constants.mcp_delimiter, delimiter + Constants.mcp_delimiter.length);+ }+ }+ return [...spellings];+}++/** Unresolved spellings predict review only; they never establish tool identity. */+function createUnresolvedReviewMatcher(+ options: AgentToolOptions,+ policy: TToolApprovalPolicy | undefined,+ toolNames: ReadonlySet<string>,+ rawServerNames: readonly string[] = [],+): (name?: string) => boolean {+ const wildcardServers: string[] = [];+ for (const name of toolNames) {+ if (isMCPAllPlaceholder(name)) {+ wildcardServers.push(name.slice(`${Constants.mcp_all}${Constants.mcp_delimiter}`.length));+ }+ }+ const declaredAliases = buildServerNameAliases(rawServerNames);+ const declaredNames = new Set(rawServerNames);+ // Do not let a normalized wildcard spelling invent a direct server over its raw owner.+ const serverNames = [+ ...rawServerNames,+ ...wildcardServers.filter(+ (server) => !declaredNames.has(server) && !declaredAliases.has(server),+ ),+ ];+ const directNames = new Set(serverNames);+ const serverAliases = buildServerNameAliases(serverNames);+ const knownNames = [...new Set([...serverNames, ...serverNames.map(normalizeServerName)])];+ const knownNameSet = new Set(knownNames);+ const resolveServer = (server: string) =>+ 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 => {+ 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) {+ 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);+ }+ return false;+ };+ const originalNames = new Map<string, string[]>();+ const strippedNames = new Map<string, string[]>();+ const index = (names: Map<string, string[]>, key: string, name: string) => {+ const entries = names.get(key) ?? [];+ entries.push(name);+ names.set(key, entries);+ };+ const canReview = (name: string, aliasName = name) =>+ !isToolBlockedByApprovalPolicy(healToolApprovalPolicy(policy, [{ name, aliasName }]), name);+ const reviewServers = new Set<string>();+ let unknownCanAsk = false;+ for (const [name, option] of Object.entries(options)) {+ if (+ option.approval_mode == null ||+ option.approval_mode === 'allow' ||+ isToolDeniedByApprovalPolicy(policy, name)+ )+ continue;+ unknownCanAsk ||= canReview(name);+ visitParts(name, (tool, server) => {+ index(originalNames, key(server, tool), name);+ const stripped = stripServerNamePrefix(tool, normalizeServerName(server));+ const canonical = `${stripped}${Constants.mcp_delimiter}${server}`;+ if (canReview(name, canonical) || canReview(canonical, name)) {+ reviewServers.add(resolveServer(server));+ unknownCanAsk = true;+ }+ if (stripped !== tool) index(strippedNames, key(server, stripped), name);+ return false;+ });+ }+ return (name) => {+ if (name == null) return unknownCanAsk;+ if (isMCPAllPlaceholder(name)) {+ const server = name.slice(`${Constants.mcp_all}${Constants.mcp_delimiter}`.length);+ return reviewServers.has(resolveServer(server));+ }+ if (options[name] != null || isToolDeniedByApprovalPolicy(policy, name)) return false;+ return visitParts(name, (tool, server) => {+ if (strippedNames.get(key(server, tool))?.some((alias) => canReview(name, alias)))+ return true;+ const stripped = stripServerNamePrefix(tool, normalizeServerName(server));+ return (+ stripped !== tool &&+ originalNames.get(key(server, stripped))?.some((alias) => canReview(name, alias)) === true+ );+ });+ };+}+function agentHasTool(agent: ToolApprovalAdmissionAgent, toolName: string): boolean {return (agent.tools?.some((tool) => (typeof tool === 'string' ? tool : tool.name) === toolName) ===@@ -55,11 +289,13 @@ function agentHasTool(agent: ToolApprovalAdmissionAgent, toolName: string): boolfunction collectApprovalAgents(roots: readonly (ToolApprovalAdmissionAgent | null | undefined)[]): {agents: ToolApprovalAdmissionAgent[];lazyAgentIds: Set<string | undefined>;+ lazyAgents: Set<ToolApprovalAdmissionAgent>;} {const agents: ToolApprovalAdmissionAgent[] = [];const visited = new Set<ToolApprovalAdmissionAgent>();const pending = [...roots];const lazyAgentIds = new Set<string | undefined>();+ const lazyAgents = new Set<ToolApprovalAdmissionAgent>();for (let index = 0; index < pending.length; index++) {const agent = pending[index];@@ -72,16 +308,21 @@ function collectApprovalAgents(roots: readonly (ToolApprovalAdmissionAgent | nulif ((agent.lazySubagentConfigs?.length ?? 0) > 0) {for (const lazyAgent of agent.lazySubagentConfigs ?? []) {lazyAgentIds.add(lazyAgent?.id);+ if (lazyAgent) lazyAgents.add(lazyAgent);}pending.push(...(agent.lazySubagentConfigs ?? []));}- pending.push(...(agent.subagentGraphMemberMetadata ?? []));+ for (const member of agent.subagentGraphMemberMetadata ?? []) {+ lazyAgentIds.add(member?.id);+ if (member) lazyAgents.add(member);+ pending.push(member);+ }for (const graph of agent.subagentGraphConfigs ?? []) {pending.push(...(graph.memberConfigs ?? []));}}- return { agents, lazyAgentIds };+ return { agents, lazyAgentIds, lazyAgents };}/**@@ -109,6 +350,8 @@ export function canAgentGraphPause({const approvalGraph = collectApprovalAgents(agents);const toolOwners = new Map<string, Set<string | undefined>>();+ const reviewGatedTools = new Set<string>();+ let unresolvedModeCanAsk = false;const aliases: MCPToolAlias[] = [];const aliasesByToolName = new Map<string, string[]>();const addToolName = (name: unknown, agentId?: string) => {@@ -124,18 +367,38 @@ export function canAgentGraphPause({}for (const agent of approvalGraph.agents) {- for (const tool of agent.tools ?? []) {- addToolName(typeof tool === 'string' ? tool : tool.name, agent.id);+ const surface = readAdmissionSurface(agent);+ 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 (agent.toolRegistry) {- for (const name of agent.toolRegistry.keys()) {- addToolName(name, agent.id);- }+ for (const name of surface.toolRegistry?.keys() ?? []) reachable.add(name);+ for (const definition of surface.toolDefinitions ?? []) {+ if (definition.name) reachable.add(definition.name);}- for (const definition of agent.toolDefinitions ?? []) {- addToolName(definition.name, agent.id);+ const options = { ...surface.tool_options };+ aliasMCPToolOptions(surface.mcpToolAliases ?? [], options);+ for (const name of reachable) {+ addToolName(name, agent.id);+ const mode = options[name]?.approval_mode;+ if (mode != null && mode !== 'allow') reviewGatedTools.add(name);}- for (const alias of agent.mcpToolAliases ?? []) {+ if (+ !unresolvedModeCanAsk &&+ approvalGraph.lazyAgents.has(agent) &&+ surface.toolRegistry == null &&+ surface.toolDefinitions == null+ ) {+ const canAsk = createUnresolvedReviewMatcher(+ options,+ buildEffectiveToolApprovalPolicy(policy, surface.mcpToolAliases ?? [], toolApprovalAllows),+ reachable,+ surface.rawMcpServerNames,+ );+ unresolvedModeCanAsk = surface.tools == null ? canAsk() : [...reachable].some(canAsk);+ }+ for (const alias of surface.mcpToolAliases ?? []) {aliases.push(alias);const names = aliasesByToolName.get(alias.name) ?? [];names.push(alias.aliasName);@@ -145,6 +408,8 @@ export function canAgentGraphPause({const effectivePolicy = buildEffectiveToolApprovalPolicy(policy, aliases, toolApprovalAllows);const knownToolCanPause = Array.from(toolOwners).some(([toolName, agentIds]) => {+ if (isToolBlockedByApprovalPolicy(effectivePolicy, toolName)) return false;+ if (reviewGatedTools.has(toolName)) return true;const matcherNames = [toolName, ...(aliasesByToolName.get(toolName) ?? [])];const pluginHookCanAsk = pluginHookSource?.hasToolApprovalHooks?.([toolName]) === true;return Array.from(agentIds).some((agentId) => {@@ -163,14 +428,109 @@ export function canAgentGraphPause({}if (approvalGraph.lazyAgentIds.size > 0) {const pluginHookCanAsk = pluginHookSource?.hasToolApprovalHooks?.() === true;- const unresolvedHookCanAsk = Array.from(approvalGraph.lazyAgentIds).some(- (agentId) =>- resolvedProgrammaticHooks.some(- ({ agentIds }) => agentIds == null || (agentId != null && agentIds.has(agentId)),- ) || pluginHookCanAsk,- );+ const exceptions = [...(effectivePolicy?.ask ?? []), ...(effectivePolicy?.allow ?? [])];+ const unboundedHookCanAsk =+ isToolApprovalPauseCapable(effectivePolicy, true) &&+ (effectivePolicy?.mode !== 'dontAsk' || exceptions.length > 0);+ const finitePolicyNames =+ effectivePolicy?.mode === 'dontAsk' && exceptions.every((name) => !name.includes('*'))+ ? exceptions+ : undefined;+ const unresolvedHookCanAsk = Array.from(approvalGraph.lazyAgents).some((agent) => {+ const surface = readAdmissionSurface(agent);+ const knownCatalog = surface.toolRegistry != null || surface.toolDefinitions != null;+ const rawNames = surface.rawMcpServerNames ?? [];+ const cache = new Map<string, string[]>();+ const spellings = (name: string): string[] => {+ let names = cache.get(name);+ if (!names) {+ names = knownCatalog ? [name] : unresolvedHookSpellings(name, rawNames);+ cache.set(name, names);+ }+ return names;+ };+ const canAskAs = (name: string, matches: (names: readonly string[]) => boolean): boolean =>+ spellings(name).some((aliasName) => {+ const possible = name === aliasName ? [name] : [name, aliasName];+ const predictedPolicy = healToolApprovalPolicy(effectivePolicy, [{ name, aliasName }]);+ return !isToolBlockedByApprovalPolicy(predictedPolicy, name) && matches(possible);+ });+ const selected: string[] | undefined = surface.tools+ ?.map((tool) => (typeof tool === 'string' ? tool : (tool.name ?? '')))+ .filter(Boolean);+ const rawAliases = buildServerNameAliases(rawNames);+ const resolveServer = (server: string) =>+ rawNames.includes(server) ? server : (rawAliases.get(server) ?? server);+ const wildcardServers = new Set(+ (selected ?? [])+ .filter(isMCPAllPlaceholder)+ .map((name) =>+ resolveServer(name.slice(`${Constants.mcp_all}${Constants.mcp_delimiter}`.length)),+ ),+ );+ const candidates = (names: readonly string[]): readonly string[] => {+ if (knownCatalog) return [];+ if (selected == null) return names;+ const concrete = selected.filter((name) => !isMCPAllPlaceholder(name));+ return [+ ...new Set([+ ...concrete,+ ...names.filter((name) => {+ // Strip the actual matcher spelling, not a guessed casing of the upstream prefix.+ if (spellings(name).some((candidate) => concrete.includes(candidate))) return true;+ const [, server] = splitMCPToolKey(name, [+ ...rawNames,+ ...rawAliases.keys(),+ ...wildcardServers,+ ]);+ return server != null && wildcardServers.has(resolveServer(server));+ }),+ ]),+ ];+ };+ return (+ resolvedProgrammaticHooks.some((hook) => {+ if (hook.agentIds != null && (agent.id == null || !hook.agentIds.has(agent.id)))+ return false;+ if (knownCatalog) return false;+ const literalNames = literalHookNames(hook.matcher);+ const names = hook.toolNames ?? literalNames ?? finitePolicyNames;+ if (names == null) return unboundedHookCanAsk;+ if (+ (hook.toolNames ?? candidates(names)).some((name) =>+ canAskAs(name, (possible) =>+ resolvedToolApprovalHooksCanMatch([hook], possible, agent.id),+ ),+ )+ )+ return true;+ if (hook.toolNames != null || literalNames != null || hook.matcher == null) return false;+ try {+ new RegExp(hook.matcher);+ } catch {+ return false;+ }+ // A catalog-free case-insensitive prefix can match a nonliteral regex in unknown casing.+ return candidates(finitePolicyNames ?? []).some(+ (name) => spellings(name).length > 1 && canAskAs(name, () => true),+ );+ }) ||+ (pluginHookCanAsk &&+ !knownCatalog &&+ (finitePolicyNames == null+ ? unboundedHookCanAsk+ : candidates(finitePolicyNames).some((name) =>+ canAskAs(+ name,+ (possible) =>+ pluginHookSource?.hasToolApprovalHooks?.(possible) === true ||+ spellings(name).length > 1,+ ),+ )))+ );+ });const staticPolicyCanAsk = isToolApprovalPauseCapable(effectivePolicy);- if (staticPolicyCanAsk || unresolvedHookCanAsk) {+ if (staticPolicyCanAsk || unresolvedHookCanAsk || unresolvedModeCanAsk) {return true;}}diff --git a/packages/api/src/agents/hitl/byom.spec.ts b/packages/api/src/agents/hitl/byom.spec.tsindex 45bf807a40..c1e21bea17 100644--- a/packages/api/src/agents/hitl/byom.spec.ts+++ b/packages/api/src/agents/hitl/byom.spec.ts@@ -629,3 +629,81 @@ describe('assertAttachedCodeEnvironmentApprovalSupported', () => {).not.toThrow();});});++for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] as const) {+ test.each(['dontAsk', 'bypass'] as const)(+ `${placement} BYOM hooks cannot predict review of statically denied tools under %s`,+ (mode) => {+ const graph = {+ id: 'root',+ tools: ['read_file'],+ [placement]: [+ {+ id: 'attached-member',+ codeExecutionContext: { environmentType: 'attached' },+ skillAuthoringAvailable: true,+ },+ ],+ };+ const ids = collectAttachedCodeEnvironmentAgentIds([graph]);+ const settings = collectAttachedCodeEnvironmentPolicySettings([graph]);+ const hooks = buildAttachedCodeEnvironmentAdmissionHooks(ids, settings);+ expect(hooks.every((h) => h.toolNames?.length)).toBe(true);+ const denied = {+ enabled: true,+ mode,+ allow: ['read_file'],+ ...(mode === 'bypass'+ ? {+ deny: [+ 'write_file',+ 'edit_file',+ 'create_file',+ 'bash_tool',+ 'execute_code',+ 'run_tools_with_bash',+ 'run_tools_with_code',+ 'compile_check',+ ],+ }+ : {}),+ };+ expect(+ canAgentGraphPause({ policy: denied, agents: [graph], resolvedProgrammaticHooks: hooks }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'dontAsk', allow: ['read_file', 'bash_tool'] },+ agents: [graph],+ resolvedProgrammaticHooks: hooks,+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy: {+ enabled: true,+ mode: 'dontAsk',+ allow: ['read_file', 'bash_tool'],+ deny: ['bash_tool'],+ },+ agents: [graph],+ resolvedProgrammaticHooks: hooks,+ }),+ ).toBe(false);+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'dontAsk', allow: ['read_file', 'create_file'] },+ agents: [graph],+ resolvedProgrammaticHooks: hooks,+ }),+ ).toBe(true);+ expect(+ canAgentGraphPause({+ policy: { enabled: true, mode: 'bypass', deny: ['*'] },+ agents: [graph],+ resolvedProgrammaticHooks: hooks,+ }),+ ).toBe(false);+ },+ );+}diff --git a/packages/api/src/agents/hitl/byom.ts b/packages/api/src/agents/hitl/byom.tsindex c349836454..4cd0c737ab 100644--- a/packages/api/src/agents/hitl/byom.ts+++ b/packages/api/src/agents/hitl/byom.ts@@ -298,13 +298,19 @@ export function buildAttachedCodeEnvironmentAdmissionHooks(if (policy?.skillAuthoringAvailable === true) skillAuthoringAgents.add(agentId);}if (askFileAgents.size > 0) {- hooks.push({ hook, matcher: exactToolMatcher(BYOM_FILE_WRITE_TOOLS), agentIds: askFileAgents });+ hooks.push({+ hook,+ matcher: exactToolMatcher(BYOM_FILE_WRITE_TOOLS),+ agentIds: askFileAgents,+ toolNames: [...BYOM_FILE_WRITE_TOOLS],+ });}if (askCommandAgents.size > 0) {hooks.push({hook,matcher: exactToolMatcher(BYOM_COMMAND_EXECUTION_TOOLS),agentIds: askCommandAgents,+ toolNames: [...BYOM_COMMAND_EXECUTION_TOOLS],});}if (skillAuthoringAgents.size > 0) {@@ -312,6 +318,7 @@ export function buildAttachedCodeEnvironmentAdmissionHooks(hook,matcher: exactToolMatcher(new Set([CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME])),agentIds: skillAuthoringAgents,+ toolNames: [CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME],});}return hooks;diff --git a/packages/api/src/agents/hitl/controller.spec.ts b/packages/api/src/agents/hitl/controller.spec.tsnew file mode 100644index 0000000000..ef6dcc8a92--- /dev/null+++ b/packages/api/src/agents/hitl/controller.spec.ts@@ -0,0 +1,273 @@+import express from 'express';+import request from 'supertest';+import type { ToolApprovalGrantStorage, Agent } from 'librechat-data-provider';+import type { MCPServerTools } from '~/tools/definitions';+import type { ParsedServerConfig } from '~/mcp/types';+import { createResetToolApprovalController } from './controller';+import { formatMCPServerTools } from '~/mcp/tools';++function fixture(user?: { id: string; role?: string }) {+ const storage: ToolApprovalGrantStorage = {+ getToolApprovalGrants: async () => [],+ rememberToolApprovalGrants: async () => {},+ resetToolApprovalGrants: jest.fn(async () => {}),+ };+ const app = express();+ app.use(express.json());+ const getAgent = jest.fn(+ async (): Promise<Pick<Agent, 'id' | 'tool_options'>> => ({+ id: 'agent-a',+ tool_options: { query_mcp_db: { approval_mode: 'chat' as const } },+ }),+ );+ const canAccessAgent = jest.fn(async () => true);+ const hasCapability = jest.fn(async () => false);+ const getMCPServerConfigs = jest.fn(+ async (): Promise<Record<string, ParsedServerConfig>> => ({+ db: { type: 'streamable-http', url: 'https://mcp.example.test/mcp' },+ }),+ );+ const getMCPServerTools = jest.fn(async (): Promise<MCPServerTools | null> => null);+ const controller = createResetToolApprovalController({+ storage,+ getAgent,+ canAccessAgent,+ hasCapability,+ getMCPServerConfigs,+ getMCPServerTools,+ });+ app.post('/reset', (req, res) => controller(Object.assign(req, { user }), res));+ return {+ storage,+ app,+ getAgent,+ canAccessAgent,+ hasCapability,+ getMCPServerConfigs,+ getMCPServerTools,+ };+}++const reset = { agentId: 'agent-a', toolName: 'query_mcp_db' };++test('reset is authenticated and never accepts a caller-selected principal', async () => {+ const missing = fixture();+ await request(missing.app).post('/reset').send(reset).expect(401);+ expect(missing.storage.resetToolApprovalGrants).not.toHaveBeenCalled();+ const forged = fixture({ id: 'user-a' });+ await request(forged.app)+ .post('/reset')+ .send({ ...reset, userId: 'user-b' })+ .expect(400);+ expect(forged.storage.resetToolApprovalGrants).not.toHaveBeenCalled();+});++test('reset scopes storage to the authenticated owner and sanitizes failures', async () => {+ const f = fixture({ id: 'user-a' });+ await request(f.app).post('/reset').send(reset).expect(200, { reset: true });+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith(+ 'user-a',+ 'agent-a',+ 'query_mcp_db',+ );+ f.storage.resetToolApprovalGrants = async () => {+ throw new Error('secret-provider-payload');+ };+ await request(f.app).post('/reset').send(reset).expect(503, { code: 'APPROVAL_RESET_FAILED' });+});++test('unknown tools and inaccessible agents cannot create reset fences', async () => {+ const f = fixture({ id: 'user-a' });+ await request(f.app)+ .post('/reset')+ .send({ ...reset, toolName: 'unknown-tool' })+ .expect(403);+ f.canAccessAgent.mockResolvedValue(false);+ await request(f.app).post('/reset').send(reset).expect(403);+ expect(f.storage.resetToolApprovalGrants).not.toHaveBeenCalled();+});++test('a VIEW-only caller resets all personal learned modes without requesting authoring data', async () => {+ const f = fixture({ id: 'viewer-a' });+ f.getAgent.mockResolvedValueOnce({ id: 'agent-a' });+ await request(f.app).post('/reset').send({ agentId: 'agent-a' }).expect(200, { reset: true });+ expect(f.canAccessAgent).toHaveBeenCalled();+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith('viewer-a', 'agent-a', undefined);+ await request(f.app)+ .post('/reset')+ .send({ agentId: 'agent-a', tenantId: 'another-tenant' })+ .expect(400);+ f.canAccessAgent.mockResolvedValue(false);+ await request(f.app).post('/reset').send({ agentId: 'agent-a' }).expect(403);+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledTimes(1);+});++test.each([undefined, 'query_mcp_db'])(+ 'manage:agents authorizes personal reset with tool=%s without a resource ACL',+ async (toolName) => {+ const f = fixture({ id: 'manager-a', role: 'USER' });+ f.hasCapability.mockResolvedValue(true);+ f.canAccessAgent.mockResolvedValue(false);+ await request(f.app)+ .post('/reset')+ .send({ agentId: 'agent-a', toolName })+ .expect(200, { reset: true });+ expect(f.hasCapability).toHaveBeenCalledWith(+ { id: 'manager-a', role: 'USER' },+ 'manage:agents',+ );+ expect(f.canAccessAgent).not.toHaveBeenCalled();+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith(+ 'manager-a',+ 'agent-a',+ toolName,+ );+ },+);++test('a failed capability lookup never grants access and preserves the normal ACL fallback', async () => {+ const f = fixture({ id: 'viewer-a', role: 'USER' });+ f.hasCapability.mockRejectedValue(new Error('synthetic capability failure'));+ f.canAccessAgent.mockResolvedValue(false);+ await request(f.app).post('/reset').send({ agentId: 'agent-a' }).expect(403);+ expect(f.storage.resetToolApprovalGrants).not.toHaveBeenCalled();+ f.canAccessAgent.mockResolvedValue(true);+ await request(f.app).post('/reset').send({ agentId: 'agent-a' }).expect(200);+});++test('targeted reset uses a verified current catalog alias without editing or saving the agent', async () => {+ const f = fixture({ id: 'viewer-a' });+ const agent = {+ id: 'agent-a',+ tool_options: { db_query_mcp_db: { approval_mode: 'chat' as const } },+ };+ f.getAgent.mockResolvedValue(agent);+ f.getMCPServerTools.mockResolvedValue(formatMCPServerTools('db', [{ name: 'db_query' }]));+ await request(f.app).post('/reset').send(reset).expect(200, { reset: true });+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith(+ 'viewer-a',+ 'agent-a',+ 'query_mcp_db',+ );+ expect(agent.tool_options).toEqual({ db_query_mcp_db: { approval_mode: 'chat' } });+ expect(f.getMCPServerTools).toHaveBeenCalledTimes(1);+});++test('a legacy request resets the canonical grant when current options already exist', async () => {+ const f = fixture({ id: 'viewer-a' });+ f.getMCPServerTools.mockResolvedValue(formatMCPServerTools('db', [{ name: 'db_query' }]));+ await request(f.app)+ .post('/reset')+ .send({ ...reset, toolName: 'db_query_mcp_db' })+ .expect(200);+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith(+ 'viewer-a',+ 'agent-a',+ 'query_mcp_db',+ );+});++test('a collision-preserved sibling never inherits another tool’s consent mode', async () => {+ const f = fixture({ id: 'viewer-a' });+ f.getAgent.mockResolvedValue({+ id: 'agent-a',+ tool_options: { db_query_mcp_db: { approval_mode: 'always' } },+ });+ f.getMCPServerTools.mockResolvedValue(+ formatMCPServerTools('db', [{ name: 'db_query' }, { name: 'query' }]),+ );+ await request(f.app).post('/reset').send(reset).expect(403);+ expect(f.storage.resetToolApprovalGrants).not.toHaveBeenCalled();+ await request(f.app)+ .post('/reset')+ .send({ ...reset, toolName: 'db_query_mcp_db' })+ .expect(200);+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith(+ 'viewer-a',+ 'agent-a',+ 'db_query_mcp_db',+ );+});++test('explicit current options override the legacy alias mode', async () => {+ const f = fixture({ id: 'viewer-a' });+ f.getAgent.mockResolvedValue({+ id: 'agent-a',+ tool_options: {+ db_query_mcp_db: { approval_mode: 'always' },+ query_mcp_db: { approval_mode: 'ask' },+ },+ });+ f.getMCPServerTools.mockResolvedValue(formatMCPServerTools('db', [{ name: 'db_query' }]));+ await request(f.app).post('/reset').send(reset).expect(403);+ expect(f.storage.resetToolApprovalGrants).not.toHaveBeenCalled();+});++test('raw server keys normalize only inside their exact configured boundary', async () => {+ const f = fixture({ id: 'viewer-a' });+ f.getMCPServerConfigs.mockResolvedValue({+ 'db ops': { type: 'streamable-http', url: 'https://mcp.example.test/mcp' },+ 'long_mcp_db ops': { type: 'streamable-http', url: 'https://other.example.test/mcp' },+ });+ f.getAgent.mockResolvedValue({+ id: 'agent-a',+ tool_options: {+ 'db_ops_query_mcp_db ops': { approval_mode: 'chat' },+ 'query_mcp_long_mcp_db ops': { approval_mode: 'always' },+ },+ });+ f.getMCPServerTools.mockResolvedValue(formatMCPServerTools('db ops', [{ name: 'db_ops_query' }]));+ await request(f.app)+ .post('/reset')+ .send({ ...reset, toolName: 'query_mcp_db_ops' })+ .expect(200);+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledWith(+ 'viewer-a',+ 'agent-a',+ 'query_mcp_db_ops',+ );+ expect(f.getMCPServerTools).toHaveBeenCalledWith('viewer-a', 'db ops', expect.any(Object));+});++test('a shadowed raw server cannot lend its options to the winning server', async () => {+ const f = fixture({ id: 'viewer-a' });+ f.getMCPServerConfigs.mockResolvedValue({+ 'db!': { type: 'streamable-http', url: 'https://shadow.example.test/mcp' },+ db_: { type: 'streamable-http', url: 'https://mcp.example.test/mcp' },+ });+ f.getAgent.mockResolvedValue({+ id: 'agent-a',+ tool_options: { 'db_query_mcp_db!': { approval_mode: 'always' } },+ });+ f.getMCPServerTools.mockResolvedValue(formatMCPServerTools('db_', [{ name: 'query' }]));+ await request(f.app)+ .post('/reset')+ .send({ ...reset, toolName: 'query_mcp_db_' })+ .expect(403);+ expect(f.storage.resetToolApprovalGrants).not.toHaveBeenCalled();+});++test('missing catalogs cannot authorize unverified aliases; operational failure stays sanitized', async () => {+ const f = fixture({ id: 'viewer-a' });+ f.getAgent.mockResolvedValue({+ id: 'agent-a',+ tool_options: { db_query_mcp_db: { approval_mode: 'always' } },+ });+ await request(f.app).post('/reset').send(reset).expect(403);+ await request(f.app)+ .post('/reset')+ .send({ ...reset, toolName: 'db_query_mcp_db' })+ .expect(200);+ f.getMCPServerTools.mockRejectedValue(new Error('secret-catalog-headers'));+ await request(f.app).post('/reset').send(reset).expect(503, { code: 'APPROVAL_RESET_FAILED' });+ expect(f.storage.resetToolApprovalGrants).toHaveBeenCalledTimes(1);+});++test('agent-wide and inaccessible resets do not load MCP catalogs', async () => {+ const f = fixture({ id: 'viewer-a' });+ await request(f.app).post('/reset').send({ agentId: 'agent-a' }).expect(200);+ f.canAccessAgent.mockResolvedValue(false);+ await request(f.app).post('/reset').send(reset).expect(403);+ expect(f.getMCPServerConfigs).not.toHaveBeenCalled();+ expect(f.getMCPServerTools).not.toHaveBeenCalled();+});diff --git a/packages/api/src/agents/hitl/controller.ts b/packages/api/src/agents/hitl/controller.tsnew file mode 100644index 0000000000..02198c073a--- /dev/null+++ b/packages/api/src/agents/hitl/controller.ts@@ -0,0 +1,137 @@+import { z } from 'zod';+import { logger, ResourceCapabilityMap } from '@librechat/data-schemas';+import {+ Constants,+ ResourceType,+ splitMCPToolKey,+ normalizeServerName,+ buildServerNameAliases,+} from 'librechat-data-provider';+import type { ToolApprovalGrantStorage, Agent } from 'librechat-data-provider';+import type { Request, Response } from 'express';+import type { HasCapabilityFn } from '~/middleware/capabilities';+import type { MCPServerTools } from '~/tools/definitions';+import type { ParsedServerConfig } from '~/mcp/types';+import { collectMCPToolAliases, aliasMCPToolOptions } from '~/tools/classification';++const resetSchema = z+ .object({ agentId: z.string().min(1).max(256), toolName: z.string().min(1).max(256).optional() })+ .strict();++interface ResetDependencies {+ storage: ToolApprovalGrantStorage;+ hasCapability?: HasCapabilityFn;+ getMCPServerConfigs?: (+ userId: string,+ user: { id: string; role?: string },+ ) => Promise<Record<string, ParsedServerConfig>>;+ getMCPServerTools?: (+ userId: string,+ serverName: string,+ config: ParsedServerConfig,+ ) => Promise<MCPServerTools | null>;+ getAgent: (filter: {+ id: string;+ }) => Promise<Pick<Agent, 'id' | 'tool_options'> | null | undefined>;+ canAccessAgent: (+ agent: Pick<Agent, 'id' | 'tool_options'>,+ user: { id: string; role?: string },+ ) => Promise<boolean>;+}++export function createResetToolApprovalController({+ storage,+ hasCapability,+ getMCPServerConfigs,+ getMCPServerTools,+ getAgent,+ canAccessAgent,+}: ResetDependencies): (+ req: Request & { user?: { id: string; role?: string } },+ res: Response,+) => Promise<void> {+ return async (+ req: Request & { user?: { id: string; role?: string } },+ res: Response,+ ): Promise<void> => {+ if (!req.user?.id) {+ res.status(401).json({ code: 'UNAUTHORIZED' });+ return;+ }+ const parsed = resetSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ code: 'INVALID_APPROVAL_RESET' });+ return;+ }+ try {+ const { agentId, toolName } = parsed.data;+ const agent = await getAgent({ id: agentId });+ if (!agent) {+ res.status(403).json({ code: 'APPROVAL_RESET_FORBIDDEN' });+ return;+ }+ let managesAgents = false;+ const capability = ResourceCapabilityMap[ResourceType.AGENT];+ try {+ managesAgents =+ capability != null &&+ req.user.role != null &&+ (await hasCapability?.({ ...req.user, role: req.user.role }, capability)) === true;+ } catch {+ logger.warn('[Tool approvals] Capability lookup failed; checking resource access.');+ }+ if (!managesAgents && !(await canAccessAgent(agent, req.user))) {+ res.status(403).json({ code: 'APPROVAL_RESET_FORBIDDEN' });+ return;+ }+ let resetToolName = toolName;+ let options = agent.tool_options;+ if (toolName != null && getMCPServerConfigs && getMCPServerTools) {+ const configs = await getMCPServerConfigs(req.user.id, req.user);+ const names = Object.keys(configs);+ const serverAliases = buildServerNameAliases(names);+ const boundaries = [...names, ...serverAliases.keys()];+ const [toolPart, parsedServer] = splitMCPToolKey(toolName, boundaries);+ const serverName =+ parsedServer == null ? undefined : (serverAliases.get(parsedServer) ?? parsedServer);+ if (serverName && serverAliases.get(normalizeServerName(serverName)) === serverName) {+ const catalog = await getMCPServerTools(req.user.id, serverName, configs[serverName]);+ if (catalog) {+ const suffix = `${Constants.mcp_delimiter}${normalizeServerName(serverName)}`;+ const aliases = collectMCPToolAliases(+ Object.entries(catalog)+ .filter(([, entry]) => entry.function != null)+ .map(([name, entry]) => ({+ name,+ serverName,+ serverToolName: entry.serverToolName,+ })),+ );+ const requested = `${toolPart}${suffix}`;+ resetToolName = catalog[requested]?.function+ ? requested+ : (aliases.find(({ aliasName }) => aliasName === requested)?.name ?? toolName);+ // Match the editor's unsaved migration. Explicit current options win.+ options = { ...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;+ const normalized = `${part}${suffix}`;+ if (options[normalized] == null) options[normalized] = value;+ }+ aliasMCPToolOptions(aliases, options);+ }+ }+ }+ const mode = resetToolName == null ? undefined : options?.[resetToolName]?.approval_mode;+ if (resetToolName != null && mode !== 'chat' && mode !== 'always') {+ res.status(403).json({ code: 'APPROVAL_RESET_FORBIDDEN' });+ return;+ }+ await storage.resetToolApprovalGrants(req.user.id, agentId, resetToolName);+ res.status(200).json({ reset: true });+ } catch {+ res.status(503).json({ code: 'APPROVAL_RESET_FAILED' });+ }+ };+}diff --git a/packages/api/src/agents/hitl/hooks.ts b/packages/api/src/agents/hitl/hooks.tsindex dc59296d0b..9d49965866 100644--- a/packages/api/src/agents/hitl/hooks.ts+++ b/packages/api/src/agents/hitl/hooks.ts@@ -49,6 +49,8 @@ export interface ResolvedToolApprovalHook {matcher?: string;/** Optional admission-only scope for hooks that inspect the executing agent at runtime. */agentIds?: ReadonlySet<string>;+ /** Complete set of tool names this hook can ask about; omission means unresolved. */+ toolNames?: readonly string[];}interface RegisteredHook {diff --git a/packages/api/src/agents/hitl/index.ts b/packages/api/src/agents/hitl/index.tsindex 2b53e1c1b5..2d2e5902d7 100644--- a/packages/api/src/agents/hitl/index.ts+++ b/packages/api/src/agents/hitl/index.ts@@ -11,3 +11,6 @@ export * from './hookLoader';export * from './askUserQuestionTool';export * from './answers';export * from './byom';+export * from './modes';+export * from './controller';+export * from './metadata';diff --git a/packages/api/src/agents/hitl/metadata.spec.ts b/packages/api/src/agents/hitl/metadata.spec.tsnew file mode 100644index 0000000000..7a20577d25--- /dev/null+++ b/packages/api/src/agents/hitl/metadata.spec.ts@@ -0,0 +1,138 @@+import {+ bindToolApprovalIdentity,+ getToolApprovalBinding,+ getToolApprovalIdentity,+ getToolApprovalAuthKind,+ getToolApprovalName,+ getToolReviewAuthority,+} from '~/tools/approval';+import { buildMCPToolReviewAuthority } from '~/mcp/approval';+import { createMCPToolApprovalMetadata } from './metadata';+import { buildMCPToolApprovalBinding } from './modes';+import { createSafeUser } from '~/utils/env';++const config = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test',+ requiresOAuth: false,+};+const parameters = { type: 'object', properties: { text: { type: 'string' } } };+const user = {+ id: 'user-a',+ role: 'USER',+ openidId: 'subject-a',+ password: 'synthetic-not-authority',+};++for (const auth of ['oauth', 'other', 'runtime'] as const) {+ test(`${auth} metadata is identical across runtime and definitions loading`, () => {+ const selected =+ auth === 'runtime'+ ? {+ ...config,+ requiresOAuth: undefined,+ url: 'https://mcp.example.test/{{LIBRECHAT_USER_ID}}',+ }+ : { ...config, requiresOAuth: auth === 'oauth' };+ const input = { serverName: 'db', config: selected, user };+ const metadata = createMCPToolApprovalMetadata();+ metadata.capture(input);+ const definition = bindToolApprovalIdentity(+ { name: 'query_mcp_db', serverName: 'db', parameters },+ 'db_query',+ parameters,+ );+ metadata.attach([definition]);+ const instance = metadata.bindInstance(+ { name: 'db_query_mcp_db' },+ { ...input, upstreamName: 'db_query', currentToolName: 'query', parameters },+ );+ expect(getToolApprovalBinding(instance)).toBe(getToolApprovalBinding(definition));+ expect(getToolReviewAuthority(instance)).toBe(getToolReviewAuthority(definition));+ expect(getToolApprovalIdentity(instance)).toBe(getToolApprovalIdentity(definition));+ expect(getToolApprovalAuthKind(instance)).toBe(auth === 'runtime' ? undefined : auth);+ expect(getToolApprovalAuthKind(definition)).toBe(getToolApprovalAuthKind(instance));+ expect(getToolApprovalName(instance)).toBe('query_mcp_db');+ expect(getToolApprovalBinding(instance)).toBe(buildMCPToolApprovalBinding('db', selected));+ expect(getToolReviewAuthority(instance)).toBe(+ buildMCPToolReviewAuthority({ ...input, user: createSafeUser(user) }),+ );+ expect(JSON.parse(JSON.stringify(instance))).toEqual({ name: 'db_query_mcp_db' });+ });+}++test('metadata capture is request-local and refreshes effective authority without changing definitions', () => {+ const first = createMCPToolApprovalMetadata();+ const second = createMCPToolApprovalMetadata();+ first.capture({ serverName: 'db', config });+ const a = { name: 'query_mcp_db', serverName: 'db' };+ const b = { ...a };+ first.attach([a]);+ second.attach([b]);+ expect(getToolApprovalBinding(a)).toEqual(expect.any(String));+ expect(getToolApprovalBinding(b)).toBeUndefined();+ const before = getToolApprovalBinding(a);+ first.capture({ serverName: 'db', config: { ...config, url: 'https://changed.example.test' } });+ const changed = { ...b };+ first.attach([changed]);+ expect(getToolApprovalBinding(changed)).not.toBe(before);+ expect(getToolApprovalBinding(a)).toBe(before);+});++test('review-only metadata pins resolved routes, preserves raw identity, and excludes unrelated user secrets', () => {+ const selected = { ...config, headers: { 'X-Workspace': '{{WORKSPACE}}' } };+ const metadata = createMCPToolApprovalMetadata();+ const build = (WORKSPACE: string, password = user.password, upstreamName = 'query') => {+ const principal = { ...user, password };+ return metadata.bindInstance(+ { name: 'query_mcp_db' },+ {+ serverName: 'db',+ config: selected,+ user: principal,+ customUserVars: { WORKSPACE },+ upstreamName,+ parameters,+ },+ );+ };+ const a = build('a');+ const b = build('b');+ expect(getToolApprovalBinding(a)).toBeUndefined();+ expect(getToolReviewAuthority(a)).toEqual(expect.any(String));+ expect(getToolReviewAuthority(b)).not.toBe(getToolReviewAuthority(a));+ expect(getToolReviewAuthority(build('a', 'different-synthetic-password'))).toBe(+ getToolReviewAuthority(a),+ );+ expect(getToolApprovalIdentity(build('a', undefined, 'other_query'))).not.toBe(+ getToolApprovalIdentity(a),+ );+});++test('identity uses normalized upstream schema and raw server names retain canonical key spelling', () => {+ const metadata = createMCPToolApprovalMetadata();+ const schema = { $ref: '#/definitions/Args', definitions: { Args: parameters } };+ const actual = metadata.bindInstance(+ { name: 'raw_mcp_db_ops' },+ {+ serverName: 'db ops',+ config,+ currentToolName: 'query',+ upstreamName: 'db_ops_query',+ parameters: schema,+ },+ );+ const normalized = metadata.bindInstance(+ { name: 'raw_mcp_db_ops' },+ {+ serverName: 'db ops',+ config,+ currentToolName: 'query',+ upstreamName: 'db_ops_query',+ parameters,+ },+ );+ expect(getToolApprovalName(actual)).toBe('query_mcp_db_ops');+ expect(getToolApprovalIdentity(actual)).toBe(getToolApprovalIdentity(normalized));+});diff --git a/packages/api/src/agents/hitl/metadata.ts b/packages/api/src/agents/hitl/metadata.tsnew file mode 100644index 0000000000..9d0a81f435--- /dev/null+++ b/packages/api/src/agents/hitl/metadata.ts@@ -0,0 +1,75 @@+import { Constants, normalizeServerName } from 'librechat-data-provider';+import type { ToolApprovalAuthKind } from 'librechat-data-provider';+import type { MCPToolReviewAuthorityInput } from '~/mcp/approval';+import type { AgentApprovalDefinition } from './modes';+import { buildMCPToolReviewAuthority, getMCPToolApprovalAuthKind } from '~/mcp/approval';+import { buildMCPToolApprovalBinding, attachMCPToolApprovalBindings } from './modes';+import { bindToolApproval, bindToolApprovalIdentity } from '~/tools/approval';+import { normalizeJsonSchema, resolveJsonSchemaRefs } from '~/mcp/zod';+import { createSafeUser } from '~/utils/env';++interface MetadataInput extends Omit<MCPToolReviewAuthorityInput, 'user'> {+ user?: Parameters<typeof createSafeUser>[0];+}+interface InstanceMetadataInput extends MetadataInput {+ upstreamName: string;+ currentToolName?: string;+ parameters?: Record<string, unknown>;+ description?: string;+}+interface ApprovalMetadata {+ binding?: string;+ authority?: string;+ authKind?: ToolApprovalAuthKind;+}+export interface MCPToolApprovalMetadata {+ capture: (input: MetadataInput) => void;+ attach: (definitions: AgentApprovalDefinition[]) => void;+ bindInstance: <T extends AgentApprovalDefinition>(tool: T, input: InstanceMetadataInput) => T;+}++/** One request-local owner for runtime and definitions-only approval provenance. */+export function createMCPToolApprovalMetadata(): MCPToolApprovalMetadata {+ const bindings = new Map<string, string | undefined>();+ const authorities = new Map<string, string | undefined>();+ const authKinds = new Map<string, ToolApprovalAuthKind | undefined>();+ const project = (input: MetadataInput): ApprovalMetadata => ({+ binding: buildMCPToolApprovalBinding(input.serverName, input.config),+ authority: buildMCPToolReviewAuthority({ ...input, user: createSafeUser(input.user) }),+ authKind: getMCPToolApprovalAuthKind(input.config),+ });+ return {+ capture(input) {+ const metadata = project(input);+ bindings.set(input.serverName, metadata.binding);+ authorities.set(input.serverName, metadata.authority);+ authKinds.set(input.serverName, metadata.authKind);+ },+ attach(definitions) {+ attachMCPToolApprovalBindings(definitions, bindings, authorities, authKinds);+ },+ bindInstance(tool, input) {+ const metadata = project(input);+ const canonicalName =+ input.currentToolName == null+ ? tool.name+ : `${input.currentToolName}${Constants.mcp_delimiter}${normalizeServerName(input.serverName)}`;+ bindToolApproval(+ tool,+ metadata.binding,+ canonicalName,+ undefined,+ metadata.authority,+ metadata.authKind,+ );+ return bindToolApprovalIdentity(+ tool,+ input.upstreamName,+ normalizeJsonSchema(+ resolveJsonSchemaRefs(input.parameters ?? { type: 'object', properties: {} }),+ ),+ input.description || undefined,+ );+ },+ };+}diff --git a/packages/api/src/agents/hitl/modes.integration.spec.ts b/packages/api/src/agents/hitl/modes.integration.spec.tsnew file mode 100644index 0000000000..9a70756d09--- /dev/null+++ b/packages/api/src/agents/hitl/modes.integration.spec.ts@@ -0,0 +1,2478 @@+import { z } from 'zod';+import express from 'express';+import request from 'supertest';+import mongoose from 'mongoose';+import { MemorySaver } from '@langchain/langgraph';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { Run, Providers, FakeChatModel } from '@librechat/agents';+import { HumanMessage } from '@librechat/agents/langchain/messages';+import { createModels, createMethods } from '@librechat/data-schemas';+import type { ToolApprovalGrantStorage, Agents } from 'librechat-data-provider';+import type { AgentApprovalSource, ReviewedToolApprovals, AgentToolApprovalSession } from './modes';+import type { ToolApprovalHook } from './hooks';+import {+ createAgentToolApprovalSession,+ bindRunToolApprovalSession,+ captureRunToolApprovalBindings,+ buildMCPToolApprovalBinding,+ describeRememberedToolApprovals,+ resolveAgentToolGrantBinding,+} from './modes';+import { ServerConfigsCacheInMemory } from '~/mcp/registry/cache/ServerConfigsCacheInMemory';+import { buildHITLRunWiring, buildToolApprovalExecutionConfig } from './runtime';+import { bindToolApproval, bindToolApprovalIdentity } from '~/tools/approval';+import { assertToolApprovalTransportEpoch } from '~/tools/approval';+import { createResetToolApprovalController } from './controller';+import { buildMCPToolReviewAuthority } from '~/mcp/approval';+import { getMCPToolApprovalAuthKind } from '~/mcp/approval';+import { bindToolReviewAuthority } from '~/tools/approval';+import { createToolExecuteHandler } from '../handlers';+import { createMCPStructuredTool } from '~/mcp/tools';+import { markMCPToolResultError } from '~/mcp/status';+import { formatMCPServerTools } from '~/mcp/tools';+import { formatToolContent } from '~/mcp/parsers';++let mongo: MongoMemoryServer;+let storage: ToolApprovalGrantStorage;+let executions = 0;+let protocolError = false;+const name = 'echo_mcp_fixture';+const fixtureSchema = z.object({ text: z.string() });+function createProbe(+ binding: string | null = 'source-one',+ upstreamName = 'echo',+ reviewAuthority?: string,+ beforeSend?: () => Promise<void>,+) {+ const probe = Object.assign(+ createMCPStructuredTool(+ async (input) => {+ const { text } = z.object({ text: z.string() }).parse(input);+ await beforeSend?.();+ executions++;+ const raw = { content: [{ type: 'text' as const, text }], isError: protocolError };+ return markMCPToolResultError(formatToolContent(raw, 'openai'), raw.isError);+ },+ {+ name,+ description: 'Scripted SDK integration tool',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ );+ return bindToolApprovalIdentity(+ bindToolReviewAuthority(bindToolApproval(probe, binding ?? undefined), reviewAuthority),+ upstreamName,+ {+ type: 'object',+ },+ );+}+const guarded = createProbe();+function definition() {+ return bindToolApprovalIdentity(+ bindToolApproval({ name, serverName: 'fixture', parameters: { type: 'object' } }, 'source-one'),+ 'echo',+ { type: 'object' },+ );+}++beforeAll(async () => {+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await mongoose.models.ToolApprovalGrant.syncIndexes();+ storage = createMethods(mongoose);+}, 60000);+afterAll(async () => {+ await mongoose.disconnect();+ await mongo?.stop();+});+beforeEach(async () => {+ executions = 0;+ protocolError = false;+ await mongoose.models.ToolApprovalGrant.deleteMany({});+});++async function build({+ source,+ chat,+ saver,+ reviewed,+ callId,+ eventDriven = false,+ executionTool = guarded,+ beforeLoad,+ sharedSession,+ rewrite,+ sessionAgents,+ background = false,+ reviewHook,+ beforeExecution,+}: {+ source: AgentApprovalSource;+ chat: string;+ saver: MemorySaver;+ reviewed?: ReviewedToolApprovals;+ callId?: string;+ eventDriven?: boolean;+ executionTool?: typeof guarded;+ beforeLoad?: () => void | Promise<void>;+ sharedSession?: AgentToolApprovalSession;+ rewrite?: { text: string; run_in_background?: boolean };+ sessionAgents?: AgentApprovalSource[];+ background?: boolean;+ reviewHook?: ToolApprovalHook;+ beforeExecution?: () => Promise<void>;+}) {+ const session =+ sharedSession ??+ createAgentToolApprovalSession({+ agents: sessionAgents ?? [source],+ storage,+ scope: { userId: '652000000000000000000001', conversationId: chat },+ reviewed,+ });+ const wiring = buildHITLRunWiring(+ { enabled: true, mode: 'bypass' },+ {},+ [],+ [+ { hook: session.hook },+ ...(reviewHook ? [{ hook: reviewHook }] : []),+ ...(rewrite ? [{ hook: () => ({ updatedInput: rewrite }) }] : []),+ ],+ )!;+ wiring.hooks.register('PostToolUse', { hooks: [session.rememberHook] });+ wiring.hooks.register('PostToolBatch', { hooks: [session.settleBatchHook] });+ const llmConfig = {+ provider: Providers.OPENAI,+ model: 'gpt-4o-mini',+ apiKey: 'test-placeholder',+ streaming: true,+ streamUsage: false,+ };+ const run = await Run.create({+ runId: `run-${chat}`,+ graphConfig: {+ type: 'standard',+ llmConfig,+ agents: [+ {+ agentId: source.id,+ provider: Providers.OPENAI,+ endpoint: Providers.OPENAI,+ clientOptions: llmConfig,+ instructions: 'Use the scripted tool.',+ tools: eventDriven ? [] : [executionTool],+ toolDefinitions: eventDriven+ ? source.toolDefinitions?.map((definition) => ({+ name: definition.name,+ description: definition.description,+ parameters: {+ type: 'object' as const,+ properties: { text: { type: 'string' as const } },+ },+ }))+ : undefined,+ },+ ],+ compileOptions: { checkpointer: saver },+ },+ returnContent: true,+ customHandlers: {+ on_tool_execute: createToolExecuteHandler({+ loadTools: async () => {+ await beforeLoad?.();+ return {+ loadedTools: [executionTool],+ ...(background && {+ configurable: { backgroundToolNames: [name] },+ }),+ };+ },+ }),+ },+ tokenCounter: (text) => String(text ?? '').length,+ indexTokenCountMap: {},+ humanInTheLoop: wiring.humanInTheLoop,+ hooks: wiring.hooks,+ });+ if (!run.Graph) throw new Error('The test run did not initialize its graph.');+ run.Graph.overrideModel = new FakeChatModel({+ responses: ['Done.'],+ ...(callId+ ? { toolCalls: [{ name, args: { text: 'hello' }, id: callId, type: 'tool_call' }] }+ : {}),+ });+ bindRunToolApprovalSession(+ run,+ beforeExecution+ ? {+ ...session,+ validateExecution: async (tool, invocation) => {+ await beforeExecution();+ return session.validateExecution(tool, invocation);+ },+ }+ : session,+ );+ return run;+}+const config = (chat: string) => ({+ configurable: {+ thread_id: chat,+ user_id: '652000000000000000000001',+ ...buildToolApprovalExecutionConfig(`response-${chat}`, 1),+ },+ streamMode: 'values' as const,+ version: 'v2' as const,+});++test.each([+ ['chat', false],+ ['always', false],+ ['chat', true],+ ['always', true],+] as const)(+ '%s mode learns only after a real reviewed execution (event-driven: %s)',+ async (mode, eventDriven) => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: { approval_mode: mode, approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05' },+ },+ toolDefinitions: [definition()],+ };+ const saver = new MemorySaver();+ const first = await build({ source, chat: 'chat-a', saver, eventDriven, callId: 'first-call' });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('chat-a'));+ const interrupt = first.getInterrupt();+ expect(interrupt?.payload.type).toBe('tool_approval');+ expect(executions).toBe(0);+ const bindings = captureRunToolApprovalBindings(+ first,+ interrupt!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ expect(bindings['first-call']?.agentId).toBe(source.id);+ const resumed = await build({+ source,+ chat: 'chat-a',+ saver,+ eventDriven,+ reviewed: { bindings, decisions: [{ tool_call_id: 'first-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'first-call': { type: 'approve' } }, config('chat-a'));+ expect(executions).toBe(1);+ expect(+ await mongoose.models.ToolApprovalGrant.countDocuments({+ binding: bindings['first-call'].binding,+ }),+ ).toBe(1);+ const next = await build({+ source,+ chat: 'chat-b',+ saver: new MemorySaver(),+ eventDriven,+ callId: 'next-call',+ });+ await next.processStream({ messages: [new HumanMessage('run')] }, config('chat-b'));+ if (mode === 'chat') {+ expect(next.getInterrupt()?.payload.type).toBe('tool_approval');+ expect(executions).toBe(1);+ } else {+ expect(next.getInterrupt()).toBeUndefined();+ expect(executions).toBe(2);+ }+ },+ 30000,+);++test.each([false, true])(+ 'a protocol-valid MCP error never teaches approval (event-driven: %s)',+ async (eventDriven) => {+ protocolError = true;+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'error-chat',+ saver,+ eventDriven,+ callId: 'failed-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('error-chat'));+ const interrupt = first.getInterrupt()!;+ const bindings = captureRunToolApprovalBindings(+ first,+ interrupt.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const resumed = await build({+ source,+ chat: 'error-chat',+ saver,+ eventDriven,+ reviewed: { bindings, decisions: [{ tool_call_id: 'failed-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'failed-call': { type: 'approve' } }, config('error-chat'));+ expect(executions).toBe(1);+ const toolMessages = (resumed.getRunMessages() ?? []).filter(+ (message) => message._getType() === 'tool',+ );+ expect(JSON.stringify(toolMessages.map((message) => message.content))).toContain('hello');+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ const next = await build({+ source,+ chat: 'retry-chat',+ saver: new MemorySaver(),+ eventDriven,+ callId: 'retry-call',+ });+ await next.processStream({ messages: [new HumanMessage('retry')] }, config('retry-chat'));+ expect(next.getInterrupt()?.payload.type).toBe('tool_approval');+ expect(executions).toBe(1);+ },+ 30000,+);++test.each([false, true])(+ 'a manually approved call cannot execute against a replaced target (event-driven: %s)',+ async (eventDriven) => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'rebind-chat',+ saver,+ eventDriven,+ callId: 'first-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('rebind-chat'));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const resumed = await build({+ source,+ chat: 'rebind-chat',+ saver,+ eventDriven,+ executionTool: createProbe('source-two'),+ reviewed: { bindings, decisions: [{ tool_call_id: 'first-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'first-call': { type: 'approve' } }, config('rebind-chat'));+ expect(executions).toBe(0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+);++test.each(['authority', 'upstream', 'revocation'] as const)(+ 'automatic consent rejects a changed %s after initialization and before event dispatch',+ async (change) => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const seed = await build({+ source,+ chat: 'seed-chat',+ saver: new MemorySaver(),+ eventDriven: true,+ callId: 'seed-call',+ });+ await seed.processStream({ messages: [new HumanMessage('run')] }, config('seed-chat'));+ const bindings = captureRunToolApprovalBindings(+ seed,+ seed.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ await storage.rememberToolApprovalGrants(+ { userId: '652000000000000000000001', conversationId: 'seed-chat' },+ [bindings['seed-call']],+ );+ let reset: Promise<void> | undefined;+ let target = guarded;+ if (change === 'authority') target = createProbe('source-two');+ if (change === 'upstream') target = createProbe('source-one', 'fixture_echo');+ const run = await build({+ source,+ chat: 'auto-chat',+ saver: new MemorySaver(),+ eventDriven: true,+ callId: 'auto-call',+ executionTool: target,+ beforeLoad:+ change === 'revocation'+ ? () => {+ reset = storage.resetToolApprovalGrants('652000000000000000000001', source.id, name);+ return reset;+ }+ : undefined,+ });+ await run.processStream({ messages: [new HumanMessage('run')] }, config('auto-chat'));+ await reset;+ expect(executions).toBe(0);+ },+);++test.each([false, true])(+ 'editing a reviewed call can execute once but never teaches approval (event-driven: %s)',+ async (eventDriven) => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'edit-chat',+ saver,+ eventDriven,+ callId: 'edit-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('edit-chat'));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const resumed = await build({+ source,+ chat: 'edit-chat',+ saver,+ eventDriven,+ reviewed: {+ bindings,+ decisions: [+ { tool_call_id: 'edit-call', decision: 'edit', editedArguments: { text: 'edited' } },+ ],+ },+ });+ await resumed.resume(+ { 'edit-call': { type: 'edit', updatedInput: { text: 'edited' } } },+ config('edit-chat'),+ );+ expect(executions).toBe(1);+ expect(+ JSON.stringify((resumed.getRunMessages() ?? []).map((message) => message.content)),+ ).toContain('edited');+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+);++test.each([false, true])(+ 'always-ask still permits an exact manually approved call (event-driven: %s)',+ async (eventDriven) => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: { [name]: { approval_mode: 'ask' } },+ toolDefinitions: [definition()],+ };+ const saver = new MemorySaver();+ const first = await build({ source, chat: 'ask-chat', saver, eventDriven, callId: 'ask-call' });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('ask-chat'));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const resumed = await build({+ source,+ chat: 'ask-chat',+ saver,+ eventDriven,+ reviewed: { bindings, decisions: [{ tool_call_id: 'ask-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'ask-call': { type: 'approve' } }, config('ask-chat'));+ expect(executions).toBe(1);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+);++test.each([+ ['chat', false, 'approve'],+ ['chat', true, 'approve'],+ ['always', false, 'approve'],+ ['always', true, 'approve'],+ ['chat', false, 'edit'],+ ['chat', true, 'edit'],+ ['always', false, 'edit'],+ ['always', true, 'edit'],+] as const)(+ 'templated %s connections permit one reviewed call (event-driven: %s, decision: %s)',+ async (mode, eventDriven, decision) => {+ const connection = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/mcp',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ expect(buildMCPToolApprovalBinding('fixture', connection)).toBeUndefined();+ const authority = buildMCPToolReviewAuthority({ serverName: 'fixture', config: connection });+ const templatedDefinition = bindToolApprovalIdentity(+ bindToolReviewAuthority(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ authority,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: { approval_mode: mode, approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05' },+ },+ toolDefinitions: [templatedDefinition],+ };+ const saver = new MemorySaver();+ const executionTool = createProbe(null, 'echo', authority);+ const first = await build({+ source,+ chat: 'template-chat',+ saver,+ eventDriven,+ executionTool,+ callId: 'template-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('template-chat'));+ const payload = first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload;+ const bindings = captureRunToolApprovalBindings(first, payload)!;+ const described = describeRememberedToolApprovals(+ payload,+ bindings,+ first,+ ) as Agents.ToolApprovalInterruptPayload;+ expect(described.review_configs[0].remember_scope).toBeUndefined();+ expect(described.review_configs[0].remember_unavailable).toBe('connection');+ const resumed = await build({+ source,+ chat: 'template-chat',+ saver,+ eventDriven,+ executionTool,+ reviewed: {+ bindings,+ decisions: [+ {+ tool_call_id: 'template-call',+ decision,+ ...(decision === 'edit' && { editedArguments: { text: 'edited-template' } }),+ },+ ],+ },+ });+ const answer =+ decision === 'edit'+ ? { type: 'edit' as const, updatedInput: { text: 'edited-template' } }+ : { type: 'approve' as const };+ await resumed.resume({ 'template-call': answer }, config('template-chat'));+ expect(executions).toBe(1);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ const again = await build({+ source,+ chat: 'template-chat',+ saver: new MemorySaver(),+ eventDriven,+ executionTool,+ callId: 'next-template-call',+ });+ await again.processStream(+ { messages: [new HumanMessage('run again')] },+ config('template-chat'),+ );+ expect(again.getInterrupt()?.payload.type).toBe('tool_approval');+ expect(executions).toBe(1);+ },+);++test.each(['allow', 'chat', 'always'] as const)(+ 'concurrent SDK agents can reuse call_0 under %s mode',+ async (mode) => {+ const sources: AgentApprovalSource[] = ['agent-a', 'agent-b'].map((id) => ({+ id,+ tool_options: {+ [name]: { approval_mode: mode, approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05' },+ },+ toolDefinitions: [definition()],+ }));+ const chat = 'parallel-chat';+ const scope = { userId: '652000000000000000000001', conversationId: chat };+ if (mode !== 'allow')+ await storage.rememberToolApprovalGrants(+ scope,+ sources.map((source) => resolveAgentToolGrantBinding(source, name, scope)!),+ );+ const sharedSession = createAgentToolApprovalSession({ agents: sources, storage, scope });+ const runs = await Promise.all(+ sources.map((source) =>+ build({+ source,+ chat,+ saver: new MemorySaver(),+ eventDriven: true,+ callId: 'call_0',+ sharedSession,+ }),+ ),+ );+ await Promise.all(+ runs.map((run) => run.processStream({ messages: [new HumanMessage('run')] }, config(chat))),+ );+ expect(executions).toBe(2);+ for (const run of runs) expect(run.getInterrupt()).toBeUndefined();+ },+);++const rewriteCases = (['ask', 'chat', 'always'] as const).flatMap((mode) =>+ [false, true].flatMap((eventDriven) =>+ (['approve', 'edit'] as const).flatMap((decision) =>+ [1, 2].map((ownerCount) => ({ mode, eventDriven, decision, ownerCount })),+ ),+ ),+);++test.each(rewriteCases)(+ 'hook-rewritten $mode/$decision calls retain review with $ownerCount owners (event-driven: $eventDriven)',+ async ({ mode, eventDriven, decision, ownerCount }) => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const sessionAgents = ownerCount === 2 ? [source, { ...source, id: 'agent-b' }] : [source];+ const rewrite = { text: 'sanitized-by-hook' };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'rewrite-chat',+ saver,+ eventDriven,+ sessionAgents,+ rewrite,+ callId: 'rewrite-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('rewrite-chat'));+ const payload = first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload;+ expect(payload.action_requests[0].arguments).toEqual(rewrite);+ const bindings = captureRunToolApprovalBindings(first, payload)!;+ expect(bindings['rewrite-call']?.agentId).toBe(source.id);+ const editedArguments = { text: 'edited-after-review' };+ const resumed = await build({+ source,+ chat: 'rewrite-chat',+ saver,+ eventDriven,+ sessionAgents,+ rewrite,+ reviewed: {+ bindings,+ decisions: [+ {+ tool_call_id: 'rewrite-call',+ decision,+ ...(decision === 'edit' && { editedArguments }),+ },+ ],+ },+ });+ const answer =+ decision === 'edit'+ ? { type: 'edit' as const, updatedInput: editedArguments }+ : { type: 'approve' as const };+ await resumed.resume({ 'rewrite-call': answer }, config('rewrite-chat'));+ expect(executions).toBe(1);+ const output = JSON.stringify(+ (resumed.getRunMessages() ?? [])+ .filter((message) => message._getType() === 'tool')+ .map((message) => message.content),+ );+ expect(output).toContain(decision === 'edit' ? editedArguments.text : rewrite.text);+ const canLearn = decision === 'approve' && mode !== 'ask';+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(canLearn ? 1 : 0);+ },+);++test.each([false, true])(+ 'templated review refuses a changed declared endpoint before resume (event-driven: %s)',+ async (eventDriven) => {+ const configA = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://a.example.test/mcp',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ const configB = { ...configA, url: 'https://b.example.test/mcp' };+ const authorityA = buildMCPToolReviewAuthority({ serverName: 'fixture', config: configA });+ const authorityB = buildMCPToolReviewAuthority({ serverName: 'fixture', config: configB });+ const targetDefinition = (authority?: string) =>+ bindToolApprovalIdentity(+ bindToolReviewAuthority(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ authority,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'chat',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [targetDefinition(authorityA)],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'authority-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', authorityA),+ callId: 'authority-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('authority-chat'));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const changed = { ...source, toolDefinitions: [targetDefinition(authorityB)] };+ const resumed = await build({+ source: changed,+ chat: 'authority-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', authorityB),+ reviewed: { bindings, decisions: [{ tool_call_id: 'authority-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'authority-call': { type: 'approve' } }, config('authority-chat'));+ expect(executions).toBe(0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+);++test.each(['ask', 'chat', 'always'] as const)(+ 'completed agents do not shadow later %s reviews with reused call IDs',+ async (mode) => {+ const sources: AgentApprovalSource[] = [+ {+ id: 'agent-a',+ tool_options: { [name]: { approval_mode: 'allow' } },+ toolDefinitions: [definition()],+ },+ {+ id: 'agent-b',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ },+ ];+ const chat = 'serial-owner-chat';+ const sharedSession = createAgentToolApprovalSession({+ agents: sources,+ storage,+ scope: { userId: '652000000000000000000001', conversationId: chat },+ });+ const a = await build({+ source: sources[0],+ chat,+ saver: new MemorySaver(),+ eventDriven: true,+ sharedSession,+ callId: 'call_0',+ });+ await a.processStream({ messages: [new HumanMessage('run A')] }, config(chat));+ expect(executions).toBe(1);+ const saver = new MemorySaver();+ const b = await build({+ source: sources[1],+ chat,+ saver,+ eventDriven: true,+ sharedSession,+ callId: 'call_0',+ });+ await b.processStream({ messages: [new HumanMessage('run B')] }, config(chat));+ const bindings = captureRunToolApprovalBindings(+ b,+ b.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ expect(bindings.call_0?.agentId).toBe('agent-b');+ const resumed = await build({+ source: sources[1],+ chat,+ saver,+ eventDriven: true,+ sessionAgents: sources,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call_0', decision: 'approve' }] },+ });+ await resumed.resume({ call_0: { type: 'approve' } }, config(chat));+ expect(executions).toBe(2);+ },+);++test('hook-rewritten background launch never teaches approval before the detached failure', async () => {+ let release!: () => void;+ let markStarted!: () => void;+ let markFailed!: () => void;+ const started = new Promise<void>((resolve) => {+ markStarted = resolve;+ });+ const failed = new Promise<void>((resolve) => {+ markFailed = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const delayed = Object.assign(+ createMCPStructuredTool(+ async () => {+ executions++;+ markStarted();+ await gate;+ markFailed();+ throw new Error('Scripted detached failure');+ },+ {+ name,+ description: 'Detached fixture',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ );+ bindToolApprovalIdentity(bindToolApproval(delayed, 'source-one'), 'echo', { type: 'object' });+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const chat = 'background-chat';+ const saver = new MemorySaver();+ const rewrite = { text: 'background', run_in_background: true };+ try {+ const first = await build({+ source,+ chat,+ saver,+ eventDriven: true,+ background: true,+ rewrite,+ executionTool: delayed,+ callId: 'background-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config(chat));+ const payload = first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload;+ expect(payload.action_requests[0].arguments).toMatchObject({ run_in_background: true });+ const bindings = captureRunToolApprovalBindings(first, payload)!;+ expect(bindings['background-call'].canRemember).toBe(false);+ const resumed = await build({+ source,+ chat,+ saver,+ eventDriven: true,+ background: true,+ rewrite,+ executionTool: delayed,+ reviewed: { bindings, decisions: [{ tool_call_id: 'background-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'background-call': { type: 'approve' } }, config(chat));+ await started;+ expect(executions).toBe(1);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ release();+ await failed;+ await new Promise((resolve) => setImmediate(resolve));+ await new Promise((resolve) => setImmediate(resolve));+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ } finally {+ release();+ await new Promise((resolve) => setImmediate(resolve));+ }+});++test.each([false, true])(+ 'request-only header authority cannot change between review and resume (event-driven: %s)',+ async (eventDriven) => {+ const declared = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/mcp',+ requestHeaders: { 'X-Workspace': '{{WORKSPACE}}' },+ };+ const authorityA = buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: declared,+ customUserVars: { WORKSPACE: 'workspace-a' },+ });+ const authorityB = buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: declared,+ customUserVars: { WORKSPACE: 'workspace-b' },+ });+ const targetDefinition = (authority?: string) =>+ bindToolApprovalIdentity(+ bindToolReviewAuthority(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ authority,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'chat',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [targetDefinition(authorityA)],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'header-review-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', authorityA),+ callId: 'header-call',+ });+ await first.processStream(+ { messages: [new HumanMessage('run')] },+ config('header-review-chat'),+ );+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const changed = { ...source, toolDefinitions: [targetDefinition(authorityB)] };+ const resumed = await build({+ source: changed,+ chat: 'header-review-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', authorityB),+ reviewed: { bindings, decisions: [{ tool_call_id: 'header-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'header-call': { type: 'approve' } }, config('header-review-chat'));+ expect(executions).toBe(0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+);++test.each([false, true])(+ 'mixed routing/token header changes cannot reuse paused consent (event-driven: %s)',+ async (eventDriven) => {+ const selected = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/mcp',+ headers: { 'X-Workspace': '{{WORKSPACE}}:{{LIBRECHAT_OPENID_TOKEN}}' },+ };+ const authorityA = buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: selected,+ user: { id: '652000000000000000000001', openidId: 'subject-a' },+ customUserVars: { WORKSPACE: 'workspace-a' },+ });+ const authorityB = buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: selected,+ user: { id: '652000000000000000000001', openidId: 'subject-a' },+ customUserVars: { WORKSPACE: 'workspace-b' },+ });+ const targetDefinition = (authority?: string) =>+ bindToolApprovalIdentity(+ bindToolReviewAuthority(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ authority,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'chat',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [targetDefinition(authorityA)],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'mixed-header-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', authorityA),+ callId: 'mixed-header-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('mixed-header-chat'));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ expect(bindings['mixed-header-call']).toBeDefined();+ const changed = { ...source, toolDefinitions: [targetDefinition(authorityB)] };+ const resumed = await build({+ source: changed,+ chat: 'mixed-header-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', authorityB),+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'mixed-header-call', decision: 'approve' }],+ },+ });+ await resumed.resume({ 'mixed-header-call': { type: 'approve' } }, config('mixed-header-chat'));+ expect(executions).toBe(0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+);++async function oauthCredential(epoch: string) {+ await mongoose.models.Token.deleteMany({ userId: '652000000000000000000001' });+ return mongoose.models.Token.create({+ userId: '652000000000000000000001',+ type: 'mcp_oauth',+ identifier: 'mcp:fixture',+ token: 'synthetic-oauth-token',+ expiresAt: new Date(Date.now() + 60000),+ metadata: { credential_set_id: epoch },+ });+}++test.each(['chat', 'always'] as const)(+ 'a changed OAuth account cannot reuse a learned %s grant',+ async (mode) => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: { approval_mode: mode, approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05' },+ },+ toolDefinitions: [definition()],+ };+ const token = await oauthCredential('account-a');+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'oauth-consent-chat',+ saver,+ eventDriven: true,+ callId: 'oauth-call',+ });+ await first.processStream(+ { messages: [new HumanMessage('run')] },+ config('oauth-consent-chat'),+ );+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ expect(bindings['oauth-call'].oauthEpoch).toBe('account-a');+ const resumed = await build({+ source,+ chat: 'oauth-consent-chat',+ saver,+ eventDriven: true,+ reviewed: { bindings, decisions: [{ tool_call_id: 'oauth-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'oauth-call': { type: 'approve' } }, config('oauth-consent-chat'));+ expect(executions).toBe(1);+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ const next = await build({+ source,+ chat: 'oauth-consent-chat',+ saver: new MemorySaver(),+ eventDriven: true,+ callId: 'next-oauth-call',+ });+ await next.processStream(+ { messages: [new HumanMessage('run again')] },+ config('oauth-consent-chat'),+ );+ expect(next.getInterrupt()?.payload.type).toBe('tool_approval');+ expect(executions).toBe(1);+ await mongoose.models.Token.deleteOne({ _id: token._id });+ },+);++test('OAuth replacement after pre-tool approval is refused before invocation', async () => {+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const token = await oauthCredential('account-a');+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'oauth-dispatch-chat',+ saver,+ eventDriven: true,+ callId: 'dispatch-oauth-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('oauth-dispatch-chat'));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const resumed = await build({+ source,+ chat: 'oauth-dispatch-chat',+ saver,+ eventDriven: true,+ beforeLoad: async () => {+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ },+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'dispatch-oauth-call', decision: 'approve' }],+ },+ });+ await resumed.resume(+ { 'dispatch-oauth-call': { type: 'approve' } },+ config('oauth-dispatch-chat'),+ );+ expect(executions).toBe(0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ await mongoose.models.Token.deleteOne({ _id: token._id });+});++test('an OAuth account replaced during transport recovery cannot dispatch the retry', async () => {+ const token = await oauthCredential('account-a');+ let sideEffects = 0;+ const retryProbe = Object.assign(+ createMCPStructuredTool(+ async () => {+ await assertToolApprovalTransportEpoch('fixture', 'account-a', true);+ // The first rejected tools/call had no side effect. Live OAuth recovery replaces its account.+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ await assertToolApprovalTransportEpoch('fixture', 'account-b', true);+ sideEffects++;+ return formatToolContent(+ { content: [{ type: 'text', text: 'unexpected retry' }] },+ 'openai',+ );+ },+ {+ name,+ description: 'Retry probe',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ );+ bindToolApprovalIdentity(bindToolApproval(retryProbe, 'source-one'), 'echo', { type: 'object' });+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'retry-consent-chat',+ saver,+ eventDriven: true,+ executionTool: retryProbe,+ callId: 'retry-consent-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config('retry-consent-chat'));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const resumed = await build({+ source,+ chat: 'retry-consent-chat',+ saver,+ eventDriven: true,+ executionTool: retryProbe,+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'retry-consent-call', decision: 'approve' }],+ },+ });+ await resumed.resume({ 'retry-consent-call': { type: 'approve' } }, config('retry-consent-chat'));+ expect(sideEffects).toBe(0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ await mongoose.models.Token.deleteOne({ _id: token._id });+});++test('unsaved verified alias reset revokes the canonical grant without resetting other tools', async () => {+ const storage = createMethods(mongoose);+ const scope = { userId: '652000000000000000000001', conversationId: 'alias-reset-chat' };+ const consent = {+ agentId: 'alias-agent',+ instanceName: 'db_query_mcp_db',+ toolName: 'query_mcp_db',+ binding: 'alias-query-binding',+ scope: 'always' as const,+ };+ const other = {+ ...consent,+ instanceName: 'other_mcp_db',+ toolName: 'other_mcp_db',+ binding: 'other-binding',+ };+ await storage.rememberToolApprovalGrants(scope, [consent, other]);+ const agent = {+ id: consent.agentId,+ tool_options: { db_query_mcp_db: { approval_mode: 'always' as const } },+ };+ const app = express();+ app.use(express.json());+ const controller = createResetToolApprovalController({+ storage,+ getAgent: async () => agent,+ canAccessAgent: async () => true,+ getMCPServerConfigs: async () => ({+ db: { type: 'streamable-http', url: 'https://mcp.example.test/mcp' },+ }),+ getMCPServerTools: async () => formatMCPServerTools('db', [{ name: 'db_query' }]),+ });+ app.post('/reset', (req, res) =>+ controller(Object.assign(req, { user: { id: scope.userId } }), res),+ );+ await request(app)+ .post('/reset')+ .send({ agentId: agent.id, toolName: 'query_mcp_db' })+ .expect(200);+ const statuses = await storage.getToolApprovalGrants(scope, [consent, other]);+ expect(statuses.map((status) => status.approved)).toEqual([false, true]);+ await storage.rememberToolApprovalGrants(scope, [consent]);+ expect((await storage.getToolApprovalGrants(scope, [consent]))[0].approved).toBe(false);+ expect(Object.keys(agent.tool_options)).toEqual(['db_query_mcp_db']);+});++for (const eventDriven of [false, true]) {+ test.each([false, true])(+ `stdio renewable env rotation permits only the unchanged reviewed route; event-driven=${eventDriven}, route changed=%s`,+ async (routeChanged) => {+ const selected = {+ type: 'stdio' as const,+ source: 'yaml' as const,+ command: 'node',+ args: ['server.js'],+ env: { UPSTREAM_ACCESS_TOKEN: '{{WORKSPACE}}:{{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ const authority = (token: string, workspace: string) =>+ buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: selected,+ user: {+ id: '652000000000000000000001',+ openidId: 'subject-a',+ openidTokens: { access_token: token, expires_at: Math.floor(Date.now() / 1000) + 3600 },+ },+ customUserVars: { WORKSPACE: workspace },+ });+ const a = authority('synthetic-a', 'workspace-a');+ const b = authority('synthetic-b', routeChanged ? 'workspace-b' : 'workspace-a');+ const targetDefinition = (value?: string) =>+ bindToolApprovalIdentity(+ bindToolReviewAuthority(+ {+ name,+ serverName: 'fixture',+ parameters: { type: 'object' },+ },+ value,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'chat',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [targetDefinition(a)],+ };+ const saver = new MemorySaver();+ const first = await build({+ source,+ chat: 'env-renewal-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', a),+ callId: 'env-renewal-call',+ });+ await first.processStream(+ { messages: [new HumanMessage('run')] },+ config('env-renewal-chat'),+ );+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const resumed = await build({+ source: { ...source, toolDefinitions: [targetDefinition(b)] },+ chat: 'env-renewal-chat',+ saver,+ eventDriven,+ executionTool: createProbe(null, 'echo', b),+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'env-renewal-call', decision: 'approve' }],+ },+ });+ await resumed.resume({ 'env-renewal-call': { type: 'approve' } }, config('env-renewal-chat'));+ expect(executions).toBe(routeChanged ? 0 : 1);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+ );+}++for (const mode of ['chat', 'always'] as const) {+ for (const eventDriven of [false, true]) {+ test.each(['approve', 'edit'] as const)(+ `${mode} reviewed templated %s refuses background dispatch; event-driven=${eventDriven}`,+ async (decision) => {+ const connection = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/mcp',+ headers: { 'X-Workspace': '{{WORKSPACE}}' },+ customUserVars: { WORKSPACE: { title: 'Workspace', description: 'Selected workspace' } },+ };+ expect(buildMCPToolApprovalBinding('fixture', connection)).toBeUndefined();+ const authority = buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: connection,+ customUserVars: { WORKSPACE: 'workspace-a' },+ });+ const reviewDefinition = bindToolApprovalIdentity(+ bindToolReviewAuthority(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ authority,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [reviewDefinition],+ };+ const saver = new MemorySaver();+ const chat = `review-background-${mode}-${eventDriven}-${decision}`;+ const rewrite = { text: 'reviewed', run_in_background: true };+ const executionTool = createProbe(null, 'echo', authority);+ const first = await build({+ source,+ chat,+ saver,+ eventDriven,+ background: true,+ executionTool,+ rewrite,+ callId: 'review-background-call',+ });+ await first.processStream({ messages: [new HumanMessage('run')] }, config(chat));+ const payload = first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload;+ expect(payload.action_requests[0].arguments).toMatchObject({ run_in_background: true });+ const bindings = captureRunToolApprovalBindings(first, payload)!;+ const reviewed = {+ bindings,+ decisions: [{ tool_call_id: 'review-background-call', decision }],+ };+ const session = createAgentToolApprovalSession({+ agents: [source],+ storage,+ scope: { userId: '652000000000000000000001', conversationId: chat },+ reviewed,+ });+ let dispatched = false;+ let finish!: () => void;+ const settled = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const note = session.noteDispatch;+ session.noteDispatch = (invocation) => {+ dispatched = invocation.background === true;+ note?.(invocation);+ };+ const complete = session.finishDispatch;+ session.finishDispatch = (invocation) => {+ complete?.(invocation);+ finish();+ };+ const resumed = await build({+ source,+ chat,+ saver,+ eventDriven,+ background: true,+ executionTool,+ rewrite,+ sharedSession: session,+ });+ const invocationConfig = config(chat);+ if (!eventDriven) {+ Object.assign(invocationConfig.configurable, {+ __librechatBackgroundToolInvocation: true,+ });+ }+ const answer =+ decision === 'edit'+ ? { type: 'edit' as const, updatedInput: rewrite }+ : { type: 'approve' as const };+ await resumed.resume({ 'review-background-call': answer }, invocationConfig);+ if (eventDriven) {+ expect(dispatched).toBe(true);+ await settled;+ }+ expect(executions).toBe(0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ },+ );+ }+}++test('old detached settlement cannot erase a newer reused call ID’s OAuth transport fence', async () => {+ const token = await oauthCredential('account-a');+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always',+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const chat = 'reused-background-provider-id';+ const grantScope = { userId: '652000000000000000000001', conversationId: chat };+ await storage.rememberToolApprovalGrants(grantScope, [+ { ...resolveAgentToolGrantBinding(source, name, grantScope)!, oauthEpoch: 'account-a' },+ ]);+ const session = createAgentToolApprovalSession({ agents: [source], storage, scope: grantScope });+ let releaseOld!: () => void;+ let markOldStarted!: () => void;+ let markNewStarted!: () => void;+ let markOldFinished!: () => void;+ const oldGate = new Promise<void>((resolve) => {+ releaseOld = resolve;+ });+ const oldStarted = new Promise<void>((resolve) => {+ markOldStarted = resolve;+ });+ const newStarted = new Promise<void>((resolve) => {+ markNewStarted = resolve;+ });+ const oldFinished = new Promise<void>((resolve) => {+ markOldFinished = resolve;+ });+ const complete = session.finishDispatch;+ session.finishDispatch = (invocation) => {+ complete?.(invocation);+ markOldFinished();+ };+ const probe = (invoke: () => Promise<unknown>) =>+ bindToolApprovalIdentity(+ bindToolApproval(+ Object.assign(+ createMCPStructuredTool(invoke, {+ name,+ description: 'Ownership fixture',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ }),+ { schema: fixtureSchema },+ ),+ 'source-one',+ ),+ 'echo',+ { type: 'object' },+ );+ const oldTool = probe(async () => {+ markOldStarted();+ await oldGate;+ return formatToolContent({ content: [{ type: 'text', text: 'old settled' }] }, 'openai');+ });+ let newSideEffects = 0;+ const newTool = probe(async () => {+ markNewStarted();+ await oldFinished;+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ await assertToolApprovalTransportEpoch('fixture', 'account-b', true);+ newSideEffects++;+ return formatToolContent({ content: [{ type: 'text', text: 'unsafe new retry' }] }, 'openai');+ });+ let newTurn: Promise<void> | undefined;+ try {+ const old = await build({+ source,+ chat,+ saver: new MemorySaver(),+ sharedSession: session,+ eventDriven: true,+ background: true,+ rewrite: { text: 'old', run_in_background: true },+ executionTool: oldTool,+ callId: 'call_0',+ });+ await old.processStream({ messages: [new HumanMessage('old background')] }, config(chat));+ await oldStarted;+ const newer = await build({+ source,+ chat,+ saver: new MemorySaver(),+ sharedSession: session,+ eventDriven: true,+ executionTool: newTool,+ callId: 'call_0',+ });+ newTurn = newer+ .processStream({ messages: [new HumanMessage('new foreground')] }, config(chat))+ .then(() => {});+ await newStarted;+ releaseOld();+ await newTurn;+ expect(newSideEffects).toBe(0);+ expect(JSON.stringify(newer.getRunMessages())).toContain('OAuth authorization changed');+ } finally {+ releaseOld();+ await newTurn;+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+});++test.each([false, true])(+ 'registry reinspection preserves paused review and learned consent (event-driven=%s)',+ async (eventDriven) => {+ const registry = new ServerConfigsCacheInMemory();+ const declared = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/mcp',+ };+ await registry.add('fixture', { ...declared, initDuration: 1 });+ const target = async () => {+ const selected = await registry.get('fixture');+ const binding = buildMCPToolApprovalBinding('fixture', selected);+ const authority = buildMCPToolReviewAuthority({ serverName: 'fixture', config: selected });+ return {+ source: {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: 'always' as const,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [+ bindToolApprovalIdentity(+ bindToolReviewAuthority(+ bindToolApproval(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ binding,+ ),+ authority,+ ),+ 'echo',+ { type: 'object' },+ ),+ ],+ },+ executionTool: createProbe(binding, 'echo', authority),+ };+ };+ const initial = await target();+ const saver = new MemorySaver();+ const chat = `registry-consent-${eventDriven}`;+ const first = await build({ ...initial, chat, saver, eventDriven, callId: 'registry-call' });+ await first.processStream({ messages: [new HumanMessage('run')] }, config(chat));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ await registry.update('fixture', {+ ...declared,+ initDuration: 900,+ tools: 'reinspected',+ capabilities: 'new summary',+ });+ const refreshed = await target();+ const resumed = await build({+ ...refreshed,+ chat,+ saver,+ eventDriven,+ reviewed: { bindings, decisions: [{ tool_call_id: 'registry-call', decision: 'approve' }] },+ });+ await resumed.resume({ 'registry-call': { type: 'approve' } }, config(chat));+ expect(executions).toBe(1);+ await registry.update('fixture', { ...declared, initDuration: 2 });+ const again = await build({+ ...(await target()),+ chat,+ saver: new MemorySaver(),+ eventDriven,+ callId: 'registry-next',+ });+ await again.processStream({ messages: [new HumanMessage('run again')] }, config(chat));+ expect(again.getInterrupt()).toBeUndefined();+ expect(executions).toBe(2);+ },+);++for (const mode of ['chat', 'always'] as const) {+ for (const eventDriven of [false, true]) {+ test.each(['connection', 'schema', 'revision'])(+ `${mode} superseded %s completion preserves replacement consent; event-driven=${eventDriven}`,+ async (change) => {+ let release!: () => void;+ let markStarted!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const started = new Promise<void>((resolve) => {+ markStarted = resolve;+ });+ const oldTool = bindToolApprovalIdentity(+ bindToolApproval(+ Object.assign(+ createMCPStructuredTool(+ async () => {+ markStarted();+ await gate;+ return formatToolContent(+ { content: [{ type: 'text', text: 'old completed' }] },+ 'openai',+ );+ },+ {+ name,+ description: 'Old approved call',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ ),+ 'source-one',+ ),+ 'echo',+ { type: 'object' },+ );+ const original: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const parameters =+ change === 'schema' ? { type: 'object', description: 'new schema' } : { type: 'object' };+ const sourceBinding = change === 'connection' ? 'source-two' : 'source-one';+ const changed: AgentApprovalSource = {+ ...original,+ tool_options: {+ [name]: {+ ...original.tool_options![name],+ approval_revision:+ change === 'revision'+ ? '2782f8d4-f52b-4a37-b65e-a60a5b5d4e5b'+ : original.tool_options![name].approval_revision,+ },+ },+ toolDefinitions: [+ bindToolApprovalIdentity(+ bindToolApproval({ name, serverName: 'fixture', parameters }, sourceBinding),+ 'echo',+ parameters,+ ),+ ],+ };+ const newTool = bindToolApprovalIdentity(createProbe(sourceBinding), 'echo', parameters);+ const oldChat = `old-authority-${mode}-${eventDriven}-${change}`;+ const newChat = mode === 'chat' ? oldChat : `new-authority-${eventDriven}-${change}`;+ const oldSaver = new MemorySaver();+ const newSaver = new MemorySaver();+ let oldCompletion: Promise<void> | undefined;+ try {+ const first = await build({+ source: original,+ chat: oldChat,+ saver: oldSaver,+ eventDriven,+ executionTool: oldTool,+ callId: 'old-call',+ });+ await first.processStream({ messages: [new HumanMessage('old')] }, config(oldChat));+ const oldBindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const old = await build({+ source: original,+ chat: oldChat,+ saver: oldSaver,+ eventDriven,+ executionTool: oldTool,+ reviewed: {+ bindings: oldBindings,+ decisions: [{ tool_call_id: 'old-call', decision: 'approve' }],+ },+ });+ oldCompletion = old+ .resume({ 'old-call': { type: 'approve' } }, config(oldChat))+ .then(() => {});+ await started;+ const second = await build({+ source: changed,+ chat: newChat,+ saver: newSaver,+ eventDriven,+ executionTool: newTool,+ callId: 'new-call',+ });+ await second.processStream({ messages: [new HumanMessage('new')] }, config(newChat));+ const newBindings = captureRunToolApprovalBindings(+ second,+ second.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const newer = await build({+ source: changed,+ chat: newChat,+ saver: newSaver,+ eventDriven,+ executionTool: newTool,+ reviewed: {+ bindings: newBindings,+ decisions: [{ tool_call_id: 'new-call', decision: 'approve' }],+ },+ });+ await newer.resume({ 'new-call': { type: 'approve' } }, config(newChat));+ const scope = { userId: '652000000000000000000001', conversationId: newChat };+ const oldGrant = resolveAgentToolGrantBinding(original, name, scope)!;+ const newGrant = resolveAgentToolGrantBinding(changed, name, scope)!;+ expect((await storage.getToolApprovalGrants(scope, [newGrant]))[0].approved).toBe(true);+ release();+ await oldCompletion;+ expect(+ (await storage.getToolApprovalGrants(scope, [oldGrant, newGrant])).map(+ (status) => status.approved,+ ),+ ).toEqual([false, true]);+ } finally {+ release();+ await oldCompletion;+ }+ },+ );+ }+}++for (const mode of ['chat', 'always'] as const) {+ for (const eventDriven of [false, true]) {+ test.each([false, true])(+ `${mode} OAuth-to-API-key consent ignores retained credentials; event-driven=${eventDriven}, templated=%s`,+ async (templated) => {+ const token = await oauthCredential('retained-account-a');+ const connection = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/mcp',+ requiresOAuth: false,+ oauth: { client_id: 'retained-client' },+ apiKey: {+ source: 'admin' as const,+ authorization_type: 'bearer' as const,+ key: 'synthetic-current-key',+ },+ ...(templated+ ? {+ headers: { 'X-Workspace': '{{WORKSPACE}}' },+ customUserVars: { WORKSPACE: { title: 'Workspace', description: 'Workspace' } },+ }+ : {}),+ };+ const kind = getMCPToolApprovalAuthKind(connection)!;+ expect(kind).toBe('other');+ const binding = buildMCPToolApprovalBinding('fixture', connection);+ const authority = buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: connection,+ user: { id: '652000000000000000000001' },+ customUserVars: { WORKSPACE: 'workspace-a' },+ });+ const def = bindToolApprovalIdentity(+ bindToolApproval(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ binding,+ undefined,+ undefined,+ authority,+ kind,+ ),+ 'echo',+ { type: 'object' },+ );+ const probe = bindToolApprovalIdentity(+ bindToolApproval(+ Object.assign(+ createMCPStructuredTool(+ async () => {+ await assertToolApprovalTransportEpoch('fixture', null, true);+ executions++;+ return formatToolContent(+ { content: [{ type: 'text', text: 'current API-key target' }] },+ 'openai',+ );+ },+ {+ name,+ description: 'Current API-key target',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ ),+ binding,+ undefined,+ undefined,+ authority,+ kind,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [def],+ };+ const chat = `auth-kind-${mode}-${eventDriven}-${templated}`;+ const saver = new MemorySaver();+ try {+ const first = await build({+ source,+ chat,+ saver,+ eventDriven,+ executionTool: probe,+ callId: 'api-key-call',+ });+ await first.processStream(+ { messages: [new HumanMessage('review current target')] },+ config(chat),+ );+ const payload = first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload;+ const bindings = captureRunToolApprovalBindings(first, payload)!;+ expect(bindings['api-key-call']).toMatchObject({ authKind: 'other', oauthEpoch: null });+ const resumed = await build({+ source,+ chat,+ saver,+ eventDriven,+ executionTool: probe,+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'api-key-call', decision: 'approve' }],+ },+ });+ await resumed.resume({ 'api-key-call': { type: 'approve' } }, config(chat));+ expect(executions).toBe(1);+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'retained-account-b' } },+ );+ const again = await build({+ source,+ chat,+ saver: new MemorySaver(),+ eventDriven,+ executionTool: probe,+ callId: 'api-key-next',+ });+ await again.processStream(+ { messages: [new HumanMessage('use current key again')] },+ config(chat),+ );+ if (templated) {+ expect(again.getInterrupt()?.payload.type).toBe('tool_approval');+ expect(executions).toBe(1);+ } else {+ expect(again.getInterrupt()).toBeUndefined();+ expect(executions).toBe(2);+ }+ const oauthDefinition = bindToolApprovalIdentity(+ bindToolApproval(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ 'renewed-oauth-authority',+ undefined,+ undefined,+ undefined,+ 'oauth',+ ),+ 'echo',+ { type: 'object' },+ );+ const switched = await build({+ source: { ...source, toolDefinitions: [oauthDefinition] },+ chat,+ saver: new MemorySaver(),+ eventDriven,+ executionTool: bindToolApproval(+ createProbe('renewed-oauth-authority'),+ 'renewed-oauth-authority',+ undefined,+ undefined,+ undefined,+ 'oauth',+ ),+ callId: 'oauth-again',+ });+ await switched.processStream(+ { messages: [new HumanMessage('use OAuth again')] },+ config(chat),+ );+ expect(switched.getInterrupt()?.payload.type).toBe('tool_approval');+ expect(+ captureRunToolApprovalBindings(+ switched,+ switched.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!['oauth-again'],+ ).toMatchObject({ authKind: 'oauth', oauthEpoch: 'retained-account-b' });+ } finally {+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+ },+ );+ }+}++for (const mode of ['ask', 'chat', 'always'] as const) {+ for (const eventDriven of [false, true]) {+ test.each(['unchanged', 'resume', 'retry'] as const)(+ `${mode} runtime-detected OAuth reviews remain account-bound; event-driven=${eventDriven}, change=%s`,+ async (change) => {+ const token = await oauthCredential('runtime-account-a');+ const declared = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/users/{{LIBRECHAT_USER_ID}}/mcp',+ };+ const authKind = getMCPToolApprovalAuthKind(declared);+ expect(authKind).toBeUndefined();+ expect(buildMCPToolApprovalBinding('fixture', declared)).toBeUndefined();+ const authority = buildMCPToolReviewAuthority({+ serverName: 'fixture',+ config: declared,+ user: { id: '652000000000000000000001' },+ });+ const definition = bindToolApprovalIdentity(+ bindToolApproval(+ { name, serverName: 'fixture', parameters: { type: 'object' } },+ undefined,+ undefined,+ undefined,+ authority,+ authKind,+ ),+ 'echo',+ { type: 'object' },+ );+ let attempts = 0;+ const probe = bindToolApprovalIdentity(+ bindToolApproval(+ Object.assign(+ createMCPStructuredTool(+ async () => {+ attempts++;+ await assertToolApprovalTransportEpoch('fixture', 'runtime-account-a', true);+ if (change === 'retry') {+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'runtime-account-b' } },+ );+ await assertToolApprovalTransportEpoch('fixture', 'runtime-account-b', true);+ }+ executions++;+ return formatToolContent(+ { content: [{ type: 'text', text: 'runtime OAuth completed' }] },+ 'openai',+ );+ },+ {+ name,+ description: 'Runtime OAuth fixture',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ ),+ undefined,+ undefined,+ undefined,+ authority,+ authKind,+ ),+ 'echo',+ { type: 'object' },+ );+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition],+ };+ const chat = `runtime-auth-${mode}-${eventDriven}-${change}`;+ const saver = new MemorySaver();+ try {+ const first = await build({+ source,+ chat,+ saver,+ eventDriven,+ executionTool: probe,+ callId: 'runtime-call',+ });+ await first.processStream({ messages: [new HumanMessage('review')] }, config(chat));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ expect(bindings['runtime-call']).toMatchObject({+ oauthEpoch: 'runtime-account-a',+ canRemember: false,+ });+ expect(bindings['runtime-call'].authKind).toBeUndefined();+ if (change === 'resume')+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'runtime-account-b' } },+ );+ const resumed = await build({+ source,+ chat,+ saver,+ eventDriven,+ executionTool: probe,+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'runtime-call', decision: 'approve' }],+ },+ });+ await resumed.resume({ 'runtime-call': { type: 'approve' } }, config(chat));+ expect(attempts).toBe(change === 'resume' ? 0 : 1);+ expect(executions).toBe(change === 'unchanged' ? 1 : 0);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ } finally {+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+ },+ );+ }+}++for (const mode of ['ask', 'chat', 'always'] as const) {+ for (const eventDriven of [false, true]) {+ test.each(['unchanged', 'connection', 'schema', 'account'] as const)(+ `${mode} pending approval stays fenced after mode removal; event-driven=${eventDriven}, change=%s`,+ async (change) => {+ const token = await oauthCredential('account-a');+ const original: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [definition()],+ };+ const chat = `inherit-resume-${mode}-${eventDriven}-${change}`;+ const saver = new MemorySaver();+ try {+ const first = await build({+ source: original,+ chat,+ saver,+ eventDriven,+ callId: 'pending-call',+ });+ await first.processStream({ messages: [new HumanMessage('review')] }, config(chat));+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const parameters =+ change === 'schema'+ ? { type: 'object', description: 'changed schema' }+ : { type: 'object' };+ const sourceBinding =+ change === 'connection' ? 'replacement-endpoint-authority' : 'source-one';+ const currentDefinition = bindToolApprovalIdentity(+ bindToolApproval({ name, serverName: 'fixture', parameters }, sourceBinding),+ 'echo',+ parameters,+ );+ const probe = bindToolApprovalIdentity(+ Object.assign(+ createMCPStructuredTool(+ async () => {+ await assertToolApprovalTransportEpoch(+ 'fixture',+ change === 'account' ? 'account-b' : 'account-a',+ true,+ );+ executions++;+ return formatToolContent(+ { content: [{ type: 'text', text: 'unexpected inherited resume' }] },+ 'openai',+ );+ },+ {+ name,+ description: 'Inheritance resume probe',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ ),+ 'echo',+ parameters,+ );+ bindToolApproval(probe, sourceBinding);+ if (change === 'account')+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ const resumed = await build({+ source: { ...original, tool_options: undefined, toolDefinitions: [currentDefinition] },+ chat,+ saver,+ eventDriven,+ executionTool: probe,+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'pending-call', decision: 'approve' }],+ },+ });+ await resumed.resume({ 'pending-call': { type: 'approve' } }, config(chat));+ expect(executions).toBe(0);+ expect(JSON.stringify(resumed.getRunMessages())).toContain(+ 'approval configuration changed',+ );+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ } finally {+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+ },+ );+ }+}++for (const eventDriven of [false, true]) {+ test.each(['unchanged', 'before-invocation', 'before-send', 'retry'] as const)(+ `programmatic review pins OAuth despite allow mode; event-driven=${eventDriven}, change=%s`,+ async (change) => {+ const token = await oauthCredential('account-a');+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: { [name]: { approval_mode: 'allow' } },+ toolDefinitions: [definition()],+ };+ const chat = `allow-reviewed-${eventDriven}-${change}`;+ const saver = new MemorySaver();+ const reviewHook: ToolApprovalHook = () => ({ decision: 'ask' });+ const replace = async () => {+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ };+ let sends = 0;+ try {+ const first = await build({+ source,+ chat,+ saver,+ eventDriven,+ reviewHook,+ callId: 'reviewed-allow',+ });+ await first.processStream(+ { messages: [new HumanMessage('review required by hook')] },+ config(chat),+ );+ expect(first.getInterrupt()?.payload.type).toBe('tool_approval');+ const bindings = captureRunToolApprovalBindings(+ first,+ first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload,+ )!;+ const probe = bindToolApprovalIdentity(+ bindToolApproval(+ Object.assign(+ createMCPStructuredTool(+ async () => {+ if (change === 'before-send') await replace();+ await assertToolApprovalTransportEpoch(+ 'fixture',+ change === 'before-send' ? 'account-b' : 'account-a',+ true,+ );+ sends++;+ if (change === 'retry') {+ await replace();+ await assertToolApprovalTransportEpoch('fixture', 'account-b', true);+ sends++;+ }+ return formatToolContent(+ { content: [{ type: 'text', text: 'reviewed account' }] },+ 'openai',+ );+ },+ {+ name,+ description: 'Reviewed allow probe',+ schema: fixtureSchema,+ responseFormat: 'content_and_artifact',+ },+ ),+ { schema: fixtureSchema },+ ),+ 'source-one',+ ),+ 'echo',+ { type: 'object' },+ );+ const resumed = await build({+ source,+ chat,+ saver,+ eventDriven,+ reviewHook,+ executionTool: probe,+ beforeExecution: change === 'before-invocation' ? replace : undefined,+ reviewed: {+ bindings,+ decisions: [{ tool_call_id: 'reviewed-allow', decision: 'approve' }],+ },+ });+ await resumed.resume({ 'reviewed-allow': { type: 'approve' } }, config(chat));+ expect(sends).toBe(change === 'unchanged' || change === 'retry' ? 1 : 0);+ if (change !== 'unchanged')+ expect(JSON.stringify(resumed.getRunMessages())).toContain('OAuth authorization changed');+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ } finally {+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+ },+ );+}++for (const eventDriven of [false, true]) {+ for (const mode of ['ask', 'chat', 'always'] as const) {+ test.each([+ 'unavailable',+ 'recovered',+ 'invoke-outage',+ 'resume-recovered',+ 'transport-outage',+ 'transport-recovered',+ 'retry-outage',+ ] as const)(+ `${mode} reviewed non-OAuth SDK execution remains once-only during %s; event-driven=${eventDriven}`,+ async (stage) => {+ const chat = `outage-${mode}-${stage}-${eventDriven}`;+ const toolDefinition = definition();+ bindToolApproval(toolDefinition, 'source-one', undefined, undefined, undefined, 'other');+ const probe = createProbe('source-one', 'echo', undefined, async () => {+ if (stage === 'transport-outage' || stage === 'transport-recovered') unavailable = true;+ await assertToolApprovalTransportEpoch('fixture', null, true);+ if (stage === 'transport-recovered') unavailable = false;+ if (stage === 'retry-outage') unavailable = true;+ await assertToolApprovalTransportEpoch('fixture', null, true);+ // Recovery before successful completion must not restore learning eligibility.+ unavailable = false;+ });+ bindToolApproval(probe, 'source-one', undefined, undefined, undefined, 'other');+ const source: AgentApprovalSource = {+ id: 'agent-a',+ tool_options: {+ [name]: {+ approval_mode: mode,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ },+ toolDefinitions: [toolDefinition],+ };+ const saver = new MemorySaver();+ let unavailable = stage === 'unavailable' || stage === 'recovered';+ const realLookup = storage.getToolApprovalGrants.bind(storage);+ const failedStorage: ToolApprovalGrantStorage = {+ ...storage,+ getToolApprovalGrants: async (...args) => {+ if (unavailable) throw new Error('synthetic grant-store outage');+ return realLookup(...args);+ },+ };+ const session = (reviewed?: ReviewedToolApprovals) =>+ createAgentToolApprovalSession({+ agents: [source],+ scope: { userId: '652000000000000000000001', conversationId: chat },+ storage: failedStorage,+ reviewed,+ });+ const first = await build({+ source,+ chat,+ saver,+ eventDriven,+ executionTool: probe,+ callId: 'outage-call',+ sharedSession: session(),+ });+ await first.processStream(+ { messages: [new HumanMessage('review this call')] },+ config(chat),+ );+ const payload = first.getInterrupt()!.payload as Agents.ToolApprovalInterruptPayload;+ const bindings = captureRunToolApprovalBindings(first, payload)!;+ expect(bindings['outage-call'].oauthEpoch).toBeNull();+ if (stage === 'unavailable' || stage === 'recovered')+ expect(bindings['outage-call']).toMatchObject({+ canRemember: false,+ unavailable: 'storage',+ });+ if (stage === 'recovered') unavailable = false;+ if (stage === 'resume-recovered') unavailable = true;+ const resumed = await build({+ source,+ chat,+ saver,+ eventDriven,+ executionTool: probe,+ sharedSession: session({+ bindings,+ decisions: [{ tool_call_id: 'outage-call', decision: 'approve' }],+ }),+ beforeExecution:+ stage === 'invoke-outage' || stage === 'resume-recovered'+ ? async () => {+ unavailable = stage === 'invoke-outage';+ }+ : undefined,+ });+ await resumed.resume({ 'outage-call': { type: 'approve' } }, config(chat));+ expect(executions).toBe(1);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+ unavailable = false;+ const next = await build({+ source,+ chat,+ saver: new MemorySaver(),+ eventDriven,+ executionTool: probe,+ callId: 'next-call',+ sharedSession: session(),+ });+ await next.processStream({ messages: [new HumanMessage('new call')] }, config(chat));+ expect(next.getInterrupt()?.payload.type).toBe('tool_approval');+ expect(executions).toBe(1);+ },+ );+ }+}diff --git a/packages/api/src/agents/hitl/modes.spec.ts b/packages/api/src/agents/hitl/modes.spec.tsnew file mode 100644index 0000000000..5146bae4b3--- /dev/null+++ b/packages/api/src/agents/hitl/modes.spec.ts@@ -0,0 +1,1467 @@+import { HookRegistry, createToolPolicyHook, executeHooks } from '@librechat/agents';+import type { ToolApprovalGrantStorage, Agents } from 'librechat-data-provider';+import type { AgentApprovalSource } from './modes';+import {+ createAgentToolApprovalSession,+ resolveAgentToolGrantBinding,+ buildMCPToolApprovalBinding,+ describeRememberedToolApprovals,+} from './modes';+import { bindToolApproval, bindToolApprovalIdentity } from '~/tools/approval';+import { buildToolApprovalPayload, toClientPendingAction } from './policy';+import { buildEffectiveToolApprovalPolicy } from './allow';+import { bindToolReviewAuthority } from '~/tools/approval';+import { buildHITLRunWiring } from './runtime';++const scope = { userId: 'user-a', tenantId: 'tenant-a', conversationId: 'chat-a' };+const name = 'query_mcp_db';+const revision = 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05';+function bindFixture<T extends { name: string; parameters?: object; description?: string }>(+ tool: T,+ binding: string,+ canonicalName?: string,+) {+ const upstreamName = tool.name.slice(0, -'_mcp_db'.length);+ return bindToolApprovalIdentity(+ bindToolApproval(tool, binding, canonicalName),+ upstreamName,+ tool.parameters,+ tool.description,+ );+}+function agent(mode: 'ask' | 'allow' | 'chat' | 'always', id = 'agent-a'): AgentApprovalSource {+ return {+ id,+ tool_options: { [name]: { approval_mode: mode, approval_revision: revision } },+ toolDefinitions: [+ bindFixture({ name, serverName: 'db', parameters: { type: 'object' } }, 'source-a'),+ ],+ };+}+function store(): ToolApprovalGrantStorage {+ const grants = new Set<string>();+ return {+ getToolApprovalGrants: jest.fn(async (_scope, candidates) =>+ candidates.map((candidate) => ({+ binding: candidate.binding,+ approved: grants.has(candidate.binding),+ revocation: 'epoch-a',+ oauthEpoch: null,+ })),+ ),+ rememberToolApprovalGrants: jest.fn(async (_scope, candidates) => {+ for (const candidate of candidates) grants.add(candidate.binding);+ }),+ resetToolApprovalGrants: jest.fn(async () => {+ grants.clear();+ }),+ };+}+const input = (agentId = 'agent-a', callId = 'call-a') => ({+ hook_event_name: 'PreToolUse' as const,+ runId: 'run-a',+ threadId: scope.conversationId,+ executingAgentId: agentId,+ toolUseId: callId,+ toolName: name,+ toolInput: {},+});++test.each(['ask', 'allow', 'chat', 'always'] as const)(+ 'enforces %s per executing agent',+ async (mode) => {+ const session = createAgentToolApprovalSession({+ agents: [agent(mode), agent('allow', 'agent-b')],+ scope,+ storage: store(),+ });+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: mode === 'allow' ? 'allow' : 'ask',+ });+ expect(await session.hook(input('agent-b'), new AbortController().signal)).toEqual({+ decision: 'allow',+ });+ expect(await session.hook(input('missing'), new AbortController().signal)).toEqual({});+ },+);++test.each(['deny', 'ask'] as const)(+ 'administrator %s wins over always approve and remembered approval',+ async (decision) => {+ const source = agent('always');+ const storage = store();+ const binding = resolveAgentToolGrantBinding(source, name, scope)!;+ await storage.rememberToolApprovalGrants(scope, [binding]);+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage });+ const registry = new HookRegistry();+ registry.register('PreToolUse', {+ hooks: [createToolPolicyHook({ mode: 'bypass', [decision]: [name] }), session.hook],+ });+ const result = await executeHooks({ registry, input: input(), matchQuery: name });+ expect(result.decision).toBe(decision);+ },+);++test('coalesces parallel grant lookups and rechecks after reset', async () => {+ const storage = store();+ const source = agent('chat');+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await Promise.all([+ session.hook(input(), new AbortController().signal),+ session.hook(input('agent-a', 'call-b'), new AbortController().signal),+ ]);+ expect(storage.getToolApprovalGrants).toHaveBeenCalledTimes(1);+ const payload = buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]);+ const bindings = session.bindingsFor(payload);+ expect(bindings['call-a']).toMatchObject({+ agentId: 'agent-a',+ scope: 'chat',+ revocation: 'epoch-a',+ });+ await storage.rememberToolApprovalGrants(scope, [bindings['call-a']]);+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: 'allow',+ });+ await storage.resetToolApprovalGrants(scope.userId, source.id, name);+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: 'ask',+ });+});++test('changed agent, user, tenant, connection, schema and revision invalidate a grant binding', () => {+ const source = agent('always');+ const original = resolveAgentToolGrantBinding(source, name, scope)!.binding;+ const cases = [+ resolveAgentToolGrantBinding({ ...source, id: 'other-agent' }, name, scope),+ resolveAgentToolGrantBinding(source, name, { ...scope, userId: 'other-user' }),+ resolveAgentToolGrantBinding(source, name, { ...scope, tenantId: 'other-tenant' }),+ resolveAgentToolGrantBinding(+ {+ ...source,+ toolDefinitions: [bindFixture({ ...source.toolDefinitions![0] }, 'other-source')],+ },+ name,+ scope,+ ),+ resolveAgentToolGrantBinding(+ {+ ...source,+ toolDefinitions: [+ bindFixture(+ { ...source.toolDefinitions![0], parameters: { type: 'string' } },+ 'source-a',+ ),+ ],+ },+ name,+ scope,+ ),+ resolveAgentToolGrantBinding(+ {+ ...source,+ tool_options: { [name]: { approval_mode: 'always', approval_revision: 'new-revision' } },+ },+ name,+ scope,+ ),+ ];+ for (const candidate of cases) expect(candidate?.binding).not.toBe(original);+ expect(+ resolveAgentToolGrantBinding(source, name, { ...scope, conversationId: 'other-chat' })!.binding,+ ).toBe(original);+});++test('only a verified, manually approved successful invocation creates a grant', async () => {+ const source = agent('chat');+ const binding = resolveAgentToolGrantBinding(source, name, scope)!;+ binding.revocation = 'epoch-a';+ const payload = buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]);+ const storage = store();+ for (const decision of ['reject', 'edit', 'respond', 'approve'] as const) {+ const session = createAgentToolApprovalSession({+ agents: [],+ scope,+ storage,+ reviewed: {+ bindings: { 'call-a': binding },+ decisions: [{ tool_call_id: 'call-a', decision }],+ },+ });+ session.addAgent(source);+ await session.hook(input(), new AbortController().signal);+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ if (decision === 'approve')+ await session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'call-a',+ });+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ if (decision === 'approve')+ expect(storage.rememberToolApprovalGrants).toHaveBeenCalledWith(scope, [binding]);+ else expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ }+ const pendingAction: Agents.PendingAction = {+ actionId: 'approval-a',+ streamId: 'chat-a',+ createdAt: 1,+ payload,+ toolApprovalBindings: { 'call-a': binding },+ };+ expect(toClientPendingAction(pendingAction)).not.toHaveProperty('toolApprovalBindings');+ const described = describeRememberedToolApprovals(+ payload,+ pendingAction.toolApprovalBindings,+ ) as Agents.ToolApprovalInterruptPayload;+ expect(described.review_configs[0].remember_scope).toBe('chat');+});++test('a changed binding is denied before an approved call executes', async () => {+ const source = agent('always');+ const binding = resolveAgentToolGrantBinding(source, name, scope)!;+ const changed = {+ ...source,+ toolDefinitions: [bindFixture({ ...source.toolDefinitions![0] }, 'rebound-server')],+ };+ const session = createAgentToolApprovalSession({+ agents: [changed],+ scope,+ storage: store(),+ reviewed: {+ bindings: { 'call-a': binding },+ decisions: [{ tool_call_id: 'call-a', decision: 'approve' }],+ },+ });+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: 'deny',+ });+});++test('missing storage or unknown bindings never auto-approve ask-once tools', async () => {+ const source = agent('always');+ const session = createAgentToolApprovalSession({ agents: [source], scope });+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: 'ask',+ });+ expect(+ resolveAgentToolGrantBinding({ ...source, toolDefinitions: [] }, name, scope),+ ).toBeUndefined();+ expect(buildMCPToolApprovalBinding('db', undefined)).toBeUndefined();+});++test('a grant lookup failure or timeout returns manual review', async () => {+ jest.useFakeTimers();+ const storage = store();+ storage.getToolApprovalGrants = async () => new Promise(() => {});+ const session = createAgentToolApprovalSession({+ agents: [agent('chat')],+ scope,+ storage,+ lookupTimeoutMs: 200,+ });+ const result = session.hook(input(), new AbortController().signal);+ await jest.advanceTimersByTimeAsync(200);+ expect(await result).toMatchObject({ decision: 'ask' });+ jest.useRealTimers();+});++test('templated connection authorities never reuse remembered approval', () => {+ const base = {+ type: 'streamable-http' as const,+ url: 'https://mcp.example.test/mcp',+ source: 'yaml' as const,+ };+ expect(buildMCPToolApprovalBinding('db', base)).toEqual(expect.any(String));+ expect(+ buildMCPToolApprovalBinding('db', {+ ...base,+ url: '{{MCP_URL}}',+ customUserVars: { MCP_URL: { title: 'URL', description: 'Target server' } },+ }),+ ).toBeUndefined();+ expect(+ buildMCPToolApprovalBinding('db', {+ ...base,+ headers: { Authorization: 'Bearer ${MCP_TOKEN}' },+ }),+ ).toBeUndefined();+});++test('collision-preserved tool keys remain distinct and resettable', () => {+ const other = 'db_query_mcp_db';+ const source = agent('always');+ source.tool_options![other] = { approval_mode: 'always', approval_revision: revision };+ source.toolDefinitions!.push(+ bindFixture({ name: other, serverName: 'db', parameters: { type: 'object' } }, 'source-a'),+ );+ const first = resolveAgentToolGrantBinding(source, name, scope)!;+ const second = resolveAgentToolGrantBinding(source, other, scope)!;+ expect(second.toolName).toBe(other);+ expect(second.binding).not.toBe(first.binding);+});++test('only a verified catalog alias changes the remembered grant key', () => {+ const legacy = 'db_query_mcp_db';+ const source = agent('always');+ source.tool_options![legacy] = { approval_mode: 'always', approval_revision: revision };+ source.toolDefinitions!.push(+ bindFixture(+ { name: legacy, serverName: 'db', parameters: { type: 'object' } },+ 'source-a',+ name,+ ),+ );+ expect(resolveAgentToolGrantBinding(source, legacy, scope)?.toolName).toBe(name);+});++test('a reviewed background launch does not teach approval before its deferred result succeeds', async () => {+ const source = agent('chat');+ const scopeBinding = resolveAgentToolGrantBinding(source, name, scope)!;+ const storage = store();+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: {+ bindings: { 'call-a': scopeBinding },+ decisions: [{ tool_call_id: 'call-a', decision: 'approve' }],+ },+ });+ await session.hook(+ { ...input(), toolInput: { run_in_background: true } },+ new AbortController().signal,+ );+ await session.rememberHook(+ {+ ...input(),+ hook_event_name: 'PostToolUse',+ toolOutput: 'Task launched',+ toolInput: { run_in_background: true },+ },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+});++test('raw upstream reassignment changes consent despite an identical catalog key and schema', () => {+ const source = agent('always');+ const original = resolveAgentToolGrantBinding(source, name, scope)!;+ const reassigned = bindToolApprovalIdentity({ ...source.toolDefinitions![0] }, 'db_query', {+ type: 'object',+ });+ source.toolDefinitions = [reassigned];+ expect(resolveAgentToolGrantBinding(source, name, scope)?.binding).not.toBe(original.binding);+});++test('execution compares the loaded authority and rechecks revocation after pre-tool approval', async () => {+ const source = agent('always');+ const storage = store();+ const expected = resolveAgentToolGrantBinding(source, name, scope)!;+ await storage.rememberToolApprovalGrants(scope, [expected]);+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage });+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: 'allow',+ });+ const targetB = bindToolApproval({ ...source.toolDefinitions![0] }, 'source-b');+ await expect(+ session.validateExecution(targetB, { agentId: source.id, toolCallId: 'call-a' }),+ ).rejects.toThrow('changed');+ await storage.resetToolApprovalGrants(scope.userId, source.id, name);+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'call-a',+ }),+ ).rejects.toThrow('revoked');+});++test('unverified success hooks cannot teach consent', async () => {+ const source = agent('always');+ const binding = resolveAgentToolGrantBinding(source, name, scope)!;+ const storage = store();+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: {+ bindings: { 'call-a': binding },+ decisions: [{ tool_call_id: 'call-a', decision: 'approve' }],+ },+ });+ await session.hook(input(), new AbortController().signal);+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+});++test('always-ask cannot execute through an unreviewed inner invocation', async () => {+ const source = agent('ask');+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage: store() });+ await expect(+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'inner-call',+ }),+ ).rejects.toThrow('foreground');+});++test.each(['ask', 'deny'] as const)(+ 'the final boundary retains administrator %s over a learned grant',+ async (decision) => {+ const source = agent('always');+ const storage = store();+ await storage.rememberToolApprovalGrants(scope, [+ resolveAgentToolGrantBinding(source, name, scope)!,+ ]);+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ policy: () => ({ enabled: true, mode: 'bypass', [decision]: [name] }),+ });+ await session.hook(input('agent-a', 'inner-call'), new AbortController().signal);+ await expect(+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'inner-call',+ }),+ ).rejects.toThrow();+ },+);++test('an automatic mode cannot bypass a missing SDK policy evaluation', async () => {+ const source = agent('allow');+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage: store() });+ await expect(+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'inner-call',+ }),+ ).rejects.toThrow('policy could not be verified');+ await session.hook(input('agent-a', 'inner-call'), new AbortController().signal);+ await expect(+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'inner-call',+ }),+ ).resolves.toBeUndefined();+});++test('non-rememberable review is agent/tool bound and single-use', async () => {+ const source = agent('chat');+ const definition = bindToolApprovalIdentity(+ bindToolReviewAuthority(+ { name, serverName: 'db', parameters: { type: 'object' } },+ 'review-only-target',+ ),+ 'query',+ { type: 'object' },+ );+ source.toolDefinitions = [definition];+ const storage = store();+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings: {}, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(definition, { agentId: 'other-agent', toolCallId: 'call-a' }),+ ).rejects.toThrow();+ await expect(+ session.validateExecution(definition, { agentId: source.id, toolCallId: 'call-a' }),+ ).resolves.toBeUndefined();+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(definition, { agentId: source.id, toolCallId: 'call-a' }),+ ).rejects.toThrow('foreground');+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+});++test.each(['allow', 'chat', 'always'] as const)(+ 'parallel agents keep independent %s witnesses for the same provider call ID',+ async (mode) => {+ const sources = [agent(mode, 'agent-a'), agent(mode, 'agent-b')];+ const storage = store();+ if (mode !== 'allow') {+ await storage.rememberToolApprovalGrants(+ scope,+ sources.map((source) => resolveAgentToolGrantBinding(source, name, scope)!),+ );+ }+ const session = createAgentToolApprovalSession({ agents: sources, scope, storage });+ const decisions = await Promise.all(+ sources.map((source) =>+ session.hook(input(source.id, 'call_0'), new AbortController().signal),+ ),+ );+ expect(decisions).toEqual([{ decision: 'allow' }, { decision: 'allow' }]);+ await expect(+ Promise.all(+ sources.map((source) =>+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'call_0',+ }),+ ),+ ),+ ).resolves.toEqual([undefined, undefined]);+ },+);++test('colliding paused call IDs cannot choose another agent’s approval binding', async () => {+ const sources = [agent('chat', 'agent-a'), agent('chat', 'agent-b')];+ const session = createAgentToolApprovalSession({ agents: sources, scope, storage: store() });+ await Promise.all(+ sources.map((source) => session.hook(input(source.id, 'call_0'), new AbortController().signal)),+ );+ const payload = buildToolApprovalPayload([{ name, tool_call_id: 'call_0', arguments: {} }]);+ expect(session.bindingsFor(payload)).toEqual({});+ const childPayload = { ...payload, subagent: { agent_id: 'agent-a' } };+ expect(session.bindingsFor(childPayload)['call_0'].agentId).toBe('agent-a');+});++test('reviewed consent and success witnesses stay on the reviewed agent when call IDs collide', async () => {+ const a = agent('chat', 'agent-a');+ const b = agent('allow', 'agent-b');+ const binding = resolveAgentToolGrantBinding(a, name, scope)!;+ binding.revocation = 'epoch-a';+ const storage = store();+ const session = createAgentToolApprovalSession({+ agents: [a, b],+ scope,+ storage,+ reviewed: {+ bindings: { call_0: binding },+ decisions: [{ tool_call_id: 'call_0', decision: 'approve' }],+ },+ });+ await Promise.all([+ session.hook(input(a.id, 'call_0'), new AbortController().signal),+ session.hook(input(b.id, 'call_0'), new AbortController().signal),+ ]);+ await Promise.all([+ session.validateExecution(a.toolDefinitions![0], { agentId: a.id, toolCallId: 'call_0' }),+ session.validateExecution(b.toolDefinitions![0], { agentId: b.id, toolCallId: 'call_0' }),+ ]);+ await Promise.all(+ [a, b].map((source) =>+ session.rememberHook(+ { ...input(source.id, 'call_0'), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ ),+ ),+ );+ expect(storage.rememberToolApprovalGrants).toHaveBeenCalledTimes(1);+ expect(storage.rememberToolApprovalGrants).toHaveBeenCalledWith(scope, [binding]);+});++test('concurrent self-spawns retain separate witnesses and paused provenance', async () => {+ const source = agent('allow');+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage: store() });+ const childContext = (run: string) => ({+ rootRunId: 'root',+ hookSessionId: 'root',+ depth: 1,+ ancestry: [+ {+ subagentRunId: run,+ subagentType: 'worker',+ subagentKind: 'agent' as const,+ subagentAgentId: source.id,+ parentRunId: 'root',+ },+ ],+ });+ await Promise.all(+ ['child-a', 'child-b'].map((run) =>+ session.hook(+ {+ ...input(source.id, 'call_0'),+ executionContext: childContext(run),+ },+ new AbortController().signal,+ ),+ ),+ );++ const payload = {+ ...buildToolApprovalPayload([{ name, tool_call_id: 'call_0', arguments: {} }]),+ subagent: { agent_id: source.id, run_id: 'child-b' },+ };+ expect(session.bindingsFor(payload)['call_0'].executionScope).toBe('child-b');+ const graphPayload = { ...payload, subagent: { agent_id: 'synthetic-team', run_id: 'child-b' } };+ expect(session.bindingsFor(graphPayload)['call_0'].agentId).toBe(source.id);+ await expect(+ Promise.all(+ ['child-a', 'child-b'].map((executionScope) =>+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'call_0',+ executionScope,+ }),+ ),+ ),+ ).resolves.toEqual([undefined, undefined]);+});++test('rewritten arguments never select a colliding sibling’s original proposal', async () => {+ const sources = [agent('chat', 'agent-a'), agent('chat', 'agent-b')];+ const session = createAgentToolApprovalSession({ agents: sources, scope, storage: store() });+ await Promise.all(+ sources.map((source) =>+ session.hook(+ { ...input(source.id, 'call_0'), toolInput: { text: source.id } },+ new AbortController().signal,+ ),+ ),+ );+ const payload = buildToolApprovalPayload([+ { name, tool_call_id: 'call_0', arguments: { text: 'agent-b' } },+ ]);+ expect(session.bindingsFor(payload)).toEqual({});+ const attributed = { ...payload, subagent: { agent_id: 'agent-a' } };+ expect(session.bindingsFor(attributed)['call_0']?.agentId).toBe('agent-a');+});++test('actual background dispatch cannot teach from a synthetic success handle', async () => {+ const source = agent('chat');+ const storage = store();+ const binding = resolveAgentToolGrantBinding(source, name, scope)!;+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: {+ bindings: { 'call-a': binding },+ decisions: [{ tool_call_id: 'call-a', decision: 'approve' }],+ },+ });+ await session.hook(input(), new AbortController().signal);+ const invocation = { agentId: source.id, toolCallId: 'call-a', background: true };+ session.noteDispatch?.(invocation);+ await session.validateExecution(source.toolDefinitions![0], invocation);+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'Task launched' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ session.finishDispatch?.(invocation);+});++test('synthetic responses retire call candidates at the settled batch boundary', async () => {+ const a = agent('ask', 'agent-a');+ const b = agent('chat', 'agent-b');+ const session = createAgentToolApprovalSession({ agents: [a, b], scope, storage: store() });+ await session.hook(input(a.id, 'call_0'), new AbortController().signal);+ await session.settleBatchHook(+ {+ hook_event_name: 'PostToolBatch',+ runId: 'run-a',+ executingAgentId: a.id,+ entries: [+ {+ toolName: name,+ toolUseId: 'call_0',+ toolInput: {},+ status: 'success',+ toolOutput: 'synthetic',+ },+ ],+ },+ new AbortController().signal,+ );+ await session.hook(input(b.id, 'call_0'), new AbortController().signal);+ expect(+ session.bindingsFor(buildToolApprovalPayload([{ name, tool_call_id: 'call_0', arguments: {} }]))+ .call_0?.agentId,+ ).toBe(b.id);+});++test.each(['ask', 'allow', 'chat', 'always'] as const)(+ 'dev conversation allows preserve the executing agent’s %s mode',+ async (mode) => {+ const source = agent(mode);+ const storage = store();+ const policy = buildEffectiveToolApprovalPolicy(+ { enabled: true, mode: 'default', allowAlways: true },+ [],+ [name],+ );+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ policy: () => policy,+ });+ const wiring = buildHITLRunWiring(policy, {}, [], [{ hook: session.hook }])!;+ const before = await executeHooks({ registry: wiring.hooks, input: input(), matchQuery: name });+ expect(before.decision).toBe(mode === 'allow' ? 'allow' : 'ask');+ if (mode === 'chat' || mode === 'always') {+ await storage.rememberToolApprovalGrants(scope, [+ resolveAgentToolGrantBinding(source, name, scope)!,+ ]);+ const after = await executeHooks({+ registry: wiring.hooks,+ input: input('agent-a', 'next-call'),+ matchQuery: name,+ });+ expect(after.decision).toBe('allow');+ }+ },+);++test('a successful reviewed call cannot learn consent after its reset epoch changes', async () => {+ const source = agent('chat');+ const binding = { ...resolveAgentToolGrantBinding(source, name, scope)!, revocation: 'epoch-a' };+ const storage = store();+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: {+ bindings: { 'call-a': binding },+ decisions: [{ tool_call_id: 'call-a', decision: 'approve' }],+ },+ });+ await session.hook(input(), new AbortController().signal);+ await session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'call-a',+ });+ jest+ .spyOn(storage, 'getToolApprovalGrants')+ .mockResolvedValue([+ { binding: binding.binding, approved: false, revocation: 'epoch-b', oauthEpoch: null },+ ]);+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+});++for (const mode of ['ask', 'chat', 'always'] as const) {+ test.each(['approve', 'edit'] as const)(+ `${mode} non-rememberable %s cannot authorize detached execution`,+ async (decision) => {+ const source = agent(mode);+ const definition = bindToolApprovalIdentity(+ bindToolReviewAuthority(+ {+ name,+ serverName: 'db',+ parameters: { type: 'object' },+ },+ 'review-only-target',+ ),+ 'query',+ { type: 'object' },+ );+ source.toolDefinitions = [definition];+ const storage = store();+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision }] },+ });+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(definition, {+ agentId: source.id,+ toolCallId: 'call-a',+ background: true,+ }),+ ).rejects.toThrow('foreground review');+ // The refused background attempt did not consume the one foreground permission.+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(definition, { agentId: source.id, toolCallId: 'call-a' }),+ ).resolves.toBeUndefined();+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ },+ );+}++test('old detached completion cannot retire a newer reused provider ID or its transport witness', async () => {+ const source = agent('always');+ const storage = store();+ await storage.rememberToolApprovalGrants(scope, [+ resolveAgentToolGrantBinding(source, name, scope)!,+ ]);+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage });+ const old = { agentId: source.id, toolCallId: 'call_0', background: true };+ await session.hook(input(source.id, 'call_0'), new AbortController().signal);+ session.noteDispatch?.(old);+ await session.validateExecution(source.toolDefinitions![0], old);+ const newer = { agentId: source.id, toolCallId: 'call_0' };+ await session.hook(input(source.id, 'call_0'), new AbortController().signal);+ await session.validateExecution(source.toolDefinitions![0], newer);+ await expect(session.validateTransport!('db', 'account-b', newer, false)).rejects.toThrow(+ 'OAuth authorization changed',+ );+ session.finishDispatch?.(old);+ session.finishDispatch?.(old);+ await expect(session.validateTransport!('db', 'account-b', newer, false)).rejects.toThrow(+ 'OAuth authorization changed',+ );+ await expect(session.validateTransport!('db', null, newer, true)).resolves.toBeUndefined();+ await expect(session.validateTransport!('db', null, old, false)).rejects.toThrow(+ 'invocation could not be verified',+ );+});++test('an old detached call retains its pinned OAuth epoch while a newer call is reviewed', async () => {+ const source = agent('always');+ const storage = store();+ await storage.rememberToolApprovalGrants(scope, [+ resolveAgentToolGrantBinding(source, name, scope)!,+ ]);+ let epoch = 'account-a';+ jest+ .spyOn(storage, 'getToolApprovalGrants')+ .mockImplementation(async (_scope, grants) =>+ grants.map((grant) => ({ binding: grant.binding, approved: true, oauthEpoch: epoch })),+ );+ const session = createAgentToolApprovalSession({ agents: [source], scope, storage });+ const old = { agentId: source.id, toolCallId: 'call_0', background: true };+ await session.hook(input(source.id, 'call_0'), new AbortController().signal);+ session.noteDispatch?.(old);+ await session.validateExecution(source.toolDefinitions![0], old);+ epoch = 'account-b';+ const newer = { agentId: source.id, toolCallId: 'call_0' };+ await session.hook(input(source.id, 'call_0'), new AbortController().signal);+ await session.validateExecution(source.toolDefinitions![0], newer);+ await expect(session.validateTransport!('db', 'account-b', newer, true)).resolves.toBeUndefined();+ await expect(session.validateTransport!('db', 'account-b', old, false)).rejects.toThrow(+ 'OAuth authorization changed',+ );+ session.finishDispatch?.(old);+ await expect(session.validateTransport!('db', 'account-b', newer, true)).resolves.toBeUndefined();+});++test('registry reinspection metadata does not change learned tool authority', () => {+ const selected = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test',+ updatedAt: 1,+ initDuration: 4,+ tools: 'old summary',+ capabilities: 'old',+ resolvedInstructions: 'old',+ };+ const first = buildMCPToolApprovalBinding('db', selected);+ expect(first).toEqual(expect.any(String));+ expect(+ buildMCPToolApprovalBinding('db', {+ ...selected,+ updatedAt: 999,+ initDuration: 50,+ tools: 'new summary',+ capabilities: 'new',+ resolvedInstructions: 'new',+ inspectionFailed: false,+ }),+ ).toBe(first);+ expect(buildMCPToolApprovalBinding('db', { ...selected, source: 'config' })).not.toBe(first);+ expect(buildMCPToolApprovalBinding('db', { ...selected, dbId: 'another-source' })).not.toBe(+ first,+ );+ expect(+ buildMCPToolApprovalBinding('db', { ...selected, url: 'https://different.example.test' }),+ ).not.toBe(first);+});++test('a late successful execution cannot learn over a replacement consent binding', async () => {+ const source = agent('always');+ const storage = store();+ let consentBinding: string | null = null;+ jest.spyOn(storage, 'getToolApprovalGrants').mockImplementation(async (_scope, grants) =>+ grants.map((candidate) => ({+ binding: candidate.binding,+ approved: false,+ revocation: 'epoch-a',+ oauthEpoch: null,+ consentBinding,+ })),+ );+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ expect(bindings['call-a'].consentBinding).toBeNull();+ const resumed = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ await resumed.hook(input(), new AbortController().signal);+ await resumed.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'call-a',+ });+ consentBinding = 'replacement-authority';+ await resumed.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'successful old call' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+});++for (const mode of ['ask', 'allow', 'chat', 'always'] as const) {+ test.each(['unchanged', 'connection', 'schema', 'account'])(+ `${mode} captured approval cannot lose its fences by switching to inheritance; change=%s`,+ async (change) => {+ const original = agent(mode);+ const storage = store();+ const first = createAgentToolApprovalSession({ agents: [original], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ let definition = original.toolDefinitions![0];+ if (change === 'connection') {+ definition = bindFixture(+ { name, serverName: 'db', parameters: { type: 'object' } },+ 'source-b',+ );+ } else if (change === 'schema') {+ definition = bindFixture(+ { name, serverName: 'db', parameters: { type: 'object', description: 'changed schema' } },+ 'source-a',+ );+ }+ const inherited = {+ ...original,+ tool_options: { [name]: { defer_loading: true } },+ toolDefinitions: [definition],+ };+ if (change === 'account')+ jest+ .spyOn(storage, 'getToolApprovalGrants')+ .mockResolvedValue([+ { binding: bindings['call-a'].binding, approved: false, oauthEpoch: 'account-b' },+ ]);+ const session = createAgentToolApprovalSession({+ agents: [inherited],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: 'deny',+ });+ await expect(+ session.validateExecution(definition, { agentId: original.id, toolCallId: 'call-a' }),+ ).rejects.toThrow('configuration changed');+ await expect(session.validateExecution(definition, { toolCallId: 'call-a' })).rejects.toThrow(+ 'executing agent identity',+ );+ await expect(+ session.validateTransport!(+ 'db',+ 'account-b',+ { agentId: original.id, toolCallId: 'call-a' },+ false,+ ),+ ).rejects.toThrow('invocation could not be verified');+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ },+ );+}++test('fresh inherited calls without captured approvals preserve the baseline', async () => {+ const inherited = { ...agent('ask'), tool_options: undefined };+ const session = createAgentToolApprovalSession({ agents: [inherited], scope, storage: store() });+ expect(await session.hook(input(), new AbortController().signal)).toEqual({});+ await expect(+ session.validateExecution(inherited.toolDefinitions![0], {+ agentId: inherited.id,+ toolCallId: 'fresh',+ }),+ ).resolves.toBeUndefined();+ await expect(+ session.validateTransport!('db', null, { agentId: inherited.id, toolCallId: 'fresh' }, false),+ ).resolves.toBeUndefined();+});++test('a fresh inherited call with a reused ID retires only the old detached proposal', async () => {+ const original = agent('chat');+ const storage = store();+ const first = createAgentToolApprovalSession({ agents: [original], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ const session = createAgentToolApprovalSession({+ agents: [original],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ await session.hook(input(), new AbortController().signal);+ const detached = { agentId: original.id, toolCallId: 'call-a', background: true };+ await session.validateExecution(original.toolDefinitions![0], detached);+ session.addAgent({ ...original, tool_options: undefined });+ expect(await session.hook(input(), new AbortController().signal)).toEqual({});+ const fresh = { agentId: original.id, toolCallId: 'call-a' };+ await expect(+ session.validateExecution(original.toolDefinitions![0], fresh),+ ).resolves.toBeUndefined();+ await expect(session.validateTransport!('db', null, detached, true)).resolves.toBeUndefined();+ await expect(session.validateTransport!('db', null, fresh, true)).resolves.toBeUndefined();+ session.finishDispatch!(detached);+ await expect(session.validateTransport!('db', null, detached, false)).rejects.toThrow(+ 'invocation could not be verified',+ );+ await expect(session.validateTransport!('db', null, fresh, false)).resolves.toBeUndefined();+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+});++for (const mode of ['ask', 'chat', 'always'] as const) {+ test.each(['pause-outage', 'invoke-outage', 'recovered', 'timeout'] as const)(+ `${mode} explicit non-OAuth foreground consent survives grant-store %s without learning`,+ async (stage) => {+ const source = agent(mode);+ const definition = source.toolDefinitions![0];+ bindToolApproval(definition, 'source-a', undefined, undefined, undefined, 'other');+ const storage = store();+ const healthy = storage.getToolApprovalGrants;+ let unavailable = stage !== 'invoke-outage';+ if (stage === 'timeout') jest.useFakeTimers();+ storage.getToolApprovalGrants = jest.fn(async (...args) => {+ if (!unavailable) return healthy(...args);+ if (stage === 'timeout') return new Promise(() => {});+ throw new Error('synthetic grant-store outage');+ });+ const wait = async <T>(promise: T | Promise<T>): Promise<T> => {+ if (stage === 'timeout') await jest.advanceTimersByTimeAsync(20);+ return promise;+ };+ try {+ const first = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ lookupTimeoutMs: 20,+ });+ expect(await wait(first.hook(input(), new AbortController().signal))).toMatchObject({+ decision: 'ask',+ });+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ expect(bindings['call-a'].oauthEpoch).toBeNull();+ if (stage !== 'invoke-outage')+ expect(bindings['call-a']).toMatchObject({ canRemember: false, unavailable: 'storage' });+ if (stage === 'recovered') unavailable = false;+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ lookupTimeoutMs: 20,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ expect(await wait(session.hook(input(), new AbortController().signal))).not.toMatchObject({+ decision: 'deny',+ });+ if (stage === 'invoke-outage') unavailable = true;+ const invocation = { agentId: source.id, toolCallId: 'call-a' };+ await expect(+ wait(session.validateExecution(definition, invocation)),+ ).resolves.toBeUndefined();+ unavailable = false;+ await expect(+ session.validateTransport!('db', null, invocation, true),+ ).resolves.toBeUndefined();+ await expect(session.validateTransport!('other', null, invocation, false)).rejects.toThrow(+ 'authorization changed',+ );+ await expect(+ session.validateTransport!('db', 'new-account', invocation, false),+ ).rejects.toThrow('authorization changed');+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ expect(+ await wait(session.hook(input('agent-a', 'later'), new AbortController().signal)),+ ).toMatchObject({ decision: 'ask' });+ } finally {+ if (stage === 'timeout') jest.useRealTimers();+ }+ },+ );+}++for (const authKind of ['oauth', undefined] as const) {+ test(`an outage cannot authorize unknown or OAuth identity (${authKind})`, async () => {+ const source = agent('chat');+ bindToolApproval(+ source.toolDefinitions![0],+ 'source-a',+ undefined,+ undefined,+ undefined,+ authKind,+ );+ const storage = store();+ storage.getToolApprovalGrants = async () => {+ throw new Error('synthetic outage');+ };+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(source.toolDefinitions![0], {+ agentId: source.id,+ toolCallId: 'call-a',+ }),+ ).rejects.toThrow('authorization changed');+ });+}++test.each(['approve', 'edit'] as const)(+ 'outage fallback is foreground-only for %s and cannot be used without a captured review',+ async (decision) => {+ const source = agent('chat');+ const definition = source.toolDefinitions![0];+ bindToolApproval(definition, 'source-a', undefined, undefined, undefined, 'other');+ const storage = store();+ storage.getToolApprovalGrants = async () => {+ throw new Error('synthetic outage');+ };+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ await expect(+ first.validateExecution(definition, { agentId: source.id, toolCallId: 'call-a' }),+ ).rejects.toThrow('authorization changed');+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision }] },+ });+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(definition, {+ agentId: source.id,+ toolCallId: 'call-a',+ background: true,+ }),+ ).rejects.toThrow('authorization changed');+ await session.hook(input(), new AbortController().signal);+ await expect(+ session.validateExecution(definition, { agentId: source.id, toolCallId: 'call-a' }),+ ).resolves.toBeUndefined();+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ },+);++for (const mode of ['chat', 'always'] as const) {+ test.each(['approve', 'edit'] as const)(+ `${mode} resume-only outage stays ineligible after repeated healthy hooks and %s`,+ async (decision) => {+ const source = agent(mode);+ const definition = source.toolDefinitions![0];+ bindToolApproval(definition, 'source-a', undefined, undefined, undefined, 'other');+ const storage = store();+ const realLookup = storage.getToolApprovalGrants;+ let unavailable = false;+ storage.getToolApprovalGrants = jest.fn(async (...args) => {+ if (unavailable) throw new Error('synthetic resumed outage');+ return realLookup(...args);+ });+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ expect(bindings['call-a'].canRemember).toBe(true);+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision }] },+ });+ unavailable = true;+ await session.hook(input(), new AbortController().signal);+ expect(+ session.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ )['call-a'],+ ).toMatchObject({ canRemember: false, unavailable: 'storage' });+ unavailable = false;+ await session.hook(input(), new AbortController().signal);+ await session.hook(input(), new AbortController().signal);+ const invocation = { agentId: source.id, toolCallId: 'call-a' };+ await expect(session.validateExecution(definition, invocation)).resolves.toBeUndefined();+ await expect(+ session.validateTransport!('db', null, invocation, true),+ ).resolves.toBeUndefined();+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ expect(bindings['call-a'].canRemember).toBe(true);+ expect(await session.hook(input(), new AbortController().signal)).toMatchObject({+ decision: 'ask',+ });+ const renewed = session.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ expect(renewed['call-a'].canRemember).toBe(true);+ const fresh = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: {+ bindings: renewed,+ decisions: [{ tool_call_id: 'call-a', decision: 'approve' }],+ },+ });+ await fresh.hook(input(), new AbortController().signal);+ await fresh.validateExecution(definition, { agentId: source.id, toolCallId: 'call-a' });+ await fresh.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).toHaveBeenCalledTimes(1);+ },+ );+}++for (const mode of ['ask', 'chat', 'always', 'allow'] as const) {+ test.each(['approve', 'edit'] as const)(+ `${mode} verified manual %s transport outage downgrades once and never learns after recovery`,+ async (decision) => {+ const source = agent(mode);+ const tool = source.toolDefinitions![0];+ bindToolApproval(tool, 'source-a', undefined, undefined, undefined, 'other');+ const storage = store();+ const lookup = storage.getToolApprovalGrants;+ let unavailable = false;+ storage.getToolApprovalGrants = jest.fn(async (...args) => {+ if (unavailable) throw new Error('synthetic before-send outage');+ return lookup(...args);+ });+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision }] },+ });+ await session.hook(input(), new AbortController().signal);+ const invocation = { agentId: source.id, toolCallId: 'call-a' };+ await session.validateExecution(tool, invocation);+ await session.validateTransport!('db', null, invocation, true);+ unavailable = true;+ await expect(+ session.validateTransport!('db', null, invocation, true),+ ).resolves.toBeUndefined();+ await expect(session.validateTransport!('other', null, invocation, true)).rejects.toThrow(+ 'authorization changed',+ );+ await expect(+ session.validateTransport!('db', 'replacement-account', invocation, true),+ ).rejects.toThrow('authorization changed');+ unavailable = false;+ const lookups = (storage.getToolApprovalGrants as jest.Mock).mock.calls.length;+ await session.validateTransport!('db', null, invocation, true);+ expect(storage.getToolApprovalGrants).toHaveBeenCalledTimes(lookups);+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ expect(+ await session.hook(input('agent-a', 'later'), new AbortController().signal),+ ).toMatchObject({ decision: mode === 'allow' ? 'allow' : 'ask' });+ },+ );+}++for (const mode of ['chat', 'always'] as const) {+ test.each(['oauth', 'unknown', 'background', 'automatic'] as const)(+ `${mode} transport storage failure cannot downgrade %s authority`,+ async (kind) => {+ const source = agent(mode);+ const tool = source.toolDefinitions![0];+ if (kind !== 'unknown')+ bindToolApproval(+ tool,+ 'source-a',+ undefined,+ undefined,+ undefined,+ kind === 'oauth' ? 'oauth' : 'other',+ );+ const storage = store();+ const lookup = storage.getToolApprovalGrants;+ let unavailable = false;+ storage.getToolApprovalGrants = async (...args) => {+ if (unavailable) throw new Error('synthetic transport outage');+ return lookup(...args);+ };+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ if (kind === 'automatic')+ await storage.rememberToolApprovalGrants(scope, [bindings['call-a']]);+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed:+ kind === 'automatic'+ ? undefined+ : { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ await session.hook(input(), new AbortController().signal);+ const invocation = {+ agentId: source.id,+ toolCallId: 'call-a',+ background: kind === 'background',+ };+ await session.validateExecution(tool, invocation);+ unavailable = true;+ await expect(session.validateTransport!('db', null, invocation, true)).rejects.toThrow(+ 'authorization changed',+ );+ },+ );+}++test('transport-time outage cannot restore a retired manual foreground witness', async () => {+ const source = agent('chat');+ const tool = source.toolDefinitions![0];+ bindToolApproval(tool, 'source-a', undefined, undefined, undefined, 'other');+ const storage = store();+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ await session.hook(input(), new AbortController().signal);+ const invocation = { agentId: source.id, toolCallId: 'call-a' };+ await session.validateExecution(tool, invocation);+ let release!: () => void;+ let started!: () => void;+ const began = new Promise<void>((resolve) => {+ started = resolve;+ });+ storage.getToolApprovalGrants = async () => {+ started();+ await new Promise<void>((resolve) => {+ release = resolve;+ });+ throw new Error('synthetic late transport outage');+ };+ const result = session.validateTransport!('db', null, invocation, true).then(+ () => null,+ (error: Error) => error,+ );+ await began;+ await session.settleBatchHook(+ {+ hook_event_name: 'PostToolBatch',+ runId: 'test',+ executingAgentId: source.id,+ entries: [+ {+ toolName: name,+ toolUseId: 'call-a',+ toolInput: {},+ toolOutput: 'settled',+ status: 'success',+ },+ ],+ },+ new AbortController().signal,+ );+ release();+ expect(await result).toMatchObject({ message: expect.stringContaining('invocation changed') });+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+});++test('verified one-time transport consent survives a bounded grant lookup timeout without learning', async () => {+ const source = agent('chat');+ const tool = source.toolDefinitions![0];+ bindToolApproval(tool, 'source-a', undefined, undefined, undefined, 'other');+ const storage = store();+ const first = createAgentToolApprovalSession({ agents: [source], scope, storage });+ await first.hook(input(), new AbortController().signal);+ const bindings = first.bindingsFor(+ buildToolApprovalPayload([{ name, tool_call_id: 'call-a', arguments: {} }]),+ );+ const session = createAgentToolApprovalSession({+ agents: [source],+ scope,+ storage,+ lookupTimeoutMs: 20,+ reviewed: { bindings, decisions: [{ tool_call_id: 'call-a', decision: 'approve' }] },+ });+ await session.hook(input(), new AbortController().signal);+ const invocation = { agentId: source.id, toolCallId: 'call-a' };+ await session.validateExecution(tool, invocation);+ storage.getToolApprovalGrants = async () => new Promise(() => {});+ jest.useFakeTimers();+ try {+ const result = session.validateTransport!('db', null, invocation, true);+ await jest.advanceTimersByTimeAsync(20);+ await expect(result).resolves.toBeUndefined();+ await session.rememberHook(+ { ...input(), hook_event_name: 'PostToolUse', toolOutput: 'success' },+ new AbortController().signal,+ );+ expect(storage.rememberToolApprovalGrants).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+});diff --git a/packages/api/src/agents/hitl/modes.ts b/packages/api/src/agents/hitl/modes.tsnew file mode 100644index 0000000000..cb5f115bea--- /dev/null+++ b/packages/api/src/agents/hitl/modes.ts@@ -0,0 +1,814 @@+import { createToolPolicyHook } from '@librechat/agents';+import { digestMCPAuthorityValue, logger } from '@librechat/data-schemas';+import type {+ AgentToolOptions,+ ToolApprovalGrantStorage,+ ToolApprovalGrantScope,+ ToolApprovalGrantBinding,+ Agents,+} from 'librechat-data-provider';+import type { ToolApprovalAuthKind } from 'librechat-data-provider';+import type { TToolApprovalPolicy } from 'librechat-data-provider';+import type { HookCallback } from '@librechat/agents';+import type { Run, IState } from '@librechat/agents';+import type { ToolApprovalExecution } from '~/tools/approval';+import type { ParsedServerConfig } from '~/mcp/types';+import { bindToolApproval, getToolApprovalBinding, getToolApprovalName } from '~/tools/approval';+import { withToolApprovalExecution, getToolApprovalIdentity } from '~/tools/approval';+import { bindToolReviewAuthority, getToolReviewAuthority } from '~/tools/approval';+import { getToolApprovalExecutionScope } from '~/tools/approval';+import { requiresEphemeralUserConnection } from '~/mcp/utils';+import { projectMCPApprovalAuthority } from '~/mcp/approval';+import { getToolApprovalAuthKind } from '~/tools/approval';+import { mapToolApprovalPolicy } from './policy';++export interface AgentApprovalDefinition {+ name: string;+ description?: string;+ parameters?: object;+ serverName?: string;+}++export interface AgentApprovalSource {+ id: string;+ tool_options?: AgentToolOptions;+ toolDefinitions?: AgentApprovalDefinition[];+}++/** A changed connection, raw schema, mode or revision requires fresh consent. */+export function buildMCPToolApprovalBinding(+ serverName: string,+ config: ParsedServerConfig | undefined,+): string | undefined {+ if (config) config = projectMCPApprovalAuthority(config);+ if (+ !config ||+ requiresEphemeralUserConnection(config) ||+ /\{\{[^{}]+\}\}|\$\{[^{}]+\}/.test(JSON.stringify(config))+ )+ return undefined;+ return digestMCPAuthorityValue({ serverName, config });+}++export function attachMCPToolApprovalBindings(+ definitions: AgentApprovalDefinition[],+ bindings: ReadonlyMap<string, string | undefined>,+ reviewAuthorities?: ReadonlyMap<string, string | undefined>,+ authKinds?: ReadonlyMap<string, ToolApprovalAuthKind | undefined>,+): void {+ for (const definition of definitions) {+ if (!definition.serverName) continue;+ bindToolApproval(+ definition,+ bindings.get(definition.serverName),+ undefined,+ undefined,+ undefined,+ authKinds?.get(definition.serverName),+ );+ bindToolReviewAuthority(definition, reviewAuthorities?.get(definition.serverName));+ }+}++export function resolveAgentToolGrantBinding(+ agent: AgentApprovalSource,+ toolName: string,+ scope: ToolApprovalGrantScope,+ executingTool?: AgentApprovalDefinition,+): ToolApprovalGrantBinding | undefined {+ const options = agent.tool_options?.[toolName];+ if (+ options?.approval_mode == null ||+ ((options.approval_mode === 'chat' || options.approval_mode === 'always') &&+ options.approval_revision == null)+ )+ return undefined;+ const definition = executingTool ?? agent.toolDefinitions?.find((tool) => tool.name === toolName);+ if (!definition) return undefined;+ const sourceBinding = getToolApprovalBinding(definition);+ const identity = getToolApprovalIdentity(definition);+ if (!sourceBinding || !identity) return undefined;+ const canonicalName = getToolApprovalName(definition) ?? toolName;+ return {+ canRemember: options.approval_mode === 'chat' || options.approval_mode === 'always',+ instanceName: toolName,+ serverName: definition.serverName,+ authKind: getToolApprovalAuthKind(definition),+ oauthEpoch: null,+ agentId: agent.id,+ toolName: canonicalName,+ scope:+ options.approval_mode === 'ask' || options.approval_mode === 'allow'+ ? 'once'+ : options.approval_mode,+ binding: digestMCPAuthorityValue({+ userId: scope.userId,+ tenantId: scope.tenantId ?? null,+ agentId: agent.id,+ toolName: canonicalName,+ revision: options.approval_revision,+ mode: options.approval_mode,+ source: sourceBinding,+ authKind: getToolApprovalAuthKind(definition),+ identity,+ }),+ };+}++function approvalCallKey(+ agentId: string | undefined,+ callId: string,+ executionScope?: string,+): string {+ return JSON.stringify([agentId ?? null, executionScope ?? null, callId]);+}++/** Non-rememberable reviews still retain the executing agent and upstream identity. */+function resolveToolReviewBinding(+ agent: AgentApprovalSource,+ toolName: string,+ scope: ToolApprovalGrantScope,+): ToolApprovalGrantBinding | undefined {+ const grant = resolveAgentToolGrantBinding(agent, toolName, scope);+ if (grant) return grant;+ const definition = agent.toolDefinitions?.find((tool) => tool.name === toolName);+ if (!definition || !getToolReviewAuthority(definition)) return undefined;+ return {+ instanceName: toolName,+ serverName: definition.serverName,+ authKind: getToolApprovalAuthKind(definition),+ oauthEpoch: null,+ agentId: agent.id,+ toolName: getToolApprovalName(definition) ?? toolName,+ scope: 'once',+ canRemember: false,+ unavailable: 'connection',+ binding: digestMCPAuthorityValue({+ ...scope,+ agentId: agent.id,+ toolName,+ identity: getToolApprovalIdentity(definition),+ authority: getToolReviewAuthority(definition),+ authKind: getToolApprovalAuthKind(definition),+ mode: agent.tool_options?.[toolName]?.approval_mode,+ revision: agent.tool_options?.[toolName]?.approval_revision,+ }),+ };+}++export interface AgentToolApprovalSession extends ToolApprovalExecution {+ hook: HookCallback<'PreToolUse'>;+ rememberHook: HookCallback<'PostToolUse'>;+ settleBatchHook: HookCallback<'PostToolBatch'>;+ addAgent: (agent: AgentApprovalSource) => void;+ unavailableFor: (callId: string, toolName: string) => ToolApprovalGrantBinding['unavailable'];+ bindingsFor: (+ payload: Agents.ToolApprovalInterruptPayload,+ ) => Record<string, ToolApprovalGrantBinding>;+}++/** Coalesce parallel lookups at the invocation boundary; do not cache revocable grants. */+export function createAgentToolApprovalSession({+ agents,+ scope,+ storage,+ authorizationStorage = storage,+ lookupTimeoutMs = 3000,+ reviewed,+ policy,+}: {+ lookupTimeoutMs?: number;+ reviewed?: ReviewedToolApprovals;+ policy?: () => TToolApprovalPolicy;+ agents: readonly AgentApprovalSource[];+ scope?: ToolApprovalGrantScope;+ storage?: ToolApprovalGrantStorage;+ authorizationStorage?: Pick<ToolApprovalGrantStorage, 'getToolApprovalGrants'>;+}): AgentToolApprovalSession {+ const owners = new Map(agents.map((agent) => [agent.id, agent]));+ const calls = new Map<string, ToolApprovalGrantBinding | null>();+ const unavailable = new Map<string, ToolApprovalGrantBinding['unavailable']>();+ const reviewedBindings = new Map<string, ToolApprovalGrantBinding>();+ const learningDisabled = new Set<string>();+ for (const [callId, binding] of Object.entries(reviewed?.bindings ?? {})) {+ const key = approvalCallKey(binding.agentId, callId, binding.executionScope);+ reviewedBindings.set(key, binding);+ if (binding.canRemember !== true) learningDisabled.add(key);+ }+ const approvedDecisions = new Set<string>();+ const permittedDecisions = new Set<string>();+ const legacyDecisions = new Map<string, Agents.ToolApprovalDecisionType>();+ for (const decision of reviewed?.decisions ?? []) {+ const binding = reviewed?.bindings?.[decision.tool_call_id];+ if (!binding) {+ legacyDecisions.set(decision.tool_call_id, decision.decision);+ continue;+ }+ const key = approvalCallKey(binding.agentId, decision.tool_call_id, binding.executionScope);+ if (decision.decision === 'approve') approvedDecisions.add(key);+ if (decision.decision === 'approve' || decision.decision === 'edit')+ permittedDecisions.add(key);+ }+ const callOwners = new Map<string, Set<string>>();+ const proposals = new Map<+ string,+ {+ agentId: string;+ callId: string;+ toolName: string;+ executionScope?: string;+ dispatched: boolean;+ ownership: symbol;+ }+ >();+ const callCandidates = (callId: string, toolName: string): string[] =>+ Array.from(callOwners.get(callId) ?? []).filter(+ (key) => proposals.get(key)?.toolName === toolName && proposals.get(key)?.dispatched !== true,+ );+ const ready = new Map<string, ToolApprovalGrantBinding>();+ const executed = new Set<string>();+ // Lost learning eligibility never recovers within the same invocation.+ const disableLearning = (key: string): void => {+ learningDisabled.add(key);+ ready.delete(key);+ executed.delete(key);+ };++ const policyChecks = new Map<string, { agentId: string; toolName: string }>();+ const dispositions = new Map<string, boolean>();+ const transportWitnesses = new Map<+ symbol,+ {+ consent?: ToolApprovalGrantBinding;+ automatic: boolean;+ reviewOnly?: boolean;+ oneTimeFallback?: boolean;+ }+ >();+ const retireCall = (key: string, ownership?: symbol, keepTransport = false): void => {+ const proposal = proposals.get(key);+ if (ownership && proposal?.ownership !== ownership) return;+ if (!keepTransport && proposal) transportWitnesses.delete(proposal.ownership);+ if (proposal) {+ const candidates = callOwners.get(proposal.callId);+ candidates?.delete(key);+ if (candidates?.size === 0) callOwners.delete(proposal.callId);+ }+ proposals.delete(key);+ calls.delete(key);+ unavailable.delete(key);+ ready.delete(key);+ executed.delete(key);+ policyChecks.delete(key);+ dispositions.delete(key);+ reviewedBindings.delete(key);+ learningDisabled.delete(key);+ approvedDecisions.delete(key);+ permittedDecisions.delete(key);+ };+ type GrantStatus = {+ binding: string;+ approved: boolean;+ revocation?: string;+ oauthEpoch?: string | null;+ consentBinding?: string | null;+ available?: boolean;+ };+ let pending: Array<{ grant: ToolApprovalGrantBinding; resolve: (status: GrantStatus) => void }> =+ [];+ let scheduled = false;+ const approved = (grant: ToolApprovalGrantBinding): Promise<GrantStatus> =>+ new Promise((resolve) => {+ const timer = setTimeout(+ () => resolve({ binding: grant.binding, approved: false, available: false }),+ lookupTimeoutMs,+ );+ pending.push({+ grant,+ resolve: (status) => {+ clearTimeout(timer);+ resolve(status);+ },+ });+ if (scheduled) return;+ scheduled = true;+ queueMicrotask(() => {+ const batch = pending;+ pending = [];+ scheduled = false;+ const decline = () => {+ for (const item of batch)+ item.resolve({ binding: item.grant.binding, approved: false, available: false });+ };+ if (!authorizationStorage || !scope) {+ decline();+ return;+ }+ void authorizationStorage+ .getToolApprovalGrants(+ scope,+ batch.map((item) => item.grant),+ )+ .then((grants) => {+ const statuses = new Map(grants.map((status) => [status.binding, status]));+ for (const item of batch)+ item.resolve(+ statuses.get(item.grant.binding) ?? {+ binding: item.grant.binding,+ approved: false,+ },+ );+ }, decline);+ });+ });+ return {+ addAgent: (agent) => {+ owners.set(agent.id, agent);+ },+ unavailableFor: (callId, toolName) => {+ const candidates = callCandidates(callId, toolName);+ return candidates.length === 1 ? unavailable.get(candidates[0]) : undefined;+ },+ noteDispatch(invocation) {+ if (!invocation.toolCallId) return;+ const key = approvalCallKey(+ invocation.agentId,+ invocation.toolCallId,+ invocation.executionScope,+ );+ const proposal = proposals.get(key);+ if (invocation.ownership && invocation.ownership !== proposal?.ownership) {+ throw new Error('Tool approval invocation ownership changed. Request approval again.');+ }+ invocation.ownership = proposal?.ownership;+ if (proposal) proposal.dispatched = true;+ dispositions.set(key, invocation.background === true);+ if (invocation.background === true) {+ ready.delete(key);+ executed.delete(key);+ }+ },+ finishDispatch(invocation) {+ if (invocation.background !== true || !invocation.toolCallId || !invocation.ownership) return;+ transportWitnesses.delete(invocation.ownership);+ retireCall(+ approvalCallKey(invocation.agentId, invocation.toolCallId, invocation.executionScope),+ invocation.ownership,+ );+ },+ async settleBatchHook(input) {+ const executionScope = getToolApprovalExecutionScope(input.executionContext);+ for (const entry of input.entries) {+ const key = approvalCallKey(input.executingAgentId, entry.toolUseId, executionScope);+ if (dispositions.get(key) !== true) retireCall(key);+ }+ return {};+ },+ bindingsFor(payload) {+ const result: Record<string, ToolApprovalGrantBinding> = {};+ for (const request of payload.action_requests) {+ const subagent = (+ payload as Agents.ToolApprovalInterruptPayload & {+ subagent?: { agent_id?: string; run_id?: string };+ }+ ).subagent;+ const ownerHint =+ subagent?.agent_id && owners.has(subagent.agent_id) ? subagent.agent_id : undefined;+ const candidates = callCandidates(request.tool_call_id, request.name).filter((key) => {+ const proposal = proposals.get(key)!;+ return (+ (ownerHint == null || proposal.agentId === ownerHint) &&+ (subagent?.run_id == null || proposal.executionScope === subagent.run_id)+ );+ });+ // The SDK binds finalized arguments. Owner/lineage must still identify exactly one call.+ if (candidates.length !== 1) continue;+ const binding = calls.get(candidates[0]);+ if (binding?.instanceName !== request.name) continue;+ const argumentsValue =+ typeof request.arguments === 'object' ? request.arguments : undefined;+ result[request.tool_call_id] =+ argumentsValue?.run_in_background === true+ ? { ...binding, canRemember: false, unavailable: 'background' }+ : binding;+ }+ return result;+ },+ async validateExecution(tool, invocation) {+ const owner = invocation.agentId == null ? undefined : owners.get(invocation.agentId);+ if (+ !owner &&+ (reviewedBindings.size > 0 ||+ Array.from(owners.values()).some((agent) =>+ ['ask', 'chat', 'always'].includes(+ agent.tool_options?.[tool.name]?.approval_mode ?? '',+ ),+ ))+ ) {+ throw new Error('MCP approval requires the executing agent identity.');+ }+ const options = owner?.tool_options?.[tool.name];+ const callId = invocation.toolCallId;+ const key = approvalCallKey(invocation.agentId, callId ?? '', invocation.executionScope);+ if (options?.approval_mode == null) {+ if (reviewedBindings.has(key)) {+ throw new Error(+ 'The reviewed tool approval configuration changed. Request approval again.',+ );+ }+ return;+ }+ const check = callId && policyChecks.get(key);+ if (!check || check.agentId !== owner?.id || check.toolName !== tool.name) {+ throw new Error('Tool policy could not be verified. Run this tool in the foreground.');+ }+ const proposal = proposals.get(key);+ if (!proposal || (invocation.ownership && invocation.ownership !== proposal.ownership)) {+ throw new Error('Tool approval invocation ownership changed. Request approval again.');+ }+ invocation.ownership = proposal.ownership;+ const pinTransport = (+ consent?: ToolApprovalGrantBinding,+ automatic = false,+ reviewOnly = false,+ oneTimeFallback = false,+ ) => {+ if (proposals.get(key)?.ownership !== invocation.ownership) {+ throw new Error('Tool approval invocation ownership changed. Request approval again.');+ }+ proposal.dispatched = true;+ transportWitnesses.set(proposal.ownership, {+ consent: consent && { ...consent },+ automatic,+ reviewOnly,+ oneTimeFallback,+ });+ };+ policyChecks.delete(key);+ dispositions.set(key, invocation.background === true);+ if (invocation.background === true) {+ ready.delete(key);+ executed.delete(key);+ }+ const initialized = owner?.toolDefinitions?.find(+ (definition) => definition.name === tool.name,+ );+ const expectedIdentity = initialized && getToolApprovalIdentity(initialized);+ const actualIdentity = getToolApprovalIdentity(tool);+ const expectedSource = initialized && getToolApprovalBinding(initialized);+ const expectedAuthority = initialized && getToolReviewAuthority(initialized);+ if (+ (expectedIdentity != null && actualIdentity !== expectedIdentity) ||+ (initialized != null &&+ getToolApprovalAuthKind(tool) !== getToolApprovalAuthKind(initialized)) ||+ (expectedSource != null && getToolApprovalBinding(tool) !== expectedSource) ||+ (expectedAuthority != null && getToolReviewAuthority(tool) !== expectedAuthority)+ ) {+ throw new Error('The advertised MCP tool or connection changed. Retry the run.');+ }+ const baseline = policy+ ? await createToolPolicyHook(mapToolApprovalPolicy(policy()) ?? {})(+ {+ hook_event_name: 'PreToolUse',+ runId: '',+ executingAgentId: owner?.id,+ toolName: tool.name,+ toolInput: {},+ toolUseId: callId ?? '',+ },+ new AbortController().signal,+ )+ : undefined;+ if (baseline?.decision === 'deny') throw new Error('Administrator policy blocks this tool.');+ if (+ options.approval_mode === 'allow' &&+ baseline?.decision !== 'ask' &&+ !reviewedBindings.has(key)+ ) {+ pinTransport(undefined, true);+ return;+ }+ const consent = calls.get(key);+ const current = consent && (await approved(consent));+ const manual = reviewedBindings.get(key);+ if (+ consent?.canRemember !== true ||+ current?.available === false ||+ current?.oauthEpoch === undefined+ )+ disableLearning(key);+ // Grant-store availability is not one-time authority for verified non-OAuth calls.+ const oneTimeFallback =+ invocation.background !== true &&+ manual?.authKind === 'other' &&+ consent?.authKind === 'other' &&+ getToolApprovalAuthKind(tool) === 'other' &&+ actualIdentity != null &&+ getToolReviewAuthority(tool) != null &&+ manual.binding === consent.binding &&+ manual.oauthEpoch === null &&+ consent.oauthEpoch === null &&+ permittedDecisions.has(key);+ const reviewOnly = oneTimeFallback && learningDisabled.has(key);+ if (+ !reviewOnly &&+ (!current ||+ current.available === false ||+ current.oauthEpoch === undefined ||+ current.oauthEpoch !== consent?.oauthEpoch)+ ) {+ throw new Error('The MCP OAuth authorization changed. Request approval again.');+ }+ const expected = owner && scope && resolveAgentToolGrantBinding(owner, tool.name, scope);+ if (!expected) {+ if (invocation.background === true) {+ throw new Error(+ 'This MCP connection requires foreground review. Run the tool without background execution.',+ );+ }+ // Unresolvable connections cannot learn consent. Only a reviewed SDK call may execute.+ const reviewTarget = owner && scope && resolveToolReviewBinding(owner, tool.name, scope);+ if (callId && reviewTarget && calls.has(key) && permittedDecisions.has(key)) {+ permittedDecisions.delete(key);+ pinTransport(consent ?? undefined, false, reviewOnly, oneTimeFallback);+ return;+ }+ throw new Error('Tool approval is required. Run this tool in the foreground for review.');+ }+ const actual = resolveAgentToolGrantBinding(owner!, tool.name, scope!, tool);+ if (actual?.binding !== expected.binding || !callId) {+ if (callId) ready.delete(key);+ throw new Error('The approved MCP tool or connection changed. Request approval again.');+ }+ if (manual && permittedDecisions.has(key) && manual.binding === actual.binding) {+ permittedDecisions.delete(key);+ if (+ invocation.background !== true &&+ manual.canRemember === true &&+ !learningDisabled.has(key) &&+ approvedDecisions.has(key)+ )+ executed.add(key);+ pinTransport(consent ?? undefined, false, reviewOnly, oneTimeFallback);+ return;+ }+ if (expected.scope === 'once' || baseline?.decision === 'ask') {+ throw new Error('Tool approval is required. Run this tool in the foreground for review.');+ }+ if (!current?.approved || !storage) {+ ready.delete(key);+ throw new Error('Tool approval is required or was revoked. Request approval again.');+ }+ pinTransport(consent ?? undefined);+ },+ async validateTransport(serverName, oauthEpoch, invocation, checkStorage) {+ const witness = invocation.ownership && transportWitnesses.get(invocation.ownership);+ if (!witness) {+ const key = approvalCallKey(+ invocation.agentId,+ invocation.toolCallId ?? '',+ invocation.executionScope,+ );+ if (invocation.ownership || reviewedBindings.has(key)) {+ throw new Error(+ 'Tool approval invocation could not be verified before transport dispatch.',+ );+ }+ return;+ }+ if (witness.automatic) return;+ const consent = witness.consent;+ if (!consent)+ throw new Error('Tool approval consent is unavailable before transport dispatch.');+ if (consent.serverName !== serverName || consent.oauthEpoch !== oauthEpoch) {+ throw new Error(+ 'The approved MCP OAuth authorization changed before transport dispatch. Request approval again.',+ );+ }+ if (checkStorage && !witness.reviewOnly) {+ const current = await approved(consent);+ if (!invocation.ownership || transportWitnesses.get(invocation.ownership) !== witness) {+ throw new Error(+ 'Tool approval invocation changed before transport dispatch. Request approval again.',+ );+ }+ if (+ current.available === false ||+ current.oauthEpoch === undefined ||+ current.oauthEpoch !== consent.oauthEpoch+ ) {+ const key = approvalCallKey(+ invocation.agentId,+ invocation.toolCallId ?? '',+ invocation.executionScope,+ );+ if (proposals.get(key)?.ownership === invocation.ownership) disableLearning(key);+ if (+ witness.oneTimeFallback &&+ consent.authKind === 'other' &&+ consent.oauthEpoch === null &&+ invocation.background !== true &&+ (current.available === false || current.oauthEpoch === undefined)+ ) {+ witness.reviewOnly = true;+ return;+ }+ throw new Error(+ 'The approved MCP OAuth authorization changed before transport retry. Request approval again.',+ );+ }+ }+ },+ async rememberHook(input) {+ const key = approvalCallKey(+ input.executingAgentId,+ input.toolUseId,+ getToolApprovalExecutionScope(input.executionContext),+ );+ // A launch handle is not the detached invocation's successful completion.+ if (dispositions.get(key) === true) return {};+ const ownership = proposals.get(key)?.ownership;+ const grant = ready.get(key);+ try {+ if (+ grant &&+ !learningDisabled.has(key) &&+ executed.has(key) &&+ grant.canRemember === true &&+ grant.agentId === input.executingAgentId &&+ grant.instanceName === input.toolName &&+ storage &&+ scope+ ) {+ const current = await approved(grant);+ if (+ current.available !== false &&+ current.oauthEpoch !== undefined &&+ current.oauthEpoch === grant.oauthEpoch &&+ current.revocation === grant.revocation &&+ ((current.consentBinding ?? null) === (grant.consentBinding ?? null) ||+ current.consentBinding === grant.binding)+ ) {+ await storage.rememberToolApprovalGrants(scope, [grant]);+ }+ }+ } catch {+ logger.warn('[Tool approvals] Could not remember approval; future calls require review.');+ } finally {+ retireCall(key, ownership);+ }+ return {};+ },+ async hook(input) {+ const agent = input.executingAgentId == null ? undefined : owners.get(input.executingAgentId);+ const mode = agent?.tool_options?.[input.toolName]?.approval_mode;+ const executionScope = getToolApprovalExecutionScope(input.executionContext);+ const key = approvalCallKey(input.executingAgentId, input.toolUseId, executionScope);+ const previous = proposals.get(key);+ if (previous?.dispatched) retireCall(key, previous.ownership, dispositions.get(key) === true);+ if (!agent || mode == null) {+ if (reviewedBindings.has(key))+ return {+ decision: 'deny',+ reason:+ 'The reviewed tool approval configuration changed. Please request approval again.',+ };+ return {};+ }+ const ownership =+ previous?.dispatched === false ? previous.ownership : Symbol('toolInvocation');+ const target = scope && resolveToolReviewBinding(agent, input.toolName, scope);+ const status = target ? await approved(target) : undefined;+ if (target) {+ target.executionScope = executionScope;+ target.oauthEpoch = target.authKind === 'other' ? null : status?.oauthEpoch;+ target.revocation = status?.revocation;+ target.consentBinding = status?.consentBinding;+ }+ const reviewedBinding = reviewedBindings.get(key);+ if (+ reviewedBinding &&+ (target?.binding !== reviewedBinding.binding ||+ target?.oauthEpoch !== reviewedBinding.oauthEpoch)+ ) {+ return {+ decision: 'deny',+ reason:+ 'The reviewed tool or OAuth authorization changed. Please request approval again.',+ };+ }+ // Older owner-less pauses remain usable only for a single known agent.+ if (owners.size === 1 && legacyDecisions.has(input.toolUseId)) {+ const decision = legacyDecisions.get(input.toolUseId);+ legacyDecisions.delete(input.toolUseId);+ if (decision === 'approve' || decision === 'edit') permittedDecisions.add(key);+ }+ policyChecks.set(key, { agentId: agent.id, toolName: input.toolName });+ const candidates = callOwners.get(input.toolUseId) ?? new Set<string>();+ candidates.add(key);+ callOwners.set(input.toolUseId, candidates);+ proposals.set(key, {+ agentId: agent.id,+ callId: input.toolUseId,+ dispatched: false,+ ownership,+ toolName: input.toolName,+ executionScope,+ });+ if (!target) {+ calls.set(key, null);+ disableLearning(key);+ unavailable.set(key, 'connection');+ return { decision: mode === 'allow' ? 'allow' : 'ask' };+ }+ const prior = calls.get(key);+ if (prior && (prior.binding !== target.binding || prior.oauthEpoch !== target.oauthEpoch)) {+ calls.set(key, null);+ return { decision: 'ask' };+ }+ if (status?.available === false || status?.oauthEpoch === undefined) {+ target.canRemember = false;+ target.unavailable = 'storage';+ } else if (!storage) {+ target.canRemember = false;+ target.unavailable = 'disabled';+ }+ if (input.toolInput.run_in_background === true) {+ target.canRemember = false;+ target.unavailable = 'background';+ ready.delete(key);+ }+ if (target.canRemember !== true) disableLearning(key);+ if (learningDisabled.has(key)) {+ target.canRemember = false;+ target.unavailable ??= prior?.unavailable ?? reviewedBinding?.unavailable;+ } else if (+ reviewedBinding &&+ approvedDecisions.has(key) &&+ reviewedBinding.canRemember === true+ ) {+ ready.set(key, reviewedBinding);+ }+ calls.set(key, target);+ if (mode === 'allow') return { decision: 'allow' };+ if (mode === 'ask') return { decision: 'ask' };+ return { decision: storage && status?.approved === true ? 'allow' : 'ask' };+ },+ };+}++const sessions = new WeakMap<object, AgentToolApprovalSession>();+export function bindRunToolApprovalSession(+ run: Pick<Run<IState>, 'processStream'>,+ session: AgentToolApprovalSession,+): void {+ if (!sessions.has(run)) {+ const processStream = run.processStream;+ run.processStream = function (...args) {+ const execution = sessions.get(this);+ return execution+ ? withToolApprovalExecution(execution, () => processStream.apply(this, args))+ : processStream.apply(this, args);+ };+ }+ sessions.set(run, session);+}++export function captureRunToolApprovalBindings(+ run: object,+ payload: Agents.HumanInterruptPayload,+): Record<string, ToolApprovalGrantBinding> | undefined {+ return payload.type === 'tool_approval' ? sessions.get(run)?.bindingsFor(payload) : undefined;+}++export function describeRememberedToolApprovals(+ payload: Agents.HumanInterruptPayload,+ bindings: Record<string, ToolApprovalGrantBinding> | undefined,+ run?: object,+): Agents.HumanInterruptPayload {+ if (payload.type !== 'tool_approval' || !bindings) return payload;+ return {+ ...payload,+ review_configs: payload.review_configs.map((config) => {+ const binding = bindings[config.tool_call_id];+ const scope = binding?.scope;+ return {+ ...config,+ remember_scope:+ binding?.canRemember === true && (scope === 'chat' || scope === 'always')+ ? scope+ : undefined,+ remember_unavailable:+ binding?.unavailable ??+ (run+ ? sessions.get(run)?.unavailableFor(config.tool_call_id, config.action_name)+ : undefined),+ };+ }),+ };+}++export interface ReviewedToolApprovals {+ bindings?: Record<string, ToolApprovalGrantBinding>;+ decisions: readonly Agents.ToolApprovalResolution[];+}diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.tsindex dea3f646ab..a27a63b293 100644--- a/packages/api/src/agents/hitl/policy.spec.ts+++ b/packages/api/src/agents/hitl/policy.spec.ts@@ -1,3 +1,4 @@+import { createToolPolicyHook } from '@librechat/agents';import { ReasoningEffort } from 'librechat-data-provider';import type { Agents, TToolApprovalPolicy } from 'librechat-data-provider';import {@@ -23,6 +24,7 @@ import {exemptAskUserQuestionFromApproval,isToolApprovalPauseCapable,isToolDeniedByApprovalPolicy,+ isToolBlockedByApprovalPolicy,} from './policy';describe('isToolApprovalPauseCapable', () => {@@ -1194,3 +1196,30 @@ describe('collectAliasMatcherNames', () => {expect(regex.test('xc_mcp_acme')).toBe(false);});});++test.each([+ { mode: 'dontAsk' as const },+ { mode: 'dontAsk' as const, allow: ['query*'] },+ { mode: 'dontAsk' as const, ask: ['query*'] },+ { mode: 'dontAsk' as const, allow: ['query*'], ask: ['query*'] },+ { mode: 'dontAsk' as const, allow: ['query*'], deny: ['query*'] },+ { mode: 'dontAsk' as const, ask: ['other*'] },+ { mode: 'bypass' as const },+ { mode: 'default' as const },+])('concrete fallback denial matches the SDK baseline: %j', async (config) => {+ const policy = { enabled: true, ...config };+ const hook = createToolPolicyHook(mapToolApprovalPolicy(policy)!);+ const result = await hook(+ {+ hook_event_name: 'PreToolUse',+ runId: 'test',+ toolName: 'query_mcp_db',+ toolInput: {},+ toolUseId: 'call',+ },+ new AbortController().signal,+ );+ expect(isToolBlockedByApprovalPolicy(policy, 'query_mcp_db')).toBe(result.decision === 'deny');+ if (result.decision === 'deny')+ expect(isToolApprovalPauseCapable(policy, true, ['query_mcp_db'])).toBe(false);+});diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.tsindex dd00e19d89..31a556d41a 100644--- a/packages/api/src/agents/hitl/policy.ts+++ b/packages/api/src/agents/hitl/policy.ts@@ -132,7 +132,7 @@ export function isToolApprovalPauseCapable(const matches = (patterns: string[] | undefined, name: string): boolean =>patterns?.some((pattern) => globToRegex(pattern).test(name)) === true;return names.some((name) => {- if (matches(enabledPolicy.deny, name)) {+ if (isToolBlockedByApprovalPolicy(enabledPolicy, name)) {return false;}if (hasProgrammaticHooks || matches(enabledPolicy.ask, name)) {@@ -180,6 +180,19 @@ export function isToolDeniedByApprovalPolicy();}+/** Static deny, including the unmatched `dontAsk` fallback, cannot be tightened into review. */+export function isToolBlockedByApprovalPolicy(+ policy: TToolApprovalPolicy | undefined,+ toolName: string,+): boolean {+ if (!isHITLEnabled(policy)) return false;+ if (isToolDeniedByApprovalPolicy(policy, toolName)) return true;+ if (policy.mode !== 'dontAsk') return false;+ const matches = (patterns?: readonly string[]) =>+ patterns?.some((pattern) => globToRegex(pattern).test(toolName)) === true;+ return !matches(policy.ask) && !matches(policy.allow);+}+/*** Extends each `toolApproval` pattern list with the names of tools whose* OTHER spelling matches, so admin YAML keeps applying when a tool's key@@ -952,6 +965,7 @@ export function toClientPendingAction(requestFingerprintV2: _requestFingerprintV2,resumeContext: _resumeContext,codeExecutionBinding: _codeExecutionBinding,+ toolApprovalBindings: _toolApprovalBindings,toolApprovalAliases: _toolApprovalAliases,...clientSafe} = pendingAction;diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.tsindex fabcc1f856..054c3e39ce 100644--- a/packages/api/src/agents/run.ts+++ b/packages/api/src/agents/run.ts@@ -50,6 +50,7 @@ import type {} from 'librechat-data-provider';import type { AppConfig, IAgentFadingTier, IUser } from '@librechat/data-schemas';import type { CallbackHandlerMethods } from '@langchain/core/callbacks/base';+import type { ToolApprovalGrantStorage } from 'librechat-data-provider';import type { BaseMessage } from '@librechat/agents/langchain/messages';import type { Callbacks } from '@langchain/core/callbacks/manager';import type { ModelBoundChatModelCallback } from '~/middleware/modelBoundContent';@@ -63,6 +64,7 @@ import type { LangfuseTraceContext } from '~/langfuse/identity';import type { ResolvedAlwaysApplySkill } from '~/agents/skills';import type { CodeExecutionContext } from '~/agents/execution';import type { MCPToolAlias } from '~/tools/classification';+import type { ReviewedToolApprovals } from './hitl/modes';import type { SubagentUsageEvent } from '~/agents/usage';import type { ProvisionState } from '~/agents/resources';import type { RunFileSession } from './files/session';@@ -110,6 +112,7 @@ import {import { resolveToolApprovalPolicy, exemptAskUserQuestionFromApproval } from '~/agents/hitl/policy';import { applyCustomHandoffPromptKeyCompatibility } from '~/agents/handoffPromptKeyCompatibility';import { stripIntentFromToolRegistry, stripIntentFromToolDefinitions } from '~/agents/intent';+import { createAgentToolApprovalSession, bindRunToolApprovalSession } from './hitl/modes';import { resolveConfigHeaders, resolveModelHeaders, mergeHeaders } from '~/utils/headers';import { extractDefaultParams, resolveReasoningParams } from '~/endpoints/openai/llm';import { getLLMConfig as getAnthropicLLMConfig } from '~/endpoints/anthropic/llm';@@ -2132,6 +2135,8 @@ export async function createRun({eventActorCheckpointing = false,hitlCapable = false,resolvedToolApprovalHooks,+ toolApprovalStorage,+ reviewedToolApprovals,scheduledMCPExecution,recordScheduledMCPDenial,toolApprovalAllows,@@ -2281,6 +2286,8 @@ export async function createRun({* Reuse them here so a context-aware factory is evaluated exactly once for the run.*/resolvedToolApprovalHooks?: readonly ResolvedToolApprovalHook[];+ toolApprovalStorage?: ToolApprovalGrantStorage;+ reviewedToolApprovals?: ReviewedToolApprovals;scheduledMCPExecution?: ScheduleMCPExecution;recordScheduledMCPDenial?: (error: ScheduledMCPPolicyError) => Promise<boolean>;/** Plugin-hook SessionStart lifecycle source: 'startup' (default) or 'resume' on HITL-rebuild paths. */@@ -2762,6 +2769,22 @@ export async function createRun({ASK_USER_QUESTION_TOOL_NAME,);const nativeEditFileAgentIds = collectNativeEditFileAgentIds(agents);+ const agentApprovalSession = createAgentToolApprovalSession({+ agents: [...codeFileAgents.values()],+ storage: toolApprovalPolicy?.agentModes === true ? toolApprovalStorage : undefined,+ authorizationStorage: toolApprovalStorage,+ reviewed: reviewedToolApprovals,+ policy: effectiveToolApprovalPolicy,+ lookupTimeoutMs: toolApprovalPolicy?.grantLookupTimeoutMs,+ scope:+ user?.id && (conversationId ?? requestBody?.conversationId)+ ? {+ userId: user.id,+ tenantId: tenantId ?? user.tenantId,+ conversationId: (conversationId ?? requestBody?.conversationId)!,+ }+ : undefined,+ });const approvalWiring = buildHITLRunWiring(// The ask tool is exempt from the approval prompt (unless explicitly// listed by the admin) — approving the right to ask a question is a@@ -2779,6 +2802,7 @@ export async function createRun({},mcpToolAliases,[+ { hook: agentApprovalSession.hook },...(resolvedToolApprovalHooks ??buildToolApprovalHooks({userId: user?.id,@@ -2800,6 +2824,10 @@ export async function createRun({],nativeEditFileAgentIds,);+ approvalWiring?.hooks.register('PostToolUse', { hooks: [agentApprovalSession.rememberHook] });+ approvalWiring?.hooks.register('PostToolBatch', {+ hooks: [agentApprovalSession.settleBatchHook],+ });const hitl = hitlCapable ? approvalWiring : undefined;const scheduledPolicy = scheduledMCPExecution? createScheduledMCPRunPolicy(@@ -2810,6 +2838,7 @@ export async function createRun({): undefined;registerResolvedMCPToolAliases = (resolvedAgent) => {+ agentApprovalSession.addAgent(resolvedAgent);scheduledPolicy?.registerAgent(resolvedAgent);for (const agentId of collectNativeEditFileAgentIds([resolvedAgent])) {nativeEditFileAgentIds.add(agentId);@@ -3069,6 +3098,7 @@ export async function createRun({...(streamLimits && { streamLimits }),};const run = await Run.create(runConfig);+ if (approvalWiring != null) bindRunToolApprovalSession(run, agentApprovalSession);runMCPToolAliases.set(run, mcpToolAliases);applyCustomHandoffPromptKeyCompatibility(run, runConfig.graphConfig);diff --git a/packages/api/src/agents/validation.ts b/packages/api/src/agents/validation.tsindex ca7965fb22..abc4ba1778 100644--- a/packages/api/src/agents/validation.ts+++ b/packages/api/src/agents/validation.ts@@ -157,6 +157,8 @@ export const toolOptionsSchema: z.ZodObject<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>;+ approval_mode: z.ZodOptional<z.ZodEnum<['ask', 'allow', 'chat', 'always']>>;+ approval_revision: z.ZodOptional<z.ZodString>;},'strip'> = z.object({@@ -164,35 +166,13 @@ export const toolOptionsSchema: z.ZodObject<allowed_callers: z.array(z.enum(['direct', 'code_execution'])).optional(),run_in_background: z.boolean().optional(),describe_intent: z.boolean().optional(),+ approval_mode: z.enum(['ask', 'allow', 'chat', 'always']).optional(),+ approval_revision: z.string().uuid().optional(),});/** Agent tool options - map of tool_id to tool options */export const agentToolOptionsSchema: 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;- }- >- >+ z.ZodRecord<z.ZodString, typeof toolOptionsSchema>> = z.record(z.string(), toolOptionsSchema).optional();/**diff --git a/packages/api/src/endpoints/config/endpoints.ts b/packages/api/src/endpoints/config/endpoints.tsindex 6e866c9b7d..4a7625d2b7 100644--- a/packages/api/src/endpoints/config/endpoints.ts+++ b/packages/api/src/endpoints/config/endpoints.ts@@ -141,6 +141,14 @@ export function createEndpointsConfigService(deps: EndpointsConfigDeps): {statefulCodeSessions: clientStatefulCodeSessions,maxSubagents,fileSharing,+ toolApproval: {+ enabled: toolApproval?.enabled === true,+ agentModes: toolApproval?.enabled === true && toolApproval.agentModes === true,+ mode: toolApproval?.mode,+ allow: toolApproval?.allow,+ deny: toolApproval?.deny,+ ask: toolApproval?.ask,+ },};}diff --git a/packages/api/src/index.ts b/packages/api/src/index.tsindex 9b6508025c..be7e6d7d0b 100644--- a/packages/api/src/index.ts+++ b/packages/api/src/index.ts@@ -137,3 +137,7 @@ export type { OpenApiRouterDeps } from './openapi/router';export type * from './mcp/types';export type * from './flow/types';export type * from './types';++export * from './tools/approval';++export * from './mcp/approval';diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex bb0fe33182..93400f3d90 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -57,6 +57,7 @@ import { formatToolContent, selectResolvedAppResource } from './parsers';import { MCPServersInitializer } from './registry/MCPServersInitializer';import { OboTokenResolutionError, resolveOboToken } from '~/mcp/oauth';import { MCPServerCatalogRecoveryTracker } from './catalog/recovery';+import { assertToolApprovalTransportEpoch } from '~/tools/approval';import { getToolUiResourceUri, isToolHiddenFromApp } from './apps';import { MCPServerInspector } from './registry/MCPServerInspector';import { MCPServersRegistry } from './registry/MCPServersRegistry';@@ -66,6 +67,7 @@ import { MCPConnectionFactory } from './MCPConnectionFactory';import { processMCPEnv, isPluginSourced } from '~/utils/env';import { OAuthLifecycleRelay } from './oauth/pending';import { isOwnedAbortError } from '~/utils/errors';+import { markMCPToolResultError } from './status';import { withMCPRequestSignal } from './signal';import { MCPConnection } from './connection';import { mcpConfig } from './mcpConfig';@@ -1862,6 +1864,11 @@ Please follow these instructions when using tools from the respective MCP serversignal: options?.signal,});options?.signal?.throwIfAborted();+ await assertToolApprovalTransportEpoch(+ serverName,+ connection!.getOAuthCredentialSetId?.() ?? null,+ true,+ );return withMCPRequestSignal(options?.signal, (signal) =>connection!.client.request({@@ -2081,20 +2088,23 @@ Please follow these instructions when using tools from the respective MCP serverresolvedAppResource = undefined;}- return formatToolContent(- toolResult,- provider,- appCompatible- ? {- serverName,- toolName,- resourceUri: resourceMeta?.uri,- resolvedAppResource,- serverBinding,- toolArgs: toolArguments,- mcpApps: admittedMCPApps,- }- : { mcpApps: admittedMCPApps },+ return markMCPToolResultError(+ formatToolContent(+ toolResult,+ provider,+ appCompatible+ ? {+ serverName,+ toolName,+ resourceUri: resourceMeta?.uri,+ resolvedAppResource,+ serverBinding,+ toolArgs: toolArguments,+ mcpApps: admittedMCPApps,+ }+ : { mcpApps: admittedMCPApps },+ ),+ toolResult?.isError === true,);} catch (error) {if (error instanceof OAuthRecoveryTakeoverRequired) {diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex 56d63485c2..d839509557 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -19,6 +19,7 @@ import {STANDARD_MCP_CAPABILITY_PROFILE,} from '~/mcp/capabilities';import { OboTokenResolutionError, detectOAuthRequirement, resolveOboToken } from '~/mcp/oauth';+import { withToolApprovalExecution, withToolApprovalTransport } from '~/tools/approval';import { executionFixture, readTool } from '~/schedules/authorization/execution.helper';import { createMCPRequestContext, cleanupMCPRequestContext } from '~/mcp/request';import { MCPServersInitializer } from '~/mcp/registry/MCPServersInitializer';@@ -26,6 +27,7 @@ import { MCPServerInspector } from '~/mcp/registry/MCPServerInspector';import { ConnectionsRepository } from '~/mcp/ConnectionsRepository';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';import { MCPAuthenticationRejectedError } from '~/mcp/errors';+import { getMCPToolApprovalAuthKind } from '~/mcp/approval';import { OpenIDReauthRequiredError } from '~/utils/oidc';import { isMCPDomainAllowed } from '~/auth/domain';import * as toolsChanged from '~/mcp/toolsChanged';@@ -2084,6 +2086,94 @@ describe('MCPManager', () => {expect(request.mock.calls[1]).toEqual(request.mock.calls[0]);});+ it.each([false, true])(+ 'approval transport fencing handles account replacement=%s after a 401',+ async (replaceAccount) => {+ let epoch = 'account-a';+ const request = jest+ .fn()+ .mockRejectedValueOnce(new Error('Non-200 status code (401)'))+ .mockResolvedValueOnce(toolResult);+ const connection = createConnection(request);+ connection.getOAuthCredentialSetId = () => epoch;+ attachOAuthHandler((active) => {+ if (replaceAccount) epoch = 'account-b';+ active.emit('oauthHandled');+ });+ const manager = await createManager(connection);+ const guard = jest.fn(async (_serverName: string, currentEpoch: string | null) => {+ if (currentEpoch !== 'account-a') throw new Error('Approved OAuth epoch changed');+ });+ const invoke = () =>+ withToolApprovalExecution(+ { validateExecution: async () => {}, validateTransport: guard },+ () =>+ withToolApprovalTransport(+ { toolCall: { id: 'approved-call' }, metadata: { agentId: 'agent-a' } },+ () => callTool(manager),+ ),+ );+ if (replaceAccount) {+ await expect(invoke()).rejects.toThrow('Approved OAuth epoch changed');+ expect(request).toHaveBeenCalledTimes(1);+ } else {+ await expect(invoke()).resolves.toBeDefined();+ expect(request).toHaveBeenCalledTimes(2);+ }+ expect(guard).toHaveBeenCalledTimes(2);+ },+ );++ it.each([true, false])(+ 'rechecks reviewed OAuth after scheduled authorization for enrolled=%s',+ async (enrolled) => {+ let epoch = 'account-a';+ const request = jest.fn().mockResolvedValue(toolResult);+ const connection = createConnection(request);+ connection.getOAuthCredentialSetId = () => epoch;+ const manager = await createManager(connection);+ const authorize = jest.fn(async () => {+ epoch = 'account-b';+ });+ const guard = jest.fn(async (_server: string, currentEpoch: string | null) => {+ if (currentEpoch !== 'account-a') throw new Error('Approved OAuth epoch changed');+ });+ const invoke = () =>+ withToolApprovalExecution(+ { validateExecution: async () => {}, validateTransport: guard },+ () =>+ withToolApprovalTransport(+ { toolCall: { id: 'approved-call' }, metadata: { agentId: 'root' } },+ () =>+ manager.callTool({+ user: mockUser,+ serverName,+ toolName: 'oauth_tool',+ provider: 'openai',+ flowManager: mockFlowManager,+ scheduledMCPInvocation: {+ identity: {+ scheduleId: 'schedule',+ ownerId: mockUser.id,+ tenantId: null,+ agentId: 'root',+ invocationMode: 'delegated',+ },+ enrolled,+ agentId: 'root',+ authorize,+ },+ }),+ ),+ );+ await expect(invoke()).rejects.toThrow('Approved OAuth epoch changed');+ expect(authorize).toHaveBeenCalledTimes(1);+ expect(guard).toHaveBeenCalledWith(serverName, 'account-b', expect.any(Object), true);+ expect(request).not.toHaveBeenCalled();+ expect(connection.connect).not.toHaveBeenCalled();+ },+ );+it.each([true, false])('preserves first JSON-RPC failure without stored-OAuth replay for enrolled=%s',async (enrolled) => {@@ -7748,6 +7838,7 @@ describe('MCPManager', () => {});(MCPConnectionFactory.create as jest.Mock).mockResolvedValue(mockConnection);+ expect(getMCPToolApprovalAuthKind(runtimeUrlConfig)).toBeUndefined();const manager = await MCPManager.createInstance(newMCPServersConfig());await manager.getUserConnection({serverName,@@ -7768,6 +7859,10 @@ describe('MCPManager', () => {}),expect.objectContaining({ useOAuth: true }),);+ const runtime = (MCPConnectionFactory.create as jest.Mock).mock.calls[0][0];+ expect(runtime.serverDefinition).toBe(runtimeUrlConfig);+ expect(getMCPToolApprovalAuthKind(runtime.serverDefinition)).toBeUndefined();+ expect(getMCPToolApprovalAuthKind(runtime.serverConfig)).toBe('oauth');});it('should reject disallowed runtime URLs before OAuth detection probes them', async () => {diff --git a/packages/api/src/mcp/__tests__/approvalTransport.spec.ts b/packages/api/src/mcp/__tests__/approvalTransport.spec.tsnew file mode 100644index 0000000000..53517f5467--- /dev/null+++ b/packages/api/src/mcp/__tests__/approvalTransport.spec.ts@@ -0,0 +1,118 @@+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';+import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';+import { withToolApprovalExecution, withToolApprovalTransport } from '~/tools/approval';+import { MCPConnection } from '../connection';++/** The actual SDK recursively sends again after auth. Only external HTTP is replaced. */+test('SDK-internal OAuth recovery cannot retry tools/call under a replacement account', async () => {+ const connection = new MCPConnection({+ serverName: 'db',+ userId: 'user-a',+ serverConfig: { type: 'streamable-http', url: 'https://mcp.example.test/mcp' },+ oauthTokens: {+ access_token: 'synthetic-a',+ token_type: 'Bearer',+ credential_set_id: 'account-a',+ obtained_at: Date.now(),+ },+ });+ let tokens: OAuthTokens = {+ access_token: 'synthetic-a',+ refresh_token: 'synthetic-refresh',+ token_type: 'Bearer',+ };+ let toolAttempts = 0;+ const provider: OAuthClientProvider = {+ redirectUrl: 'https://callback.example.test',+ clientMetadata: {+ redirect_uris: ['https://callback.example.test'],+ token_endpoint_auth_method: 'none',+ logo_uri: undefined,+ tos_uri: undefined,+ },+ clientInformation: () => ({ client_id: 'test-client' }),+ tokens: async () => tokens,+ saveTokens: async (replacement) => {+ tokens = replacement;+ connection.setOAuthTokens({+ ...replacement,+ credential_set_id: 'account-b',+ obtained_at: Date.now(),+ });+ },+ redirectToAuthorization: async () => {+ throw new Error('The scripted refresh should not redirect.');+ },+ saveCodeVerifier: async () => {},+ codeVerifier: async () => 'verifier',+ };+ const fetch = jest.fn(async (input: string | URL | Request) => {+ let url: string;+ if (typeof input === 'string') url = input;+ else if (input instanceof URL) url = input.href;+ else url = input.url;+ if (url === 'https://mcp.example.test/mcp') {+ toolAttempts++;+ return new Response('', {+ status: 401,+ headers: {+ 'www-authenticate': 'Bearer resource_metadata="https://mcp.example.test/metadata"',+ },+ });+ }+ if (url === 'https://mcp.example.test/metadata')+ return Response.json({+ resource: 'https://mcp.example.test/mcp',+ authorization_servers: ['https://auth.example.test'],+ });+ if (url.includes('/.well-known/'))+ return Response.json({+ issuer: 'https://auth.example.test',+ authorization_endpoint: 'https://auth.example.test/authorize',+ token_endpoint: 'https://auth.example.test/token',+ response_types_supported: ['code'],+ grant_types_supported: ['refresh_token'],+ code_challenge_methods_supported: ['S256'],+ token_endpoint_auth_methods_supported: ['none'],+ });+ if (url === 'https://auth.example.test/token')+ return Response.json({ access_token: 'synthetic-b', token_type: 'Bearer', expires_in: 3600 });+ throw new Error('Unexpected scripted HTTP endpoint');+ });+ const transport = new StreamableHTTPClientTransport(new URL('https://mcp.example.test/mcp'), {+ authProvider: provider,+ fetch,+ });+ connection['transport'] = transport;+ connection['patchTransportSend']();+ const execution = {+ validateExecution: async () => {},+ validateTransport: async (_server: string, epoch: string | null) => {+ if (epoch !== 'account-a') throw new Error('Reviewed epoch changed before send');+ },+ };+ try {+ await expect(+ withToolApprovalExecution(execution, () =>+ withToolApprovalTransport(+ {+ toolCall: { id: 'approved-call' },+ metadata: { agentId: 'agent-a' },+ },+ () =>+ transport.send({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'mutate', arguments: {} },+ }),+ ),+ ),+ ).rejects.toThrow('Reviewed epoch changed before send');+ expect(tokens.access_token).toBe('synthetic-b');+ expect(toolAttempts).toBe(1);+ } finally {+ await transport.close();+ }+});diff --git a/packages/api/src/mcp/approval.spec.ts b/packages/api/src/mcp/approval.spec.tsnew file mode 100644index 0000000000..731a5a551f--- /dev/null+++ b/packages/api/src/mcp/approval.spec.ts@@ -0,0 +1,459 @@+import { ServerConfigsCacheInMemory } from './registry/cache/ServerConfigsCacheInMemory';+import { buildMCPToolApprovalBinding } from '~/agents/hitl/modes';+import { buildMCPToolReviewAuthority } from './approval';+import { getMCPToolApprovalAuthKind } from './approval';+import { processMCPEnv } from '~/utils/env';++const config = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://a.example.test/mcp',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+};++test('review-only authority pins a templated endpoint without enabling remembered consent', () => {+ expect(buildMCPToolApprovalBinding('db', config)).toBeUndefined();+ const first = buildMCPToolReviewAuthority({ serverName: 'db', config });+ expect(first).toEqual(expect.any(String));+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: { ...config, url: 'https://b.example.test/mcp' },+ }),+ ).not.toBe(first);+});++test('resolved custom destinations and request routes are part of invocation consent', () => {+ const variable = {+ ...config,+ url: '{{DESTINATION}}',+ customUserVars: { DESTINATION: { title: 'Destination', description: 'URL' } },+ };+ const input = { serverName: 'db', config: variable };+ expect(+ buildMCPToolReviewAuthority({+ ...input,+ customUserVars: { DESTINATION: 'https://a.example.test/mcp' },+ }),+ ).not.toBe(+ buildMCPToolReviewAuthority({+ ...input,+ customUserVars: { DESTINATION: 'https://b.example.test/mcp' },+ }),+ );+ const request = { ...config, url: 'https://a.example.test/{{LIBRECHAT_BODY_CONVERSATIONID}}' };+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: request,+ body: { conversationId: 'a' },+ }),+ ).not.toBe(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: request,+ body: { conversationId: 'b' },+ }),+ );+});++test('unresolved routing cannot establish invocation consent', () => {+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: { ...config, url: '{{DESTINATION}}' },+ }),+ ).toBeUndefined();+});++test('current principal identity remains part of invocation-only consent', () => {+ const first = buildMCPToolReviewAuthority({+ serverName: 'db',+ config,+ user: { id: 'user-a', openidId: 'subject-a' },+ });+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config,+ user: { id: 'user-b', openidId: 'subject-b' },+ }),+ ).not.toBe(first);+});++test('plugin literals remain opaque without resolving host variables or losing review authority', () => {+ const plugin = {+ type: 'stdio' as const,+ source: 'plugin' as const,+ command: 'node',+ args: ['server.js', '${PLUGIN_LITERAL}'],+ };+ const first = buildMCPToolReviewAuthority({ serverName: 'plugin-server', config: plugin });+ expect(first).toEqual(expect.any(String));+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'plugin-server',+ config: plugin,+ customUserVars: { PLUGIN_LITERAL: 'ignored' },+ }),+ ).toBe(first);+});++test('effective admin credentials are not masked by a shadowed renewable header template', () => {+ const selected = {+ ...config,+ apiKey: {+ source: 'admin' as const,+ authorization_type: 'bearer' as const,+ key: '{{ADMIN_KEY}}',+ },+ };+ const first = buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ customUserVars: { ADMIN_KEY: 'review-only-renewable-bearer-a' },+ });+ const second = buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ customUserVars: { ADMIN_KEY: 'review-only-renewable-bearer-b' },+ });+ expect(second).not.toBe(first);+});++test('request-only workspace headers are resolved before authority fingerprinting', () => {+ const selected = { ...config, requestHeaders: { 'X-Workspace': '{{WORKSPACE}}' } };+ const first = buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ customUserVars: { WORKSPACE: 'workspace-a' },+ });+ const second = buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ customUserVars: { WORKSPACE: 'workspace-b' },+ });+ expect(second).not.toBe(first);+});++test('request-only renewable auth uses the same merge and principal handling as the transport', () => {+ const selected = {+ ...config,+ headers: { 'X-Base': 'base' },+ requestHeaders: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ 'X-Workspace': '{{WORKSPACE}}',+ },+ };+ const first = buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: { id: 'user-a', openidId: 'subject-a' },+ customUserVars: { WORKSPACE: 'workspace-a' },+ });+ expect(first).toEqual(expect.any(String));+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: { id: 'user-a', openidId: 'subject-a' },+ customUserVars: { WORKSPACE: 'workspace-b' },+ }),+ ).not.toBe(first);+});++const renewableFields = [+ 'LIBRECHAT_OPENID_TOKEN',+ 'LIBRECHAT_OPENID_ACCESS_TOKEN',+ 'LIBRECHAT_OPENID_ID_TOKEN',+ 'LIBRECHAT_GRAPH_ACCESS_TOKEN',+] as const;++test.each(renewableFields)('mixed %s headers retain resolved workspace authority', (field) => {+ const placeholder = `{{${field}}}`;+ const selected = { ...config, headers: { 'X-Workspace': `{{WORKSPACE}}:${placeholder}` } };+ const input = {+ serverName: 'db',+ config: selected,+ user: { id: 'user-a', openidId: 'subject-a' },+ };+ const a = buildMCPToolReviewAuthority({ ...input, customUserVars: { WORKSPACE: 'workspace-a' } });+ const b = buildMCPToolReviewAuthority({ ...input, customUserVars: { WORKSPACE: 'workspace-b' } });+ expect(a).toEqual(expect.any(String));+ expect(b).not.toBe(a);+ expect(selected.headers['X-Workspace']).toBe(`{{WORKSPACE}}:${placeholder}`);+});++test.each(renewableFields)('%s alias loading does not require renewable token bytes', (field) => {+ const selected = { ...config, headers: { Authorization: `Bearer {{${field}}}` } };+ const principal = { id: 'user-a', openidId: 'subject-a' };+ expect(() =>+ buildMCPToolReviewAuthority({ serverName: 'db', config: selected, user: principal }),+ ).not.toThrow();+ expect(+ buildMCPToolReviewAuthority({ serverName: 'db', config: selected, user: principal }),+ ).toEqual(expect.any(String));+});++const tokenPrincipal = (token: string) => ({+ id: 'user-a',+ openidId: 'subject-a',+ openidTokens: { access_token: token, expires_at: Math.floor(Date.now() / 1000) + 3600 },+});++for (const field of renewableFields) {+ test(`${field} stdio env and arguments retain routing without renewable token bytes`, () => {+ const selected = {+ type: 'stdio' as const,+ source: 'yaml' as const,+ command: 'node',+ args: ['server.js', `--credential={{${field}}}`, '--workspace={{WORKSPACE}}'],+ env: {+ UPSTREAM_ACCESS_TOKEN: `{{WORKSPACE}}:{{${field}}}`,+ USER: '{{LIBRECHAT_USER_OPENIDID}}',+ },+ };+ const authority = (token: string, workspace = 'a', subject = 'subject-a') =>+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: { ...tokenPrincipal(token), openidId: subject },+ customUserVars: { WORKSPACE: workspace },+ });+ const first = authority('synthetic-a');+ expect(first).toEqual(expect.any(String));+ expect(authority('synthetic-b')).toBe(first);+ expect(authority('synthetic-b', 'b')).not.toBe(first);+ expect(authority('synthetic-b', 'a', 'subject-b')).not.toBe(first);+ expect(selected.env.UPSTREAM_ACCESS_TOKEN).toBe(`{{WORKSPACE}}:{{${field}}}`);+ });+}++test('renewable OAuth and URL fragments retain surrounding destination authority', () => {+ const selected = {+ ...config,+ url: 'https://{{WORKSPACE}}.example.test/mcp?token={{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ oauth: {+ client_id: '{{WORKSPACE}}',+ client_secret: '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ authorization_url: 'https://{{WORKSPACE}}.example.test/authorize',+ },+ };+ const authority = (token: string, workspace = 'a') =>+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: tokenPrincipal(token),+ customUserVars: { WORKSPACE: workspace },+ });+ expect(authority('synthetic-b')).toBe(authority('synthetic-a'));+ expect(authority('synthetic-b', 'b')).not.toBe(authority('synthetic-a'));+});++test('an injected renewable API key is masked without ignoring declared credential changes', () => {+ const selected = {+ ...config,+ apiKey: {+ source: 'admin' as const,+ authorization_type: 'bearer' as const,+ key: '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ },+ };+ const a = buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: tokenPrincipal('synthetic-a'),+ });+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: tokenPrincipal('synthetic-b'),+ }),+ ).toBe(a);+ expect(+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: { ...selected, apiKey: { ...selected.apiKey, key: 'static-admin-credential' } },+ user: tokenPrincipal('synthetic-b'),+ }),+ ).not.toBe(a);+});++test('real registry timestamps and inspection summaries do not change review authority', async () => {+ const registry = new ServerConfigsCacheInMemory();+ await registry.add('db', { ...config, initDuration: 2 });+ const before = buildMCPToolReviewAuthority({+ serverName: 'db',+ config: await registry.get('db'),+ });+ await registry.update('db', {+ ...config,+ initDuration: 200,+ capabilities: 'reinspected',+ tools: 'new summary',+ resolvedInstructions: 'new instructions',+ });+ expect(buildMCPToolReviewAuthority({ serverName: 'db', config: await registry.get('db') })).toBe(+ before,+ );+ expect(+ buildMCPToolReviewAuthority({ serverName: 'db', config: { ...config, source: 'user' } }),+ ).not.toBe(before);+});++test.each(['header', 'env', 'argument', 'url'] as const)(+ 'environment-expanded renewable %s is stable before refresh and still binds routing',+ (field) => {+ const saved = process.env.TEST_MCP_APPROVAL_TEMPLATE;+ process.env.TEST_MCP_APPROVAL_TEMPLATE = '{{WORKSPACE}}:{{LIBRECHAT_OPENID_ACCESS_TOKEN}}';+ const template = '${TEST_MCP_APPROVAL_TEMPLATE}';+ const selected =+ field === 'env' || field === 'argument'+ ? {+ type: 'stdio' as const,+ source: 'yaml' as const,+ command: 'node',+ args: field === 'argument' ? [template] : ['server.js'],+ env: field === 'env' ? { UPSTREAM_TOKEN: template } : undefined,+ }+ : {+ ...config,+ headers: field === 'header' ? { Authorization: template } : undefined,+ url: field === 'url' ? `https://mcp.example.test/${template}` : config.url,+ };+ const authority = (access_token: string, expires_at: number, WORKSPACE = 'a') =>+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: { ...tokenPrincipal(access_token), openidTokens: { access_token, expires_at } },+ customUserVars: { WORKSPACE },+ });+ try {+ const first = authority('synthetic-a', Math.floor(Date.now() / 1000) + 3600);+ expect(first).toEqual(expect.any(String));+ expect(authority('synthetic-b', 0)).toBe(first);+ expect(authority('synthetic-b', 0, 'b')).not.toBe(first);+ expect(() =>+ processMCPEnv({+ options: selected,+ user: {+ ...tokenPrincipal('synthetic-b'),+ openidTokens: { access_token: 'synthetic-b', expires_at: 0 },+ },+ }),+ ).toThrow('re-authentication');+ } finally {+ if (saved == null) delete process.env.TEST_MCP_APPROVAL_TEMPLATE;+ else process.env.TEST_MCP_APPROVAL_TEMPLATE = saved;+ }+ },+);++test('renewable placeholders introduced by operator substitution are masked after routing resolves', () => {+ const selected = { ...config, headers: { Authorization: '{{AUTH_TEMPLATE}}' } };+ const authority = (token: string, WORKSPACE: string) =>+ buildMCPToolReviewAuthority({+ serverName: 'db',+ config: selected,+ user: tokenPrincipal(token),+ customUserVars: {+ AUTH_TEMPLATE: '{{WORKSPACE}}:{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ WORKSPACE,+ },+ });+ expect(authority('synthetic-b', 'a')).toBe(authority('synthetic-a', 'a'));+ expect(authority('synthetic-b', 'b')).not.toBe(authority('synthetic-a', 'a'));+});++test('approval authentication kind follows effective factory auth, not retained OAuth config', () => {+ const base = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test',+ };+ expect(getMCPToolApprovalAuthKind({ ...base, requiresOAuth: true })).toBe('oauth');+ expect(getMCPToolApprovalAuthKind({ ...base, oauth: { client_id: 'client' } })).toBe('oauth');+ expect(+ getMCPToolApprovalAuthKind({+ ...base,+ requiresOAuth: false,+ oauth: { client_id: 'retained' },+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'synthetic-key' },+ }),+ ).toBe('other');+ expect(getMCPToolApprovalAuthKind(base)).toBe('other');+ expect(getMCPToolApprovalAuthKind(undefined)).toBeUndefined();+ expect(getMCPToolApprovalAuthKind({ ...base, obo: { scopes: 'api://resource/.default' } })).toBe(+ 'other',+ );+ expect(+ getMCPToolApprovalAuthKind({+ ...base,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ }),+ ).toBe('other');+ expect(+ getMCPToolApprovalAuthKind({+ ...base,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ requestHeaders: { Authorization: 'Bearer static-user-key' },+ requiresOAuth: true,+ }),+ ).toBe('oauth');+});++test.each(['yaml', 'config'] as const)(+ '%s runtime URL keeps OAuth provenance unresolved until detection',+ (source) => {+ const selected = {+ type: 'streamable-http' as const,+ source,+ url: 'https://mcp.example.test/users/{{LIBRECHAT_USER_ID}}/mcp',+ };+ expect(getMCPToolApprovalAuthKind(selected)).toBeUndefined();+ expect(getMCPToolApprovalAuthKind({ ...selected, requiresOAuth: true })).toBe('oauth');+ expect(getMCPToolApprovalAuthKind({ ...selected, requiresOAuth: false })).toBe('other');+ expect(getMCPToolApprovalAuthKind({ ...selected, oauth: { client_id: 'configured' } })).toBe(+ 'oauth',+ );+ expect(+ getMCPToolApprovalAuthKind({+ ...selected,+ apiKey: { source: 'admin', key: 'synthetic-key', authorization_type: 'bearer' },+ }),+ ).toBe('other');+ expect(+ getMCPToolApprovalAuthKind({+ ...selected,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ }),+ ).toBe('other');+ expect(+ getMCPToolApprovalAuthKind({ ...selected, obo: { scopes: 'api://scope/.default' } }),+ ).toBe('other');+ expect(getMCPToolApprovalAuthKind({ ...selected, source: 'user', dbId: 'user-config' })).toBe(+ 'other',+ );+ expect(getMCPToolApprovalAuthKind({ ...selected, source: 'plugin' })).toBe('other');+ },+);++test('body-bound and environment-indirected runtime URLs retain conservative OAuth checks', () => {+ const selected = {+ type: 'streamable-http' as const,+ source: 'yaml' as const,+ url: 'https://mcp.example.test/{{LIBRECHAT_BODY_CONVERSATIONID}}',+ };+ expect(getMCPToolApprovalAuthKind(selected)).toBeUndefined();+ const saved = process.env.TEST_MCP_DYNAMIC_URL;+ process.env.TEST_MCP_DYNAMIC_URL = 'https://mcp.example.test/{{LIBRECHAT_USER_ID}}';+ try {+ expect(+ getMCPToolApprovalAuthKind({ ...selected, url: '${TEST_MCP_DYNAMIC_URL}' }),+ ).toBeUndefined();+ } finally {+ if (saved == null) delete process.env.TEST_MCP_DYNAMIC_URL;+ else process.env.TEST_MCP_DYNAMIC_URL = saved;+ }+});diff --git a/packages/api/src/mcp/approval.ts b/packages/api/src/mcp/approval.tsnew file mode 100644index 0000000000..c2bc431ea7--- /dev/null+++ b/packages/api/src/mcp/approval.ts@@ -0,0 +1,103 @@+import { digestMCPAuthorityValue } from '@librechat/data-schemas';+import type { ToolApprovalAuthKind } from 'librechat-data-provider';+import type { IUser } from '@librechat/data-schemas';+import type { ParsedServerConfig } from './types';+import type { RequestBody } from '~/types';+import { isOAuthServer, hasRuntimeUrlPlaceholders } from './utils';+import { isDirectOpenIDBearerRecoveryEnabled } from './openid';+import { processMCPEnv, isPluginSourced } from '~/utils/env';+import { applyRequestHeaders } from './utils';++export interface MCPToolReviewAuthorityInput {+ serverName: string;+ config: ParsedServerConfig | undefined;+ user?: Partial<+ Pick<+ IUser,+ | 'id'+ | 'tenantId'+ | 'username'+ | 'email'+ | 'name'+ | 'openidId'+ | 'provider'+ | 'openidTokens'+ | 'federatedTokens'+ >+ >;+ body?: RequestBody;+ customUserVars?: Record<string, string>;+}++/** Match the configured factory path, not the existence of old stored tokens. */+export function getMCPToolApprovalAuthKind(+ config: ParsedServerConfig | undefined,+): ToolApprovalAuthKind | undefined {+ if (!config) return undefined;+ const effective = applyRequestHeaders(config);+ if (effective.obo || isDirectOpenIDBearerRecoveryEnabled(effective)) return 'other';+ if (isOAuthServer(effective)) return 'oauth';+ // UserConnectionManager detects auth only after a trusted runtime URL resolves.+ if (+ effective.requiresOAuth == null &&+ effective.apiKey == null &&+ hasRuntimeUrlPlaceholders(effective)+ )+ return undefined;+ return 'other';+}++/** Registry timestamps and inspection summaries do not change executable authority. */+export function projectMCPApprovalAuthority(config: ParsedServerConfig): ParsedServerConfig {+ const {+ updatedAt: _updatedAt,+ initDuration: _duration,+ capabilities: _capabilities,+ tools: _tools,+ toolFunctions: _functions,+ resolvedInstructions: _instructions,+ inspectionFailed: _failed,+ ...authority+ } = config;+ return authority;+}++/** Renewable bearer bytes are not authority; routing, principal and provider configuration are. */+export function buildMCPToolReviewAuthority({+ serverName,+ config,+ user,+ body,+ customUserVars,+}: MCPToolReviewAuthorityInput): string | undefined {+ if (!config) return undefined;+ config = projectMCPApprovalAuthority(applyRequestHeaders(config));+ const renewableMarker =+ /\{\{LIBRECHAT_(?:OPENID_(?:(?:ACCESS|ID)_)?TOKEN|GRAPH_ACCESS_TOKEN)\}\}/g;+ const mask = (value: string): string =>+ value.replace(renewableMarker, 'review-only-renewable-bearer');+ const resolved = processMCPEnv({+ options: config,+ user,+ body,+ customUserVars,+ beforeCredentialResolution: mask,+ });+ const projected = { ...resolved } as typeof resolved & {+ headers?: Record<string, string>;+ oauth_headers?: Record<string, string>;+ };+ const target = {+ url: 'url' in projected ? projected.url : undefined,+ command: 'command' in projected ? projected.command : undefined,+ args: 'args' in projected ? projected.args : undefined,+ };+ if (!isPluginSourced(config) && /\{\{[^{}]+\}\}|\$\{[^{}]+\}/.test(JSON.stringify(target)))+ return undefined;+ return digestMCPAuthorityValue({+ serverName,+ principal: { id: user?.id, tenantId: user?.tenantId, openidId: user?.openidId },+ declared: config,+ resolved: projected,+ });+}diff --git a/packages/api/src/mcp/connection.ts b/packages/api/src/mcp/connection.tsindex d44d917dde..fddd6b8f1f 100644--- a/packages/api/src/mcp/connection.ts+++ b/packages/api/src/mcp/connection.ts@@ -42,6 +42,7 @@ import {import { MCP_APPS_CAPABILITY_PROFILE, STANDARD_MCP_CAPABILITY_PROFILE } from './capabilities';import { createSSRFSafeUndiciConnect, isSSRFTarget, resolveHostnameSSRF } from '~/auth';import { projectMCPAppRuntimeTarget, type MCPAppRuntimeTarget } from './apps/binding';+import { assertToolApprovalTransportEpoch } from '~/tools/approval';import { reserveMCPToolsChangedRevision } from './toolsChanged';import { runOutsideTracing } from '~/utils/tracing';import { mediaTypeEssence } from '~/utils/headers';@@ -2303,6 +2304,12 @@ export class MCPConnection extends EventEmitter {this.lastPingTime = Date.now();}const method = 'method' in msg ? msg.method : undefined;+ if (method === 'tools/call') {+ await assertToolApprovalTransportEpoch(+ this.serverName,+ this.oauthTokens?.credential_set_id ?? null,+ );+ }const id = 'id' in msg ? (msg as { id: string | number | null }).id : undefined;logger.debug(`${this.getLogPrefix()} Transport sending: method=${method ?? 'response'} id=${id ?? 'none'}`,diff --git a/packages/api/src/mcp/status.spec.ts b/packages/api/src/mcp/status.spec.tsnew file mode 100644index 0000000000..deb347502b--- /dev/null+++ b/packages/api/src/mcp/status.spec.ts@@ -0,0 +1,43 @@+import { z } from 'zod';+import { ToolMessage } from '@librechat/agents/langchain/messages';+import { markMCPToolResultError, isMCPToolResultError } from './status';+import { createMCPStructuredTool } from './tools';+import { formatToolContent } from './parsers';++test('protocol errors retain content and status through the structured-tool adapter', async () => {+ const formatted = markMCPToolResultError(+ formatToolContent(+ { isError: true, content: [{ type: 'text', text: 'Invalid query' }] },+ 'openai',+ ),+ true,+ );+ const probe = createMCPStructuredTool(async () => formatted, {+ name: 'probe',+ description: 'Protocol status probe',+ schema: z.object({}),+ responseFormat: 'content_and_artifact',+ });+ const result = await probe.invoke({ name: 'probe', args: {}, id: 'call-a', type: 'tool_call' });+ expect(result).toBeInstanceOf(ToolMessage);+ expect(result.status).toBe('error');+ expect(JSON.stringify(result.content)).toContain('Invalid query');+ expect(result.tool_call_id).toBe('call-a');+ expect(isMCPToolResultError(JSON.parse(JSON.stringify(formatted)))).toBe(false);+});++test('successful MCP results retain their existing content and artifact contract', async () => {+ const formatted = markMCPToolResultError(+ formatToolContent({ content: [{ type: 'text', text: 'Success' }] }, 'openai'),+ false,+ );+ const probe = createMCPStructuredTool(async () => formatted, {+ name: 'probe',+ description: 'Protocol status probe',+ schema: z.object({}),+ responseFormat: 'content_and_artifact',+ });+ const result = await probe.invoke({ name: 'probe', args: {}, id: 'call-a', type: 'tool_call' });+ expect(result.status).toBe('success');+ expect(result.artifact).toEqual(formatted[1]);+});diff --git a/packages/api/src/mcp/status.ts b/packages/api/src/mcp/status.tsnew file mode 100644index 0000000000..5081b25b21--- /dev/null+++ b/packages/api/src/mcp/status.ts@@ -0,0 +1,11 @@+const failedResults = new WeakSet<object>();++/** Preserve the protocol status outside untrusted content and provider payloads. */+export function markMCPToolResultError<T extends object>(result: T, failed: boolean): T {+ if (failed) failedResults.add(result);+ return result;+}++export function isMCPToolResultError(result: object): boolean {+ return failedResults.has(result);+}diff --git a/packages/api/src/mcp/tools.ts b/packages/api/src/mcp/tools.tsindex 70d324c832..fb6de6632b 100644--- a/packages/api/src/mcp/tools.ts+++ b/packages/api/src/mcp/tools.ts@@ -1,4 +1,5 @@import { logger } from '@librechat/data-schemas';+import { ToolMessage } from '@librechat/agents/langchain/messages';import { DynamicStructuredTool } from '@librechat/agents/langchain/tools';import { patchConfig, pickRunnableConfigKeys } from '@langchain/core/runnables';import { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';@@ -8,14 +9,16 @@ import {normalizeServerName,stripServerNamePrefixes,} from 'librechat-data-provider';+import type { JsonSchemaType, SubagentExecutionContext } from '@librechat/agents';import type { Tool } from '@modelcontextprotocol/sdk/types.js';-import type { JsonSchemaType } from '@librechat/agents';import type { LCAvailableTools, LCFunctionTool, ParsedServerConfig } from './types';import type { MCPClientCapabilityProfile } from './capabilities';+import { assertToolApprovalExecution, withToolApprovalTransport } from '~/tools/approval';import { canUseAppConnection, requiresEphemeralUserConnection } from './utils';import { normalizeJsonSchema, resolveJsonSchemaRefs } from './zod';import { STANDARD_MCP_CAPABILITY_PROFILE } from './capabilities';import { getMCPToolCatalogGeneration } from './toolsChanged';+import { isMCPToolResultError } from './status';import { isToolHiddenFromModel } from './apps';type DynamicStructuredToolFields = ConstructorParameters<typeof DynamicStructuredTool>[0];@@ -28,16 +31,42 @@ export function createMCPStructuredTool() => ReturnType<DynamicStructuredToolFunction>,fields: Omit<DynamicStructuredToolFields, 'func'>,): DynamicStructuredTool<unknown> {- return new DynamicStructuredTool({+ const tool = new DynamicStructuredTool({...fields,- func: (input, runManager, config) => {+ func: async (input, runManager, config) => {+ const invocation = config as typeof config & {+ toolCall?: { id?: string };+ configurable?: { __librechatBackgroundToolInvocation?: boolean };+ metadata?: {+ executingAgentId?: string;+ activeAgentId?: string;+ agentId?: string;+ executionContext?: SubagentExecutionContext;+ };+ };+ const approvalInvocation = await assertToolApprovalExecution(tool, invocation);const childConfig = patchConfig(config, { callbacks: runManager?.getChild() });- return AsyncLocalStorageProviderSingleton.runWithConfig(+ const result = await AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig),- () => func(input, childConfig),+ () =>+ withToolApprovalTransport(invocation, () => func(input, childConfig), approvalInvocation),);+ if (Array.isArray(result) && result.length === 2 && isMCPToolResultError(result)) {+ return [+ new ToolMessage({+ content: result[0],+ artifact: result[1],+ status: 'error',+ tool_call_id: invocation?.toolCall?.id ?? '',+ name: fields.name,+ }),+ result[1],+ ];+ }+ return result;},});+ return tool;}/** `_meta` carries the MCP Apps `ui.visibility` used to hide app-only tools from the model. */diff --git a/packages/api/src/middleware/capabilities.integration.spec.ts b/packages/api/src/middleware/capabilities.integration.spec.tsindex 7aa460fed2..d2ed7e432c 100644--- a/packages/api/src/middleware/capabilities.integration.spec.ts+++ b/packages/api/src/middleware/capabilities.integration.spec.ts@@ -1,4 +1,7 @@+import express from 'express';+import request from 'supertest';import mongoose, { Types } from 'mongoose';+import { tenantStorage } from '@librechat/data-schemas';import { MongoMemoryServer } from 'mongodb-memory-server';import { PrincipalType, SystemRoles } from 'librechat-data-provider';import {@@ -14,6 +17,7 @@ import {capabilityStore,capabilityContextMiddleware,} from './capabilities';+import { createResetToolApprovalController } from '~/agents/hitl/controller';jest.mock('@librechat/data-schemas', () => ({...jest.requireActual('@librechat/data-schemas'),@@ -222,6 +226,51 @@ describe('capabilities integration (real MongoDB)', () => {expect(tenantResult).toBe(true);});+ it('personal approval reset honors manage:agents only in its tenant, without a VIEW ACL', async () => {+ await methods.grantCapability({+ principalType: PrincipalType.USER,+ principalId: regularUser.id,+ capability: SystemCapabilities.MANAGE_AGENTS,+ tenantId: 'tenant-a',+ });+ let tenantId = 'tenant-a';+ const acl = jest.fn(async () => false);+ const reset = jest.fn(methods.resetToolApprovalGrants);+ const controller = createResetToolApprovalController({+ getAgent: async () => ({ id: 'shared-agent' }),+ hasCapability,+ canAccessAgent: acl,+ storage: { ...methods, resetToolApprovalGrants: reset },+ });+ const app = express();+ app.use(express.json());+ app.post('/reset', (req, res) =>+ tenantStorage.run({ tenantId }, () =>+ controller(Object.assign(req, { user: { ...regularUser, tenantId } }), res),+ ),+ );+ await request(app)+ .post('/reset')+ .send({ agentId: 'shared-agent' })+ .expect(200, { reset: true });+ expect(acl).not.toHaveBeenCalled();+ expect(reset).toHaveBeenCalledWith(regularUser.id, 'shared-agent', undefined);+ expect(+ await mongoose.models.ToolApprovalGrant.countDocuments({+ user: regularUser.id,+ tenantId: 'tenant-a',+ agentId: 'shared-agent',+ }),+ ).toBe(1);+ tenantId = 'tenant-b';+ await request(app).post('/reset').send({ agentId: 'shared-agent' }).expect(403);+ expect(acl).toHaveBeenCalled();+ expect(reset).toHaveBeenCalledTimes(1);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments({ tenantId: 'tenant-b' })).toBe(+ 0,+ );+ });+it('hasConfigCapability falls back to section-specific grant', async () => {await methods.grantCapability({principalType: PrincipalType.USER,diff --git a/packages/api/src/tools/approval.spec.ts b/packages/api/src/tools/approval.spec.tsnew file mode 100644index 0000000000..cdbb2f55dc--- /dev/null+++ b/packages/api/src/tools/approval.spec.ts@@ -0,0 +1,126 @@+import {+ bindToolApproval,+ getToolApprovalBinding,+ bindToolApprovalIdentity,+ getToolApprovalIdentity,+ assertToolApprovalExecution,+ withToolApprovalExecution,+ bindToolReviewAuthority,+ getToolReviewAuthority,+} from './approval';+import {+ bindToolApprovalInvocation,+ noteToolApprovalDispatch,+ withToolApprovalTransport,+ assertToolApprovalTransportEpoch,+} from './approval';+import { getToolApprovalAuthKind } from './approval';++test('connection-derived bindings survive local copies without reaching JSON or provider payloads', () => {+ const definition = bindToolApproval(+ { name: 'query_mcp_db', parameters: { type: 'object' } },+ 'private-source-hash',+ );+ const copied = { ...definition };+ expect(getToolApprovalBinding(copied)).toBe('private-source-hash');+ expect(JSON.parse(JSON.stringify(copied))).toEqual({+ name: 'query_mcp_db',+ parameters: { type: 'object' },+ });+ expect(JSON.stringify(copied)).not.toContain('private-source-hash');+});++test('raw target fingerprints stay private when definitions are copied or serialized', () => {+ const definition = bindToolApprovalIdentity(+ { name: 'query_mcp_db', parameters: { type: 'object' } },+ 'db_query',+ { type: 'object' },+ );+ expect(getToolApprovalIdentity({ ...definition })).toEqual(expect.any(String));+ expect(getToolApprovalIdentity(JSON.parse(JSON.stringify(definition)))).toBeUndefined();+});++test('concurrent runs isolate the execution guard without a global run-id lookup', async () => {+ const first = jest.fn(async () => {});+ const second = jest.fn(async () => {});+ await Promise.all([+ withToolApprovalExecution({ validateExecution: first }, async () => {+ await new Promise((resolve) => setImmediate(resolve));+ await assertToolApprovalExecution(+ { name: 'query_mcp_db' },+ { toolCall: { id: 'first' }, metadata: { activeAgentId: 'agent-a' } },+ );+ }),+ withToolApprovalExecution({ validateExecution: second }, async () => {+ await assertToolApprovalExecution(+ { name: 'query_mcp_db' },+ { toolCall: { id: 'second' }, metadata: { activeAgentId: 'agent-b' } },+ );+ }),+ ]);+ expect(first).toHaveBeenCalledWith(+ { name: 'query_mcp_db' },+ { agentId: 'agent-a', toolCallId: 'first', background: false },+ );+ expect(second).toHaveBeenCalledWith(+ { name: 'query_mcp_db' },+ { agentId: 'agent-b', toolCallId: 'second', background: false },+ );+ await assertToolApprovalExecution({ name: 'query_mcp_db' });+ expect(first).toHaveBeenCalledTimes(1);+ expect(second).toHaveBeenCalledTimes(1);+});++test('invocation-only authority stays private while surviving internal definition copies', () => {+ const definition = bindToolReviewAuthority({ name: 'query_mcp_db' }, 'private-review-authority');+ expect(getToolReviewAuthority({ ...definition })).toBe('private-review-authority');+ expect(JSON.stringify(definition)).not.toContain('private-review-authority');+});++test('private dispatch ownership survives metadata copies and binds the exact transport invocation', async () => {+ const token = Symbol('invocation');+ const dispatch = { agentId: 'agent-a', toolCallId: 'call_0', background: true };+ const execution = {+ validateExecution: jest.fn(async () => {}),+ noteDispatch: (invocation: import('./approval').ToolApprovalInvocation) => {+ invocation.ownership = token;+ },+ validateTransport: jest.fn(async () => {}),+ };+ await withToolApprovalExecution(execution, async () => {+ noteToolApprovalDispatch(dispatch);+ const metadata = { ...bindToolApprovalInvocation({ agentId: 'agent-a' }, dispatch) };+ expect(JSON.stringify(metadata)).toBe('{"agentId":"agent-a"}');+ const config = {+ toolCall: { id: 'call_0' },+ metadata,+ configurable: { __librechatBackgroundToolInvocation: true },+ };+ const approved = await assertToolApprovalExecution({ name: 'query_mcp_db' }, config);+ await withToolApprovalTransport(+ config,+ () => assertToolApprovalTransportEpoch('db', null),+ approved,+ );+ });+ expect(execution.validateTransport).toHaveBeenCalledWith(+ 'db',+ null,+ expect.objectContaining({ ownership: token, toolCallId: 'call_0' }),+ false,+ );+});++test('effective auth kind stays private while surviving definition copies', () => {+ const def = bindToolApproval(+ { name: 'query_mcp_db' },+ 'source',+ undefined,+ undefined,+ undefined,+ 'other',+ );+ expect(getToolApprovalAuthKind({ ...def })).toBe('other');+ expect(getToolApprovalAuthKind(JSON.parse(JSON.stringify(def)))).toBeUndefined();+ expect(JSON.stringify(def)).toBe('{"name":"query_mcp_db"}');+});diff --git a/packages/api/src/tools/approval.ts b/packages/api/src/tools/approval.tsnew file mode 100644index 0000000000..ef794d3268--- /dev/null+++ b/packages/api/src/tools/approval.ts@@ -0,0 +1,191 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import { digestMCPAuthorityValue } from '@librechat/data-schemas';+import type { ToolApprovalAuthKind } from 'librechat-data-provider';+import type { SubagentExecutionContext } from '@librechat/agents';+const invocationKey: unique symbol = Symbol('toolApprovalInvocation');+const bindingKey: unique symbol = Symbol.for('librechat.toolApprovalBinding');+const nameKey: unique symbol = Symbol.for('librechat.toolApprovalName');+const identityKey: unique symbol = Symbol.for('librechat.toolApprovalIdentity');+const authKindKey: unique symbol = Symbol.for('librechat.toolApprovalAuthKind');+const reviewAuthorityKey: unique symbol = Symbol.for('librechat.toolReviewAuthority');+type BoundTool = {+ [bindingKey]?: string;+ [nameKey]?: string;+ [identityKey]?: string;+ [reviewAuthorityKey]?: string;+ [authKindKey]?: ToolApprovalAuthKind;+};++/** Object spreads retain the binding; JSON/provider payloads cannot expose it. */+export function bindToolApproval<T extends object>(+ tool: T,+ binding: string | undefined,+ name?: string,+ identity?: string,+ reviewAuthority?: string,+ authKind?: ToolApprovalAuthKind,+): T {+ if (binding != null) (tool as BoundTool)[bindingKey] = binding;+ if (name != null) (tool as BoundTool)[nameKey] = name;+ if (identity != null) (tool as BoundTool)[identityKey] = identity;+ if (reviewAuthority != null) (tool as BoundTool)[reviewAuthorityKey] = reviewAuthority;+ if (authKind != null) (tool as BoundTool)[authKindKey] = authKind;+ return tool;+}++export function getToolApprovalAuthKind(tool: object): ToolApprovalAuthKind | undefined {+ return (tool as BoundTool)[authKindKey];+}++export function getToolApprovalBinding(tool: object): string | undefined {+ return (tool as BoundTool)[bindingKey];+}++export function getToolApprovalName(tool: object): string | undefined {+ return (tool as BoundTool)[nameKey];+}++export function bindToolApprovalIdentity<T extends object>(+ tool: T,+ upstreamName: string,+ parameters?: object,+ description?: string,+): T {+ (tool as BoundTool)[identityKey] = digestMCPAuthorityValue({+ upstreamName,+ parameters,+ description,+ });+ return tool;+}++export function getToolApprovalIdentity(tool: object): string | undefined {+ return (tool as BoundTool)[identityKey];+}++export function bindToolReviewAuthority<T extends object>(+ tool: T,+ authority: string | undefined,+): T {+ if (authority != null) (tool as BoundTool)[reviewAuthorityKey] = authority;+ return tool;+}++export function getToolReviewAuthority(tool: object): string | undefined {+ return (tool as BoundTool)[reviewAuthorityKey] ?? getToolApprovalBinding(tool);+}++export interface ToolApprovalInvocation {+ agentId?: string;+ toolCallId?: string;+ executionScope?: string;+ background?: boolean;+ /** Process-local ownership capability; never serialized. */+ ownership?: symbol;+}++export function bindToolApprovalInvocation<T extends object>(+ metadata: T,+ invocation: ToolApprovalInvocation,+): T {+ Object.assign(metadata, { [invocationKey]: invocation });+ return metadata;+}++export function getToolApprovalExecutionScope(+ context?: Pick<SubagentExecutionContext, 'ancestry'>,+): string | undefined {+ const ancestry = context?.ancestry;+ return ancestry?.length ? ancestry[ancestry.length - 1].subagentRunId : undefined;+}++export interface ToolApprovalExecution {+ validateExecution: (tool: { name: string }, invocation: ToolApprovalInvocation) => Promise<void>;+ validateTransport?: (+ serverName: string,+ oauthEpoch: string | null,+ invocation: ToolApprovalInvocation,+ checkStorage: boolean,+ ) => Promise<void>;+ noteDispatch?: (invocation: ToolApprovalInvocation) => void;+ finishDispatch?: (invocation: ToolApprovalInvocation) => void;+}++const executionContext = new AsyncLocalStorage<ToolApprovalExecution>();+const transportContext = new AsyncLocalStorage<{+ execution: ToolApprovalExecution;+ invocation: ToolApprovalInvocation;+}>();++type InvocationConfig = Parameters<typeof assertToolApprovalExecution>[1];+function getInvocation(config: InvocationConfig): ToolApprovalInvocation {+ const bound = (config?.metadata as { [invocationKey]?: ToolApprovalInvocation } | undefined)?.[+ invocationKey+ ];+ return {+ agentId:+ config?.metadata?.executingAgentId ??+ config?.metadata?.activeAgentId ??+ config?.metadata?.agentId,+ toolCallId: config?.toolCall?.id,+ executionScope: getToolApprovalExecutionScope(config?.metadata?.executionContext),+ background: config?.configurable?.__librechatBackgroundToolInvocation === true,+ ...(bound?.ownership ? { ownership: bound.ownership } : {}),+ };+}++export function withToolApprovalTransport<T>(+ config: InvocationConfig,+ invoke: () => T,+ invocation: ToolApprovalInvocation = getInvocation(config),+): T {+ const execution = executionContext.getStore();+ return execution ? transportContext.run({ execution, invocation }, invoke) : invoke();+}++/** Reconnect and SDK-internal retries cannot change the credential generation a call approved. */+export async function assertToolApprovalTransportEpoch(+ serverName: string,+ oauthEpoch: string | null,+ checkStorage = false,+): Promise<void> {+ const context = transportContext.getStore();+ await context?.execution.validateTransport?.(+ serverName,+ oauthEpoch,+ context.invocation,+ checkStorage,+ );+}++/** Async context keeps policy capabilities out of checkpoint, request and model data. */+export function withToolApprovalExecution<T>(execution: ToolApprovalExecution, invoke: () => T): T {+ return executionContext.run(execution, invoke);+}++export async function assertToolApprovalExecution(+ tool: { name: string },+ config?: {+ toolCall?: { id?: string };+ configurable?: { __librechatBackgroundToolInvocation?: boolean };+ metadata?: {+ executingAgentId?: string;+ activeAgentId?: string;+ agentId?: string;+ executionContext?: SubagentExecutionContext;+ };+ },+): Promise<ToolApprovalInvocation> {+ const execution = executionContext.getStore();+ const invocation = getInvocation(config);+ if (execution) await execution.validateExecution(tool, invocation);+ return invocation;+}++export function noteToolApprovalDispatch(invocation: ToolApprovalInvocation): void {+ executionContext.getStore()?.noteDispatch?.(invocation);+}++export function finishToolApprovalDispatch(invocation: ToolApprovalInvocation): void {+ executionContext.getStore()?.finishDispatch?.(invocation);+}diff --git a/packages/api/src/tools/classification.spec.ts b/packages/api/src/tools/classification.spec.tsindex 5ca9b0faab..51a0927358 100644--- a/packages/api/src/tools/classification.spec.ts+++ b/packages/api/src/tools/classification.spec.ts@@ -12,6 +12,8 @@ import {getServerNameFromTool,agentHasDeferredTools,} from './classification';+import { bindToolApproval, getToolApprovalAuthKind } from './approval';+import { extractMCPToolDefinition } from './classification';describe('classification.ts', () => {describe('getServerNameFromTool', () => {@@ -777,3 +779,36 @@ describe('classification.ts', () => {});});});++test.each(['oauth', 'other'] as const)(+ 'classification and both registries preserve private %s auth provenance',+ async (kind) => {+ const tool = bindToolApproval(+ {+ name: 'query_mcp_db',+ mcp: true,+ mcpRawServerName: 'db',+ mcpJsonSchema: { type: 'object' as const },+ },+ 'source',+ undefined,+ undefined,+ undefined,+ kind,+ );+ const definition = extractMCPToolDefinition(tool);+ expect(getToolApprovalAuthKind(definition)).toBe(kind);+ const configured = buildToolRegistryFromAgentOptions([definition], {+ query_mcp_db: { approval_mode: 'always' },+ });+ expect(getToolApprovalAuthKind(configured.get('query_mcp_db')!)).toBe(kind);+ const plain = await buildToolClassification({+ userId: 'user-a',+ agentId: 'agent-a',+ loadedTools: [tool as unknown as GenericTool],+ definitionsOnly: true,+ deferredToolsEnabled: false,+ });+ expect(getToolApprovalAuthKind(plain.toolRegistry!.get('query_mcp_db')!)).toBe(kind);+ },+);diff --git a/packages/api/src/tools/classification.ts b/packages/api/src/tools/classification.tsindex 2c84a193e5..b06b609dfb 100644--- a/packages/api/src/tools/classification.ts+++ b/packages/api/src/tools/classification.ts@@ -1,3 +1,12 @@+import {+ bindToolApproval,+ getToolApprovalBinding,+ getToolApprovalName,+ getToolApprovalIdentity,+ bindToolApprovalIdentity,+} from './approval';+import { getToolApprovalAuthKind } from './approval';+import { getToolReviewAuthority } from './approval';/*** @fileoverview Utility functions for building tool registries from agent tool_options.* Tool classification (deferred_tools, allowed_callers) is configured via the agent UI.@@ -158,6 +167,14 @@ export function buildToolRegistryFromAgentOptions(toolDef.serverName = tool.serverName;}+ bindToolApproval(+ toolDef,+ getToolApprovalBinding(tool),+ getToolApprovalName(tool),+ getToolApprovalIdentity(tool),+ getToolReviewAuthority(tool),+ getToolApprovalAuthKind(tool),+ );registry.set(name, toolDef);}@@ -192,6 +209,14 @@ export function extractMCPToolDefinition(tool: MCPToolInstance): ToolDefinitiondef.description = tool.description;}+ bindToolApproval(+ def,+ getToolApprovalBinding(tool),+ getToolApprovalName(tool),+ getToolApprovalIdentity(tool),+ getToolReviewAuthority(tool),+ getToolApprovalAuthKind(tool),+ );if (tool.mcpJsonSchema) {def.parameters = tool.mcpJsonSchema;}@@ -205,8 +230,22 @@ export function extractMCPToolDefinition(tool: MCPToolInstance): ToolDefinitiondef.serverToolName = tool.mcpServerToolName;}- if (tool.mcpCurrentToolName) {+ if (getToolApprovalIdentity(def) == null && serverName) {+ const suffix = `${Constants.mcp_delimiter}${normalizeServerName(serverName)}`;+ const upstreamName =+ tool.mcpServerToolName ??+ (tool.name.endsWith(suffix) ? tool.name.slice(0, -suffix.length) : undefined);+ if (upstreamName != null)+ bindToolApprovalIdentity(def, upstreamName, def.parameters, def.description);+ }++ if (tool.mcpCurrentToolName && serverName) {def.currentToolName = tool.mcpCurrentToolName;+ bindToolApproval(+ def,+ getToolApprovalBinding(def),+ `${tool.mcpCurrentToolName}${Constants.mcp_delimiter}${normalizeServerName(serverName)}`,+ );}return def;@@ -247,13 +286,23 @@ function buildToolRegistry(/** No agent options - build basic definitions for event-driven mode */const registry: LCToolRegistry = new Map<string, LCTool>();for (const toolDef of mcpToolDefs) {- registry.set(toolDef.name, {- name: toolDef.name,- description: toolDef.description,- parameters: toolDef.parameters,- serverName: toolDef.serverName,- toolType: 'mcp',- });+ registry.set(+ toolDef.name,+ bindToolApproval(+ {+ name: toolDef.name,+ description: toolDef.description,+ parameters: toolDef.parameters,+ serverName: toolDef.serverName,+ toolType: 'mcp',+ },+ getToolApprovalBinding(toolDef),+ getToolApprovalName(toolDef),+ getToolApprovalIdentity(toolDef),+ getToolReviewAuthority(toolDef),+ getToolApprovalAuthKind(toolDef),+ ),+ );}return registry;}diff --git a/packages/api/src/tools/definitions.spec.ts b/packages/api/src/tools/definitions.spec.tsindex 89d71b5de8..9586c8322e 100644--- a/packages/api/src/tools/definitions.spec.ts+++ b/packages/api/src/tools/definitions.spec.ts@@ -6,7 +6,10 @@ import type {} from './definitions';import { toolkitExpansion, toolkitParent } from './toolkits/mapping';import { getToolDefinition } from './registry/definitions';+import { getToolApprovalIdentity } from './approval';import { loadToolDefinitions } from './definitions';+import { formatMCPServerTools } from '~/mcp/tools';+import { getToolApprovalName } from './approval';const MAX_PROVIDER_TOOL_DESCRIPTION_LENGTH = 1024;@@ -1226,3 +1229,82 @@ describe('definitions.ts', () => {});});});++test('definitions-only loading retains the verified reset key without collapsing a collision sibling', async () => {+ const current = 'query_mcp_db';+ const legacy = 'db_query_mcp_db';+ const catalog = {+ [current]: {+ function: { name: current, parameters: { type: 'object' as const } },+ serverToolName: 'db_query',+ },+ };+ const options = {+ [current]: {+ approval_mode: 'chat' as const,+ approval_revision: 'c09e8bb4-00fa-41be-90ca-f53f1a0c1f05',+ },+ };+ const result = await loadToolDefinitions(+ {+ userId: 'user-a',+ agentId: 'agent-a',+ tools: [legacy],+ toolOptions: options,+ mcpServerNames: ['db'],+ rawServerNames: ['db'],+ },+ {+ getOrFetchMCPServerTools: async () => catalog,+ isBuiltInTool: () => false,+ },+ );+ expect(result.toolDefinitions[0].name).toBe(legacy);+ expect(getToolApprovalName(result.toolDefinitions[0])).toBe(current);+ const collision = await loadToolDefinitions(+ {+ userId: 'user-a',+ agentId: 'agent-a',+ tools: [legacy],+ mcpServerNames: ['db'],+ rawServerNames: ['db'],+ },+ {+ getOrFetchMCPServerTools: async () => ({+ ...catalog,+ [legacy]: { function: { name: legacy, parameters: { type: 'object' as const } } },+ }),+ isBuiltInTool: () => false,+ },+ );+ expect(getToolApprovalName(collision.toolDefinitions[0])).toBeUndefined();+});++test('live catalog reassignment changes consent while retaining the same displayed key and schema', async () => {+ const upstream = (name: string) => ({+ name,+ description: 'Same description',+ inputSchema: { type: 'object' as const, properties: {} },+ });+ const before = formatMCPServerTools('db', [upstream('query'), upstream('db_query')]);+ const after = formatMCPServerTools('db', [upstream('db_query')]);+ const params = {+ userId: 'user-a',+ agentId: 'agent-a',+ tools: ['query_mcp_db'],+ mcpServerNames: ['db'],+ rawServerNames: ['db'],+ };+ const first = await loadToolDefinitions(params, {+ isBuiltInTool: () => false,+ getOrFetchMCPServerTools: async () => before,+ });+ const second = await loadToolDefinitions(params, {+ isBuiltInTool: () => false,+ getOrFetchMCPServerTools: async () => after,+ });+ expect(second.toolDefinitions[0].name).toBe(first.toolDefinitions[0].name);+ expect(getToolApprovalIdentity(second.toolDefinitions[0])).not.toBe(+ getToolApprovalIdentity(first.toolDefinitions[0]),+ );+});diff --git a/packages/api/src/tools/definitions.ts b/packages/api/src/tools/definitions.tsindex eb4b01064d..a2d4b03052 100644--- a/packages/api/src/tools/definitions.ts+++ b/packages/api/src/tools/definitions.ts@@ -1,3 +1,4 @@+import { bindToolApproval, bindToolApprovalIdentity, getToolApprovalIdentity } from './approval';/*** @fileoverview Tool definitions loader for event-driven mode.* Loads tool definitions without creating tool instances for efficient initialization.@@ -311,13 +312,28 @@ export async function loadToolDefinitions(if (isMCPAllPlaceholder(toolName)) {for (const [actualToolName, toolDef] of Object.entries(serverTools)) {if (toolDef?.function) {- mcpToolDefs.push({- name: actualToolName,- description: toolDef.function.description || undefined,- parameters: buildMcpParameters(toolDef.function.parameters),- serverName,- serverToolName: toolDef.serverToolName,- });+ mcpToolDefs.push(+ bindToolApprovalIdentity(+ {+ name: actualToolName,+ description: toolDef.function.description || undefined,+ parameters: buildMcpParameters(toolDef.function.parameters),+ serverName,+ serverToolName: toolDef.serverToolName,+ },+ toolDef.serverToolName ??+ actualToolName.slice(+ 0,+ -`${Constants.mcp_delimiter}${normalizeServerName(serverName)}`.length,+ ),+ normalizeJsonSchema(+ resolveJsonSchemaRefs(+ toolDef.function.parameters ?? { type: 'object', properties: {} },+ ),+ ),+ toolDef.function.description || undefined,+ ),+ );resolvedMCPToolCount++;}}@@ -326,14 +342,29 @@ export async function loadToolDefinitions(const toolMatch = findToolMatch(serverTools);if (toolMatch?.def.function) {- mcpToolDefs.push({- name: toolName,- description: toolMatch.def.function.description || undefined,- parameters: buildMcpParameters(toolMatch.def.function.parameters),- serverName,- serverToolName: toolMatch.def.serverToolName,- currentToolName: toolMatch.currentToolName,- });+ mcpToolDefs.push(+ bindToolApprovalIdentity(+ {+ name: toolName,+ description: toolMatch.def.function.description || undefined,+ parameters: buildMcpParameters(toolMatch.def.function.parameters),+ serverName,+ serverToolName: toolMatch.def.serverToolName,+ currentToolName: toolMatch.currentToolName,+ },+ toolMatch.def.serverToolName ??+ toolName.slice(+ 0,+ -`${Constants.mcp_delimiter}${normalizeServerName(serverName)}`.length,+ ),+ normalizeJsonSchema(+ resolveJsonSchemaRefs(+ toolMatch.def.function.parameters ?? { type: 'object', properties: {} },+ ),+ ),+ toolMatch.def.function.description || undefined,+ ),+ );resolvedMCPToolCount++;}}@@ -353,15 +384,22 @@ export async function loadToolDefinitions(});}- const loadedTools = mcpToolDefs.map((def) => ({- name: def.name,- description: def.description,- mcp: true as const,- mcpJsonSchema: def.parameters,- mcpRawServerName: def.serverName,- mcpServerToolName: def.serverToolName,- mcpCurrentToolName: def.currentToolName,- })) as unknown as GenericTool[];+ const loadedTools = mcpToolDefs.map((def) =>+ bindToolApproval(+ {+ name: def.name,+ description: def.description,+ mcp: true as const,+ mcpJsonSchema: def.parameters,+ mcpRawServerName: def.serverName,+ mcpServerToolName: def.serverToolName,+ mcpCurrentToolName: def.currentToolName,+ },+ undefined,+ undefined,+ getToolApprovalIdentity(def),+ ),+ ) as unknown as GenericTool[];const classificationResult = await buildToolClassification({userId,diff --git a/packages/api/src/utils/env.ts b/packages/api/src/utils/env.tsindex e980c272d1..70573ae982 100644--- a/packages/api/src/utils/env.ts+++ b/packages/api/src/utils/env.ts@@ -107,7 +107,10 @@ export function encodeHeaderValue(value: string): string {* @returns A new object containing only allowed fields plus federatedTokens if present*/export function createSafeUser(- user: IUser | null | undefined,+ user:+ | (Partial<SafeUser> & Pick<IUser, 'tenantId'> & { federatedTokens?: IUser['federatedTokens'] })+ | null+ | undefined,): Partial<SafeUser> & { federatedTokens?: IUser['federatedTokens'] } {if (!user) {return {};@@ -300,6 +303,7 @@ function processSingleValue({body = undefined,isHeader = false,dbSourced = false,+ beforeCredentialResolution,}: {originalValue: string;customUserVars?: Record<string, string>;@@ -308,6 +312,7 @@ function processSingleValue({isHeader?: boolean;/** When true, only resolve customUserVars — skip env vars, user/OpenID/body placeholders */dbSourced?: boolean;+ beforeCredentialResolution?: (value: string) => string;}): string {// Type guard: ensure we're working with a stringif (typeof originalValue !== 'string') {@@ -342,6 +347,7 @@ function processSingleValue({value = processUserPlaceholders(value, user, isHeader);+ value = beforeCredentialResolution?.(value) ?? value;const openidTokenInfo = extractOpenIDTokenInfo(user);if (openidTokenInfo && isOpenIDTokenValid(openidTokenInfo)) {value = processOpenIDPlaceholders(value, openidTokenInfo);@@ -393,8 +399,10 @@ export function processMCPEnv(params: {body?: RequestBody;/** When true, only resolve customUserVars — skip env vars, user/OpenID/body placeholders (for DB-stored servers) */dbSourced?: boolean;+ /** Trusted projection hook, after substitutions and before credential resolution. */+ beforeCredentialResolution?: (value: string) => string;}): MCPOptions {- const { options, user, body } = params;+ const { options, user, body, beforeCredentialResolution } = params;if (options === null || options === undefined) {return options;@@ -446,6 +454,7 @@ export function processMCPEnv(params: {user,body,dbSourced,+ beforeCredentialResolution,originalValue,customUserVars,});@@ -457,7 +466,14 @@ export function processMCPEnv(params: {const processedArgs: string[] = [];for (const originalValue of newObj.args) {processedArgs.push(- processSingleValue({ originalValue, customUserVars, user, body, dbSourced }),+ processSingleValue({+ originalValue,+ customUserVars,+ user,+ body,+ dbSourced,+ beforeCredentialResolution,+ }),);}newObj.args = processedArgs;@@ -472,6 +488,7 @@ export function processMCPEnv(params: {user,body,dbSourced,+ beforeCredentialResolution,originalValue,customUserVars,isHeader: true, // Important: Enable header encoding@@ -488,6 +505,7 @@ export function processMCPEnv(params: {user,body,dbSourced,+ beforeCredentialResolution,originalValue,customUserVars,isHeader: true,@@ -502,6 +520,7 @@ export function processMCPEnv(params: {user,body,dbSourced,+ beforeCredentialResolution,customUserVars,originalValue: newObj.url,});@@ -523,6 +542,7 @@ export function processMCPEnv(params: {user,body,dbSourced,+ beforeCredentialResolution,originalValue,customUserVars,});diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 369526788d..7b182030c8 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -645,3 +645,5 @@ export const getAllEffectivePermissions = (resourceType: ResourceType) =>// SharePoint Graph API Tokenexport const graphToken = (scopes: string) =>`${BASE_URL}/api/auth/graph-token?scopes=${encodeURIComponent(scopes)}`;++export const resetToolApprovalGrants = (): string => `${BASE_URL}/api/agents/tools/approvals/reset`;diff --git a/packages/data-provider/src/approval.spec.ts b/packages/data-provider/src/approval.spec.tsnew file mode 100644index 0000000000..f840bfa06d--- /dev/null+++ b/packages/data-provider/src/approval.spec.ts@@ -0,0 +1,13 @@+import { getToolApprovalConstraint } from './approval';+import { toolApprovalPolicySchema } from './config';++test.each([+ [{ enabled: true, mode: 'bypass', deny: ['delete_*'] }, 'delete_mcp_db', 'deny'],+ [{ enabled: true, mode: 'bypass', ask: ['*_mcp_db'] }, 'query_mcp_db', 'ask'],+ [{ enabled: true, mode: 'default', allow: ['query_mcp_db'] }, 'query_mcp_db', undefined],+ [{ enabled: true, mode: 'dontAsk' }, 'query_mcp_db', 'deny'],+ [{ enabled: true }, 'query_mcp_db', 'ask'],+ [{ enabled: false, deny: ['*'] }, 'query_mcp_db', undefined],+] as const)('projects the administrator constraint for %s', (policy, name, expected) => {+ expect(getToolApprovalConstraint(toolApprovalPolicySchema.parse(policy), name)).toBe(expected);+});diff --git a/packages/data-provider/src/approval.ts b/packages/data-provider/src/approval.tsnew file mode 100644index 0000000000..be783ab736--- /dev/null+++ b/packages/data-provider/src/approval.ts@@ -0,0 +1,20 @@+import type { TToolApprovalPolicy } from './config';++/** Presentation-only constraints. Execution remains owned by the SDK policy hook. */+export function getToolApprovalConstraint(+ policy: TToolApprovalPolicy,+ toolName: string,+): 'ask' | 'deny' | undefined {+ if (policy?.enabled !== true) return undefined;+ const matches = (patterns?: string[]) =>+ patterns?.some((pattern) => {+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&');+ return new RegExp('^' + escaped.replace(/\*/g, '.*') + '$').test(toolName);+ }) === true;+ if (matches(policy.deny)) return 'deny';+ if (matches(policy.ask)) return 'ask';+ if (matches(policy.allow)) return undefined;+ if (policy.mode === 'dontAsk') return 'deny';+ if (policy.mode !== 'bypass') return 'ask';+ return undefined;+}diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 9c9961c8b9..61948abd0b 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1100,6 +1100,10 @@ export const toolApprovalPolicySchema = z.object({enabled: z.boolean().optional(),mode: toolApprovalModeSchema.optional(),+ /** Enable after all replicas support agent-scoped approval modes and grants. */+ agentModes: z.boolean().optional(),+ /** Bounded grant lookups fail back to manual review, never automatic approval. */+ grantLookupTimeoutMs: z.number().int().min(100).max(5000).optional(),allow: z.array(z.string()).optional(),deny: z.array(z.string()).optional(),ask: z.array(z.string()).optional(),diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex cc19d747a1..6c4b14efa8 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -567,6 +567,11 @@ export const callTool = <T extends m.ToolId>({);};+export const resetToolApprovalGrants = (params: {+ agentId: string;+ toolName?: string;+}): Promise<{ reset: true }> => request.post(endpoints.resetToolApprovalGrants(), params);+export const getToolCalls = (params: q.GetToolCallParams): Promise<q.ToolCallResults> => {return request.get(endpoints.agents({diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 4396e32067..df59360348 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -103,3 +103,5 @@ export * from './code/approval';export * from './code/workspace';export * from './types/scheduleConsent';++export * from './approval';diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex eb876ff2ce..c7aa940a43 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -123,6 +123,7 @@ export const DynamicQueryKeys = {} as const;export enum MutationKeys {+ resetToolApprovalGrants = 'resetToolApprovalGrants',subagentControl = 'subagentControl',cancelBackgroundTasks = 'cancelBackgroundTasks',enqueueAgentQueuedTurn = 'enqueueAgentQueuedTurn',diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.tsindex 2d771b30ce..2b7738fa82 100644--- a/packages/data-provider/src/types/agents.ts+++ b/packages/data-provider/src/types/agents.ts@@ -1,8 +1,13 @@/* eslint-disable @typescript-eslint/no-namespace */import { z } from 'zod';+import type {+ FunctionTool,+ ToolResources,+ AgentToolOptions,+ ToolApprovalGrantBinding,+} from './tools';import type { TAttachment, TPlugin, AgentProvider, MemoryScope, SkillsScope } from 'src/schemas';import type { TTokenUsageEvent, TContextUsageEvent, TPendingSteer } from './runs';-import type { FunctionTool, ToolResources, AgentToolOptions } from './tools';import type { StatefulCodeEnvironment } from '../stateful-code';import type { SummaryContentPart } from './content';import type { TFile } from './files';@@ -133,6 +138,8 @@ export namespace Agents {actionId: string;allowed_decisions: ToolApprovalDecisionType[];description?: string;+ remember_scope?: 'chat' | 'always';+ remember_unavailable?: 'connection' | 'disabled' | 'storage' | 'background';/** Server-authored: an `approve` may carry `scope: 'session'` for this call. */allow_always?: boolean;};@@ -472,6 +479,8 @@ export namespace Agents {* by `tool_call_id`. `action_name` is retained for display only.*/export interface ToolReviewConfig {+ remember_scope?: 'chat' | 'always';+ remember_unavailable?: 'connection' | 'disabled' | 'storage' | 'background';action_name: string;tool_call_id: string;allowed_decisions: ToolApprovalDecisionType[];@@ -599,6 +608,7 @@ export namespace Agents {* tool execution so an approval cannot migrate to another VM or workspace.*/codeExecutionBinding?: CodeExecutionApprovalBinding;+ toolApprovalBindings?: Record<string, ToolApprovalGrantBinding>;/*** Server-only MCP key-spelling pairs the paused run knew for the tools it offered* "Always allow", including pairs lazily resolved subagents reported. Resume rechecksdiff --git a/packages/data-provider/src/types/tools.ts b/packages/data-provider/src/types/tools.tsindex 26db147d12..ecd8650261 100644--- a/packages/data-provider/src/types/tools.ts+++ b/packages/data-provider/src/types/tools.ts@@ -77,11 +77,66 @@ export interface FileSearchResource {*/export type AllowedCaller = 'direct' | 'code_execution';+export const AGENT_TOOL_APPROVAL_MODES = ['ask', 'allow', 'chat', 'always'] as const;+export type AgentToolApprovalMode = (typeof AGENT_TOOL_APPROVAL_MODES)[number];++export type ToolApprovalAuthKind = 'oauth' | 'other';++export interface ToolApprovalGrantBinding {+ instanceName: string;+ /** SDK child execution identity; never part of remembered consent scope. */+ executionScope?: string;+ serverName?: string;+ /** Effective MCP authentication path; server-owned. Unset retains legacy OAuth checks. */+ authKind?: ToolApprovalAuthKind;+ /** Server-only OAuth authorization generation, not renewable token bytes. */+ oauthEpoch?: string | null;+ agentId: string;+ toolName: string;+ binding: string;+ scope: 'once' | 'chat' | 'always';+ revocation?: string;+ /** Existing consent at review capture; server-only compare-and-set witness. */+ consentBinding?: string | null;+ canRemember?: boolean;+ unavailable?: 'connection' | 'disabled' | 'storage' | 'background';+}++export interface ToolApprovalGrantScope {+ userId: string;+ tenantId?: string;+ conversationId: string;+}++export interface ToolApprovalGrantStorage {+ getToolApprovalGrants: (+ scope: ToolApprovalGrantScope,+ bindings: readonly ToolApprovalGrantBinding[],+ ) => Promise<+ Array<{+ binding: string;+ approved: boolean;+ revocation?: string;+ oauthEpoch?: string | null;+ consentBinding?: string | null;+ }>+ >;+ rememberToolApprovalGrants: (+ scope: ToolApprovalGrantScope,+ grants: readonly ToolApprovalGrantBinding[],+ ) => Promise<void>;+ resetToolApprovalGrants: (userId: string, agentId: string, toolName?: string) => Promise<void>;+}+/*** Per-tool configuration options stored at the agent level.* Keyed by tool_id (e.g., "search_mcp_github").*/export type ToolOptions = {+ /** Unset inherits the administrator policy. */+ approval_mode?: AgentToolApprovalMode;+ /** Changing a mode invalidates previously remembered approvals. */+ approval_revision?: string;/*** If true, the tool uses deferred loading (discoverable via tool search).* @default falsediff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.tsindex 074e5ea8c3..6baa5c0442 100644--- a/packages/data-schemas/src/methods/conversation.ts+++ b/packages/data-schemas/src/methods/conversation.ts@@ -3893,6 +3893,15 @@ export function createConversationMethods(logger.error('[deleteConvos] Conversations deleted but message cleanup failed', error);}+ try {+ await mongoose.models.ToolApprovalGrant?.deleteMany({+ user,+ conversationId: { $in: conversationIds },+ });+ } catch {+ logger.warn('[deleteConvos] Remembered approval cleanup failed.');+ }+// conversationIds lets callers run sibling cleanup that lives in higher layers// (e.g. pruning the conversations' durable agent checkpoints) without re-querying// documents that no longer exist.diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.tsindex c5417b8d7a..682adf8d82 100644--- a/packages/data-schemas/src/methods/index.ts+++ b/packages/data-schemas/src/methods/index.ts@@ -1,4 +1,6 @@+import type { ToolApprovalGrantStorage } from 'librechat-data-provider';import type { ScheduleMCPConsentStorage } from './scheduleConsent';+import { createToolApprovalGrantMethods } from './toolApprovalGrant';import { createScheduleMCPConsentStorage } from './scheduleConsent';export { createScheduleMCPConsentStorage } from './scheduleConsent';export type { ScheduleMCPConsentStorage, ScheduleConsentSnapshot } from './scheduleConsent';@@ -246,7 +248,8 @@ export {AgentQueuedTurnLaneRetiredError,};-export type AllMethods = UserMethods &+export type AllMethods = ToolApprovalGrantStorage &+ UserMethods &SessionMethods &TokenMethods &RefreshTokenBridgeMethods &@@ -484,6 +487,7 @@ export function createMethods(const agentMethods = createAgentMethods(mongoose, agentDeps);return {...createUserMethods(mongoose, { getCache: deps.getCache }),+ ...createToolApprovalGrantMethods(mongoose),...createSessionMethods(mongoose),...createTokenMethods(mongoose),...createRefreshTokenBridgeMethods(mongoose),diff --git a/packages/data-schemas/src/methods/toolApprovalGrant.spec.ts b/packages/data-schemas/src/methods/toolApprovalGrant.spec.tsnew file mode 100644index 0000000000..eda0fca89b--- /dev/null+++ b/packages/data-schemas/src/methods/toolApprovalGrant.spec.ts@@ -0,0 +1,540 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import type { ToolApprovalGrantBinding } from 'librechat-data-provider';+import { createToolApprovalGrantModel } from '../models/toolApprovalGrant';+import { createToolApprovalGrantMethods } from './toolApprovalGrant';+import { tenantStorage } from '~/config/tenantContext';+import { createModels } from '../models';++let mongo: MongoMemoryServer;+const scope = { userId: 'user-a', conversationId: 'chat-a' };+const grant: ToolApprovalGrantBinding = {+ agentId: 'agent-a',+ instanceName: 'query_mcp_db',+ toolName: 'query_mcp_db',+ binding: 'digest-a',+ scope: 'chat',+};+const storage = createToolApprovalGrantMethods(mongoose);++/** Delay only the real grant update, after its authoritative read has completed. */+function suspendGrantWrite() {+ let resume!: () => void;+ let reached!: () => void;+ const suspended = new Promise<void>((resolve) => {+ resume = resolve;+ });+ const started = new Promise<void>((resolve) => {+ reached = resolve;+ });+ const execute = mongoose.Query.prototype.exec;+ let paused = false;+ const execution = jest.spyOn(mongoose.Query.prototype, 'exec').mockImplementation(function (+ this: mongoose.Query<unknown, unknown>,+ ) {+ if (+ !paused &&+ this.model.modelName === 'ToolApprovalGrant' &&+ 'op' in this &&+ this.op === 'updateOne'+ ) {+ paused = true;+ reached();+ return suspended.then(() => execute.call(this));+ }+ return execute.call(this);+ });+ return { started, resume, restore: () => execution.mockRestore() };+}++beforeAll(async () => {+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await createToolApprovalGrantModel(mongoose).syncIndexes();+}, 60000);+afterAll(async () => {+ await mongoose.disconnect();+ await mongo?.stop();+});+beforeEach(async () => {+ await mongoose.models.ToolApprovalGrant.deleteMany({});+});++test('per-chat approval survives a rebuilt reader without crossing chats or users', async () => {+ await storage.rememberToolApprovalGrants(scope, [grant]);+ const rebuilt = createToolApprovalGrantMethods(mongoose);+ expect((await rebuilt.getToolApprovalGrants(scope, [grant]))[0].approved).toBe(true);+ expect(+ (await rebuilt.getToolApprovalGrants({ ...scope, conversationId: 'chat-b' }, [grant]))[0]+ .approved,+ ).toBe(false);+ expect(+ (await rebuilt.getToolApprovalGrants({ ...scope, userId: 'user-b' }, [grant]))[0].approved,+ ).toBe(false);+});++test('persistent approval crosses chats but a schema-binding change does not', async () => {+ await storage.rememberToolApprovalGrants(scope, [{ ...grant, scope: 'always' }]);+ expect(+ (await storage.getToolApprovalGrants({ ...scope, conversationId: 'chat-b' }, [grant]))[0]+ .approved,+ ).toBe(true);+ expect(+ (await storage.getToolApprovalGrants(scope, [{ ...grant, binding: 'digest-b' }]))[0].approved,+ ).toBe(false);+});++test('reset fences every chat and a late approval cannot resurrect the grant', async () => {+ await storage.rememberToolApprovalGrants(scope, [grant]);+ await storage.resetToolApprovalGrants(scope.userId, grant.agentId, grant.toolName);+ await storage.rememberToolApprovalGrants(scope, [grant]);+ const reset = (await storage.getToolApprovalGrants(scope, [grant]))[0];+ expect(reset.approved).toBe(false);+ expect(reset.revocation).toEqual(expect.any(String));+ await storage.rememberToolApprovalGrants(scope, [{ ...grant, revocation: reset.revocation }]);+ expect((await storage.getToolApprovalGrants(scope, [grant]))[0].approved).toBe(true);+});++test('parallel saves remain idempotent', async () => {+ await Promise.all(+ Array.from({ length: 6 }, () => storage.rememberToolApprovalGrants(scope, [grant])),+ );+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(1);+});++test('identical user and tool identifiers stay isolated between tenants', async () => {+ const tenantA = { ...scope, tenantId: 'tenant-a' };+ const tenantB = { ...scope, tenantId: 'tenant-b' };+ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ storage.rememberToolApprovalGrants(tenantA, [grant]),+ );+ const a = await tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ storage.getToolApprovalGrants(tenantA, [grant]),+ );+ const b = await tenantStorage.run({ tenantId: 'tenant-b' }, () =>+ storage.getToolApprovalGrants(tenantB, [grant]),+ );+ expect(a[0].approved).toBe(true);+ expect(b[0].approved).toBe(false);+ await tenantStorage.run({ tenantId: 'tenant-b' }, () =>+ storage.resetToolApprovalGrants(scope.userId, grant.agentId, grant.toolName),+ );+ expect(+ (+ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ storage.getToolApprovalGrants(tenantA, [grant]),+ )+ )[0].approved,+ ).toBe(true);+});++test('reset before the first stored grant fences a late approved execution', async () => {+ const initial = (await storage.getToolApprovalGrants(scope, [grant]))[0];+ await storage.resetToolApprovalGrants(scope.userId, grant.agentId, grant.toolName);+ await storage.rememberToolApprovalGrants(scope, [{ ...grant, revocation: initial.revocation }]);+ expect((await storage.getToolApprovalGrants(scope, [grant]))[0].approved).toBe(false);+});++test('one-time review bindings cannot become stored grants', async () => {+ await expect(+ storage.rememberToolApprovalGrants(scope, [{ ...grant, scope: 'once' }]),+ ).rejects.toThrow('One-time');+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(0);+});++test('OAuth consent is generation-bound without hashing renewable token bytes', async () => {+ const owner = new mongoose.Types.ObjectId().toString();+ const authScope = { userId: owner, conversationId: 'oauth-chat' };+ const bound = { ...grant, serverName: 'db', oauthEpoch: 'grant-a' };+ const row = await mongoose.models.Token.create({+ userId: owner,+ type: 'mcp_oauth',+ identifier: 'mcp:db',+ token: 'synthetic-token-a',+ expiresAt: new Date(Date.now() + 60000),+ metadata: { credential_set_id: 'grant-a' },+ });+ await storage.rememberToolApprovalGrants(authScope, [bound]);+ expect((await storage.getToolApprovalGrants(authScope, [bound]))[0].approved).toBe(true);+ await mongoose.models.Token.updateOne(+ { _id: row._id },+ { $set: { token: 'synthetic-refreshed-token' } },+ );+ expect((await storage.getToolApprovalGrants(authScope, [bound]))[0].approved).toBe(true);+ await mongoose.models.Token.updateOne(+ { _id: row._id },+ { $set: { 'metadata.credential_set_id': 'grant-b' } },+ );+ const changed = (await storage.getToolApprovalGrants(authScope, [bound]))[0];+ expect(changed.oauthEpoch).toBe('grant-b');+ expect(changed.approved).toBe(false);+ expect(JSON.stringify(changed)).not.toContain('synthetic-refreshed-token');+ await mongoose.models.Token.deleteOne({ _id: row._id });+});++test('agent-wide personal reset fences every learned tool without touching another user or agent', async () => {+ const persistent: ToolApprovalGrantBinding = {+ ...grant,+ toolName: 'other_mcp_db',+ instanceName: 'other_mcp_db',+ binding: 'digest-b',+ scope: 'always',+ };+ const anotherAgent = { ...grant, agentId: 'agent-b', binding: 'digest-agent-b' };+ await storage.rememberToolApprovalGrants(scope, [grant, persistent, anotherAgent]);+ await storage.rememberToolApprovalGrants({ ...scope, userId: 'user-b' }, [grant]);+ await storage.resetToolApprovalGrants(scope.userId, grant.agentId);+ // A completed in-flight approval still carries the pre-reset epoch.+ await storage.rememberToolApprovalGrants(scope, [grant, persistent]);+ expect(+ (await storage.getToolApprovalGrants(scope, [grant, persistent])).map(+ (status) => status.approved,+ ),+ ).toEqual([false, false]);+ expect((await storage.getToolApprovalGrants(scope, [anotherAgent]))[0].approved).toBe(true);+ expect(+ (await storage.getToolApprovalGrants({ ...scope, userId: 'user-b' }, [grant]))[0].approved,+ ).toBe(true);+});++test('agent-wide reset before the first grant fences every unseen in-flight tool', async () => {+ const pending: ToolApprovalGrantBinding = {+ ...grant,+ toolName: 'pending_mcp_db',+ instanceName: 'pending_mcp_db',+ binding: 'pending-binding',+ };+ await storage.resetToolApprovalGrants(scope.userId, grant.agentId);+ await storage.rememberToolApprovalGrants(scope, [grant, pending]);+ expect(+ (await storage.getToolApprovalGrants(scope, [grant, pending])).map((status) => status.approved),+ ).toEqual([false, false]);+});++test('agent-wide reset cannot cross tenant scope for the same user and tools', async () => {+ const other: ToolApprovalGrantBinding = {+ ...grant,+ toolName: 'other_mcp_db',+ instanceName: 'other_mcp_db',+ binding: 'digest-b',+ };+ const a = { ...scope, tenantId: 'tenant-a' };+ const b = { ...scope, tenantId: 'tenant-b' };+ for (const current of [a, b])+ await tenantStorage.run({ tenantId: current.tenantId }, () =>+ storage.rememberToolApprovalGrants(current, [grant, other]),+ );+ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ storage.resetToolApprovalGrants(scope.userId, grant.agentId),+ );+ expect(+ (+ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ storage.getToolApprovalGrants(a, [grant, other]),+ )+ ).map((status) => status.approved),+ ).toEqual([false, false]);+ expect(+ (+ await tenantStorage.run({ tenantId: 'tenant-b' }, () =>+ storage.getToolApprovalGrants(b, [grant, other]),+ )+ ).map((status) => status.approved),+ ).toEqual([true, true]);+});++for (const mode of ['chat', 'always'] as const) {+ for (const resetScope of ['tool', 'agent'] as const) {+ test(`${mode} consent renewed after ${resetScope} reset survives a late stale completion`, async () => {+ const pending = { ...grant, scope: mode };+ await storage.rememberToolApprovalGrants(scope, [pending]);+ await storage.resetToolApprovalGrants(+ scope.userId,+ grant.agentId,+ resetScope === 'tool' ? grant.toolName : undefined,+ );+ const current = (await storage.getToolApprovalGrants(scope, [pending]))[0];+ const renewed = { ...pending, revocation: current.revocation };+ await storage.rememberToolApprovalGrants(scope, [renewed]);+ await storage.rememberToolApprovalGrants(scope, [pending]);+ expect((await storage.getToolApprovalGrants(scope, [renewed]))[0].approved).toBe(true);+ });++ test.each([false, true])(+ `${mode} ${resetScope} reset between fence read and write cannot clobber renewal; first grant=%s`,+ async (firstGrant) => {+ const pending = { ...grant, scope: mode };+ if (!firstGrant) await storage.rememberToolApprovalGrants(scope, [pending]);+ const pause = suspendGrantWrite();+ const staleWrite = storage.rememberToolApprovalGrants(scope, [pending]);+ await pause.started;+ try {+ await storage.resetToolApprovalGrants(+ scope.userId,+ grant.agentId,+ resetScope === 'tool' ? grant.toolName : undefined,+ );+ const status = (await storage.getToolApprovalGrants(scope, [pending]))[0];+ const renewed = { ...pending, revocation: status.revocation };+ await storage.rememberToolApprovalGrants(scope, [renewed]);+ pause.resume();+ await staleWrite;+ expect((await storage.getToolApprovalGrants(scope, [renewed]))[0].approved).toBe(true);+ } finally {+ pause.resume();+ await staleWrite;+ pause.restore();+ }+ },+ );+ }+}++for (const mode of ['chat', 'always'] as const) {+ test(`${mode} storage refuses an OAuth epoch already replaced before persistence`, async () => {+ const userId = new mongoose.Types.ObjectId().toString();+ const current = { ...scope, userId };+ const old = { ...grant, scope: mode, serverName: 'db', oauthEpoch: 'account-a' };+ const token = await mongoose.models.Token.create({+ userId,+ type: 'mcp_oauth',+ identifier: 'mcp:db',+ token: 'synthetic-a',+ expiresAt: new Date(Date.now() + 60000),+ metadata: { credential_set_id: 'account-a' },+ });+ try {+ await storage.rememberToolApprovalGrants(current, [old]);+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ const renewed = { ...old, oauthEpoch: 'account-b' };+ await storage.rememberToolApprovalGrants(current, [renewed]);+ await storage.rememberToolApprovalGrants(current, [old]);+ expect((await storage.getToolApprovalGrants(current, [renewed]))[0].approved).toBe(true);+ } finally {+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+ });++ test(`${mode} current OAuth consent can replace a changed tool binding`, async () => {+ const userId = new mongoose.Types.ObjectId().toString();+ const current = { ...scope, userId };+ const original = { ...grant, scope: mode, serverName: 'db', oauthEpoch: 'account-a' };+ const token = await mongoose.models.Token.create({+ userId,+ type: 'mcp_oauth',+ identifier: 'mcp:db',+ token: 'synthetic-a',+ expiresAt: new Date(Date.now() + 60000),+ metadata: { credential_set_id: 'account-a' },+ });+ try {+ await storage.rememberToolApprovalGrants(current, [original]);+ const changed = {+ ...original,+ binding: 'changed-tool-schema',+ consentBinding: original.binding,+ };+ await storage.rememberToolApprovalGrants(current, [changed]);+ expect((await storage.getToolApprovalGrants(current, [changed]))[0].approved).toBe(true);+ expect((await storage.getToolApprovalGrants(current, [original]))[0].approved).toBe(false);+ } finally {+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+ });++ for (const initialEpoch of ['account-a', null]) {+ test.each([false, true])(+ `${mode} delayed OAuth write cannot clobber account B; initial=${initialEpoch}, first grant=%s`,+ async (firstGrant) => {+ const userId = new mongoose.Types.ObjectId().toString();+ const current = { ...scope, userId };+ const old = { ...grant, scope: mode, serverName: 'db', oauthEpoch: initialEpoch };+ const tokenData = {+ userId,+ type: 'mcp_oauth',+ identifier: 'mcp:db',+ token: 'synthetic-token',+ expiresAt: new Date(Date.now() + 60000),+ };+ if (initialEpoch)+ await mongoose.models.Token.create({+ ...tokenData,+ metadata: { credential_set_id: initialEpoch },+ });+ if (!firstGrant) await storage.rememberToolApprovalGrants(current, [old]);+ const pause = suspendGrantWrite();+ const stale = storage.rememberToolApprovalGrants(current, [old]);+ await pause.started;+ try {+ await mongoose.models.Token.deleteMany({ userId });+ await mongoose.models.Token.create({+ ...tokenData,+ metadata: { credential_set_id: 'account-b' },+ });+ const renewed = { ...old, oauthEpoch: 'account-b' };+ await storage.rememberToolApprovalGrants(current, [renewed]);+ pause.resume();+ await stale;+ const status = (await storage.getToolApprovalGrants(current, [renewed]))[0];+ expect(status.approved).toBe(true);+ expect(status).not.toHaveProperty('previousOAuthEpoch');+ expect(JSON.stringify(status)).not.toContain('synthetic-token');+ } finally {+ pause.resume();+ await stale;+ pause.restore();+ await mongoose.models.Token.deleteMany({ userId });+ }+ },+ );+ }+}++for (const mode of ['chat', 'always'] as const) {+ test.each(['connection', 'schema', 'revision'])(+ `${mode} late completion cannot replace renewed %s consent`,+ async (change) => {+ const original = { ...grant, scope: mode };+ await storage.rememberToolApprovalGrants(scope, [original]);+ const snapshot = (await storage.getToolApprovalGrants(scope, [original]))[0];+ const oldExecution = { ...original, consentBinding: snapshot.consentBinding };+ const replacement = {+ ...original,+ binding: `replacement-${change}`,+ consentBinding: snapshot.consentBinding,+ };+ await storage.rememberToolApprovalGrants(scope, [replacement]);+ await storage.rememberToolApprovalGrants(scope, [oldExecution]);+ expect(+ (await storage.getToolApprovalGrants(scope, [original, replacement])).map(+ (status) => status.approved,+ ),+ ).toEqual([false, true]);+ },+ );++ test.each([false, true])(+ `${mode} binding replacement between read and write wins; first grant=%s`,+ async (firstGrant) => {+ const original = { ...grant, scope: mode };+ if (!firstGrant) await storage.rememberToolApprovalGrants(scope, [original]);+ const snapshot = (await storage.getToolApprovalGrants(scope, [original]))[0];+ const captured = { ...original, consentBinding: snapshot.consentBinding };+ const pause = suspendGrantWrite();+ const oldWrite = storage.rememberToolApprovalGrants(scope, [captured]);+ await pause.started;+ try {+ const replacement = { ...captured, binding: 'new-current-authority' };+ await storage.rememberToolApprovalGrants(scope, [replacement]);+ pause.resume();+ await oldWrite;+ expect(+ (await storage.getToolApprovalGrants(scope, [original, replacement])).map(+ (status) => status.approved,+ ),+ ).toEqual([false, true]);+ } finally {+ pause.resume();+ await oldWrite;+ pause.restore();+ }+ },+ );++ test(`${mode} reviewed replacement can supersede a previous binding and parallel repeats remain idempotent`, async () => {+ const original = { ...grant, scope: mode };+ await storage.rememberToolApprovalGrants(scope, [original]);+ const snapshot = (await storage.getToolApprovalGrants(scope, [original]))[0];+ const replacement = {+ ...original,+ binding: 'reviewed-new-authority',+ consentBinding: snapshot.consentBinding,+ };+ await Promise.all(+ Array.from({ length: 4 }, () => storage.rememberToolApprovalGrants(scope, [replacement])),+ );+ expect((await storage.getToolApprovalGrants(scope, [replacement]))[0].approved).toBe(true);+ expect(await mongoose.models.ToolApprovalGrant.countDocuments()).toBe(1);+ });+}++test('non-OAuth authority ignores retained OAuth epochs without querying token records', async () => {+ const userId = new mongoose.Types.ObjectId().toString();+ const current = { userId, conversationId: 'api-key-chat' };+ const token = await mongoose.models.Token.create({+ userId,+ type: 'mcp_oauth',+ identifier: 'mcp:db',+ token: 'synthetic-retained-token',+ expiresAt: new Date(Date.now() + 60000),+ metadata: { credential_set_id: 'old-oauth-account' },+ });+ const apiKey = {+ ...grant,+ serverName: 'db',+ authKind: 'other' as const,+ oauthEpoch: null,+ binding: 'current-api-key-authority',+ };+ const find = jest.spyOn(mongoose.models.Token, 'find');+ try {+ await storage.rememberToolApprovalGrants(current, [apiKey]);+ const status = (await storage.getToolApprovalGrants(current, [apiKey]))[0];+ expect(status.oauthEpoch).toBeNull();+ expect(status.approved).toBe(true);+ expect(find).not.toHaveBeenCalled();+ } finally {+ find.mockRestore();+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+});++test('batched OAuth and API-key tools on the same server resolve distinct effective epochs', async () => {+ const userId = new mongoose.Types.ObjectId().toString();+ const current = { ...scope, userId };+ const token = await mongoose.models.Token.create({+ userId,+ type: 'mcp_oauth',+ identifier: 'mcp:db',+ token: 'synthetic-token',+ expiresAt: new Date(Date.now() + 60000),+ metadata: { credential_set_id: 'account-a' },+ });+ const oauth = { ...grant, serverName: 'db', authKind: 'oauth' as const, oauthEpoch: 'account-a' };+ const apiKey = {+ ...grant,+ serverName: 'db',+ authKind: 'other' as const,+ oauthEpoch: null,+ toolName: 'key_mcp_db',+ instanceName: 'key_mcp_db',+ binding: 'key-authority',+ };+ try {+ await storage.rememberToolApprovalGrants(current, [oauth, apiKey]);+ expect(+ (await storage.getToolApprovalGrants(current, [oauth, apiKey])).map((status) => [+ status.oauthEpoch,+ status.approved,+ ]),+ ).toEqual([+ ['account-a', true],+ [null, true],+ ]);+ await mongoose.models.Token.updateOne(+ { _id: token._id },+ { $set: { 'metadata.credential_set_id': 'account-b' } },+ );+ expect(+ (await storage.getToolApprovalGrants(current, [oauth, apiKey])).map(+ (status) => status.approved,+ ),+ ).toEqual([false, true]);+ } finally {+ await mongoose.models.Token.deleteOne({ _id: token._id });+ }+});diff --git a/packages/data-schemas/src/methods/toolApprovalGrant.ts b/packages/data-schemas/src/methods/toolApprovalGrant.tsnew file mode 100644index 0000000000..486e4ff59d--- /dev/null+++ b/packages/data-schemas/src/methods/toolApprovalGrant.ts@@ -0,0 +1,285 @@+import { z } from 'zod';+import { randomUUID } from 'crypto';+import type {+ ToolApprovalGrantStorage,+ ToolApprovalGrantScope,+ ToolApprovalGrantBinding,+} from 'librechat-data-provider';++interface StoredGrant {+ agentId: string;+ toolName: string;+ conversationId: string;+ binding?: string;+ revocation?: string;+ generation?: number;+ approvedRevocation?: string;+ oauthEpoch?: string | null;+}++/** Canonical MCP tool keys include their source; `*` is reserved for the agent-wide fence. */+const AGENT_FENCE_TOOL = '*';+const epochSchema = z.tuple([+ z.string(),+ z.string(),+ z.number().int().nonnegative(),+ z.number().int().nonnegative(),+]);++function epochGenerations(revocation?: string): readonly [number, number] | undefined {+ if (revocation == null) return [0, 0];+ try {+ const epoch = epochSchema.safeParse(JSON.parse(revocation));+ return epoch.success ? [epoch.data[2], epoch.data[3]] : undefined;+ } catch {+ return undefined;+ }+}++export function createToolApprovalGrantMethods(+ mongoose: typeof import('mongoose'),+): ToolApprovalGrantStorage {+ async function readGrants(+ scope: ToolApprovalGrantScope,+ bindings: readonly ToolApprovalGrantBinding[],+ ) {+ if (bindings.length === 0) return [];+ const recordsQuery = mongoose.models.ToolApprovalGrant.find({+ user: scope.userId,+ tenantId: scope.tenantId ?? null,+ $or: [+ {+ binding: { $in: bindings.map((grant) => grant.binding) },+ conversationId: { $in: ['', scope.conversationId] },+ },+ ...bindings.map(({ agentId, toolName }) => ({+ agentId,+ toolName,+ conversationId: { $in: ['', scope.conversationId] },+ })),+ {+ agentId: { $in: [...new Set(bindings.map((grant) => grant.agentId))] },+ toolName: AGENT_FENCE_TOOL,+ conversationId: '',+ },+ ],+ })+ .select(+ 'agentId toolName conversationId binding revocation generation approvedRevocation oauthEpoch -_id',+ )+ .lean<StoredGrant[]>();+ const servers = [+ ...new Set(+ bindings.flatMap((binding) =>+ binding.serverName && binding.authKind !== 'other' ? [binding.serverName] : [],+ ),+ ),+ ];+ const identities = servers.flatMap((server) => [+ { server, type: 'mcp_oauth', identifier: `mcp:${server}` },+ { server, type: 'mcp_oauth_refresh', identifier: `mcp:${server}:refresh` },+ { server, type: 'mcp_oauth_client', identifier: `mcp:${server}:client` },+ ]);+ const [records, tokens] = await Promise.all([+ recordsQuery,+ identities.length === 0+ ? Promise.resolve([])+ : mongoose.models.Token.find({+ userId: scope.userId,+ tenantId: scope.tenantId ?? null,+ $or: identities.map(({ type, identifier }) => ({ type, identifier })),+ })+ .select('type identifier metadata.credential_set_id -_id')+ .lean<+ Array<{+ type: string;+ identifier: string;+ metadata?: { credential_set_id?: string };+ }>+ >({ flattenMaps: true }),+ ]);+ const identityKey = (type: string, identifier: string) => JSON.stringify([type, identifier]);+ const owners = new Map(+ identities.map(({ server, type, identifier }) => [identityKey(type, identifier), server]),+ );+ const generations = new Map<string, Set<string | undefined>>();+ for (const token of tokens) {+ const server = owners.get(identityKey(token.type, token.identifier));+ if (!server) continue;+ const values = generations.get(server) ?? new Set<string | undefined>();+ values.add(token.metadata?.credential_set_id);+ generations.set(server, values);+ }+ const epochs = new Map<string, string | null | undefined>();+ for (const server of servers) {+ const values = generations.get(server);+ if (!values) {+ epochs.set(server, null);+ continue;+ }+ const value = values.values().next().value;+ epochs.set(+ server,+ values.size === 1 && typeof value === 'string' && value.length > 0 ? value : undefined,+ );+ }+ const agentRevocations = new Map<string, StoredGrant>();+ const revocations = new Map<string, StoredGrant>();+ const granted = new Map<string, StoredGrant>();+ const stored = new Map<string, StoredGrant>();+ const recordKey = (agentId: string, toolName: string, conversationId: string) =>+ JSON.stringify([agentId, toolName, conversationId]);+ const key = (agentId: string, toolName: string) => JSON.stringify([agentId, toolName]);+ for (const record of records) {+ stored.set(recordKey(record.agentId, record.toolName, record.conversationId), record);+ if (record.conversationId === '') {+ if (record.toolName === AGENT_FENCE_TOOL) agentRevocations.set(record.agentId, record);+ else revocations.set(key(record.agentId, record.toolName), record);+ }+ if (record.binding) granted.set(record.binding, record);+ }+ return bindings.map((grant) => {+ const toolRevocation = revocations.get(key(grant.agentId, grant.toolName));+ const agentRevocation = agentRevocations.get(grant.agentId);+ const revocation =+ agentRevocation?.revocation == null && toolRevocation?.revocation == null+ ? undefined+ : JSON.stringify([+ agentRevocation?.revocation ?? '',+ toolRevocation?.revocation ?? '',+ agentRevocation?.generation ?? 0,+ toolRevocation?.generation ?? 0,+ ]);+ const record = granted.get(grant.binding);+ const oauthEpoch =+ grant.serverName && grant.authKind !== 'other' ? epochs.get(grant.serverName) : null;+ const previous = stored.get(+ recordKey(+ grant.agentId,+ grant.toolName,+ grant.scope === 'chat' ? scope.conversationId : '',+ ),+ );+ return {+ previousOAuthEpoch: previous?.oauthEpoch ?? null,+ status: {+ binding: grant.binding,+ revocation,+ oauthEpoch,+ consentBinding: previous?.binding ?? null,+ approved:+ oauthEpoch !== undefined &&+ record != null &&+ (record.oauthEpoch ?? null) === oauthEpoch &&+ (record.approvedRevocation ?? '') === (revocation ?? ''),+ },+ };+ });+ }+ const methods: ToolApprovalGrantStorage = {+ async getToolApprovalGrants(scope, bindings) {+ return (await readGrants(scope, bindings)).map(({ status }) => status);+ },+ async rememberToolApprovalGrants(scope, grants) {+ if (grants.some((grant) => grant.scope === 'once'))+ throw new TypeError('One-time approvals cannot be remembered.');+ const current = new Map(+ (await readGrants(scope, grants)).map((snapshot) => [snapshot.status.binding, snapshot]),+ );+ await Promise.all(+ grants.map(async (grant) => {+ const snapshot = current.get(grant.binding);+ if (+ !snapshot ||+ snapshot.status.revocation !== grant.revocation ||+ snapshot.status.oauthEpoch === undefined ||+ snapshot.status.oauthEpoch !== (grant.oauthEpoch ?? null) ||+ (snapshot.status.consentBinding !== (grant.consentBinding ?? null) &&+ snapshot.status.consentBinding !== grant.binding)+ )+ return;+ const generations = epochGenerations(grant.revocation);+ if (!generations) return;+ const [agentGeneration, toolGeneration] = generations;+ // Monotonic predicates protect renewal if reset lands after the batched fence read.+ const filter = {+ user: scope.userId,+ tenantId: scope.tenantId ?? null,+ agentId: grant.agentId,+ toolName: grant.toolName,+ conversationId: grant.scope === 'chat' ? scope.conversationId : '',+ // A replacement account's successful write wins even if this read preceded reauthorization.+ oauthEpoch: snapshot.previousOAuthEpoch,+ // Idempotent same-authority completions cannot overwrite a replacement binding.+ binding: { $in: [grant.consentBinding ?? null, grant.binding] },+ $and: [+ {+ $or: [+ { approvedAgentGeneration: { $lte: agentGeneration } },+ { approvedAgentGeneration: { $exists: false } },+ ],+ },+ {+ $or: [+ { approvedToolGeneration: { $lte: toolGeneration } },+ { approvedToolGeneration: { $exists: false } },+ ],+ },+ // Persistent grants share the targeted reset fence's document.+ {+ $or: [{ generation: { $lte: toolGeneration } }, { generation: { $exists: false } }],+ },+ ],+ };+ const update = {+ $set: {+ binding: grant.binding,+ approvedRevocation: grant.revocation ?? '',+ oauthEpoch: grant.oauthEpoch ?? null,+ approvedAgentGeneration: agentGeneration,+ approvedToolGeneration: toolGeneration,+ },+ $setOnInsert: {+ user: scope.userId,+ tenantId: scope.tenantId ?? null,+ agentId: grant.agentId,+ toolName: grant.toolName,+ conversationId: filter.conversationId,+ },+ };+ try {+ await mongoose.models.ToolApprovalGrant.updateOne(filter, update, {+ upsert: true,+ runValidators: true,+ });+ } catch (error) {+ if (!(error instanceof Error) || !('code' in error) || error.code !== 11000)+ throw error;+ await mongoose.models.ToolApprovalGrant.updateOne(filter, update, {+ runValidators: true,+ });+ }+ }),+ );+ },+ async resetToolApprovalGrants(userId, agentId, toolName) {+ const filter = {+ user: userId,+ agentId,+ toolName: toolName ?? AGENT_FENCE_TOOL,+ conversationId: '',+ };+ await mongoose.models.ToolApprovalGrant.updateOne(+ filter,+ {+ $set: { revocation: randomUUID() },+ $inc: { generation: 1 },+ $unset: { binding: 1, approvedRevocation: 1 },+ $setOnInsert: filter,+ },+ { upsert: true, runValidators: true },+ );+ },+ };+ return methods;+}diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.tsindex 290cb0974b..acf4bdafd9 100644--- a/packages/data-schemas/src/methods/user.methods.spec.ts+++ b/packages/data-schemas/src/methods/user.methods.spec.ts@@ -6,6 +6,7 @@ import {AUTH_USER_DOC_CACHE_TTL_MS,} from 'librechat-data-provider';import type * as t from '~/types';+import { createToolApprovalGrantModel } from '~/models/toolApprovalGrant';import { createUserMethods, USER_DELETION_FENCE_STALE_MS } from './user';import balanceSchema from '~/schema/balance';import userSchema from '~/schema/user';@@ -49,6 +50,7 @@ beforeAll(async () => {/** Initialize methods */methods = createUserMethods(mongoose);+ createToolApprovalGrantModel(mongoose);});afterAll(async () => {@@ -1996,3 +1998,63 @@ describe('User Methods - Database Tests', () => {});});});++describe('personal grant cleanup before account deletion', () => {+ async function owner() {+ const user = await User.create({ email: '[email protected]', provider: 'local' });+ const id = user._id.toString();+ await mongoose.models.ToolApprovalGrant.create({+ user: id,+ agentId: 'agent',+ toolName: 'query_mcp_db',+ conversationId: 'chat',+ binding: 'personal-consent',+ });+ return { user, id };+ }++ it('cleanup failure preserves the account and grants so deletion can be retried', async () => {+ const { user, id } = await owner();+ const cleanup = jest+ .spyOn(mongoose.models.ToolApprovalGrant.collection, 'deleteMany')+ .mockRejectedValueOnce(new Error('synthetic grant-store failure'));+ const deletion = jest.spyOn(User, 'deleteOne');+ try {+ await expect(methods.deleteUserById(id)).rejects.toThrow('synthetic grant-store failure');+ expect(deletion).not.toHaveBeenCalled();+ expect(await User.exists({ _id: user._id })).not.toBeNull();+ expect(await mongoose.models.ToolApprovalGrant.countDocuments({ user: id })).toBe(1);+ await expect(methods.deleteUserById(id)).resolves.toMatchObject({ deletedCount: 1 });+ expect(await User.exists({ _id: user._id })).toBeNull();+ expect(await mongoose.models.ToolApprovalGrant.countDocuments({ user: id })).toBe(0);+ } finally {+ cleanup.mockRestore();+ deletion.mockRestore();+ }+ });++ it('successful cleanup precedes account commit and affects only that owner', async () => {+ const { id } = await owner();+ await mongoose.models.ToolApprovalGrant.create({+ user: 'another-user',+ agentId: 'agent',+ toolName: 'query_mcp_db',+ conversationId: 'chat',+ binding: 'other-consent',+ });+ const cleanup = jest.spyOn(mongoose.models.ToolApprovalGrant, 'deleteMany');+ const deletion = jest.spyOn(User, 'deleteOne');+ try {+ await expect(methods.deleteUserById(id)).resolves.toMatchObject({ deletedCount: 1 });+ expect(cleanup.mock.invocationCallOrder[0]).toBeLessThan(+ deletion.mock.invocationCallOrder[0],+ );+ expect(await mongoose.models.ToolApprovalGrant.countDocuments({ user: 'another-user' })).toBe(+ 1,+ );+ } finally {+ cleanup.mockRestore();+ deletion.mockRestore();+ }+ });+});diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.tsindex b2508bf7c5..7c31842fdb 100644--- a/packages/data-schemas/src/methods/user.ts+++ b/packages/data-schemas/src/methods/user.ts@@ -523,6 +523,7 @@ export function createUserMethods(async function deleteUserById(userId: string): Promise<UserDeleteResult> {try {const User = mongoose.models.User;+ await mongoose.models.ToolApprovalGrant?.deleteMany({ user: userId });const result = await User.deleteOne({ _id: userId });if (result.deletedCount === 0) {return { deletedCount: 0, message: 'No user found with that ID.' };diff --git a/packages/data-schemas/src/models/index.ts b/packages/data-schemas/src/models/index.tsindex 2fe5b49b9d..646f010c55 100644--- a/packages/data-schemas/src/models/index.ts+++ b/packages/data-schemas/src/models/index.ts@@ -7,6 +7,7 @@ import { createOpenIDRefreshFlightModel } from './openidRefreshFlight';import { createAgentTriggerUserPurgeModel } from './triggerUserPurge';import { createRefreshTokenBridgeModel } from './refreshTokenBridge';import { createAgentTriggerDeliveryModel } from './triggerDelivery';+import { createToolApprovalGrantModel } from './toolApprovalGrant';import { createSkillSyncStatusModel } from './skillSyncStatus';import { createConversationTagModel } from './conversationTag';import { createCodeEnvironmentModel } from './codeEnvironment';@@ -52,6 +53,7 @@ import logger from '~/config/winston';*/export function createModels(mongoose: typeof import('mongoose')): {User: ReturnType<typeof createUserModel>;+ ToolApprovalGrant: ReturnType<typeof createToolApprovalGrantModel>;Token: ReturnType<typeof createTokenModel>;Session: ReturnType<typeof createSessionModel>;Passkey: ReturnType<typeof createPasskeyModel>;@@ -102,6 +104,7 @@ export function createModels(mongoose: typeof import('mongoose')): {} {const models = {User: createUserModel(mongoose),+ ToolApprovalGrant: createToolApprovalGrantModel(mongoose),Token: createTokenModel(mongoose),Session: createSessionModel(mongoose),Passkey: createPasskeyModel(mongoose),diff --git a/packages/data-schemas/src/models/toolApprovalGrant.ts b/packages/data-schemas/src/models/toolApprovalGrant.tsnew file mode 100644index 0000000000..8c0e44d128--- /dev/null+++ b/packages/data-schemas/src/models/toolApprovalGrant.ts@@ -0,0 +1,48 @@+import { Schema } from 'mongoose';+import type { Model } from 'mongoose';+import { applyTenantIsolation } from './plugins/tenantIsolation';++interface ToolApprovalGrantRecord {+ user: string;+ tenantId?: string;+ agentId: string;+ toolName: string;+ conversationId: string;+ binding?: string;+ revocation?: string;+ generation?: number;+ approvedAgentGeneration?: number;+ approvedToolGeneration?: number;+ approvedRevocation?: string;+ oauthEpoch?: string | null;+}++const schema: Schema<ToolApprovalGrantRecord> = new Schema<ToolApprovalGrantRecord>(+ {+ user: { type: String, required: true },+ tenantId: { type: String },+ agentId: { type: String, required: true },+ toolName: { type: String, required: true },+ conversationId: { type: String, default: '' },+ binding: { type: String },+ revocation: { type: String },+ generation: { type: Number, min: 0 },+ approvedAgentGeneration: { type: Number, min: 0 },+ approvedToolGeneration: { type: Number, min: 0 },+ approvedRevocation: { type: String },+ oauthEpoch: { type: String, default: null },+ },+ { timestamps: true },+);+schema.index(+ { user: 1, tenantId: 1, agentId: 1, toolName: 1, conversationId: 1 },+ { unique: true },+);+schema.index({ user: 1, tenantId: 1, binding: 1, conversationId: 1 });++export function createToolApprovalGrantModel(+ mongoose: typeof import('mongoose'),+): Model<ToolApprovalGrantRecord> {+ applyTenantIsolation(schema);+ return mongoose.models.ToolApprovalGrant ?? mongoose.model('ToolApprovalGrant', schema);+}