Skip to content

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

🦺 fix: Skip Redundant MCP OAuth Probes and Teardown Cancellations (#16298)

lia-by-librechat[bot]8fb4056e8a83
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index b5f3b98616..913a000029 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -403,6 +403,10 @@ export class MCPConnectionFactory {
return { tools: null, connection: null, oauthRequired: false, oauthUrl: null };
}
oauthTokens = loaded.value;
+ if (!oauthTokens && !this.usesObo && isOAuthServer(this.serverConfig)) {
+ oauthRequired = true;
+ shouldAttemptAuthenticatedDiscovery = false;
+ }
}
let connection: MCPConnection | null = null;
diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.ts
index 738a6e179e..016af28aa4 100644
--- a/packages/api/src/mcp/MCPManager.ts
+++ b/packages/api/src/mcp/MCPManager.ts
@@ -44,6 +44,7 @@ import { processMCPEnv, isPluginSourced } from '~/utils/env';
import { OAuthLifecycleRelay } from './oauth/pending';
import { preProcessGraphTokens } from '~/utils/graph';
import { isOwnedAbortError } from '~/utils/errors';
+import { withMCPRequestSignal } from './signal';
import { formatToolContent } from './parsers';
import { MCPConnection } from './connection';
import { mcpConfig } from './mcpConfig';
@@ -1526,20 +1527,23 @@ Please follow these instructions when using tools from the respective MCP server
}
const requestTool = () =>
- connection!.client.request(
- {
- method: 'tools/call',
- params: {
- name: toolName,
- arguments: toolArguments,
+ withMCPRequestSignal(options?.signal, (signal) =>
+ connection!.client.request(
+ {
+ method: 'tools/call',
+ params: {
+ name: toolName,
+ arguments: toolArguments,
+ },
+ },
+ CallToolResultSchema,
+ {
+ timeout: connection!.timeout,
+ resetTimeoutOnProgress: true,
+ ...options,
+ signal,
},
- },
- CallToolResultSchema,
- {
- timeout: connection!.timeout,
- resetTimeoutOnProgress: true,
- ...options,
- },
+ ),
);
const requestedCredentialSetId = connection.getOAuthCredentialSetId?.();
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
index c723985eca..64b398b4ab 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
@@ -200,6 +200,95 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (
jest.clearAllMocks();
});
+ it('tries unauthenticated public tool listing only once when an OAuth server has no token', async () => {
+ const postHeaders: Array<string | undefined> = [];
+ server = await createOAuthMCPServer({
+ onResourceRequest: (request) => {
+ if (request.method === 'POST') postHeaders.push(request.headers.authorization);
+ },
+ });
+ const result = await MCPConnectionFactory.discoverTools(
+ {
+ serverName: SERVER_NAME,
+ serverConfig: { type: 'streamable-http', url: server.url, requiresOAuth: true },
+ },
+ {
+ useOAuth: true,
+ user: { id: USER_ID } as IUser,
+ flowManager: createFlowManager(),
+ tokenMethods: {
+ findToken: tokenStore.findToken,
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ deleteTokens: tokenStore.deleteTokens,
+ },
+ },
+ );
+
+ expect(result).toMatchObject({ tools: null, connection: null, oauthRequired: true });
+ expect(postHeaders).toEqual([undefined]);
+ });
+
+ it('does not cancel finished SDK requests when a shared run signal is aborted', async () => {
+ let resourcePosts = 0;
+ server = await createOAuthMCPServer({
+ onResourceRequest: (request) => {
+ if (request.method === 'POST') resourcePosts += 1;
+ },
+ });
+ const tokens = await issueTokens(server);
+ await storeTokens(tokenStore, server, tokens);
+ const flowManager = createFlowManager();
+ const tokenMethods = {
+ findToken: tokenStore.findToken,
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ deleteTokens: tokenStore.deleteTokens,
+ };
+ const serverConfig = {
+ type: 'streamable-http' as const,
+ url: server.url,
+ requiresOAuth: true,
+ };
+ connection = await MCPConnectionFactory.create(
+ { serverName: SERVER_NAME, serverConfig },
+ { useOAuth: true, user: { id: USER_ID } as IUser, flowManager, tokenMethods },
+ );
+ const manager = new MCPManager();
+ jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);
+ const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
+ resolveAllowlists: jest.fn().mockResolvedValue({
+ allowedDomains: null,
+ allowedAddresses: null,
+ useSSRFProtection: false,
+ }),
+ } as unknown as MCPServersRegistry);
+ const controller = new AbortController();
+ try {
+ for (let index = 0; index < 3; index += 1) {
+ await expect(
+ manager.callTool({
+ user: { id: USER_ID } as IUser,
+ serverName: SERVER_NAME,
+ serverConfig,
+ toolName: 'echo',
+ toolArguments: { message: `call ${index}` },
+ provider: 'openai',
+ flowManager,
+ tokenMethods,
+ options: { signal: controller.signal },
+ }),
+ ).resolves.toBeDefined();
+ }
+ const completedPosts = resourcePosts;
+ controller.abort(new Error('Run ended'));
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(resourcePosts).toBe(completedPosts);
+ } finally {
+ registrySpy.mockRestore();
+ }
+ });
+
it('refreshes an expired callback for the active connection and token waiter after publication settles', async () => {
server = await createOAuthMCPServer({
issueRefreshTokens: true,
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
index 652d71b2a5..af050c348e 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
@@ -4873,6 +4873,42 @@ describe('MCPConnectionFactory', () => {
{ name: 'tool2', description: 'Second tool', inputSchema: { type: 'object' } },
];
+ it('preserves public tool listing without a redundant OAuth connect when tokens are absent', async () => {
+ const serverConfig = {
+ type: 'streamable-http' as const,
+ url: 'https://mcp.example.com',
+ requiresOAuth: true,
+ };
+ mockProcessMCPEnv.mockImplementation(({ options }) => options);
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);
+ mockConnectionInstance.connect.mockResolvedValue(undefined);
+ mockConnectionInstance.isConnected.mockResolvedValue(true);
+ mockConnectionInstance.fetchOrderedToolsSnapshot = jest.fn().mockResolvedValue({
+ tools: mockTools,
+ complete: true,
+ });
+
+ const result = await MCPConnectionFactory.discoverTools(
+ { serverName: 'public-oauth', serverConfig },
+ {
+ useOAuth: true,
+ user: mockUser!,
+ flowManager: mockFlowManager,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+
+ expect(result.tools).toEqual(mockTools);
+ expect(result.oauthRequired).toBe(true);
+ expect(mockMCPConnection).toHaveBeenCalledTimes(1);
+ expect(mockConnectionInstance.connect).toHaveBeenCalledTimes(1);
+ });
+
it('should discover tools from a successfully connected server', async () => {
const basicOptions = {
serverName: 'test-server',
@@ -6165,7 +6201,7 @@ describe('MCPConnectionFactory', () => {
);
expect(result.tools).toEqual(mockTools);
- expect(result.oauthRequired).toBe(false);
+ expect(result.oauthRequired).toBe(true);
expect(oauthOptions.oauthStart).not.toHaveBeenCalled();
expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
});
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts
index 8a23c26258..bcfdf2f890 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts
@@ -379,15 +379,18 @@ describe('MCPConnection.fetchTools pagination', () => {
expect(reserve).not.toHaveBeenCalled();
});
- it('hands the caller signal to the SDK so an in-flight page is cancellable', async () => {
+ it('detaches a completed SDK page request from its caller signal', async () => {
const listTools = jest.fn().mockResolvedValue({ tools: [makeTool('a')] });
const conn = createConnectionWithListTools(listTools);
- const signal = AbortSignal.timeout(5000);
+ const controller = new AbortController();
- await conn.fetchToolsSnapshot(Date.now() + 5000, signal);
+ await conn.fetchToolsSnapshot(Date.now() + 5000, controller.signal);
const options = listTools.mock.calls[0][1]!;
- expect(options.signal).toBe(signal);
+ expect(options.signal === controller.signal).toBe(false);
+ expect(options.signal?.aborted).toBe(false);
+ controller.abort();
+ expect(options.signal?.aborted).toBe(false);
});
it('makes no request and no reservation when the signal is already aborted', async () => {
diff --git a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
index 3956ea2fa9..628a0b0441 100644
--- a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
+++ b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
@@ -81,6 +81,8 @@ export interface OAuthTestServerOptions {
refreshGate?: () => Promise<void> | undefined;
/** Optional test hook for controlling echo-tool completion. */
echoHandler?: (message: string) => string | Promise<string>;
+ /** Observes MCP resource requests, including unauthenticated and cancellation POSTs. */
+ onResourceRequest?: (request: http.IncomingMessage) => void;
}
export interface OAuthTokenRequestRecord {
@@ -149,6 +151,7 @@ export async function createOAuthMCPServer(
requireResourceParameter = false,
rejectRefreshTokens = 0,
echoHandler,
+ onResourceRequest,
refreshFailure,
refreshGate,
} = options;
@@ -466,6 +469,7 @@ export async function createOAuthMCPServer(
}
// All other paths require Bearer token auth
+ onResourceRequest?.(req);
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
writeBearerChallenge(res, 401, 'invalid_token', 'Missing Authorization header');
diff --git a/packages/api/src/mcp/connection.ts b/packages/api/src/mcp/connection.ts
index 24d1ed08b9..818b6c17a1 100644
--- a/packages/api/src/mcp/connection.ts
+++ b/packages/api/src/mcp/connection.ts
@@ -35,6 +35,7 @@ import { reserveMCPToolsChangedRevision } from './toolsChanged';
import { runOutsideTracing } from '~/utils/tracing';
import { mediaTypeEssence } from '~/utils/headers';
import { isAddressAllowed } from '~/auth/domain';
+import { withMCPRequestSignal } from './signal';
import { withTimeout } from '~/utils/promise';
import { isOAuthServer } from './utils';
import { mcpConfig } from './mcpConfig';
@@ -2740,11 +2741,13 @@ export class MCPConnection extends EventEmitter {
signal?: AbortSignal,
): Promise<MCPListToolsResult> {
try {
- return await this.client.listTools(cursor != null ? { cursor } : undefined, {
- timeout: timeoutMs,
- maxTotalTimeout: timeoutMs,
- signal,
- });
+ return await withMCPRequestSignal(signal, (requestSignal) =>
+ this.client.listTools(cursor != null ? { cursor } : undefined, {
+ timeout: timeoutMs,
+ maxTotalTimeout: timeoutMs,
+ signal: requestSignal,
+ }),
+ );
} catch (error) {
this.emitError(error, 'Failed to fetch tools');
throw error;
@@ -2793,7 +2796,9 @@ export class MCPConnection extends EventEmitter {
try {
// Try ping first as it's the lightest check
- await this.client.ping({ signal });
+ await withMCPRequestSignal(signal, (requestSignal) =>
+ this.client.ping({ signal: requestSignal }),
+ );
return this.connectionState === 'connected';
} catch (error) {
if (probeAborted()) {
@@ -2827,13 +2832,19 @@ export class MCPConnection extends EventEmitter {
// If we have capabilities, try calling a supported method to verify connection
if (capabilities?.tools) {
- await this.client.listTools(undefined, { signal });
+ await withMCPRequestSignal(signal, (requestSignal) =>
+ this.client.listTools(undefined, { signal: requestSignal }),
+ );
return this.connectionState === 'connected';
} else if (capabilities?.resources) {
- await this.client.listResources(undefined, { signal });
+ await withMCPRequestSignal(signal, (requestSignal) =>
+ this.client.listResources(undefined, { signal: requestSignal }),
+ );
return this.connectionState === 'connected';
} else if (capabilities?.prompts) {
- await this.client.listPrompts(undefined, { signal });
+ await withMCPRequestSignal(signal, (requestSignal) =>
+ this.client.listPrompts(undefined, { signal: requestSignal }),
+ );
return this.connectionState === 'connected';
} else {
// No capabilities to test, but we're in connected state and initialization succeeded
diff --git a/packages/api/src/mcp/signal.spec.ts b/packages/api/src/mcp/signal.spec.ts
new file mode 100644
index 0000000000..59a9e6c86a
--- /dev/null
+++ b/packages/api/src/mcp/signal.spec.ts
@@ -0,0 +1,49 @@
+import { withMCPRequestSignal } from './signal';
+
+describe('withMCPRequestSignal', () => {
+ it('relays cancellation to an in-flight request and detaches on rejection', async () => {
+ const parent = new AbortController();
+ const reason = new Error('Stop');
+ const remove = jest.spyOn(parent.signal, 'removeEventListener');
+ const request = jest.fn(
+ (signal?: AbortSignal) =>
+ new Promise<never>((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
+ }),
+ );
+ const pending = withMCPRequestSignal(parent.signal, request);
+
+ expect(request).toHaveBeenCalledTimes(1);
+ expect(request.mock.calls[0][0]).not.toBe(parent.signal);
+ parent.abort(reason);
+ await expect(pending).rejects.toBe(reason);
+ expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
+ });
+
+ it('does not abort a completed request when its parent is aborted later', async () => {
+ const parent = new AbortController();
+ const request = jest.fn(async (signal?: AbortSignal) => signal);
+ const child = await withMCPRequestSignal(parent.signal, request);
+
+ expect(child).toBeDefined();
+ parent.abort();
+ expect(child?.aborted).toBe(false);
+ });
+
+ it('does not start a request whose parent is already aborted', async () => {
+ const parent = new AbortController();
+ const reason = new Error('Stop');
+ parent.abort(reason);
+ const request = jest.fn(async () => undefined);
+
+ await expect(withMCPRequestSignal(parent.signal, request)).rejects.toBe(reason);
+ expect(request).not.toHaveBeenCalled();
+ });
+
+ it('passes through requests without a parent signal', async () => {
+ const request = jest.fn(async (signal?: AbortSignal) => signal);
+
+ await expect(withMCPRequestSignal(undefined, request)).resolves.toBeUndefined();
+ expect(request).toHaveBeenCalledWith(undefined);
+ });
+});
diff --git a/packages/api/src/mcp/signal.ts b/packages/api/src/mcp/signal.ts
new file mode 100644
index 0000000000..db42118e82
--- /dev/null
+++ b/packages/api/src/mcp/signal.ts
@@ -0,0 +1,23 @@
+/** The MCP SDK retains its abort listener after a response; never give it a long-lived run signal. */
+export async function withMCPRequestSignal<T>(
+ parent: AbortSignal | undefined,
+ request: (signal: AbortSignal | undefined) => Promise<T>,
+): Promise<T> {
+ if (!parent) {
+ return request(undefined);
+ }
+
+ parent.throwIfAborted();
+ const controller = new AbortController();
+ const onAbort = () => controller.abort(parent.reason);
+ parent.addEventListener('abort', onAbort, { once: true });
+ try {
+ if (parent.aborted) {
+ onAbort();
+ parent.throwIfAborted();
+ }
+ return await request(controller.signal);
+ } finally {
+ parent.removeEventListener('abort', onAbort);
+ }
+}