Skip to content

feat(den): reuse downstream MCP sessions across capability operations - #3208

Merged
benjaminshafii merged 6 commits into
devfrom
feat/external-mcp-session-reuse
Aug 4, 2026
Merged

benjaminshafii merged 6 commits into
devfrom
feat/external-mcp-session-reuse

Conversation

@benjaminshafii

@benjaminshafii benjaminshafii commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

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 listExternalMcpTools and runExternalMcpToolCall (external-mcp-session-pool.ts):

  • Per-member safety first. 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 — 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.
  • Lease-slot design. Deadlines, diagnostic trackers, and tool-call inspectors were baked into each transport's fetch closure — naive reuse would leak operation A's deadline/diagnostics into operation B. Pooled transports resolve {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).
  • Lifecycle: 120s idle TTL, 10m absolute, 64-entry LRU (idle-only), single-flight connects, close-on-evict. Reused sessions failing with auth/session/transport-shaped errors → evict + one fresh retry; deadline exhaustion never retries; fresh-session failures surface exactly as today.
  • Invalidation hooks on OAuth token save/refresh/invalidate, connection update/delete/disconnect, member disconnect.
  • Kill switch: DEN_EXTERNAL_MCP_SESSION_REUSE=0 restores today's behavior exactly.
  • Unchanged on purpose: health probes and OAuth completion stay ephemeral; search_capabilities keeps 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)

  • New 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.
  • Existing client suites (external-mcp-diagnostics, external-mcp-resolve, external-mcp-tool-inspection, external-mcp-tool-arguments, enterprise-mcp-adapter-budget, external-capability-errors) — pass.
  • Full den-api suite: failures identical to the origin/dev baseline on this machine (172, all pre-existing local-MySQL/env failures — verified by stash A/B with per-file attribution; zero attributed to this change).
  • 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_INITIALIZE phase 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.ts standardized list/call/inspect on 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:

  1. fix(den): route external MCP tool operations through the pooled client — list/call/inspect now 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-client and flipping tool ops back (follow-up issue linked below). The spec is client-agnostic, so that migration is protected by the same proof.
  2. test(evals): prove external MCP session reuse contract end-to-end — fast-lane spec evals/specs/org-connector-session-reuse.test.ts driving Den directly, with the mock connector as witness (now records initialize handshakes + per-request session ids):
    • search→execute reuses one session (exactly one initialize; negative half bounded);
    • a second member never rides the first member's session (distinct sessionId + tokenId);
    • credential rotation forces a fresh handshake;
    • a killed session evicts and retries exactly once;
    • DEN_EXTERNAL_MCP_SESSION_REUSE=0 restores 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 suite ee/apps/den-api/test/external-mcp-session-reuse.test.ts → 10 pass / 0 fail.

Note: this update merges origin/dev into the branch — the testkit/spec infrastructure only exists post-merge.

Rollback honesty: the DEN_EXTERNAL_MCP_SESSION_REUSE=0 kill 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).

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.
@vercel

vercel Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
openwork-app Ready Ready Preview Aug 4, 2026 11:45am
openwork-den Ready Ready Preview Aug 4, 2026 11:45am
openwork-den-worker-proxy Ready Ready Preview Aug 4, 2026 11:45am
openwork-landing Ready Ready Preview, v0 Aug 4, 2026 11:45am
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
openwork-diagnostics Skipped Skipped Aug 4, 2026 11:45am

@Pallavikumarimdb

Copy link
Copy Markdown

@benjaminshafii I pulled the branch locally and spot-checked the session reuse and kill switch behavior.

  • With session reuse enabled, two sequential tool calls only triggered a single initialize handshake (both reused session-0).
  • With reuse disabled, the same flow triggered two initialize handshakes as expected.

So the "1 initialize instead of 2" claim in the PR checks out.

I also verified the DEN_EXTERNAL_MCP_SESSION_REUSE kill switch separately by clearing the test overrides and reading env.externalMcpSessionReuseEnabled directly:

  • DEN_EXTERNAL_MCP_SESSION_REUSE=0 → false
  • DEN_EXTERNAL_MCP_SESSION_REUSE=1 → true

That matches the expected runtime config behavior outside the test setup.

