Skip to content

fix(mcp): external MCP calls audit the real caller (#20709) - #21134

Merged
mrveiss merged 12 commits into
mainfrom
issue-20709
Nov 8, 2026
Merged

mrveiss merged 12 commits into
mainfrom
issue-20709

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Thinking Path

Closes #20709. External MCP tool calls reached the audit log without the user who made them. MCPExternalBridge.call_tool accepts user_id and audits it on every outcome. However, _call_external_bridge had no user_id parameter and passed only role, so the chat path always audited None. The issue also suspected that dispatch was called without session_id. That is confirmed: the CoT events lost the session.

Single-issue rationale

One defect: the caller's identity is dropped between the chat tool path and the external MCP audit. It is fixed along the single dispatch chain.

What Changed

  • chat_workflow/tool_permission_gate.py: new caller_identity(ctx, session_id). It reads only the server-verified user (VERIFIED_USER_KEY in ctx.context), never tool arguments or a client-supplied user_id.
  • chat_workflow/tool_handler.py (_try_mcp_dispatch): passes **caller_identity(ctx, session_id) to dispatcher.dispatch. The helper lives in the gate module because tool_handler.py is at its size ceiling.
  • services/mcp_dispatch.py: dispatch takes user_id and passes it through _call_bridge and _call_external_bridge to MCPExternalBridge.call_tool.
  • services/mcp_external_bridge.py: a new _audit_tool_call writes user_id=user_id or SYSTEM_ACTOR with details.actor_type set to "user" or "system" on every outcome. A call with no user, such as a background job, is recorded explicitly as the system actor; it can no longer be mistaken for a lost identity. No new audit action.
  • services/mcp_external_bridge.py: the audit is written durable=True (awaited, committed), like the other security-relevant audits (backup, approval gates). session_id now reaches call_tool through dispatch -> _call_bridge -> _call_external_bridge and is recorded on the audit row (session_id field and details.session_id); the CoT events already carried it.
  • chat_workflow/session_role.py, attachment_context.py, manager.py: a resumed graph turn did not go through apply_auth_role, so a checkpoint without the verified key was audited as system. resume_graph now overlays the resumer's verified scope with the same key pairs (stamp_resumer_identity). process_message also dropped auth_scope; it now forwards it.
  • dispatch has no other production caller. standardized_agent.py only reads the tool list, and tools/parallel/executor.py is a different dispatch.

Verification

  • services/mcp_external_identity_20709_test.py (6 tests):
    • the real user_id lands in the audit row;
    • a call with no user records the system actor;
    • a tool-argument user_id is ignored;
    • the chat path forwards only the context user and session.
  • services/mcp_dispatch_external_test.py and tests/unit/chat_workflow/test_auth_role_plumbing.py are updated for the new parameter. The second passes 16/16.
  • Added: durable flag and session_id on the audit row; a resumed turn whose checkpoint lacks the key audits the resumer.
  • Full requested set after the final edit: 2687 passed, 0 failed.

Model Used

Claude (Sonnet for implementation, Opus coordinating).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Resumed conversations now reflect the identity and access scope of the person continuing them.
    • External tool activity records now include verified user and session details, with system attribution when a verified user identity is unavailable.
    • Tool arguments cannot be used to choose the user identity recorded for external tool activity.

@mrveiss mrveiss added this to the M2 - Company OS workflow-ready milestone Nov 8, 2026
@coderabbitai

coderabbitai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 21 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 61ad77e and a3f54d8.

Files ignored due to path filters: 1

  • scripts/python_file_size_known_large.py is excluded by !scripts/python_file_size_known_large.py
Files selected for processing: 11

  • autobot-backend/chat_workflow/attachment_bounds_20195_test.py
  • autobot-backend/chat_workflow/attachment_context.py
  • autobot-backend/chat_workflow/manager.py
  • autobot-backend/chat_workflow/session_role.py
  • autobot-backend/chat_workflow/tool_handler.py
  • autobot-backend/chat_workflow/tool_permission_gate.py
  • autobot-backend/services/mcp_dispatch.py
  • autobot-backend/services/mcp_dispatch_external_test.py
  • autobot-backend/services/mcp_external_bridge.py
  • autobot-backend/services/mcp_external_identity_20709_test.py
  • autobot-backend/tests/unit/chat_workflow/test_auth_role_plumbing.py
Walkthrough

The change carries verified user and session identity through chat processing, graph resumption and MCP dispatch. External MCP audit events now record caller identity and session details, with a system actor used when no user ID is supplied.

Changes: External MCP Identity and Auditing

Layer / File(s) Summary
Verified identity in chat and resumed context
autobot-backend/chat_workflow/session_role.py, autobot-backend/chat_workflow/attachment_context.py, autobot-backend/chat_workflow/manager.py
A shared helper overlays verified company and user identity onto context. Chat processing and graph resumption pass authentication scope so resumed context receives that overlay.
Identity propagation to external tools
autobot-backend/chat_workflow/tool_permission_gate.py, autobot-backend/chat_workflow/tool_handler.py, autobot-backend/services/mcp_dispatch.py
The chat tool path obtains the user ID from verified context and passes it with the session ID through MCP dispatch to external tool calls.
External audit records and validation
autobot-backend/services/mcp_external_bridge.py, autobot-backend/services/mcp_dispatch_external_test.py, autobot-backend/services/mcp_external_identity_20709_test.py, autobot-backend/tests/unit/chat_workflow/test_auth_role_plumbing.py
External call audits record durable actor and session details, using a system actor when no user ID is supplied. Tests cover identity propagation, audit details and resume behaviour.

Severity of issue fixed: Medium

Merge Risk: Moderate · previous review 61ad7

Identity propagation includes fail-closed handling for resumed turns, but an existing resume test now fails. Update that test before merging. Failed audit writes also remain a recovery limitation.

Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix(mcp): external MCP calls audit the real caller (#20709)" matches the main change. The PR passes the server-verified user ID and session ID through dispatch to the external MCP audit, so…
Linked Issues check Passed Scope: directly linked issue #20709 (active, open). Its three coding acceptance criteria apply. No parent or contextual issues are present. Non-coding items do not apply.

Objective 1 [#20709] Dispatc…
Out of Scope Changes check Passed All reviewed changes relate to the identity and audit path for external MCP calls in #20709.

- tool_permission_gate.py (caller_identity), tool_handler.py and mcp_dispatch.py: identity and session plu…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Title check

Explanation

The title "fix(mcp): external MCP calls audit the real caller (#20709)" matches the main change. The PR passes the server-verified user ID and session ID through dispatch to the external MCP audit, so the audit records the real caller instead of a missing or wrong identity. The title is specific, concise, and follows a conventional-commit style. The summary also covers the external MCP audit path, which is the primary focus of the objectives and linked issue #20709. The resumed-turn identity overlay and the auth_scope forwarding are secondary changes that the title does not name, which is expected.

Full details: Linked Issues check

Explanation

Scope: directly linked issue #20709 (active, open). Its three coding acceptance criteria apply. No parent or contextual issues are present. Non-coding items do not apply.

Objective 1 [#20709] Dispatch carries the caller identity from the chat tool path to call_tool. Evidence: tool_handler.py (_try_mcp_dispatch) passes **caller_identity(ctx, session_id) to dispatcher.dispatch. caller_identity in tool_permission_gate.py reads user_id only from the server-verified VERIFIED_USER_KEY in ctx.context. dispatch in mcp_dispatch.py accepts user_id and passes it through _call_bridge and _call_external_bridge to MCPExternalBridge.call_tool. The test file records that the chat path forwards only the context user and session.

Objective 2 [#20709] An external MCP call from chat writes an audit row with the real user_id, shown by a test. Evidence: _audit_tool_call in mcp_external_bridge.py writes user_id=user_id or SYSTEM_ACTOR on every outcome. services/mcp_external_identity_20709_test.py includes a test that the real user_id lands in the audit row.

Objective 3 [#20709] A call with no user records that explicitly. Evidence: _audit_tool_call writes SYSTEM_ACTOR with details.actor_type set to "system". The test file includes a test that a call with no user records the system actor. A tool-argument user_id is ignored, which keeps identity server-derived.

Session confirmation [#20709] The issue asks the fix to confirm that chat dispatch omits session_id. The PR confirms this and forwards session_id through dispatch, _call_bridge and _call_external_bridge to call_tool. It is recorded on the audit row (session_id field and details.session_id).

Resumed turns [#20709] A resumed graph turn without the verified key would audit as system. The PR adds overlay_verified_identity (session_role.py), which replaces org and user keys from the resumer's scope and removes each key when its scope value is absent or falsy. This is fail-closed. resume_graph and resume_command use it. The test file covers a checkpoint lacking a user and a resumer with no user.

Limits: this assessment relies on the supplied change summary, PR description and test descriptions. No repository inspection was performed, and the test results were not independently re-run.

Full details: Out of Scope Changes check

Explanation

All reviewed changes relate to the identity and audit path for external MCP calls in #20709.

  • tool_permission_gate.py (caller_identity), tool_handler.py and mcp_dispatch.py: identity and session plumbing from chat to dispatch. Directly required.
  • mcp_external_bridge.py (_audit_tool_call, SYSTEM_ACTOR, actor_type, session_id on the audit row): required by objectives 2, 3 and the session confirmation.
  • mcp_external_bridge.py durable=True audit write: not an explicit issue requirement. It changes the same audit function and supports the traceability goal of the issue (an action on an external system must remain traceable). The PR gives this rationale. It is adjacent, not unrelated.
  • session_role.py, attachment_context.py, manager.py (overlay_verified_identity, stamp of resumer identity, process_message forwarding auth_scope): needed so that resumed chat turns and chat-originated calls keep the verified identity. Connected to objective 1 and the resumed-turn case.
  • mcp_dispatch_external_test.py and test_auth_role_plumbing.py: test updates for the new parameters. Supporting changes.
  • mcp_external_identity_20709_test.py: tests for the issue criteria.

No change was shown to be unrelated to #20709.

Excluded file: scripts/python_file_size_known_large.py is listed in ignored_files and was not inspected. This verdict does not depend on it.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 14 functions across 10 files.

Finishing Touches

Generate docstrings

  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@mrveiss mrveiss added backend bug Something isn't working area: mcp-governance Wave 3 · cluster G — MCP tool governance phase:M2.8 Audit trail and run supervision labels Nov 8, 2026
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Notice: 29 open PRs — past the runaway threshold (25)

This is not a request to defer this PR. There is no cap on open PRs (#19397) -- nothing blocks opening or pushing a PR.

This notice only means the count is high enough to be worth a glance for a runaway — something opening PRs in a loop, or a merge pipeline that has stalled so nothing is draining.

Currently open:

If the queue is draining normally, ignore this. Otherwise:

  1. Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
  2. Approved PRs land through the merge train the coordinator sequences (merge commits, never squash) -- check the open chore(merge-train) PR is moving, not each PR on its own
  3. Look for a loop opening near-identical PRs

Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Review of f00b4d8: CHANGES (minor, 3 items)

Verified:

  • Identity is not spoofable. caller_identity (tool_permission_gate.py:62-71) reads only the verified-user key, which apply_auth_role sets from the authenticated scope. It never reads tool args, headers or the body.
  • One caller. The only production path that executes an external MCP tool is tool_handler.py:1061. Its identity flows through mcp_dispatch.py:340 and :392 into call_tool(..., user_id=...).
  • All 3 ACs of bug(mcp): external MCP calls reach the audit log with no user, because dispatch passes only the role #20709 are met in code. AC3 is at mcp_external_bridge.py:99-113: user_id or SYSTEM_ACTOR, with actor_type set to user or system.
  • CI at head: 0 failures. The non-green rows are cancelled runs, so it needs a full run.
  • Hygiene: fine. No print calls, nothing hardcoded, new functions are ≤30 lines.

To change:

  1. mcp_external_bridge.py:99-113: write the audit row with durable=True. Today it is scheduled as fire-and-forget, so a crash can lose the record this issue exists to produce. If not durable, record why.
  2. mcp_external_bridge.py:99-113: session_id never reaches call_tool, so the audit row has no session. Pass it through, or correct the description, which currently says "user and session to call_tool".
  3. tool_permission_gate.py:70: an authenticated turn that lacks the verified key (e.g. a resumed turn) is audited as system, which is the mislabel bug(mcp): external MCP calls reach the audit log with no user, because dispatch passes only the role #20709 removes. Confirm every chat entry point runs apply_auth_role. Add a test that an authenticated turn on each entry path is never recorded as system.

Non-blocking: identity test 1 asserts on a mocked audit_log, not a stored row. That is acceptable if the audit pipeline is covered elsewhere; please name where.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Verdict: CHANGES (1 item). Delta f00b4d8...3139aa9 reviewed (9 files, 1 commit).

Verified

  • Durable audit: mcp_external_bridge.py _audit_tool_call now passes durable=True; mcp_external_identity_20709_test.py::test_audit_row_is_durable_and_carries_the_session_id asserts it.
  • session_id: dispatch -> _call_bridge -> _call_external_bridge -> call_tool -> audit session_id and details.session_id, all five hops forwarded and asserted. The origin is caller_identity(ctx, session_id) (tool_handler.py:1061, tool_permission_gate.py:63), which takes the session id from the turn and user_id only from the server-verified context key, never from tool arguments.
  • Resume route: /chats/{chat_id}/resume (api/chat.py) depends on validate_chat_ownership before the stream starts, and auth_scope=principal_scope(current_user) comes from the request auth. So user B resuming A's checkpoint is refused by the ownership dependency, or is an admin, and the stamp is the resumer's scope.
  • Callers: process_message has no non-test caller on this head. acp/runner.py:70 calls process_message_stream(session_id, prompt, context) with no scope, so it stays system. The only resume_graph caller is chat_streaming.py:168. I did not exhaustively check websocket paths beyond a grep of non-test callers.
  • File size: manager.py is 3750 lines at f00b4d8 and 3749 at 3139aa9. The ceiling in scripts/python_file_size_known_large.py went 3750 -> 3749. The file shrank by 1 and the ceiling was lowered, not raised. OK.
  • Hygiene: the new/changed functions are under 30 lines, with no print calls, no hardcoded values and no swallowed errors in the delta.

Finding (blocking)

  1. autobot-backend/chat_workflow/session_role.py stamp_resumer_identity (about lines 76-85): when the resumer's scope has no user_id/org_id, the loop skips the key and the checkpoint's value survives. The docstring says that is intended ("keeps the checkpoint's"), but then a resumed turn can be audited as the user who paused it, not the person who resumed. apply_auth_role pops the key in the same case (else: merged.pop(key, None)). The two functions share only _identity_pairs; the overlay loop is duplicated with different semantics. Fix: have stamp_resumer_identity reuse one implementation of the overlay, for example an _overlay_identity(merged, scope) helper that apply_auth_role also calls, with the fail-closed pop. A resume without a verified principal then falls to system, never to the previous user's identity.
  2. Tests (same item): the new test only covers a checkpoint lacking the key. It would fail without the fix, which is good. Add two cases: (a) checkpoint holds verified_user_id=alice, resume scope is bob, so the result is bob; (b) checkpoint holds alice, resume scope is empty or None, so the key is absent.

CI at 3139aa9 (check-runs): 30 success, 30 cancelled, 12 skipped, 1 neutral, 1 in progress, 0 failure. The cancelled runs are not failures.

Not a blocker: process_message forwarding auth_scope is fine; it has no production caller.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b936aa2 and 61ad77e.

Files ignored due to path filters: 1

  • scripts/python_file_size_known_large.py is excluded by !scripts/python_file_size_known_large.py
Files selected for processing: 10

  • autobot-backend/chat_workflow/attachment_context.py
  • autobot-backend/chat_workflow/manager.py
  • autobot-backend/chat_workflow/session_role.py
  • autobot-backend/chat_workflow/tool_handler.py
  • autobot-backend/chat_workflow/tool_permission_gate.py
  • autobot-backend/services/mcp_dispatch.py
  • autobot-backend/services/mcp_dispatch_external_test.py
  • autobot-backend/services/mcp_external_bridge.py
  • autobot-backend/services/mcp_external_identity_20709_test.py
  • autobot-backend/tests/unit/chat_workflow/test_auth_role_plumbing.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Delta review 3139aa9 → 61ad77e: APPROVE.

The blocking finding is fixed canonically. overlay_verified_identity in chat_workflow/session_role.py is now the one overlay. apply_auth_role and resume_context both call it, and the duplicate stamp_resumer_identity is gone, with no remaining reference at head.

It fails closed: a present scope value overwrites, and an absent one pops the key. So a resumed turn can never carry the identity of the user who paused it.

New tests:

  • B resuming A's checkpoint: both the context and the MCP audit row name B.
  • A resumer scope of None, {} or {org_id}: the key is dropped and the audit row is system.

Both would fail on the previous head, which kept the checkpoint value.

With the earlier items (a durable audit, session_id through to call_tool, ownership checked on resume), every finding is addressed. Queued for the next merge train.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at 842cfac
Verdict: APPROVE (0 blocking) - delta 61ad77e..842cfac (author commit 842cfac on top of one main merge)

# Severity File:line Issue Fix
1 info autobot-backend/services/mcp_external_bridge.py:268-282 The outcome row is written in an except Exception branch and after the try. A task cancellation (BaseException) mid-call leaves only the "attempted" row. This is acceptable: the pre-call row is the record. none
Required checks:
  1. Refusal is visible: bridge.py:254-256 returns success=False, error="audit trail unavailable; the tool was not called". mcp_dispatch.py:394-401 maps it to {"success": False, "result": , "bridge": "external"}. dispatch() returns it unchanged (mcp_dispatch.py:340). tool_handler.py:1061-1086 builds WorkflowMessage(type="error", content="[external] audit trail unavailable...") and the dispatcher at tool_handler.py:3382-3386 yields it to the chat.
  2. Outcome row: bridge.py:277-282 writes "error" on any Exception, and bridge.py:284 writes "success". _audit_tool_call swallows its own failures (returns False), so the outcome write cannot turn a finished call into an exception.
  3. The only entry to the external call is client.call_tool at bridge.py:275, inside _call_and_audit. Its sole caller is bridge.py:257, after the attempted guard at bridge.py:254. No retry or alternate method exists. The only other external route into the bridge is _call_external_bridge, which goes through call_tool.
  4. attachment_bounds_20195_test.py:64 asserts "verified_user_id" not in refused["context"] after the real resume_context with scope=None, with the checkpoint holding "alice". overlay_verified_identity (session_role.py:73-86) pops the key, and the test then confirms "bob" replaces "alice" and the snapshot is unmutated. mcp_external_identity_20709_test.py:158-160 adds the audit side: user_id == "system". These are behavioural assertions, not mocks of the code under test.
    New tests: test_a_failed_audit_write_means_the_tool_is_not_called (return False and raise, client.call_tool.assert_not_awaited()), plus before/after order ["attempted","success"] with durable=True on both.
    CodeRabbit threads: 2 total; all answered/fixed (attachment_context.py thread: fail-closed asserted at test line 64, was already resolved; mcp_external_bridge.py thread: write-before-action, resolved).
    AC coverage (Closes PRs only): no change from the 61ad77e approval.
    Main-merge commits: clean (git show --cc 69ab47914d is empty)

@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

✅ SSOT Configuration Compliance: Passing

🎉 No new hardcoded values of either class — ssot and other both block.

Known backlog in pipeline-scripts/hardcoded_values_baseline.txt is suppressed and tracked in #14371.

@mrveiss
mrveiss merged commit 34c6776 into main Nov 8, 2026
80 checks passed
@mrveiss
mrveiss deleted the issue-20709 branch November 8, 2026 21:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: mcp-governance Wave 3 · cluster G — MCP tool governance backend bug Something isn't working phase:M2.8 Audit trail and run supervision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(mcp): external MCP calls reach the audit log with no user, because dispatch passes only the role

1 participant