refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them - #2134

Closed
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction
Closed

refactor!: extract LegacyServer/LegacyClient; NEW Server/Client compose them#2134
felixweinberger wants to merge 6 commits into
fweinberger/v2-sectionedfrom
fweinberger/v2-legacy-extraction

Conversation

@felixweinberger

@felixweinbergerfelixweinberger commented May 20, 2026

Copy link
Copy Markdown
Contributor

2026-06 stateless stack (v2-stateless label):

#PR
1#2128tasks-delete (mechanical)
2#2129schema-sync (mechanical)
3#2130Dispatcher extraction (zero-Δ refactor)
4#2131HTTP-stateless (the substantive review)
5#2132stdio/InMemory transports (additive)
6#2133docs + changeset
7#2134LegacyServer/LegacyClient extraction

Extracts LegacyServer/LegacyClient (the Protocol-derived, session-stateful classes) and introduces NEW Server/Client that own the 2026 stateless path and compose the legacy class via .legacy.

Motivation and Context

After #2131 the sectioned Server/Client carry both the 2026 stateless surface and the pre-2026 session-dependent surface side by side. That works, but nothing in the type system tells a caller which methods are session-only. This PR makes the boundary structural:

  • The NEW Server/Client no longer extend Protocol. They expose the 2026 stateless surface plus the version-agnostic typed request methods.
  • Session-dependent methods (createMessage/elicitInput/listRoots/sendLoggingMessage/ping on the server; subscribeResource/unsubscribeResource/sendRootsListChanged/ping on the client; raw request/notification/setNotificationHandler on both) live only on LegacyServer/LegacyClient, reachable via the explicit .legacy escape hatch.
  • _assertSession() guards the legacy methods at runtime and throws SdkErrorCode.SessionRequired with a migration URL when called on a 2026 connection.

Both classes share one handler registry and negotiated state (single source of truth on the legacy instance), so behavior is identical to the sectioned base; this PR just moves the seam into the type system.

How Has This Been Tested?

pnpm typecheck:all && lint:fix:all && build:all && test:all && docs:check all green. Integration tests updated to call session-dependent methods through .legacy.

Breaking Changes

Server/Client no longer extend Protocol. Session-dependent methods move to .legacy.*. See docs/migration.md.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Reviewable per-commit:

  1. refactor(server): rename Server -> LegacyServer (verbatim)git mv + class rename, zero body changes
  2. refactor(server)!: NEW Server class (Protocol-free) composes LegacyServer
  3. refactor(client): rename Client -> LegacyClient (verbatim)git mv + class rename, zero body changes
  4. refactor(client)!: NEW Client class (Protocol-free) composes LegacyClient
  5. test: adapt tests to .legacy getter for session-dependent methods

@felixweinbergerfelixweinberger added the v2-stateless 2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless) label May 20, 2026
@changeset-bot

changeset-botBot commented May 20, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b0624

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
NameType
@modelcontextprotocol/serverMajor
@modelcontextprotocol/clientMajor
@modelcontextprotocol/expressMajor
@modelcontextprotocol/fastifyMajor
@modelcontextprotocol/honoMajor
@modelcontextprotocol/nodeMajor

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

@pkg-pr-new

pkg-pr-newBot commented May 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@modelcontextprotocol/client

npm i https://pkg.pr.new/@modelcontextprotocol/client@2134

@modelcontextprotocol/server

npm i https://pkg.pr.new/@modelcontextprotocol/server@2134

@modelcontextprotocol/express

npm i https://pkg.pr.new/@modelcontextprotocol/express@2134

@modelcontextprotocol/fastify

npm i https://pkg.pr.new/@modelcontextprotocol/fastify@2134

@modelcontextprotocol/hono

npm i https://pkg.pr.new/@modelcontextprotocol/hono@2134

@modelcontextprotocol/node

npm i https://pkg.pr.new/@modelcontextprotocol/node@2134

commit: 65b0624

