Skip to content

Commit f8fc2ed

Browse files
committed
fix(mcp): resync on re-subscribe so events missed while the tab was closed reconcile
Leaving the settings tab tears down the shared EventSource; remounting created a new connection whose first open was skipped, so a tools_changed fired while unsubscribed wasn't reconciled (the 5min stale time also won't refetch on remount). Track a per-workspace 'ever subscribed' flag: skip resync only on the session's first subscription (queries fetch fresh then); resync on the first open of any re-subscription and on every reconnect.
1 parent 289c81d commit f8fc2ed

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

apps/sim/hooks/queries/mcp.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,12 @@ const sseConnections: Map<string, SseEntry> =
527527
((globalThis as Record<string, unknown>)[SSE_KEY] as Map<string, SseEntry>) ??
528528
((globalThis as Record<string, unknown>)[SSE_KEY] = new Map<string, SseEntry>())
529529

530+
/** Per-workspace flag: has this session ever held a live SSE subscription for it? */
531+
const SSE_SUBSCRIBED_KEY = '__mcp_sse_subscribed' as const
532+
const sseEverSubscribed: Set<string> =
533+
((globalThis as Record<string, unknown>)[SSE_SUBSCRIBED_KEY] as Set<string>) ??
534+
((globalThis as Record<string, unknown>)[SSE_SUBSCRIBED_KEY] = new Set<string>())
535+
530536
/** Subscribes to `tools_changed` SSE events and invalidates the affected query keys. */
531537
export function useMcpToolsEvents(workspaceId: string) {
532538
const queryClient = useQueryClient()
@@ -563,12 +569,16 @@ export function useMcpToolsEvents(workspaceId: string) {
563569
invalidate(serverId)
564570
})
565571

566-
// EventSource fires `onopen` on the initial connect and on every auto-reconnect. A
567-
// reconnect may have missed a `tools_changed` event during the gap, so re-sync the
568-
// whole workspace on reconnect (never on the first open — the query already fetched).
572+
// EventSource fires `onopen` on the initial connect and on every auto-reconnect. Re-sync
573+
// the workspace whenever we could have missed a `tools_changed` event: on any reconnect,
574+
// and on the first open of a RE-subscription (leaving the tab tears the connection down,
575+
// so events fired while unsubscribed would otherwise be missed). Skip only the very first
576+
// subscription of the session — the queries fetch fresh on their own initial mount.
577+
const isResubscribe = sseEverSubscribed.has(workspaceId)
578+
sseEverSubscribed.add(workspaceId)
569579
let opened = false
570580
source.onopen = () => {
571-
if (opened) invalidate()
581+
if (opened || isResubscribe) invalidate()
572582
opened = true
573583
}
574584

0 commit comments

Comments
 (0)