MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / runProxyServer

Function runProxyServer

examples/server/proxy/main.go:72–110  ·  view source on GitHub ↗

Proxy Server: Forwards requests to the backend with headers.

(ctx context.Context)

Source from the content-addressed store, hash-verified

70
71// Proxy Server: Forwards requests to the backend with headers.
72func runProxyServer(ctx context.Context) {
73 // Connect to the backend server (acting as a client).
74 client := mcp.NewClient(&mcp.Implementation{Name: "proxy-client", Version: "1.0.0"}, nil)
75 clientSession, err := client.Connect(ctx, &mcp.StreamableClientTransport{
76 Endpoint: "http://localhost:8082/mcp",
77 HTTPClient: NewHeaderForwardingClient(),
78 }, nil)
79 if err != nil {
80 log.Fatalf("Failed to connect to backend: %v", err)
81 }
82 defer clientSession.Close()
83
84 server := mcp.NewServer(&mcp.Implementation{Name: "proxy-server", Version: "1.0.0"}, nil)
85 // Add a tool that forwards the call to the backend.
86 mcp.AddTool(server, &mcp.Tool{
87 Name: "forward_headers",
88 Description: "Calls the backend server, ensuring headers are propagated",
89 }, func(ctx context.Context, req *mcp.CallToolRequest, args struct{}) (*mcp.CallToolResult, any, error) {
90 incomingHeaders := req.Extra.Header
91 log.Printf("Gateway received headers: %v", incomingHeaders)
92 propagateCtx := context.WithValue(ctx, headerContextKey, incomingHeaders)
93 result, err := clientSession.CallTool(propagateCtx, &mcp.CallToolParams{
94 Name: "echo_headers",
95 })
96 if err != nil {
97 return nil, nil, fmt.Errorf("failed to call backend: %w", err)
98 }
99
100 return result, nil, nil
101 })
102
103 // Start the gateway server on port 8081.
104 log.Println("Starting Gateway Server on :8081")
105 if err := http.ListenAndServe(":8081", mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
106 return server
107 }, nil)); err != nil {
108 log.Fatal(err)
109 }
110}
111
112func runClient(ctx context.Context) {
113 // Connect to the proxy server (acting as a client).

Callers 1

mainFunction · 0.85

Calls 8

ConnectMethod · 0.95
NewClientFunction · 0.92
NewServerFunction · 0.92
AddToolFunction · 0.92
NewStreamableHTTPHandlerFunction · 0.92
CallToolMethod · 0.80
CloseMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…