← Back to Pull requests

feat(aiguard): link OpenAI tool calls to the MCP tools that a client listed #11309

Closed
avara1986 closed this pull request without merging on Nov 30, 2026 08:25 UTC
View on GitHub
avara1986 avara1986 commented on Nov 18, 2026 14:16 UTC
Author

What does this PR do?

Jira: APPSEC-70373

Part 3 of 5. AI Guard links the tool calls of an OpenAI request to the MCP tools that a client listed.

  • The instrumentation publishes dd-trace:mcp:listTools:result. AI Guard records the server of each listed tool by its inputSchema object.

  • When a chat completions or Responses request uses that schema object as the parameters of a function tool, the evaluation of the model call adds the mcp reference and the mcp_servers entry to that tool call.

  • An allowed response marks each MCP tool call. A later callTool with the same tool and arguments, on the same connection and in the same trace, gets no second check. A call on another connection gets its own check.

  • The records keep no client or transport alive.
  • Motivation

    With the link, AI Guard evaluates the MCP tool call with its conversation context, and the application gets one check for each tool call.

    Additional Notes

  • Scope: MCP SDK v1 only; part 4 adds v2.

  • An OpenAI request span that is the root of its trace (a script with no outer span) does not get the link. Those calls still get the check of part 2.

  • Tests: the link, marks per connection, reconnect, retention (fixtures/mcp-client-retention.js), and OpenAI chat completions and Responses flows (unit and integration).
  • Stack

    Review the parts in order; each PR shows only its own diff. Parts 4 and 5 can be reviewed at the same time as part 3. Merge in order.

    1. #11307 Evaluate contract and server identity
    2. #11308 Check MCP SDK v1 tool calls at callTool
    3. #11309 Link OpenAI tool calls to MCP tools
    4. #11310 MCP v2 client
    5. #11311 @openai/agents MCP server name

    Related, independent: #11306 (logging of thrown values that are not an Error). Review history: #11224 (draft, not for merge).

    🤖 Generated with Claude Code

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

    Diff: 1859 lines (+1822 / -37) across 15 files Reviewer: None requested Review duration: 16929m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.81) × (1 − Review Confidence (0.72)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.81 · 1859 lines diff across 15 files
    0.81
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.53 · 5 substantive comment(s)
    0.53
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 10%
    72%
    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.400
    No Reviewer Assigned no_reviewer_assigned
    0.120
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    6 items
    dd-octo-sts[bot] dd-octo-sts[bot] commented on Nov 18, 2026 14:18 UTC
    Bot

    Overall package size

    Self size: 9.53 MB
    Deduped: 10.29 MB
    No deduping: 10.29 MB

    <details><summary>Dependency sizes</summary>
    | name | version | self size | total size |
    |------|---------|-----------|------------|
    | import-in-the-middle | 3.5.3 | 131.25 kB | 531.9 kB |
    | opentracing | 0.14.7 | 194.81 kB | 194.81 kB |
    | dc-polyfill | 0.1.11 | 25.74 kB | 25.74 kB |

    </details>

    <sub>🤖 This report was automatically generated by heaviest-objects-in-the-universe<sub>

    codecov[bot] codecov[bot] commented on Nov 18, 2026 14:25 UTC
    Bot

    Codecov Report


    :white_check_mark: All modified and coverable lines are covered by tests.
    :white_check_mark: Project coverage is 99.15%. Comparing base (b22c429) to head (9d58ea1).

    <details><summary>Additional details and impacted files</summary>

    @@                           Coverage Diff                            @@
    ##           alberto.vara/aiguard-mcp-2-calltool-v1   #11309    +/-   ##
    ========================================================================
      Coverage                                   99.15%   99.15%            
    ========================================================================
      Files                                        1125     1125            
      Lines                                      187351   187924   +573     
      Branches                                       82       82            
    ========================================================================
    + Hits                                       185760   186333   +573     
      Misses                                       1590     1590            
      Partials                                        1        1            
    

    | Flag | Coverage Δ | |
    |---|---|---|
    | ai-guard | 65.08% <100.00%> (+0.32%) | :arrow_up: |
    | apm-capabilities | 54.93% <45.54%> (-0.03%) | :arrow_down: |
    | apm-integrations | 81.94% <ø> (ø) | |
    | appsec | 59.09% <32.25%> (-0.01%) | :arrow_down: |
    | debugger | 71.03% <ø> (ø) | |
    | instrumentation | 60.10% <32.25%> (-0.01%) | :arrow_down: |
    | llmobs | 82.81% <100.00%> (+<0.01%) | :arrow_up: |
    | openfeature | 68.17% <ø> (ø) | |
    | platform | 68.17% <ø> (-0.03%) | :arrow_down: |
    | profiling | 66.12% <ø> (ø) | |
    | serverless | 65.57% <ø> (ø) | |
    | test-optimization | 82.13% <ø> (+<0.01%) | :arrow_up: |

    Flags with carried forward coverage won't be shown. Click here to find out more.
    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    datadog-official[bot] datadog-official[bot] commented on Nov 18, 2026 14:33 UTC
    Bot

    <a target='_blank' href='https://app.datadoghq.com/ci/pipeline-executions?query=ci_level%3Ajob+%40ci.status%3Aerror+%40git.commit.sha%3A9d58ea19f54574bed93f8549f90c8e0ad40ccb94&referrer=pr-comment&start=1795163569000'><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/pipelines-warning.svg"/><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/pipelines-warning-light.svg" alt="Pipelines" align="center" /></picture></a> &nbsp;<a target='_blank' href='https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest+%40git.commit.sha%3A55ad68f4e21729938894534f638e5276e8b2858f&referrer=pr-comment&start=1795163569000'><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/tests-warning.svg"/><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/tests-warning-light.svg" alt="Tests" align="center" /></picture></a>

    ⚠️ Warnings

    Your PR has warnings. Tests failed — unable to determine if these are from required jobs.

    🚦 2 Pipeline jobs failed

    <blockquote>
    <div>

    <details open>
    <summary>System Tests | main / parametric / parametric (7) — ❌ 1 test failed · 🔧 Needs a code fix, caused by this PR</summary>

    <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzExMzA5?referrer=pr-comment&amp;buildId=AwAAAaH4NsdwIBYkDAAAABhBYUg0TnNkd0FBQ19GUTlNRElWUjlJQWsAAAAkMDFhMWY4NGEtOTFkOC00ZWUyLThmYjAtYTZiNTc1NzdkZTM5AAAGyQ&amp;ciFailurePanel=job">View more details</a> · <a href="https://github.com/DataDog/dd-trace-js/actions/runs/44707467384/job/136191431011">View in GitHub Actions</a>

    <blockquote>

    <details>
    <summary>❌&nbsp;<code>tests.parametric.otel_env_vars.test_otel_traces_exporter.Test_OTEL_TRACES_EXPORTER.test_otlp_in_list[console-otlp, parametric-nodejs]</code>&nbsp;from&nbsp;<code>system_tests_suite</code></summary>

    assert False
     &#43;  where False = any(&lt;generator object _assert_otlp_export.&lt;locals&gt;.&lt;genexpr&gt; at 0x7f8b8f364d40&gt;)
    
    self = &lt;tests.parametric.otel_env_vars.test_otel_traces_exporter.Test_OTEL_TRACES_EXPORTER object at 0x7f8b9c87c3b0&gt;
    test_agent = &lt;utils.docker_fixtures._test_agent.TestAgentAPI object at 0x7f8b993ca9c0&gt;
    test_library = &lt;utils.docker_fixtures._test_clients._test_client_parametric.ParametricTestClientApi object at 0x7f8b8f35f9b0&gt;
    
        @pytest.mark.parametrize(&#34;library_env&#34;, OTLP_IN_LIST_VALUE)
        def test_otlp_in_list(self, test_agent: TestAgentAPI, test_library: APMLibrary) -&gt; None:
    &gt;       _assert_otlp_export(test_agent, test_library)
    ...
    

    </details>
    </blockquote>
    </details>

    <details open>
    <summary>Serverless | azure-functions (cosmosdb) — 🔧 Needs a code fix, caused by this PR</summary>

    <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzExMzA5?referrer=pr-comment&amp;buildId=AwAAAaH4OiLQC_pqRwAAABhBYUg0T2lMUUFBQ1BQaWF5bklPMlNGM0cAAAAkMDFhMWY4NGEtOTVhYi00NzQ4LWI2NzgtNWEwNzQ5OGMzNmYyAAC2Zw&amp;ciFailurePanel=job">View more details</a> · <a href="https://github.com/DataDog/dd-trace-js/actions/runs/44707466068/job/136193117081">View in GitHub Actions</a>
    </details>
    </div>
    </blockquote>

    🧪 4 Tests failed in 1 job

    <blockquote>
    <div>

    <details open>
    <summary>Serverless | azure-functions — ❌ 4 tests failed</summary>

    <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzExMzA5?referrer=pr-comment&amp;ciFailurePanel=test&amp;testId=AwAAAaH4OQJ2jaZrbQAAABhBYUg0T1FKMkFBQm9YSnZRdzBDenNHZzcAAAAkZjFhMWY4MzktMzA5Zi00YjA5LTgzYTQtZDhkODE4NTY4YmNlAAAy4A">View more details</a> · <a href="https://github.com/DataDog/dd-trace-js/actions/runs//job/136190533960">View in GitHub Actions</a>

    <blockquote>

    <details>
    <summary>❌&nbsp;<code>esm with @azure/functions &gt;=4 (4.0.0) default configuration &#34;after all&#34; hook for &#34;propagates cosmosdb writes to azure function trigger&#34;</code>&nbsp;from&nbsp;<code>default configuration</code> &nbsp; <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzExMzA5?referrer=pr-comment&amp;ciFailurePanel=test&amp;testId=AwAAAaH4OQJ2jaZrbQAAABhBYUg0T1FKMkFBQm9YSnZRdzBDenNHZzcAAAAkZjFhMWY4MzktMzA5Zi00YjA5LTgzYTQtZDhkODE4NTY4YmNlAAAy4A" title="View in Datadog"><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/datadog_icon.svg" alt="View in Datadog" align="center" /></a></summary>

    Unexpected token &#39;P&#39;, &#34;PGCosmosEr&#34;... is not valid JSON
    
    SyntaxError: Unexpected token &#39;P&#39;, &#34;PGCosmosEr&#34;... is not valid JSON
        at JSON.parse (&lt;anonymous&gt;)
        at httpRequest (file:///tmp/23ff69e2b19cea26/27c1f32bd8cda25e/node_modules/@azure/cosmos/dist/esm/request/RequestHandler.js:104:16)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
        at async file:///tmp/23ff69e2b19cea26/27c1f32bd8cda25e/node_modules/@azure/cosmos/dist/esm/retry/retryUtility.js:65:30
        at async addDiagnosticChild (file:///tmp/23ff69e2b19cea26/27c1f32bd8cda25e/node_modules/@azure/cosmos/dist/esm/utils/diagnostics.js:44:26)
        at async addDiagnosticChild (file:///tmp/23ff69e2b19cea26/27c1f32bd8cda25e/node_modules/@azure/cosmos/dist/esm/utils/diagnostics.js:44:26)
        at async ClientContext.delete (file:///tmp/23ff69e2b19cea26/27c1f32bd8cda25e/node_modules/@azure/cosmos/dist/esm/ClientContext.js:285:30)
    ...
    

    </details>
    <details>
    <summary>❌&nbsp;<code>esm with @azure/functions &gt;=4 (4.17.1) default configuration &#34;after all&#34; hook for &#34;propagates cosmosdb writes to azure function trigger&#34;</code>&nbsp;from&nbsp;<code>default configuration</code> &nbsp; <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzExMzA5?referrer=pr-comment&amp;ciFailurePanel=test&amp;testId=AwAAAaH4ObJIvcL49wAAABhBYUg0T2JKSUFBQVBkN3BSdmdBZ1VneG4AAAAkZjFhMWY4M2EtMWFmZi00ZWFiLWE1MzItZmVlYzNiMGZjZDlhAAAJ_A" title="View in Datadog"><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/datadog_icon.svg" alt="View in Datadog" align="center" /></a></summary>

    Unexpected token &#39;P&#39;, &#34;PGCosmosEr&#34;... is not valid JSON
    
    SyntaxError: Unexpected token &#39;P&#39;, &#34;PGCosmosEr&#34;... is not valid JSON
        at JSON.parse (&lt;anonymous&gt;)
        at httpRequest (file:///tmp/23ff69e2b19cea26/15cb00589727553b/node_modules/@azure/cosmos/dist/esm/request/RequestHandler.js:104:16)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
        at async file:///tmp/23ff69e2b19cea26/15cb00589727553b/node_modules/@azure/cosmos/dist/esm/retry/retryUtility.js:65:30
        at async addDiagnosticChild (file:///tmp/23ff69e2b19cea26/15cb00589727553b/node_modules/@azure/cosmos/dist/esm/utils/diagnostics.js:44:26)
        at async addDiagnosticChild (file:///tmp/23ff69e2b19cea26/15cb00589727553b/node_modules/@azure/cosmos/dist/esm/utils/diagnostics.js:44:26)
        at async ClientContext.delete (file:///tmp/23ff69e2b19cea26/15cb00589727553b/node_modules/@azure/cosmos/dist/esm/ClientContext.js:285:30)
    ...
    

    </details>
    ↳ and 2 more — <a href="https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest&#43;%40git.commit.sha%3A55ad68f4e21729938894534f638e5276e8b2858f&#43;%40test.status%3Afail&amp;referrer=pr-comment&amp;start=1795163569000">View all</a>
    </blockquote>
    </details>
    </div>
    </blockquote>

    ℹ️ Info

    <details><summary>No other issues found (see more)</summary>

    ❄️ No new flaky tests detected
    </details>

    🔄 Datadog retried 1 test - 1 passed on retry <a href="https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest+%40git.commit.sha%3A55ad68f4e21729938894534f638e5276e8b2858f+%40test.is_retry%3Atrue+AND+%28%40test.retry_reason%3Aauto_test_retry+OR+%28-%40test.retry_reason%3A%2A+AND+-%40test.is_new%3Atrue%29%29&referrer=pr-comment" title="View in Datadog"><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/datadog_icon.svg" alt="View in Datadog" align="center" /></a>

    🎯 Code Coverage (<a target='_blank' href='https://app.datadoghq.com/ci/code-coverage/github.com%2Fdatadog%2Fdd-trace-js/pull-requests/11309'>details</a>)<br>• <strong><span title="Percentage of modified executable lines covered by tests in this PR">Patch Coverage</span></strong>: 100.00%<br>• <strong><span title="Percentage of all executable lines covered by tests in the entire codebase">Overall Coverage</span></strong>: 98.55% <span title="Change in overall coverage compared to the base branch">(-0.01%)</span><br>

    Useful? React with 👍 / 👎

    <sub>
    This comment will be updated automatically if new data arrives. <br />
    🔗 Commit SHA: 9d58ea1 | <a href="https://docs.datadoghq.com/integrations/guide/source-code-integration/#pr-comments">Docs</a> | <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzExMzA5?referrer=pr-comment">View more details</a> | Give us <a href="https://dd.enterprise.slack.com/archives/C07E3U2QRMM">feedback</a>!
    </sub>

    pr-commenter[bot] pr-commenter[bot] commented on Nov 18, 2026 14:34 UTC
    Bot

    Benchmarks

    Benchmark execution time: 2026-11-20 09:21:32

    Comparing candidate commit 9d58ea19f54574bed93f8549f90c8e0ad40ccb94 in PR branch alberto.vara/aiguard-mcp-3-openai-link with baseline commit b22c429f1de3f27201fdeb09754a37b8ea7bbf9b in branch alberto.vara/aiguard-mcp-2-calltool-v1.

    📊 Benchmarking dashboard

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

    <details>
    <summary><h3>Explanation</h3></summary>

    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.

    <details>
    <summary><h4>More details about the CI and significant changes</h4></summary>

    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 ----------------------------------'
    

    </details>

    </details>

    <details>
    <summary><h3>Unstable benchmarks</h3></summary>

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

    scenario:appsec-appsec-enabled-20

  • unstable max_rss_usage [-88.885MB; +21.345MB] or [-37.027%; +8.892%]
  • scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-20

  • unstable max_rss_usage [-32.530MB; +28.870MB] or [-9.028%; +8.012%]
  • scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-24

  • unstable max_rss_usage [-21.876MB; +15.606MB] or [-5.986%; +4.270%]
  • scenario:debugger-line-probe-with-snapshot-default-20

  • unstable max_rss_usage [-4.271MB; +9.268MB] or [-3.182%; +6.905%]
  • scenario:encoders-0.4-immediate-flush-20

  • unstable max_rss_usage [-2.281MB; +6.532MB] or [-2.677%; +7.666%]
  • scenario:openfeature-initialization-configuration-20

  • unstable max_rss_usage [-4663.063KB; +3072.154KB] or [-6.215%; +4.095%]
  • scenario:openfeature-initialization-configuration-26

  • unstable cpu_user_time [-108.142ms; +68.422ms] or [-6.417%; +4.060%]

  • unstable execution_time [-107.158ms; +70.330ms] or [-6.124%; +4.019%]
  • scenario:openfeature-initialization-error-20

  • unstable max_rss_usage [-6.496MB; +3.327MB] or [-8.463%; +4.334%]
  • scenario:openfeature-scale-full-26

  • unstable max_rss_usage [-15.564MB; +46.166MB] or [-6.865%; +20.363%]
  • scenario:plugin-graphql-long-with-depth-off-26

  • unstable cpu_user_time [-352.482ms; +571.920ms] or [-5.376%; +8.723%]

  • unstable execution_time [-370.401ms; +599.801ms] or [-5.541%; +8.973%]

  • unstable max_rss_usage [-27.606MB; +52.370MB] or [-12.678%; +24.052%]

  • unstable throughput [-28.847op/s; +18.713op/s] or [-8.494%; +5.510%]
  • scenario:plugin-graphql-long-with-depth-on-max-26

  • unstable max_rss_usage [-16.506MB; +60.914MB] or [-7.139%; +26.347%]
  • </details>

    avara1986 avara1986 commented on Nov 30, 2026 08:25 UTC
    Author

    This PR used the RFC v1.0 contract (configuration fingerprint server IDs, URL origin only). It is replaced by #11535, which follows RFC v2.0 (request-local server IDs, URL with path, command program name) and is based on the current master. The full stack is #11533 to #11537.

    Reviewers
    None requested
    Assignees
    avara1986 avara1986
    Labels
    risk: low confidence: 72.1% 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: 80.5% (HIGH) · Higher = larger blast radius
    80.5%
    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: 72.1% · Lower = rushed or shallow review
    72.1%
    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: 22.5% · Safe to merge
    22.5%