Added the MCP protocol 2024-11-05 HTTP+SSE transport so type:"sse" opens the endpoint stream, posts JSON-RPC to the announced endpoint, and correlates streamed responses.
Fixes#3710
* feat: auto-reconnect MCP servers on connection loss
When an HTTP SSE stream drops (server restart, network interruption),
the transport fires onClose, and the manager proactively reconnects
with retry backoff (500ms, 1s, 2s, 4s). Tools are kept in the registry
during reconnection so they remain selected and available to the agent.
If proactive reconnection fails, stale tools stay registered. When the
agent calls one, the tool bridge detects the retriable connection error
(ECONNREFUSED, ECONNRESET, stale session 404/502/503, etc.), triggers
reconnectServer on the manager, and retries the call once on the fresh
connection. Concurrent reconnect attempts for the same server are deduped.
connectToServer now always installs a default onRequest handler for ping
and roots/list (using getProjectDir()), so all connections -- including
short-lived test/probe ones -- properly respond to server-initiated
requests during initialization.
Post-connection setup (resources, prompts, subscriptions) is extracted
into a shared #loadServerResourcesAndPrompts method used by both initial
connection and reconnection paths.
Add /mcp reconnect <name> command for manual recovery after extended
outages where both proactive and reactive reconnection have failed.
* docs: add changelog entry for MCP auto-reconnect
* fix: address P1 review findings in MCP reconnection
- Save server configs before connection attempt so deferred tools can
reconnect even when the initial connection timed out (P1-1)
- Make waitForConnection() and getConnectionStatus() aware of in-flight
reconnections so callers wait instead of failing immediately (P1-2)
- Add epoch counter incremented on disconnectAll() and checked in
connectAndWireServer() to invalidate stale reconnect attempts that
outlive a manager reset/reload (P1-3)
- Skip servers with pending reconnections in connectServers() to prevent
parallel connection attempts for the same server
* fix: deferred tool reconnect and non-blocking transport teardown
- DeferredMCPTool.execute now reconnects when getConnection() fails
("MCP server not connected"), not only on network errors from
callTool. Servers that missed the startup window can now be woken
by the first tool call against their cached tools. (P1-4)
- #doReconnect fire-and-forgets the old transport close instead of
awaiting it. HttpTransport.close() sends a DELETE with 30s timeout;
blocking here delayed the first reconnect attempt by that amount
on every server restart. (P1-5)
* fix: abort-aware reconnect waits and preserve tool selection on reconnect
- Wrap all reconnect() awaits with withAbort(signal) so user
cancellation (Esc) interrupts the reconnect backoff loop instead
of blocking for up to 7.5s. Applies to MCPTool (1 site) and
DeferredMCPTool (2 sites). (P2-1)
- Remove activateDiscoveredMCPTools call from /mcp reconnect handler.
refreshMCPTools already preserves the user's prior MCP tool
selection; the extra activation was silently opting into all
server tools including ones the user had not enabled. (P2-2)
* fix: rebind MCPTool connection after reconnect, add stdio retriable error
- MCPTool.connection is now mutable; after a successful reconnect retry,
this.connection is rebound to the fresh connection so subsequent calls
on the same instance (e.g. batched tool calls) use it instead of
triggering another reconnect cycle. (P2-3)
- Add "Transport closed" to RETRIABLE_PATTERNS. StdioTransport rejects
pending requests with this message when the subprocess dies, which
should trigger the reconnect path just like HTTP transport errors. (P2-4)
---------
Co-authored-by: Miroslav Drbal <miroslav.drbal@gendigital.com>
Co-authored-by: Can Bölük <can1357@users.noreply.github.com>
* feat(mcp): implement roots/list and server-to-client request handling
Add support for MCP server-to-client JSON-RPC requests across both
stdio and HTTP transports, enabling servers to query client capabilities
such as roots/list during initialization.
Transport layer (types.ts, stdio.ts, http.ts):
- Add onRequest callback to MCPTransport interface for server-initiated
requests; add toJsonRpcError helper for error code propagation
- Classify incoming messages by checking method+id (request), id-only
(response), method-only (notification); guard against id:null per
JSON-RPC 2.0 spec
- StdioTransport: detect server requests in #handleMessage, respond via
#sendResponse writing JSON-RPC response to subprocess stdin
- HttpTransport: detect server requests via #dispatchSSEMessage across
all SSE streams (dedicated listener, POST response drain, notify
piggybacking), respond via #sendServerResponse POST with proper
Accept header and session ID
- Refactor startSSEListener to resolve once SSE GET connects (not when
stream ends), enabling await before notifications/initialized; reset
#sseConnection via .finally() for reconnection after transient failure
- #parseSSEResponse continues reading after capturing the primary
response to drain piggybacked server requests/notifications; clears
timeout after capture so drain phase is unbounded
- notify() reads text/event-stream response bodies for piggybacked
messages; cancels non-SSE response bodies to release connections
- #sendServerResponse includes AbortSignal.timeout and cancels response
body; fire-and-forget handlers wrapped in try/catch to prevent
unhandled rejections
Client wiring (client.ts):
- Add onRequest to connectToServer options, wire to transport before
initialization
- Add awaitable onInitialized hook in initializeConnection, called
between initialize response (which sets session ID) and initialized
notification, so SSE stream is open when server sends roots/list
- Pass only signal to transport.request (not full options object)
- Hoist transport ref to outer scope; close on timeout/abort to prevent
orphaned transports when SSE GET hangs
Manager (manager.ts):
- Wire onRequest handler in connectServers for all MCP connections
- Handle roots/list by returning project CWD as file:// URI via
pathToFileURL; return -32601 for unsupported methods
Tests (mcp-roots-list.test.ts):
- toJsonRpcError: code extraction, defaults, non-Error values
- Message classification spec tests: request/response/notification/
unknown dispatch, id:null and id:0 edge cases
- Roots response shape: file:// URI generation, Windows paths, spaces
* fix(mcp): return SSE response immediately instead of blocking on stream drain
The #parseSSEResponse loop continued iterating the SSE stream after
capturing the response for the expected request ID. Since clearTimeout
was called after capture, a server that holds the SSE stream open for
follow-up events (permitted by Streamable HTTP) would block the
request() call indefinitely.
Return the result as soon as it's captured and drain remaining
messages in a detached background task via #readSSEStream, which
already handles dispatch and error swallowing.
* fix(mcp): handle batched JSON-RPC messages in both transports
JSON-RPC 2.0 section 6 allows sending an array of request/notification
objects as a batch. If a server sent a batch, the message classifier
in both transports would fail the 'method in message' check on the
array object and silently drop all contained messages.
Add an Array.isArray guard at the top of #handleMessage (stdio) and
#dispatchSSEMessage (http) that recurses into each element. Defensive
measure — no known MCP server sends batches today, but the guard is
cheap and correct per the JSON-RPC spec.
* fix(mcp): address second Codex review round
- http: break from SSE loop before starting background drain to avoid
ReadableStream locked error (the for-await iterator still holds the
reader when #drainSSEBackground was called inline)
- types: toJsonRpcError now accepts plain { code, message } objects,
not just Error instances, so onRequest handlers can throw structured
JSON-RPC errors without wrapping in Error
- test: relax Windows path name assertion to toBeTruthy since
path.basename is platform-dependent for backslash paths; add tests
for plain-object toJsonRpcError
* fix(mcp): address third Codex review round
- parseSSEResponse: flatten JSON-RPC batch arrays before checking for
the expected response, so a server that batches the primary response
with piggybacked requests/notifications in a single SSE event still
has the response extracted correctly
- sendServerResponse: retry once on 401/403 via onAuthError, matching
the auth-refresh logic in #executeRequest; prevents server-initiated
request replies from failing after token expiry on long-lived SSE
sessions
---------
Co-authored-by: Miroslav Drbal <miroslav.drbal@gendigital.com>
* feat(mcp): resource notifications, subscriptions, and read_resource builtin tool
- Add MCP resource subscription lifecycle (subscribe/unsubscribe on connect/disconnect)
- Wire mcp.notifications setting with live toggle support
- Add debounced followUp injection for resource change notifications
- Add global read_resource builtin tool with server resolution by URI/template scheme
- Add MCP prompt commands (buildMCPPromptCommands) with array content support
- Add server instructions injection into system prompt with attribution
- Add mcp.notificationDebounceMs configurable setting
Client (client.ts):
listResources, listResourceTemplates, readResource with pagination
subscribeToResources, unsubscribeFromResources
listPrompts, getPrompt, serverSupportsPrompts
serverSupportsResources, serverSupportsResourceSubscriptions
Manager (manager.ts):
Notification dispatch with subscribed-URI guard
Concurrent refresh deduplication via pending promise map
setNotificationsEnabled with subscribe/unsubscribe toggle
Tests:
client-resources.test.ts (31 tests)
client-prompts.test.ts (20 tests)
mcp-read-resource.test.ts (13 tests)
* fix(mcp): address PR review - eager prompt init and stale subscription cleanup
P1: Make setOnPromptsChanged eagerly fire for servers that already
have prompts loaded. The callback is registered after MCP discovery
has already loaded prompts and fired the hook, so without this the
handler is never called on the common startup path. The fix is in
the manager itself (not the caller), eliminating the race condition
regardless of when the callback is wired.
P2: Unsubscribe removed resource URIs on resource refresh.
refreshServerResources was subscribing to the new URI set and
overwriting #subscribedResources without unsubscribing URIs that
were previously subscribed but no longer present, leaving stale
subscriptions active on the server.
* fix(mcp): add resources and prompts to /mcp help text and subcommand completions
* feat(mcp): add /mcp notifications command
Shows per-server notification capabilities with subscription state:
- Lists supported notification types (tools/list_changed, resources/list_changed,
prompts/list_changed) with check marks
- Shows resources/subscribe status with active subscription count
- Lists subscribed URIs with green ticks when notifications are enabled
- Displays overall enabled/disabled state (mcp.notifications setting)
* fix(mcp): address PR review comments on race conditions and stale state
- Await subscribe/unsubscribe in refreshServerResources so the refresh
promise doesn't resolve before subscriptions are settled, preventing
a second refresh from racing and overwriting tracking state (P2 #3)
- Guard setNotificationsEnabled subscribe .then() against a disable
that happens while the subscribe request is in-flight (P2 #5)
- Re-check mcp.notifications setting inside debounce setTimeout
callback so toggling off mid-window actually suppresses the
follow-up message (P2 #4)
- Fire onToolsChanged and onPromptsChanged callbacks in
disconnectServer so stale slash commands and tool registrations
are cleaned up when a server is removed (P2 #2)
---------
Co-authored-by: Miroslav Drbal <miroslav.drbal@gendigital.com>
- Added abort signal support to MCP server connection and tool listing operations, enabling cancellation via Escape key during testing.
- Enhanced MCP connection timeout handling with improved abort signal integration in the withTimeout function to prevent race conditions.
- Improved MCP test command UI to display '(esc to cancel)' indicator and handle cancellation gracefully.
- Updated HTTP transport session termination to include timeout mechanism preventing indefinite hangs.
- Fixed MCP test command cleanup to prevent resource leaks when operations are cancelled or aborted.
- Added MCPRequestOptions interface with signal property for request cancellation via AbortSignal.
- Added abort signal support to MCP tool execution enabling request cancellation via Escape-to-interrupt or other abort mechanisms.
- Enhanced MCP request handling with abort signal propagation through HTTP, SSE, and stdio transports with proper cleanup.
- Improved stdio transport request handling to use Promise.withResolvers for cleaner async flow and better abort signal integration.
- Updated HTTP transport to combine operation abort signals with timeout signals using AbortSignal.any() for unified cancellation.
- Modified SSE response parsing to support abort signals and distinguish between timeout and user-initiated cancellation.
- Removed Prettier configuration files (.prettierignore and .prettierrc) and migrated formatting to Biome.
- Updated Biome configuration from version 2.3.11 to 2.3.12 and changed arrowParentheses rule from 'always' to 'asNeeded'.
- Pinned @biomejs/biome dependency to exact version 2.3.12 in package.json and bun.lock.
- Applied consistent arrow function formatting across 489 files by removing unnecessary parentheses around single parameters.
- Removed blank lines after comment blocks and reorganized imports for consistency across the codebase.