Your MCP tool middleware can't return a 429
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
Your MCP tool middleware can’t return a 429
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.
一位阅读过我关于 MCP 服务器书籍的读者提出了一个合理的问题:为什么配套代码不是基于 mcp-go 构建的?所以我对其进行了移植。协议部分很简单,但有趣的部分在于发现哪些检查不能放在 SDK 建议的位置。简而言之:任何以 HTTP 状态码作为响应的检查都必须在 SDK 接收请求之前运行。这包括启动 OAuth 发现的 401 错误、指明缺失作用域的 403 错误,以及带有 Retry-After 的 429 错误。对于这三者而言,工具中间件的介入都太晚了。
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:
实验性的 mcp-go (v1.6.0, MCP 修订版 2026-07-28) 提供了 server.WithToolHandlerMiddleware。它封装了每一个工具调用,是限流器的理想位置: type ToolHandlerFunc func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) type ToolHandlerMiddleware func(ToolHandlerFunc) ToolHandlerFunc 看看中间件能返回什么:结果或错误。这里没有 http.ResponseWriter。因此,我在中间件内部测试了两种表示“减速”的方法:
| 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 |
| 中间件返回 | HTTP 状态 | Retry-After | JSON-RPC 错误 |
|---|---|---|---|
| 普通 Go 错误 | 200 | 无 | -32603 内部错误 |
| server.NewHandlerError(…) 代码 -32010 | 200 | 无 | -32010 限流 |
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.
类型化错误更好:客户端至少能收到你的错误代码,而不是“内部错误”。但响应仍然是 200,且没有任何头部信息告知何时重试。为什么状态码很重要:人们很容易认为 JSON-RPC 错误就是 JSON-RPC 错误。但在代理和你的服务器之间存在许多中间层,而它们大多只读取 HTTP。401 是 OAuth 发现的起点。一个没有令牌就访问你服务器的 MCP 客户端,期望收到一个带有 WWW-Authenticate 头的 401 响应,该头指向你的受保护资源元数据 (RFC 9728)。这就是它找到授权服务器的方式。如果返回一个带有错误主体的 200 响应,客户端将一无所获。
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.
403 告诉客户端需要请求哪个作用域。WWW-Authenticate: Bearer error=“insufficient_scope”, scope=“refunds:write” 为客户端提供了行动依据:请求具有该作用域的令牌。而一个提示“不允许”的工具错误只会让客户端陷入困境。429 是每一层都能理解的状态码。HTTP 客户端库、API 网关、代理和代理运行时都知道在收到 429 时进行退避,且许多都会遵守 Retry-After。对于它们中的每一个来说,带有错误信息的 200 响应看起来都像是成功。剩下的唯一补救措施就是代理自身的重试循环。代理重试非常频繁,所以这正是你最不希望依赖它的地方。此外,这种方式成本更低。在 SDK 之前进行的检查会在主体被分发、参数被解码、配额被消耗或处理程序被查找之前运行。尽早拒绝正是限流器的意义所在。
Three hooks, three kinds of check: In the port, each check went where it has what it needs:
- Hook: net/http middleware in front of mcp-go Checks: token (issuer, audience, expiry, tenant) → 401; scope per tool → 403; cost-weighted burst limit → 429 + Retry-After
- Hook: server.WithToolFilter Checks: tools/list shows only what the token’s scopes allow. mcp-go applies the same filter at call time.
- Hook: server.WithToolHandlerMiddleware Checks: daily quota, idempotency keys, deprecation warnings, turning faults into safe tool errors, completing the audit record
三个钩子,三种检查:在移植过程中,每种检查都被放置在它所需的位置:
- 钩子:mcp-go 前的 net/http 中间件 检查:令牌(发行者、受众、过期时间、租户)→ 401;每个工具的作用域 → 403;成本加权突发限制 → 429 + Retry-After
- 钩子:server.WithToolFilter 检查:tools/list 仅显示令牌作用域允许的内容。mcp-go 在调用时应用相同的过滤器。
- 钩子:server.WithToolHandlerMiddleware 检查:每日配额、幂等键、弃用警告、将故障转化为安全的工具错误、完成审计记录
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. 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.
第一个钩子需要工具名称来确定其成本:在我的服务器中,退款消耗 5 个令牌,查询消耗 1 个。因此,HTTP 中间件会读取主体、窥探内容,然后将其放回。修订版 2026-07-28 还将方法和工具名称放入 Mcp-Method 和 Mcp-Name 头部,这可以避免读取主体。我仍然解析主体,因为旧版客户端不会发送这些头部。限流键来自经过验证的令牌,绝非来自参数。租户是其中的一部分,因此一个高频调用的卖家不会耗尽另一个卖家的预算。
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 { … } 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.
跨越 SDK 边界获取身份:HTTP 中间件已经确定了调用者是谁。工具处理程序也需要知道这一点,且不能信任模型写入的任何内容。mcp-go 正好为此提供了一个钩子: func carry(ctx context.Context, r *http.Request) context.Context { … } mcpHTTP := server.NewStreamableHTTPServer(s, server.WithStateLess(true), server.WithHTTPContextFunc(carry)) 审计事件也随之传递。它在 HTTP 层开启,因此即使是收到 429 的调用也会被记录。它在工具中间件中完成,因为只有那里才知道调用是成功、失败还是被重放了。无论谁拦截了调用,你都能为每次调用获得一条记录。
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.
工具中间件的擅长之处:一旦调用被准入,工具中间件就是处理任何需要已解析调用或结果的任务的正确位置。