Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ Releases follow [Semantic Versioning](https://semver.org/).

### Features

- **`mcp_reject_query_apikey` refuses query-parameter credentials on MCP endpoints.** Set it to `true` and every MCP endpoint (`/mcp`, `/mcp/p/<slug>`, `/mcp/all`, `/mcp/code`, `/mcp/call` and the legacy `/v1/tool_code` aliases) answers a request carrying `?apikey=` with a 401 instead of honouring it, which forces every client onto `Authorization: Bearer` or `X-API-Key`. It cannot stop a URL that was already sent from being logged by whatever sits in front of the proxy; it makes sure such a client stops working until it is migrated, so the token stops appearing in access logs, proxy logs and browser history from then on. The refusal is explicit rather than "no credential" because, with `require_mcp_auth` off, an unrecognised credential would otherwise be served as the anonymous administrator. Default `false`, so nothing changes unless you opt in; the REST API, the Web UI and its `/events` stream are not affected. Live, no restart. **Caveat:** the Connect wizard writes Codex (and the generic fallback) entries with `?apikey=<credential>` in the URL, so a client connected that way gets a 401 once the option is on: remove the query parameter and carry the credential in a header instead (`env_http_headers` or `http_headers`, see the Connect clients guide); Connect itself is not yet aware of the option.
- **config: `MCPPROXY_API_KEY_FILE` reads the API key from a file (#1706).** The `*_FILE` form of Docker Compose/Swarm secrets, Kubernetes secret volumes and systemd `LoadCredential=`: the key is not in the process environment (`docker inspect`, `/proc/<pid>/environ`) and is never written to `mcp_config.json`. The path must be absolute; one trailing LF or CRLF is removed; at most 64 KiB is read. Setting both `MCPPROXY_API_KEY` and `MCPPROXY_API_KEY_FILE` (both non-empty) is an error: mcpproxy refuses to start with a message naming both variables (never a key or file contents), and the CLI commands and the tray stop the same way. An empty value is treated as unset. A file that is named but cannot be used stops startup with an error naming the variable and path: mcpproxy does not fall back to the config file or a generated key. `mcpproxy status`, the other CLI commands and the tray read it too, and a tray-launched core reads the file itself instead of receiving the key in its environment. `Config.EnsureAPIKey` now also returns an error. (refs #1706, spec 111 FR-014/FR-030/US7)

- **catalog:** a catalog source whose live search times out or fails is now answered from the listing
Expand Down
1 change: 1 addition & 0 deletions docs/configuration/config-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ MCPProxy uses a JSON configuration file located at `~/.mcpproxy/mcp_config.json`
| `trusted_hosts` | string[] | `[]` | Non-loopback `Host` header values accepted on a loopback listener. Needed when running behind a reverse proxy — see [Reverse Proxy Deployment](/operations/reverse-proxy). This is DNS-rebinding protection only; it is **not** the control for forwarded headers (see `trusted_proxies`) |
| `trusted_proxies` | string[] | `[]` (trust nobody) | CIDRs or IP addresses whose `X-Forwarded-For`, `X-Real-IP`, `X-Forwarded-Proto` and `X-Forwarded-Host` headers are believed. Headers from any other peer are ignored and the direct `RemoteAddr` is used. Env `MCPPROXY_TRUSTED_PROXIES` (comma list). Live (hot-reload, no restart). Validation: `trusted_proxies[N] "value" is not a valid CIDR or IP address` — refused identically at boot, `PATCH /api/v1/config` and `/config/apply`. See [Reverse Proxy Deployment](/operations/reverse-proxy#trusted_proxies-forwarded-headers) |
| `require_mcp_auth` | boolean | `false` | Require an API key on the `/mcp` endpoint (off by default for client compatibility). Enable when exposing MCPProxy beyond localhost. **Server edition:** forced to `true` whenever `server_edition.enabled` is `true` — an explicit `false` is not an error, but boot logs `require_mcp_auth: false is overridden to true because server_edition.enabled is true` and `mcpproxy doctor` reports the same finding |
| `mcp_reject_query_apikey` | boolean | `false` | Refuse a `?apikey=` query parameter on every MCP endpoint (`/mcp*` and the legacy `/v1/tool_code` aliases) with a 401, forcing clients onto `Authorization: Bearer <token>` or `X-API-Key` so tokens stop appearing in access logs, proxy logs and browser history (a URL already sent is still logged in transit; the option makes the client fail until it is migrated). MCP endpoints only: the REST API, the Web UI and `/events` keep accepting the query form. Clients connected by the Connect wizard with `?apikey=` in the URL (Codex, the generic fallback) must be switched to a header carrier first. Live, no restart |
| `enable_socket` | boolean | `true` | Enable Unix socket/named pipe for local communication |
| `forward_client_headers` | boolean | `true` | Master switch for [client header forwarding](/configuration/upstream-servers#client-header-forwarding). Nothing is forwarded until a server lists names in `forward_headers`. Env `MCPPROXY_FORWARD_CLIENT_HEADERS=false` disables it for the process (never persisted). |

Expand Down
1 change: 1 addition & 0 deletions docs/features/agent-tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,7 @@ curl -X POST http://localhost:8080/api/v1/tokens \
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `require_mcp_auth` | bool | `false` | Require authentication on `/mcp` endpoint |
| `mcp_reject_query_apikey` | bool | `false` | Refuse a `?apikey=` query parameter on every MCP endpoint (`/mcp*` and the legacy `/v1/tool_code` aliases) with a 401, forcing clients onto `Authorization: Bearer <token>` or `X-API-Key`. It does not stop a URL already sent from being logged in transit; it makes a query-form client fail until it is migrated, so tokens stop appearing in access logs, proxy logs and browser history. Applies to MCP endpoints only; the REST API, the Web UI and its `/events` stream keep accepting the query form. Clients the Connect wizard configured with `?apikey=` in the URL (Codex, the generic fallback) need a header carrier first (see [Connect clients](./connect-clients.md)). Takes effect without a restart |
| `api_key` | string | auto-generated | Admin API key for full access |

### CLI Flags
Expand Down
8 changes: 8 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,14 @@ type Config struct {
// Security settings
APIKey string `json:"api_key,omitempty" mapstructure:"api-key"` // API key for REST API authentication
RequireMCPAuth bool `json:"require_mcp_auth" mapstructure:"require-mcp-auth"` // Require authentication on /mcp endpoint (default: false)
// MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that
// carries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,
// proxy logs and browser history; MCP clients can send Authorization:
// Bearer or X-API-Key instead. Default false (the query form keeps
// working, for clients that can only configure a URL). It covers only the
// MCP endpoints: the Web UI and its SSE stream (/events) still use the
// query form. Live, no restart needed.
MCPRejectQueryAPIKey bool `json:"mcp_reject_query_apikey,omitempty" mapstructure:"mcp-reject-query-apikey"`
// TrustedHosts lists non-loopback Host header values accepted on loopback
// listeners (GH #898). DNS-rebinding protection rejects requests whose Host
// header is not a loopback address when mcpproxy listens on loopback; a
Expand Down
2 changes: 1 addition & 1 deletion internal/runtime/config_hotreload.go
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,7 @@ func (r *ConfigApplyResult) FormatChangedFields() string {
// adopted into the live config, and reported by its JSON key.
var undiffedHotConfigFields = []string{
"EnableTray", "TopK", "MaxResultSizeChars", "InitTimeout", "ForwardProxyEnv",
"RequireMCPAuth", "CheckServerRepo", "DockerRecovery",
"RequireMCPAuth", "MCPRejectQueryAPIKey", "CheckServerRepo", "DockerRecovery",
"RegistriesLocked", "AllowPrivateRegistryFetch", "Features",
"ToolResponseSessionRiskWarning", "OAuthExpiryWarningHours",
"ActivityRetentionDays", "ActivityMaxRecords", "ActivityMaxSizeMB",
Expand Down
79 changes: 79 additions & 0 deletions internal/server/mcp_reject_query_apikey_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package server

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"

"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
)

func newRejectQueryTestServer(t *testing.T, reject bool) *Server {
t.Helper()
cfg := config.DefaultConfig()
cfg.DataDir = t.TempDir()
cfg.Listen = "127.0.0.1:0"
cfg.APIKey = "test-api-key-reject-query"
cfg.MCPRejectQueryAPIKey = reject
srv, err := NewServer(cfg, zap.NewNop())
require.NoError(t, err)
t.Cleanup(func() { _ = srv.Shutdown() })
return srv
}

// With mcp_reject_query_apikey a URL-borne credential is a 401 on every MCP
// path, and the downstream handler never runs. It must not degrade to the
// anonymous administrator that an unrecognised credential gets when
// require_mcp_auth is off.
func TestMCPAuthMiddleware_RejectQueryAPIKey(t *testing.T) {
srv := newRejectQueryTestServer(t, true)

for _, path := range []string{"/mcp", "/mcp/all", "/mcp/code"} {
t.Run("query credential refused on "+path, func(t *testing.T) {
for _, q := range []string{"?apikey=test-api-key-reject-query", "?apikey=", "?apikey=mcp_agt_whatever"} {
seen, code := captureAuthContext(t, srv, httptest.NewRequest(http.MethodPost, path+q, http.NoBody))
assert.Equal(t, http.StatusUnauthorized, code, q)
assert.Nil(t, seen, "handler must not run for %s", q)
}
})
}

t.Run("header credentials still work", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/mcp", http.NoBody)
req.Header.Set("X-API-Key", "test-api-key-reject-query")
seen, code := captureAuthContext(t, srv, req)
require.Equal(t, http.StatusOK, code)
require.NotNil(t, seen)
assert.True(t, seen.IsAdmin())
assert.False(t, seen.Anonymous)

req = httptest.NewRequest(http.MethodPost, "/mcp", http.NoBody)
req.Header.Set("Authorization", "Bearer test-api-key-reject-query")
seen, code = captureAuthContext(t, srv, req)
require.Equal(t, http.StatusOK, code)
require.NotNil(t, seen)
assert.False(t, seen.Anonymous)
})

t.Run("other query parameters are untouched", func(t *testing.T) {
seen, code := captureAuthContext(t, srv, httptest.NewRequest(http.MethodPost, "/mcp?profile=work", http.NoBody))
require.Equal(t, http.StatusOK, code)
require.NotNil(t, seen)
})
}

// The default keeps the query form working, so existing clients that can only
// configure a URL are unaffected.
func TestMCPAuthMiddleware_QueryAPIKeyAcceptedByDefault(t *testing.T) {
srv := newRejectQueryTestServer(t, false)

seen, code := captureAuthContext(t, srv, httptest.NewRequest(http.MethodPost, "/mcp?apikey=test-api-key-reject-query", http.NoBody))
require.Equal(t, http.StatusOK, code)
require.NotNil(t, seen)
assert.True(t, seen.IsAdmin())
assert.False(t, seen.Anonymous, "the query credential must still authenticate by default")
}
9 changes: 9 additions & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,15 @@ func (s *Server) mcpAuthMiddleware(next http.Handler) http.Handler {
// consumers.
next = directRequestKindMiddleware(next)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// mcp_reject_query_apikey: refuse a URL-borne credential outright. It
// must be a 401 and not "no token": with require_mcp_auth off a request
// without a recognised credential is served as the anonymous
// administrator, so silently ignoring the parameter would downgrade a
// caller that thinks it is authenticated.
if cfg := s.runtime.Config(); cfg != nil && cfg.MCPRejectQueryAPIKey && r.URL.Query().Has("apikey") {
http.Error(w, `{"error":"A credential in the ?apikey= query parameter is not accepted on MCP endpoints. Send it as Authorization: Bearer <token> or X-API-Key."}`, http.StatusUnauthorized)
return
}
token := httpapi.ExtractToken(r)
if token == "" {
// Check if MCP auth is required
Expand Down
2 changes: 1 addition & 1 deletion oas/docs.go

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions oas/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,16 @@ components:
inline-response ceiling from 50k to up to 500k chars. Omit the key for
the 500000 default; set it to 0 to disable the annotation.
type: integer
mcp_reject_query_apikey:
description: |-
MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that
carries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,
proxy logs and browser history; MCP clients can send Authorization:
Bearer or X-API-Key instead. Default false (the query form keeps
working, for clients that can only configure a URL). It covers only the
MCP endpoints: the Web UI and its SSE stream (/events) still use the
query form. Live, no restart needed.
type: boolean
mcpServers:
items:
$ref: '#/components/schemas/config.ServerConfig'
Expand Down
Loading