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

### Features

- **profiles: per-profile `tool_response_limit` (#2027).** A profile can replace the global response limit for calls served under it: `profiles[].tool_response_limit`, where `0` means no limit and unset inherits. A script that parses whole results gets its own profile and receives text blocks and `structuredContent` whole, while chats keep the default bound. Set it in the config file, with `mcpproxy profile create|update --tool-response-limit <n|inherit>`, over REST and the MCP `profiles` tool, or in the Web UI and macOS profile editors. See [Response limit per profile](https://docs.mcpproxy.app/features/profiles#response-limit-per-profile).
- **agent tokens: per-token call rate limit (#1699).** Cap how many upstream tool calls one agent token may make per minute, so a runaway agent loop cannot burn through an upstream's quota. Off by default. `agent_token_rate_limit` (`per_minute`, optional `burst`) sets a default for every agent token and is live-reloadable; `mcpproxy token create --rate-limit N [--rate-burst M]` (or `rate_limit` on `POST /api/v1/tokens`) gives one token its own budget, and `--rate-limit 0` exempts it. It is enforced where the concurrency limits are, so it covers `call_tool_*`, direct routing mode, `code_execution` and the REST tool-call endpoint, and never applies to the admin API key or unauthenticated local callers. A refused call never reaches the upstream: MCP callers get an error result, REST callers get `429` with `Retry-After`, the activity log records a `tool_call` with status `rejected`, reason `rate_limited` and the token's name, and `mcpproxy_tool_calls_rejected_total` counts it with `reason="rate_limited"`, `scope="token"`. The audit-line `reason` vocabulary gains `rate_limited`. Buckets are in memory, so a restart refills them.
- **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
Expand Down
1 change: 1 addition & 0 deletions cmd/generate-types/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1045,6 +1045,7 @@ export interface ProfileView {
code_execution?: boolean;
management_tools?: boolean;
switchable_to?: string[];
tool_response_limit?: number;
effective_servers: string[];
effective_unannotated: string;
effective_code_execution: boolean;
Expand Down
14 changes: 13 additions & 1 deletion cmd/mcpproxy/profile_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ func renderProfileBlock(v runtime.ProfileView) string {
fmt.Fprintf(&b, "Unannotated: %s\n", unannotatedLabel(v))
fmt.Fprintf(&b, "Code execution: %s\n", codeExecutionLabel(v))
fmt.Fprintf(&b, "Management tools: %s\n", managementToolsLabel(v))
fmt.Fprintf(&b, "Tool response limit: %s\n", responseLimitLabel(v))
switch {
case v.SwitchableTo == nil:
b.WriteString("Switchable to: unset (legacy)\n")
Expand Down Expand Up @@ -401,6 +402,17 @@ func managementToolsLabel(v runtime.ProfileView) string {
return "inherited"
}

func responseLimitLabel(v runtime.ProfileView) string {
switch {
case v.ToolResponseLimit == nil:
return "inherited"
case *v.ToolResponseLimit == 0:
return "none (whole responses)"
default:
return fmt.Sprintf("%d characters", *v.ToolResponseLimit)
}
}

// --- create / update ---------------------------------------------------------

func newProfileCreateCmd() *cobra.Command {
Expand Down Expand Up @@ -687,7 +699,7 @@ exist yet) with --set overrides applied; nothing is persisted.

--set keys are the REST field names: servers, title, description, max_tier,
unannotated, tools.allow, tools.deny, tools.classify.<server:tool>,
code_execution, management_tools, switchable_to. Lists are comma-separated;
code_execution, management_tools, switchable_to, tool_response_limit. Lists are comma-separated;
code_execution=inherit clears the field.

Examples:
Expand Down
89 changes: 89 additions & 0 deletions cmd/mcpproxy/profile_cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -566,3 +566,92 @@ func TestProfileShow_EffectiveNonAdminRowsArePolicyOnly(t *testing.T) {
require.NotContains(t, out, "callable")
require.NotContains(t, out, "tool_approval")
}

// Issue #2027: --tool-response-limit sets a profile's own response limit; 0 is
// an explicit "no limit" and must be sent, inherit omits the field.
func TestProfileCreate_ToolResponseLimit(t *testing.T) {
create := func(args ...string) (map[string]any, error) {
rec := newRESTRecorder(t, map[string]cannedResponse{"POST /api/v1/profiles": createdResp(`{"profile":` + mustJSON(t, fullView()) + `,"warnings":[]}`)})
_, _, err := runCLI(t, GetProfileCommand, "table", append([]string{"create", "script", "--servers", "github"}, args...)...)
if err != nil {
require.Empty(t, rec.all(), "a bad value must be rejected before any request")
return nil, err
}
return rec.only(t).jsonBody(t), nil
}

body, err := create("--tool-response-limit", "0")
require.NoError(t, err)
require.Equal(t, float64(0), body["tool_response_limit"], "0 (no limit) is sent, not dropped")

body, err = create("--tool-response-limit", "500000")
require.NoError(t, err)
require.Equal(t, float64(500000), body["tool_response_limit"])

body, err = create("--tool-response-limit", "inherit")
require.NoError(t, err)
require.NotContains(t, body, "tool_response_limit")

body, err = create()
require.NoError(t, err)
require.NotContains(t, body, "tool_response_limit")

_, err = create("--tool-response-limit", "lots")
require.Error(t, err)
require.Equal(t, ExitCodeGeneralError, classifyError(err))
}

func TestProfileUpdate_ToolResponseLimitKeptAndCleared(t *testing.T) {
stored := readonlyView()
zero := 0
stored.ToolResponseLimit = &zero
update := func(args ...string) map[string]any {
rec := newRESTRecorder(t, map[string]cannedResponse{
"GET /api/v1/profiles/work-ro2": okResp(mustJSON(t, stored)),
"PUT /api/v1/profiles/work-ro2": okResp(`{"profile":` + mustJSON(t, stored) + `,"warnings":[]}`),
})
_, _, err := runCLI(t, GetProfileCommand, "table", append([]string{"update", "work-ro2"}, args...)...)
require.NoError(t, err)
return rec.all()[1].jsonBody(t)
}

require.Equal(t, float64(0), update("--title", "x")["tool_response_limit"], "an unrelated update keeps the stored limit")
require.Equal(t, float64(9000), update("--tool-response-limit", "9000")["tool_response_limit"])
require.NotContains(t, update("--clear-tool-response-limit"), "tool_response_limit")

rec := newRESTRecorder(t, map[string]cannedResponse{})
_, _, err := runCLI(t, GetProfileCommand, "table", "update", "work-ro2", "--tool-response-limit", "5", "--clear-tool-response-limit")
require.Error(t, err)
require.Empty(t, rec.all())
}

func TestProfileShow_ToolResponseLimit(t *testing.T) {
zero, some := 0, 9000
base := runtime.ProfileView{Name: "p", Servers: []string{"github"}, EffectiveServers: []string{"github"}, EffectiveUnannotated: "as_read", EffectiveCodeExecution: true, IsLegacy: true}
unlimited, bounded := base, base
unlimited.ToolResponseLimit, bounded.ToolResponseLimit = &zero, &some
newRESTRecorder(t, map[string]cannedResponse{
"GET /api/v1/profiles/inherit": okResp(mustJSON(t, base)),
"GET /api/v1/profiles/unlimited": okResp(mustJSON(t, unlimited)),
"GET /api/v1/profiles/bounded": okResp(mustJSON(t, bounded)),
})
for name, want := range map[string]string{
"inherit": "Tool response limit: inherited\n",
"unlimited": "Tool response limit: none (whole responses)\n",
"bounded": "Tool response limit: 9000 characters\n",
} {
out, _, err := runCLI(t, GetProfileCommand, "table", "show", name)
require.NoError(t, err)
require.Contains(t, out, want)
}
}

func TestApplyDraftSet_ToolResponseLimit(t *testing.T) {
p := config.ProfileConfig{Name: "p"}
require.NoError(t, applyDraftSet(&p, "tool_response_limit=0"))
require.NotNil(t, p.ToolResponseLimit)
require.Equal(t, 0, *p.ToolResponseLimit)
require.NoError(t, applyDraftSet(&p, "tool_response_limit=inherit"))
require.Nil(t, p.ToolResponseLimit)
require.Error(t, applyDraftSet(&p, "tool_response_limit=x"))
}
38 changes: 36 additions & 2 deletions cmd/mcpproxy/profile_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package main

import (
"sort"
"strconv"
"strings"

"github.com/spf13/cobra"
Expand All @@ -25,6 +26,7 @@ type profileFlags struct {
codeExecution string
managementTools string
switchableTo []string
responseLimit string

// update only
addServers []string
Expand All @@ -39,7 +41,7 @@ type profileFlags struct {
// profileClearFields are the --clear-<field> flags of `profile update`.
var profileClearFields = []string{
"title", "description", "max-tier", "unannotated", "allow", "deny", "classify",
"code-execution", "management-tools", "switchable-to",
"code-execution", "management-tools", "switchable-to", "tool-response-limit",
}

func (f *profileFlags) register(cmd *cobra.Command, update bool) {
Expand All @@ -54,6 +56,7 @@ func (f *profileFlags) register(cmd *cobra.Command, update bool) {
fl.StringVar(&f.codeExecution, "code-execution", "", "Code execution: on, off or inherit (inherit clears the field)")
fl.StringVar(&f.managementTools, "management-tools", "", "Management tools (upstream_servers, quarantine_security): on, off or inherit")
fl.StringSliceVar(&f.switchableTo, "switchable-to", nil, "Comma-separated profiles a session may switch into; an empty value means none")
fl.StringVar(&f.responseLimit, "tool-response-limit", "", "Response limit in characters for calls under the profile, replacing the global tool_response_limit: a number, 0 for no limit, or inherit")
if !update {
return
}
Expand Down Expand Up @@ -86,6 +89,21 @@ func parseTriState(flag, value string) (*bool, error) {
return nil, newFlagValidationError("--%s must be on, off or inherit (got %q)", flag, value)
}

// parseResponseLimit reads a profile tool_response_limit: a whole number of
// characters (0 = no limit) or inherit, which yields nil (the field is
// omitted). The range is left to the one REST validator.
func parseResponseLimit(flag, value string) (*int, error) {
v := strings.ToLower(strings.TrimSpace(value))
if v == "inherit" || v == "" {
return nil, nil
}
n, err := strconv.Atoi(v)
if err != nil {
return nil, newFlagValidationError("--%s must be a number of characters, 0 for no limit, or inherit (got %q)", flag, value)
}
return &n, nil
}

// canonicalUnannotated maps the kebab input aliases to the wire spelling. Any
// other value is passed through for the one REST validator to judge.
func canonicalUnannotated(v string) string {
Expand Down Expand Up @@ -164,6 +182,13 @@ func (f *profileFlags) apply(cmd *cobra.Command, p *config.ProfileConfig, update
list := append([]string{}, f.switchableTo...)
p.SwitchableTo = &list
}
if changed("tool-response-limit") {
v, err := parseResponseLimit("tool-response-limit", f.responseLimit)
if err != nil {
return err
}
p.ToolResponseLimit = v
}
if !update {
normalizeTools(p)
return nil
Expand Down Expand Up @@ -210,6 +235,9 @@ func (f *profileFlags) apply(cmd *cobra.Command, p *config.ProfileConfig, update
if clear("switchable-to") {
p.SwitchableTo = nil
}
if clear("tool-response-limit") {
p.ToolResponseLimit = nil
}
normalizeTools(p)
return nil
}
Expand Down Expand Up @@ -263,7 +291,7 @@ func removeItems(list, remove []string) []string {
var draftFields = []string{
"servers", "title", "description", "max_tier", "unannotated",
"tools.allow", "tools.deny", "tools.classify.<server:tool>",
"code_execution", "management_tools", "switchable_to",
"code_execution", "management_tools", "switchable_to", "tool_response_limit",
}

// applyDraftSet applies one `--set key=value` override to a draft profile. Keys
Expand Down Expand Up @@ -327,6 +355,12 @@ func applyDraftSet(p *config.ProfileConfig, kv string) error {
case key == "switchable_to":
l := list()
p.SwitchableTo = &l
case key == "tool_response_limit":
v, err := parseResponseLimit("set tool_response_limit", value)
if err != nil {
return err
}
p.ToolResponseLimit = v
default:
return newFlagValidationError("unknown draft field %q; valid: %s", key, strings.Join(draftFields, ", "))
}
Expand Down
5 changes: 5 additions & 0 deletions cmd/mcpproxy/testdata/cli108/profile-create-help-json.golden
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@
"description": "Display title (at most 80 characters)",
"type": "string"
},
{
"name": "tool-response-limit",
"description": "Response limit in characters for calls under the profile, replacing the global tool_response_limit: a number, 0 for no limit, or inherit",
"type": "string"
},
{
"name": "unannotated",
"description": "Handling of tools with no tier hint: deny, as_write or as_read (as-write and as-read are accepted)",
Expand Down
2 changes: 1 addition & 1 deletion docs/api/rest-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1658,7 +1658,7 @@ binding_bypassable_without_auth` (personal edition) and writes nothing.
`{profiles: ProfileView[], anonymous_profile?}`. A `ProfileView` has the config
fields as stored (`name`, `title`, `description`, `servers`, `max_tier`,
`unannotated`, `tools {allow, deny, classify}`, `code_execution`,
`management_tools`, `switchable_to`), the derived `effective_servers`,
`management_tools`, `switchable_to`, `tool_response_limit`), the derived `effective_servers`,
`effective_unannotated`, `effective_code_execution`, `is_legacy`,
`tool_counts {read, write, destructive, unannotated_hidden}` (visible tools by
the tier the profile gives them), the deprecated v2 `tool_count`, `calls_24h`,
Expand Down
2 changes: 1 addition & 1 deletion docs/cli/profile-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ With a running daemon the write goes through the daemon (it mints, records and n
|---|---|
| `profile list` | One row per profile: servers, tool counts by tier, who uses it (administrators only), last-24h calls and blocked calls |
| `profile show <name> [--effective] [--client <id>] [--server <s>] [--reason <r>]` | The profile with the effective value of each policy field and its origin (`off (default under max tier read)`, `on (inherited)`). `--effective` lists every tool with its verdict (`callable`, `held`, `hidden`) and reason, and its header keeps *allowed by profile* apart from *callable* and *held* (administrators; `held` is allowed by the profile but a later gate such as tool approval or server state still refuses the call, and the output names `mcpproxy access explain --profile <name> --tool <server:tool>`); a classification that no longer applies is flagged `classification ignored — tool is now annotated` |
| `profile create <name> --servers a,b [--title] [--description] [--max-tier] [--unannotated deny\|as_write\|as_read] [--allow p,...] [--deny p,...] [--code-execution on\|off\|inherit] [--management-tools on\|off\|inherit] [--switchable-to x,y]` | Create a profile. `--switchable-to ''` means "none"; `inherit` leaves a field unset. `as-write` and `as-read` are accepted as aliases and stored as `as_write` and `as_read` |
| `profile create <name> --servers a,b [--title] [--description] [--max-tier] [--unannotated deny\|as_write\|as_read] [--allow p,...] [--deny p,...] [--code-execution on\|off\|inherit] [--management-tools on\|off\|inherit] [--switchable-to x,y] [--tool-response-limit n\|inherit]` | Create a profile. `--switchable-to ''` means "none"; `inherit` leaves a field unset. `--tool-response-limit` gives the profile its own response limit in characters (`0` = no limit). `as-write` and `as-read` are accepted as aliases and stored as `as_write` and `as_read` |
| `profile update <name> [create flags] [--add-server] [--remove-server] [--add-allow] [--remove-allow] [--add-deny] [--remove-deny] [--clear-<field>]` | Read the stored profile, apply the flags (set, then add/remove, then clear) and write it back. Contradicting flags are rejected before any request. REST has no ETag, so a concurrent edit between the read and the write is lost (last writer wins) |
| `profile rename <old> <new>` | Rename and move every client binding and token pin; prints what moved |
| `profile delete <name> [--reassign-to <p>] [--force]` | Exits 1 and prints who uses the profile unless `--reassign-to` moves them or `--force` leaves them dangling (a dangling reference denies everything, never widens). The `anonymous_profile` can only be deleted with `--reassign-to` |
Expand Down
Loading
Loading