|
| 1 | +// Copyright 2025 The Go MCP SDK Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by an MIT-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "errors" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 13 | + "golang.org/x/time/rate" |
| 14 | +) |
| 15 | + |
| 16 | +// GlobalRateLimiterMiddleware creates a middleware that applies a global rate limit. |
| 17 | +// Every request attempting to pass through will try to acquire a token. |
| 18 | +// If a token cannot be acquired immediately, the request will be rejected. |
| 19 | +func GlobalRateLimiterMiddleware[S mcp.Session](limiter *rate.Limiter) mcp.Middleware[S] { |
| 20 | + return func(next mcp.MethodHandler[S]) mcp.MethodHandler[S] { |
| 21 | + return func(ctx context.Context, session S, method string, params mcp.Params) (mcp.Result, error) { |
| 22 | + if !limiter.Allow() { |
| 23 | + return nil, errors.New("JSON RPC overloaded") |
| 24 | + } |
| 25 | + return next(ctx, session, method, params) |
| 26 | + } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +// PerMethodRateLimiterMiddleware creates a middleware that applies rate limiting |
| 31 | +// on a per-method basis. |
| 32 | +// Methods not specified in limiters will not be rate limited by this middleware. |
| 33 | +func PerMethodRateLimiterMiddleware[S mcp.Session](limiters map[string]*rate.Limiter) mcp.Middleware[S] { |
| 34 | + return func(next mcp.MethodHandler[S]) mcp.MethodHandler[S] { |
| 35 | + return func(ctx context.Context, session S, method string, params mcp.Params) (mcp.Result, error) { |
| 36 | + if limiter, ok := limiters[method]; ok { |
| 37 | + if !limiter.Allow() { |
| 38 | + return nil, errors.New("JSON RPC overloaded") |
| 39 | + } |
| 40 | + } |
| 41 | + return next(ctx, session, method, params) |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func main() { |
| 47 | + server := mcp.NewServer("greeter1", "v0.0.1", nil) |
| 48 | + server.AddReceivingMiddleware(GlobalRateLimiterMiddleware[*mcp.ServerSession](rate.NewLimiter(rate.Every(time.Second/5), 10))) |
| 49 | + server.AddReceivingMiddleware(PerMethodRateLimiterMiddleware[*mcp.ServerSession](map[string]*rate.Limiter{ |
| 50 | + "callTool": rate.NewLimiter(rate.Every(time.Second), 5), // once a second with a burst up to 5 |
| 51 | + "listTools": rate.NewLimiter(rate.Every(time.Minute), 20), // once a minute with a burst up to 20 |
| 52 | + })) |
| 53 | + // Run Server logic. |
| 54 | +} |
0 commit comments