Repository navigation
Extract the per-message request log (requestlog), with a request id #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
53c13ec
Extract the per-message request log (requestlog), with a request id
jeremy d481cce
requestlog: give a headerless request's clone a header map before set…
jeremy 4b166f1
result: a request state alone asks for input, as the SDK's check says
jeremy a56ea73
requestlog: describe an initialize by its own params; prompts and res…
jeremy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| package requestlog | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| ) | ||
|
|
||
| // Header carries a request's id: kamal-proxy sets it on every request it | ||
| // forwards that arrives without one (a UUID), and keeps one that arrives | ||
| // with it, so a client may choose its own. | ||
| const Header = "X-Request-ID" | ||
|
|
||
| type requestIDKey struct{} | ||
|
|
||
| // WithRequestID returns ctx carrying id as its request's id, cut to | ||
| // MaxField bytes. A server that makes its own id when a request arrives | ||
| // without one sets it here, so the per-message line and the server's own | ||
| // lines name the same id. | ||
| func WithRequestID(ctx context.Context, id string) context.Context { | ||
| return context.WithValue(ctx, requestIDKey{}, truncate(id)) | ||
| } | ||
|
|
||
| // RequestID is the id ctx's request carries, or "". | ||
| func RequestID(ctx context.Context) string { | ||
| id, _ := ctx.Value(requestIDKey{}).(string) | ||
| return id | ||
| } | ||
|
|
||
| // Inbound gives each request's context the id its Header names, unless the | ||
| // context already carries one (a server that set its own, outside). A | ||
| // request without the header carries none: Inbound makes no id of its own. | ||
| func Inbound(next http.Handler) http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| if id := r.Header.Get(Header); id != "" && RequestID(r.Context()) == "" { | ||
| r = r.WithContext(WithRequestID(r.Context(), id)) | ||
| } | ||
| next.ServeHTTP(w, r) | ||
| }) | ||
| } | ||
|
|
||
| // Transport sends the id of the request an outbound call is made for, as | ||
| // Header, on every outbound request whose context carries one and that | ||
| // doesn't name an id of its own, so the app's log of the call joins the line | ||
| // of the MCP request that made it. base nil is http.DefaultTransport. | ||
| // | ||
| // It changes nothing else about the request: not its credentials, not its | ||
| // body. Several outbound calls made for one MCP request all carry its id. | ||
| func Transport(base http.RoundTripper) http.RoundTripper { | ||
| if base == nil { | ||
| base = http.DefaultTransport | ||
| } | ||
| return &transport{base: base} | ||
| } | ||
|
|
||
| type transport struct { | ||
| base http.RoundTripper | ||
| } | ||
|
|
||
| func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { | ||
| id := RequestID(req.Context()) | ||
| if id == "" || req.Header.Get(Header) != "" { | ||
| return t.base.RoundTrip(req) | ||
| } | ||
| // A RoundTripper must not modify the request it was given. | ||
| clone := req.Clone(req.Context()) | ||
| if clone.Header == nil { | ||
| // A request may carry no header map at all; Clone keeps it nil. | ||
| clone.Header = make(http.Header) | ||
| } | ||
| clone.Header.Set(Header, id) | ||
| return t.base.RoundTrip(clone) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| package requestlog | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestInboundTakesTheHeaderUnlessTheContextHasOne(t *testing.T) { | ||
| var got string | ||
| h := Inbound(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { got = RequestID(r.Context()) })) | ||
|
|
||
| r := httptest.NewRequest(http.MethodPost, "/mcp", nil) | ||
| r.Header.Set(Header, "abc-123") | ||
| h.ServeHTTP(httptest.NewRecorder(), r) | ||
| assert.Equal(t, "abc-123", got) | ||
|
|
||
| r = httptest.NewRequest(http.MethodPost, "/mcp", nil) | ||
| r.Header.Set(Header, "abc-123") | ||
| r = r.WithContext(WithRequestID(r.Context(), "made-here")) | ||
| h.ServeHTTP(httptest.NewRecorder(), r) | ||
| assert.Equal(t, "made-here", got) | ||
|
|
||
| h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/mcp", nil)) | ||
| assert.Empty(t, got, "no header, no id: Inbound makes none") | ||
| } | ||
|
|
||
| func TestTransportSendsTheRequestsID(t *testing.T) { | ||
| var seen []string | ||
| app := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { | ||
| seen = append(seen, r.Header.Get(Header)+"|"+r.Header.Get("Authorization")) | ||
| })) | ||
| defer app.Close() | ||
| client := &http.Client{Transport: Transport(app.Client().Transport)} | ||
|
|
||
| send := func(ctx context.Context, own string) { | ||
| t.Helper() | ||
| req, err := http.NewRequestWithContext(ctx, http.MethodPost, app.URL, nil) | ||
| require.NoError(t, err) | ||
| req.Header.Set("Authorization", "Bearer x") | ||
| if own != "" { | ||
| req.Header.Set(Header, own) | ||
| } | ||
| resp, err := client.Do(req) | ||
| require.NoError(t, err) | ||
| _ = resp.Body.Close() | ||
| assert.Equal(t, own, req.Header.Get(Header), "the caller's request is left as it was") | ||
| } | ||
| ctx := WithRequestID(context.Background(), "rid-1") | ||
| send(ctx, "") | ||
| send(ctx, "its-own") | ||
| send(context.Background(), "") | ||
|
|
||
| assert.Equal(t, []string{"rid-1|Bearer x", "its-own|Bearer x", "|Bearer x"}, seen) | ||
| } | ||
|
|
||
| func TestTransportDefaultsToTheDefaultTransport(t *testing.T) { | ||
| assert.Equal(t, http.DefaultTransport, Transport(nil).(*transport).base) | ||
| } | ||
|
|
||
| // A request may carry no header map; the transport gives the clone one and | ||
| // leaves the caller's request without. | ||
| func TestTransportSendsTheIDOnARequestWithNoHeader(t *testing.T) { | ||
| var got string | ||
| base := roundTripFunc(func(r *http.Request) (*http.Response, error) { | ||
| got = r.Header.Get(Header) | ||
| return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody, Request: r}, nil | ||
| }) | ||
| req, err := http.NewRequestWithContext(WithRequestID(context.Background(), "rid-2"), http.MethodGet, "http://app.invalid/", nil) | ||
| require.NoError(t, err) | ||
| req.Header = nil | ||
| resp, err := Transport(base).RoundTrip(req) | ||
| require.NoError(t, err) | ||
| _ = resp.Body.Close() | ||
| assert.Equal(t, "rid-2", got) | ||
| assert.Nil(t, req.Header) | ||
| } | ||
|
|
||
| type roundTripFunc func(*http.Request) (*http.Response, error) | ||
|
|
||
| func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| // Package requestlog writes the one line per MCP message a hosted server | ||
| // answers ("mcp request"): which method and tool, who asked (the client's | ||
| // name and version, the protocol revision, the grant), how long it took and | ||
| // how it ended, and the request id that joins it to the HTTP request it rode | ||
| // in on and to the calls the server made for it. | ||
| // | ||
| // It never logs what a message carries: no arguments, no tool input or | ||
| // output, no error text (a tool's error can quote the user's content), no | ||
| // token. A tools/call names its tool only when it is one the server serves, | ||
| // so a client can't write a name of its own into the log, and every string a | ||
| // client chooses (client name and version, User-Agent, request id) is cut to | ||
| // MaxField bytes. | ||
| // | ||
| // Extracted from hey-mcp-server and fizzy-mcp-server internal/hosted | ||
| // (requestlog.go), which logged the same line; the request id is new here. | ||
| package requestlog | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "log/slog" | ||
| "net/http" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/modelcontextprotocol/go-sdk/jsonrpc" | ||
| "github.com/modelcontextprotocol/go-sdk/mcp" | ||
| ) | ||
|
|
||
| // Message is the line's slog message. | ||
| const Message = "mcp request" | ||
|
|
||
| // MaxField bounds each client-chosen string the line carries, so a client | ||
| // can't fill a line. | ||
| const MaxField = 128 | ||
|
|
||
| // UnknownTool is what a tools/call naming a tool the server doesn't serve | ||
| // logs as its tool. | ||
| const UnknownTool = "(unknown)" | ||
|
|
||
| // Options are what a server plugs into the line. | ||
| type Options struct { | ||
| // Tools are the tools the server serves. | ||
| Tools []string | ||
| // Grant names the grant a request rides on, or "" when it isn't known. | ||
| // The line has no grant when Grant is nil or answers "". | ||
| Grant func(context.Context) string | ||
| // CutShort reports a request cut short other than by its context's | ||
| // cancellation or deadline: a request budget that isn't a deadline on | ||
| // the context, say. A tool cut short answers with an error result and no | ||
| // error, so without this the line would say tool_error. Optional. | ||
| CutShort func(context.Context) bool | ||
| } | ||
|
|
||
| // Install has server log one line per MCP message it receives. Call it last, | ||
| // after every other receiving middleware, so the line times all of them. | ||
| func Install(server *mcp.Server, logger *slog.Logger, opts Options) { | ||
| server.AddReceivingMiddleware(Middleware(logger, opts)) | ||
| } | ||
|
|
||
| // Middleware writes one line per MCP message the server receives, once it is | ||
| // answered. Install it outermost, so the duration covers every other | ||
| // middleware and the handler. | ||
| func Middleware(logger *slog.Logger, opts Options) mcp.Middleware { | ||
| tools := make(map[string]bool, len(opts.Tools)) | ||
| for _, name := range opts.Tools { | ||
| tools[name] = true | ||
| } | ||
| return func(next mcp.MethodHandler) mcp.MethodHandler { | ||
| return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) { | ||
| start := time.Now() | ||
| res, err := next(ctx, method, req) | ||
| logger.LogAttrs(ctx, slog.LevelInfo, Message, | ||
| append(requestAttrs(ctx, method, req, tools, opts.Grant), | ||
| slog.Int64("duration_ms", time.Since(start).Milliseconds()), | ||
| slog.Group("result", outcomeAttrs(ctx, res, err, opts.CutShort)...))...) | ||
| return res, err | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // clientDescriber is what any server request says about its client: from | ||
| // the request's own _meta under 2026-07-28, else from the session's | ||
| // initialize, which a stateless server's later requests don't have. | ||
| type clientDescriber interface { | ||
| ProtocolVersion() string | ||
| ClientInfo() *mcp.Implementation | ||
| } | ||
|
|
||
| func requestAttrs(ctx context.Context, method string, req mcp.Request, tools map[string]bool, grant func(context.Context) string) []slog.Attr { | ||
| attrs := []slog.Attr{slog.String("method", method)} | ||
| protocol, client := "", (*mcp.Implementation)(nil) | ||
| if d, ok := req.(clientDescriber); ok { | ||
| protocol, client = d.ProtocolVersion(), d.ClientInfo() | ||
| } | ||
| // The initialize request names its client and revision in its params, | ||
| // before the session has recorded either. | ||
| if init, ok := req.(*mcp.InitializeRequest); ok && mcp.HasParams(init) { | ||
| protocol, client = init.Params.ProtocolVersion, init.Params.ClientInfo | ||
| } | ||
| attrs = append(attrs, slog.String("protocol", truncate(protocol))) | ||
| if client != nil { | ||
| attrs = append(attrs, slog.String("client", truncate(client.Name)), slog.String("client_version", truncate(client.Version))) | ||
| } | ||
| if call, ok := req.(*mcp.CallToolRequest); ok && mcp.HasParams(call) { | ||
| name := call.Params.Name | ||
| if !tools[name] { | ||
| name = UnknownTool | ||
| } | ||
| attrs = append(attrs, slog.String("tool", name)) | ||
| } | ||
| // A stateless server keeps no sessions, so what tells clients apart is | ||
| // whether one sent an Mcp-Session-Id anyway, believing it holds a | ||
| // session. | ||
| session := "none" | ||
| var header http.Header | ||
| if extra := req.GetExtra(); extra != nil { | ||
| header = extra.Header | ||
| } | ||
| if header != nil { | ||
| if header.Get("Mcp-Session-Id") != "" { | ||
| session = "sent" | ||
| } | ||
| if ua := header.Get("User-Agent"); ua != "" { | ||
| attrs = append(attrs, slog.String("user_agent", truncate(ua))) | ||
| } | ||
| } | ||
| attrs = append(attrs, slog.String("session", session)) | ||
| if grant != nil { | ||
| if id := grant(ctx); id != "" { | ||
| attrs = append(attrs, slog.String("grant", id)) | ||
| } | ||
| } | ||
| id := RequestID(ctx) | ||
| if id == "" && header != nil { | ||
| id = truncate(header.Get(Header)) | ||
| } | ||
| if id != "" { | ||
| attrs = append(attrs, slog.String("request_id", id)) | ||
| } | ||
| return attrs | ||
| } | ||
|
|
||
| // outcomeAttrs says how a message ended: canceled (the client cancelled or | ||
| // went away, a deadline passed, or the server cut it short), ok, a tool's | ||
| // own error result (tool_error), a question back to the client | ||
| // (input_required), or a protocol error with its JSON-RPC code. Never the | ||
| // error's text. | ||
| // | ||
| // Cancellation comes first: a tool whose upstream call is cut short answers | ||
| // with an error result and no error, so only the request's context (or | ||
| // cutShort) tells it from a tool that failed on its own. | ||
| func outcomeAttrs(ctx context.Context, res mcp.Result, err error, cutShort func(context.Context) bool) []any { | ||
| if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || (cutShort != nil && cutShort(ctx)) { | ||
| return []any{slog.String("status", "canceled")} | ||
| } | ||
| if err != nil { | ||
| var wire *jsonrpc.Error | ||
| if errors.As(err, &wire) { | ||
| return []any{slog.String("status", "error"), slog.Int64("code", wire.Code)} | ||
| } | ||
| return []any{slog.String("status", "error")} | ||
| } | ||
| if call, ok := res.(*mcp.CallToolResult); ok && call != nil { | ||
| switch { | ||
| // The SDK labels a result input_required (NeedsInput) only after | ||
| // every middleware has returned, so this asks what it asks: the | ||
| // same test the SDK's label applies. | ||
| case call.InputRequests != nil || call.RequestState != "": | ||
| return []any{slog.String("status", "input_required")} | ||
| case call.IsError: | ||
| return []any{slog.String("status", "tool_error")} | ||
| } | ||
| } | ||
| return []any{slog.String("status", "ok")} | ||
| } | ||
|
|
||
| func truncate(s string) string { | ||
| if len(s) <= MaxField { | ||
| return s | ||
| } | ||
| return strings.ToValidUTF8(s[:MaxField], "") | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.