diff --git a/README.md b/README.md index b3a56af..3f8dbd6 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,24 @@ _Benefits of Streamable HTTP:_ - **Flexible Responses**: Supports both streaming and direct JSON responses - **Modern Protocol**: Uses the latest MCP transport specification +#### Custom HTTP Headers + +Use repeatable `--headers NAME=VALUE` options with `tools`, `resources`, `prompts`, +or `call` to send custom headers to HTTP and SSE servers: + +```bash +mcp tools https://example.com/mcp --headers X-Project=demo +mcp tools --transport sse https://example.com/sse --headers X-Project=demo --headers X-Mode=preview +mcp call lookup https://example.com/mcp --headers X-Project=demo +``` + +Values can contain `=`. Repeated header names are case-insensitive, and the last +value wins. Explicit `--auth-user` and `--auth-header` options take precedence +over a custom `Authorization` header. Header names and values are validated +before connecting. With custom headers enabled, requests to a different origin +(scheme, host, or port) are rejected, including redirects and SSE message endpoints. +Supply sensitive values at runtime rather than committing them to scripts. + ### Output Formats MCP Tools supports three output formats to accommodate different needs: diff --git a/cmd/mcptools/commands/call.go b/cmd/mcptools/commands/call.go index 2f29a09..59a03e5 100644 --- a/cmd/mcptools/commands/call.go +++ b/cmd/mcptools/commands/call.go @@ -36,6 +36,9 @@ func parseCallArgs(cmdArgs []string) (string, []string) { case (cmdArgs[i] == FlagAuthHeader) && i+1 < len(cmdArgs): AuthHeader = cmdArgs[i+1] i += 2 + case cmdArgs[i] == FlagHeaders && i+1 < len(cmdArgs): + CustomHTTPHeaders = append(CustomHTTPHeaders, cmdArgs[i+1]) + i += 2 case !entityExtracted: entityName = cmdArgs[i] entityExtracted = true diff --git a/cmd/mcptools/commands/http_headers.go b/cmd/mcptools/commands/http_headers.go new file mode 100644 index 0000000..b9921aa --- /dev/null +++ b/cmd/mcptools/commands/http_headers.go @@ -0,0 +1,59 @@ +package commands + +import ( + "fmt" + "net/http" + "net/textproto" + "net/url" + "strings" +) + +func addCustomHTTPHeaders(headers map[string]string, options []string) error { + for _, option := range options { + name, value, found := strings.Cut(option, "=") + if !found || name == "" { + return fmt.Errorf("--headers requires NAME=VALUE") + } + for _, char := range name { + if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || + (char >= '0' && char <= '9') || strings.ContainsRune("!#$%&'*+-.^_`|~", char) { + continue + } + return fmt.Errorf("invalid --headers name") + } + for _, char := range value { + if (char < 32 && char != '\t') || char == 127 { + return fmt.Errorf("invalid --headers value") + } + } + headers[textproto.CanonicalMIMEHeaderKey(name)] = value + } + return nil +} + +// headerOriginTransport prevents custom headers from being sent to another origin. +// This also covers an SSE endpoint event or an HTTP redirect changing the scheme. +type headerOriginTransport struct { + origin *url.URL + headers map[string]string +} + +func (t *headerOriginTransport) RoundTrip(request *http.Request) (*http.Response, error) { + if !strings.EqualFold(request.URL.Scheme, t.origin.Scheme) || !strings.EqualFold(request.URL.Host, t.origin.Host) { + return nil, fmt.Errorf("refusing to send custom HTTP headers to a different origin") + } + forwarded := request.Clone(request.Context()) + if forwarded.Header == nil { + forwarded.Header = make(http.Header) + } + for name, value := range t.headers { + forwarded.Header.Set(name, value) + } + return http.DefaultTransport.RoundTrip(forwarded) +} + +func customHeaderClient(rawURL string, headers map[string]string) *http.Client { + // The transport constructor validates this URL before making a request. + origin, _ := url.Parse(rawURL) + return &http.Client{Transport: &headerOriginTransport{origin: origin, headers: headers}} +} diff --git a/cmd/mcptools/commands/http_headers_test.go b/cmd/mcptools/commands/http_headers_test.go new file mode 100644 index 0000000..5491cf9 --- /dev/null +++ b/cmd/mcptools/commands/http_headers_test.go @@ -0,0 +1,133 @@ +package commands + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/mark3labs/mcp-go/mcp" + "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestProcessCustomHeaders(t *testing.T) { + original := CustomHTTPHeaders + defer func() { CustomHTTPHeaders = original }() + for _, args := range [][]string{ + {"--headers", "X-Project=demo", "server"}, + {"server", "--headers", "X-Project=demo"}, + {"--headers", "X-Project=demo", "server", "--headers", "X-Mode=unit"}, + } { + CustomHTTPHeaders = nil + assert.Equal(t, []string{"server"}, ProcessFlags(args)) + assert.NotEmpty(t, CustomHTTPHeaders) + } +} + +func TestCallCustomHeaders(t *testing.T) { + original := CustomHTTPHeaders + defer func() { CustomHTTPHeaders = original }() + CustomHTTPHeaders = nil + entity, args := parseCallArgs([]string{"lookup", "--headers", "X-Project=demo", "server"}) + assert.Equal(t, "lookup", entity) + assert.Equal(t, []string{"server"}, args) + assert.Equal(t, []string{"X-Project=demo"}, CustomHTTPHeaders) +} + +func TestAddCustomHTTPHeaders(t *testing.T) { + headers := map[string]string{"Accept": "application/json, text/event-stream"} + require.NoError(t, addCustomHTTPHeaders(headers, []string{"X-Project=demo", "x-project=updated", "X-Expression=a=b", "X-Empty="})) + assert.Equal(t, "updated", headers["X-Project"]) + assert.Equal(t, "a=b", headers["X-Expression"]) + assert.Equal(t, "", headers["X-Empty"]) + assert.Equal(t, "application/json, text/event-stream", headers["Accept"]) + + for _, option := range []string{"missing-value", "=empty-name", "Bad Name=private-value", "X-Test=private-value\r\nInjected: true", "X-Test=private-value\x00"} { + err := addCustomHTTPHeaders(map[string]string{}, []string{option}) + require.Error(t, err) + assert.NotContains(t, err.Error(), "private-value") + } +} + +func TestCustomHTTPHeadersTransports(t *testing.T) { + originalHeaders, originalTransport := CustomHTTPHeaders, TransportOption + originalUser, originalAuth := AuthUser, AuthHeader + defer func() { + CustomHTTPHeaders, TransportOption = originalHeaders, originalTransport + AuthUser, AuthHeader = originalUser, originalAuth + }() + for _, transport := range []string{TransportHTTP, TransportSSE} { + t.Run(transport, func(t *testing.T) { + CustomHTTPHeaders, TransportOption, AuthUser, AuthHeader = nil, transport, "", t.Name() + mcpServer := server.NewMCPServer("header-test", "1.0.0", server.WithToolCapabilities(false)) + var handler http.Handler = server.NewStreamableHTTPServer(mcpServer) + if transport == TransportSSE { + handler = server.NewSSEServer(mcpServer) + } + var requests atomic.Int32 + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + assert.Equal(t, "demo", r.Header.Get("X-Project")) + assert.Equal(t, "a=b", r.Header.Get("X-Expression")) + assert.Equal(t, t.Name(), r.Header.Get("Authorization")) + handler.ServeHTTP(w, r) + })) + defer httpServer.Close() + url := httpServer.URL + if transport == TransportSSE { + url += "/sse" + } + args := ProcessFlags([]string{url, "--headers", "X-Project=demo", "--headers", "X-Expression=a=b", "--headers", "Authorization=overridden-option"}) + mcpClient, err := CreateClientFunc(args) + require.NoError(t, err) + defer func() { assert.NoError(t, mcpClient.Close()) }() + _, err = mcpClient.ListTools(context.Background(), mcp.ListToolsRequest{}) + require.NoError(t, err) + assert.Positive(t, requests.Load()) + }) + } +} + +func TestCustomHTTPHeadersOrigin(t *testing.T) { + var received atomic.Int32 + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + received.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer other.Close() + current := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/same" { + assert.Equal(t, "demo", r.Header.Get("X-Project")) + w.WriteHeader(http.StatusOK) + return + } + if r.URL.Path == "/local" { + http.Redirect(w, r, "/same", http.StatusTemporaryRedirect) + return + } + http.Redirect(w, r, other.URL, http.StatusTemporaryRedirect) + })) + defer current.Close() + httpClient := customHeaderClient(current.URL, map[string]string{"X-Project": "demo"}) + for _, path := range []string{"/same", "/local"} { + request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, current.URL+path, nil) + require.NoError(t, err) + request.Header.Set("X-Project", "demo") + response, err := httpClient.Do(request) + require.NoError(t, err) + _, _ = io.Copy(io.Discard, response.Body) + require.NoError(t, response.Body.Close()) + } + _, err := httpClient.Get(current.URL + "/cross-origin") + require.Error(t, err) + assert.Zero(t, received.Load()) + _, err = httpClient.Get(other.URL) + require.Error(t, err) + assert.Zero(t, received.Load()) + _, err = httpClient.Get("https" + current.URL[len("http"):]) + require.ErrorContains(t, err, "different origin") +} diff --git a/cmd/mcptools/commands/root.go b/cmd/mcptools/commands/root.go index 068a7eb..fe36a71 100644 --- a/cmd/mcptools/commands/root.go +++ b/cmd/mcptools/commands/root.go @@ -19,6 +19,7 @@ const ( FlagTransport = "--transport" FlagAuthUser = "--auth-user" FlagAuthHeader = "--auth-header" + FlagHeaders = "--headers" ) // entity types. @@ -51,6 +52,8 @@ var ( AuthUser string // AuthHeader is a custom Authorization header. AuthHeader string + // CustomHTTPHeaders contains repeatable NAME=VALUE HTTP header options. + CustomHTTPHeaders []string ) // RootCmd creates the root command. @@ -68,6 +71,7 @@ It allows you to discover and call tools, list resources, and interact with MCP- cmd.PersistentFlags().StringVar(&TransportOption, "transport", "http", "HTTP transport type (http, sse)") cmd.PersistentFlags().StringVar(&AuthUser, "auth-user", "", "Basic authentication in username:password format") cmd.PersistentFlags().StringVar(&AuthHeader, "auth-header", "", "Custom Authorization header (e.g., 'Bearer token' or 'Basic base64credentials')") + cmd.PersistentFlags().StringArrayVar(&CustomHTTPHeaders, "headers", nil, "Custom HTTP header as NAME=VALUE (repeatable)") return cmd } diff --git a/cmd/mcptools/commands/utils.go b/cmd/mcptools/commands/utils.go index 3789004..35a41fe 100644 --- a/cmd/mcptools/commands/utils.go +++ b/cmd/mcptools/commands/utils.go @@ -118,21 +118,31 @@ var CreateClientFunc = func(args []string, _ ...client.ClientOption) (*client.Cl // Create headers map with required Accept header for MCP protocol headers := make(map[string]string) - // Add authentication header if provided - if authHeader != "" { - headers["Authorization"] = authHeader - } - // Add Accept header required by MCP streamable HTTP and SSE transports // Many MCP servers require clients to accept both JSON responses and event streams headers["Accept"] = "application/json, text/event-stream" + if err = addCustomHTTPHeaders(headers, CustomHTTPHeaders); err != nil { + return nil, err + } + // Explicit authentication options take precedence over custom Authorization. + if authHeader != "" { + headers["Authorization"] = authHeader + } if TransportOption == TransportSSE { // For SSE transport, use transport.ClientOption - c, err = client.NewSSEMCPClient(cleanURL, transport.WithHeaders(headers)) + options := []transport.ClientOption{transport.WithHeaders(headers)} + if len(CustomHTTPHeaders) > 0 { + options = append(options, transport.WithHTTPClient(customHeaderClient(cleanURL, headers))) + } + c, err = client.NewSSEMCPClient(cleanURL, options...) } else { // For StreamableHTTP transport, use transport.StreamableHTTPCOption - c, err = client.NewStreamableHttpClient(cleanURL, transport.WithHTTPHeaders(headers)) + options := []transport.StreamableHTTPCOption{transport.WithHTTPHeaders(headers)} + if len(CustomHTTPHeaders) > 0 { + options = append(options, transport.WithHTTPBasicClient(customHeaderClient(cleanURL, headers))) + } + c, err = client.NewStreamableHttpClient(cleanURL, options...) } if err != nil { @@ -211,6 +221,9 @@ func ProcessFlags(args []string) []string { case args[i] == FlagAuthHeader && i+1 < len(args): AuthHeader = args[i+1] i += 2 + case args[i] == FlagHeaders && i+1 < len(args): + CustomHTTPHeaders = append(CustomHTTPHeaders, args[i+1]) + i += 2 default: parsedArgs = append(parsedArgs, args[i]) i++