Repository navigation
fix(mcp-adapters): report silent failures and correct stale contracts - #11663
Merged
Baihao Wang (byhow) merged 11 commits intoSep 23, 2026
Merged
Baihao Wang (byhow) merged 11 commits into
Baihao Wang (byhow) merged 11 commits into
Conversation
🦋 Changeset detectedLatest commit: 9ab30b8 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Baihao Wang (byhow)
force-pushed
the
codex/mcp-subscription-lifecycle
branch
from
September 17, 2026 16:10
48ba868 to
de76aed
Compare
Baihao Wang (byhow)
force-pushed
the
codex/mcp-subscription-lifecycle
branch
2 times, most recently
from
September 17, 2026 16:19
594a2e7 to
7d05b94
Compare
Hunter Lovell (hntrl)
force-pushed
the
codex/mcp-subscription-lifecycle
branch
from
September 23, 2026 01:23
b78dd1d to
9655fd4
Compare
Hunter Lovell (hntrl)
previously approved these changes
Sep 23, 2026
Baihao Wang (byhow)
force-pushed
the
codex/mcp-subscription-lifecycle
branch
from
September 23, 2026 14:58
8dd4b2e to
2db6117
Compare
Background reconnection swallowed every attempt in a bare catch and returned with no signal when `maxAttempts` ran out, so a server that never came back produced nothing — no log, no handler call. Report an exhausted budget through `onConnectionError`. It deliberately does not throw: reconnection runs detached, so there is no caller to throw at. Correct two contracts that no longer matched the code. `onProgress` named a debug logger the package removed; failures are ignored so an observer cannot fail a tool call that already completed. The `maxElicitationRounds` and `logLevel` errors said `mode: modern` where the schema also accepts `auto`, which is the default. Document elicitation and the error surface in the README, which covered neither, and fix its negotiation description for SSE.
The elicitation and error-handling prose belongs in langchain-ai/docs, where this package's reference content lives: #11605 removed `docs/client-reference.md` on exactly those grounds, and the README has linked to the docs site nowhere since. Replace the two sections with the `**Documentation**:` pointer the sibling packages carry, and drop the README claims from the changeset. The prose itself goes up as a separate PR against langchain-ai/docs.
`#createSSETransport` rebuilt the stream's request in its own
`eventSourceInit.fetch`: it re-read the token off the `authProvider`, reapplied
the configured headers and set `Accept: text/event-stream`. SDK 1 needed that,
because supplying that fetch replaced the transport's own. SDK 2 wraps it
instead -- `_startOrAuth` builds `_commonHeaders()` and hands them to the
caller's fetch -- and its `adaptOAuthProvider().token()` is the same
`(await provider.tokens())?.access_token` the adapter was calling. So the block
recomputed, byte for byte, what it had already been given. Verified against a
recording server before removing it.
Removing it exposed a defect the block had been hiding on SSE alone.
`mergeHeaders` lowercases every name, while a transport builds its request as
`{ Authorization, ...ours }` -- a plain-object spread, so `authorization`
survives as a second key and `new Headers()` joins the two values. An
`Authorization` configured next to an `authProvider` therefore went out as
`Bearer <provider>, Bearer <configured>`. Streamable HTTP has always sent that;
SSE only started to once its hand-rolled `set()` was gone.
Spell the names the SDK spells itself so the spread replaces rather than
appends, which is what configuring both asks for, and cover both transports
with a test that drives a real transport against a recording server. Removing
the fix makes both cases fail with the joined header.
…receives `should process valid SSE connection config` built its expectation with `Object.fromEntries(new Headers(...))`, which lowercases, and so encoded the spelling the previous commit deliberately stopped producing. State the header literally instead: the capital `Authorization` is the point of the change, not an artifact of how the expectation was constructed.
…rates `createClient` is overloaded per transport, so the `"sse" | "http"` union an `it.each` table yields matches no overload. Branch on the literal at the call so each arm passes a narrowed one.
Nine changesets accumulated across the stack, one per PR, because each was written when that PR was the unit of work. They are not the unit a reader gets: changesets concatenates every file for a package under one version heading, so this release would have published 182 lines in nine voices, with negotiation described twice and the same options introduced in three places. Replace them with one, ordered the way someone upgrading reads it -- what breaks, then negotiation, elicitation, results, interactions, fixes. 92 lines. The aggregate is unchanged. `changeset status` reports the same single major bump of `@langchain/mcp-adapters` before and after, and a full `changeset version` run renders 2.0.0 from this file alone, touching no other package. Nothing was dropped silently: every API name the nine mentioned is diffed against the one. That recovered `initializeConnections`, `setLoggingLevel`, `automaticSSEFallback`, `onProgress`, `afterToolCall`, `beforeToolCall` and `readResource()` across two passes. Four names are deliberately gone -- `_resolveNonCompleteResult` and `eventSourceInit.fetch` are internal seams, and `McpServer`/`Accept` belonged to an example fix and to a behaviour-neutral SSE cleanup, none of which a release note owes its reader.
The consolidated changeset still sold the durable design: a per-round task cache, one budget spanning server questions and re-asks, and re-asking on an invalid answer. All three were removed when elicitation moved onto the SDK's public input-required path, so the release note described behaviour that no longer exists. It now states the opt-in (`elicitation: true`, replacing the `maxElicitationRounds` budget), the replay contract and its O(N^2) request cost, the `questionId` that binds a resume to the question and effective arguments it was written for, and that a resume is parsed as a whole rather than re-asked. `onCancelled` moves from a fixed behaviour to a removal, since the SDK exposes no seam that observes cancellation without displacing its own dispatch.
…collides
Answering hntrl's "why do we need this": a transport builds its request
headers as `new Headers({ Authorization, ...ours })` — a case-sensitive spread
over a case-insensitive namespace. `mergeHeaders` lowercases every key, so
ours survives as a second entry and the `Headers` constructor appends. Against
a real transport and a recording server, an `Authorization` configured beside
an `authProvider` went out as `Bearer <provider>, Bearer <ours>` on both
transports; with the fix, `Bearer <ours>`.
Half the map was doing nothing. Input to it is always already lower case, so
mapping `mcp-protocol-version` to itself was an identity lookup. It is gone,
along with the implication that the list needs a new entry per header: the SDK
spells every header it sets in lower case except `Authorization`, and a
lower-case name already replaces cleanly. `mcp-session-id` needs nothing. The
comment states that rule now, and names the case that would actually break it
— a future capitalised SDK header.
Deferring to the caller's own spelling instead was the obvious simpler fix and
it does not work: it only helps a caller who happens to type `Authorization`,
leaving `authorization` and `AUTHORIZATION` joined. Passing a `Headers`
instance is worse still, since the SDK's `normalizeHeaders` lowercases it and
guarantees the collision.
The test asserted one spelling, which proved the fix agreed with `mergeHeaders`
rather than that it canonicalises. It now runs every spelling across both
transports; removing the canonicalisation fails the four that differ from the
SDK's and leaves the two that already matched passing.
…SSE forks
Header case was being corrected at the transport, after `mergeHeaders` had
lower-cased it — a round trip, and an incomplete one. The connection schema is
where headers are actually created, so `sdkHeaderCase` is a transform on that
one field now, and `matchSdkHeaderCase` is gone. Everything the adapter holds
is spelled the SDK's way from the moment it is parsed.
Correcting at the producer instead was the obvious move and it does not work:
`client.ts` reaches `createClient` with a raw resolved connection whose headers
never pass through `mergeHeaders`. `mergeHeaders` still respells, because a
merge produces headers that never saw the schema.
Why any of it is needed: a transport builds its own request headers as
`new Headers({ Authorization, ...ours })`, a case-sensitive spread over a
case-insensitive namespace. A differently-cased key of ours survives as a
second entry and `Headers` appends, so an `Authorization` configured beside an
`authProvider` went to the wire as `Bearer <provider>, Bearer <ours>`.
`Authorization` is the only name this can happen to — the SDK spells every
other header it sets in lower case, where any case of ours already replaces.
The old map's `mcp-protocol-version` entry was an identity lookup doing
nothing.
`fork()` now merges on both transports. SSE replaced the whole set, so forking
an SSE connection to add one header silently dropped its credentials, while
HTTP kept them. `main` replaced on both; the split arrived with the HTTP-only
`mergeHeaders` in a00eff4.
The test built its connection by hand with `as never`, so the schema never ran
on it — it proved the transport did the work, which is no longer where the
work happens. It parses through `connectionSchema` now, which is what
production does, and still fails on every spelling that differs from the SDK's
when the transform is removed.
…pped #11643 merged client.comprehensive.test.ts into client.basic.test.ts, so this branch's edits to that file had nowhere to land when it was rebased, and one edit to connection.test.ts came back stale. Unit tests failed on CI as a result. Restore them as this branch first wrote them: - The maxAttempts test waits with `vi.waitFor` and a 10ms delay instead of a fixed 100ms sleep, which this branch's longer default delay outlasts. Its two unconsumed `connect` rejections were leaking into the next two tests. - Bring back the test that an exhausted reconnection budget reaches `onConnectionError`, which the rebase lost entirely. - The SSE connection test no longer drives `eventSourceInit.fetch`, which this branch removed; `transport.headers.test.ts` covers the same intent against a live server.
…notes The release notes still described two things the code no longer does: - A `questionId` binding the resume to the question the human saw. It was removed with the question comparison in #11643, matching the Python adapter. - A pause that "cannot outlive a `requestState` lifetime". It is the reverse: resume replays the call and uses the continuation the replay returns, so the one issued before the pause may expire while the graph waits. Also record that SSE now rejects `elicitation` and `logLevel`, which only a modern server can serve, since an upgrading config can hit that error.
Baihao Wang (byhow)
force-pushed
the
codex/mcp-subscription-lifecycle
branch
from
September 23, 2026 17:42
2db6117 to
9ab30b8
Compare
Hunter Lovell (hntrl)
approved these changes
Sep 23, 2026
Baihao Wang (byhow)
added a commit
that referenced
this pull request
Sep 23, 2026
) Modern MCP elicitation should survive loss of the agent process without recreating the server conversation or applying saved consent to a different question. - Checkpoint each completed MCP round as plain LangGraph task data, then interrupt outside the task. Resume retrieves the saved question and continuation instead of repeating earlier requests. - Bind answers to the graph interrupt and question attempt. Reconstruct the original question/correction allowance from persisted rounds and answers; reject changed effective arguments and stale answers. - Keep clients and credentials runtime-only. Preserve legacy callbacks, SDK validation, hook context, and the approved lower-stack architecture. Hook-header overrides remain available for ordinary calls, but durable elicitation requires stable configured authentication. - Document the recovery boundary: rebuild compatible tools/graph against the same persistent thread and logical server/auth scope. Server continuation expiry remains independent; expiry fails instead of silently restarting with old consent. Remote effects still need idempotency across checkpoint crash windows. - Public interrupts omit continuation state; internal graph streams and traces can contain protocol data and retain normal application access controls. Python's [current modern elicitation implementation](https://github.com/langchain-ai/langchain/blob/fbac0b2d0c2550a9ab0a0adad64a789a76fada78/libs/langchain_v1/langchain/mcp/elicitation.py#L312-L379) provides the modern-only/manual-round reference, but deliberately reissues calls on resume. This implementation instead records completed wire rounds, including across host-process replacement and simulated multi-day pauses. Stacks on #11642; lower branches are unchanged. Lifecycle follow-ups remain in #11663, and tool-retry interrupt passthrough remains in #11649. Made by [Open SWE](https://github.com/langchain-ai/open-swe) · [view thread](https://openswe.vercel.app/agents/35b211f9-e362-54f7-9f19-7ba150daf663) · openai:gpt-6-astra (high) --------- Co-authored-by: open-swe[bot] <[email protected]>
4 tasks done
Hunter Lovell (hntrl)
added a commit
that referenced
this pull request
Sep 27, 2026
… retryable (#11720) This is the first of two stacked PRs adding OAuth to `@langchain/mcp-adapters` 2.0. It does four things: - moves the adapter to MCP SDK 2.1; - accepts the SDK's token-based `AuthProvider`; - labels authentication failures correctly; - lets servers that failed on authentication be retried. It also documents these changes in the README. The follow-up PR, stacked on this one, adds `finishAuth` to complete an OAuth redirect. Merging this releases nothing. `@langchain/mcp-adapters` is still in the changesets `ignore` list (#11715). **966 changed lines:** implementation 143, tests 738 (of which the OAuth server fixture is 320), README 18, lockfile 67. ## MCP SDK 2.1 replaces the header workaround In SDK 2.0, a configured `Authorization` header and the provider's token were sent joined into one value, `Bearer <provider>, Bearer <configured>`. #11663 worked around this with `getSdkHeaderCase`. SDK 2.1.0 (modelcontextprotocol/typescript-sdk#2475) fixes it upstream by matching the transport's own `Authorization` case-insensitively, so the workaround is deleted rather than kept alongside. The SDK's fix also decides which value wins, and it picks the opposite of what #11663 did: - once the provider has a token, that token replaces a configured `Authorization`; - until then, the configured header is sent. We follow the SDK instead of patching over it. This order is also the useful one: a static API key works until an OAuth login completes, then the OAuth token takes over. The header tests now pin both cases. `@modelcontextprotocol/client` and `core` now require `^2.1.0`. The dev-only server packages move to `^2.1.0` with them. ## Token providers `authProvider` now accepts the SDK's minimal `AuthProvider`, `{ token(), onUnauthorized?() }`, as well as an `OAuthClientProvider`. The adapter hands it to the transport unchanged: - the SDK calls `token()` before each request; - on a 401, it calls `onUnauthorized()` once, then retries. This covers tokens the application already manages, without implementing the whole OAuth client interface. `AuthProvider` is exported as a type. ## Authentication failures When a provider-driven flow fails, the SDK throws `UnauthorizedError`. That error carries no HTTP status, so the old `code === 401` check missed it. The new `isAuthenticationError` recognizes either `UnauthorizedError` or a 401, on the error itself or up to three levels down its `cause` chain. The depth matters because the legacy HTTP→SSE fallback wraps the SSE 401 twice. Both the HTTP and SSE paths now use it. As a result, a provider auth failure: - gets the authentication error message; - keeps the SDK error as `cause`; - in legacy mode, does not fall back to SSE. Tests pin this on both transports. `UnauthorizedError` is exported so callers can check the cause. ## Auth failures stay retryable Discovery used to add every server that failed to connect to `#failedServers`, which skips that server for the rest of the adapter's lifetime. After a 401, completing the login couldn't bring the server back without creating a new adapter. Now: - auth failures stay out of `#failedServers`, so the next discovery retries them; - unreachable servers and a throwing `token()` still stay blocked; - `onConnectionError` still runs for every failure. ## Docs - The README's Authentication section covers both provider shapes, which `Authorization` value wins, implementing `invalidateCredentials()` (without it, a refresh the server rejects fails instead of restarting the login), and `UnauthorizedError` as the `cause`. - No changeset: since #11728, `main` can't carry a changeset for the ignored adapter without blocking every release (changesets/action#541). The release PR restores the 2.0 changeset, including this PR's notes. ## Testing - `pnpm --filter @langchain/mcp-adapters test`: 463 passed, 2 skipped, no type errors. oxlint and oxfmt report no issues. - The OAuth tests run the real SDK client transport against a real in-process authorization server (`src/tests/fixtures/oauth-server.ts`). The SDK is not mocked. The server is built from the SDK's own `mcpAuthRouter` and `requireBearerAuth` and supports: - dynamic client registration; - PKCE; - RFC 9207 `iss`, which can be sent, omitted or unsupported; - token refresh; - RFC 9728 resource metadata for both `/mcp` and `/sse`. - A test reproduces the double-wrapped legacy HTTP→SSE fallback and checks the server is retried. It fails when `isAuthenticationError` checks only one `cause` level. - In the stack's mutation run, deliberately reverting the token-provider, auth-labeling or retry change each made its tests fail. --------- Signed-off-by: Hunter Lovell <[email protected]> Co-authored-by: Hunter Lovell <[email protected]>
Hunter Lovell (hntrl)
added a commit
to langchain-ai/docs
that referenced
this pull request
Oct 1, 2026
## Overview Updates Still some items to do * [x] audit connection doc changes (there's some in flight changes we have here) * [x] add migration guide * [x] add auth guide (pending more guidance on auth) * [x] add admonitions everywhere for migration guide + backlink to old mcp docs ## Type of change **Type:** Update existing documentation ## Related issues/PRs * langchain-ai/langchainjs#11605 * langchain-ai/langchainjs#11612 * langchain-ai/langchainjs#11614 * langchain-ai/langchainjs#11663 * langchain-ai/langchainjs#11642 * langchain-ai/langchainjs#11700 * langchain-ai/langchainjs#11597 * langchain-ai/langchainjs#11643 * langchain-ai/langchainjs#11716 * langchain-ai/langchainjs#11717 * langchain-ai/langchainjs#11718 ## Additional notes MCP sample dependency fix by Open SWE: - Pin `@langchain/[email protected]` for the rewritten API and align Core/LangGraph peers. - Pin `@modelcontextprotocol/[email protected]`, `@modelcontextprotocol/[email protected]`, and `@modelcontextprotocol/[email protected]` for sample types and real local MCP fixtures. - Pin `@modelcontextprotocol/[email protected]` for the legacy SSE fixture instead of adding the deprecated, frozen `server-legacy` package. The fixture now imports `sdk/server/sse.js`; no reader-facing snippet changed. - All five packages are MIT-licensed, recently released, maintained by multiple publishers, and widely downloaded. npm audit reports no advisories on these packages or their added dependency paths; the sample project retains 31 existing findings (18 high, 13 moderate) in unchanged dependencies. - Existing packages and Node's standard library cannot supply the MCP adapter/protocol implementation. Mocks or skipping samples would conceal the failure; the published packages keep the fixtures real. - Peer versions and API behavior were checked against the installed adapter and MCP SDK source. Live model calls remain unverified locally because provider keys are absent; CI runs them. - `make format` reports two existing E501 violations in `pipeline/core/builder.py:275` and `tests/unit_tests/test_generate_code_snippet_mdx.py:13`; neither file was changed by this fix. MCP sample compatibility follow-up by Open SWE: - Use `claude-sonnet-5` in the MCP examples and generated snippets: unlike Sonnet 5.5, it accepts the installed Anthropic integration's default disabled thinking. Provider behavior confirmed against https://platform.claude.com/docs/en/build-with-claude/thinking#turning-thinking-off. - Pin the existing Zod dependency to `4.6.5` so MCP schemas expose Standard JSON Schema and no longer emit the fallback warning; deduplicate six nested Zod copies without updating other packages. npm audit retains 31 existing findings (17 high, 14 moderate), none on Zod. - Live model calls remain unverified locally because the sandbox has no Anthropic key. The unrelated existing formatting violation is `tests/unit_tests/test_generate_code_snippet_mdx.py:37` (E501). --------- Co-authored-by: byhow <[email protected]> Co-authored-by: Hunter Lovell <[email protected]> Co-authored-by: open-swe[bot] <[email protected]> Co-authored-by: Naomi Pentrel <[email protected]> Co-authored-by: Lauren Hirata Singh <[email protected]>
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.
Three silent failures, three stale contracts, and nine changesets collapsed into one. Everything here was out of scope for the feature PRs in the stack. Stacks on #11643.
576 changed lines — implementation 129, tests 203, changesets 241 (182 deleted, 92 added, 33 net removed), README 3.
Background reconnection failed silently
_attemptReconnectswallowed every attempt in a barecatch {}and returned with no signal whenmaxAttemptsran out, so a server that never came back produced nothing: no log, no handler call, no notification. Thedebugdependency that used to carry this was removed package-wide, and nothing replaced it.An exhausted budget now reports through
onConnectionErrorwith the last error. It deliberately does not throw — reconnection runs detached, so there is no caller to throw at, and throwing would surface as an unhandled rejection.A configured Authorization header went out mangled
Header names merge case-insensitively inside the adapter —
mergeHeadersreturnsObject.fromEntries(new Headers(...)), so every name reaches a transport lowercased. A transport then builds its request as{ Authorization, ...ours }, a plain-object spread, soauthorizationsurvives as a second key andnew Headers()joins the two values. AnAuthorizationconfigured alongside anauthProvidertherefore went out asBearer <provider>, Bearer <configured>, which servers reject.Streamable HTTP has always sent that. SSE did not, because
#createSSETransportrebuilt the request by hand in its owneventSourceInit.fetch— re-reading the token off theauthProvider, reapplying the configured headers and settingAccept: text/event-stream— and itsset()replaced rather than appended.That hand-rolled fetch was an SDK 1 workaround: supplying
eventSourceInit.fetchthere replaced the transport's own, dropping all three. SDK 2 wraps it —_startOrAuthbuilds_commonHeaders()and hands them to the caller's fetch — andadaptOAuthProvider().token()is the same(await provider.tokens())?.access_tokenthe adapter was calling. The block recomputed what it had already been given. I confirmed that against a recording server before deleting it, rather than inferring it from the source.Removing it left SSE joining headers like HTTP already did, so both are fixed the same way: spell the names the SDK spells itself, making the spread a replacement, which is what configuring both asks for. A test drives a real transport against a recording server for each; reverting the fix makes both fail with the joined header.
Nine changesets become one
Each PR in the stack wrote its own changeset, which was right while that PR was the unit of work. It is not the unit a reader gets: changesets concatenates every file for a package under one version heading, so this release would have published 182 lines in nine voices — negotiation described twice, the same options introduced in three places, and an example fix sitting beside the migration guide.
One changeset replaces them, ordered the way someone upgrading reads: what breaks, then negotiation, elicitation, results and discovery, server interactions, fixes. 92 lines.
The aggregate is unchanged, and I checked rather than assumed:
changeset statusreports the same single major bump of@langchain/mcp-adaptersbefore and after.changeset versionrun renders 2.0.0 from this file alone and touches no other package. Reverted afterwards.initializeConnections,setLoggingLevel,automaticSSEFallback,onProgress,afterToolCall,beforeToolCallandreadResource().Four names are deliberately gone:
_resolveNonCompleteResultandeventSourceInit.fetchare internal seams, andMcpServer/Acceptbelonged to an example fix and to a behaviour-neutral SSE cleanup — none of which a release note owes its reader.Worth knowing for whoever reviews the lower PRs: this deletes changesets those PRs introduced. If one of them is revised, this file conflicts; it is a one-line merge each time.