Skip to content

fix(mcp): #848 keyless sign-in — hold the verified session across requests (#2035) - #2087

Merged
vybe merged 5 commits into
devfrom
feature/2035-mcp-session-auth-memo
Aug 10, 2026
Merged

vybe merged 5 commits into
devfrom
feature/2035-mcp-session-auth-memo

Conversation

@obasilakis

Copy link
Copy Markdown
Contributor

Summary

#848 keyless MCP sign-in never worked end-to-end. A verified email survived exactly one HTTP request, so verify_login reported success and the very next tool call answered login_required.

#848 upgrades a session by mutating its auth context in place, on the premise that FastMCP hands every tool the same object by reference. That holds within a request and is false across requests: MCP streamable HTTP is discrete POSTs, mcp-proxy re-runs authenticate on every one, and FastMCPSession#updateAuth is this.#auth = auth — replace, not merge. A callback returning a fresh context per request therefore discarded every login before anything could read it.

Option A, approved by @vybe on #2035: return the same context object for the same transport session, so updateAuth reinstalls it. Option B (an opaque token from verify_login) was rejected because MCP gives a tool no way to make a client attach a header to later calls — the token would ride as a tool argument and live in the calling model's context window, which is worse on exposure and the "minted key" shape the #848 sign-off ruled out.

Flag-gated MCP_INLINE_AUTH_ENABLED, default OFF. This is "feature non-functional when enabled", not a live vulnerability.