For per_member connections, buildExternalMcpSessionPoolKey includes both orgMembershipId and the member credential revision in the pool key. Missing member context throws instead of silently falling back, and credential updates naturally force a new session, so the isolation logic looks correct.

Tests are all passing locally:

  • New test suite: 10/10
  • Related MCP suites mentioned in the PR: all passing
  • Full den-api suite: 203/203

I didn't find anything that contradicts the PR description. I haven't dug into the lease-slot concurrency path yet (2s wait / throwaway session fallback), but I can take a look if that's useful before merging.

…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.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Deploying openwork with  Cloudflare Pages  Cloudflare Pages

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

View logs

@benjaminshafii

benjaminshafii commented Aug 4, 2026 •

Copy link
Copy Markdown
Member Author

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

⚠ evidence from a90c771, PR head is e754d1d

ℹ️ FACT — 1. Member A reused one connector session across discovery and repeated execution

Connector 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

  • ✅ PASS Member A reused one connector session across discovery and repeated execution — Connector 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 isolated

Connector 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

  • ✅ PASS Member sessions and bearer credentials remained isolated — Connector 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 session

Connector 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

  • ✅ PASS Rotating member A's credential invalidated the old pooled session — Connector 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 once

Mock 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

  • ✅ PASS A dead connector session was evicted and retried exactly once — Mock 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: evals/results/rolls/2026-08-04T10-11-57-951Z-organization-connector-sessions-are-reused-isolated-rotated-and-recovered-throug/roll.json · Repro: pnpm fraimz:publish -- --pr 3208 --roll 2026-08-04T10-11-57-951Z-organization-connector-sessions-are-reused-isolated-rotated-and-recovered-throug

@benjaminshafii

Copy link
Copy Markdown
Member Author

@reachjalil ready for your pass when you land. Two things changed since you last saw this:

  1. The e2e spec caught the pool being bypassed — runtime routed list/call/inspect through the enterprise client (fix(den): standardize external MCP OAuth on enterprise client #2810), so the pool never engaged on the live path. Fixed here as a stopgap by flipping tool ops to the pooled SDK client (connect/OAuth untouched on the enterprise client). End-state is feat(den): move the external MCP session pool inside @openwork/enterprise-mcp-client, then retire the SDK client path #3493: pool moves inside the enterprise client, tool ops flip back, SDK path retires. The spec is client-agnostic and protects that migration.
  2. Review asks: (a) the per-member pool keying (external-mcp-session-pool.ts — membership + connected-account revision in the key, fail-closed without member context); (b) whether the stopgap routing loses anything the enterprise client provides on tool calls today (diagnostics/inspection/budget suites pass, but you know that surface best).

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.
@benjaminshafii

Copy link
Copy Markdown
Member Author

@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 session-0 naming is the tell) exercised the pooled module directly, same as the unit tests. It turns out the runtime had standardized tool operations on the enterprise MCP client (#2810) before this branch was cut, so the pool — while working exactly as you verified — was never on the live capability path. The new e2e spec (evals/specs/org-connector-session-reuse.test.ts) drives Den itself and caught that on its first run; a small routing commit now engages the pool for real, and the evidence tape in the sticky comment covers the full contract (reuse, per-member isolation, rotation, dead-session retry, kill switch).

Module-level verification + live-path proof are both useful — thanks again for doing the first one.

@diff-warden diff-warden Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@benjaminshafii
benjaminshafii merged commit c8adbe7 into dev Aug 4, 2026
20 of 21 checks passed
@benjaminshafii
benjaminshafii deleted the feat/external-mcp-session-reuse branch August 4, 2026 11:51

This branch was successfully deployed

4 active and 1 inactive deployments
Preview – openwork-den-worker-proxy — e754d1de Deployed Aug 4, 2026 by vercel[bot]
Preview – openwork-den — e754d1de Deployed Aug 4, 2026 by vercel[bot]
Preview – openwork-landing — e754d1de Deployed Aug 4, 2026 by vercel[bot]
Preview – openwork-app — e754d1de Deployed Aug 4, 2026 by vercel[bot]
Preview – openwork-diagnostics — e754d1de Deployed Aug 4, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants