---
title: "Connect Microsoft Defender to AI Agents: Automate Response & Assets"
slug: connect-microsoft-defender-to-ai-agents-automate-response-assets
date: 2026-11-22
author: Nachi Raman
categories: ["AI & Agents"]
excerpt: "Learn how to connect Microsoft Defender to AI agents using Truto's tools endpoint to automate alert triage, device isolation, and vulnerability audits."
tldr: "Give your AI agent secure, programmatic access to Microsoft Defender. Learn to bind Truto's tools to LangChain, handle rate limits, and build autonomous workflows for alert triage and device isolation."
canonical: https://truto.one/blog/connect-microsoft-defender-to-ai-agents-automate-response-assets/
---

# Connect Microsoft Defender to AI Agents: Automate Response & Assets


You want to connect Microsoft Defender to an AI agent so your system can independently read alerts, triage security events, isolate compromised machines, and trigger live response workflows based on organizational context. Here is exactly how to do it using Truto's `/tools` endpoint and SDK, bypassing the need to construct and maintain a custom Microsoft Defender API integration from scratch.

Giving a Large Language Model (LLM) [read and write access](https://truto.one/connect-ai-agents-to-readwrite-in-salesforce-hubspot/) to your enterprise security infrastructure is a high-stakes engineering challenge. You either spend months building, securing, and updating a custom connector, or you rely on a managed infrastructure layer that handles the boilerplate and schema mapping for you. If your team uses ChatGPT, check out our guide on [connecting Microsoft Defender to ChatGPT](https://truto.one/connect-microsoft-defender-to-chatgpt-resolve-alerts-triage/), or if you are building on Anthropic's models, read our guide on [connecting Microsoft Defender to Claude](https://truto.one/connect-microsoft-defender-to-claude-audit-vulnerabilities-risks/). For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for Microsoft Defender, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex security operations workflows. For a deeper look at the architecture behind this approach, refer to our research on [architecting AI agents and the SaaS integration bottleneck](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/).

## The Engineering Reality of the Microsoft Defender API

Giving an LLM access to external systems sounds simple in a prototype. You write a standard function that makes a fetch request and wrap it in an `@tool` decorator. In production against a complex enterprise security product like Microsoft Defender, this approach collapses.

Microsoft Defender's API introduces several specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning capabilities.

### Delegated Permission Sprawl and Scope Granularity

Microsoft Defender enforces a highly granular, heavily delegated permission model. Unlike simpler SaaS tools where a single API token grants broad read/write access, Defender requires specific scopes for nearly every distinct operation. 

For example, retrieving a list of alerts requires `Alert.ReadWrite`. But if your agent decides it needs to isolate the machine associated with that alert, it cannot use the same baseline permissions - it specifically needs `Machine.Isolate`. If it wants to fetch the logged-on users for that machine, it needs `User.Read.All`. If you expose the raw API to an LLM, the model must somehow understand which endpoints correlate to which OAuth scopes, leading to inevitable authentication errors during complex reasoning chains. A unified tool layer abstracts the endpoint routing, allowing the LLM to simply call `microsoft_defender_machines_isolate` without worrying about the underlying Graph API permission matrix.

### Complex OData Queries and Nested Pagination

Microsoft Defender relies heavily on OData query parameters (`$filter`, `$top`, `$skip`) for data retrieval. LLMs are notoriously bad at generating syntactically correct OData strings. If you ask an agent to "find all high severity alerts from the last 24 hours", a raw API integration expects the LLM to generate a URL-encoded string like `$filter=severity eq 'High' and alertCreationTime ge 2024-03-14T00:00:00Z`.

Furthermore, Defender's pagination often utilizes skip tokens and link headers that expire or require precise sequential handling. Expecting an LLM to manage stateful pagination cursors across multiple reasoning steps is a guaranteed failure path. The tools provided by Truto handle all query parameter processing and pagination natively, exposing a predictable, flat JSON schema to the agent.

### Strict Rate Limiting Without Built-In Retries

Security APIs are heavily throttled to prevent abuse and denial-of-service, and Microsoft Defender is no exception. It enforces strict rate limits based on tenant and application quotas. 

**A critical architectural note:** Truto does not retry, throttle, or apply backoff on [rate limit errors](https://truto.one/how-to-handle-third-party-api-rate-limits-when-an-ai-agent-is-scraping-data/). When the upstream Microsoft Defender API returns an HTTP 429 Too Many Requests, Truto passes that error directly to the caller. However, Truto normalizes the upstream rate limit information into standardized headers (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`) per the IETF specification. The caller (your agent framework or application logic) is entirely responsible for implementing retry logic and exponential backoff. 

If your agent hits a 429, you must catch the error, read the `ratelimit-reset` header, pause the execution thread, and retry. Do not assume the integration layer will absorb these spikes for you.

## Building Multi-Step Workflows

Before writing integration code, you must decide what layer your agent talks to. Direct API tools (one tool per raw Defender endpoint) push vendor quirks into the LLM's context window. A unified tool layer collapses these complexities behind a stable schema.

Truto provides a set of tools for your LLM frameworks by offering a description and schema for all the Methods defined on the Resources for an integration. We call the `/integrated-account/:id/tools` endpoint on the Truto API to return all of these Proxy APIs with their descriptions and schemas, creating Tools that frameworks can bind to natively.

Here is how an [autonomous security agent](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/) processes an event using a unified tool layer:

```mermaid
sequenceDiagram
    participant User as Security Analyst
    participant Agent as AI Agent (LangChain)
    participant Truto as Truto Tool Manager
    participant Upstream as Upstream API (Defender)

    User->>Agent: "Triage new alerts and isolate high-risk devices"
    Agent->>Truto: fetch tools via /tools endpoint
    Truto-->>Agent: returns list_all_alerts, isolate_machine, etc.
    Agent->>Agent: LLM plans execution steps
    
    Agent->>Truto: Call list_all_alerts(severity="High")
    Truto->>Upstream: GET /alerts?$filter=severity eq 'High'
    Upstream-->>Truto: 200 OK (Alerts JSON)
    Truto-->>Agent: Normalized Alerts Data
    
    Agent->>Agent: LLM analyzes alerts, identifies Machine ID
    
    Agent->>Truto: Call microsoft_defender_machines_isolate(machine_id, comment)
    Truto->>Upstream: POST /machines/{id}/isolate
    Upstream-->>Truto: 201 Created (Action Status)
    Truto-->>Agent: Isolation Confirmation
    
    Agent-->>User: "Triage complete. 2 high-risk machines isolated."
```

By binding these tools directly to the model, the LLM only ever chooses from stable function names. It never invents OData fragments. Invalid arguments are rejected by the strict JSON schema before they hit the upstream API, ensuring that a broken tool call fails fast.

## Hero Tools for Microsoft Defender

Rather than exposing hundreds of raw endpoints, your agent requires high-leverage operations that map to actual security workflows. Here are the core tools you should provide to an autonomous security agent.

### Get Single Alert by ID

Retrieves a specific Alert by its ID, pulling the full contextual payload required for triage.

> "Retrieve the full details for alert ID 'da72b3-9992'. I need to see the severity, category, and the associated machine ID to determine the next steps."

**Tool Name:** `get_single_microsoft_defender_alert_by_id`
**Contextual Note:** This tool is the starting point for most investigations. Agents should use this to gather facts before taking destructive actions or escalating to a human. Requires `Alert.ReadWrite`.

### Update an Alert

Updates properties of an existing Alert, such as resolving it, changing its status, or assigning it to a specific queue.

> "Mark alert ID 'da72b3-9992' as 'Resolved' with the classification 'TruePositive'."

**Tool Name:** `update_a_microsoft_defender_alert_by_id`
**Contextual Note:** Used by the agent to maintain state within the Defender dashboard. If the agent successfully remediates an issue, it should use this tool to close the loop so human analysts do not duplicate effort.

### Isolate Machine

Isolates a device from accessing the external network, containing potential lateral movement while maintaining connectivity to the Defender service.

> "Isolate the machine with ID 'machine-883a' immediately. Leave a comment that this was triggered by the autonomous containment agent due to suspected ransomware activity."

**Tool Name:** `microsoft_defender_machines_isolate`
**Contextual Note:** This is a high-impact remediation tool. Ensure your agent prompts or system prompts mandate a strict threshold of certainty (or human-in-the-loop approval) before executing this tool. Requires `Machine.Isolate`.

### Run Antivirus Scan

Initiates a Microsoft Defender Antivirus scan on a specific device to confirm the presence of malicious files post-alert.

> "Trigger a 'Full' antivirus scan on machine ID 'machine-883a'. Comment that this is a follow-up to the recent suspicious file drop alert."

**Tool Name:** `microsoft_defender_machines_run_antivirus_scan`
**Contextual Note:** A low-risk investigative tool. The agent can trigger this while waiting for human input or as a prerequisite step before deciding to fully isolate a machine. Requires `Machine.Scan`.

### Run Live Response

Runs a sequence of live response commands on a device, allowing the agent to gather forensics or execute scripts directly on the endpoint.

> "Execute the standard forensic data collection live response script on machine ID 'machine-883a'."

**Tool Name:** `microsoft_defender_machines_run_live_response`
**Contextual Note:** Highly powerful for deep investigations. The agent can use this to pull specific logs or processes that are not surfaced in the standard alert payload. Requires `Machine.LiveResponse`.

### List Machine Vulnerabilities

Retrieves a collection of discovered vulnerabilities related to a given device ID, providing context on the machine's risk profile.

> "List all discovered vulnerabilities for machine ID 'machine-883a' so I can determine if the recent alert is exploiting a known unpatched CVE."

**Tool Name:** `list_all_microsoft_defender_machine_vulnerabilities`
**Contextual Note:** Essential for root cause analysis. When an alert fires, the agent should cross-reference the machine's vulnerabilities to understand the attack vector. Requires `Vulnerability.Read`.

To view the complete schema details and the full list of available tools, review the [Microsoft Defender integration page](https://truto.one/integrations/detail/msdefender).

## Workflows in Action

With the tools bound to your agent, you can prompt the system to execute complex, multi-step operations that would traditionally require a human analyst to pivot between multiple dashboards.

### Scenario 1: Autonomous Alert Triage and Containment

When a high-severity alert fires, time to containment is critical. An AI agent can parse the alert, evaluate the risk, and contain the threat in seconds.

> "Fetch the details for alert ID '8829-alpha'. If the alert category is 'Malware' and the severity is 'High', trigger a full antivirus scan on the associated machine. If the alert title contains 'Ransomware', isolate the machine immediately and update the alert status to 'InProgress'."

**Execution Steps:**
1. The agent calls `get_single_microsoft_defender_alert_by_id` with ID '8829-alpha'.
2. It parses the response, noting the `category`, `severity`, and `machineId`.
3. Because the category is Malware and severity is High, it calls `microsoft_defender_machines_run_antivirus_scan` passing the `machineId`.
4. It evaluates the title. Finding 'Ransomware', it calls `microsoft_defender_machines_isolate` to cut the machine off from the network.
5. Finally, it calls `update_a_microsoft_defender_alert_by_id` to update the status to 'InProgress'.

**Result:** The user gets a confirmation that the ransomware alert was validated, a scan was initiated, the compromised host was isolated from the network, and the ticket was updated - all within seconds of the alert triggering.

### Scenario 2: Vulnerability Context Enrichment

Security teams often suffer from alert fatigue because alerts lack context. An agent can enrich an alert with vulnerability data before a human even looks at it.

> "Look up the machine associated with alert ID '774-beta'. Once you have the machine ID, list all of its vulnerabilities. Summarize any critical CVEs found on this machine and append that summary as a comment to the original alert."

**Execution Steps:**
1. The agent calls `get_single_microsoft_defender_alert_by_id` to extract the `machineId`.
2. It calls `list_all_microsoft_defender_machine_vulnerabilities` using that `machineId`.
3. The LLM processes the returned JSON, filtering for critical CVEs.
4. The agent formulates a summary string.
5. It calls `update_a_microsoft_defender_alert_by_id` to append the vulnerability summary into the alert's comments or description.

**Result:** When the security analyst opens the alert, they immediately see a machine-generated summary of the host's unpatched vulnerabilities, providing instant context on how the attack likely occurred.

## Implementing the Connection

To build these workflows, you need to fetch the tools from Truto and bind them to your agent. Below is an example using TypeScript and LangChain to dynamically load Microsoft Defender tools.

Remember that Truto passes upstream HTTP 429 rate limit errors directly to you. You must wrap your agent execution or tool invocation in a retry block that respects the `ratelimit-reset` headers.

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
// TrutoToolManager handles fetching schemas from /tools and formatting them for LangChain
import { TrutoToolManager } from "truto-langchainjs-toolset"; 

async function runSecurityAgent() {
  // 1. Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4-turbo-preview",
    temperature: 0,
  });

  // 2. Fetch Microsoft Defender tools from Truto for a specific integrated account
  const trutoManager = new TrutoToolManager({
    trutoApiKey: process.env.TRUTO_API_KEY,
    integratedAccountId: "YOUR_MS_DEFENDER_ACCOUNT_ID"
  });

  // Optionally filter tools if you only want read operations or specific methods
  const tools = await trutoManager.getTools();

  // 3. Create the prompt instruction
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are a senior SOC analyst. You have access to Microsoft Defender tools. Execute triage and remediation workflows accurately. If a tool fails with a rate limit error, you must notify the user."],
    ["human", "{input}"],
    ["placeholder", "{agent_scratchpad}"],
  ]);

  // 4. Bind the tools and create the agent
  const agent = createToolCallingAgent({
    llm,
    tools,
    prompt,
  });

  const agentExecutor = new AgentExecutor({
    agent,
    tools,
    // Ensure the agent surfaces errors gracefully rather than crashing
    handleParsingErrors: true,
  });

  // 5. Execute a workflow (Wrap in your own rate-limit backoff logic if needed)
  try {
    const result = await agentExecutor.invoke({
      input: "Fetch the details for alert ID '8829-alpha'. If the severity is 'High', trigger an antivirus scan on the machine."
    });
    console.log("Agent Result:", result.output);
  } catch (error) {
    // Inspect the error for 429 status and read ratelimit-reset headers
    if (error.status === 429) {
      console.warn("Rate limit exceeded. Implement backoff based on ratelimit-reset header.");
    }
    console.error("Execution failed:", error);
  }
}

runSecurityAgent();
```

Because the Truto tools endpoint dynamically returns JSON schemas generated from the underlying API integration, any updates made to the integration schema in the Truto UI immediately reflect in the tools available to your agent. There is no need to redeploy your agent code when adding a new Defender capability.

## Strategic Wrap-up

Building autonomous security agents requires rock-solid infrastructure. If your agent is fighting with OAuth token lifecycles, OData query strings, or missing permission scopes, it cannot effectively secure your environment. 

By leveraging a unified tool layer, you strip away the API boilerplate and present your LLM with a clean, deterministic set of actions. You dictate the error handling, you manage the rate limit backoff, and the agent focuses entirely on executing the security playbook.

> Stop writing defensive integration code and start building autonomous workflows. Talk to our team to see how Truto can power your AI agents today.
>
> [Talk to us](https://truto.one/book-a-demo/)
