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: Stop Routine MCP Teardowns From Failing Concurrent Tool Calls (#15333)

Danny Avila1740f64439ad
diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.ts
index 4dfcaa9c24..888f79d910 100644
--- a/packages/api/src/mcp/UserConnectionManager.ts
+++ b/packages/api/src/mcp/UserConnectionManager.ts
@@ -31,7 +31,35 @@ type PendingConnection = {
oauth: OAuthLifecycleRelay;
};
-type ConnectionCreationGuard = { cancelled: boolean };
+/**
+ * Why a connection is being torn down. A `mutation` teardown follows a committed change to the
+ * server config or its credentials, so whatever an in-flight creation resolved before it may be
+ * stale and that creation cannot be re-established from the same inputs. A `lifecycle` teardown
+ * — an idle sweep, a forced replacement, a dead connection cleaned up — leaves those inputs
+ * exactly as valid as they were, and only the connection object itself goes away.
+ */
+type ConnectionTeardownReason = 'mutation' | 'lifecycle';
+
+type ConnectionTeardownOptions = {
+ /** The creation that requested the teardown; it is fenced by its own replacement. */
+ preservedCreation?: ConnectionCreationGuard;
+ reason?: ConnectionTeardownReason;
+};
+
+type ConnectionCreationGuard = { cancelledBy: ConnectionTeardownReason | null };
+
+/** Signals that a teardown fenced an in-flight creation before it could finish. */
+class ConnectionCreationCancelledError extends Error {
+ constructor(
+ message: string,
+ public readonly reason: ConnectionTeardownReason,
+ ) {
+ super(message);
+ }
+}
+
+/** Bounds re-establishment so back-to-back teardowns cannot spin a caller forever. */
+const MAX_TEARDOWN_RESTARTS = 3;
/**
* Abstract base class for managing user-specific MCP connections with lifecycle management.
@@ -110,10 +138,29 @@ export abstract class UserConnectionManager {
}
}
- private cancelConnectionCreations(key: string, preserved?: ConnectionCreationGuard): void {
+ private assertCreationNotCancelled(
+ guard: ConnectionCreationGuard | undefined,
+ userId: string,
+ serverName: string,
+ ): void {
+ if (!guard?.cancelledBy) {
+ return;
+ }
+ throw new ConnectionCreationCancelledError(
+ `[MCP][User: ${userId}][${serverName}] Connection creation was cancelled during teardown`,
+ guard.cancelledBy,
+ );
+ }
+
+ /** A mutation fence outranks a lifecycle one: the stale inputs stay stale either way. */
+ private cancelConnectionCreations(
+ key: string,
+ reason: ConnectionTeardownReason,
+ preserved?: ConnectionCreationGuard,
+ ): void {
for (const guard of this.activeConnectionCreations.get(key) ?? []) {
- if (guard !== preserved) {
- guard.cancelled = true;
+ if (guard !== preserved && guard.cancelledBy !== 'mutation') {
+ guard.cancelledBy = reason;
}
}
}
@@ -194,10 +241,59 @@ export abstract class UserConnectionManager {
if (!this.lostToolPublicationLeases.has(connection)) {
return;
}
- await this.disconnectUserConnection(userId, serverName, creationGuard);
+ await this.disconnectUserConnection(userId, serverName, { preservedCreation: creationGuard });
throw new Error(`[MCP][User: ${userId}][${serverName}] Publication lease is no longer current`);
}
+ /**
+ * A teardown fences every creation in flight for the same user and server, since one of them
+ * may install the connection it is removing, or hand back the one it just disposed. What the
+ * fenced attempt deserves depends on why the teardown ran. After a `lifecycle` teardown it is
+ * next in line rather than stale — nothing its caller resolved changed — so the attempt is
+ * discarded and re-established. After a `mutation` teardown the config and credentials that
+ * caller resolved may be the ones that were just replaced, and only the caller can resolve
+ * them again, so the fence stays fatal. A caller that has since aborted gets neither: there
+ * is nobody left to hand the connection to.
+ *
+ * Re-establishment happens inside the queue slot the attempt already holds, so a replacement
+ * queued behind another one keeps its position instead of moving to the tail and overwriting
+ * a newer connection later.
+ */
+ private async createUserConnectionWithLifecycleRestarts(
+ options: t.UserMCPConnectionOptions,
+ userId: string,
+ clearCooldown: boolean,
+ creationGuard: ConnectionCreationGuard,
+ ): Promise<MCPConnection> {
+ for (let attempt = 0; ; attempt++) {
+ /** A lifecycle fence raised while this attempt waited its turn has nothing left to fence;
+ * a mutation fence is kept, so the attempt below fails on it immediately. */
+ if (creationGuard.cancelledBy === 'lifecycle') {
+ creationGuard.cancelledBy = null;
+ }
+ try {
+ return await this.createUserConnectionInternal(
+ options,
+ userId,
+ clearCooldown,
+ creationGuard,
+ );
+ } catch (error) {
+ if (
+ !(error instanceof ConnectionCreationCancelledError) ||
+ error.reason !== 'lifecycle' ||
+ attempt >= MAX_TEARDOWN_RESTARTS ||
+ options.signal?.aborted === true
+ ) {
+ throw error;
+ }
+ logger.info(
+ `[MCP][User: ${userId}][${options.serverName}] Connection creation raced a teardown; re-establishing`,
+ );
+ }
+ }
+ }
+
/** Gets or creates a connection for a specific user, coalescing concurrent attempts */
public async getUserConnection(opts: t.UserMCPConnectionOptions): Promise<MCPConnection> {
const { serverName, forceNew, user } = opts;
@@ -323,10 +419,10 @@ export abstract class UserConnectionManager {
oauthEnd: opts.oauthEnd,
logPrefix: `[MCP][User: ${userId}][${serverName}]`,
});
- const creationGuard: ConnectionCreationGuard = { cancelled: false };
+ const creationGuard: ConnectionCreationGuard = { cancelledBy: null };
this.registerConnectionCreation(lockKey, creationGuard);
const createConnection = () =>
- this.createUserConnectionInternal(
+ this.createUserConnectionWithLifecycleRestarts(
{
...opts,
forceNew: forceNewConnection,
@@ -387,11 +483,7 @@ export abstract class UserConnectionManager {
clearCooldown: boolean,
creationGuard?: ConnectionCreationGuard,
): Promise<MCPConnection> {
- if (creationGuard?.cancelled) {
- throw new Error(
- `[MCP][User: ${userId}][${serverName}] Connection creation was cancelled during teardown`,
- );
- }
+ this.assertCreationNotCancelled(creationGuard, userId, serverName);
if (await this.appConnections!.has(serverName)) {
throw new McpError(
ErrorCode.InvalidRequest,
@@ -415,7 +507,10 @@ export abstract class UserConnectionManager {
logger.info(
`[MCP][User: ${userId}][${serverName}] Disposing existing connection before forced replacement`,
);
- await this.disconnectUserConnection(userId, serverName, creationGuard);
+ await this.disconnectUserConnection(userId, serverName, {
+ preservedCreation: creationGuard,
+ reason: 'lifecycle',
+ });
connection = undefined;
} else if (forceNew) {
connection = undefined;
@@ -441,7 +536,9 @@ export abstract class UserConnectionManager {
logger.info(
`[MCP][User: ${userId}][${serverName}] Config identity changed, disconnecting stale connection`,
);
- await this.disconnectUserConnection(userId, serverName, creationGuard);
+ await this.disconnectUserConnection(userId, serverName, {
+ preservedCreation: creationGuard,
+ });
connection = undefined;
}
if (
@@ -453,7 +550,9 @@ export abstract class UserConnectionManager {
logger.info(
`[MCP][User: ${userId}][${serverName}] Cache generation changed, disconnecting stale connection`,
);
- await this.disconnectUserConnection(userId, serverName, creationGuard);
+ await this.disconnectUserConnection(userId, serverName, {
+ preservedCreation: creationGuard,
+ });
connection = undefined;
}
@@ -463,7 +562,10 @@ export abstract class UserConnectionManager {
logger.info(`[MCP][User: ${userId}] User idle for too long. Disconnecting all connections.`);
// Disconnect all user connections
try {
- await this.disconnectUserConnections(userId, creationGuard);
+ await this.disconnectUserConnections(userId, {
+ preservedCreation: creationGuard,
+ reason: 'lifecycle',
+ });
} catch {
logger.error(`[MCP][User: ${userId}] Error disconnecting idle connections`);
}
@@ -475,7 +577,9 @@ export abstract class UserConnectionManager {
`[MCP][User: ${userId}] Server configuration updated; disconnecting stale connection`,
);
}
- await this.disconnectUserConnection(userId, serverName, creationGuard);
+ await this.disconnectUserConnection(userId, serverName, {
+ preservedCreation: creationGuard,
+ });
connection = undefined;
} else {
const activeRecovery = this.getActiveConnectionRecovery(connection);
@@ -500,15 +604,14 @@ export abstract class UserConnectionManager {
serverName,
creationGuard,
);
- if (creationGuard?.cancelled) {
- throw new Error(
- `[MCP][User: ${userId}][${serverName}] Connection creation was cancelled during teardown`,
- );
- }
+ this.assertCreationNotCancelled(creationGuard, userId, serverName);
return connection;
}
logger.warn(`[MCP][User: ${userId}] Found disconnected connection object; cleaning up`);
- await this.disconnectUserConnection(userId, serverName, creationGuard);
+ await this.disconnectUserConnection(userId, serverName, {
+ preservedCreation: creationGuard,
+ reason: 'lifecycle',
+ });
connection = undefined;
}
}
@@ -593,11 +696,7 @@ export abstract class UserConnectionManager {
connection = await MCPConnectionFactory.create(basic, connectionOptions);
- if (creationGuard?.cancelled) {
- throw new Error(
- `[MCP][User: ${userId}][${serverName}] Connection creation was cancelled during teardown`,
- );
- }
+ this.assertCreationNotCancelled(creationGuard, userId, serverName);
if (publicationGeneration) {
this.toolPublicationGenerations.set(connection, publicationGeneration);
@@ -623,11 +722,7 @@ export abstract class UserConnectionManager {
if (!ephemeralConnection) {
await connection.refreshToolList();
- if (creationGuard?.cancelled) {
- throw new Error(
- `[MCP][User: ${userId}][${serverName}] Connection creation was cancelled during teardown`,
- );
- }
+ this.assertCreationNotCancelled(creationGuard, userId, serverName);
if (!this.userConnections.has(userId)) {
this.userConnections.set(userId, new Map());
}
@@ -639,11 +734,7 @@ export abstract class UserConnectionManager {
await this.updateUserLastActivity(userId);
await this.assertToolPublicationLeaseCurrent(connection, userId, serverName, creationGuard);
}
- if (creationGuard?.cancelled) {
- throw new Error(
- `[MCP][User: ${userId}][${serverName}] Connection creation was cancelled during teardown`,
- );
- }
+ this.assertCreationNotCancelled(creationGuard, userId, serverName);
return connection;
} catch (error) {
logger.error(`[MCP][User: ${userId}] Failed to establish connection`);
@@ -938,41 +1029,54 @@ export abstract class UserConnectionManager {
}
}
- /** Disconnects and removes a specific user connection */
+ /**
+ * Disconnects and removes a specific user connection. Teardowns default to `mutation`, the
+ * conservative reading for external callers, which all tear down after committing a change.
+ */
public async disconnectUserConnection(
userId: string,
serverName: string,
- preservedCreation?: ConnectionCreationGuard,
+ { preservedCreation, reason = 'mutation' }: ConnectionTeardownOptions = {},
): Promise<void> {
const pendingKey = `${userId}:${serverName}`;
const pending = this.pendingConnections.get(pendingKey);
- this.cancelConnectionCreations(pendingKey, preservedCreation);
+ this.cancelConnectionCreations(pendingKey, reason, preservedCreation);
if (pending && preservedCreation == null) {
this.pendingConnections.delete(pendingKey);
}
const userMap = this.userConnections.get(userId);
const connection = userMap?.get(serverName);
+ const logPrefix = `[MCP][User: ${userId}]`;
+ if (connection) {
+ logger.info(`${logPrefix} Disconnecting server connection`);
+ connection.removeAllListeners?.('toolsChanged');
+ this.removeUserConnection(userId, serverName);
+ }
+ /**
+ * Started in the same synchronous stretch as the fence: `cancelMCPToolsChanged` drops the
+ * pending publication before it awaits, so a creation re-established while this teardown
+ * is still disposing cannot have its own publication and retry timer cancelled by it.
+ */
+ const publicationCancelled = cancelMCPToolsChanged({ userId, serverName });
+ /** Observed here so a rejection cannot surface as unhandled while disposal is awaited. */
+ publicationCancelled.catch(() => undefined);
try {
if (connection) {
- const logPrefix = `[MCP][User: ${userId}]`;
- logger.info(`${logPrefix} Disconnecting server connection`);
- connection.removeAllListeners?.('toolsChanged');
- this.removeUserConnection(userId, serverName);
await this.disposeEvictedConnection(connection, logPrefix);
}
} finally {
- await cancelMCPToolsChanged({ userId, serverName });
+ await publicationCancelled;
}
}
/** Disconnects and removes all connections for a specific user */
public async disconnectUserConnections(
userId: string,
- preservedCreation?: ConnectionCreationGuard,
+ { preservedCreation, reason = 'mutation' }: ConnectionTeardownOptions = {},
): Promise<void> {
for (const key of this.activeConnectionCreations.keys()) {
if (key.startsWith(`${userId}:`)) {
- this.cancelConnectionCreations(key, preservedCreation);
+ this.cancelConnectionCreations(key, reason, preservedCreation);
}
}
if (preservedCreation == null) {
@@ -989,22 +1093,28 @@ export abstract class UserConnectionManager {
const userServers = Array.from(userMap.keys());
for (const serverName of userServers) {
disconnectPromises.push(
- this.disconnectUserConnection(userId, serverName, preservedCreation).catch(() => {
- logger.error(`[MCP][User: ${userId}] Error during server disconnection`);
- }),
+ this.disconnectUserConnection(userId, serverName, { preservedCreation, reason }).catch(
+ () => {
+ logger.error(`[MCP][User: ${userId}] Error during server disconnection`);
+ },
+ ),
);
}
await Promise.allSettled(disconnectPromises);
logger.info(`[MCP][User: ${userId}] All connections processed for disconnection.`);
}
/**
- * Always clear the activity timestamp, even when userMap was missing.
- * `updateUserLastActivity` can be called before a connection is established
- * (e.g. in MCPManager.callTool prior to getConnection); if that connection
- * attempt fails, the activity entry would otherwise leak and trigger the
- * idle check repeatedly for the same userId.
+ * Clear the activity timestamp whenever nothing is left to track, including when userMap
+ * was missing. `updateUserLastActivity` can be called before a connection is established
+ * (e.g. in MCPManager.callTool prior to getConnection); if that connection attempt fails,
+ * the activity entry would otherwise leak and trigger the idle check repeatedly for the
+ * same userId. A connection installed while this teardown was disposing keeps its own
+ * timestamp: `checkIdleConnections` walks activity rather than connections, so clearing it
+ * would hide that connection from every later idle sweep.
*/
- this.userLastActivity.delete(userId);
+ if ((this.userConnections.get(userId)?.size ?? 0) === 0) {
+ this.userLastActivity.delete(userId);
+ }
}
/** Check for and disconnect idle connections */
@@ -1021,7 +1131,7 @@ export abstract class UserConnectionManager {
`[MCP][User: ${userId}] User idle for too long. Disconnecting all connections...`,
);
// Disconnect all user connections asynchronously (fire and forget)
- this.disconnectUserConnections(userId).catch(() =>
+ this.disconnectUserConnections(userId, { reason: 'lifecycle' }).catch(() =>
logger.error(`[MCP][User: ${userId}] Error disconnecting idle connections`),
);
}
diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.ts
index e29aadc4a6..530bd71c2f 100644
--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts
@@ -3140,6 +3140,15 @@ describe('MCPManager', () => {
refreshToolList: jest.fn().mockResolvedValue(undefined),
on: jest.fn(),
} as unknown as MCPConnection;
+ const newUserConnection = () =>
+ ({
+ isConnected: jest.fn().mockResolvedValue(true),
+ isStale: jest.fn().mockReturnValue(false),
+ refreshToolList: jest.fn().mockResolvedValue(undefined),
+ on: jest.fn(),
+ removeAllListeners: jest.fn(),
+ dispose: jest.fn().mockResolvedValue(undefined),
+ }) as unknown as MCPConnection;
it('should pass useOAuth for servers with configured oauth and no requiresOAuth value', async () => {
mockAppConnections({
@@ -3263,14 +3272,8 @@ describe('MCPManager', () => {
it.each([false, true])(
'cancels and disposes a pending connection during mutation teardown (forceNew=%s)',
async (forceNew) => {
- const pendingConnection = {
- isConnected: jest.fn().mockResolvedValue(true),
- isStale: jest.fn().mockReturnValue(false),
- refreshToolList: jest.fn().mockResolvedValue(undefined),
- on: jest.fn(),
- removeAllListeners: jest.fn(),
- dispose: jest.fn().mockResolvedValue(undefined),
- } as unknown as MCPConnection;
+ const pendingConnection = newUserConnection();
+ const neverReached = newUserConnection();
let resolveConnection: ((connection: MCPConnection) => void) | undefined;
const factoryResult = new Promise<MCPConnection>((resolve) => {
resolveConnection = resolve;
@@ -3282,7 +3285,9 @@ describe('MCPManager', () => {
source: 'user',
dbId: 'server-1',
});
- (MCPConnectionFactory.create as jest.Mock).mockReturnValue(factoryResult);
+ (MCPConnectionFactory.create as jest.Mock)
+ .mockReturnValueOnce(factoryResult)
+ .mockResolvedValue(neverReached);
const manager = await MCPManager.createInstance(newMCPServersConfig());
const creation = manager.getUserConnection({ serverName, user: mockUser, forceNew });
@@ -3297,21 +3302,277 @@ describe('MCPManager', () => {
expect(pendingConnection.removeAllListeners).toHaveBeenCalledWith('toolsChanged');
expect(pendingConnection.dispose).toHaveBeenCalledTimes(1);
expect(manager.getUserConnections(userId)?.has(serverName) ?? false).toBe(false);
+ /** A committed mutation invalidates what the caller resolved, so nothing re-establishes. */
+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);
},
);
+ it('resolves both callers when a forced replacement races a plain creation', async () => {
+ const original = newUserConnection();
+ const replacement = newUserConnection();
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ });
+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(original);
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ await manager.getUserConnection({ serverName, user: mockUser });
+
+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(replacement);
+ const results = await Promise.allSettled([
+ manager.getUserConnection({ serverName, user: mockUser, forceNew: true }),
+ manager.getUserConnection({ serverName, user: mockUser }),
+ ]);
+
+ expect(results.map((result) => result.status)).toEqual(['fulfilled', 'fulfilled']);
+ expect(manager.getUserConnections(userId)?.get(serverName)).toBe(replacement);
+ expect(original.dispose).toHaveBeenCalledTimes(1);
+ });
+
+ it('tears down idle users with a lifecycle teardown', async () => {
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ });
+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(newUserConnection());
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ await manager.getUserConnection({ serverName, user: mockUser });
+ const internals = manager as unknown as {
+ userLastActivity: Map<string, number>;
+ checkIdleConnections(currentUserId?: string): void;
+ };
+ internals.userLastActivity.set(userId, 0);
+ const disconnectSpy = jest
+ .spyOn(manager, 'disconnectUserConnections')
+ .mockResolvedValue(undefined);
+
+ internals.checkIdleConnections();
+
+ expect(disconnectSpy).toHaveBeenCalledWith(userId, { reason: 'lifecycle' });
+ disconnectSpy.mockRestore();
+ });
+
+ it('re-establishes a creation cancelled by a user-wide lifecycle teardown', async () => {
+ const cancelledConnection = newUserConnection();
+ const reestablishedConnection = newUserConnection();
+ let resolveConnection: ((connection: MCPConnection) => void) | undefined;
+ const factoryResult = new Promise<MCPConnection>((resolve) => {
+ resolveConnection = resolve;
+ });
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ });
+ (MCPConnectionFactory.create as jest.Mock)
+ .mockReturnValueOnce(factoryResult)
+ .mockResolvedValue(reestablishedConnection);
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const creation = manager.getUserConnection({ serverName, user: mockUser });
+ while ((MCPConnectionFactory.create as jest.Mock).mock.calls.length === 0) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+
+ await manager.disconnectUserConnections(userId, { reason: 'lifecycle' });
+ resolveConnection?.(cancelledConnection);
+
+ await expect(creation).resolves.toBe(reestablishedConnection);
+ expect(cancelledConnection.dispose).toHaveBeenCalledTimes(1);
+ expect(manager.getUserConnections(userId)?.get(serverName)).toBe(reestablishedConnection);
+ });
+ it('fails a caller-resolved creation fenced by a credential mutation', async () => {
+ const fencedConnection = newUserConnection();
+ const neverReached = newUserConnection();
+ const serverConfig: t.ParsedServerConfig = {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ };
+ let resolveConnection: ((connection: MCPConnection) => void) | undefined;
+ const factoryResult = new Promise<MCPConnection>((resolve) => {
+ resolveConnection = resolve;
+ });
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);
+ (MCPConnectionFactory.create as jest.Mock)
+ .mockReturnValueOnce(factoryResult)
+ .mockResolvedValue(neverReached);
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ /** Callers resolve the config and credentials per request and hand them in; a mutation
+ * teardown invalidates both, and only the caller can resolve them again. */
+ const creation = manager.getUserConnection({
+ serverName,
+ user: mockUser,
+ serverConfig,
+ customUserVars: { API_KEY: 'revoked-key' },
+ });
+ while ((MCPConnectionFactory.create as jest.Mock).mock.calls.length === 0) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+
+ await manager.disconnectUserConnection(userId, serverName);
+ resolveConnection?.(fencedConnection);
+
+ await expect(creation).rejects.toThrow('Connection creation was cancelled during teardown');
+ expect(fencedConnection.dispose).toHaveBeenCalledTimes(1);
+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);
+ expect(manager.getUserConnections(userId)?.has(serverName) ?? false).toBe(false);
+ });
+
+ it('keeps the activity timestamp for a connection installed during a user-wide teardown', async () => {
+ const otherServer = 'other_server';
+ const installedConnection = newUserConnection();
+ let resolveDispose: (() => void) | undefined;
+ (installedConnection.dispose as jest.Mock).mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveDispose = () => resolve();
+ }),
+ );
+ const fencedConnection = newUserConnection();
+ const reestablishedConnection = newUserConnection();
+ let resolveConnection: ((connection: MCPConnection) => void) | undefined;
+ const factoryResult = new Promise<MCPConnection>((resolve) => {
+ resolveConnection = resolve;
+ });
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ });
+ (MCPConnectionFactory.create as jest.Mock)
+ .mockResolvedValueOnce(installedConnection)
+ .mockReturnValueOnce(factoryResult)
+ .mockResolvedValue(reestablishedConnection);
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ await manager.getUserConnection({ serverName, user: mockUser });
+ const creation = manager.getUserConnection({ serverName: otherServer, user: mockUser });
+ while ((MCPConnectionFactory.create as jest.Mock).mock.calls.length < 2) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+
+ /** The sweep is still disposing the first connection when the fenced one re-establishes. */
+ const teardown = manager.disconnectUserConnections(userId, { reason: 'lifecycle' });
+ resolveConnection?.(fencedConnection);
+ await expect(creation).resolves.toBe(reestablishedConnection);
+ resolveDispose?.();
+ await teardown;
+
+ const internals = manager as unknown as { userLastActivity: Map<string, number> };
+ expect(manager.getUserConnections(userId)?.get(otherServer)).toBe(reestablishedConnection);
+ expect(internals.userLastActivity.has(userId)).toBe(true);
+ });
+
+ it('does not re-establish a lifecycle-fenced creation whose caller aborted', async () => {
+ const fencedConnection = newUserConnection();
+ const neverReached = newUserConnection();
+ let resolveConnection: ((connection: MCPConnection) => void) | undefined;
+ const factoryResult = new Promise<MCPConnection>((resolve) => {
+ resolveConnection = resolve;
+ });
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ });
+ (MCPConnectionFactory.create as jest.Mock)
+ .mockReturnValueOnce(factoryResult)
+ .mockResolvedValue(neverReached);
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const controller = new AbortController();
+ const creation = manager.getUserConnection({
+ serverName,
+ user: mockUser,
+ signal: controller.signal,
+ });
+ while ((MCPConnectionFactory.create as jest.Mock).mock.calls.length === 0) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+
+ controller.abort();
+ await manager.disconnectUserConnection(userId, serverName, { reason: 'lifecycle' });
+ resolveConnection?.(fencedConnection);
+
+ await expect(creation).rejects.toThrow('Connection creation was cancelled during teardown');
+ expect(fencedConnection.dispose).toHaveBeenCalledTimes(1);
+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);
+ expect(manager.getUserConnections(userId)?.has(serverName) ?? false).toBe(false);
+ });
+
+ it('cancels pending tool publications before it starts disposing', async () => {
+ const connection = newUserConnection();
+ const cancelSpy = jest.spyOn(toolsChanged, 'cancelMCPToolsChanged');
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ });
+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(connection);
+
+ try {
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ await manager.getUserConnection({ serverName, user: mockUser });
+ cancelSpy.mockClear();
+
+ await manager.disconnectUserConnection(userId, serverName);
+
+ /** A creation re-established while disposal is still awaited publishes its own catalog;
+ * a cancellation issued after that point would drop the replacement's pending change. */
+ expect(cancelSpy).toHaveBeenCalledWith({ userId, serverName });
+ expect(cancelSpy.mock.invocationCallOrder[0]).toBeLessThan(
+ (connection.dispose as jest.Mock).mock.invocationCallOrder[0],
+ );
+ } finally {
+ cancelSpy.mockRestore();
+ }
+ });
+
+ it('fails a creation that a lifecycle teardown keeps cancelling on every attempt', async () => {
+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ source: 'user',
+ dbId: 'server-1',
+ });
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ (MCPConnectionFactory.create as jest.Mock).mockReset();
+ (MCPConnectionFactory.create as jest.Mock).mockImplementation(async () => {
+ const connection = newUserConnection();
+ await manager.disconnectUserConnection(userId, serverName, { reason: 'lifecycle' });
+ return connection;
+ });
+
+ await expect(manager.getUserConnection({ serverName, user: mockUser })).rejects.toThrow(
+ 'Connection creation was cancelled during teardown',
+ );
+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(4);
+ expect(manager.getUserConnections(userId)?.has(serverName) ?? false).toBe(false);
+ });
+
it('disposes the tracked durable connection before a forced replacement', async () => {
- const createConnection = () =>
- ({
- isConnected: jest.fn().mockResolvedValue(true),
- isStale: jest.fn().mockReturnValue(false),
- refreshToolList: jest.fn().mockResolvedValue(undefined),
- on: jest.fn(),
- removeAllListeners: jest.fn(),
- dispose: jest.fn().mockResolvedValue(undefined),
- }) as unknown as MCPConnection;
- const previousConnection = createConnection();
- const replacementConnection = createConnection();
+ const previousConnection = newUserConnection();
+ const replacementConnection = newUserConnection();
mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
(mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
type: 'streamable-http',
@@ -3341,18 +3602,9 @@ describe('MCPManager', () => {
});
it('serializes an ordinary load with multiple queued forced replacements', async () => {
- const createConnection = () =>
- ({
- isConnected: jest.fn().mockResolvedValue(true),
- isStale: jest.fn().mockReturnValue(false),
- refreshToolList: jest.fn().mockResolvedValue(undefined),
- on: jest.fn(),
- removeAllListeners: jest.fn(),
- dispose: jest.fn().mockResolvedValue(undefined),
- }) as unknown as MCPConnection;
- const initial = createConnection();
- const firstReplacement = createConnection();
- const secondReplacement = createConnection();
+ const initial = newUserConnection();
+ const firstReplacement = newUserConnection();
+ const secondReplacement = newUserConnection();
let resolveFirst: ((connection: MCPConnection) => void) | undefined;
let resolveSecond: ((connection: MCPConnection) => void) | undefined;
const firstFactoryResult = new Promise<MCPConnection>((resolve) => {
diff --git a/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.ts b/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.ts
index 0a97b3518f..fd8ecb110a 100644
--- a/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.ts
+++ b/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.ts
@@ -255,7 +255,9 @@ describe('OAuthReconnectionManager', () => {
// Verify failure handling
expect(reconnectionTracker.isFailed(userId, 'server1')).toBe(true);
expect(reconnectionTracker.isActive(userId, 'server1')).toBe(false);
- expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1');
+ expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1', {
+ reason: 'lifecycle',
+ });
});
it('should not reconnect servers with expired tokens and no refresh token', async () => {
@@ -394,7 +396,9 @@ describe('OAuthReconnectionManager', () => {
expect(mockConnection.disconnect).toHaveBeenCalled();
expect(reconnectionTracker.isFailed(userId, 'server1')).toBe(true);
expect(reconnectionTracker.isActive(userId, 'server1')).toBe(false);
- expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1');
+ expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1', {
+ reason: 'lifecycle',
+ });
});
it('should handle MCPManager not available gracefully', async () => {
@@ -661,7 +665,9 @@ describe('OAuthReconnectionManager', () => {
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('Failed to reconnect'));
expect(reconnectionTracker.isActive(userId, 'server1')).toBe(false);
expect(reconnectionTracker.isFailed(userId, 'server1')).toBe(true);
- expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1');
+ expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1', {
+ reason: 'lifecycle',
+ });
});
});
diff --git a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts b/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts
index 0857462559..b2fb0bd4e2 100644
--- a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts
+++ b/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts
@@ -134,7 +134,7 @@ export class OAuthReconnectionManager {
private cleanupOnFailedReconnect(userId: string, serverName: string): void {
this.reconnectionsTracker.setFailed(userId, serverName);
this.reconnectionsTracker.removeActive(userId, serverName);
- this.mcpManager?.disconnectUserConnection(userId, serverName);
+ this.mcpManager?.disconnectUserConnection(userId, serverName, { reason: 'lifecycle' });
}
/**