A reader of my book on MCP servers asked a fair question: why isn't the companion code built on mcp-go? So I ported it. The protocol part was easy. The interesting part was finding out which checks can't live where an SDK invites you to put them.

The short version: anything whose answer is an HTTP status code has to run before the SDK sees the request. That includes the 401 that starts OAuth discovery, the 403 that names the missing scope, and the 429 with Retry-After. Tool middleware is too late for all three.

The experiment

mcp-go (v1.6.0, MCP revision 2026-07-28) gives you server.WithToolHandlerMiddleware. It wraps every tool call, and it's the obvious place for a rate limiter:

type ToolHandlerFunc func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) type ToolHandlerMiddleware func(ToolHandlerFunc) ToolHandlerFunc 

Look at what a middleware can return: a result or an error. There's no http.ResponseWriter. So I tested both ways of saying "slow down" from inside one:

Middleware returns HTTP status Retry-After JSON-RPC error
a plain Go error 200 none -32603 internal error
server.NewHandlerError(...) with code -32010 200 none -32010 rate limited

The typed error is better: the client at least gets your code instead of "internal error". But the response is still a 200, with no header telling anyone when to come back.

Why the status code matters

It's tempting to say a JSON-RPC error is a JSON-RPC error. But a lot sits between an agent and your server, and most of it only reads HTTP.

401 is how OAuth discovery starts. An MCP client that hits your server without a token expects a 401 with a WWW-Authenticate header pointing at your protected resource metadata (RFC 9728). That's how it finds your authorization server. Return a 200 with an error body and the client has nothing to discover.

403 tells the client which scope to ask for. WWW-Authenticate: Bearer error="insufficient_scope", scope="refunds:write" gives the client something to act on: request a token with that scope. A tool error saying "not allowed" leaves the client stuck.

429 is the one every layer understands. HTTP client libraries, API gateways, proxies and agent runtimes all know to back off on a 429, and many honour Retry-After. A 200 with an error inside looks like success to every one of them. The agent's own retry loop is the only thing left to notice. Agents retry a lot, so that's where you least want to rely on it.

It's also cheaper. A check in front of the SDK runs before the body is dispatched, the arguments are decoded, the quota is spent, or a handler is looked up. Rejecting early is the point of a rate limiter.

Three hooks, three kinds of check

In the port, each check went where it has what it needs:

Hook Checks
net/http middleware in front of mcp-go token (issuer, audience, expiry, tenant) → 401; scope per tool → 403; cost-weighted burst limit → 429 + Retry-After
server.WithToolFilter tools/list shows only what the token's scopes allow. mcp-go applies the same filter at call time.
server.WithToolHandlerMiddleware daily quota, idempotency keys, deprecation warnings, turning faults into safe tool errors, completing the audit record

The first hook needs the tool's name to know its cost: in my server a refund costs 5 tokens and a lookup costs 1. So the HTTP middleware reads the body, peeks at it, and puts it back:

body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody)) if err != nil { writeJSON(w, http.StatusRequestEntityTooLarge, jsonrpc.Fail(nil, jsonrpc.InvalidRequest, "request too large", nil)) return } r.Body = io.NopCloser(bytes.NewReader(body)) // ... decode method and params.name; anything that isn't tools/call goes straight to mcp-go spec, _, err := k.Registry.Resolve(req.Params.Name, k.now()) if err == nil { // unknown and retired tools are answered further in if !auth.HasScope(who.Scopes, spec.Scope, k.Implies) { auth.Challenge(w.Header(), k.MetadataURL, "insufficient_scope", spec.Scope) writeJSON(w, http.StatusForbidden, jsonrpc.Fail(req.ID, jsonrpc.InvalidRequest, "insufficient scope: "+spec.Scope, nil)) return } if ok, wait := k.Limiter.Allow(who.Tenant+"|"+who.ClientID, spec.Cost); !ok { ev.Outcome = audit.RateLimited w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds()+0.999))) writeJSON(w, http.StatusTooManyRequests, jsonrpc.Fail(req.ID, jsonrpc.RateLimited, "rate limited", map[string]int64{"retryAfterMs": wait.Milliseconds()})) return } } next.ServeHTTP(w, r.WithContext(context.WithValue(ctx, eventKey{}, ev))) 

Revision 2026-07-28 also puts the method and tool name in Mcp-Method and Mcp-Name headers, which would avoid reading the body. I still parse the body, because older clients don't send those headers.

The rate-limit key comes from the validated token, never from the arguments. The tenant is part of it, so one noisy seller can't drain another seller's budget.

Getting identity across the SDK boundary

The HTTP middleware has decided who's calling. The tool handlers need to know too, without trusting anything the model wrote. mcp-go has a hook for exactly this:

func carry(ctx context.Context, r *http.Request) context.Context { if p, ok := tenant.From(r.Context()); ok { ctx = tenant.With(ctx, p) } if ev, ok := r.Context().Value(eventKey{}).(*audit.Event); ok { ctx = context.WithValue(ctx, eventKey{}, ev) } return ctx } mcpHTTP := server.NewStreamableHTTPServer(s, server.WithStateLess(true), server.WithHTTPContextFunc(carry)) 

The audit event rides along too. It's opened at the HTTP layer, so a call that gets a 429 is still recorded. It's completed in the tool middleware, which is the only place that knows whether the call succeeded, failed or was replayed. You get one record per call, whoever stopped it.

What tool middleware is good at

Once a call is admitted, tool middleware is the right place for anything that needs the parsed call or the result:

res, replayed, err := k.once(ctx, spec, req, next) // idempotency key from _meta switch { case err != nil: ev.Outcome, ev.Detail = audit.ToolError, err.Error() res = toolError("The tool failed (trace " + ev.TraceID + "). Check state before retrying.") case replayed: ev.Outcome = audit.Replayed case res.IsError: ev.Outcome = audit.ToolError default: ev.Outcome = audit.OK } 

Two details there matter for agents. A fault becomes a tool error the model can read ("check state before retrying"), never a stack trace. And a replayed refund returns the first answer instead of running twice.

A bonus bug

2026-07-28 requires io.modelcontextprotocol/clientCapabilities in _meta on every request. An empty object is fine. mcp-go enforces this and rejects requests without it with -32602. My own tiny test client had been leaving it out from day one, because my hand-written server never checked. Porting to a stricter implementation found a bug that hand-rolled tests didn't.

Did anything else change?

No. The same end-to-end walkthrough runs against both servers: no token, a cross-tenant lookup, an invalid enum, the same refund sent twice, a 429 with Retry-After, then "nothing left to refund". The checks are the same Go packages; only the protocol layer moved. That's the argument for keeping checks in small packages behind plain interfaces: an SDK becomes a swap, not a rewrite.

The full example, with a table mapping every check to its hook, is here: github.com/AlwyAbdullah/the-tool-layer/tree/main/examples/mcp-go.

This comes from the companion code for The Tool Layer, a book on building MCP servers that survive production. The repo is MIT-licensed and works without the book.