Skip to content

fix: record an intercepted 401's status, headers and body in the network log - #2371

Merged
cliffhall merged 4 commits into
v2/mainfrom
v2/fix/2297-401-response-body
Sep 14, 2026
Merged

cliffhall merged 4 commits into
v2/mainfrom
v2/fix/2297-401-response-body

Conversation

@cliffhall

Copy link
Copy Markdown
Member

Closes #2297

Why the body never appeared

In createTransportNode the network tracker wrapped the auth-challenge interceptor:

tracker( intercept( observer( baseFetch ) ) )

On a 401/403 the interceptor cancels the body and throws AuthChallengeError, so the tracker never saw a response — it caught the throw and logged an entry carrying only error: "MCP auth challenge (401)". NetworkEntry renders its Response section only when responseStatus is set, so the status, the WWW-Authenticate header (with its resource_metadata and scope) and the body were all absent.

What changed

  • core/mcp/node/transport.ts — the tracker now sits under the interceptor (intercept( tracker( observer( baseFetch ) ) )), so it records the real response and clones the body before the interceptor cancels it. One withTracking helper replaces the three per-branch tracker constructions. Interception behavior is unchanged. The fix applies to both the direct (CLI/TUI) path and the web backend, which builds its transport through the same function and relays the body update.
  • core/mcp/node/authChallengeFetch.ts — the body cancel() is no longer awaited. With the tracker's clone as the other branch of the tee, cancelling one branch settles only once the clone has read to the end, so a 401 whose body never ends would hang the challenge throw.

Tests

Two regression tests in clients/web/src/test/integration/mcp/node/transport.test.ts, each mutation-checked:

Mutation Result
Tracker restored above the interceptor both new tests fail
cancel() awaited again the unending-body test times out at 30s

npm run local:gate passes.

No UI code changed — NetworkEntry already renders a status-bearing entry's body; it simply never received one — so no screenshots are attached.

🤖 Generated with Claude Code

https://claude.ai/code/session_01SG6q6YEDJyJB5H2Hr8nBDS

The network tracker wrapped the auth-challenge interceptor, so a 401/403
never reached it as a response: the interceptor cancelled the body and
threw, and the tracker logged only the thrown error. NetworkEntry renders
its response section only when a status is present, so the body — and the
WWW-Authenticate resource_metadata and scope — were never shown.

Move the tracker below the interceptor so it records the real response and
clones its body before the interceptor cancels it, and stop awaiting that
cancel: with the tracker's clone as the other tee branch, the cancel settles
only once the clone reads to the end, which would hang on an unending body.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01SG6q6YEDJyJB5H2Hr8nBDS
Signed-off-by: cliffhall <[email protected]>
@cliffhall cliffhall added the v2 Issues and PRs for v2 label Sep 14, 2026
@cliffhall
cliffhall requested a balanced review from Copilot September 14, 2026 04:47

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Connect-time web responses remain undiscoverable, and unending bodies can retain resources indefinitely.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Moves network tracking beneath auth interception so challenge responses retain diagnostic details.

Changes:

  • Records intercepted 401/403 status, headers, and body.
  • Makes body cancellation non-blocking.
  • Adds regression tests for bounded and unending bodies.
File summaries
File Description
core/mcp/node/transport.ts Reorders and consolidates fetch wrappers.
core/mcp/node/authChallengeFetch.ts Detaches response-body cancellation.
clients/web/src/test/integration/mcp/node/transport.test.ts Tests intercepted challenge logging.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 2
  • Review effort level: Balanced

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Comment thread core/mcp/node/authChallengeFetch.ts Resolved
Comment thread core/mcp/node/transport.ts Resolved
Copilot review round 1. With the tracker below the auth-challenge
interceptor, its background clone kept draining a 401 body after the
interceptor cancelled its own branch — so a body that never ended left the
connection live. Read a 401/403 body up front instead, capped at 64 KiB and
2s, and cancel the clone's reader when either bound is hit so the
interceptor's cancel releases the source. The body now lands on the entry
itself before the challenge is thrown.

