Skip to content

Extract the per-message request log (requestlog), with a request id - #19

Merged
jeremy merged 4 commits into
mainfrom
request-log-parity
Nov 18, 2026
Merged

jeremy merged 4 commits into
mainfrom
request-log-parity

Conversation

@jeremy

@jeremy jeremy commented Nov 18, 2026

Copy link
Copy Markdown
Member

hey-mcp-server and fizzy-mcp-server each log one "mcp request" line per MCP message they answer, from two copies of internal/hosted/requestlog.go. basecamp-mcp-server logs no such line. This PR moves the line here as requestlog and adds request_id, so the line can be joined to the HTTP request it came in on and to the token exchange made for it.

API

package requestlog

const Message = "mcp request"
const MaxField = 128
const UnknownTool = "(unknown)"
const Header = "X-Request-ID"

type Options struct {
	Tools    []string                        // the tools the server serves
	Grant    func(context.Context) string    // "" or nil: no grant key
	CutShort func(context.Context) bool      // a cut outside the context (fizzy's request budget)
}

func Install(server *mcp.Server, logger *slog.Logger, opts Options) // outermost receiving middleware
func Middleware(logger *slog.Logger, opts Options) mcp.Middleware

func WithRequestID(ctx context.Context, id string) context.Context  // cut to MaxField
func RequestID(ctx context.Context) string
func Inbound(next http.Handler) http.Handler            // the inbound header goes on the context unless one is already there
func Transport(base http.RoundTripper) http.RoundTripper // sends the context's id on outbound calls that don't name one

The line

The field names and meanings are the ones hey and fizzy log today, so existing queries and the Loki allowlist still match: method, protocol, client, client_version, tool, user_agent, session, grant, duration_ms, result.status, result.code. The new field is request_id.