Acceptance criteria (@vybe's five conditions)

# Condition
1 Reclassify mcp-session-id as a credential; audit anything that logs it ✅
2 Short TTL on the memoized context — hours not days, err aggressive ✅ 30 min idle / 4 h absolute (was 8 h)
3 Memoization strictly anonymous-tier; needs its own test ✅ source guard + behavioural
4 Real-transport regression test ✅
5 Docs note: keyless tier behind TLS only ✅

1 — the session id is now a credential

Making it bearer-equivalent means it must not be written to a log file. Trinity's own code already logged an independent correlation id, but the bundled mcp-proxy prints the raw id at INFO on three paths — including the SSE line that fires on every connection — and Vector ships container stdout to /data/logs.

Measured on this machine before the fix: 331 full session ids sitting in /data/logs in plaintext.

FastMCP accepts a logger and looks like the clean seam, but those sites are bare console.log and mcp-proxy takes no logger of its own, so there is no injection point. Redaction happens at the console boundary instead (src/log-redaction.ts): UUID-shaped tokens in [mcp-proxy]-prefixed lines are truncated to 8 chars — enough to keep two lines for one connection joinable, leaving 90 bits to guess online inside the TTL. Vector-layer redaction was rejected for leaving the id in Docker's own json log.

Scope is deliberately narrow so ids Trinity logs on purpose keep their full value. That narrowness is guarded, not assumed: a static scan of the installed mcp-proxy and fastmcp bundles fails CI if either grows a session-id log site the prefix does not cover.

2 — TTL, and why it is the only bound

disconnect-eviction reads as available (fastmcp emits disconnect with the session; FastMCPSession exposes a sessionId getter) and is not. Probed against this tree rather than assumed:

  • connect fires with sessionId still unset — the id is copied off the transport, which has not minted one at initialize
  • disconnect never fires for a client that simply quits — the MCP SDK's close() only aborts the SSE stream, and the DELETE that ends the server-side session is sent solely by the opt-in terminateSession()

With no logout tool either (decided against, see Known limitations), expiry is the only thing that ends a keyless session, so the absolute cap is the exposure window for a leaked id. Halved to 4 h accordingly. The test pins the direction, not the value — lowering is always safe, raising weakens every keyless session at once.

3 — anonymous-tier only

Tool visibility cannot serve as the observable: updateAuth sets #auth and stops, so the callable tool map stays the one built at session creation and a mid-session identity change is invisible in tools/list. Two guards instead:

  • Structural (inline-auth-scope.test.ts) — the store has exactly one call site, inside the no-Authorization branch, ahead of the line where a presented key is read. A behavioural test only samples the paths it drives; this fails the moment a second call site appears anywhere.
  • Behavioural — a keyed session re-validates its credential against the backend on every request, including when it presents a session id that has a live, signed-in anonymous entry. That is the precise shape the condition forbids.

4 — the regression test crosses the transport

inline-auth-transport.test.ts drives a real StreamableHTTPClientTransport against a stubbed backend across separate POSTs. #848's 30 tests were all handler-level — they invoke execute with a context the test owns, so the object is never swapped and this bug class is invisible by construction. That is why it shipped green, and it is why this file must not be replaced with a handler test.

Verification

  • 236/236 tests, tsc --noEmit clean, after merging 44 commits of dev (incl. the fastmcp 4.12.1→4.12.2 bump).
  • Negative controls, both discriminating:
    • revert the memo → exactly 3 transport cases fail, the other 7 pass
    • disable the redaction install → exactly 1 fails
  • Live end-to-end against the real stack, post-merge, image rebuilt from this branch:
    list_playbooks → not signed in → request_login → verify_login with the code alone → signed in → list_playbooks returns real playbooks. The correlation id is now one stable value across all five POSTs; bug(mcp): #848 inline email auth — a verified session is discarded on the next request, so keyless sign-in never works #2035 recorded six distinct ones for six POSTs.
  • Redaction confirmed in the captured log: for session ID f7ccb092-REDACTED in /data/logs, no full id anywhere.

The 331 pre-existing full ids in /data/logs are all dead — any upgrade restarts the mcp-server, which drops every keyless session — so no live credential survives the deploy.

Also in this PR

Refreshes the [email protected] citations in server.ts and tool-visibility.test.ts to the 4.12.2 dev bumped to in #2003. Every cited line number was re-verified byte-identical under 4.12.2; only the version string had rotted, which is the exact failure mode those comments warn about.

Known limitations (deliberate)

  • No logout tool. Decided against for this PR. Nothing ends a keyless session early — expiry or an mcp-server restart only. Documented rather than hidden.
  • No disconnect eviction. Not deferred — not implementable; see condition 2 above.
  • /clear in an MCP client does not log out. It resets the conversation, not the transport session. Now documented, since the session outliving a /clear is surprising.

Release-cut note

#848 must stay out of any release PR's Closes lines until this ships — it is deliberately back on status-in-progress for that reason. Same handling PR #1839 gave #1819.

Closes #2035
Refs #848

🤖 Generated with Claude Code

#848 upgrades a session by mutating its auth context in place, on the
premise that FastMCP hands every tool the same object by reference. That
holds WITHIN a request and fails ACROSS requests, so keyless sign-in never
worked: verify_login reported success and the next tool call answered
login_required.

MCP streamable HTTP is discrete POSTs. mcp-proxy's handleStreamRequest
(bundled in [email protected]) re-runs authenticate on every one of them and
then calls FastMCPSession#updateAuth, which is `this.#auth = auth` —
replace, not merge. Returning a fresh context per request therefore
discarded the upgrade before anything could read it. server.ts already
noted updateAuth's replace semantics, but only as a reason not to key tool
VISIBILITY on login state; that it runs per request was not followed up.

Resolve the anonymous context through a store keyed by the transport
session id, so the same object is handed back and updateAuth reinstalls it.

Constraints, each load-bearing:
- anonymous tier only; a keyed session keeps re-validating its key, or
  Mcp-Session-Id would stand in for a key never presented
- consulted only on the no-Authorization-header path, structurally
- idle + absolute TTL, since fastmcp exposes no session-close hook here
- bounded map, oldest-first, or an unauthenticated caller could exhaust
  memory by reconnecting in a loop

This makes Mcp-Session-Id bearer-equivalent for keyless sessions and it
must now be handled as a credential — it is no longer logged, and
McpAuthContext.sessionId stays an independent id so the value that appears
in logs and rate-limit keys is not the one that grants access. Damage is
bounded by #848's own design: the backend re-gates authorization per call,
so only authentication is remembered.

Tests: 15 new (185 total). The transport suite drives a real
StreamableHTTPClientTransport across three separate POSTs — the handler-level
tests #848 shipped cannot observe a bug that lives between requests, which is
why it shipped green. Verified as a negative control: reverting the fix fails
exactly the two bug-specific cases and no others.

Option A per #2035, signed off by obasilakis 2026-08-06.
The transport regression test added alongside this imports the MCP SDK
client, but the package appeared ONLY in `overrides` — a security pin from
the #1868 bump. An overrides entry constrains a version if something else
pulls the package in; it does not install it. The import therefore resolved
purely by hoisting out of fastmcp's tree, and would break the moment fastmcp
changes how it bundles mcp-proxy — surfacing as "Cannot find package" rather
than as a real signal about the code under test.

Pinned to ^1.26.0, the version already resolved in the tree, NOT the ^1.30.0
`npm install --save-dev` picks on its own: a bug fix must not carry an
untested transport-library bump. Lock diff is 7 added lines, no churn.
#2035)

#2035 makes `Mcp-Session-Id` bearer-equivalent for the #848 keyless tier: with
no credential on the wire to re-present, the verified identity is resolved per
request from a store keyed on that header. vybe approved that trade with five
conditions attached; this lands three of them.

1. The id no longer reaches the log in full. Trinity's own code already logged
   an independent correlation id, but the bundled mcp-proxy prints the raw one
   at INFO on three paths — including the SSE line that fires on every
   connection — and Vector ships container stdout to /data/logs, so every live
   keyless session id was being written to a log file in plaintext. FastMCP
   accepts a `logger` and looks like the clean seam, but those sites are bare
   `console.log` and mcp-proxy takes no logger of its own, so redaction happens
   at the console boundary instead: UUID-shaped tokens in `[mcp-proxy]`-prefixed
   lines are truncated to 8 characters, which keeps two lines for one connection
   joinable while leaving 90 bits to guess online inside the TTL. Scope is
   deliberately narrow so ids Trinity logs on purpose keep their full value —
   and the narrowness is guarded rather than assumed: a static scan of the
   installed bundles fails CI if mcp-proxy or fastmcp grows a session-id log
   site the prefix does not cover.

2. Absolute TTL halved, 8h to 4h; idle stays 30 min. Constraint 2 in the store's
   own comment is the reason, and it is now written from measurement rather than
   from reading the API surface: fastmcp emits `disconnect` and FastMCPSession
   exposes `sessionId`, so evicting on disconnect reads as available. Probing
   this tree shows otherwise — `connect` fires with the id still unset, and
   `disconnect` never fires for a client that simply quits, because the MCP
   SDK's `close()` only aborts the SSE stream and the DELETE that ends the
   server-side session is sent solely by the opt-in `terminateSession()`. With
   no logout tool either (decided against on #2035), expiry is the ONLY thing
   that ends a keyless session, so this number is the exposure window for a
   leaked id. The test pins the direction, not the value.

3. The anonymous-tier scoping gets its own test, and the structural one is the
   stronger of the two: the store has exactly one call site, inside the
   no-Authorization branch, ahead of the line where a presented key is read. A
   behavioural test only samples the paths it drives; the source guard fails the
   moment a second call site appears anywhere. Behaviourally, a keyed session is
   shown re-validating its key against the backend on every request — including
   when it presents a session id that has a live, signed-in anonymous entry,
   which is the precise shape the condition forbids. Tool visibility cannot be
   the observable here: `updateAuth` sets `#auth` and stops, so the callable
   tool map stays the one built at session creation.

Also refreshes the fastmcp citations in server.ts and tool-visibility.test.ts
from 4.12.1 to the 4.12.2 dev bumped to in #2003. Every cited line number was
re-verified byte-identical under 4.12.2; only the version string had rotted,
which is the exact failure mode those comments warn about.

Tests: 236 total, +25. Both negative controls run and both discriminate —
reverting the memo fails exactly 3 transport cases and no others, and disabling
the redaction install fails exactly 1.

Refs #848
… TLS (#2035)

Condition 5 of the #2035 sign-off. #848's docs said "session, not a minted key"
and stopped there. What identifies the session is the `Mcp-Session-Id` header,
which the client resends on every request — so for the keyless tier that header
IS a bearer credential, and over plain HTTP it is sniffable. That is a
deployment constraint a self-hoster cannot infer from the feature description.

Four facts the code cannot tell an operator, now in requirements/mcp.md §7.6,
feature-flows/mcp-connector.md and the .env.example block for the flag:

- expose the MCP port over TLS only when MCP_INLINE_AUTH_ENABLED is on; keyed
  connector clients are unaffected, since their key is on the wire regardless
- the id is truncated in logs, and the value in Trinity's own log lines is a
  deliberately different, non-granting correlation id
- expiry is the only exit — 30 min idle, 4 h absolute, no logout tool, no usable
  disconnect signal; an mcp-server restart drops every keyless session at once
- `/clear` in an MCP client resets the conversation, not the transport session,
  so it does not log the user out

Also corrects two architecture.md claims the fix moved: the anonymous tier
described as holding "no credential" (it holds no *key*), and the auth.ts tool
row's account of the in-place upgrade, which survives only because the context
is memoized per session id.

Refs #848

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Validated via /validate-pr.

  • Base dev ✅ · 13 files ✅ · all 4 required checks green, full matrix green ✅
  • Closes #2035 present → auto-promotes on merge. Refs #848 is deliberately not a closing keyword, matching the release-cut note — #848 stays out of the release Closes lines until the keyless tier actually works. Correct call, and the #1839/#1819 precedent is the right one.
  • Docs tier is right for a behaviour change: architecture.md + feature-flows/mcp-connector.md + requirements/mcp.md all moved, plus the .env.example TLS-only warning that makes the new credential's exposure model discoverable at the config surface.
  • Security scan clean. The one API_KEY = "trinity_mcp_test_key" hit is a fixture in *.test.ts beside [email protected]. MCP_INLINE_AUTH_ENABLED was already wired in both compose files — no packaging gap.
  • Test adequacy (fix PR): inline-auth-transport.test.ts drives a real StreamableHTTPClientTransport across separate POSTs, which is the only shape that can see this bug — #848's 30 handler-level tests owned the context object, so the class was invisible by construction. Naming that in-file is what stops it being replaced with a handler test later. inline-auth-scope.test.ts fails on a second call site rather than sampling paths, which is the stronger guard.

Two things I checked rather than took on trust: the disconnect-eviction claim (connect fires before sessionId is minted, and close() never sends the DELETE) is why TTL is the only bound, so the 4h absolute cap really is the exposure window — halving it was the right response. And the 331 plaintext session ids already in /data/logs are dead on any upgrade, so no live credential survives the deploy.

@vybe
vybe merged commit 787db51 into dev Aug 10, 2026
29 of 30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants