Repository navigation
fix(agent): MCP fixes for dropped tool arguments, list_changed auto-refresh, and cached transport - #165
Open
mattapperson wants to merge 10 commits into
Open
fix(agent): MCP fixes for dropped tool arguments, list_changed auto-refresh, and cached transport#165mattapperson wants to merge 10 commits into
mattapperson wants to merge 10 commits into
Conversation
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.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/clientpeer floor from^2.0.0to^2.2.0and is aminorbump for@openrouter/agent.1. Tool arguments were silently deleted for composed schemas
Problem.
convertMcpInputSchemafalls back to a per-property conversion whenz.fromJSONSchemareturns a non-object (a rootoneOf/anyOf/allOf) or throws (if/then/else,not, a draft-07#/definitions/$ref, an external$ref, a non-ECMAScript regex). The fallback returnedz.object(shape)built from the root-levelpropertiesonly, andz.objectstrips 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{}(rootoneOf/allOf) or a partial object (rootanyOfplus 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 reachescallToolunchanged and the server decides. The converter is shared withoutputSchema, where it was stripping fields fromstructuredContent.Model-facing schema. A root that is not
type: 'object'gets nowireInputSchema, so its parameters are regenerated from this Zod object and now carryadditionalProperties: {}where they carriedfalse. 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:wrapMcpToolnever setsstrict, so it serializes asnull. A test pins both facts.Tests (
json-schema-to-zod.test.ts,wire-input-schema.test.ts). Five schemas run throughwrapMcpTooland the realexecuteTool, asserting what the fake client'scallToolreceived: rootoneOf, rootallOf, rootanyOfplus root properties,if/then, and a draft-07definitionsref with an extra key. Each case first asserts the schema really takes the fallback. Also: a wrongly-typed known root property is still rejected, anoutputSchemaon the fallback keeps its fields, and the regenerated schema for a non-object root.2.
autoRefreshOnListChangednever fired on 2026-07-28 servers over HTTPProblem.
makeClientonly registered a handler fornotifications/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-eranotifications/initialized), so the server can deliver the notification only on asubscriptions/listenstream. We never opened one, and'auto'negotiation is our default, so the default-on auto-refresh andonToolsChangedwere dead for every modern server. The existing modern-era test passed becauseInMemoryTransportlets a fake push an unsolicited notification, which a real modern HTTP server cannot do.Change. New
list-changed-subscription.ts, called fromsetToolListChangedHandlerinmcp-connection.ts.makeHandledoes only whenautoRefreshOnListChangedis on. With it off, nothing is opened. The cold path (freshConnect) and the replay path (rehydrateMCPTools) both go through that registration.tools.listChanged(the rule the SDK applies). 2025-era connections are untouched, including servers that notify without advertising the capability.createMCPTools/rehydrateMCPTools.handle.close()stops it and closes the stream. Aborting the caller'ssignalends it too.Why
client.listen()and notClientOptions.listChanged. I read both in the SDK (2.0.0 originally, re-checked on 2.4.0).ClientOptions.listChangedopens the subscription insideconnect()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 explicitlisten()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:
Behaviour to know about. Against a modern server that advertises
tools.listChanged, a handle now holds one SSE stream open untilclose(). 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). RealcreateMCPTools/rehydrateMCPTools, real SDK client, realStreamableHTTPClientTransport, against a fetch-level fake server that answerssubscriptions/listenwith 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 inconnect(). If the server later dropped SSE, the replay failed, the fallback failed the same way,createMCPToolsrejected on every call, and the entry was never rewritten, while the same call with no cache connected. Separately,createMCPToolsdid not forward the caller'stransporton a hit, so an explicittransport: 'streamableHttp'was ignored.Change (
rehydrate.ts,create-mcp-tools.ts).RehydrateMCPToolsOptionsgainstransport?: MCPTransportKind, andcreateMCPToolsforwards it on a hit (FORWARDED_REHYDRATE_KEYS).PASS_THROUGH_CREATE_KEYS), otherwise it is unpinned, so the normal ladder runs and the rewritten entry records the transport that worked.Tests (
cache-transport.test.ts, 6 tests). RealcreateMCPTools,rehydrateMCPToolsandconnect()with only the SDK faked, so the ladder under test is the real one. Covers the migration (storedsse, SSE now rejected, the warm call succeeds, the stored transport becomesstreamableHttp), the same through a directrehydrateMCPTools, the caller's pin honoured on a hit and kept through the fallback, the recorded transport still tried first when nothing is pinned, andreconnectOnExpiry: 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()awaitstransport.send()before anything observes the internal promise it rejects on. Aclose(), a signal abort, or the 60s acknowledgement timeout during that send rejects a promise no caller can reach, so thetry/catcharoundclient.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 whosetokens()does any asynchronous work holds the send open long enough that connect, readtools,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/clientis now^2.2.0inpackages/agent/package.json(peer and dev) andpackages/mcp/package.json(dependency). The lockfile is at 2.4.0; the lockfile diff is only the SDK client and itscorepackage.connect()not tearing down a transport whosestart()threw, the GET stream opened afternotifications/initialized,ClientOptions.listChangedawaiting the acknowledgement insideconnect(), its capability gate on 2025-era servers, and "no automatic re-listen". All still hold, so the bump made no comment wrong.mcp-sdk.tsloads the same four exports. No doc or error message named a version; the README install section now does.Regression tests (three, in
list-changed-subscription.test.ts): an OAuth provider with an asynchronoustokens(), then an immediateclose(), and an immediate abort, while the subscription is still being opened; and an acknowledgement timeout on a request that rejects late. Each asserts nounhandledRejectionis 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
openswallowed every failure and the loop rescheduled it. With OAuth and a rejected token, each attempt ran discovery,saveCodeVerifierandredirectToAuthorizationfrom a timer, indefinitely.A failed open that the existing
isAuthFailurerecognises (with the connection's auth and the SDK'sUnauthorizedError) 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 withmcp-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/listenrequests, 1redirectToAuthorizationand 1saveCodeVerifier.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.
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 addsannotations) is covered without a field list. Anything it cannot prove equal counts as changed.tools/list_changedand an explicithandle.refresh()behave exactly as before; the test asserts both still rebuild and write on an identical listing.makeHandleinhandle.tsgets a small edit for this (anadoptstep shared byrefresh()and the comparing re-list, and a second callback passed to the connection). It is away fromlistToolDefs.Process lifetime, bump, examples
The changeset is now
minorand 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/mcpgets its ownpatchchangeset for the dependency range.API example
The same example is in the changeset, and was type-checked against this branch. JSDoc on
transport,autoRefreshOnListChanged,onToolsChangedandclose()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.
tools.listChangedgets none. A first subscription that fails for a transient reason is not retried;refresh()still works.bearerorheadersauth, 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.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'sonUnauthorized, which from our layer would require replacing the OAuth provider with a minimalAuthProviderand losingfinishAuthand 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
mainand on this branch with the same probe:main["sse"]["streamableHttp","sse"]ssepin, rehydrated directly without credentialssse, entry staysssestreamableHttp, entry rewritten tostreamableHttpSo 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 passtransport. 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
signalis also passed to everycallTooland torefresh(). Once it aborts, re-listing fails, so auto-refresh is over regardless, which is why the subscription ends with it.isAuthStatusinmcp-connection.tssays a 403 never enters the SDK's OAuth flow. A 403 carryinginsufficient_scopedoes 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 throwsUnauthorizedError, whichisAuthFailurematches 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:
pnpm lintpnpm typecheckpnpm --filter @openrouter/agent testpnpm --filter @openrouter/mcp testpnpm verify:packagessentrux gateThe 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:
z.looseObjectback toz.objectoutputSchemacase, the regenerated-schema casewatchToolListChangedcall inwrap()cache-transport.test.ts. The sixth asserts the recorded transport is still tried firstA dry-run merge with the head of the open MCP tool annotations PR (148) has no conflicts.