Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Arriving as the extraction sequence lands (see the program board):
| `result` | basecamp-mcp-server `internal/tools` (result_shape.go, result_cap.go), hey-mcp-server `internal/server/wire_shape.go`; first consumed by hey-mcp-server and fizzy-mcp-server | structuredContent always a JSON object, the serialized-size result cap with page/offset continuations, title mirroring; one receiving middleware applies all three |
| `auth/exchange` | basecamp-mcp-server `internal/auth/exchange` | RFC 8693 delegation-exchange client for a hosted server: client_secret_post and private_key_jwt client auth, the terminal (re-authorize) vs infra (retry, never re-consent) error fork, allowlisted OAuth error codes with credential-redacted descriptions, optional DPoP proofs and the nonce retry |
| `auth/upstream` | basecamp-mcp-server `internal/upstream` | the error type for credentialed endpoints whose text never renders its cause (fixed reason, status, allowlisted code, scrubbed description), bounded Retry-After and lifetimes, and `upstreamtest`'s hostile-endpoint catalog |
| `requestlog` | hey-mcp-server and fizzy-mcp-server `internal/hosted` (requestlog.go) | the one line per MCP message a hosted server answers (method, tool, client, protocol, grant, session, duration, outcome; never arguments or results), plus the request id (`X-Request-ID`) that joins it to the HTTP request and, through an outbound transport, to the app's log of the calls made for it |

Per-product forever: domain curation and blurbs, vendored SDK model snapshots,
SDK clients and adapters, env var surfaces, product-specific tools and
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ go 1.26

require (
github.com/go-jose/go-jose/v4 v4.1.5
github.com/modelcontextprotocol/go-sdk v1.7.0
github.com/modelcontextprotocol/go-sdk v1.8.1-0.20261014132652-7c486efa8223
github.com/stretchr/testify v1.12.1
)

Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/modelcontextprotocol/go-sdk v1.8.1-0.20261014132652-7c486efa8223 h1:THyv0oM2i7h3ezGwwXWCOqwsh/C2rUTabh+ukQCiClE=
github.com/modelcontextprotocol/go-sdk v1.8.1-0.20261014132652-7c486efa8223/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
Expand Down
72 changes: 72 additions & 0 deletions requestlog/requestid.go
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)
Comment thread
Copilot marked this conversation as resolved.
Resolved
return t.base.RoundTrip(clone)
}
85 changes: 85 additions & 0 deletions requestlog/requestid_test.go
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) }
183 changes: 183 additions & 0 deletions requestlog/requestlog.go
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], "")
}
Loading
Loading