Skip to content

feat: add a session-safe shared MCP tools bridge runtime - #16221

Closed
sanshengai wants to merge 1 commit into
stablyai:mainfrom
sanshengai:feat/shared-mcp-bridge-foundation
Closed

sanshengai wants to merge 1 commit into
stablyai:mainfrom
sanshengai:feat/shared-mcp-bridge-foundation

Conversation

@sanshengai

Copy link
Copy Markdown

Summary

Adds the runtime foundation for a session-safe, shared MCP bridge (part of #7362 and the resource-reduction work tracked in #16211).

The bridge exposes a bearer-protected Streamable HTTP endpoint on 127.0.0.1 and multiplexes independent upstream MCP sessions onto one downstream stdio MCP client/process. This is intentionally runtime-first and tools-only; settings UI, automatic agent config injection, and non-tools capabilities remain follow-ups.

Why

Sharing a raw stdio pipe is not protocol-safe: unrelated clients can reuse JSON-RPC request IDs and have independent cancellation/session lifecycles. The bridge instead terminates each upstream session with its own MCP Server/HTTP transport, then forwards tool calls through one SDK Client, which owns downstream request IDs.

Safety boundary

  • loopback-only endpoint with a random bearer token
  • explicit tools-capable stdio definition; no automatic coalescing
  • pool fingerprint includes command, args, cwd, environment values, and a caller-owned isolationKey for workspace/auth/version boundaries
  • secrets participate only through a SHA-256 identity and are not returned or logged
  • no prompts, roots, raw tool payloads, or child stderr are logged
  • direct stdio remains the fallback until later settings/injection work opts a server in

Lifecycle

  • concurrent initialization is single-flight, so five clients spawn one downstream process
  • each upstream session can disconnect independently
  • the last session starts a bounded idle shutdown
  • a crashed downstream is recreated on the next tool request
  • tools/list_changed notifications fan out to all live sessions
  • cancellation and progress are forwarded, with progress tokens remapped to the upstream request

Tests

  • pnpm exec vitest run --config config/vitest.config.ts src/main/mcp-bridge/shared-mcp-tools-bridge.test.ts
  • pnpm run typecheck
  • pnpm run audit:code-quality:native
  • pnpm run audit:code-quality:type-aware
  • pnpm run check:max-lines-ratchet

The integration test connects five independent Streamable HTTP clients, invokes tools concurrently (their SDK request ID sequences collide naturally), verifies one shared child PID, disconnects one client without disturbing the others, verifies bounded last-client cleanup, rejects a bad token, and verifies crash recovery.

@coderabbitai

coderabbitai Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds the SharedMcpToolsBridge for authenticated loopback HTTP access to tools from a shared downstream MCP stdio server. The bridge manages isolated MCP sessions, shared downstream connections, progress notifications, tool-list updates, idle shutdown, crash recovery, and teardown. It adds bridge support types and utilities, public exports, the MCP SDK dependency, a stdio test fixture, and integration tests.

Merge Risk: 🟡 Moderate · up to 344bf

The bridge can leave application shutdown hanging when an upstream connection remains open, and its integration test does not currently prove that multiple clients share one downstream process. These bounded runtime and validation issues should be fixed before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, rationale, safety boundary, lifecycle, linked issues, and tests, but omits most required template sections and checklist items. Add the required template headings and complete the linked issue, visual proof or N/A, testing checklist, AI disclosure, review, boundary, notes, and final checklist sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the new session-safe shared MCP tools bridge runtime.
Docstring Coverage ✅ Passed Docstring check was indeterminate for this PR — some files could not be analyzed in time. Not blocking.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Warning

⚠️ This pull request shows signs of AI-generated slop (trivial_assertion). It has been flagged by CodeRabbit slop detection and should be reviewed carefully.

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9fff26c3-37ef-4574-8f1f-7b37630dc7de

📥 Commits

Reviewing files that changed from the base of the PR and between 4ee41fe and 344bf63.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • package.json
  • src/main/mcp-bridge/index.ts
  • src/main/mcp-bridge/shared-mcp-tools-bridge-support.ts
  • src/main/mcp-bridge/shared-mcp-tools-bridge.test.ts
  • src/main/mcp-bridge/shared-mcp-tools-bridge.ts
  • src/main/mcp-bridge/test-fixtures/tools-server.mjs

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

)
const parsed = results.map(readResult)

