Skip to content

fix(aiguard): evaluate Anthropic MCP connector tool calls and results - #22113

Draft
avara1986 wants to merge 8 commits into
mainfrom
alberto.vara/appsec-71909-anthropic-mcp-connector
Draft

avara1986 wants to merge 8 commits into
mainfrom
alberto.vara/appsec-71909-anthropic-mcp-connector

Conversation

@avara1986

@avara1986 avara1986 commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Description

AI Guard's Anthropic integration dropped mcp_tool_use and mcp_tool_result content blocks as unknown block types. With the Anthropic MCP connector (client.beta.messages.create(mcp_servers=[...])), Anthropic runs the MCP client itself and reports each call and its result with these blocks, so connector tool calls and their results never reached AI Guard: neither in the evaluation of the response nor in the history of later requests.

The design is: read the connector servers of the request once, then attach them while converting the messages.

  1. Read the servers (_connector_mcp_servers): each hook maps the name of every entry of the request's mcp_servers to a managed_by: provider server entry, with transport unknown and the URL reduced to its origin. Only name and url are read; authorization_token never is.
  2. Convert the blocks: the existing converter gets that map. mcp_tool_use becomes an assistant tool call whose mcp.server_id references its server (tools map to themselves), and mcp_tool_result becomes a tool message. Content blocks are converted in block order: each result of a tool Anthropic ran (server tools, mcp_tool_result) ends the assistant message before it and follows as a tool message, so several connector rounds in one message keep their order. Servers are read from extra_body when it carries mcp_servers (the only way on older SDKs). A server that the request does not declare is identified by its name alone, and only servers referenced by a tool call are sent. The conversion happens whatever DD_AI_GUARD_MCP_ENABLED says; only the MCP metadata depends on it.
  3. Streams: the shared contrib stream rebuild drops server_name and renames mcp_tool_result to tool_result. reconstruct_anthropic restores both from the content_block_start chunks, on AI Guard's side, so the shape LLM Observability reads is unchanged.
  4. Resumed turns: a server or connector result whose call is in an earlier message is still evaluated, before any text after it. This applies to Anthropic's own server tools too.
  5. Pending client calls: client tool_use calls wait for the next user turn, so they go in the last assistant message of a turn, after any server or connector result, whatever their position among the blocks. A response that stops for a client call therefore stays an output evaluation. dd-trace-js still puts a client call that comes before a connector result in the same message as the connector call; aligning it is tracked in APPSEC-72055.
  6. Single-use nested content: nested content (tool_result / mcp_tool_result content, document source.content, web_search_tool_result content) is evaluated only when it is a string, a list or a tuple. Any other iterable may only be read once (an iterator, or an iterable that hands out the same iterator), so AI Guard leaves it unread and the SDK still sends it intact; AI Guard does not evaluate it and reports the skip to telemetry.
  7. What extra_body sends: the SDK merges extra_body over the params, so every read of messages, system, tools and mcp_servers (before and after the call, and buffered streams) uses the extra_body value when there is one (_sent_param). AI Guard leaves a param that extra_body replaces unread (the SDK and LLM Observability may still read it), and iterable extra_body values are listed once into a new extra_body dict, so the caller's is unchanged. Before, AI Guard evaluated the top-level values even when they were not sent.
  8. Request iterables: the before-hook lists iterable messages, system, tools and mcp_servers once, in the kwargs the SDK gets, so the SDK, LLM Observability and AI Guard read the same lists; an error raised by a caller iterable reaches the caller, as it would from the SDK. Buffered streams evaluate with the contrib stream handler's kwargs, that same dict.
  9. Client-managed MCP tools with the same name: attach_mcp no longer reassigns a call that already references a server, and mark_evaluated skips the response's connector calls, so a connector call never spares a client-managed tool call its own check.

Also: docs for DD_AI_GUARD_MCP_ENABLED, the AI Guard development rule, a fixes release note, the shared test helpers moved into the anthropic tests' conftest.py, and the line pinned for _anthropic.py in scripts/check_constant_log_message.py (67 to 70).

Jira: APPSEC-71909

Customer impact

Applications that use the Anthropic MCP connector now get AI Guard evaluations of the connector's tool calls and results, and those evaluations can block. Anthropic has already run a connector call when the response arrives, so a blocking verdict withholds the response from the application but cannot stop the call itself.

