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
📴 fix: Surface Missing Scheduled OBO Authorization (#16416)
lia-by-librechat[bot]6658e3b31408
diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex 6edf562a05..61750ac982 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -842,6 +842,8 @@ async function reconnectServer({upstreamTokenProviderResolver,recoveryPolicy,oboIdentityContext,+ streamId,+ jobCreatedAt,forceNew: true,returnOnOAuth: false,connectionTimeout: Time.THIRTY_SECONDS,@@ -1386,6 +1388,16 @@ function createToolInstance({);}+ // The schedule service checks the typed cause and verified job identity before+ // recording a durable tool failure; other tool errors are a cheap no-op.+ await require('~/server/services/Schedules').recordMCPToolAuthFailure({+ error,+ streamId,+ jobCreatedAt,+ userId,+ serverName,+ });+/** Carries the actionable re-auth message; the substring heuristic below would misreport it as an OAuth configuration problem */if (error instanceof OpenIDReauthRequiredError ||diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex 11b5328e09..487a50730b 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -87,6 +87,10 @@ jest.mock('./Tools/mcp', () => ({reinitMCPServer: jest.fn(),}));+jest.mock('~/server/services/Schedules', () => ({+ recordMCPToolAuthFailure: jest.fn(async () => true),+}));+jest.mock('./GraphTokenService', () => ({getGraphApiToken: jest.fn(),}));@@ -1544,6 +1548,44 @@ describe('User parameter passing tests', () => {});describe('createMCPTool', () => {+ it('records a typed OBO failure against the scheduled generation before returning an error', async () => {+ const user = { id: 'scheduled-owner', role: 'USER' };+ const missing = new Error('Unattended provider not configured');+ const error = Object.assign(new Error('MCP tool error'), { cause: missing });+ 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({+ user,+ toolKey: `test-tool${D}test-server`,+ provider: 'openai',+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ config: { type: 'streamable-http', url: 'https://mcp.example.com' },+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: { description: 'Test MCP', parameters: { type: 'object', properties: {} } },+ },+ },+ });+ await expect(+ tool.func({}, undefined, {+ configurable: { user },+ metadata: { provider: 'openai', thread_id: 'scheduled-conversation', run_id: 'run-1' },+ toolCall: {},+ }),+ ).rejects.toThrow();+ expect(receipt).toHaveBeenCalledWith({+ error,+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ userId: 'scheduled-owner',+ serverName: 'test-server',+ });+ });+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() };@@ -2783,6 +2825,8 @@ describe('User parameter passing tests', () => {serverName: 'server1',provider: 'anthropic',userMCPAuthMap: {},+ streamId: 'scheduled-stream',+ jobCreatedAt: 42,});// Verify all calls to reinitMCPServer had the user@@ -2790,6 +2834,8 @@ describe('User parameter passing tests', () => {reinitCalls.forEach((call) => {expect(call.user).toBe(mockUser);expect(call.user.id).toBe('user-001');+ expect(call.streamId).toBe('scheduled-stream');+ expect(call.jobCreatedAt).toBe(42);});});@@ -2817,12 +2863,16 @@ describe('User parameter passing tests', () => {provider: 'google',userMCPAuthMap: {},availableTools: undefined, // Force reinit+ streamId: 'resumed-stream',+ jobCreatedAt: 43,});// Verify the call to reinitMCPServer had the userexpect(reinitCalls.length).toBe(1);expect(reinitCalls[0].user).toBe(mockUser);expect(reinitCalls[0].user.id).toBe('user-002');+ expect(reinitCalls[0].streamId).toBe('resumed-stream');+ expect(reinitCalls[0].jobCreatedAt).toBe(43);});});diff --git a/api/server/services/Schedules/index.js b/api/server/services/Schedules/index.jsindex 50944efd01..2968ddfc59 100644--- a/api/server/services/Schedules/index.js+++ b/api/server/services/Schedules/index.js@@ -84,6 +84,11 @@ module.exports = {getLimits: invoke('getLimits'),fireScheduleNow: invoke('fireScheduleNow'),recordScheduleOutcome: invoke('recordScheduleOutcome'),+ recordMCPToolAuthFailure: (input) =>+ require('@librechat/api').recordScheduledMCPToolAuthFailure(+ input,+ () => getService().recordMCPToolAuthFailure,+ ),beginScheduledStop: invoke('beginScheduledStop'),acknowledgeScheduledStopPersistence: invoke('acknowledgeScheduledStopPersistence'),claimScheduleResume: invoke('claimScheduleResume'),diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex a64713f75f..f215d60cda 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -1193,6 +1193,8 @@ async function loadToolDefinitionsWrapper({const result = await reinitMCPServer({signal,user: req.user,+ streamId,+ jobCreatedAt,oauthStart,flowManager,serverName,@@ -1224,6 +1226,8 @@ async function loadToolDefinitionsWrapper({const result = await reinitMCPServer({signal,user: req.user,+ streamId,+ jobCreatedAt,forceNew: true,oauthStart,flowManager,@@ -1376,6 +1380,8 @@ async function loadToolDefinitionsWrapper({const result = await reinitMCPServer({signal,user: req.user,+ streamId,+ jobCreatedAt,serverName,configServers,userMCPAuthMap,diff --git a/api/server/services/Tools/mcp.js b/api/server/services/Tools/mcp.jsindex aea58c8728..762c9a3e56 100644--- a/api/server/services/Tools/mcp.js+++ b/api/server/services/Tools/mcp.js@@ -9,6 +9,7 @@ const {getMissingRuntimeBodyPlaceholderFields,isMCPInitializationError,prepareMCPAuthorizationMutation,+ recordScheduledMCPToolAuthFailure,} = require('@librechat/api');const { CacheKeys, Constants } = require('librechat-data-provider');const { getMCPManager, getMCPServersRegistry, getFlowStateManager } = require('~/config');@@ -127,6 +128,8 @@ async function loadMCPServerCatalogs({* @param {import('@librechat/api').RequestScopedMCPConnectionStore} [params.requestScopedConnections]* @param {Record<string, Record<string, string>>} [params.userMCPAuthMap]* @param {import('@librechat/api').MCPServerCatalogRecoveryPolicy} [params.recoveryPolicy]+ * @param {string | null} [params.streamId] - Owning generation's stream ID, if resumable.+ * @param {number} [params.jobCreatedAt] - Owning generation epoch.*/async function reinitMCPServer({user,@@ -147,6 +150,8 @@ async function reinitMCPServer({oboIdentityContext,oauthEnd,recoveryPolicy,+ streamId,+ jobCreatedAt,}) {/** @type {MCPConnection | null} */let connection = null;@@ -452,6 +457,10 @@ async function reinitMCPServer({return result;} catch (error) {if (isMCPInitializationError(error, signal)) {+ await recordScheduledMCPToolAuthFailure(+ { error, streamId, jobCreatedAt, userId: user?.id, serverName },+ () => require('~/server/services/Schedules').recordMCPToolAuthFailure,+ );throw error;}logger.error('[MCP Reinitialize] Error loading MCP tools; servers may still be initializing');diff --git a/api/server/services/Tools/mcp.spec.js b/api/server/services/Tools/mcp.spec.jsindex bc50be0fcc..9e5def2622 100644--- a/api/server/services/Tools/mcp.spec.js+++ b/api/server/services/Tools/mcp.spec.js@@ -58,6 +58,9 @@ jest.mock('~/server/services/GraphTokenService', () => ({jest.mock('~/cache', () => ({getLogStores: jest.fn(() => ({})),}));+jest.mock('~/server/services/Schedules', () => ({+ recordMCPToolAuthFailure: jest.fn(async () => true),+}));const { reinitMCPServer, loadMCPServerCatalogs } = require('./mcp');@@ -536,6 +539,75 @@ describe('reinitMCPServer — recovery of a server that failed inspection', () =});});+describe('scheduled MCP connection initialization', () => {+ beforeEach(() => jest.clearAllMocks());++ it('records a typed missing OBO provider before any tool instance exists', async () => {+ const { OboTokenResolutionError } = require('@librechat/api');+ const failure = new OboTokenResolutionError('missing_upstream_provider', 'Provider missing');+ const receipt = require('~/server/services/Schedules').recordMCPToolAuthFailure;+ mockGetConnection.mockRejectedValueOnce(failure);++ await expect(+ reinitMCPServer({+ user: { id: 'owner' },+ serverName: 'Graph',+ serverConfig: {+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ obo: { scopes: 'api://graph/.default' },+ },+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ }),+ ).rejects.toBe(failure);+ expect(receipt).toHaveBeenCalledTimes(1);+ expect(receipt).toHaveBeenCalledWith({+ error: failure,+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ userId: 'owner',+ serverName: 'Graph',+ });+ });++ it('preserves the connection error when the receipt store fails', async () => {+ const { OboTokenResolutionError } = require('@librechat/api');+ const failure = new OboTokenResolutionError('missing_upstream_provider', 'Provider missing');+ const receipt = require('~/server/services/Schedules').recordMCPToolAuthFailure;+ receipt.mockRejectedValueOnce(new Error('Mongo unavailable'));+ mockGetConnection.mockRejectedValueOnce(failure);++ await expect(+ reinitMCPServer({+ user: { id: 'owner' },+ serverName: 'Graph',+ serverConfig: { type: 'streamable-http', url: 'https://mcp.example.com', source: 'yaml' },+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ }),+ ).rejects.toBe(failure);+ });++ it('does not construct the schedule facade for unrelated typed OBO failures', async () => {+ const { OboTokenResolutionError } = require('@librechat/api');+ const failure = new OboTokenResolutionError('session_refresh_failed', 'Retry later', true);+ const receipt = require('~/server/services/Schedules').recordMCPToolAuthFailure;+ mockGetConnection.mockRejectedValueOnce(failure);+ await expect(+ reinitMCPServer({+ user: { id: 'owner' },+ serverName: 'Graph',+ serverConfig: { type: 'streamable-http', url: 'https://mcp.example.com', source: 'yaml' },+ streamId: 'scheduled-conversation',+ jobCreatedAt: 42,+ }),+ ).rejects.toBe(failure);+ expect(receipt).not.toHaveBeenCalled();+ });+});+describe('reinitMCPServer — direct bearer authentication outcomes', () => {it('preserves a typed rejection instead of reducing it to a generic result', async () => {const { MCPAuthenticationRejectedError } = require('@librechat/api');diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.jsindex f57a506b07..dd388f232d 100644--- a/api/server/services/__tests__/ToolService.spec.js+++ b/api/server/services/__tests__/ToolService.spec.js@@ -1767,6 +1767,9 @@ describe('ToolService - Action Capability Gating', () => {expect(emittedStreamId).toBe(streamId);expect(options).toEqual({ expectedCreatedAt: jobCreatedAt });}+ for (const [reinitInput] of reinitMCPServer.mock.calls) {+ expect(reinitInput).toEqual(expect.objectContaining({ streamId, jobCreatedAt }));+ }});it('should not expose cached MCP tool definitions when the registry lookup fails', async () => {@@ -2307,6 +2310,8 @@ describe('ToolService - Action Capability Gating', () => {definitionsOnly: true,signal,upstreamTokenProvider: scheduledProvider,+ streamId: 'scheduled-stream',+ jobCreatedAt: 42,});expect(reinitMCPServer).toHaveBeenCalledWith(@@ -2314,6 +2319,8 @@ describe('ToolService - Action Capability Gating', () => {serverName,forceNew: true,upstreamTokenProvider: scheduledProvider,+ streamId: 'scheduled-stream',+ jobCreatedAt: 42,}),);});diff --git a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx b/client/src/components/SidePanel/Schedules/ScheduleCard.tsxindex 31ecb3cefc..fb979853d8 100644--- a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx+++ b/client/src/components/SidePanel/Schedules/ScheduleCard.tsx@@ -17,18 +17,19 @@ import {import type { TSchedule, ScheduleRunStatus, ScheduleDisabledReason } from 'librechat-data-provider';import type { ImmediateScheduleMCPFailure } from './errors';import type { TranslationKeys } from '~/hooks';-import {- useGetAgentByIdQuery,- useDeleteScheduleMutation,- useUpdateScheduleMutation,- useRunScheduleNowMutation,-} from '~/data-provider';import {scheduleMCPErrorMessage,scheduleMCPErrorOutcomes,scheduleLastRunKey,scheduleMCPCardOutcomes,+ scheduleDisabledMCPLabel,} from './errors';+import {+ useGetAgentByIdQuery,+ useDeleteScheduleMutation,+ useUpdateScheduleMutation,+ useRunScheduleNowMutation,+} from '~/data-provider';import { useLocalize, useHasAccess, useClockFormat, useWeekStart } from '~/hooks';import ScheduleMCPRecovery from './ScheduleMCPRecovery';import { useAgentsMapContext } from '~/Providers';@@ -75,6 +76,7 @@ export default function ScheduleCard({ schedule, projectName }: ScheduleCardPropconst [immediateMCPFailure, setImmediateMCPFailure] =useState<ImmediateScheduleMCPFailure | null>(null);const mcpOutcomes = scheduleMCPCardOutcomes(schedule, immediateMCPFailure);+ const disabledMCPLabel = scheduleDisabledMCPLabel(schedule.disabledReason, mcpOutcomes);const { i18n } = useTranslation();const { showToast } = useToastContext();const agentsMap = useAgentsMapContext();@@ -293,7 +295,9 @@ export default function ScheduleCard({ schedule, projectName }: ScheduleCardProp<Chip tone={statusChip.tone}>{localize(statusChip.label)}</Chip>))}{schedule.disabledReason != null && (- <Chip tone="error">{localize(DISABLED_REASON_LABELS[schedule.disabledReason])}</Chip>+ <Chip tone="error">+ {localize(disabledMCPLabel ?? DISABLED_REASON_LABELS[schedule.disabledReason])}+ </Chip>)}</div>)}diff --git a/client/src/components/SidePanel/Schedules/ScheduleMCPRecovery.tsx b/client/src/components/SidePanel/Schedules/ScheduleMCPRecovery.tsxindex 91ae6b8c44..17721a6ab6 100644--- a/client/src/components/SidePanel/Schedules/ScheduleMCPRecovery.tsx+++ b/client/src/components/SidePanel/Schedules/ScheduleMCPRecovery.tsx@@ -1,5 +1,5 @@import type { ScheduleMCPOutcome } from 'librechat-data-provider';-import { MCP_STATUS_LABELS, scheduleMCPNeedsAgentRecovery } from './errors';+import { scheduleMCPStatusLabel, scheduleMCPNeedsAgentRecovery } from './errors';import { useLocalize } from '~/hooks';export default function ScheduleMCPRecovery({@@ -28,7 +28,7 @@ export default function ScheduleMCPRecovery({className="flex flex-wrap items-baseline gap-x-2 text-xs text-text-secondary"><p>- {item.server} ({ownerLabel}): {localize(MCP_STATUS_LABELS[item.status])}+ {item.server} ({ownerLabel}): {localize(scheduleMCPStatusLabel(item))}</p>{scheduleMCPNeedsAgentRecovery([item]) && (<buttondiff --git a/client/src/components/SidePanel/Schedules/__tests__/ScheduleMCPRecovery.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/ScheduleMCPRecovery.spec.tsxindex ced818d972..b3a2dda7df 100644--- a/client/src/components/SidePanel/Schedules/__tests__/ScheduleMCPRecovery.spec.tsx+++ b/client/src/components/SidePanel/Schedules/__tests__/ScheduleMCPRecovery.spec.tsx@@ -28,3 +28,26 @@ it('opens the exact descendant that owns an immediate MCP failure', async () =>);expect(onOpenAgent).toHaveBeenCalledWith('research-agent');});++it('explains missing unattended credentials without suggesting interactive reconnection', () => {+ const onOpenAgent = jest.fn();+ render(+ <ScheduleMCPRecovery+ outcomes={[+ {+ server: 'Company Graph',+ status: 'mcp_configuration_missing',+ detail: 'unattended_auth_required',+ },+ ]}+ fallbackAgentId="root-agent"+ onOpenAgent={onOpenAgent}+ />,+ );++ expect(screen.getByRole('alert')).toHaveTextContent(+ 'Company Graph (root-agent): com_ui_schedule_mcp_unattended_auth',+ );+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ expect(onOpenAgent).not.toHaveBeenCalled();+});diff --git a/client/src/components/SidePanel/Schedules/__tests__/errors.spec.ts b/client/src/components/SidePanel/Schedules/__tests__/errors.spec.tsindex 09292e53c3..ac73cd29a6 100644--- a/client/src/components/SidePanel/Schedules/__tests__/errors.spec.ts+++ b/client/src/components/SidePanel/Schedules/__tests__/errors.spec.ts@@ -5,6 +5,7 @@ import {scheduleMCPCardOutcomes,scheduleMCPRecoveryOutcomes,scheduleMCPNeedsAgentRecovery,+ scheduleDisabledMCPLabel,} from '../errors';it('shows localized recovery reasons and exact server names', () => {@@ -74,6 +75,44 @@ it('ignores unrelated and malformed server errors', () => {expect(readScheduleMCPOutcomes('mcp_reauth_required: [malformed')).toEqual([]);});+it('preserves the permanent unattended-auth failure across API errors and saved runs', () => {+ const outcomes = [+ {+ server: 'Company Graph',+ status: 'mcp_configuration_missing' as const,+ detail: 'unattended_auth_required' as const,+ },+ ];+ const error = Object.assign(new Error('Internal OBO credentials'), {+ response: { status: 400, data: { code: 'mcp_configuration_missing', mcp: outcomes } },+ });+ expect(scheduleMCPErrorMessage(error, (key) => key)).toBe(+ 'Company Graph: com_ui_schedule_mcp_unattended_auth',+ );+ expect(scheduleMCPErrorOutcomes(error)).toEqual(outcomes);+ expect(+ scheduleMCPRecoveryOutcomes({+ enabled: false,+ disabledReason: 'mcp_configuration_missing',+ lastRun: {+ status: 'error',+ firedAt: new Date().toISOString(),+ error:+ 'mcp_configuration_missing: [{"server":"Company Graph","status":"mcp_configuration_missing","detail":"unattended_auth_required"}]',+ },+ }),+ ).toEqual(outcomes);+ expect(scheduleMCPNeedsAgentRecovery(outcomes)).toBe(false);+ expect(scheduleDisabledMCPLabel('mcp_configuration_missing', outcomes)).toBe(+ 'com_ui_schedule_disabled_mcp_unattended_auth',+ );+ expect(+ scheduleDisabledMCPLabel('mcp_configuration_missing', [+ { server: 'Graph', status: 'mcp_configuration_missing' },+ ]),+ ).toBeUndefined();+});+it('explains transient MCP infrastructure failures without server outcomes', () => {const error = Object.assign(new Error('private infrastructure details'), {response: { status: 503, data: { code: 'mcp_unavailable' } },diff --git a/client/src/components/SidePanel/Schedules/errors.ts b/client/src/components/SidePanel/Schedules/errors.tsindex 66abd5ef8e..4ef8c923db 100644--- a/client/src/components/SidePanel/Schedules/errors.ts+++ b/client/src/components/SidePanel/Schedules/errors.ts@@ -10,6 +10,22 @@ export const MCP_STATUS_LABELS: Record<ScheduleMCPStatus, TranslationKeys> = {mcp_unavailable: 'com_ui_schedule_mcp_unavailable',};+export function scheduleMCPStatusLabel(outcome: ScheduleMCPOutcome): TranslationKeys {+ return outcome.detail === 'unattended_auth_required'+ ? 'com_ui_schedule_mcp_unattended_auth'+ : MCP_STATUS_LABELS[outcome.status];+}++export function scheduleDisabledMCPLabel(+ reason: TSchedule['disabledReason'],+ outcomes: ScheduleMCPOutcome[],+): TranslationKeys | undefined {+ return reason === 'mcp_configuration_missing' &&+ outcomes.some((outcome) => outcome.detail === 'unattended_auth_required')+ ? 'com_ui_schedule_disabled_mcp_unattended_auth'+ : undefined;+}+export function scheduleMCPRecoveryOutcomes(schedule: Pick<TSchedule, 'enabled' | 'disabledReason' | 'lastRun'>,) {@@ -45,7 +61,10 @@ export function scheduleMCPCardOutcomes(export function scheduleMCPNeedsAgentRecovery(outcomes: ScheduleMCPOutcome[]): boolean {return outcomes.some(- (outcome) => outcome.status !== 'ready' && outcome.status !== 'mcp_permission_denied',+ (outcome) =>+ outcome.status !== 'ready' &&+ outcome.status !== 'mcp_permission_denied' &&+ outcome.detail !== 'unattended_auth_required',);}@@ -56,7 +75,7 @@ export function scheduleMCPErrorMessage(const failures = scheduleMCPErrorOutcomes(error).filter((item) => item.status !== 'ready');if (failures.length > 0) {return failures- .map((item) => `${item.server}: ${localize(MCP_STATUS_LABELS[item.status])}`)+ .map((item) => `${item.server}: ${localize(scheduleMCPStatusLabel(item))}`).join('; ');}const response = (diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 424f45ddde..47b7bfb1ad 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -64,11 +64,13 @@"com_ui_code_workspace_default_description": "New chats use this workspace. Without a default, reuse your last available choice for this agent and machine in this browser. Existing chats keep their workspace.","com_ui_schedule_mcp_ready": "Ready for scheduled chats","com_ui_schedule_mcp_reauth": "Reconnect this MCP server before enabling the schedule.",+ "com_ui_schedule_mcp_unattended_auth": "Unattended access is not configured for this MCP server. Ask your administrator to set up a renewable credential provider; reconnecting in chat will not fix this.","com_ui_schedule_mcp_configuration": "Configure or remove this MCP server before enabling the schedule.","com_ui_schedule_mcp_permission": "An administrator must restore your MCP server permission.","com_ui_schedule_mcp_unavailable": "MCP server unavailable. Try again later.","com_ui_schedule_mcp_open_agent": "Open agent to reconnect MCPs","com_ui_schedule_disabled_mcp_reauth": "Disabled: MCP reauthentication required",+ "com_ui_schedule_disabled_mcp_unattended_auth": "Disabled: unattended MCP access not configured","com_ui_schedule_disabled_mcp_configuration": "Disabled: MCP configuration required","com_ui_schedule_disabled_mcp_permission": "Disabled: MCP permission revoked","com_ui_code_approval_mode": "Code approval mode",diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.tsindex 913a000029..3f6006fa39 100644--- a/packages/api/src/mcp/MCPConnectionFactory.ts+++ b/packages/api/src/mcp/MCPConnectionFactory.ts@@ -682,10 +682,9 @@ export class MCPConnectionFactory {);}if (!this.upstreamTokenProvider) {- throw new Error(- `${this.logPrefix} Internal: upstreamTokenProvider not plumbed for OBO connection. ` +- 'OBO requires a live upstream-token closure; the caller must construct one via ' +- 'createOpenIDSessionTokenProvider() and forward it through the MCP connection options.',+ throw new OboTokenResolutionError(+ 'missing_upstream_provider',+ 'No upstream credential provider is configured for this OBO MCP connection.',);}@@ -733,6 +732,8 @@ export class MCPConnectionFactory {recoveryHint = 'Please retry.';} else if (error.reason === 'exchange_failed') {recoveryHint = 'Re-authenticate the user or verify the configured OBO scopes and retry.';+ } else if (error.reason === 'missing_upstream_provider') {+ recoveryHint = 'Configure a renewable upstream credential provider before retrying.';}return new OboTokenResolutionError(diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex 016af28aa4..54c17f73e0 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -62,6 +62,8 @@ function createOboToolCallErrorMessage(failureSuffix = 'Re-authenticate the user or verify the configured OBO scopes and retry.';} else if (error.reason === 'session_refresh_failed') {failureSuffix = 'Please sign in again.';+ } else if (error.reason === 'missing_upstream_provider') {+ failureSuffix = 'Configure a renewable upstream credential provider before retrying.';}return `${logPrefix} ${error.userMessage} Cannot execute tool ${toolName}. ${failureSuffix}`;@@ -1323,11 +1325,16 @@ Please follow these instructions when using tools from the respective MCP server);}if (!oboUpstreamTokenProvider) {- throw new McpError(- ErrorCode.InternalError,- `${logPrefix} Internal: upstreamTokenProvider not plumbed for OBO tool call. ` +- 'OBO requires a live upstream-token closure; the caller must construct one via ' +- 'createOpenIDSessionTokenProvider() and forward it through callTool().',+ const missing = new OboTokenResolutionError(+ 'missing_upstream_provider',+ 'No upstream credential provider is configured for this OBO MCP tool.',+ );+ throw Object.assign(+ new McpError(+ ErrorCode.InternalError,+ createOboToolCallErrorMessage(logPrefix, toolName, missing),+ ),+ { cause: missing },);}const oboTrusted = oboTrustChecker@@ -1361,10 +1368,14 @@ Please follow these instructions when using tools from the respective MCP server);} catch (error) {if (error instanceof OboTokenResolutionError) {- throw new McpError(+ const failure = new McpError(ErrorCode.InternalError,createOboToolCallErrorMessage(logPrefix, toolName, error),);+ if (error.reason === 'missing_upstream_provider') {+ throw Object.assign(failure, { cause: error });+ }+ throw failure;}throw error;}diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.tsindex af050c348e..2e70d1a82b 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts@@ -6426,11 +6426,22 @@ describe('MCPConnectionFactory', () => {expect(upstreamTokenProviderResolver).not.toHaveBeenCalled();});- it('throws an internal error when upstreamTokenProvider is omitted on an OBO connection', async () => {+ it('identifies missing upstream credentials before exchanging an OBO token', async () => {const { resolveOboToken } = jest.requireMock('~/mcp/oauth') as {resolveOboToken: jest.Mock;};resolveOboToken.mockClear();+ const OboError = OboTokenResolutionError as unknown as jest.Mock;+ OboError.mockImplementation((reason: string, userMessage: string, retryable = false) => {+ const error = new Error(userMessage);+ Object.setPrototypeOf(error, OboError.prototype);+ return Object.assign(error, {+ name: 'OboTokenResolutionError',+ reason,+ retryable,+ userMessage,+ });+ });const oboTokenResolver = jest.fn();await expect(@@ -6450,7 +6461,11 @@ describe('MCPConnectionFactory', () => {/** upstreamTokenProvider intentionally omitted */},),- ).rejects.toThrow(/upstreamTokenProvider not plumbed/);+ ).rejects.toMatchObject({+ name: 'OboTokenResolutionError',+ reason: 'missing_upstream_provider',+ retryable: false,+ });expect(resolveOboToken).not.toHaveBeenCalled();});diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex 3970263c12..c6369c41e5 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -3224,7 +3224,7 @@ describe('MCPManager', () => {/** upstreamTokenProvider intentionally omitted */}),).rejects.toMatchObject({- message: expect.stringContaining('upstreamTokenProvider not plumbed'),+ cause: expect.objectContaining({ reason: 'missing_upstream_provider', retryable: false }),});expect(mockResolveOboToken).not.toHaveBeenCalled();});diff --git a/packages/api/src/mcp/oauth/obo.spec.ts b/packages/api/src/mcp/oauth/obo.spec.tsindex daa1572641..2cde171d2a 100644--- a/packages/api/src/mcp/oauth/obo.spec.ts+++ b/packages/api/src/mcp/oauth/obo.spec.ts@@ -192,7 +192,7 @@ describe('resolveOboToken', () => {mockResolver,createLazyOboUpstreamTokenProvider(lookup),),- ).rejects.toMatchObject({ reason: 'session_refresh_failed', retryable: false });+ ).rejects.toMatchObject({ reason: 'missing_upstream_provider', retryable: false });expect(mockExtractOpenIDTokenInfo).not.toHaveBeenCalled();expect(mockResolver).not.toHaveBeenCalled();});diff --git a/packages/api/src/mcp/oauth/obo.ts b/packages/api/src/mcp/oauth/obo.tsindex 32fca35f2e..5e3d091ea8 100644--- a/packages/api/src/mcp/oauth/obo.ts+++ b/packages/api/src/mcp/oauth/obo.ts@@ -117,7 +117,10 @@ export function createLazyOboUpstreamTokenProvider(effectiveSignal?.throwIfAborted();if (!provider) {pending = undefined;- throw new Error('Renewable upstream credentials are unavailable.');+ throw new OboTokenResolutionError(+ 'missing_upstream_provider',+ 'No renewable upstream credential provider is available for this MCP server.',+ );}return await detachOnAbort(provider({ ...options, signal: effectiveSignal }),@@ -130,6 +133,7 @@ export function createLazyOboUpstreamTokenProvider(}export type OboTokenResolutionReason =+ | 'missing_upstream_provider'| 'missing_upstream_token'| 'missing_upstream_access_token'| 'empty_exchange_response'@@ -299,6 +303,9 @@ export async function resolveOboToken(liveTokens = await upstreamTokenProvider();} catch (error) {if (isAbortError(error)) throw error;+ if (error instanceof OboTokenResolutionError && error.reason === 'missing_upstream_provider') {+ throw error;+ }logger.error('[OBO] Upstream session refresh failed:', error);const retryable = isRetryableOboExchangeError(error);throw new OboTokenResolutionError(diff --git a/packages/api/src/schedules/README.md b/packages/api/src/schedules/README.mdindex e155a4b402..678625c698 100644--- a/packages/api/src/schedules/README.md+++ b/packages/api/src/schedules/README.md@@ -23,13 +23,18 @@ Supported authentication is determined by a successful unattended connection:Browser-only credentials, interactive OpenID bearer/OBO sources, missing uservariables, and OAuth grants needing renewed consent cannot be assumed available.-Reconnect or configure the server in an interactive agent chat, or remove it from the-agent, then enable the schedule. A browser connection alone does not prove readiness;-enabling always reruns the unattended check.+An OBO server without a host-owned renewable upstream-token provider reports+`mcp_configuration_missing` with `detail: 'unattended_auth_required'` (a+backward-compatible subtype); reconnecting in a browser cannot make it ready.+The operator must configure a properly authorized unattended provider, or the+owner must remove the server from the agent. Other servers with missing user+credentials can be reconnected or configured in an interactive agent chat.+A browser connection alone does not prove readiness; enabling always reruns+the unattended check.-`mcp_reauth_required`, `mcp_configuration_missing`, and `mcp_permission_denied` stop a-scheduled occurrence and disable the schedule immediately. The permission status tells-the owner that an administrator must restore MCP use access. `mcp_unavailable` counts+`mcp_reauth_required`, `mcp_configuration_missing`, and `mcp_permission_denied`+stop a scheduled occurrence and disable the schedule immediately. The permission status tells the owner that an administrator must+restore MCP use access. `mcp_unavailable` countstoward the existing configured consecutive-failure threshold. Credential-store andconfiguration-store outages are transient; they must never be treated as proof of missing credentials.Failure records contain only server names and resolution statuses, never exceptiondiff --git a/packages/api/src/schedules/erasure.spec.ts b/packages/api/src/schedules/erasure.spec.tsindex 0617201ad6..a47269d338 100644--- a/packages/api/src/schedules/erasure.spec.ts+++ b/packages/api/src/schedules/erasure.spec.ts@@ -24,6 +24,9 @@ async function sweepOnce(options: {eraseScheduleIfDrained: jest.fn(async () => false),markEraseAttempted: jest.fn(async () => undefined),getRunsForReconciliation: jest.fn(async () => []),+ getUnbookkeptRuns: jest.fn(async () => []),+ finalizeBookkeeping: jest.fn(async () => undefined),+ markRunsReconciled: jest.fn(async () => undefined),};const sweep = startScheduleErasureSweep({methods: methods as unknown as ScheduleMethods,@@ -118,6 +121,9 @@ describe('topology-safe dead-delivery convergence', () => {getRunsForReconciliation: jest.fn(async () => [oldRun({ deliveryKey: 'dk-1', ...options.run } as Partial<IScheduleRun>),]),+ getUnbookkeptRuns: jest.fn(async () => []),+ finalizeBookkeeping: jest.fn(async () => undefined),+ markRunsReconciled: jest.fn(async () => undefined),};const getTriggerDelivery = jest.fn(async () => options.delivery ?? null);const clearReconciledJob = jest.fn(async () => undefined);@@ -328,6 +334,64 @@ describe('topology-safe dead-delivery convergence', () => {});});+describe('permanent MCP bookkeeping recovery without an armed scheduler', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ jest.spyOn(Math, 'random').mockReturnValue(0);+ });++ afterEach(() => {+ jest.useRealTimers();+ jest.restoreAllMocks();+ });++ it('replays a half-bookkept MCP run without applying ordinary failure policy', async () => {+ const mcp = [+ {+ server: 'Graph',+ status: 'mcp_configuration_missing' as const,+ detail: 'unattended_auth_required' as const,+ },+ ];+ const permanent = oldRun({ status: 'error', error: 'MCP unavailable', mcp });+ const ordinary = oldRun({+ scheduleId: 'schedule-2',+ status: 'error',+ error: 'Temporary upstream failure',+ });+ const methods = {+ getDeletingSchedules: jest.fn(async () => []),+ getActiveRunsForSchedule: jest.fn(async () => []),+ eraseScheduleIfDrained: jest.fn(async () => false),+ markEraseAttempted: jest.fn(async () => undefined),+ getRunsForReconciliation: jest.fn(async () => []),+ recordRunOutcome: jest.fn(async () => undefined),+ getUnbookkeptRuns: jest.fn(async () => [permanent, ordinary]),+ finalizeBookkeeping: jest.fn(async () => undefined),+ markRunsReconciled: jest.fn(async () => undefined),+ };+ const sweep = startScheduleErasureSweep({+ methods: methods as unknown as ScheduleMethods,+ getJobStatus: jest.fn(async () => null),+ getTriggerDelivery: jest.fn(async () => null),+ clearReconciledJob: jest.fn(async () => undefined),+ canInferOwnerDeathFromMissingJob: false,+ });+ await jest.advanceTimersByTimeAsync(5 * 60_000);+ sweep.stop();+ expect(methods.finalizeBookkeeping).toHaveBeenCalledTimes(1);+ expect(methods.finalizeBookkeeping).toHaveBeenCalledWith(+ expect.objectContaining({+ scheduleId: 'schedule-1',+ status: 'error',+ mcp,+ autoDisableAfterFailures: Number.MAX_SAFE_INTEGER,+ }),+ );+ expect(methods.markRunsReconciled).toHaveBeenCalledWith([permanent, ordinary]);+ });+});+describe('dead-delivery certainty fence', () => {beforeEach(() => {jest.useFakeTimers();@@ -350,6 +414,9 @@ describe('dead-delivery certainty fence', () => {eraseScheduleIfDrained: jest.fn(async () => false),markEraseAttempted: jest.fn(async () => undefined),getRunsForReconciliation: jest.fn(async () => [oldRun({ deliveryKey: 'dk-1' } as never)]),+ getUnbookkeptRuns: jest.fn(async () => []),+ finalizeBookkeeping: jest.fn(async () => undefined),+ markRunsReconciled: jest.fn(async () => undefined),};const sweep = startScheduleErasureSweep({methods: methods as unknown as ScheduleMethods,diff --git a/packages/api/src/schedules/erasure.ts b/packages/api/src/schedules/erasure.tsindex 37dc92ea01..de21024459 100644--- a/packages/api/src/schedules/erasure.ts+++ b/packages/api/src/schedules/erasure.ts@@ -1,4 +1,5 @@import { logger, runAsSystem } from '@librechat/data-schemas';+import { getScheduleMCPDisabledReason } from 'librechat-data-provider';import type { ScheduleMethods, IScheduleRun } from '@librechat/data-schemas';import type { JobState, ScheduleEngineDeps } from './types';import {@@ -39,6 +40,9 @@ export interface ScheduleErasureDeps {| 'markEraseAttempted'| 'getActiveRunsForSchedule'| 'getRunsForReconciliation'+ | 'getUnbookkeptRuns'+ | 'markRunsReconciled'+ | 'finalizeBookkeeping'| 'recordRunOutcome'>;/** Job state at a run's conversationId; null = confirmed absent, throw = unknown. */@@ -229,8 +233,9 @@ async function settleFromObservedJob(* is observed (a shared store shows the real generation; a process-local store can only be* showing this process's own), and a `dead` delivery is shared state proving no generation* owns the reservation. This never claims, fires, or advances, and defers anything fenced- * by an in-flight abort or resume hand-off. Auto-disable policy is deliberately NOT applied- * (the armed engine owns that): the run settles and frees its slot, the streak is untouched.+ * by an in-flight abort or resume hand-off. Generic failures retain the fallback's+ * no-auto-disable policy; a durable MCP configuration receipt still disables via the+ * run-row transition, including when a retained job originally ended as a success.*/async function settleStrandedRuns(deps: ScheduleErasureDeps): Promise<void> {const runs = await deps.methods.getRunsForReconciliation(@@ -297,8 +302,35 @@ async function settleStrandedRuns(deps: ScheduleErasureDeps): Promise<void> {}}+/** Replays a crashed permanent-MCP terminal projection where no engine is armed. */+async function replayUnbookkeptMCPRuns(deps: ScheduleErasureDeps): Promise<void> {+ const runs = await deps.methods.getUnbookkeptRuns(+ new Date(Date.now() - STRANDED_RUN_MIN_AGE_MS),+ SWEEP_BATCH,+ );+ for (const run of runs) {+ if (run.status !== 'error' || !getScheduleMCPDisabledReason(run.mcp)) {+ continue;+ }+ try {+ await deps.methods.finalizeBookkeeping({+ scheduleId: run.scheduleId,+ scheduledFor: run.scheduledFor,+ status: 'error',+ conversationId: run.conversationId,+ error: run.error,+ mcp: run.mcp,+ autoDisableAfterFailures: Number.MAX_SAFE_INTEGER,+ });+ } catch (error) {+ logger.warn(`[schedules] MCP bookkeeping replay failed for ${run.scheduleId}:`, error);+ }+ }+ await deps.methods.markRunsReconciled(runs);+}+/**- * Erases soft-deleted schedules once they drain — and NOTHING else.+ * Maintains erasure and positively evidenced stranded-run convergence without arming a scheduler.** A `deleting` row is normally erased by whichever actor first observes it drained: the* delete request, or the terminal outcome write (erase-on-settle). Both are single@@ -307,11 +339,9 @@ async function settleStrandedRuns(deps: ScheduleErasureDeps): Promise<void> {* retry it (the row is hidden from their list). In the standard entrypoint the* reconciler retries it; the clustered entrypoint runs no engine, so nothing does.*- * This is deliberately NOT the engine: it never claims, leases, fires, advances, or- * reconciles a run, so running it in every replica of a clustered deployment is safe and- * changes nothing about v1's single-process scheduling. It only re-drives- * `eraseScheduleIfDrained`, which re-checks drained-ness itself (no active run, no live- * lease) and is idempotent — concurrent sweepers race harmlessly.+ * This is deliberately NOT the engine: it never claims, leases, fires or advances.+ * Every convergence write is idempotent and guarded by the run or schedule's current+ * state, so concurrent clustered sweepers can re-drive cleanup safely.*/export function startScheduleErasureSweep(deps: ScheduleErasureDeps): ScheduleErasureSweep {let stopped = false;@@ -340,6 +370,9 @@ export function startScheduleErasureSweep(deps: ScheduleErasureDeps): ScheduleErawait settleStrandedRuns(deps).catch((err) =>logger.warn('[schedules] stranded-run convergence pass failed:', err),);+ await replayUnbookkeptMCPRuns(deps).catch((err) =>+ logger.warn('[schedules] MCP bookkeeping replay pass failed:', err),+ );});} catch (err) {logger.error('[schedules] erasure sweep failed:', err);diff --git a/packages/api/src/schedules/mcp.spec.ts b/packages/api/src/schedules/mcp.spec.tsindex da647d57af..b491e8882f 100644--- a/packages/api/src/schedules/mcp.spec.ts+++ b/packages/api/src/schedules/mcp.spec.ts@@ -152,6 +152,43 @@ it('lazily resolves an upstream token provider for an OBO preflight', async () =);});+it('reports missing unattended OBO credentials without offering a browser reconnect', async () => {+ const { check, deps } = setup();+ deps.getServerConfigs = jest.fn(async () => ({+ docs: { ...server, obo: { scopes: 'api://mcp/.default' } },+ }));+ deps.resolveUpstreamTokenProvider = jest.fn(async () => undefined);+ deps.connect = jest.fn(async (options) => {+ const provider = createLazyOboUpstreamTokenProvider(+ options.upstreamTokenProviderResolver!,+ options.signal,+ { mcpServer: options.serverName, scopes: options.serverConfig!.obo!.scopes },+ );+ await provider();+ throw new Error('A missing provider must never connect');+ });++ await expect(check('agent', principal, { scheduleId: 'schedule' })).rejects.toMatchObject({+ code: 'mcp_configuration_missing',+ outcomes: [+ { server: 'docs', status: 'mcp_configuration_missing', detail: 'unattended_auth_required' },+ ],+ });+ expect(deps.resolveUpstreamTokenProvider).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'owner' }),+ {+ signal: undefined,+ context: {+ scheduleId: 'schedule',+ ownerId: 'owner',+ agentId: 'agent',+ invocationMode: 'delegated',+ },+ target: { mcpServer: 'docs', scopes: 'api://mcp/.default' },+ },+ );+});+it('does not resolve upstream credentials for non-OBO servers', async () => {const { check, deps } = setup();deps.resolveUpstreamTokenProvider = jest.fn(async () => {@@ -271,6 +308,19 @@ it('classifies a transport outage as retryable', async () => {});});+it('classifies absent OBO provider wiring as a permanent unattended-auth setup failure', async () => {+ const { check, deps } = setup();+ deps.connect = async () => {+ throw new OboTokenResolutionError('missing_upstream_provider', 'Internal provider detail');+ };++ await expect(check('agent', principal)).rejects.toMatchObject({+ code: 'mcp_configuration_missing',+ message:+ 'mcp_configuration_missing: [{"server":"docs","status":"mcp_configuration_missing","detail":"unattended_auth_required"}]',+ });+});+it('classifies a permanent OBO credential failure as requiring reauthentication', async () => {const { check, deps } = setup();deps.connect = async () => {diff --git a/packages/api/src/schedules/mcp.ts b/packages/api/src/schedules/mcp.tsindex 37d3a34489..7697f133c2 100644--- a/packages/api/src/schedules/mcp.ts+++ b/packages/api/src/schedules/mcp.ts@@ -751,6 +751,17 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPrmissingOwners.size > 0 ? missingOwners : undefined,);} catch (error) {+ if (+ error instanceof OboTokenResolutionError &&+ error.reason === 'missing_upstream_provider'+ ) {+ return outcomesForOwners(server, 'mcp_configuration_missing').map(+ (outcome) => ({+ ...outcome,+ detail: 'unattended_auth_required' as const,+ }),+ );+ }return outcomesForOwners(server,reauth ||diff --git a/packages/api/src/schedules/service.spec.ts b/packages/api/src/schedules/service.spec.tsindex 0c616ac7d3..5251ddd7ce 100644--- a/packages/api/src/schedules/service.spec.ts+++ b/packages/api/src/schedules/service.spec.ts@@ -1,7 +1,9 @@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 { OboTokenResolutionError } from '../mcp/oauth/obo';import { isShutdownInProgress } from '../app/shutdown';-import { createSchedulesService } from './service';/** 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;@@ -55,6 +57,7 @@ function makeService(countActiveRuns: jest.fn(async () => 0),requestRunAbort: jest.fn(async () => true),getScheduleRunAbortState: jest.fn(async () => null),+ recordMCPToolAuthFailure: jest.fn(async () => true),markRunAbortPersisted: jest.fn(async () => undefined),recordRunOutcome,};@@ -724,6 +727,195 @@ describe('erase-on-settle', () => {});});+describe('scheduled OBO tool failure settlement', () => {+ const occurrence = '2026-09-09T12:00:00.000Z';+ const failure = {+ server: 'Graph',+ status: 'mcp_configuration_missing' as const,+ detail: 'unattended_auth_required' as const,+ };++ function setup() {+ const service = makeService(jest.fn<Promise<ActiveRun[]>, [string]>(async () => []));+ const methods = service.engineDeps.methods as unknown as {+ getScheduleById: jest.Mock;+ eraseScheduleIfDrained: jest.Mock;+ getScheduleRunAbortState: jest.Mock;+ recordMCPToolAuthFailure: jest.Mock;+ recordRunOutcome: jest.Mock;+ };+ methods.getScheduleById = jest.fn(async () => null);+ methods.eraseScheduleIfDrained = jest.fn(async () => false);+ methods.getScheduleRunAbortState = jest.fn(async () => ({ status: 'started', mcp: [failure] }));+ const store = {+ getJob: jest.fn(async () => ({+ createdAt: 42,+ scheduleId: 's1',+ scheduledFor: occurrence,+ conversationId: 'c1',+ userId: 'owner',+ tenantId: 'tenant-1',+ status: 'running',+ })),+ };+ mockJobStore = store;+ return { service, methods, store };+ }++ it('does not initialize the schedule service for unrelated MCP errors', async () => {+ const getRecorder = jest.fn();+ await expect(+ recordScheduledMCPToolAuthFailure(+ {+ error: new Error('Ordinary MCP failure'),+ streamId: 'c1',+ jobCreatedAt: 42,+ userId: 'owner',+ serverName: 'Graph',+ },+ getRecorder,+ ),+ ).resolves.toBe(false);+ expect(getRecorder).not.toHaveBeenCalled();+ });++ it.each(['job lookup', 'run write'] as const)(+ 'keeps receipt persistence best-effort when the %s fails',+ async (failurePoint) => {+ const { service, methods, store } = setup();+ const persistenceError = new Error('Storage temporarily unavailable');+ if (failurePoint === 'job lookup') {+ store.getJob.mockRejectedValueOnce(persistenceError);+ } else {+ methods.recordMCPToolAuthFailure.mockRejectedValueOnce(persistenceError);+ }+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);+ const missing = new OboTokenResolutionError('missing_upstream_provider', 'No credentials');+ const input = {+ error: missing,+ streamId: 'c1',+ jobCreatedAt: 42,+ userId: 'owner',+ serverName: 'Graph',+ };++ await expect(+ recordScheduledMCPToolAuthFailure(input, () => service.recordMCPToolAuthFailure),+ ).resolves.toBe(false);+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('could not persist'),+ persistenceError,+ );+ warn.mockRestore();+ },+ );++ 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');+ const error = Object.assign(new McpError(ErrorCode.InternalError, 'OBO failed'), {+ cause: source,+ });+ const input = { error, streamId: 'c1', jobCreatedAt: 42, userId: 'owner', serverName: 'Graph' };+ await expect(service.recordMCPToolAuthFailure(input)).resolves.toBe(true);+ expect(methods.recordMCPToolAuthFailure).toHaveBeenCalledWith({+ scheduleId: 's1',+ scheduledFor: new Date(occurrence),+ conversationId: 'c1',+ tenantId: 'tenant-1',+ server: 'Graph',+ });+ expect(store.getJob).toHaveBeenCalledWith('c1');++ for (const wrong of [{ jobCreatedAt: 43 }, { userId: 'another' }]) {+ await expect(service.recordMCPToolAuthFailure({ ...input, ...wrong })).resolves.toBe(false);+ }+ await expect(+ service.recordMCPToolAuthFailure({ ...input, error: new Error('No credentials') }),+ ).resolves.toBe(false);+ store.getJob.mockResolvedValueOnce({+ createdAt: 42,+ userId: 'owner',+ scheduleId: '',+ scheduledFor: occurrence,+ conversationId: 'c1',+ tenantId: 'tenant-1',+ status: 'running',+ });+ await expect(service.recordMCPToolAuthFailure(input)).resolves.toBe(false);+ expect(methods.recordMCPToolAuthFailure).toHaveBeenCalledTimes(1);+ });++ it('settles a resumed run with missing MCP credentials as an error with old-client-readable guidance', async () => {+ const { service, methods } = setup();+ methods.getScheduleRunAbortState.mockResolvedValue({ status: 'started', mcp: [failure] });+ await service.recordScheduleOutcome({+ scheduleId: 's1',+ scheduledFor: occurrence,+ status: 'requires_action',+ });+ expect(methods.getScheduleRunAbortState).not.toHaveBeenCalled();+ 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: [failure],+ error: 'MCP unattended authorization unavailable',+ }),+ );+ expect(+ jest.requireMock('../stream/GenerationJobManager').GenerationJobManager.updateMetadata,+ ).toHaveBeenCalledWith('c1', expect.objectContaining({ scheduleOutcome: 'error' }), 42);+ });++ it('retains an error rather than a balance skip for a known missing OBO provider', async () => {+ const { service, methods } = setup();+ await service.recordScheduleOutcome({+ scheduleId: 's1',+ scheduledFor: occurrence,+ status: 'skipped_balance',+ conversationId: 'c1',+ streamId: 'c1',+ jobCreatedAt: 42,+ });+ expect(methods.recordRunOutcome).toHaveBeenLastCalledWith(+ expect.objectContaining({+ status: 'error',+ error: 'MCP unattended authorization unavailable',+ mcp: [failure],+ }),+ );+ expect(+ jest.requireMock('../stream/GenerationJobManager').GenerationJobManager.updateMetadata,+ ).toHaveBeenCalledWith('c1', expect.objectContaining({ scheduleOutcome: 'error' }), 42);+ });++ it('keeps ordinary completion and missing-run outcomes unchanged', async () => {+ const { service, methods } = setup();+ methods.getScheduleRunAbortState.mockResolvedValueOnce({+ status: 'started',+ mcp: [{ server: 'Graph', status: 'ready' }],+ });+ await service.recordScheduleOutcome({+ scheduleId: 's1',+ scheduledFor: occurrence,+ status: 'success',+ });+ expect(methods.recordRunOutcome).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: 'success' }),+ );+ });+});+describe('interactive Stop persistence barrier', () => {function outcomeService() {const service = makeService(jest.fn<Promise<ActiveRun[]>, [string]>().mockResolvedValue([]));diff --git a/packages/api/src/schedules/service.ts b/packages/api/src/schedules/service.tsindex 4c3fb6d7c3..63715062f9 100644--- a/packages/api/src/schedules/service.ts+++ b/packages/api/src/schedules/service.ts@@ -2,6 +2,7 @@ import { logger, runAsSystem, tenantStorage, isRuntimeDisabled } from '@librechaimport { getRefillEligibilityDate, Permissions, PermissionTypes } 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';import type { Types } from 'mongoose';import type {ScheduleEngineDeps,@@ -34,6 +35,7 @@ import { GenerationJobManager } from '../stream/GenerationJobManager';import { isStopConfirmed } from '../stream/interfaces/IJobStore';import { buildBalanceUpdateFields } from '../middleware/balance';import { getAppConfigOptionsFromUser } from '../app/service';+import { OboTokenResolutionError } from '../mcp/oauth/obo';import { isShutdownInProgress } from '../app/shutdown';import { startScheduleErasureSweep } from './erasure';import { getBalanceConfig } from '../app/config';@@ -193,6 +195,13 @@ export interface SchedulesService {options?: { signal?: AbortSignal },) => Promise<FireResult | null>;recordScheduleOutcome: (input: RecordScheduleOutcomeInput) => Promise<boolean>;+ recordMCPToolAuthFailure: (input: {+ error: unknown;+ streamId?: string;+ jobCreatedAt?: number;+ userId?: string;+ serverName: string;+ }) => Promise<boolean>;/*** Stamps a scheduled run's interactive Stop BEFORE the abort is signalled, so the owner* settlement barrier, reconciliation, and schedule/account deletion hold off settling or@@ -273,14 +282,37 @@ export interface SchedulesService {* the topology cannot be shown safe (process-local job store with no single-process* assertion) — see isTopologySafeToArm. */initializeScheduleEngine: () => Promise<ReturnType<typeof startScheduleEngine> | undefined>;- /** Starts erasure-ONLY maintenance for an entrypoint that never arms the engine (the+ /** Starts bounded maintenance for an entrypoint that never arms the engine (the* clustered worker). Idempotent per process and a no-op once the full engine is armed.- * Arms nothing else — no claims, firing, cadence advancement, or absence-based- * reconciliation — and refuses to infer owner death from a process-local missing job- * (isTopologySafeToArm gates that). See startScheduleErasureSweep. */+ * Replays terminal permanent-MCP bookkeeping but never claims, fires, advances, or+ * infers owner death from a process-local missing job. See startScheduleErasureSweep. */initializeScheduleErasureSweep: () => void;}+/** Screening happens before the CJS facade constructs any schedule dependencies. */+export async function recordScheduledMCPToolAuthFailure(+ input: Parameters<SchedulesService['recordMCPToolAuthFailure']>[0],+ getRecorder: () => SchedulesService['recordMCPToolAuthFailure'],+): Promise<boolean> {+ 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.streamId ||+ input.jobCreatedAt == null ||+ !input.userId+ ) {+ return false;+ }+ try {+ return await getRecorder()(input);+ } catch (error) {+ logger.warn('[schedules] could not persist MCP authorization failure receipt:', error);+ return false;+ }+}+/** Test-only overrides for the service's bounded waits (drains, barriers). */export interface ScheduleServiceTimings {drainTimeoutMs?: number;@@ -752,12 +784,10 @@ export function createSchedulesService(}/**- * The clustered entrypoint's ONLY schedule maintenance. Exposes the same erasure sweep- * the standard entrypoint falls back to, so a soft-deleted row whose delete/terminal- * erase-on-settle attempts missed still drains instead of retaining the owner's prompt- * forever. It shares startErasureFallback's idempotent startup guard, the sweep's own- * shutdown registration, and the topology-fenced owner-death policy — and arms nothing- * else, so running it in every clustered replica changes nothing about v1 scheduling.+ * The clustered entrypoint's ONLY schedule maintenance. The fallback erases soft-deleted+ * rows and converges terminal evidence, including permanent MCP bookkeeping interrupted+ * between the run-row transition and card projection. It shares startErasureFallback's+ * idempotent startup guard and topology-fenced owner-death policy, and never fires work.*/function initializeScheduleErasureSweep(): void {startErasureFallback();@@ -811,6 +841,43 @@ export function createSchedulesService(}}+ async function recordMCPToolAuthFailure({+ error,+ streamId,+ jobCreatedAt,+ userId,+ serverName,+ }: 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' ||+ !streamId ||+ jobCreatedAt == null ||+ !userId+ ) {+ return false;+ }+ const job = await GenerationJobManager.getJobStore()?.getJob(streamId);+ if (+ job?.createdAt !== jobCreatedAt ||+ job.userId !== userId ||+ !job.scheduleId ||+ !job.scheduledFor ||+ !job.conversationId+ ) {+ return false;+ }+ return methods.recordMCPToolAuthFailure({+ scheduleId: job.scheduleId,+ scheduledFor: new Date(job.scheduledFor),+ conversationId: job.conversationId,+ ...(job.tenantId ? { tenantId: job.tenantId } : {}),+ server: serverName,+ });+ }+const OUTCOME_RETRY_ATTEMPTS = 3;/**@@ -829,7 +896,10 @@ export function createSchedulesService(* marker, a non-stop source, or a stamp gone stale (its route presumed dead) proceeds* immediately, so the stale-owner timeout remains the bounded recovery path.*/- async function waitForStopPersistence(scheduleId: string, scheduledFor: Date): Promise<boolean> {+ async function waitForStopPersistence(+ scheduleId: string,+ scheduledFor: Date,+ ): Promise<ScheduleMCPOutcome[] | null> {const deadline = Date.now() + STOP_BARRIER_TIMEOUT_MS;for (;;) {const state = await methods.getScheduleRunAbortState(scheduleId, scheduledFor);@@ -841,7 +911,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 true;+ return state?.mcp?.filter((item) => item.detail === 'unattended_auth_required') ?? [];}if (Date.now() >= deadline) {// Still an UNACKNOWLEDGED, FRESH Stop. The poll budget expiring proves nothing about@@ -850,7 +920,7 @@ export function createSchedulesService(// its deletion/erasure barriers) while beforePublish may still be writing. DEFER// instead: the acknowledgement settles it, or the stale-owner cutoff authorizes a// later attempt.- return false;+ return null;}await new Promise((resolve) => setTimeout(resolve, STOP_BARRIER_POLL_MS));}@@ -871,18 +941,26 @@ export function createSchedulesService(return true;}const terminal = status !== 'requires_action';+ let mcp: ScheduleMCPOutcome[] = [];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// must report "not settled" so callers with durable retry (the approval-expiry host// action, reconciliation) re-drive it rather than assuming the outcome landed.- if (!(await waitForStopPersistence(scheduleId, new Date(scheduledFor)))) {+ const observed = await waitForStopPersistence(scheduleId, new Date(scheduledFor));+ if (observed == null) {logger.info(`[schedules] deferring terminal settlement for ${scheduleId}: interactive Stop persistence is still unacknowledged`,);return false;}+ mcp = observed;}+ const missingAuth =+ mcp.length > 0 &&+ (status === 'success' || status === 'error' || status === 'skipped_balance');+ const effectiveStatus = missingAuth ? 'error' : status;+ const effectiveError = missingAuth ? 'MCP unattended authorization unavailable' : error;if (terminal && streamId && jobCreatedAt != null) {try {await GenerationJobManager.updateMetadata(@@ -890,13 +968,13 @@ export function createSchedulesService({preserveForScheduleReconcile: true,scheduleOutcome:- status === 'success' ||- status === 'error' ||- status === 'interrupted' ||- status === 'skipped_balance'- ? status+ effectiveStatus === 'success' ||+ effectiveStatus === 'error' ||+ effectiveStatus === 'interrupted' ||+ effectiveStatus === 'skipped_balance'+ ? effectiveStatus: 'error',- ...(error ? { scheduleOutcomeError: error } : {}),+ ...(effectiveError ? { scheduleOutcomeError: effectiveError } : {}),},jobCreatedAt,);@@ -915,13 +993,14 @@ export function createSchedulesService(await methods.recordRunOutcome({scheduleId,scheduledFor: new Date(scheduledFor),- status,+ status: effectiveStatus,clearConversationId,conversationId,...(status === 'requires_action' && checkpointNamespace != null? { checkpointNamespace }: {}),- error,+ error: effectiveError,+ ...(mcp.length > 0 ? { mcp } : {}),autoDisableAfterFailures: limits.autoDisableAfterFailures,balanceSkipDisableThreshold: BALANCE_SKIP_DISABLE_THRESHOLD,});@@ -1716,6 +1795,7 @@ export function createSchedulesService(engineDeps,fireScheduleNow,recordScheduleOutcome,+ recordMCPToolAuthFailure,beginScheduledStop,acknowledgeScheduledStopPersistence,claimScheduleResume,diff --git a/packages/data-provider/src/types/schedules.spec.ts b/packages/data-provider/src/types/schedules.spec.tsnew file mode 100644index 0000000000..3514d73306--- /dev/null+++ b/packages/data-provider/src/types/schedules.spec.ts@@ -0,0 +1,34 @@+import { z } from 'zod';+import {+ getScheduleMCPDisabledReason,+ readScheduleMCPOutcomes,+ scheduleMCPOutcomeSchema,+} from './schedules';++it('preserves the previous wire status while providing an optional unattended-auth diagnosis', () => {+ const outcome = {+ server: 'Graph',+ status: 'mcp_configuration_missing' as const,+ detail: 'unattended_auth_required' as const,+ };+ // Represents the schema used by an open tab from before this feature.+ const previousClientSchema = z.object({+ server: z.string(),+ agentId: z.string().optional(),+ status: z.enum([+ 'ready',+ 'mcp_reauth_required',+ 'mcp_configuration_missing',+ 'mcp_permission_denied',+ 'mcp_unavailable',+ ]),+ });+ expect(previousClientSchema.array().parse([outcome])).toEqual([+ { server: 'Graph', status: 'mcp_configuration_missing' },+ ]);+ expect(scheduleMCPOutcomeSchema.parse(outcome)).toEqual(outcome);+ expect(getScheduleMCPDisabledReason([outcome])).toBe('mcp_configuration_missing');+ expect(+ readScheduleMCPOutcomes(`mcp_configuration_missing: ${JSON.stringify([outcome])}`),+ ).toEqual([outcome]);+});diff --git a/packages/data-provider/src/types/schedules.ts b/packages/data-provider/src/types/schedules.tsindex 1575c21e30..b62f492d69 100644--- a/packages/data-provider/src/types/schedules.ts+++ b/packages/data-provider/src/types/schedules.ts@@ -209,6 +209,8 @@ export const scheduleMCPOutcomeSchema = z.object({/** Agent whose selected tool requires this server. Used to open the correct* recovery chat when the requirement belongs to a handoff or subagent. */agentId: z.string().optional(),+ /** Additional diagnosis; older clients ignore unknown keys and retain the known status. */+ detail: z.enum(['unattended_auth_required']).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 4f3f012637..dc4faee158 100644--- a/packages/data-schemas/src/methods/schedule.methods.spec.ts+++ b/packages/data-schemas/src/methods/schedule.methods.spec.ts@@ -3042,6 +3042,223 @@ describe('erasure sweep rotation and idempotency-key lookup', () => {});});+describe('scheduled MCP tool failure receipt', () => {+ it('records only the matching active run and preserves the backwards-compatible failure', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-09-09T14:00:00Z');+ await methods.insertScheduleRun(runData(schedule, { scheduledFor, conversationId: 'c1' }));+ const input = { scheduleId: schedule.id, scheduledFor, conversationId: 'c1', server: 'Graph' };+ expect(await methods.recordMCPToolAuthFailure({ ...input, conversationId: 'another' })).toBe(+ false,+ );+ expect(await methods.recordMCPToolAuthFailure({ ...input, tenantId: 'other-tenant' })).toBe(+ false,+ );+ expect(await methods.recordMCPToolAuthFailure(input)).toBe(true);+ expect(await methods.recordMCPToolAuthFailure(input)).toBe(true);+ const run = await methods.getScheduleRunAbortState(schedule.id, scheduledFor);+ expect(run?.mcp).toEqual([+ { server: 'Graph', status: 'mcp_configuration_missing', detail: 'unattended_auth_required' },+ ]);+ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'error',+ mcp: run!.mcp,+ error: `mcp_configuration_missing: ${JSON.stringify(run!.mcp)}`,+ autoDisableAfterFailures: 5,+ });+ const after = await getSchedule(schedule.id);+ expect(after.enabled).toBe(false);+ expect(after.disabledReason).toBe('mcp_configuration_missing');+ expect(after.lastRun?.mcp).toEqual(run!.mcp);+ expect(await methods.recordMCPToolAuthFailure(input)).toBe(false);+ });+});++describe('scheduled MCP receipt settlement', () => {+ const failure = {+ server: 'Graph',+ status: 'mcp_configuration_missing' as const,+ detail: 'unattended_auth_required' as const,+ };+ const ready = { server: 'Graph', status: 'ready' as const };++ it.each(['success', 'skipped_balance', 'error'] as const)(+ 'keeps a persisted receipt through post-enqueue writes and settles %s as a permanent failure',+ async (status) => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-09-09T15:00:00Z');+ const input = {+ scheduleId: schedule.id,+ scheduledFor,+ conversationId: 'c1',+ server: 'Graph',+ };+ await methods.insertScheduleRun(+ runData(schedule, {+ scheduledFor,+ conversationId: 'c1',+ configRevision: schedule.configRevision,+ mcp: [ready],+ }),+ );++ expect(await methods.recordMCPToolAuthFailure(input)).toBe(true);+ await methods.setRunFireDetails(schedule.id, scheduledFor, {+ conversationId: 'c1',+ mcp: [ready],+ droppedFileIds: ['missing-file'],+ });+ expect((await getRun(schedule.id, scheduledFor)).mcp).toEqual([ready, failure]);++ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status,+ conversationId: 'c1',+ ...(status === 'success' ? { mcp: [ready] } : {}),+ ...(status === 'error' ? { error: 'Run ended in error' } : {}),+ autoDisableAfterFailures: Number.MAX_SAFE_INTEGER,+ balanceSkipDisableThreshold: 3,+ });+ const result = await getRun(schedule.id, scheduledFor);+ const card = await getSchedule(schedule.id);+ 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.failureCount).toBe(1);+ expect(card.balanceSkipCount).toBe(0);+ expect(card.lastRun?.error).toBe(+ status === 'error' ? 'Run ended in error' : 'MCP unattended authorization unavailable',+ );+ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'success',+ autoDisableAfterFailures: Number.MAX_SAFE_INTEGER,+ });+ expect((await getSchedule(schedule.id)).failureCount).toBe(1);+ expect(await methods.recordMCPToolAuthFailure(input)).toBe(false);+ },+ );++ it('lets the receipt and terminal settlement linearize in either order', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-09-09T16:00:00Z');+ await methods.insertScheduleRun(runData(schedule, { scheduledFor, conversationId: 'c1' }));+ const [recorded] = await Promise.all([+ methods.recordMCPToolAuthFailure({+ scheduleId: schedule.id,+ scheduledFor,+ conversationId: 'c1',+ server: 'Graph',+ }),+ methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'success',+ autoDisableAfterFailures: Number.MAX_SAFE_INTEGER,+ }),+ ]);+ 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.lastRun?.status).toBe(run.status);+ });++ it('does not restore a cleared conversation ID from late fire bookkeeping', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-09-09T17:00:00Z');+ await methods.insertScheduleRun(runData(schedule, { scheduledFor, conversationId: 'c1' }));+ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'interrupted',+ clearConversationId: true,+ autoDisableAfterFailures: 5,+ });+ await methods.setRunFireDetails(schedule.id, scheduledFor, {+ conversationId: 'c1',+ mcp: [ready],+ });+ const result = await getRun(schedule.id, scheduledFor);+ expect(result.conversationId).toBeUndefined();+ expect(result.mcp).toBeUndefined();+ });++ it('fences an old receipt from disabling a schedule the owner has edited', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-09-09T18:00:00Z');+ await methods.insertScheduleRun(+ runData(schedule, { scheduledFor, conversationId: 'c1', configRevision: 0 }),+ );+ await methods.recordMCPToolAuthFailure({+ scheduleId: schedule.id,+ scheduledFor,+ conversationId: 'c1',+ server: 'Graph',+ });+ await Schedule.updateOne({ id: schedule.id }, { $inc: { configRevision: 1 } });++ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'success',+ autoDisableAfterFailures: 5,+ });+ expect((await getRun(schedule.id, scheduledFor)).status).toBe('error');+ expect(await getSchedule(schedule.id)).toMatchObject({ enabled: true, failureCount: 0 });+ expect((await getSchedule(schedule.id)).lastRun).toBeUndefined();+ });++ it('replays a receipt when schedule bookkeeping fails after the run terminalizes', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scheduledFor = new Date('2026-09-09T19:00:00Z');+ await methods.insertScheduleRun(runData(schedule, { scheduledFor, conversationId: 'c1' }));+ await methods.recordMCPToolAuthFailure({+ scheduleId: schedule.id,+ scheduledFor,+ conversationId: 'c1',+ server: 'Graph',+ });+ const firstWrite = jest+ .spyOn(Schedule, 'updateOne')+ .mockRejectedValueOnce(new Error('DB unavailable'));+ await expect(+ methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor,+ status: 'success',+ autoDisableAfterFailures: Number.MAX_SAFE_INTEGER,+ }),+ ).rejects.toThrow('DB unavailable');+ firstWrite.mockRestore();+ const pending = await getRun(schedule.id, scheduledFor);+ expect(pending).toMatchObject({ status: 'error', bookkept: false, mcp: [failure] });++ const replay = {+ scheduleId: schedule.id,+ scheduledFor,+ status: 'error' as const,+ conversationId: 'c1',+ error: pending.error,+ mcp: pending.mcp,+ autoDisableAfterFailures: Number.MAX_SAFE_INTEGER,+ };+ await methods.finalizeBookkeeping(replay);+ await methods.finalizeBookkeeping(replay);+ expect((await getRun(schedule.id, scheduledFor)).bookkept).toBe(true);+ expect(await getSchedule(schedule.id)).toMatchObject({+ enabled: false,+ disabledReason: 'mcp_configuration_missing',+ failureCount: 1,+ });+ });+});+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 e5ed0240f4..dc6e29b631 100644--- a/packages/data-schemas/src/methods/schedule.ts+++ b/packages/data-schemas/src/methods/schedule.ts@@ -266,8 +266,16 @@ export type ScheduleMethods = {scheduledFor: Date,) => Promise<Pick<IScheduleRun,- 'status' | 'abortRequestedAt' | 'abortSource' | 'abortPersistedAt'+ 'status' | 'abortRequestedAt' | 'abortSource' | 'abortPersistedAt' | 'mcp'> | null>;+ /** Records an exact live generation's missing OBO authorization before the tool returns. */+ recordMCPToolAuthFailure: (input: {+ scheduleId: string;+ scheduledFor: Date;+ conversationId: string;+ tenantId?: string;+ server: string;+ }) => Promise<boolean>;markRunResumeClaimed: (scheduleId: string,scheduledFor: Date,@@ -1037,14 +1045,14 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): SchescheduledFor: Date,): Promise<Pick<IScheduleRun,- 'status' | 'abortRequestedAt' | 'abortSource' | 'abortPersistedAt'+ 'status' | 'abortRequestedAt' | 'abortSource' | 'abortPersistedAt' | 'mcp'> | null> {return ScheduleRun().findOne({ scheduleId, scheduledFor })- .select('status abortRequestedAt abortSource abortPersistedAt')+ .select('status abortRequestedAt abortSource abortPersistedAt mcp').lean<Pick<IScheduleRun,- 'status' | 'abortRequestedAt' | 'abortSource' | 'abortPersistedAt'+ 'status' | 'abortRequestedAt' | 'abortSource' | 'abortPersistedAt' | 'mcp'> | null>();}@@ -1115,6 +1123,31 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche);}+ async function recordMCPToolAuthFailure({+ scheduleId,+ scheduledFor,+ conversationId,+ tenantId,+ server,+ }: Parameters<ScheduleMethods['recordMCPToolAuthFailure']>[0]): Promise<boolean> {+ const updated = await ScheduleRun().updateOne(+ {+ scheduleId,+ scheduledFor,+ conversationId,+ ...(tenantId ? { tenantId } : { tenantId: { $exists: false } }),+ status: { $in: ['started', 'requires_action'] },+ },+ {+ $addToSet: {+ mcp: { server, status: 'mcp_configuration_missing', detail: 'unattended_auth_required' },+ },+ },+ { timestamps: false },+ );+ return (updated.matchedCount ?? 0) > 0;+ }+/** Count of in-flight scheduled runs (across all schedules) for the fire cap. */async function countActiveRuns(): Promise<number> {return ScheduleRun().countDocuments({ status: 'started' });@@ -1463,39 +1496,77 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche// TERMINAL: flip the run row (match-guarded), then apply bookkeeping. `bookkept` is// set false at the flip and true only after bookkeeping lands, so a crash between is// re-applied by the reconciler (getUnbookkeptRuns) while countedFor keeps counters idempotent.- const settled = await ScheduleRun()+ const runFilter = {+ scheduleId: params.scheduleId,+ scheduledFor: params.scheduledFor,+ status: { $in: ['started', 'requires_action'] },+ };+ const canOverride =+ params.status === 'success' ||+ params.status === 'error' ||+ params.status === 'skipped_balance';+ const incomingFailure =+ canOverride && params.mcp?.some((item) => item.detail === 'unattended_auth_required');+ const authError =+ params.status === 'error' && params.error+ ? params.error+ : 'MCP unattended authorization unavailable';+ const terminalUpdate = (+ status: RecordRunOutcomeParams['status'],+ error: string | undefined,+ includeInputMcp: boolean,+ ) => ({+ $set: {+ status,+ bookkept: false,+ settledAt: firedAt,+ ...(params.conversationId && !params.clearConversationId+ ? { conversationId: params.conversationId }+ : {}),+ ...(error ? { error } : {}),+ ...(includeInputMcp && params.mcp ? { mcp: params.mcp } : {}),+ ...(params.durationMs != null ? { durationMs: params.durationMs } : {}),+ },+ // Only terminal settlement releases the global capacity slot, not an abort request.+ $unset: {+ capacitySlot: 1,+ admissionOnly: 1,+ ...(params.clearConversationId ? { conversationId: 1 } : {}),+ },+ });+ // The absence check is part of the row update, not a stale read. A concurrent+ // receipt either wins first (the fallback below records an error) or loses to+ // terminalization (and can no longer stamp this run).+ let settled = await ScheduleRun().findOneAndUpdate({- scheduleId: params.scheduleId,- scheduledFor: params.scheduledFor,- status: { $in: ['started', 'requires_action'] },- },- {- $set: {- status: params.status,- bookkept: false,- settledAt: firedAt,- ...(params.conversationId && !params.clearConversationId- ? { conversationId: params.conversationId }- : {}),- ...(params.error ? { error: params.error } : {}),- ...(params.mcp ? { mcp: params.mcp } : {}),- ...(params.durationMs != null ? { durationMs: params.durationMs } : {}),- },- // SETTLEMENT: a terminal outcome is the generation owner confirming the run- // actually stopped, so this is the ONLY place the global capacity slot is- // released. An abort request alone does not free it (see requestRunAbort).- $unset: {- capacitySlot: 1,- admissionOnly: 1,- ...(params.clearConversationId ? { conversationId: 1 } : {}),- },+ ...runFilter,+ ...(canOverride ? { 'mcp.detail': { $ne: 'unattended_auth_required' } } : {}),},+ terminalUpdate(+ incomingFailure ? 'error' : params.status,+ incomingFailure ? authError : params.error,+ true,+ ),{ new: false },).lean<IScheduleRun>();- // No-match guard: never touch schedule bookkeeping without a matching run- // (protects against a spoofed scheduleId on a normal chat).+ let effectiveParams = incomingFailure+ ? { ...params, status: 'error' as const, error: authError }+ : params;+ if (settled == null && canOverride) {+ settled = await ScheduleRun()+ .findOneAndUpdate(+ { ...runFilter, 'mcp.detail': 'unattended_auth_required' },+ terminalUpdate('error', authError, false),+ { new: false },+ )+ .lean<IScheduleRun>();+ if (settled != null) {+ effectiveParams = { ...params, status: 'error', error: authError, mcp: settled.mcp };+ }+ }+ // No-match guard: never touch schedule bookkeeping without a matching run.if (settled == null) {return;}@@ -1503,7 +1574,7 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche// 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// balance-skip paths previously shipped unfenced.- if (params.status === 'skipped_balance') {+ if (effectiveParams.status === 'skipped_balance') {await applyBalanceSkipBookkeeping({scheduleId: params.scheduleId,scheduledFor: params.scheduledFor,@@ -1514,7 +1585,7 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche});} else {await applyTerminalBookkeeping({- ...params,+ ...effectiveParams,firedAt: settled.firedAt ?? firedAt,expectConfigRevision: settled.configRevision,});@@ -1597,13 +1668,13 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Schedetails: { conversationId: string; droppedFileIds?: string[]; mcp?: IScheduleRun['mcp'] },): Promise<void> {await ScheduleRun().updateOne(- { scheduleId, scheduledFor },+ { scheduleId, scheduledFor, conversationId: details.conversationId },{$set: {conversationId: details.conversationId,- ...(details.mcp ? { mcp: details.mcp } : {}),...(details.droppedFileIds?.length ? { droppedFileIds: details.droppedFileIds } : {}),},+ ...(details.mcp?.length ? { $addToSet: { mcp: { $each: details.mcp } } } : {}),},);}@@ -2148,6 +2219,7 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): SchepersistResolvedProject,getScheduleRunProject,getScheduleRunAbortState,+ recordMCPToolAuthFailure,markRunResumeClaimed,releaseRunResumeClaim,markRunAbortPersisted,diff --git a/packages/data-schemas/src/schema/schedule.ts b/packages/data-schemas/src/schema/schedule.tsindex 0990cad5b9..e52cf95863 100644--- a/packages/data-schemas/src/schema/schedule.ts+++ b/packages/data-schemas/src/schema/schedule.ts@@ -232,6 +232,7 @@ const scheduleSchema: Schema<IScheduleDocument> = new Schema(_id: false,server: { type: String, required: true },agentId: { type: String },+ detail: { type: String, enum: ['unattended_auth_required'] },status: {type: String,required: true,diff --git a/packages/data-schemas/src/schema/scheduleRun.ts b/packages/data-schemas/src/schema/scheduleRun.tsindex b51a105a60..ba685bee99 100644--- a/packages/data-schemas/src/schema/scheduleRun.ts+++ b/packages/data-schemas/src/schema/scheduleRun.ts@@ -71,6 +71,7 @@ const scheduleRunSchema: Schema<IScheduleRunDocument> = new Schema(_id: false,server: { type: String, required: true },agentId: { type: String },+ detail: { type: String, enum: ['unattended_auth_required'] },status: {type: String,required: true,