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: Enforce Scheduled MCP Read-Only Authority (#16681)
lia-by-librechat[bot]38a9dab3f587
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.jsindex a60becd413..25a2ef800d 100644--- a/api/app/clients/tools/util/handleTools.js+++ b/api/app/clients/tools/util/handleTools.js@@ -686,6 +686,7 @@ const loadTools = async ({getMCPServerTools(userId, serverName, config, capabilityProfile),context: {mcpPermissionContext,+ agentId: agent?.id,signal,user: safeUser,userMCPAuthMap,diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.jsindex 5211dd610c..cef45b6f7c 100644--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js@@ -4470,6 +4470,58 @@ describe('ResumableAgentController resume metadata', () => {},);+ it('never copies a preparation dependency diagnostic into the stream or scheduled outcome', async () => {+ const { initializeWithScheduleMCPExecution } = jest.requireActual('@librechat/api');+ const privateError = new Error('PRIVATE schedule database query');+ const provider = jest.fn();+ const req = {+ _isScheduledFire: true,+ _isAgentTrigger: true,+ user: { id: 'user-123' },+ body: {+ text: 'Read',+ messageId: 'read',+ conversationId: 'conversation-123',+ scheduleId: 'schedule',+ scheduledFor: '2026-10-03T00:00:00.000Z',+ endpointOption: { endpoint: 'agents', agent_id: 'root' },+ },+ config: {},+ };+ const initializeClient = ({ signal }) =>+ initializeWithScheduleMCPExecution(+ { req, signal },+ () => ({+ prepare: async () => {+ throw privateError;+ },+ }),+ provider,+ );+ const res = createResumableResponse();+ await AgentController(req, res, jest.fn(), initializeClient, null);+ expect(provider).not.toHaveBeenCalled();+ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(+ 'conversation-123',+ expect.stringContaining('dependency_unavailable'),+ 1000,+ expect.anything(),+ );+ expect(mockRecordScheduleOutcome).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'error',+ error: expect.stringContaining('dependency_unavailable'),+ }),+ );+ expect(+ JSON.stringify([+ mockGenerationJobManager.completeJob.mock.calls,+ mockRecordScheduleOutcome.mock.calls,+ res.json.mock.calls,+ ]),+ ).not.toContain('PRIVATE');+ });+it('finalizes the failed job before releasing the idempotency claim', async () => {mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim());const initializeClient = jest.fn().mockRejectedValue(new Error('init boom after res.json'));diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex 2f3b9b9b25..8cc6943194 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -1129,6 +1129,33 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {});});+ it('passes retained completion lineage to authenticated approval initialization without claiming an occurrence', async () => {+ const lineage = {+ scheduleId: 'original-schedule',+ ownerId: USER_ID,+ tenantId: TENANT_ID,+ agentId: 'original-root',+ invocationMode: 'delegated',+ };+ mockGenerationJobManager.getJob.mockResolvedValue(+ makeToolApprovalJob({ metadata: { scheduleMCPCompletion: lineage } }),+ );+ const res = await post(+ approveBody({+ agentCompletion: { scheduleMCPIdentity: { ...lineage, agentId: 'forged-root' } },+ }),+ );+ expect(res.status).toBe(200);+ await settled;+ expect(mockInitializeClient.mock.calls[0][0].scheduleJobIdentity.scheduleMCPCompletion).toEqual(+ lineage,+ );+ expect(mockInitializeClient.mock.calls[0][0].scheduledTokenContext).toBeUndefined();+ expect(capturedInit.isScheduledFire).not.toBe(true);+ expect(mockClaimScheduleResume).not.toHaveBeenCalled();+ expect(mockRecordScheduleOutcome).not.toHaveBeenCalled();+ });+describe('scheduled occurrence lifecycle', () => {const scheduledFor = '2026-08-17T12:00:00.000Z';const makeScheduledJob = () =>diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 63d615daed..b2be1bfd56 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -1,3 +1,4 @@+const { getMCPRequestContext } = require('~/server/services/MCPRequestContext');require('events').EventEmitter.defaultMaxListeners = 100;const { logger, MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH } = require('@librechat/data-schemas');const { getBufferString, HumanMessage } = require('@librechat/agents/langchain/messages');@@ -23,6 +24,8 @@ const {isMemoryAgentEnabled,recordCollectedUsage,resolveRunUsageContext,+ getScheduleMCPExecution,+ createScheduledMCPPolicyRecorder,recordFallbackTokenUsage,createDetachedSubagentUsageRecorder,sendEvent,@@ -5012,6 +5015,17 @@ class AgentClient extends BaseClient {activityPhase?.handlers(offsetHandlers) ??(activityLabel ? createAssistantPhaseStampingHandlers(offsetHandlers) : offsetHandlers);const createRunPromise = createRun({+ scheduledMCPExecution: getScheduleMCPExecution(getMCPRequestContext(this.options.req)),+ recordScheduledMCPDenial: createScheduledMCPPolicyRecorder(+ getScheduleMCPExecution(getMCPRequestContext(this.options.req)),+ {+ streamId,+ jobCreatedAt: this.jobCreatedAt,+ userId: this.options.req?.user?.id,+ tenantId: this.options.req?.user?.tenantId,+ },+ require('~/server/services/Schedules').recordMCPToolAuthFailure,+ ),agents,// Conversation-stable identity for the e2e run hook; a resumed run// carries no messages, so history cannot identify the conversation.@@ -5808,6 +5822,17 @@ class AgentClient extends BaseClient {activityPhase?.handlers(offsetHandlers) ??(activityLabel ? createAssistantPhaseStampingHandlers(offsetHandlers) : offsetHandlers);run = await createRun({+ scheduledMCPExecution: getScheduleMCPExecution(getMCPRequestContext(this.options.req)),+ recordScheduledMCPDenial: createScheduledMCPPolicyRecorder(+ getScheduleMCPExecution(getMCPRequestContext(this.options.req)),+ {+ streamId,+ jobCreatedAt: this.jobCreatedAt,+ userId: this.options.req?.user?.id,+ tenantId: this.options.req?.user?.tenantId,+ },+ require('~/server/services/Schedules').recordMCPToolAuthFailure,+ ),agents,conversationId: this.conversationId,modelCallbacks: [diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex 77511c55de..d331920151 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -1947,6 +1947,7 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)});const result = await initializeClient({scheduledTokenContext: restoreScheduledTokenContext(req, job.metadata),+ scheduleJobIdentity: job.metadata,req,res,endpointOption: req.body.endpointOption,diff --git a/api/server/routes/schedules.js b/api/server/routes/schedules.jsindex e3007ebba7..51b5e23f3d 100644--- a/api/server/routes/schedules.js+++ b/api/server/routes/schedules.js@@ -5,8 +5,6 @@ const {SCHEDULE_FILE_HOLD,generateCheckAccess,createSchedulesHandlers,- createScheduleMCPConsentHost,- createScheduleMCPEnrollmentResolver,} = require('@librechat/api');const { requireJwtAuth, configMiddleware, messageIpLimiter } = require('~/server/middleware');const {@@ -88,29 +86,7 @@ const handlers = createSchedulesHandlers({isUserDeleting,});-const consentHost = createScheduleMCPConsentHost({- resolveEnrollment: createScheduleMCPEnrollmentResolver({- canUseRoot: async (agentId, user) => (await resolveAgentFireAccess(agentId, user)) === 'ok',- findUser: (id) => methods.findUser({ _id: id }),- getAppConfig: require('~/server/services/Config/app').getAppConfig,- resolveGraphAccess: (user) =>- methods.resolveAgentGraphAccess({- userId: user.id,- role: user.role,- idOnTheSource: user.idOnTheSource,- }),- getNodes: methods.getAgentGraphNodes,- getModelsConfig: (user) =>- require('~/server/controllers/ModelController').getModelsConfig({ user }),- getServers: (user, config) =>- require('~/config').getMCPServersRegistry().getAllServerConfigs(user.id, config, user.role),- }),- methods,- getLimits,- findUser: (id) => methods.findUser({ _id: id }),- getRoleByName,- canViewAgent: async (agentId, user) => (await resolveAgentFireAccess(agentId, user)) === 'ok',-});+const consentHost = require('~/server/services/Schedules/consent').consent;router.get('/:id/mcp-consent', consentHost.handlers.get);router.post('/:id/mcp-consent', checkSchedulesCreate, consentHost.handlers.confirm);diff --git a/api/server/services/Agents/triggers.js b/api/server/services/Agents/triggers.jsindex 3977b8e3f8..3bbf64be6e 100644--- a/api/server/services/Agents/triggers.js+++ b/api/server/services/Agents/triggers.js@@ -25,11 +25,13 @@ const getGenerationAdmissionEvidence = (userId, clientRequestId, streamId, conveconst subagentCompletionAdapter = createSubagentCompletionWakeupResolver({methods,getGenerationJob: (conversationId) => GenerationJobManager.getJob(conversationId),+ getScheduleMCPCompletionState: methods.getScheduleMCPCompletionState,getWaitMaxIntervalMs: () => service.getCompletionWaitMaxIntervalMs(),});const backgroundToolCompletionAdapter = createBackgroundToolCompletionWakeupResolver({methods,getGenerationJob: (conversationId) => GenerationJobManager.getJob(conversationId),+ getScheduleMCPCompletionState: methods.getScheduleMCPCompletionState,getResultBatchSize: () => service.getBackgroundCompletionResultBatchSize(),getGenerationAdmissionEvidence,recoverDeadClaim: createBackgroundToolDeadClaimRecovery(diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex 39fd0798fd..eb66305571 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -43,6 +43,10 @@ const {encodeAndFormatVideos,extractFileContext,createScheduleUpstreamTokenProviderResolver,+ initializeWithScheduleMCPExecution,+ retainScheduleMCPCompletion,+ getScheduleMCPExecution,+ getMCPRequestContext,} = require('@librechat/api');const {ResourceType,@@ -441,6 +445,7 @@ const initializeClientWithProvider = async ({const invokedSkillIdentities = new Map();const toolExecuteOptions = {+ scheduledMCPExecution: getScheduleMCPExecution(getMCPRequestContext(req, res)),// Keep foreground cancellation owned by this request even when the agents// SDK rebuilds a graph for approval resume. The SDK event's breaker signal// is composed with this authoritative job signal by the handler.@@ -1643,7 +1648,10 @@ const initializeClientWithProvider = async ({? { tenantId: req.user.tenantId }: {}),},- { completionWakeups: completionWakeupsEnabled },+ {+ completionWakeups: completionWakeupsEnabled,+ scheduleMCPIdentity: getScheduleMCPExecution(getMCPRequestContext(req, res))?.identity,+ },): undefined;let hasExistingSubagentTask = false;@@ -1923,7 +1931,29 @@ function createInitializeClient(dependencies = {}) {params.signal,params.scheduledTokenContext,);- return initializeClientWithProvider({ ...params, upstreamTokenProviderResolver });+ return initializeWithScheduleMCPExecution(+ {+ req: params.req,+ signal: params.signal,+ context: require('~/server/services/MCPRequestContext').getMCPRequestContext(+ params.req,+ params.res,+ ),+ restoredContext: params.scheduledTokenContext,+ restoredJob: params.scheduleJobIdentity,+ },+ () => require('~/server/services/Schedules/consent'),+ () => initializeClientWithProvider({ ...params, upstreamTokenProviderResolver }),+ (identity) =>+ retainScheduleMCPCompletion(+ identity,+ {+ streamId: params.req._resumableStreamId,+ createdAt: params.jobCreatedAt,+ },+ GenerationJobManager.getJobStore(),+ ),+ );};}diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex 190bcb7a60..8b2e8e9b0d 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -40,7 +40,7 @@ jest.mock('@librechat/api', () => ({...jest.requireActual('@librechat/api'),initializeAgent: (...args) => mockInitializeAgent(...args),validateAgentModel: (...args) => mockValidateAgentModel(...args),- GenerationJobManager: { setCollectedUsage: jest.fn() },+ GenerationJobManager: { setCollectedUsage: jest.fn(), getJobStore: jest.fn() },getCustomEndpointConfig: jest.fn(),createSequentialChainEdges: jest.fn(),}));@@ -193,6 +193,16 @@ describe('initializeClient — processAgent ACL gate', () => {source: { type: 'schedule', id: 'sched-1' },},};+ await db.createSchedule({+ id: 'sched-1',+ user: testUser._id,+ agent_id: PRIMARY_ID,+ name: 'Legacy read',+ prompt: 'Read',+ cadence: { frequency: 'hourly', minute: 0, hour: 1 },+ timezone: 'UTC',+ enabled: true,+ });const signal = new AbortController().signal;mockInitializeAgent.mockImplementationOnce(async ({ loadTools, agent }) => {await loadTools({@@ -235,6 +245,104 @@ describe('initializeClient — processAgent ACL gate', () => {});});+ it('persists trusted completion lineage before initialization and rechecks it on authenticated resume', async () => {+ const { InMemoryJobStore, GenerationJobManager } = require('@librechat/api');+ const store = new InMemoryJobStore();+ GenerationJobManager.getJobStore.mockReturnValue(store);+ const req = makeReq();+ req._isAgentTrigger = true;+ req._resumableStreamId = 'completion-lineage';+ req.body.conversationId = 'completion-lineage';+ req.body.agentCompletion = {+ version: 1,+ sourceId: 'subagent-completion',+ scheduleMCPIdentity: {+ scheduleId: 'completion-schedule',+ ownerId: req.user.id,+ tenantId: null,+ agentId: PRIMARY_ID,+ invocationMode: 'delegated',+ },+ };+ req.body.agent_id = PRIMARY_ID;+ const identity = {+ scheduleId: 'completion-schedule',+ ownerId: req.user.id,+ tenantId: null,+ agentId: PRIMARY_ID,+ invocationMode: 'delegated',+ };+ await db.createSchedule({+ id: identity.scheduleId,+ user: testUser._id,+ agent_id: PRIMARY_ID,+ name: 'Legacy',+ prompt: 'Read',+ cadence: { frequency: 'hourly', minute: 0, hour: 1 },+ timezone: 'UTC',+ enabled: true,+ });+ await db.insertScheduleRun({+ scheduleId: identity.scheduleId,+ user: testUser._id,+ conversationId: req.body.conversationId,+ scheduledFor: new Date(),+ status: 'started',+ });+ const job = await store.createJob(req._resumableStreamId, req.user.id, req.body.conversationId);+ try {+ mockInitializeAgent.mockImplementationOnce(async () => {+ expect((await store.getJob(job.streamId)).scheduleMCPCompletion).toEqual(identity);+ return makePrimaryConfig([]);+ });+ await initializeClient({+ req,+ res: {},+ endpointOption: makeEndpointOption(),+ signal: new AbortController().signal,+ jobCreatedAt: job.createdAt,+ });+ const retained = await store.getJob(job.streamId);+ expect(retained.scheduleId).toBeUndefined();+ await mongoose.models.Schedule.updateOne(+ { id: identity.scheduleId },+ { $set: { mcpConsent: { version: 999 } } },+ );+ mockInitializeAgent.mockClear();+ await expect(+ initializeClient({+ req: { ...req, _isAgentTrigger: false },+ res: {},+ endpointOption: makeEndpointOption(),+ signal: new AbortController().signal,+ jobCreatedAt: job.createdAt,+ scheduleJobIdentity: { scheduleMCPCompletion: retained.scheduleMCPCompletion },+ }),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(mockInitializeAgent).not.toHaveBeenCalled();+ } finally {+ await store.destroy();+ }+ });++ it('preserves the owning cancellation before scheduled preparation begins', async () => {+ const req = makeReq();+ req._isScheduledFire = true;+ const controller = new AbortController();+ const stop = new Error('Owner stopped');+ controller.abort(stop);+ mockInitializeAgent.mockClear();+ await expect(+ initializeClient({+ req,+ res: {},+ endpointOption: makeEndpointOption(),+ signal: controller.signal,+ }),+ ).rejects.toBe(stop);+ expect(mockInitializeAgent).not.toHaveBeenCalled();+ });+it('keeps interactive agent initialization independent of the host resolver', async () => {const resolveUpstreamTokenProvider = jest.fn();const hostInitializeClient = createInitializeClient({ resolveUpstreamTokenProvider });diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex bde54deb5a..75b401a899 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -51,6 +51,8 @@ const {resolveMCPClientCapabilityProfile,getMCPConnectionPoolKey,getMCPUserConnectionPoolKey,+ bindScheduledMCPInvocation,+ ScheduledMCPPolicyError,} = require('@librechat/api');const {Time,@@ -897,6 +899,7 @@ async function reconnectServer({* @returns { Promise<Array<typeof tool | { _call: (toolInput: Object | string) => unknown}>> } An object with `_call` method to execute the tool input.*/async function createMCPTools({+ agentId,res,mcpPermissionContext,user,@@ -980,6 +983,7 @@ async function createMCPTools({);for (const tool of result.tools) {const toolInstance = await createMCPTool({+ agentId,res,mcpPermissionContext,user,@@ -1037,6 +1041,7 @@ async function createMCPTools({* @returns { Promise<typeof tool | { _call: (toolInput: Object | string) => unknown}> } An object with `_call` method to execute the tool input.*/async function createMCPTool({+ agentId,res,mcpPermissionContext,user,@@ -1213,6 +1218,7 @@ async function createMCPTool({}return createToolInstance({+ scheduledMCPInvocation: bindScheduledMCPInvocation(requestScopedConnections, agentId, toolName),res,mcpPermissionContext,user,@@ -1244,6 +1250,7 @@ async function createMCPTool({}function createToolInstance({+ scheduledMCPInvocation,res,mcpPermissionContext,user: capturedUser = null,@@ -1351,6 +1358,7 @@ function createToolInstance({* as the jwt-bearer assertion.*/const result = await mcpManager.callTool({+ scheduledMCPInvocation,serverName,serverConfig: capturedServerConfig,/** The upstream server never sees stripped names — a key that dropped@@ -1419,6 +1427,7 @@ function createToolInstance({// recording a durable tool failure; other tool errors are a cheap no-op.await require('~/server/services/Schedules').recordMCPToolAuthFailure({error,+ identity: scheduledMCPInvocation?.identity,streamId,jobCreatedAt,userId,@@ -1427,6 +1436,7 @@ function createToolInstance({/** Carries the actionable re-auth message; the substring heuristic below would misreport it as an OAuth configuration problem */if (+ error instanceof ScheduledMCPPolicyError ||error instanceof OpenIDReauthRequiredError ||error instanceof MCPAuthenticationRefreshError ||error instanceof MCPAuthenticationRejectedErrordiff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex a774118948..0900b35f5b 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -1737,6 +1737,7 @@ describe('User parameter passing tests', () => {).rejects.toThrow();expect(receipt).toHaveBeenCalledWith({error,+ identity: undefined,streamId: 'scheduled-conversation',jobCreatedAt: 42,userId: 'scheduled-owner',@@ -1744,6 +1745,82 @@ describe('User parameter passing tests', () => {});});+ it('carries captured schedule identity into the transport failure receipt', async () => {+ const {+ createScheduleMCPExecution,+ createMCPRequestContext,+ ScheduledMCPPolicyError,+ } = require('@librechat/api');+ const user = { id: 'scheduled-owner', tenantId: 'tenant', role: 'USER' };+ const identity = {+ scheduleId: 'schedule',+ ownerId: user.id,+ tenantId: 'tenant',+ agentId: 'root',+ invocationMode: 'delegated',+ };+ const context = createMCPRequestContext();+ const execution = createScheduleMCPExecution({+ storage: {+ readScheduleMCPConsent: async () => ({+ agentId: 'root',+ enabled: true,+ configRevision: 0,+ enrollment: null,+ compatible: true,+ }),+ },+ loadAuthorization: async () => {+ throw new Error('Unused legacy policy loader');+ },+ });+ await execution.attach(context, identity, 'invoke');+ const error = new ScheduledMCPPolicyError('consent_revoked', 'test-server', 'child');+ const receipt = require('~/server/services/Schedules').recordMCPToolAuthFailure;+ require('~/models').getRoleByName.mockResolvedValue({+ permissions: { [PermissionTypes.MCP_SERVERS]: { [Permissions.USE]: true } },+ });+ mockGetMCPManager.mockReturnValue({ callTool: jest.fn().mockRejectedValue(error) });+ const tool = await createMCPTool({+ agentId: 'child',+ user,+ toolKey: `test-tool${D}test-server`,+ provider: 'openai',+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ requestScopedConnections: context,+ config: { type: 'streamable-http', url: 'https://mcp.example.com' },+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: { description: 'Test MCP', parameters: { type: 'object', properties: {} } },+ },+ },+ });+ // Model/run metadata cannot replace the tool-construction identity.+ const expectedIdentity = { ...identity };+ identity.scheduleId = 'mutated';+ await expect(+ tool.func({}, undefined, {+ configurable: {+ user,+ requestScopedConnections: createMCPRequestContext(),+ scheduleId: 'forged',+ },+ metadata: { provider: 'openai', thread_id: 'scheduled-conversation', run_id: 'run' },+ toolCall: {},+ }),+ ).rejects.toBe(error);+ expect(receipt).toHaveBeenCalledWith({+ error,+ identity: expectedIdentity,+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ userId: 'scheduled-owner',+ serverName: 'test-server',+ });+ expect(Object.isFrozen(receipt.mock.calls.at(-1)[0].identity)).toBe(true);+ });+it('keeps shared OAuth recovery alive when one tool caller aborts', async () => {const mockUser = { id: 'shared-recovery-user', role: 'USER' };const mockRes = { write: jest.fn(), flush: jest.fn() };diff --git a/api/server/services/Schedules/consent.js b/api/server/services/Schedules/consent.jsnew file mode 100644index 0000000000..a0c573f118--- /dev/null+++ b/api/server/services/Schedules/consent.js@@ -0,0 +1,29 @@+const { createScheduleMCPRuntimeHost } = require('@librechat/api');+const { getMCPServersRegistry } = require('~/config');+const { getAppConfig } = require('~/server/services/Config/app');+const { getModelsConfig } = require('~/server/controllers/ModelController');+const { resolveAgentFireAccess } = require('./access');+const methods = require('~/models');++module.exports = createScheduleMCPRuntimeHost({+ methods,+ getScheduleMCPCompletionState: methods.getScheduleMCPCompletionState,+ findUser: (id) => methods.findUser({ _id: id }),+ getRoleByName: methods.getRoleByName,+ canViewAgent: async (agentId, user) => (await resolveAgentFireAccess(agentId, user)) === 'ok',+ enrollment: {+ canUseRoot: async (agentId, user) => (await resolveAgentFireAccess(agentId, user)) === 'ok',+ findUser: (id) => methods.findUser({ _id: id }),+ getAppConfig,+ resolveGraphAccess: (user) =>+ methods.resolveAgentGraphAccess({+ userId: user.id,+ role: user.role,+ idOnTheSource: user.idOnTheSource,+ }),+ getNodes: methods.getAgentGraphNodes,+ getModelsConfig: (user) => getModelsConfig({ user }),+ getServers: (user, config) =>+ getMCPServersRegistry().getAllServerConfigs(user.id, config, user.role),+ },+});diff --git a/api/server/services/Schedules/mcp.js b/api/server/services/Schedules/mcp.jsindex ae358c08f3..66e700824a 100644--- a/api/server/services/Schedules/mcp.js+++ b/api/server/services/Schedules/mcp.js@@ -31,6 +31,7 @@ function createMCPPreflight(options = {}) {getMCPServersRegistry().getAllServerConfigs(userId, config, role),findPluginAuthsByKeys: methods.findPluginAuthsByKeys,resolveUpstreamTokenProvider: options.resolveUpstreamTokenProvider,+ execution: require('./consent').execution,connect: (connectionOptions) =>getMCPManager().getConnection({...connectionOptions,diff --git a/packages/api/src/agents/__tests__/run-summarization.test.ts b/packages/api/src/agents/__tests__/run-summarization.test.tsindex dfb662bbae..9c5da0ce4b 100644--- a/packages/api/src/agents/__tests__/run-summarization.test.ts+++ b/packages/api/src/agents/__tests__/run-summarization.test.ts@@ -17,6 +17,7 @@ import type { OpenAI } from 'openai';import type { ModelBoundChatModelCallback } from '~/middleware/modelBoundContent';import type { OpenAIConfiguration, AzureOptions } from '~/types';import { clearToolApprovalHooks, registerToolApprovalHook } from '~/agents/hitl/hooks';+import { executionFixture } from '~/schedules/authorization/execution.helper';import { createRun, isAskUserQuestionAdminDisabled } from '~/agents/run';import { initializeOpenAI } from '~/endpoints/openai/initialize';import { getOpenAIConfig } from '~/endpoints/openai/config';@@ -101,8 +102,10 @@ import {Providers,HookRegistry,ToolNode,+ Constants,buildChildInputs,InMemorySubagentTaskStore,+ buildSubagentToolParams,executeHooks,} from '@librechat/agents';@@ -4521,6 +4524,196 @@ describe('HITL wiring is gated on hitlCapable', () => {},);+ it.each([false, true])(+ 'enforces the enrolled ceiling in a real SDK ToolNode with approval enabled=%s',+ async (enabled) => {+ const f = await executionFixture();+ const agent = makeAgent({+ id: 'root',+ toolRegistry: new Map([+ [+ 'query_mcp_warehouse',+ { name: 'query_mcp_warehouse', toolType: 'mcp', serverName: 'warehouse' },+ ],+ ]),+ });+ await createRun({+ agents: [agent] as never,+ signal: new AbortController().signal,+ scheduledMCPExecution: f.execution,+ appConfig: {+ ...hitlAppConfig,+ endpoints: {+ agents: { toolApproval: { enabled, mode: 'bypass', deny: ['query_mcp_warehouse'] } },+ },+ } as unknown as AppConfig,+ });+ const config = (Run.create as jest.Mock).mock.calls[0][0];+ expect(config).not.toHaveProperty('humanInTheLoop');+ for (const name of ['action_write', 'execute_code', 'query_mcp_warehouse']) {+ const body = jest.fn(async () => 'executed');+ const tool = new DynamicStructuredTool({+ name,+ description: 'Boundary regression',+ schema: z.object({}),+ func: body,+ });+ const node = new ToolNode({ tools: [tool], agentId: 'root', hookRegistry: config.hooks });+ const result = await node.invoke(+ {+ messages: [+ new AIMessage({ content: '', tool_calls: [{ id: 'call-1', name, args: {} }] }),+ ],+ },+ { configurable: { run_id: 'scheduled', thread_id: 'thread' } },+ );+ if (name === 'query_mcp_warehouse' && !enabled) expect(body).toHaveBeenCalledTimes(1);+ else {+ expect(body).not.toHaveBeenCalled();+ expect(JSON.stringify(result)).toContain('Blocked:');+ }+ }+ },+ );++ it.each([true, false])(+ 'withholds detached task/wakeup capabilities only for enrolled=%s',+ async (enrolled) => {+ const f = await executionFixture();+ if (!enrolled) f.snapshot.enrollment = null;+ const execution = (await f.factory.resolve(f.identity, 'invoke'))!;+ const tasks = {+ store: new InMemorySubagentTaskStore(),+ scopeId: 'scheduled-tasks',+ completionDelivery: 'wakeup' as const,+ };+ const root = makeAgent({+ id: 'root',+ subagents: { enabled: true, allowSelf: false, agent_ids: ['child'] },+ subagentAgentConfigs: [makeAgent({ id: 'child' })],+ });+ await createRun({+ agents: [root] as never,+ signal: new AbortController().signal,+ scheduledMCPExecution: execution,+ subagentTasks: tasks,+ appConfig: {+ ...hitlAppConfig,+ endpoints: { agents: { toolApproval: { enabled: false } } },+ } as unknown as AppConfig,+ });+ const config = (Run.create as jest.Mock).mock.calls[0][0];+ expect(config.subagentTasks).toBe(enrolled ? undefined : tasks);+ const params = buildSubagentToolParams(config.graphConfig.agents[0].subagentConfigs, {+ background: config.subagentTasks != null,+ threadContinuation: true,+ });+ expect(+ Object.prototype.hasOwnProperty.call(params.schema.properties ?? {}, 'run_in_background'),+ ).toBe(!enrolled);+ expect(+ Object.prototype.hasOwnProperty.call(params.schema.properties ?? {}, 'subagent_thread_id'),+ ).toBe(!enrolled);+ const agent = config.graphConfig.agents[0];+ expect(agent.subagentConfigs).toEqual([+ expect.objectContaining({ type: 'child', allowNested: true }),+ ]);+ const names = (agent.toolDefinitions ?? []).map((tool: { name: string }) => tool.name);+ expect(names.includes('check_background_task')).toBe(!enrolled);+ },+ );++ it.each([false, true])(+ 'retains mandatory denial receipts with remembered conversation approval=%s',+ async (remembered) => {+ const f = await executionFixture();+ const recorder = jest.fn(async () => true);+ await createRun({+ agents: [makeAgent({ id: 'root' })] as never,+ signal: new AbortController().signal,+ scheduledMCPExecution: f.execution,+ recordScheduledMCPDenial: recorder,+ toolApprovalAllows: remembered ? ['write_action_api'] : undefined,+ appConfig: {+ ...hitlAppConfig,+ endpoints: {+ agents: {+ toolApproval: { enabled: remembered, mode: 'default', allowAlways: remembered },+ },+ },+ } as unknown as AppConfig,+ });+ const config = (Run.create as jest.Mock).mock.calls[0][0];+ const body = jest.fn(async () => 'side effect');+ const action = new DynamicStructuredTool({+ name: 'write_action_api',+ description: 'Late action',+ schema: z.object({}),+ func: body,+ });+ const node = new ToolNode({ tools: [action], agentId: 'root', hookRegistry: config.hooks });+ await node.invoke(+ {+ messages: [+ new AIMessage({+ content: '',+ tool_calls: [{ id: 'call', name: action.name, args: {} }],+ }),+ ],+ },+ { configurable: { run_id: 'scheduled', thread_id: 'thread' } },+ );+ expect(body).not.toHaveBeenCalled();+ expect(recorder).toHaveBeenCalledWith(+ expect.objectContaining({+ failure: {+ reason: 'tool_policy_denied',+ status: 'mcp_permission_denied',+ recovery: 'configure',+ automaticReplay: false,+ },+ }),+ );+ },+ );++ it('passes only admitted root graph handoffs into the mandatory scheduled hook', async () => {+ const f = await executionFixture();+ const agents = [+ makeAgent({ id: 'root', edges: [{ from: 'root', to: 'child', edgeType: 'handoff' }] }),+ makeAgent({ id: 'child' }),+ makeAgent({ id: 'peer' }),+ ];+ await createRun({+ agents: agents as never,+ signal: new AbortController().signal,+ scheduledMCPExecution: f.execution,+ appConfig: {+ ...hitlAppConfig,+ endpoints: { agents: { toolApproval: { enabled: false } } },+ } as unknown as AppConfig,+ });+ const config = (Run.create as jest.Mock).mock.calls[0][0];+ for (const [toolName, expected] of [+ [`${Constants.LC_TRANSFER_TO_}child`, undefined],+ [`${Constants.LC_TRANSFER_TO_}peer`, 'deny'],+ ]) {+ const result = await executeHooks({+ registry: config.hooks,+ input: {+ hook_event_name: 'PreToolUse',+ runId: 'run',+ toolName: toolName!,+ toolInput: {},+ toolUseId: 'transfer',+ executingAgentId: 'root',+ },+ matchQuery: toolName!,+ });+ expect(result.decision).toBe(expected);+ }+ });+it('registers trusted per-run hooks on headless calls without prompting', async () => {const factory = jest.fn(() => async () => ({ decision: 'deny' as const }));const unregister = registerToolApprovalHook(factory, { matcher: '^write_file$' });diff --git a/packages/api/src/agents/backgroundCompletion.ts b/packages/api/src/agents/backgroundCompletion.tsindex e04f82a262..f1cf9b8191 100644--- a/packages/api/src/agents/backgroundCompletion.ts+++ b/packages/api/src/agents/backgroundCompletion.ts@@ -1,3 +1,4 @@+import type { ScheduledMCPIdentity } from 'librechat-data-provider';/** Deadline after which an invocation owner requests cancellation. */export const BACKGROUND_TASK_TIMEOUT_MS: number = 30 * 60 * 1000;/** Gives a cooperative tool a short window to settle after cancellation before@@ -16,6 +17,8 @@ export const BACKGROUND_SHUTDOWN_TEARDOWN_RESERVE_MS: number = 2_000;/** Host-owned identity recorded before ordinary background tool work begins. */export interface BackgroundToolWakeupRegistration {+ /** Origin captured by the generation's host, null for an ordinary turn. */+ scheduleMCPIdentity?: ScheduledMCPIdentity | null;taskId: string;toolCallId: string;toolName: string;diff --git a/packages/api/src/agents/backgroundCompletionWakeup.spec.ts b/packages/api/src/agents/backgroundCompletionWakeup.spec.tsindex f599dad7a6..139ccf0460 100644--- a/packages/api/src/agents/backgroundCompletionWakeup.spec.ts+++ b/packages/api/src/agents/backgroundCompletionWakeup.spec.ts@@ -1071,6 +1071,32 @@ describe('pending background completions', () => {});});+it('fences an ordinary background wakeup queued before schedule enrollment', async () => {+ const { methods } = resolverMethods();+ const lookup = jest.fn(async () => ({+ identity: {+ scheduleId: 'schedule',+ ownerId: 'user-1',+ tenantId: 'tenant-1',+ agentId: 'agent_parent_1',+ invocationMode: 'delegated' as const,+ },+ enrolled: true,+ }));+ const prepare = createBackgroundToolCompletionWakeupResolver({+ methods: methods as never,+ getGenerationJob: async () => null,+ getScheduleMCPCompletionState: lookup,+ });+ await expect(+ prepare(await envelope({ scheduleMCPIdentity: (await lookup()).identity }), {+ idempotencyKey: 'wakeup',+ } as never),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(lookup).toHaveBeenCalledWith((await lookup()).identity);+ expect(methods.claimBackgroundToolResults).not.toHaveBeenCalled();+});+describe('capability-gated receipt batch resolution', () => {function batchMethods() {const { methods } = resolverMethods();@@ -1101,6 +1127,37 @@ describe('capability-gated receipt batch resolution', () => {};}+ it.each([true, false])(+ 'keeps schedule lineage before receipt batch admission (enrolled=%s)',+ async (enrolled) => {+ const methods = batchMethods();+ const identity = {+ scheduleId: 'schedule',+ ownerId: 'user-1',+ tenantId: 'tenant-1',+ agentId: 'agent_parent_1',+ invocationMode: 'delegated' as const,+ };+ const prepare = createBackgroundToolCompletionWakeupResolver({+ methods: methods as never,+ getGenerationJob: async () => null,+ getScheduleMCPCompletionState: async () => ({ identity, enrolled }),+ });+ const pending = prepare(await envelope({ scheduleMCPIdentity: identity }), {+ idempotencyKey: 'batch',+ requiredWorkerCapability: AGENT_TRIGGER_WORKER_CAPABILITY_BACKGROUND_COMPLETION_BATCH_V3,+ });+ if (enrolled) {+ await expect(pending).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(methods.claimAgentBackgroundToolResultBatch).not.toHaveBeenCalled();+ } else+ await expect(pending).resolves.toMatchObject({+ status: 'ready',+ scheduleMCPIdentity: identity,+ });+ },+ );+it('does not probe batch storage for rollout-default v2 deliveries', async () => {const methods = batchMethods();const resolve = createBackgroundToolCompletionWakeupResolver({@@ -1271,3 +1328,28 @@ describe('capability-gated receipt batch resolution', () => {});});});++it.each([+ AGENT_TRIGGER_WORKER_CAPABILITY_BACKGROUND_COMPLETION_RECEIPT_V2,+ AGENT_TRIGGER_WORKER_CAPABILITY_BACKGROUND_COMPLETION_BATCH_V3,+])(+ 'does not apply historical schedule authority to an ordinary background completion (%s)',+ async (capability) => {+ const { methods } = resolverMethods();+ const lookup = jest.fn(async () => {+ throw new Error('historical schedule must not be consulted');+ });+ const prepare = createBackgroundToolCompletionWakeupResolver({+ methods: methods as never,+ getGenerationJob: async () => null,+ getScheduleMCPCompletionState: lookup,+ });+ const prepared = await prepare(await envelope(), {+ idempotencyKey: 'ordinary',+ requiredWorkerCapability: capability,+ });+ expect(prepared).toMatchObject({ status: 'ready' });+ expect(prepared).not.toHaveProperty('scheduleMCPIdentity');+ expect(lookup).not.toHaveBeenCalled();+ },+);diff --git a/packages/api/src/agents/backgroundCompletionWakeup.ts b/packages/api/src/agents/backgroundCompletionWakeup.tsindex 56a057f95d..efb96e171a 100644--- a/packages/api/src/agents/backgroundCompletionWakeup.ts+++ b/packages/api/src/agents/backgroundCompletionWakeup.ts@@ -24,9 +24,11 @@ import type {AgentTriggerContinuePreparation,AgentTriggerExecutionHostDeps,} from './triggers/host';+import type { ScheduleMCPCompletionLookup } from '~/schedules/authorization/continuation';import type { AgentContinueTriggerEnvelope } from './triggers/envelope';import type { AgentTriggerDispatchContext } from './triggers/dispatch';import type { AgentTriggerEnqueueOptions } from './triggers/delivery';+import { resolveScheduleMCPCompletion } from '~/schedules/authorization/continuation';import { WAITING_RETRY_CAP_MS, waitingRetryAfter } from './triggers/backoff';import { BACKGROUND_TOOL_PRODUCER_LEASE_MS } from './backgroundCompletion';import { SUBAGENT_COMPLETION_SOURCE } from './subagentCompletionWakeup';@@ -103,6 +105,7 @@ interface GenerationState {}export interface BackgroundToolCompletionWakeupResolverDeps {+ getScheduleMCPCompletionState?: ScheduleMCPCompletionLookup;methods: WakeupMethods;getGenerationJob: (conversationId: string) => Promise<GenerationState | null>;getResultBatchSize?: () => number | undefined;@@ -280,6 +283,7 @@ export function createBackgroundToolCompletionWakeupResolver({getGenerationJob,getResultBatchSize,getWaitMaxIntervalMs,+ getScheduleMCPCompletionState,recoverDeadClaim,getGenerationAdmissionEvidence,}: BackgroundToolCompletionWakeupResolverDeps): NonNullable<@@ -333,6 +337,18 @@ export function createBackgroundToolCompletionWakeupResolver({status: 404,});}+ const payload = envelope.event.payload;+ const scheduleMCPIdentity = await resolveScheduleMCPCompletion(+ {+ ownerId: userId,+ tenantId: envelope.principal.tenantId ?? null,+ scheduleMCPIdentity:+ payload && typeof payload === 'object' && 'scheduleMCPIdentity' in payload+ ? payload.scheduleMCPIdentity+ : undefined,+ },+ getScheduleMCPCompletionState,+ );const parentMessages = await methods.getMessages({ user: userId, conversationId: envelope.target.conversationId },MESSAGE_SELECT,@@ -620,6 +636,7 @@ export function createBackgroundToolCompletionWakeupResolver({return {status: 'ready',parentMessageId,+ ...(scheduleMCPIdentity && { scheduleMCPIdentity }),...(parent.codeApprovalMode != null && { codeApprovalMode: parent.codeApprovalMode }),input: buildWakeupInput(batch.results),releaseOnDefiniteFailure: async () => {@@ -725,6 +742,7 @@ export function createBackgroundToolCompletionWakeupResolver({return {status: 'ready',parentMessageId,+ ...(scheduleMCPIdentity && { scheduleMCPIdentity }),...(parent.codeApprovalMode != null && { codeApprovalMode: parent.codeApprovalMode }),input,releaseOnDefiniteFailure: async () => {@@ -795,6 +813,7 @@ export function createBackgroundToolCompletionWakeupResolver({return {status: 'ready',parentMessageId,+ ...(scheduleMCPIdentity && { scheduleMCPIdentity }),...(parent.codeApprovalMode != null && { codeApprovalMode: parent.codeApprovalMode }),input: buildWakeupInput(receiptClaim.results),releaseOnDefiniteFailure: async () => {@@ -831,6 +850,7 @@ export function createBackgroundToolCompletionWakeupResolver({return {status: 'ready',parentMessageId,+ ...(scheduleMCPIdentity && { scheduleMCPIdentity }),...(parent.codeApprovalMode != null && { codeApprovalMode: parent.codeApprovalMode }),input: buildWakeupInput([{ ...registration, status: receipt.status, output: receipt.output },@@ -1001,6 +1021,7 @@ export function createBackgroundToolCompletionWakeupHandler(occurredAt: registration.createdAt,source: { id: BACKGROUND_TOOL_COMPLETION_SOURCE, type: 'internal' },payload: {+ scheduleMCPIdentity: registration.scheduleMCPIdentity ?? null,taskId: registration.taskId,toolCallId: registration.toolCallId,toolName: registration.toolName,diff --git a/packages/api/src/agents/errors.ts b/packages/api/src/agents/errors.tsindex 37f6d1b207..f82c42df72 100644--- a/packages/api/src/agents/errors.ts+++ b/packages/api/src/agents/errors.ts@@ -4,6 +4,7 @@ import {parseLangChainErrorCode,stripLangChainTroubleshootingUrl,} from 'librechat-data-provider';+import { ScheduledMCPPolicyError } from '~/schedules/authorization/policy';import { MCPErrorCodes, isMCPInitializationError } from '~/mcp/errors';import { OboTokenResolutionError } from '~/mcp/oauth/obo';@@ -59,6 +60,7 @@ export function isFatalAgentInitializationError(): boolean {const code = getErrorCode(error);return (+ error instanceof ScheduledMCPPolicyError ||isMCPInitializationError(error, options.signal) ||FATAL_AGENT_INITIALIZATION_CODES.has(code as string) ||(code === AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE && options.allowExpectedMCPFallback !== true)diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex 719bf07583..1f2727c96e 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -110,6 +110,99 @@ function invokeHandlerWithConfig(* badge / persisted `skills_enabled` + ACL). Tests that mock* `getSkillByName` directly need this so they reach the lookup.*/+it('keeps enrolled MCP work foreground even when runnable metadata requests detached execution', async () => {+ const configs: Record<string, unknown>[] = [];+ const args: unknown[] = [];+ const name = 'query_mcp_warehouse';+ const tool = createMockTool(name, configs, { capturedArgs: args });+ const handler = createToolExecuteHandler({+ scheduledMCPExecution: {+ enrolled: true,+ identity: {+ scheduleId: 'schedule',+ ownerId: 'scheduled-owner',+ tenantId: null,+ agentId: 'root',+ invocationMode: 'delegated',+ },+ },+ loadTools: async () => ({ loadedTools: [tool] as never[] }),+ });+ const results = await invokeHandlerWithConfig(+ handler,+ [{ id: 'read', name, args: { run_in_background: true } }],+ {+ user_id: 'scheduled-owner',+ thread_id: 'scheduled-conversation',+ backgroundToolNames: [name],+ scheduledMCPExecution: { enrolled: false },+ },+ );+ expect(results).toEqual([+ expect.objectContaining({ status: 'success', content: expect.stringContaining('executed') }),+ ]);+ expect(JSON.stringify(results)).not.toContain('background_task_id');+ expect(args).toEqual([{}]);+ expect(configs).toHaveLength(1);+});++it.each([true, false])(+ 'captures background completion origin only from its host execution (scheduled=%s)',+ async (scheduled) => {+ const identity = {+ scheduleId: 'original-schedule',+ ownerId: 'origin-owner',+ tenantId: null,+ agentId: 'original-root',+ invocationMode: 'delegated' as const,+ };+ const preregister = jest.fn(async () => false as const);+ const name = 'query_mcp_warehouse';+ const handler = createToolExecuteHandler({+ ...(scheduled && { scheduledMCPExecution: { enrolled: false, identity } }),+ loadTools: async () => ({ loadedTools: [createMockTool(name, [])] as never[] }),+ backgroundToolCompletion: {+ preregister,+ persist: async () => true,+ claim: async () => {+ throw new Error('Unused manual claim');+ },+ },+ });+ await new Promise<ToolExecuteResult[]>((resolve, reject) => {+ void handler.handle('on_tool_execute', {+ resolve,+ reject,+ agentId: 'child',+ toolCalls: [+ {+ id: `origin-${scheduled}`,+ stepId: 'origin-step',+ name,+ args: { run_in_background: true, scheduleId: 'forged' },+ },+ ],+ configurable: {+ user_id: identity.ownerId,+ thread_id: 'origin-conversation',+ backgroundToolNames: [name],+ scheduledMCPExecution: { identity: { ...identity, scheduleId: 'forged' } },+ req: { user: { id: identity.ownerId }, body: { conversationId: 'origin-conversation' } },+ },+ metadata: { run_id: `origin-response-${scheduled}`, thread_id: 'origin-conversation' },+ });+ });+ expect(preregister).toHaveBeenCalledWith(+ expect.objectContaining({+ parentMessageId: `origin-response-${scheduled}`,+ conversationId: 'origin-conversation',+ scheduleMCPIdentity: scheduled ? identity : null,+ }),+ );+ await new Promise((resolve) => setImmediate(resolve));+ },+);+function skillsInScope(): unknown[] {const { Types } = jest.requireActual('mongoose') as typeof import('mongoose');return [new Types.ObjectId()];diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex b628525966..fb40c62e8e 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -52,6 +52,7 @@ import type {BackgroundToolWakeupRegistration,PendingBackgroundCompletionControls,} from './backgroundCompletion';+import type { ScheduleMCPExecution } from '~/schedules/authorization/execution';import type { SkillFileRecord, PrimeSkillFilesResult } from './skillFiles';import type { ArtifactDeliveryFailure } from '~/files/code';import type { BackgroundToolResultState } from './harvest';@@ -276,6 +277,8 @@ export function createOwnedToolEndHandler(}export interface ToolExecuteOptions {+ /** Host-captured authority ceiling, never runnable/model metadata. */+ scheduledMCPExecution?: Pick<ScheduleMCPExecution, 'enrolled' | 'identity'>;/*** Host-owned signal for the foreground run. This is authoritative across* graph reconstruction (including approval resume); the SDK event signal is@@ -5603,6 +5606,7 @@ function createSkillFilesHandoff(export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandler {const {+ scheduledMCPExecution,runSignal: hostRunSignal,foregroundRunId,loadTools,@@ -6048,6 +6052,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand) {try {const admission = await backgroundToolCompletion.preregister({+ scheduleMCPIdentity: scheduledMCPExecution?.identity ?? null,taskId: task.id,toolCallId: tc.id,toolName: tc.name,@@ -7158,6 +7163,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand}if (+ scheduledMCPExecution?.enrolled !== true &&backgroundToolSet.has(tc.name) &&isBackgroundRequested(tc.args) &&!toolRequiresEphemeralConnection(toolMap.get(tc.name)) &&diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.tsindex 5c5071580c..fabcc1f856 100644--- a/packages/api/src/agents/run.ts+++ b/packages/api/src/agents/run.ts@@ -53,6 +53,8 @@ import type { CallbackHandlerMethods } from '@langchain/core/callbacks/base';import type { BaseMessage } from '@librechat/agents/langchain/messages';import type { Callbacks } from '@langchain/core/callbacks/manager';import type { ModelBoundChatModelCallback } from '~/middleware/modelBoundContent';+import type { ScheduledMCPPolicyError } from '~/schedules/authorization/policy';+import type { ScheduleMCPExecution } from '~/schedules/authorization/execution';import type { ModelErrorTrackerCallback } from '~/agents/failures/tracker';import type { ToolInputValidationError } from '~/agents/toolValidation';import type { ResolvedToolApprovalHook } from '~/agents/hitl/hooks';@@ -111,6 +113,7 @@ import { stripIntentFromToolRegistry, stripIntentFromToolDefinitions } from '~/aimport { resolveConfigHeaders, resolveModelHeaders, mergeHeaders } from '~/utils/headers';import { extractDefaultParams, resolveReasoningParams } from '~/endpoints/openai/llm';import { getLLMConfig as getAnthropicLLMConfig } from '~/endpoints/anthropic/llm';+import { createScheduledMCPRunPolicy } from '~/schedules/authorization/run';import { CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME } from '~/agents/tools';import { buildAgentInitialToolSessions } from '~/agents/codeFilesSession';import { getDirectDispatcher, getProxyDispatcher } from '~/utils/proxy';@@ -2129,6 +2132,8 @@ export async function createRun({eventActorCheckpointing = false,hitlCapable = false,resolvedToolApprovalHooks,+ scheduledMCPExecution,+ recordScheduledMCPDenial,toolApprovalAllows,toolInputValidationErrors,sessionStartSource,@@ -2276,6 +2281,8 @@ export async function createRun({* Reuse them here so a context-aware factory is evaluated exactly once for the run.*/resolvedToolApprovalHooks?: readonly ResolvedToolApprovalHook[];+ scheduledMCPExecution?: ScheduleMCPExecution;+ recordScheduledMCPDenial?: (error: ScheduledMCPPolicyError) => Promise<boolean>;/** Plugin-hook SessionStart lifecycle source: 'startup' (default) or 'resume' on HITL-rebuild paths. */sessionStartSource?: string;/** Request-scoped tool input failures consumed by the completion handler. */@@ -2305,7 +2312,9 @@ export async function createRun({}// Detached child threads resume in a new host request without this run's// input snapshot or publication routing. Shared children stay foreground.- const activeSubagentTasks = runFilesActive ? undefined : subagentTasks;+ // Detached completion turns cannot yet restore enrolled schedule authority.+ const activeSubagentTasks =+ runFilesActive || scheduledMCPExecution?.enrolled === true ? undefined : subagentTasks;/*** Only extract discovered tools if:* 1. We have message history to parse@@ -2792,7 +2801,16 @@ export async function createRun({nativeEditFileAgentIds,);const hitl = hitlCapable ? approvalWiring : undefined;+ const scheduledPolicy = scheduledMCPExecution+ ? createScheduledMCPRunPolicy(+ scheduledMCPExecution,+ agents,+ agents[0].edges ?? [],+ recordScheduledMCPDenial,+ )+ : undefined;registerResolvedMCPToolAliases = (resolvedAgent) => {+ scheduledPolicy?.registerAgent(resolvedAgent);for (const agentId of collectNativeEditFileAgentIds([resolvedAgent])) {nativeEditFileAgentIds.add(agentId);}@@ -2849,6 +2867,10 @@ export async function createRun({* this guard is defense in depth).*/let hooks = approvalWiring?.hooks;+ if (scheduledPolicy) {+ hooks ??= new HookRegistry();+ hooks.register('PreToolUse', { hooks: [scheduledPolicy.hook, scheduledPolicy.receipt] });+ }if (usesSubagentCompletionWakeups(activeSubagentTasks)) {hooks = hooks ?? new HookRegistry();hooks.register('PostToolUse', {diff --git a/packages/api/src/agents/subagentCompletionWakeup.spec.ts b/packages/api/src/agents/subagentCompletionWakeup.spec.tsindex 0f09627557..460da1ea69 100644--- a/packages/api/src/agents/subagentCompletionWakeup.spec.ts+++ b/packages/api/src/agents/subagentCompletionWakeup.spec.ts@@ -127,7 +127,9 @@ describe('createSubagentCompletionWakeupHandler', () => {});});-function wakeupEnvelope(): AgentContinueTriggerEnvelope {+function wakeupEnvelope(+ scheduleMCPIdentity?: SubagentTaskWakeupRegistration['scheduleMCPIdentity'],+): AgentContinueTriggerEnvelope {const envelope = createAgentTriggerEnvelope({mode: 'continue',requestId: 'request-1',@@ -139,7 +141,12 @@ function wakeupEnvelope(): AgentContinueTriggerEnvelope {type: 'subagent.completion',occurredAt: NOW,source: { id: 'subagent-completion', type: 'internal' },- payload: { taskId: 'task-1', threadId: 'thread-1', subagentType: 'researcher' },+ payload: {+ taskId: 'task-1',+ threadId: 'thread-1',+ subagentType: 'researcher',+ scheduleMCPIdentity: scheduleMCPIdentity ?? null,+ },},target: {agentId: 'agent_parent_1',@@ -1564,3 +1571,47 @@ describe('createSubagentCompletionWakeupResolver', () => {});});});++it('refuses a queued legacy scheduled wakeup after enrollment before claiming its result', async () => {+ const { methods } = resolverMethods();+ const lookup = jest.fn(async () => ({+ identity: {+ scheduleId: 'schedule',+ ownerId: 'user-1',+ tenantId: 'tenant-1',+ agentId: 'agent_parent_1',+ invocationMode: 'delegated' as const,+ },+ enrolled: true,+ }));+ const prepare = createSubagentCompletionWakeupResolver({+ methods: methods as never,+ getGenerationJob: async () => null,+ getScheduleMCPCompletionState: lookup,+ });+ await expect(+ prepare(wakeupEnvelope((await lookup()).identity), {+ idempotencyKey: 'wakeup',+ attempt: 1,+ maxAttempts: 3,+ }),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(lookup).toHaveBeenCalledWith((await lookup()).identity);+ expect(methods.claimSubagentTaskResult).not.toHaveBeenCalled();+});++it('does not attach a historical schedule to an ordinary later subagent completion', async () => {+ const { methods } = resolverMethods();+ const lookup = jest.fn(async () => {+ throw new Error('historical schedule must not be consulted');+ });+ const prepare = createSubagentCompletionWakeupResolver({+ methods: methods as never,+ getGenerationJob: async () => null,+ getScheduleMCPCompletionState: lookup,+ });+ const prepared = await prepare(wakeupEnvelope(), { idempotencyKey: 'ordinary' });+ expect(prepared).toMatchObject({ status: 'ready' });+ expect(prepared).not.toHaveProperty('scheduleMCPIdentity');+ expect(lookup).not.toHaveBeenCalled();+});diff --git a/packages/api/src/agents/subagentCompletionWakeup.ts b/packages/api/src/agents/subagentCompletionWakeup.tsindex 0b70b205a2..357f4e847d 100644--- a/packages/api/src/agents/subagentCompletionWakeup.ts+++ b/packages/api/src/agents/subagentCompletionWakeup.ts@@ -5,10 +5,12 @@ import type {AgentTriggerContinuePreparation,AgentTriggerExecutionHostDeps,} from './triggers/host';+import type { ScheduleMCPCompletionLookup } from '~/schedules/authorization/continuation';import type { SubagentTaskWakeupRegistration } from './subagentThreads';import type { AgentContinueTriggerEnvelope } from './triggers/envelope';import type { AgentTriggerDispatchContext } from './triggers/dispatch';import type { AgentTriggerEnqueueOptions } from './triggers/delivery';+import { resolveScheduleMCPCompletion } from '~/schedules/authorization/continuation';import { WAITING_RETRY_CAP_MS, waitingRetryAfter } from './triggers/backoff';import { boundedSubagentTaskResult } from './subagentTaskRouting';import { createAgentTriggerEnvelope } from './triggers/envelope';@@ -79,6 +81,7 @@ interface OrchestrationSnapshotResolution {}export interface SubagentCompletionWakeupResolverDeps {+ getScheduleMCPCompletionState?: ScheduleMCPCompletionLookup;methods: WakeupMethods;getGenerationJob: (conversationId: string) => Promise<GenerationState | null>;now?: () => number;@@ -589,6 +592,7 @@ export function createSubagentCompletionWakeupResolver({getGenerationJob,now = Date.now,getWaitMaxIntervalMs,+ getScheduleMCPCompletionState,}: SubagentCompletionWakeupResolverDeps): NonNullable<AgentTriggerExecutionHostDeps['prepareContinue']> {@@ -748,6 +752,18 @@ export function createSubagentCompletionWakeupResolver({});}+ const payload = envelope.event.payload;+ const scheduleMCPIdentity = await resolveScheduleMCPCompletion(+ {+ ownerId: userId,+ tenantId: envelope.principal.tenantId ?? null,+ scheduleMCPIdentity:+ payload && typeof payload === 'object' && 'scheduleMCPIdentity' in payload+ ? payload.scheduleMCPIdentity+ : undefined,+ },+ getScheduleMCPCompletionState,+ );const claim = await methods.claimSubagentTaskResult({userId,conversationId: registration.threadId,@@ -790,6 +806,7 @@ export function createSubagentCompletionWakeupResolver({return {status: 'ready',parentMessageId,+ ...(scheduleMCPIdentity && { scheduleMCPIdentity }),...(parent.codeApprovalMode != null && { codeApprovalMode: parent.codeApprovalMode }),input: renderWakeupInput(registration, resultTaskId, claim.message, orchestrationSnapshot),releaseOnDefiniteFailure: async () => {@@ -832,6 +849,7 @@ export function createSubagentCompletionWakeupHandler(occurredAt: registration.createdAt,source: { id: SUBAGENT_COMPLETION_SOURCE, type: 'internal' },payload: {+ scheduleMCPIdentity: registration.scheduleMCPIdentity ?? null,taskId: registration.taskId,threadId: registration.threadId,subagentType: registration.subagentType,diff --git a/packages/api/src/agents/subagentThreads.spec.ts b/packages/api/src/agents/subagentThreads.spec.tsindex 003a8aaa17..df315f415f 100644--- a/packages/api/src/agents/subagentThreads.spec.ts+++ b/packages/api/src/agents/subagentThreads.spec.ts@@ -517,6 +517,7 @@ describe('SubagentThreadTaskStore', () => {userId,parentConversationId,parentMessageId: 'parent-response-1',+ scheduleMCPIdentity: null,parentAgentId: 'agent_parent_1',taskId: requireAccepted(started).task.taskId,threadId: requireThreadId(started),@@ -525,6 +526,58 @@ describe('SubagentThreadTaskStore', () => {});});+ it('captures authority from the parent task config, never SDK request fields or a reused conversation', async () => {+ const userId = 'task-origin-user';+ const parentConversationId = randomUUID();+ await saveParent(userId, parentConversationId);+ const prepared = jest.fn(async (_registration: SubagentTaskWakeupRegistration) => {});+ const store = new SubagentThreadTaskStore(methods, { onTaskPrepared: prepared });+ const identity = {+ scheduleId: 'original-schedule',+ ownerId: userId,+ tenantId: null,+ agentId: 'parent-agent',+ invocationMode: 'delegated' as const,+ };+ const scheduled = buildSubagentThreadTaskConfig(+ store,+ { userId, parentConversationId },+ { completionWakeups: true, scheduleMCPIdentity: identity },+ );+ identity.agentId = 'mutated-after-construction';+ const first = scheduled.store.start(+ taskRequest(scheduled.scopeId, {+ parentRunId: 'scheduled-response',+ idempotencyKey: randomUUID(),+ scheduleMCPIdentity: null,+ } as never),+ );+ await waitForSettled(store, scheduled.scopeId, first);+ expect(prepared).toHaveBeenLastCalledWith(+ expect.objectContaining({+ parentMessageId: 'scheduled-response',+ scheduleMCPIdentity: { ...identity, agentId: 'parent-agent' },+ }),+ );+ const ordinary = buildSubagentThreadTaskConfig(+ store,+ { userId, parentConversationId },+ { completionWakeups: true },+ );+ const later = ordinary.store.start(+ taskRequest(ordinary.scopeId, {+ parentRunId: 'ordinary-response',+ idempotencyKey: randomUUID(),+ scheduleMCPIdentity: identity,+ } as never),+ );+ await waitForSettled(store, ordinary.scopeId, later);+ expect(prepared).toHaveBeenLastCalledWith(+ expect.objectContaining({ parentMessageId: 'ordinary-response', scheduleMCPIdentity: null }),+ );+ store.destroyActivityStream();+ });+it('announces a settled child only after its terminal message is durable', async () => {const userId = 'settled-child-user';const parentConversationId = randomUUID();diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.tsindex 10171e48ae..c2d5fb81d2 100644--- a/packages/api/src/agents/subagentThreads.ts+++ b/packages/api/src/agents/subagentThreads.ts@@ -30,6 +30,7 @@ import type {} from '@librechat/data-schemas';import type { BaseMessage, StoredMessage } from '@librechat/agents/langchain/messages';import type { TSubagentActivityConfig } from 'librechat-data-provider';+import type { ScheduledMCPIdentity } from 'librechat-data-provider';import type {SubagentActivityUpdateEvent,SubagentActivitySubscriber,@@ -146,6 +147,7 @@ interface PreparedThread {}interface HostSubagentTaskStartRequest extends SubagentTaskStartRequest {+ scheduleMCPIdentity?: ScheduledMCPIdentity | null;completionDelivery?: typeof SUBAGENT_COMPLETION_DELIVERY;}@@ -281,6 +283,8 @@ export interface SubagentThreadTaskStoreOptions extends InMemorySubagentTaskStor}export interface SubagentTaskWakeupRegistration {+ /** Host-captured generation origin, never inferred from conversation history. */+ scheduleMCPIdentity?: ScheduledMCPIdentity | null;userId: string;parentConversationId: string;parentMessageId: string;@@ -3335,6 +3339,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {return;}const admitted = await this.onTaskPrepared({+ scheduleMCPIdentity: (request as HostSubagentTaskStartRequest).scheduleMCPIdentity ?? null,userId: scope.userId,parentConversationId: scope.parentConversationId,parentMessageId: task.parentRunId,@@ -3609,8 +3614,12 @@ type CompletionWakeupStore = SubagentTaskStore &const completionWakeupStores = new WeakMap<SubagentThreadTaskStore, CompletionWakeupStore>();-function completionWakeupStore(store: SubagentThreadTaskStore): CompletionWakeupStore {- const existing = completionWakeupStores.get(store);+function completionWakeupStore(+ store: SubagentThreadTaskStore,+ identity?: ScheduledMCPIdentity,+): CompletionWakeupStore {+ const captured = identity && Object.freeze(structuredClone(identity));+ const existing = captured ? undefined : completionWakeupStores.get(store);if (existing != null) {return existing;}@@ -3620,6 +3629,7 @@ function completionWakeupStore(store: SubagentThreadTaskStore): CompletionWakeupconst hostRequest: HostSubagentTaskStartRequest = {...request,completionDelivery: SUBAGENT_COMPLETION_DELIVERY,+ scheduleMCPIdentity: captured ?? null,};return store.start(hostRequest);},@@ -3633,16 +3643,19 @@ function completionWakeupStore(store: SubagentThreadTaskStore): CompletionWakeuphasTasks: (scopeId) => store.hasTasks(scopeId),listTasks: (scopeId) => store.listTasks(scopeId),};- completionWakeupStores.set(store, adapter);+ if (!captured) completionWakeupStores.set(store, adapter);return adapter;}export function buildSubagentThreadTaskConfig(store: SubagentThreadTaskStore,scope: Omit<SubagentThreadScope, 'version'>,- options: { completionWakeups?: boolean } = {},+ options: { completionWakeups?: boolean; scheduleMCPIdentity?: ScheduledMCPIdentity } = {},): HostSubagentTaskConfig {- const taskStore = options.completionWakeups === true ? completionWakeupStore(store) : store;+ const taskStore =+ options.completionWakeups === true+ ? completionWakeupStore(store, options.scheduleMCPIdentity)+ : store;return {store: taskStore,scopeId: serializeScope(scope),diff --git a/packages/api/src/agents/triggers/host.spec.ts b/packages/api/src/agents/triggers/host.spec.tsindex ecc1a74023..3ee976c4f2 100644--- a/packages/api/src/agents/triggers/host.spec.ts+++ b/packages/api/src/agents/triggers/host.spec.ts@@ -576,6 +576,7 @@ describe('createAgentTriggerExecutionHost continue adapter', () => {const [input, init] = fetcher.mock.calls[0];expect(String(input)).toBe('http://127.0.0.1:3080/api/agents/chat/agents');expect(JSON.parse(String(init?.body))).toEqual({+ agentCompletion: { version: 1, sourceId: 'subagent-completion' },text: envelope.input,endpoint: EModelEndpoint.agents,agent_id: 'agent-1',diff --git a/packages/api/src/agents/triggers/host.ts b/packages/api/src/agents/triggers/host.tsindex 30c6eb818e..30c1d7493e 100644--- a/packages/api/src/agents/triggers/host.ts+++ b/packages/api/src/agents/triggers/host.ts@@ -1,6 +1,7 @@import { logger, tenantStorage } from '@librechat/data-schemas';import { Constants, EModelEndpoint } from 'librechat-data-provider';import type { CodeApprovalMode, TFile, TReasoningOverride } from 'librechat-data-provider';+import type { ScheduledMCPIdentity } from 'librechat-data-provider';import type {AgentContinueTriggerEnvelope,AgentFireTriggerEnvelope,@@ -50,6 +51,7 @@ export interface AgentContinuationAdmissionSource {export type AgentTriggerContinuePreparation =| {status: 'ready';+ scheduleMCPIdentity?: ScheduledMCPIdentity;input: string;parentMessageId: string;expectedPredecessorCreatedAt?: number;@@ -717,6 +719,19 @@ async function startRun(...(detachedCompletion == null ? {} : { internalCompletion: detachedCompletion }),},}),+ ...(envelope.mode === 'continue' &&+ envelope.event.source.type === 'internal' &&+ ['subagent-completion', 'background-tool-completion'].includes(+ envelope.event.source.id,+ ) && {+ agentCompletion: {+ version: 1,+ sourceId: envelope.event.source.id,+ ...(readyPreparation?.scheduleMCPIdentity && {+ scheduleMCPIdentity: readyPreparation.scheduleMCPIdentity,+ }),+ },+ }),...(envelope.mode === 'fire' && {agentTrigger: {version: envelope.version,diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex cc30d4ee54..bb0fe33182 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -11,6 +11,7 @@ import type {UpstreamTokenProvider,UpstreamTokenProviderResolver,} from '~/mcp/oauth/obo';+import type { ScheduledMCPInvocation } from '~/schedules/authorization/execution';import type { MCPAppOperationContext, MCPAppValidationContext } from './apps';import type { MCPClientCapabilityProfile } from './capabilities';import type { AuthIdentityContext } from '~/utils/identity';@@ -51,6 +52,7 @@ import { MCPAuthenticationRejectedError, isMCPTransportAuthenticationError } froimport { resolveDirectOpenIDBearerConfig, usesDirectOpenIDBearerRecovery } from './openid';import { createLazyOboUpstreamTokenProvider, awaitOboOperation } from '~/mcp/oauth/obo';import { MCPAppOperationBudget, getMCPAppOperationLimits } from './apps/budget';+import { ScheduledMCPPolicyError } from '~/schedules/authorization/policy';import { formatToolContent, selectResolvedAppResource } from './parsers';import { MCPServersInitializer } from './registry/MCPServersInitializer';import { OboTokenResolutionError, resolveOboToken } from '~/mcp/oauth';@@ -1426,7 +1428,9 @@ Please follow these instructions when using tools from the respective MCP serveronOAuthCredentialsChanged,onOAuthCredentialsChanging,mcpApps,+ scheduledMCPInvocation,}: {+ scheduledMCPInvocation?: ScheduledMCPInvocation;user?: IUser;serverName: string;/** Pre-resolved config from tool creation context — avoids readThrough TTL and cross-tenant issues */@@ -1453,6 +1457,8 @@ Please follow these instructions when using tools from the respective MCP servermcpApps?: TMCPAppsPolicy;}): Promise<t.FormattedToolResponse> {const userId = user?.id;+ const enforceSchedule =+ scheduledMCPInvocation != null && scheduledMCPInvocation.enrolled !== false;const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);const logPrefix = userId ? `[MCP][User: ${userId}][${serverName}]` : `[MCP][${serverName}]`;this.bindRequestScopedConnectionStore(requestScopedConnections);@@ -1846,8 +1852,17 @@ Please follow these instructions when using tools from the respective MCP server}}- const requestTool = () =>- withMCPRequestSignal(options?.signal, (signal) =>+ const requestTool = async () => {+ await scheduledMCPInvocation?.authorize({+ user,+ serverName,+ serverConfig: declaredConfig,+ toolName,+ loadTools: () => connection!.fetchToolsSnapshot(undefined, options?.signal),+ signal: options?.signal,+ });+ options?.signal?.throwIfAborted();+ return withMCPRequestSignal(options?.signal, (signal) =>connection!.client.request({method: 'tools/call',@@ -1865,6 +1880,7 @@ Please follow these instructions when using tools from the respective MCP server},),);+ };// Deliberately use `request`: the typed wrapper also enforces the tool's output schema and// rejects task-required tools, which would turn a server response into a host-side failure.@@ -1873,6 +1889,14 @@ Please follow these instructions when using tools from the respective MCP servertry {result = await requestTool();} catch (error) {+ if (error instanceof ScheduledMCPPolicyError) throw error;+ // A resource rejection cannot prove that the operation had no side effects.+ if (enforceSchedule) {+ if (isMCPTransportAuthenticationError(error))+ throw new MCPAuthenticationRejectedError(serverName, false, error);+ // JSON-RPC OAuth-looking errors are operation failures, not replay permission.+ throw error;+ }if (directBearerRecovery && user && isMCPTransportAuthenticationError(error)) {if (directBearerRecoveryState.attempted) {throw new MCPAuthenticationRejectedError(serverName, false, error);@@ -2085,6 +2109,13 @@ Please follow these instructions when using tools from the respective MCP serverlogger.debug(`${logPrefix}[${toolName}] Tool call cancelled by user abort`);throw error;}+ if (enforceSchedule && error instanceof MCPAuthenticationRejectedError) {+ throw new ScheduledMCPPolicyError(+ 'credential_rejected',+ serverName,+ scheduledMCPInvocation?.agentId,+ );+ }// Log with context and re-throw or handle as neededlogger.error(`${logPrefix}[${toolName}] Tool call failed`, error);// Rethrowing allows the caller (createMCPTool) to handle the final user messagediff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex b769ee993a..56d63485c2 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 { executionFixture, readTool } from '~/schedules/authorization/execution.helper';import { createMCPRequestContext, cleanupMCPRequestContext } from '~/mcp/request';import { MCPServersInitializer } from '~/mcp/registry/MCPServersInitializer';import { MCPServerInspector } from '~/mcp/registry/MCPServerInspector';@@ -918,6 +919,121 @@ describe('MCPManager', () => {});});+ describe('callTool - scheduled authority boundary', () => {+ async function setupScheduled(stage: 'invoke' | 'resume' = 'invoke') {+ const fixture = await executionFixture(stage);+ const request = jest.fn().mockResolvedValue({ content: [{ type: 'text', text: 'read' }] });+ const snapshot = jest.fn().mockResolvedValue({ tools: [readTool], complete: true });+ const connection = {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ fetchToolsSnapshot: snapshot,+ timeout: 30_000,+ client: fakeClient(request, { tools: {} }),+ } as unknown as MCPConnection;+ const manager = new MCPManager();+ jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);+ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(+ async (options) => options,+ );+ const call = (agentId = 'root') =>+ manager.callTool({+ user: fixture.user,+ serverName: 'warehouse',+ serverConfig: fixture.config,+ toolName: 'query',+ provider: 'openai',+ flowManager: {} as Parameters<MCPManager['callTool']>[0]['flowManager'],+ scheduledMCPInvocation: fixture.invocation(agentId),+ });+ return { fixture, request, snapshot, call };+ }++ it.each(['root', 'child'])('dispatches an authorized %s read once', async (agentId) => {+ const { request, call } = await setupScheduled();+ await call(agentId);+ expect(request.mock.calls.filter(([input]) => input.method === 'tools/call')).toHaveLength(1);+ });++ it.each(['revoke', 'expire', 'deny'] as const)(+ 'never dispatches after %s, including deliberate retries',+ async (mutation) => {+ const { fixture, request, call } = await setupScheduled('resume');+ await fixture[mutation]();+ await expect(call()).rejects.toMatchObject({ failure: { automaticReplay: false } });+ await expect(call()).rejects.toMatchObject({ failure: { automaticReplay: false } });+ expect(request).not.toHaveBeenCalled();+ },+ );++ it('rejects misleading mutating metadata and changed definitions without reaching tools/call', async () => {+ const { request, snapshot, call } = await setupScheduled();+ snapshot.mockResolvedValue({+ tools: [+ {+ ...readTool,+ description: 'Read only!',+ annotations: { readOnlyHint: true },+ inputSchema: { type: 'object', properties: { write: { type: 'boolean' } } },+ },+ ],+ complete: true,+ });+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'tool_policy_denied' } });+ expect(request).not.toHaveBeenCalled();+ });++ it('fences consent revoked during live tools/list immediately before dispatch', async () => {+ const { fixture, request, snapshot, call } = await setupScheduled();+ snapshot.mockImplementation(async () => {+ await fixture.revoke();+ return { tools: [readTool], complete: true };+ });+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'consent_revoked' } });+ expect(request).not.toHaveBeenCalled();+ });++ it('attributes a protected catalog credential rejection without dispatch or provider text', async () => {+ const { request, snapshot, call } = await setupScheduled();+ snapshot.mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError: Object.assign(new Error('Bearer PRIVATE'), { status: 401 }),+ });+ let failure: unknown;+ try {+ await call('child');+ } catch (error) {+ failure = error;+ }+ expect(failure).toMatchObject({+ failure: {+ reason: 'credential_rejected',+ status: 'mcp_reauth_required',+ automaticReplay: false,+ },+ outcomes: [expect.objectContaining({ agentId: 'child' })],+ });+ expect(String(failure)).not.toContain('PRIVATE');+ expect(request).not.toHaveBeenCalled();+ });++ it('never automatically replays a protected call after resource bearer rejection', async () => {+ const { request, call } = await setupScheduled();+ request.mockRejectedValue(Object.assign(new Error('HTTP 401'), { status: 401 }));+ await expect(call()).rejects.toMatchObject({+ failure: {+ reason: 'credential_rejected',+ status: 'mcp_reauth_required',+ automaticReplay: false,+ },+ outcomes: [expect.objectContaining({ agentId: 'root' })],+ });+ expect(request).toHaveBeenCalledTimes(1);+ });+ });+describe('callTool - cancellation logging', () => {const mockUser = { id: 'cancel-user' } as IUser;const mockFlowManager = {} as Parameters<MCPManager['callTool']>[0]['flowManager'];@@ -1968,6 +2084,39 @@ describe('MCPManager', () => {expect(request.mock.calls[1]).toEqual(request.mock.calls[0]);});+ it.each([true, false])(+ 'preserves first JSON-RPC failure without stored-OAuth replay for enrolled=%s',+ async (enrolled) => {+ const failure = new McpError(ErrorCode.InternalError, 'HTTP 401 invalid_token');+ const request = jest.fn().mockRejectedValueOnce(failure).mockResolvedValueOnce(toolResult);+ const connection = createConnection(request);+ attachOAuthHandler();+ const manager = await createManager(connection);+ const authorize = jest.fn(async () => undefined);+ const identity = {+ scheduleId: 's',+ ownerId: mockUser.id,+ tenantId: null,+ agentId: 'root',+ invocationMode: 'delegated' as const,+ };+ const result = manager.callTool({+ user: mockUser,+ serverName,+ toolName: 'oauth_tool',+ provider: 'openai',+ flowManager: mockFlowManager,+ oauthStart: jest.fn(),+ scheduledMCPInvocation: { identity, enrolled, agentId: 'root', authorize },+ });+ if (enrolled) await expect(result).rejects.toBe(failure);+ else await expect(result).resolves.toBeDefined();+ expect(request).toHaveBeenCalledTimes(enrolled ? 1 : 2);+ expect(authorize).toHaveBeenCalledTimes(enrolled ? 1 : 2);+ expect(connection.connect).toHaveBeenCalledTimes(enrolled ? 0 : 1);+ },+ );+it('carries the request credential through a delayed 401 after the connection rotates', async () => {let credential = 'credential-a';const request = jest@@ -3716,6 +3865,60 @@ describe('MCPManager', () => {expect(mockResolveOboToken).not.toHaveBeenCalled();});+ it.each([true, false])(+ 'does not replay an enrolled OBO JSON-RPC invalid_token failure, enrolled=%s',+ async (enrolled) => {+ const failure = new McpError(ErrorCode.InternalError, 'invalid_token');+ const request = jest+ .fn()+ .mockRejectedValueOnce(failure)+ .mockResolvedValueOnce({ content: [{ type: 'text', text: 'retried' }] });+ const connection = {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ setOAuthTokens: jest.fn(),+ isOAuthAuthenticationError: jest.fn().mockReturnValue(true),+ timeout: 30000,+ client: { request },+ } as unknown as MCPConnection;+ mockResolveOboToken.mockResolvedValue({+ access_token: 'current-token',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ expires_at: Date.now() + 3600_000,+ });+ mockAppConnections({ get: jest.fn().mockResolvedValue(connection) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ jest.spyOn(manager, 'getUserConnection').mockResolvedValue(connection);+ const authorize = jest.fn(async () => undefined);+ const identity = {+ scheduleId: 's',+ ownerId: String(mockUser.id),+ tenantId: null,+ agentId: 'root',+ invocationMode: 'delegated' as const,+ };+ const result = manager.callTool({+ user: mockUser as IUser,+ serverName,+ toolName: 'test_tool',+ provider: 'openai',+ flowManager: mockFlowManager as unknown as Parameters<+ typeof manager.callTool+ >[0]['flowManager'],+ oboTokenResolver: mockOboTokenResolver,+ upstreamTokenProvider: mockUpstreamTokenProvider,+ scheduledMCPInvocation: { identity, enrolled, agentId: 'root', authorize },+ });+ if (enrolled) await expect(result).rejects.toBe(failure);+ else await expect(result).resolves.toBeDefined();+ expect(request).toHaveBeenCalledTimes(enrolled ? 1 : 2);+ expect(authorize).toHaveBeenCalledTimes(enrolled ? 1 : 2);+ expect(mockResolveOboToken).toHaveBeenCalledTimes(enrolled ? 1 : 2);+ },+ );+it('re-exchanges past the token cache when the server rejects the bearer mid-call', async () => {const authError = new Error('HTTP 401 Unauthorized');const rejectingConnection = {diff --git a/packages/api/src/mcp/__tests__/scope.integration.test.ts b/packages/api/src/mcp/__tests__/scope.integration.test.tsindex 1ffec3e56a..4a6f043f11 100644--- a/packages/api/src/mcp/__tests__/scope.integration.test.ts+++ b/packages/api/src/mcp/__tests__/scope.integration.test.ts@@ -11,6 +11,7 @@ import type { FlowStateManager } from '~/flow/manager';import type { MCPRequestContext } from '~/mcp/request';import type { MCPOAuthTokens } from '~/mcp/oauth';import { createMCPRequestContext, cleanupMCPRequestContext } from '~/mcp/request';+import { executionFixture } from '~/schedules/authorization/execution.helper';import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { getFreePort } from '~/mcp/__tests__/helpers/oauthTestServer';import { ConnectionsRepository } from '~/mcp/ConnectionsRepository';@@ -118,6 +119,10 @@ async function createRequestScopedTestServer(): Promise<RequestScopedTestServer>toolCalls += 1;return { content: [{ type: 'text', text: value }] };});+ mcp.tool('write', 'Legacy mutation', {}, async () => {+ toolCalls += 1;+ return { content: [{ type: 'text', text: 'write performed' }] };+ });await mcp.connect(transport);}@@ -247,6 +252,213 @@ describe('request-scoped MCP lifecycle integration', () => {return context;}+ it('sends enrolled reads once and never sends a revoked child/resume retry to the real server', async () => {+ const context = createContext();+ const config: ParsedServerConfig = { type: 'streamable-http', url: server.url };+ const connection = await manager.getConnection({+ user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const catalog = await connection.fetchToolsSnapshot();+ const f = await executionFixture('resume', catalog.tools[0], server.url);+ const protectedConnection = await manager.getConnection({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const invoke = (agentId: string) =>+ manager.callTool({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ toolName: 'echo',+ provider: 'openai',+ toolArguments: { value: 'read' },+ requestScopedConnections: context,+ flowManager,+ scheduledMCPInvocation: f.invocation(agentId),+ });+ try {+ await invoke('root');+ await invoke('child');+ expect(server.toolCallCount()).toBe(2);+ await f.revoke();+ await expect(invoke('child')).rejects.toMatchObject({+ failure: { reason: 'consent_revoked', automaticReplay: false },+ });+ await expect(invoke('root')).rejects.toMatchObject({+ failure: { reason: 'consent_revoked' },+ });+ expect(server.toolCallCount()).toBe(2);+ } finally {+ await Promise.all([connection.disconnect(), protectedConnection.disconnect()]);+ }+ MCPConnection.clearCooldown('warehouse');+ });++ it.each(['snapshot', 'consent'] as const)(+ 'never dispatches an enrolled operation when %s authorization storage fails',+ async (phase) => {+ const context = createContext();+ const config: ParsedServerConfig = { type: 'streamable-http', url: server.url };+ const connection = await manager.getConnection({+ user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const catalog = await connection.fetchToolsSnapshot();+ const f = await executionFixture(+ 'resume',+ catalog.tools.find(({ name }) => name === 'echo')!,+ server.url,+ );+ const active = await manager.getConnection({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const internal = new Error('PRIVATE principal/configuration/consent read');+ if (phase === 'snapshot') f.loadAuthorization.mockRejectedValue(internal);+ else jest.spyOn(f.service.authority, 'authorize').mockRejectedValue(internal);+ const call = (agentId: string) =>+ manager.callTool({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ toolName: 'echo',+ toolArguments: { value: 'read' },+ provider: 'openai',+ requestScopedConnections: context,+ flowManager,+ scheduledMCPInvocation: f.invocation(agentId),+ });+ try {+ for (const agentId of ['root', 'child']) {+ await expect(call(agentId)).rejects.toMatchObject({+ failure: { reason: 'dependency_unavailable', automaticReplay: false },+ outcomes: [{ server: 'warehouse', agentId, reason: 'dependency_unavailable' }],+ });+ }+ expect(server.toolCallCount()).toBe(0);+ } finally {+ await Promise.all([connection.disconnect(), active.disconnect()]);+ MCPConnection.clearCooldown('warehouse');+ }+ },+ );++ it('dispatches a paused enrolled manual read without permitting an automatic call', async () => {+ const context = createContext();+ const config: ParsedServerConfig = { type: 'streamable-http', url: server.url };+ const connection = await manager.getConnection({+ user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const catalog = await connection.fetchToolsSnapshot();+ const f = await executionFixture('resume', catalog.tools[0], server.url);+ f.snapshot.enabled = false;+ const manual = (await f.factory.resolve(f.identity, 'resume', { manual: true }))!;+ const protectedConnection = await manager.getConnection({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const call = (guard: ReturnType<typeof manual.bind>) =>+ manager.callTool({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ toolName: 'echo',+ provider: 'openai',+ toolArguments: { value: 'read' },+ requestScopedConnections: context,+ flowManager,+ scheduledMCPInvocation: guard,+ });+ try {+ await expect(call(f.invocation('root'))).rejects.toMatchObject({+ failure: { reason: 'binding_mismatch' },+ });+ expect(server.toolCallCount()).toBe(0);+ await call(manual.bind('child', 'echo'));+ expect(server.toolCallCount()).toBe(1);+ await f.revoke();+ await expect(call(manual.bind('child', 'echo'))).rejects.toMatchObject({+ failure: { reason: 'consent_revoked' },+ });+ expect(server.toolCallCount()).toBe(1);+ } finally {+ await Promise.all([connection.disconnect(), protectedConnection.disconnect()]);+ MCPConnection.clearCooldown('warehouse');+ }+ });++ it('fences a cached legacy MCP write immediately after narrower enrollment', async () => {+ const context = createContext();+ const config: ParsedServerConfig = { type: 'streamable-http', url: server.url };+ const connection = await manager.getConnection({+ user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const catalog = await connection.fetchToolsSnapshot();+ const echo = catalog.tools.find(({ name }) => name === 'echo')!;+ const f = await executionFixture('invoke', echo, server.url);+ f.snapshot.enrollment = null;+ const legacy = (await f.factory.resolve(f.identity, 'invoke'))!;+ const cachedWrite = legacy.bind('root', 'write');+ const active = await manager.getConnection({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ requestScopedConnections: context,+ flowManager,+ });+ const call = () =>+ manager.callTool({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: config,+ toolName: 'write',+ toolArguments: {},+ provider: 'openai',+ requestScopedConnections: context,+ flowManager,+ scheduledMCPInvocation: cachedWrite,+ });+ try {+ await call();+ expect(server.toolCallCount()).toBe(1);+ const offer = await f.service.view(f.identity);+ await f.service.confirm(f.identity, {+ offerDigest: offer.offer!.digest,+ expectedRevision: null,+ lifetimeHours: 1,+ });+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(server.toolCallCount()).toBe(1);+ } finally {+ await Promise.all([connection.disconnect(), active.disconnect()]);+ MCPConnection.clearCooldown('warehouse');+ }+ });+it('coalesces a concurrent burst, tears down the run, and isolates the next run', async () => {const config = createServerConfig(server.url);const firstRun = createContext();diff --git a/packages/api/src/schedules/authorization/continuation.ts b/packages/api/src/schedules/authorization/continuation.tsnew file mode 100644index 0000000000..085a10b5a7--- /dev/null+++ b/packages/api/src/schedules/authorization/continuation.ts@@ -0,0 +1,75 @@+import { scheduledMCPIdentitySchema } from 'librechat-data-provider';+import type { ScheduledMCPIdentity } from 'librechat-data-provider';+import type { ScheduleMethods } from '@librechat/data-schemas';+import type { IJobStore } from '~/stream/interfaces/IJobStore';+import { ScheduledMCPPolicyError } from './policy';++export type ScheduleMCPCompletionLookup = ScheduleMethods['getScheduleMCPCompletionState'];++/** Completion turns cannot adopt consent granted after their parent task was admitted. */+export async function resolveScheduleMCPCompletion(+ scope: { ownerId: string; tenantId: string | null; scheduleMCPIdentity?: unknown },+ lookup?: ScheduleMCPCompletionLookup,+): Promise<ScheduledMCPIdentity | undefined> {+ if (scope.scheduleMCPIdentity == null) return;+ const identity = parseScheduleMCPCompletion(scope.scheduleMCPIdentity);+ if (identity.ownerId !== scope.ownerId || identity.tenantId !== scope.tenantId)+ throw new ScheduledMCPPolicyError('binding_mismatch', '', identity.agentId);+ if (!lookup) throw new ScheduledMCPPolicyError('dependency_unavailable', '', identity.agentId);+ const state = await lookup(identity);+ if (!state || state.enrolled)+ throw new ScheduledMCPPolicyError('binding_mismatch', '', identity.agentId);+ return identity;+}++/** Only the signed host may project a task's captured origin into completion admission. */+export function isScheduledMCPCompletionRequest(req: {+ _isAgentTrigger?: boolean;+ body?: Record<string, unknown>;+}): boolean {+ return (+ req._isAgentTrigger === true &&+ typeof req.body?.conversationId === 'string' &&+ req.body.agentTrigger == null &&+ req.body.agentEventDelivery == null+ );+}++/** A malformed retained identity is never an ordinary, unrestricted job. */+export function parseScheduleMCPCompletion(+ value: unknown,+ serialized = false,+): ScheduledMCPIdentity {+ try {+ return scheduledMCPIdentitySchema.parse(+ serialized && typeof value === 'string' ? JSON.parse(value) : value,+ );+ } catch {+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ }+}++/** Complete the epoch-fenced write before tools or a checkpoint can execute. */+export async function retainScheduleMCPCompletion(+ identity: ScheduledMCPIdentity,+ scope: { streamId?: string; createdAt?: number },+ store: Pick<IJobStore, 'getJob' | 'updateJob'>,+): Promise<void> {+ if (!scope.streamId || scope.createdAt == null)+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ const lineage = parseScheduleMCPCompletion(identity);+ const matches = (job: Awaited<ReturnType<IJobStore['getJob']>>) =>+ job != null &&+ job.createdAt === scope.createdAt &&+ job.userId === lineage.ownerId &&+ (job.tenantId ?? null) === lineage.tenantId;+ const job = await store.getJob(scope.streamId);+ if (!matches(job)) throw new ScheduledMCPPolicyError('binding_mismatch', '');+ await store.updateJob(scope.streamId, { scheduleMCPCompletion: lineage }, scope.createdAt);+ const retained = await store.getJob(scope.streamId);+ if (+ !matches(retained) ||+ JSON.stringify(retained?.scheduleMCPCompletion) !== JSON.stringify(lineage)+ )+ throw new ScheduledMCPPolicyError('dependency_unavailable', '');+}diff --git a/packages/api/src/schedules/authorization/contract.ts b/packages/api/src/schedules/authorization/contract.tsindex c90b16869e..bc881703ba 100644--- a/packages/api/src/schedules/authorization/contract.ts+++ b/packages/api/src/schedules/authorization/contract.ts@@ -1,5 +1,6 @@import type {ScheduleMCPOutcome,+ ScheduledMCPFailureReason,ScheduledMCPIdentity,ScheduledMCPResource,ScheduledMCPConsent,@@ -13,21 +14,7 @@ export type {ScheduledMCPToolSelection,} from 'librechat-data-provider';-export type ScheduledMCPFailureReason =- | 'consent_missing'- | 'consent_expired'- | 'consent_revoked'- | 'binding_mismatch'- | 'rbac_denied'- | 'tool_policy_denied'- | 'approval_required'- | 'credential_missing'- | 'credential_rejected'- | 'resource_permission_denied'- | 'provider_missing'- | 'resource_unverified'- | 'unsupported_mode'- | 'dependency_unavailable';+export type { ScheduledMCPFailureReason } from 'librechat-data-provider';/** Safe diagnosis projected onto existing schedule statuses. */export interface ScheduledMCPFailure {@@ -46,6 +33,8 @@ export interface ScheduledMCPAuthorizationRequest {readonly identity: ScheduledMCPIdentity;readonly resource: ScheduledMCPResource;readonly stage: 'activation' | 'mint' | 'invoke' | 'resume';+ /** Set only by the owner-authorized manual trigger or its verified resume metadata. */+ readonly manual?: boolean;readonly selection: ScheduledMCPToolSelection;}diff --git a/packages/api/src/schedules/authorization/enrollment.spec.ts b/packages/api/src/schedules/authorization/enrollment.spec.tsindex 8513efe12a..fdfa475fbe 100644--- a/packages/api/src/schedules/authorization/enrollment.spec.ts+++ b/packages/api/src/schedules/authorization/enrollment.spec.ts@@ -27,6 +27,11 @@ function setup() {schedules: {mcpConsent: {enabled: true,+ readOnlyPolicy: {+ warehouse: {+ tools: { query: { effect: 'read_only', definitionSha256: 'a'.repeat(64) } },+ },+ },resources: {warehouse: {url: 'https://warehouse.example/mcp',@@ -354,3 +359,57 @@ it('does not offer owner consent for recipient-defining custom user variables',).rejects.toMatchObject({ code: 'consent_unavailable' });expect(confirm).not.toHaveBeenCalled();});++it.each([+ undefined,+ {},+ { tools: {} },+ { tools: { query: { effect: 'write', definitionSha256: 'a'.repeat(64) } } },+ { tools: { other: { effect: 'read_only', definitionSha256: 'a'.repeat(64) } } },+])('does not offer or confirm unusable read-only consent for policy %s', async (policy) => {+ const f = setup();+ const config = (await f.deps.getAppConfig({}))!;+ if (typeof config.interfaceConfig?.schedules !== 'object')+ throw new Error('Expected schedule config');+ config.interfaceConfig.schedules.mcpConsent!.readOnlyPolicy = { warehouse: policy } as never;+ jest.mocked(f.deps.getAppConfig).mockResolvedValue(config);+ const storage: ScheduleMCPConsentStorage = {+ readScheduleMCPConsent: jest.fn(async () => ({+ agentId: 'root',+ enabled: true,+ configRevision: 0,+ enrollment: null,+ })),+ confirmScheduleMCPConsent: jest.fn(async () => true),+ revokeScheduleMCPConsent: jest.fn(async () => true),+ admitScheduleMCPConsent: jest.fn(async () => true),+ };+ const service = createScheduleMCPConsentService({+ storage,+ resolveEnrollment: f.resolve,+ getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),+ canUse: async () => true,+ });+ await expect(service.view(identity)).rejects.toMatchObject({ code: 'consent_unavailable' });+ await expect(+ service.confirm(identity, {+ expectedRevision: null,+ offerDigest: 'outdated',+ lifetimeHours: 1,+ }),+ ).rejects.toMatchObject({ code: 'consent_unavailable' });+ expect(storage.confirmScheduleMCPConsent).not.toHaveBeenCalled();+});++it('cannot offer read-only authority supplied only by a principal-specific configuration override', async () => {+ const f = setup();+ const effective = (await f.deps.getAppConfig({}))!;+ const base = structuredClone(effective);+ if (typeof base.interfaceConfig?.schedules !== 'object')+ throw new Error('Expected schedule config');+ delete base.interfaceConfig.schedules.mcpConsent!.readOnlyPolicy;+ jest+ .mocked(f.deps.getAppConfig)+ .mockImplementation(async (options) => (options.baseOnly ? base : effective));+ await expect(f.resolve(identity, {})).rejects.toMatchObject({ code: 'consent_unavailable' });+});diff --git a/packages/api/src/schedules/authorization/enrollment.ts b/packages/api/src/schedules/authorization/enrollment.tsindex 182876b53e..9fd73e7a15 100644--- a/packages/api/src/schedules/authorization/enrollment.ts+++ b/packages/api/src/schedules/authorization/enrollment.ts@@ -1,9 +1,11 @@-import { createHash } from 'node:crypto';import {Constants,buildServerNameAliases,splitMCPToolKey,+ normalizeServerName,+ stripServerNamePrefix,scheduledMCPResourceBindingSchema,+ scheduledMCPReadOnlyPolicySchema,} from 'librechat-data-provider';import type {AgentGraphAccessContext,@@ -15,6 +17,7 @@ import type { ScheduledMCPTarget, TModelsConfig } from 'librechat-data-provider'import type { ScheduleMCPEnrollmentResolver } from './service';import type { GetAppConfigOptions } from '~/app/service';import type { ParsedServerConfig } from '~/mcp/types';+import { getScheduledMCPPolicyRevision, isScheduledMCPCandidate } from './policy';import { getScheduledMCPConfigurationRevision } from './configuration';import { resolveScheduledMCPRequirements } from '../requirements';import { getAppConfigOptionsFromUser } from '~/app/service';@@ -45,10 +48,10 @@ export function createScheduleMCPEnrollmentResolver(user.id = identity.ownerId;if (!(await deps.canUseRoot(identity.agentId, user)))throw new ScheduleMCPConsentError('consent_forbidden');- const appConfig = await deps.getAppConfig({- ...getAppConfigOptionsFromUser(user),- failClosed: true,- });+ const [appConfig, baseConfig] = await Promise.all([+ deps.getAppConfig({ ...getAppConfigOptionsFromUser(user), failClosed: true }),+ deps.getAppConfig({ baseOnly: true, failClosed: true }),+ ]);const schedules = appConfig?.interfaceConfig?.schedules;const bindings = typeof schedules === 'object' ? schedules?.mcpConsent?.resources : undefined;if (!bindings || !Object.keys(bindings).length) return [];@@ -59,7 +62,7 @@ export function createScheduleMCPEnrollmentResolver(const names = Object.keys(servers);const aliases = buildServerNameAliases(names);const candidates = [...names, ...aliases.keys()];- const { tools } = await resolveScheduledMCPRequirements(+ const { tools, candidates: candidateTools } = await resolveScheduledMCPRequirements(identity.agentId,user,{@@ -70,6 +73,8 @@ export function createScheduleMCPEnrollmentResolver(async () => appConfig,signal,);+ if (candidateTools.some(({ name }) => !isScheduledMCPCandidate(name)))+ throw new ScheduleMCPConsentError('consent_unavailable');const selected = new Map<string, Map<string, Set<string>>>();for (const { name: key, agentId } of tools) {if (@@ -120,10 +125,34 @@ export function createScheduleMCPEnrollmentResolver(signal?.throwIfAborted();for (const target of targets.values()) {target.permittedTools.sort((a, b) => a.agentId.localeCompare(b.agentId));- // Selection revision is not read-only certification; invocation still requires trusted policy.- target.policyRevision = createHash('sha256')- .update(JSON.stringify(target.permittedTools))- .digest('hex');+ const baseSchedules = baseConfig?.interfaceConfig?.schedules;+ const declaration =+ typeof baseSchedules === 'object'+ ? baseSchedules.mcpConsent?.readOnlyPolicy?.[target.resource.serverName]+ : undefined;+ const effective =+ typeof schedules === 'object'+ ? schedules.mcpConsent?.readOnlyPolicy?.[target.resource.serverName]+ : undefined;+ if (effective != null && JSON.stringify(effective) !== JSON.stringify(declaration))+ throw new ScheduleMCPConsentError('consent_unavailable');+ const policy = scheduledMCPReadOnlyPolicySchema.safeParse(declaration);+ if (+ !policy.success ||+ target.permittedTools.some(({ tools }) =>+ tools.some(+ (selection) =>+ Object.keys(policy.data.tools).filter(+ (name) =>+ name === selection ||+ stripServerNamePrefix(name, normalizeServerName(target.resource.serverName)) ===+ selection,+ ).length !== 1,+ ),+ )+ )+ throw new ScheduleMCPConsentError('consent_unavailable');+ target.policyRevision = getScheduledMCPPolicyRevision(target.permittedTools, policy.data);}return [...targets.values()];};diff --git a/packages/api/src/schedules/authorization/execution.helper.ts b/packages/api/src/schedules/authorization/execution.helper.tsnew file mode 100644index 0000000000..2dc376cd24--- /dev/null+++ b/packages/api/src/schedules/authorization/execution.helper.ts@@ -0,0 +1,144 @@+import type {+ ScheduledMCPIdentity,+ ScheduledMCPTarget,+ ScheduledMCPReadOnlyPolicy,+} from 'librechat-data-provider';+import type {+ ScheduleMCPConsentStorage,+ ScheduleConsentSnapshot,+ IUser,+} from '@librechat/data-schemas';+import type { Tool } from '@modelcontextprotocol/sdk/types.js';+import type { ParsedServerConfig } from '~/mcp/types';+import { getScheduledMCPToolDefinitionDigest, getScheduledMCPPolicyRevision } from './policy';+import { getScheduledMCPConfigurationRevision } from './configuration';+import { createScheduleMCPConsentService } from './service';+import { createScheduleMCPExecution } from './execution';++export const readTool: Tool = {+ name: 'query',+ description: 'Read a fixed resource',+ inputSchema: { type: 'object', properties: {} },+};++export async function executionFixture(+ stage: 'activation' | 'invoke' | 'resume' = 'invoke',+ tool: Tool = readTool,+ url = 'https://resource.example/mcp',+) {+ let time = 1000;+ let allowed = true;+ const identity: ScheduledMCPIdentity = {+ scheduleId: 'schedule',+ ownerId: 'owner',+ tenantId: 'tenant',+ agentId: 'root',+ invocationMode: 'delegated',+ };+ const config: ParsedServerConfig = {+ type: 'streamable-http',+ url,+ };+ const user = { id: 'owner', tenantId: 'tenant', role: 'USER' } as IUser;+ let policy: Record<string, ScheduledMCPReadOnlyPolicy> = {+ warehouse: {+ tools: {+ [tool.name]: {+ effect: 'read_only',+ definitionSha256: getScheduledMCPToolDefinitionDigest(tool),+ },+ },+ },+ };+ const target: ScheduledMCPTarget = {+ resource: {+ serverName: 'warehouse',+ url: config.url,+ credentialMode: 'anonymous',+ issuer: null,+ audience: null,+ scopes: [],+ configurationRevision: '',+ },+ permittedTools: [+ { agentId: 'root', tools: [tool.name] },+ { agentId: 'child', tools: [tool.name] },+ ],+ policyRevision: '',+ };+ target.resource.configurationRevision = getScheduledMCPConfigurationRevision(+ config,+ target.resource,+ );+ const resolveEnrollment = async () => {+ target.policyRevision = getScheduledMCPPolicyRevision(target.permittedTools, policy.warehouse);+ return structuredClone([target]);+ };+ const snapshot: ScheduleConsentSnapshot = {+ enabled: true,+ agentId: 'root',+ configRevision: 0,+ enrollment: null,+ };+ const storage: ScheduleMCPConsentStorage = {+ readScheduleMCPConsent: jest.fn(async () => structuredClone(snapshot)),+ confirmScheduleMCPConsent: jest.fn(async ({ enrollment }) => {+ snapshot.enrollment = structuredClone(enrollment);+ return true;+ }),+ revokeScheduleMCPConsent: jest.fn(async () => {+ for (const consent of snapshot.enrollment?.consents ?? []) consent.revokedAtMs = time;+ return true;+ }),+ admitScheduleMCPConsent: jest.fn(+ async (input) =>+ (input.requireEnabled === false || snapshot.enabled) &&+ snapshot.configRevision === input.expectedConfigRevision &&+ snapshot.enrollment?.revision === input.revision &&+ snapshot.enrollment.consents.every(+ (c) => c.revokedAtMs == null && c.absoluteExpiresAtMs > time,+ ),+ ),+ };+ const service = createScheduleMCPConsentService({+ storage,+ resolveEnrollment,+ getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),+ canUse: async () => allowed,+ checkToolPolicy: async () => Object.keys(policy.warehouse?.tools ?? {}).length > 0,+ now: () => time,+ });+ const offer = await service.view(identity);+ await service.confirm(identity, {+ offerDigest: offer.offer!.digest,+ expectedRevision: null,+ lifetimeHours: 1,+ });+ const loadAuthorization = jest.fn(async () => ({ authority: service.authority, policy }));+ const factory = createScheduleMCPExecution({ storage, loadAuthorization });+ const execution = (await factory.resolve(identity, stage))!;+ return {+ identity,+ config,+ user,+ target,+ snapshot,+ storage,+ service,+ execution,+ factory,+ loadAuthorization,+ policy,+ revoke: () => service.revoke(identity, snapshot.enrollment!.revision),+ expire: () => {+ time = 3_601_000;+ },+ deny: () => {+ allowed = false;+ },+ removePolicy: () => {+ policy = {};+ },+ invocation: (agentId = 'root', selection = tool.name) => execution.bind(agentId, selection),+ };+}diff --git a/packages/api/src/schedules/authorization/execution.spec.ts b/packages/api/src/schedules/authorization/execution.spec.tsnew file mode 100644index 0000000000..008f5bda49--- /dev/null+++ b/packages/api/src/schedules/authorization/execution.spec.ts@@ -0,0 +1,413 @@+import { Constants } from '@librechat/agents';+import type { Tool } from '@modelcontextprotocol/sdk/types.js';+import { getScheduledMCPToolDefinitionDigest, isScheduledMCPToolReadOnly } from './policy';+import { executionFixture, readTool } from './execution.helper';+import { bindScheduledMCPInvocation } from './execution';+import { createMCPRequestContext } from '~/mcp/request';+import { createScheduledMCPRunPolicy } from './run';+import { ScheduledMCPPolicyError } from './policy';++const catalog = (tools: Tool[] = [readTool]) => ({ tools, complete: true });++it('requires a trusted exact-definition declaration, ignoring misleading names and annotations', () => {+ const mutating: Tool = {+ name: 'get_read_only_data',+ inputSchema: { type: 'object' },+ annotations: { readOnlyHint: true, destructiveHint: false },+ };+ expect(isScheduledMCPToolReadOnly(mutating)).toBe(false);+ expect(+ isScheduledMCPToolReadOnly(mutating, {+ tools: {+ query: {+ effect: 'read_only',+ definitionSha256: getScheduledMCPToolDefinitionDigest(readTool),+ },+ },+ }),+ ).toBe(false);+ expect(+ isScheduledMCPToolReadOnly(readTool, {+ tools: {+ query: {+ effect: 'read_only',+ definitionSha256: getScheduledMCPToolDefinitionDigest(readTool),+ },+ },+ }),+ ).toBe(true);+});++it('canonicalizes object key order without dropping policy-relevant definition fields', () => {+ const left: Tool = {+ name: 'read',+ inputSchema: { type: 'object', properties: { x: { type: 'string', maxLength: 8 } } },+ };+ const right: Tool = {+ inputSchema: { properties: { x: { maxLength: 8, type: 'string' } }, type: 'object' },+ name: 'read',+ };+ expect(getScheduledMCPToolDefinitionDigest(left)).toBe(+ getScheduledMCPToolDefinitionDigest(right),+ );+ expect(+ getScheduledMCPToolDefinitionDigest({ ...right, outputSchema: { type: 'object' } }),+ ).not.toBe(getScheduledMCPToolDefinitionDigest(left));+});++it.each(['root', 'child'])(+ 'checks the actual %s operation through the real consent service',+ async (agentId) => {+ const fixture = await executionFixture();+ await fixture.invocation(agentId).authorize({+ user: fixture.user,+ serverName: 'warehouse',+ serverConfig: fixture.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ });+ expect(fixture.storage.admitScheduleMCPConsent).toHaveBeenCalledWith(+ expect.objectContaining({ identity: fixture.identity, requireEnabled: true }),+ );+ },+);++it.each([+ [+ 'revocation',+ 'consent_revoked',+ (f: Awaited<ReturnType<typeof executionFixture>>) => f.revoke(),+ ],+ ['expiry', 'consent_expired', (f: Awaited<ReturnType<typeof executionFixture>>) => f.expire()],+ ['RBAC', 'rbac_denied', (f: Awaited<ReturnType<typeof executionFixture>>) => f.deny()],+ [+ 'root change',+ 'binding_mismatch',+ (f: Awaited<ReturnType<typeof executionFixture>>) => {+ f.snapshot.agentId = 'other';+ },+ ],+ [+ 'schedule change',+ 'binding_mismatch',+ (f: Awaited<ReturnType<typeof executionFixture>>) => {+ f.snapshot.configRevision++;+ },+ ],+ [+ 'selected tool change',+ 'binding_mismatch',+ (f: Awaited<ReturnType<typeof executionFixture>>) => {+ f.target.permittedTools[0].tools.push('write');+ },+ ],+ [+ 'policy removal',+ 'tool_policy_denied',+ (f: Awaited<ReturnType<typeof executionFixture>>) => f.removePolicy(),+ ],+] as const)('rechecks %s after admission on approval resume', async (_name, reason, change) => {+ const f = await executionFixture('resume');+ await change(f);+ await expect(+ f.invocation().authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ }),+ ).rejects.toMatchObject({ failure: { reason, automaticReplay: false } });+});++it('refuses a changed catalog, an incomplete snapshot, and ambiguous duplicate definitions', async () => {+ const f = await executionFixture();+ for (const snapshot of [+ catalog([+ {+ ...readTool,+ inputSchema: { type: 'object', properties: { mutation: { type: 'boolean' } } },+ },+ ]),+ { ...catalog(), complete: false },+ catalog([readTool, readTool]),+ ]) {+ await expect(+ f.invocation().authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => snapshot,+ }),+ ).rejects.toMatchObject({ failure: { reason: 'tool_policy_denied' } });+ }+ expect(f.storage.admitScheduleMCPConsent).not.toHaveBeenCalled();+});++it('refuses a cross-tenant caller, unselected child, and changed transport binding', async () => {+ const f = await executionFixture();+ const input = {+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ };+ const invocation = f.invocation();+ await expect(+ invocation.authorize({+ ...input,+ user: Object.assign(structuredClone(f.user), { tenantId: 'other' }),+ }),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ await expect(f.invocation('stranger').authorize(input)).rejects.toMatchObject({+ failure: { reason: 'tool_policy_denied' },+ });+ await expect(+ f.invocation().authorize({+ ...input,+ serverConfig: { type: 'streamable-http', url: 'https://other.example/mcp' },+ }),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+});++it('fences revocation and expiry that land during catalog loading', async () => {+ for (const mutation of ['revoke', 'expire'] as const) {+ const f = await executionFixture();+ await expect(+ f.invocation().authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => {+ await f[mutation]();+ return catalog();+ },+ }),+ ).rejects.toMatchObject({+ failure: { reason: mutation === 'revoke' ? 'consent_revoked' : 'consent_expired' },+ });+ }+});++it('keeps a captured guard after enrollment disappears and never falls back to legacy', async () => {+ const f = await executionFixture();+ const context = createMCPRequestContext();+ await f.factory.attach(context, f.identity, 'invoke');+ const bound = bindScheduledMCPInvocation(context, 'root', 'query')!;+ f.snapshot.enrollment = null;+ await expect(+ bound.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ }),+ ).rejects.toMatchObject({ failure: { reason: 'consent_missing' } });+ expect(bindScheduledMCPInvocation(createMCPRequestContext(), 'root', 'query')).toBeUndefined();+});++it('retains legacy schedules with no enrollment but never grandfathers revoked enrollment', async () => {+ const f = await executionFixture();+ await f.revoke();+ expect(await f.factory.resolve(f.identity, 'invoke')).toBeDefined();+ f.snapshot.enrollment = null;+ expect(await f.factory.resolve(f.identity, 'invoke')).toMatchObject({ enrolled: false });+});++it('admits disabled consent only for activation, not invocation', async () => {+ const f = await executionFixture('activation');+ f.snapshot.enabled = false;+ const input = {+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ };+ await expect(f.invocation().authorize(input)).resolves.toBeUndefined();+ const invoke = (await f.factory.resolve(f.identity, 'invoke'))!;+ await expect(invoke.bind('root', 'query').authorize(input)).rejects.toMatchObject({+ failure: { reason: 'binding_mismatch' },+ });+});++it('installs an independent ceiling for root, child, handoff, and lazy tools without loosening approval', async () => {+ const f = await executionFixture();+ const policy = createScheduledMCPRunPolicy(f.execution, [+ {+ id: 'root',+ toolDefinitions: [{ name: 'query_mcp_warehouse', serverName: 'warehouse', toolType: 'mcp' }],+ subagentAgentConfigs: [+ {+ id: 'child',+ toolRegistry: new Map([+ [+ 'query_mcp_warehouse',+ { name: 'query_mcp_warehouse', serverName: 'warehouse', toolType: 'mcp' },+ ],+ ]),+ },+ ],+ },+ ]);+ const call = async (toolName: string, executingAgentId = 'root') =>+ policy.hook(+ {+ hook_event_name: 'PreToolUse',+ runId: 'run',+ toolName,+ executingAgentId,+ toolInput: {},+ toolUseId: 'tool',+ },+ new AbortController().signal,+ );+ expect(await call('query_mcp_warehouse')).toEqual({});+ expect(await call('query_mcp_warehouse', 'child')).toEqual({});+ expect(await call(Constants.SUBAGENT)).toEqual({});+ for (const name of [+ 'action_write',+ Constants.BASH_TOOL,+ Constants.EXECUTE_CODE,+ 'forged_mcp_warehouse',+ ])+ expect(await call(name)).toMatchObject({ decision: 'deny' });+ expect(await call('query_mcp_warehouse', 'unknown')).toMatchObject({ decision: 'deny' });+ policy.registerAgent({+ id: 'handoff',+ toolRegistry: new Map([+ [+ 'query_mcp_warehouse',+ { name: 'query_mcp_warehouse', serverName: 'warehouse', toolType: 'mcp' },+ ],+ ]),+ });+ expect(await call('query_mcp_warehouse', 'handoff')).toEqual({});+});++it('refuses a consent deadline crossed while the final database admission is in flight', async () => {+ const f = await executionFixture();+ jest.mocked(f.storage.admitScheduleMCPConsent).mockImplementationOnce(async () => {+ f.expire();+ return true;+ });+ const call = f.invocation().authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ });+ await expect(call).rejects.toMatchObject({+ failure: { reason: 'consent_expired', automaticReplay: false },+ });+});++it.each(['snapshot', 'consent', 'admission', 'catalog'] as const)(+ 'projects %s dependency failures into a safe denial for root and resumed child calls',+ async (phase) => {+ for (const stage of ['invoke', 'resume'] as const) {+ const f = await executionFixture(stage);+ const internal = new Error('PRIVATE authorization storage query with credentials');+ if (phase === 'snapshot') f.loadAuthorization.mockRejectedValue(internal);+ if (phase === 'consent')+ jest.mocked(f.storage.readScheduleMCPConsent).mockRejectedValue(internal);+ if (phase === 'admission')+ jest.mocked(f.storage.admitScheduleMCPConsent).mockRejectedValue(internal);+ const provider = jest.fn();+ for (const agentId of ['root', 'child']) {+ const call = async () => {+ await f.invocation(agentId).authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => {+ if (phase === 'catalog') throw internal;+ return catalog();+ },+ });+ return provider();+ };+ let failure: unknown;+ try {+ await call();+ } catch (error) {+ failure = error;+ }+ expect(failure).toBeInstanceOf(ScheduledMCPPolicyError);+ expect(failure).toMatchObject({+ failure: {+ reason: 'dependency_unavailable',+ recovery: 'retry_later',+ automaticReplay: false,+ },+ outcomes: [{ server: 'warehouse', agentId, reason: 'dependency_unavailable' }],+ });+ expect(String(failure)).not.toContain('PRIVATE');+ expect(failure).not.toHaveProperty('cause');+ }+ expect(provider).not.toHaveBeenCalled();+ }+ },+);++it.each(['snapshot', 'authorize'] as const)(+ 'preserves typed denials and owned cancellation from %s',+ async (phase) => {+ const f = await executionFixture();+ const controller = new AbortController();+ const typed = new ScheduledMCPPolicyError('rbac_denied', 'warehouse', 'child');+ const authorize = jest.spyOn(f.service.authority, 'authorize');+ const fail = (error: Error, cancel = false) => {+ const reject = async () => {+ if (cancel) controller.abort(error);+ throw error;+ };+ if (phase === 'snapshot') f.loadAuthorization.mockImplementation(reject);+ else authorize.mockImplementation(reject);+ };+ const invocation = f.invocation('child');+ const call = () =>+ invocation.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ signal: controller.signal,+ });+ fail(typed);+ await expect(call()).rejects.toBe(typed);+ const unowned = Object.assign(new Error('PRIVATE unrelated abort'), { name: 'AbortError' });+ fail(unowned);+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+ const stop = new Error('Owner stopped');+ fail(stop, true);+ await expect(call()).rejects.toBe(stop);+ },+);++it('does not hide a non-abort authorization failure when Stop races its rejection', async () => {+ const f = await executionFixture();+ const controller = new AbortController();+ f.loadAuthorization.mockImplementation(async () => {+ controller.abort(new Error('Stop'));+ throw new Error('PRIVATE database failure');+ });+ const invocation = f.invocation();+ await expect(+ invocation.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => catalog(),+ signal: controller.signal,+ }),+ ).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+});diff --git a/packages/api/src/schedules/authorization/execution.ts b/packages/api/src/schedules/authorization/execution.tsnew file mode 100644index 0000000000..8565895ad0--- /dev/null+++ b/packages/api/src/schedules/authorization/execution.ts@@ -0,0 +1,241 @@+import { DEFAULT_HOOK_TIMEOUT_MS } from '@librechat/agents';+import { normalizeServerName, stripServerNamePrefix } from 'librechat-data-provider';+import type { ScheduledMCPIdentity, ScheduledMCPReadOnlyPolicy } from 'librechat-data-provider';+import type { ScheduleMCPConsentStorage } from '@librechat/data-schemas';+import type { Tool } from '@modelcontextprotocol/sdk/types.js';+import type { ParsedServerConfig, RequestScopedMCPConnectionStore } from '~/mcp/types';+import type { MCPToolsSnapshot } from '~/mcp/connection';+import type { ScheduledMCPAuthority } from './contract';+import type { ScheduledTokenContext } from '../context';+import { isScheduledMCPToolReadOnly, ScheduledMCPPolicyError } from './policy';+import { getScheduledMCPConfigurationRevision } from './configuration';+import { ScheduleMCPConsentError } from './service';+import { isOwnedAbortError } from '~/utils/errors';+import { waitUntilDeadline } from '~/mcp/utils';++export interface ScheduledMCPInvocation {+ readonly identity: ScheduledMCPIdentity;+ /** False only for a monitored legacy occurrence. */+ readonly enrolled?: boolean;+ readonly agentId?: string;+ readonly authorize: (input: {+ user?: { id: string; tenantId?: string };+ serverName: string;+ serverConfig: ParsedServerConfig;+ toolName: string;+ loadTools: () => Promise<MCPToolsSnapshot>;+ signal?: AbortSignal;+ }) => Promise<void>;+}++export interface ScheduleMCPExecution {+ readonly identity: ScheduledMCPIdentity;+ readonly stage: 'activation' | 'invoke' | 'resume';+ readonly enrolled: boolean;+ /** Legacy admits only while enrollment is still absent; it never acquires a later grant. */+ readonly checkEnrollment: () => Promise<void>;+ readonly bind: (agentId: string | undefined, selectionName: string) => ScheduledMCPInvocation;+}++const executions = new WeakMap<RequestScopedMCPConnectionStore, ScheduleMCPExecution>();++/** Captured at tool construction. Runnable config cannot remove or replace this guard. */+export function bindScheduledMCPInvocation(+ context: RequestScopedMCPConnectionStore | undefined,+ agentId: string | undefined,+ selectionName: string,+): ScheduledMCPInvocation | undefined {+ return context && executions.get(context)?.bind(agentId, selectionName);+}++export function getScheduleMCPExecution(+ context?: RequestScopedMCPConnectionStore,+): ScheduleMCPExecution | undefined {+ return context && executions.get(context);+}++export interface ScheduleMCPExecutionDeps {+ storage: ScheduleMCPConsentStorage;+ /** Fresh for each call; only this attempt may reuse its principal/configuration. */+ loadAuthorization: (identity: ScheduledMCPIdentity) => Promise<{+ authority: ScheduledMCPAuthority;+ policy?: Record<string, ScheduledMCPReadOnlyPolicy>;+ }>;+}++export function createScheduleMCPExecution(deps: ScheduleMCPExecutionDeps): {+ resolve: (+ identity: ScheduledMCPIdentity,+ stage: ScheduleMCPExecution['stage'],+ options?: { manual?: boolean; legacy?: boolean },+ ) => Promise<ScheduleMCPExecution | undefined>;+ attach: (+ context: RequestScopedMCPConnectionStore,+ identity: ScheduledMCPIdentity,+ stage: ScheduleMCPExecution['stage'],+ requireEnrollment?: boolean,+ options?: { manual?: boolean; legacy?: boolean },+ ) => Promise<void>;+} {+ async function resolve(+ identity: ScheduledMCPIdentity,+ stage: ScheduleMCPExecution['stage'],+ options: { manual?: boolean; legacy?: boolean } = {},+ ): Promise<ScheduleMCPExecution | undefined> {+ const snapshot = await deps.storage.readScheduleMCPConsent(identity);+ if (snapshot?.compatible === false) throw new ScheduledMCPPolicyError('binding_mismatch', '');+ if (!snapshot) return;+ const enrolled = snapshot.enrollment != null;+ if (enrolled && options.legacy === true)+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ const capturedIdentity = Object.freeze({ ...identity });+ const manual = options.manual === true;+ const resources = new Map(+ (snapshot.enrollment?.consents ?? []).map(({ resource }) => [+ resource.serverName,+ structuredClone(resource),+ ]),+ );+ let fenced = false;+ const checkEnrollment = async (): Promise<void> => {+ if (enrolled) return;+ if (fenced) throw new ScheduledMCPPolicyError('binding_mismatch', '');+ // Finish before the SDK discards a timed-out hook's contribution. No allow decision cached.+ const observed = await waitUntilDeadline(+ deps.storage.readScheduleMCPConsent(capturedIdentity),+ Date.now() + DEFAULT_HOOK_TIMEOUT_MS / 2,+ );+ if (!observed.settled) throw new ScheduledMCPPolicyError('dependency_unavailable', '');+ if (+ !observed.value ||+ observed.value.compatible === false ||+ observed.value.enrollment != null+ ) {+ fenced = true;+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ }+ };+ return Object.freeze({+ identity: capturedIdentity,+ stage,+ enrolled,+ checkEnrollment,+ bind(agentId: string | undefined, selectionName: string): ScheduledMCPInvocation {+ return Object.freeze({+ identity: capturedIdentity,+ agentId,+ enrolled,+ async authorize({+ user,+ serverName,+ serverConfig,+ toolName,+ loadTools,+ signal,+ }: Parameters<ScheduledMCPInvocation['authorize']>[0]): Promise<void> {+ signal?.throwIfAborted();+ const deny = (+ reason: ConstructorParameters<typeof ScheduledMCPPolicyError>[0],+ ): never => {+ throw new ScheduledMCPPolicyError(reason, serverName, agentId);+ };+ if (+ !agentId ||+ user?.id !== capturedIdentity.ownerId ||+ (user.tenantId ?? null) !== capturedIdentity.tenantId+ )+ deny('binding_mismatch');+ if (!enrolled) {+ try {+ await checkEnrollment();+ } catch (error) {+ signal?.throwIfAborted();+ deny(+ error instanceof ScheduledMCPPolicyError+ ? error.failure.reason+ : 'dependency_unavailable',+ );+ }+ signal?.throwIfAborted();+ return;+ }+ // Only the recipient is captured. Authority re-resolves live graph/policy below.+ const resource = resources.get(serverName);+ if (!resource) deny('tool_policy_denied');+ try {+ if (+ getScheduledMCPConfigurationRevision(serverConfig, resource!) !==+ resource!.configurationRevision+ )+ deny('binding_mismatch');+ } catch (error) {+ if (error instanceof ScheduleMCPConsentError) deny('binding_mismatch');+ throw error;+ }+ // Resolve the actual upstream operation, including legacy and prefix-stripped keys.+ if (+ selectionName !== toolName &&+ selectionName !== stripServerNamePrefix(toolName, normalizeServerName(serverName))+ )+ deny('tool_policy_denied');+ try {+ const [evaluation, catalog] = await Promise.all([+ deps.loadAuthorization(capturedIdentity),+ loadTools(),+ ]);+ signal?.throwIfAborted();+ if (catalog.authenticationError != null) deny('credential_rejected');+ const definitions = catalog.tools.filter((tool: Tool) => tool.name === toolName);+ if (+ !catalog.complete ||+ definitions.length !== 1 ||+ !isScheduledMCPToolReadOnly(definitions[0], evaluation.policy?.[serverName])+ )+ deny('tool_policy_denied');+ const authorization = await evaluation.authority.authorize(+ {+ identity: capturedIdentity,+ resource: resource!,+ stage,+ ...(manual && { manual: true }),+ selection: { agentId: agentId!, tools: [selectionName] },+ },+ { signal },+ );+ if (authorization.state === 'denied') deny(authorization.failure.reason);+ if (authorization.state === 'cancelled') {+ signal?.throwIfAborted();+ deny('dependency_unavailable');+ }+ signal?.throwIfAborted();+ } catch (error) {+ if (error instanceof ScheduledMCPPolicyError || isOwnedAbortError(error, signal))+ throw error;+ deny('dependency_unavailable');+ }+ },+ });+ },+ });+ }+ return {+ resolve,+ async attach(context, identity, stage, requireEnrollment = false, options) {+ const execution = await resolve(identity, stage, options);+ if ((!execution || !execution.enrolled) && requireEnrollment)+ throw new ScheduledMCPPolicyError('consent_missing', '');+ if (execution) executions.set(context, execution);+ },+ };+}++/** The trusted trigger/resume host owns the context. No body-provided schedule opt-in. */+export function scheduledMCPIdentity(context: ScheduledTokenContext): ScheduledMCPIdentity {+ return {+ scheduleId: context.scheduleId,+ ownerId: context.ownerId,+ tenantId: context.tenantId ?? null,+ agentId: context.agentId,+ invocationMode: 'delegated',+ };+}diff --git a/packages/api/src/schedules/authorization/policy.ts b/packages/api/src/schedules/authorization/policy.tsnew file mode 100644index 0000000000..28cef39101--- /dev/null+++ b/packages/api/src/schedules/authorization/policy.ts@@ -0,0 +1,86 @@+import { createHash } from 'node:crypto';+import { Constants as AgentConstants } from '@librechat/agents';+import { Constants, isActionTool } from 'librechat-data-provider';+import type {+ ScheduledMCPReadOnlyPolicy,+ ScheduledMCPToolSelection,+ ScheduledMCPFailureReason,+ ScheduleMCPOutcome,+} from 'librechat-data-provider';+import type { Tool } from '@modelcontextprotocol/sdk/types.js';+import type { ScheduledMCPFailure } from './contract';+import { failureFixtures } from './failures';++/** Only MCP selections and side-effect-free SDK controls belong to this consent phase. */+export function isScheduledMCPCandidate(name: string): boolean {+ if (isActionTool(name)) return false;+ return (+ (name.includes(Constants.mcp_delimiter) &&+ !name.startsWith(`${Constants.mcp_server}${Constants.mcp_delimiter}`) &&+ !name.startsWith(`${Constants.mcp_all}${Constants.mcp_delimiter}`)) ||+ name === AgentConstants.SUBAGENT ||+ name === AgentConstants.TOOL_SEARCH ||+ name === 'ask_user_question'+ );+}++/** Stable across object insertion order. Arrays retain their semantic order. */+function canonical(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(canonical);+ if (value !== null && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value)+ .filter(([, entry]) => entry !== undefined)+ .sort(([a], [b]) => (a < b ? -1 : Number(a > b)))+ .map(([key, entry]) => [key, canonical(entry)]),+ );+ }+ return value;+}++/** A pin binds trusted service policy to the full upstream definition, not its hints. */+export function getScheduledMCPToolDefinitionDigest(tool: Tool): string {+ return createHash('sha256')+ .update(JSON.stringify(canonical(tool)))+ .digest('hex');+}++export function getScheduledMCPPolicyRevision(+ selections: readonly ScheduledMCPToolSelection[],+ policy?: ScheduledMCPReadOnlyPolicy,+): string {+ return createHash('sha256')+ .update(JSON.stringify(canonical({ selections, policy: policy ?? null })))+ .digest('hex');+}++export function isScheduledMCPToolReadOnly(+ tool: Tool,+ policy?: ScheduledMCPReadOnlyPolicy,+): boolean {+ const pin = policy?.tools[tool.name];+ return (+ pin?.effect === 'read_only' &&+ pin.definitionSha256 === getScheduledMCPToolDefinitionDigest(tool)+ );+}++/** Expected denial. Only the approved projection can reach a client or persisted run. */+export class ScheduledMCPPolicyError extends Error {+ readonly failure: ScheduledMCPFailure;+ readonly outcomes: ScheduleMCPOutcome[];+ readonly code: ScheduledMCPFailure['status'];+ readonly statusCode: number;+ readonly retryable = false;++ constructor(reason: ScheduledMCPFailureReason, server: string, agentId?: string) {+ const failure = failureFixtures[reason];+ const outcomes = [{ server, ...(agentId ? { agentId } : {}), ...failure }];+ super(`${failure.status}: ${JSON.stringify(outcomes)}`);+ this.name = 'ScheduledMCPPolicyError';+ this.failure = failure;+ this.outcomes = outcomes;+ this.code = failure.status;+ this.statusCode = failure.status === 'mcp_unavailable' ? 503 : 403;+ }+}diff --git a/packages/api/src/schedules/authorization/receipt.spec.ts b/packages/api/src/schedules/authorization/receipt.spec.tsnew file mode 100644index 0000000000..459a22d78d--- /dev/null+++ b/packages/api/src/schedules/authorization/receipt.spec.ts@@ -0,0 +1,1242 @@+import { z } from 'zod';+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { DynamicStructuredTool } from '@langchain/core/tools';+import { AIMessage } from '@librechat/agents/langchain/messages';+import { createModels, createMethods } from '@librechat/data-schemas';+import { Constants, HookRegistry, ToolNode, executeHooks } from '@librechat/agents';+import type { AppConfig, AgentGraphAccessContext } from '@librechat/data-schemas';+import type { SchedulesServiceDeps } from '../service';+import {+ createSchedulesService,+ createScheduledMCPPolicyRecorder,+ recordScheduledMCPToolAuthFailure,+} from '../service';+import { createScheduleMCPRuntimeHost, initializeWithScheduleMCPExecution } from './runtime';+import { createScheduleMCPExecution, getScheduleMCPExecution } from './execution';+import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';+import { createAgentTriggerExecutionHost } from '~/agents/triggers/host';+import { createAgentTriggerEnvelope } from '~/agents/triggers/envelope';+import { GenerationJobManager } from '~/stream/GenerationJobManager';+import { executionFixture, readTool } from './execution.helper';+import { resolveScheduleMCPCompletion } from './continuation';+import { retainScheduleMCPCompletion } from './continuation';+import { createScheduleMCPConsentService } from './service';+import { createMCPRequestContext } from '~/mcp/request';+import { createScheduledMCPRunPolicy } from './run';+import { ScheduledMCPPolicyError } from './policy';++let mongo: MongoMemoryServer;+let store: InMemoryJobStore;++beforeAll(async () => {+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await Promise.all([mongoose.models.Schedule.init(), mongoose.models.ScheduleRun.init()]);+}, 60_000);+afterAll(async () => {+ await mongoose.disconnect();+ await mongo?.stop();+}, 60_000);+beforeEach(async () => {+ await Promise.all([+ mongoose.models.Schedule.deleteMany({}),+ mongoose.models.ScheduleRun.deleteMany({}),+ ]);+ store = new InMemoryJobStore();+ // The generation store is the injected external state. SDK policy and Mongo methods stay real.+ jest.spyOn(GenerationJobManager, 'getJobStore').mockReturnValue(store);+ jest+ .spyOn(GenerationJobManager, 'updateMetadata')+ .mockImplementation((id, patch, epoch) => store.updateJob(id, patch, epoch));+});+afterEach(async () => {+ jest.restoreAllMocks();+ await store.destroy();+});++async function setup(legacy = false) {+ const methods = createMethods(mongoose);+ const owner = new mongoose.Types.ObjectId();+ const fixture = await executionFixture();+ const identity = { ...fixture.identity, ownerId: owner.toString() };+ const schedule = await methods.createSchedule({+ id: 'schedule',+ user: owner,+ tenantId: 'tenant',+ agent_id: 'root',+ name: 'Read',+ prompt: 'Read',+ enabled: true,+ timezone: 'UTC',+ cadence: { frequency: 'hourly', minute: 0, hour: 1 },+ });+ const consent = createScheduleMCPConsentService({+ storage: methods,+ resolveEnrollment: async () => [fixture.target],+ getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),+ canUse: async () => true,+ checkToolPolicy: async () => true,+ });+ const enroll = async () => {+ const offer = await consent.view(identity);+ await consent.confirm(identity, {+ offerDigest: offer.offer!.digest,+ expectedRevision: offer.revision,+ lifetimeHours: 1,+ });+ };+ if (!legacy) await enroll();+ const loadAuthorization = jest.fn(async () => ({+ authority: consent.authority,+ policy: fixture.policy,+ }));+ const factory = createScheduleMCPExecution({ storage: methods, loadAuthorization });+ const execution = (await factory.resolve(identity, 'invoke'))!;+ const scheduledFor = new Date('2026-10-02T12:00:00Z');+ await methods.insertScheduleRun({+ scheduleId: schedule.id,+ user: owner,+ tenantId: 'tenant',+ scheduledFor,+ conversationId: 'stream',+ status: 'started',+ configRevision: 0,+ });+ const job = await store.createJob('stream', owner.toString(), 'stream', 'tenant', {+ scheduleId: schedule.id,+ scheduledFor: scheduledFor.toISOString(),+ agent_id: 'root',+ });+ const config = {+ interfaceConfig: { schedules: { use: true, autoDisableAfterFailures: 99 } },+ } as AppConfig;+ const deps: SchedulesServiceDeps = {+ methods: {+ ...methods,+ getRoleByName: async () => null,+ getFiles: async () => [],+ extendFilesTTL: async () => 0,+ },+ getAppConfig: async () => config,+ findUserById: async () => ({ _id: owner, tenantId: 'tenant', role: 'USER' }),+ findBalance: async () => null,+ upsertBalance: async () => null,+ initializeNullBalance: async () => null,+ getChatProject: async () => null,+ resolveAgentFireAccess: async () => 'ok',+ isUserDeleting: async () => false,+ preflightMCP: async () => [],+ enqueueAgentTrigger: async () => undefined,+ getTriggerDelivery: async () => null,+ };+ const service = createSchedulesService(deps);+ const scope = {+ streamId: 'stream',+ jobCreatedAt: job.createdAt,+ userId: owner.toString(),+ tenantId: 'tenant',+ };+ const record = createScheduledMCPPolicyRecorder(execution, scope, (input) =>+ recordScheduledMCPToolAuthFailure(input, () => service.recordMCPToolAuthFailure),+ )!;+ return {+ methods,+ execution,+ schedule,+ scheduledFor,+ job,+ scope,+ record,+ service,+ enroll,+ deps,+ loadAuthorization,+ consent,+ fixture,+ };+}++it.each(['root', 'child'])(+ 'records a late direct-action denial from %s before handled-success settlement',+ async (agentId) => {+ const f = await setup();+ const policy = createScheduledMCPRunPolicy(+ f.execution,+ [{ id: 'root' }, { id: 'child' }],+ [],+ f.record,+ );+ const hooks = new HookRegistry();+ hooks.register('PreToolUse', { hooks: [policy.hook, policy.receipt] });+ const body = jest.fn(async () => 'write executed');+ const action = new DynamicStructuredTool({+ name: 'write_action_api',+ description: 'Late action',+ schema: z.object({ privateValue: z.string() }),+ func: body,+ });+ const node = new ToolNode({ agentId, tools: [action], hookRegistry: hooks });+ const result = await node.invoke(+ {+ messages: [+ new AIMessage({+ content: '',+ tool_calls: [{ id: 'call', name: action.name, args: { privateValue: 'PRIVATE' } }],+ }),+ ],+ },+ { configurable: { run_id: 'run', thread_id: 'thread' } },+ );+ expect(body).not.toHaveBeenCalled();+ expect(JSON.stringify(result)).toContain('Blocked:');+ const before = await f.methods.getScheduleRunAbortState(f.schedule.id, f.scheduledFor);+ expect(before?.mcp).toEqual([+ {+ server: '',+ agentId,+ reason: 'tool_policy_denied',+ status: 'mcp_permission_denied',+ recovery: 'configure',+ automaticReplay: false,+ },+ ]);+ expect(JSON.stringify(before)).not.toContain('PRIVATE');+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ const card = await f.methods.getScheduleById(f.schedule.id);+ expect(card).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_permission_denied',+ failureCount: 1,+ lastRun: { status: 'error', mcp: before?.mcp },+ });+ expect((await store.getJob('stream'))?.scheduleOutcome).toBe('error');+ },+);++it.each([+ { createdAt: -1 },+ { userId: 'other' },+ { tenantId: 'other' },+ { scheduleId: 'other' },+ { agent_id: 'other' },+])('never stamps a different persisted job identity %j', async (change) => {+ const f = await setup();+ await store.updateJob('stream', change, f.job.createdAt);+ expect(await f.record(new ScheduledMCPPolicyError('tool_policy_denied', '', 'child'))).toBe(+ false,+ );+ expect(+ (await f.methods.getScheduleRunAbortState(f.schedule.id, f.scheduledFor))?.mcp,+ ).toBeUndefined();+});++it('captures recorder scope and does not initialize it for legacy runs', async () => {+ const f = await setup();+ f.scope.streamId = 'spoofed';+ f.scope.jobCreatedAt = -1;+ expect(await f.record(new ScheduledMCPPolicyError('tool_policy_denied', '', 'child'))).toBe(true);+ expect(createScheduledMCPPolicyRecorder(undefined, f.scope, jest.fn())).toBeUndefined();+});++it.each(['throw', 'timeout'] as const)(+ 'keeps the SDK ceiling denied when receipt persistence %s fails',+ async (failure) => {+ const f = await setup();+ const record = jest.fn(async () => {+ if (failure === 'throw') throw new Error('PRIVATE database details');+ return new Promise<boolean>(() => undefined);+ });+ const policy = createScheduledMCPRunPolicy(f.execution, [{ id: 'root' }], [], record);+ const hooks = new HookRegistry();+ hooks.register('PreToolUse', { hooks: [policy.hook, policy.receipt], internal: true });+ const result = await executeHooks({+ registry: hooks,+ timeoutMs: 10,+ input: {+ hook_event_name: 'PreToolUse',+ runId: 'run',+ executingAgentId: 'root',+ toolName: 'write',+ toolInput: {},+ toolUseId: 'call',+ },+ });+ expect(result.decision).toBe('deny');+ expect(result.reason).toContain('tool_policy_denied');+ expect(result.reason).not.toContain('PRIVATE');+ },+);++it('fences a real legacy SDK action when narrowed consent is confirmed after initialization', async () => {+ const f = await setup(true);+ const policy = createScheduledMCPRunPolicy(f.execution, [{ id: 'root' }], [], f.record);+ const hooks = new HookRegistry();+ hooks.register('PreToolUse', { hooks: [policy.hook, policy.receipt] });+ const body = jest.fn(async () => 'legacy write');+ const action = new DynamicStructuredTool({+ name: 'write_action_api',+ description: 'Cached legacy action',+ schema: z.object({}),+ func: body,+ });+ const node = new ToolNode({ agentId: 'root', tools: [action], hookRegistry: hooks });+ const call = () =>+ node.invoke(+ {+ messages: [+ new AIMessage({+ content: '',+ tool_calls: [{ id: 'legacy-call', name: action.name, args: {} }],+ }),+ ],+ },+ { configurable: { run_id: 'legacy', thread_id: 'thread' } },+ );+ await call();+ expect(body).toHaveBeenCalledTimes(1);+ await f.enroll();+ const result = await call();+ expect(JSON.stringify(result)).toContain('Blocked:');+ expect(body).toHaveBeenCalledTimes(1);+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ lastRun: { status: 'error', mcp: [expect.objectContaining({ reason: 'binding_mismatch' })] },+ });+});++it('retains a failed Mongo receipt in the job store and replays it after service reconstruction', async () => {+ const f = await setup();+ jest+ .spyOn(f.service.engineDeps.methods, 'recordMCPToolAuthFailure')+ .mockRejectedValueOnce(new Error('Storage outage PRIVATE'));+ const failure = new ScheduledMCPPolicyError('tool_policy_denied', '', 'child');+ expect(await f.record(failure)).toBe(true);+ expect((await store.getJob('stream'))?.scheduleMCPFailure).toEqual(failure.outcomes[0]);+ expect(+ (await f.methods.getScheduleRunAbortState(f.schedule.id, f.scheduledFor))?.mcp,+ ).toBeUndefined();+ const recovered = createSchedulesService(f.deps);+ await recovered.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_permission_denied',+ lastRun: { status: 'error', mcp: failure.outcomes },+ });+});++it('defers success while both receipt channels are unavailable, then settles the retained denial', async () => {+ const f = await setup();+ const mongoWrite = jest+ .spyOn(f.service.engineDeps.methods, 'recordMCPToolAuthFailure')+ .mockRejectedValue(new Error('Mongo outage'));+ const jobWrite = jest.spyOn(store, 'updateJob').mockRejectedValue(new Error('Job store outage'));+ const failure = new ScheduledMCPPolicyError('tool_policy_denied', '', 'root');+ expect(await f.record(failure)).toBe(false);+ const settle = () =>+ f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ expect(await settle()).toBe(false);+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: true,+ failureCount: 0,+ });+ jobWrite.mockRestore();+ mongoWrite.mockRestore();+ expect(await settle()).toBe(true);+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_permission_denied',+ lastRun: { status: 'error', mcp: failure.outcomes },+ });+});++it('retains a denial before a failed first job lookup and does not stamp a replacement generation', async () => {+ const f = await setup();+ const epoch = f.job.createdAt;+ const recorder = jest.spyOn(f.service, 'recordMCPToolAuthFailure');+ const read = jest.spyOn(store, 'getJob').mockRejectedValueOnce(new Error('Lookup outage'));+ expect(await f.record(new ScheduledMCPPolicyError('tool_policy_denied', '', 'child'))).toBe(+ false,+ );+ read.mockRestore();+ expect(recorder).toHaveBeenCalledWith(+ expect.objectContaining({ identity: f.execution.identity, jobCreatedAt: epoch }),+ );+ expect(await f.service.engineDeps.getJobStatus('stream')).toMatchObject({+ scheduleMCPFailure: expect.objectContaining({ reason: 'tool_policy_denied' }),+ });+ await store.updateJob(+ 'stream',+ { createdAt: f.job.createdAt + 1, scheduleId: 'other' },+ f.job.createdAt,+ );+ const outcome = jest.spyOn(f.service.engineDeps.methods, 'recordRunOutcome');+ expect(+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: epoch,+ }),+ ).toBe(true);+ expect(outcome).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'error',+ mcp: [expect.objectContaining({ reason: 'tool_policy_denied' })],+ }),+ );+ expect((await store.getJob('stream'))?.scheduleMCPFailure).toBeUndefined();+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ lastRun: { status: 'error', mcp: [expect.objectContaining({ reason: 'tool_policy_denied' })] },+ });+});++it('upgrades a transient receipt to a later permanent policy denial', async () => {+ const f = await setup();+ expect(await f.record(new ScheduledMCPPolicyError('dependency_unavailable', '', 'root'))).toBe(+ true,+ );+ const permanent = new ScheduledMCPPolicyError('tool_policy_denied', '', 'child');+ expect(await f.record(permanent)).toBe(true);+ expect((await store.getJob('stream'))?.scheduleMCPFailure).toEqual(permanent.outcomes[0]);+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_permission_denied',+ });+});++it('keeps a failed receipt through approval pause and a rebuilt settlement service', async () => {+ const f = await setup();+ const mongoWrite = jest+ .spyOn(f.service.engineDeps.methods, 'recordMCPToolAuthFailure')+ .mockRejectedValue(new Error('Mongo outage'));+ const jobWrite = jest.spyOn(store, 'updateJob').mockRejectedValue(new Error('Job outage'));+ const failure = new ScheduledMCPPolicyError('tool_policy_denied', '', 'child');+ expect(await f.record(failure)).toBe(false);+ const pause = () =>+ f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'requires_action',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ expect(await pause()).toBe(false);+ mongoWrite.mockRestore();+ jobWrite.mockRestore();+ expect(await pause()).toBe(true);+ const resumed = createSchedulesService(f.deps);+ expect(+ await resumed.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ }),+ ).toBe(true);+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ lastRun: { status: 'error', mcp: failure.outcomes },+ });+});++it('retains a transport consent denial before a transient first job lookup', async () => {+ const f = await setup();+ const invocation = f.execution.bind('child', 'query');+ const failure = new ScheduledMCPPolicyError('consent_revoked', 'warehouse', 'child');+ const read = jest+ .spyOn(store, 'getJob')+ .mockRejectedValueOnce(new Error('Transient lookup outage'));+ const persisted = await recordScheduledMCPToolAuthFailure(+ {+ error: failure,+ identity: invocation.identity,+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ userId: f.execution.identity.ownerId,+ serverName: 'warehouse',+ },+ () => f.service.recordMCPToolAuthFailure,+ );+ expect(persisted).toBe(false);+ read.mockRestore();+ expect(+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ }),+ ).toBe(true);+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_reauth_required',+ lastRun: { status: 'error', mcp: failure.outcomes },+ });+});++it.each(['success', 'error', 'skipped_balance'] as const)(+ 'merges an earlier Mongo receipt with a job-only permanent denial during %s settlement',+ async (status) => {+ const f = await setup(true);+ const transient = new ScheduledMCPPolicyError('dependency_unavailable', '', 'root');+ expect(await f.record(transient)).toBe(true);+ await f.enroll();+ const permanent = new ScheduledMCPPolicyError('binding_mismatch', '', 'child');+ const write = jest+ .spyOn(f.service.engineDeps.methods, 'recordMCPToolAuthFailure')+ .mockRejectedValueOnce(new Error('Transient Mongo receipt outage'));+ expect(await f.record(permanent)).toBe(true);+ write.mockRestore();+ expect((await store.getJob('stream'))?.scheduleMCPFailure).toEqual(permanent.outcomes[0]);+ expect((await f.methods.getScheduleRunAbortState(f.schedule.id, f.scheduledFor))?.mcp).toEqual(+ transient.outcomes,+ );+ expect(+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status,+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ }),+ ).toBe(true);+ const card = await f.methods.getScheduleById(f.schedule.id);+ expect(card).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_reauth_required',+ failureCount: 1,+ lastRun: { status: 'error' },+ });+ expect(card!.lastRun!.mcp).toEqual([...transient.outcomes, ...permanent.outcomes]);+ },+);++it.each(['root', 'child'])(+ 'blocks enrolled background delegation from %s before a completion can be registered',+ async (agentId) => {+ const f = await setup();+ const policy = createScheduledMCPRunPolicy(+ f.execution,+ [{ id: 'root' }, { id: 'child' }],+ [],+ f.record,+ );+ const registry = new HookRegistry();+ registry.register('PreToolUse', { hooks: [policy.hook, policy.receipt] });+ const start = jest.fn(async () => 'background handle');+ const delegate = new DynamicStructuredTool({+ name: Constants.SUBAGENT,+ description: 'SDK delegation surface',+ schema: z.object({+ run_in_background: z.boolean().optional(),+ subagent_thread_id: z.string().optional(),+ }),+ func: start,+ });+ const node = new ToolNode({ agentId, tools: [delegate], hookRegistry: registry });+ const call = (args: Record<string, unknown>, id: string) =>+ node.invoke(+ {+ messages: [+ new AIMessage({ content: '', tool_calls: [{ id, name: delegate.name, args }] }),+ ],+ },+ { configurable: { run_id: 'scheduled', thread_id: 'thread' } },+ );+ for (const args of [+ { run_in_background: true },+ { run_in_background: true, subagent_thread_id: 'saved-thread' },+ ]) {+ expect(JSON.stringify(await call(args, 'detached'))).toContain('Blocked:');+ expect(start).not.toHaveBeenCalled();+ }+ await call({ run_in_background: false }, 'foreground');+ expect(start).toHaveBeenCalledTimes(1);+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_permission_denied',+ lastRun: {+ status: 'error',+ mcp: [expect.objectContaining({ agentId, reason: 'tool_policy_denied' })],+ },+ });+ },+);++it('fences both newly prepared and already serialized legacy completion turns after enrollment', async () => {+ const f = await setup(true);+ const scope = {+ ownerId: f.execution.identity.ownerId,+ tenantId: 'tenant',+ scheduleMCPIdentity: f.execution.identity,+ };+ const identity = await resolveScheduleMCPCompletion(+ scope,+ f.methods.getScheduleMCPCompletionState,+ );+ expect(identity).toEqual(f.execution.identity);+ await f.enroll();+ await expect(+ resolveScheduleMCPCompletion(scope, f.methods.getScheduleMCPCompletionState),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ const host = createScheduleMCPRuntimeHost({+ methods: f.methods,+ getScheduleMCPCompletionState: f.methods.getScheduleMCPCompletionState,+ findUser: async () => null,+ getRoleByName: async () => null,+ canViewAgent: async () => false,+ enrollment: {+ findUser: async () => null,+ canUseRoot: async () => false,+ getAppConfig: async () => undefined,+ resolveGraphAccess: async () => ({}) as AgentGraphAccessContext,+ getNodes: async () => [],+ getModelsConfig: async () => ({}),+ getServers: async () => ({}),+ },+ });+ for (const sourceId of ['subagent-completion', 'background-tool-completion']) {+ for (const marker of [{ version: 1, sourceId, scheduleMCPIdentity: identity }]) {+ const initialize = jest.fn(async () => 'mutation would execute');+ const req = {+ user: { id: f.execution.identity.ownerId, tenantId: 'tenant' },+ _isAgentTrigger: true,+ _isScheduledFire: false,+ body: { conversationId: 'stream', agent_id: 'root', agentCompletion: marker },+ };+ await expect(+ initializeWithScheduleMCPExecution(+ { req, context: createMCPRequestContext() },+ () => host,+ initialize,+ ),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(initialize).not.toHaveBeenCalled();+ }+ }+});++it('atomically keeps a permanent denial when an older delayed transient job write lands last', async () => {+ const f = await setup();+ const mongoWrite = jest+ .spyOn(f.service.engineDeps.methods, 'recordMCPToolAuthFailure')+ .mockRejectedValue(new Error('Receipt storage outage'));+ const original = store.updateJob.bind(store);+ let enter!: () => void;+ let release!: () => void;+ const entered = new Promise<void>((resolve) => {+ enter = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ jest.spyOn(store, 'updateJob').mockImplementation(async (id, patch, epoch) => {+ if (patch.scheduleMCPFailure?.reason === 'dependency_unavailable') {+ enter();+ await gate;+ }+ await original(id, patch, epoch);+ });+ const earlier = f.record(new ScheduledMCPPolicyError('dependency_unavailable', '', 'root'));+ await entered;+ const permanent = new ScheduledMCPPolicyError('binding_mismatch', '', 'child');+ expect(await f.record(permanent)).toBe(true);+ release();+ expect(await earlier).toBe(true);+ expect((await store.getJob('stream'))?.scheduleMCPFailure).toEqual(permanent.outcomes[0]);+ mongoWrite.mockRestore();+ const rebuilt = createSchedulesService(f.deps);+ await rebuilt.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ expect(await f.methods.getScheduleById(f.schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_reauth_required',+ failureCount: 1,+ lastRun: { status: 'error', mcp: permanent.outcomes },+ });+});++it('projects the original schedule identity from the production host into a queued completion', async () => {+ const f = await setup(true);+ const identity = await resolveScheduleMCPCompletion(+ {+ ownerId: f.execution.identity.ownerId,+ tenantId: 'tenant',+ scheduleMCPIdentity: f.execution.identity,+ },+ f.methods.getScheduleMCPCompletionState,+ );+ let body: Record<string, unknown> | undefined;+ const trigger = createAgentTriggerExecutionHost({+ getBaseUrl: () => 'http://localhost:3080',+ mintToken: async () => 'fixture-token',+ prepareContinue: async () => ({+ status: 'ready',+ input: 'completed',+ parentMessageId: 'response',+ scheduleMCPIdentity: identity,+ }),+ fetch: async (_url, request) => {+ body = JSON.parse(String(request?.body));+ return new Response(+ JSON.stringify({+ status: 'started',+ conversationId: 'stream',+ streamId: 'stream',+ generationCreatedAt: 1,+ }),+ { status: 200 },+ );+ },+ });+ await trigger.dispatch(+ createAgentTriggerEnvelope({+ mode: 'continue',+ requestId: 'request',+ deliveryId: 'task',+ receivedAt: Date.now(),+ principal: { id: f.execution.identity.ownerId, tenantId: 'tenant' },+ event: {+ id: 'task',+ type: 'subagent.completion',+ occurredAt: Date.now(),+ source: { id: 'subagent-completion', type: 'internal' },+ },+ target: { agentId: 'root', conversationId: 'stream', parentMessageId: 'response' },+ input: 'completed',+ }),+ );+ expect(body).toMatchObject({+ agentCompletion: { version: 1, sourceId: 'subagent-completion', scheduleMCPIdentity: identity },+ });+ expect(body).not.toHaveProperty('agentTrigger');+});++it('keeps a legacy continuation guarded if confirmation lands after request admission', async () => {+ const f = await setup(true);+ const context = createMCPRequestContext();+ const host = createScheduleMCPRuntimeHost({+ methods: f.methods,+ getScheduleMCPCompletionState: f.methods.getScheduleMCPCompletionState,+ findUser: async () => null,+ getRoleByName: async () => null,+ canViewAgent: async () => false,+ enrollment: {+ findUser: async () => null,+ canUseRoot: async () => false,+ getAppConfig: async () => undefined,+ resolveGraphAccess: async () => ({}) as AgentGraphAccessContext,+ getNodes: async () => [],+ getModelsConfig: async () => ({}),+ getServers: async () => ({}),+ },+ });+ await host.prepare({+ context,+ req: {+ user: { id: f.execution.identity.ownerId, tenantId: 'tenant' },+ _isAgentTrigger: true,+ body: {+ conversationId: 'stream',+ agent_id: 'child',+ agentCompletion: {+ version: 1,+ sourceId: 'subagent-completion',+ scheduleMCPIdentity: f.execution.identity,+ },+ },+ },+ });+ const execution = getScheduleMCPExecution(context)!;+ expect(execution.enrolled).toBe(false);+ expect(execution.identity.agentId).toBe('root');+ await f.enroll();+ const policy = createScheduledMCPRunPolicy(execution, [{ id: 'child' }]);+ const registry = new HookRegistry();+ registry.register('PreToolUse', { hooks: [policy.hook] });+ const mutate = jest.fn(async () => 'mutated');+ const action = new DynamicStructuredTool({+ name: 'mutation',+ description: 'Write',+ schema: z.object({}),+ func: mutate,+ });+ const node = new ToolNode({ agentId: 'child', tools: [action], hookRegistry: registry });+ expect(+ JSON.stringify(+ await node.invoke(+ {+ messages: [+ new AIMessage({+ content: '',+ tool_calls: [{ id: 'write', name: action.name, args: {} }],+ }),+ ],+ },+ { configurable: { run_id: 'completion', thread_id: 'stream' } },+ ),+ ),+ ).toContain('Blocked:');+ expect(mutate).not.toHaveBeenCalled();+});++it('scopes captured completion lineage to its owner, tenant and root, and rejects deleted authority', async () => {+ const f = await setup(true);+ const lookup = jest.spyOn(f.methods, 'getScheduleMCPCompletionState');+ const scope = {+ ownerId: f.scope.userId,+ tenantId: 'tenant',+ scheduleMCPIdentity: f.execution.identity,+ };+ expect(+ await resolveScheduleMCPCompletion(+ { ...scope, scheduleMCPIdentity: null },+ f.methods.getScheduleMCPCompletionState,+ ),+ ).toBeUndefined();+ expect(lookup).not.toHaveBeenCalled();+ for (const identity of [+ { ...f.execution.identity, tenantId: 'foreign' },+ { ...f.execution.identity, ownerId: new mongoose.Types.ObjectId().toString() },+ { ...f.execution.identity, agentId: 'replacement-root' },+ ])+ await expect(+ resolveScheduleMCPCompletion(+ { ...scope, scheduleMCPIdentity: identity },+ f.methods.getScheduleMCPCompletionState,+ ),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ await mongoose.models.Schedule.deleteOne({ id: f.schedule.id });+ await expect(+ resolveScheduleMCPCompletion(scope, f.methods.getScheduleMCPCompletionState),+ ).rejects.toMatchObject({+ failure: { reason: 'binding_mismatch' },+ });+});++it('refuses an authenticated completion approval after its original schedule was enrolled and revoked', async () => {+ const f = await setup(true);+ const identity = f.execution.identity;+ const host = createScheduleMCPRuntimeHost({+ methods: f.methods,+ getScheduleMCPCompletionState: f.methods.getScheduleMCPCompletionState,+ findUser: async () => null,+ getRoleByName: async () => null,+ canViewAgent: async () => false,+ enrollment: {+ findUser: async () => null,+ canUseRoot: async () => false,+ getAppConfig: async () => undefined,+ resolveGraphAccess: async () => ({}) as AgentGraphAccessContext,+ getNodes: async () => [],+ getModelsConfig: async () => ({}),+ getServers: async () => ({}),+ },+ });+ await f.enroll();+ const snapshot = await f.methods.readScheduleMCPConsent(identity);+ await f.methods.revokeScheduleMCPConsent(identity, snapshot!.enrollment!.revision);+ const provider = jest.fn(async () => 'approved read would execute');+ const req = {+ user: { id: identity.ownerId, tenantId: 'tenant' },+ _isAgentTrigger: false,+ _isScheduledFire: false,+ body: {+ conversationId: 'stream',+ agent_id: 'child',+ agentCompletion: {+ version: 1,+ sourceId: 'subagent-completion',+ scheduleMCPIdentity: f.execution.identity,+ },+ },+ };+ await expect(+ initializeWithScheduleMCPExecution(+ {+ req,+ context: createMCPRequestContext(),+ restoredJob: { scheduleMCPCompletion: identity } as never,+ },+ () => host,+ provider,+ ),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(provider).not.toHaveBeenCalled();+});++it('persists completion identity before tool construction and restores its monitor across repeated approvals', async () => {+ const f = await setup(true);+ const host = createScheduleMCPRuntimeHost({+ methods: f.methods,+ getScheduleMCPCompletionState: f.methods.getScheduleMCPCompletionState,+ findUser: async () => null,+ getRoleByName: async () => null,+ canViewAgent: async () => false,+ enrollment: {+ findUser: async () => null,+ canUseRoot: async () => false,+ getAppConfig: async () => undefined,+ resolveGraphAccess: async () => ({}) as AgentGraphAccessContext,+ getNodes: async () => [],+ getModelsConfig: async () => ({}),+ getServers: async () => ({}),+ },+ });+ const req = {+ user: { id: f.execution.identity.ownerId, tenantId: 'tenant' },+ _isAgentTrigger: true,+ body: {+ conversationId: 'stream',+ agent_id: 'child',+ agentCompletion: {+ version: 1,+ sourceId: 'subagent-completion',+ scheduleMCPIdentity: f.execution.identity,+ },+ },+ };+ const provider = jest.fn(async () => {+ expect((await store.getJob('stream'))?.scheduleMCPCompletion).toEqual(f.execution.identity);+ });+ await initializeWithScheduleMCPExecution(+ { req, context: createMCPRequestContext() },+ () => host,+ provider,+ (identity) =>+ retainScheduleMCPCompletion(+ identity,+ { streamId: 'stream', createdAt: f.job.createdAt },+ store,+ ),+ );+ expect(provider).toHaveBeenCalledTimes(1);+ const lineage = (await store.getJob('stream'))!.scheduleMCPCompletion!;+ for (let i = 0; i < 2; i++) {+ const context = createMCPRequestContext();+ await initializeWithScheduleMCPExecution(+ {+ req: { ...req, _isAgentTrigger: false },+ context,+ restoredJob: { scheduleMCPCompletion: lineage },+ },+ () => host,+ async () => {+ expect(getScheduleMCPExecution(context)?.identity).toEqual(lineage);+ expect(getScheduleMCPExecution(context)?.stage).toBe('resume');+ },+ );+ }+ await f.enroll();+ const context = createMCPRequestContext();+ await expect(+ initializeWithScheduleMCPExecution(+ {+ req: { ...req, _isAgentTrigger: false },+ context,+ restoredJob: { scheduleMCPCompletion: lineage },+ },+ () => host,+ provider,+ ),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ expect(provider).toHaveBeenCalledTimes(1);+});++it('cannot launch a completion when its lineage cannot be durably retained', async () => {+ const f = await setup(true);+ const scope = { streamId: 'stream', createdAt: f.job.createdAt };+ jest.spyOn(store, 'updateJob').mockResolvedValueOnce(undefined);+ await expect(+ retainScheduleMCPCompletion(f.execution.identity, scope, store),+ ).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+ await expect(+ retainScheduleMCPCompletion(+ f.execution.identity,+ { ...scope, createdAt: scope.createdAt - 1 },+ store,+ ),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ await expect(+ retainScheduleMCPCompletion({ ...f.execution.identity, tenantId: 'foreign' }, scope, store),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+});++it.each(['snapshot', 'consent', 'admission', 'catalog'] as const)(+ 'retains a safe %s authorization failure when the model handles it as success',+ async (phase) => {+ const f = await setup();+ const internal = new Error('PRIVATE authorization dependency details');+ if (phase === 'snapshot') f.loadAuthorization.mockRejectedValue(internal);+ if (phase === 'consent')+ jest.spyOn(f.consent.authority, 'authorize').mockRejectedValue(internal);+ if (phase === 'admission')+ jest.spyOn(f.methods, 'admitScheduleMCPConsent').mockRejectedValue(internal);+ const provider = jest.fn(async () => 'read executed');+ const tool = new DynamicStructuredTool({+ name: 'query_mcp_warehouse',+ description: 'Read',+ schema: z.object({}),+ func: async () => {+ try {+ await f.execution.bind('child', 'query').authorize({+ user: { id: f.scope.userId, tenantId: 'tenant' },+ serverName: 'warehouse',+ serverConfig: f.fixture.config,+ toolName: 'query',+ loadTools: async () => {+ if (phase === 'catalog') throw internal;+ return { tools: [readTool], complete: true };+ },+ });+ return provider();+ } catch (error) {+ await recordScheduledMCPToolAuthFailure(+ {+ error,+ identity: f.execution.identity,+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ userId: f.scope.userId,+ serverName: 'warehouse',+ },+ () => f.service.recordMCPToolAuthFailure,+ );+ throw error;+ }+ },+ });+ const result = await new ToolNode({ agentId: 'child', tools: [tool] }).invoke(+ {+ messages: [+ new AIMessage({ content: '', tool_calls: [{ id: 'read', name: tool.name, args: {} }] }),+ ],+ },+ { configurable: { run_id: 'scheduled', thread_id: 'stream' } },+ );+ expect(provider).not.toHaveBeenCalled();+ expect(JSON.stringify(result)).toContain('dependency_unavailable');+ expect(JSON.stringify(result)).not.toContain('PRIVATE');+ expect((await store.getJob('stream'))?.scheduleMCPFailure).toMatchObject({+ server: 'warehouse',+ agentId: 'child',+ reason: 'dependency_unavailable',+ });+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ const saved = await f.methods.getScheduleById(f.schedule.id);+ expect(saved).toMatchObject({+ enabled: true,+ failureCount: 1,+ lastRun: {+ status: 'error',+ mcp: [+ expect.objectContaining({ reason: 'dependency_unavailable', automaticReplay: false }),+ ],+ },+ });+ expect(JSON.stringify(saved)).not.toContain('PRIVATE');+ },+);++it('stores only a safe preparation outage when initial authorization fails after readiness', async () => {+ const f = await setup();+ const host = createScheduleMCPRuntimeHost({+ methods: {+ ...f.methods,+ getScheduleById: async () => {+ throw new Error('PRIVATE database query');+ },+ },+ getScheduleMCPCompletionState: f.methods.getScheduleMCPCompletionState,+ findUser: async () => null,+ getRoleByName: async () => null,+ canViewAgent: async () => false,+ enrollment: {+ findUser: async () => null,+ canUseRoot: async () => false,+ getAppConfig: async () => undefined,+ resolveGraphAccess: async () => ({}) as AgentGraphAccessContext,+ getNodes: async () => [],+ getModelsConfig: async () => ({}),+ getServers: async () => ({}),+ },+ });+ const provider = jest.fn();+ let failure: unknown;+ try {+ await initializeWithScheduleMCPExecution(+ {+ req: {+ user: { id: f.scope.userId, tenantId: 'tenant' },+ _isScheduledFire: true,+ _isAgentTrigger: true,+ body: {+ agent_id: 'root',+ agentTrigger: {+ version: 1,+ event: {+ type: 'schedule.occurrence',+ occurredAt: 0,+ source: { id: f.schedule.id, type: 'schedule' },+ },+ },+ },+ },+ context: createMCPRequestContext(),+ },+ () => host,+ provider,+ );+ } catch (error) {+ failure = error;+ }+ expect(failure).toBeInstanceOf(ScheduledMCPPolicyError);+ if (!(failure instanceof ScheduledMCPPolicyError)) throw new Error('Expected safe denial');+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'error',+ error: failure.message,+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ const saved = await f.methods.getScheduleById(f.schedule.id);+ expect(saved).toMatchObject({+ enabled: true,+ failureCount: 1,+ lastRun: { status: 'error', error: failure.message },+ });+ expect(saved?.lastRun?.error).toContain('dependency_unavailable');+ expect(JSON.stringify(saved)).not.toContain('PRIVATE');+ expect(provider).not.toHaveBeenCalled();+});++it.each(+ ['subagent-completion', 'background-tool-completion'].flatMap((sourceId) =>+ ['legacy', 'enrolled', 'deleted'].map((scheduleState) => ({ sourceId, scheduleState })),+ ),+)(+ 'does not apply historical schedule authority to an ordinary task: %s',+ async ({ sourceId, scheduleState }) => {+ const f = await setup(true);+ await f.service.recordScheduleOutcome({+ scheduleId: f.schedule.id,+ scheduledFor: f.scheduledFor,+ status: 'success',+ conversationId: 'stream',+ streamId: 'stream',+ jobCreatedAt: f.job.createdAt,+ });+ if (scheduleState === 'enrolled') await f.enroll();+ if (scheduleState === 'deleted')+ await mongoose.models.Schedule.deleteOne({ id: f.schedule.id });+ const host = createScheduleMCPRuntimeHost({+ methods: f.methods,+ getScheduleMCPCompletionState: f.methods.getScheduleMCPCompletionState,+ findUser: async () => null,+ getRoleByName: async () => null,+ canViewAgent: async () => false,+ enrollment: {+ findUser: async () => null,+ canUseRoot: async () => false,+ getAppConfig: async () => undefined,+ resolveGraphAccess: async () => ({}) as AgentGraphAccessContext,+ getNodes: async () => [],+ getModelsConfig: async () => ({}),+ getServers: async () => ({}),+ },+ });+ const context = createMCPRequestContext();+ const initialize = jest.fn(async () => 'ordinary continuation');+ await expect(+ initializeWithScheduleMCPExecution(+ {+ context,+ req: {+ user: { id: f.scope.userId, tenantId: 'tenant' },+ _isAgentTrigger: true,+ body: {+ conversationId: 'stream',+ agent_id: 'root',+ agentCompletion: { version: 1, sourceId, scheduleMCPIdentity: null },+ },+ },+ },+ () => host,+ initialize,+ ),+ ).resolves.toBe('ordinary continuation');+ expect(getScheduleMCPExecution(context)).toBeUndefined();+ expect(initialize).toHaveBeenCalledTimes(1);+ },+);diff --git a/packages/api/src/schedules/authorization/run.spec.ts b/packages/api/src/schedules/authorization/run.spec.tsnew file mode 100644index 0000000000..e216bce73a--- /dev/null+++ b/packages/api/src/schedules/authorization/run.spec.ts@@ -0,0 +1,186 @@+import { StructuredTool } from '@langchain/core/tools';+import { AIMessage } from '@librechat/agents/langchain/messages';+import {+ Constants,+ HookRegistry,+ MultiAgentGraph,+ Providers,+ ToolNode,+ executeHooks,+} from '@librechat/agents';+import type { GraphEdge } from '@librechat/agents';+import { executionFixture } from './execution.helper';+import { createScheduledMCPRunPolicy } from './run';++async function setup(edges: GraphEdge[]) {+ const fixture = await executionFixture();+ const agents = ['root', 'child', 'peer'].map((id) => ({ id }));+ const policy = createScheduledMCPRunPolicy(fixture.execution, agents, edges);+ const hooks = new HookRegistry();+ hooks.register('PreToolUse', { hooks: [policy.hook] });+ const graph = new MultiAgentGraph({+ agents: agents.map(({ id }) => ({ agentId: id, provider: Providers.OPENAI, tools: [] })),+ edges,+ });+ const invoke = async (agentId: string, name: string) => {+ const tools: StructuredTool[] = [];+ for (const tool of graph.agentContexts.get(agentId)?.graphTools ?? []) {+ if (tool instanceof StructuredTool) tools.push(tool);+ }+ const node = new ToolNode({ tools, agentId, hookRegistry: hooks });+ return node.invoke(+ {+ messages: [+ new AIMessage({+ content: '',+ tool_calls: [{ id: 'transfer', name, args: {} }],+ }),+ ],+ },+ { configurable: { run_id: 'scheduled', thread_id: 'thread' } },+ );+ };+ const check = (agentId: string, name: string) =>+ policy.hook(+ {+ hook_event_name: 'PreToolUse',+ runId: 'scheduled',+ executingAgentId: agentId,+ toolName: name,+ toolUseId: 'transfer',+ toolInput: {},+ },+ new AbortController().signal,+ );+ return { invoke, check, policy, graph };+}++it('executes the exact SDK handoff tool and keeps unrelated transfer names denied', async () => {+ const f = await setup([{ from: 'root', to: 'child', edgeType: 'handoff' }]);+ const result = await f.invoke('root', `${Constants.LC_TRANSFER_TO_}child`);+ expect(JSON.stringify(result)).toContain('Successfully transferred to child');+ expect(JSON.stringify(result)).not.toContain('Blocked:');+ for (const [agent, name] of [+ ['root', `${Constants.LC_TRANSFER_TO_}peer`],+ ['child', `${Constants.LC_TRANSFER_TO_}root`],+ ['root', 'conditional_transfer'],+ ['root', `${Constants.LC_TRANSFER_TO_}forged`],+ ])+ expect(await f.check(agent, name)).toMatchObject({ decision: 'deny' });+});++it('executes a conditional SDK transfer without permitting unlisted destinations', async () => {+ const f = await setup([{ from: 'root', to: ['child', 'peer'], condition: () => 'child' }]);+ const result = await f.invoke('root', 'conditional_transfer');+ expect(JSON.stringify(result)).toContain('Conditionally transferred to child');+ expect(JSON.stringify(result)).not.toContain('Blocked:');+ expect(await f.check('child', 'conditional_transfer')).toMatchObject({ decision: 'deny' });+ expect(await f.check('root', `${Constants.LC_TRANSFER_TO_}peer`)).toMatchObject({+ decision: 'deny',+ });+ const invalid = await setup([{ from: 'root', to: 'child', condition: () => 'peer' }]);+ expect(JSON.stringify(await invalid.invoke('root', 'conditional_transfer'))).toContain(+ 'undeclared destination',+ );+});++it('does not invent transfer controls for direct or orphaned edges', async () => {+ const f = await setup([{ from: 'root', to: ['child', 'peer'] }]);+ expect(f.graph.agentContexts.get('root')?.graphTools).toBeUndefined();+ expect(await f.check('root', `${Constants.LC_TRANSFER_TO_}child`)).toMatchObject({+ decision: 'deny',+ });+ const fixture = await executionFixture();+ const orphan = createScheduledMCPRunPolicy(+ fixture.execution,+ [{ id: 'root' }],+ [{ from: 'root', to: 'missing', edgeType: 'handoff' }],+ );+ expect(+ await orphan.hook(+ {+ hook_event_name: 'PreToolUse',+ runId: 'run',+ executingAgentId: 'root',+ toolName: `${Constants.LC_TRANSFER_TO_}missing`,+ toolInput: {},+ toolUseId: 'call',+ },+ new AbortController().signal,+ ),+ ).toMatchObject({ decision: 'deny' });+});++it('registers nested graph controls only from their resolved member edges', async () => {+ const f = await setup([]);+ f.policy.registerAgent({+ id: 'lazy',+ subagentGraphConfigs: [+ {+ definition: { edges: [{ from: 'child', to: 'peer', edgeType: 'handoff' }] },+ memberConfigs: [{ id: 'child' }, { id: 'peer' }],+ },+ ],+ });+ expect(await f.check('child', `${Constants.LC_TRANSFER_TO_}peer`)).toEqual({});+ expect(await f.check('root', `${Constants.LC_TRANSFER_TO_}peer`)).toMatchObject({+ decision: 'deny',+ });+});++it('denies safely when an unenrolled run cannot recheck enrollment', async () => {+ const f = await executionFixture();+ f.snapshot.enrollment = null;+ const legacy = (await f.factory.resolve(f.identity, 'invoke'))!;+ const record = jest.fn(async () => true);+ const policy = createScheduledMCPRunPolicy(legacy, [{ id: 'root' }], [], record);+ jest.mocked(f.storage.readScheduleMCPConsent).mockRejectedValueOnce(new Error('PRIVATE outage'));+ const registry = new HookRegistry();+ registry.register('PreToolUse', { hooks: [policy.hook, policy.receipt], internal: true });+ const input = {+ hook_event_name: 'PreToolUse' as const,+ runId: 'legacy',+ executingAgentId: 'root',+ toolName: 'write',+ toolInput: {},+ toolUseId: 'call',+ };+ const result = await executeHooks({ registry, input });+ expect(result).toMatchObject({ decision: 'deny' });+ expect(result.reason).toContain('dependency_unavailable');+ expect(result.reason).not.toContain('PRIVATE');+ expect(record).toHaveBeenCalledTimes(1);+});++it('denies only host-marked ordinary background MCP work, while retaining foreground reads', async () => {+ const f = await executionFixture();+ const policy = createScheduledMCPRunPolicy(f.execution, [+ {+ id: 'root',+ backgroundToolNames: ['query_mcp_warehouse'],+ toolRegistry: new Map([+ [+ 'query_mcp_warehouse',+ { name: 'query_mcp_warehouse', toolType: 'mcp', serverName: 'warehouse' },+ ],+ ]),+ },+ ]);+ const input = {+ hook_event_name: 'PreToolUse' as const,+ runId: 'scheduled',+ executingAgentId: 'root',+ toolName: 'query_mcp_warehouse',+ toolInput: { run_in_background: true },+ toolUseId: 'read',+ };+ expect(await policy.hook(input, new AbortController().signal)).toMatchObject({+ decision: 'deny',+ });+ expect(+ await policy.hook(+ { ...input, toolInput: { run_in_background: false } },+ new AbortController().signal,+ ),+ ).toEqual({});+});diff --git a/packages/api/src/schedules/authorization/run.ts b/packages/api/src/schedules/authorization/run.tsnew file mode 100644index 0000000000..5f85a11012--- /dev/null+++ b/packages/api/src/schedules/authorization/run.ts@@ -0,0 +1,160 @@+import { Constants } from '@librechat/agents';+import type { HookCallback } from '@librechat/agents';+import type { ScheduleMCPExecution } from './execution';+import { ASK_USER_QUESTION_TOOL_NAME } from '~/agents/hitl/askUserQuestionTool';+import { ScheduledMCPPolicyError } from './policy';++interface HandoffEdge {+ from: string | string[];+ to: string | string[];+ edgeType?: 'handoff' | 'direct';+ /** Only presence is used; evaluation and destination validation remain SDK-owned. */+ condition?: unknown;+}++interface PolicyTool {+ name: string;+ toolType?: string;+ serverName?: string;+ mcpRawServerName?: string;+}+export interface ScheduledMCPPolicyAgent {+ id: string;+ toolDefinitions?: readonly PolicyTool[];+ toolRegistry?: ReadonlyMap<string, PolicyTool>;+ backgroundToolNames?: readonly string[];+ subagentAgentConfigs?: readonly ScheduledMCPPolicyAgent[];+ subagentGraphConfigs?: readonly {+ definition?: { edges: readonly HandoffEdge[] };+ memberConfigs: readonly ScheduledMCPPolicyAgent[];+ }[];+}++/** No direct actions, arbitrary code or unclassified tools in an enrolled read-only run. */+export function createScheduledMCPRunPolicy(+ execution: ScheduleMCPExecution,+ agents: readonly ScheduledMCPPolicyAgent[],+ edges: readonly HandoffEdge[] = [],+ recordDenial?: (error: ScheduledMCPPolicyError) => Promise<boolean>,+): {+ hook: HookCallback<'PreToolUse'>;+ receipt: HookCallback<'PreToolUse'>;+ registerAgent: (agent: ScheduledMCPPolicyAgent) => void;+} {+ const mcpTools = new Map<string, Set<string>>();+ const handoffs = new Map<string, Set<string>>();+ const backgroundTools = new Map<string, Set<string>>();+ const registerGraph = (+ members: readonly ScheduledMCPPolicyAgent[],+ admittedEdges: readonly HandoffEdge[],+ ): void => {+ const ids = new Set(members.map(({ id }) => id));+ for (const edge of admittedEdges) {+ const sources = Array.isArray(edge.from) ? edge.from : [edge.from];+ const targets = Array.isArray(edge.to) ? edge.to : [edge.to];+ // Match SDK categorization, including its implicit one-to-many direct edge.+ if (+ edge.edgeType === 'direct' ||+ (edge.edgeType == null &&+ edge.condition == null &&+ sources.length === 1 &&+ targets.length > 1) ||+ !targets.length ||+ !targets.every((id) => ids.has(id))+ )+ continue;+ const names =+ edge.condition != null+ ? ['conditional_transfer']+ : targets.map((id) => `${Constants.LC_TRANSFER_TO_}${id}`);+ for (const source of sources) {+ if (!ids.has(source)) continue;+ const controls = handoffs.get(source) ?? new Set<string>();+ for (const name of names) controls.add(name);+ handoffs.set(source, controls);+ }+ }+ };+ const registerAgent = (root: ScheduledMCPPolicyAgent): void => {+ const queue = [root];+ const visited = new Set<ScheduledMCPPolicyAgent>();+ for (const agent of queue) {+ if (visited.has(agent)) continue;+ visited.add(agent);+ queue.push(...(agent.subagentAgentConfigs ?? []));+ for (const graph of agent.subagentGraphConfigs ?? []) {+ queue.push(...graph.memberConfigs);+ registerGraph(graph.memberConfigs, graph.definition?.edges ?? []);+ }+ const names = mcpTools.get(agent.id) ?? new Set<string>();+ for (const tool of agent.toolDefinitions ?? []) {+ if (tool.toolType === 'mcp' && tool.serverName) names.add(tool.name);+ }+ for (const [name, tool] of agent.toolRegistry ?? []) {+ if (tool.toolType === 'mcp' && (tool.mcpRawServerName || tool.serverName)) names.add(name);+ }+ mcpTools.set(agent.id, names);+ backgroundTools.set(agent.id, new Set(agent.backgroundToolNames ?? []));+ }+ };+ agents.forEach(registerAgent);+ registerGraph(agents, edges);+ const controls = new Set<string>([+ Constants.SUBAGENT,+ Constants.TOOL_SEARCH,+ ASK_USER_QUESTION_TOOL_NAME,+ ]);+ const denied = (input: Parameters<HookCallback<'PreToolUse'>>[0]): boolean => {+ const agentId = input.executingAgentId;+ // Foreground delegation stays in this guarded run; detached continuations do not.+ if (+ input.toolInput.run_in_background === true &&+ (input.toolName === Constants.SUBAGENT ||+ (agentId != null && backgroundTools.get(agentId)?.has(input.toolName)))+ )+ return true;+ return !(+ mcpTools.has(execution.identity.agentId) &&+ agentId != null &&+ mcpTools.has(agentId) &&+ (controls.has(input.toolName) ||+ handoffs.get(agentId)?.has(input.toolName) === true ||+ mcpTools.get(agentId)!.has(input.toolName))+ );+ };+ const decisions = new WeakMap<object, Promise<ScheduledMCPPolicyError | undefined>>();+ const failure = (input: Parameters<HookCallback<'PreToolUse'>>[0]) => {+ const pending = decisions.get(input);+ if (pending) return pending;+ const evaluated = (async () => {+ try {+ await execution.checkEnrollment();+ } catch (error) {+ return new ScheduledMCPPolicyError(+ error instanceof ScheduledMCPPolicyError+ ? error.failure.reason+ : 'dependency_unavailable',+ '',+ input.executingAgentId,+ );+ }+ if (!execution.enrolled || !denied(input)) return;+ return new ScheduledMCPPolicyError('tool_policy_denied', '', input.executingAgentId);+ })();+ decisions.set(input, evaluated);+ return evaluated;+ };+ return {+ registerAgent,+ hook: async (input) => {+ const error = await failure(input);+ return error ? { decision: 'deny', reason: error.message } : {};+ },+ // Separate hook: a failed or timed-out receipt must never erase the immediate deny.+ receipt: async (input) => {+ const error = await failure(input);+ if (error) await recordDenial?.(error);+ return {};+ },+ };+}diff --git a/packages/api/src/schedules/authorization/runtime.spec.ts b/packages/api/src/schedules/authorization/runtime.spec.tsnew file mode 100644index 0000000000..acf24499f9--- /dev/null+++ b/packages/api/src/schedules/authorization/runtime.spec.ts@@ -0,0 +1,658 @@+import { Permissions, PermissionTypes, AgentCapabilities } from 'librechat-data-provider';+import type { AppConfig, IRole, ISchedule, AgentGraphAccessContext } from '@librechat/data-schemas';+import {+ createScheduleMCPRuntimeHost,+ prepareScheduleMCPExecution,+ initializeWithScheduleMCPExecution,+} from './runtime';+import { bindScheduledMCPInvocation, getScheduleMCPExecution } from './execution';+import { executionFixture, readTool } from './execution.helper';+import { createMCPRequestContext } from '~/mcp/request';+import { createScheduleMCPPreflight } from '../mcp';+import { ScheduledMCPPolicyError } from './policy';++async function setup() {+ const fixture = await executionFixture();+ jest.spyOn(Date, 'now').mockReturnValue(1000);+ let candidates = ['query_mcp_warehouse'];+ const config = {+ interfaceConfig: {+ schedules: {+ use: true,+ create: true,+ mcpConsent: {+ enabled: true,+ maxLifetimeHours: 24,+ resources: {+ warehouse: {+ url: 'https://resource.example/mcp',+ credentialMode: 'anonymous',+ issuer: null,+ audience: null,+ scopes: [],+ },+ },+ readOnlyPolicy: fixture.policy,+ },+ },+ },+ endpoints: { agents: { capabilities: [AgentCapabilities.tools] } },+ mcpConfig: { warehouse: fixture.config },+ } as unknown as AppConfig;+ const row = {+ id: fixture.identity.scheduleId,+ user: fixture.identity.ownerId,+ agent_id: 'root',+ tenantId: 'tenant',+ enabled: true,+ configRevision: 0,+ mcpConsent: fixture.snapshot.enrollment,+ } as unknown as ISchedule;+ const getRoleByName = jest.fn(+ async () =>+ ({+ permissions: {+ [PermissionTypes.SCHEDULES]: { [Permissions.USE]: true, [Permissions.CREATE]: true },+ [PermissionTypes.MCP_SERVERS]: { [Permissions.USE]: true },+ },+ }) as IRole,+ );+ const findUser = jest.fn(async () => fixture.user);+ const getAppConfig = jest.fn(+ async (+ _options?: Parameters<+ Parameters<typeof createScheduleMCPRuntimeHost>[0]['enrollment']['getAppConfig']+ >[0],+ ) => config,+ );+ const getNodes = jest.fn(async (ids: string[]) =>+ ids.map((id) => ({+ id,+ provider: 'test',+ model: 'test',+ tools: candidates,+ agent_ids: id === 'root' ? ['child'] : [],+ })),+ );+ const getModelsConfig = jest.fn(async () => ({ test: ['test'] }));+ const getServers = jest.fn(async () => ({ warehouse: fixture.config }));+ const resolveGraphAccess = jest.fn(async () => ({}) as AgentGraphAccessContext);+ const getScheduleById = jest.fn(async () => row);+ const getScheduleMCPCompletionState = jest.fn(async () => ({+ identity: fixture.identity,+ enrolled: false,+ }));+ const host = createScheduleMCPRuntimeHost({+ getScheduleMCPCompletionState,+ methods: { ...fixture.storage, getScheduleById },+ findUser,+ getRoleByName,+ canViewAgent: async () => true,+ enrollment: {+ findUser,+ getAppConfig,+ getModelsConfig,+ getServers,+ getNodes,+ resolveGraphAccess,+ canUseRoot: async () => true,+ },+ });+ // Confirm through the actual shipped resolver, not the synthetic fixture's resolver.+ fixture.snapshot.enrollment = null;+ const offer = await host.consent.service.view(fixture.identity);+ await host.consent.service.confirm(fixture.identity, {+ offerDigest: offer.offer!.digest,+ expectedRevision: null,+ lifetimeHours: 1,+ });+ row.mcpConsent = fixture.snapshot.enrollment!;+ const connect = jest.fn(async () => ({+ fetchToolsSnapshot: async () => ({ tools: [readTool], complete: true }),+ }));+ const preflight = createScheduleMCPPreflight({+ getRoleByName,+ getUser: findUser,+ getAppConfig,+ getModelsConfig,+ getAgentGraphNodes: getNodes,+ resolveAgentGraphAccess: resolveGraphAccess,+ getServerConfigs: getServers,+ ensureConfigServers: async () => ({ warehouse: fixture.config }),+ findPluginAuthsByKeys: async () => [],+ connect,+ execution: host.execution,+ });+ const context = createMCPRequestContext();+ const req = {+ user: fixture.user,+ _isScheduledFire: true,+ _isAgentTrigger: true,+ body: {+ agent_id: 'root',+ agentTrigger: {+ version: 1,+ event: {+ type: 'schedule.occurrence',+ occurredAt: 1000,+ source: { type: 'schedule', id: 'schedule' },+ },+ },+ },+ };+ return {+ ...fixture,+ row,+ config,+ serverConfig: fixture.config,+ host,+ context,+ req,+ preflight,+ connect,+ getRoleByName,+ findUser,+ getAppConfig,+ getScheduleById,+ getScheduleMCPCompletionState,+ setCandidates: (names: string[]) => {+ candidates = names;+ },+ check: () =>+ preflight('root', fixture.user, {+ scheduleId: 'schedule',+ stage: 'activation',+ concurrency: 3,+ }),+ };+}++afterEach(() => jest.restoreAllMocks());++it('uses the same real enrollment policy at readiness, root, and child invocation', async () => {+ const f = await setup();+ await expect(f.check()).resolves.toEqual([{ server: 'warehouse', status: 'ready' }]);+ await f.host.prepare({ req: f.req, context: f.context });+ expect(getScheduleMCPExecution(f.context)?.identity).toEqual(f.identity);+ for (const agentId of ['root', 'child']) {+ await expect(+ bindScheduledMCPInvocation(f.context, agentId, 'query')!.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.serverConfig,+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ }),+ ).resolves.toBeUndefined();+ }+});++it.each(+ [[], ['execute_code'], ['query_mcp_warehouse', 'write_action_api']].map((tools) => ({ tools })),+)(+ 'refuses prohibited or empty protected candidate sets before connecting: %s',+ async ({ tools }) => {+ const f = await setup();+ f.setCandidates(tools);+ await expect(f.check()).rejects.toMatchObject({+ outcomes: [expect.objectContaining({ automaticReplay: false })],+ });+ expect(f.connect).not.toHaveBeenCalled();+ },+);++it('returns a structured unsupported-version denial and never probes the provider', async () => {+ const f = await setup();+ f.snapshot.compatible = false;+ await expect(f.check()).rejects.toMatchObject({+ outcomes: [expect.objectContaining({ reason: 'binding_mismatch' })],+ });+ expect(f.connect).not.toHaveBeenCalled();+});++it('rebuilds the protected root on resume and refuses revoked consent even after approval', async () => {+ const f = await setup();+ const req = { user: f.user, _isScheduledFire: true, body: {} };+ await f.host.prepare({+ req,+ context: f.context,+ restoredContext: {+ scheduleId: 'schedule',+ ownerId: 'owner',+ tenantId: 'tenant',+ agentId: 'root',+ invocationMode: 'delegated',+ },+ });+ expect(getScheduleMCPExecution(f.context)?.stage).toBe('resume');+ await f.host.consent.service.revoke(f.identity, f.snapshot.enrollment!.revision);+ await expect(+ bindScheduledMCPInvocation(f.context, 'child', 'query')!.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: { type: 'streamable-http', url: 'https://resource.example/mcp' },+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ }),+ ).rejects.toMatchObject({ failure: { reason: 'consent_revoked' } });+});++it('never grants enrolled legacy resumes lacking trusted root metadata', async () => {+ const f = await setup();+ await expect(+ f.host.prepare({+ req: { user: f.user, _isScheduledFire: true, body: { agent_id: 'root' } },+ context: f.context,+ restoredJob: { scheduleId: 'schedule' },+ }),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+ f.row.mcpConsent = undefined;+ f.snapshot.enrollment = null;+ await expect(+ f.host.prepare({+ req: { user: f.user, _isScheduledFire: true, body: {} },+ context: f.context,+ restoredJob: { scheduleId: 'schedule' },+ }),+ ).resolves.toBeUndefined();+ expect(getScheduleMCPExecution(f.context)).toMatchObject({ enrolled: false });+});++it('ignores spoofed body fields on ordinary chat and refuses cross-tenant triggers', async () => {+ const f = await setup();+ await f.host.prepare({+ req: { ...f.req, _isScheduledFire: false, _isAgentTrigger: false },+ context: f.context,+ });+ expect(getScheduleMCPExecution(f.context)).toBeUndefined();+ const user = Object.assign(structuredClone(f.user), { tenantId: 'other' });+ await expect(+ f.host.prepare({ req: { ...f.req, user }, context: f.context }),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+});++it('keeps live role denial and policy removal fail-closed for enrolled schedules', async () => {+ const f = await setup();+ const role = await f.getRoleByName();+ f.getRoleByName.mockResolvedValue({ permissions: {} } as IRole);+ await expect(f.check()).rejects.toMatchObject({ code: 'mcp_permission_denied' });+ f.getRoleByName.mockResolvedValue(role);+ const schedules = f.config.interfaceConfig?.schedules;+ if (typeof schedules === 'object') delete schedules.mcpConsent?.readOnlyPolicy;+ await expect(f.check()).rejects.toMatchObject({+ outcomes: [expect.objectContaining({ reason: 'tool_policy_denied' })],+ });+});++it('does not construct the host for ordinary chats', async () => {+ const f = await setup();+ const getHost = jest.fn(() => f.host);+ await prepareScheduleMCPExecution(+ { req: { ...f.req, _isScheduledFire: false, _isAgentTrigger: false }, context: f.context },+ getHost,+ );+ expect(getHost).not.toHaveBeenCalled();+});++it('does not downgrade if enrollment disappears during run preparation', async () => {+ const f = await setup();+ f.snapshot.enrollment = null;+ await expect(f.host.prepare({ req: f.req, context: f.context })).rejects.toMatchObject({+ failure: { reason: 'consent_missing' },+ });+});++it.each([null, false, 0, ''])(+ 'does not downgrade malformed stored consent %s to legacy execution',+ async (value) => {+ const f = await setup();+ Reflect.set(f.row, 'mcpConsent', value);+ f.snapshot.enrollment = null;+ f.snapshot.compatible = false;+ await expect(f.host.prepare({ req: f.req, context: f.context })).rejects.toMatchObject({+ failure: { reason: 'binding_mismatch' },+ });+ expect(getScheduleMCPExecution(f.context)).toBeUndefined();+ },+);++it('loads one fresh principal and configuration pair per authorization, not per phase', async () => {+ const f = await setup();+ await f.host.prepare({ req: f.req, context: f.context });+ const call = () =>+ bindScheduledMCPInvocation(f.context, 'root', 'query')!.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.serverConfig,+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ });+ for (let round = 0; round < 2; round++) {+ f.findUser.mockClear();+ f.getAppConfig.mockClear();+ await call();+ expect(f.findUser).toHaveBeenCalledTimes(1);+ expect(f.getAppConfig).toHaveBeenCalledTimes(2);+ expect(f.getAppConfig).toHaveBeenCalledWith({ baseOnly: true, failClosed: true });+ expect(f.getAppConfig).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'owner', failClosed: true }),+ );+ }+ f.getRoleByName.mockResolvedValue({ permissions: {} } as IRole);+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'rbac_denied' } });+});++it('reuses the captured configuration and preserves the global stop on later calls', async () => {+ const f = await setup();+ await f.host.prepare({ req: f.req, context: f.context });+ const call = () =>+ bindScheduledMCPInvocation(f.context, 'child', 'query')!.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.serverConfig,+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ });+ await call();+ f.getAppConfig.mockImplementation(async (options) =>+ options?.baseOnly+ ? ({ ...f.config, interfaceConfig: { schedules: false } } as AppConfig)+ : f.config,+ );+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'provider_missing' } });+});++it('does not share an authority snapshot across concurrent attempts', async () => {+ const f = await setup();+ await f.host.prepare({ req: f.req, context: f.context });+ f.findUser.mockClear();+ f.getAppConfig.mockClear();+ const call = (agentId: string) =>+ bindScheduledMCPInvocation(f.context, agentId, 'query')!.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.serverConfig,+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ });+ await Promise.all([call('root'), call('child')]);+ expect(f.findUser).toHaveBeenCalledTimes(2);+ expect(f.getAppConfig).toHaveBeenCalledTimes(4);+});++it.each([false, true])(+ 'allows a paused enrolled manual run at readiness and execution, restored=%s',+ async (restored) => {+ const f = await setup();+ f.row.enabled = false;+ f.snapshot.enabled = false;+ await expect(+ f.preflight('root', f.user, { scheduleId: 'schedule', manual: true, concurrency: 2 }),+ ).resolves.toEqual([{ server: 'warehouse', status: 'ready' }]);+ await expect(+ f.preflight('root', f.user, { scheduleId: 'schedule', concurrency: 2 }),+ ).rejects.toMatchObject({+ outcomes: [expect.objectContaining({ reason: 'binding_mismatch' })],+ });+ const trigger = structuredClone(f.req);+ const manualReq = {+ ...trigger,+ body: {+ ...trigger.body,+ agentTrigger: { ...trigger.body.agentTrigger, metadata: { manual: true } },+ },+ };+ await f.host.prepare(+ restored+ ? {+ req: { user: f.user, _isScheduledFire: true, body: { manual: false } },+ context: f.context,+ restoredContext: {+ scheduleId: 'schedule',+ ownerId: 'owner',+ tenantId: 'tenant',+ agentId: 'root',+ invocationMode: 'delegated',+ },+ restoredJob: { scheduleId: 'schedule', scheduleManual: true },+ }+ : { req: manualReq, context: f.context },+ );+ const call = () =>+ bindScheduledMCPInvocation(f.context, 'child', 'query')!.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.serverConfig,+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ });+ await expect(call()).resolves.toBeUndefined();+ expect(f.storage.admitScheduleMCPConsent).toHaveBeenLastCalledWith(+ expect.objectContaining({ requireEnabled: false }),+ );+ await f.host.consent.service.revoke(f.identity, f.snapshot.enrollment!.revision);+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'consent_revoked' } });+ expect(f.row.enabled).toBe(false);+ },+);++it('does not elevate automatic paused runs from body or mutable request flags', async () => {+ const f = await setup();+ f.row.enabled = false;+ f.snapshot.enabled = false;+ const req = {+ ...f.req,+ _isManualScheduledFire: true,+ body: { ...f.req.body, manual: true, scheduleManual: true },+ };+ await f.host.prepare({ req, context: f.context });+ await expect(+ bindScheduledMCPInvocation(f.context, 'root', 'query')!.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.serverConfig,+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ }),+ ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+});++it.each(['expire', 'deny'] as const)('manual invocation still denies %s', async (mutation) => {+ const f = await executionFixture();+ f.snapshot.enabled = false;+ const execution = (await f.factory.resolve(f.identity, 'invoke', { manual: true }))!;+ f[mutation]();+ await expect(+ execution.bind('root', 'query').authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.config,+ toolName: 'query',+ loadTools: async () => ({ tools: [readTool], complete: true }),+ }),+ ).rejects.toMatchObject({+ failure: { reason: mutation === 'expire' ? 'consent_expired' : 'rbac_denied' },+ });+});++it('attaches a legacy monitor without minting a grant and fences its next tool after confirmation', async () => {+ const f = await setup();+ f.snapshot.enrollment = null;+ f.row.mcpConsent = undefined;+ await f.host.prepare({ req: f.req, context: f.context });+ const execution = getScheduleMCPExecution(f.context)!;+ expect(execution.enrolled).toBe(false);+ const guard = bindScheduledMCPInvocation(f.context, 'root', 'write')!;+ const call = () =>+ guard.authorize({+ user: f.user,+ serverName: 'warehouse',+ serverConfig: f.serverConfig,+ toolName: 'write',+ loadTools: async () => ({ tools: [], complete: true }),+ });+ await expect(call()).resolves.toBeUndefined();+ const offer = await f.host.consent.service.view(f.identity);+ await f.host.consent.service.confirm(f.identity, {+ offerDigest: offer.offer!.digest,+ expectedRevision: null,+ lifetimeHours: 1,+ });+ await expect(call()).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });+});++it.each(['schedule', 'consent', 'completion'] as const)(+ 'sanitizes %s preparation failures before tool initialization',+ async (phase) => {+ const f = await setup();+ const privateError = new Error('PRIVATE database authorization query');+ if (phase === 'schedule') f.getScheduleById.mockRejectedValue(privateError);+ if (phase === 'consent')+ jest.mocked(f.storage.readScheduleMCPConsent).mockRejectedValue(privateError);+ if (phase === 'completion') f.getScheduleMCPCompletionState.mockRejectedValue(privateError);+ const req =+ phase === 'completion'+ ? {+ ...f.req,+ _isScheduledFire: false,+ body: {+ conversationId: 'completion',+ agent_id: 'root',+ agentCompletion: {+ version: 1,+ sourceId: 'subagent-completion',+ scheduleMCPIdentity: f.identity,+ },+ },+ }+ : f.req;+ const initialize = jest.fn();+ for (const call of [+ () => f.host.prepare({ req, context: f.context }),+ () =>+ initializeWithScheduleMCPExecution({ req, context: f.context }, () => f.host, initialize),+ ]) {+ let failure: unknown;+ try {+ await call();+ } catch (error) {+ failure = error;+ }+ expect(failure).toBeInstanceOf(ScheduledMCPPolicyError);+ expect(failure).toMatchObject({+ failure: {+ reason: 'dependency_unavailable',+ recovery: 'retry_later',+ automaticReplay: false,+ },+ });+ expect(String(failure)).not.toContain('PRIVATE');+ expect(failure).not.toHaveProperty('cause');+ }+ expect(initialize).not.toHaveBeenCalled();+ },+);++it('sanitizes consent attachment failures on authenticated completion approval resumes', async () => {+ const f = await setup();+ jest+ .mocked(f.storage.readScheduleMCPConsent)+ .mockRejectedValue(new Error('PRIVATE consent query'));+ const initialize = jest.fn();+ await expect(+ initializeWithScheduleMCPExecution(+ {+ req: { ...f.req, _isAgentTrigger: false, _isScheduledFire: false },+ context: f.context,+ restoredJob: { scheduleMCPCompletion: f.identity },+ },+ () => f.host,+ initialize,+ ),+ ).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+ expect(initialize).not.toHaveBeenCalled();+});++it('sanitizes host construction and lineage-retention failures without masking provider initialization', async () => {+ const f = await setup();+ const privateError = new Error('PRIVATE dependency details');+ const initialize = jest.fn();+ const getHost = () => {+ throw privateError;+ };+ await expect(+ prepareScheduleMCPExecution({ req: f.req, context: f.context }, getHost),+ ).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+ await expect(+ initializeWithScheduleMCPExecution({ req: f.req, context: f.context }, getHost, initialize),+ ).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+ f.snapshot.enrollment = null;+ f.row.mcpConsent = undefined;+ const req = {+ ...f.req,+ _isScheduledFire: false,+ body: {+ conversationId: 'completion',+ agent_id: 'child',+ agentCompletion: {+ version: 1,+ sourceId: 'subagent-completion',+ scheduleMCPIdentity: f.identity,+ },+ },+ };+ await expect(+ initializeWithScheduleMCPExecution(+ { req, context: f.context },+ () => f.host,+ initialize,+ async () => {+ throw privateError;+ },+ ),+ ).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+ expect(initialize).not.toHaveBeenCalled();+ await expect(+ initializeWithScheduleMCPExecution(+ { req, context: f.context },+ () => f.host,+ async () => {+ throw privateError;+ },+ async () => {},+ ),+ ).rejects.toBe(privateError);+});++it('preserves typed denials and owned cancellation at the preparation boundary', async () => {+ const f = await setup();+ const controller = new AbortController();+ const typed = new ScheduledMCPPolicyError('rbac_denied', 'warehouse', 'root');+ f.getScheduleById.mockRejectedValue(typed);+ await expect(f.host.prepare({ req: f.req, context: f.context })).rejects.toBe(typed);+ const stop = new Error('Owner stopped');+ f.getScheduleById.mockImplementation(async () => {+ controller.abort(stop);+ throw stop;+ });+ await expect(+ initializeWithScheduleMCPExecution(+ { req: f.req, context: f.context, signal: controller.signal },+ () => f.host,+ jest.fn(),+ ),+ ).rejects.toBe(stop);+ const other = new Error('PRIVATE non-abort');+ const otherController = new AbortController();+ f.getScheduleById.mockImplementation(async () => {+ otherController.abort(stop);+ throw other;+ });+ await expect(+ initializeWithScheduleMCPExecution(+ { req: f.req, context: f.context, signal: otherController.signal },+ () => f.host,+ jest.fn(),+ ),+ ).rejects.toMatchObject({ failure: { reason: 'dependency_unavailable' } });+});diff --git a/packages/api/src/schedules/authorization/runtime.ts b/packages/api/src/schedules/authorization/runtime.tsnew file mode 100644index 0000000000..0052311e84--- /dev/null+++ b/packages/api/src/schedules/authorization/runtime.ts@@ -0,0 +1,263 @@+import {+ normalizeServerName,+ stripServerNamePrefix,+ scheduledMCPReadOnlyPolicySchema,+} from 'librechat-data-provider';+import type { ScheduledMCPIdentity, ScheduledMCPReadOnlyPolicy } from 'librechat-data-provider';+import type { RequestScopedMCPConnectionStore } from '~/mcp/types';+import type { ScheduleMCPCompletionLookup } from './continuation';+import type { ScheduleMCPEnrollmentDeps } from './enrollment';+import type { ScheduledTokenContext } from '../context';+import {+ isScheduledMCPCompletionRequest,+ resolveScheduleMCPCompletion,+ parseScheduleMCPCompletion,+} from './continuation';+import {+ createScheduleMCPExecution,+ scheduledMCPIdentity,+ getScheduleMCPExecution,+} from './execution';+import { readScheduleFireContext, isScheduleFireRequest } from '../trigger';+import { createScheduleMCPEnrollmentResolver } from './enrollment';+import { getAppConfigOptionsFromUser } from '~/app/service';+import { createScheduleLimitsResolver } from '../service';+import { createScheduleMCPConsentHost } from './host';+import { isOwnedAbortError } from '~/utils/errors';+import { ScheduledMCPPolicyError } from './policy';++type RuntimeRequest = Parameters<typeof readScheduleFireContext>[0] & {+ user: { id: string; tenantId?: string };+};++export function createScheduleMCPRuntimeHost(+ deps: Omit<+ Parameters<typeof createScheduleMCPConsentHost>[0],+ 'resolveEnrollment' | 'checkToolPolicy' | 'getLimits'+ > & {+ enrollment: ScheduleMCPEnrollmentDeps;+ getScheduleMCPCompletionState?: ScheduleMCPCompletionLookup;+ },+): {+ consent: ReturnType<typeof createScheduleMCPConsentHost>;+ execution: ReturnType<typeof createScheduleMCPExecution>;+ prepare: (input: {+ req: RuntimeRequest;+ signal?: AbortSignal;+ context?: RequestScopedMCPConnectionStore;+ restoredContext?: ScheduledTokenContext;+ restoredJob?: {+ scheduleId?: string;+ scheduleManual?: boolean;+ scheduleMCPCompletion?: ScheduledMCPIdentity;+ };+ }) => Promise<void>;+} {+ function createEvaluation(enrollment: ScheduleMCPEnrollmentDeps) {+ const resolveEnrollment = createScheduleMCPEnrollmentResolver(enrollment);+ const getReadOnlyPolicy = async (+ identity: ScheduledMCPIdentity,+ ): Promise<Record<string, ScheduledMCPReadOnlyPolicy> | undefined> => {+ const user = await enrollment.findUser(identity.ownerId);+ if (!user || (user.tenantId ?? null) !== identity.tenantId) return;+ user.id = identity.ownerId;+ const config = await enrollment.getAppConfig({+ ...getAppConfigOptionsFromUser(user),+ failClosed: true,+ });+ const schedules = config?.interfaceConfig?.schedules;+ const configured =+ typeof schedules === 'object' ? schedules.mcpConsent?.readOnlyPolicy : undefined;+ if (!configured) return;+ const policy: Record<string, ScheduledMCPReadOnlyPolicy> = {};+ for (const [name, value] of Object.entries(configured)) {+ const parsed = scheduledMCPReadOnlyPolicySchema.safeParse(value);+ if (parsed.success) policy[name] = parsed.data;+ }+ return policy;+ };+ const consent = createScheduleMCPConsentHost({+ ...deps,+ findUser: enrollment.findUser,+ getLimits: createScheduleLimitsResolver((options = {}) => enrollment.getAppConfig(options)),+ resolveEnrollment,+ checkToolPolicy: async (request) => {+ const policy = (await getReadOnlyPolicy(request.identity))?.[request.resource.serverName];+ if (!policy) return false;+ return request.selection.tools.every(+ (selection) =>+ Object.keys(policy.tools).filter(+ (name) =>+ name === selection ||+ stripServerNamePrefix(name, normalizeServerName(request.resource.serverName)) ===+ selection,+ ).length === 1,+ );+ },+ });+ return { consent, getReadOnlyPolicy };+ }+ const { consent } = createEvaluation(deps.enrollment);+ const execution = createScheduleMCPExecution({+ storage: deps.methods,+ async loadAuthorization(identity) {+ // Private to this attempt. No resolved principal, config or allow decision survives it.+ const principal = deps.findUser(identity.ownerId).then((user) => {+ if (!user || (user.tenantId ?? null) !== identity.tenantId) return null;+ user.id = identity.ownerId;+ return user;+ });+ const effectiveConfig = principal.then((user) =>+ user+ ? deps.enrollment.getAppConfig({ ...getAppConfigOptionsFromUser(user), failClosed: true })+ : undefined,+ );+ const baseConfig = deps.enrollment.getAppConfig({ baseOnly: true, failClosed: true });+ const [user, config, base] = await Promise.all([principal, effectiveConfig, baseConfig]);+ const evaluation = createEvaluation({+ ...deps.enrollment,+ findUser: async () => user,+ getAppConfig: async (options) => (options?.baseOnly ? base : config),+ });+ const policy = await evaluation.getReadOnlyPolicy(identity);+ return { authority: evaluation.consent.service.authority, policy };+ },+ });+ return {+ consent,+ execution,+ prepare: (input) =>+ prepareSafely(async () => {+ const { req, context, restoredContext, restoredJob } = input;+ const completion = restoredJob?.scheduleMCPCompletion;+ if (completion !== undefined || isScheduledMCPCompletionRequest(req)) {+ if (!context) throw new ScheduledMCPPolicyError('binding_mismatch', '');+ const marker = req.body?.agentCompletion;+ if (+ marker != null &&+ (typeof marker !== 'object' ||+ !('version' in marker) ||+ marker.version !== 1 ||+ !('sourceId' in marker) ||+ !['subagent-completion', 'background-tool-completion'].includes(+ String(marker.sourceId),+ ))+ )+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ const origin =+ marker && typeof marker === 'object' && 'scheduleMCPIdentity' in marker+ ? marker.scheduleMCPIdentity+ : undefined;+ const identity =+ completion !== undefined+ ? parseScheduleMCPCompletion(completion)+ : await resolveScheduleMCPCompletion(+ {+ ownerId: req.user.id,+ tenantId: req.user.tenantId ?? null,+ scheduleMCPIdentity: origin,+ },+ deps.getScheduleMCPCompletionState,+ );+ if (!identity) return;+ if (identity.ownerId !== req.user.id || identity.tenantId !== (req.user.tenantId ?? null))+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ await execution.attach(+ context,+ identity,+ completion !== undefined ? 'resume' : 'invoke',+ false,+ { legacy: true },+ );+ if (!getScheduleMCPExecution(context))+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ return;+ }+ if (!isScheduleFireRequest(req)) return;+ const fire = readScheduleFireContext(req);+ const scheduleId =+ restoredContext?.scheduleId ?? fire?.scheduleId ?? restoredJob?.scheduleId;+ if (!scheduleId || !context) throw new ScheduledMCPPolicyError('binding_mismatch', '');+ const row = await deps.methods.getScheduleById(scheduleId, req.user.id);+ if (!row || (row.tenantId ?? null) !== (req.user.tenantId ?? null))+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ const enrolled = row.mcpConsent !== undefined;+ const rootId =+ restoredContext?.agentId ??+ (fire ? req.body?.agent_id : undefined) ??+ (!enrolled ? row.agent_id : undefined);+ if (typeof rootId !== 'string' || rootId !== row.agent_id)+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ const identity = scheduledMCPIdentity({+ scheduleId,+ ownerId: req.user.id,+ tenantId: req.user.tenantId,+ agentId: rootId,+ invocationMode: 'delegated',+ });+ if (+ restoredContext &&+ (restoredContext.ownerId !== req.user.id ||+ (restoredContext.tenantId ?? null) !== (req.user.tenantId ?? null))+ )+ throw new ScheduledMCPPolicyError('binding_mismatch', '');+ await execution.attach(context, identity, restoredContext ? 'resume' : 'invoke', enrolled, {+ legacy: !enrolled,+ manual: restoredContext+ ? restoredJob?.scheduleId === scheduleId && restoredJob.scheduleManual === true+ : fire?.manual === true,+ });+ }, input.signal),+ };+}++/** Ordinary chats do not construct scheduling dependencies or perform schedule reads. */+export async function prepareScheduleMCPExecution(+ input: Parameters<ReturnType<typeof createScheduleMCPRuntimeHost>['prepare']>[0],+ getHost: () => Pick<ReturnType<typeof createScheduleMCPRuntimeHost>, 'prepare'>,+): Promise<void> {+ if (+ input.restoredJob?.scheduleMCPCompletion === undefined &&+ !isScheduleFireRequest(input.req) &&+ !isScheduledMCPCompletionRequest(input.req)+ )+ return;+ await prepareSafely(() => getHost().prepare(input), input.signal);+}++/** Ordinary startup keeps its original synchronous admission of independent reads. */+export function initializeWithScheduleMCPExecution<T>(+ input: Parameters<ReturnType<typeof createScheduleMCPRuntimeHost>['prepare']>[0],+ getHost: () => Pick<ReturnType<typeof createScheduleMCPRuntimeHost>, 'prepare'>,+ initialize: () => Promise<T>,+ retainCompletion?: (identity: ScheduledMCPIdentity) => Promise<void>,+): Promise<T> {+ if (+ input.restoredJob?.scheduleMCPCompletion === undefined &&+ !isScheduleFireRequest(input.req) &&+ !isScheduledMCPCompletionRequest(input.req)+ )+ return initialize();+ return prepareSafely(async () => {+ await getHost().prepare(input);+ const execution = getScheduleMCPExecution(input.context);+ if (+ isScheduledMCPCompletionRequest(input.req) &&+ execution &&+ input.restoredJob?.scheduleMCPCompletion === undefined+ )+ await retainCompletion?.(execution.identity);+ }, input.signal).then(initialize);+}++/** Only authorization preparation is projected; provider failures remain caller-owned. */+async function prepareSafely(operation: () => Promise<void>, signal?: AbortSignal): Promise<void> {+ try {+ signal?.throwIfAborted();+ await operation();+ signal?.throwIfAborted();+ } catch (error) {+ if (error instanceof ScheduledMCPPolicyError || isOwnedAbortError(error, signal)) throw error;+ throw new ScheduledMCPPolicyError('dependency_unavailable', '');+ }+}diff --git a/packages/api/src/schedules/authorization/service.ts b/packages/api/src/schedules/authorization/service.tsindex fe961e70cb..37dbefb11f 100644--- a/packages/api/src/schedules/authorization/service.ts+++ b/packages/api/src/schedules/authorization/service.ts@@ -298,14 +298,21 @@ export function createScheduleMCPConsentService(if (request.resource.credentialMode === 'browser_bearer') return denial('unsupported_mode');if (now() >= consent.absoluteExpiresAtMs) return denial('consent_expired');if (- !snapshot!.enabled ||+ (!snapshot!.enabled && request.stage !== 'activation' && request.manual !== true) ||snapshot!.agentId !== request.identity.agentId ||enrollment!.scheduleRevision !== snapshot!.configRevision ||!identityMatches(consent.identity, request.identity) ||!sameResource(consent.resource, request.resource))return denial('binding_mismatch');- const targets = canonicalTargets(await deps.resolveEnrollment(request.identity, options));+ let targets: ScheduledMCPTarget[];+ try {+ targets = canonicalTargets(await deps.resolveEnrollment(request.identity, options));+ } catch (error) {+ if (error instanceof ScheduleMCPConsentError)+ return denial(error.code === 'consent_forbidden' ? 'rbac_denied' : 'binding_mismatch');+ throw error;+ }const target = targets.find((t) => t.resource.serverName === request.resource.serverName);if (!target ||@@ -334,6 +341,7 @@ export function createScheduleMCPConsentService(expectedConfigRevision: snapshot!.configRevision,revision: enrollment!.revision,consentId: consent.id,+ requireEnabled: request.stage !== 'activation' && request.manual !== true,});if (!admitted) {const latest = await authority.lookupConsent(request.identity, request.resource, options);@@ -342,6 +350,8 @@ export function createScheduleMCPConsentService(if (now() >= latest.consent.absoluteExpiresAtMs) return denial('consent_expired');return denial('binding_mismatch');}+ if (options.signal?.aborted) return { state: 'cancelled' };+ if (now() >= consent.absoluteExpiresAtMs) return denial('consent_expired');return {state: 'authorized',consentId: consent.id,diff --git a/packages/api/src/schedules/engine.spec.ts b/packages/api/src/schedules/engine.spec.tsindex 5698bc3a72..c85dd20ee1 100644--- a/packages/api/src/schedules/engine.spec.ts+++ b/packages/api/src/schedules/engine.spec.ts@@ -746,6 +746,60 @@ describe('reconciliation preserves the intended outcome', () => {* `success` from it turned a transient outcome-write failure into a reset of the very* streaks that drive insufficient_balance and too_many_failures auto-disable.*/+ it('does not copy denial evidence from a replacement occurrence at the same stream', async () => {+ const methods = makeMethods(makeClaimedSchedule());+ (methods.getRunsForReconciliation as jest.Mock).mockResolvedValue([unsettledRun()]);+ const failure = {+ server: '',+ reason: 'tool_policy_denied' as const,+ status: 'mcp_permission_denied' as const,+ automaticReplay: false as const,+ };+ await tickOnce(+ makeDeps(methods, {+ getJobStatus: async () => ({+ status: 'complete',+ scheduleId: 'other',+ scheduledFor: scheduledFor.toISOString(),+ scheduleMCPFailure: failure,+ }),+ }),+ );+ expect(methods.recordRunOutcome).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'interrupted' }),+ );+ expect(methods.recordRunOutcome).not.toHaveBeenCalledWith(+ expect.objectContaining({ mcp: expect.anything() }),+ );+ });++ it('passes job-retained MCP denial evidence to crash-recovery settlement', async () => {+ const methods = makeMethods(makeClaimedSchedule());+ (methods.getRunsForReconciliation as jest.Mock).mockResolvedValue([unsettledRun()]);+ const failure = {+ server: '',+ agentId: 'child',+ reason: 'tool_policy_denied' as const,+ status: 'mcp_permission_denied' as const,+ recovery: 'configure' as const,+ automaticReplay: false as const,+ };+ await tickOnce(+ makeDeps(methods, {+ getJobStatus: async () => ({+ status: 'complete',+ scheduleId: 'sched-1',+ scheduledFor: scheduledFor.toISOString(),+ scheduleMCPFailure: failure,+ }),+ clearReconciledJob: async () => undefined,+ }),+ );+ expect(methods.recordRunOutcome).toHaveBeenCalledWith(+ expect.objectContaining({ mcp: [failure] }),+ );+ });+it('recovers a balance refusal as skipped_balance, not success', async () => {const methods = makeMethods(makeClaimedSchedule());(methods.getRunsForReconciliation as jest.Mock).mockResolvedValue([unsettledRun()]);diff --git a/packages/api/src/schedules/engine.ts b/packages/api/src/schedules/engine.tsindex e32aed21e4..c99dc08125 100644--- a/packages/api/src/schedules/engine.ts+++ b/packages/api/src/schedules/engine.ts@@ -102,7 +102,12 @@ export function startScheduleEngine(deps: ScheduleEngineDeps): ScheduleEngine {conversationId: opts?.omitConversationId ? undefined : run.conversationId,clearConversationId: opts?.omitConversationId,error,- ...(run.mcp ? { mcp: run.mcp } : {}),+ ...((run.mcp || jobState?.scheduleMCPFailure) && {+ mcp: [+ ...(run.mcp ?? []),+ ...(jobState?.scheduleMCPFailure ? [jobState.scheduleMCPFailure] : []),+ ],+ }),autoDisableAfterFailures: runLimits.autoDisableAfterFailures,});// Admission-only rows never reached the delivery or generation layers.@@ -115,7 +120,8 @@ export function startScheduleEngine(deps: ScheduleEngineDeps): ScheduleEngine {continue;}jobState = run.conversationId ? await deps.getJobStatus(run.conversationId) : null;- const jobStatus = jobIdentityMatches(jobState, run) ? jobState!.status : null;+ if (!jobIdentityMatches(jobState, run)) jobState = null;+ const jobStatus = jobState?.status ?? null;const ageMs = Date.now() - (run.firedAt?.getTime() ?? 0);// The clear runs AFTER finalize (the retained job is the only evidence if// the finalize write fails), which means a clear that keeps failing has nodiff --git a/packages/api/src/schedules/fire.spec.ts b/packages/api/src/schedules/fire.spec.tsindex a2073f5f50..e21ebffeb9 100644--- a/packages/api/src/schedules/fire.spec.ts+++ b/packages/api/src/schedules/fire.spec.ts@@ -355,13 +355,20 @@ describe('fireSchedule', () => {it('marks a Run Now trigger as manual for downstream limiter policy', async () => {const { methods } = makeMethods();+ const deps = makeDeps(methods);+ const preflight = jest.spyOn(deps, 'preflightMCP');const enqueueTrigger = jest.fn<ReturnType<ScheduleEngineDeps['enqueueTrigger']>,Parameters<ScheduleEngineDeps['enqueueTrigger']>>(async () => undefined);- await fireSchedule(makeDeps(methods, { enqueueTrigger }), makeSchedule(), LIMITS, dueAt(), {+ await fireSchedule({ ...deps, enqueueTrigger }, makeSchedule(), LIMITS, dueAt(), {manual: true,});+ expect(preflight).toHaveBeenCalledWith(+ 'agent-1',+ expect.anything(),+ expect.objectContaining({ manual: true }),+ );const envelope = enqueueTrigger.mock.calls[0][0];expect(envelope).toMatchObject({mode: 'fire',diff --git a/packages/api/src/schedules/fire.ts b/packages/api/src/schedules/fire.tsindex 64f63a8bdb..48ad22cf7a 100644--- a/packages/api/src/schedules/fire.ts+++ b/packages/api/src/schedules/fire.ts@@ -449,6 +449,7 @@ export async function fireSchedule(Math.min(ownerLimits.mcpPreflightTimeoutMs, deploymentLimits.mcpPreflightTimeoutMs);mcp = await deps.preflightMCP(schedule.agent_id, user, {scheduleId: schedule.id,+ ...(options?.manual === true && { manual: true }),signal: options?.signal,concurrency: Math.min(ownerLimits.mcpPreflightConcurrency,diff --git a/packages/api/src/schedules/handlers.ts b/packages/api/src/schedules/handlers.tsindex 8df26b8a20..27f111e58b 100644--- a/packages/api/src/schedules/handlers.ts+++ b/packages/api/src/schedules/handlers.ts@@ -399,6 +399,7 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHtry {await deps.preflightMCP(agentId, requestUser(req), {scheduleId,+ stage: 'activation',signal,concurrency: limits.mcpPreflightConcurrency,deadlineMs: Date.now() + limits.mcpPreflightTimeoutMs,@@ -1113,6 +1114,13 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH// loser simply retries against fresh state.const schedule = await deps.methods.updateScheduleById(existing.id, user.id, update, unset, {expectedConfigRevision: existing.configRevision,+ ...(existing.mcpConsent &&+ existing.mcpConsent.scheduleRevision === existing.configRevision &&+ Object.keys(editedFields).every((key) => key === 'enabled') &&+ !clearsProject &&+ (chatProjectId == null || chatProjectId === existing.chatProjectId) && {+ preserveMCPConsentRevision: existing.mcpConsent.revision,+ }),});if (schedule == null) {// Either the row is gone, or a concurrent edit moved the revision. Distinguishdiff --git a/packages/api/src/schedules/index.ts b/packages/api/src/schedules/index.tsindex 554a154d89..04772e4356 100644--- a/packages/api/src/schedules/index.ts+++ b/packages/api/src/schedules/index.ts@@ -16,3 +16,8 @@ export * from './authorization/handlers';export type * from './authorization/contract';export * from './authorization/enrollment';+export * from './authorization/execution';+export * from './authorization/runtime';+export * from './authorization/policy';++export * from './authorization/continuation';diff --git a/packages/api/src/schedules/mcp.ts b/packages/api/src/schedules/mcp.tsindex 6e15ef5a9f..92477e09b3 100644--- a/packages/api/src/schedules/mcp.ts+++ b/packages/api/src/schedules/mcp.ts@@ -8,6 +8,7 @@ import {buildServerNameAliases,normalizeMCPToolKey,normalizeServerName,+ stripServerNamePrefix,} from 'librechat-data-provider';import type {IUser,@@ -22,6 +23,7 @@ import type {UpstreamTokenProviderResolver,UpstreamTokenTarget,} from '../mcp/oauth/obo';+import type { ScheduleMCPExecution, createScheduleMCPExecution } from './authorization/execution';import type { ParsedServerConfig, UserMCPConnectionOptions } from '../mcp/types';import type { CheckAccessParams } from '../middleware/access';import type { MCPToolsSnapshot } from '../mcp/connection';@@ -39,6 +41,7 @@ import {findShadowedServerNames,createDeadlineAbortSignal,} from '../mcp/utils';+import { ScheduledMCPPolicyError, isScheduledMCPCandidate } from './authorization/policy';import { MCPConfigInitializationCanceledError } from '../mcp/registry/MCPServersRegistry';import { createMCPRequestContext, cleanupMCPRequestContext } from '../mcp/request';import { isScheduleFireRequest, readScheduleFireContext } from './trigger';@@ -184,6 +187,7 @@ interface ScheduleMCPDeps {) => Promise<Record<string, ParsedServerConfig>>;findPluginAuthsByKeys: PluginAuthMethods['findPluginAuthsByKeys'];resolveUpstreamTokenProvider?: HostUpstreamTokenProviderResolver;+ execution?: ReturnType<typeof createScheduleMCPExecution>;connect: (options: UserMCPConnectionOptions) => Promise<{fetchToolsSnapshot: (deadlineMs?: number, signal?: AbortSignal) => Promise<MCPToolsSnapshot>;}>;@@ -194,6 +198,26 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPrconst sharedProbeLimit = createConcurrencyLimiter(MAX_SHARED_MCP_PREFLIGHT_CONCURRENCY);const runPreflight: ScheduleMCPPreflight = async (agentId, principal, options) => {const signal = options.signal;+ let execution: ScheduleMCPExecution | undefined;+ try {+ execution =+ options.scheduleId && deps.execution+ ? await deps.execution.resolve(+ {+ scheduleId: options.scheduleId,+ ownerId: principal.id,+ tenantId: principal.tenantId ?? null,+ agentId,+ invocationMode: 'delegated',+ },+ options.stage ?? 'invoke',+ { manual: options.manual === true },+ )+ : undefined;+ } catch (error) {+ if (error instanceof ScheduledMCPPolicyError) throw new ScheduleMCPError(error.outcomes);+ throw error;+ }const throwIfAborted = () => {if (signal?.aborted) throw signal.reason ?? new Error('MCP preflight aborted');};@@ -210,7 +234,7 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPr});return appConfig;};- const { tools, serverHints } = await resolveScheduledMCPRequirements(+ const { tools, serverHints, candidates } = await resolveScheduledMCPRequirements(agentId,user,deps,@@ -222,6 +246,18 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPrname.includes(Constants.mcp_delimiter) &&!name.startsWith(`${Constants.mcp_server}${Constants.mcp_delimiter}`),);+ if (execution?.enrolled) {+ const denied = candidates.find(({ name }) => !isScheduledMCPCandidate(name));+ if (denied || selectedTools.length === 0) {+ throw new ScheduleMCPError(+ new ScheduledMCPPolicyError(+ denied ? 'tool_policy_denied' : 'binding_mismatch',+ '',+ denied?.agentId ?? agentId,+ ).outcomes,+ );+ }+ }if (selectedTools.length === 0) return [];const effectiveConfig = await loadAppConfig();@@ -410,6 +446,27 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPr});const snapshot = await connection.fetchToolsSnapshot(options.deadlineMs, signal);if (snapshot.authenticationError) throw snapshot.authenticationError;+ if (execution) {+ for (const [toolKey, owners] of toolAgentIds.get(server) ?? []) {+ const [selectionName] = splitMCPToolKey(toolKey, authoritativeCandidates);+ const definitions = snapshot.tools.filter(+ (tool) =>+ tool.name === selectionName ||+ stripServerNamePrefix(tool.name, normalizeServerName(server)) ===+ selectionName,+ );+ for (const ownerId of owners) {+ await execution.bind(ownerId, selectionName).authorize({+ user,+ serverName: server,+ serverConfig,+ toolName: definitions.length === 1 ? definitions[0].name : '',+ loadTools: async () => snapshot,+ signal,+ });+ }+ }+ }const available = new Set(Object.keys(formatMCPServerTools(server, snapshot.tools)),);@@ -445,6 +502,7 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPrmissingOwners.size > 0 ? missingOwners : undefined,);} catch (error) {+ if (error instanceof ScheduledMCPPolicyError) return error.outcomes;if (error instanceof OboTokenResolutionError &&error.reason === 'missing_upstream_provider'diff --git a/packages/api/src/schedules/requirements.ts b/packages/api/src/schedules/requirements.tsindex 61699d197b..9cc71570fa 100644--- a/packages/api/src/schedules/requirements.ts+++ b/packages/api/src/schedules/requirements.ts@@ -26,6 +26,7 @@ export type ScheduleMCPGraphDeps = Pick<export interface ScheduledMCPRequirements {tools: Array<{ name: string; agentId: string }>;serverHints: Set<string>;+ candidates: Array<{ name: string; agentId: string }>;}/** The runtime's bounded graph expansion, shared by readiness and enrollment metadata. */@@ -41,6 +42,7 @@ export async function resolveScheduledMCPRequirements(};throwIfAborted();const tools: Array<{ name: string; agentId: string }> = [];+ const candidates: Array<{ name: string; agentId: string }> = [];const serverHints = new Set<string>();const graphEdges: NonNullable<AgentGraphNode['edges']> = [];const explicitSeeds = new Set<string>([agentId]);@@ -336,6 +338,7 @@ export async function resolveScheduledMCPRequirements(for (const id of reachable) {const agent = accessibleById.get(id);if (!agent || !expanded.has(id)) continue;+ candidates.push(...(agent.tools ?? []).map((name) => ({ name, agentId: agent.id })));tools.push(...(agent.tools ?? []).filter((tool) => !isActionTool(tool))@@ -343,5 +346,5 @@ export async function resolveScheduledMCPRequirements();for (const name of agent.mcpServerNames ?? []) serverHints.add(name);}- return { tools, serverHints };+ return { tools, serverHints, candidates };}diff --git a/packages/api/src/schedules/service.spec.ts b/packages/api/src/schedules/service.spec.tsindex 5251ddd7ce..23c29e3ab2 100644--- a/packages/api/src/schedules/service.spec.ts+++ b/packages/api/src/schedules/service.spec.ts@@ -2,11 +2,12 @@ import { logger } from '@librechat/data-schemas';import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';import type { SchedulesServiceDeps } from './service';import { createSchedulesService, recordScheduledMCPToolAuthFailure } from './service';+import { ScheduledMCPPolicyError } from './authorization/policy';import { OboTokenResolutionError } from '../mcp/oauth/obo';import { isShutdownInProgress } from '../app/shutdown';/** Swappable per test: null keeps the no-job-store harness the drain tests rely on. */-let mockJobStore: { getJob: jest.Mock; deleteJob?: jest.Mock } | null = null;+let mockJobStore: { getJob: jest.Mock; deleteJob?: jest.Mock; updateJob?: jest.Mock } | null = null;jest.mock('../agents/checkpointer', () => ({checkpointStorageConfigs: jest.fn(async (_user, _tenant, cfg) => [cfg]),@@ -748,6 +749,7 @@ describe('scheduled OBO tool failure settlement', () => {methods.eraseScheduleIfDrained = jest.fn(async () => false);methods.getScheduleRunAbortState = jest.fn(async () => ({ status: 'started', mcp: [failure] }));const store = {+ updateJob: jest.fn(async () => undefined),getJob: jest.fn(async () => ({createdAt: 42,scheduleId: 's1',@@ -810,6 +812,68 @@ describe('scheduled OBO tool failure settlement', () => {},);+ it('records the public-safe policy denial for the exact scheduled generation', async () => {+ const { service, methods } = setup();+ const error = new ScheduledMCPPolicyError('tool_policy_denied', 'Graph', 'child');+ const input = { error, streamId: 'c1', jobCreatedAt: 42, userId: 'owner', serverName: 'Graph' };+ await expect(+ recordScheduledMCPToolAuthFailure(input, () => service.recordMCPToolAuthFailure),+ ).resolves.toBe(true);+ expect(methods.recordMCPToolAuthFailure).toHaveBeenCalledWith(+ expect.objectContaining({+ outcome: {+ server: 'Graph',+ agentId: 'child',+ status: 'mcp_permission_denied',+ reason: 'tool_policy_denied',+ recovery: 'configure',+ automaticReplay: false,+ },+ }),+ );+ await expect(service.recordMCPToolAuthFailure({ ...input, jobCreatedAt: 43 })).resolves.toBe(+ false,+ );+ });++ it.each(['consent_revoked', 'tool_policy_denied', 'credential_rejected'] as const)(+ 'settles a handled %s tool denial as an error with the durable diagnosis',+ async (reason) => {+ const { service, methods } = setup();+ const error = new ScheduledMCPPolicyError(reason, 'Graph', 'child');+ const input = {+ error,+ streamId: 'c1',+ jobCreatedAt: 42,+ userId: 'owner',+ serverName: 'Graph',+ };+ await expect(+ recordScheduledMCPToolAuthFailure(input, () => service.recordMCPToolAuthFailure),+ ).resolves.toBe(true);+ methods.getScheduleRunAbortState.mockResolvedValue({+ status: 'started',+ mcp: error.outcomes,+ });+ await expect(+ service.recordScheduleOutcome({+ scheduleId: 's1',+ scheduledFor: occurrence,+ status: 'success',+ conversationId: 'c1',+ streamId: 'c1',+ jobCreatedAt: 42,+ }),+ ).resolves.toBe(true);+ expect(methods.recordRunOutcome).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'error', mcp: error.outcomes }),+ );+ expect(+ jest.requireMock('../stream/GenerationJobManager').GenerationJobManager.updateMetadata,+ ).toHaveBeenCalledWith('c1', expect.objectContaining({ scheduleOutcome: 'error' }), 42);+ },+ );+it('records a typed tool failure only for the matching scheduled generation and owner', async () => {const { service, methods, store } = setup();const source = new OboTokenResolutionError('missing_upstream_provider', 'No credentials');diff --git a/packages/api/src/schedules/service.ts b/packages/api/src/schedules/service.tsindex 57bd44c60c..e93dc37f84 100644--- a/packages/api/src/schedules/service.ts+++ b/packages/api/src/schedules/service.ts@@ -1,6 +1,9 @@-import { DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS } from 'librechat-data-provider';import { logger, runAsSystem, tenantStorage, isRuntimeDisabled } from '@librechat/data-schemas';import { getRefillEligibilityDate, Permissions, PermissionTypes } from 'librechat-data-provider';+import {+ DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS,+ isScheduleMCPAuthorizationFailure,+} from 'librechat-data-provider';import type { ScheduleMethods, AppConfig, IBalance, IChatProject } from '@librechat/data-schemas';import type { TCheckpointerConfig } from 'librechat-data-provider';import type { ScheduleMCPOutcome } from 'librechat-data-provider';@@ -17,6 +20,7 @@ import type {} from './types';import type { SerializableJobData } from '../stream/interfaces/IJobStore';import type { AgentCheckpointGeneration } from '../agents/checkpointer';+import type { ScheduleMCPExecution } from './authorization/execution';import type { BalanceUpdateFields } from '../types/balance';import type { GetAppConfigOptions } from '../app/service';import {@@ -31,8 +35,10 @@ import {captureAgentCheckpointGeneration,checkpointStorageConfigs,} from '../agents/checkpointer';+import { scheduleMCPFailurePriority } from '~/stream/scheduleFailure';import { fireSchedule, BALANCE_SKIP_DISABLE_THRESHOLD } from './fire';import { GenerationJobManager } from '../stream/GenerationJobManager';+import { ScheduledMCPPolicyError } from './authorization/policy';import { isStopConfirmed } from '../stream/interfaces/IJobStore';import { buildBalanceUpdateFields } from '../middleware/balance';import { getAppConfigOptionsFromUser } from '../app/service';@@ -202,6 +208,8 @@ export interface SchedulesService {jobCreatedAt?: number;userId?: string;serverName: string;+ /** Trusted mandatory-hook scope; transport receipts retain their existing epoch fence. */+ identity?: ScheduleMCPExecution['identity'];}) => Promise<boolean>;/*** Stamps a scheduled run's interactive Stop BEFORE the abort is signalled, so the owner@@ -298,8 +306,9 @@ export async function recordScheduledMCPToolAuthFailure(const cause = input.error instanceof Error ? input.error.cause : undefined;const missing = input.error instanceof OboTokenResolutionError ? input.error : cause;if (- !(missing instanceof OboTokenResolutionError) ||- missing.reason !== 'missing_upstream_provider' ||+ (!(input.error instanceof ScheduledMCPPolicyError) &&+ (!(missing instanceof OboTokenResolutionError) ||+ missing.reason !== 'missing_upstream_provider')) ||!input.streamId ||input.jobCreatedAt == null ||!input.userId@@ -314,6 +323,29 @@ export async function recordScheduledMCPToolAuthFailure(}}+/** Captures host scope, never model arguments or mutable runnable config. */+export function createScheduledMCPPolicyRecorder(+ execution: ScheduleMCPExecution | undefined,+ job: { streamId?: string | null; jobCreatedAt?: number; userId?: string; tenantId?: string },+ record: SchedulesService['recordMCPToolAuthFailure'],+): ((error: ScheduledMCPPolicyError) => Promise<boolean>) | undefined {+ if (!execution) return;+ const identity = Object.freeze({ ...execution.identity });+ const scope = Object.freeze({ ...job });+ return (error) => {+ if (scope.userId !== identity.ownerId || (scope.tenantId ?? null) !== identity.tenantId)+ return Promise.resolve(false);+ return record({+ error,+ identity,+ streamId: scope.streamId ?? undefined,+ jobCreatedAt: scope.jobCreatedAt,+ userId: identity.ownerId,+ serverName: error.outcomes[0].server,+ });+ };+}+/** Test-only overrides for the service's bounded waits (drains, barriers). */export interface ScheduleServiceTimings {drainTimeoutMs?: number;@@ -327,40 +359,14 @@ export interface ScheduleServiceTimings {* own engine singleton and job-store-shared flag, so state never leaks between* instances.*/-export function createSchedulesService(- deps: SchedulesServiceDeps,- timings?: ScheduleServiceTimings,-): SchedulesService {- const { methods } = deps;-- // Fail LOUDLY at construction, not per-fire. The JS adapter (api/server/services/- // Schedules) is not typechecked against SchedulesServiceDeps, so a missing dep would- // otherwise surface only as a `deps.X is not a function` deep inside a live fire —- // which is exactly how the deletion-barrier probe shipped unwired twice.- const REQUIRED_DEPS: Array<keyof SchedulesServiceDeps> = [- 'methods',- 'getAppConfig',- 'findUserById',- 'findBalance',- 'upsertBalance',- 'initializeNullBalance',- 'resolveAgentFireAccess',- 'getChatProject',- 'isUserDeleting',- 'enqueueAgentTrigger',- 'getTriggerDelivery',- ];- for (const key of REQUIRED_DEPS) {- if (deps[key] == null) {- throw new Error(`createSchedulesService: missing required dependency "${key}"`);- }- }-+export function createScheduleLimitsResolver(+ getAppConfig: SchedulesServiceDeps['getAppConfig'],+): SchedulesService['getLimits'] {/*** Resolves schedule limits, honoring per-principal (role/user) config overrides* when a user is supplied (routes pass req.user, the fire path passes the owner).*/- async function getLimits(user?: ScheduleUserContext): Promise<ScheduleLimits> {+ return async function getLimits(user?: ScheduleUserContext): Promise<ScheduleLimits> {// The BASE `interface.schedules: false` is a global stop and must win over any// principal override. Without this a tenant/role/user override resolving to// enabled would let the sidebar and CRUD handlers admit schedules that@@ -373,7 +379,7 @@ export function createSchedulesService(// the engine gate (isGloballyDisabled) already uses.if (user != null &&- isRuntimeDisabled((await deps.getAppConfig({ baseOnly: true }))?.interfaceConfig?.schedules)+ isRuntimeDisabled((await getAppConfig({ baseOnly: true }))?.interfaceConfig?.schedules)) {return { ...DEFAULT_SCHEDULE_LIMITS, enabled: false };}@@ -385,8 +391,8 @@ export function createSchedulesService(// override as if it were the deployment-wide value, which is exactly what the// global cap exists to prevent an override from widening.const appConfig = user- ? await deps.getAppConfig(getAppConfigOptionsFromUser(user))- : await deps.getAppConfig({ baseOnly: true });+ ? await getAppConfig(getAppConfigOptionsFromUser(user))+ : await getAppConfig({ baseOnly: true });// The env kill switch is a GLOBAL stop and must be visible everywhere limits are// consulted (write handlers, fire path), not only at the engine tick.if (isEnabled(process.env.SCHEDULES_DISABLED)) {@@ -431,8 +437,53 @@ export function createSchedulesService(requireProject: config.requireProject === true || projectId != null,...(projectId != null && { projectId }),};+ };+}++export function createSchedulesService(+ deps: SchedulesServiceDeps,+ timings?: ScheduleServiceTimings,+): SchedulesService {+ const { methods } = deps;++ // Fail LOUDLY at construction, not per-fire. The JS adapter (api/server/services/+ // Schedules) is not typechecked against SchedulesServiceDeps, so a missing dep would+ // otherwise surface only as a `deps.X is not a function` deep inside a live fire —+ // which is exactly how the deletion-barrier probe shipped unwired twice.+ const REQUIRED_DEPS: Array<keyof SchedulesServiceDeps> = [+ 'methods',+ 'getAppConfig',+ 'findUserById',+ 'findBalance',+ 'upsertBalance',+ 'initializeNullBalance',+ 'resolveAgentFireAccess',+ 'getChatProject',+ 'isUserDeleting',+ 'enqueueAgentTrigger',+ 'getTriggerDelivery',+ ];+ for (const key of REQUIRED_DEPS) {+ if (deps[key] == null) {+ throw new Error(`createSchedulesService: missing required dependency "${key}"`);+ }}+ const getLimits = createScheduleLimitsResolver(deps.getAppConfig);+ // Recovery evidence, not an allow cache. Only an undurable active generation retains an entry.+ const pendingMCPFailures = new Map<+ string,+ {+ outcome: ScheduleMCPOutcome;+ identity: ScheduleMCPExecution['identity'];+ }+ >();+ const failureKey = (streamId: string, epoch: number) => JSON.stringify([streamId, epoch]);+ const preferFailure = (previous: ScheduleMCPOutcome | undefined, next: ScheduleMCPOutcome) =>+ !previous || scheduleMCPFailurePriority(next) > scheduleMCPFailurePriority(previous)+ ? next+ : previous;+const MANUAL_RUN_LEASE_MS = 5 * 60 * 1000;// Bounded wait for aborted scheduled runs to settle during account-deletion quiesce,// before the message/conversation cascade runs. Long enough to cover a generation that@@ -602,6 +653,14 @@ export function createSchedulesService(if (job == null) {return null;}+ const pending = pendingMCPFailures.get(failureKey(conversationId, job.createdAt));+ const retained =+ pending &&+ job.scheduleId === pending.identity.scheduleId &&+ job.userId === pending.identity.ownerId &&+ (job.tenantId ?? null) === pending.identity.tenantId+ ? preferFailure(job.scheduleMCPFailure, pending.outcome)+ : job.scheduleMCPFailure;return {status: job.status,createdAt: job.createdAt,@@ -614,6 +673,7 @@ export function createSchedulesService(...(job.scheduleOutcomeError != null && {scheduleOutcomeError: job.scheduleOutcomeError,}),+ ...(retained && { scheduleMCPFailure: retained }),};},abortScheduledJob: async (conversationId, identity, options) => {@@ -855,35 +915,99 @@ export function createSchedulesService(jobCreatedAt,userId,serverName,+ identity,}: Parameters<SchedulesService['recordMCPToolAuthFailure']>[0]): Promise<boolean> {const cause = error instanceof Error ? error.cause : undefined;const missing = error instanceof OboTokenResolutionError ? error : cause;if (- !(missing instanceof OboTokenResolutionError) ||- missing.reason !== 'missing_upstream_provider' ||+ (!(error instanceof ScheduledMCPPolicyError) &&+ (!(missing instanceof OboTokenResolutionError) ||+ missing.reason !== 'missing_upstream_provider')) ||!streamId ||jobCreatedAt == null ||!userId) {return false;}- const job = await GenerationJobManager.getJobStore()?.getJob(streamId);+ const key = failureKey(streamId, jobCreatedAt);+ if (error instanceof ScheduledMCPPolicyError && identity)+ pendingMCPFailures.set(key, {+ outcome: preferFailure(pendingMCPFailures.get(key)?.outcome, error.outcomes[0]),+ identity: Object.freeze({ ...identity }),+ });+ const store = GenerationJobManager.getJobStore();+ const job = await store?.getJob(streamId);if (job?.createdAt !== jobCreatedAt ||job.userId !== userId ||!job.scheduleId ||!job.scheduledFor ||- !job.conversationId+ !job.conversationId ||+ (identity != null &&+ (job.scheduleId !== identity.scheduleId ||+ job.userId !== identity.ownerId ||+ (job.tenantId ?? null) !== identity.tenantId ||+ (job.agent_id != null && job.agent_id !== identity.agentId)))) {+ pendingMCPFailures.delete(key);return false;}- return methods.recordMCPToolAuthFailure({+ const input = {scheduleId: job.scheduleId,scheduledFor: new Date(job.scheduledFor),conversationId: job.conversationId,...(job.tenantId ? { tenantId: job.tenantId } : {}),server: serverName,+ ...(error instanceof ScheduledMCPPolicyError && { outcome: error.outcomes[0] }),+ };+ if (!(error instanceof ScheduledMCPPolicyError)) return methods.recordMCPToolAuthFailure(input);+ const outcome = preferFailure(+ job.scheduleMCPFailure,+ pendingMCPFailures.get(key)?.outcome ?? error.outcomes[0],+ );+ pendingMCPFailures.set(key, {+ outcome,+ identity: identity ?? {+ scheduleId: job.scheduleId,+ ownerId: userId,+ tenantId: job.tenantId ?? null,+ agentId: job.agent_id ?? '',+ invocationMode: 'delegated',+ },});+ const writes = await Promise.allSettled([+ store.updateJob(+ streamId,+ {+ scheduleMCPFailure: outcome,+ preserveForScheduleReconcile: true,+ scheduleOutcome: 'error',+ scheduleOutcomeError: `${outcome.status}: ${JSON.stringify([outcome])}`,+ },+ jobCreatedAt,+ ),+ methods.recordMCPToolAuthFailure({ ...input, outcome }),+ ]);+ let jobRetained = false;+ if (writes[0].status === 'fulfilled') {+ const latest = await store.getJob(streamId).catch(() => null);+ jobRetained =+ latest?.createdAt === jobCreatedAt &&+ latest.scheduleId === job.scheduleId &&+ latest.scheduledFor === job.scheduledFor &&+ latest.userId === userId &&+ (latest.tenantId ?? null) === (job.tenantId ?? null) &&+ scheduleMCPFailurePriority(latest.scheduleMCPFailure) >=+ scheduleMCPFailurePriority(outcome);+ }+ if (jobRetained || (writes[1].status === 'fulfilled' && writes[1].value)) {+ const pending = pendingMCPFailures.get(key);+ if (scheduleMCPFailurePriority(pending?.outcome) <= scheduleMCPFailurePriority(outcome))+ pendingMCPFailures.delete(key);+ return true;+ }+ logger.warn('[schedules] MCP denial evidence awaiting durable recovery');+ return false;}const OUTCOME_RETRY_ATTEMPTS = 3;@@ -919,7 +1043,7 @@ export function createSchedulesService() {// Cleared to settle: no Stop owns the run, it acknowledged, or its owner is past// the stale cutoff and is presumed dead (the bounded recovery path).- return state?.mcp?.filter((item) => item.detail === 'unattended_auth_required') ?? [];+ return state?.mcp?.filter(isScheduleMCPAuthorizationFailure) ?? [];}if (Date.now() >= deadline) {// Still an UNACKNOWLEDGED, FRESH Stop. The poll budget expiring proves nothing about@@ -950,6 +1074,47 @@ export function createSchedulesService(}const terminal = status !== 'requires_action';let mcp: ScheduleMCPOutcome[] = [];+ const key = streamId && jobCreatedAt != null ? failureKey(streamId, jobCreatedAt) : undefined;+ let retained: ScheduleMCPOutcome | undefined;+ if (streamId && jobCreatedAt != null) {+ try {+ const job = await GenerationJobManager.getJobStore()?.getJob(streamId);+ const pending = key ? pendingMCPFailures.get(key) : undefined;+ if (pending?.identity.scheduleId === scheduleId) retained = pending.outcome;+ if (+ job?.createdAt === jobCreatedAt &&+ job.scheduleId === scheduleId &&+ new Date(job.scheduledFor ?? '').getTime() === new Date(scheduledFor).getTime() &&+ (!pending ||+ (job.userId === pending.identity.ownerId &&+ (job.tenantId ?? null) === pending.identity.tenantId &&+ (job.agent_id == null || job.agent_id === pending.identity.agentId)))+ )+ retained = pending+ ? preferFailure(job.scheduleMCPFailure, pending.outcome)+ : job.scheduleMCPFailure;+ else if (!retained && key) pendingMCPFailures.delete(key);+ } catch {+ // A known denial cannot be replaced by success while its evidence is undurable.+ if (key && pendingMCPFailures.has(key)) return false;+ logger.warn('[schedules] retained generation evidence is unavailable');+ return false;+ }+ }+ if (!terminal && retained && streamId && jobCreatedAt != null) {+ try {+ await GenerationJobManager.updateMetadata(+ streamId,+ {+ scheduleMCPFailure: retained,+ preserveForScheduleReconcile: true,+ },+ jobCreatedAt,+ );+ } catch {+ return false;+ }+ }if (terminal) {// Honor an in-flight interactive Stop's persistence before terminalizing. A deferral// is NOT a failure to record — the run is deliberately left active/preserved — but it@@ -963,6 +1128,17 @@ export function createSchedulesService(return false;}mcp = observed;+ if (+ retained &&+ !mcp.some(+ (item) =>+ item.server === retained.server &&+ item.agentId === retained.agentId &&+ item.reason === retained.reason &&+ item.status === retained.status,+ )+ )+ mcp.push(retained);}const missingAuth =mcp.length > 0 &&@@ -975,6 +1151,7 @@ export function createSchedulesService(streamId,{preserveForScheduleReconcile: true,+ ...(retained && { scheduleMCPFailure: retained }),scheduleOutcome:effectiveStatus === 'success' ||effectiveStatus === 'error' ||@@ -1012,6 +1189,7 @@ export function createSchedulesService(autoDisableAfterFailures: limits.autoDisableAfterFailures,balanceSkipDisableThreshold: BALANCE_SKIP_DISABLE_THRESHOLD,});+ if (terminal && key) pendingMCPFailures.delete(key);// ERASE-ON-SETTLE: whichever process records a run's terminal outcome also// attempts the deferred erase of a deleting schedule. This is what makes a// delete's `draining` state converge in EVERY topology — the clustereddiff --git a/packages/api/src/schedules/types.ts b/packages/api/src/schedules/types.tsindex b247c3d7e5..d017b869cc 100644--- a/packages/api/src/schedules/types.ts+++ b/packages/api/src/schedules/types.ts@@ -300,6 +300,7 @@ export interface JobState {* owner left it. See SerializableJobData.scheduleOutcome. */scheduleOutcome?: string;scheduleOutcomeError?: string;+ scheduleMCPFailure?: ScheduleMCPOutcome;preserveForScheduleReconcile?: boolean;}@@ -330,5 +331,13 @@ export type FireableSchedule = ISchedule;export type ScheduleMCPPreflight = (agentId: string,user: ScheduleUserContext,- options: { concurrency: number; signal?: AbortSignal; deadlineMs?: number; scheduleId?: string },+ options: {+ concurrency: number;+ signal?: AbortSignal;+ deadlineMs?: number;+ scheduleId?: string;+ stage?: 'activation' | 'invoke' | 'resume';+ /** Trusted fire host provenance, never a body-provided permission. */+ manual?: boolean;+ },) => Promise<ScheduleMCPOutcome[]>;diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.tsindex 71f88ae52d..4bbc4a1b47 100644--- a/packages/api/src/stream/GenerationJobManager.ts+++ b/packages/api/src/stream/GenerationJobManager.ts@@ -3073,8 +3073,10 @@ class GenerationJobManagerClass {scheduledFor: jobData.scheduledFor,scheduleConfigRevision: jobData.scheduleConfigRevision,scheduleManual: jobData.scheduleManual,+ scheduleMCPCompletion: jobData.scheduleMCPCompletion,scheduleOutcome: jobData.scheduleOutcome,scheduleOutcomeError: jobData.scheduleOutcomeError,+ scheduleMCPFailure: jobData.scheduleMCPFailure,preserveForScheduleReconcile: jobData.preserveForScheduleReconcile,// Surface deferred tools discovered before the pause so the resume route can// replay them into createRun (the rebuilt graph passes `messages: []`).diff --git a/packages/api/src/stream/__tests__/GenerationJobManager.resumeReplay.spec.ts b/packages/api/src/stream/__tests__/GenerationJobManager.resumeReplay.spec.tsindex 5456045ebb..6775cd704a 100644--- a/packages/api/src/stream/__tests__/GenerationJobManager.resumeReplay.spec.ts+++ b/packages/api/src/stream/__tests__/GenerationJobManager.resumeReplay.spec.ts@@ -658,3 +658,26 @@ describe('GenerationJobManager resume replay events', () => {expect(resumeState?.replayEvents).toEqual(expect.arrayContaining(events));});});++it('projects private completion authority for a freshly reconstructed approval job', async () => {+ const store = new InMemoryJobStore();+ const manager = createManagerWithStore(store);+ const identity = {+ scheduleId: 'schedule',+ ownerId: 'owner',+ tenantId: 'tenant',+ agentId: 'original-root',+ invocationMode: 'delegated' as const,+ };+ try {+ const job = await manager.createJob('completion', 'owner', 'completion', {+ initialMetadata: { scheduleMCPCompletion: identity },+ });+ const rebuilt = await manager.getJob('completion');+ expect(rebuilt?.metadata.scheduleMCPCompletion).toEqual(identity);+ expect(rebuilt?.metadata.scheduleId).toBeUndefined();+ expect(rebuilt?.createdAt).toBe(job.createdAt);+ } finally {+ await manager.destroy();+ }+});diff --git a/packages/api/src/stream/__tests__/RedisJobStore.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.spec.tsindex 72b873051c..ffcb5da542 100644--- a/packages/api/src/stream/__tests__/RedisJobStore.spec.ts+++ b/packages/api/src/stream/__tests__/RedisJobStore.spec.ts@@ -342,11 +342,26 @@ describe('RedisJobStore', () => {agentEventInvocationGenerationCreatedAt: 987654,agentEventDetachedActionProducerRequired: true,scheduleId: 'schedule-1',+ scheduleMCPCompletion: {+ scheduleId: 'original-schedule',+ ownerId: 'user-1',+ tenantId: null,+ agentId: 'original-root',+ invocationMode: 'delegated',+ },scheduledFor: '2026-08-17T12:00:00.000Z',scheduleConfigRevision: 4,scheduleManual: false,scheduleOutcome: 'interrupted',scheduleOutcomeError: 'Schedule deleted',+ scheduleMCPFailure: {+ server: '',+ agentId: 'child',+ reason: 'tool_policy_denied',+ status: 'mcp_permission_denied',+ recovery: 'configure',+ automaticReplay: false,+ },preserveForScheduleReconcile: true,promptTokens: 0,discoveredTools: [],@@ -436,11 +451,26 @@ describe('RedisJobStore', () => {isTemporary: false,retentionExpiresAt: '2030-01-01T00:00:00.000Z',scheduleId: 'schedule-1',+ scheduleMCPCompletion: {+ scheduleId: 'original-schedule',+ ownerId: 'user-1',+ tenantId: null,+ agentId: 'original-root',+ invocationMode: 'delegated',+ },scheduledFor: '2026-08-17T12:00:00.000Z',scheduleConfigRevision: 4,scheduleManual: false,scheduleOutcome: 'interrupted',scheduleOutcomeError: 'Schedule deleted',+ scheduleMCPFailure: {+ server: '',+ agentId: 'child',+ reason: 'tool_policy_denied',+ status: 'mcp_permission_denied',+ recovery: 'configure',+ automaticReplay: false,+ },preserveForScheduleReconcile: true,promptTokens: 0,discoveredTools: [],@@ -492,6 +522,14 @@ describe('RedisJobStore', () => {scheduleManual: '0',scheduleOutcome: 'interrupted',scheduleOutcomeError: 'Schedule deleted',+ scheduleMCPFailure: JSON.stringify({+ server: '',+ agentId: 'child',+ reason: 'tool_policy_denied',+ status: 'mcp_permission_denied',+ recovery: 'configure',+ automaticReplay: false,+ }),preserveForScheduleReconcile: '1',promptTokens: '0',discoveredTools: '[]',diff --git a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.tsindex 639c93ee58..788752d7cc 100644--- a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts+++ b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts@@ -93,6 +93,71 @@ describe('RedisJobStore Integration Tests', () => {process.env = originalEnv;});+ test.each(['update', 'transition'] as const)(+ 'retains the strongest scheduled denial atomically through %s',+ async (writer) => {+ expect(ioredisClient).not.toBeNull();+ const { RedisJobStore } = await import('../implementations/RedisJobStore');+ const { ScheduledMCPPolicyError } = await import('../../schedules/authorization/policy');+ const first = new RedisJobStore(ioredisClient!);+ const second = new RedisJobStore(ioredisClient!);+ const id = 'schedule-denial';+ const job = await first.createJob(id, 'owner', id, 'tenant');+ const lineage = {+ scheduleId: 'original-schedule',+ ownerId: 'owner',+ tenantId: 'tenant',+ agentId: 'original-root',+ invocationMode: 'delegated' as const,+ };+ await first.updateJob(id, { scheduleMCPCompletion: lineage }, job.createdAt);+ expect((await second.getJob(id))?.scheduleMCPCompletion).toEqual(lineage);++ const transient = new ScheduledMCPPolicyError('dependency_unavailable', 'warehouse', 'root')+ .outcomes[0];+ const permanent = new ScheduledMCPPolicyError('binding_mismatch', 'warehouse', 'child')+ .outcomes[0];+ const patch = (scheduleMCPFailure: typeof permanent) => ({+ scheduleMCPFailure,+ preserveForScheduleReconcile: true,+ scheduleOutcome: 'error' as const,+ scheduleOutcomeError: `${scheduleMCPFailure.status}: ${JSON.stringify([scheduleMCPFailure])}`,+ });+ try {+ await first.updateJob(id, patch(permanent), job.createdAt);+ if (writer === 'update') await second.updateJob(id, patch(transient), job.createdAt);+ else+ expect(+ await second.transitionStatus(id, {+ from: 'running',+ to: 'complete',+ expectCreatedAt: job.createdAt,+ patch: patch(transient),+ }),+ ).toBe(true);+ expect(await first.getJob(id)).toMatchObject({+ scheduleMCPFailure: permanent,+ scheduleOutcome: 'error',+ scheduleOutcomeError: patch(permanent).scheduleOutcomeError,+ });+ await second.updateJob(+ id,+ patch(new ScheduledMCPPolicyError('tool_policy_denied', 'warehouse').outcomes[0]),+ job.createdAt - 1,+ );+ expect((await first.getJob(id))?.scheduleMCPFailure).toEqual(permanent);+ expect((await first.getJob(id))?.scheduleMCPCompletion).toEqual(lineage);+ await ioredisClient!.hset(`stream:{${id}}:job`, 'scheduleMCPCompletion', '{invalid');+ await expect(second.getJob(id)).rejects.toMatchObject({+ failure: { reason: 'binding_mismatch' },+ });+ } finally {+ await first.destroy();+ await second.destroy();+ }+ },+ );+test.each([false, true])('owner cleanup recovers legacy terminal membership once (detached=%s)',async (detached) => {diff --git a/packages/api/src/stream/implementations/InMemoryJobStore.ts b/packages/api/src/stream/implementations/InMemoryJobStore.tsindex 14c290c597..dbc1b96392 100644--- a/packages/api/src/stream/implementations/InMemoryJobStore.ts+++ b/packages/api/src/stream/implementations/InMemoryJobStore.ts@@ -44,6 +44,7 @@ import {RecoveredSteerPayloadMismatchError,} from '~/stream/SteerRecovery';import { createCheckpointNamespace } from '~/stream/checkpoints';+import { retainScheduleMCPFailure } from '../scheduleFailure';import { toPendingSteer } from '~/stream/SteeringLifecycle';/** Recovery window for parked steers (mirrors Redis's completed-job TTL). */@@ -724,7 +725,7 @@ export class InMemoryJobStore implements IJobStoreV2 {}// Plain field writer. Membership-aware status transitions// (running ⇄ requires_action) go solely through transitionStatus.- Object.assign(job, updates);+ Object.assign(job, retainScheduleMCPFailure(job, updates));}async markProviderExecutionDrained(@@ -801,7 +802,7 @@ export class InMemoryJobStore implements IJobStoreV2 {}job.status = args.to;if (args.patch) {- Object.assign(job, args.patch);+ Object.assign(job, retainScheduleMCPFailure(job, args.patch));}for (const field of args.clear ?? []) {delete job[field];diff --git a/packages/api/src/stream/implementations/RedisJobStore.ts b/packages/api/src/stream/implementations/RedisJobStore.tsindex 0489061deb..d873b8d821 100644--- a/packages/api/src/stream/implementations/RedisJobStore.ts+++ b/packages/api/src/stream/implementations/RedisJobStore.ts@@ -2,6 +2,8 @@ import { logger } from '@librechat/data-schemas';import { createContentAggregator } from '@librechat/agents';import {ContentTypes,+ scheduleMCPOutcomeSchema,+ isScheduleMCPAuthorizationFailure,StepEvents,getRunStepDurationMs,getRunStepCloseMetadata,@@ -51,8 +53,10 @@ import {MAX_COALESCED_EVENTS,resolveCoalesceWindowMs,} from '~/stream/internal/coalescing';+import { parseScheduleMCPCompletion } from '~/schedules/authorization/continuation';import { instrumentIORedisClient, RedisUseCases } from '~/cache/redisTelemetry';import { RecoveredSteerPayloadMismatchError } from '~/stream/SteerRecovery';+import { SCHEDULE_MCP_FAILURE_PATCH_LUA } from '../scheduleFailure';import { createCheckpointNamespace } from '~/stream/checkpoints';import { createToolTimingTracker } from '~/agents/toolTiming';import { evalScript } from '~/cache/redisScript';@@ -184,6 +188,7 @@ const JOB_CAS_LUA ='for i = 1, hdelCount do redis.call("HDEL", KEYS[1], ARGV[idx]) idx = idx + 1 end ' +'local hset = {} ' +'for i = idx, #ARGV do hset[#hset + 1] = ARGV[i] end ' ++ SCHEDULE_MCP_FAILURE_PATCH_LUA +'if #hset > 0 then redis.call("HSET", KEYS[1], unpack(hset)) end ' +'if terminal then redis.call("HSET", KEYS[1], "steersClosed", "1") end ' +// A same-status pause-barrier release does not carry pendingAction again.@@ -614,6 +619,7 @@ const JOB_UPDATE_LUA ='if ARGV[1] ~= "" and redis.call("HGET", KEYS[1], "createdAt") ~= ARGV[1] then return 0 end ' +'local hset = {} ' +'for i = 6, #ARGV do hset[#hset + 1] = ARGV[i] end ' ++ SCHEDULE_MCP_FAILURE_PATCH_LUA +'if #hset > 0 then redis.call("HSET", KEYS[1], unpack(hset)) end ' +'if ARGV[2] == "1" then ' +'local completedTtl = tonumber(ARGV[3]) ' +@@ -5403,6 +5409,10 @@ export class RedisJobStore implements IJobStoreV2 {? JSON.parse(data.agentEventSuspension): undefined,agentEventLegacyTurnToken: data.agentEventLegacyTurnToken || undefined,+ scheduleMCPCompletion:+ data.scheduleMCPCompletion === undefined+ ? undefined+ : parseScheduleMCPCompletion(data.scheduleMCPCompletion, true),scheduleId: data.scheduleId || undefined,scheduledFor: data.scheduledFor || undefined,scheduleConfigRevision: data.scheduleConfigRevision@@ -5417,6 +5427,17 @@ export class RedisJobStore implements IJobStoreV2 {? data.scheduleOutcome: undefined,scheduleOutcomeError: data.scheduleOutcomeError || undefined,+ scheduleMCPFailure: (() => {+ if (!data.scheduleMCPFailure) return;+ try {+ const parsed = scheduleMCPOutcomeSchema.safeParse(JSON.parse(data.scheduleMCPFailure));+ return parsed.success && isScheduleMCPAuthorizationFailure(parsed.data)+ ? parsed.data+ : undefined;+ } catch {+ return;+ }+ })(),preserveForScheduleReconcile:data.preserveForScheduleReconcile != null? data.preserveForScheduleReconcile === '1'diff --git a/packages/api/src/stream/interfaces/IJobStore.ts b/packages/api/src/stream/interfaces/IJobStore.tsindex 3dd497b203..5fe02cdcc7 100644--- a/packages/api/src/stream/interfaces/IJobStore.ts+++ b/packages/api/src/stream/interfaces/IJobStore.ts@@ -8,6 +8,7 @@ import type {TPendingSteer,UserSubmittedMessageFieldPath,} from 'librechat-data-provider';+import type { ScheduleMCPOutcome, ScheduledMCPIdentity } from 'librechat-data-provider';import type { RunStep, StandardGraph } from '@librechat/agents';import type { AgentEventDetachedTerminalEvidence } from '~/agents/triggers/types';import type { EarlyBufferOverflowState } from '../../types/earlyBufferRecovery';@@ -264,9 +265,13 @@ export interface SerializableJobData {scheduledFor?: string;scheduleConfigRevision?: number;scheduleManual?: boolean;+ /** Original schedule root for a legacy completion, never occurrence bookkeeping. */+ scheduleMCPCompletion?: ScheduledMCPIdentity;/** Terminal outcome evidence retained when the schedule row could not be updated. */scheduleOutcome?: 'success' | 'error' | 'interrupted' | 'skipped_balance';scheduleOutcomeError?: string;+ /** Safe invocation denial retained until schedule settlement, never tool arguments. */+ scheduleMCPFailure?: ScheduleMCPOutcome;preserveForScheduleReconcile?: boolean;/*** A terminal transition (currently approval expiry) still owes a durable host@@ -482,8 +487,10 @@ export type JobMetadataPatch = Partial<| 'scheduledFor'| 'scheduleConfigRevision'| 'scheduleManual'+ | 'scheduleMCPCompletion'| 'scheduleOutcome'| 'scheduleOutcomeError'+ | 'scheduleMCPFailure'| 'preserveForScheduleReconcile'| 'promptTokens'| 'discoveredTools'diff --git a/packages/api/src/stream/metadata.spec.ts b/packages/api/src/stream/metadata.spec.tsnew file mode 100644index 0000000000..2d7ea4e525--- /dev/null+++ b/packages/api/src/stream/metadata.spec.ts@@ -0,0 +1,55 @@+import { sanitizeJobMetadata } from './metadata';++const failure = {+ server: '',+ agentId: 'child',+ status: 'mcp_permission_denied' as const,+ reason: 'tool_policy_denied' as const,+ recovery: 'configure' as const,+ automaticReplay: false as const,+};++it('retains only safe structured schedule-denial metadata', () => {+ const outcome = { ...failure, token: 'PRIVATE', arguments: { text: 'PRIVATE' } };+ expect(sanitizeJobMetadata({ scheduleMCPFailure: outcome }).scheduleMCPFailure).toEqual(failure);+ expect(JSON.stringify(sanitizeJobMetadata({ scheduleMCPFailure: outcome }))).not.toContain(+ 'PRIVATE',+ );+});++it('does not manufacture a failure receipt from a ready or ordinary outcome', () => {+ expect(sanitizeJobMetadata({}).scheduleMCPFailure).toBeUndefined();+ expect(+ sanitizeJobMetadata({ scheduleMCPFailure: { server: 'mcp', status: 'ready' } })+ .scheduleMCPFailure,+ ).toBeUndefined();+ expect(+ sanitizeJobMetadata({ scheduleMCPFailure: { server: 'mcp', status: 'mcp_permission_denied' } })+ .scheduleMCPFailure,+ ).toBeUndefined();+});++const completion = {+ scheduleId: 'schedule',+ ownerId: 'owner',+ tenantId: 'tenant',+ agentId: 'root',+ invocationMode: 'delegated' as const,+};+it('retains validated completion-lineage identity in private metadata', () => {+ expect(sanitizeJobMetadata({ scheduleMCPCompletion: completion })).toEqual({+ scheduleMCPCompletion: completion,+ });+ expect(() =>+ sanitizeJobMetadata({ scheduleMCPCompletion: { ...completion, token: 'PRIVATE' } } as never),+ ).toThrow('binding_mismatch');+ expect(sanitizeJobMetadata({})).not.toHaveProperty('scheduleMCPCompletion');+});+it.each([null, {}, 'malformed', { ...completion, invocationMode: 'autonomous' }])(+ 'never treats invalid completion lineage as ordinary metadata: %s',+ (value) => {+ expect(() => sanitizeJobMetadata({ scheduleMCPCompletion: value } as never)).toThrow(+ 'binding_mismatch',+ );+ },+);diff --git a/packages/api/src/stream/metadata.ts b/packages/api/src/stream/metadata.tsindex a3bdbcbf04..2b2d27eb64 100644--- a/packages/api/src/stream/metadata.ts+++ b/packages/api/src/stream/metadata.ts@@ -1,5 +1,10 @@+import {+ scheduleMCPOutcomeSchema,+ isScheduleMCPAuthorizationFailure,+} from 'librechat-data-provider';import type { JobMetadataPatch } from './interfaces/IJobStore';import type { GenerationJobMetadata } from '~/types';+import { parseScheduleMCPCompletion } from '~/schedules/authorization/continuation';export function sanitizeJobMetadata(metadata: Partial<GenerationJobMetadata>): JobMetadataPatch {const patch: JobMetadataPatch = {};@@ -68,6 +73,9 @@ export function sanitizeJobMetadata(metadata: Partial<GenerationJobMetadata>): Jif (metadata.agentEventLegacyTurnToken) {patch.agentEventLegacyTurnToken = metadata.agentEventLegacyTurnToken;}+ if (metadata.scheduleMCPCompletion !== undefined) {+ patch.scheduleMCPCompletion = parseScheduleMCPCompletion(metadata.scheduleMCPCompletion);+ }if (metadata.scheduleId) {patch.scheduleId = metadata.scheduleId;}@@ -86,6 +94,11 @@ export function sanitizeJobMetadata(metadata: Partial<GenerationJobMetadata>): Jif (metadata.scheduleOutcomeError !== undefined) {patch.scheduleOutcomeError = metadata.scheduleOutcomeError;}+ if (metadata.scheduleMCPFailure !== undefined) {+ const failure = scheduleMCPOutcomeSchema.safeParse(metadata.scheduleMCPFailure);+ if (failure.success && isScheduleMCPAuthorizationFailure(failure.data))+ patch.scheduleMCPFailure = failure.data;+ }if (metadata.preserveForScheduleReconcile !== undefined) {patch.preserveForScheduleReconcile = metadata.preserveForScheduleReconcile;}diff --git a/packages/api/src/stream/scheduleFailure.ts b/packages/api/src/stream/scheduleFailure.tsnew file mode 100644index 0000000000..0f3453c660--- /dev/null+++ b/packages/api/src/stream/scheduleFailure.ts@@ -0,0 +1,61 @@+import {+ scheduleMCPOutcomeSchema,+ isScheduleMCPAuthorizationFailure,+} from 'librechat-data-provider';+import type { ScheduleMCPOutcome } from 'librechat-data-provider';+import type { SerializableJobData } from './interfaces/IJobStore';++const priorities: Record<ScheduleMCPOutcome['status'], number> = {+ ready: 0,+ mcp_unavailable: 1,+ mcp_reauth_required: 2,+ mcp_configuration_missing: 3,+ mcp_permission_denied: 4,+};++export function scheduleMCPFailurePriority(outcome?: ScheduleMCPOutcome): number {+ return outcome && isScheduleMCPAuthorizationFailure(outcome) ? priorities[outcome.status] : 0;+}++/** Called inside the in-memory writer's non-awaiting section. */+export function retainScheduleMCPFailure(+ current: SerializableJobData,+ patch: Partial<SerializableJobData>,+): Partial<SerializableJobData> {+ if (patch.scheduleMCPFailure === undefined) return patch;+ const incoming = scheduleMCPOutcomeSchema.safeParse(patch.scheduleMCPFailure);+ const retained = current.scheduleMCPFailure;+ const next =+ incoming.success && scheduleMCPFailurePriority(incoming.data) > 0 ? incoming.data : undefined;+ const failure =+ scheduleMCPFailurePriority(retained) >= scheduleMCPFailurePriority(next) ? retained : next;+ const { scheduleMCPFailure: _failure, ...rest } = patch;+ return failure+ ? {+ ...rest,+ scheduleMCPFailure: failure,+ scheduleOutcome: 'error',+ scheduleOutcomeError: `${failure.status}: ${JSON.stringify([failure])}`,+ }+ : rest;+}++/** Normalizes HSET pairs inside the already epoch-fenced Redis CAS, never a prior read. */+export const SCHEDULE_MCP_FAILURE_PATCH_LUA: string =+ 'local incomingFailure = nil ' ++ 'for i = 1, #hset, 2 do if hset[i] == "scheduleMCPFailure" then incomingFailure = hset[i + 1] end end ' ++ 'if incomingFailure then ' ++ 'local priorities = { mcp_unavailable = 1, mcp_reauth_required = 2, mcp_configuration_missing = 3, mcp_permission_denied = 4 } ' ++ 'local function priority(raw) if not raw then return 0 end local ok, value = pcall(cjson.decode, raw) ' ++ 'if not ok or type(value) ~= "table" or (value.detail ~= "unattended_auth_required" and (not value.reason or value.automaticReplay ~= false)) then return 0 end ' ++ 'return priorities[value.status] or 0 end ' ++ 'local retained = redis.call("HGET", KEYS[1], "scheduleMCPFailure") ' ++ 'local winner = priority(retained) >= priority(incomingFailure) and retained or incomingFailure ' ++ 'local filtered = {} for i = 1, #hset, 2 do local field = hset[i] ' ++ 'if field ~= "scheduleMCPFailure" and field ~= "scheduleOutcome" and field ~= "scheduleOutcomeError" then ' ++ 'filtered[#filtered + 1] = field filtered[#filtered + 1] = hset[i + 1] end end ' ++ 'if priority(winner) > 0 then local value = cjson.decode(winner) ' ++ 'filtered[#filtered + 1] = "scheduleMCPFailure" filtered[#filtered + 1] = winner ' ++ 'filtered[#filtered + 1] = "scheduleOutcome" filtered[#filtered + 1] = "error" ' ++ 'filtered[#filtered + 1] = "scheduleOutcomeError" filtered[#filtered + 1] = value.status .. ": [" .. winner .. "]" end ' ++ 'hset = filtered end ';diff --git a/packages/api/src/types/stream.ts b/packages/api/src/types/stream.tsindex d3096cb1c8..4802d79d7b 100644--- a/packages/api/src/types/stream.ts+++ b/packages/api/src/types/stream.ts@@ -2,6 +2,7 @@ import type {IAgentEventActorContextMeta,ICompactionSemanticIndexProjection,} from '@librechat/data-schemas';+import type { ScheduleMCPOutcome, ScheduledMCPIdentity } from 'librechat-data-provider';import type { Agents, UserSubmittedMessageFieldPath } from 'librechat-data-provider';import type { EventEmitter } from 'events';import type {@@ -79,10 +80,14 @@ export interface GenerationJobMetadata {scheduledFor?: string;scheduleConfigRevision?: number;scheduleManual?: boolean;+ /** Original schedule root for a legacy completion, never occurrence bookkeeping. */+ scheduleMCPCompletion?: ScheduledMCPIdentity;/** Intended terminal classification retained when Mongo outcome persistence* fails. The scheduler reconciler consumes this evidence before clearing the job. */scheduleOutcome?: 'success' | 'error' | 'interrupted' | 'skipped_balance';scheduleOutcomeError?: string;+ /** Safe invocation denial retained until schedule settlement, never tool arguments. */+ scheduleMCPFailure?: ScheduleMCPOutcome;/** Prevent normal terminal cleanup until schedule reconciliation has consumed* the retained outcome evidence. */preserveForScheduleReconcile?: boolean;diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 0952704775..86be6771e6 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -33,7 +33,10 @@ import {MIN_BALANCE_RESERVATION_TTL_MS,DEFAULT_BALANCE_RESERVATION_TTL_MS,} from './balance';-import { scheduledMCPResourceBindingSchema } from './types/scheduleConsent';+import {+ scheduledMCPResourceBindingSchema,+ scheduledMCPReadOnlyPolicySchema,+} from './types/scheduleConsent';export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_DEFAULT = 24 * 1024;export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_HARD_MAX = 64 * 1024;@@ -2682,6 +2685,8 @@ export const interfaceSchema = zenabled: z.boolean().optional(),maxLifetimeHours: z.number().int().min(1).max(8760).optional(),resources: z.record(scheduledMCPResourceBindingSchema).optional(),+ /** Trusted service declarations, keyed by raw server and upstream tool name. */+ readOnlyPolicy: z.record(scheduledMCPReadOnlyPolicySchema).optional(),}).optional(),mcpPreflightConcurrency: z.number().int().min(1).max(10).optional(),diff --git a/packages/data-provider/src/types/scheduleConsent.spec.ts b/packages/data-provider/src/types/scheduleConsent.spec.tsindex f8fcfa6487..f371454e74 100644--- a/packages/data-provider/src/types/scheduleConsent.spec.ts+++ b/packages/data-provider/src/types/scheduleConsent.spec.ts@@ -3,7 +3,9 @@ import {scheduledMCPResourceSchema,scheduledMCPIdentitySchema,scheduledMCPEnrollmentSchema,+ scheduledMCPReadOnlyPolicySchema,} from './scheduleConsent';+import { scheduleMCPOutcomeSchema, readScheduleMCPOutcomes } from './schedules';import { configSchema } from '../config';it('keeps scheduled consent opt-in and bounds its absolute lifetime', () => {@@ -67,3 +69,40 @@ it('does not accept an unknown persisted consent version', () => {.success,).toBe(false);});++it('requires an explicit read-only effect and a full-definition pin, not MCP hints', () => {+ const pin = { effect: 'read_only', definitionSha256: 'a'.repeat(64) };+ expect(scheduledMCPReadOnlyPolicySchema.safeParse({ tools: { query: pin } }).success).toBe(true);+ for (const invalid of [+ { definitionSha256: pin.definitionSha256 },+ { ...pin, effect: 'write' },+ { ...pin, definitionSha256: '' },+ { ...pin, readOnlyHint: true },+ ]) {+ expect(scheduledMCPReadOnlyPolicySchema.safeParse({ tools: { query: invalid } }).success).toBe(+ false,+ );+ }+});++it('keeps legacy statuses and projects only public-safe policy denial fields', () => {+ const outcome = {+ server: 'warehouse',+ status: 'mcp_permission_denied',+ reason: 'tool_policy_denied',+ recovery: 'configure',+ automaticReplay: false,+ };+ expect(scheduleMCPOutcomeSchema.parse({ ...outcome, providerResponse: 'secret' })).toEqual(+ outcome,+ );+ expect(readScheduleMCPOutcomes(`mcp_permission_denied: ${JSON.stringify([outcome])}`)).toEqual([+ outcome,+ ]);+ expect(scheduleMCPOutcomeSchema.safeParse({ server: 'warehouse', status: 'ready' }).success).toBe(+ true,+ );+ expect(scheduleMCPOutcomeSchema.safeParse({ ...outcome, automaticReplay: true }).success).toBe(+ false,+ );+});diff --git a/packages/data-provider/src/types/scheduleConsent.ts b/packages/data-provider/src/types/scheduleConsent.tsindex adc6cb8e95..ffec01692b 100644--- a/packages/data-provider/src/types/scheduleConsent.ts+++ b/packages/data-provider/src/types/scheduleConsent.ts@@ -23,6 +23,40 @@ const safeUrl = z}});+/** Service policy for tools whose every admitted operation is read-only. Never inferred from MCP hints. */+export const scheduledMCPReadOnlyPolicySchema = z+ .object({+ tools: z.record(+ identifier,+ z+ .object({+ effect: z.literal('read_only'),+ definitionSha256: z.string().regex(/^[a-f0-9]{64}$/),+ })+ .strict(),+ ),+ })+ .strict();+export type ScheduledMCPReadOnlyPolicy = z.infer<typeof scheduledMCPReadOnlyPolicySchema>;++export const scheduledMCPFailureReasonSchema = z.enum([+ 'consent_missing',+ 'consent_expired',+ 'consent_revoked',+ 'binding_mismatch',+ 'rbac_denied',+ 'tool_policy_denied',+ 'approval_required',+ 'credential_missing',+ 'credential_rejected',+ 'resource_permission_denied',+ 'provider_missing',+ 'resource_unverified',+ 'unsupported_mode',+ 'dependency_unavailable',+]);+export type ScheduledMCPFailureReason = z.infer<typeof scheduledMCPFailureReasonSchema>;+export const scheduledMCPIdentitySchema = z.object({scheduleId: identifier,diff --git a/packages/data-provider/src/types/schedules.spec.ts b/packages/data-provider/src/types/schedules.spec.tsindex 3514d73306..d1babeb655 100644--- a/packages/data-provider/src/types/schedules.spec.ts+++ b/packages/data-provider/src/types/schedules.spec.ts@@ -1,6 +1,7 @@import { z } from 'zod';import {getScheduleMCPDisabledReason,+ isScheduleMCPAuthorizationFailure,readScheduleMCPOutcomes,scheduleMCPOutcomeSchema,} from './schedules';@@ -32,3 +33,24 @@ it('preserves the previous wire status while providing an optional unattended-aureadScheduleMCPOutcomes(`mcp_configuration_missing: ${JSON.stringify([outcome])}`),).toEqual([outcome]);});++it('recognizes durable structured denials without treating readiness snapshots as receipts', () => {+ const failure = {+ server: 'warehouse',+ status: 'mcp_reauth_required' as const,+ reason: 'credential_rejected' as const,+ automaticReplay: false as const,+ };+ expect(isScheduleMCPAuthorizationFailure(failure)).toBe(true);+ expect(isScheduleMCPAuthorizationFailure({ ...failure, status: 'ready' })).toBe(false);+ expect(+ isScheduleMCPAuthorizationFailure({ server: 'warehouse', status: 'mcp_reauth_required' }),+ ).toBe(false);+ expect(+ isScheduleMCPAuthorizationFailure({+ server: 'warehouse',+ status: 'mcp_configuration_missing',+ detail: 'unattended_auth_required',+ }),+ ).toBe(true);+});diff --git a/packages/data-provider/src/types/schedules.ts b/packages/data-provider/src/types/schedules.tsindex 2074663768..b5a7278ed6 100644--- a/packages/data-provider/src/types/schedules.ts+++ b/packages/data-provider/src/types/schedules.ts@@ -1,4 +1,5 @@import { z } from 'zod';+import { scheduledMCPFailureReasonSchema } from './scheduleConsent';/** Cadences the dialog builds from structured pickers (hour, minute, weekday). */export const scheduleStructuredFrequencies = ['hourly', 'daily', 'weekdays', 'weekly'] as const;@@ -195,6 +196,14 @@ export type TScheduleRunNowResponse = {status: 'started';};+/** A durable invocation receipt, not a readiness snapshot or an arbitrary tool error. */+export function isScheduleMCPAuthorizationFailure(outcome: ScheduleMCPOutcome): boolean {+ return (+ outcome.detail === 'unattended_auth_required' ||+ (outcome.status !== 'ready' && outcome.reason != null && outcome.automaticReplay === false)+ );+}+/** Only structured schedule preflight failures may request immediate suspension. */export function getScheduleMCPDisabledReason(outcomes?: ScheduleMCPOutcome[],@@ -213,6 +222,9 @@ export const scheduleMCPOutcomeSchema = z.object({agentId: z.string().optional(),/** Additional diagnosis; older clients ignore unknown keys and retain the known status. */detail: z.enum(['unattended_auth_required']).optional(),+ reason: scheduledMCPFailureReasonSchema.optional(),+ recovery: z.enum(['authorize', 'configure', 'restore_permission', 'retry_later']).optional(),+ automaticReplay: z.literal(false).optional(),status: z.enum(['ready','mcp_reauth_required',diff --git a/packages/data-schemas/src/methods/schedule.methods.spec.ts b/packages/data-schemas/src/methods/schedule.methods.spec.tsindex dc4faee158..1cbf65bccc 100644--- a/packages/data-schemas/src/methods/schedule.methods.spec.ts+++ b/packages/data-schemas/src/methods/schedule.methods.spec.ts@@ -1,5 +1,6 @@import mongoose from 'mongoose';import { MongoMemoryServer } from 'mongodb-memory-server';+import { scheduledMCPFailureReasonSchema } from 'librechat-data-provider';import type { Model } from 'mongoose';import type {ISchedule,@@ -3076,12 +3077,37 @@ describe('scheduled MCP tool failure receipt', () => {});});-describe('scheduled MCP receipt settlement', () => {- const failure = {+describe.each([+ {server: 'Graph',status: 'mcp_configuration_missing' as const,detail: 'unattended_auth_required' as const,- };+ },+ {+ server: 'Graph',+ agentId: 'child',+ status: 'mcp_reauth_required' as const,+ reason: scheduledMCPFailureReasonSchema.enum.consent_revoked,+ recovery: 'authorize' as const,+ automaticReplay: false as const,+ },+ {+ server: 'Graph',+ agentId: 'child',+ status: 'mcp_permission_denied' as const,+ reason: scheduledMCPFailureReasonSchema.enum.tool_policy_denied,+ recovery: 'configure' as const,+ automaticReplay: false as const,+ },+ {+ server: 'Graph',+ agentId: 'child',+ status: 'mcp_reauth_required' as const,+ reason: scheduledMCPFailureReasonSchema.enum.credential_rejected,+ recovery: 'authorize' as const,+ automaticReplay: false as const,+ },+])('scheduled MCP receipt settlement: $reason', (failure) => {const ready = { server: 'Graph', status: 'ready' as const };it.each(['success', 'skipped_balance', 'error'] as const)(@@ -3094,6 +3120,7 @@ describe('scheduled MCP receipt settlement', () => {scheduledFor,conversationId: 'c1',server: 'Graph',+ outcome: failure,};await methods.insertScheduleRun(runData(schedule, {@@ -3127,7 +3154,7 @@ describe('scheduled MCP receipt settlement', () => {expect(result).toMatchObject({ status: 'error', bookkept: true, mcp: [ready, failure] });expect(card.lastRun).toMatchObject({ status: 'error', mcp: [ready, failure] });expect(card.enabled).toBe(false);- expect(card.disabledReason).toBe('mcp_configuration_missing');+ expect(card.disabledReason).toBe(failure.status);expect(card.failureCount).toBe(1);expect(card.balanceSkipCount).toBe(0);expect(card.lastRun?.error).toBe(@@ -3154,6 +3181,7 @@ describe('scheduled MCP receipt settlement', () => {scheduledFor,conversationId: 'c1',server: 'Graph',+ outcome: failure,}),methods.recordRunOutcome({scheduleId: schedule.id,@@ -3165,7 +3193,7 @@ describe('scheduled MCP receipt settlement', () => {const run = await getRun(schedule.id, scheduledFor);const card = await getSchedule(schedule.id);expect(run.status).toBe(recorded ? 'error' : 'success');- expect(card.disabledReason).toBe(recorded ? 'mcp_configuration_missing' : undefined);+ expect(card.disabledReason).toBe(recorded ? failure.status : undefined);expect(card.lastRun?.status).toBe(run.status);});@@ -3200,6 +3228,7 @@ describe('scheduled MCP receipt settlement', () => {scheduledFor,conversationId: 'c1',server: 'Graph',+ outcome: failure,});await Schedule.updateOne({ id: schedule.id }, { $inc: { configRevision: 1 } });@@ -3223,6 +3252,7 @@ describe('scheduled MCP receipt settlement', () => {scheduledFor,conversationId: 'c1',server: 'Graph',+ outcome: failure,});const firstWrite = jest.spyOn(Schedule, 'updateOne')@@ -3253,12 +3283,173 @@ describe('scheduled MCP receipt settlement', () => {expect((await getRun(schedule.id, scheduledFor)).bookkept).toBe(true);expect(await getSchedule(schedule.id)).toMatchObject({enabled: false,- disabledReason: 'mcp_configuration_missing',+ disabledReason: failure.status,failureCount: 1,});});});+describe('scheduled MCP mixed receipt settlement', () => {+ const transient = {+ server: 'Graph',+ agentId: 'root',+ status: 'mcp_unavailable' as const,+ reason: scheduledMCPFailureReasonSchema.enum.dependency_unavailable,+ recovery: 'retry_later' as const,+ automaticReplay: false as const,+ };+ const permanent = {+ server: 'Graph',+ agentId: 'child',+ status: 'mcp_reauth_required' as const,+ reason: scheduledMCPFailureReasonSchema.enum.binding_mismatch,+ recovery: 'authorize' as const,+ automaticReplay: false as const,+ };++ it.each(['success', 'error', 'skipped_balance'] as const)(+ 'retains the atomic union and immediately suspends on %s',+ async (status) => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-10-02T12:00:00Z');+ await methods.insertScheduleRun(+ runData(schedule, {+ scheduledFor,+ conversationId: 'c1',+ configRevision: 0,+ mcp: [transient],+ }),+ );+ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status,+ mcp: [transient, permanent, permanent],+ autoDisableAfterFailures: 99,+ });+ const result = await getRun(schedule.id, scheduledFor);+ expect(result).toMatchObject({ status: 'error', bookkept: true });+ expect(result.mcp).toEqual([transient, permanent]);+ const card = await getSchedule(schedule.id);+ expect(card).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_reauth_required',+ failureCount: 1,+ lastRun: { status: 'error', mcp: [transient, permanent] },+ });+ },+ );++ it('merges a receipt that lands after admission observed only job evidence', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-10-02T13:00:00Z');+ await methods.insertScheduleRun(+ runData(schedule, { scheduledFor, conversationId: 'c1', configRevision: 0 }),+ );+ const [recorded] = await Promise.all([+ methods.recordMCPToolAuthFailure({+ scheduleId: schedule.id,+ scheduledFor,+ conversationId: 'c1',+ server: 'Graph',+ outcome: transient,+ }),+ methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'success',+ mcp: [permanent],+ autoDisableAfterFailures: 99,+ }),+ ]);+ const run = await getRun(schedule.id, scheduledFor);+ expect(run.status).toBe('error');+ expect(run.mcp).toEqual(+ expect.arrayContaining(recorded ? [transient, permanent] : [permanent]),+ );+ expect(await getSchedule(schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_reauth_required',+ failureCount: 1,+ });+ });++ it('makes the union durable before bookkeeping, with classic operators', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-10-02T14:00:00Z');+ await methods.insertScheduleRun(+ runData(schedule, {+ scheduledFor,+ conversationId: 'c1',+ configRevision: 0,+ mcp: [transient],+ }),+ );+ const transition = jest.spyOn(ScheduleRun, 'findOneAndUpdate');+ const write = jest+ .spyOn(Schedule, 'updateOne')+ .mockRejectedValueOnce(new Error('Bookkeeping outage'));+ await expect(+ methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'success',+ mcp: [permanent],+ autoDisableAfterFailures: 99,+ }),+ ).rejects.toThrow('Bookkeeping outage');+ write.mockRestore();+ const run = await getRun(schedule.id, scheduledFor);+ expect(run).toMatchObject({ status: 'error', bookkept: false, mcp: [transient, permanent] });+ expect(transition).toHaveBeenLastCalledWith(+ expect.anything(),+ expect.objectContaining({ $addToSet: { mcp: { $each: [permanent] } } }),+ { new: true },+ );+ for (const [, mutation] of transition.mock.calls) expect(Array.isArray(mutation)).toBe(false);+ transition.mockRestore();+ const replay = {+ scheduleId: schedule.id,+ scheduledFor,+ status: 'error' as const,+ mcp: run.mcp,+ autoDisableAfterFailures: 99,+ };+ await methods.finalizeBookkeeping(replay);+ await methods.finalizeBookkeeping(replay);+ expect(await getSchedule(schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_reauth_required',+ failureCount: 1,+ });+ expect((await getRun(schedule.id, scheduledFor)).bookkept).toBe(true);+ });++ it('cannot suspend a schedule edited after the mixed-denial occurrence started', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-10-02T15:00:00Z');+ await methods.insertScheduleRun(+ runData(schedule, {+ scheduledFor,+ conversationId: 'c1',+ configRevision: 0,+ mcp: [transient],+ }),+ );+ await Schedule.updateOne({ id: schedule.id }, { $inc: { configRevision: 1 } });+ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'success',+ mcp: [permanent],+ autoDisableAfterFailures: 99,+ });+ expect((await getRun(schedule.id, scheduledFor)).mcp).toEqual([transient, permanent]);+ expect(await getSchedule(schedule.id)).toMatchObject({ enabled: true, failureCount: 0 });+ expect((await getSchedule(schedule.id)).lastRun).toBeUndefined();+ });+});+describe('scheduled MCP failure policy', () => {it.each(['mcp_reauth_required',diff --git a/packages/data-schemas/src/methods/schedule.ts b/packages/data-schemas/src/methods/schedule.tsindex dc6e29b631..e1a0c781f0 100644--- a/packages/data-schemas/src/methods/schedule.ts+++ b/packages/data-schemas/src/methods/schedule.ts@@ -1,6 +1,11 @@import { randomUUID } from 'node:crypto';-import { getScheduleMCPDisabledReason } from 'librechat-data-provider';+import {+ getScheduleMCPDisabledReason,+ isScheduleMCPAuthorizationFailure,+ scheduledMCPFailureReasonSchema,+} from 'librechat-data-provider';import type { ScheduleRunStatus, ScheduleDisabledReason } from 'librechat-data-provider';+import type { ScheduleMCPOutcome, ScheduledMCPIdentity } from 'librechat-data-provider';import type { Model, Types, AnyBulkWriteOperation } from 'mongoose';import type {ISchedule,@@ -182,6 +187,10 @@ export type ResumedRunReservation =| { conflict: 'not-paused' | 'overlap' | 'slot-taken' };export type ScheduleMethods = {+ /** Resolves live state only for a task's captured schedule identity. */+ getScheduleMCPCompletionState: (+ identity: ScheduledMCPIdentity,+ ) => Promise<{ identity: ScheduledMCPIdentity; enrolled: boolean } | null>;ensureScheduleIndexes: () => Promise<void>;createSchedule: (data: Partial<ISchedule>) => Promise<ISchedule>;createScheduleWithSlot: (@@ -193,7 +202,7 @@ export type ScheduleMethods = {userId: string | Types.ObjectId,update: Partial<ISchedule>,unset?: Record<string, 1>,- options?: { expectedConfigRevision?: number },+ options?: { expectedConfigRevision?: number; preserveMCPConsentRevision?: string },) => Promise<ISchedule | null>;deleteScheduleById: (id: string, userId: string | Types.ObjectId) => Promise<boolean>;deleteUnarmedSchedule: (@@ -275,6 +284,7 @@ export type ScheduleMethods = {conversationId: string;tenantId?: string;server: string;+ outcome?: ScheduleMCPOutcome;}) => Promise<boolean>;markRunResumeClaimed: (scheduleId: string,@@ -431,18 +441,44 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Scheunset?: Record<string, 1>,/** Optional edit-generation fence, so two overlapping owner edits cannot each* persist state derived from a row the other has already replaced. */- options?: { expectedConfigRevision?: number },+ options?: { expectedConfigRevision?: number; preserveMCPConsentRevision?: string },): Promise<ISchedule | null> {+ const preserveConsent = options?.preserveMCPConsentRevision != null;+ if (+ preserveConsent &&+ (options?.expectedConfigRevision == null ||+ Object.keys(update).some(+ (key) =>+ !['enabled', 'nextRunAt', 'failureCount', 'balanceSkipCount', 'chatProjectId'].includes(+ key,+ ),+ ) ||+ Object.keys(unset ?? {}).some((key) => key !== 'disabledReason'))+ )+ throw new Error('Consent continuity is limited to activation state');const filter = {id,user: userId,deleting: { $ne: true },+ ...(preserveConsent && {+ 'mcpConsent.version': 1,+ 'mcpConsent.revision': options!.preserveMCPConsentRevision,+ 'mcpConsent.scheduleRevision': options!.expectedConfigRevision,+ }),+ ...(preserveConsent &&+ update.chatProjectId != null && { chatProjectId: update.chatProjectId }),...(options?.expectedConfigRevision !== undefined? { configRevision: options.expectedConfigRevision }: {}),};const mutation = {- $set: { ...update, claimToken: randomUUID() },+ $set: {+ ...update,+ claimToken: randomUUID(),+ ...(preserveConsent && {+ 'mcpConsent.scheduleRevision': options!.expectedConfigRevision! + 1,+ }),+ },// The ONLY writer of configRevision: an owner edit moves the config// generation forward atomically with the claim-token rotation, so a run// that started under the old config can detect it and skip bookkeeping.@@ -1038,8 +1074,28 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Schereturn (renewed.matchedCount ?? 0) > 0;}- /** The abort-coordination view of a run row, for the generation owner's settlement- * barrier (see abortPersistedAt). */+ /** Captured origin cannot adopt a later grant or a different schedule root. */+ async function getScheduleMCPCompletionState(identity: ScheduledMCPIdentity): Promise<{+ identity: ScheduledMCPIdentity;+ enrolled: boolean;+ } | null> {+ const schedule = await Schedule()+ .findOne({ id: identity.scheduleId, user: identity.ownerId, tenantId: identity.tenantId })+ .select('agent_id mcpConsent deleting erased')+ .read('primary')+ .lean<ISchedule>();+ return {+ identity,+ enrolled:+ !schedule ||+ schedule.agent_id !== identity.agentId ||+ schedule.deleting === true ||+ schedule.erased === true ||+ schedule.mcpConsent !== undefined,+ };+ }++ /** The generation owner's abort-coordination view (see abortPersistedAt). */async function getScheduleRunAbortState(scheduleId: string,scheduledFor: Date,@@ -1129,6 +1185,7 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): ScheconversationId,tenantId,server,+ outcome,}: Parameters<ScheduleMethods['recordMCPToolAuthFailure']>[0]): Promise<boolean> {const updated = await ScheduleRun().updateOne({@@ -1140,7 +1197,11 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche},{$addToSet: {- mcp: { server, status: 'mcp_configuration_missing', detail: 'unattended_auth_required' },+ mcp: outcome ?? {+ server,+ status: 'mcp_configuration_missing',+ detail: 'unattended_auth_required',+ },},},{ timestamps: false },@@ -1505,8 +1566,19 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Scheparams.status === 'success' ||params.status === 'error' ||params.status === 'skipped_balance';- const incomingFailure =- canOverride && params.mcp?.some((item) => item.detail === 'unattended_auth_required');+ const incomingFailure = canOverride && params.mcp?.some(isScheduleMCPAuthorizationFailure);+ const receiptPredicates = [+ { 'mcp.detail': 'unattended_auth_required' },+ {+ mcp: {+ $elemMatch: {+ reason: { $in: scheduledMCPFailureReasonSchema.options },+ status: { $ne: 'ready' },+ automaticReplay: false,+ },+ },+ },+ ];const authError =params.status === 'error' && params.error? params.error@@ -1514,7 +1586,6 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Scheconst terminalUpdate = (status: RecordRunOutcomeParams['status'],error: string | undefined,- includeInputMcp: boolean,) => ({$set: {status,@@ -1524,9 +1595,10 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche? { conversationId: params.conversationId }: {}),...(error ? { error } : {}),- ...(includeInputMcp && params.mcp ? { mcp: params.mcp } : {}),...(params.durationMs != null ? { durationMs: params.durationMs } : {}),},+ // Merge in the same transition; neither a receipt race nor a crash can lose a source.+ ...(params.mcp?.length && { $addToSet: { mcp: { $each: params.mcp } } }),// Only terminal settlement releases the global capacity slot, not an abort request.$unset: {capacitySlot: 1,@@ -1541,14 +1613,13 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche.findOneAndUpdate({...runFilter,- ...(canOverride ? { 'mcp.detail': { $ne: 'unattended_auth_required' } } : {}),+ ...(canOverride ? { $nor: receiptPredicates } : {}),},terminalUpdate(incomingFailure ? 'error' : params.status,incomingFailure ? authError : params.error,- true,),- { new: false },+ { new: true },).lean<IScheduleRun>();let effectiveParams = incomingFailure@@ -1557,9 +1628,9 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Scheif (settled == null && canOverride) {settled = await ScheduleRun().findOneAndUpdate(- { ...runFilter, 'mcp.detail': 'unattended_auth_required' },- terminalUpdate('error', authError, false),- { new: false },+ { ...runFilter, $or: receiptPredicates },+ terminalUpdate('error', authError),+ { new: true },).lean<IScheduleRun>();if (settled != null) {@@ -1570,6 +1641,8 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Scheif (settled == null) {return;}+ // The post-image is the authoritative union, including receipts admitted just before this CAS.+ effectiveParams = { ...effectiveParams, mcp: settled.mcp };// SINGLE SEAM: the config fence is DERIVED here from the row being settled, not// passed in by each caller. Callers only say "this occurrence reached status X" and// structurally cannot forget a token — which is exactly how the reconcile and@@ -2219,6 +2292,7 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): SchepersistResolvedProject,getScheduleRunProject,getScheduleRunAbortState,+ getScheduleMCPCompletionState,recordMCPToolAuthFailure,markRunResumeClaimed,releaseRunResumeClaim,diff --git a/packages/data-schemas/src/methods/scheduleConsent.spec.ts b/packages/data-schemas/src/methods/scheduleConsent.spec.tsindex c007177eba..a6d1fc2166 100644--- a/packages/data-schemas/src/methods/scheduleConsent.spec.ts+++ b/packages/data-schemas/src/methods/scheduleConsent.spec.ts@@ -77,6 +77,89 @@ beforeEach(async () => {});});+it('admits a disabled row only for activation, with the same live consent fence', async () => {+ await confirm();+ await mongoose.models.Schedule.updateOne(+ { id: identity.scheduleId },+ { $set: { enabled: false } },+ );+ const input = {+ identity,+ revision: 'grant-1',+ consentId: 'consent-1',+ expectedConfigRevision: 0,+ };+ expect(await storage.admitScheduleMCPConsent(input)).toBe(false);+ expect(await storage.admitScheduleMCPConsent({ ...input, requireEnabled: false })).toBe(true);+ await storage.revokeScheduleMCPConsent(identity, 'grant-1');+ expect(await storage.admitScheduleMCPConsent({ ...input, requireEnabled: false })).toBe(false);+});++it('carries consent through activation atomically without extending its absolute expiry', async () => {+ await confirm();+ const before = await storage.readScheduleMCPConsent(identity);+ const methods = createScheduleMethods(mongoose);+ const updated = await methods.updateScheduleById(+ identity.scheduleId,+ owner,+ { enabled: false },+ undefined,+ {+ expectedConfigRevision: 0,+ preserveMCPConsentRevision: 'grant-1',+ },+ );+ expect(updated?.mcpConsent?.scheduleRevision).toBe(1);+ const after = await storage.readScheduleMCPConsent(identity);+ expect(after?.enrollment?.consents).toEqual(before?.enrollment?.consents);+ expect(after?.configRevision).toBe(1);+ expect(after?.enabled).toBe(false);+ expect(+ await storage.admitScheduleMCPConsent({+ identity,+ revision: 'grant-1',+ consentId: 'consent-1',+ expectedConfigRevision: 1,+ requireEnabled: false,+ }),+ ).toBe(true);+});++it('does not revive stale enrollment through a later enabled-state edit', async () => {+ await confirm();+ const methods = createScheduleMethods(mongoose);+ await methods.updateScheduleById(identity.scheduleId, owner, { prompt: 'Changed' }, undefined, {+ expectedConfigRevision: 0,+ });+ expect(+ await methods.updateScheduleById(identity.scheduleId, owner, { enabled: true }, undefined, {+ expectedConfigRevision: 1,+ preserveMCPConsentRevision: 'grant-1',+ }),+ ).toBeNull();+});++it('never overwrites revocation racing an activation edit or carries consent across prompt edits', async () => {+ await confirm();+ await storage.revokeScheduleMCPConsent(identity, 'grant-1');+ const methods = createScheduleMethods(mongoose);+ expect(+ await methods.updateScheduleById(identity.scheduleId, owner, { enabled: false }, undefined, {+ expectedConfigRevision: 0,+ preserveMCPConsentRevision: 'grant-1',+ }),+ ).toBeNull();+ await expect(+ methods.updateScheduleById(identity.scheduleId, owner, { prompt: 'Write now' }, undefined, {+ expectedConfigRevision: 0,+ preserveMCPConsentRevision: 'grant-1',+ }),+ ).rejects.toThrow('Consent continuity is limited to activation state');+ expect(+ (await storage.readScheduleMCPConsent(identity))?.enrollment?.consents[0].revokedAtMs,+ ).not.toBeNull();+});+const confirm = (expectedRevision: string | null = null, grant = enrollment()) =>storage.confirmScheduleMCPConsent({identity,diff --git a/packages/data-schemas/src/methods/scheduleConsent.ts b/packages/data-schemas/src/methods/scheduleConsent.tsindex d19976da4c..962159e721 100644--- a/packages/data-schemas/src/methods/scheduleConsent.ts+++ b/packages/data-schemas/src/methods/scheduleConsent.ts@@ -28,6 +28,7 @@ export interface ScheduleMCPConsentStorage {expectedConfigRevision: number;revision: string;consentId: string;+ requireEnabled?: boolean;}) => Promise<boolean>;}@@ -134,7 +135,7 @@ export function createScheduleMCPConsentStorage(...configFilter(input.expectedConfigRevision),...revisionFilter(input.revision),agent_id: input.identity.agentId,- enabled: true,+ ...(input.requireEnabled !== false && { enabled: true }),'mcpConsent.consents': {$elemMatch: { id: input.consentId, revision: input.revision, revokedAtMs: null },},diff --git a/packages/data-schemas/src/schema/schedule.ts b/packages/data-schemas/src/schema/schedule.tsindex df7b6a040e..7adf6cd9c7 100644--- a/packages/data-schemas/src/schema/schedule.ts+++ b/packages/data-schemas/src/schema/schedule.ts@@ -1,6 +1,7 @@import { Schema } from 'mongoose';import { SCHEDULE_CRON_MAX_LENGTH } from 'librechat-data-provider';import { scheduledMCPEnrollmentSchema } from 'librechat-data-provider';+import { scheduledMCPFailureReasonSchema } from 'librechat-data-provider';import type { IScheduleDocument } from '~/types/schedule';/** `cadence` is a nested path rather than a subdocument, so a validator on@@ -240,6 +241,12 @@ const scheduleSchema: Schema<IScheduleDocument> = new Schema(server: { type: String, required: true },agentId: { type: String },detail: { type: String, enum: ['unattended_auth_required'] },+ reason: { type: String, enum: scheduledMCPFailureReasonSchema.options },+ recovery: {+ type: String,+ enum: ['authorize', 'configure', 'restore_permission', 'retry_later'],+ },+ automaticReplay: { type: Boolean, enum: [false] },status: {type: String,required: true,diff --git a/packages/data-schemas/src/schema/scheduleRun.ts b/packages/data-schemas/src/schema/scheduleRun.tsindex ba685bee99..5dc918ee4b 100644--- a/packages/data-schemas/src/schema/scheduleRun.ts+++ b/packages/data-schemas/src/schema/scheduleRun.ts@@ -1,4 +1,5 @@import { Schema } from 'mongoose';+import { scheduledMCPFailureReasonSchema } from 'librechat-data-provider';import type { IScheduleRunDocument } from '~/types/schedule';const SCHEDULE_RUN_TTL_SECONDS = 90 * 24 * 60 * 60;@@ -72,6 +73,12 @@ const scheduleRunSchema: Schema<IScheduleRunDocument> = new Schema(server: { type: String, required: true },agentId: { type: String },detail: { type: String, enum: ['unattended_auth_required'] },+ reason: { type: String, enum: scheduledMCPFailureReasonSchema.options },+ recovery: {+ type: String,+ enum: ['authorize', 'configure', 'restore_permission', 'retry_later'],+ },+ automaticReplay: { type: Boolean, enum: [false] },status: {type: String,required: true,@@ -185,4 +192,7 @@ scheduleRunSchema.index({ status: 1, firedAt: 1 });// without this the round-robin rotation re-sorts the whole live set every tick.scheduleRunSchema.index({ status: 1, reconciledAt: 1, firedAt: 1 });+// Owner-scoped automatic-completion admission, including settled occurrences.+scheduleRunSchema.index({ user: 1, tenantId: 1, conversationId: 1 });+export default scheduleRunSchema;