Testing

  • New tests/aiguard/anthropic/test_mcp_connector.py: conversion; the /evaluate payload and the ai_guard span meta-struct, where every mcp.server_id resolves; no authorization_token or URL user information, path, query or fragment in either; flag off; undeclared server; two names on one origin; generator mcp_servers (also in buffered streams, sync and async); caller iterator errors; resumed results, pending client calls and several connector rounds in one message, in responses and in history; extra_body servers as a list or an iterator, and an overridden mcp_servers iterator left unread; single-use result content (an iterator and an iterable wrapper) reaching Anthropic intact through the SDK; a pending client call before or after a connector result; and through the SDK, beta.messages.create sync, async and buffered streams (sync and async), and a blocking verdict.
  • tests/aiguard/anthropic/test_anthropic.py: the before-hook with messages, system and tools from extra_body, the replaced iterators left unread and the caller's extra_body unchanged; through the SDK, extra_body messages (list) and system (string) in the sent request and both evaluations; one-shot document source and web search result content left unread, in top-level and extra_body messages; a web search error result converted without a report.
  • tests/aiguard/anthropic/test_mcp.py: a connector call named like a client-managed tool, on another origin and on the same origin.
Suite Environment Result
ai_guard_anthropic 5316c60f847a py3.13, anthropic==0.84.0, mcp<2 227 passed
ai_guard_anthropic 5051ae7c17f6 py3.14, anthropic<1, mcp<3 227 passed
ai_guard_anthropic 8bc03089e6c5 py3.9, anthropic==0.28.0 134 passed, 22 skipped (no MCP connector, no mcp)
ai_guard_litellm_guardrail 1227021fb1a6 / 0c22a699084f, litellm[proxy]==1.78.5 / 1.82.6 255 passed each

scripts/lint (format, typing, constant log check) passes. Not run: a live call through the connector. No benchmark scenario covers the AI Guard listeners, and the overhead was not measured. The changed code runs for every Anthropic request AI Guard evaluates, including buffered streams; it adds a few type checks and dictionary lookups per request and per content block.

Risks

  • Connector calls and results, and server tool results of resumed turns, now reach AI Guard, so applications can get blocking verdicts on responses that passed before.
  • A client-managed server and a connector server on the same URL origin share a server ID, so they are sent as one entry that keeps the first server's name, transport and managed_by.

Additional Notes

This replaces #22068, which grew beyond the ticket. Follow-ups, not in this PR:

  1. Streamed results of Anthropic's own server tools (web search, code execution) are still dropped by the buffered stream reconstruction.
  2. With ChatAnthropic under LangChain, the LangChain integration evaluates instead of the Anthropic hooks, and its converter drops the connector blocks.
  3. Known gap: nested content (tool results, document sources, web search results) given as an iterable other than a list or tuple reaches Anthropic intact but is not evaluated by AI Guard, since reading it would leave it empty for the SDK. Evaluating it needs the request content listed once for both the SDK and AI Guard, ideally from the body the SDK prepares. Tracked in APPSEC-72036 and APPSEC-72047.

🤖 Generated with Claude Code

The Anthropic converter dropped mcp_tool_use and mcp_tool_result blocks as
unknown types, so the calls and results of MCP servers run by the Anthropic
MCP connector (client.beta.messages.create(mcp_servers=...)) were never
evaluated, neither in the response nor in the history of later requests.

- Convert mcp_tool_use into an assistant tool call and mcp_tool_result into
  a tool message, split like server tools (tool call, tool result, synthesis).
- With DD_AI_GUARD_MCP_ENABLED, reference a managed_by provider mcp_servers
  entry built from the name and URL origin of the request's mcp_servers entry
  with that name, or from the name alone when the request does not declare
  it. authorization_token is never read.
- Restore server_name and the mcp_tool_result type in the buffered stream
  reconstruction, which the shared contrib rebuild drops.
- Keep a connector call named like a client-managed MCP tool apart from that
  tool: it keeps its provider reference and never spares the tool its check.
- Share the Anthropic AI Guard test helpers through the tests' conftest.

APPSEC-71909

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 22 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 22 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=103)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.internal.span_bus -×-> ddtrace._trace.span  (internal-core -> product:tracing, score=35)
ddtrace.llmobs._llmobs -×-> ddtrace._trace.span  (product:llmobs -> product:tracing, score=33)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

.cursor/rules/ai-guard.mdc                                              @DataDog/asm-python
ddtrace/aiguard/_constants.py                                           @DataDog/asm-python
ddtrace/aiguard/_listener.py                                            @DataDog/asm-python
ddtrace/aiguard/_streaming.py                                           @DataDog/asm-python
ddtrace/aiguard/integrations/_anthropic.py                              @DataDog/asm-python
ddtrace/aiguard/integrations/_anthropic_mcp.py                          @DataDog/asm-python
ddtrace/aiguard/integrations/_anthropic_streaming.py                    @DataDog/asm-python
docs/configuration.rst                                                  @DataDog/apm-python-guild
releasenotes/notes/aiguard-anthropic-mcp-connector-9a59c70d7bb700b0.yaml  @DataDog/apm-python
scripts/check_constant_log_message.py                                   @DataDog/apm-python-guild
tests/aiguard/anthropic/conftest.py                                     @DataDog/asm-python
tests/aiguard/anthropic/test_anthropic.py                               @DataDog/asm-python
tests/aiguard/anthropic/test_mcp.py                                     @DataDog/asm-python
tests/aiguard/anthropic/test_mcp_connector.py                           @DataDog/asm-python

