Skip to content

🀯 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.

πŸ› fix: tell share visitors an expired connector is the creator's to fix (#21292)

YuTengjing6fac9f45f53e
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
new file mode 100644
index 00000000000..5d679c997e3
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { refreshExpiredConnectorTokens } from '@/server/services/connector/tokens';
+
+import { discoverTools } from '../toolDiscovery';
+
+vi.mock('@/business/client/model-bank/loadModels', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('@/database/models/aiModel', () => ({
+ AiModelModel: class {
+ findByIdAndProvider = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+vi.mock('@/database/models/aiProvider', () => ({
+ AiProviderModel: class {
+ findById = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+// The background stale-tool refresh reaches for the request-scoped `after()`,
+// which does not exist in a bare unit-test runtime.
+vi.mock('@/server/services/connector/refresh', () => ({
+ buildLastSyncedAtMap: vi.fn().mockReturnValue(new Map()),
+ scheduleStaleConnectorToolsRefresh: vi.fn(),
+}));
+// The gatekeeper encrypts rotated credentials; without one discovery skips
+// the refresh, so stand one in for the bare test runtime.
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({}) },
+}));
+vi.mock('@/server/services/connector/tokens', () => ({
+ refreshExpiredConnectorTokens: vi.fn(async (connectors: any[]) =>
+ connectors.map((c) => ({ ...c, credentials: { accessToken: 'fresh', type: 'oauth2' } })),
+ ),
+}));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },
+}));
+
+const XMIND = 'xmind-mcp';
+
+const oauthConnector = {
+ credentials: { accessToken: 'expired', type: 'oauth2' },
+ id: 'conn-xmind',
+ identifier: XMIND,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://app.xmind.com/api/mcp',
+ metadata: {},
+ name: 'XMind',
+};
+
+const connectorTools = [
+ {
+ description: 'Who am I',
+ inputSchema: { properties: {}, type: 'object' },
+ permission: 'auto',
+ toolName: 'xmind_whoami',
+ userConnectorId: oauthConnector.id,
+ },
+];
+
+const run = (plugins: string[]) =>
+ discoverTools(
+ {
+ agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
+ composioService: { getComposioManifests: vi.fn().mockResolvedValue([]) },
+ connectorModel: {
+ resolveAll: vi.fn().mockResolvedValue([oauthConnector]),
+ resolveByIdentifiers: vi.fn(async (ids: string[]) =>
+ ids.includes(XMIND) ? [oauthConnector] : [],
+ ),
+ },
+ connectorToolModel: {
+ queryAllByConnectorIds: vi.fn().mockResolvedValue(connectorTools),
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ },
+ db: {} as never,
+ getMarketService: vi.fn().mockResolvedValue({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ }),
+ messageModel: { update: vi.fn() },
+ pluginModel: { query: vi.fn().mockResolvedValue([]) },
+ userId: 'creator-1',
+ } as never,
+ {
+ agentConfig: { chatConfig: {}, plugins },
+ appContext: undefined,
+ canUseDevice: false,
+ model: 'test-model',
+ prompt: 'make a mind map',
+ provider: 'test-provider',
+ resolvedAgentId: 'agent-1',
+ runFacts: {
+ deviceSystemInfo: vi.fn().mockResolvedValue(undefined),
+ userPreference: vi.fn().mockResolvedValue(undefined),
+ },
+ } as never,
+ {
+ disabledPluginIds: [],
+ globalMemoryEnabled: false,
+ hasMentionedAgents: false,
+ isFixedDeviceTarget: false,
+ loadHistoryMessages: vi.fn().mockResolvedValue([]),
+ throwIfExecutionAborted: vi.fn(),
+ } as never,
+ );
+
+const manifestToken = (manifest: unknown) =>
+ (manifest as { mcpParams?: { auth?: { accessToken?: string } } })?.mcpParams?.auth?.accessToken;
+
+// LOBE-14771: manifests carry the connector token for the whole run, so an
+// expired-but-refreshable token used to 401 on the first call after expiry.
+describe('discoverTools β€” connector OAuth token refresh', () => {
+ it('builds a pinned connector manifest from refreshed credentials', async () => {
+ const result = await run([XMIND]);
+
+ expect(refreshExpiredConnectorTokens).toHaveBeenCalled();
+ expect(manifestToken(result.toolManifestMap[XMIND])).toBe('fresh');
+ });
+
+ it('builds an unpinned connector manifest from refreshed credentials', async () => {
+ const result = await run([]);
+
+ expect(manifestToken(result.toolManifestMap[XMIND])).toBe('fresh');
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
index 165f7d09659..37963d6eff9 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
@@ -5,12 +5,13 @@ import type { FrozenCredentialFacts } from '@lobechat/types';
import { agentShareFileAccessScope, ordinaryFileAccessScope } from '@lobechat/types';
import debug from 'debug';
-import type { DecryptedConnector } from '@/database/models/connector';
+import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import type { UserConnectorToolItem } from '@/database/schemas';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { refreshExpiredConnectorTokens } from '@/server/services/connector/tokens';
import { deviceGateway } from '@/server/services/deviceGateway';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
@@ -92,6 +93,25 @@ export const readCredentialFacts = async (
}
};
+/**
+ * Manifests carry each connector's access token for the whole run, so refresh
+ * expired OAuth tokens first. Rotated credentials are persisted encrypted,
+ * which needs the gatekeeper; without one, keep the stored tokens.
+ */
+const refreshConnectorTokens = async (
+ deps: ToolDiscoveryDeps,
+ gateKeeper: KeyVaultsGateKeeper | undefined,
+ connectors: DecryptedConnector[],
+ onTimeout: () => void,
+): Promise<DecryptedConnector[]> => {
+ if (!gateKeeper || connectors.length === 0) return connectors;
+ return refreshExpiredConnectorTokens(
+ connectors,
+ new ConnectorModel(deps.db, deps.userId, deps.workspaceId, gateKeeper),
+ { onTimeout },
+ );
+};
+
/**
* Connector resolution: the gatekeeper decrypts the stored OAuth tokens, or
* `buildConnectorManifests` gets no auth and every tool call 401s.
@@ -105,7 +125,11 @@ const readConnectors = async (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) =>
log('execAgent: failed to init gatekeeper for connector credentials: %O', err);
}
- return traceDiscoveryStage('connectors', async () => {
+ return traceDiscoveryStage('connectors', async (span) => {
+ let refreshTimeouts = 0;
+ const onRefreshTimeout = () => {
+ refreshTimeouts += 1;
+ };
const connectors =
candidateIds.length > 0
? await deps.connectorModel.resolveByIdentifiers(
@@ -119,8 +143,11 @@ const readConnectors = async (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) =>
// manifest. Connectors WITHOUT an endpoint (e.g. Lobehub/Composio OAuth skills synced via
// syncToolsFromClient) must continue using their original plugin executor path β€” otherwise
// after humanIntervention approval the runtime tries to call mcpServerUrl='' and returns empty.
- const connectorsMcp = connectors.filter(
- (c) => c.mcpServerUrl || c.mcpConnectionType === 'stdio',
+ const connectorsMcp = await refreshConnectorTokens(
+ deps,
+ connectorGateKeeper,
+ connectors.filter((c) => c.mcpServerUrl || c.mcpConnectionType === 'stdio'),
+ onRefreshTimeout,
);
// Fetch ALL tools for all real-MCP connectors (including disabled tools) so that
@@ -131,7 +158,13 @@ const readConnectors = async (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) =>
? await deps.connectorToolModel.queryAllByConnectorIds(connectorsMcp.map((c) => c.id))
: [];
- const discoverable = await readDiscoverableConnectors(deps, ctx, connectorGateKeeper);
+ const discoverable = await readDiscoverableConnectors(
+ deps,
+ ctx,
+ connectorGateKeeper,
+ onRefreshTimeout,
+ );
+ markDegradedStage(span, refreshTimeouts, 'connector token refreshes');
return {
connectorGateKeeper,
@@ -161,6 +194,7 @@ const readDiscoverableConnectors = async (
deps: ToolDiscoveryDeps,
ctx: ToolReadsContext,
gateKeeper: KeyVaultsGateKeeper | undefined,
+ onRefreshTimeout: () => void,
): Promise<{
connectorsMcp: DecryptedConnector[];
manifests: LobeToolManifest[];
@@ -192,9 +226,15 @@ const readDiscoverableConnectors = async (
const tools = await deps.connectorToolModel.queryAllByConnectorIds(
connectorsMcp.map((c) => c.id),
);
- return {
+ const refreshed = await refreshConnectorTokens(
+ deps,
+ gateKeeper,
connectorsMcp,
- manifests: buildConnectorManifests(connectorsMcp, tools) as LobeToolManifest[],
+ onRefreshTimeout,
+ );
+ return {
+ connectorsMcp: refreshed,
+ manifests: buildConnectorManifests(refreshed, tools) as LobeToolManifest[],
tools,
};
} catch (error) {
diff --git a/apps/server/src/services/connector/tokens.test.ts b/apps/server/src/services/connector/tokens.test.ts
new file mode 100644
index 00000000000..433000b4469
--- /dev/null
+++ b/apps/server/src/services/connector/tokens.test.ts
@@ -0,0 +1,191 @@
+import { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as OauthModule from './oauth';
+import { refreshConnectorToken } from './oauth';
+import { refreshExpiredConnectorTokens } from './tokens';
+
+vi.mock('@modelcontextprotocol/sdk/client/auth.js', () => ({
+ discoverAuthorizationServerMetadata: vi.fn(),
+}));
+vi.mock('./oauth', async (importOriginal) => ({
+ ...(await importOriginal<typeof OauthModule>()),
+ refreshConnectorToken: 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,
+ 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();
+ });
+
+ // LOBE-14771: 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) }),
+ );
+ });
+
+ it('leaves a valid token alone without contacting the authorization server', async () => {
+ const valid = oauthConnector('valid', NOW + 3_600_000);
+
+ const result = await refreshExpiredConnectorTokens([valid], { update: vi.fn() } as any);
+
+ expect(result).toEqual([valid]);
+ expect(discoverAuthorizationServerMetadata).not.toHaveBeenCalled();
+ });
+
+ it('skips disabled connectors, which never reach the manifests', async () => {
+ const disabled = { ...oauthConnector('disabled', NOW - 1000), isEnabled: false };
+
+ const result = await refreshExpiredConnectorTokens([disabled], { update: vi.fn() } as any);
+
+ expect(result).toEqual([disabled]);
+ expect(discoverAuthorizationServerMetadata).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('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,
+ });
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(await pending).toEqual([expired]);
+ expect(onTimeout).toHaveBeenCalledTimes(1);
+ });
+
+ 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);
+
+ expect(refreshConnectorToken).toHaveBeenCalledTimes(2);
+ expect(connector.credentials).toMatchObject({ accessToken: 'recovered' });
+ });
+
+ 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);
+
+ expect(await pending).toEqual([expired]);
+ });
+
+ 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),
+ ]);
+
+ 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' },
+ };
+
+ const [connector] = await refreshExpiredConnectorTokens([expired], {
+ findById: vi.fn().mockResolvedValue(rotated),
+ update: vi.fn(),
+ } as any);
+
+ expect(connector.credentials).toMatchObject({ accessToken: 'winner' });
+ });
+
+ 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' });
+ });
+});
diff --git a/apps/server/src/services/connector/tokens.ts b/apps/server/src/services/connector/tokens.ts
index 0e39aee7433..87cd8a1ef9e 100644
--- a/apps/server/src/services/connector/tokens.ts
+++ b/apps/server/src/services/connector/tokens.ts
@@ -1,6 +1,7 @@
import { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
import debug from 'debug';
+import pMap from 'p-map';
import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';
import type { ConnectorCredentials } from '@/database/schemas';
@@ -32,6 +33,16 @@ 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 hasKnownExpiry = (connector: DecryptedConnector): boolean =>
+ connector.credentials?.type === 'oauth2' && !!connector.credentials.expiresAt;
+
/**
* 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
@@ -45,8 +56,9 @@ export const ensureFreshConnectorToken = async (
const creds = connector.credentials;
const oidc = connector.oidcConfig;
- if (!creds || creds.type !== 'oauth2' || !creds.refreshToken) return connector;
- if (creds.expiresAt && creds.expiresAt - EXPIRY_SKEW_MS > Date.now()) return connector;
+ if (!creds || creds.type !== 'oauth2' || !creds.refreshToken || !isRefreshDue(connector)) {
+ return connector;
+ }
if (!oidc?.issuer || !oidc.clientId) return connector;
try {
@@ -75,6 +87,135 @@ export const ensureFreshConnectorToken = async (
return { ...connector, credentials };
} catch {
log('token refresh failed for connector=%s', connector.id);
+ 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;
+
+const readRotatedCredentials = 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 };
+ }
+};
+
+/**
+ * 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 (
+ connector: DecryptedConnector,
+ connectorModel: ConnectorModel,
+): 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;
}
};
+
+/**
+ * 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 = (
+ connector: DecryptedConnector,
+ connectorModel: ConnectorModel,
+): Promise<DecryptedConnector> => {
+ const pending = inFlightRefreshes.get(connector.id);
+ if (pending) return pending;
+
+ const refresh = ensureFreshConnectorToken(connector, connectorModel).finally(() => {
+ if (inFlightRefreshes.get(connector.id) === refresh) inFlightRefreshes.delete(connector.id);
+ });
+ inFlightRefreshes.set(connector.id, refresh);
+ return refresh;
+};
+
+/**
+ * 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 (LOBE-14771).
+ *
+ * `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,
+ 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);
+ }
+ },
+ { concurrency: RUN_TOKEN_REFRESH_CONCURRENCY },
+ );
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index c8c00e5a8b5..285932b1b5d 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -1,6 +1,8 @@
// @vitest-environment node
import { executeToolWithRetry } from '@lobechat/agent-runtime';
import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';
+import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { deviceGateway } from '@/server/services/deviceGateway';
@@ -845,4 +847,76 @@ describe('ToolExecutionService', () => {
expect(callTool).not.toHaveBeenCalled();
});
});
+
+ // LOBE-14771: the SDK puts the 401 status only in `.code` and MCPService
+ // wraps it in a TRPCError, so the model used to see a bare "Invalid or
+ // expired token" and told Share visitors to reauthorize a connection that
+ // belongs to the creator.
+ describe('MCP authorization failures', () => {
+ const mcpPayload = {
+ apiName: 'xmind_whoami',
+ arguments: '{}',
+ id: 'tool-call-auth',
+ identifier: 'xmind-mcp',
+ type: 'mcp',
+ } as any;
+
+ const unauthorized = () =>
+ new TRPCError({
+ cause: new StreamableHTTPError(
+ 401,
+ 'Error POSTing to endpoint: {"error":"Unauthorized: Invalid or expired token"}',
+ ),
+ code: 'INTERNAL_SERVER_ERROR',
+ message:
+ 'Streamable HTTP error: Error POSTing to endpoint: {"error":"Unauthorized: Invalid or expired token"}',
+ });
+
+ const run = (over: Record<string, unknown> = {}, error: unknown = unauthorized()) => {
+ const service = new ToolExecutionService({
+ builtinToolsExecutor: { execute: vi.fn() } as any,
+ mcpService: { callTool: vi.fn().mockRejectedValue(error) } as any,
+ });
+ return service.executeTool(mcpPayload, {
+ toolManifestMap: {
+ 'xmind-mcp': {
+ mcpParams: { name: 'xmind-mcp', type: 'http', url: 'https://app.xmind.com/api/mcp' },
+ },
+ },
+ userId: 'creator-1',
+ ...over,
+ } as any);
+ };
+
+ it('tells the model a Share visitor cannot repair the creator connection', async () => {
+ const result = await run({ agentShareVisitor: { shareId: 'share-1' } });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain("set up on this agent creator's side");
+ expect(result.content).toContain('do not ask them to sign in, authorize, or reconnect');
+ expect(result.error).toMatchObject({ code: 'UNAUTHORIZED', kind: 'stop' });
+ });
+
+ it('asks the owner to reconnect outside Share', async () => {
+ const result = await run();
+
+ expect(result.content).toContain('reconnect');
+ expect(result.content).not.toContain("agent's creator");
+ expect(result.error).toMatchObject({ code: 'UNAUTHORIZED', kind: 'stop' });
+ });
+
+ it('keeps other MCP failures as raw replannable errors', async () => {
+ const result = await run(
+ { agentShareVisitor: { shareId: 'share-1' } },
+ new TRPCError({
+ cause: new StreamableHTTPError(500, 'boom'),
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Streamable HTTP error: boom',
+ }),
+ );
+
+ expect(result.content).toBe('Streamable HTTP error: boom');
+ expect(result.error).toMatchObject({ code: 'MCP_EXECUTION_ERROR', kind: 'replan' });
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index 0e56cce5513..449b6dbbc75 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -25,6 +25,7 @@ import { DiscoverService } from '../discover';
import { type MCPService } from '../mcp';
import { type BuiltinToolsExecutor } from './builtin';
import { classifyToolError, getToolAccessDeniedError } from './errorClassification';
+import { buildMcpAuthorizationErrorContent, isMcpAuthorizationError } from './mcpAuthError';
import { resolveRunWorkspaceId } from './serverRuntimes/resolveWorkspaceScope';
import { withoutDeviceReplay } from './serverRuntimes/withoutDeviceReplay';
import {
@@ -352,6 +353,16 @@ export class ToolExecutionService {
};
} catch (error) {
log('MCP tool execution failed for %s:%s: %O', identifier, apiName, error);
+ if (isMcpAuthorizationError(error)) {
+ const content = buildMcpAuthorizationErrorContent(identifier, {
+ isShareVisitor: !!context.agentShareVisitor,
+ });
+ return {
+ content,
+ error: { code: 'UNAUTHORIZED', message: (error as Error).message },
+ success: false,
+ };
+ }
return {
content: (error as Error).message,
error: {
diff --git a/apps/server/src/services/toolExecution/mcpAuthError.ts b/apps/server/src/services/toolExecution/mcpAuthError.ts
new file mode 100644
index 00000000000..656c4f3060e
--- /dev/null
+++ b/apps/server/src/services/toolExecution/mcpAuthError.ts
@@ -0,0 +1,43 @@
+import { toRecord } from '@lobechat/utils/object';
+
+/** Bounds the `cause` walk so a self-referencing error cannot loop forever. */
+const MAX_CAUSE_DEPTH = 5;
+
+/**
+ * Whether an MCP call failed because the server rejected its credentials.
+ *
+ * The SDK transports (`StreamableHTTPError`, `SseError`) carry the HTTP status
+ * only in `.code`; the message is the response body (e.g.
+ * `{"error":"Unauthorized: Invalid or expired token"}`) and usually omits
+ * "401". `MCPService` then wraps the transport error in a `TRPCError` whose
+ * `cause` holds it, so walk the chain instead of matching message text.
+ * `MCPClient.initialize` may also have already mapped it to an
+ * `AUTHORIZATION_ERROR`.
+ */
+export const isMcpAuthorizationError = (error: unknown): boolean => {
+ let current: unknown = error;
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && current; depth++) {
+ const record = toRecord(current);
+ if (!record) return false;
+ if (record.code === 401) return true;
+ if (toRecord(record.data)?.type === 'AUTHORIZATION_ERROR') return true;
+ current = record.cause;
+ }
+ return false;
+};
+
+/**
+ * Model-visible content for an MCP credential rejection. The raw transport
+ * error says nothing about who owns the connection, so models guessed and told
+ * Agent Share visitors to "reauthorize in the browser" β€” but a shared run
+ * executes with a connection from the creator's side (theirs, or one a
+ * workspace member authorized), which the visitor can neither see nor repair
+ * (LOBE-14771).
+ */
+export const buildMcpAuthorizationErrorContent = (
+ identifier: string,
+ options: { isShareVisitor: boolean },
+): string =>
+ options.isShareVisitor
+ ? `The '${identifier}' connection was set up on this agent creator's side (by the creator or a member of their workspace), and its authorization has expired or been revoked. The person in this shared conversation cannot reconnect it and has no sign-in or authorization option here. Tell them this tool is unavailable until the agent's creator (or whoever manages this connection for them) reconnects it. They cannot do it themselves, so do not ask them to sign in, authorize, or reconnect anything, and continue with what you can do without this tool.`
+ : `The '${identifier}' connection's authorization has expired or been revoked (HTTP 401). Ask the user to reconnect '${identifier}' in their tool or connector settings, then retry.`;