2 KiB
2 KiB
Proxy Header Propagation Example
This example demonstrates how to propagate HTTP headers from an incoming MCP server request to an outgoing MCP client request.
This is particularly useful when building a gateway or proxy server that needs to forward authentication tokens, trace IDs, or other context-sensitive headers to downstream services.
Architecture
This example runs three components in a single process:
-
Backend Server (Port 8082):
- Exposes a tool
echo_headersthat returns the headers it received.
- Exposes a tool
-
Proxy Server (Port 8081):
- Exposes a tool
forward_headers. - Acts as a client to the Backend Server.
- Uses a custom
http.RoundTripper(HeaderForwardingTransport) to inject headers from the context into outgoing requests.
- Exposes a tool
-
Client:
- Connects to the Proxy Server.
- Calls
forward_headers.
How it works
- The Client calls
forward_headerson the Proxy Server. - The Proxy Server receives the request. The request context contains the HTTP headers in
req.Extra.Header. - The Proxy's tool handler extracts these headers and places them into a new
context.Contextusing a specific key (headerContextKey). - The Proxy uses an
mcp.Clientconfigured with a customHTTPClientthat usesHeaderForwardingTransport. HeaderForwardingTransport.RoundTripinspects the context of outgoing requests. If it finds headers underheaderContextKey, it adds them to the HTTP request.- The Backend Server receives the request with the propagated headers.
Running the Example
Run the example with:
go run main.go
You should see output indicating:
- Backend and Proxy servers starting.
- Gateway receiving headers.
- Client receiving the result, which contains the echoed headers.
Example output:
2025/08/29 10:00:00 Starting Backend Server on :8082
2025/08/29 10:00:00 Starting Gateway Server on :8081
2025/08/29 10:00:00 Gateway received headers: map[...]
2025/08/29 10:00:00 Client received result: ...