request_id comes from the first of these that is set:

  1. The id on the context, from Inbound or from a server that makes its own id (basecamp-mcp-server's HTTP middleware) and stores it with WithRequestID.
  2. The request's X-Request-ID header.

When neither is set, the line has no request_id. kamal-proxy sets X-Request-ID to a UUID when a request arrives without one, and keeps the value when it arrives with one (internal/server/request_id_middleware.go). That means a client can choose the value, so it is cut to MaxField bytes, the same as client and user_agent.

The rest is unchanged from the two copies. The line never logs arguments, tool input or output, error text, or tokens. A tools/call names its tool only if the server serves it, and logs (unknown) otherwise.

There is one deliberate difference from hey's copy. The input_required check is fizzy's (InputRequests != nil || RequestState != ""). The SDK sets NeedsInput() only after every middleware has returned, so hey's NeedsInput() check never fired inside the middleware.

go-sdk

go-sdk moves from v1.7.0 to v1.8.1-0.20261014132652-7c486efa8223. That is the revision all three servers already build against, and this package needs its request ProtocolVersion() and ClientInfo().

Tests

The tests port hey's requestlog_test over a real stateless streamable server running on three protocol revisions. They check:

  • the tool name is logged, and a made-up name logs as (unknown) with error and its code
  • arguments, output and error text are never logged
  • session is none before init
  • client strings are truncated
  • a cancelled call and a CutShort call log canceled
  • input_required is logged inside the chain
  • the Grant hook
  • request_id: each line carries its own HTTP request's X-Request-ID, an id on the context wins over the header, and with neither there is no key
  • Inbound and Transport: the caller's request is left unmodified, an existing id is kept, and credentials are untouched

Mutation check: 13 of 13 mutants fail the tests. The mutants were: drop request_id, log arguments, ignore the context id, log request_id untruncated, store it untruncated, use hey's NeedsInput rule, log unknown tool names, drop CutShort, never report session: sent, Transport sends nothing, Transport overwrites an id the caller set, Transport mutates the caller's request, Inbound overrides the server's id.

make ready passes. go mod tidy -diff is clean.

Release

This repo has no tags, and consumers pin pseudo-versions of main commits. The three server PRs pin this PR's merge commit.

hey-mcp-server and fizzy-mcp-server each log one "mcp request" line per
MCP message they answer, from two copies of internal/hosted/requestlog.go;
basecamp-mcp-server logs none. This moves the line here, unchanged in its
fields (method, protocol, client, client_version, tool, user_agent,
session, grant, duration_ms, result.status, result.code), so existing
queries keep working, and adds request_id.

What differed between the copies is now an option: Grant names the
grant a request rides on, CutShort reports a request the server cut short
outside its context (fizzy's request budget). The input_required test is
fizzy's: the SDK labels a result NeedsInput only after every middleware has
returned, so hey's NeedsInput() check never saw a question.

request_id is the request's X-Request-ID, which kamal-proxy sets when a
request arrives without one: Inbound puts it on the request's context, a
server that makes its own id puts that there with WithRequestID, and the
line falls back to the header when neither did. Transport sends it on
outbound calls made for the request, so the app's log of a token exchange
joins the line. Every client-chosen string, the id included, is cut to
MaxField bytes, and the line still never carries arguments or results.

go-sdk moves to the revision every server already builds against, for the
request's ProtocolVersion and ClientInfo.
Copilot AI balanced review requested due to automatic review settings November 18, 2026 00:28

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 transport can panic when setting a context request ID on a cloned request with a nil Header; it must allocate the cloned header map before setting the ID.

1 open issue
What changed in this PR

Extracts shared per-message logging from hey and fizzy into the MCP toolkit’s requestlog package, adding request IDs to correlate MCP messages with inbound HTTP requests and outbound calls.

Changes:

  • Adds logging middleware for request metadata, duration, and outcomes without logging message content.
  • Adds context, inbound HTTP, and outbound transport helpers for request IDs, with integration and unit tests.
  • Documents the package and updates go-sdk to the revision used by the consuming servers.

[!TIP]
If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.

File Description
requestlog/​requestlog.go Implements per-message logging and outcome classification.
requestlog/​requestlog_test.go Tests logging, content exclusion, outcomes, and request IDs.
requestlog/​requestid.go Adds request-ID context and HTTP propagation helpers.
requestlog/​requestid_test.go Tests ID precedence, propagation, and request preservation.
README.md Documents the package’s origins and purpose.
go.sum Updates go-sdk checksums.
go.mod Updates go-sdk for request-level protocol and client metadata.

Review effort: Balanced

Comment thread requestlog/requestid.go Resolved
…ting its id

A request may carry a nil Header, and Clone keeps it nil, so Transport's
Set panicked before the base transport ran. The clone gets a fresh map;
the caller's request is left without one.

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.

🔵 Needs a closer look

Oversized state-only input continuations are misclassified as completed results, causing the size cap to clear their request state and prevent continuation.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Preserve oversized state-only input continuations

go.mod:7

With this SDK revision, a result with non-empty RequestState and nil InputRequests represents an input-required continuation, but result/cap.go:176 does not recognize it before the SDK sets resultType. If that result exceeds the size cap, capCoarse clears its state and replaces it with a completed truncation notice, preventing continuation. Add result.RequestState != "" to result.asksForInput and cover an oversized state-only result without resultType in a regression test.

1 resolved since last review

Review effort: Balanced

With the go-sdk this PR moves to, a result with a requestState and no
inputRequests is an input-required continuation (SEP-2322), and the SDK
labels it so only after the middleware returns. Cap counted only
InputRequests, so an oversized state-only result took the coarse cut,
which drops its state and ends the round trip.
@jeremy

jeremy commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Fixed — finding from this review: result.asksForInput now also counts a non-empty RequestState, which matches the SDK's own check at this revision (SEP-2322). An oversized result that has only a state now passes through uncut and keeps its state. TestCap_InputRequestsWithoutResultTypeUntouched has a new state-only case, and that case fails without the fix. (4b166f1)

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.

🔵 Needs a closer look

Request logging misclassifies input-required prompt and resource results as successful and can omit or report stale client and protocol fields for inbound initialization.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Log initialization fields from the current request

requestlog/​requestlog.go:100

Received initialize messages use *mcp.ServerRequest[*mcp.InitializeParams], but mcp.InitializeRequest aliases a ClientRequest, so this branch never matches inbound initialization. If inner middleware rejects initialization, the log loses the supplied protocol and client fields; a duplicate initialize can instead report the previous client's fields. Read *mcp.InitializeParams through req.GetParams() so the log describes the current message rather than session state.

Medium severity Recognize input-required results from prompts and resources

requestlog/​requestlog.go:174

The pinned SDK also supports InputRequests and RequestState on GetPromptResult and ReadResourceResult. For a 2026-07-28 prompts/get or resources/read returning either field, this tools-only assertion falls through to status: ok, although the SDK sends an input_required result. Extend the input-required classification to those two result types, keeping IsError handling specific to tools.

Review effort: Balanced

…ources ask too

A received initialize is a ServerRequest, and mcp.InitializeRequest is the
ClientRequest alias, so the branch that read its params never matched: the
line took the session's record, which a refused handshake doesn't have and
a repeated one holds from an earlier client. It now reads the params of any
request whose params are InitializeParams. The truncation test built the
client-side type, which is why it passed.

prompts/get and resources/read results can carry inputRequests or a
requestState under 2026-07-28 as tool results can; they log
input_required now instead of ok.
@jeremy

jeremy commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Fixed — both findings from this review, in a56ea73:

  • Initialize: the line now reads protocol and client from the params of any request whose params are *mcp.InitializeParams. The old branch type-asserted mcp.InitializeRequest, which is the client-side alias, so it never matched a received initialize. The truncation test built that client-side type too, which is why it passed. It now builds a ServerRequest. TestInitializeIsDescribedByItsOwnParams covers a refused handshake with no session record behind it.
  • Prompts and resources: GetPromptResult and ReadResourceResult that carry InputRequests or RequestState now log input_required. TestPromptAndResourceQuestionsAreLoggedAsInputRequired covers it.

Mutation check: 4 of 4 mutants fail the tests (the old initialize branch, no prompt case, no resource case, a tool result with only a state).

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.

🟢 Approved

No active review issues block the shared request logging and request-ID propagation changes.

No open issues 🎉

Review effort: Balanced

@jeremy

jeremy commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Review threads: 1 resolved (1 fixed: the nil-Header panic in Transport, d481cce).
Review bodies: 3 findings answered, 3 fixed: the cap now keeps a result that has only a request state (4b166f1, reply); an initialize is described by its own params, and prompts and resources can log input_required (a56ea73, reply).
Copilot approved a56ea73, CI is green on it, and nothing is open.

@jeremy
jeremy merged commit b123cc0 into main Nov 18, 2026
7 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