Also cover the web path end to end: a streamable-http 401 on
/api/mcp/send reaches the event stream with its status and body.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01SG6q6YEDJyJB5H2Hr8nBDS
Signed-off-by: cliffhall <[email protected]>
@cliffhall

Copy link
Copy Markdown
Member Author

Copilot review round 1: responses (inline replies are in each thread; mirrored here because pushing the fix marks those threads outdated)

  1. Unending 401 body kept the connection live (authChallengeFetch.ts) — fixed in a7c4c52. The tracker reads a 401/403 body up front, capped at 64 KiB and 2s, then cancels its clone's reader, so the interceptor's cancel releases the source. The body lands on the entry before the throw.
  2. Initial 401 invisible on web (transport.ts) — declined with evidence. Streamable HTTP's start() makes no request, so the 401 arrives on /api/mcp/send over a registered session with an open event stream. New test remote-auth-branches.test.ts › relays a streamable-http 401's status and body over the event stream covers the remote flow end to end, and it fails with the wrapper order reverted. The connect-time branch is unreachable for this transport. The SSE connect-time case predates this PR and is out of scope.

No suppressed comments this round. npm run local:gate passes on a7c4c52.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

The body cap can be exceeded, SSE challenge bodies remain omitted, and truncated JSON can bypass secret redaction.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (2)

core/mcp/fetchTracking.ts:440

  • This exclusion still drops the body for a 401/403 returned to a GET with Content-Type: text/event-stream, including an SSE authorization failure. Challenge reads are now explicitly bounded by size and deadline, so they do not have the unbounded-read risk that justified skipping successful long-lived streams. Apply the bounded challenge path regardless of the response content type so these auth responses are recorded consistently.
      !isLongLivedStream &&

core/mcp/fetchTracking.ts:448

  • A JSON body stopped by either bound always has [truncated] appended, so it is no longer valid JSON and redactBody returns it unchanged. For example, a large or stalled 401 beginning with {"access_token":"live-access",... will put that credential verbatim into the network log and persisted sinks, bypassing the response-body redaction guarantee. Preserve truncation metadata separately and ensure an incomplete structured body is suppressed or safely redacted rather than falling back to the raw prefix.
      entry.responseBody =
        body === undefined
          ? undefined
          : (redactBody(body, response.headers.get("content-type")) ?? body);
  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread core/mcp/fetchTracking.ts Resolved
…ON (#2297)

Copilot review round 2:

- Slice each chunk to the remaining budget, so one oversized chunk can no
  longer carry the recorded body past CHALLENGE_BODY_MAX_BYTES.
- Drop the long-lived-stream exclusion from the challenge branch. It guards
  an unbounded read and this one is bounded, so a 401 to an SSE GET now
  records its body too.
- Keep truncation out of the string that gets redacted. A cut-off body that
  looks like JSON cannot be redacted (redactBody only masks JSON that
  parses), so it is replaced by WITHHELD_TRUNCATED_JSON_BODY. Cut-off form
  and plain-text bodies are redacted, then marked [truncated].

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01SG6q6YEDJyJB5H2Hr8nBDS
Signed-off-by: cliffhall <[email protected]>
@cliffhall

Copy link
Copy Markdown
Member Author

Copilot review round 2: responses (the inline finding has a reply in its thread; the two suppressed findings have no thread, so this comment is their only answer)

  1. Byte cap exceeded by one large chunk (fetchTracking.ts, inline) — fixed in 1fd1b15. Chunks are sliced to the remaining budget before decoding.

  2. SSE-typed 401/403 bodies still omitted (fetchTracking.ts:440, suppressed) — fixed. I had carried the !isLongLivedStream exclusion into the new challenge branch. That exclusion guards an unbounded read, and the challenge read is bounded, so it is gone from that branch. A 401 to a text/event-stream GET now records its body. The background read for non-challenge statuses keeps the exclusion.

  3. Truncated JSON bypasses redaction (fetchTracking.ts:448, suppressed) — fixed. readChallengeBody now returns { text, truncated }, and recordableChallengeBody decides what is recorded:

    • Complete body → redacted as before.
    • Truncated body that looks like JSON (a json content type, or text starting with {/[) → replaced by WITHHELD_TRUNCATED_JSON_BODY. No prefix is recorded, because redactBody can only mask JSON that parses.
    • Truncated form or plain text → redacted, then marked [truncated]. Form pairs still redact when cut; text has no fields to redact.

    Truncation is no longer mixed into the string before redaction, which was the cause.

Each fix has its own test, and each was mutation-checked by reverting that guard alone:

Guard reverted Result
Chunk slice caps a single chunk larger than the budget fails; 50 pass
SSE exclusion restored in the challenge branch records the body of a 401 to a long-lived-stream GET fails; 50 pass
JSON not withheld both withheld-JSON tests fail; 49 pass

Also added: complete JSON challenge bodies still redact, and a cut-off form body redacts field by field.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Deeply nested JSON can make synchronous redaction throw instead of delivering the expected authentication challenge.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread core/mcp/fetchTracking.ts
Comment on lines +486 to +490
const read = await readChallengeBody(response);
entry.responseBody =
read === undefined
? undefined
: recordableChallengeBody(read, response.headers.get("content-type"));

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Declined: redactBody cannot throw here, so the challenge path cannot surface a RangeError.

The recursion is inside redactBody's own try (fetchTracking.ts:189-196): JSON.parse(body) and JSON.stringify(redactJsonValue(parsed)) share that block, and its catch falls through to return body. A stack overflow in redactJsonValue is caught there before it reaches recordableChallengeBody, the tracker, or the interceptor. The interceptor always receives the response and throws AuthChallengeError as usual.

Checked directly against redactBody on Node 26, with application/json:

Body Bytes Result
12k / 20k / 32k nested arrays 24000 / 40000 / 64000 returns a string
10k nested objects (under the cap) 60001 returns a string
200k nested arrays 400000 returns a string
200k nested objects 1200001 returns a string

None throws, including the last two, which are far past anything the 64 KiB cap lets through.

There is a real property underneath, but it is not this PR's: if the recursion did overflow on some engine, redactBody would return the body unredacted. That is equally true of the asynchronous body path and of every other redactBody caller, and I could not make it overflow within the cap. So I am leaving it out of this PR rather than widening scope.

@cliffhall

Copy link
Copy Markdown
Member Author

Copilot review round 3: response (reply is inline in the thread; mirrored here)

  1. Deeply nested JSON makes synchronous redaction throw (fetchTracking.ts) — declined, premise does not hold. redactBody's try (fetchTracking.ts:189-196) wraps both JSON.parse and the redactJsonValue recursion, so an overflow is caught inside redactBody and never reaches the tracker or the interceptor. On Node 26, redactBody returns a string for nesting from 12k arrays up to 200k arrays and 200k objects (1.2 MB). The AuthChallengeError path is unaffected.

    Out of scope, noted for the record: if the recursion ever did overflow, redactBody would return the body unredacted. That applies equally to the async body path and every other caller, predates this PR, and did not reproduce within the 64 KiB cap.

No suppressed comments this round. This round's only finding was declined, so I am not requesting another review. Next: merge v2/main into the branch and merge on green CI.

…sponse-body

Signed-off-by: cliffhall <[email protected]>

# Conflicts:
#	core/mcp/node/transport.ts
@cliffhall
cliffhall merged commit 48376cb into v2/main Sep 14, 2026
4 checks passed
@cliffhall
cliffhall deleted the v2/fix/2297-401-response-body branch September 14, 2026 06:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2 Issues and PRs for v2

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ResponseBody not printed verbatim after receiving 401 status. Allow protocol era to be set on an ad-hoc --server-url launch (not just via mcp.json)

2 participants