@avara1986

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T09:33:15.020188Z 7a69951 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 7a69951a62

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@pr-commenter

pr-commenter Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-26 18:12:46

Comparing candidate commit 684e6f7 in PR branch alberto.vara/appsec-71909-anthropic-mcp-connector with baseline commit e48e0f1 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 387 metrics, 9 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

Unstable benchmarks

These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

scenario:coreapiscenario-context_with_data_listeners

  • unstable execution_time [-689.949ns; +787.289ns] or [-6.478%; +7.392%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-41.042ns; +37.771ns] or [-6.423%; +5.911%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1943.386ns; +1895.895ns] or [-9.725%; +9.487%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1711.387ns; +1967.694ns] or [-8.903%; +10.236%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-384.991ns; +374.150ns] or [-9.046%; +8.791%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-226.614ns; +229.411ns] or [-8.530%; +8.635%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-89.133ns; +90.802ns] or [-6.480%; +6.602%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4610.531ns; +4632.557ns] or [-9.510%; +9.556%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-1061.356ns; +823.947ns] or [-10.286%; +7.985%]

avara1986 and others added 6 commits November 26, 2026 12:23
…er intact

- List iterable messages, system, tools and mcp_servers once in the
  before-hook, in the kwargs the SDK gets, replacing three inline copies; an
  error raised by a caller iterable reaches the caller, as it would from the SDK.
- Evaluate buffered streams with the contrib stream handler's request kwargs,
  the dict the before-hook listed, instead of the wrapper's own kwargs.
- Emit a client tool_use that follows a server or connector result after that
  result, so a response that stops for a client call stays an output.
- Emit server and connector results even when their call is in an earlier
  message, before any text that follows them.

APPSEC-71909

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ra_body servers

- Replace the pre/post buckets with one conversion in block order: each
  result of a tool Anthropic ran (server tools, mcp_tool_result) ends the
  assistant message before it and follows as a tool message, so several
  connector rounds in one message keep their order. User turns keep their tool
  results before their text; responses ignore generic tool_result blocks,
  which the stream rebuild also gives to server tool results.
- Read the connector servers from extra_body when it carries mcp_servers: the
  SDK merges extra_body over the params, and older SDKs can only send them
  that way.
- Move the line pinned for _anthropic.py in the constant log message check
  to 70.

APPSEC-71909

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The before-hook no longer lists the top-level mcp_servers when extra_body
replaces it, since that param is never sent. Tool result content that is a
one-shot iterator is not read, so the SDK still sends it intact; AI Guard
does not evaluate it and reports the skip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SDK sends extra_body mcp_servers given as a one-pass iterable, but AI
Guard only read lists and tuples, so connector calls lost their declared
server URL. The before-hook now lists them once into a new extra_body dict,
leaving the caller's dict unchanged, and both evaluations read that list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ends

The SDK merges extra_body over the request params, but AI Guard read the
top-level messages, system and tools, so it evaluated values that were never
sent and missed the ones that were. Every read now goes through _sent_param,
which prefers extra_body. A param that extra_body replaces is left unread,
and extra_body values are listed once into a new dict, leaving the caller's
dict unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t unread

The converter consumed one-shot iterators in document source content and
web search result content without writing them back, so the SDK sent empty
lists. Like tool result content, they are now left unread (_is_one_shot):
the SDK still sends them, AI Guard does not evaluate them, and the skip is
reported. The anthropic tests share one recording client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@avara1986

avara1986 commented Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

Two points from the latest review:

Performance note in the description (P3). This is already addressed: since 826af3e, the description no longer says the added work is a dictionary lookup limited to connector requests. It says the changed code runs for every Anthropic request AI Guard evaluates, including buffered streams, and that the overhead was not measured because no benchmark scenario covers the AI Guard listeners.

Single-use nested content (known gap). Nested content that may only be read once (tool result content, document source.content, web search results), whether an iterator or an iterable that hands out the same iterator, is left unread on purpose: reading it in the AI Guard hook would leave it empty for the SDK, so the request Anthropic receives would change. The content reaches Anthropic intact, AI Guard does not evaluate it, and the skip is reported to telemetry. Evaluating it needs the request content read once for both the SDK and AI Guard, ideally from the body the SDK prepares; that is tracked in APPSEC-72036 and APPSEC-72047, and stated in the PR description under Additional Notes.

…ep pending client calls last

Nested content is read only when it is a string, list or tuple: any other
iterable may only be read once (an iterator, or an iterable that hands out
the same iterator), so it is left for the SDK and the skip is reported. Web
search error results are not reported. Client tool_use calls go in the last
assistant message of a turn, so a client call before a connector result no
longer ends the response on a tool message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant