* fix(core): register peer-request handlers before connect (#1797) The roots/sampling/elicitation capabilities are advertised on the SDK `Client` at construction, so from the moment `connect()` sends `notifications/initialized` the server may issue any of those requests. The handlers, however, were registered after the handshake resolved and after `fetchServerInfo()` — leaving a window in which the SDK answered `-32601 Method not found`. `server-filesystem` asks for `roots/list` the instant it is initialized (that is how it learns its allowed directories) and lost the race, so it silently fell back to its CLI-argument directories instead of the roots configured in the Inspector. `server-everything` asks later and did not. Extract the four peer-request handler blocks into `registerPeerRequestHandlers()` and call it before `client.connect()`. None of them depend on server capabilities — only on constructor-set state. The notification handlers that do gate on `this.capabilities` stay in `connect()`, after `initialize`. Regression test drives the race deterministically with a fake transport that delivers `roots/list` synchronously from inside the `send()` of `notifications/initialized`; it fails on the pre-fix ordering. Closes #1797 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-1 fixes — pre-connect roots/list_changed, wider timing test (#1797) Finding 1: `notifications/roots/list_changed` was the one handler in the post-handshake block that gates on nothing but constructor state, so it sat in the same race — a server emitting it right after `initialized` had it silently dropped (no wire error; the symptom is a missed UI refresh). Moved to a new `registerPeerNotificationHandlers()` called next to `registerPeerRequestHandlers()` before `connect()`. Finding 2: the timing test asserted one of the four moved handler blocks. It now injects `tasks/list` and the `roots/list_changed` notification in the same burst as `roots/list`, so moving any of the block back after `connect()` fails the test. Sampling/elicitation stay out — they park a pending request awaiting user input and have no reply to assert on. Dropped the unused `sessionId`/`setProtocolVersion` transport fields. Verified the added assertions are load-bearing: the notification assertion fails against the previous commit, the `roots/list` one against `origin/v2/main`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-2 fixes — correct the roots/list_changed premise (#1797) The round-1 doc comment claimed a server may emit `notifications/roots/list_changed` at initialize. It can't, normally: `RootsListChangedNotificationSchema` is a member of `ClientNotificationSchema` and absent from `ServerNotificationSchema` — the client sends it (setRoots does, at :4251). The inbound handler is defensive coverage for a non-conformant server, and dispatches `rootsChange` with our own already-known roots. Reworded the method doc and the test's header so neither states the false premise; the move itself stands (it gates on no server capability, so it belongs with the request handlers). Also from review: - Dropped the vacuous `notificationRejected` flag and its inverted comment. The SDK does not throw for an unregistered notification, so the try/catch could never observe one — confirmed by bisect, where the pre-fix failure was always `rootsChanges`, never the flag. Removing the catch also stops it swallowing a genuine throw from the injected requests. - Narrowed `replies` to responses (`"result" in message || "error" in message`) so it can't also collect client-originated requests. - Annotated the unreachable `if (!this.client)` guard with a justified `v8 ignore` per the AGENTS.md dead-guard policy. Re-verified both regression directions: the `roots/list` assertion fails against `origin/v2/main`, the `rootsChange` one against `55e25b7c`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-3 fix — drop stale comments inside the roots handler (#1797) The four inline comments moved verbatim with the handler contradicted the method doc reworded one round earlier: they said "server's roots" (they are ours — it is a ClientNotification) and "we'll just dispatch an empty array", which is not what `this.roots || []` does when roots are configured. The new timing test asserts exactly that non-empty dispatch. Replaced with one accurate line. Comment-only. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(cli): advertise roots so roots/set is actually serviceable (#1797) Round-4 review found the same -32601 symptom on a second path: the CLI constructed its InspectorClient with no `roots` option, so `capabilities.roots` was never advertised and no `roots/list` handler was registered — yet `--method roots/set` calls `setRoots()`, which announces `notifications/roots/list_changed` to the server. A server taking up that invitation got "Method not found", after the CLI reported success. The review's suggested fix — register `roots/list` unconditionally — is not implementable: the SDK asserts the client capability inside `setRequestHandler` ("Client does not support roots capability"), so it throws during connect for any client built without the option, and `registerCapabilities` refuses to run after connect. A client that omits `roots` therefore cannot legally serve `roots/list` at all. Fixed at the layer that can fix it: `cli.ts` seeds `roots: []`, matching web (`App.tsx` always passes it). The core registration stays gated on the constructor value, now with the SDK constraint documented so the next reader doesn't retry the unconditional version. `setRoots()`'s doc claimed it "will enable roots capability if it wasn't already enabled" — it cannot, for the reasons above. Corrected, and dropped the dead `if (this.roots === undefined) this.roots = []` the very next line overwrote. Tests: a CLI test drives `list_roots` over an HTTP test server (verified load-bearing — without the seed it fails on the -32601 error text), and the core timing test gains a case pinning that roots set after connect are served with the current values, not the constructor's. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(cli,tui): advertise the roots configured in mcp.json (#1797) Round-5 review: seeding `roots: []` fixed the -32601 but not the outcome. `server-filesystem` discards an empty roots answer (`validatedRootDirs .length > 0`) and keeps its CLI-argument directories — which is the symptom this PR set out to fix. The user's roots were already in hand two lines away, on `serverSettings.roots` (lifted from mcp.json by `mcpConfigToServerEntries`). Now passed through `cleanRoots`, the same shared helper web uses, so both clients answer `roots/list` byte-identically for the same config. This matters most on the CLI because it is one-shot: `--method roots/set` sets roots on a connection torn down a few statements later, so the config file is the only durable way to give a run its roots. Same gap in the TUI (`App.tsx` built its options with no `roots` key at all), fixed the same way. The review suggested a follow-up issue for it; folding it in here instead, since it is the identical line and splitting it would leave a known-wrong client in tree. Also from review: hoisted `waiters` up with the other fields, and `injectRequest` now rejects after 1s naming the method and id rather than hanging to the vitest timeout. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-6 fixes — document roots in the CLI README, harden cleanRoots (#1797) - clients/cli/README.md enumerated the settings lifted from a catalog/config file without roots. Roots are the least discoverable member of that list — there is no flag, and `--method roots/set` dies with the connection — so the file is the only durable way to supply them. Said so. - cleanRoots() trusted its input's shape. `Root[]` is a compile-time type over hand-editable mcp.json, and as of this PR all three clients feed it straight from disk, so `"roots": [{"name":"Work"}]` or `"roots": "file:///work"` threw at connect. Non-array bails to []; an entry without a string uri is dropped with a warning. Hardened in the one shared place rather than three call sites. Review suggested a follow-up issue; folded in for the same reason as the TUI fix last round. - Test comment said the CLI passes a `roots: []` seed — true one commit ago. - injectRequest clears its timeout on reply (an armed timer outliving a test is the #1760 teardown class), and setRoots' doc drops the "despite what this comment used to claim" archaeology. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-7 fix — cleanRoots also throws on a non-string name (#1797) The round-6 hardening guarded `uri` and left `name` throwing one line later: `r.name?.trim()` guards null/undefined, not "is a string", so `"roots": [{"uri":"file:///a","name":42}]` still died at connect — the same crash class, one field over, reachable from all three clients and the web settings-save path. Reproduced against the shipped function body before fixing. A bad `name` now costs the name, not the root (it is optional, and the uri is still usable), with a warning. The doc no longer overstates what is validated. Also from review: the CLI test comment said "`cli.ts` now seeds `roots: []`" — true only of that ad-hoc test's path; and the registration comment's `(:588)` line reference is now a durable name. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): normalize roots in setRoots() too (#1797) Round-8 review: this PR made cleanRoots the single normalizer for roots at connect and at save, but setRoots — the third way roots enter the client — did a bare `this.roots = [...roots]`. Web cleans at its call site; the CLI does not, so `--method roots/set --roots-json '[{"name":"Work"}]'` stored a root with no uri, advertised it in the roots/list reply, and echoed it back as success. cleanRoots is idempotent, so calling it inside setRoots covers the CLI without disturbing web's pre-clean, and all three entry points now agree. Review filed this as an optional follow-up; folding it in for the same reason as the TUI and cleanRoots items — it is smaller than the issue describing it. Test asserts the malformed entry is dropped and the valid one survives; verified load-bearing against the bare-spread version. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-9 fixes — normalize roots in the constructor too (#1797) The round-8 commit claimed "all three entry points now agree"; review pointed out the constructor is a fourth, and the only one still raw. All three clients clean at their call site, so nothing was broken — but the invariant was enforced by convention rather than by the class, at the very entry point this whole thread started from. `this.roots` now runs through cleanRoots, with a ternary so the `undefined`-vs-`[]` distinction that gates capabilities.roots survives. Also from review: - The CLI roots/set test provoked a cleanRoots warning without suppressing it (AGENTS.md). Suppressed, and the spy now asserts the drop was reported rather than silent. - `enables roots when previously undefined …` in coverage-backfill was named after behaviour round 5 established does not exist. Renamed, with a comment on what that client actually can and cannot do. - setRoots dispatches a copy to rootsChange, as getRoots() already did, so a listener can't push into the list we advertise. - run-method.test.ts's connectStdio now passes `roots: []` like cli.ts, so the helper matches the client shape production builds. Verified load-bearing: the constructor test fails against the raw assignment. validate / coverage / build-gate / smoke / storybook all green (run as separate stages — full `npm run ci` kept being killed mid-coverage by the environment). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-10 fixes — copy at both rootsChange dispatches (#1797) Round-9 claimed setRoots' copy closed the "a listener can't push into the list we advertise" hole. It closed one of two sites: my reply conflated the notification handler's *dispatch* with the roots/list *request* handler — the latter is serialized to the wire immediately and is fine, the former hands listeners the internal array. Both copy now. Also from review: dropped the `({}) as never` in the new constructor test for the real factory the sibling tests use (this test never connects, so it is never invoked), and the needless `async` on it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-11 doc fixes; merge v2/main (#1797) - cleanRoots' opening sentence still framed it as the settings-form normalizer, contradicting the paragraph below it that says every client feeds it from disk. It has four callers now; says so. - Marked the two runtime guards `Keep:` with the reason. The `Root[]` parameter narrows both to `never`, so "the compiler says this can't happen" is the argument someone will use to delete the checks rounds 6-7 installed. The reason now lives where the deletion would happen. - Noted the constructor-normalization case in the timing test's header, so it is discoverable from a file otherwise about the initialized race. Also merged origin/v2/main (#1796, loopback binding), which had advanced by one commit and touched the smoke scripts. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): clear queued peer requests when connect() fails (#1797) Round-12 review found a second-order consequence of the handler move. Before it, registration happened after every await in connect(), so the moment a peer request could be queued the connect could no longer fail — queue and failure path never overlapped. Registering before the handshake puts both the handshake and the post-connect `setLoggingLevel` inside that window. The catch sets status to error and drops the transport but never cleared pendingSamples/pendingElicitations; only disconnect() does, and connect() reaches it solely on the connect-timeout path (not the default). So a server that elicits at `initialized` and then fails the connect left a live pending-request modal on a dead connection — web derives it from the queue lengths with no status gate — and the elicitation's cancel() never fired, hanging any awaitUrlElicitation waiter. Extracted disconnect()'s clear-and-cancel into clearPendingPeerRequests() and called it from the catch, dispatching the change events so the UI drops the modal. CLI/TUI are unaffected either way (sample/elicit off). Test note: the first version of this test passed with and without the fix — its `requestedSchema` omitted `properties`, so the SDK rejected the inbound params and nothing was ever queued. Fixed the fixture; it now fails without the change with a queued ElicitationCreateMessage. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): clear the peer-request queue on a mid-session crash too (#1797) Round-13 review, two items. The test asserted only `getPendingElicitations()`/`getPendingSamples()`, which read the arrays directly — but the arrays are not what removes the modal. `usePendingClientRequests` tracks its own state off the pendingSamplesChange/pendingElicitationsChange events, so a regression that cleared without dispatching would strand a live modal on a dead connection and stay green. Both tests now assert the events fired with an empty payload; verified by deleting just the dispatches, which fails them. The connect-failure fix left the other way a connection ends uncovered: a mid-session crash goes through the transport's `onclose`, which sets status and fires `disconnect` but never touched the queues. Same two hazards, and arguably more reachable. `clearAndAnnouncePendingPeerRequests` wraps the clear plus its events, guarded on a non-empty queue so the paths that overlap (a connect failure whose dropCachedTransport also fires onclose) announce once; called from both. New test queues an elicitation, fires onclose, and asserts the queue and the event — fails without the change. Review flagged the crash path as a follow-up; folding it in, as with the earlier out-of-scope items — it is the same seam and three lines. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-14 fixes — make both teardown paths agree (#1797) - The crash path's comment claimed "cleared before the `disconnect` event so a consumer sees an empty queue" while disconnect() cleared *after* its own dispatch — an invariant stated as a property and held at one of two sites, the same shape as the round-10 finding. Moved disconnect()'s clear above its status/disconnect block so both paths agree; its change events stay batched with the other teardown dispatches. Full gate green, so nothing depended on the old ordering. - clearPendingPeerRequests' doc still named the `connect()` failure path as a caller; that path now goes through clearAndAnnouncePendingPeerRequests. Names the two real callers. - The mid-session test waited on `await Promise.resolve()` — the microtask-counting pattern this file replaced with injectRequest two rounds ago, working today only because the enqueue happens exactly one tick deep. Waits on the client's own `newPendingElicitation` instead. - The file header still called the constructor case "the last case"; it is third of five, and the two teardown cases went undescribed. Rewritten. - Restored the missing blank line between two tests, and noted why the sampling-event assertion holds for a queue that never held anything. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-15 fixes — scope the parity claim to the arrays (#1797) Round-14 made the two teardown paths agree on when the queue is cleared, and the comment then claimed parity flatly. It holds for the arrays but not the events: the crash path announces before `disconnect`, while disconnect() batches its change events with the rest of its teardown, so they land just after. Since the events are what drives the modal, the distinction matters to the next reader. Scoped the comment rather than un-batching — un-batching would trade a documented ordering for a real behaviour change with no gain. Same rule as round 14, one level down: check the other site, then check the other axis. Also gave the new `newPendingElicitation` wait the timeout that `injectRequest` documents, so a regression that stops the enqueue fails at the wait instead of hanging to the vitest timeout. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * test: pin disconnect()'s clear-before-announce ordering (#1797) Round-14 moved clearPendingPeerRequests() above disconnect()'s status block so a `disconnect` consumer sees an empty queue on both teardown paths, and round 15 documented it — but nothing enforced it. The existing `disconnect` listeners only count events, and the two teardown tests cover the crash and connect-failure paths, neither of which goes through disconnect(). So the one behavioural change in the stack was untested in both directions, and the tidy that undoes it (regrouping the clear with the batched change events) would have stayed green. Test records the queue length from inside a `disconnect` listener; the fixture's close() never fires onclose, so it exercises disconnect()'s own ordering rather than the crash path. Verified against the pre-round-14 position: `expected 1 to be +0`. Folded the newPendingElicitation wait into a shared helper now that two tests use it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * test: pin disconnect()'s announce as well as its clear (#1797) Round-16 pinned the array half of disconnect()'s teardown and left the events unpinned — and nothing else in the suite covers them, so deleting disconnect()'s two change-event dispatches would have left a live modal after a user-initiated disconnect with the suite green. That is the path most likely to have a modal open when it runs. Asserted after the await rather than inside the disconnect listener, since disconnect() batches the events deliberately; verified by deleting the dispatches (`expected undefined to be +0`). Header rewritten by category rather than position: it has now gone stale twice in three rounds because it counted tests ("the last two") and enumerated paths that a new test falsified. It names the three teardown paths and what distinguishes them instead. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-18 doc fixes — scope the three-path claim, re-attribute cancel() (#1797) The header I rewrote last round claimed all three teardown paths clear before announcing. True only if "announcing" means the `disconnect` event: the connect-failure path emits none at all, and both it and the crash path clear after their `statusChange`. Scoped to what's true. Same shape as rounds 10/14/15 — a parity asserted in prose that holds on one of the axes it could mean — which is now the fourth time, in a sentence I wrote. ElicitationCreateMessage.cancel()'s doc still credited `disconnect()` teardown; this PR made clearPendingPeerRequests() its only caller, serving three paths. Re-attributed, and promoted the no-`onRemove` note to its own paragraph with the consequence spelled out — it quietly became a three-caller invariant during this PR, and "don't splice mid-iteration" reads like a style note until you know it would skip every other entry and leave those promises unsettled. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): gate roots/list on what was advertised, not on this.roots (#1797) Round-19 review found a latent wedge, reproduced before fixing: a client constructed without `roots` that later calls setRoots() has this.roots defined, so registerPeerRequestHandlers tried to register the handler on every subsequent connect() — and the SDK throws "Client does not support roots capability" from setRequestHandler when the capability was never advertised. That throw lands before the handshake, so the client can never reconnect. Worse than the -32601 this PR started from: the connection is gone rather than answering one method badly. Not a regression (the same gate lived after the handshake before) and unreachable from the three shipped clients, which all pass roots. But core/ is a library surface, and the failure is unrecoverable. Gate now reads a construction-time `rootsCapabilityAdvertised` — the thing the SDK actually asserts on — so this.roots stays free to change. setRoots' doc says what does happen on such a client: the roots are stored and readable, but no server can ask for them. Also scoped the header's claim that the connect-failure path emits no `disconnect`: true of connect()'s own catch, but on a real transport dropCachedTransport's close() fires onclose first, which does dispatch one — making the catch's own call the auth-recovery backstop. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-20 — derive the roots gate from the advertisement itself (#1797) Round-19's fix restored the invariant but not the derivation: rootsCapabilityAdvertised was computed from `options.roots` alongside the capability block rather than from it, so the two encodings of "did we advertise roots" could drift. Adding any term to the advertisement condition would leave the flag true with `capabilities.roots` absent — the same unrecoverable wedge, reintroduced silently and in the throwing direction. Now read off the built capability object after it is assembled, so divergence is structurally impossible rather than merely absent. Verified the reconnect test still fails against the old `this.roots` gate. Also: named the capability-lifetime category in the test header (the new test was none of the three it listed), moved that test below the teardown group so the group stays contiguous, and rewrapped the over-long comment line. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): gate elicitation/create on what was advertised too (#1797) Round-21 review asked round-20's question of the capability next door, and there the two derivations already disagreed — no future edit needed. `elicit` is typed `boolean | { form?, url? }`, so `{}` or `{ form: false, url: false }` is valid, enables no mode, and advertises no `capabilities.elicitation` — while the registration gated on `this.elicit` being truthy. Reproduced before fixing: CONNECT ERROR: Client does not support elicitation capability (required for elicitation/create) Since #1797 moved registration before the handshake, that throw means the client cannot connect at all. Same wedge as the roots one, one capability over, and reachable through a documented option value rather than a future edit. Gated on a new elicitationCapabilityAdvertised, derived from the built capability object exactly as the roots flag now is. Test constructs with `{ form: false, url: false }` and asserts connect() resolves; verified load-bearing. Also made the four construction-time capability inputs (sample, elicit, receiverTasks, advertisedExtensions) `readonly`. The round-19 bug was a mutator making a construction-time fact stale, so a future setter for any of these should be a compile error rather than a review catch. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): derive tasks.requests and the remaining gates from the advertisement (#1797) capabilities.tasks.requests declares which server→client requests we accept as tasks, but was built from `receiverTasks` alone — so `{ receiverTasks: true, elicit: false }` told the server it could send a task-augmented elicitation/create while advertising no elicitation capability and (since the last commit) registering no handler. A server taking the invitation gets -32601: the advertise-then-refuse shape this PR opened with, and the last place it survived. Now built from capabilities.sampling / capabilities.elicitation, both decided just above, with the key omitted entirely if neither applies. Also made the remaining three registration gates read the built capability object like the two from the last two rounds — sampling, tasks/*, and the URL-elicitation completion handler. None could diverge today, but a mixed convention means the next reader has to re-derive which gates are safe, and adding one condition to an advertisement block is exactly how elicitation broke. Five gates, one rule now. Test asserts a receiverTasks+elicit:false client advertises tasks.requests with sampling and without elicitation; verified load-bearing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-23 — pin the omitted-requests arm, drop the count again (#1797) The `requests` key is omitted when neither sampling nor elicitation is advertised, but every `receiverTasks: true` construction in the tree left one of them enabled, so that arm was unexercised — and it would not have shown as a coverage failure, since one uncovered branch in a ~4900-line file sits well inside the per-file gate. Second client in the same test asserts `tasks` survives (list/cancel are still serviceable) while `requests` is absent rather than empty; verified against `requests: taskRequests`. The header regained a numeral four commits after round 17 rewrote it by category to stop exactly that, and it was already stale. Dropped, and named the third category — advertise-only-what-you-serve, which is about the capability object rather than a registration gate. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): settle queued samples on teardown instead of discarding them (#1797) Round-24 review. Round 13 recorded the samples-vs-elicitations asymmetry as deliberate on two grounds: nothing internal awaits a sample, and the transport is gone by then. The first still holds; the second is false on one path, and it is a path this PR created. `connect()`'s catch drops the transport only when `!transportHasAuthProvider`, so on the HTTP+OAuth path — web's ordinary authenticated case — it is retained and the caller reconnects over it. A sampling request queued during the handshake was then discarded with the connection still live: no response frame ever written, and the server waits forever for a reply to a request we accepted. Accept-then-silence, which is worse for the peer than the -32601 this PR opened with. SamplingCreateMessage.cancel() mirrors the elicitation one — settles (rejects, what the UI's decline path already sends and the SDK turns into an error response) without calling onRemove, since the caller iterates the queue and clears it. clearPendingPeerRequests loops it like the elicitations. Also corrected two comments that assumed the catch always tore the transport down, and noted that the retention is gated on transportHasAuthProvider alone — independently of isConnectAuthRecoveryError, which gates only the status hold. Test asserts settlement rather than a wire frame, since on the disconnect() path the transport is closed before the settle; a later respond() throwing "already resolved or rejected" is the proof. Verified load-bearing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): mark receiver-task payload promises handled (#1797) Round-25 review. clearPendingPeerRequests iterates every entry in pendingSamples, and two shapes live there: the plain server-request one, whose reject reaches the SDK handler, and the task-augmented one, whose reject reaches the receiver task's payloadPromise. That promise only gets a consumer when the server polls tasks/result, so a task sitting in input_required has no handler attached — and the settle added last commit surfaced as an unhandled rejection. Not hypothetical: the repo already worked around it test-side, with a helper that reaches into private state to attach no-op catches, whose comment describes this exact race. Fixed at the source instead — one `void payloadPromise.catch(() => {})` at creation, which also covers the pre-existing cancelReceiverTask path. Removed the now-redundant helper and its two call sites. Verified: dropping the source line makes that suite report two unhandled rejections. Corrected SamplingCreateMessage.cancel()'s doc — its "no response frame is ever written" rationale is true of the plain shape only; a task-augmented sample already answered the wire with a CreateTaskResult, so settling it is about not leaving the task in input_required limbo. Nits: generalized the enqueue wait helper to both events so the sampling wait gets the timeout the elicitation one has; moved the sampling teardown test back into the contiguous teardown group; named the settle property in the header; fixed the fixture doc that still claimed to record replies. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-26 — drop the comment that outlived its call (#1797) The suppressReceiverPayloadRejections call went last commit; its two-line comment stayed, describing a pre-attach that no longer happens and crediting the test for handling a rejection the source now handles. Removed. Also reworded the surviving .catch() in inspectorClient.test.ts: it is still needed, but as a value capture for the assertion, not for unhandled-rejection suppression. Rewrapped the teardown paragraph in the test header — my round-25 edit left a 104-char line, and two hand-fixes left it ragged, so it is reflowed in one pass. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-27 — skip the roots/list_changed the SDK would refuse (#1797) Review reported setRoots() emitting roots/list_changed on a client that never advertised roots, inviting a re-fetch we'd answer -32601. Probed it: the premise is wrong. The SDK asserts the notification capability too — `notification()` rejects with "Client does not support roots list changed notifications" and nothing reaches the wire. No spec violation and no invitation; what actually happened is that setRoots provoked that rejection and logged it as "Failed to send", implying a transient failure where the truth is structural. Kept the early return on that corrected basis: it stops us provoking a rejection we know will come, and warns accurately instead. Doc and comment say the SDK is the enforcer rather than claiming this guard is what keeps the wire clean. The test pins the end state (no invitation for roots we can't serve) and passes either way — recorded as such rather than presented as a regression guard, since it isn't one. Also moved the advertise-category test below the two gate cases, matching the order the header introduces them. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-28 — gate the notification on the predicate the SDK asserts (#1797) The roots/list_changed guard read `capabilities.roots !== undefined`, but the SDK asserts `capabilities.roots.listChanged` for the notification — wider than the flag. Identical today (roots are only ever advertised as `{ listChanged: true }`), but a conditional advertisement would un-gate it silently, which is the round-21 shape again. Split into rootsListChangedCapabilityAdvertised, mirroring urlElicitationCapabilityAdvertised, which already reads its assertion's sub-field; rootsCapabilityAdvertised keeps the roots/list registration, where presence is what setRequestHandler checks. Also moved the new test out of the gate pair it had split — it is a runtime-emission case, not a registration-gate one — and extended the header's converse-category paragraph to cover notifications, which indexes it without inventing a category. Reflowed the setRoots doc paragraph in one pass (111-char line from the last commit, plus a ragged orphan from an earlier edit). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-29 — chase the corrected premise into clients/cli (#1797) Round 27 corrected "setRoots announces roots/list_changed to a server that then gets -32601" — the SDK refuses the notification from a client that never declared it, so nothing reached the wire. That reword happened in core/, but the same premise had been written into the two comments justifying the CLI's roots seed, and they still asserted it. Both now state the real pre-fix failure: a server asking for roots on its own got -32601, and roots/set could not announce at all. Also fixed the warn message under the round-28 gate: it named the roots capability while the gate is on roots.listChanged — precisely the pair that split was made to distinguish, so a client advertising `{}` would have been told it advertised nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): reject in-flight raw-wire requests on a mid-session crash (#1797) rejectPendingRawWireRequests had one caller — disconnect() — so the crash path settled the inbound peer-request queue this PR added and left the outbound raw-wire map alone. That map holds the modern tasks/* frames the SDK's era gate refuses to route, so the SDK's chained _onclose doesn't know about them: a Tasks-tab poll in flight when the server died waited out its own 30s timeout and reported a timeout for what was a crash, on a connection that had already dispatched `disconnect`. Pre-existing — both the map and the crash path predate this PR. Fixing it here because the invariant it violates is one this PR wrote down: "every path that ends a connection has to clear that queue, announce it, and settle each entry", in clearAndAnnouncePendingPeerRequests' doc and the timing test's header. One channel was true of one path out of three. Test starts a raw-wire request and fires onclose; without the call it hangs to the vitest timeout, which is the symptom. Checked the two siblings and left both: taskInputAbortControllers is already unblocked via the elicitation cancel the crash path performs, and activeToolCallAbortController rides an ordinary client.request the SDK settles itself. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-31 test fixes — justify the cast, drop the no-op tick (#1797) - The new test's `as unknown as` had no justification, which AGENTS.md explicitly prohibits. It is unavoidable — rawWireRequest is private and every public route is gated on isTasksExtensionNegotiated(), which needs a modern handshake the fixture doesn't perform — so that reasoning is now written down instead of left to be re-derived. - `await Promise.resolve()` was a no-op: rawWireRequest registers its entry in the promise executor, synchronously, before any suspension. Dropped, which also makes the test pin that ordering rather than paper over it — and stops the third recurrence of the microtask-counting pattern this file's own helper doc argues against. - Moved the test into the teardown group and extended the header's teardown paragraph to cover the outbound direction, which it framed entirely as inbound. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-32 — separate the outbound teardown claim from the inbound one (#1797) My round-31 header edit spliced the outbound raw-wire passage into the middle of the inbound claim, so "There are three: a failed connect(), a mid-session transport close, and an explicit disconnect()" ended up reading as scoping the outbound settle — which is two by design, since nothing populates the map before the handshake. Round 31 established that scoping so the code wouldn't imply an impossible state; the prose then un-scoped it. Split into its own paragraph with its own scope clause, and reflowed both in one pass rather than nudging breaks. Also raced the raw-wire assertion, for the reason the file's own wait helper documents: without the teardown rejection the test waited out the request timeout and reported a bare vitest timeout. It now fails with "raw-wire request not settled by teardown" — verified. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-33 — extract the timeout race, mark the failure-path promise handled (#1797) Three copies of "reject after 1s so a regression fails where it happened" had accumulated, each re-explaining itself. Extracted `withTimeout`, used by the enqueue wait and the raw-wire assertion; injectRequest keeps its own since its timeout also deletes the waiter entry. On the failing path the raw-wire test left the production 30s timer armed, so a regressed run got the intended failure plus a stray unhandled rejection up to 30s later — the armed-timer class the file's own comment names, on the failure path. `settled` is marked handled before the race. Verified: with the fix removed the run fails with "raw-wire request not settled by teardown" and no unhandled rejection. Recorded why disconnect() drains the SDK's in-flight requests but rejects the raw-wire map outright: the user asked to disconnect, and a Tasks poll is not worth delaying that for. Pre-existing and deliberate, now written down where the asymmetry is visible. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-34 — drop a no-op guard and the false mechanism it asserted (#1797) Round 33 claimed the raw-wire test could leave `settled` rejecting unhandled on a regression run, and round 33's fix encoded that as `void settled.catch(() => {})` with a comment explaining it. Both were wrong: `Promise.race` attaches a rejection handler to every input, so `withTimeout(settled, …)` on the next line already marks it handled. Verified with a standalone script — no unhandledRejection fires, and the pre-fix version was equally safe. Removed the line and the comment. The comment mattered more than the line: it told the next reader that `Promise.race` does not mark its losers handled, which is false and would cost them elsewhere. Kept the true half by setting `timeout: 50` on that test's client, so a regression leaves no 30s timer armed and fails with `Raw request "tasks/get" timed out after 50 ms` — more self-describing than the raced generic message. Verified. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-35 — the drain comment described a trade-off nobody made (#1797) Last round's comment said raw-wire requests "get no share of the drain above: the user asked to disconnect, and a Tasks poll is not worth delaying that for" — framing a decision. Verified it isn't one: `safeDisconnectTimeout` defaults to 0 and the only caller anywhere that passes a value is a single test, so nothing is drained in production; and the drain polls the SDK's `_responseHandlers`, which never holds raw-wire ids, so those were never eligible regardless. Reworded to what is true. The framing came from my own round-33 reply, which described the drain as running on every disconnect — a comment faithfully encoding a half-read mechanism, which is the same failure as the `Promise.race` one it followed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-36 — the race comment outlived the mechanism its own commit replaced (#1797) `timeout: 50` made the request settle in ~50ms, so the 1s race can never win and a regression fails on the assertion (`timed out after 50 ms` vs the expected /Connection closed/) — which the commit message said, while the comment beside it still credited the race. Reworded: the short timeout is what fails fast and names itself, the race is the backstop for a promise that never settles at all. Race kept; it covers the case where the request's own timer is broken too. Third comment in three rounds encoding a mechanism the same commit changed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-37 — scope the timeout comment, align the bypass guards (#1797) `timeout: 50` is the client-wide request timeout, not a bound on the raw-wire request; it is inert in that test only because the test issues no SDK request after connect. Noted, so someone adding one later knows it would inherit a 50ms budget rather than reading the comment and looking elsewhere. The two installReceiverTaskResponseBypass guards read `this.receiverTasks` while the five gates around them read the advertisement. Installing the bypass mutates the Protocol's _requestHandlers map, so it is registration — same as the setRequestHandler it follows. Equivalent today; aligned so the convention is uniform rather than something the next reader has to re-derive per site. The genuinely-runtime `receiverTasks` reads are left. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-38 — one predicate for the whole bypass mechanism (#1797) Round 37 moved the bypass *install* guard to the advertisement and left the three branches it controls on the raw option, splitting one immutable fact across two sources. The dead direction is the harmful one: if the tasks advertisement ever acquires a condition — the exact edit that produced the elicitation wedge — then advertised goes false while receiverTasks stays true, the bypass is not installed, and the handler still returns `{ task }` into the SDK's validating wrapper, which rejects it. That is the breakage the bypass exists to prevent, and before round 37 it could not happen because install and branch read the same field. All three now read tasksCapabilityAdvertised. `receiverTasks` is left where it belongs: assigned once, and driving the advertisement. Also noted that the wrapper's own check is redundant with its install guard and kept deliberately, since it must agree with the handler branch. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): don't carry receiver tasks into the next session (#1797) Round-39 review found the last member of the enumeration rounds 12-14 and 31 built: receiverTaskRecords was cleared only by disconnect(). The crash path doesn't clear it, the connect() failure catch doesn't, and connect() never reset it — so a record created in one session survived into the next connect() on the same instance, and `tasks/list` is answered from that map. A new server would be told about a task it never created. Reachable in web (the only client with receiverTasks): a task-augmented sampling/createMessage arriving in the handshake window creates a record; if that connect then fails with a 401, App.tsx retries connect() on the same instance. Cleared at the top of connect() rather than only on the crash path — the auth-recovery retry means ending a session isn't the only way a new one begins, and starting clean covers every route in. disconnect() keeps its clear via the same extracted helper. Pre-existing — the crash path never cleared these — but the handshake window this PR opened is what lets a receiver task exist before connect resolves, and this was the one member left outside the invariant the PR documented. Test verified load-bearing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): reset all session-scoped state on connect, not just receiver tasks (#1797) Round-40 review: receiverTaskRecords was one of five collections cleared only by disconnect(). Two of the other four have real symptoms on the same crash-then-reconnect path: - subscribedResources — the modern subscribeToResource early-returns on a uri already in the set, so after a reconnect the user's Subscribe click silently sends nothing to the new server while the UI keeps listing it. - cancelledTaskIds — a leftover id mislabels a *new* task sharing it as cancelled rather than failed, and server task ids are often short. taskInputAbortControllers leaked un-aborted controllers. modernLogLevel had the opposite asymmetry: disconnect() cleared it so it couldn't leak (#1629), but nothing restored it, so a reconnect after an explicit disconnect silently lost the user's configured level while a reconnect after a crash kept a mid-session override. It is now recomputed from serverSettings the way the constructor does, so both routes agree. clearReceiverTasks became resetSessionState, called from the same place. Tests cover the two symptomatic siblings and now assert receiver tasks through the `tasks/list` handler — what a server actually sees, and the symptom itself — which also removed the unjustified `as unknown as` the previous commit added. The remaining cast is justified in place, since cancelledTaskIds has no public reader. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(web): re-seed the Logs control when the client re-seeds its own level (#1797) Round-41 review caught a consequence of the last commit. `resetSessionState` restores the client's modern log level from the server setting at connect; `resetSessionScopedUiState` still blanked the web control to null on every disconnect. On the one path that reconnects the *same* instance — auth recovery — the control then read Off while every modern request carried `_meta` logLevel "debug", the default. A tool whose job is showing what you send should not disagree with itself about what it sent. The control now re-seeds from the active server's settings exactly as setupClientForServer does, instead of blanking. Also from review: - Added the tests the restore never had, covering both halves: a mid-session override does not survive a reconnect, and a disconnect no longer drops the configured level (the #1629 half, and the actual behaviour change). - resetSessionState's doc claimed "every piece of state scoped to one connection", which invites assuming membership rather than checking it. Now states the rule: state a new session would misread; what only needs settling on the way out stays with the teardown paths. - Header: session-scoping paragraph moved below the outbound one to match test order, and it now names all five members rather than three. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * refactor(core): one derivation for the modern log level (#1797) Round-42 review: the configured level was computed independently in four places — twice in InspectorClient (constructor, resetSessionState) and twice in App.tsx (the seed and the re-seed). The client and the Logs control agreed only because four sites happened to compute the same expression, and any drift reproduces exactly the symptom the previous commit fixed: the control reading one level while every modern request stamps another. Extracted resolveModernLogLevel into core/mcp/types.ts beside DEFAULT_MODERN_LOG_LEVEL; all four call sites use it, with the web mapping undefined→null at its own boundary (display, not a second derivation). Also from review: - disconnect()'s comment still credited itself with preventing the #1629 leak, which resetSessionState now prevents. It says what the line does now — read "not opted in" while disconnected — and notes the web control deliberately shows the configured level in that window. - resetSessionState's doc claimed an un-aborted taskInputAbortControllers entry "leaks a paused poll loop". Both registration sites release in a finally, so nothing leaks permanently; the abort closes the window between a crash and the unwind. Softened, and it now has the test it lacked — the only member of the five without one. - Noted in App.tsx that the re-seed depends on activeServerIdRef still holding the outgoing id (it syncs in a passive effect), so an eager clear would silently drop it to the default. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): reset the subscription stream state with the set it derives from (#1797) Round-43 review: resetSessionState cleared subscribedResources but left modernStreamState, so a crash-then-reconnect on the same instance held an empty set alongside `{ active: true }` — a combination the rest of the file treats as impossible, since onModernSubscriptionClosed and onModernReconnectFailed both compute `active` from `subscribedResources.size > 0`, and the comment at :4712 asserts a terminal drop clears both. No symptom today only because the UI mirror resets itself independently, in another file — which is the arrangement this PR has spent its rounds removing. Clearing it here also announces the reset; that set's every other mutation dispatches. Also from review: - The web re-seed treated "no server found" as the default level rather than Off, because resolveModernLogLevel returns the default for absent *settings*. Reachable via a second disconnect after a crash, and via removing the active server. Now distinguishes the two. - Converged the two injectRequest copies: withTimeout takes an optional onTimeout, so both drop their waiter on the timeout path. The newer copy had lost exactly the cleanup that was round 33's reason for leaving the original alone. Test seeds the stream state a live subscription would have left; verified load-bearing (the earlier version passed either way, since the fixture never activates a stream). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(web,core): correct the re-seed branch; share the subscription-stream reset (#1797) Round-44 review. My round-43 fix traded one wrong branch for another: it read `?.settings`, which is undefined both when no server matched *and* when the server has no settings node — and the second is the common case (a hand-written mcp.json entry never opened in Server Settings). Those servers showed Debug while connected and Off after disconnect, which is exactly the client/UI disagreement rounds 41-42 removed, with no modernLogLevelChange event to reconcile it. Now branches on the server. Worth noting no test would have caught it: App.tsx is a documented exclusion from the coverage gate. Also from review: - resetSessionState cleared subscribedResources without announcing it, two lines below a comment arguing that every other mutation of that set dispatches. And it took two statements of a six-statement cluster disconnect() clears together — leaving modernReconnectAttempts (a new session's first drop would back off as if it were the old one's nth), modernListenGeneration (the bump that makes an in-flight re-listen bail), and a stale modernSubscription. One resetSubscriptionStream helper now serves both, announcing both axes; disconnect() keeps only the live stream's best-effort close. That also removed the file's one assignment to modernStreamState that bypassed its setter. - The stream-state test pinned the value, not the dispatch — the half the UI actually tracks. Now asserts both; verified against a bare field assignment. - onModernSubscriptionClosed's comment claimed the disconnect reset always clears the set; on a crash it doesn't until the next connect. Says so. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-45 — reattach the orphaned doc, order the announcements (#1797) Extracting resetSubscriptionStream last round inserted it *and its doc* between resetSessionState's doc and resetSessionState — so two doc blocks stacked, the new helper took the nearest, and the 23-line block explaining each member's symptom attached to nothing. Dead text where it sat, and the most load-bearing comment in the batch. Moved, not reworded. That is round 32's finding in production code, from the same cause: inserting anything between a doc block and its method is a move that needs checking, prose or code. Also from review: - resetSubscriptionStream announced the cleared set before updating the stream state derived from it, so a listener in between saw an empty set with an `active` stream — the combination the helper exists to prevent, exposed by its own dispatches. Both fields move first, then both are announced. The onModernSubscriptionClosed comment now says that window is never observable, which is newly true. - The test header called the log level "cleared"; it is re-seeded, which is the #1629 half of the test twenty lines below. Says "reset", with the distinction spelled out, and the paragraph reflowed in one pass. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * fix(core): close the listen stream the connect-path reset drops (#1797) Round-46 review: resetSubscriptionStream's doc claimed disconnect() is the only caller with a stream worth closing, and the helper did a bare `modernSubscription = null`. Not guaranteed on the connect path — an `onerror` without an `onclose` leaves the transport up, connect() reuses it, and the reset then drops the last reference to a stream still open on the server. Nothing can close it afterwards: the `closed` handler bails on the bumped generation, and `closed` never resolves for a live stream. Before the extraction the surviving reference was eventually closed by refreshModernSubscription as `previous`, so this was newly unclosable. The helper now closes it itself, best-effort, after the dispatches so the round-45 ordering is unaffected; disconnect() drops its two hand-rolled lines. Also from review: - The session test pinned the subscription set's value but not its dispatch — the half the UI tracks, and the gap round 43 closed for the stream axis one line away. Both now asserted; verified load-bearing. - resetSessionState's doc said disconnect() "clears all of this", which is true by duplication for two of the five members; it now says a sixth has to be added in both places. And "the teardown paths" handle the in-flight tool call only on the disconnect route — on a crash it is callTool's own finally. Named. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-47 — fix the doc's count, catch the closed-promise chain (#1797) - resetSessionState's doc said "two members through the same helpers, the other two hand-rolled" for a body with five. It is two and three — and the member the enumeration dropped is the one that is *paired* rather than duplicated: modernLogLevel is re-derived here and blanked in disconnect(), deliberately. Both corrected. - `subscription.closed.then(...)` had no rejection handler, unlike every other promise around that stream. Newly reachable: before the last commit a connect-path reset dropped the reference with `closed` permanently pending, so the chain never settled at all; closing the stream is what makes it settle. Added, with the Node-terminates reasoning the file already applies to payloadPromise. - The listen-stream test exercised transport reuse without asserting it — the half that makes "still open on the server" true. Counts factory calls now, so the premise fails loudly if a future change recreates the transport rather than silently ceasing to apply. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-48 — scope the catch, guard the close, index the test (#1797) - The .catch comment claimed the connect-path close made a *rejecting* `closed` reachable. It doesn't: closing resolves it. What that close newly reaches is the handler running at all, where the reference used to be dropped with `closed` pending forever. And chaining after `.then` also swallowed handler throws — silently abandoning a re-listen on the path whose job is recovering a dropped stream. Now the second argument to `.then`, scoped to the rejection, with the comment saying which half is which. - `closing?.close()` reaches into third-party code from `disconnect()`'s straight-line teardown, none of which is inside a `try` — a synchronous throw would skip the raw-wire rejects, the task aborts, the receiver-task clear and nine dispatches, silently, since most callers catch a disconnect(). Best-effort now against both failure modes. - Header indexes the listen-stream test: same category, but a release obligation rather than a misread one. - Its comment described the generation guard, which the stub can't exercise; marked as production behaviour. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011TrCvpunxToe7qnppk6zwr * review: round-49 — pin the best-effort close, unorphan the doc (#1797) Round 48 made `resetSubscriptionStream`'s close best-effort against both a rejected promise and a synchronous throw, but nothing exercised either arm: both `modernSubscription` stubs in the tree resolve. On the `disconnect()` path an escaping failure would silently skip the raw-wire rejects, the paused task-input aborts, the tool-call abort and `clearReceiverTasks()` — the findings rounds 13 and 30 closed, re-opened at once with a green suite. Two table-driven cases now seed a `close()` that throws and one that rejects, and assert teardown continued past it. Also: the `.then` comment gave opposite verdicts on one mechanism (an unhandled rejection is named unacceptable, then chosen for a handler throw) — reworded to say the handler cannot throw today and why the shape is defensive; and `refreshModernSubscription`'s doc block, orphaned two methods up since before this branch, moved onto the method it describes. Closes #1797 * review: round-50 — sweep the queues start-clean, unify the close (#1797) `resetSessionState`'s doc excluded the peer-request queues and the raw-wire map because "the teardown paths handle them" — true of the paths that run. An `onerror` without an `onclose` runs none of them: it flips status to "error" and leaves `baseTransport` cached, so a `connect()` on the same instance reuses a live transport. That is the route the round-46 stream close was built on, and it strands these two the same way — the web pending-request modal is derived from the queue length with no status gate, so it outlives the session, and answering it writes a response for the old request id onto the new connection. Both are now swept start-clean beside the reset (both helpers are idempotent, so the routes that already ran them are unaffected), the end-clean clears stay put for the `disconnect`-event consumer, and both docs say which is which. Also folds the three subscription `close()` sites onto one `closeSubscriptionBestEffort` helper, so all three absorb a synchronous throw as well as a rejection — at `refreshModernSubscription`'s first site the reference is already dropped, so a throw there both leaks a live stream and aborts the refresh before its replacement is opened. Closes #1797 * review: round-51 — pin the sweep's ordering, name the category (#1797) The connect-start sweep must sit after `resetSessionState()`, and the two calls read as independent. Cancelling a task-augmented peer request settles it synchronously into the record callback, which ends in `upsertReceiverTask` — a no-op only because `clearReceiverTasks()` just emptied the map. Hoisted, it would emit a `notifications/tasks/status` for the outgoing session's task onto the transport the connect is about to reuse. Stated at the call and pinned by a test (which fails on the hoist). Adding that third caller also made five docs stale, all describing the old set by count or as "teardown" — the class round 23 diagnosed. All five now name the category: every route out, plus the top of `connect()` as a backstop for the one route in that settles nothing. And the site where round 50's fold actually changed behaviour — `refreshModernSubscription`'s first close, where the reference is already dropped and a `.catch()` never caught a synchronous throw — is now tested from the public surface (a re-list over a poisoned stream), table-driven over both arms. Verified to fail on the pre-fold form. Closes #1797 * review: round-52 — say what the sweep prevents, scope the close doc (#1797) The sweep's comment named as its harm the exact write the sweep performs: on this route the SDK's transport is still live, so cancelling a queued peer request emits a response for the old id immediately — which is right, and is the settle-don't-discard rule, at the best available moment. As written it read as an argument against emitting the frame, inviting the clear-without- settling regression rounds 24–25 removed. It now names the real hazard: a *user*-authored answer landing arbitrarily later, past the re-handshake. `closeSubscriptionBestEffort`'s "at each site" held at two of three — the superseded-generation discard stored nothing and has nothing following it, so its escaping failure would only reject an already-superseded `subscribeToResource`. Scoped, still wrapped. Also moves the `disconnect()`-side close pair next to its `connect()`-side twin, and states which axis the file's ordering follows, since route and category both describe it and cut differently. Closes #1797 * review: round-53 — give each close site its real harm, pin it (#1797) The doc grouped `resetSubscriptionStream`'s close with the "takes the caller's remaining work with it" sites. It can't: the call is `void`-ed onto an `async` helper, so even a synchronous `close()` throw becomes a dropped rejection — `disconnect()`'s teardown runs regardless. The harm there is an *unhandled* rejection, which this PR already established (the payloadPromise fix) is the process-fatal class in Node — so the one site with the severe failure mode was documented as having the mild one. Each site now carries its own consequence, and the local comment no longer gives two reasons that cancel each other. The test had the same gap: both its assertions hold with the helper's try/catch deleted. It now also asserts no unhandled rejection fired, which does fail without the guard (verified on both arms); the teardown assertions stay, since they still catch unwrapping the call to a bare `close()`. Also names the two back-references the round-52 move left positional, and softens the "on the wire until dropCachedTransport()" claim — that drop is conditional and never runs on stdio. Closes #1797 * review: round-54 — the mildest site isn't mild from every caller (#1797) `refreshModernSubscription` has three callers, and the superseded-generation discard's failure reaches all of them. From `unsubscribeFromResource` — which deliberately keeps the removal when a re-listen fails — it surfaces "Failed to unsubscribe" for an unsubscribe that actually stuck, which is worse than the consequence the doc assigned to the site it called mildest. The re-listen bullet had the mirror gap: on the reconnect caller the escape is absorbed into the backoff run, not a set left with no stream. Both now name their callers, and the generation-bump claim is softened to what it proves (a newer refresh *started*). Test: the `unhandledRejection` listener is process-wide, so the assertion now filters to this fixture's own reason rather than failing on a rejection some other test left pending; and it is registered inside the `try` whose `finally` removes it, so a throw in the setup can't leak it into the rest of the file. Re-verified the filtered form still fails on both arms with the helper's try/catch removed. Closes #1797 * fix(core): don't roll back a subscribe a newer refresh superseded (#1797) `subscribeToResource`'s rollback assumes what its comment says — that the server filter is unchanged — which is exactly what supersession falsifies. The newer refresh built its filter from the set *including* this URI, so on success the server honors it; rolling back leaves the set missing a URI the live stream carries (the UI showing it unsubscribed while its resources/updated keep arriving) and, if it was the only one, an empty set with an active stream — the combination `resetSubscriptionStream` exists to prevent, reached from the other end. Reachable without any close() failure: a rejecting `listen()` propagates the same way, which a user subscribing while the reconnect timer re-lists — i.e. exactly when the server is flaky — can produce. The rollback is now gated on the generation not having advanced past this call's own bump; the error still reaches the caller either way. Test drives two overlapping subscribes with the first `listen()` rejecting, and fails without the gate. The doc bullet that called this the mild site is corrected with it: both user-initiated callers report a failure that did not happen, in mirrored ways. Also gives the two close-failure arms distinct reasons so the unhandled-rejection filter can exclude the sibling arm as well as a foreign rejection. Closes #1797 * fix(core): reconcile the stream badge when a re-listen this call owned fails The supersession gate left the both-fail case stuck: two overlapping subscribes whose listens both reject leave the superseded URI in the set (its rollback correctly skipped) while the state keeps the optimistic "connecting" — no stream, no reconnect armed (neither onModernSubscriptionClosed nor onModernReconnectFailed ran), so the badge never changes and no resources/updated ever arrive. That is the caveat this file already wrote down for the neighbouring case — the bump proves a newer refresh *started* — applied to the gate itself. Fixed in the branch that knows the answer: the call that still owns the re-listen reconciles the state instead of only handling an emptied set, reusing the "ended" badge onModernSubscriptionClosed already reports for "stream gone, URIs still subscribed". unsubscribeFromResource gets the same treatment — it rolls nothing back by design, but its failed re-listen left the badge reading Listening over no stream. Also: the gate's comment named one of the two things that bump the generation (resetSubscriptionStream also does, from disconnect and the start-clean reset) and cross-referenced the wrong invariant; both corrected, and `<=` tightened to `===`, which is what the monotonic synchronous bump actually guarantees. Closes #1797 * fix(core): order the subscription writes, retry instead of stranding Two sites emptied the subscription set and announced it before the stream state caught up — the last-URI rollback in subscribeToResource's catch, and (pre-existing) the ordinary last-URI unsubscribe, which dispatches a round-trip before the re-listen sets INACTIVE. Both exposed an empty set with an active stream: the pair resetSubscriptionStream orders its own writes to prevent, and which three comments in this branch now cite. State before the announce at both, asserted from the consumer's side. And the reconcile added last round settled for an honest but dead badge: it was the only route to "stream gone, URIs live" that had made no attempt at all, over subscriptions the server may never have honored, recoverable only by an Unsubscribe/Subscribe toggle (a fresh Subscribe early-returns). It now hands them to the reconnect machinery, which already fits — base delay after a user-initiated refresh, bails on a terminal status or an emptied set, and lands on the same "ended" badge past the cap. That also removes the provably-dead null check the reconcile carried. Closes #1797 --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
cea22d86b8
commit
c2af547cc8
17 changed files with 2624 additions and 331 deletions
|
|
@ -78,7 +78,9 @@ npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --tr
|
|||
npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --transport http --method tools/list --header "X-API-Key: your-api-key"
|
||||
```
|
||||
|
||||
When a server is loaded from a `--catalog`/`--config` file, its per-server settings (headers, connection/request timeouts, and OAuth) are applied to the connection — the same resolution the TUI uses. A `--header` flag overrides the file's headers for that run while leaving the file's timeouts and OAuth in place.
|
||||
When a server is loaded from a `--catalog`/`--config` file, its per-server settings (headers, connection/request timeouts, OAuth, and `roots`) are applied to the connection — the same resolution the TUI uses. A `--header` flag overrides the file's headers for that run while leaving the file's timeouts and OAuth in place.
|
||||
|
||||
The file is the only durable way to give a run its roots: there is no roots flag, and `--method roots/set` applies only to that one short-lived connection. Roots configured for a server (the same field the web UI's Server Settings writes) are advertised at connect, so a server that asks for `roots/list` — `@modelcontextprotocol/server-filesystem` does, to learn its allowed directories — gets them.
|
||||
|
||||
**Environment-variable semantics.** `MCP_CATALOG_PATH` is honored only when no ad-hoc target is given (positional command, `--server-url`, or `--transport`) — so a shell that exports it can still run one-off ad-hoc invocations without hitting the catalog/ad-hoc conflict. `MCP_STORAGE_DIR` sets the storage directory used by the OAuth persist backend (`<MCP_STORAGE_DIR>/oauth.json`); the per-file `MCP_INSPECTOR_OAUTH_STATE_PATH` override still takes precedence over it.
|
||||
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import {
|
|||
getTestMcpServerCommand,
|
||||
createTestServerHttp,
|
||||
createEchoTool,
|
||||
createListRootsTool,
|
||||
createTestServerInfo,
|
||||
} from "@modelcontextprotocol/inspector-test-server";
|
||||
import type { MCPServerConfig } from "@modelcontextprotocol/inspector-core/mcp/index.js";
|
||||
|
|
@ -325,6 +326,89 @@ describe("CLI Tests", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("Roots capability (#1797)", () => {
|
||||
it("answers a server's roots/list instead of -32601", async () => {
|
||||
// The CLI used to omit `roots` when constructing its InspectorClient, so
|
||||
// the capability was never advertised and no `roots/list` handler was
|
||||
// registered — a server that asked got -32601 Method not found. (And
|
||||
// `--method roots/set` could not announce the change: the SDK refuses
|
||||
// `roots/list_changed` from a client that never declared it, so nothing
|
||||
// reached the wire.) `cli.ts` now always passes the `roots` option —
|
||||
// empty on this ad-hoc path, since there is no config file.
|
||||
const server = createTestServerHttp({
|
||||
serverInfo: createTestServerInfo(),
|
||||
tools: [createListRootsTool()],
|
||||
});
|
||||
try {
|
||||
await server.start();
|
||||
|
||||
const result = await runCli([
|
||||
server.url,
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/call",
|
||||
"--tool-name",
|
||||
"list_roots",
|
||||
]);
|
||||
|
||||
expectCliSuccess(result);
|
||||
const json = expectValidJson(result);
|
||||
// The tool asks the client for roots and renders what it got. An
|
||||
// unregistered handler surfaces as an isError result quoting -32601.
|
||||
expect(json.isError).toBeFalsy();
|
||||
expect(JSON.stringify(json)).toContain("Roots:");
|
||||
expect(JSON.stringify(json)).not.toContain("-32601");
|
||||
} finally {
|
||||
await server.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("answers with the roots configured for the server in the config file", async () => {
|
||||
// Answering `roots/list` is only half the fix: the roots a user
|
||||
// configured in mcp.json have to be the answer. They ride in on
|
||||
// `serverSettings.roots` (lifted by `mcpConfigToServerEntries`), which is
|
||||
// what web passes too — a CLI that seeded `[]` would let a server fall
|
||||
// back to its own defaults, the outcome #1797 is about.
|
||||
const server = createTestServerHttp({
|
||||
serverInfo: createTestServerInfo(),
|
||||
tools: [createListRootsTool()],
|
||||
});
|
||||
let configPath: string | undefined;
|
||||
try {
|
||||
await server.start();
|
||||
configPath = createTestConfig({
|
||||
mcpServers: {
|
||||
web: {
|
||||
type: "streamable-http",
|
||||
url: server.url,
|
||||
roots: [{ uri: "file:///configured", name: "Configured" }],
|
||||
} as unknown as MCPServerConfig,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await runCli([
|
||||
"--config",
|
||||
configPath,
|
||||
"--server",
|
||||
"web",
|
||||
"--cli",
|
||||
"--method",
|
||||
"tools/call",
|
||||
"--tool-name",
|
||||
"list_roots",
|
||||
]);
|
||||
|
||||
expectCliSuccess(result);
|
||||
const json = expectValidJson(result);
|
||||
expect(json.isError).toBeFalsy();
|
||||
expect(JSON.stringify(json)).toContain("file:///configured");
|
||||
} finally {
|
||||
await server.stop();
|
||||
if (configPath) deleteConfigFile(configPath);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Config-file settings lifting (#1482)", () => {
|
||||
it("applies a config file's custom header on a tools/call over HTTP", async () => {
|
||||
const server = createTestServerHttp({
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import { describe, it, expect, afterEach, vi } from "vitest";
|
||||
import { getTestMcpServerCommand } from "@modelcontextprotocol/inspector-test-server";
|
||||
import { InspectorClient } from "@inspector/core/mcp/index.js";
|
||||
import { createTransportNode } from "@inspector/core/mcp/node/index.js";
|
||||
|
|
@ -25,6 +25,9 @@ describe("runMethod", () => {
|
|||
progress: false,
|
||||
sample: false,
|
||||
elicit: false,
|
||||
// Mirrors `cli.ts`, which always passes the option so the capability is
|
||||
// negotiated and the `roots/list` handler registered (#1797).
|
||||
roots: [],
|
||||
},
|
||||
);
|
||||
await client.connect();
|
||||
|
|
@ -92,6 +95,33 @@ describe("runMethod", () => {
|
|||
}
|
||||
});
|
||||
|
||||
it("roots/set drops a malformed root rather than advertising it", async () => {
|
||||
// `--roots-json` only checks that the payload parses to an array, so a
|
||||
// root with no `uri` used to be stored and then handed to the server in
|
||||
// the `roots/list` reply — an invalid Root on the wire, echoed back to the
|
||||
// user as success. `setRoots` normalizes through `cleanRoots` now (#1797).
|
||||
const c = await connectStdio();
|
||||
// cleanRoots reports the drop; suppress it here and assert it happened, so
|
||||
// the test also covers that a dropped root is not dropped silently.
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
try {
|
||||
const set = await runMethod(c, {
|
||||
method: "roots/set",
|
||||
rootsJson: JSON.stringify([
|
||||
{ name: "no uri" },
|
||||
{ uri: "file:///keep" },
|
||||
]),
|
||||
});
|
||||
expect(set.kind).toBe("result");
|
||||
if (set.kind === "result") {
|
||||
expect(set.result.roots).toEqual([{ uri: "file:///keep" }]);
|
||||
}
|
||||
expect(warn).toHaveBeenCalled();
|
||||
} finally {
|
||||
warn.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("consumeMethodOutcome writes result json", async () => {
|
||||
let stdout = "";
|
||||
const original = process.stdout.write;
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { listServerEntries, showServerEntry } from "./handlers/servers-list.js";
|
|||
import { writeFormattedResult } from "./handlers/format-output.js";
|
||||
import { clearStoredAuthForRelogin } from "./clear-stored-auth-for-relogin.js";
|
||||
import { InspectorClient } from "@inspector/core/mcp/index.js";
|
||||
import { cleanRoots } from "@inspector/core/mcp/serverList.js";
|
||||
import {
|
||||
createTransportNode,
|
||||
loadServerEntries,
|
||||
|
|
@ -152,6 +153,15 @@ async function callMethod(
|
|||
progress: false,
|
||||
sample: false,
|
||||
elicit: false,
|
||||
// Advertise the roots configured for this server in mcp.json, exactly as
|
||||
// web does (`App.tsx`) so both answer `roots/list` with the same content.
|
||||
// Passing the option (even empty) is what negotiates `capabilities.roots`
|
||||
// at `initialize` and registers the `roots/list` handler. Omitting it meant
|
||||
// a server that asks for roots on its own — `server-filesystem` does, at
|
||||
// `initialize` — got -32601, and `--method roots/set` could not announce
|
||||
// the change at all: the SDK refuses `roots/list_changed` from a client
|
||||
// that never declared it, which `setRoots` logged as a send failure (#1797).
|
||||
roots: cleanRoots(serverSettings?.roots ?? []),
|
||||
serverSettings,
|
||||
// Per-server protocol era (SEP §7.8) from mcp.json → SDK versionNegotiation.
|
||||
// Absent era defaults to legacy in the InspectorClient constructor (#1626).
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import type {
|
|||
GetPromptResult,
|
||||
} from "@modelcontextprotocol/client";
|
||||
import { InspectorClient } from "@inspector/core/mcp/index.js";
|
||||
import { cleanRoots } from "@inspector/core/mcp/serverList.js";
|
||||
import { eraToVersionNegotiation } from "@inspector/core/mcp/types.js";
|
||||
import {
|
||||
ManagedToolsState,
|
||||
|
|
@ -304,6 +305,11 @@ function App({
|
|||
defaultMetadata,
|
||||
}),
|
||||
...(savedSettings && { serverSettings: savedSettings }),
|
||||
// Advertise the roots configured for this server in mcp.json, as web
|
||||
// and the CLI do. The TUI has no roots editor, but a user who set
|
||||
// roots in the web UI expects them to apply to the same server here
|
||||
// (#1797).
|
||||
roots: cleanRoots(savedSettings?.roots ?? []),
|
||||
// Per-server protocol era (SEP §7.8) from mcp.json → SDK
|
||||
// versionNegotiation; absent era defaults to legacy (#1626).
|
||||
...(savedSettings?.protocolEra && {
|
||||
|
|
|
|||
|
|
@ -44,9 +44,9 @@ import type {
|
|||
} from "@inspector/core/mcp/types.js";
|
||||
import {
|
||||
DEFAULT_MAX_FETCH_REQUESTS,
|
||||
DEFAULT_MODERN_LOG_LEVEL,
|
||||
DEFAULT_TASK_TTL_MS,
|
||||
eraToVersionNegotiation,
|
||||
resolveModernLogLevel,
|
||||
} from "@inspector/core/mcp/types.js";
|
||||
import {
|
||||
API_SERVER_ENV_VARS,
|
||||
|
|
@ -1216,7 +1216,27 @@ function App() {
|
|||
setConsoleUi(EMPTY_CONSOLE_UI);
|
||||
setProgressByTaskId({});
|
||||
setCurrentLogLevel("info");
|
||||
setModernLogLevel(null);
|
||||
// Re-seed rather than blank: the client restores its own opt-in from the
|
||||
// server setting at connect (`resetSessionState`), so blanking here would
|
||||
// leave the control reading Off while every modern request still carries
|
||||
// the level — visible on the auth-recovery path, which reconnects the same
|
||||
// client instance rather than rebuilding it (#1629, #1797).
|
||||
// `activeServerIdRef` is synced in a passive effect, so it still holds the
|
||||
// outgoing server's id when this runs from `onDisconnect` — which is what
|
||||
// lets the re-seed find its settings. Clearing that ref eagerly would take
|
||||
// the no-server branch below and silently drop this to Off.
|
||||
// Branch on the *server*, not its settings: an entry with no settings node
|
||||
// is the common case (`mcp.json` written by hand, never opened in Server
|
||||
// Settings), and there the default is right — it is what the seed and the
|
||||
// client both use. Only "no server at all" means Off.
|
||||
const activeServer = serversRef.current.find(
|
||||
(s) => s.id === activeServerIdRef.current,
|
||||
);
|
||||
setModernLogLevel(
|
||||
activeServer
|
||||
? (resolveModernLogLevel(activeServer.settings) ?? null)
|
||||
: null,
|
||||
);
|
||||
setPendingStepUp(null);
|
||||
setPendingReauth(null);
|
||||
setReAuthBanner(null);
|
||||
|
|
@ -2337,9 +2357,7 @@ function App() {
|
|||
// setting so the Logs-tab control reflects what the client stamps by
|
||||
// default (the client was seeded the same way in its constructor). "off"
|
||||
// means not opted in (null). Only affects modern connections.
|
||||
const seededModernLevel =
|
||||
savedSettings?.modernLogLevel ?? DEFAULT_MODERN_LOG_LEVEL;
|
||||
setModernLogLevel(seededModernLevel === "off" ? null : seededModernLevel);
|
||||
setModernLogLevel(resolveModernLogLevel(savedSettings) ?? null);
|
||||
setManagedToolsState(new ManagedToolsState(client));
|
||||
setPagedToolsState(new PagedToolsState(client));
|
||||
setPagedPromptsState(new PagedPromptsState(client));
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
20
clients/web/src/test/core/mcp/modernLogLevel.test.ts
Normal file
20
clients/web/src/test/core/mcp/modernLogLevel.test.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
DEFAULT_MODERN_LOG_LEVEL,
|
||||
resolveModernLogLevel,
|
||||
} from "@inspector/core/mcp/types.js";
|
||||
|
||||
describe("resolveModernLogLevel", () => {
|
||||
it("falls back to the default when unset", () => {
|
||||
expect(resolveModernLogLevel()).toBe(DEFAULT_MODERN_LOG_LEVEL);
|
||||
expect(resolveModernLogLevel({})).toBe(DEFAULT_MODERN_LOG_LEVEL);
|
||||
});
|
||||
|
||||
it('treats "off" as not opted in', () => {
|
||||
expect(resolveModernLogLevel({ modernLogLevel: "off" })).toBeUndefined();
|
||||
});
|
||||
|
||||
it("passes an explicit level through", () => {
|
||||
expect(resolveModernLogLevel({ modernLogLevel: "error" })).toBe("error");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import {
|
||||
cleanRoots,
|
||||
DEFAULT_SEED_CONFIG,
|
||||
|
|
@ -23,6 +23,7 @@ import type {
|
|||
ServerEntry,
|
||||
StoredMCPServer,
|
||||
} from "@inspector/core/mcp/types.js";
|
||||
import type { Root } from "@modelcontextprotocol/client";
|
||||
|
||||
describe("normalizeServerType", () => {
|
||||
it("defaults missing type to stdio", () => {
|
||||
|
|
@ -102,6 +103,53 @@ describe("cleanRoots", () => {
|
|||
{ uri: "file:///b", _meta: { k: 2 } },
|
||||
]);
|
||||
});
|
||||
|
||||
// Every client now feeds this straight from hand-editable mcp.json (#1797),
|
||||
// where `Root[]` is only a compile-time promise. Malformed input must be
|
||||
// reported and skipped, not thrown at connect.
|
||||
describe("malformed input from disk", () => {
|
||||
let warn: ReturnType<typeof vi.spyOn>;
|
||||
beforeEach(() => {
|
||||
warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => {
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it("drops an entry with no uri instead of throwing", () => {
|
||||
// A hand-edited `"roots": [{ "name": "Work" }]`.
|
||||
const malformed = [{ name: "Work" }, { uri: "file:///ok" }];
|
||||
expect(cleanRoots(malformed as unknown as Root[])).toEqual([
|
||||
{ uri: "file:///ok" },
|
||||
]);
|
||||
expect(warn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("drops an entry whose uri is not a string", () => {
|
||||
const malformed = [{ uri: 42 }, { uri: "file:///ok" }];
|
||||
expect(cleanRoots(malformed as unknown as Root[])).toEqual([
|
||||
{ uri: "file:///ok" },
|
||||
]);
|
||||
expect(warn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a root whose name is not a string, dropping just the name", () => {
|
||||
// `name` is optional, so a bad one costs the name, not the root.
|
||||
expect(
|
||||
cleanRoots([
|
||||
{ uri: "file:///a", name: 42 },
|
||||
{ uri: "file:///b", name: { x: 1 } },
|
||||
] as unknown as Root[]),
|
||||
).toEqual([{ uri: "file:///a" }, { uri: "file:///b" }]);
|
||||
expect(warn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("bails to an empty list when roots is not an array", () => {
|
||||
// A hand-edited `"roots": "file:///work"`.
|
||||
expect(cleanRoots("file:///work" as unknown as Root[])).toEqual([]);
|
||||
expect(warn).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("mcpConfigToServerEntries", () => {
|
||||
|
|
|
|||
|
|
@ -57,23 +57,6 @@ async function getTool(client: InspectorClient, name: string): Promise<Tool> {
|
|||
return tool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach a no-op catch to every outstanding receiver-task payload promise so a
|
||||
* deliberate reject (failure-path test) doesn't bubble up as an unhandled
|
||||
* rejection. The real consumer (the server polling tasks/result) handles the
|
||||
* rejection, but it may not have a handler attached at the instant we reject.
|
||||
*/
|
||||
function suppressReceiverPayloadRejections(client: InspectorClient): void {
|
||||
const records = (
|
||||
client as unknown as {
|
||||
receiverTaskRecords: Map<string, { payloadPromise: Promise<unknown> }>;
|
||||
}
|
||||
).receiverTaskRecords;
|
||||
for (const record of records.values()) {
|
||||
record.payloadPromise.catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
describe("InspectorClient coverage backfill", () => {
|
||||
let client: InspectorClient | null = null;
|
||||
let server: TestServerHttp | null = null;
|
||||
|
|
@ -200,8 +183,11 @@ describe("InspectorClient coverage backfill", () => {
|
|||
});
|
||||
|
||||
describe("setRoots", () => {
|
||||
it("enables roots when previously undefined and dispatches rootsChange", async () => {
|
||||
// No roots option → this.roots is undefined initially.
|
||||
it("stores roots and dispatches rootsChange when none were configured", async () => {
|
||||
// No roots option → this.roots is undefined initially. Note setRoots does
|
||||
// *not* enable the capability: this client still has no `roots/list`
|
||||
// handler and no `capabilities.roots`, so only `getRoots()` reflects the
|
||||
// change — see the note on setRoots (#1797).
|
||||
client = stdioClient();
|
||||
await client.connect();
|
||||
const rootsChange = waitForEvent(client, "rootsChange", {
|
||||
|
|
@ -323,9 +309,6 @@ describe("InspectorClient coverage backfill", () => {
|
|||
.catch((e: unknown) => e);
|
||||
|
||||
const sample = await samplingPromise;
|
||||
// Pre-attach a catch to the receiver task's payload promise so its
|
||||
// rejection (driven below) doesn't surface as an unhandled rejection.
|
||||
suppressReceiverPayloadRejections(client);
|
||||
// Reject instead of respond — drives the receiver-task error callback,
|
||||
// which sets status "failed" and calls upsertReceiverTask.
|
||||
await sample.reject(new Error("user rejected sampling"));
|
||||
|
|
@ -374,7 +357,6 @@ describe("InspectorClient coverage backfill", () => {
|
|||
.catch((e: unknown) => e);
|
||||
|
||||
const elicitation = await elicitationPromise;
|
||||
suppressReceiverPayloadRejections(client);
|
||||
await elicitation.reject(new Error("user declined elicitation"));
|
||||
|
||||
const outcome = await callPromise;
|
||||
|
|
|
|||
|
|
@ -297,6 +297,196 @@ describe("resource subscriptions era fork (#1630)", () => {
|
|||
return fake;
|
||||
}
|
||||
|
||||
for (const [label, close] of [
|
||||
[
|
||||
"throws synchronously",
|
||||
(): Promise<void> => {
|
||||
throw new Error("close blew up");
|
||||
},
|
||||
],
|
||||
[
|
||||
"returns a rejected promise",
|
||||
(): Promise<void> => Promise.reject(new Error("close blew up")),
|
||||
],
|
||||
] as const) {
|
||||
it(`re-lists when the superseded stream's close() ${label}`, async () => {
|
||||
// A re-list drops its reference to the previous stream *before* closing
|
||||
// it, so an escaping failure would both abandon a stream that may still
|
||||
// be open on the server and abort the refresh before its replacement
|
||||
// `listen()` — leaving a non-empty subscription set with no stream. The
|
||||
// close is best-effort against both failure modes for that reason; this
|
||||
// is the site where being best-effort against the *synchronous* one
|
||||
// changed behaviour (a `.catch()` alone never caught it).
|
||||
const started = await startServer({});
|
||||
const { connected } = await connect(started.url, "modern");
|
||||
await connected.subscribeToResource(RESOURCE_URI);
|
||||
|
||||
const int = internals(connected);
|
||||
// Swap the live stream for a poisoned one, closing the real stream so
|
||||
// the wire is torn down (as `installFakeSubscription` does).
|
||||
const real = int.modernSubscription;
|
||||
int.modernSubscription = { close } as unknown as McpSubscription;
|
||||
await real?.close().catch(() => {});
|
||||
|
||||
// A second URI changes the filter, so this re-lists over the poisoned
|
||||
// stream.
|
||||
await expect(
|
||||
connected.subscribeToResource(RESOURCE_URI_2),
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(connected.getSubscribedResources()).toEqual([
|
||||
RESOURCE_URI,
|
||||
RESOURCE_URI_2,
|
||||
]);
|
||||
const state = connected.getResourceSubscriptionStreamState();
|
||||
expect(state.active).toBe(true);
|
||||
expect(state.status).toBe("acknowledged");
|
||||
expect(int.modernSubscription).not.toBeNull();
|
||||
});
|
||||
}
|
||||
|
||||
it("keeps the optimistic add when a newer refresh superseded the failure", async () => {
|
||||
// The rollback's premise is that the server filter is unchanged, which is
|
||||
// exactly what supersession falsifies: the newer refresh built its filter
|
||||
// from the set *including* this URI, so on success the server honors it.
|
||||
// Rolling back anyway would leave the set missing a URI the live stream
|
||||
// carries — and with only one subscribed, an empty set with an active
|
||||
// stream, the combination `resetSubscriptionStream` exists to prevent.
|
||||
// Reachable without any close() failure: a rejecting `listen()` does it,
|
||||
// which is what a user subscribing while the reconnect timer re-lists
|
||||
// (i.e. exactly when the server is flaky) can produce.
|
||||
const started = await startServer({});
|
||||
const { connected } = await connect(started.url, "modern");
|
||||
const int = internals(connected);
|
||||
|
||||
const real = int.client.listen;
|
||||
// The first listen hangs, so the second can supersede it before it fails.
|
||||
let failFirst: (error: Error) => void = () => {};
|
||||
int.client.listen = () =>
|
||||
new Promise<McpSubscription>((_, reject) => {
|
||||
failFirst = reject;
|
||||
});
|
||||
const first = connected.subscribeToResource(RESOURCE_URI);
|
||||
// Attached before the supersession so the rejection is never unhandled.
|
||||
const firstSettled = expect(first).rejects.toThrow(/listen boom/);
|
||||
|
||||
// A newer refresh starts and acknowledges, carrying both URIs.
|
||||
int.client.listen = real;
|
||||
await connected.subscribeToResource(RESOURCE_URI_2);
|
||||
|
||||
failFirst(new Error("listen boom"));
|
||||
await firstSettled;
|
||||
|
||||
// The superseded call still reports its failure, but leaves the filter to
|
||||
// the refresh that owns it.
|
||||
expect(connected.getSubscribedResources()).toEqual([
|
||||
RESOURCE_URI,
|
||||
RESOURCE_URI_2,
|
||||
]);
|
||||
const state = connected.getResourceSubscriptionStreamState();
|
||||
expect(state.active).toBe(true);
|
||||
expect(state.status).toBe("acknowledged");
|
||||
});
|
||||
|
||||
it("retries rather than stranding the URIs when both overlapping subscribes fail", async () => {
|
||||
// The other half of the gate: skipping the superseded call's rollback is
|
||||
// only safe if the superseding call reconciles when *it* fails too.
|
||||
// Otherwise the set keeps the first URI while the state keeps the
|
||||
// optimistic "connecting" — a badge that never changes, over a
|
||||
// subscription no server ever honored, with nothing armed to fix it
|
||||
// (neither `onModernSubscriptionClosed` nor `onModernReconnectFailed`
|
||||
// ran). The reconcile hands it to the reconnect machinery instead.
|
||||
const started = await startServer({});
|
||||
const { connected } = await connect(started.url, "modern");
|
||||
const int = internals(connected);
|
||||
|
||||
let failFirst: (error: Error) => void = () => {};
|
||||
int.client.listen = () =>
|
||||
new Promise<McpSubscription>((_, reject) => {
|
||||
failFirst = reject;
|
||||
});
|
||||
const first = connected.subscribeToResource(RESOURCE_URI);
|
||||
const firstSettled = expect(first).rejects.toThrow(/listen boom/);
|
||||
|
||||
// The superseding call fails on its own listen.
|
||||
int.client.listen = () => Promise.reject(new Error("listen boom 2"));
|
||||
await expect(
|
||||
connected.subscribeToResource(RESOURCE_URI_2),
|
||||
).rejects.toThrow(/listen boom 2/);
|
||||
|
||||
failFirst(new Error("listen boom"));
|
||||
await firstSettled;
|
||||
|
||||
// Its own URI rolled back; the superseded one survives — and rather than
|
||||
// sitting at "connecting" forever it is now a retry in progress.
|
||||
expect(connected.getSubscribedResources()).toEqual([RESOURCE_URI]);
|
||||
expect(connected.getResourceSubscriptionStreamState().status).toBe(
|
||||
"reconnecting",
|
||||
);
|
||||
|
||||
// And the retry makes the state true: the next re-listen acknowledges.
|
||||
int.client.listen = () => Promise.resolve(makeFakeSub().sub);
|
||||
await vi.waitFor(() => {
|
||||
expect(connected.getResourceSubscriptionStreamState().status).toBe(
|
||||
"acknowledged",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("retries rather than stranding the URIs when the unsubscribe's re-listen fails", async () => {
|
||||
// `unsubscribeFromResource` keeps its removal when the re-listen fails,
|
||||
// so nothing is rolled back — but the stream is gone with URIs still
|
||||
// subscribed, and without the reconcile the badge would keep reporting
|
||||
// the previous success ("acknowledged"/Listening) over no stream at all.
|
||||
const started = await startServer({});
|
||||
const { connected } = await connect(started.url, "modern");
|
||||
await connected.subscribeToResource(RESOURCE_URI);
|
||||
await connected.subscribeToResource(RESOURCE_URI_2);
|
||||
expect(connected.getResourceSubscriptionStreamState().status).toBe(
|
||||
"acknowledged",
|
||||
);
|
||||
|
||||
const int = internals(connected);
|
||||
int.client.listen = () => Promise.reject(new Error("re-listen boom"));
|
||||
await expect(
|
||||
connected.unsubscribeFromResource(RESOURCE_URI_2),
|
||||
).rejects.toThrow(/re-listen boom/);
|
||||
|
||||
expect(connected.getSubscribedResources()).toEqual([RESOURCE_URI]);
|
||||
expect(connected.getResourceSubscriptionStreamState().status).toBe(
|
||||
"reconnecting",
|
||||
);
|
||||
});
|
||||
|
||||
it("never announces an empty subscription set with an active stream", async () => {
|
||||
// The pair `resetSubscriptionStream` orders its own writes to prevent,
|
||||
// asserted from the consumer's side at the two sites that empty the set
|
||||
// outside it: the last-URI unsubscribe (happy path, where the re-listen
|
||||
// that would set INACTIVE is a round-trip away) and the last-URI rollback
|
||||
// of a failed subscribe (where the state still reads "connecting").
|
||||
const started = await startServer({});
|
||||
const { connected } = await connect(started.url, "modern");
|
||||
const seen: { size: number; active: boolean }[] = [];
|
||||
connected.addEventListener("resourceSubscriptionsChange", () => {
|
||||
seen.push({
|
||||
size: connected.getSubscribedResources().length,
|
||||
active: connected.getResourceSubscriptionStreamState().active,
|
||||
});
|
||||
});
|
||||
|
||||
await connected.subscribeToResource(RESOURCE_URI);
|
||||
await connected.unsubscribeFromResource(RESOURCE_URI);
|
||||
|
||||
const int = internals(connected);
|
||||
int.client.listen = () => Promise.reject(new Error("listen boom"));
|
||||
await expect(connected.subscribeToResource(RESOURCE_URI)).rejects.toThrow(
|
||||
/listen boom/,
|
||||
);
|
||||
|
||||
expect(seen.length).toBeGreaterThan(0);
|
||||
expect(seen.filter((s) => s.size === 0 && s.active)).toEqual([]);
|
||||
});
|
||||
|
||||
it("rolls back the optimistic add when listen() fails", async () => {
|
||||
const started = await startServer({});
|
||||
const { connected } = await connect(started.url, "modern");
|
||||
|
|
|
|||
|
|
@ -5560,7 +5560,9 @@ describe("InspectorClient", () => {
|
|||
initialStatus: "working",
|
||||
statusMessage: "running",
|
||||
});
|
||||
// Pre-attach a catch so cancel's reject doesn't surface as unhandled
|
||||
// Capture the rejection's message for the assertion below. (Not for
|
||||
// unhandled-rejection suppression — `createReceiverTask` marks the
|
||||
// promise handled at the source.)
|
||||
const payloadResult = record.payloadPromise.catch(
|
||||
(e) => (e as Error).message,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -102,11 +102,17 @@ export class ElicitationCreateMessage {
|
|||
|
||||
/**
|
||||
* Settle a still-pending elicitation as cancelled, without removing it from
|
||||
* the queue. Used by `disconnect()` teardown so an awaiting caller — notably
|
||||
* the error-path `awaitUrlElicitation` that blocks `callTool` — doesn't hang
|
||||
* forever when the pending queue is dropped wholesale. No-op once already
|
||||
* resolved; deliberately does not call `onRemove` (the caller clears the
|
||||
* queue itself, so we must not splice it mid-iteration).
|
||||
* the queue. Called from `InspectorClient`'s `clearPendingPeerRequests()`,
|
||||
* which serves every route that drops the queue wholesale — each route out of
|
||||
* a connection, and the top of `connect()` as a backstop for the one route in
|
||||
* that settles nothing — so an awaiting caller (notably the error-path
|
||||
* `awaitUrlElicitation` that blocks `callTool`) doesn't hang forever. The
|
||||
* category, not a count: that set has grown. No-op once already resolved.
|
||||
*
|
||||
* Deliberately does not call `onRemove`: that caller iterates the queue and
|
||||
* clears it itself, so removing here would splice mid-iteration — skipping
|
||||
* every other entry and leaving those promises unsettled, the exact hang this
|
||||
* method exists to prevent.
|
||||
*/
|
||||
cancel(): void {
|
||||
if (this.resolvePromise) {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -86,6 +86,42 @@ export class SamplingCreateMessage {
|
|||
this.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* Settle a still-pending sample as cancelled, without removing it from the
|
||||
* queue. Called from `InspectorClient`'s `clearPendingPeerRequests()`, which
|
||||
* serves every route that drops the queue wholesale — each route out of a
|
||||
* connection, and the top of `connect()` as a backstop for the one route in
|
||||
* that settles nothing. The category, not a count: that set has grown.
|
||||
*
|
||||
* Unlike an elicitation there is no internal awaiter to unblock, but on the
|
||||
* plain server-request shape the *server* is one: we accepted its
|
||||
* `sampling/createMessage`, so dropping the request without settling means no
|
||||
* response frame is ever written and it waits forever. That is reachable when
|
||||
* the transport outlives the failed attempt — `connect()` keeps it when an
|
||||
* auth provider holds it open — so settle rather than discard. Rejecting is
|
||||
* the right settle: it is what the UI's decline path sends, and the SDK turns
|
||||
* it into a JSON-RPC error response. No-op once already resolved.
|
||||
*
|
||||
* A *task-augmented* sample sits in the same queue but already answered the
|
||||
* wire request synchronously with a `CreateTaskResult`, so nothing is waiting
|
||||
* on a frame; settling there is about not leaving the task in
|
||||
* `input_required` limbo. Its reject reaches the receiver task's payload
|
||||
* promise, which `InspectorClient` marks handled at creation for exactly this
|
||||
* reason.
|
||||
*
|
||||
* Deliberately does not call `onRemove`, for the same reason as
|
||||
* `ElicitationCreateMessage.cancel()`: the caller iterates the queue and
|
||||
* clears it itself, so removing here would splice mid-iteration — skipping
|
||||
* every other entry and leaving those requests unanswered.
|
||||
*/
|
||||
cancel(): void {
|
||||
if (this.rejectPromise) {
|
||||
this.rejectPromise(new Error("Connection torn down"));
|
||||
}
|
||||
this.resolvePromise = undefined;
|
||||
this.rejectPromise = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove this pending sample from the list
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -88,19 +88,48 @@ export function normalizeServerType(
|
|||
}
|
||||
|
||||
/**
|
||||
* Normalize the form's controlled root rows into the shape the Inspector
|
||||
* advertises and persists: drop rows whose `uri` is blank (the form leaves a
|
||||
* new row empty mid-edit) and drop a blank/whitespace `name`. Any other fields
|
||||
* a root carries (e.g. `_meta` from a hand-edited `mcp.json`) are preserved —
|
||||
* only `uri`/`name` are normalized. Shared by the settings → disk converter
|
||||
* (`inspectorSettingsToStoredFields`) and the web client's connect-time +
|
||||
* `setRoots` wiring so the roots told to the server match what hits disk.
|
||||
* The shared roots normalizer — for a list from the web settings form, from
|
||||
* `mcp.json`, or from `setRoots()`. Puts them in the shape the Inspector
|
||||
* advertises and persists: drop entries whose `uri` is blank (the settings form
|
||||
* leaves a new row empty mid-edit) and drop a blank/whitespace `name`. Any other
|
||||
* fields a root carries (e.g. `_meta` from a hand-edited `mcp.json`) are
|
||||
* preserved — only `uri`/`name` are normalized. Every path roots take runs
|
||||
* through here — the settings → disk converter
|
||||
* (`inspectorSettingsToStoredFields`), the `InspectorClient` constructor and
|
||||
* `setRoots`, and all three clients' connect-time wiring — so what the server is
|
||||
* told matches what hits disk.
|
||||
*
|
||||
* `Root[]` is a compile-time type over hand-editable `mcp.json`, and every
|
||||
* client now feeds this straight from disk (#1797), so the shape is validated
|
||||
* at runtime too, rather than throwing at connect: a non-array bails to `[]`,
|
||||
* an entry without a string `uri` is dropped, and a non-string `name` is
|
||||
* dropped from an otherwise-usable entry. Each case warns.
|
||||
*/
|
||||
export function cleanRoots(roots: Root[]): Root[] {
|
||||
// Keep: the `Root[]` parameter narrows this branch to `never`, but the type is
|
||||
// a promise hand-edited `mcp.json` does not keep. Not dead code (#1797).
|
||||
if (!Array.isArray(roots)) {
|
||||
console.warn("Ignoring `roots`: expected an array, got", typeof roots);
|
||||
return [];
|
||||
}
|
||||
return roots
|
||||
.filter((r) => r.uri.trim() !== "")
|
||||
.filter((r) => {
|
||||
// Keep: unreachable per the parameter type, reachable from disk.
|
||||
if (typeof r?.uri !== "string") {
|
||||
console.warn("Dropping root without a string `uri`:", r);
|
||||
return false;
|
||||
}
|
||||
return r.uri.trim() !== "";
|
||||
})
|
||||
.map((r) => {
|
||||
const trimmedName = r.name?.trim();
|
||||
// `?.` would guard null/undefined but not a non-string `name` from disk,
|
||||
// which `.trim()` throws on — the `uri` case above, one field over.
|
||||
const rawName = r.name;
|
||||
if (rawName !== undefined && typeof rawName !== "string") {
|
||||
console.warn("Dropping non-string `name` on root:", r);
|
||||
}
|
||||
const trimmedName =
|
||||
typeof rawName === "string" ? rawName.trim() : undefined;
|
||||
// Strip `name` off the carried-through rest so a cleared optional name
|
||||
// doesn't persist as `name: ""`; re-add it only when non-empty.
|
||||
const { name: _name, ...rest } = r;
|
||||
|
|
|
|||
|
|
@ -567,6 +567,24 @@ export type ModernLogLevel = LoggingLevel | "off";
|
|||
*/
|
||||
export const DEFAULT_MODERN_LOG_LEVEL: ModernLogLevel = "debug";
|
||||
|
||||
/**
|
||||
* The live modern per-request log level a server's settings imply: the
|
||||
* configured value, or {@link DEFAULT_MODERN_LOG_LEVEL} when unset, with
|
||||
* `"off"` meaning not opted in.
|
||||
*
|
||||
* One derivation, because the client stamps `_meta` from it while the web Logs
|
||||
* control displays it — computing it separately on each side is how the two
|
||||
* come to disagree, which is a bad failure for a tool whose job is showing what
|
||||
* it sent (#1629, #1797). The web maps `undefined` to `null` at its own
|
||||
* boundary; that is display, not a second derivation.
|
||||
*/
|
||||
export function resolveModernLogLevel(
|
||||
settings?: Pick<InspectorServerSettings, "modernLogLevel">,
|
||||
): LoggingLevel | undefined {
|
||||
const level = settings?.modernLogLevel ?? DEFAULT_MODERN_LOG_LEVEL;
|
||||
return level === "off" ? undefined : level;
|
||||
}
|
||||
|
||||
/** All modern-log-level values, for form options and the runtime guard. */
|
||||
export const MODERN_LOG_LEVELS: ModernLogLevel[] = [
|
||||
"off",
|
||||
|
|
|
|||
Loading…
Reference in a new issue