From a3b73f86ce995f35507b6fc68fa210e591286ee6 Mon Sep 17 00:00:00 2001 From: Alberto Vara Date: Mon, 23 Nov 2026 14:33:21 +0100 Subject: [PATCH] AI Guard: test MCP server metadata in SDK evaluations The /ai_guard/evaluate weblog endpoint also accepts an object body with the messages and the MCP servers they reference, passed to the SDK (mcp_servers in Python, mcpServers in Node.js). Test_MCP_ToolCalls sends a tool call with mcp.server_id and its server list, and checks that the evaluation matches its body-hashed cassette and that the ai_guard span reports mcp_servers and the mcp reference. The cassette was recorded and scrubbed. Enabled for Python from v4.18.0-rc1; missing_feature for Node.js until DataDog/dd-trace-js#11384 ships. APPSEC-71867 Co-Authored-By: Claude Opus 5.5 --- docs/understand/weblogs/end-to-end_weblog.md | 33 ++++++++++- manifests/cpp_httpd.yml | 1 + manifests/cpp_nginx.yml | 1 + manifests/dotnet.yml | 1 + manifests/golang.yml | 1 + manifests/java.yml | 1 + manifests/nodejs.yml | 4 ++ manifests/php.yml | 1 + manifests/python.yml | 4 ++ manifests/ruby.yml | 1 + tests/ai_guard/test_ai_guard_sdk.py | 57 +++++++++++++++++++ utils/build/docker/nodejs/express/app.js | 6 +- utils/build/docker/python/flask/app.py | 9 ++- .../aiguard_evaluate_post_812be9b8.json | 35 ++++++++++++ 14 files changed, 150 insertions(+), 5 deletions(-) create mode 100644 utils/build/docker/vcr/cassettes/aiguard/aiguard_evaluate_post_812be9b8.json diff --git a/docs/understand/weblogs/end-to-end_weblog.md b/docs/understand/weblogs/end-to-end_weblog.md index bf72194e014..27317de9a06 100644 --- a/docs/understand/weblogs/end-to-end_weblog.md +++ b/docs/understand/weblogs/end-to-end_weblog.md @@ -1487,7 +1487,10 @@ This endpoint triggers AI Guard SDK evaluations using the `evaluate()` method fr **Request Format:** - **Content-Type:** `application/json` -- **Body:** List of AI Guard `Message` objects to be evaluated +- **Body:** List of AI Guard `Message` objects to be evaluated, or an object with: + - `messages`: that list + - `mcp_servers` (optional): the MCP servers that the `mcp.server_id` of the tool calls reference, + passed to the SDK evaluation (`mcp_servers` argument in Python, `mcpServers` option in Node.js) - **Header:** `X-AI-Guard-Block` (optional, default: `false`) - Controls whether blocking is enabled - **Header:** `X-User-Id` (optional) - If present and non-empty, sets `usr.id` on the local root span - **Header:** `X-Session-Id` (optional) - If present and non-empty, sets `session.id` on the local root span @@ -1518,6 +1521,34 @@ This endpoint triggers AI Guard SDK evaluations using the `evaluate()` method fr ] ``` +**Request Body Example with MCP servers:** +```json +{ + "messages": [ + { + "role": "assistant", + "tool_calls": [ + { + "id": "call_mcp_1", + "function": { "name": "local_search", "arguments": "{\"query\":\"APPSEC\"}" }, + "mcp": { "server_id": "mcp_0f2f11f8cafdbcc5" } + } + ] + } + ], + "mcp_servers": [ + { + "id": "mcp_0f2f11f8cafdbcc5", + "managed_by": "client", + "transport": "stdio", + "command": "uvx", + "args": ["mcp-example"], + "tools": { "local_search": "search" } + } + ] +} +``` + **Response Behavior:** - **Success (200 OK):** Returns the `Evaluation` result as JSON when evaluation succeeds - **Blocked (403 Forbidden):** Returns `AIGuardAbortError` when blocking is enabled and content is flagged diff --git a/manifests/cpp_httpd.yml b/manifests/cpp_httpd.yml index 6d8ad8e7f58..047a0073e2c 100644 --- a/manifests/cpp_httpd.yml +++ b/manifests/cpp_httpd.yml @@ -24,6 +24,7 @@ manifest: tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTags: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTagsFailSafe: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_Full_Response_And_Tags: missing_feature + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_RedactedMessagesInSDKResponse: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_Redaction: missing_feature diff --git a/manifests/cpp_nginx.yml b/manifests/cpp_nginx.yml index dd3fa63dd57..97c07c0944b 100644 --- a/manifests/cpp_nginx.yml +++ b/manifests/cpp_nginx.yml @@ -22,6 +22,7 @@ manifest: tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTags: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTagsFailSafe: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_Full_Response_And_Tags: missing_feature + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_RedactedMessagesInSDKResponse: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_Redaction: missing_feature diff --git a/manifests/dotnet.yml b/manifests/dotnet.yml index 0ca7c22c0e4..9d5cebc1c50 100644 --- a/manifests/dotnet.yml +++ b/manifests/dotnet.yml @@ -14,6 +14,7 @@ manifest: tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTags: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTagsFailSafe: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_Full_Response_And_Tags: missing_feature + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_RedactedMessagesInSDKResponse: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_Redaction: missing_feature diff --git a/manifests/golang.yml b/manifests/golang.yml index 97d0185a51c..f15c67d027f 100644 --- a/manifests/golang.yml +++ b/manifests/golang.yml @@ -14,6 +14,7 @@ manifest: tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTags: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTagsFailSafe: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_Full_Response_And_Tags: missing_feature + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_RedactedMessagesInSDKResponse: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_Redaction: missing_feature diff --git a/manifests/java.yml b/manifests/java.yml index 9103d2916e4..f9e70e43831 100644 --- a/manifests/java.yml +++ b/manifests/java.yml @@ -59,6 +59,7 @@ manifest: - weblog_declaration: "*": irrelevant (just one weblog is enough to test the SDK) "spring-boot": v1.57.0 + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: incomplete_test_app (weblog /ai_guard/evaluate does not accept MCP servers) tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: - weblog_declaration: "*": irrelevant (just one weblog is enough to test the SDK) diff --git a/manifests/nodejs.yml b/manifests/nodejs.yml index c54218552ab..2760d185862 100644 --- a/manifests/nodejs.yml +++ b/manifests/nodejs.yml @@ -173,6 +173,10 @@ manifest: - weblog_declaration: "*": irrelevant (just one weblog is enough to test the SDK) express5: *ref_5_81_0 + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: + - weblog_declaration: + "*": irrelevant (just one weblog is enough to test the SDK) + express5: "missing_feature (MCP servers in the SDK evaluate call, DataDog/dd-trace-js#11384)" tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: - weblog_declaration: "*": irrelevant (just one weblog is enough to test the SDK) diff --git a/manifests/php.yml b/manifests/php.yml index e1d041dff59..d7126053145 100644 --- a/manifests/php.yml +++ b/manifests/php.yml @@ -14,6 +14,7 @@ manifest: tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTags: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_ExtraTagsFailSafe: missing_feature (APPSEC-70724) tests/ai_guard/test_ai_guard_sdk.py::Test_Full_Response_And_Tags: missing_feature + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_RedactedMessagesInSDKResponse: missing_feature tests/ai_guard/test_ai_guard_sdk.py::Test_Redaction: missing_feature diff --git a/manifests/python.yml b/manifests/python.yml index d1899416d0e..084ba820074 100644 --- a/manifests/python.yml +++ b/manifests/python.yml @@ -72,6 +72,10 @@ manifest: - weblog_declaration: "*": irrelevant (just one weblog is enough to test the SDK) "flask-poc": v4.1.0 + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: + - weblog_declaration: + "*": irrelevant (just one weblog is enough to test the SDK) + "flask-poc": v4.18.0-rc1 tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: - weblog_declaration: "*": irrelevant (just one weblog is enough to test the SDK) diff --git a/manifests/ruby.yml b/manifests/ruby.yml index feff569168c..32a561546cd 100644 --- a/manifests/ruby.yml +++ b/manifests/ruby.yml @@ -100,6 +100,7 @@ manifest: sinatra32: irrelevant sinatra41: irrelevant uds-sinatra: irrelevant + tests/ai_guard/test_ai_guard_sdk.py::Test_MCP_ToolCalls: incomplete_test_app (weblog /ai_guard/evaluate does not accept MCP servers) tests/ai_guard/test_ai_guard_sdk.py::Test_NoRedaction: - weblog_declaration: '*': irrelevant diff --git a/tests/ai_guard/test_ai_guard_sdk.py b/tests/ai_guard/test_ai_guard_sdk.py index 717d80eab2b..86fb7f7a2fb 100644 --- a/tests/ai_guard/test_ai_guard_sdk.py +++ b/tests/ai_guard/test_ai_guard_sdk.py @@ -502,6 +502,63 @@ def test_sds_in_response(self): # redaction_replacements the backend returns, the messages expected once redaction has been # applied and the expected value of the redacted tags, so the tests below and the cassettes # never drift. Regenerate both after editing. +# Cross-tracer contract: "mcp_" + sha256(key).hexdigest()[:16], with key "stdio|uvx|mcp-example". +MCP_SERVER_ID = "mcp_0f2f11f8cafdbcc5" +MCP_SERVERS: list[dict] = [ + { + "id": MCP_SERVER_ID, + "managed_by": "client", + "transport": "stdio", + "name": "local-docs", + "command": "uvx", + "args": ["mcp-example"], + "tools": {"local_search": "search"}, + } +] +MCP_MESSAGES: list[dict] = [ + {"role": "user", "content": "Search the local docs for APPSEC issues."}, + { + "role": "assistant", + "tool_calls": [ + { + "id": "call_mcp_1", + "function": {"name": "local_search", "arguments": '{"query":"APPSEC"}'}, + "mcp": {"server_id": MCP_SERVER_ID}, + } + ], + }, +] + + +@features.ai_guard +@scenarios.ai_guard +class Test_MCP_ToolCalls: + """SDK evaluations send the MCP servers that the tool calls reference, and report them on the span. + + The evaluate cassette is addressed by a hash of the exact request body: a tracer that drops the + mcp_servers list or the mcp.server_id of the tool call misses it, and the evaluation fails. + """ + + def setup_mcp_tool_call(self): + self.r = weblog.post("/ai_guard/evaluate", json={"messages": MCP_MESSAGES, "mcp_servers": MCP_SERVERS}) + + def test_mcp_tool_call(self): + assert self.r.status_code == 200, f"the evaluation did not match its cassette: {self.r.text}" + _assert_key(json.loads(self.r.text), "action", "ALLOW") + + def validate(span: DataDogLibrarySpan) -> bool: + if span["resource"] != "ai_guard": + return False + assert span["meta"]["ai_guard.target"] == "tool" + ai_guard = _assert_key(span["meta_struct"], "ai_guard") + assert _assert_key(ai_guard, "mcp_servers") == MCP_SERVERS + (tool_call,) = _assert_key(ai_guard, "messages")[-1]["tool_calls"] + assert tool_call["mcp"] == {"server_id": MCP_SERVER_ID} + return True + + interfaces.library.validate_one_span(self.r, validator=validate, full_trace=True) + + REDACTION_SCENARIOS: dict = json.loads((Path(__file__).parent / "redaction_scenarios.json").read_text()) REDACTED_TAG = "ai_guard.redacted" diff --git a/utils/build/docker/nodejs/express/app.js b/utils/build/docker/nodejs/express/app.js index 15c4ac5cfa9..9ff34e5793d 100644 --- a/utils/build/docker/nodejs/express/app.js +++ b/utils/build/docker/nodejs/express/app.js @@ -888,14 +888,16 @@ app.post('/ai_guard/evaluate', async (req, res) => { redaction_replacements }) const block = req.headers['x-ai-guard-block'] === 'true' - const messages = req.body + // The body is a list of messages, or an object with the messages and the MCP servers they reference. + const messages = Array.isArray(req.body) ? req.body : req.body.messages + const mcpServers = Array.isArray(req.body) ? undefined : req.body.mcp_servers const userId = req.headers['x-user-id'] const sessionId = req.headers['x-session-id'] if (userId && sessionId) { tracer.setUser({ id: userId, session_id: sessionId }) } try { - const evaluation = await tracer.aiguard.evaluate(messages, { block }) + const evaluation = await tracer.aiguard.evaluate(messages, mcpServers ? { block, mcpServers } : { block }) res.status(200).json(renameAttrs(evaluation)) } catch (e) { if (e.name === 'AIGuardAbortError') { diff --git a/utils/build/docker/python/flask/app.py b/utils/build/docker/python/flask/app.py index d9870428bc1..da858e96f21 100644 --- a/utils/build/docker/python/flask/app.py +++ b/utils/build/docker/python/flask/app.py @@ -2313,7 +2313,10 @@ def ai_guard_evaluate(): from ddtrace.appsec.track_user_sdk import track_user_id should_block = flask_request.headers.get("X-AI-Guard-Block", "false").lower() == "true" - messages = flask_request.get_json() + # The body is a list of messages, or an object with the messages and the MCP servers they reference. + body = flask_request.get_json() + messages = body.get("messages") if isinstance(body, dict) else body + mcp_servers = body.get("mcp_servers") if isinstance(body, dict) else None user_id = flask_request.headers.get("X-User-Id") session_id = flask_request.headers.get("X-Session-Id") @@ -2321,7 +2324,9 @@ def ai_guard_evaluate(): track_user_id(user_id, session_id=session_id) client = new_ai_guard_client(endpoint=os.environ.get("DD_AI_GUARD_ENDPOINT")) - evaluation = client.evaluate(messages, Options(block=should_block)) + # mcp_servers is only passed when sent, so tracers without the argument keep working. + kwargs = {"mcp_servers": mcp_servers} if mcp_servers is not None else {} + evaluation = client.evaluate(messages, Options(block=should_block), **kwargs) return jsonify(evaluation), 200 except AIGuardAbortError as e: diff --git a/utils/build/docker/vcr/cassettes/aiguard/aiguard_evaluate_post_812be9b8.json b/utils/build/docker/vcr/cassettes/aiguard/aiguard_evaluate_post_812be9b8.json new file mode 100644 index 00000000000..4bdd9fda798 --- /dev/null +++ b/utils/build/docker/vcr/cassettes/aiguard/aiguard_evaluate_post_812be9b8.json @@ -0,0 +1,35 @@ +{ + "request": { + "method": "POST", + "url": "https://app.datadoghq.com/api/v2/ai-guard/evaluate", + "headers": { + "Content-Type": "application/json", + "dd-ai-guard-version": "4.18.0rc1", + "dd-ai-guard-source": "SDK", + "dd-ai-guard-language": "python", + "Content-Length": "548" + }, + "body": "{\"data\": {\"attributes\": {\"messages\": [{\"role\": \"user\", \"content\": \"Search the local docs for APPSEC issues.\"}, {\"role\": \"assistant\", \"tool_calls\": [{\"id\": \"call_mcp_1\", \"function\": {\"name\": \"local_search\", \"arguments\": \"{\\\"query\\\":\\\"APPSEC\\\"}\"}, \"mcp\": {\"server_id\": \"mcp_0f2f11f8cafdbcc5\"}}]}], \"meta\": {\"service\": \"weblog\", \"env\": \"system-tests\"}, \"mcp_servers\": [{\"id\": \"mcp_0f2f11f8cafdbcc5\", \"managed_by\": \"client\", \"transport\": \"stdio\", \"name\": \"local-docs\", \"command\": \"uvx\", \"args\": [\"mcp-example\"], \"tools\": {\"local_search\": \"search\"}}]}}}" + }, + "response": { + "status": { + "code": 200, + "message": "OK" + }, + "headers": { + "content-type": "application/vnd.api+json", + "vary": "Accept-Encoding", + "x-frame-options": "SAMEORIGIN", + "content-length": "314", + "date": "Mon, 23 Nov 2026 13:29:31 GMT", + "x-ratelimit-limit": "700", + "x-ratelimit-period": "60", + "x-ratelimit-remaining": "699", + "x-ratelimit-reset": "29", + "x-ratelimit-name": "ai_guard_evaluate_per_org", + "x-content-type-options": "nosniff", + "strict-transport-security": "max-age=31536000; includeSubDomains; preload" + }, + "body": "{\"data\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"type\":\"evaluations\",\"attributes\":{\"action\":\"ALLOW\",\"extra_tags\":[{\"key\":\"ai_guard.evaluate_id\",\"value\":\"00000000-0000-4000-8000-000000000001\"}],\"global_prob\":0.0037689208984375,\"is_blocking_enabled\":false,\"reason\":\"No rule match.\",\"tag_probs\":null,\"tags\":[]}}}" + } +} \ No newline at end of file