← Back to Pull requests

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

Closed
unknown closed this pull request without merging on Nov 27, 2026 09:35 UTC
View on GitHub
unknown unknown commented on Nov 26, 2026 09:27 UTC
Author

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 (tracked in APPSEC-72056), so the change was timed offline against main (anthropic==0.84.0, /evaluate stubbed, best of 7 x 2000 calls): the before-call and after-call checks on an ordinary 41-message request are unchanged within noise (about 120 µs on both); an MCP connector response goes from 9.9 to 22.6 µs, since main dropped its blocks; reconstruct_anthropic goes from 2.8 to 4.2 µs for a text stream and from 5.8 to 10.3 µs for a connector stream.

    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

    [APPSEC-71909]: https://datadoghq.atlassian.net/browse/APPSEC-71909?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

    [APPSEC-72055]: https://datadoghq.atlassian.net/browse/APPSEC-72055?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: avara1986 Review duration: 1447m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #22113"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%