fix(server): refresh MCP clients when reusing a provider session #18884
main fromrefs/pull/18884/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
coderabbitai[bot](GitHub profile, opens in a new tab) requested changes
apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 1739 to 1743OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1694,3 +1729,15 @@16941729 modelFamily: normalizeModelMetricLabel(model),16951730 },16961731 });1732+ const resumeNativeThread = (1733+ input: Parameters<ProviderAdapterV2SessionRuntime["resumeThread"]>[0],1734+ staleMcpCredential: boolean,1735+ ) => {1736+ // Codex keeps its MCP clients in a loaded native conversation.1737+ // A resume alone retains the revoked token; unload only this1738+ // conversation before resuming it with the refreshed config.1739+ const unload =1740+ staleMcpCredential && runtime.unloadThread !== undefined1741+ ? runtime.unloadThread({ providerThread: input.providerThread })1742+ : Effect.void;1743+ return unload.pipe(Effect.andThen(runtime.resumeThread(input)));- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 1740 to 1742OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1694,3 +1729,14 @@16941729 modelFamily: normalizeModelMetricLabel(model),16951730 },16961731 });1732+ const resumeNativeThread = (1733+ input: Parameters<ProviderAdapterV2SessionRuntime["resumeThread"]>[0],1734+ staleMcpCredential: boolean,1735+ ) => {1736+ // Codex keeps its MCP clients in a loaded native conversation.1737+ // A resume alone retains the revoked token; unload only this1738+ // conversation before resuming it with the refreshed config.1739+ const unload =1740+ staleMcpCredential && runtime.unloadThread !== undefined1741+ ? runtime.unloadThread({ providerThread: input.providerThread })1742+ : Effect.void;apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 1799 to 1806Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1317,3 +1344,11 @@13171344 Effect.tap((runtime) => Effect.sync(() => (attachedTo = runtime))),13181345 Effect.uninterruptible,13191346 );1347+ // A cached runtime may still be attached after another provider1348+ // rotated this thread's token. Validate it on every use, so its1349+ // next resume can reload the native MCP client with a live token.1350+ const prepared = yield* prepareMcpSession(1351+ input.threadId,1352+ input.providerInstanceId,1353+ (prepared) => (preparedForCleanup = prepared),1354+ );
coderabbitai[bot](GitHub profile, opens in a new tab) requested changes
apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 2218 to 2235OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2066,3 +2217,19 @@20662217 });2067- yield* touchActivity(input.providerSessionId);2068- return existing.exposedRuntime;2218+ const currentCredential = yield* mcpSessions.read(input.threadId);2219+ if (2220+ attached &&2221+ existing.runtime.unloadThread === undefined &&2222+ (existing.loadedProviderThreadKeyByThread.get(input.threadId)?.mcpCredentialId ??2223+ existing.mcpCredentialIdByThread.get(input.threadId)) !==2224+ currentCredential?.providerSessionId2225+ ) {2226+ // Pi and other process-bound MCP clients can only pick up2227+ // changed access by reopening through the normal lifecycle.2228+ yield* releaseEntry({2229+ providerSessionId: input.providerSessionId,2230+ reason: "manual_shutdown",2231+ });2232+ } else {2233+ yield* touchActivity(input.providerSessionId);2234+ return existing.exposedRuntime;2235+ }- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 1420OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1376,11 +1411,10 @@1376- (mcpCredentialId !== undefined &&1377- other.mcpCredentialIdByThread.get(input.threadId) ===1378- mcpCredentialId)),1379- )1380- ? Effect.void1381- : clearMcpSession(input.threadId, mcpCredentialId),1382- ),1383- );1384- }),1385- ),1386- ),1411+ : removeThreadAttachment({ ...input, runtime: attachedTo })1412+ ).pipe(1413+ Effect.andThen(1414+ Effect.suspend(() => {1415+ dropReservation();1416+ // Revoke only a credential this attach freshly minted: a1417+ // REUSED credential is by definition held by another1418+ // live provider process, and revoking it thread-wide1419+ // would break that process's MCP client mid-conversation.1420+ if (preparedForCleanup?.issued !== true) return Effect.void;apps/server/src/orchestration-v2/ProviderSessionManager.ts line 1809OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1705,8 +1795,15 @@1795+ ensureThreadAttached({17051796 providerSessionId,1706- ensureThreadAttached({1707- providerSessionId,1708- threadId: input.threadId,1709- providerInstanceId: runtime.instanceId,1710- }),1711- ).pipe(1797+ threadId: input.threadId,1798+ providerInstanceId: runtime.instanceId,1799+ runtime,1800+ }).pipe(1801+ Effect.mapError(1802+ (cause) =>1803+ new ProviderAdapter.ProviderAdapterEnsureThreadError({1804+ driver: runtime.driver,1805+ threadId: input.threadId,1806+ cause,1807+ }),1808+ ),17121809 Effect.andThen(runtime.ensureThread(input)),
juliusmarminge added labelsmacroscope-review
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 2248 to 2250Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1696 +1768,21 @@16961768 });1769+ const resumeNativeThread = (1770+ input: Parameters<ProviderAdapter.ProviderAdapterV2SessionRuntime["resumeThread"]>[0],1771+ staleMcpCredential: boolean,1772+ ) => {1773+ // Codex keeps its MCP clients in a loaded native conversation.1774+ // A resume alone retains the revoked token; unload only this1775+ // conversation before resuming it with the refreshed config.1776+ if (staleMcpCredential && runtime.unloadThread === undefined) {1777+ return Effect.fail(1778+ new ProviderAdapter.ProviderAdapterResumeThreadError({1779+ driver: runtime.driver,1780+ providerSessionId,1781+ providerThreadId: input.providerThread.id,1782+ cause: "MCP access changed; reopen the provider session before continuing.",1783+ }),1784+ );1785+ }1786+ const unload = staleMcpCredential1787+ ? runtime.unloadThread!({ providerThread: input.providerThread }).pipe(1788+ Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS),apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 2242 to 2245OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -2063,6 +2227,19 @@20632227 providerSessionId: input.providerSessionId,20642228 threadId: input.threadId,20652229 providerInstanceId: existing.runtime.instanceId,2230+ runtime: existing.runtime,20662231 });2067- yield* touchActivity(input.providerSessionId);2068- return existing.exposedRuntime;2232+ const currentCredential = yield* mcpSessions.read(input.threadId);2233+ if (2234+ attached &&2235+ existing.runtime.unloadThread === undefined &&2236+ (existing.loadedProviderThreadKeyByThread.get(input.threadId)?.mcpCredentialId ??2237+ existing.mcpCredentialIdByThread.get(input.threadId)) !==2238+ currentCredential?.providerSessionId2239+ ) {2240+ // Pi and other process-bound MCP clients can only pick up2241+ // changed access by reopening through the normal lifecycle.2242+ yield* releaseEntry({2243+ providerSessionId: input.providerSessionId,2244+ reason: "manual_shutdown",2245+ requireIdle: true,
coderabbitai[bot](GitHub profile, opens in a new tab) approved these changes
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 2285 to 2289OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -2134,3 +2272,18 @@2134- prepared.issued2135- ? clearMcpSession(input.threadId, mcpCredentialId)2136- : Effect.void,2272+ const key = sessionKey(input.providerSessionId);2273+ const existing = (yield* Ref.get(sessions)).get(key);2274+ if (existing !== undefined) {2275+ const attached = existing.attachedThreadIds.has(input.threadId);2276+ if (!attached && !existing.supportsMultipleProviderThreads) {2277+ return yield* new ProviderSessionOpenError({2278+ instanceId: input.modelSelection.instanceId,2279+ providerSessionId: input.providerSessionId,2280+ cause: `Provider ${existing.runtime.driver} does not support attaching multiple app threads to one session.`,2281+ });2282+ }2283+ // Joining a shared session is a new session for this thread.2284+ if (!attached) yield* agentScope.clear(input.threadId);2285+ yield* ensureThreadAttached({2286+ providerSessionId: input.providerSessionId,2287+ threadId: input.threadId,2288+ providerInstanceId: existing.runtime.instanceId,2289+ runtime: existing.runtime,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 1773OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1694,3 +1769,5 @@16941769 modelFamily: normalizeModelMetricLabel(model),16951770 },16961771 });1772+ const prepareRuntimeThread = (threadId: ThreadId) =>1773+ ensureThreadAttached({
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 1914OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1697,15 +1902,13 @@1902+ ),1903+ )1904+ : Effect.void;1905+ return unload.pipe(Effect.andThen(runtime.resumeThread(input)));1906+ };16971907 return {16981908 ...runtime,16991909 subscribeEvents,17001910 events: Stream.unwrap(17011911 subscribeEvents.pipe(Effect.map((subscription) => subscription.events)),17021912 ),17031913 ensureThread: (input) =>1704- observeActivity(1705- providerSessionId,1706- ensureThreadAttached({1707- providerSessionId,1708- threadId: input.threadId,1709- providerInstanceId: runtime.instanceId,1710- }),1711- ).pipe(1914+ prepareRuntimeThread(input.threadId).pipe(
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 1914OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1697,15 +1902,13 @@1902+ ),1903+ )1904+ : Effect.void;1905+ return unload.pipe(Effect.andThen(runtime.resumeThread(input)));1906+ };16971907 return {16981908 ...runtime,16991909 subscribeEvents,17001910 events: Stream.unwrap(17011911 subscribeEvents.pipe(Effect.map((subscription) => subscription.events)),17021912 ),17031913 ensureThread: (input) =>1704- observeActivity(1705- providerSessionId,1706- ensureThreadAttached({1707- providerSessionId,1708- threadId: input.threadId,1709- providerInstanceId: runtime.instanceId,1710- }),1711- ).pipe(1914+ prepareRuntimeThread(input.threadId).pipe(
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 2209OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1696,0 +1829,21 @@1829+ cause: "An active turn prevents refreshing MCP access.",1830+ });1831+ }1832+ const pending = yield* (1833+ runtime.hasPendingBackgroundWorkForThread?.(nativeThread) ?? Effect.succeed(false)1834+ ).pipe(1835+ Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS),1836+ Effect.mapError(1837+ (cause) => new ProviderSessionActivityError({ providerSessionId, cause }),1838+ ),1839+ );1840+ if (pending) {1841+ return yield* new ProviderSessionActivityError({1842+ providerSessionId,1843+ cause: "Pending background work prevents refreshing MCP access.",1844+ });1845+ }1846+ }1847+ }).pipe(1848+ Effect.andThen(1849+ ensureThreadAttached({apps/server/src/orchestration-v2/ProviderSessionManager.ts line 1812OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1694,3 +1795,18 @@16941795 modelFamily: normalizeModelMetricLabel(model),16951796 },16961797 });1798+ const prepareRuntimeThread = (1799+ threadId: ThreadId,1800+ providerThread?: OrchestrationV2ProviderThread,1801+ ) =>1802+ Effect.gen(function* () {1803+ const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId));1804+ // Ensure/fork fallbacks omit the native thread, but an existing1805+ // conversation's work still owns the credential they would rotate.1806+ const nativeThread =1807+ providerThread ?? entry?.idleThreadUnloads.get(threadId)?.providerThread;1808+ if (runtime.unloadThread === undefined) {1809+ if (1810+ entry === undefined ||1811+ entry.runtime !== runtime ||1812+ (yield* mcpAccessNeedsRefresh(entry, threadId))
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 1672 to 1674Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1261,14 +1361,14 @@12611361 });126213621263- const isProviderThreadLoaded = (input: {1363+ const providerThreadLoadStatus = (input: {12641364 readonly providerSessionId: ProviderSessionId;12651365 readonly threadId: ThreadId;12661366 readonly providerThreadKey: string;12671367 }) =>12681368 Ref.get(sessions).pipe(1269- Effect.map(1270- (current) =>1271- current1272- .get(sessionKey(input.providerSessionId))1273- ?.loadedProviderThreadKeyByThread.get(input.threadId) === input.providerThreadKey,1274- ),1369+ Effect.map((current) => {1370+ const entry = current.get(sessionKey(input.providerSessionId));1371+ const loaded = entry?.loadedProviderThreadKeyByThread.get(input.threadId);1372+ const staleMcpCredential =1373+ loaded !== undefined &&1374+ loaded.mcpCredentialId !== entry?.mcpCredentialIdByThread.get(input.threadId);apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 2816 to 2819Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -2137,6 +2379,16 @@2379+ providerSessionId: input.providerSessionId,2380+ cause,2381+ }),21372382 ),2138- Effect.ensuring(2139- closeScopeWithin(sessionScope, {2140- providerSessionId: input.providerSessionId,2141- reason: "open_failed",2142- }),2383+ );2384+ if (pending) {2385+ return yield* new ProviderSessionOpenError({2386+ instanceId: input.modelSelection.instanceId,2387+ providerSessionId: input.providerSessionId,2388+ cause: "Pending background work prevents reopening the provider session.",2389+ });2390+ }2391+ yield* releaseEntry({2392+ providerSessionId: input.providerSessionId,2393+ reason: "manual_shutdown",2394+ requireIdle: true,
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 584 to 586OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -525,4 +567,20 @@567+ const prepared = { mcpCredentialId: existing.providerSessionId, issued: false };568+ // The caller owns this reservation before a guard can yield569+ // or fail, including when the last live owner just released it.570+ onPrepared(prepared);571+ if (checkAccess !== undefined)572+ yield* checkAccess(existing.providerSessionId, false);573+ return prepared;525574 }526- dropMcpCredentialReservation(threadId, existing.providerSessionId);575+ yield* Effect.sync(() =>576+ dropMcpCredentialReservation(threadId, existing.providerSessionId),577+ ).pipe(578+ Effect.andThen(clearUnownedMcpSession(threadId, existing.providerSessionId)),579+ Effect.uninterruptible,580+ );527581 }582+ // Validate work against this same settings/credential snapshot583+ // before any live credential is revoked or issued.584+ if (checkAccess !== undefined)585+ yield* checkAccess(existing?.providerSessionId, true);528586 yield* mcpSessionRegistry.revokeThread(threadId);apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 1919 to 1922OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1696,0 +1902,21 @@1902+ if (runtime.unloadThread === undefined) {1903+ if (needsRefresh) {1904+ return yield* new ProviderSessionActivityError({1905+ providerSessionId,1906+ cause: "MCP access changed; reopen the provider session before continuing.",1907+ });1908+ }1909+ } else if (nativeThread !== undefined && loaded !== undefined && needsRefresh) {1910+ if (hasBusyTurn(entry, nativeThread.id)) {1911+ return yield* new ProviderSessionActivityError({1912+ providerSessionId,1913+ cause: "An active turn prevents refreshing MCP access.",1914+ });1915+ }1916+ // A partial detach may have unloaded the tracked client but1917+ // left another native client alive with this credential.1918+ const pending = yield* (1919+ loaded.key === undefined && runtime.hasPendingBackgroundWork !== undefined1920+ ? runtime.hasPendingBackgroundWork1921+ : (runtime.hasPendingBackgroundWorkForThread?.(nativeThread) ??1922+ Effect.succeed(false))
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 697 to 698OutdatedResolvedby Alb11747(GitHub profile, opens in a new tab)@@ -560,0 +678,21 @@678+ (entry.runtime.providerSessionId === providerSessionId &&679+ loaded.providerThread.id === reload.providerThreadId &&680+ loaded.mcpCredentialId !== reload.candidateId)),681+ );682+ // An explicit retained native is known even before its first resume683+ // in this process. Probe it without inventing a loaded client record.684+ if (685+ providerThread !== undefined &&686+ entry.runtime.providerSessionId === providerSessionId &&687+ !entry.loadedProviderThreads.has(providerThread.id) &&688+ reload === undefined689+ ) {690+ records.push({691+ threadId,692+ providerThread,693+ key: undefined,694+ mcpCredentialId: entry.mcpCredentialIdByThread.get(threadId),695+ });696+ }697+ const processOwner =698+ reload === undefined && entry.mcpCredentialIdByThread.has(threadId);
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 2836Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -2137,6 +2616,16 @@2616+ Effect.mapError(2617+ (cause) =>2618+ new ProviderSessionOpenError({2619+ instanceId: input.modelSelection.instanceId,2620+ providerSessionId: input.providerSessionId,2621+ cause,2622+ }),21372623 ),2138- Effect.ensuring(2139- closeScopeWithin(sessionScope, {2140- providerSessionId: input.providerSessionId,2141- reason: "open_failed",2142- }),2624+ );2625+ } else {2626+ // Joining a shared session is a new session for this thread.2627+ if (!attached) yield* agentScope.clear(input.threadId);2628+ // Cached native clients prepare access at the operation2629+ // boundary, where pending work can reject a reload safely.2630+ if (2631+ !attached &&
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 2987Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2206,20 +2771 @@2206- releaseEntry(2207- Cause.hasInterruptsOnly(cause)2208- ? {2209- providerSessionId: input.providerSessionId,2210- reason: "manual_shutdown",2211- detail: "The provider session start was interrupted.",2212- }2213- : {2214- providerSessionId: input.providerSessionId,2215- reason: "runtime_error",2216- detail: "Failed to persist the provider-session attachment.",2217- },2218- ).pipe(logReleaseFailure(input.providerSessionId)),2219- ),2220- );2221- yield* startEventPump(entry);2222- yield* scheduleIdleRelease(input.providerSessionId);2223- return exposedRuntime;2224- }),2225- ),2771+ }).pipe(Effect.onError((cause) => cleanupOpen(cause))),
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 1752 to 1753Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1292,0 +1610,21 @@1610+ if (entry?.runtime !== runtime || loaded === undefined)1611+ return [undefined, current] as const;1612+ const loadedProviderThreads = new Map(entry.loadedProviderThreads);1613+ const unknownLoad = { ...loaded, key: undefined };1614+ loadedProviderThreads.set(nativeKey, unknownLoad);1615+ return [1616+ unknownLoad,1617+ new Map(current).set(key, { ...entry, loadedProviderThreads }),1618+ ] as const;1619+ });1620+ yield* runtime.unloadThread!({ providerThread });1621+ // Failure or interruption retains the pointer and consumed credential.1622+ yield* Ref.update(sessions, (current) => {1623+ const entry = current.get(key);1624+ if (1625+ entry?.runtime !== runtime ||1626+ entry.loadedProviderThreads.get(nativeKey) !== unloading1627+ )1628+ return current;1629+ const loadedProviderThreads = new Map(entry.loadedProviderThreads);1630+ loadedProviderThreads.delete(nativeKey);
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 2987Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -2206,20 +2841 @@2206- releaseEntry(2207- Cause.hasInterruptsOnly(cause)2208- ? {2209- providerSessionId: input.providerSessionId,2210- reason: "manual_shutdown",2211- detail: "The provider session start was interrupted.",2212- }2213- : {2214- providerSessionId: input.providerSessionId,2215- reason: "runtime_error",2216- detail: "Failed to persist the provider-session attachment.",2217- },2218- ).pipe(logReleaseFailure(input.providerSessionId)),2219- ),2220- );2221- yield* startEventPump(entry);2222- yield* scheduleIdleRelease(input.providerSessionId);2223- return exposedRuntime;2224- }),2225- ),2841+ }).pipe(Effect.onError((cause) => cleanupOpen(cause))),
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 2353 to 2354Resolvedby Alb11747(GitHub profile, opens in a new tab)@@ -1863,4 +2315,19 @@2315+ holdThreadLoaded({18632316 providerSessionId,18642317 threadId,1865- providerInstanceId: runtime.instanceId,1866- }),2318+ providerThread: input.providerThread,2319+ }).pipe(2320+ Effect.andThen(2321+ providerThreadLoadStatus({2322+ providerSessionId,2323+ threadId,2324+ providerThread: input.providerThread,2325+ providerThreadKey,2326+ }),2327+ ),2328+ Effect.flatMap(({ loaded, staleMcpCredential }) => {2329+ if (loaded) return Effect.succeed(input.providerThread);2330+ return resumeNativeThread(input, staleMcpCredential);2331+ }),2332+ Effect.tap((providerThread) =>2333+ markProviderThreadLoaded({
Alb11747(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Codex Review Summary#
This comment shows the latest Codex review activity on this pull request.
ce7cf34ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.