Repository navigation
feat(den): reuse downstream MCP sessions across capability operations - #3208
Conversation
Every search_capabilities and execute_capability opened a full MCP session against the customer's gateway (initialize, initialized notice, SSE probe, work, close) and threw it away — roughly two handshakes per agent prompt, which shows up as request bursts in partner gateway logs. Add an in-process session pool for listExternalMcpTools and runExternalMcpToolCall: - key: sha256 over connection id/url/authType/credentialMode, hashed apiKey/oauth config, row updatedAt, and for per_member connections the orgMembershipId plus the member's connected-account revision — token rotation or config change naturally misses the old session; per-member sessions can never be shared across members - exclusive lease per operation with a mutable lease slot: the pooled transport's fetch resolves deadline, diagnostic tracker, and tool-call inspector from the current lease, so one operation's lifecycle can never leak into the next; concurrent same-key callers wait up to 2s then fall back to a throwaway session - 120s idle TTL, 10m absolute lifetime, 64-entry LRU (idle entries only), single-flight connects, close-on-evict - reused sessions that fail with auth-, session-, or transport-shaped errors are evicted and retried once on a fresh session; deadline exhaustion is never retried; fresh-session failures surface exactly as before - invalidation hooks on OAuth token save/refresh/invalidate, connection update/delete/disconnect, and member disconnect - kill switch: DEN_EXTERNAL_MCP_SESSION_REUSE=0 restores session-per-operation Health probes (connectExternalMcp) and OAuth completion stay ephemeral by design, and the live tools/list catalog semantics are unchanged — this reuses the session, not the catalog.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
1 Skipped Deployment
|
|
@benjaminshafii I pulled the branch locally and spot-checked the session reuse and kill switch behavior.
So the "1 initialize instead of 2" claim in the PR checks out. I also verified the
That matches the expected runtime config behavior outside the test setup. For Tests are all passing locally:
I didn't find anything that contradicts the PR description. I haven't dug into the lease-slot concurrency path yet ( |
…ion-reuse-spec # Conflicts: # ee/apps/den-api/src/capability-sources/external-mcp-client.ts
The runtime standardized list/call/inspect on the enterprise MCP client (#2810) before this branch was cut, so the session pool introduced here never engaged on the live capability path: unit tests exercised the pooled module directly and passed while production traffic dialed a fresh downstream session per operation. Route listExternalMcpTools/callExternalMcpTool/inspectExternalMcpToolCall through the pooled SDK client; connect/OAuth lifecycle stays on the enterprise client. Stopgap until the pool moves inside @openwork/enterprise-mcp-client (follow-up issue), after which tool ops flip back and the SDK client path retires.
Fast-lane spec (no app): Den is driven directly and the mock connector is the witness. Claims: search->execute reuses one session (one initialize); a second member never rides the first member's session (distinct sessionId + tokenId, negative halves asserted); credential rotation forces a fresh handshake; a killed session evicts and retries exactly once; DEN_EXTERNAL_MCP_SESSION_REUSE=0 restores session-per-operation. Witness: mock MCP server now records initialize handshakes and per-request session ids, and exposes handshakes() plus session invalidation for dead-session drills. Additive only. The first run of this spec exposed the runtime bypass fixed in the previous commit; with the original routing restored the reuse claim fails and the kill-switch claim passes, so the spec discriminates.
Deploying openwork with
|
| Latest commit: |
e754d1d
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://5fa3311c.openwork.pages.dev |
| Branch Preview URL: | https://feat-external-mcp-session-re.openwork.pages.dev |
Photo roll — organization-connector-sessions-are-reused-isolated-rotated-and-recovered-throug — 0/0 frames passed · 4 facts✅ 0/0 frames passed · 4 facts · 4 expectations passed · 0 failed ℹ️ FACT — 1. Member A reused one connector session across discovery and repeated executionConnector handshakes: [{"atIso":"2026-08-04T10:12:18.150Z","tokenId":"443c5eafa5bb","sessionId":"mock-session-3"}]; tool calls: [{"name":"mock_echo","args":{"text":"reuse-a-first-1785838338157"},"tokenId":"443c5eafa5bb","sessionId":"mock-session-3","at":"2026-08-04T10:12:18.177Z"},{"name":"mock_echo","args":{"text":"reuse-a-second-1785838338157"},"tokenId":"443c5eafa5bb","sessionId":"mock-session-3","at":"2026-08-04T10:12:18.197Z"}]; bounded no-second-handshake count: 1
ℹ️ FACT — 2. Member sessions and bearer credentials remained isolatedConnector handshakes: [{"atIso":"2026-08-04T10:12:20.220Z","tokenId":"529db875fbe5","sessionId":"mock-session-4"}]; B and returning-A calls: [{"name":"mock_echo","args":{"text":"isolation-b-1785838340227"},"tokenId":"529db875fbe5","sessionId":"mock-session-4","at":"2026-08-04T10:12:20.246Z"},{"name":"mock_echo","args":{"text":"isolation-a-return-1785838340227"},"tokenId":"443c5eafa5bb","sessionId":"mock-session-3","at":"2026-08-04T10:12:20.265Z"}]; bounded handshake count: 1
ℹ️ FACT — 3. Rotating member A's credential invalidated the old pooled sessionConnector handshakes after reconnect completed: [{"atIso":"2026-08-04T10:12:22.336Z","tokenId":"7625c6d50ea8","sessionId":"mock-session-6"}]; rotated call: {"name":"mock_echo","args":{"text":"rotation-a-1785838342318"},"tokenId":"7625c6d50ea8","sessionId":"mock-session-6","at":"2026-08-04T10:12:22.349Z"}; bounded no-second-handshake count: 1
ℹ️ FACT — 4. A dead connector session was evicted and retried exactly onceMock invalidated 6 live sessions; recovery handshakes: [{"atIso":"2026-08-04T10:12:24.378Z","tokenId":"7625c6d50ea8","sessionId":"mock-session-7"}]; successful call: {"name":"mock_echo","args":{"text":"dead-session-a-1785838344357"},"tokenId":"7625c6d50ea8","sessionId":"mock-session-7","at":"2026-08-04T10:12:24.387Z"}; bounded no-second-handshake count: 1
Roll created 2026-08-04T10:11:57.952Z · Source: |
|
@reachjalil ready for your pass when you land. Two things changed since you last saw this:
Evidence tape for the full contract (reuse, isolation, rotation, dead-session retry, kill switch) is in the sticky comment above; falsification check documented in the PR body. |
…oudly This mirrors skill-grant-access's test.skipIf mechanism, gating the contract on a Den URL or local MySQL and the kill switch on local MySQL.
|
@Pallavikumarimdb thank you for pulling the branch and checking this — genuinely appreciated, and your observations were correct for what they measured. One nuance we found since: those runs (the Module-level verification + live-path proof are both useful — thanks again for doing the first one. |
There was a problem hiding this comment.
Warden security clearance: clear. No new security issues found in this diff (e754d1de03d40ef7ae06c1d4a137043e9d5f03cd). Automated clearance satisfies the required-review gate only — a human still reviews and merges. Analysis run
Why
Gateway logs from an enterprise self-hosted deployment showed the cost of our session-per-operation design: one agent prompt ("show me the last 10 opportunities") =
search_capabilities+execute_capability= two full MCP handshakes against the org's AI gateway, each with initialize + initialized + SSE probe (the gateway's 405) + work + close — ~8–12 requests per prompt, plus live status probes. The 405s are spec-correct and stay; the volume is what this PR halves.What
In-process session pool for
listExternalMcpToolsandrunExternalMcpToolCall(external-mcp-session-pool.ts):updatedAt, and forper_memberconnections theorgMembershipIdplus the member's connected-account revision — a rotated token or edited connection misses the old session by construction; sessions can never be shared across members. Missing member context on a per_member connection fails closed.{deadline, diagnostic, inspector}from the current lease per request; leases are exclusive, concurrent same-key callers wait ≤2s then use a throwaway session (no head-of-line blocking).DEN_EXTERNAL_MCP_SESSION_REUSE=0restores today's behavior exactly.search_capabilitieskeeps its live tools/list (we reuse the session, not the catalog); SDK GET/SSE behavior untouched.Result
Mock-measured: search→execute now performs 1 initialize instead of 2; steady-state per-prompt traffic to the gateway roughly halves (handshake amortized across the TTL window).
Tests (all run by reviewer-side commands below)
test/external-mcp-session-reuse.test.ts(initialize-counting mock MCP server): reuse across list→call, per-member session isolation (distinct sessions/credentials asserted on the wire), key rotation on credential change, evict+retry on killed session (404) and on 401, idle-TTL expiry, kill switch, lease deadline/diagnostic isolation, bounded concurrency — 10 pass / 0 fail.external-mcp-diagnostics,external-mcp-resolve,external-mcp-tool-inspection,external-mcp-tool-arguments,enterprise-mcp-adapter-budget,external-capability-errors) — pass.pnpm --filter @openwork-ee/den-api build✅Validation honesty: originally verified only against an initialize-counting mock at unit level. Now superseded by the end-to-end spec below. Diagnostics note: reused sessions legitimately skip the
MCP_INITIALIZEphase in their tracker (there is no initialize); all other phases unchanged. Recommend one review pass from @reachjalil on the per-member keying before merge, and rollout with the kill switch documented for self-hosted deployments in case a gateway dislikes long-lived sessions.Update (Aug 4): e2e spec found the pool was bypassed; routing fixed; contract now proven end-to-end
Writing the testkit spec for this PR exposed an integration defect the unit tests could not see: the runtime never routed tool operations through this pool.
external-mcp-client-runtime.tsstandardizedlist/call/inspecton the enterprise MCP client (#2810) before this branch was cut, so the pool was dead code on the live capability path — unit tests exercised the pooled module directly and passed, while production Den dialed a fresh downstream session per operation.Two commits added:
fix(den): route external MCP tool operations through the pooled client—list/call/inspectnow use the pooled SDK client; connect/OAuth lifecycle stays on the enterprise client. This is a stopgap: the intended end-state is moving the pool inside@openwork/enterprise-mcp-clientand flipping tool ops back (follow-up issue linked below). The spec is client-agnostic, so that migration is protected by the same proof.test(evals): prove external MCP session reuse contract end-to-end— fast-lane specevals/specs/org-connector-session-reuse.test.tsdriving Den directly, with the mock connector as witness (now records initialize handshakes + per-request session ids):DEN_EXTERNAL_MCP_SESSION_REUSE=0restores session-per-operation.Falsification check: with the original enterprise routing restored, the reuse claim fails and the kill-switch claim passes — the spec discriminates rather than rubber-stamps.
Ran:
pnpm dev:den:mysql && pnpm --dir evals exec vitest run --config vitest.config.ts --project pr specs/org-connector-session-reuse.test.ts→ 2 passed / 0 failed (evidence tape published in the sticky comment). Branch unit suiteee/apps/den-api/test/external-mcp-session-reuse.test.ts→ 10 pass / 0 fail.Note: this update merges
origin/devinto the branch — the testkit/spec infrastructure only exists post-merge.Rollback honesty: the
DEN_EXTERNAL_MCP_SESSION_REUSE=0kill switch restores the session-per-operation traffic shape but not the enterprise client on tool calls — routing stays on the pooled SDK client either way. If the SDK tool path turns out to lack something the enterprise client provides, the correct lever is reverting the small routing commit, not the env var.Merge decision: owner waived the pre-merge review to ship the traffic relief now. @reachjalil's pass on (a) the per-member pool keying and (b) SDK-vs-enterprise tool-path parity moves to post-merge, folded into #3493. If (b) turns up a gap, the rollback is reverting the small routing commit (see above), and #3493 becomes the fix path.
CI note: the spec gates itself — it skips loudly on runners without a Den URL or local MySQL (mirrors
skill-grant-access), and the CodeQL alert on the pool-key sha256 is dismissed as false positive (in-memory cache-key derivation, not password storage).