Skip to content

fix(gateway): inject agent key in MCP bridge so session tools resolve identity - #1197

Merged
mrgoonie merged 1 commit into
nextlevelbuilder:devfrom
zezaeoh:fix/bridge-agent-key
Jun 15, 2026
Merged

mrgoonie merged 1 commit into
nextlevelbuilder:devfrom
zezaeoh:fix/bridge-agent-key

Conversation

@zezaeoh

@zezaeoh zezaeoh commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Builtin session tools (sessions_list, sessions_history, sessions_send, session_status) always fail with "agent context required" when invoked through the MCP bridge (e.g. by a claude-cli provider agent). They are enabled and callable, but unusable over /mcp/bridge.

Root cause

bridgeContextMiddleware (internal/gateway/server.go) injects the agent UUID via store.WithAgentID(ctx, id) but never the agent key. The session tools resolve the caller via tools.ToolAgentKeyFromCtx(ctx) — the agent key, because session keys are namespaced by key (agent:<key>:...), not UUID — and over the bridge there is no RunContext fallback, so it returns "" and every tool short-circuits:

agentKey := ToolAgentKeyFromCtx(ctx)
if agentKey == "" {
    return ErrorResult("agent context required")
}

Fix

The middleware already fetches the agent (ag) in the same block to apply shell-deny-group overrides. Inject the key right there, symmetric with the existing store.WithShellDenyGroups(ctx, groups):

if err == nil && ag != nil {
    ctx = tools.WithToolAgentKey(ctx, ag.AgentKey)
    groups := ag.ParseShellDenyGroups()
    ...
}

No extra DB round-trip (reuses the existing GetByIDUnscoped), no new imports (tools is already used here for WithToolChannel / WithToolChatID).

Scope vs #1094

Correction (was inaccurate in the original description): #1094 does touch this same bridgeContextMiddleware block — it adds ctx = tools.WithToolAgentKey(ctx, ag.AgentKey) at the same GetByIDUnscoped site. So the server-path fix overlaps; my earlier claim that it "does not touch this path" was wrong. Thanks to the reviewer for catching it.

This PR is the minimal, isolated extraction of exactly that slice, intended as the deliberate successor for it:

  • fix(acp): propagate agent_key through MCP bridge so tools resolve identity #1094 is a 70+ file, ~7.3k-line PR bundling an ACP/Gemini provider refactor, a full Korean i18n catalog, and BuiltinToolStore plumbing. It is currently CONFLICTING against dev and last updated 2026-05-04 (stale), so the load-bearing 5-line bridge fix is blocked behind unrelated work that is unlikely to land soon.
  • This PR changes only internal/gateway/server.go (+5) plus a regression test, so it can merge independently and immediately unblock session tools over /mcp/bridge.
  • It also intentionally omits fix(acp): propagate agent_key through MCP bridge so tools resolve identity #1094's companion store.WithAgentKey(ctx, ag.AgentKey) write: nothing on dev reads the store-level key (store.AgentKeyFromCtx has no callers), while every session tool reads tools.ToolAgentKeyFromCtx. Keeping the change to exactly what is load-bearing.

I can't edit/close #1094 (different author). Suggested resolution: land this minimal PR, and drop the internal/gateway/server.go slice from #1094 when it rebases — the rest of #1094 is independent.

Testing

  • New regression test internal/gateway/bridge_context_test.go exercises the bridge propagation that regressed here: a signed X-Agent-ID + a stub AgentStore returning an AgentKey, asserting the downstream handler sees tools.ToolAgentKeyFromCtx(ctx) populated, plus a negative control (no store → empty key). Mutation-checked: removing the fix line makes TestBridgeContextMiddleware_InjectsAgentKey fail with ToolAgentKeyFromCtx = "".
  • Existing tool tests already cover both states: TestSessionStatus_EmptyAgentID_Error (no key → "agent context required") and the positive cases via the agentCtx() helper. This PR makes the bridge actually supply the key those tools expect.
  • Verified in production (v3.13.2 + this patch): sessions_list / sessions_history now return the agent's sessions over the bridge instead of erroring.