expect(new Set(parsed.map(({ pid }) => pid))).toHaveLength(1)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the installed Vitest toHaveLength implementation requires a numeric `.length`.
fd -t f 'jest-expect' node_modules/@vitest --exec rg -n -A 12 "'toHaveLength'" 2>/dev/null \
  || rg -n -A 12 "'toHaveLength'" -g '**/@vitest/expect/**' .

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- test file ---'
cat -n src/main/mcp-bridge/shared-mcp-tools-bridge.test.ts | sed -n '65,100p'
printf '%s\n' '--- Vitest declarations and package metadata ---'
rg -n -S 'toHaveLength|vitest' package.json package-lock.json pnpm-lock.yaml yarn.lock src 2>/dev/null | head -120
printf '%s\n' '--- local dependency candidates ---'
find . -path '*/node_modules/@vitest/expect*' -o -path '*/node_modules/@vitest/utils*' 2>/dev/null | head -40

Repository: stablyai/orca

Length of output: 16118


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- Vitest 4.1.5 matcher implementation ---'
rg -n -S -A 20 -B 8 'toHaveLength|length.*expected|expected.*length' \
  node_modules/@vitest/expect node_modules/.pnpm/@[email protected] 2>/dev/null | head -160
printf '%s\n' '--- package exports and matcher files ---'
find node_modules/@vitest/expect -maxdepth 3 -type f -print 2>/dev/null | sort | head -100
printf '%s\n' '--- Set property behavior ---'
node - <<'JS'
const values = [new Set([1]), [1], { length: 1 }]
for (const value of values) {
  console.log(value.constructor.name, {
    length: value.length,
    size: value.size,
    hasOwnLength: Object.prototype.hasOwnProperty.call(value, 'length')
  })
}
JS

Repository: stablyai/orca

Length of output: 438


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- resolved Vitest package paths ---'
readlink -f node_modules/@vitest/expect 2>/dev/null || true
find -L node_modules/@vitest/expect -maxdepth 3 -type f -print 2>/dev/null | sort | head -120
printf '%s\n' '--- matcher references in installed Vitest packages ---'
rg -n -S 'toHaveLength' node_modules/.pnpm 2>/dev/null | head -80

Repository: stablyai/orca

Length of output: 533


Assert Set cardinality with size.

Set exposes size, not length. Therefore, toHaveLength(1) does not assert the number of unique process IDs. Use expect(new Set(parsed.map(({ pid }) => pid)).size).toBe(1).

Comment on lines +296 to +312
async close(): Promise<void> {
if (this.closing) {
return
}
this.closing = true
this.cancelIdleShutdown()
const sessionServers = [...this.sessions.values()].map((session) => session.server)
this.sessions.clear()
await Promise.allSettled(sessionServers.map((server) => server.close()))
await this.closeDownstream()
const server = this.httpServer
this.httpServer = null
this.connection = null
if (server) {
await new Promise<void>((resolve) => server.close(() => resolve()))
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Drop live sockets during close().

server.close(cb) stops new connections only. The callback runs after every open socket ends. A connected upstream client can hold a socket, for example an open GET stream or a socket that never initialized a session. In that case the promise at Line 310 stays pending and application shutdown stalls.

Call closeAllConnections() after close() so teardown always completes.

🔧 Proposed fix
     if (server) {
-      await new Promise<void>((resolve) => server.close(() => resolve()))
+      const closed = new Promise<void>((resolve) => server.close(() => resolve()))
+      server.closeAllConnections()
+      await closed
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async close(): Promise<void> {
if (this.closing) {
return
}
this.closing = true
this.cancelIdleShutdown()
const sessionServers = [...this.sessions.values()].map((session) => session.server)
this.sessions.clear()
await Promise.allSettled(sessionServers.map((server) => server.close()))
await this.closeDownstream()
const server = this.httpServer
this.httpServer = null
this.connection = null
if (server) {
await new Promise<void>((resolve) => server.close(() => resolve()))
}
}
async close(): Promise<void> {
if (this.closing) {
return
}
this.closing = true
this.cancelIdleShutdown()
const sessionServers = [...this.sessions.values()].map((session) => session.server)
this.sessions.clear()
await Promise.allSettled(sessionServers.map((server) => server.close()))
await this.closeDownstream()
const server = this.httpServer
this.httpServer = null
this.connection = null
if (server) {
const closed = new Promise<void>((resolve) => server.close(() => resolve()))
server.closeAllConnections()
await closed
}
}

@sanshengai

Copy link
Copy Markdown
Author

Closing as stale. main has moved on substantially since this branch was opened on Aug 24, and I am no longer following it. Happy to reopen a rebased, single-change PR if maintainers still want the fix.

@sanshengai sanshengai closed this Sep 11, 2026
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.

1 participant