Skip to content

fix(agent): MCP fixes for dropped tool arguments, list_changed auto-refresh, and cached transport - #165

Open
mattapperson wants to merge 10 commits into
mainfrom
t3/fix-mcp-args-listchanged-transport
Open

mattapperson wants to merge 10 commits into
mainfrom
t3/fix-mcp-args-listchanged-transport

Conversation

@mattapperson

@mattapperson mattapperson commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Fixes three confirmed bugs in the MCP integration (packages/agent/src/mcp). Each was found by reading the code and then reproduced by running it, and each fix has tests that fail when the fix is reverted (see Verification).

An adversarial review of the first version of this PR found two blocking problems in the new subscription code and some smaller ones. They are fixed in the last five commits and described under Review follow-up.

This PR raises the @modelcontextprotocol/client peer floor from ^2.0.0 to ^2.2.0 and is a minor bump for @openrouter/agent.

1. Tool arguments were silently deleted for composed schemas

Problem. convertMcpInputSchema falls back to a per-property conversion when z.fromJSONSchema returns a non-object (a root oneOf / anyOf / allOf) or throws (if/then/else, not, a draft-07 #/definitions/ $ref, an external $ref, a non-ECMAScript regex). The fallback returned z.object(shape) built from the root-level properties only, and z.object strips unknown keys on parse. Since #146 the model is sent the server's own schema, so it sends correct arguments, the executor parses them with this Zod schema, and the server receives {} (root oneOf / allOf) or a partial object (root anyOf plus root properties, if/then). The holistic path already kept unknown keys; only the fallback was wrong.

Change. The fallback returns z.looseObject(shape) (schema/json-schema-to-zod.ts). Root properties it knows are still validated; everything else reaches callTool unchanged and the server decides. The converter is shared with outputSchema, where it was stripping fields from structuredContent.

Model-facing schema. A root that is not type: 'object' gets no wireInputSchema, so its parameters are regenerated from this Zod object and now carry additionalProperties: {} where they carried false. That is the shape ordinary MCP tools were sent before #146 (the holistic path yields a loose object too). It would only be a problem under OpenAI-style strict mode, which MCP tools cannot opt into: wrapMcpTool never sets strict, so it serializes as null. A test pins both facts.

Tests (json-schema-to-zod.test.ts, wire-input-schema.test.ts). Five schemas run through wrapMcpTool and the real executeTool, asserting what the fake client's callTool received: root oneOf, root allOf, root anyOf plus root properties, if/then, and a draft-07 definitions ref with an extra key. Each case first asserts the schema really takes the fallback. Also: a wrongly-typed known root property is still rejected, an outputSchema on the fallback keeps its fields, and the regenerated schema for a non-object root.

2. autoRefreshOnListChanged never fired on 2026-07-28 servers over HTTP

Problem. makeClient only registered a handler for notifications/tools/list_changed. On a 2026-07-28 connection there is no session and no standalone GET stream (the transport opens that only after the 2025-era notifications/initialized), so the server can deliver the notification only on a subscriptions/listen stream. We never opened one, and 'auto' negotiation is our default, so the default-on auto-refresh and onToolsChanged were dead for every modern server. The existing modern-era test passed because InMemoryTransport lets a fake push an unsolicited notification, which a real modern HTTP server cannot do.

Change. New list-changed-subscription.ts, called from setToolListChangedHandler in mcp-connection.ts.

  • The stream is opened when a callback is registered on the connection, which makeHandle does only when autoRefreshOnListChanged is on. With it off, nothing is opened. The cold path (freshConnect) and the replay path (rehydrateMCPTools) both go through that registration.
  • Only on a modern connection whose server advertises tools.listChanged (the rule the SDK applies). 2025-era connections are untouched, including servers that notify without advertising the capability.
  • It is opened in the background. A refused subscription, or one the server never acknowledges, leaves a working handle and does not delay createMCPTools / rehydrateMCPTools.
  • handle.close() stops it and closes the stream. Aborting the caller's signal ends it too.

Why client.listen() and not ClientOptions.listChanged. I read both in the SDK (2.0.0 originally, re-checked on 2.4.0). ClientOptions.listChanged opens the subscription inside connect() and awaits the acknowledgement there, so a server that accepts the request and never acknowledges would stall every connect for the request timeout (60s). It would also need the auto-refresh flag threaded down to client construction, it only registers on 2025-era servers that advertise the capability, and it never re-listens. An explicit listen() after connect has none of those problems and keeps the one existing notification handler as the dispatch path for both eras.

When the stream ends. The SDK does not re-listen. Streams end in normal operation (a proxy idle timeout, a redeploy), and stopping there would leave auto-refresh working until the first drop and then silently dead again, so it is handled:

  • Once a subscription has been acknowledged, a lost stream is re-opened after a nominal 1s, doubling to a 60s ceiling while attempts keep failing or streams keep dying young. Each delay is jittered 50% either way. A stream that stays up 60s resets the backoff. It keeps trying for as long as the connection is open.
  • After a stream is re-established the tools are re-listed once, because a change made while it was down was never announced. If that listing equals the current one, nothing else happens: no rebuild, no cache write, no listener call.
  • A first subscription that is never acknowledged is not retried.
  • A failed open that is a credential rejection ends the watch for good.

Behaviour to know about. Against a modern server that advertises tools.listChanged, a handle now holds one SSE stream open until close(). Like any open connection it keeps a Node process alive, so a script that never closes its handle no longer exits by itself against such a server. The README says so, and every example in it and in the changeset now closes its handles.

Tests (list-changed-subscription.test.ts, 20 tests). Real createMCPTools / rehydrateMCPTools, real SDK client, real StreamableHTTPClientTransport, against a fetch-level fake server that answers subscriptions/listen with an SSE stream. protocol-era.test.ts: the modern-era dispatch tests are renamed and their comments rewritten to say they cover dispatch of an already-delivered notification, not delivery.

3. A warm cache pinned the snapshot's transport

Problem. A cold connect that fell back to SSE stores transport: 'sse'. On a cache hit both the replay (toReplayConnectOptions) and the fresh-connect fallback (toCreateOptions) took that value, and a pinned transport disables the Streamable HTTP → SSE ladder in connect(). If the server later dropped SSE, the replay failed, the fallback failed the same way, createMCPTools rejected on every call, and the entry was never rewritten, while the same call with no cache connected. Separately, createMCPTools did not forward the caller's transport on a hit, so an explicit transport: 'streamableHttp' was ignored.

Change (rehydrate.ts, create-mcp-tools.ts).

  • RehydrateMCPToolsOptions gains transport?: MCPTransportKind, and createMCPTools forwards it on a hit (FORWARDED_REHYDRATE_KEYS).
  • The replay dials the caller's transport when given, otherwise the snapshot's as a first-attempt hint.
  • The fallback uses the caller's transport when given (PASS_THROUGH_CREATE_KEYS), otherwise it is unpinned, so the normal ladder runs and the rewritten entry records the transport that worked.
  • The auth-failure and abort guards on the fallback are unchanged.

Tests (cache-transport.test.ts, 6 tests). Real createMCPTools, rehydrateMCPTools and connect() with only the SDK faked, so the ladder under test is the real one. Covers the migration (stored sse, SSE now rejected, the warm call succeeds, the stored transport becomes streamableHttp), the same through a direct rehydrateMCPTools, the caller's pin honoured on a hit and kept through the fallback, the recorded transport still tried first when nothing is pinned, and reconnectOnExpiry: false.

Review follow-up

Blocking: closing or aborting shortly after connect could crash the process

In SDK 2.0.0 and 2.1.0, listen() awaits transport.send() before anything observes the internal promise it rejects on. A close(), a signal abort, or the 60s acknowledgement timeout during that send rejects a promise no caller can reach, so the try/catch around client.listen() never sees it. Node reports an unhandled rejection and, by default, exits with code 1. It is reachable from ordinary use: an OAuth provider whose tokens() does any asynchronous work holds the send open long enough that connect, read tools, close() hits it.

SDK 2.2.0 attaches the handler before the send. As decided by the repo owner, the fix is the SDK floor:

  • @modelcontextprotocol/client is now ^2.2.0 in packages/agent/package.json (peer and dev) and packages/mcp/package.json (dependency). The lockfile is at 2.4.0; the lockfile diff is only the SDK client and its core package.
  • I checked the comments that cite SDK internals against the 2.4.0 source: the session-id negotiation skip, the response cache and its 24h ceiling, the base connect() not tearing down a transport whose start() threw, the GET stream opened after notifications/initialized, ClientOptions.listChanged awaiting the acknowledgement inside connect(), its capability gate on 2025-era servers, and "no automatic re-listen". All still hold, so the bump made no comment wrong. mcp-sdk.ts loads the same four exports. No doc or error message named a version; the README install section now does.
  • Nothing in our code can defend against the old behaviour, so there is no runtime guard. Someone who ignores the peer warning and stays on 2.0.x or 2.1.x can still hit the crash.

Regression tests (three, in list-changed-subscription.test.ts): an OAuth provider with an asynchronous tokens(), then an immediate close(), and an immediate abort, while the subscription is still being opened; and an acknowledgement timeout on a request that rejects late. Each asserts no unhandledRejection is raised. I ran them against SDK 2.0.0 installed in a temp directory: all three fail, with one unhandled rejection each, and the other 219 MCP unit tests pass. Against 2.2.0 (the floor itself) and 2.4.0, all 222 pass.

Blocking: the re-listen loop re-drove the OAuth authorization flow

open swallowed every failure and the loop rescheduled it. With OAuth and a rejected token, each attempt ran discovery, saveCodeVerifier and redirectToAuthorization from a timer, indefinitely.

A failed open that the existing isAuthFailure recognises (with the connection's auth and the SDK's UnauthorizedError) now stops the watch for good. The first run of the flow happens inside the SDK's send and cannot be prevented, so the bound is one. The predicate is passed into the subscription module rather than imported, to avoid an import cycle with mcp-connection.ts.

Test: OAuth, one acknowledged stream, then 401 on everything and the stream drops. Across eleven minutes of backoff periods there are exactly 2 subscriptions/listen requests, 1 redirectToAuthorization and 1 saveCodeVerifier.

A dropped stream turned auto-refresh into polling

Every re-established stream re-listed, rebuilt, wrote the cache and called listeners whether or not anything changed, and the backoff had no jitter.

  • On the re-subscribe path only, the re-listed definitions are compared with the current ones (tool-defs-equal.ts) and an identical listing is a no-op. The comparison is structural over the whole definition, ignoring object key order, so a field added later (PR 148 adds annotations) is covered without a field list. Anything it cannot prove equal counts as changed.
  • A genuine tools/list_changed and an explicit handle.refresh() behave exactly as before; the test asserts both still rebuild and write on an identical listing.
  • Each delay is jittered 50% either way.
  • makeHandle in handle.ts gets a small edit for this (an adopt step shared by refresh() and the comparing re-list, and a second callback passed to the connection). It is away from listToolDefs.

Process lifetime, bump, examples

The changeset is now minor and explains the peer floor. The README has a "Tool list changes" section stating the open-stream behaviour, and its caching and multi-server examples and the changeset's example close their handles. @openrouter/mcp gets its own patch changeset for the dependency range.

API example

import {
  createMCPTools,
  InMemoryMCPCacheStore,
  rehydrateMCPTools,
} from '@openrouter/agent/mcp';

const store = new InMemoryMCPCacheStore();

// `transport` on a cache hit. was: ignored, the entry's transport was dialled.
const mcp = await createMCPTools({ url, auth, transport: 'streamableHttp', cache: { store } });

// was: never called on a 2026-07-28 server. now: called when the tool set changes.
mcp.onToolsChanged((tools) => console.log(tools.length));
// opt out (no stream is opened): createMCPTools({ url, autoRefreshOnListChanged: false })

// new: `transport` on rehydrateMCPTools overrides the one in the snapshot.
const snapshot = await mcp.serialize();
const replayed = await rehydrateMCPTools({ snapshot, auth, transport: 'streamableHttp' });

// now required to let the process exit: each handle may hold a stream open.
await Promise.all([mcp.close(), replayed.close()]);

The same example is in the changeset, and was type-checked against this branch. JSDoc on transport, autoRefreshOnListChanged, onToolsChanged and close() and the MCP README are updated to match.

Not done, and why

Bug 1. The fallback does not validate arguments declared in composition branches and does not honour a root additionalProperties: false. It passes unknown keys through and leaves validation to the server.

Bug 2.

  • A modern server that would honour the subscription but does not advertise tools.listChanged gets none. A first subscription that fails for a transient reason is not retried; refresh() still works.
  • Once the watch has stopped on rejected credentials, auto-refresh stays off for that handle.
  • With bearer or headers auth, a 401 is not an auth failure by the existing predicate (a retry has no side effects), so the watch keeps retrying at the 60s ceiling with a token that will not start working.
  • A modern connection over the deprecated SSE transport is not tested.
  • Known limitation, refresh-token races. The reviewer suspected a background re-listen racing a foreground call at token expiry could spend a rotating refresh token twice. I confirmed it with a probe on SDK 2.4.0, and it is not specific to the subscription: the SDK does not single-flight token refresh, so any two concurrent requests on one connection can do it. Two concurrent foreground calls at expiry, with no subscription, used the refresh token twice; the second got invalid_grant, the SDK invalidated the stored tokens and started a new authorization (one redirect), and one of the two calls rejected. A background re-listen racing one foreground call gave the same result. A re-listen alone refreshed once with no redirect. Fixing it means serialising the SDK's onUnauthorized, which from our layer would require replacing the OAuth provider with a minimal AuthProvider and losing finishAuth and step-up handling, so it is not done here. The subscription adds one more request that can take part; the credential-rejection stop above bounds what it does afterwards.

Bug 3: the recorded transport is not tried first on the paths that skip the replay. With no credentials, expired tokens or a stale snapshot, the fresh connect is now unpinned. I measured these on main and on this branch with the same probe:

Case main This branch
Unauthenticated SSE-only server through a cache, every warm call ["sse"] ["streamableHttp","sse"]
Snapshot written under an explicit sse pin, rehydrated directly without credentials connects over sse, entry stays sse connects over streamableHttp, entry rewritten to streamableHttp
Dead server, warm call 4 attempts 6 attempts

So an SSE-only server pays one failed Streamable HTTP attempt per call on those paths, a cold-connect pin is not carried by the snapshot, and a dead server takes longer to fail. Trying the recorded transport first and then the other would fix the first and third, but needs a "preferred first" mode in connect(); this PR does not expand to that. A caller who needs the old behaviour can pass transport. Also, a caller's pin on a hit is not written back to the stored entry, because a successful replay does not write.

Noticed nearby, not touched

  • The connect signal is also passed to every callTool and to refresh(). Once it aborts, re-listing fails, so auto-refresh is over regardless, which is why the subscription ends with it.
  • A snapshot without credentials is never replayed (every call fresh-connects), so the transport hint does not apply to unauthenticated servers.
  • The comment on isAuthStatus in mcp-connection.ts says a 403 never enters the SDK's OAuth flow. A 403 carrying insufficient_scope does run step-up authorization, in 2.0.0 and in 2.4.0 alike. The behaviour is still right, because when step-up does not end authorized the SDK throws UnauthorizedError, which isAuthFailure matches unconditionally (so the subscription watch stops there too). Only the comment is imprecise, and it predates this PR, so I left it.

Verification

Run locally on the head commit, with SDK 2.4.0 from the lockfile:

Command Result
pnpm lint pass
pnpm typecheck pass
pnpm --filter @openrouter/agent test 114 files, 1318 tests pass. Coverage 86.4% statements, 78.1% branches, 91.7% functions, 86.4% lines (floors 82 / 74 / 88 / 82)
pnpm --filter @openrouter/mcp test 5 files, 12 tests pass
pnpm verify:packages pass
sentrux gate no degradation

The MCP unit folder (21 files, 222 tests) was also run against other SDK versions by aliasing the import to a copy installed in a temp directory: 222 pass on 2.2.0, and on 2.0.0 the three opening-phase tests fail and the other 219 pass.

Each change was reverted in turn, the tests rerun, and the change restored:

Reverted Tests that then fail
z.looseObject back to z.object 7: the five argument cases, the outputSchema case, the regenerated-schema case
the watchToolListChanged call in wrap() every test that needs a subscription; the guards that no subscription is opened, and the 2025-era cases, still pass
the four bug 3 edits 5 of 6 in cache-transport.test.ts. The sixth asserts the recorded transport is still tried first
SDK 2.2.0+ (run on 2.0.0) the three opening-phase tests
the credential-rejection stop the OAuth redirect-count test
skip-when-unchanged the "only re-lists" test
jitter the jitter-bounds test

A dry-run merge with the head of the open MCP tool annotations PR (148) has no conflicts.

When z.fromJSONSchema cannot convert a tool's inputSchema as a whole (a root
oneOf/anyOf/allOf, if/then/else, not, a draft-07 #/definitions/ $ref), the
per-property fallback built z.object(shape) from the root-level properties
only. z.object strips unknown keys on parse, so arguments declared in a
composition branch were deleted before callTool: the model, which is sent the
server's own schema, sent valid arguments and the server received {} or a
partial object.

The fallback now builds a loose object, so unknown keys reach the server
unchanged and the server stays the arbiter. The same converter handles
outputSchema, where it was stripping fields from structuredContent.

A root that is not type: 'object' has no wire schema, so its model-facing
parameters are regenerated from this Zod object and now say
additionalProperties: {} rather than false. MCP tools never set strict, so
that does not conflict with OpenAI-style strict mode; a test pins both.
autoRefreshOnListChanged is on by default but never fired against a
2026-07-28 server over HTTP. That revision has no session and no standalone
GET stream (the transport only opens one after the 2025-era
notifications/initialized), so the server can deliver
notifications/tools/list_changed only on a subscriptions/listen stream. We
registered a notification handler and never opened one, and 'auto' negotiation
is our default, so the feature was dead for every modern server.

The connection now opens that stream when a list_changed callback is
registered, which the handle does only when auto-refresh is enabled, and only
on a modern connection whose server advertises tools.listChanged. It is
opened in the background with an explicit client.listen() rather than through
ClientOptions.listChanged, because the latter awaits the acknowledgement
inside connect(): a server that never acknowledges would stall
createMCPTools() for a full request timeout. A refused or unanswered
subscription leaves a working handle. Both the cold path and the snapshot
replay path go through the same registration.

The SDK does not re-listen when a stream ends, so once a subscription has
been acknowledged a lost stream is re-opened with capped exponential backoff
(1s doubling to 60s), and the tools are re-listed once after it is back since
changes made in between were never announced. close() and the caller's signal
both end it. 2025-era connections are untouched, including servers that send
the notification without advertising the capability.

The existing modern-era dispatch tests passed only because InMemoryTransport
lets a fake push an unsolicited notification. They are re-scoped to say they
cover dispatch, and delivery is now tested over StreamableHTTPClientTransport
against a fetch-level fake server.
A cold connect that fell back to SSE stores transport: 'sse'. On every later
cache hit the replay dialled SSE only, and so did the fresh-connect fallback,
because both took the snapshot's transport and a pinned transport disables
the Streamable HTTP -> SSE ladder in connect(). A server that later dropped
SSE was unreachable through the cache on every call, the entry never
rewritten, while the same call without a cache connected. Separately,
createMCPTools did not forward the caller's transport on a hit, so an
explicit transport: 'streamableHttp' was ignored in favour of the snapshot's.

The snapshot's transport is now a first-attempt hint. The replay still dials
it, since it is what worked last time. The fallback is left unpinned so the
normal ladder runs, and the rewritten entry records the transport that
worked. RehydrateMCPToolsOptions gains transport, createMCPTools forwards it
on a hit, and when given it pins both the replay and the fallback. The
auth-failure and abort guards on the fallback are unchanged.

With reconnectOnExpiry: false there is no fallback, so the recorded transport
is the only one tried unless the caller names one; a test documents that.
… exactly

toMatchObject accepts false where {} is expected, so the assertion passed with the fallback fix reverted. Assert the value on its own.

@devin-ai-integration devin-ai-integration 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

SDK 2.0.0 and 2.1.0 can end the process when a tools/list_changed
subscription is torn down while it is still being opened. Their listen()
awaits transport.send() before anything observes the internal promise it
rejects on, so a close, a signal abort or the 60s acknowledgement timeout
during that send rejects a promise no caller can reach. Node reports an
unhandled rejection and, by default, exits with code 1. Nothing in this
package can catch it: it is a different promise from the one listen()
returns.

It is reachable from ordinary use. An OAuth provider whose tokens() does
any asynchronous work holds the send open long enough that connecting,
reading the tools and closing straight away hits it; so does a fetch
wrapper that rejects late after an abort.

SDK 2.2.0 attaches the handler before the send. Raise the floor to ^2.2.0
in the agent's peer and dev ranges and in @openrouter/mcp's dependency, and
move the lockfile to 2.4.0. Regression tests follow in the next commit.
…edentials

The re-listen loop swallowed every failed open and rescheduled it. With an
OAuth provider and a token the server no longer accepts, each attempt ran
the SDK's authorization flow from a timer: discovery, saveCodeVerifier and
redirectToAuthorization, sixteen times in eleven minutes and then about
once a minute until close(). That is the duplicated side effect connect()
and rehydrateMCPTools already refuse to cause.

A failed open that isAuthFailure() recognises, with the connection's auth
and the SDK's UnauthorizedError, now stops the watch for good. The first
run of the flow happens inside the SDK's send and cannot be prevented, so
the bound is one redirect and one PKCE verifier. Other failures still back
off and retry as before.

Also adds the regression tests for the SDK floor raised in the previous
commit: an OAuth provider with an asynchronous tokens(), then an immediate
close() and an immediate abort while the subscription is still being
opened, and an acknowledgement timeout on a request that rejects late.
Each asserts that no unhandledRejection is raised. All three fail on SDK
2.0.0 and pass on 2.2.0 and 2.4.0.
Every re-established stream re-listed, rebuilt the tools, wrote the cache
and called onToolsChanged listeners, whether or not anything had changed.
Behind a proxy with a 60s idle timeout that is 59 extra tools/list calls,
cache writes and listener calls an hour for a tool set that never moved.
The backoff also had no jitter, so one server redeploy brought every client
back, and re-listing, in the same second.

On the re-subscribe path only, the re-listed definitions are now compared
with the current ones and an identical listing is a no-op: no rebuild, no
cache write, no listener call. The comparison is structural over the whole
definition rather than a list of fields, so a field added to McpToolDef
later is covered. A genuine tools/list_changed notification and an explicit
refresh() rebuild, write and (for the notification) announce exactly as
before. The connection takes a second, optional callback for the
re-subscribe case; makeHandle passes the comparing one.

Each re-listen delay is now spread 50% either side of its nominal value.
…y example

Against a 2026-07-28 server that advertises tools.listChanged, a handle now
keeps one subscriptions/listen stream open until close(), which keeps a
Node process alive. The README gets a "Tool list changes" section saying
so, its caching and multi-server examples close their handles, and the
install section names the SDK floor. JSDoc on autoRefreshOnListChanged,
onToolsChanged and close() matches the behaviour.

The changeset moves to minor: default-on behaviour changed, a public option
was added, and the peer floor is now @modelcontextprotocol/client ^2.2.0,
which it explains. Its example closes its handles. @openrouter/mcp gets its
own patch changeset for the dependency range.
The OAuth discovery, 401 and hung-request cases pushed the fake server's fetch past the structural gate's cyclomatic-complexity ceiling (sentrux gate counts test files). Route to module-level handlers instead; behaviour is unchanged, and the fails-without-fix checks were repeated against it.

This branch has not been deployed

No deployments
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