🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(connector): coordinate OAuth refresh across instances (T-14372) (#23300)
Bryan3b1342e3bd82
diff --git a/apps/server/src/routers/lambda/__tests__/connector.links.test.ts b/apps/server/src/routers/lambda/__tests__/connector.links.test.tsindex d2adae40016..90588a15102 100644--- a/apps/server/src/routers/lambda/__tests__/connector.links.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.links.test.ts@@ -181,7 +181,7 @@ describe('connector account APIs', () => {});const links = await linkModel.listByConnectorIds([row.id]);expect(links.map((item) => item.id)).toEqual([link.linkId]);- const refreshed = await ensureFreshLinkToken(updated, links[0], linkModel, model);+ const refreshed = await ensureFreshLinkToken(updated, links[0], model);expect(refreshed.credentials.accessToken).toMatch(/^tok-alice-/);expect((await linkModel.findById(row.id, link.linkId))?.credentials.accessToken).toBe(refreshed.credentials.accessToken,diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.tsindex 004399bc472..a085d6e6418 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts@@ -15,7 +15,6 @@ import type { UserConnectorToolItem } from '@/database/schemas';import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import {- getConnectorLinkModel,loadConnectorLinksMap,pickPrimaryLink,withLinkCredentials,@@ -142,13 +141,7 @@ const refreshConnectorTokens = async (if (links.length > 1) return { ...connector, credentials: null, links: choices };const primary = pickPrimaryLink(links);if (primary) {- const [fresh] = await refreshExpiredLinkTokens(- connector,- [primary],- getConnectorLinkModel(linksContext),- model,- { onTimeout },- );+ const [fresh] = await refreshExpiredLinkTokens(connector, [primary], model, { onTimeout });return { ...withLinkCredentials(connector, fresh), links: choices };}return (await refreshExpiredConnectorTokens([connector], model, { onTimeout }))[0];diff --git a/apps/server/src/services/connector/__tests__/multiAccount.integration.test.ts b/apps/server/src/services/connector/__tests__/multiAccount.integration.test.tsindex bb480f2a918..24afdd55786 100644--- a/apps/server/src/services/connector/__tests__/multiAccount.integration.test.ts+++ b/apps/server/src/services/connector/__tests__/multiAccount.integration.test.ts@@ -3,6 +3,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitestimport { getTestDB } from '@/database/core/getTestDB';import { ConnectorModel } from '@/database/models/connector';+import { LEGACY_LINK_ID } from '@/database/models/connectorLink';import { ConnectorToolModel } from '@/database/models/connectorTool';import { users } from '@/database/schemas';import { startOAuthMcpServer } from '@/libs/mcp/__tests__/fixtures/oauthMcpServer';@@ -20,7 +21,12 @@ import {toClientInformation,} from '../oauth';import { syncConnectorToolsById } from '../sync';-import { tokensToCredentials } from '../tokens';+import {+ ensureFreshConnectorToken,+ ensureFreshLinkToken,+ refreshExpiredConnectorTokens,+ tokensToCredentials,+} from '../tokens';vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: async () => false }));vi.mock('../refresh', () => ({@@ -54,6 +60,66 @@ afterEach(async () => {});describe('OAuth account routing over real HTTP and database', () => {+ it('persists one rotation across concurrent connector and account callers after the run timeout', async () => {+ const refreshResponse = Promise.withResolvers<void>();+ const fixture = await startOAuthMcpServer('none', 0, {+ beforeRefreshResponse: () => refreshResponse.promise,+ });+ try {+ await db.insert(users).values({ id: 'account-e2e' });+ const created = await model.create({+ credentials: JSON.stringify({+ accessToken: 'tok-alice-expired',+ expiresAt: Date.now() - 1000,+ refreshToken: 'refresh-alice-initial',+ type: 'oauth2',+ }),+ identifier: 'rotating-fixture',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: `${fixture.base}/mcp`,+ name: 'Rotating OAuth',+ oidcConfig: { clientId: 'fixture-client', issuer: fixture.base, scheme: 'dcr' },+ sourceType: 'custom',+ status: 'connected',+ });+ const original = (await model.findById(created.id))!;+ const account = (await linkModel.findById(created.id, LEGACY_LINK_ID))!;+ const onTimeout = vi.fn();+ const [timedOut] = await refreshExpiredConnectorTokens([original], model, { onTimeout });+ expect(onTimeout).toHaveBeenCalledOnce();+ expect(timedOut.credentials).toEqual(original.credentials);+ expect((await model.findById(created.id))?.credentials).toMatchObject({+ refreshState: { status: 'pending' },+ });++ const concurrent = Array.from({ length: 10 }, (_, index) => {+ const worker = new ConnectorModel(db, 'account-e2e', undefined, vault);+ return index % 2+ ? ensureFreshConnectorToken(original, worker)+ : ensureFreshLinkToken(original, account, worker);+ });+ expect(fixture.refreshes).toHaveLength(1);+ refreshResponse.resolve();+ const snapshots = await Promise.all(concurrent);+ expect(+ snapshots.every(+ (item) =>+ item.credentials?.type === 'oauth2' && item.credentials.accessToken === 'tok-alice-1',+ ),+ ).toBe(true);+ expect(fixture.refreshes).toHaveLength(1);+ expect((await model.findById(created.id))?.credentials).toMatchObject({+ accessToken: 'tok-alice-1',+ refreshState: { status: 'complete' },+ refreshToken: 'refresh-alice-1',+ });+ } finally {+ refreshResponse.resolve();+ await fixture.close();+ }+ }, 20_000);+it.each(['idtoken', 'userinfo', 'none'] as const)('authorizes and routes two accounts (%s)',async (variant) => {diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.tsindex 65cb5aabaf1..c5936a44989 100644--- a/apps/server/src/services/connector/exec.test.ts+++ b/apps/server/src/services/connector/exec.test.ts@@ -310,6 +310,29 @@ describe('callConnectorToolById', () => {);});+ it('asks the owner to reconnect a terminal OAuth account before sending a tool call', async () => {+ vi.mocked(ensureFreshConnectorToken).mockResolvedValueOnce({+ ...connector,+ credentials: {+ accessToken: 'expired',+ refreshState: { status: 'reconnect_required' },+ type: 'oauth2',+ },+ });++ const result = await callConnectorToolById(+ { identifier: 'my-conn', toolName: 'do_thing' },+ makeCtx([connector], [tool()]),+ );++ expect(result).toMatchObject({+ content: expect.stringContaining("reconnect 'my-conn'"),+ error: { type: 'AUTHORIZATION_ERROR' },+ success: false,+ });+ expect(mcpService.callTool).not.toHaveBeenCalled();+ });+it('schedules a background tool-list refresh for the connector', async () => {vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });const ctx = makeCtx([connector], [tool()]);diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.tsindex 3f85b4de900..bb0e403557a 100644--- a/apps/server/src/services/connector/exec.ts+++ b/apps/server/src/services/connector/exec.ts@@ -1,7 +1,7 @@import { hasCallableMcpEndpoint, isMarketplaceInstallRunnable } from '@lobechat/const';import { getMcpServerFingerprint, isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';import type { LobeChatDatabase } from '@lobechat/database';-import { getDisabledPluginIds } from '@lobechat/types';+import { getDisabledPluginIds, needsConnectorReauthorization } from '@lobechat/types';import {connectorDeviceBinding,connectorMcpEndpoint,@@ -388,6 +388,17 @@ const resolveCallAccount = async (const fresh = resolved.linkId? resolved.connector: await ensureFreshConnectorToken(connector, ctx.connectorModel);+ if (needsConnectorReauthorization(fresh.credentials)) {+ return {+ failure: failedToolResult(+ buildMcpAuthorizationErrorContent(connector.identifier, {+ isShareVisitor: false,+ linkName: resolved.linkName,+ }),+ 'AUTHORIZATION_ERROR',+ ),+ };+ }return { argsStr: resolved.argsStr, fresh, linkName: resolved.linkName };} catch (error) {if (error instanceof ConnectorLinkSelectionError)diff --git a/apps/server/src/services/connector/links.test.ts b/apps/server/src/services/connector/links.test.tsindex 71ad91dddc5..b3da0f0a53c 100644--- a/apps/server/src/services/connector/links.test.ts+++ b/apps/server/src/services/connector/links.test.ts@@ -55,12 +55,7 @@ describe('resolveLinkedCall', () => {linkId: 'lnk_b',connector: { credentials: { accessToken: 'bob-token' } },});- expect(ensureFreshLinkToken).toHaveBeenLastCalledWith(- connector,- links[1],- expect.anything(),- expect.anything(),- );+ expect(ensureFreshLinkToken).toHaveBeenLastCalledWith(connector, links[1], expect.anything());});it('requires a selector by total count, lists current choices and hides names for visitors', async () => {await expect(resolveLinkedCall({ connector }, context())).rejects.toThrow(diff --git a/apps/server/src/services/connector/links.ts b/apps/server/src/services/connector/links.tsindex 265dda70006..b183e5ac19f 100644--- a/apps/server/src/services/connector/links.ts+++ b/apps/server/src/services/connector/links.ts@@ -88,12 +88,7 @@ export const resolveConnectorAccount = async (accountCount: links.length,connector: await ensureFreshConnectorToken(connector, ctx.connectorModel),};- const fresh = await ensureFreshLinkToken(- connector,- link,- getConnectorLinkModel(ctx),- ctx.connectorModel,- );+ const fresh = await ensureFreshLinkToken(connector, link, ctx.connectorModel);return {accountCount: links.length,connector: withLinkCredentials(connector, fresh),@@ -166,12 +161,7 @@ export const resolveLinkedCall = async (throw new ConnectorLinkSelectionError(`The selected account no longer exists. Current accounts: ${choices}`,);- const fresh = await ensureFreshLinkToken(- connector,- link,- getConnectorLinkModel(ctx),- ctx.connectorModel,- );+ const fresh = await ensureFreshLinkToken(connector, link, ctx.connectorModel);return {connector: withLinkCredentials(connector, fresh),argsStr: split.argsStr,diff --git a/apps/server/src/services/connector/localCallToken.ts b/apps/server/src/services/connector/localCallToken.tsindex 82775162b8d..0dec4dce3b1 100644--- a/apps/server/src/services/connector/localCallToken.ts+++ b/apps/server/src/services/connector/localCallToken.ts@@ -1,9 +1,10 @@+import { needsConnectorReauthorization } from '@lobechat/types';import { connectorMcpEndpoint, isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';import { TRPCError } from '@trpc/server';import type { ConnectorModel } from '@/database/models/connector';-import { getConnectorLinkModel, loadConnectorLinksMap, pickPrimaryLink } from './links';+import { loadConnectorLinksMap, pickPrimaryLink } from './links';import { ensureFreshLinkToken } from './tokens';/**@@ -51,12 +52,13 @@ export const getConnectorLocalCallToken = async (});}- const fresh = await ensureFreshLinkToken(- connector,- link,- getConnectorLinkModel(ctx),- ctx.connectorModel,- );+ const fresh = await ensureFreshLinkToken(connector, link, ctx.connectorModel);+ if (needsConnectorReauthorization(fresh.credentials)) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'Reconnect this connector to continue.',+ });+ }return fresh.credentials.accessToken? { accessToken: fresh.credentials.accessToken, type: 'oauth2' }: null;diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.tsindex b9892fba356..59a351e9f7d 100644--- a/apps/server/src/services/connector/oauth.ts+++ b/apps/server/src/services/connector/oauth.ts@@ -85,8 +85,11 @@ const connectorFetch: FetchLike = mcpSsrfSafeFetch;/** RFC 8414 / OIDC discovery for a connector's authorization server. */export const discoverConnectorAuthorizationServerMetadata = (authorizationServerUrl: string,+ signal?: AbortSignal,): Promise<AuthorizationServerMetadata | undefined> =>- discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: connectorFetch });+ discoverAuthorizationServerMetadata(authorizationServerUrl, {+ fetchFn: signal ? (url, init) => connectorFetch(url, { ...init, signal }) : connectorFetch,+ });export interface DiscoveredOAuth {authorizationServerUrl: string;@@ -458,11 +461,14 @@ export const refreshConnectorToken = async (params: {metadata: AuthorizationServerMetadata;refreshToken: string;resource?: string;+ signal?: AbortSignal;}): Promise<{ authMethod?: TokenEndpointAuthMethod; tokens: OAuthTokens }> =>withClientAuthFallback(params.clientInformation, params.metadata, (clientInformation) =>refreshAuthorization(params.authorizationServerUrl, {clientInformation,- fetchFn: connectorFetch,+ fetchFn: params.signal+ ? (url, init) => connectorFetch(url, { ...init, signal: params.signal })+ : connectorFetch,metadata: params.metadata,refreshToken: params.refreshToken,resource: params.resource ? new URL(params.resource) : undefined,diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.tsindex f783f04cb3b..ad44d6b88ab 100644--- a/apps/server/src/services/connector/sync.ts+++ b/apps/server/src/services/connector/sync.ts@@ -11,6 +11,7 @@ import {resolveMcpUiToolMeta,} from '@lobechat/const/mcpApp';import { type LobeChatDatabase } from '@lobechat/database';+import { needsConnectorReauthorization } from '@lobechat/types';import {connectorConnectVia,connectorDeviceBinding,@@ -28,6 +29,7 @@ import {ConnectorToolPermission,} from '@/database/schemas';import type { AuthConfig, McpTool } from '@/libs/mcp';+import { createMCPError } from '@/libs/mcp/types';import { inferCrudType } from '@/libs/mcp/utils';import { resolveConnectorToolPermission } from '@/server/routers/lambda/_helpers/connectorToolPermission';import { deviceGateway } from '@/server/services/deviceGateway';@@ -69,6 +71,9 @@ export const buildConnectorMcpParams = (};}if (!connector.mcpServerUrl) throw new Error('Connector has no MCP server URL configured');+ if (needsConnectorReauthorization(connector.credentials)) {+ throw createMCPError('AUTHORIZATION_ERROR', 'Reconnect this connector to continue.');+ }const { auth, headers } = buildHttpAuthFromCredentials(connector.credentials);// Custom headers live in `metadata.customHeaders` (plaintext, independent of// the single-kind `credentials` column) so they can coexist with any authdiff --git a/apps/server/src/services/connector/tokens.test.ts b/apps/server/src/services/connector/tokens.test.tsindex f83d379dee4..e8054dbd938 100644--- a/apps/server/src/services/connector/tokens.test.ts+++ b/apps/server/src/services/connector/tokens.test.ts@@ -1,311 +1,269 @@-import {- discoverAuthorizationServerMetadata,- IssuerMismatchError,-} from '@modelcontextprotocol/client';+import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type * as OauthModule from './oauth';-import { refreshConnectorToken } from './oauth';-import { ensureFreshLinkToken, refreshExpiredConnectorTokens } from './tokens';+import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';+import type { DecryptedConnectorLink, OAuthCredentials } from '@/database/models/connectorLink';+import { LEGACY_LINK_ID } from '@/database/models/connectorLink';-vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({- ...(await importOriginal<object>()),- discoverAuthorizationServerMetadata: vi.fn(),-}));-vi.mock('./oauth', async (importOriginal) => ({- ...(await importOriginal<typeof OauthModule>()),+import { discoverConnectorAuthorizationServerMetadata, refreshConnectorToken } from './oauth';+import {+ ensureFreshConnectorToken,+ ensureFreshLinkToken,+ refreshExpiredConnectorTokens,+ refreshExpiredLinkTokens,+} from './tokens';++vi.mock('./oauth', () => ({+ discoverConnectorAuthorizationServerMetadata: vi.fn(),refreshConnectorToken: vi.fn(),+ toClientInformation: vi.fn(),}));const NOW = 1_800_000_000_000;--const oauthConnector = (id: string, expiresAt: number) =>- ({- credentials: { accessToken: `old-${id}`, expiresAt, refreshToken: 'refresh', type: 'oauth2' },- id,- identifier: id,+const expired: OAuthCredentials = {+ accessToken: 'expired',+ expiresAt: NOW - 1000,+ refreshToken: 'previous',+ type: 'oauth2',+};+const rotated = {+ tokens: { access_token: 'fresh', expires_in: 3600, refresh_token: 'next', token_type: 'Bearer' },+};++function store(kind: 'link' | 'legacy' = 'legacy') {+ let row = {+ credentials: kind === 'legacy' ? expired : null,+ id: 'connector',isEnabled: true,mcpServerUrl: 'https://mcp.example.com/mcp',- oidcConfig: { clientId: 'client', issuer: 'https://auth.example.com' },- }) as any;--describe('refreshExpiredConnectorTokens', () => {- beforeEach(() => {- vi.useFakeTimers({ now: NOW });- vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({} as any);- });-- afterEach(() => {- vi.useRealTimers();- vi.clearAllMocks();- });-- it.each([- new TypeError('network unavailable'),- new IssuerMismatchError('metadata', 'https://as', 'https://other'),- ])(- 'keeps credentials and reloads a concurrent rotation after discovery failure: %s',- async (error) => {- const expired = oauthConnector('discovery-failed', NOW - 1000);- const findById = vi.fn().mockResolvedValue(expired);- vi.mocked(discoverAuthorizationServerMetadata).mockRejectedValueOnce(error);- const pending = refreshExpiredConnectorTokens([expired], { findById } as any);- await vi.advanceTimersByTimeAsync(1000);- expect(await pending).toEqual([expired]);- expect(findById).toHaveBeenCalledTimes(2);+ oidcConfig: { clientId: 'client', issuer: 'https://auth.example.com', scheme: 'dcr' },+ status: 'connected',+ workspaceId: null,+ } as DecryptedConnector;+ let link = {+ credentials: expired,+ id: kind === 'legacy' ? LEGACY_LINK_ID : 'lnk_account',+ status: 'connected',+ tokenExpiresAt: new Date(expired.expiresAt!),+ } as DecryptedConnectorLink;+ let queue = Promise.resolve();+ const instance = () => {+ const model = {+ getLinkModel: () => ({+ listByConnectorIds: async () => [+ kind === 'legacy' ? { ...link, credentials: row.credentials, status: row.status } : link,+ ],+ updateCredentials: async (+ _connectorId: string,+ _linkId: string,+ credentials: OAuthCredentials,+ status: DecryptedConnectorLink['status'],+ ) => {+ link = { ...link, credentials, status };+ },+ }),+ update: async (_id: string, { credentials, ...patch }: { credentials?: string }) => {+ row = { ...row, ...patch, ...(credentials && { credentials: JSON.parse(credentials) }) };+ return true;+ },+ withOAuthRefreshLock: vi.fn(+ (_row, action: (current: DecryptedConnector, tx: ConnectorModel) => Promise<unknown>) => {+ const result = queue.then(() => action(row, model as unknown as ConnectorModel));+ queue = result.then(() => {});+ return result;+ },+ ),+ };+ return model as unknown as ConnectorModel;+ };+ return {+ instance,+ read: () => row,+ readLink: () => link,+ reconnect: (credentials: OAuthCredentials) => {+ row = { ...row, credentials };},- );+ };+}- // Agent runs baked the stored (expired) token into manifests, so- // the first call after every expiry 401'd even when it was refreshable.- it('refreshes an expired token and persists the rotated credentials', async () => {- vi.mocked(refreshConnectorToken).mockResolvedValue({- tokens: { access_token: 'new-token', expires_in: 3600, token_type: 'Bearer' },- } as any);- const update = vi.fn();-- const [connector] = await refreshExpiredConnectorTokens([oauthConnector('xmind', NOW - 1000)], {- update,- } as any);-- expect(connector.credentials).toMatchObject({ accessToken: 'new-token' });- expect(update).toHaveBeenCalledWith(- 'xmind',- expect.objectContaining({ tokenExpiresAt: new Date(NOW + 3_600_000) }),- );- });+beforeEach(() => {+ vi.useFakeTimers({ now: NOW });+ vi.mocked(discoverConnectorAuthorizationServerMetadata).mockResolvedValue({} as never);+ vi.mocked(refreshConnectorToken).mockResolvedValue(rotated);+});- it('leaves a valid token alone without contacting the authorization server', async () => {- const valid = oauthConnector('valid', NOW + 3_600_000);+afterEach(() => {+ vi.useRealTimers();+ vi.resetAllMocks();+});- const result = await refreshExpiredConnectorTokens([valid], { update: vi.fn() } as any);+describe('OAuth refresh coordination', () => {+ it('makes one request across two instances and both ways of reading a legacy account', async () => {+ const db = store();+ const stale = db.read();+ const outcomes = Promise.all([+ ensureFreshConnectorToken(stale, db.instance()),+ ensureFreshLinkToken(stale, db.readLink(), db.instance()),+ ]);+ await vi.advanceTimersByTimeAsync(500);- expect(result).toEqual([valid]);- expect(discoverAuthorizationServerMetadata).not.toHaveBeenCalled();+ for (const current of await outcomes) {+ expect(current.credentials).toMatchObject({ accessToken: 'fresh', refreshToken: 'next' });+ }+ expect(refreshConnectorToken).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ refreshToken: 'previous' }),+ );+ expect(db.read().credentials).toMatchObject({ refreshState: { status: 'complete' } });});- it('skips disabled connectors, which never reach the manifests', async () => {- const disabled = { ...oauthConnector('disabled', NOW - 1000), isEnabled: false };+ it.each(['legacy', 'link'] as const)(+ 'keeps a %s refresh claimed after the caller stops waiting',+ async (kind) => {+ const db = store(kind);+ const stale = db.read();+ const link = db.readLink();+ const pending = Promise.withResolvers<typeof rotated>();+ const onTimeout = vi.fn();+ vi.mocked(refreshConnectorToken).mockReturnValueOnce(pending.promise);+ const batch = () =>+ kind === 'legacy'+ ? refreshExpiredConnectorTokens([stale], db.instance(), { onTimeout })+ : refreshExpiredLinkTokens(stale, [link], db.instance(), { onTimeout });++ const first = batch();+ await vi.advanceTimersByTimeAsync(5_000);+ expect((await first)[0].credentials).toEqual(expired);++ const second = batch();+ await vi.advanceTimersByTimeAsync(1000);+ expect(refreshConnectorToken).toHaveBeenCalledTimes(1);+ pending.resolve(rotated);+ await vi.advanceTimersByTimeAsync(500);- const result = await refreshExpiredConnectorTokens([disabled], { update: vi.fn() } as any);+ expect((await second)[0].credentials).toMatchObject({ accessToken: 'fresh' });+ expect(onTimeout).toHaveBeenCalledTimes(1);+ expect(refreshConnectorToken).toHaveBeenCalledTimes(1);+ },+ );- expect(result).toEqual([disabled]);- expect(discoverAuthorizationServerMetadata).not.toHaveBeenCalled();+ it('reuses a persisted rotation even when the provider omitted expires_in', async () => {+ const db = store();+ const stale = db.read();+ db.reconnect({ accessToken: 'different', refreshToken: 'rotated', type: 'oauth2' });+ expect((await ensureFreshConnectorToken(stale, db.instance())).credentials).toMatchObject({+ accessToken: 'different',+ refreshToken: 'rotated',+ });+ expect(refreshConnectorToken).not.toHaveBeenCalled();});- it('does not refresh a token whose expiry is unknown', async () => {- const unknown = oauthConnector('unknown-expiry', NOW);- delete unknown.credentials.expiresAt;-- const result = await refreshExpiredConnectorTokens([unknown], { update: vi.fn() } as any);-- expect(result).toEqual([unknown]);- expect(discoverAuthorizationServerMetadata).not.toHaveBeenCalled();+ it.each([+ new OAuthError(OAuthErrorCode.InvalidGrant, 'Grant is no longer valid'),+ new TypeError('Connection lost with unknown refresh outcome'),+ new DOMException('Token response timed out', 'TimeoutError'),+ ])('marks an unusable or uncertain grant as requiring reconnection: %s', async (error) => {+ const db = store('link');+ const stale = db.readLink();+ vi.mocked(refreshConnectorToken).mockRejectedValueOnce(error);+ for (let call = 0; call < 2; call++) {+ expect(await ensureFreshLinkToken(db.read(), stale, db.instance())).toMatchObject({+ credentials: { refreshState: { status: 'reconnect_required' } },+ status: 'error',+ });+ }+ expect(db.read().status).toBe('error');+ expect(db.readLink().credentials.refreshToken).toBeUndefined();+ expect(refreshConnectorToken).toHaveBeenCalledTimes(1);});- it('keeps the stored credentials when the authorization server hangs', async () => {- vi.mocked(refreshConnectorToken).mockReturnValue(new Promise(() => {}));- const expired = oauthConnector('slow', NOW - 1000);-- const onTimeout = vi.fn();-- const pending = refreshExpiredConnectorTokens([expired], { update: vi.fn() } as any, {- onTimeout,+ it('does not submit a token again when the owner stops before recording the outcome', async () => {+ const db = store();+ db.reconnect({+ ...expired,+ refreshState: { deadline: NOW, id: 'abandoned', status: 'pending' },});- await vi.advanceTimersByTimeAsync(5000);- expect(await pending).toEqual([expired]);- expect(onTimeout).toHaveBeenCalledTimes(1);+ expect(await ensureFreshConnectorToken(db.read(), db.instance())).toMatchObject({+ credentials: { refreshState: { status: 'reconnect_required' } },+ status: 'error',+ });+ expect(refreshConnectorToken).not.toHaveBeenCalled();});- it('retries on a later run after a refresh hung past the timeout', async () => {- vi.mocked(refreshConnectorToken).mockReturnValue(new Promise(() => {}));- const expired = oauthConnector('hung', NOW - 1000);- const model = { update: vi.fn() } as any;-- const first = refreshExpiredConnectorTokens([expired], model);- await vi.advanceTimersByTimeAsync(5000);- await first;-- vi.mocked(refreshConnectorToken).mockResolvedValue({- tokens: { access_token: 'recovered', expires_in: 3600, token_type: 'Bearer' },- } as any);- const [connector] = await refreshExpiredConnectorTokens([expired], model);+ it('preserves credentials when discovery fails and permits a later attempt', async () => {+ const db = store();+ const stale = db.read();+ vi.mocked(discoverConnectorAuthorizationServerMetadata).mockRejectedValueOnce(+ new TypeError('Discovery unavailable'),+ );+ expect((await ensureFreshConnectorToken(stale, db.instance())).credentials).toEqual(expired);+ expect(refreshConnectorToken).not.toHaveBeenCalled();- expect(refreshConnectorToken).toHaveBeenCalledTimes(2);- expect(connector.credentials).toMatchObject({ accessToken: 'recovered' });+ expect((await ensureFreshConnectorToken(stale, db.instance())).credentials).toMatchObject({+ accessToken: 'fresh',+ });});- it('keeps the stored credentials when the refresh is rejected', async () => {- vi.mocked(refreshConnectorToken).mockRejectedValue(new Error('invalid_grant'));- const expired = oauthConnector('revoked', NOW - 1000);- const findById = vi.fn().mockResolvedValue(expired);-- const pending = refreshExpiredConnectorTokens([expired], { findById, update: vi.fn() } as any);- await vi.advanceTimersByTimeAsync(1000);+ it('keeps a refresh token when the provider does not rotate it', async () => {+ const db = store();+ vi.mocked(refreshConnectorToken).mockResolvedValueOnce({+ tokens: { access_token: 'fresh', expires_in: 3600, token_type: 'Bearer' },+ });- expect(await pending).toEqual([expired]);+ expect((await ensureFreshConnectorToken(db.read(), db.instance())).credentials).toMatchObject({+ accessToken: 'fresh',+ refreshToken: 'previous',+ });});- it('spends the refresh token once for concurrent runs on one instance', async () => {- vi.mocked(refreshConnectorToken).mockResolvedValue({- tokens: { access_token: 'new-token', expires_in: 3600, token_type: 'Bearer' },- } as any);- const model = { update: vi.fn() } as any;- const expired = oauthConnector('shared', NOW - 1000);-- const [[first], [second]] = await Promise.all([- refreshExpiredConnectorTokens([expired], model),- refreshExpiredConnectorTokens([expired], model),+ it('coalesces overlapping calls when an unrotated grant returns identical credentials', async () => {+ const db = store();+ db.reconnect({ ...expired, expiresAt: undefined });+ vi.mocked(refreshConnectorToken).mockResolvedValueOnce({+ tokens: { access_token: expired.accessToken, token_type: 'Bearer' },+ });+ const stale = db.read();+ const outcomes = Promise.all([+ ensureFreshConnectorToken(stale, db.instance()),+ ensureFreshConnectorToken(stale, db.instance()),]);-+ await vi.advanceTimersByTimeAsync(500);++ for (const current of await outcomes) {+ expect(current.credentials).toMatchObject({+ accessToken: expired.accessToken,+ refreshState: { status: 'complete' },+ refreshToken: expired.refreshToken,+ });+ }expect(refreshConnectorToken).toHaveBeenCalledTimes(1);- expect(first.credentials).toMatchObject({ accessToken: 'new-token' });- expect(second.credentials).toMatchObject({ accessToken: 'new-token' });});- it('uses the token another instance rotated when its own refresh loses the race', async () => {- vi.mocked(refreshConnectorToken).mockRejectedValue(new Error('invalid_grant'));- const expired = oauthConnector('raced', NOW - 1000);- const rotated = {- ...expired,- credentials: { accessToken: 'winner', expiresAt: NOW + 3_600_000, type: 'oauth2' },- };+ it('keeps a reauthorized grant if an older refresh finishes afterward', async () => {+ const db = store();+ const pending = Promise.withResolvers<typeof rotated>();+ vi.mocked(refreshConnectorToken).mockReturnValueOnce(pending.promise);- const [connector] = await refreshExpiredConnectorTokens([expired], {- findById: vi.fn().mockResolvedValue(rotated),- update: vi.fn(),- } as any);+ const refresh = ensureFreshConnectorToken(db.read(), db.instance());+ await vi.advanceTimersByTimeAsync(0);+ const authorized: OAuthCredentials = { ...expired, accessToken: 'newly-authorized' };+ db.reconnect(authorized);+ pending.resolve(rotated);- expect(connector.credentials).toMatchObject({ accessToken: 'winner' });+ expect((await refresh).credentials).toEqual(authorized);+ expect(db.read().credentials).toEqual(authorized);});- it('waits for a winner that is still persisting the rotated token', async () => {- vi.mocked(refreshConnectorToken).mockRejectedValue(new Error('invalid_grant'));- const expired = oauthConnector('persisting', NOW - 1000);- const rotated = {- ...expired,- credentials: { accessToken: 'winner', expiresAt: NOW + 3_600_000, type: 'oauth2' },- };- const findById = vi.fn().mockResolvedValueOnce(expired).mockResolvedValueOnce(rotated);-- const pending = refreshExpiredConnectorTokens([expired], { findById, update: vi.fn() } as any);- await vi.advanceTimersByTimeAsync(1000);-- expect((await pending)[0].credentials).toMatchObject({ accessToken: 'winner' });- expect(findById).toHaveBeenCalledTimes(2);- });-- it('uses a rotated token whose authorization server omitted an expiry', async () => {- vi.mocked(refreshConnectorToken).mockRejectedValue(new Error('invalid_grant'));- const expired = oauthConnector('no-expiry', NOW - 1000);- const rotated = { ...expired, credentials: { accessToken: 'winner', type: 'oauth2' } };-- const [connector] = await refreshExpiredConnectorTokens([expired], {- findById: vi.fn().mockResolvedValue(rotated),- update: vi.fn(),- } as any);-- expect(connector.credentials).toMatchObject({ accessToken: 'winner' });- });-});--describe('per-account token refresh', () => {- beforeEach(() => {- vi.useFakeTimers({ now: NOW });- vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({} as any);- });- afterEach(() => {- vi.useRealTimers();- vi.clearAllMocks();- });- const makeLink = (id: string) =>- ({- id,- userConnectorId: 'parent',- name: id,- status: 'connected',- credentials: {- accessToken: `old-${id}`,- refreshToken: `refresh-${id}`,- expiresAt: NOW - 1,- type: 'oauth2',- },- }) as any;- it('coalesces concurrent refreshes by link id and never writes tokens onto the parent', async () => {- vi.mocked(refreshConnectorToken).mockResolvedValue({- tokens: { access_token: 'fresh', expires_in: 3600, token_type: 'Bearer' },- } as any);- const link = makeLink('coalesce');- const linkModel = { updateCredentials: vi.fn() } as any;- const parentModel = { update: vi.fn() } as any;- const connector = oauthConnector('parent', NOW - 1);- const results = await Promise.all([- ensureFreshLinkToken(connector, link, linkModel, parentModel),- ensureFreshLinkToken(connector, link, linkModel, parentModel),- ]);- expect(refreshConnectorToken).toHaveBeenCalledOnce();- expect(linkModel.updateCredentials).toHaveBeenCalledWith(- 'parent',- 'coalesce',- expect.objectContaining({ accessToken: 'fresh', refreshToken: 'refresh-coalesce' }),- );- expect(parentModel.update).not.toHaveBeenCalled();- expect(results[0].credentials.accessToken).toBe('fresh');- });- // Account ids are unique within their connector only: every connector read- // from a token written before accounts existed has the same one.- it('refreshes accounts with the same id on different connectors separately', async () => {- vi.mocked(refreshConnectorToken).mockImplementation(async ({ refreshToken }) => ({- tokens: { access_token: `fresh-${refreshToken}`, expires_in: 3600, token_type: 'Bearer' },- }));- const linkModel = { updateCredentials: vi.fn() } as any;- const linkOf = (connectorId: string) => ({- ...makeLink('lnk_default'),- userConnectorId: connectorId,- credentials: {- ...makeLink('lnk_default').credentials,- refreshToken: `refresh-${connectorId}`,- },- });- const results = await Promise.all(- ['first', 'second'].map((id) =>- ensureFreshLinkToken(oauthConnector(id, NOW - 1), linkOf(id), linkModel, {} as any),- ),- );- expect(refreshConnectorToken).toHaveBeenCalledTimes(2);- expect(results.map((link) => link.credentials.accessToken)).toEqual([- 'fresh-refresh-first',- 'fresh-refresh-second',- ]);- expect(linkModel.updateCredentials).toHaveBeenCalledWith(- 'second',- 'lnk_default',- expect.objectContaining({ accessToken: 'fresh-refresh-second' }),- );- });- it('recovers a rotation from another process before marking invalid_grant as unhealthy', async () => {- vi.mocked(refreshConnectorToken).mockRejectedValue({ code: 'invalid_grant' });- const stale = makeLink('rotated');- const fresh = {- ...stale,- credentials: { ...stale.credentials, accessToken: 'winner', expiresAt: NOW + 3600000 },- };- const linkModel = { findById: vi.fn().mockResolvedValue(fresh), updateStatus: vi.fn() } as any;- expect(- (await ensureFreshLinkToken(oauthConnector('parent', NOW - 1), stale, linkModel, {} as any))- .credentials.accessToken,- ).toBe('winner');- expect(linkModel.updateStatus).not.toHaveBeenCalled();- linkModel.findById.mockResolvedValue(stale);- const pending = ensureFreshLinkToken(- oauthConnector('parent', NOW - 1),- stale,- linkModel,- {} as any,- );- await vi.advanceTimersByTimeAsync(1000);- expect((await pending).status).toBe('error');- expect(linkModel.updateStatus).toHaveBeenCalledWith('parent', 'rotated', 'error');+ it('skips disabled, valid and unknown-expiry credentials during run preparation', async () => {+ const db = store();+ const row = db.read();+ const rows = [+ { ...row, isEnabled: false },+ { ...row, credentials: { ...expired, expiresAt: NOW + 3_600_000 } },+ { ...row, credentials: { ...expired, expiresAt: undefined } },+ ];+ const model = db.instance();+ expect(await refreshExpiredConnectorTokens(rows, model)).toEqual(rows);+ expect(model.withOAuthRefreshLock).not.toHaveBeenCalled();});});diff --git a/apps/server/src/services/connector/tokens.ts b/apps/server/src/services/connector/tokens.tsindex 6d134b17b7f..af014cbfd3c 100644--- a/apps/server/src/services/connector/tokens.ts+++ b/apps/server/src/services/connector/tokens.ts@@ -1,10 +1,15 @@-import type { OAuthTokens } from '@modelcontextprotocol/client';+import { randomUUID } from 'node:crypto';++import { OAuthError, OAuthErrorCode, type OAuthTokens } from '@modelcontextprotocol/client';import debug from 'debug';import pMap from 'p-map';import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';-import type { ConnectorLinkModel, DecryptedConnectorLink } from '@/database/models/connectorLink';-import type { ConnectorCredentials } from '@/database/schemas';+import {+ type DecryptedConnectorLink,+ LEGACY_LINK_ID,+ type OAuthCredentials,+} from '@/database/models/connectorLink';import {discoverConnectorAuthorizationServerMetadata,@@ -21,7 +26,7 @@ const EXPIRY_SKEW_MS = 60_000;export const tokensToCredentials = (tokens: OAuthTokens,opts: { clientSecret?: string; fallbackRefreshToken?: string } = {},-): { credentials: ConnectorCredentials; tokenExpiresAt: Date | null } => {+): { credentials: OAuthCredentials; tokenExpiresAt: Date | null } => {const expiresAt = tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined;return {credentials: {@@ -37,307 +42,328 @@ export const tokensToCredentials = (};};-/** Whether the connector holds a refreshable OAuth token that is expired or about to expire. */-const isRefreshDue = (connector: DecryptedConnector): boolean => {- const creds = connector.credentials;- if (!creds || creds.type !== 'oauth2' || !creds.refreshToken) return false;- return !creds.expiresAt || creds.expiresAt - EXPIRY_SKEW_MS <= Date.now();-};+const RUN_TOKEN_REFRESH_TIMEOUT_MS = 5000;+const RUN_TOKEN_REFRESH_CONCURRENCY = 5;+const REFRESH_REQUEST_TIMEOUT_MS = 20_000;+const REFRESH_ATTEMPT_TTL_MS = 30_000;+const REFRESH_POLL_INTERVAL_MS = 500;-const hasKnownExpiry = (connector: DecryptedConnector): boolean =>- connector.credentials?.type === 'oauth2' && !!connector.credentials.expiresAt;+const isRefreshDue = (+ credentials: DecryptedConnector['credentials'],+): credentials is OAuthCredentials & { refreshToken: string } =>+ credentials?.type === 'oauth2' &&+ !!credentials.refreshToken &&+ (!credentials.expiresAt || credentials.expiresAt - EXPIRY_SKEW_MS <= Date.now());-/**- * Lazily refresh a connector's OAuth access token when it is expired (or about- * to expire). Persists the rotated credentials and returns the connector with- * fresh credentials in memory. No-op for non-oauth2 connectors or when the- * token is still valid / not refreshable.- */-export const ensureFreshConnectorToken = async (+interface RefreshSlot {+ connector: DecryptedConnector;+ credentials: OAuthCredentials;+ link?: DecryptedConnectorLink;+ linkCount: number;+}++const readSlot = async (connector: DecryptedConnector,- connectorModel: ConnectorModel,-): Promise<DecryptedConnector> => {- const creds = connector.credentials;- const oidc = connector.oidcConfig;+ model: ConnectorModel,+ linkId?: string,+): Promise<RefreshSlot | undefined> => {+ if (!linkId && connector.credentials?.type === 'oauth2') {+ return { connector, credentials: connector.credentials, linkCount: 0 };+ }+ // An older single-token row can be migrated to an account while a run+ // still holds the old snapshot. Both entry points target that same slot.+ const links = await model.getLinkModel().listByConnectorIds([connector.id]);+ const link = links.find((item) => item.id === (linkId ?? LEGACY_LINK_ID));+ if (link) return { connector, credentials: link.credentials, link, linkCount: links.length };+};++const writeSlot = async (+ model: ConnectorModel,+ slot: RefreshSlot,+ credentials: OAuthCredentials,+ update?: {+ authMethod?: NonNullable<DecryptedConnector['oidcConfig']>['tokenEndpointAuthMethod'];+ status: 'connected' | 'error';+ },+): Promise<RefreshSlot> => {+ const { connector, link, linkCount } = slot;+ const tokenExpiresAt = credentials.expiresAt ? new Date(credentials.expiresAt) : null;+ const oidcConfig =+ update?.authMethod && connector.oidcConfig+ ? { ...connector.oidcConfig, tokenEndpointAuthMethod: update.authMethod }+ : undefined;+ const status = linkCount <= 1 && update?.status === 'error' ? update.status : undefined;- if (!creds || creds.type !== 'oauth2' || !creds.refreshToken || !isRefreshDue(connector)) {- return connector;+ if (link && connector.credentials?.type !== 'oauth2') {+ await model+ .getLinkModel()+ .updateCredentials(connector.id, link.id, credentials, update?.status ?? link.status);+ if (status || oidcConfig) {+ await model.update(connector.id, {+ ...(status && { status }),+ ...(oidcConfig && { oidcConfig }),+ });+ }+ } else {+ await model.update(connector.id, {+ credentials: JSON.stringify(credentials),+ tokenExpiresAt,+ ...(status && { status }),+ ...(oidcConfig && { oidcConfig }),+ });}- if (!oidc?.issuer || !oidc.clientId) return connector;- try {- const metadata = await discoverConnectorAuthorizationServerMetadata(oidc.issuer);- if (!metadata) return connector;+ return {+ ...slot,+ connector: { ...connector, ...(status && { status }), ...(oidcConfig && { oidcConfig }) },+ credentials,+ link: link && { ...link, credentials, status: update?.status ?? link.status, tokenExpiresAt },+ };+};++const reconnectCredentials = (credentials: OAuthCredentials): OAuthCredentials => ({+ ...credentials,+ refreshState: { status: 'reconnect_required' },+ refreshToken: undefined,+});++const isSameCredential = (current: OAuthCredentials, original: OAuthCredentials) =>+ current.refreshToken === original.refreshToken &&+ current.accessToken === original.accessToken &&+ current.expiresAt === original.expiresAt &&+ current.refreshState?.status === original.refreshState?.status &&+ (current.refreshState?.status !== 'complete' ||+ (original.refreshState?.status === 'complete' &&+ current.refreshState.id === original.refreshState.id));+type RefreshDecision =+ | { kind: 'done'; slot?: RefreshSlot }+ | { kind: 'send'; attemptId: string; deadline: number; slot: RefreshSlot }+ | { kind: 'wait'; deadline: number; slot: RefreshSlot };++const claimRefresh = (+ connector: DecryptedConnector,+ original: OAuthCredentials,+ model: ConnectorModel,+ linkId?: string,+) =>+ model.withOAuthRefreshLock<RefreshDecision>(connector, async (row, lockedModel) => {+ const slot = await readSlot(row, lockedModel, linkId);+ if (!slot) return { kind: 'done' };+ const { credentials } = slot;+ const state = credentials.refreshState;+ if (state?.status === 'pending') {+ if (state.deadline > Date.now()) return { deadline: state.deadline, kind: 'wait', slot };+ // The owner may have submitted the token before exiting. Its outcome+ // is unknown, so allowing a new owner to send the same token is unsafe.+ const failed = await writeSlot(lockedModel, slot, reconnectCredentials(credentials), {+ status: 'error',+ });+ return { kind: 'done', slot: failed };+ }++ if (+ !row.isEnabled ||+ !row.oidcConfig?.issuer ||+ !row.oidcConfig.clientId ||+ !isSameCredential(credentials, original) ||+ !isRefreshDue(credentials)+ ) {+ return { kind: 'done', slot };+ }++ const attemptId = randomUUID();+ const deadline = Date.now() + REFRESH_ATTEMPT_TTL_MS;+ await writeSlot(lockedModel, slot, {+ ...credentials,+ refreshState: { deadline, id: attemptId, status: 'pending' },+ });+ // The claim commits before the OAuth request starts. No database lock or+ // transaction needs to stay open while waiting on the provider.+ return { attemptId, deadline, kind: 'send', slot };+ });++const fetchRefresh = async (slot: RefreshSlot, attemptId: string, signal: AbortSignal) => {+ const { connector, credentials } = slot;+ const oidc = connector.oidcConfig;+ if (!oidc?.issuer || !credentials.refreshToken) return;+ const metadata = await discoverConnectorAuthorizationServerMetadata(oidc.issuer, signal);+ if (!metadata) return;+ signal.throwIfAborted();++ try {const { authMethod, tokens } = await refreshConnectorToken({authorizationServerUrl: oidc.issuer,clientInformation: toClientInformation(oidc),metadata,- refreshToken: creds.refreshToken,+ refreshToken: credentials.refreshToken,resource: connector.mcpServerUrl ?? undefined,+ signal,});+ return {+ authMethod,+ credentials: {+ ...tokensToCredentials(tokens, {+ clientSecret: oidc.clientSecret,+ fallbackRefreshToken: credentials.refreshToken,+ }).credentials,+ refreshState: { id: attemptId, status: 'complete' as const },+ },+ status: 'connected' as const,+ };+ } catch (error) {+ if (+ !signal.aborted &&+ OAuthError.isInstance(error) &&+ error.code !== OAuthErrorCode.InvalidGrant &&+ error.code !== OAuthErrorCode.ServerError+ ) {+ // The provider explicitly rejected the request without issuing tokens.+ return;+ }+ // A rejected grant or an uncertain transport/server failure must not+ // cause another submission. The provider may already have rotated it.+ return { credentials: reconnectCredentials(credentials), status: 'error' as const };+ }+};- const { credentials, tokenExpiresAt } = tokensToCredentials(tokens, {- clientSecret: oidc.clientSecret,- fallbackRefreshToken: creds.refreshToken,- });-- await connectorModel.update(connector.id, {- credentials: JSON.stringify(credentials),- ...(authMethod && { oidcConfig: { ...oidc, tokenEndpointAuthMethod: authMethod } }),- tokenExpiresAt,- });-- return { ...connector, credentials };+const runClaimedRefresh = async (+ decision: Extract<RefreshDecision, { kind: 'send' }>,+ model: ConnectorModel,+ linkId?: string,+) => {+ const { attemptId, deadline, slot } = decision;+ let result: Awaited<ReturnType<typeof fetchRefresh>>;+ try {+ const remaining = Math.min(REFRESH_REQUEST_TIMEOUT_MS, deadline - Date.now());+ if (remaining > 0) result = await fetchRefresh(slot, attemptId, AbortSignal.timeout(remaining));} catch (error) {+ // Discovery failed before the token request was sent.log(- 'token refresh failed for connector=%s errorType=%s',- connector.id,+ 'OAuth discovery failed for connector=%s errorType=%s',+ slot.connector.id,error instanceof Error ? error.name : typeof error,);- return reloadIfRotatedElsewhere(connector, connectorModel);}-};-/**- * How long a failed refresh waits for a concurrent winner to persist the- * rotated token before re-reading once more.- */-const ROTATION_PERSIST_GRACE_MS = 1000;+ return model.withOAuthRefreshLock(slot.connector, async (row, lockedModel) => {+ const current = await readSlot(row, lockedModel, linkId);+ if (!current) return;+ const state = current.credentials.refreshState;+ // Reauthorization, account removal or a newer outcome won while the+ // OAuth request was in flight. Leave that state alone.+ if (state?.status !== 'pending' || state.id !== attemptId) return current;+ return writeSlot(lockedModel, current, result?.credentials ?? slot.credentials, result);+ });+};-const readRotatedCredentials = async (+const refreshSlot = async (connector: DecryptedConnector,- connectorModel: ConnectorModel,-): Promise<DecryptedConnector | undefined> => {- const staleCreds = connector.credentials;- const latestCreds = (await connectorModel.findById(connector.id))?.credentials;- if (- latestCreds?.type === 'oauth2' &&- staleCreds?.type === 'oauth2' &&- latestCreds.accessToken !== staleCreds.accessToken &&- // Servers may omit `expires_in`, so a rotated token can lack an expiry.- (!latestCreds.expiresAt || latestCreds.expiresAt - EXPIRY_SKEW_MS > Date.now())- ) {- return { ...connector, credentials: latestCreds };+ credentials: DecryptedConnector['credentials'],+ model: ConnectorModel,+ linkId?: string,+ waitUntil = Date.now() + REFRESH_ATTEMPT_TTL_MS,+): Promise<RefreshSlot | undefined> => {+ if (!isRefreshDue(credentials)) return;+ try {+ while (true) {+ const decision = await claimRefresh(connector, credentials, model, linkId);+ if (!decision || decision.kind === 'done') return decision?.slot;+ if (decision.kind === 'send') return await runClaimedRefresh(decision, model, linkId);+ if (Date.now() >= waitUntil) return decision.slot;+ const now = Date.now();+ const delay = Math.min(REFRESH_POLL_INTERVAL_MS, decision.deadline - now, waitUntil - now);+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ } catch (error) {+ log(+ 'OAuth refresh state failed for connector=%s errorType=%s',+ connector.id,+ error instanceof Error ? error.name : typeof error,+ );}};-/**- * A rotating authorization server invalidates a refresh token once it is used,- * so when two runs refresh the same connector concurrently the loser fails- * with credentials the winner already replaced. Re-read the row — once more- * after a short grace, since the winner may still be persisting — and use the- * winner's token instead of failing the run with a stale one.- */-const reloadIfRotatedElsewhere = async (+export const ensureFreshConnectorToken = async (connector: DecryptedConnector,- connectorModel: ConnectorModel,+ model: ConnectorModel,+ waitUntil?: number,): Promise<DecryptedConnector> => {- try {- const rotated = await readRotatedCredentials(connector, connectorModel);- if (rotated) return rotated;-- await new Promise((resolve) => setTimeout(resolve, ROTATION_PERSIST_GRACE_MS));- return (await readRotatedCredentials(connector, connectorModel)) ?? connector;- } catch {- log('reloading connector=%s after a failed refresh failed', connector.id);- return connector;- }+ const slot = await refreshSlot(connector, connector.credentials, model, undefined, waitUntil);+ if (!slot) return connector;+ const { credentials } = slot;+ return {+ ...slot.connector,+ credentials,+ tokenExpiresAt: credentials.expiresAt ? new Date(credentials.expiresAt) : null,+ };};-/**- * Upper bound a run waits on one authorization server. On timeout the run- * keeps the stored credentials; the refresh still finishes and persists.- */-const RUN_TOKEN_REFRESH_TIMEOUT_MS = 5000;--/**- * Concurrent authorization-server calls per run. Runs rarely hold more due- * OAuth connectors than this, so the common case still finishes in one wave.- */-const RUN_TOKEN_REFRESH_CONCURRENCY = 5;--/**- * Refreshes in flight on this instance, keyed by connector id, so concurrent- * runs of one shared agent spend the refresh token once instead of racing.- */-const inFlightRefreshes = new Map<string, Promise<DecryptedConnector>>();--const refreshOnce = (+export const ensureFreshLinkToken = async (connector: DecryptedConnector,- connectorModel: ConnectorModel,-): Promise<DecryptedConnector> => {- const pending = inFlightRefreshes.get(connector.id);- if (pending) return pending;+ link: DecryptedConnectorLink,+ model: ConnectorModel,+ waitUntil?: number,+): Promise<DecryptedConnectorLink> =>+ (await refreshSlot(connector, link.credentials, model, link.id, waitUntil))?.link ?? link;- const refresh = ensureFreshConnectorToken(connector, connectorModel).finally(() => {- if (inFlightRefreshes.get(connector.id) === refresh) inFlightRefreshes.delete(connector.id);+/** Bound the caller's wait while a claimed refresh continues to persist its outcome. */+const waitForRunRefresh = async <T>(+ original: T,+ refresh: (waitUntil: number) => Promise<T>,+ onTimeout?: () => void,+): Promise<T> => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const waitUntil = Date.now() + RUN_TOKEN_REFRESH_TIMEOUT_MS;+ const timeout = new Promise<T>((resolve) => {+ timer = setTimeout(() => {+ onTimeout?.();+ resolve(original);+ }, RUN_TOKEN_REFRESH_TIMEOUT_MS);});- inFlightRefreshes.set(connector.id, refresh);- return refresh;+ try {+ return await Promise.race([timeout, refresh(waitUntil)]);+ } finally {+ clearTimeout(timer);+ }};-/**- * Refresh expired OAuth tokens before an agent run bakes connector credentials- * into its tool manifests. Without this the runtime only refreshed through the- * background tool sync scheduled after the run started, so the first call after- * every access-token expiry 401'd even when the refresh token was still valid —- * and the model then reported a connection that only needed a refresh as one- * the owner must reconnect.- *- * `connectorModel` must carry the gatekeeper so rotated credentials are- * persisted encrypted. Never throws; a connector that cannot be refreshed is- * returned unchanged, and `onTimeout` reports each one that hit the time limit.- */export const refreshExpiredConnectorTokens = (connectors: DecryptedConnector[],- connectorModel: ConnectorModel,+ model: ConnectorModel,options: { onTimeout?: () => void } = {},): Promise<DecryptedConnector[]> =>pMap(connectors,- async (connector) => {- // Disabled connectors never reach the manifests, so refreshing them only- // delays the run and rotates credentials nobody uses. A token without a- // known expiry (the server omitted `expires_in`) is not known to be- // stale; refreshing it here would rotate it on every chat.- if (!connector.isEnabled || !hasKnownExpiry(connector) || !isRefreshDue(connector)) {- return connector;- }-- const refresh = refreshOnce(connector, connectorModel);- let timer: ReturnType<typeof setTimeout> | undefined;- const timeout = new Promise<DecryptedConnector>((resolve) => {- timer = setTimeout(() => {- log('token refresh timed out for connector=%s', connector.id);- // A refresh that never settles would otherwise stay shared forever,- // making every later run wait on it instead of retrying.- if (inFlightRefreshes.get(connector.id) === refresh) {- inFlightRefreshes.delete(connector.id);- }- options.onTimeout?.();- resolve(connector);- }, RUN_TOKEN_REFRESH_TIMEOUT_MS);- });- try {- return await Promise.race([refresh, timeout]);- } finally {- clearTimeout(timer);- }- },+ // When a provider omitted expires_in, the agent run has no expiry to act on.+ (connector) =>+ connector.isEnabled &&+ connector.credentials?.type === 'oauth2' &&+ connector.credentials.expiresAt+ ? waitForRunRefresh(+ connector,+ (waitUntil) => ensureFreshConnectorToken(connector, model, waitUntil),+ options.onTimeout,+ )+ : connector,{ concurrency: RUN_TOKEN_REFRESH_CONCURRENCY },);-/**- * Account refreshes in flight on this instance. Keyed by connector and account:- * account ids are unique within their connector only.- */-const inFlightLinkRefreshes = new Map<string, Promise<DecryptedConnectorLink>>();-const linkRefreshKey = (connector: DecryptedConnector, link: DecryptedConnectorLink) =>- `${connector.id}:${link.id}`;-export const ensureFreshLinkToken = (- connector: DecryptedConnector,- link: DecryptedConnectorLink,- linkModel: ConnectorLinkModel,- connectorModel: ConnectorModel,-): Promise<DecryptedConnectorLink> => {- const creds = link.credentials;- const oidc = connector.oidcConfig;- if (- !creds.refreshToken ||- (creds.expiresAt && creds.expiresAt - EXPIRY_SKEW_MS > Date.now()) ||- !oidc?.issuer ||- !oidc.clientId- )- return Promise.resolve(link);- const key = linkRefreshKey(connector, link);- const pending = inFlightLinkRefreshes.get(key);- if (pending) return pending;- const refresh = (async () => {- try {- const metadata = await discoverConnectorAuthorizationServerMetadata(oidc.issuer!);- if (!metadata) return link;- const { authMethod, tokens } = await refreshConnectorToken({- authorizationServerUrl: oidc.issuer!,- clientInformation: toClientInformation(oidc),- metadata,- refreshToken: creds.refreshToken!,- resource: connector.mcpServerUrl ?? undefined,- });- const { credentials, tokenExpiresAt } = tokensToCredentials(tokens, {- clientSecret: oidc.clientSecret,- fallbackRefreshToken: creds.refreshToken,- });- if (credentials.type !== 'oauth2') return link;- await linkModel.updateCredentials(connector.id, link.id, credentials);- if (authMethod && authMethod !== oidc.tokenEndpointAuthMethod)- await connectorModel.update(connector.id, {- oidcConfig: { ...oidc, tokenEndpointAuthMethod: authMethod },- });- return { ...link, credentials, tokenExpiresAt, status: 'connected' as const };- } catch (error) {- // Another process may have rotated this refresh token. Re-read before- // marking the account unhealthy, including a short persistence grace.- for (let attempt = 0; attempt < 2; attempt++) {- if (attempt) await new Promise((resolve) => setTimeout(resolve, ROTATION_PERSIST_GRACE_MS));- const latest = await linkModel.findById(connector.id, link.id);- if (- latest &&- latest.credentials.accessToken !== creds.accessToken &&- (!latest.credentials.expiresAt ||- latest.credentials.expiresAt - EXPIRY_SKEW_MS > Date.now())- )- return latest;- }- const code =- (error as { error?: string; code?: string }).error ?? (error as { code?: string }).code;- if (- code === 'invalid_grant' ||- (error instanceof Error && /invalid_grant/i.test(error.message))- ) {- await linkModel.updateStatus(connector.id, link.id, 'error');- return { ...link, status: 'error' as const };- }- log(- 'token refresh failed for link=%s errorType=%s',- link.id,- error instanceof Error ? error.name : typeof error,- );- return link;- }- })().finally(() => {- if (inFlightLinkRefreshes.get(key) === refresh) inFlightLinkRefreshes.delete(key);- });- inFlightLinkRefreshes.set(key, refresh);- return refresh;-};--export const refreshExpiredLinkTokens = async (+export const refreshExpiredLinkTokens = (connector: DecryptedConnector,links: DecryptedConnectorLink[],- linkModel: ConnectorLinkModel,- connectorModel: ConnectorModel,+ model: ConnectorModel,options: { onTimeout?: () => void } = {},-) =>+): Promise<DecryptedConnectorLink[]> =>pMap(links,- async (link) => {- if (!connector.isEnabled || !link.credentials.expiresAt) return link;- const refresh = ensureFreshLinkToken(connector, link, linkModel, connectorModel);- let timer: ReturnType<typeof setTimeout> | undefined;- const timeout = new Promise<DecryptedConnectorLink>((resolve) => {- timer = setTimeout(() => {- const key = linkRefreshKey(connector, link);- if (inFlightLinkRefreshes.get(key) === refresh) inFlightLinkRefreshes.delete(key);- options.onTimeout?.();- resolve(link);- }, RUN_TOKEN_REFRESH_TIMEOUT_MS);- });- try {- return await Promise.race([refresh, timeout]);- } finally {- clearTimeout(timer);- }- },+ (link) =>+ connector.isEnabled && link.credentials.expiresAt+ ? waitForRunRefresh(+ link,+ (waitUntil) => ensureFreshLinkToken(connector, link, model, waitUntil),+ options.onTimeout,+ )+ : link,{ concurrency: RUN_TOKEN_REFRESH_CONCURRENCY },);diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 82b25bbef78..af886b02e47 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -13,6 +13,7 @@ import {getConnectorToolPermission,} from '@/libs/mcp/connectorPermissionCheck';import { isMCPSSRFBlockedError } from '@/libs/mcp/ssrf';+import { createMCPError } from '@/libs/mcp/types';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { resolveLinkedCall } from '@/server/services/connector/links';import { buildConnectorMcpParams } from '@/server/services/connector/sync';@@ -339,6 +340,12 @@ export class ToolExecutionService {}try {+ if (+ (manifest as { connectorReauthorizationRequired?: boolean })+ .connectorReauthorizationRequired+ ) {+ throw createMCPError('AUTHORIZATION_ERROR', 'Reconnect this connector to continue.');+ }const marker = (manifest as { connectorLinks?: { connectorId: string; param: string } }).connectorLinks;if (marker) {diff --git a/apps/server/src/services/widget/credentials.ts b/apps/server/src/services/widget/credentials.tsindex f283677f9b4..5429aa45ddc 100644--- a/apps/server/src/services/widget/credentials.ts+++ b/apps/server/src/services/widget/credentials.ts@@ -1,4 +1,4 @@-import type { WidgetEnvRequirement } from '@lobechat/types';+import { needsConnectorReauthorization, type WidgetEnvRequirement } from '@lobechat/types';import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';import type { DecryptedConnectorLink } from '@/database/models/connectorLink';@@ -327,13 +327,14 @@ export const resolveWidgetEnv = async (if (connector) {const link = accountOf.get(connector.id);connector = link- ? withLinkCredentials(- connector,- await ensureFreshLinkToken(connector, link, model.getLinkModel(), model),- )+ ? withLinkCredentials(connector, await ensureFreshLinkToken(connector, link, model)): await ensureFreshConnectorToken(connector, model);}- const selection = selectConnectorSecret(connector?.credentials ?? null, requirement.field);+ const credentials = connector?.credentials ?? null;+ const selection = selectConnectorSecret(+ needsConnectorReauthorization(credentials) ? null : credentials,+ requirement.field,+ );if ('error' in selection) {// A manifest that does not pick one header is wrong whether or not the// variable is optional: report it rather than silently dropping it.diff --git a/locales/en-US/integration.json b/locales/en-US/integration.jsonindex a06931aca4b..7ba9e549747 100644--- a/locales/en-US/integration.json+++ b/locales/en-US/integration.json@@ -177,8 +177,8 @@"mcpEvent.eventCount_other": "{{count}} events","mcpEvent.hideData": "Hide data","mcpEvent.notice.subscription_terminated": "Subscription ended",- "mcpEvent.noticeReason.access_revoked": "The connector revoked access","mcpEvent.noticeReason.event_unavailable": "The connector no longer offers this event",+ "mcpEvent.noticeReason.reconnectToResubscribe": "The connector revoked access. Reconnect it, then ask the agent to subscribe again.","mcpEvent.noticeReason.unknown": "The connector ended the subscription","mcpEvent.omitted": "{{count}} not listed","mcpEvent.senderCaption": "Event subscription",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 2213ba4e458..95642cf1ab2 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -300,7 +300,6 @@"automations.descWorkspace": "Connector events the agents in this workspace subscribed to. Each event runs the agent and uses credits. If events stop arriving, Check confirms the subscription with the connector and resumes paused delivery. Only the member who set one up or a workspace admin can check or delete it.","automations.empty.desc": "Ask an agent to keep an eye on a connector for you, like \"Tell me when CI fails on this PR\". Subscriptions you approve show up here.","automations.empty.title": "No automations yet",- "automations.error.access_revoked": "Access was revoked; the subscription ended. Delete it and ask the agent to resubscribe.","automations.error.auth": "The connector's authorization has expired.","automations.error.challenge_failed": "The connector could not verify LobeHub's callback address.","automations.error.channel_unavailable": "Couldn't post the last result to the Channel: the Agent or its creator is no longer a member, or the Channel was archived.",@@ -310,6 +309,7 @@"automations.error.http_4xx": "LobeHub rejected the connector's deliveries.","automations.error.http_5xx": "LobeHub failed while receiving the connector's deliveries.","automations.error.insufficient_budget": "Not enough credits to run the agent. Later events run once you top up.",+ "automations.error.reconnectToResubscribe": "Access was revoked and the subscription ended. Reconnect the connector, then delete this subscription and ask the agent to subscribe again.","automations.error.server_unreachable": "Could not reach the connector's server.","automations.error.terminated": "The connector ended this subscription.","automations.error.timeout": "The connector timed out delivering events to LobeHub.",diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.jsonindex 2b851e10f08..23113d88165 100644--- a/locales/zh-CN/integration.json+++ b/locales/zh-CN/integration.json@@ -177,8 +177,8 @@"mcpEvent.eventCount_other": "{{count}} 个事件","mcpEvent.hideData": "收起数据","mcpEvent.notice.subscription_terminated": "订阅已结束",- "mcpEvent.noticeReason.access_revoked": "连接器撤销了访问权限","mcpEvent.noticeReason.event_unavailable": "连接器已不再提供这个事件",+ "mcpEvent.noticeReason.reconnectToResubscribe": "连接器撤销了访问权限。请重新连接,再让助理重新订阅。","mcpEvent.noticeReason.unknown": "连接器结束了订阅","mcpEvent.omitted": "其中 {{count}} 个未列出","mcpEvent.senderCaption": "事件订阅",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex fe69535cb8c..1926d6ddfac 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -300,7 +300,6 @@"automations.descWorkspace": "这个工作区的助理订阅的连接器事件。每次事件都会运行一次助理并消耗额度。事件没有按时到达时,点「检查」向连接器确认订阅,被暂停的投递也会因此恢复。只有创建订阅的成员或工作区管理员可以检查或删除。","automations.empty.desc": "在对话中让助理替你留意连接器里的动静,比如「这个 PR 的 CI 挂了告诉我」。你批准的订阅会显示在这里。","automations.empty.title": "还没有自动化",- "automations.error.access_revoked": "连接器撤销了访问权限,订阅已结束。删除后可以让助理重新订阅。","automations.error.auth": "连接器的授权已失效。","automations.error.challenge_failed": "连接器未能验证 LobeHub 的回调地址。","automations.error.channel_unavailable": "上一次的结果没能发到频道:助理或创建人已不在频道中,或频道已归档。",@@ -310,6 +309,7 @@"automations.error.http_4xx": "LobeHub 拒绝了连接器的投递。","automations.error.http_5xx": "LobeHub 接收连接器的投递时出错。","automations.error.insufficient_budget": "额度不足,助理没有运行。充值后,之后的事件会正常运行。",+ "automations.error.reconnectToResubscribe": "访问权限已撤销,订阅已结束。请重新连接连接器,然后删除此订阅,并让助理重新订阅。","automations.error.server_unreachable": "无法连接到连接器的服务器。","automations.error.terminated": "连接器结束了这个订阅。","automations.error.timeout": "连接器向 LobeHub 投递事件超时。",diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.tsindex 3c08baf1f85..5f42585fdca 100644--- a/packages/database/src/models/connector.ts+++ b/packages/database/src/models/connector.ts@@ -141,6 +141,29 @@ export class ConnectorModel {getLinkModel = () =>new ConnectorLinkModel(this.db, this.userId, this.workspaceId, this.gateKeeper);+ /** Serialize refresh state changes with account writes, reauthorization and deletion. */+ withOAuthRefreshLock = <T>(+ connector: Pick<DecryptedConnector, 'id' | 'workspaceId'>,+ action: (row: DecryptedConnector, model: ConnectorModel) => Promise<T>,+ ): Promise<T | undefined> =>+ this.db.transaction(async (tx) => {+ // A workspace run can resolve an owner's personal connector. Keep its+ // refresh writes in personal scope, still constrained to the same owner.+ const model = new ConnectorModel(+ tx,+ this.userId,+ connector.workspaceId === null ? undefined : this.workspaceId,+ this.gateKeeper,+ );+ model.evaluationDatasetId = this.evaluationDatasetId;+ const [row] = await tx+ .select()+ .from(userConnectors)+ .where(and(eq(userConnectors.id, connector.id), model.ownership()))+ .for('update');+ if (row) return action(await decryptRow(row, this.gateKeeper), model);+ });+private ownership = () =>connectorAccessScope(this.db,diff --git a/packages/database/src/models/connectorLink.ts b/packages/database/src/models/connectorLink.tsindex cbdaf22e59f..3e254b98df2 100644--- a/packages/database/src/models/connectorLink.ts+++ b/packages/database/src/models/connectorLink.ts@@ -355,6 +355,7 @@ export class ConnectorLinkModel {connectorId: string,linkId: string,credentials: OAuthCredentials,+ status: ConnectorLinkStatus = 'connected',): Promise<void> => {await this.mutate(connectorId, (records) => ({records: records.some((r) => r.id === linkId)@@ -363,7 +364,7 @@ export class ConnectorLinkModel {? {...r,credentials: toStoredCredentials(credentials),- status: 'connected' as const,+ status,}: r,)diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.tsindex 9a329e99ba4..89641c8d1bc 100644--- a/packages/locales/src/default/integration.ts+++ b/packages/locales/src/default/integration.ts@@ -236,7 +236,8 @@ export default {'mcpEvent.truncated': 'Possible gap','mcpEvent.truncatedDesc': 'Some events before these may not have arrived.','mcpEvent.notice.subscription_terminated': 'Subscription ended',- 'mcpEvent.noticeReason.access_revoked': 'The connector revoked access',+ 'mcpEvent.noticeReason.reconnectToResubscribe':+ 'The connector revoked access. Reconnect it, then ask the agent to subscribe again.','mcpEvent.noticeReason.event_unavailable': 'The connector no longer offers this event','mcpEvent.noticeReason.unknown': 'The connector ended the subscription','mcpEvent.senderCaption': 'Event subscription',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex b1868a9142c..fa388a8e5c4 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -5310,8 +5310,8 @@ When I am ___, I need ___'Events arrived too often, so some runs in the last 10 minutes were skipped.','automations.error.insufficient_budget':'Not enough credits to run the agent. Later events run once you top up.',- 'automations.error.access_revoked':- 'Access was revoked; the subscription ended. Delete it and ask the agent to resubscribe.',+ 'automations.error.reconnectToResubscribe':+ 'Access was revoked and the subscription ended. Reconnect the connector, then delete this subscription and ask the agent to subscribe again.','automations.error.event_unavailable':'The connector no longer offers this event, so the subscription ended.','automations.error.server_unreachable': "Could not reach the connector's server.",diff --git a/packages/types/src/connector.ts b/packages/types/src/connector.tsindex 24dc46edfde..0c5318af374 100644--- a/packages/types/src/connector.ts+++ b/packages/types/src/connector.ts@@ -61,6 +61,11 @@ export type ConnectorCredentials =type: 'oauth2';accessToken: string;refreshToken?: string;+ /** Persisted before submitting a refresh. An abandoned attempt requires reauthorization. */+ refreshState?:+ | { id: string; status: 'complete' }+ | { deadline: number; id: string; status: 'pending' }+ | { status: 'reconnect_required' };clientSecret?: string;/** DCR — token for managing the dynamic registration */registrationAccessToken?: string;@@ -74,6 +79,9 @@ export type ConnectorCredentials =export type ConnectorOAuthCredentials = Extract<ConnectorCredentials, { type: 'oauth2' }>;+export const needsConnectorReauthorization = (credentials: ConnectorCredentials | null) =>+ credentials?.type === 'oauth2' && credentials.refreshState?.status === 'reconnect_required';+/** One OAuth account connected to a connector, stored in {@link ConnectorOAuthAccounts}. */export interface ConnectorLinkRecord {/** Epoch ms; accounts are listed in this order. */diff --git a/src/features/Automations/status.test.ts b/src/features/Automations/status.test.tsindex e6830da2906..ce05d480f80 100644--- a/src/features/Automations/status.test.ts+++ b/src/features/Automations/status.test.ts@@ -76,7 +76,7 @@ describe('resolveAutomationStatus', () => {).toMatchObject({kind: 'terminated',labelKey: 'automations.status.terminated',- reasonKey: 'automations.error.access_revoked',+ reasonKey: 'automations.error.reconnectToResubscribe',remedy: 'resubscribe',tone: 'default',});@@ -100,8 +100,7 @@ describe('automationErrorKey', () => {const keys = INBOUND_WEBHOOK_ERRORS.map((error) => automationErrorKey(error));expect(new Set(keys).size).toBe(INBOUND_WEBHOOK_ERRORS.length);- for (const error of INBOUND_WEBHOOK_ERRORS)- expect(automationErrorKey(error)).toBe(`automations.error.${error}`);+ for (const key of keys) expect(key).toMatch(/^automations\.error\./);});it('falls back to unknown for a value the client does not know yet', () => {diff --git a/src/features/Automations/status.ts b/src/features/Automations/status.tsindex d19e8aeee16..5611775effd 100644--- a/src/features/Automations/status.ts+++ b/src/features/Automations/status.ts@@ -32,7 +32,9 @@ export interface AutomationStatus {/** One readable reason per `last_error` value (契约 3.1); `unknown` covers anything unmapped. */export const automationErrorKey = (error: InboundWebhookError | string) =>- `automations.error.${ERROR_KEYS.has(error as InboundWebhookError) ? error : 'unknown'}`;+ error === 'access_revoked'+ ? 'automations.error.reconnectToResubscribe'+ : `automations.error.${ERROR_KEYS.has(error as InboundWebhookError) ? error : 'unknown'}`;const ERROR_KEYS = new Set<InboundWebhookError>(['access_revoked',diff --git a/src/features/Conversation/Markdown/plugins/McpEvent/Render.tsx b/src/features/Conversation/Markdown/plugins/McpEvent/Render.tsxindex ac049bf1c48..bf14aff2d9f 100644--- a/src/features/Conversation/Markdown/plugins/McpEvent/Render.tsx+++ b/src/features/Conversation/Markdown/plugins/McpEvent/Render.tsx@@ -240,9 +240,11 @@ const Render = memo<MarkdownElementProps<McpEventAttributes>>(({ children, node</EventPill>{card.notice.namesEvent && eventPill}<Text type={'secondary'}>- {t(`mcpEvent.noticeReason.${card.notice.reason}` as any, {- defaultValue: t('mcpEvent.noticeReason.unknown'),- })}+ {card.notice.reason === 'access_revoked'+ ? t('mcpEvent.noticeReason.reconnectToResubscribe')+ : t(`mcpEvent.noticeReason.${card.notice.reason}` as any, {+ defaultValue: t('mcpEvent.noticeReason.unknown'),+ })}</Text></Flexbox>)}diff --git a/src/libs/mcp/__tests__/fixtures/oauthMcpServer.ts b/src/libs/mcp/__tests__/fixtures/oauthMcpServer.tsindex 3ef770fae37..1ce9488d51c 100644--- a/src/libs/mcp/__tests__/fixtures/oauthMcpServer.ts+++ b/src/libs/mcp/__tests__/fixtures/oauthMcpServer.ts@@ -6,7 +6,7 @@ export type OAuthMcpVariant = 'idtoken' | 'userinfo' | 'none';export const startOAuthMcpServer = async (variant: OAuthMcpVariant = 'idtoken',port = 0,- options: { collidingTool?: boolean } = {},+ options: { beforeRefreshResponse?: () => Promise<void>; collidingTool?: boolean } = {},) => {const requests: {authorization: string | null;@@ -77,7 +77,10 @@ export const startOAuthMcpServer = async (if (url.pathname === '/token') {const form = new URLSearchParams(raw);const refresh = form.get('refresh_token');- if (refresh) refreshes.push(refresh);+ if (refresh) {+ refreshes.push(refresh);+ await options.beforeRefreshResponse?.();+ }const account = (refresh ?? form.get('code') ?? 'alice').replace(/^refresh-/, '').split('-')[0];diff --git a/src/libs/mcp/buildConnectorManifests.test.ts b/src/libs/mcp/buildConnectorManifests.test.tsindex 749fb372c40..e99b47e1c47 100644--- a/src/libs/mcp/buildConnectorManifests.test.ts+++ b/src/libs/mcp/buildConnectorManifests.test.ts@@ -41,6 +41,22 @@ const mcpParamsOf = (connector: DecryptedConnector) => {};describe('buildConnectorManifests mcpParams headers', () => {+ it('keeps the tool available for a reconnect error without baking in the old access token', () => {+ const connector = httpConnector({+ accessToken: 'expired',+ refreshState: { status: 'reconnect_required' },+ type: 'oauth2',+ });++ const [manifest] = buildConnectorManifests([connector], [tool()]);++ expect(manifest).toMatchObject({+ api: [expect.objectContaining({ name: 'doThing' })],+ connectorReauthorizationRequired: true,+ mcpParams: { auth: undefined },+ });+ });+it('merges metadata.customHeaders alongside bearer auth', () => {const params = mcpParamsOf(httpConnector({ token: 'tok', type: 'bearer' }, { customHeaders: { 'X-Tenant': 't1' } }),diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.tsindex b85297a0a96..af2d112b308 100644--- a/src/libs/mcp/buildConnectorManifests.ts+++ b/src/libs/mcp/buildConnectorManifests.ts@@ -1,5 +1,5 @@import { buildConnectorManifest, resolveConnectorLinkParam } from '@lobechat/mecha';-import type { ToolManifest } from '@lobechat/types';+import { needsConnectorReauthorization, type ToolManifest } from '@lobechat/types';import { connectorConnectVia, connectorDeviceBinding } from '@lobechat/utils/mcpEndpoint';import type { DecryptedConnector } from '@/database/models/connector';@@ -45,12 +45,16 @@ export function buildConnectorManifests();if (!manifest) continue;+ const reauthorizationRequired = needsConnectorReauthorization(connector.credentials);manifests.push({...(manifest as ToolManifest),// @ts-ignore — mcpParams is a runtime-only field not in the public typemcpParams: buildMcpParams(- (connector.links?.length ?? 0) > 1 ? { ...connector, credentials: null } : connector,+ reauthorizationRequired || (connector.links?.length ?? 0) > 1+ ? { ...connector, credentials: null }+ : connector,),+ ...(reauthorizationRequired && { connectorReauthorizationRequired: true }),...((connector.links?.length ?? 0) > 1? {connectorLinks: {