Proxy Server: Forwards requests to the backend with headers.
(ctx context.Context)
| 70 | |
| 71 | // Proxy Server: Forwards requests to the backend with headers. |
| 72 | func 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 | |
| 112 | func runClient(ctx context.Context) { |
| 113 | // Connect to the proxy server (acting as a client). |
no test coverage detected
searching dependent graphs…