@zezaeoh
zezaeoh changed the base branch from main to dev June 9, 2026 06:23

@mrgoonie mrgoonie 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.

Summary

This PR fixes the MCP bridge session-tool identity path by loading the agent row that bridgeContextMiddleware already fetches and injecting ag.AgentKey into the tool context. The code change itself matches the session tools' current contract: those tools fail closed on empty tools.ToolAgentKeyFromCtx(ctx), while bridge requests currently only inject the agent UUID.

Risk level: Medium. The code delta is low risk, but the PR materially overlaps an existing open PR and the overlap needs maintainer coordination before merge.

Mandatory gates

  • Duplicate / prior implementation: overlap found. #1094 already patches internal/gateway/server.go in the same bridgeContextMiddleware block and injects tools.WithToolAgentKey(ctx, ag.AgentKey) there.
  • Project standards: docs found. Checked README.md, CLAUDE.md, AGENTS.md, and current code patterns.
  • Strategic necessity: clear value. This unblocks session tools over /mcp/bridge for provider agents using signed bridge headers.

Findings

Important

  1. Resolve the material overlap with #1094 before merge. This PR says #1094 does not touch the bridgeContextMiddleware path, but the current #1094 diff does: it adds agent-key recovery in internal/gateway/server.go around the same GetByIDUnscoped lookup, including ctx = tools.WithToolAgentKey(ctx, ag.AgentKey). That makes the PR rationale inaccurate and leaves two open PRs carrying the same server-path fix. Please either mark this PR as the deliberate minimal successor for that slice and retarget/close the overlapping portion of #1094, or rebase/merge the intended implementation into one PR.

Suggestions

  • Add a narrow regression test for bridgeContextMiddleware: signed X-Agent-ID, fake AgentStore returning AgentKey, and a handler assertion that tools.ToolAgentKeyFromCtx(ctx) is populated. Existing session-tool tests cover the tool behavior, but not the bridge propagation that regressed here.
  • Before merge or squash, remove the AI co-author trailer from the commit metadata to align with the repo's no-AI-reference commit guidance.

Verdict: Request changes.

Posted by /ck:review-pr at 2026-06-15T03:50:40Z

… identity

bridgeContextMiddleware injects the agent UUID (store.WithAgentID) but never the
agent key, so session tools (sessions_list/history/send/status) that resolve the
caller via tools.ToolAgentKeyFromCtx always get "" and fail with "agent context
required" when invoked over /mcp/bridge (e.g. by a claude-cli provider agent).
Session keys are namespaced by agent key (agent:<key>:...), not UUID, and the
bridge has no RunContext fallback.

Inject the key in the same block that already fetches the agent for shell-deny
overrides — symmetric with store.WithShellDenyGroups, no extra DB call, no new
imports.

nextlevelbuilder#1094 makes the same fix at this site but bundles it into a large, stale
(CONFLICTING) ACP/i18n refactor; this is the minimal extraction of that slice.
It omits nextlevelbuilder#1094's companion store.WithAgentKey write, which nothing on dev reads
(every session tool reads tools.ToolAgentKeyFromCtx).

Add internal/gateway/bridge_context_test.go: a regression guard asserting a
signed X-Agent-ID lands the agent key in tools.ToolAgentKeyFromCtx, plus a
no-store negative control.

Signed-off-by: Jaegeon Oh <zezaeoh@gmail.com>
@zezaeoh
zezaeoh force-pushed the fix/bridge-agent-key branch from 0b51f7f to 36c88fd Compare June 15, 2026 04:18
@zezaeoh

zezaeoh commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review — all three points addressed. Pushed 36c88fd.

Important — overlap with #1094: You're right, and my original description was wrong. #1094 does patch this same bridgeContextMiddleware site with tools.WithToolAgentKey(ctx, ag.AgentKey); it's not only the ACP path. I've corrected the PR description to own that and reframed this PR as the deliberate minimal extraction of that slice, for two reasons:

I can't retarget/close #1094 (different author). Suggested resolution: land this minimal PR and drop the internal/gateway/server.go slice from #1094 when it rebases — the rest of it is independent.

Suggestion — regression test: Added internal/gateway/bridge_context_test.go. It drives bridgeContextMiddleware with a signed X-Agent-ID and a stub AgentStore returning an AgentKey, and asserts the downstream handler sees tools.ToolAgentKeyFromCtx(ctx) populated, plus a no-store negative control. Mutation-checked: reverting the fix line makes it fail with ToolAgentKeyFromCtx = "".

Suggestion — commit trailer: Removed the AI co-author trailer; Signed-off-by (DCO) retained.

@zezaeoh
zezaeoh requested a review from mrgoonie June 15, 2026 04:27

@mrgoonie mrgoonie 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.

Summary

This PR fixes the MCP bridge identity path by reusing the already-loaded agent row in and injecting into the tool context. The new regression test covers the signed bridge path and the no-store negative control.

Risk level: Medium. The code delta is narrow, but it touches the signed bridge identity context used by session tools. I did not find a correctness or security blocker.

Mandatory gates

  • Duplicate / prior implementation: overlap found, acceptable. already contains the same server-path slice, but this PR now correctly documents itself as the minimal successor/extraction from that stale, broad PR.
  • Project standards: docs found. Checked , , , and current bridge/session-tool patterns.
  • Strategic necessity: clear value. This unblocks , , , and over for provider agents that currently only propagate the agent UUID.

Findings

No critical or important findings remain.

Verification

  • Reviewed the full PR diff: and .
  • Confirmed session tools fail closed on empty and use agent keys, not UUIDs, for session ownership checks.
  • Confirmed the Claude MCP bridge signs the same context fields used by the new test.
  • Ran on PR head : -> passed.
  • GitHub reports no PR checks for this branch, so the approval relies on the targeted local test plus diff review.

Verdict: Approve.

Posted by /ck:review-pr at 2026-06-15T07:17:44Z

@mrgoonie mrgoonie 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.

Correction

The previous approval review submitted successfully, but shell expansion stripped the inline-code tokens from its body. Approval verdict stands; corrected review text below.

Summary

This PR fixes the MCP bridge identity path by reusing the already-loaded agent row in bridgeContextMiddleware and injecting ag.AgentKey into the tool context. The new regression test covers the signed X-Agent-ID bridge path and the no-store negative control.

Risk level: Medium. The code delta is narrow, but it touches the signed bridge identity context used by session tools. I did not find a correctness or security blocker.

Mandatory gates

  • Duplicate / prior implementation: overlap found, acceptable. #1094 already contains the same server-path slice, but this PR now correctly documents itself as the minimal successor/extraction from that stale, broad PR.
  • Project standards: docs found. Checked README.md, CLAUDE.md, AGENTS.md, and current bridge/session-tool patterns.
  • Strategic necessity: clear value. This unblocks sessions_list, sessions_history, sessions_send, and session_status over /mcp/bridge for provider agents that currently only propagate the agent UUID.

Findings

No critical or important findings remain.

Verification

  • Reviewed the full PR diff: internal/gateway/server.go and internal/gateway/bridge_context_test.go.
  • Confirmed session tools fail closed on empty tools.ToolAgentKeyFromCtx(ctx) and use agent keys, not UUIDs, for session ownership checks.
  • Confirmed the Claude MCP bridge signs the same context fields used by the new test.
  • Ran on PR head 36c88fdd6e4cd78d3f75c9c597381e31800759ba: go test ./internal/gateway -run TestBridgeContextMiddleware -count=1 -> passed.
  • GitHub reports no PR checks for this branch, so the approval relies on the targeted local test plus diff review.

Verdict: Approve.

Posted by /ck:review-pr at 2026-06-15T07:18:03Z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready to ship Reviewed and ready to merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants