Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion docs/understand/weblogs/end-to-end_weblog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions manifests/cpp_httpd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions manifests/cpp_nginx.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions manifests/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions manifests/golang.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions manifests/java.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions manifests/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions manifests/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions manifests/python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions manifests/ruby.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
57 changes: 57 additions & 0 deletions tests/ai_guard/test_ai_guard_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 4 additions & 2 deletions utils/build/docker/nodejs/express/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
9 changes: 7 additions & 2 deletions utils/build/docker/python/flask/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2313,15 +2313,20 @@ 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")
if user_id and session_id:
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:
Expand Down
Original file line number Diff line number Diff line change
@@ -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\":[]}}}"
}
}
Loading