Skip to content

fix(tools): pass agent context window and max_tokens to media tools via the claude_cli bridge and /v1/tools/invoke (#1649) - #1650

Merged
clark-cant merged 4 commits into
nextlevelbuilder:devfrom
RyoKusnadi:fix/bridge-agent-budget-context
Nov 6, 2026
Merged

clark-cant merged 4 commits into
nextlevelbuilder:devfrom
RyoKusnadi:fix/bridge-agent-budget-context

Conversation

@RyoKusnadi

@RyoKusnadi RyoKusnadi commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Media tools (read_image, read_audio, read_video) now work for claude_cli agents (through the MCP bridge) and when called directly through POST /v1/tools/invoke. They failed on every call with agent budget wiring error: missing agent_context_window,agent_max_tokens.

How it happens: a claude_cli agent calls a media tool through /mcp/bridge, or an operator calls POST /v1/tools/invoke {"tool":"read_image"}. Neither path puts the agent's context window or max_tokens into the tool context. agentBudgetFromContext (internal/tools/usage_caps.go:53) reads them, and GuardContextWindowWithMediaTokens (internal/usage/caps/context_guard.go) returns AgentBudgetWiringError when either is 0. The in-process loop sets both (internal/agent/loop_context.go:68-69), which is why native providers work.

Cause: bridgeContextMiddleware (internal/gateway/server.go) and ToolsInvokeHandler.ServeHTTP (internal/http/tools_invoke.go) inject the agent ID (and, on the bridge, key, policy and shell deny groups), but not the budget.

Fix: in both places, start from config.DefaultContextWindow / config.DefaultMaxTokens before the agent id is parsed or looked up, overwrite from the agent row when it has values above 0, and slog.Warn when the row cannot be read. This mirrors internal/consolidation/agent_budget.go. The guard itself is unchanged.

Behavior change: subagents spawned from a bridge call now get the calling agent's context window (subagent_spawn.go:321) instead of the default, because that value used to arrive as 0.

Behavior change on /v1/tools/invoke: a request that resolves no agent now runs media tools with the default budget instead of failing with the wiring error. The endpoint is operator-gated, and the guard bounds a request but does not authenticate it.

Scope: the same defaulting also exists in resolver.go, loop_types.go, consolidation/agent_budget.go and http/agents*.go. I did not merge these into one shared helper here, to keep the diff small. A CHANGELOG entry is added.

Type

  • Bug fix

Target Branch

dev

Checklist

  • go build ./... passes (ran go build -tags sqliteonly ./internal/gateway ./internal/http only)
  • go vet ./... passes (ran on ./internal/gateway ./internal/http)
  • Tests pass: go test -race ./... (ran go test ./internal/gateway ./internal/http, without -race)
  • No hardcoded secrets or credentials
  • SQL queries use parameterized $1, $2 (no SQL changes)

Test Plan

  • TestBridgeContextMiddleware_InjectsAgentBudget (internal/gateway/bridge_context_test.go): explicit values, unset columns, a missing agent row, a lookup error (sql.ErrNoRows, the warn branch), and a non-UUID agent id.
  • TestToolsInvoke_InjectsAgentBudget (internal/http/tools_invoke_budget_test.go): explicit values, unset columns, and a failed lookup. It posts to the real handler with a probe tool that reads the budget from its context.
  • Before the fix (handler change reverted): context window = 0, want 120000, max tokens = 0, want 4096 (explicit), and 0, want 200000 / 0, want 8192 for the other two cases.
  • After: go test ./internal/gateway ./internal/http passes.
  • Commands: go vet and go test on those two packages.
  • Not run: full suite, -race, integration tests, a live claude_cli agent.

Fixes #1649

…_cli bridge (#1649)

Media tools (read_image/read_audio/read_video) refuse to run without the agent budget in context. The bridge middleware set the agent key and tool policy but not the budget, so every call from a claude_cli agent failed with an agent budget wiring error. Set both values from the agent row, using the loop's defaults when the columns are unset.

Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>

@clark-cant clark-cant left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — fix(mcp): pass agent context window and max_tokens through the claude_cli bridge (#1649)

Summary: bridgeContextMiddleware now sets agent_context_window and agent_max_tokens on the tool context from the agent row, with the loop's own fallbacks when the columns are unset. That closes the AgentBudgetWiringError that made read_image / read_audio / read_video fail for every claude_cli agent.

Risk level: Low. 13 lines in one middleware, one test, no auth/HMAC change, no schema, no contract.

Verdict: approve on the code.

Mandatory gates

  • Duplicate / prior implementation: clear. agent_context_window search returns only #1649 and this PR. The pattern is the established one: #1197 (agent key), #1094, #512, #799 all inject into the same middleware and all merged. Open PR #1105 touches bridgeContextMiddleware too, but for sender/role, and has been DIRTY since 2026-06-26 — no semantic overlap.
  • Project standards: AGENTS.md present. Go conventions followed (errors untouched, no ignored returns, no new imports needed — config was already imported at server.go:21).
  • Strategic necessity: clear value. This is the reported bug for a whole provider class, and it is a 13-line fix.

Verified at 5662d581 (worktree, no edits)

  • gofmt -l on both changed files: empty.
  • go build ./internal/gateway and go build -tags sqliteonly ./internal/gateway: clean. go vet on both tag variants: clean. go test ./internal/gateway: ok.
  • Red/green on the new test: checking server.go back to 5662d581^ makes TestBridgeContextMiddleware_InjectsAgentBudget fail with context window = 0, want 120000 / max tokens = 0, want 4096 and 0, want 200000 / 0, want 8192; restoring the head makes it pass. The test pins exactly the pre-fix state, so it is not phantom coverage.
  • The defaulting is a true mirror of the loop: resolver.go:243-246 computes contextWindow the same way, loop_types.go:477-483 (effectiveMaxTokens) returns config.DefaultMaxTokens at 0, and loop_context.go:67-69 injects that same pair. Bridge tools therefore see the same budget the in-process tools see — which is the property that matters, since the guard is shared (usage_caps.go:54 → context_guard.go:62-72).
  • No regression for paths that used to run: every consumer of these two keys hard-fails with AgentBudgetWiringError when either is 0 (context_guard.go:65-72), and clampToolRequestMaxTokens lives after that guard, so nothing that previously succeeded can now be clamped by the newly non-zero max_tokens.
  • store.WithAgentContextWindow / WithAgentMaxTokens already ignore values <= 0 (store/context.go:151-186), so the guards here are belt-and-braces rather than load-bearing.

Findings

Important — the second affected surface is still broken, and Fixes #1649 would close the issue over it.
/v1/tools/invoke has the identical gap: tools_invoke.go:98-104 loads the agent row and injects only store.WithAgentID, so POST /v1/tools/invoke {"tool":"read_image"} still returns agent budget wiring error: missing agent_context_window,agent_max_tokens. AGENTS.md → "Cross-Surface Feature/Fix Parity" requires auditing every affected surface before a fix is marked complete, and the PR body already names this one. The body's honesty is appreciated, but the close keyword is the problem: once this merges, #1649 reads as fixed while an operator-visible path keeps the exact symptom in the title. Either extend this PR (the row is already in hand at tools_invoke.go:100, so it is the same six lines) or switch to Refs #1649 and file the follow-up now. I would extend it — the second call site is cheaper to fix than to remember.

Suggestion — default before the lookup, and log a failed lookup.
The budget injection sits inside if err == nil && ag != nil (server.go:443-444), so a store error or a nil row leaves both keys unset and the media tool fails with the wiring error again, with nothing in the log to distinguish it from the pre-fix behavior. internal/consolidation/agent_budget.go:17-40 already codifies the project's answer to this exact question: start at config.DefaultContextWindow / DefaultMaxTokens, slog.Warn when the row cannot be read, then overwrite from the row when it can. Moving the two initializations above the lookup and adding the warn would make the bridge match that precedent — worth it for the diagnostics even if the call is already degraded by the missing row.

Suggestion — the same defaulting now exists in six places.
resolver.go:243-246, loop_types.go:505, consolidation/agent_budget.go:25-26, http/agents.go:313, http/agents_import_agent.go:157, and now server.go:462-469. The body preempts this ("kept inline here to keep the diff small") and that is a defensible call for this PR. Recording it anyway because the next call site is the tools_invoke fix above, and internal/store already imports config (store/agent_store.go:10), so AgentData.EffectiveContextWindow() / EffectiveMaxTokens() costs no new dependency and gives every future call site one thing to call instead of a seventh copy. Not a request to change this diff.

Suggestion — two notes for the body/changelog.
Bridge-spawned subagents now inherit the calling agent's window: subagent_spawn.go:321 reads store.AgentContextWindowFromContext into OriginContextWindow, which previously arrived as 0 and fell through to NewLoop's config.DefaultContextWindow (loop_types.go:505). That is the correct direction, but it is a behavior change beyond the media tools and is worth one line in the PR body so it is not discovered later. A CHANGELOG.md entry would also match the repo's fix cadence (d70ef203 is a recent example), though nothing in AGENTS.md makes it mandatory.

CI / merge state

Zero check runs on 5662d581. CI run 41699471055 is completed / action_required, created 2026-11-03T19:02:18Z — the first-time-contributor workflow gate, same as every other external PR here. mergeable: true, mergeable_state: unstable, base dev at 22e71c80, so nothing to rebase.

No formal approval and no merge from me: approving another author's workflow run is a maintainer call, and the head carries no checks to review. Once a maintainer approves the run and CI is green, this is a merge-on-green PR barring the tools_invoke decision above.

…ge (#1649)

Start from the default context window and max tokens, overwrite from the agent row, and warn when the row cannot be read. /v1/tools/invoke now injects the budget too.

Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
@RyoKusnadi RyoKusnadi changed the title fix(mcp): pass agent context window and max_tokens through the claude_cli bridge (#1649) fix(tools): pass agent context window and max_tokens to media tools via the claude_cli bridge and /v1/tools/invoke (#1649) Nov 3, 2026
@RyoKusnadi

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, @clark-cant. I pushed 86c8b98 with these changes:

  • /v1/tools/invoke: fixed in this PR. It now injects the context window and max tokens the same way as the bridge. I added TestToolsInvoke_InjectsAgentBudget, which posts to the real handler. It fails before the change (context window = 0, want 120000) and passes after.
  • Defaults and warn: in both places the defaults are now set before the agent lookup. The agent row overwrites them when it has values, and a failed lookup logs a slog.Warn, as in consolidation/agent_budget.go. I added a "missing row" case to the bridge test. I left the other four copies alone, as you said.
  • Subagents: the PR body now has a line saying bridge-spawned subagents get the calling agent's context window (subagent_spawn.go:321) instead of the default.
  • Changelog: added an entry under Fixed.

I also updated the title and description to cover both surfaces.

@clark-cant clark-cant left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — fix(tools): pass agent context window and max_tokens to media tools via the claude_cli bridge and /v1/tools/invoke (#1649)

Summary: 86c8b986 closes the parity finding from the 19:09Z review. /v1/tools/invoke now injects the agent budget too, both surfaces start from config.DefaultContextWindow / DefaultMaxTokens before the row lookup, and a failed lookup logs a warning. The delta also adds TestToolsInvoke_InjectsAgentBudget, the subagent-inheritance note in the body, and a CHANGELOG entry.

Risk level: Low. 5 files, +168/−0, 2 commits. No auth/HMAC change, no schema, no contract change; the only behavior change is that a path which previously hard-failed now runs with the same defaults the agent loop uses.

Verdict: approve on the code.

Mandatory gates

  • Duplicate / prior implementation: clear. Searches for agent_context_window and tools_invoke return only this PR; no merged or open PR duplicates it. This is the chosen successor to #1649's triage, not a parallel implementation.
  • Project standards: AGENTS.md present. The shape now matches internal/consolidation/agent_budget.go:17-40 exactly (defaults first, warn on lookup failure, overwrite from the row), which is the precedent the previous review asked for.
  • Strategic necessity: clear. This is the user-visible failure in #1649, on both surfaces, fixed in five files.

Verified at 86c8b986 (fresh clone, no edits)

  • gofmt -l on the four changed Go files: empty.
  • go build and go vet on ./internal/gateway ./internal/http: clean; go build -tags sqliteonly on the same two: clean.
  • go test ./internal/gateway ./internal/http -count=1: ok 0.06s / 3.54s.
  • Red/green on the new /v1/tools/invoke test: checking tools_invoke.go back to 5662d58 makes all three cases fail with context window = 0, want 120000 / 200000 and max tokens = 0, want 4096 / 8192; the head passes. Real coverage.
  • Red/green on the new bridge case: checking server.go back to 5662d58 makes missing_row_falls_back_to_defaults fail with 0, want 200000 / 0, want 8192, confirming the default-before-lookup path is what the test pins.
  • Merge state: MERGEABLE / UNSTABLE, base dev at 22e71c80, 2 commits, 5 files, +168/−0.

Findings

No Critical, no Important.

Suggestion — the warn branch has no test. stubAgentKeyStore.GetByIDUnscoped returns (s.ag, nil), so the missing row case exercises ag == nil && err == nil, not the new else if err != nil branch. A stub variant returning sql.ErrNoRows would pin the diagnostic line. Relatedly, the CHANGELOG says "log a warning when the row cannot be read" — for the bridge that holds only on an error, because a nil row with a nil error is silent.

Suggestion — the no-agent path is now fail-open by design. tools_invoke.go sets the defaults before agentIDStr is resolved, so a request that resolves no agent at all now runs media tools at 200000/8192 where it previously failed with the wiring error. That is the intended trade (the guard bounds a request; it does not authenticate it) and the endpoint is operator-gated, but it is a behavior change worth one line in the body rather than only in the diff.

Suggestion — default injection is scoped differently on the two surfaces. tools_invoke sets it unconditionally; the bridge sets it only after uuid.Parse(agentIDStr) succeeds, so a bridge call whose signed agent id is not a UUID still returns the original wiring error. One placement rule would remove the asymmetry.

Note — the if ag.ContextWindow > 0 guards duplicate what store.WithAgentContextWindow already enforces (store/context.go:151,167 ignore <= 0). Harmless and self-documenting; no action.

CI / merge state

Zero check runs on 86c8b986. CI run 41702631834 is completed / action_required, created 2026-11-03T19:22:17Z — the first-time-contributor workflow gate. 0 approvals repo-wide, reviewDecision empty, mergeStateStatus: UNSTABLE. No merge from me: approving another author's workflow and merging remain maintainer calls.

Posted by /ck:review-pr at 2026-11-03T22:08Z

…se (#1649)

Set the default context window and max tokens before parsing the signed
agent id, so the bridge follows the same rule as /v1/tools/invoke. Add
bridge cases for a failed lookup and a non-UUID agent id, and say in the
CHANGELOG that the warning is logged on a lookup error.

Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
@RyoKusnadi

Copy link
Copy Markdown
Contributor Author

Thanks @clark-cant for the careful review and for re-running the red/green checks. All three suggestions are done in fda4771: a bridge test case where the agent lookup returns sql.ErrNoRows (defaults still apply), the CHANGELOG now says the warning is logged when the lookup returns an error, the default budget is now set before the agent id is parsed on the bridge (with a non-UUID test case), and the /v1/tools/invoke behavior change is spelled out in the PR body.

@clark-cant clark-cant left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at fda47715 (delta vs 86c8b98: 3 files, +26/−11, one commit). Verdict: approve on the code.

All three suggestions from my 22:08Z review are addressed, and the non-UUID agent id case is the one that actually mattered — it was the last behavioural difference between the two surfaces:

  • Defaults are now set before the agent-id parse (internal/gateway/server.go:436-440), so a signed bridge request with a malformed id gets the default budget instead of reaching the media tools with 0, matching /v1/tools/invoke:99-100.
  • stubAgentKeyStore gained an err field, and the lookup-error path is now covered.
  • The CHANGELOG sentence now says "when the agent lookup returns an error", which is what the code does.

Verification at the head (fresh checkout of refs/pull/1650/head):

  • gofmt -l on both changed Go files: empty.
  • go build + go vet clean on ./internal/gateway ./internal/http, default and -tags sqliteonly.
  • go test ./internal/gateway ./internal/http -count=1: ok (0.14s / 4.99s).
  • Red/green on the new case: reverting server.go to 86c8b98 fails non-UUID agent id keeps defaults with context window = 0, want 200000 / max tokens = 0, want 8192; the head passes. Note the lookup error case passes on the parent too (defaults were already set inside the uuid branch there), so it pins the warn-and-default contract rather than a new behaviour — fine to keep, just don't read it as the regression test for this commit.

Two non-blocking notes, no action needed for this PR:

  1. The slog.Warn only fires when agentStore != nil; with a nil store the defaults apply silently. Same shape as /v1/tools/invoke, so parity holds — just worth knowing the silent path exists on both.
  2. The surfaces still resolve the agent differently (GetByIDUnscoped with a UUID here, GetByKey with a key there). That is inherent to what each caller has, not something this PR should change.

Not approving formally and not merging: check-runs for fda47715 still return total_count 0, CI run 41729441134 is completed / action_required (created 2026-11-03T22:17:10Z) under the first-time-contributor workflow gate, and the repo has zero approved PRs. Once a maintainer approves the workflow run and it goes green, this is mergeable as-is.

@RyoKusnadi

Copy link
Copy Markdown
Contributor Author

@clark-cant thanks for the approval. Is anything else needed before this can be merged?

@clark-cant

Copy link
Copy Markdown
Contributor

Thanks for checking in. To be precise about the state, since "approval" is doing two jobs here:

  • Informal code approval: yes — three reviews at 5662d581, 86c8b986 and fda47715 all ended "approve on the code", with no Critical or Important findings left.
  • Formal GitHub approval: no. reviewDecision is still empty and the repo currently has zero approved PRs, so the merge gate is not met.

Nothing else is needed from you. What remains is a maintainer action on the two gates this account cannot clear:

  1. Workflow approval. Check-runs for fda47715 still return total_count 0; CI run 41729441134 sits at completed / action_required from 2026-11-03T22:17:10Z (the first-time-contributor gate). Until a maintainer approves that run, no CI result exists to gate the merge on.
  2. One formal approval, then merge.

Branch state is MERGEABLE / UNSTABLE, base dev, so there is nothing to rebase while you wait. If the run does get approved and CI comes back red, ping here and I will take the failure.

@clark-cant clark-cant added the pr:reviewed Reviewed by maintainer label Nov 5, 2026
@clark-cant

Copy link
Copy Markdown
Contributor

Conflict, not a code problem — one CHANGELOG.md rebase needed

Heads-up: the branch went from MERGEABLE (last checked 16:03Z) to CONFLICTING shortly after 22:17Z yesterday. The cause is ours, not yours: PR #1648 merged into dev as 8a5a10b0, and both PRs insert their ### Fixed entry at the top of the same Unreleased block, so git has no ordering rule to pick.

Verified with git merge-tree --write-tree origin/dev pr1650-review on a fresh fetch: exactly one conflicted path, CHANGELOG.md. Every Go file auto-merges — no code rebase, no logic change needed, and the three reviews still stand at the same diff.

Resolution: after ### Fixed, keep all three entries in any order —

  1. **Anthropic model picker lists every model, not only the first 20** (from fix(providers): paginate the Anthropic models list #1648)
  2. **Queued agent runs no longer inherit the context of the session's first request (#1662)** (from fix(scheduler): run queued requests with their own context (#1662) #1661)
  3. your **Media tools work again for claude_cli agents and /v1/tools/invoke (#1649)** block, unchanged

Then git fetch origin && git merge origin/dev (or rebase onto origin/dev) and push.

Why I am asking instead of doing it: the automation's token has read-only access to your fork, so it cannot push the resolution to fix/bridge-agent-budget-context.

Nothing else is outstanding on the code side — 5662d58, 86c8b98 and fda4771 all approve the diff with zero Critical and zero Important, and the last suggestion was addressed. What remains after the push is process-only: the first-time-contributor workflow run (41729441134, action_required since 2026-11-03T22:17:10Z) has to be approved, then one formal approval. Ping here when the branch is updated.

@RyoKusnadi

Copy link
Copy Markdown
Contributor Author

Merged dev in and kept all three CHANGELOG entries. Build and the gateway and http tests pass.

@clark-cant clark-cant left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at fec996e0 (delta vs fda47715: one merge commit, parents fda47715 + 8a5a10b0). Verdict: approve.

The only content change is the CHANGELOG.md conflict resolution; the PR's own four files are byte-identical to the head I reviewed at 2026-11-04T01:06Z (git diff fda47715 pr1650-new -- internal is empty).

Verified on pr1650-new in a clean worktree:

  • git diff origin/dev...fec996e0 is still 5 files, +180/−2 — the dev sync added the 1648/1661 code without touching this PR's diff beyond the changelog entry.
  • CHANGELOG.md resolution is ours-not-theirs and additive: 10 lines, 0 deletions, a single ### Fixed bullet placed after the 1661 "Queued agent runs" entry and before 1627. Nothing from dev was dropped, no conflict markers anywhere.
  • gofmt -l on the four changed Go files: empty.
  • go build ./internal/gateway ./internal/http and go vet on the same two: clean.
  • go test ./internal/gateway ./internal/http -count=1: ok (0.07s / 4.32s).

CI on fec996e0: run 42146256236 — web pass (56s), release-versioning pass (6s), go still in progress. The workflow gate is cleared on this head, so this is now merge-on-green. Approving, and merging as soon as go reports.

@clark-cant
clark-cant merged commit ed0db5d into nextlevelbuilder:dev Nov 6, 2026
7 of 9 checks passed
@clark-cant clark-cant added area:mcp Model Context Protocol bridge/server pr:approved-by-maintain Approved by github-maintain automation pr:merge-ready Ready to merge — all gates passed pr:merged-by-maintain PR merged by github-maintain automation labels Nov 6, 2026
@RyoKusnadi
RyoKusnadi deleted the fix/bridge-agent-budget-context branch November 6, 2026 15:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:mcp Model Context Protocol bridge/server pr:approved-by-maintain Approved by github-maintain automation pr:merge-ready Ready to merge — all gates passed pr:merged-by-maintain PR merged by github-maintain automation pr:reviewed Reviewed by maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

claude_cli agents: media tools fail with 'agent budget wiring error' (bridge calls lack agent_context_window/agent_max_tokens)

2 participants