@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment threaddocs/client.md
Comment threadpackages/client/src/client/legacyClient.ts
Comment threadpackages/client/src/client/legacyClient.ts Outdated
Comment threadpackages/client/src/client/client.ts Outdated
Comment threadpackages/server/src/server/server.ts
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from c73c457 to fecd8fdCompareMay 21, 2026 10:42
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from dfae0de to f70313fCompareMay 21, 2026 10:46
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-sectioned branch from fecd8fd to 4e002f6CompareMay 21, 2026 11:16
git mv server.ts legacyServer.ts + class rename. Zero body changes.
Importers updated to `LegacyServer as Server` so behavior is identical
and the rename shows as a true file rename in history.
…rver
`Server` no longer extends `Protocol`. It owns the 2026 stateless dispatch
path (subscriptions, statelessHandlers, _dispatchStateless,
_buildDispatchServerContext, _ondiscover) and the dual-mode surface
(connect/close/transport/onclose/onerror, _fanoutNotify, send*ListChanged),
lifted verbatim from the sectioned `LegacyServer` with field reads
re-pointed at `this.config.*` / `this._legacy.*`.
`LegacyServer` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`.
`server.legacy` is the explicit escape hatch.
LegacyServer body changes are limited to:
- `_assertSession()` guard inserted at top of createMessage / elicitInput /
listRoots / sendLoggingMessage / ping
- ctor: dropped `subscriptions` init + `server/discover` registration
(lifted to NEW Server)
Adds `SdkErrorCode.SessionRequired`.
git mv client.ts legacyClient.ts + class rename. Zero body changes.
Importers updated to `LegacyClient as Client` so behavior is identical
and the rename shows as a true file rename in history.
…ient
`Client` no longer extends `Protocol`. It owns the 2026 stateless send
path (_isStateless/_buildMeta/_withMeta/_collect/_send/_negotiate/
subscribe/_listChangedLoop) and the typed request methods
(callTool/listTools/getPrompt/listPrompts/readResource/listResources/
listResourceTemplates/complete/setLoggingLevel), lifted verbatim from
the sectioned `LegacyClient` with field reads re-pointed at
`this.config.*` / `this._legacy.*`.
`LegacyClient` keeps the session-dependent block. Both share one handler
registry via `_legacy._dispatch`/`_legacy.setRequestHandler`; negotiated
server state lives on `_legacy` (single source of truth) and is written
by both `_negotiate` (via `_setNegotiated`) and `_initialize`.
`client.legacy` is the explicit escape hatch.
LegacyClient body changes are limited to:
- `_assertSession()` guard inserted at top of ping / subscribeResource /
unsubscribeResource / sendRootsListChanged
- ctor: dropped now-unused `_enforceStrictCapabilities` /
`_pendingListChangedConfig` / `_cachedToolOutputValidators` fields
(lifted to NEW Client)
- `_initialize` / `_setupListChangedHandler` visibility widened to @internal
Integration tests that exercise the pre-2026 session-dependent surface
(server.createMessage / elicitInput / listRoots / sendLoggingMessage /
ping / getClientCapabilities / getClientVersion / oninitialized /
createElicitationCompletionNotifier / notification / request /
setNotificationHandler; client.sendRootsListChanged / ping /
subscribeResource / unsubscribeResource / request / notification) now
go through `.legacy`.
LegacyTestClient unchanged: it extends NEW Client and pins versions, so
`connect()` skips the discover probe exactly as before.
clientSend statelessClient() helper updated to set `_transport` /
negotiated state on `c.legacy` (private state moved there).
@felixweinberger
felixweinbergerforce-pushed the fweinberger/v2-legacy-extraction branch from f70313f to 65b0624CompareMay 21, 2026 11:25
@felixweinberger

Copy link
Copy Markdown
ContributorAuthor

@claude review

Comment on lines +242 to +253
_setNegotiated(r: {
serverCapabilities: ServerCapabilities;
serverVersion: Implementation;
instructions: string | undefined;
protocolVersion: string;
}): void {
this._serverCapabilities = r.serverCapabilities;
this._serverVersion = r.serverVersion;
this._instructions = r.instructions;
this._negotiatedProtocolVersion = r.protocolVersion;
this._isStatelessConnection = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 LegacyClient._isStatelessConnection is set to true in _setNegotiated() but is never reset to false — not in Protocol.close(), not in a LegacyClient.close() override, and not in _initialize(). After connect(2026 server)close()connect(pre-2026 server), the legacy session is fully established but _assertSession() still sees the stale flag and client.legacy.ping() / subscribeResource() / unsubscribeResource() / sendRootsListChanged() incorrectly throw SdkError(SessionRequired). Reset _isStatelessConnection = false in _initialize() (where a legacy session is established) or have Client.close() reach in and reset it, mirroring how Client.close() already resets its own _isStateless.

Extended reasoning...

What the bug is

_isStatelessConnection was added in commit 8e502fd (in response to earlier review feedback) so that _assertSession() would fire on a 2026-stateless connection, not just when no transport is connected. It is set to true in LegacyClient._setNegotiated() (legacyClient.ts:252) when Client._negotiate() succeeds against a 2026 server, but there is no code path that ever resets it back to false. The only references to the field are: the declaration = false at line 200, the = true assignment at line 252, and the read at line 271 in _assertSession().

The code path that triggers it

Client is explicitly designed to be reusable after close()Client.close() resets this._isStateless = false and tears down _listChangedAbort precisely so a subsequent connect() starts from a clean slate. But that reset only covers the composing Client's own flag; the symmetric reset on LegacyClient._isStatelessConnection is missing. Protocol._onclose() only nulls _transport; it does not touch subclass fields. LegacyClient._initialize() (the legacy handshake that runs on a non-stateless reconnect) sets _serverCapabilities, _serverVersion, _negotiatedProtocolVersion, and _instructions, but does not reset _isStatelessConnection.

Step-by-step proof

  1. client.connect(transport1) against a 2026-stateless server → _negotiate() succeeds → _setNegotiated() sets LegacyClient._isStatelessConnection = true.
  2. await client.close()Client._isStateless = false; Protocol._onclose() clears _transport; _isStatelessConnection stays true.
  3. client.connect(transport2) against a pre-2026 server → _negotiate() falls through (no mutual stateless version) → _legacy._initialize() runs the legacy initialize handshake successfully and sets capabilities/version, but does not reset the flag.
  4. await client.legacy.ping()_assertSession('ping') evaluates (!this.transport || this._isStatelessConnection)(false || true)true → throws SdkError(SdkErrorCode.SessionRequired, 'LegacyClient.ping requires a connected pre-2026 session…') even though a valid pre-2026 session is connected. The same applies to subscribeResource(), unsubscribeResource(), and sendRootsListChanged().

Why nothing else catches it

The Protocol.request() path's own NotConnected check would pass (transport is set), so _assertSession() is the only guard — and it's now reporting a false positive. The composed pair is left in an inconsistent state: Client._isStateless says "not stateless", LegacyClient._isStatelessConnection says "stateless", and both are reachable from public surface.

Impact

Any application that reconnects a single Client instance across protocol eras — e.g. a tool that probes a list of servers sequentially, or one that retries against an older fallback endpoint after closing — will get a misleading SessionRequired error pointing at the migration docs when the user is in fact correctly connected to a pre-2026 server. The error message tells them to migrate when no migration is needed.

How to fix

Reset _isStatelessConnection = false in LegacyClient._initialize() (where a legacy session is established and the flag should be cleared regardless of how it got set), or override close() on LegacyClient, or have Client.close() reach into _legacy to reset it alongside Client._isStateless. The first option is the most robust since it makes the legacy handshake self-correcting.

Comment threaddocs/migration.md
Comment on lines +906 to +910
| Removed from `Server`/`Client` | Moved to |
| --- | --- |
| `server.createMessage(...)` / `elicitInput` / `listRoots` / `sendLoggingMessage` / `ping` | `server.legacy.*` |
| `client.ping()` / `subscribeResource` / `unsubscribeResource` / `sendRootsListChanged` | `client.legacy.*` |
| `request(...)` / `notification(...)` (raw `Protocol` methods) | `server.legacy.*` / `client.legacy.*` |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new "Removed from Server/Client / Moved to" migration table omits several public Server members that this PR also removes (the PR's own tests/examples had to migrate them to server.legacy.*): oninitialized, getClientCapabilities(), getClientVersion(), createElicitationCompletionNotifier(), and setNotificationHandler/fallbackNotificationHandler. Add the missing rows, fix the now-stale server.setNotificationHandler('notifications/message', …) v2 example at docs/migration.md:~363, and update the Server.legacy escape-hatch JSDoc (which currently lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized).

Extended reasoning...

What is incomplete

The migration table added by this PR at docs/migration.md:906-910 is the structured "what moved where" reference users land on when their build breaks. It currently lists:

  • server.createMessage / elicitInput / listRoots / sendLoggingMessage / pingserver.legacy.*
  • client.ping / subscribeResource / unsubscribeResource / sendRootsListChangedclient.legacy.*
  • request() / notification()*.legacy.*

But the new Server class (packages/server/src/server/server.ts) also no longer exposes the following public members that existed on the old Server (declared on the class or inherited from Protocol), all of which now live only on LegacyServer:

  • oninitialized (legacyServer.ts:259)
  • getClientCapabilities() (legacyServer.ts:598)
  • getClientVersion() (legacyServer.ts:607)
  • createElicitationCompletionNotifier() (legacyServer.ts:711)
  • setNotificationHandler and fallbackNotificationHandler (inherited from Protocol; the new Server delegates only setRequestHandler/removeRequestHandler/assertCanSetRequestHandler/fallbackRequestHandler/registerCapabilities/getCapabilities)

None of these appear in the migration table.

Proof from this PR's own diff

The PR's tests and examples were forced to migrate every one of these to server.legacy.*:

  1. test/integration/test/server.test.ts:54server.setNotificationHandler('notifications/initialized', …)server.legacy.setNotificationHandler(...)
  2. test/integration/test/server.test.ts:312 and statelessAcceptance.test.ts:341-344server.getClientCapabilities() / server.getClientVersion()server.legacy.*
  3. test/integration/test/server.test.ts:843/893/930 and examples/server/src/elicitationUrlExample.ts:56/92/586-587server.createElicitationCompletionNotifier(...)server.legacy.createElicitationCompletionNotifier(...)

Each of those is a compile error on a real call site that a user will hit and then turn to the migration table for guidance — and find none.

A second, contradicting doc-vs-code spot

docs/migration.md:~363 (the "setRequestHandler and setNotificationHandler use method strings" section) still shows the v2 example as:

server.setNotificationHandler('notifications/message',notification=>{console.log(notification.params.data);});

After this PR that does not compile — Server has no setNotificationHandler (only Client retains a delegating wrapper). The section header at line ~330 still reads "…on Client, Server, and Protocol", which is also no longer accurate for Server.

On the Client/Server asymmetry (addressing the refutation)

A refutation argued the asymmetry itself is intentional: under the 2026 stateless model the server never receives client notifications, so server-side notification handlers are inherently a pre-2026 concept and correctly live only on LegacyServer, whereas Client receives server notifications under both eras and therefore keeps a top-level setNotificationHandler wrapper. That is a fair design call and this comment does not dispute it. The remaining issue is purely documentation: an intentional removal still has to be documented, and right now the migration guide both omits the move and shows a code sample that no longer compiles.

Why nothing else surfaces it

These are tsc errors, not runtime failures, so users hit them immediately on upgrade — but the migration guide is the only structured reference for "X moved to Y," and docs/migration-SKILL.md (consumed by automated migration tooling) mirrors the same incomplete table. The Server.legacy JSDoc (server.ts, the get legacy() accessor) lists only createMessage/elicitInput/listRoots/ping/sendLoggingMessage/oninitialized, so a user reading the in-editor hover also won't see getClientCapabilities, getClientVersion, createElicitationCompletionNotifier, or setNotificationHandler.

How to fix

  1. Add rows to the "Removed from Server/Client / Moved to" table at docs/migration.md:906-910 for: server.oninitialized, server.getClientCapabilities(), server.getClientVersion(), server.createElicitationCompletionNotifier(), and server.setNotificationHandler / server.fallbackNotificationHandler (server-side only — note that Client retains delegating wrappers for the latter two). Mirror the same additions in docs/migration-SKILL.md.
  2. Update the v2 example at docs/migration.md:~363 to server.legacy.setNotificationHandler('notifications/message', ...) (or note the server/client asymmetry inline) and adjust the line ~330 prose about "on Client, Server, and Protocol".
  3. Update the Server.legacy JSDoc to list the full set of session-dependent members it gates.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2-stateless2026-06 SDK: Protocol decomposition + SEP alignment (request-first / stateless)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@felixweinberger