๐คฏ 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
โจ feat: auto-refresh connector MCP tool lists in the background (#17245)
LiJianb632c61e78f9
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex e931fe4d305..f118fdaf8f9 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -137,6 +137,10 @@ import {} from '@/server/services/agentSignal/featureGate';import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSignal';import { ComposioService } from '@/server/services/composio';+import {+ buildLastSyncedAtMap,+ scheduleStaleConnectorToolsRefresh,+} from '@/server/services/connector/refresh';import { deviceGateway } from '@/server/services/deviceGateway';import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';import { DocumentService } from '@/server/services/document';@@ -2531,6 +2535,28 @@ export class AiAgentService {connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);+ // Auto-refresh stale connector tool lists in the background so upstream MCP+ // tool changes propagate without the user manually re-syncing โ the freshness+ // the connectors migration lost from the old plugin system. Reuses the tools+ // just fetched as the last-sync marker (no extra query), HTTP-only, throttled,+ // and deferred via after() so it adds no latency to this run. Wrapped+ // defensively: it is a pure optimization and must never break the agent run.+ try {+ // The background sync decrypts stored OAuth/bearer credentials to auth+ // against the MCP server, so it needs a gatekeeper-backed model โ the+ // same `connectorGateKeeper` used above. `this.connectorModel` has none,+ // which would decrypt to null and make an authed connector 401 โ error.+ const refreshConnectorModel = connectorGateKeeper+ ? new ConnectorModel(this.db, this.userId, this.workspaceId, connectorGateKeeper)+ : this.connectorModel;+ scheduleStaleConnectorToolsRefresh(connectorsMcp, buildLastSyncedAtMap(connectorTools), {+ connectorModel: refreshConnectorModel,+ connectorToolModel: this.connectorToolModel,+ });+ } catch (err) {+ log('execAgent: failed to schedule connector tool refresh (ignored): %O', err);+ }+// Only connectors that ACTUALLY produced a manifest (enabled + with synced// tools) replace a same-named plugin. Deriving the set from connectorsMcp// instead would let a disabled / not-yet-synced connector evict the plugindiff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.tsindex 3a4d640d074..05b3e6c2728 100644--- a/apps/server/src/services/connector/exec.test.ts+++ b/apps/server/src/services/connector/exec.test.ts@@ -4,10 +4,17 @@ import { ConnectorToolPermission } from '@/database/schemas';import { mcpService } from '@/server/services/mcp';import { callConnectorToolById } from './exec';+import { scheduleStaleConnectorToolsRefresh } from './refresh';import { ensureFreshConnectorToken } from './tokens';vi.mock('@/server/services/mcp', () => ({ mcpService: { callTool: vi.fn() } }));vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) }));+// The background tool-list refresh is exercised in refresh.test.ts. Here we only+// verify the call site wires it up and stays isolated from it.+vi.mock('./refresh', () => ({+ buildLastSyncedAtMap: vi.fn(() => new Map()),+ scheduleStaleConnectorToolsRefresh: vi.fn(),+}));const connector = {credentials: { accessToken: 'tok', type: 'oauth2' },@@ -110,4 +117,38 @@ describe('callConnectorToolById', () => {}),);});++ it('schedules a background tool-list refresh for the connector', async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });+ const ctx = makeCtx([connector], [tool()]);++ await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);++ expect(scheduleStaleConnectorToolsRefresh).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ id: 'c1',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ }),+ ],+ expect.anything(),+ ctx,+ );+ });++ it('still returns the tool result when the background refresh scheduler throws', async () => {+ // The refresh is a pure optimization; a failure in it must never break the+ // tool call the user actually asked for.+ vi.mocked(scheduleStaleConnectorToolsRefresh).mockImplementationOnce(() => {+ throw new Error('scheduler exploded');+ });+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });+ const ctx = makeCtx([connector], [tool()]);++ const res = await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);++ expect(res).toEqual({ success: true });+ expect(mcpService.callTool).toHaveBeenCalledTimes(1);+ });});diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.tsindex fe5cd073a1b..56b45e55d4b 100644--- a/apps/server/src/services/connector/exec.ts+++ b/apps/server/src/services/connector/exec.ts@@ -1,6 +1,7 @@import { ConnectorToolPermission } from '@/database/schemas';import { mcpService } from '@/server/services/mcp';+import { buildLastSyncedAtMap, scheduleStaleConnectorToolsRefresh } from './refresh';import { buildConnectorMcpParams, type ConnectorToolSyncContext } from './sync';import { ensureFreshConnectorToken } from './tokens';@@ -57,6 +58,28 @@ export const callConnectorToolById = async ();}+ // Keep the tool list fresh through normal use: if it hasn't been synced in a+ // while, refresh it from the upstream MCP server in the background so the user+ // never has to open the connector page and click Refresh by hand. HTTP-only,+ // throttled, and deferred โ reuses the `tools` rows already loaded above.+ // Wrapped defensively: this is a pure optimization and must never break the+ // tool call, even if the scheduler itself throws.+ try {+ scheduleStaleConnectorToolsRefresh(+ [+ {+ id: connector.id,+ mcpConnectionType: connector.mcpConnectionType,+ mcpServerUrl: connector.mcpServerUrl,+ },+ ],+ buildLastSyncedAtMap(tools),+ ctx,+ );+ } catch {+ // Background tool-list refresh is best-effort โ never fail the tool call.+ }+const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);return mcpService.callTool({diff --git a/apps/server/src/services/connector/refresh.test.ts b/apps/server/src/services/connector/refresh.test.tsnew file mode 100644index 00000000000..2c817376f49--- /dev/null+++ b/apps/server/src/services/connector/refresh.test.ts@@ -0,0 +1,235 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { after } from '@/server/utils/scheduleAfterResponse';++import {+ buildLastSyncedAtMap,+ CONNECTOR_TOOLS_REFRESH_TTL_MS,+ scheduleStaleConnectorToolsRefresh,+} from './refresh';+import { syncConnectorToolsById } from './sync';++// Capture deferred work instead of running it, so each test controls exactly+// when (and whether) the background refresh executes.+const deferred: Array<() => Promise<unknown>> = [];+vi.mock('@/server/utils/scheduleAfterResponse', () => ({+ after: vi.fn((work: () => Promise<unknown>) => {+ deferred.push(work);+ }),+}));+vi.mock('./sync', () => ({ syncConnectorToolsById: vi.fn().mockResolvedValue({ toolCount: 3 }) }));++const ctx = {} as any;+const NOW = 1_000_000_000_000;++// Unique connector id per test keeps the module-level in-flight guard isolated+// across tests (a fresh id is never "in flight" from a previous test).+let seq = 0;+const nextId = () => `conn-${seq++}`;++const httpConnector = (id: string) => ({+ id,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+});++/** Run and await all currently-captured deferred works. */+const flushDeferred = async () => {+ const works = deferred.splice(0);+ for (const work of works) await work();+};++beforeEach(() => {+ vi.clearAllMocks();+ deferred.length = 0;+ vi.mocked(syncConnectorToolsById).mockResolvedValue({ toolCount: 3 });+});++describe('buildLastSyncedAtMap', () => {+ it('keeps the max updatedAt per connector', () => {+ const map = buildLastSyncedAtMap([+ { updatedAt: new Date(100), userConnectorId: 'a' },+ { updatedAt: new Date(300), userConnectorId: 'a' },+ { updatedAt: new Date(200), userConnectorId: 'b' },+ ]);+ expect(map.get('a')).toBe(300);+ expect(map.get('b')).toBe(200);+ });++ it('treats a missing/null updatedAt as 0', () => {+ const map = buildLastSyncedAtMap([{ updatedAt: null, userConnectorId: 'a' }]);+ expect(map.get('a')).toBe(0);+ });++ it('returns an empty map for no tools', () => {+ expect(buildLastSyncedAtMap([]).size).toBe(0);+ });+});++describe('scheduleStaleConnectorToolsRefresh โ eligibility', () => {+ it('schedules a refresh for an HTTP connector whose tools are stale', async () => {+ const id = nextId();+ const lastSynced = NOW - CONNECTOR_TOOLS_REFRESH_TTL_MS - 1;+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map([[id, lastSynced]]), ctx, NOW);++ expect(after).toHaveBeenCalledTimes(1);+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledWith(id, ctx);+ });++ it('schedules a refresh for a connector that has never synced (no map entry)', async () => {+ const id = nextId();+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);++ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledWith(id, ctx);+ });++ it('skips a connector synced within the TTL', async () => {+ const id = nextId();+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map([[id, NOW - 1000]]), ctx, NOW);++ expect(after).not.toHaveBeenCalled();+ await flushDeferred();+ expect(syncConnectorToolsById).not.toHaveBeenCalled();+ });++ it('skips stdio connectors (must run on the user machine, not the server)', async () => {+ const id = nextId();+ scheduleStaleConnectorToolsRefresh(+ [{ id, mcpConnectionType: 'stdio', mcpServerUrl: null }],+ new Map(),+ ctx,+ NOW,+ );+ await flushDeferred();+ expect(syncConnectorToolsById).not.toHaveBeenCalled();+ });++ it('skips connectors without an HTTP endpoint', async () => {+ const id = nextId();+ scheduleStaleConnectorToolsRefresh(+ [{ id, mcpConnectionType: 'http', mcpServerUrl: null }],+ new Map(),+ ctx,+ NOW,+ );+ await flushDeferred();+ expect(syncConnectorToolsById).not.toHaveBeenCalled();+ });++ it('throttles a second call for the same connector at the same instant', async () => {+ const id = nextId();+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ // Second call at the same `now` โ within TTL of the recorded attempt โ skipped.+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);++ expect(after).toHaveBeenCalledTimes(1);+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledTimes(1);+ });++ it('keeps throttling a connector whose upstream tool list is empty', async () => {+ // Empty upstream list โ no tool row records the sync โ DB marker stays 0.+ // The in-memory attempt marker must still honor the TTL so it does not+ // re-fire on every run.+ const id = nextId();+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ await flushDeferred();+ // Later, but still within the TTL, with an empty DB marker again โ skipped.+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW + 1000);+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledTimes(1);+ });+});++describe('scheduleStaleConnectorToolsRefresh โ remote result handling', () => {+ it('completes cleanly when the remote sync succeeds', async () => {+ const id = nextId();+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ await expect(flushDeferred()).resolves.toBeUndefined();+ expect(syncConnectorToolsById).toHaveBeenCalledTimes(1);+ });++ it('swallows a remote sync failure (never rejects, never surfaces)', async () => {+ const id = nextId();+ vi.mocked(syncConnectorToolsById).mockRejectedValueOnce(new Error('remote MCP down'));+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ // The deferred work must resolve, not reject, even though the sync failed.+ await expect(flushDeferred()).resolves.toBeUndefined();+ });++ it('re-syncs once the TTL has elapsed since the last attempt', async () => {+ const id = nextId();+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ await flushDeferred();+ // Past the TTL โ eligible again even though the DB marker never advanced.+ scheduleStaleConnectorToolsRefresh(+ [httpConnector(id)],+ new Map(),+ ctx,+ NOW + CONNECTOR_TOOLS_REFRESH_TTL_MS + 1,+ );+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledTimes(2);+ });++ it('backs off a failed connector for a TTL, then retries', async () => {+ const id = nextId();+ vi.mocked(syncConnectorToolsById).mockRejectedValueOnce(new Error('remote MCP down'));+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ await flushDeferred();++ // Within the TTL after a failure โ still backed off, not retried.+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW + 1000);+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledTimes(1);++ // After the TTL โ retried, and this time it succeeds.+ vi.mocked(syncConnectorToolsById).mockResolvedValueOnce({ toolCount: 5 });+ scheduleStaleConnectorToolsRefresh(+ [httpConnector(id)],+ new Map(),+ ctx,+ NOW + CONNECTOR_TOOLS_REFRESH_TTL_MS + 1,+ );+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledTimes(2);+ });+});++describe('scheduleStaleConnectorToolsRefresh โ never throws into the caller', () => {+ it('does not throw when the sync throws synchronously', async () => {+ const id = nextId();+ vi.mocked(syncConnectorToolsById).mockImplementationOnce(() => {+ throw new Error('sync exploded synchronously');+ });+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ await expect(flushDeferred()).resolves.toBeUndefined();+ });++ it('does not throw when after() itself throws, and frees the guard for retry', async () => {+ const id = nextId();+ vi.mocked(after).mockImplementationOnce(() => {+ throw new Error('scheduling failed');+ });+ expect(() =>+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW),+ ).not.toThrow();+ expect(syncConnectorToolsById).not.toHaveBeenCalled();++ // Guard was released despite the scheduling failure โ next call schedules.+ scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledTimes(1);+ });++ it('processes remaining connectors even if one entry is malformed', async () => {+ const goodId = nextId();+ // A null entry would throw on property access โ the per-item guard must+ // catch it and still schedule the healthy connector.+ scheduleStaleConnectorToolsRefresh([null as any, httpConnector(goodId)], new Map(), ctx, NOW);+ await flushDeferred();+ expect(syncConnectorToolsById).toHaveBeenCalledWith(goodId, ctx);+ });+});diff --git a/apps/server/src/services/connector/refresh.ts b/apps/server/src/services/connector/refresh.tsnew file mode 100644index 00000000000..1790506ca34--- /dev/null+++ b/apps/server/src/services/connector/refresh.ts@@ -0,0 +1,138 @@+import debug from 'debug';++import { ConnectorMcpConnectionType } from '@/database/schemas';+import { after } from '@/server/utils/scheduleAfterResponse';++import { type ConnectorToolSyncContext, syncConnectorToolsById } from './sync';++const log = debug('lobe-server:connector-refresh');++/**+ * Refresh a connector's synced tool list at most once per this window. Picked to+ * keep the list fresh through normal use without hammering the upstream MCP+ * server on every tool call / chat run.+ */+export const CONNECTOR_TOOLS_REFRESH_TTL_MS = 10 * 60 * 1000;++/**+ * `connectorId โ epoch ms of the last refresh we scheduled`, per instance.+ *+ * Combined with the DB tool timestamps as the throttle. It does three jobs the+ * DB marker alone can't:+ * - **Empty tool lists**: a connector whose upstream returns no tools writes no+ * tool row, so the DB marker never advances; without this it would re-fire on+ * every run. Recording the attempt here honors the TTL regardless.+ * - **Concurrency**: many tool calls in one turn resolve to the same `now`, so+ * the second sees a fresh attempt and is skipped โ no fan-out.+ * - **Failure backoff**: a failed sync leaves the attempt recorded, so a down+ * connector is retried at most once per TTL instead of every message.+ *+ * Best-effort only โ a fresh serverless instance starts empty and falls back to+ * the DB marker. Pruned opportunistically to stay bounded.+ */+const lastAttemptAt = new Map<string, number>();++/** Cap the attempt map by dropping entries older than the TTL (no longer throttling). */+const pruneAttempts = (now: number): void => {+ if (lastAttemptAt.size < 1000) return;+ for (const [id, ts] of lastAttemptAt) {+ if (now - ts > CONNECTOR_TOOLS_REFRESH_TTL_MS) lastAttemptAt.delete(id);+ }+};++export interface StaleRefreshConnector {+ id: string;+ mcpConnectionType: ConnectorMcpConnectionType | string | null;+ mcpServerUrl: string | null;+}++/**+ * Build the `connectorId โ last-sync epoch ms` map from already-fetched tool+ * rows, so callers reuse the rows they loaded anyway instead of issuing an extra+ * query. A tool's `updatedAt` is bumped on every `upsertMany` sync, so the max+ * across a connector's tools is a good proxy for "last synced". A connector with+ * no tools maps to nothing (treated as never synced โ eligible to refresh).+ */+export const buildLastSyncedAtMap = (+ tools: { updatedAt?: Date | null; userConnectorId: string }[],+): Map<string, number> => {+ const map = new Map<string, number>();+ for (const tool of tools) {+ const ts = tool.updatedAt ? tool.updatedAt.getTime() : 0;+ const prev = map.get(tool.userConnectorId) ?? 0;+ map.set(tool.userConnectorId, Math.max(prev, ts));+ }+ return map;+};++/**+ * Background-refresh stale connector tool lists โ the auto-update the connectors+ * migration dropped.+ *+ * The old plugin system silently re-fetched every plugin's manifest on each chat+ * load, so upstream MCP tool changes showed up without any user action. Connectors+ * only re-fetch on the manual Refresh button / OAuth callback, so a user's tool+ * list stays frozen at install time until they re-sync by hand (the "ๅฟ ้กปๆๅจ่ฟๆ่ฝ+ * ็ฎก็ๆดๆฐ" complaint). This reinstates that freshness at the tool-call / chat-run+ * boundary:+ *+ * - **HTTP connectors only** โ stdio servers must spawn on the user's own machine,+ * not the cloud server, so we never auto-connect them here.+ * - **Throttled** to one sync per connector per {@link CONNECTOR_TOOLS_REFRESH_TTL_MS}+ * using the tools' own `updatedAt` as the last-sync marker (no schema change).+ * - **Deferred** via `after()` so it runs past the response โ zero added latency.+ * Refreshed tools therefore take effect on the *next* run, which is fine for a+ * background freshness sweep, and failures are swallowed (never user-facing).+ */+export const scheduleStaleConnectorToolsRefresh = (+ connectors: StaleRefreshConnector[],+ lastSyncedAtById: Map<string, number>,+ ctx: ConnectorToolSyncContext,+ now: number = Date.now(),+): void => {+ // This runs inline on the request/agent-run hot path. It is a best-effort+ // optimization only: under NO circumstances may it throw into the caller and+ // break the tool call or chat flow. Every step is guarded so a bad input, a+ // logging failure, or an `after()` scheduling failure is swallowed here.+ pruneAttempts(now);++ for (const connector of connectors) {+ try {+ // stdio can't be refreshed server-side (the binary lives on the user's+ // machine); skip anything without an HTTP endpoint.+ if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) continue;+ if (!connector.mcpServerUrl) continue;++ const { id } = connector;+ // Throttle on whichever is more recent: the DB tool marker or the last+ // attempt we scheduled on this instance (covers empty tool lists and+ // concurrent calls, and backs off failed syncs to once per TTL).+ const lastSyncedAt = Math.max(lastSyncedAtById.get(id) ?? 0, lastAttemptAt.get(id) ?? 0);+ if (now - lastSyncedAt < CONNECTOR_TOOLS_REFRESH_TTL_MS) continue;++ lastAttemptAt.set(id, now);++ try {+ after(async () => {+ try {+ const { toolCount } = await syncConnectorToolsById(id, ctx);+ log('auto-refreshed connector %s: %d tools', id, toolCount);+ } catch (err) {+ // Remote unreachable / auth failure / etc. โ best-effort background+ // sweep, never surfaced to the user. The attempt stays recorded so+ // the connector backs off for a TTL instead of retrying every call.+ log('auto-refresh failed for connector %s: %O', id, err);+ }+ });+ } catch (err) {+ // `after()` failed to even schedule the work โ clear the attempt so a+ // later call can retry, and swallow.+ lastAttemptAt.delete(id);+ log('failed to schedule refresh for connector %s: %O', id, err);+ }+ } catch (err) {+ // Defensive: never let background-refresh bookkeeping touch the caller.+ log('unexpected error while scheduling connector refresh: %O', err);+ }+ }+};