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: Close Only Scheduled MCP Authority at Request Cleanup (#17354)
Danny Avila253112ff8dec
diff --git a/packages/api/src/mcp/__tests__/scope.integration.test.ts b/packages/api/src/mcp/__tests__/scope.integration.test.tsindex d88e744ff4..41f307af2b 100644--- a/packages/api/src/mcp/__tests__/scope.integration.test.ts+++ b/packages/api/src/mcp/__tests__/scope.integration.test.ts@@ -187,6 +187,18 @@ function createServerConfig(url: string): ParsedServerConfig {};}+/** Static headers keep the connection pooled per user instead of per request. */+function createPooledConfig(url: string): ParsedServerConfig {+ return {+ type: 'streamable-http',+ url,+ source: 'yaml',+ requiresOAuth: false,+ initTimeout: 500,+ headers: { 'X-Run-Id': 'static' },+ };+}+function callEcho({manager,config,@@ -541,6 +553,68 @@ describe('request-scoped MCP lifecycle integration', () => {expect(server.toolCallCount()).toBe(1);expect(new Set(server.observedRunIds())).toEqual(new Set(['recovery-run']));});++ it('lets a pooled call outlive the turn that cleaned its context, keeping request-scoped servers closed', async () => {+ const turn = createContext();+ const callPooled = () =>+ callEcho({+ manager,+ config: createPooledConfig(server.url),+ requestScopedConnections: turn,+ runId: 'run-1',+ value: 'select 1',+ serverName: 'pooled',+ });+ try {+ await callPooled();+ expect(server.toolCallCount()).toBe(1);+ expect(turn.connections.size).toBe(0);++ await cleanupMCPRequestContext(turn);+ expect(turn.cleanupStarted).toBe(true);++ // A detached child keeps the parent's context after the parent turn ends.+ await expect(callPooled()).resolves.toBeDefined();+ expect(server.toolCallCount()).toBe(2);+ await expect(+ callEcho({+ manager,+ config: createServerConfig(server.url),+ requestScopedConnections: turn,+ runId: 'run-1',+ value: 'late',+ }),+ ).rejects.toThrow('Request-scoped connection context is closed');+ expect(server.toolCallCount()).toBe(2);+ } finally {+ await manager.disconnectUserConnection(user.id, 'pooled').catch(() => undefined);+ MCPConnection.clearCooldown('pooled');+ }+ });++ it('creates a pooled connection on the first call after its turn cleaned the context', async () => {+ const turn = createContext();+ await cleanupMCPRequestContext(turn);+ expect(turn.cleanupStarted).toBe(true);+ try {+ // A detached child's first call to a server its parent never used.+ await expect(+ callEcho({+ manager,+ config: createPooledConfig(server.url),+ requestScopedConnections: turn,+ runId: 'run-1',+ value: 'select 1',+ serverName: 'pooled-late',+ }),+ ).resolves.toBeDefined();+ expect(server.toolCallCount()).toBe(1);+ expect(turn.connections.size).toBe(0);+ } finally {+ await manager.disconnectUserConnection(user.id, 'pooled-late').catch(() => undefined);+ MCPConnection.clearCooldown('pooled-late');+ }+ });});describe('operator requestHeaders integration', () => {diff --git a/packages/api/src/schedules/bearer.spec.ts b/packages/api/src/schedules/bearer.spec.tsindex 91b9850e15..00919f62ea 100644--- a/packages/api/src/schedules/bearer.spec.ts+++ b/packages/api/src/schedules/bearer.spec.ts@@ -349,6 +349,26 @@ it('withholds provider completion when request cleanup closes the occurrence durawait expect(f.call()).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } });});+it('closes scheduled authority at request cleanup without closing unscheduled calls', async () => {+ const unscheduled = createMCPRequestContext();+ const scheduled = createMCPRequestContext();+ attachScheduledMCPBearer(scheduled, identity);+ await cleanupMCPRequestContext(unscheduled);+ await cleanupMCPRequestContext(scheduled);+ expect(unscheduled.cleanupStarted).toBe(true);+ expect(scheduled.cleanupStarted).toBe(true);+ // A detached child's interactive call after its parent turn cleaned up keeps the declared config.+ await expect(+ resolveScheduledMCPBearerConfig({ context: unscheduled, config, user, serverName: 'Files' }),+ ).resolves.toBe(config);+ await expect(+ resolveScheduledMCPBearerConfig({ context: scheduled, config, user, serverName: 'Files' }),+ ).rejects.toMatchObject({+ name: 'ScheduledMCPBearerError',+ failure: { reason: 'binding_mismatch' },+ });+});+it('does not let one cancelled waiter cancel shared minting for a sibling', async () => {const f = await bearerFixture();let resolve!: (result: ScheduledMCPBearerResult) => void;diff --git a/packages/api/src/schedules/bearer.ts b/packages/api/src/schedules/bearer.tsindex 4ad2bd0989..1bffae63fc 100644--- a/packages/api/src/schedules/bearer.ts+++ b/packages/api/src/schedules/bearer.ts@@ -439,42 +439,43 @@ export async function resolveScheduledMCPBearerConfig(context?: RequestScopedMCPConnectionStore;},): Promise<ParsedServerConfig> {- if (input.context?.quiesceStarted) throw new MCPRequestQuiescedError();- if (input.context?.cleanupStarted)+ const { context } = input;+ if (context?.quiesceStarted) throw new MCPRequestQuiescedError();+ const scope = context && scopes.get(context);+ /** Cleanup ends scheduled authority only; request-scoped checkout refuses a closed context. */+ if (!context || !scope) return input.config;+ if (context.cleanupStarted)throw new ScheduledMCPBearerError('binding_mismatch', input.serverName);- const scope = input.context && scopes.get(input.context);- let config = input.config;- if (scope && input.context) {- const requestSignal = getMCPRequestSignal(input.context);- const signal = input.signal ? AbortSignal.any([input.signal, requestSignal]) : requestSignal;- signal.throwIfAborted();- let knownFailure: Promise<never> | undefined;- let observedError: ScheduledMCPBearerError | undefined;- const observe = (error: ScheduledMCPBearerError): void => {- if (observedError === error) return;- observedError = error;- input.onFailure?.(error);- const admission = admitBearerFailure(input.context!, error);- const failure = Promise.resolve(admission).then((): never => {- throw error;- });- knownFailure ??= failure;- holdMCPRequestFailure(failure);- };- // Observe before any outer waiter detaches; receipt admission has a separate lifetime.- const operation = scope.resolve({ ...input, signal, onFailure: observe }).catch((error) => {- if (error instanceof ScheduledMCPBearerError) observe(error);+ const requestSignal = getMCPRequestSignal(context);+ const signal = input.signal ? AbortSignal.any([input.signal, requestSignal]) : requestSignal;+ signal.throwIfAborted();+ let knownFailure: Promise<never> | undefined;+ let observedError: ScheduledMCPBearerError | undefined;+ const observe = (error: ScheduledMCPBearerError): void => {+ if (observedError === error) return;+ observedError = error;+ input.onFailure?.(error);+ const admission = admitBearerFailure(context, error);+ const failure = Promise.resolve(admission).then((): never => {throw error;});- try {- config = await awaitOboOperation(operation, signal);- } catch (error) {- if (knownFailure) return await knownFailure;- throw error;- }+ knownFailure ??= failure;+ holdMCPRequestFailure(failure);+ };+ // Observe before any outer waiter detaches; receipt admission has a separate lifetime.+ const operation = scope.resolve({ ...input, signal, onFailure: observe }).catch((error) => {+ if (error instanceof ScheduledMCPBearerError) observe(error);+ throw error;+ });+ let config: ParsedServerConfig;+ try {+ config = await awaitOboOperation(operation, signal);+ } catch (error) {+ if (knownFailure) return await knownFailure;+ throw error;}- if (input.context?.quiesceStarted) throw new MCPRequestQuiescedError();- if (input.context?.cleanupStarted)+ if (context.quiesceStarted) throw new MCPRequestQuiescedError();+ if (context.cleanupStarted)throw new ScheduledMCPBearerError('binding_mismatch', input.serverName);return config;}