-
Notifications
You must be signed in to change notification settings - Fork 273
examples/server/distributed: a stateless distributed server #380
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 all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| // Copyright 2025 The Go MCP SDK Authors. All rights reserved. | ||
| // Use of this source code is governed by an MIT-style | ||
| // license that can be found in the LICENSE file. | ||
|
|
||
| // The distributed command is an example of a distributed MCP server. | ||
| // | ||
| // It forks multiple child processes (according to the -child_ports flag), each | ||
| // of which is a streamable HTTP MCP server with the 'inc' tool, and proxies | ||
| // incoming http requests to them. | ||
| // | ||
| // Distributed MCP servers must be stateless, because there's no guarantee that | ||
| // subsequent requests for a session land on the same backend. However, they | ||
| // may still have logical session IDs, as can be seen with verbose logging | ||
| // (-v). | ||
| // | ||
| // Example: | ||
| // | ||
| // ./distributed -http=localhost:8080 -child_ports=8081,8082 | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "flag" | ||
| "fmt" | ||
| "log" | ||
| "net/http" | ||
| "net/http/httputil" | ||
| "net/url" | ||
| "os" | ||
| "os/exec" | ||
| "os/signal" | ||
| "strings" | ||
| "sync" | ||
| "sync/atomic" | ||
| "time" | ||
|
|
||
| "github.com/modelcontextprotocol/go-sdk/mcp" | ||
| ) | ||
|
|
||
| const childPortVar = "MCP_CHILD_PORT" | ||
|
|
||
| var ( | ||
| httpAddr = flag.String("http", "", "if set, use streamable HTTP at this address, instead of stdin/stdout") | ||
| childPorts = flag.String("child_ports", "", "comma-separated child ports to distribute to") | ||
| verbose = flag.Bool("v", false, "if set, enable verbose logging") | ||
| ) | ||
|
|
||
| func main() { | ||
| // This command runs as either a parent or a child, depending on whether | ||
| // childPortVar is set (a.k.a. the fork-and-exec trick). | ||
| // | ||
| // Each child is a streamable HTTP server, and the parent is a reverse proxy. | ||
| flag.Parse() | ||
| if v := os.Getenv(childPortVar); v != "" { | ||
| child(v) | ||
| } else { | ||
| parent() | ||
| } | ||
| } | ||
|
|
||
| func parent() { | ||
| exe, err := os.Executable() | ||
| if err != nil { | ||
| log.Fatal(err) | ||
| } | ||
|
|
||
| if *httpAddr == "" { | ||
| log.Fatal("must provide -http") | ||
| } | ||
| if *childPorts == "" { | ||
| log.Fatal("must provide -child_ports") | ||
| } | ||
|
|
||
| // Ensure that children are cleaned up on CTRL-C | ||
| ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) | ||
| defer stop() | ||
|
|
||
| // Start the child processes. | ||
| ports := strings.Split(*childPorts, ",") | ||
| var wg sync.WaitGroup | ||
| childURLs := make([]*url.URL, len(ports)) | ||
| for i, port := range ports { | ||
| wg.Add(1) | ||
| childURL := fmt.Sprintf("http://localhost:%s", port) | ||
| childURLs[i], err = url.Parse(childURL) | ||
| if err != nil { | ||
| log.Fatal(err) | ||
| } | ||
| cmd := exec.CommandContext(ctx, exe, os.Args[1:]...) | ||
| cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", childPortVar, port)) | ||
| cmd.Stderr = os.Stderr | ||
| go func() { | ||
| defer wg.Done() | ||
| log.Printf("starting child %d at %s", i, childURL) | ||
| if err := cmd.Run(); err != nil && ctx.Err() == nil { | ||
| log.Printf("child %d failed: %v", i, err) | ||
| } else { | ||
| log.Printf("child %d exited gracefully", i) | ||
findleyr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| }() | ||
| } | ||
|
|
||
| // Start a reverse proxy that round-robin's requests to each backend. | ||
| var nextBackend atomic.Int64 | ||
| server := http.Server{ | ||
| Addr: *httpAddr, | ||
| Handler: &httputil.ReverseProxy{ | ||
| Rewrite: func(r *httputil.ProxyRequest) { | ||
| child := int(nextBackend.Add(1)) % len(childURLs) | ||
| if *verbose { | ||
| log.Printf("dispatching to localhost:%s", ports[child]) | ||
| } | ||
| r.SetURL(childURLs[child]) | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| wg.Add(1) | ||
| go func() { | ||
| defer wg.Done() | ||
| if err := server.ListenAndServe(); err != nil && ctx.Err() == nil { | ||
| log.Printf("Server failed: %v", err) | ||
| } | ||
| }() | ||
|
|
||
| log.Printf("Serving at %s (CTRL-C to cancel)", *httpAddr) | ||
|
|
||
| <-ctx.Done() | ||
| stop() // restore the interrupt signal | ||
|
|
||
| shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
| defer cancel() | ||
|
|
||
| // Attempt the graceful shutdown. | ||
| if err := server.Shutdown(shutdownCtx); err != nil { | ||
| log.Fatalf("Server shutdown failed: %v", err) | ||
| } | ||
|
|
||
| // Wait for the subprocesses and http server to stop. | ||
| wg.Wait() | ||
|
|
||
| log.Println("Server shutdown gracefully.") | ||
| } | ||
|
|
||
| func child(port string) { | ||
| // Create a server with a single tool that increments a counter. | ||
| server := mcp.NewServer(&mcp.Implementation{Name: "counter"}, nil) | ||
|
|
||
| var count atomic.Int64 | ||
| inc := func(ctx context.Context, req *mcp.CallToolRequest, args struct{}) (*mcp.CallToolResult, struct{ Count int64 }, error) { | ||
| n := count.Add(1) | ||
| if *verbose { | ||
| log.Printf("request %d (session %s)", n, req.Session.ID()) | ||
| } | ||
| return nil, struct{ Count int64 }{n}, nil | ||
| } | ||
| mcp.AddTool(server, &mcp.Tool{Name: "inc"}, inc) | ||
|
|
||
| handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { | ||
| return server | ||
| }, &mcp.StreamableHTTPOptions{ | ||
| Stateless: true, | ||
| }) | ||
| log.Printf("child listening on localhost:%s", port) | ||
| log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%s", port), handler)) | ||
| } | ||
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
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.