Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ Releases follow [Semantic Versioning](https://semver.org/).

### Features

- **profiles:** `mcpproxy access suggest` turns the calls your profiles blocked into reviewed profile
changes (#1700). It reads the profile refusals in the audit log (`--since`, default 24h), groups them
by profile, tool and block reason, re-checks each group with the access explainer so tools that are
reachable now drop out, and prints the command that would fix each one. A deny rule is reported and
never offered for widening, an unannotated tool is never given a tier, and `code_execution` and
management refusals carry a warning. Nothing is applied. `--patch` adds the proposed profile
document per profile, in mcpproxy's own profile format. Also `GET /api/v1/access/suggest` and the
`suggest` operation of the `profiles` MCP tool (administrators only).
- **`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)

Expand Down
134 changes: 134 additions & 0 deletions cmd/mcpproxy/access_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func GetAccessCommand() *cobra.Command {
Short: "Explain what a client, token or profile can reach",
}
cmd.AddCommand(newAccessExplainCmd())
cmd.AddCommand(newAccessSuggestCmd())
silenceUsageOnRun(cmd)
return cmd
}
Expand Down Expand Up @@ -89,6 +90,139 @@ Examples:
return cmd
}

func newAccessSuggestCmd() *cobra.Command {
var since, token, prof string
var patch bool
cmd := &cobra.Command{
Use: "suggest",
Short: "Suggest profile changes from calls the profiles blocked",
Long: `Read the profile refusals in the audit log, group them by profile, tool and
block reason, and print one reviewed suggestion per group with the command that
would apply it. Each group is re-checked with the access explainer, so a tool
that is reachable now no longer appears.

Nothing is applied. A deny rule is reported and never offered for widening, and
an unannotated tool is never given a tier: you choose it. Blocks that no profile
change fixes (quarantine, token permissions) are counted; use "access explain".
Administrators only.

--since is a duration (90m, 24h, 7d); the default is 24h and the audit-log
retention is the only limit. --patch also prints, per profile, the proposed
profile document. That is mcpproxy's own profile format (what PUT
/api/v1/profiles/{name} takes, and a profiles[] entry in the config file), not a
client permission file.

Examples:
mcpproxy access suggest
mcpproxy access suggest --since 7d --profile work-readonly
mcpproxy access suggest --token ci-bot --patch
mcpproxy access suggest -o json`,
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
q := url.Values{}
q.Set("since", since)
if token != "" {
q.Set("token", token)
}
if prof != "" {
q.Set("profile", prof)
}
if patch {
q.Set("patch", "true")
}
data, err := restDo("access", http.MethodGet, "/api/v1/access/suggest?"+q.Encode(), nil)
if err != nil {
return err
}
if structuredOutput() {
return printData(data)
}
var res runtime.AccessSuggestions
if err := json.Unmarshal(data, &res); err != nil {
return err
}
return printSuggestions(res, patch)
},
}
cmd.Flags().StringVar(&since, "since", "24h", "Look-back window: a duration such as 90m, 24h or 7d")
cmd.Flags().StringVar(&token, "token", "", "Only blocks of this token")
cmd.Flags().StringVar(&prof, "profile", "", "Only blocks under this profile")
cmd.Flags().BoolVar(&patch, "patch", false, "Also print the proposed profile document per profile")
return cmd
}

func printSuggestions(res runtime.AccessSuggestions, patch bool) error {
fmt.Printf("Profile refusals in the last %s: %d\n", res.Window, res.BlockedCalls)
if len(res.Suggestions) == 0 {
fmt.Println("Nothing to suggest.")
} else {
rows := make([][]string, 0, len(res.Suggestions))
for _, s := range res.Suggestions {
rows = append(rows, []string{
s.Profile, s.Tool, string(s.BlockReason), fmt.Sprint(s.Count),
dash(strings.Join(s.Tokens, ",")), s.LastSeen.Local().Format("2006-01-02 15:04"), string(s.Suggestion),
})
}
if err := printTable([]string{"PROFILE", "TOOL", "REASON", "BLOCKED", "TOKENS", "LAST SEEN", "SUGGESTION"}, rows); err != nil {
return err
}
for _, s := range res.Suggestions {
printSuggestionDetail(s)
}
}
var skipped []string
add := func(n int, what string) {
if n > 0 {
skipped = append(skipped, fmt.Sprintf("%d %s", n, what))
}
}
add(res.AlreadyFixed, "group(s) already reachable")
add(res.ProfileRemoved, "group(s) of a removed profile")
add(res.NonProfileBlocked, "blocked call(s) not caused by a profile (see 'mcpproxy access explain')")
add(res.Unattributed, "refusal(s) naming no profile")
if len(skipped) > 0 {
fmt.Println("Not listed: " + strings.Join(skipped, "; ") + ".")
}
if patch {
if len(res.Patches) == 0 {
fmt.Println("No apply-ready profile change (classify needs a tier from you).")
}
for _, p := range res.Patches {
doc, err := json.MarshalIndent(p.Proposed, "", " ")
if err != nil {
return err
}
fmt.Printf("\nProposed profile %s (%s):\n%s\n", p.Profile, strings.Join(p.Changes, "; "), doc)
}
}
return nil
}

// printSuggestionDetail prints the command, note and warning of one row.
func printSuggestionDetail(s runtime.AccessSuggestion) {
var want profile.FixAction
switch s.Suggestion {
case runtime.SuggestAllow:
want = profile.FixAllowInProfile
case runtime.SuggestAddServer:
want = profile.FixAddServerToProfile
case runtime.SuggestClassify:
want = profile.FixClassifyInProfile
}
fmt.Printf("\n%s %s (%s, %d blocked)\n", s.Profile, s.Tool, s.BlockReason, s.Count)
for _, f := range s.Fixes {
if f.Action == want {
fmt.Printf(" %s\n", fixCommand(f, s.Tool))
}
}
if s.Note != "" {
fmt.Printf(" %s\n", s.Note)
}
if s.Warning != "" {
fmt.Printf(" WARNING: %s\n", s.Warning)
}
}

func printExplanation(ex runtime.AccessExplanation) {
subject := string(ex.Subject.Kind)
if ex.Subject.Name != "" {
Expand Down
110 changes: 110 additions & 0 deletions cmd/mcpproxy/access_suggest_cmd_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package main

import (
"net/url"
"testing"
"time"

"github.com/stretchr/testify/require"
)

// `mcpproxy access suggest` (#1700): the query it sends, what it prints, and
// that it never applies anything.

const suggestResponse = `{
"since":"2026-10-19T12:00:00Z","until":"2026-10-20T12:00:00Z","window":"24h0m0s",
"blocked_calls":9,"already_fixed":1,"profile_removed":0,"non_profile_blocked":2,"unattributed":0,
"suggestions":[
{"profile":"research","tool":"github:create_issue","server":"github","block_reason":"profile_tier","count":5,
"tokens":["ci-bot","dev-bot"],"clients":[],"first_seen":"2026-10-20T08:00:00Z","last_seen":"2026-10-20T11:00:00Z",
"suggestion":"allow","fixes":[{"step":"tier_cap","action":"allow_in_profile","target":"research","label":"Allow github:create_issue in research"}]},
{"profile":"research","tool":"github:search_code","server":"github","block_reason":"profile_unannotated","count":2,
"tokens":["ci-bot"],"clients":[],"first_seen":"2026-10-20T08:00:00Z","last_seen":"2026-10-20T09:00:00Z",
"suggestion":"classify","needs_input":["tier"],"note":"The tool declares no tier. Choose read, write or destructive; no tier is assumed.",
"fixes":[{"step":"tier_cap","action":"classify_in_profile","target":"research","label":"Classify github:search_code in research"}]},
{"profile":"research","tool":"github:delete_repo","server":"github","block_reason":"profile_rule","count":1,
"tokens":["ci-bot"],"clients":[],"first_seen":"2026-10-20T08:00:00Z","last_seen":"2026-10-20T08:00:00Z",
"suggestion":"none","note":"Denied by an explicit rule in the profile. Edit tools.deny if this access is intended.","fixes":[]},
{"profile":"research","tool":"code_execution","block_reason":"profile_code_execution","count":1,
"tokens":["ci-bot"],"clients":[],"first_seen":"2026-10-20T08:00:00Z","last_seen":"2026-10-20T08:00:00Z",
"suggestion":"none","warning":"Setting code_execution on profile research lets scripts call every upstream tool the profile can reach.","fixes":[]}
],
"patches":[{"profile":"research","changes":["tools.allow += github:create_issue"],
"proposed":{"name":"research","servers":["github"],"max_tier":"read","tools":{"allow":["github:create_issue"]}}}]
}`

func TestAccessSuggest_DefaultQuery(t *testing.T) {
rec := newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": okResp(suggestResponse)})
_, _, err := runCLI(t, GetAccessCommand, "table", "suggest")
require.NoError(t, err)
q, _ := url.ParseQuery(rec.only(t).RawQuery)
require.Equal(t, url.Values{"since": {"24h"}}, q, "the default window is 24h and no patch is asked for")
}

func TestAccessSuggest_FlagsMapToTheQuery(t *testing.T) {
rec := newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": okResp(suggestResponse)})
_, _, err := runCLI(t, GetAccessCommand, "table", "suggest", "--since", "7d", "--profile", "research", "--token", "ci-bot", "--patch")
require.NoError(t, err)
q, _ := url.ParseQuery(rec.only(t).RawQuery)
require.Equal(t, url.Values{"since": {"7d"}, "profile": {"research"}, "token": {"ci-bot"}, "patch": {"true"}}, q)
}

func TestAccessSuggest_TableShowsCommandsNotesAndWarnings(t *testing.T) {
newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": okResp(suggestResponse)})
out, _, err := runCLI(t, GetAccessCommand, "table", "suggest")
require.NoError(t, err)

last := time.Date(2026, 10, 20, 11, 0, 0, 0, time.UTC).Local().Format("2006-01-02 15:04")
require.Contains(t, out, "Profile refusals in the last 24h0m0s: 9")
require.Contains(t, out, "github:create_issue")
require.Contains(t, out, "ci-bot,dev-bot")
require.Contains(t, out, last)
require.Contains(t, out, "mcpproxy profile update research --add-allow github:create_issue")
// A tier is never filled in for the operator.
require.Contains(t, out, "mcpproxy profile classify research github:search_code <read|write|destructive>")
require.Contains(t, out, "Denied by an explicit rule")
require.NotContains(t, out, "--add-allow github:delete_repo", "a deny rule is never offered for widening")
require.Contains(t, out, "WARNING: Setting code_execution on profile research")
require.Contains(t, out, "Not listed: 1 group(s) already reachable; 2 blocked call(s) not caused by a profile")
require.NotContains(t, out, "Proposed profile", "the patch is opt-in")
}

func TestAccessSuggest_PatchPrintsTheProposedProfileDocument(t *testing.T) {
newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": okResp(suggestResponse)})
out, _, err := runCLI(t, GetAccessCommand, "table", "suggest", "--patch")
require.NoError(t, err)
require.Contains(t, out, "Proposed profile research (tools.allow += github:create_issue):")
require.Contains(t, out, `"allow": [`)
require.Contains(t, out, `"max_tier": "read"`)
}

func TestAccessSuggest_JSONIsData(t *testing.T) {
newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": okResp(suggestResponse)})
out, _, err := runCLI(t, GetAccessCommand, "json", "suggest")
require.NoError(t, err)
require.Equal(t, indented(t, suggestResponse), out)
}

func TestAccessSuggest_NothingToSuggest(t *testing.T) {
newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": okResp(`{"window":"24h0m0s","suggestions":[],"blocked_calls":0}`)})
out, _, err := runCLI(t, GetAccessCommand, "table", "suggest")
require.NoError(t, err)
require.Contains(t, out, "Nothing to suggest.")
}

func TestAccessSuggest_RefusalIsExit1(t *testing.T) {
newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": refuse(400, `{"success":false,"error":"invalid since \"soon\": use a duration such as 90m, 24h or 7d"}`)})
_, _, err := runCLI(t, GetAccessCommand, "table", "suggest", "--since", "soon")
require.Error(t, err)
require.Equal(t, ExitCodeGeneralError, classifyError(err))
require.Contains(t, err.Error(), "invalid since")
}

func TestAccessSuggest_OnlyReadsFromTheDaemon(t *testing.T) {
rec := newRESTRecorder(t, map[string]cannedResponse{"GET /api/v1/access/suggest": okResp(suggestResponse)})
_, _, err := runCLI(t, GetAccessCommand, "table", "suggest", "--patch")
require.NoError(t, err)
for _, r := range rec.all() {
require.Equal(t, "GET", r.Method, "suggest never writes a profile")
}
}
24 changes: 24 additions & 0 deletions docs/cli/profile-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,30 @@ mcpproxy access explain --tool github:create_issue (--client cursor | --token ci

Walks the gates a call meets (credential, profile, server in scope, tool rule, tier cap, token permission, global gate, server state, tool approval), prints the verdict (`allowed`, `blocked`, `hidden`) and the fixes in preference order, each with the command that performs it. The verdict is computed by the same predicate that enforces the call, so it never disagrees with what actually happens. The move-client fix prints `mcpproxy client set-profile <client> <destination-profile>` with the profile it names. Exit code 0 whenever an explanation is produced: the verdict is data.

## `mcpproxy access suggest`

```bash
mcpproxy access suggest [--since 24h] [--profile <p>] [--token <name>] [--patch] [-o json]
```

Turns the calls your profiles blocked into reviewed profile changes. It reads the profile refusals in the audit log over `--since` (a duration such as `90m`, `24h` or `7d`; default `24h`, and the audit-log retention is the only limit), groups them by profile, tool and block reason, and prints one row per group: how many calls, which tokens, when last, and the command that would fix it. Each group is checked again with the access explainer first, so a tool that is reachable now no longer appears.

What it will and will not suggest:

| Block reason | Suggestion |
|--------------|------------|
| `profile_tier` | `profile update <p> --add-allow <server:tool>` |
| `profile_unannotated` | `profile classify <p> <server:tool> <read\|write\|destructive>`. The tier is yours to choose; none is assumed. |
| `profile_server_scope` | `profile update <p> --add-server <server>` (a `code_execution` script called a server outside the profile) |
| `profile_rule` | Reported, never offered for widening. A deny rule is a decision someone wrote. |
| `profile_code_execution`, `profile_management` | Reported with a warning naming the profile field (`code_execution`, `management_tools`); no command. |

Only profile changes are suggested. Calls blocked for another reason (quarantine, token permissions, a global gate) are counted under "Not listed"; use `access explain` for those. Nothing is applied: you run the commands yourself. Administrators only.

`--patch` also prints, per profile, the stored profile with every apply-ready suggestion merged in. That document is mcpproxy's own profile format: the body `PUT /api/v1/profiles/<name>` takes and the shape of a `profiles[]` entry in the config file. It is not a permission file for Claude, Codex or any other client; those clients do not decide what a profile allows. A classify suggestion is left out of the document, because it needs a tier from you. With `-o json` the same data (and `patches` when `--patch` is set) is returned as JSON.

The same data is available as `GET /api/v1/access/suggest` (`since`, `profile`, `token`, `patch`) and as the `suggest` operation of the `profiles` MCP tool.

## `mcpproxy token`

- `token create --profile <p>` pins the token to a profile; its scope comes from the profile. `--servers`/`--permissions` are optional with `--profile`; without it at least one is required (a legacy scope, which prints a hint to prefer a profile). `--profile-pin` still works as a hidden alias and prints a deprecation notice. Names starting with `client-` are reserved for client credentials.
Expand Down
Loading
Loading