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: Cancel MCP Discovery Work at the Caller Deadline (#15353)
Danny Avilab97d2868d497
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.tsindex 4fe087b3ce..1b722dc1a7 100644--- a/packages/api/src/mcp/MCPConnectionFactory.ts+++ b/packages/api/src/mcp/MCPConnectionFactory.ts@@ -22,11 +22,10 @@ import {ReauthenticationRequiredError,resolveOboToken,} from '~/mcp/oauth';+import { createDeadlineAbortSignal, isClientRejectionMessage, isOAuthServer } from './utils';import { PENDING_STALE_MS, normalizeExpiresAt } from '~/flow/manager';-import { isClientRejectionMessage, isOAuthServer } from './utils';import { isOAuthAuthenticationError } from './errors';import { preProcessGraphTokens } from '~/utils/graph';-import { withTimeout } from '~/utils/promise';import { MCPConnection } from './connection';import { processMCPEnv } from '~/utils';import { mcpConfig } from './mcpConfig';@@ -139,6 +138,15 @@ export class MCPConnectionFactory {basic: t.BasicConnectionOptions,options?: Omit<t.OAuthConnectionOptions, 'returnOnOAuth'> | t.UserConnectionContext,): Promise<ToolDiscoveryResult> {+ /** Checked before credential preparation begins: a spent budget or an already-cancelled+ * caller must not start Graph preprocessing or token resolution it cannot cancel. */+ if (+ (options?.deadlineMs != null && Date.now() >= options.deadlineMs) ||+ options?.signal?.aborted === true+ ) {+ logger.debug('[MCP] [Discovery] Cancelled or out of budget before discovery began');+ return { tools: null, connection: null, oauthRequired: false, oauthUrl: null };+ }const preparedBasic = await this.prepareBasicConnectionOptions(basic, options);if (options != null && 'useOAuth' in options) {const factory = new this(preparedBasic, { ...options, returnOnOAuth: true });@@ -171,9 +179,19 @@ export class MCPConnectionFactory {}protected async discoverToolsInternal(): Promise<ToolDiscoveryResult> {+ /** Rechecked here because credential preparation in `discoverTools` is uncancellable: a+ * budget that expired or a caller that cancelled while it ran must not go on to token+ * resolution or a connect. */+ if (this.isDiscoveryCancelled()) {+ logger.debug(+ `${this.logPrefix} [Discovery] Cancelled or out of budget before discovery began`,+ );+ return { tools: null, connection: null, oauthRequired: false, oauthUrl: null };+ }const oauthUrl: string | null = null;let oauthRequired = false;let shouldAttemptAuthenticatedDiscovery = true;+ const abortSignal = this.createDiscoveryAbortSignal();let oauthTokens: MCPOAuthTokens | null = null;if (this.usesObo) {@@ -220,15 +238,10 @@ export class MCPConnectionFactory {connection.once('oauthRequired', oauthHandler);try {- const connectTimeout = this.resolveConnectTimeout(30000);- await withTimeout(- connection.connect(),- connectTimeout,- `Connection timeout after ${connectTimeout}ms`,- );+ await this.connectWithinBudget(connection, this.resolveConnectTimeout(30000), abortSignal);- if (await connection.isConnected()) {- const snapshot = await connection.fetchOrderedToolsSnapshot(this.deadlineMs);+ if (await connection.isConnected(abortSignal)) {+ const snapshot = await connection.fetchOrderedToolsSnapshot(this.deadlineMs, abortSignal);connection.removeListener('oauthRequired', oauthHandler);return {tools: snapshot.complete ? snapshot.tools : null,@@ -244,24 +257,24 @@ export class MCPConnectionFactory {);}- /** The authenticated attempt is done with, but `withTimeout` does not cancel the `connect()`- * it gave up on — that socket stays open. Dispose before the fallback opens a second one so- * a single discovery never holds two concurrent connects to the same server. */+ /** The authenticated attempt is done with, but abandoning `connect()` does not cancel it —+ * that socket stays open. Dispose before the fallback opens a second one so a single+ * discovery never holds two concurrent connects to the same server. */connection.removeListener('oauthRequired', oauthHandler);await this.disposeQuietly(connection);connection = null;oauthHandler = null;}- if (this.isPastDeadline()) {+ if (this.isDiscoveryCancelled()) {logger.debug(- `${this.logPrefix} [Discovery] Budget exhausted; skipping unauthenticated tool listing`,+ `${this.logPrefix} [Discovery] Cancelled or out of budget; skipping unauthenticated tool listing`,);return { tools: null, connection: null, oauthRequired, oauthUrl };}try {- const tools = await this.attemptUnauthenticatedToolListing();+ const tools = await this.attemptUnauthenticatedToolListing(abortSignal);if (tools && tools.length > 0) {logger.info(`${this.logPrefix} [Discovery] Successfully discovered ${tools.length} tools without auth`,@@ -290,6 +303,64 @@ export class MCPConnectionFactory {return this.deadlineMs != null && Date.now() >= this.deadlineMs;}+ /** The ONE cancellation predicate for discovery gates. The budget and the caller's signal are+ * two representations of the same fact; a gate that consults only one re-opens the class of+ * bug where cancelled callers keep starting work. */+ private isDiscoveryCancelled(): boolean {+ return this.isPastDeadline() || this.signal?.aborted === true;+ }++ /**+ * Races `connect()` against the discovery signal as well as the timeout. `connect()` cannot+ * carry the signal itself, so an abort rejects this wait and the caller's normal cleanup+ * disposes the attempt — the connection's mid-connect disposal guard then discards whatever+ * the abandoned connect still constructs, instead of the socket living to the full timeout.+ */+ private async connectWithinBudget(+ connection: MCPConnection,+ timeoutMs: number,+ signal?: AbortSignal,+ ): Promise<void> {+ if (signal?.aborted === true) {+ throw new Error('Discovery cancelled before connect');+ }+ const connect = connection.connect();+ /** The abandoned attempt still settles eventually; swallow its rejection so losing the race+ * never surfaces as an unhandled rejection. */+ connect.catch(() => undefined);+ let timer: NodeJS.Timeout | undefined;+ let onAbort: (() => void) | undefined;+ const interrupted = new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error(`Connection timeout after ${timeoutMs}ms`)),+ timeoutMs,+ );+ timer.unref?.();+ if (signal != null) {+ onAbort = () => reject(new Error('Discovery cancelled during connect'));+ signal.addEventListener('abort', onAbort, { once: true });+ }+ });+ try {+ return await Promise.race([connect, interrupted]);+ } finally {+ clearTimeout(timer);+ if (onAbort != null) {+ signal?.removeEventListener('abort', onAbort);+ }+ }+ }++ /**+ * One abort signal for this discovery operation: the remaining budget and the caller's own+ * cancellation, whichever fires first. It reaches only work the SDK can genuinely cancel —+ * the health probe and `tools/list` requests. Teardown is deliberately exempt: `dispose()`+ * must finish, so cancelling it would trade a bounded overrun for a leaked session.+ */+ private createDiscoveryAbortSignal(): AbortSignal | undefined {+ return createDeadlineAbortSignal(this.deadlineMs, this.signal);+ }+private async disposeQuietly(connection: MCPConnection): Promise<void> {try {await connection.dispose();@@ -298,7 +369,7 @@ export class MCPConnectionFactory {}}- protected async attemptUnauthenticatedToolListing(): Promise<Tool[] | null> {+ protected async attemptUnauthenticatedToolListing(signal?: AbortSignal): Promise<Tool[] | null> {const unauthConnection = new MCPConnection({serverName: this.serverName,serverConfig: this.serverConfig,@@ -320,11 +391,10 @@ export class MCPConnectionFactory {});try {- const connectTimeout = this.resolveConnectTimeout(15000);- await withTimeout(unauthConnection.connect(), connectTimeout, `Unauth connection timeout`);+ await this.connectWithinBudget(unauthConnection, this.resolveConnectTimeout(15000), signal);- if (await unauthConnection.isConnected()) {- const snapshot = await unauthConnection.fetchOrderedToolsSnapshot(this.deadlineMs);+ if (await unauthConnection.isConnected(signal)) {+ const snapshot = await unauthConnection.fetchOrderedToolsSnapshot(this.deadlineMs, signal);await this.disposeQuietly(unauthConnection);return snapshot.complete ? snapshot.tools : null;}@@ -357,6 +427,7 @@ export class MCPConnectionFactory {this.ephemeralConnection = basic.ephemeralConnection === true;this.connectionTimeout = options?.connectionTimeout;this.deadlineMs = options?.deadlineMs;+ this.signal = options?.signal;this.tenantContext = tenantStorage?.getStore?.();this.tenantId = this.tenantContext?.tenantId ?? getTenantId();this.logPrefix = options?.user ? `[MCP][User: ${options.user.id}]` : '[MCP]';@@ -368,7 +439,6 @@ export class MCPConnectionFactory {this.userId = options.user?.id;this.flowManager = options.flowManager;this.tokenMethods = options.tokenMethods;- this.signal = options.signal;this.oauthStart = options.oauthStart;this.oauthEnd = options.oauthEnd;this.returnOnOAuth = options.returnOnOAuth;diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex 3ce946a875..c43d4d747d 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -13,6 +13,7 @@ import type { RequestBody } from '~/types';import type * as t from './types';import {getMissingRuntimeBodyPlaceholderFields,+ createDeadlineAbortSignal,canUseAppConnection,isOAuthServer,isUserSourced,@@ -279,8 +280,18 @@ export class MCPManager extends UserConnectionManager {const existingAppConnection = useAppConnection? await this.appConnections?.get(serverName): null;- if (existingAppConnection && (await existingAppConnection.isConnected())) {- const snapshot = await existingAppConnection.fetchOrderedToolsSnapshot(args.deadlineMs);+ /** Cancels the shared connection's health probe and `tools/list` for THIS caller only —+ * an aborted probe reports false without touching the shared connection's state. Combines+ * the budget with the caller's own signal so cancelling the request also stops the work. */+ const budgetSignal =+ existingAppConnection != null+ ? createDeadlineAbortSignal(args.deadlineMs, args.signal)+ : undefined;+ if (existingAppConnection && (await existingAppConnection.isConnected(budgetSignal))) {+ const snapshot = await existingAppConnection.fetchOrderedToolsSnapshot(+ args.deadlineMs,+ budgetSignal,+ );return {tools: snapshot.complete ? snapshot.tools : null,oauthRequired: false,@@ -291,6 +302,19 @@ export class MCPManager extends UserConnectionManager {logger.debug('[MCP][Discovery] App connection unavailable; trying discovery mode');}+ /** A probe aborted by the caller is not a dead server: falling through here would open a+ * fresh connection on behalf of a request that no longer exists (or a budget already+ * spent), and the fallback keeps running after the caller has gone. */+ if (+ args.signal?.aborted === true ||+ (args.deadlineMs != null && Date.now() >= args.deadlineMs)+ ) {+ logger.debug(+ '[MCP][Discovery] Caller cancelled or budget spent; skipping discovery fallback',+ );+ return { tools: null, oauthRequired: false, oauthUrl: null };+ }+const missingBodyFields = getMissingRuntimeBodyPlaceholderFields(serverConfig,args.requestBody,@@ -351,6 +375,7 @@ export class MCPManager extends UserConnectionManager {graphTokenResolver: args.graphTokenResolver,connectionTimeout: args.connectionTimeout,deadlineMs: args.deadlineMs,+ signal: args.signal,});return finalizeDiscoveryResult(result);}diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.tsindex d01b4f0677..094a6d396c 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts@@ -4236,7 +4236,7 @@ describe('MCPConnectionFactory', () => {]);});- it('skips the unauthenticated fallback once the deadline has passed', async () => {+ it('skips discovery entirely once the deadline has passed', async () => {const events: string[] = [];trackConnections(events);@@ -4246,6 +4246,97 @@ describe('MCPConnectionFactory', () => {);expect(result.tools).toBeNull();+ expect(events).toEqual([]);+ expect(mockMCPConnection).not.toHaveBeenCalled();+ expect(mockPreProcessGraphTokens).not.toHaveBeenCalled();+ });++ it('stops before token resolution when the budget expires during credential preparation', async () => {+ const events: string[] = [];+ trackConnections(events);+ mockPreProcessGraphTokens.mockImplementationOnce(async (options) => {+ await new Promise((resolve) => setTimeout(resolve, 60));+ return options;+ });++ const result = await MCPConnectionFactory.discoverTools(+ { serverName: 'test-server', serverConfig: mockServerConfig },+ { deadlineMs: Date.now() + 20, graphTokenResolver: jest.fn() },+ );++ expect(result.tools).toBeNull();+ expect(events).toEqual([]);+ expect(mockMCPConnection).not.toHaveBeenCalled();+ });++ it('skips discovery entirely for a caller whose signal is already aborted', async () => {+ const events: string[] = [];+ trackConnections(events);+ const controller = new AbortController();+ controller.abort();++ const result = await MCPConnectionFactory.discoverTools(+ { serverName: 'test-server', serverConfig: mockServerConfig },+ { signal: controller.signal },+ );++ expect(result.tools).toBeNull();+ expect(events).toEqual([]);+ expect(mockMCPConnection).not.toHaveBeenCalled();+ expect(mockPreProcessGraphTokens).not.toHaveBeenCalled();+ });++ it('stops before connecting when the caller aborts during credential preparation', async () => {+ const events: string[] = [];+ trackConnections(events);+ const controller = new AbortController();+ mockPreProcessGraphTokens.mockImplementationOnce(async (options) => {+ controller.abort();+ return options;+ });++ const result = await MCPConnectionFactory.discoverTools(+ { serverName: 'test-server', serverConfig: mockServerConfig },+ { signal: controller.signal, graphTokenResolver: jest.fn() },+ );++ expect(result.tools).toBeNull();+ expect(mockMCPConnection).not.toHaveBeenCalled();+ });++ it('abandons a hung connect promptly when a signal-only caller aborts mid-connect', async () => {+ const events: string[] = [];+ let index = 0;+ mockMCPConnection.mockImplementation(() => {+ const label = index++ === 0 ? 'auth' : 'unauth';+ return {+ connect: jest.fn(() => {+ events.push(`${label}:connect`);+ return new Promise(() => {});+ }),+ isConnected: jest.fn().mockResolvedValue(false),+ setOAuthTokens: jest.fn(),+ on: jest.fn(),+ once: jest.fn(),+ off: jest.fn(),+ removeListener: jest.fn(),+ emit: jest.fn(),+ dispose: jest.fn(async () => {+ events.push(`${label}:dispose`);+ }),+ } as unknown as jest.Mocked<MCPConnection>;+ });+ const controller = new AbortController();+ setTimeout(() => controller.abort(), 20);++ const start = Date.now();+ const result = await MCPConnectionFactory.discoverTools(+ { serverName: 'test-server', serverConfig: mockServerConfig },+ { signal: controller.signal },+ );++ expect(result.tools).toBeNull();+ expect(Date.now() - start).toBeLessThan(2000);expect(events).toEqual(['auth:connect', 'auth:dispose']);expect(mockMCPConnection).toHaveBeenCalledTimes(1);});@@ -4263,7 +4354,11 @@ describe('MCPConnectionFactory', () => {{ deadlineMs },);- expect(mockConnectionInstance.fetchOrderedToolsSnapshot).toHaveBeenCalledWith(deadlineMs);+ expect(mockConnectionInstance.fetchOrderedToolsSnapshot).toHaveBeenCalledWith(+ deadlineMs,+ expect.any(AbortSignal),+ );+ expect(mockConnectionInstance.isConnected).toHaveBeenCalledWith(expect.any(AbortSignal));});it('clamps a long initTimeout to the remaining budget instead of waiting it out', async () => {diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.tsindex 8805b887b8..705b9ef89d 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts@@ -296,6 +296,7 @@ describe('MCPConnection.fetchTools pagination', () => {.spyOn(Date, 'now').mockReturnValueOnce(deadline - 20).mockReturnValueOnce(deadline - 20)+ .mockReturnValueOnce(deadline - 20).mockReturnValue(deadline + 1);const snapshot = await conn.fetchToolsSnapshot(deadline);@@ -306,15 +307,42 @@ describe('MCPConnection.fetchTools pagination', () => {dateNow.mockRestore();});- it('returns an incomplete empty snapshot without a request when the deadline has passed', async () => {+ it('returns an incomplete empty snapshot without a request or a reservation when the deadline has passed', async () => {const listTools = jest.fn();const conn = createConnectionWithListTools(listTools);+ const reserve = jest.spyOn(conn, 'reserveToolsPublicationRevision');const snapshot = await conn.fetchToolsSnapshot(Date.now() - 1);expect(snapshot.tools).toEqual([]);expect(snapshot.complete).toBe(false);expect(listTools).not.toHaveBeenCalled();+ expect(reserve).not.toHaveBeenCalled();+ });++ it('hands the caller signal to the SDK so an in-flight page is cancellable', async () => {+ const listTools = jest.fn().mockResolvedValue({ tools: [makeTool('a')] });+ const conn = createConnectionWithListTools(listTools);+ const signal = AbortSignal.timeout(5000);++ await conn.fetchToolsSnapshot(Date.now() + 5000, signal);++ const options = listTools.mock.calls[0][1]!;+ expect(options.signal).toBe(signal);+ });++ it('makes no request and no reservation when the signal is already aborted', async () => {+ const listTools = jest.fn();+ const conn = createConnectionWithListTools(listTools);+ const reserve = jest.spyOn(conn, 'reserveToolsPublicationRevision');+ const controller = new AbortController();+ controller.abort();++ const snapshot = await conn.fetchToolsSnapshot(undefined, controller.signal);++ expect(snapshot.complete).toBe(false);+ expect(listTools).not.toHaveBeenCalled();+ expect(reserve).not.toHaveBeenCalled();});it('stops waiting on an in-flight refresh that outlasts the caller deadline', async () => {@@ -341,6 +369,30 @@ describe('MCPConnection.fetchTools pagination', () => {expect(Date.now() - start).toBeLessThan(2000);});+ it('stops waiting on an in-flight refresh when the caller signal aborts, without a deadline', async () => {+ mcpConfig.TOOLS_LIST_TIMEOUT_MS = 30000;+ const conn = createConnectionWithListTools(jest.fn());+ const mutable = conn as unknown as {+ toolListChangeGeneration: number;+ toolListRefreshPromise: Promise<void> | null;+ };+ const listTools = jest.fn(async () => {+ mutable.toolListChangeGeneration = 1;+ return { tools: [makeTool('a')] };+ });+ conn.client.listTools = listTools;+ mutable.toolListRefreshPromise = new Promise<void>(() => {});+ jest.spyOn(conn.client, 'getServerCapabilities').mockReturnValue({ tools: {} });+ const controller = new AbortController();+ setTimeout(() => controller.abort(), 20);++ const start = Date.now();+ const snapshot = await conn.fetchOrderedToolsSnapshot(undefined, controller.signal);++ expect(snapshot.complete).toBe(false);+ expect(Date.now() - start).toBeLessThan(2000);+ });+it('stops and warns when the server repeats a cursor instead of looping forever', async () => {const listTools = jest.fn().mockResolvedValue({ tools: [makeTool('x')], nextCursor: 'same' });const conn = createConnectionWithListTools(listTools);diff --git a/packages/api/src/mcp/__tests__/MCPConnectionProbeAbort.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionProbeAbort.test.tsnew file mode 100644index 0000000000..cb09696e85--- /dev/null+++ b/packages/api/src/mcp/__tests__/MCPConnectionProbeAbort.test.ts@@ -0,0 +1,80 @@+/**+ * Real-SDK coverage for aborting the `isConnected` health probe.+ *+ * The probe's `client.ping()` carries only the SDK's own 60s default timeout, so a budgeted+ * discovery caller probing an unresponsive server would otherwise hold its fan-out slot for that+ * long. The caller's signal must cancel the in-flight ping — and, because the probed connection+ * can be the shared app connection, an aborted probe must report `false` without disturbing the+ * connection's state for everyone else.+ *+ * The client, transport, and server are real SDK objects; the server is made unresponsive by+ * swallowing its inbound messages after the handshake, which no mock of our own code could model.+ */+import { Server } from '@modelcontextprotocol/sdk/server/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';+import { MCPConnection } from '~/mcp/connection';++jest.setTimeout(10_000);++jest.mock('@librechat/data-schemas', () => ({+ logger: {+ info: jest.fn(),+ warn: jest.fn(),+ error: jest.fn(),+ debug: jest.fn(),+ },+}));++jest.mock('~/auth', () => ({+ createSSRFSafeUndiciConnect: jest.fn(() => undefined),+ isOAuthUrlAllowed: jest.fn(() => false),+ isSSRFTarget: jest.fn(() => false),+ resolveHostnameSSRF: jest.fn(async () => false),+}));++describe('MCPConnection health-probe abort', () => {+ let server: Server | undefined;++ afterEach(async () => {+ await server?.close().catch(() => undefined);+ server = undefined;+ });++ it('cancels a hung ping at the caller signal without disturbing connection state', async () => {+ server = new Server(+ { name: 'probe-abort-server', version: '1.0.0' },+ { capabilities: { tools: {} } },+ );+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [] }));++ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);++ const connection = new MCPConnection({+ serverName: 'probe-abort',+ serverConfig: { type: 'streamable-http', url: 'http://localhost/mcp' },+ useSSRFProtection: false,+ });+ await connection.client.connect(clientTransport);+ connection.emit('connectionChange', 'connected');++ /** The handshake used the real server; from here on it swallows every request, so the+ * ping stays in flight until the signal cancels it. */+ serverTransport.onmessage = () => {};++ const start = Date.now();+ const alive = await connection.isConnected(AbortSignal.timeout(40));++ expect(alive).toBe(false);+ expect(Date.now() - start).toBeLessThan(2000);+ const state = (connection as unknown as { connectionState: string }).connectionState;+ expect(state).toBe('connected');++ /** The aborted probe answered nothing, so it must not stamp the health-check TTL: with the+ * server now genuinely gone, the next unbudgeted caller has to probe for real and see it —+ * a TTL-cached result would report a dead shared connection as healthy for 60 seconds. */+ await server?.close();+ expect(await connection.isConnected()).toBe(false);+ });+});diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex 2caa1ab518..eb27129e98 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -2957,6 +2957,75 @@ describe('MCPManager', () => {expect(MCPConnectionFactory.discoverTools).not.toHaveBeenCalled();});+ it('gives a budgeted caller an abort signal for the app-connection probe and snapshot', async () => {+ mockAppConnections({+ get: jest.fn().mockResolvedValue(mockConnection),+ });+ const deadlineMs = Date.now() + 3000;++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const result = await manager.discoverServerTools({ serverName, deadlineMs });++ expect(result.tools).toEqual(mockTools);+ expect(mockConnection.isConnected).toHaveBeenCalledWith(expect.any(AbortSignal));+ expect(mockConnection.fetchOrderedToolsSnapshot).toHaveBeenCalledWith(+ deadlineMs,+ expect.any(AbortSignal),+ );+ });++ it('lets the caller signal cancel app-connection work even without a deadline', async () => {+ mockAppConnections({+ get: jest.fn().mockResolvedValue(mockConnection),+ });+ const controller = new AbortController();++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await manager.discoverServerTools({ serverName, signal: controller.signal });++ expect(mockConnection.isConnected).toHaveBeenCalledWith(controller.signal);+ expect(mockConnection.fetchOrderedToolsSnapshot).toHaveBeenCalledWith(+ undefined,+ controller.signal,+ );+ });++ it('does not start discovery fallback for a caller whose signal already aborted', async () => {+ const isConnected = jest.fn().mockResolvedValue(false);+ mockAppConnections({+ get: jest.fn().mockResolvedValue({ ...mockConnection, isConnected }),+ });+ const controller = new AbortController();+ controller.abort();++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const result = await manager.discoverServerTools({ serverName, signal: controller.signal });++ expect(result.tools).toBeNull();+ expect(MCPConnectionFactory.discoverTools).not.toHaveBeenCalled();+ });++ it('forwards the caller signal into non-OAuth fallback discovery', async () => {+ mockAppConnections({+ get: jest.fn().mockResolvedValue(null),+ });+ (MCPConnectionFactory.discoverTools as jest.Mock).mockResolvedValue({+ tools: mockTools,+ connection: null,+ oauthRequired: false,+ oauthUrl: null,+ });+ const controller = new AbortController();++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await manager.discoverServerTools({ serverName, signal: controller.signal });++ expect(MCPConnectionFactory.discoverTools).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ signal: controller.signal }),+ );+ });+it('does not reuse an app connection for a tenant-scoped config override', async () => {const configOverride = {type: 'streamable-http' as const,diff --git a/packages/api/src/mcp/connection.ts b/packages/api/src/mcp/connection.tsindex a19514123b..2ec69c9830 100644--- a/packages/api/src/mcp/connection.ts+++ b/packages/api/src/mcp/connection.ts@@ -2388,11 +2388,22 @@ export class MCPConnection extends EventEmitter {* @param deadlineMs Absolute epoch-ms cap for a caller working to a fixed budget. Pagination* stops at whichever comes first, this or `TOOLS_LIST_TIMEOUT_MS`, and the partial result is* returned as incomplete so it is never published as an authoritative catalog.+ * @param signal Cancels the in-flight `tools/list` request itself, not just the wait for it —+ * the SDK raises an abort from `request()` and the failed page ends pagination gracefully.*/- public async fetchToolsSnapshot(deadlineMs?: number): Promise<MCPToolsSnapshot> {+ public async fetchToolsSnapshot(+ deadlineMs?: number,+ signal?: AbortSignal,+ ): Promise<MCPToolsSnapshot> {const maxPages = mcpConfig.TOOLS_LIST_MAX_PAGES;const maxTools = mcpConfig.TOOLS_LIST_MAX_TOOLS;const maxBytes = mcpConfig.TOOLS_LIST_MAX_BYTES;+ /** A spent budget ends the fetch before the reservation below spends cache round trips on an+ * ordering this incomplete result can never publish under. */+ if ((deadlineMs != null && Date.now() >= deadlineMs) || signal?.aborted === true) {+ this.warnToolsListBudgetExceeded('time', 0);+ return { tools: [], complete: false };+ }/** Reserved before the first page so the resulting catalog can never outrank one published* from a `tools/list` that started later. Every app-level publisher reads its ordering off* the snapshot it received, which is the only way to know when the data was actually read. */@@ -2427,7 +2438,7 @@ export class MCPConnection extends EventEmitter {return snapshot(false);}- const result = await this.listToolsPage(cursor, remainingMs);+ const result = await this.listToolsPage(cursor, remainingMs, signal);if (result == null) {/** Request failed mid-pagination: return the pages already fetched instead of discarding them. */return snapshot(false);@@ -2511,11 +2522,16 @@ export class MCPConnection extends EventEmitter {** @param deadlineMs Absolute epoch-ms cap; see `fetchToolsSnapshot`. It also bounds the wait* for a concurrent refresh, so a caller on a budget is never held by another caller's fetch.+ * @param signal Cancels this caller's own `tools/list` requests; see `fetchToolsSnapshot`. A+ * concurrent refresh is shared work and is never aborted on one caller's behalf.*/- public async fetchOrderedToolsSnapshot(deadlineMs?: number): Promise<MCPToolsSnapshot> {+ public async fetchOrderedToolsSnapshot(+ deadlineMs?: number,+ signal?: AbortSignal,+ ): Promise<MCPToolsSnapshot> {const startEpoch = this.toolListRefreshEpoch;const startGeneration = this.toolListChangeGeneration;- const snapshot = await this.fetchToolsSnapshot(deadlineMs);+ const snapshot = await this.fetchToolsSnapshot(deadlineMs, signal);if (startEpoch === this.toolListRefreshEpoch &&@@ -2528,7 +2544,7 @@ export class MCPConnection extends EventEmitter {startEpoch === this.toolListRefreshEpoch &&this.handledToolListChangeGeneration < this.toolListChangeGeneration) {- if (deadlineMs != null && Date.now() >= deadlineMs) {+ if ((deadlineMs != null && Date.now() >= deadlineMs) || signal?.aborted === true) {break;}this.startToolListRefresh();@@ -2537,11 +2553,13 @@ export class MCPConnection extends EventEmitter {break;}/** The refresh runs on the connection's own budget, not the caller's, so a refresh already- * in flight can outlast this deadline. Stop waiting on it rather than adopting its budget;- * it keeps running for whoever else wants it and this caller reports an incomplete read. */- if (deadlineMs == null) {+ * in flight can outlast this deadline — and a cancelled caller must stop waiting even+ * though the shared refresh itself is never aborted on one caller's behalf. Stop waiting+ * rather than adopting its budget; it keeps running for whoever else wants it and this+ * caller reports an incomplete read. */+ if (deadlineMs == null && signal == null) {await refresh;- } else if (!(await this.settlesBefore(refresh, deadlineMs))) {+ } else if (!(await this.settlesBefore(refresh, deadlineMs, signal))) {break;}if (this.toolListRefreshRetryTimer) {@@ -2567,17 +2585,34 @@ export class MCPConnection extends EventEmitter {return { tools: [], complete: false };}- /** Waits for `promise` only until `deadlineMs`, reporting whether it settled in time. */- private async settlesBefore(promise: Promise<unknown>, deadlineMs: number): Promise<boolean> {+ /** Waits for `promise` only until `deadlineMs` or an abort, reporting whether it settled first. */+ private async settlesBefore(+ promise: Promise<unknown>,+ deadlineMs?: number,+ signal?: AbortSignal,+ ): Promise<boolean> {+ if (signal?.aborted === true) {+ return false;+ }let timer: NodeJS.Timeout | undefined;- const expiry = new Promise<false>((resolve) => {- timer = setTimeout(() => resolve(false), Math.max(0, deadlineMs - Date.now()));- timer.unref?.();+ let onAbort: (() => void) | undefined;+ const interrupted = new Promise<false>((resolve) => {+ if (deadlineMs != null) {+ timer = setTimeout(() => resolve(false), Math.max(0, deadlineMs - Date.now()));+ timer.unref?.();+ }+ if (signal != null) {+ onAbort = () => resolve(false);+ signal.addEventListener('abort', onAbort, { once: true });+ }});try {- return await Promise.race([promise.then(() => true), expiry]);+ return await Promise.race([promise.then(() => true), interrupted]);} finally {clearTimeout(timer);+ if (onAbort != null) {+ signal?.removeEventListener('abort', onAbort);+ }}}@@ -2591,11 +2626,13 @@ export class MCPConnection extends EventEmitter {private async listToolsPage(cursor: string | undefined,timeoutMs: number,+ signal?: AbortSignal,): Promise<MCPListToolsResult | null> {try {return await this.client.listTools(cursor != null ? { cursor } : undefined, {timeout: timeoutMs,maxTotalTimeout: timeoutMs,+ signal,});} catch (error) {this.emitError(error, 'Failed to fetch tools');@@ -2613,7 +2650,12 @@ export class MCPConnection extends EventEmitter {}}- public async isConnected(): Promise<boolean> {+ /**+ * @param signal Aborts the in-flight verification request (ping or its fallback) so a caller on+ * a budget is not held for the probe's own SDK timeout. An aborted probe reports `false` for+ * this caller only; it never mutates connection state, so a shared connection stays usable.+ */+ public async isConnected(signal?: AbortSignal): Promise<boolean> {// First check if we're in a connected stateif (this.connectionState !== 'connected') {return false;@@ -2624,14 +2666,26 @@ export class MCPConnection extends EventEmitter {if (now - this.lastConnectionCheckAt < mcpConfig.CONNECTION_CHECK_TTL) {return true;}+ const previousCheckAt = this.lastConnectionCheckAt;this.lastConnectionCheckAt = now;this.lastConnectionCheckError = undefined;+ /** An aborted probe answered nothing: restore the TTL stamp so the next caller probes for+ * real, instead of a dead shared connection reading as healthy for the whole TTL window. */+ const probeAborted = (): boolean => signal?.aborted === true;+ const abandonProbe = (): false => {+ this.lastConnectionCheckAt = previousCheckAt;+ logger.debug(`${this.getLogPrefix()} Health probe aborted by caller signal`);+ return false;+ };try {// Try ping first as it's the lightest check- await this.client.ping();+ await this.client.ping({ signal });return this.connectionState === 'connected';} catch (error) {+ if (probeAborted()) {+ return abandonProbe();+ }// Check if the error is because ping is not supported (method not found)const pingUnsupported =error instanceof Error &&@@ -2658,13 +2712,13 @@ export class MCPConnection extends EventEmitter {// If we have capabilities, try calling a supported method to verify connectionif (capabilities?.tools) {- await this.client.listTools();+ await this.client.listTools(undefined, { signal });return this.connectionState === 'connected';} else if (capabilities?.resources) {- await this.client.listResources();+ await this.client.listResources(undefined, { signal });return this.connectionState === 'connected';} else if (capabilities?.prompts) {- await this.client.listPrompts();+ await this.client.listPrompts(undefined, { signal });return this.connectionState === 'connected';} else {// No capabilities to test, but we're in connected state and initialization succeeded@@ -2674,6 +2728,9 @@ export class MCPConnection extends EventEmitter {return this.connectionState === 'connected';}} catch (capabilityError) {+ if (probeAborted()) {+ return abandonProbe();+ }// If capability check fails, the connection is likely brokenthis.lastConnectionCheckError = capabilityError;logger.error(`${this.getLogPrefix()} Connection verification failed`);diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.tsindex 07a13c91c7..b94a0ed57f 100644--- a/packages/api/src/mcp/types/index.ts+++ b/packages/api/src/mcp/types/index.ts@@ -227,6 +227,9 @@ export interface UserConnectionContext {requestScopedConnections?: RequestScopedMCPConnectionStore;graphTokenResolver?: GraphTokenResolver;connectionTimeout?: number;+ /** Cancels the connection's SDK requests when the caller itself is cancelled; previously only+ * OAuth connections could carry a signal, leaving non-OAuth discovery uncancellable. */+ signal?: AbortSignal;/** Absolute epoch-ms bound on the whole connect-and-list operation. `connectionTimeout` bounds* only a single `connect()`, so a caller that must return within a fixed budget sets this to* cap every segment, including `tools/list` pagination and the unauthenticated fallback. */diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.tsindex ea0d4c0446..62918ef1fa 100644--- a/packages/api/src/mcp/utils.ts+++ b/packages/api/src/mcp/utils.ts@@ -614,6 +614,23 @@ export function escapeRegex(str: string): string {* @param title - The display title to convert* @returns A slug suitable for use as serverName (e.g., "GitHub MCP Tool" → "github-mcp-tool")*/+/**+ * One cancellation signal for a budgeted operation: the remaining budget and the caller's own+ * signal, whichever fires first. Undefined when neither bound exists, so unbudgeted callers pay+ * nothing.+ */+export function createDeadlineAbortSignal(+ deadlineMs?: number,+ callerSignal?: AbortSignal,+): AbortSignal | undefined {+ const budget =+ deadlineMs != null ? AbortSignal.timeout(Math.max(1, deadlineMs - Date.now())) : undefined;+ if (budget != null && callerSignal != null) {+ return AbortSignal.any([budget, callerSignal]);+ }+ return budget ?? callerSignal;+}+export function generateServerNameFromTitle(title: string): string {const slug = title.toLowerCase()