This example demonstrates an MCP (Model Context Protocol) server that transparently passes authentication tokens through the context, supporting both HTTP and stdio transports. It is designed to show how tokens can be extracted from incoming requests or environment variables and made available to downstream tools and operations.
- Token Passthrough: Extracts authentication tokens from HTTP headers or environment variables and injects them into the request context.
- Multiple Transports: Supports
stdioandhttptransports. - Tool Registration: Registers example tools such as
make_authenticated_requestandshow_auth_token. - Extensible: Built on top of the mcp-go server library and integrates with the Gin web framework for HTTP handling.
flowchart TD
subgraph Client
A1[HTTP Request]
A2[Stdio Input]
end
subgraph MCP Server
B1[Token Extraction]
B2[Context Injection]
B3[Tool Execution]
end
subgraph Downstream
C1[Operation/Tool]
end
A1 -- HTTP Header --> B1
A2 -- Env Variable --> B1
B1 --> B2
B2 --> B3
B3 --> C1
- Token Extraction:
- For HTTP: Extracts token from request headers.
- For stdio: Extracts token from environment variables.
- Context Injection:
- Injects the token and a unique request ID into the context for each request.
- Tool Execution:
- Tools can access the token from the context.
02-basic-token-passthrough/
├── server.go # Main MCP server implementationgo build -o mcp-server server.go./mcp-server./mcp-server -t http -addr :8080or
./mcp-server --transport http --addr :8080| Flag | Description | Default |
|---|---|---|
-t |
Transport type (stdio, http) |
stdio |
--transport |
Same as -t |
stdio |
-addr |
Address to listen on (for HTTP) | :8080 |
When running in HTTP mode, the server exposes the following endpoints:
POST /mcpGET /mcpDELETE /mcp
All handled by the MCP server, with token extraction from HTTP headers.
See server.go for the full source.
-
MCPServer: Wraps the underlying MCP server instance. -
NewMCPServer(): Creates and configures the MCP server, registering tools. -
ServeHTTP(): Returns a streamable HTTP server that injects the auth token from HTTP requests into the context. -
ServeStdio(): Starts the MCP server using stdio transport, injecting the auth token from the environment. -
main(): Parses CLI flags, selects the transport, and starts the server accordingly.
-
HTTP:
Usescore.AuthFromRequest(ctx, r)to extract the token from the HTTP request and inject it into the context. -
Stdio:
Usescore.AuthFromEnv(ctx)to extract the token from environment variables. -
Request ID:
Each context is also assigned a unique request ID viacore.WithRequestID(ctx)for traceability.
operation.RegisterAuthTool(mcpServer)This line registers tools that can access the authentication token from the context.
To add more tools or customize token handling, modify the registration logic in NewMCPServer() and the context injection logic in ServeHTTP() and ServeStdio().