Skip to content

mcp: expose parsed streamable HTTP request summary hook #1076

Description

@CaliLuke

Is your feature request related to a problem? Please describe.

Applications wrapping mcp.StreamableHTTPHandler can observe HTTP lifecycle data, but cannot safely observe JSON-RPC/MCP envelope metadata that the SDK already parses internally. To log method, request ID, batch size, notification-only status, or the active session, middleware must currently read and restore req.Body and parse the envelope a second time. That duplicates SDK parsing, can disagree with accepted SDK semantics, adds buffering, and risks retaining request arguments.

This blocks protocol-aware transport observability in generated framework integrations such as CaliLuke/loom-mcp#271. I confirmed that v1.6.1 and v1.7.0-pre.2 expose no parsed-envelope hook on StreamableHTTPOptions.

Describe the solution you'd like

Expose a concurrency-safe hook from the streamable HTTP transport after readBatch has parsed an incoming POST, using the already parsed representation. A safe summary type would be preferable to exposing params/results and could include:

  • whether the input was a batch and its envelope count;
  • method for a single envelope, or sorted unique methods for a batch;
  • request ID for a single request, without synthesizing IDs for notifications;
  • whether a single envelope is a notification, or every batch envelope is a notification;
  • request Mcp-Session-Id, and the negotiated session ID for successful initialization when available.

The hook should not cause any additional req.Body reads, replacement, or buffering, and should not expose or retain params, authorization data, or response payloads. Parse failures can remain represented by the existing HTTP outcome when no safe summary exists.

An API shape such as an optional StreamableHTTPOptions callback receiving *http.Request plus an immutable request summary would let outer middleware emit start events before parsing and enrich its terminal event after ServeHTTP returns. The exact shape is flexible; the key contract is access to the SDK's accepted parsed envelope without reparsing the body.

Describe alternatives you've considered

  • Reading/restoring the body in middleware: rejected because it duplicates parsing and buffering.
  • Inferring methods from URLs or handler callbacks: MCP uses one endpoint and this misses notifications, batches, malformed input, and unknown methods.
  • Logging inside each typed MCP handler: incomplete because it misses protocol-level failures, notifications without handlers, batches, and initialization/session metadata.

Additional context

The consumer needs metadata only for structured transport diagnostics. Request arguments, headers, cookies, authorization data, and response bodies must remain redacted.

Activity

  1. Jaegeonyoon commented on Jul 13, 2026

    @Jaegeonyoon

    I traced the current steamable HTTP request path and the downstream integration in more detail; The most useful contract would be an optional callback invoked synchronously after readBatch has successfully decoded the body, yet before later method, protocol-version, header, or session validation rejects the request.

    A possible shape is:

    type StreamableHTTPRequestSummary struct {
        IsBatch          bool
        EnvelopeCount    int
        Methods          []string
        RequestID        jsonrpc.ID
        NotificationOnly bool
        RequestSessionID string
    }
    
    type StreamableHTTPRequestObserver func(
        req *http.Request,
        summary StreamableHTTPRequestSummary,
    )
    
    

    Suggested semantics:

    • invoke the callback once per successfully decoded POST;
    • do not invoke it for empty, malformed, unreadable, or over-limit bodies;
    • invoke it for envelopes that decode successfully but are rejected later, such as unsupported methods, prohibited batches, header mismatches, or invalid session state;
    • collect methods only from request envelopes, deduplicate them, and sort them lexicographically;
    • expose a request ID only for a single non-batch call;
    • set NotificationOnly only when every envelope is an ID-less request; a response envelope makes it false;
    • use the incoming Mcp-Session-Id as RequestSessionID;
    • return a callback-owned methods slice and do not expose params, results, RequestExtra, headers, authorization data, or cookies.

    The callback contract should be explicit. it should run synchronously, may be invoked concurrently for different HTTP requests, and should return promptly.

    This matters for downstream integrations whose request-scoped observation is finalized when ServeHTTP returns; an asynchronous callback could arrive after the terminal event has already been emitted.

    The incoming Mcp-Session-Id belongs naturally in the parsed request summary. A newly issued response session ID is response-side lifecycle metadata and should not be presented as a successfully established session unless the transport exposes a reliable establishment signal. The enclosing HTTP integration can inspect the final response header after ServeHTTP returns, but the presence of that header alone should not be treated as proof that initialization succeeded.

    The body-safety test should compare equivalent requests with the observer disabled and enabled. Enabling the observer must add zero body Read calls, read zero additional bytes, perform no additional body replacement, and retain neither the body nor copied body bytes. The test should not assume that the SDK itself reads the body only once.

    If this direction looks appropriate, I'd be happy to work on the implementation. Feel free to assign the issue to me.

  2. guglielmo-san commented on Jul 14, 2026

    @guglielmo-san
    Contributor

    Thanks for the detailed proposal @CaliLuke. Agreed the middleware-body-restore workaround is unfortunate. However, I'm hesitant to add a StreamableHTTPOptions callback for this — it's a fairly niche observability need and every new option on that struct is a long-term maintenance commitment.
    I marked as a Low priority enhancement for now

  3. CaliLuke commented on Jul 16, 2026

    @CaliLuke
    ContributorAuthor

    Thanks, @guglielmo-san. I understand the concern about expanding StreamableHTTPOptions and taking on a long-term API commitment. I do want to push back gently on this being a niche observability need, though.

    Streamable HTTP multiplexes every MCP operation through the same endpoint. Without access to metadata from the SDK's accepted parse, an application sees only something like POST /mcp. It cannot determine whether a slow or failing request was initialize, tools/call, resources/read, or another operation; correlate it with its JSON-RPC ID; distinguish a notification from a request; understand batch traffic; or diagnose session-state failures.

    In practice, downstream frameworks and applications are left with three choices:

    • Provide HTTP-only telemetry, leaving operators unable to build meaningful per-method latency/error metrics or diagnose protocol-level production failures.
    • Read, buffer, and parse the body again in middleware. This adds allocations and latency, can diverge from the SDK's parsing semantics, and unnecessarily copies potentially sensitive request arguments into another layer.
    • Instrument individual MCP handlers, which misses requests rejected before dispatch, unknown methods, batches, notifications, and transport/session validation failures.

    This has direct consequences for adoption of the Go SDK. Teams building production servers reasonably expect the official transport implementation to support protocol-aware observability without requiring them to parse the protocol independently. If the SDK owns the request body and the authoritative JSON-RPC parse but exposes no safe summary of that parse, adopters must choose between operating with a significant diagnostic blind spot, duplicating protocol parsing, or forking or bypassing the SDK transport.

    That makes the SDK substantially less attractive to frameworks, platforms, and applications that need production-grade observability. One of the main reasons to adopt an official SDK is to centralize correct protocol handling and avoid maintaining a parallel interpretation of the protocol. Requiring consumers to reconstruct information the SDK has already parsed undercuts that value and encourages exactly the fragmented, potentially incompatible implementations an SDK is intended to prevent.

    I see this less as adding a telemetry convenience and more as exposing information at the only layer that can provide it safely and authoritatively. A narrow immutable summary also avoids exposing the parsed request itself, params, or response payloads. Centralizing that contract in the SDK prevents every server framework from independently reimplementing JSON-RPC parsing around it.

    Would you be open to reconsidering the priority, or to a smaller SDK-owned observation point if a callback on StreamableHTTPOptions is not the right abstraction? The exact API shape is flexible. I'd be happy to implement it along with tests proving that enabling it performs no additional body reads or replacement and retains no body or parameter data.

  4. guglielmo-san commented on Jul 17, 2026

    @guglielmo-san
    Contributor

    I see you point, and it seems also TS SDK is providing a similar feature. I agree on shipping this feature, but I doubt we will be able to integrate already in the next release for protocolVersion20260728 as our focus will be on the new protocol related fixes

  5. CaliLuke commented on Jul 17, 2026

    @CaliLuke
    ContributorAuthor

    I made a PR anyways, I'm happy to rebase on the next release if you folks don't have time to review it for this one.

  6. CaliLuke commented on Jul 22, 2026

    @CaliLuke
    ContributorAuthor

    @guglielmo-san could you approve running the test jobs so I can verify the code is ready?

  7. added
    P3
    on Aug 6, 2026
  8. CaliLuke commented on Sep 18, 2026

    @CaliLuke
    ContributorAuthor

    @guglielmo-san the PR is ready to go, any chance it can finally get looked at? been quite a while.

  9. added a commit that references this issue on Sep 22, 2026
    d4ee62e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions