Microsoft Defender AI agent runtime protection, part 7: from Defender detection to a Conditional Access block

Part 7 - from Defender detection to a Conditional Access block
Part 7 - from Defender detection to a Conditional Access block

In the previous part: we moved AI agent governance from Defender into Agent 365 - one inventory of agents, their owners and the controls that come with agent identities.

Parts 1 to 6 were about seeing local AI agents, controlling what they connect to and governing them in Agent 365. Part 7 asks the next question: when someone runs an agent you have not approved, can you stop them signing in? At Ignite 2026 Microsoft announced a chain for exactly that - Entra Agent ID for local agents, an Intune compliance setting for unapproved agents, and a Conditional Access block. Most write-ups so far summarise the announcement. This post tests it in a lab and reports what actually happened.

Short version: the Microsoft-native route needs Agent 365, which this E5 lab does not have. So I built the chain from E5 parts. The device-compliance route stalled. The identity route worked end to end, from an unapproved agent launching to the user being blocked at sign-in.

The lab

  • One onboarded Windows 11 VM, purview, used throughout the series.
  • Test user edge: Microsoft 365 E5, no Entra roles, local admin on the VM.
  • The admin account is excluded from every policy in this post, so a noncompliant lab device can never lock out the admin.
  • Approved agents: Claude Code (CLI and VS Code), Claude Desktop and GitHub Copilot (CLI and VS Code). Anything else is unapproved - block-all by default, as in Part 5.
  • The unapproved test agent: Gemini CLI, installed by edge with npm.

Before testing, the VM carried 31 alerts from earlier parts of the series, which left it at High device risk. I closed those as Benign Positive - Security Testing and dismissed the user risk, so every result below starts from a clean baseline.

What Defender already knows

Advanced hunting against AgentsInfo shows six local agents discovered on purview: Claude Code, the Claude Code and GitHub Copilot VS Code extensions, GitHub Copilot CLI, Claude Desktop and Gemini CLI.

AgentsInfo
| where Timestamp > ago(30d)
| where Platform == "LocalAgents"
| summarize arg_max(Timestamp, *) by Name
| project Timestamp, Name, Version, AgentId
AgentsInfo - six local agents discovered on the lab VM
AgentsInfo - six local agents discovered on the lab VM

The table now has an EntraAgentID column, which was not there when Part 3 was written. That is where the Ignite preview records the Entra identity given to a discovered local agent. In this lab it is empty for every agent, and Entra ID > Agents > Overview agrees: no agent identities. Every action these agents take is still recorded against the signed-in user. Keep that in mind - it decides which Conditional Access policy can stop them.

Baseline - EntraAgentID is empty for every local agent
Baseline - EntraAgentID is empty for every local agent

Route A: Microsoft’s agent compliance setting

The announced Intune setting marks a device noncompliant when it runs an unapproved local agent. In an E5 tenant without Agent 365 it does not appear. Creating a Windows 10 and later compliance policy offers only the classic policy and an empty Templates list. The new Agents node in Intune is for Security Copilot agents, not local AI agents.

Intune compliance - no agent-specific profile type without Agent 365
Intune compliance - no agent-specific profile type without Agent 365

So Route A is out for most E5 customers today. The rest of this post is Route B: the same outcome built from parts you already own.

Route B, step 1: detect the unapproved agent

The scheduled rule

AgentsInfo has no DeviceId column. The device, user and vendor sit inside RawAgentInfo.localAgentMetadata, so the query pulls them out to give the detection the entities it needs.

// Detect-UnapprovedLocalAgent.kql
// cloud-secure.ai - Defender AI agent runtime protection, Part 7
// Raises an alert when Defender discovers a local AI agent that is not on the approved list.
// AgentsInfo has no DeviceId column - the device and user live in RawAgentInfo.localAgentMetadata.
// Block-all-by-default: anything not in ApprovedAgents alerts.
// Matches on name fragments: "Claude Code" also covers the VS Code Claude extension, "GitHub Copilot" covers CLI and VS Code.
let ApprovedAgents = dynamic(["Claude Code", "Claude Desktop", "GitHub Copilot"]);
AgentsInfo
| where Timestamp > ago(4h)
| where Platform == "LocalAgents"
| where not(Name has_any (ApprovedAgents))
| extend Meta = RawAgentInfo.localAgentMetadata
| extend DeviceId    = tostring(Meta.machineId),
         DeviceName  = tostring(Meta.deviceName),
         AccountUpn  = tostring(Meta.upn),
         AccountSid  = tostring(Meta.accountSid),
         Vendor      = tostring(Meta.vendor)
| summarize arg_max(Timestamp, *) by DeviceId, Name
| project Timestamp, DeviceId, DeviceName, AccountUpn, AccountSid,
          AgentName = Name, Vendor, Version, ReportId = tostring(AgentId)

Saved as a custom detection: every hour, High severity, entities mapped to Device (DeviceId) and User (AccountSid). Two gotchas from the rule wizard:

  • The alert description takes a maximum of three dynamic columns. Five were rejected with “Too many column names”.
  • A new rule queries 30 days on its first run. Without the ago(4h) filter inside the query, it would alert immediately on old discoveries.
The first-run warning - keep a time filter in the query
The first-run warning - keep a time filter in the query

Why one rule was not enough

AgentsInfo is a periodic inventory, not a live feed. In the lab its last report was hours old. And searching process events for “gemini” found nothing, because npm-installed agent CLIs run as node.exe - the agent name only appears in the command line. So I added a near-real-time (NRT) rule on DeviceProcessEvents:

DeviceProcessEvents
| where FileName =~ "node.exe"
| where ProcessCommandLine has "gemini-cli" or ProcessCommandLine has "@openai" or ProcessCommandLine has "qwen-code"
| project Timestamp, DeviceId, DeviceName, AccountName, AccountSid, InitiatingProcessAccountUpn, InitiatingProcessAccountObjectId, ProcessCommandLine, InitiatingProcessFileName, ReportId

The Continuous (NRT) option stayed greyed out until the query was this simple. NRT rules reject let, dynamic(), has_any, column renames and even comments, so the notes live in a README alongside the query in the repo.

The NRT rule - Continuous frequency
The NRT rule - Continuous frequency

Route B, step 2: the device route

The plan: a High alert raises the device risk, Intune marks the device noncompliant, and Conditional Access requires a compliant device.

The connector switch that is easy to miss

Intune only receives Defender’s device risk if, under Endpoint security > Microsoft Defender for Endpoint, Connect Windows devices version 10.0.15063 and above is switched on for compliance policy evaluation. In the lab it was off. With it off, a machine risk score setting silently does nothing. It is tenant-wide, so check the impact before switching it on.

Before - the Windows compliance connection switched off
Before - the Windows compliance connection switched off

Compliance policy and Conditional Access

A Windows compliance policy requiring a machine risk score at or under Low, marking the device noncompliant immediately. One lesson: I first assigned it to a user group containing edge, and it applied to zero devices. User-targeted compliance follows the device’s primary user, which on this VM is the admin. Compliance is a device state, so it now targets a device group containing only purview.

The Conditional Access policy targets the user: edge only, admin excluded, All resources, grant Require device to be marked as compliant, created in Report-only and then switched on. The Users pane now states that user policies apply when users access resources directly or through agents acting on their behalf - exactly the case for a local agent with no identity of its own. The new All agent resources option is for agent identities and needs Agent 365.

Conditional Access - user policies cover agents acting on the user's behalf
Conditional Access - user policies cover agents acting on the user’s behalf

Result: the device route stalled

edge installed Gemini CLI with npm and ran it. The NRT rule fired as High alerts within minutes, and Defender correlated them into one incident. The attack graph tells the story at a glance: the device, the user and the processes that triggered the alerts.

Attack graph - the lab device, the user and the agent processes, four High alerts
Attack graph - the lab device, the user and the agent processes, four High alerts

Drilling into the processes node shows why the NRT rule matches on the command line: both are node.exe, launched from edge’s npm folder. Nothing in the process name says Gemini.

Processes node - node.exe running from the user's npm folder
Processes node - node.exe running from the user’s npm folder

But the device risk level did not move: it was still None more than 30 minutes later.

Two High alerts, device risk still None
Two High alerts, device risk still None

Custom detection alerts did not feed device risk in this lab, so the device never became noncompliant and the compliant-device policy had nothing to act on. If you are planning this route, test it in your own tenant before relying on it.

Route B, step 3: the identity route

Since the agent acts as the user, the user is the better place to apply the control. Custom detections have a response action, Mark user as compromised, which sets the user’s Entra risk to High. Conditional Access can block on that.

The action stays greyed out until the query returns an Entra object ID. Adding InitiatingProcessAccountObjectId to the NRT query and mapping User > AadUserId to it unlocks it.

NRT rule - Mark user as compromised
NRT rule - Mark user as compromised

Then a second Conditional Access policy: edge, admin excluded, condition user risk High, grant Block access.

Conditional Access - user risk High
Conditional Access - user risk High

Result: blocked

edge ran Gemini CLI again. The NRT rule fired, ID Protection showed edge as Confirmed compromised with High risk, and the next sign-in was refused.

ID Protection - edge confirmed compromised, risk High
ID Protection - edge confirmed compromised, risk High
The end of the chain - sign-in blocked for an at-risk user
The end of the chain - sign-in blocked for an at-risk user

What worked, what didn’t

Link in the chainRoute A (Microsoft native)Route B (built from E5)
Detect the agentDefender local agent discoveryScheduled AgentsInfo rule plus NRT process rule - worked
Agent identityEntra Agent ID - needs Agent 365Not used; the agent acts as the user
Mark it riskyIntune agent compliance setting - not availableDevice risk: did not move. User risk via Mark user as compromised: worked
BlockAgent CA templates - need Agent 365CA user risk High โ†’ Block access - worked

Before you use this in production

  • It is a blunt instrument. Marking a user compromised blocks them everywhere, not just the agent. Running an unapproved CLI is a policy breach, not proof of compromise. Scope it to high-sensitivity groups, and have a fast path for an admin to dismiss the risk.
  • Keep the approved list current. Anything not on it is treated as unapproved, including a new version that reports a different name.
  • Exclude your admins from both policies, and start in Report-only.
  • Check the connector switch before trusting any machine risk compliance setting.

Licensing

  • Local agent discovery and custom detections: Defender for Endpoint P2.
  • Mark user as compromised and user risk in Conditional Access: Entra ID P2 (included in E5).
  • Compliance policy and compliant-device Conditional Access: Intune and Entra ID P1.
  • Entra Agent ID for local agents, the Intune agent compliance setting and the agent Conditional Access templates: Agent 365 or Microsoft 365 E7.

Next in the series

Next in the series: Part 8 looks at Route A properly - automatic Entra Agent IDs for local agents and the agent Conditional Access templates - and what changes when an agent gets an identity of its own.

The detection queries and the NRT README are in the GitHub repo for this series.

Data classification first, part 7: protecting Contosoโ€™s intellectual property with Microsoft Purview

Part 7 cover - Data classification first: protecting Contoso's intellectual property

What can DLP protect if nothing has been classified?

Very little. A DLP policy is only as good as the sensitive information types and labels behind it. If Contoso has never defined what its sensitive data looks like, DLP has nothing to look for.

Out of the box, Purview DLP recognises what Microsoft has already classified for every tenant: credit card numbers, PPSNs, IBANs, passport numbers, credentials. Useful, but none of it is Contoso’s. Not one built-in SIT knows what a Contoso project code, design specification, customer list or product roadmap looks like. Without classification, a DLP policy is left with two options:

  • Match on Microsoft’s built-in types only. Personal and financial data is protected; Contoso’s intellectual property walks straight past every rule.
  • Fall back on context alone. Block every attachment to an external domain, every upload to an AI app, every file copied to USB. That stops IP, and it stops the business with it. Users find a workaround within a week, and the policy is rolled back to audit within a month.

Blind or blunt: the policy either misses what matters or blocks everything. Classification is what gives it a third option – block what is sensitive and let everything else through.

The same applies to every control I have written about this month. I have blocked unsanctioned MCP servers, inspected traffic to AI apps, governed agents in Agent 365 and stopped credentials leaking from Exchange and Teams. Each of those posts answers the question where is this data allowed to go? None of them can answer the question that has to come first: what is this data? A network indicator blocks a destination whatever is sent to it. A Copilot policy can only exclude content that carries a label. Inline DLP can only block a prompt that matches a SIT.

The credentials post came closest to saying this. It works because Microsoft has already done the classification for you: the All Credential Types SIT ships ready-made, so the policy simply has to be switched on. Intellectual property gets no such head start.

The post that should have come first. This is the seventh post in the run, but it is the foundation the other six stand on. If you are new to the series, start here, then read the AI agent runtime protection series, Entra Internet Access inline DLP and Stopping leaked credentials with Purview DLP.

This post covers the classification methods Microsoft Purview offers, the different types of DLP that act on them, where you can find sensitive data already sitting at rest, and how to put it all together around the asset that is hardest to protect and most damaging to lose: Contoso’s intellectual property.

Key terms

If you are new to Purview, these are the terms the rest of the post relies on:

  • DLP (data loss prevention) – policies that detect sensitive content and audit, warn or block when someone tries to move it.
  • SIT (sensitive information type) – a pattern Purview recognises, such as a credit card number: usually a regular expression (regex) plus supporting keywords.
  • Confidence level – how sure Purview is that a SIT match is real: Low (65), Medium (75) or High (85). More supporting evidence means higher confidence.
  • Proximity – how close, in characters, a supporting keyword must be to the pattern to count as evidence.
  • Sensitivity label – a tag such as Highly Confidential written into a file or email, which can also encrypt it.
  • EDM (exact data match) – matching on the actual values in your own data, such as real customer account numbers, rather than on a pattern.
  • Document fingerprint – a SIT built from a blank form or template, which matches any document written on it.
  • Trainable classifier – a machine learning model that recognises a type of document, such as source code or a patent.
  • Inline DLP – DLP applied to web traffic as it leaves, either inside Edge for Business or at the network through Global Secure Access (GSA), Microsoft’s cloud network security service.
  • MCP server – a service an AI agent connects to for extra tools or data.

Why the earlier controls worked

It is worth looking back at why the earlier posts produced clean blocks, because the answer is classification every time.

Post What made it work What it cannot see without classification
Stopping leaked credentials Microsoft ships the All Credential Types SIT, with checksums and patterns already built Anything that is not a credential
Entra Internet Access inline DLP A custom SIT for Contoso project references, imported before the policy was built, with a supporting keyword required within 300 characters for a High confidence match A design document or roadmap that contains no project reference
Parts 4 and 5: MCP server blocking Defender indicators block the destination outright What the agent sends to an approved server
Part 6: Agent 365 governance Approval, ownership and Conditional Access for agents Which content an approved agent can ground on

The pattern is clear. Destination controls are binary: a server is allowed or it is not. Once a destination is approved, whether that is a sanctioned MCP server, Copilot or an external partner, the only thing that can stop the wrong content reaching it is a control that knows what the content is.

Why intellectual property is the hard case

Most DLP deployments start with personal and financial data because it is easy. A credit card number has a checksum. A PPSN has a fixed format. Microsoft ships hundreds of SITs for these, and a policy can be live in an afternoon.

Intellectual property has none of that. There is no built-in SIT for Contoso’s product roadmap, a formulation, a tender response or the code behind Contoso’s custom-developed pricing application. IP is defined by what a document is and who it belongs to, not by a pattern inside it. That makes it the case where classification matters most, and the one most organisations never get to.

Contoso’s crown jewels

Before choosing a classification method, list what actually needs protecting. For Contoso, whose flagship R&D programme – codename Project Halcyon – is the running example in this post:

IP asset What it looks like Best classification method
Project and product codes CONTOSO-FIN-204815-K in specs, emails and chats Custom SIT (regex and keywords)
Patent drafts and design specifications Written on a standard Contoso template Document fingerprinting
Custom-developed applications The source code, scripts and configuration behind Contoso’s in-house apps, in any language Pretrained Source Code classifier
Customer and supplier lists Real names and account numbers from the CRM Exact data match (EDM)
Strategy, M&A and roadmaps Free-form documents and slide decks Pretrained or custom trainable classifier, plus a manual label
Everything on the Engineering site Whatever the team saves there Default sensitivity label on the site library

No single method covers the list. That is the point of this post: IP protection is built from several classification methods layered together, then enforced by several types of DLP.

Key risks of losing Contoso’s intellectual property

Scenario What could happen Risk level
The departing engineer Design files and the code of Contoso’s custom-developed apps copied to USB or a personal cloud account in the weeks before a resignation. โ— Critical
Pasted into an AI app A roadmap or specification pasted into a consumer AI tool to summarise it, where it may be retained or used for training. โ— Critical
Sent to an AI agent’s tools A coding agent passes the code of a custom-developed Contoso app to an approved MCP server, which logs it. โ— High
Oversharing through Copilot Copilot grounds an answer on an M&A document a user could technically open but should never have seen. โ— High
External sharing A patent draft emailed to an external partner before filing, or shared through an “anyone” link. โ— Critical
Loss of trade secret status Information only qualifies as a trade secret where reasonable steps were taken to keep it secret. Unclassified, unprotected IP weakens that position in any dispute. โ— High

The last row deserves attention. Under the EU Trade Secrets Directive, transposed in Ireland by the European Union (Protection of Trade Secrets) Regulations 2018, information is protected only where its holder took reasonable steps to keep it secret. Classification and DLP are not legal advice, but they are evidence of exactly those steps. Discuss the specifics with your legal team.

Methods of classification

Microsoft Purview classifies content in three ways: manually, by automated pattern matching, and with trainable classifiers. In practice those break down into the methods below.

Purview classification methods - manual labelling, pattern matching and trainable classifiers
Method How it decides Strong for Weak for
Manual sensitivity labels The author decides Strategy and M&A, where context matters Consistency at scale
Default labels Where the file is saved, or who created it Engineering and R&D sites Content that leaves that location
Built-in SITs Microsoft patterns, checksums and keywords Credentials, PII, financial data Anything unique to Contoso
Custom SITs Your own regex and keywords Project codes, part numbers IP with no identifier in it
Exact data match Hashed values from your own source table Customer lists, product catalogues Unstructured documents
Document fingerprinting Similarity to a standard template Patent and design specification forms Documents not written on the template
Pretrained classifiers Machine learning on what the item is Source code, IP, M&A, business plans Precision; encrypted items
Custom trainable classifiers Machine learning trained on your own samples A document category only Contoso has Non-English content; quick wins

Rule of thumb: if the IP carries an identifier, use a custom SIT. If it lives in a table, use EDM. If it is written on a standard template, use a fingerprint. If it is none of those, use a trainable classifier. And label anything only a person can judge.

One place to manage all of this. MC1486289 introduces a unified Classification Management experience in the Purview portal. It brings sensitive information types, Exact Data Match, trainable classifiers and document fingerprinting into one view, with search, filters and guidance in the creation flow on which method suits your scenario – the same decision the table above walks through. Public preview began in October 2026, with general availability scheduled from mid to late November 2026. Portal paths in this post may change as it rolls out.

MC1486289 - Microsoft Purview Unified Classification Management Experience, published 2 October 2026

Sensitivity labels: manual, default and automatic

A sensitivity label is the only classification that travels with the file. Every other method detects content each time it is evaluated; a label is written into the file’s metadata, stays with it wherever it goes, and can apply encryption that keeps working outside Contoso entirely.

  • Manual. The author chooses. Best where only a person can judge sensitivity, such as a board paper or an acquisition target.
  • Default. A label applied by policy or by a SharePoint document library. Everything saved to the Contoso R&D library is Highly Confidential – Contoso IP unless someone changes it.
  • Automatic. Client-side auto-labelling recommends or applies a label in the Office apps as a user works. Service-side auto-labelling applies labels to content already at rest in SharePoint, OneDrive and Exchange. Both use the SITs, fingerprints and classifiers described below as conditions.

Labels matter most once content is encrypted. Trainable classifiers only work on items that are not encrypted, so once a label encrypts a file, content-based detection can no longer read it. From that point on, the label is the only thing downstream controls can recognise, which is why label-based DLP conditions are not optional.

Sensitive information types

A SIT is a pattern, usually a regular expression, supported by keywords, checksums and a proximity window, with confidence levels for how much evidence was found. Microsoft ships several hundred. The credentials post used the bundled All Credential Types SIT, and it belongs in any IP policy too: source code and configuration files are where secrets hide.

For Contoso’s own identifiers you write a custom SIT. The project reference SIT used in the inline DLP post is a good model:

\bCONTOSO-[A-Z]{3}-\d{6}-[A-Z]\b
  • High confidence (85) – the pattern plus a keyword such as “project reference” or “confidential project” within 300 characters.
  • Medium confidence (75) – the pattern on its own.

The fixed CONTOSO- prefix means it cannot collide with any built-in type, and the next two sections explain why that matters. The New-ContosoSIT.ps1 script in the inline DLP repository builds and imports the rule package in one run, and takes -Prefix and -DisplayName parameters so it can be reused for any client.

A regex is not a SIT

regex101.com is the best place to build the pattern. Paste a candidate regex and a block of sample text and it highlights every match as you type, explains each token in plain English, and lets you keep a set of test strings that should and should not match. For Contoso, that is where you prove \bCONTOSO-[A-Z]{3}-\d{6}-[A-Z]\b matches CONTOSO-FIN-204815-K and rejects a five-digit number, a missing prefix or a reference glued to another word – before it goes anywhere near Purview.

What regex101 cannot tell you is everything else the pattern will match across Exchange, SharePoint, OneDrive and Teams. Purview’s regex engine is not one of regex101’s flavours either, so a pattern that works there still has to be proved in Purview. regex101 proves the pattern; it does not prove the SIT.

A loose pattern such as \d{6} or [A-Z]{3}-\d{6} will happily match phone numbers, dates, order numbers, postcodes and invoice references, and it will overlap with a large share of Microsoft’s built-in SITs, most of which are numeric identifiers. Deploy it in a blocking DLP rule and the service desk will know about it within the hour.

To see how many built-in SITs your tenant has for a new pattern to collide with, run:

Get-DlpSensitiveInformationType | Where-Object Publisher -eq 'Microsoft Corporation' | Measure-Object

What turns a regex into a usable SIT is the evidence around it:

  • A distinctive primary element. The fixed CONTOSO- prefix rules out almost every accidental match before anything else is checked.
  • Supporting keywords within a proximity window. “Project reference”, “codename” or “confidential project” within 300 characters is what lifts a match to High confidence. A string that merely looks like a reference stays at Medium.
  • Confidence levels in the policy. Block on High; use Medium for audit or a policy tip while you tune.
  • Testing against real content. The Test option on the SIT, fed with samples that should and should not match, is where false positives show up. regex101 proves the pattern; the Test option proves the SIT.

Inside the Contoso SIT: how proximity decides

A custom SIT is defined in an XML rule package and imported into Purview. This is the core of the Contoso Project Reference SIT used in the inline DLP post. Three parts of it do the work:

<Entity id="b6ebde7d-..." patternsProximity="300" recommendedConfidence="85">
  <!-- High confidence: pattern + supporting keyword within 300 characters -->
  <Pattern confidenceLevel="85">
    <IdMatch idRef="Regex_contoso_project_ref"/>
    <Match idRef="Keyword_contoso_project_ref"/>
  </Pattern>
  <!-- Medium confidence: pattern alone -->
  <Pattern confidenceLevel="75">
    <IdMatch idRef="Regex_contoso_project_ref"/>
  </Pattern>
</Entity>

<Regex id="Regex_contoso_project_ref">\bCONTOSO-[A-Z]{3}-\d{6}-[A-Z]\b</Regex>

<Keyword id="Keyword_contoso_project_ref">
  <Group matchStyle="word">
    <Term>project reference</Term>
    <Term>project ref</Term>
    <Term>project code</Term>
    <Term>codename</Term>
    <Term>confidential project</Term>
    <Term>Contoso project</Term>
  </Group>
</Keyword>
  • The regex is the primary element. Nothing is evaluated unless the text contains CONTOSO-, three letters, six digits and a check letter, bounded by word breaks. Purview matches it without regard to case.
  • The keywords are supporting evidence. On their own they match nothing. They only matter when they appear near a project reference, and matchStyle="word" means they must be whole words: “codename” counts, “codenames” does not.
  • The proximity window is 300 characters. patternsProximity="300" sets it: A keyword counts only if it falls within 300 characters of the reference. Inside the window, the match is High confidence (85). Outside it, or with no keyword at all, the match drops to Medium (75).

The DLP rule in the inline DLP post blocks at High confidence only. That one setting is what keeps false positives down: a reference has to look like a Contoso project code and be described as one before anything is blocked. A Medium match is still recorded, so it can drive an audit rule or a policy tip while you tune.

Here is how that plays out for prompts typed into an AI app, with the policy blocking at High confidence:

Prompt SIT match Blocked? Why
“Summarise the risks on project reference CONTOSO-FIN-204815-K for the board” High (85) Yes Pattern plus keyword in the same sentence
“Codename CONTOSO-RND-550731-H: draft a launch plan for this product” High (85) Yes Pattern plus keyword
“Rewrite this update – Contoso project CONTOSO-OPS-118204-M is three weeks late” High (85) Yes Pattern plus keyword
“Here is the spec for confidential project CONTOSO-ENG-904117-P. Find the weaknesses” High (85) Yes Pattern plus keyword
“project code: contoso-hrs-300221-b – turn this into a job description” High (85) Yes Case does not matter to the regex or the keywords
A pasted document with “Project ref” in the heading and CONTOSO-FIN-204815-K two paragraphs (under 300 characters) later High (85) Yes Keyword inside the proximity window
“Is CONTOSO-FIN-204815-K a valid format for our tracker?” Medium (75) No – audit Pattern with no supporting keyword
A long paste where “project reference” appears more than 300 characters from CONTOSO-FIN-204815-K Medium (75) No – audit Keyword outside the proximity window
“Our codenames list starts with CONTOSO-RND-550731-H” Medium (75) No – audit “codenames” is not the whole word “codename”
“Project reference CONTOSO-FN-204815-K” None No Two letters, not three – the regex fails
“Project reference CONTOSO-FIN-20481-K” None No Five digits, not six
“Project reference XCONTOSO-FIN-204815-K” None No No word boundary before the prefix
“Project reference FABRIKAM-FIN-204815-K” None No Wrong prefix
“What is our project code policy?” None No A keyword on its own never matches

The last row is the important one. The keyword list contains everyday phrases that appear in thousands of emails and chats. On their own they do nothing; they only raise the confidence of a real project reference. That is the difference between a SIT and a keyword list, and it is why this SIT can block at High confidence without flooding the alert queue.

Prove it before you block. Paste these examples into a text file and run them through the Test option on the SIT. The results should match the table: six High, three Medium, five with no match. Purview lists a High match under Medium and Low as well, so seeing a value more than once is expected.

Custom SITs only find IP that carries an identifier. A design document that never mentions its project code passes straight through, which is why the next methods exist.

Exact data match

Exact data match (EDM) detects the actual values in your own data rather than a pattern that looks like them. You export a table, for example Contoso’s customer list with account numbers and contact names, hash it and upload the hashes. Purview then matches on those exact values, so a twelve-digit number only fires if it is a real Contoso customer account.

EDM gives the lowest false-positive rate of any method and suits structured IP: customer and supplier lists, a bill of materials, a product price book. The original data never leaves Contoso in clear text. The cost is operational: the source table has to be refreshed on a schedule as the data changes.

Document fingerprinting

Document fingerprinting is the most underused method for IP, and the best fit for any organisation that writes its IP on standard forms. You upload a blank template, such as Contoso’s patent disclosure form or design specification, and Purview converts its word pattern into a SIT. Any document written on that template then matches, whatever has been filled in.

Only a hash is stored; the original template cannot be reconstructed from it. Partial matching lets you set what percentage of the template text must be present for low, medium and high confidence, or select Exact to match only identical text.

Create it in the Purview portal under Information Protection > Classifiers > Sensitive info types > Create Fingerprint based SIT, or in Security & Compliance PowerShell:

$template = [System.IO.File]::ReadAllBytes('C:\Demo\Contoso-Design-Specification.docx')

New-DlpSensitiveInformationType -Name 'Contoso Design Specification' `
    -FileData $template `
    -ThresholdConfig @{ low = 40; medium = 60; high = 80 } `
    -IsExact $false `
    -Description 'Documents written on the Contoso design specification template'

Limits worth knowing before you promise it to anyone:

  • The template needs at least 256 characters of extracted text, and embedded documents in it are ignored.
  • It does not detect password-protected files, image-only files, files larger than 4 MB, or documents missing some of the template text.
  • Fingerprints share a 300 KB rule pack, which allows roughly 100 per tenant.
  • On devices, Advanced classification scanning and protection must be turned on in Endpoint DLP settings.

Trainable classifiers

Trainable classifiers identify an item by what it is rather than what it contains. For IP that is the only method that works on free-form documents with no identifiers and no template.

Pretrained classifiers are ready to use. Several map directly onto IP, including Source Code, Intellectual Property, Patents, Mergers and Acquisitions, and business and marketing plans. Check the current list in your tenant under Information Protection > Classifiers > Trainable classifiers, as it grows.

Custom trainable classifiers are trained on Contoso’s own documents. You provide a set of samples that definitely are the category, such as past tender responses, and a set that definitely are not. Purview trains on them, you review its predictions, and publish when the accuracy is acceptable.

  • Classifiers only work on items that are not encrypted.
  • Custom classifiers support English only.
  • Published custom classifiers cannot be retrained. To improve one, remove it and start again with larger sample sets.
  • The Source Code classifier fires when the bulk of the text is code, not on snippets pasted into a document or chat.
  • If you create a new SharePoint site for seed data, allow at least an hour for it to be indexed before training.

Precision versus coverage: EDM and exact fingerprints rarely misfire but only catch what they were built from. Classifiers catch far more but will produce false positives. Use the precise methods to block, and the broad ones to label, audit and warn while you tune.

The types of DLP

Classification decides what is sensitive. DLP decides what happens when that content moves. Purview DLP is not one control but a family, split into two policy scopes in the portal: Enterprise applications & devices and Inline web traffic. Each location sees a different part of the journey and offers different actions.

There are a lot of locations, and the table below lists them all for completeness. For the purposes of this post, the next sections focus on the route keeping most security teams awake: Contoso’s IP finding its way into generative AI.

Where each type of Purview DLP acts as Contoso IP moves between cloud, device, network and AI
Type of DLP Where it acts What it stops for Contoso IP
Microsoft 365 workloads Exchange, SharePoint, OneDrive, Teams chat and channel messages Patent drafts emailed externally, design files shared with guests or “anyone” links, project codes posted to external Teams chats
Endpoint DLP Onboarded Windows and macOS devices Copy to USB, print, upload to unallowed domains or personal cloud, copy to clipboard, access by unallowed apps – the departing engineer scenario
Microsoft 365 Copilot and Copilot Chat Prompts, grounding content and agent interactions Copilot processing labelled IP in its responses, and sensitive data typed into prompts
Inline web traffic – Edge for Business Inside the managed browser Pasting or uploading IP to unmanaged AI apps, with an in-page policy message
Inline web traffic – Network Entra Internet Access, or a supported non-Microsoft SASE The same, in any browser – covered in the inline DLP post
Defender for Cloud Apps instances Connected third-party SaaS apps IP sitting in sanctioned non-Microsoft cloud storage
On-premises repositories File shares and SharePoint Server, through the Information Protection scanner Legacy engineering shares nobody has migrated
Fabric and Power BI Semantic models, lakehouses and warehouses Pricing and product data uploaded to analytics workspaces

Protecting generative AI: where each type of DLP helps

AI reaches Contoso’s IP through several routes: a user pastes it into a prompt, uploads a file, asks Copilot a question that grounds on it, or lets an agent read it. No single DLP location covers all of them. Together they do:

Control AI route it covers What it does for Contoso IP
Microsoft 365 Copilot and Copilot Chat location Copilot grounding, prompts and prebuilt agents in Copilot Stops Copilot using content labelled Highly Confidential – Contoso IP in its responses, so a user who can open a file still cannot have Copilot summarise it
Endpoint DLP Paste and upload into AI websites from managed devices, and desktop AI apps reading files Blocks or warns on paste to browsers, upload to AI sites grouped as sensitive service domains, and access to labelled files by unallowed apps
Inline web traffic – Edge for Business Typed and pasted prompts in Edge Inspects the prompt in real time and blocks it before it leaves the browser, with a policy message the user can read
Inline web traffic – Network Any browser, plus apps, APIs and add-ins, through Entra Internet Access or a supported SASE Covers the browsers Edge for Business cannot – see the inline DLP post for tested results by app
Sensitivity labels with encryption Any AI app, managed or not Non-Microsoft AI apps cannot decrypt Purview-encrypted content, so a labelled file uploaded to them is unreadable
Exchange, SharePoint, OneDrive and Teams AI-generated content shared onwards A Copilot-drafted summary of Halcyon is still checked for SITs and labels when it is emailed or shared externally

Defender for Cloud Apps adds visibility of how Copilot is used and alerts on risky interactions, and DSPM for AI shows which AI apps are in use and what sensitive data reaches them. Neither blocks on its own; both tell you where to point the controls above.

Where Endpoint DLP protects

Endpoint DLP runs on Windows and macOS devices onboarded to Purview, and it is the control closest to the user. It acts on the actions people take with a file, wherever the file came from:

Activity Contoso scenario it stops
Upload to cloud service domains Design specification uploaded to a personal cloud drive or an AI website
Paste to supported browsers Code from a custom-developed app pasted into a consumer AI chat
Copy to clipboard Halcyon content copied out of a labelled document into an unmanaged app
Copy to removable USB device The departing engineer’s copy of the project folder
Copy to network share IP moved to an unmonitored file share before it leaves
Print Patent drafts printed and walked out of the building
Transfer using Bluetooth Files sent to a personal phone
Copy to remote desktop session Data moved into a session on a machine Contoso does not manage
Access by unallowed apps A labelled file opened by an unsanctioned desktop AI app or sync client

Each activity can be set to audit, block with override or block. Two settings matter for IP: Advanced classification scanning and protection must be on for fingerprint SITs to work on devices, and sensitive service domain groups let you treat AI websites differently from the rest of the internet.

Not every location understands every classifier

This is where classification and DLP design meet, and where most policies quietly fail. Locations support different conditions, and when you combine locations in one policy you keep only the conditions they all share.

  • Copilot acts on sensitivity labels for grounding content. Its location is only available in the Custom template and cannot be combined with any other location in the same policy. No label, no protection.
  • Fabric and Power BI support sensitivity labels and only a subset of SITs.
  • Inline web traffic classifies what it can parse. As the inline DLP post showed, a prompt sent in a binary format passes without a verdict, however good the classifier.
  • Encrypted content cannot be read by classifiers anywhere, so the label condition has to carry it.

The practical rule: build separate policies per location, and make sure every critical IP category is recognisable by a label as well as by content. Labels are the one classification every DLP location understands.

Where Global Secure Access prompt injection protection fits

Global Secure Access has a second AI control that is easy to confuse with inline DLP: prompt injection protection, configured as a prompt policy under Global Secure Access > Secure > Prompt policies and linked to the same security profile and Conditional Access policy as the content policy. It sits on the same TLS-inspected traffic path, but it answers a different question. Inline DLP asks is Contoso data leaving? Prompt injection protection asks is this prompt an attack on the model?

What it provides What it does not provide
Blocks adversarial prompts and jailbreak attempts before they reach the model Any recognition of Contoso IP. It has no SITs, labels, fingerprints or classifiers – a roadmap pasted politely passes straight through
Network-level enforcement with no change to the app, in any browser on a device running the Global Secure Access client Inspection of files. It covers text prompts only
Preconfigured conversation schemes for ChatGPT, Claude, Cohere, DeepSeek, Gemini, Grok, Meta AI, Mistral, Perplexity, Pi and Qwen Coverage of apps that do not send prompts as JSON, or of any app whose endpoint is missing from the conversation scheme
Custom schemes for in-house or other JSON-based AI apps, defined by endpoint URL and the JSON path to the prompt Protection without TLS inspection, or for QUIC traffic. Untrusted certificates or QUIC left on means the prompt is never seen
A Block action. Allow with Always log lets you measure impact first, but blocks nothing Inspection of prompts beyond 64,000 characters – longer prompts are truncated – and scanning is rate limited
Prompt activity recorded in the Generative AI Insights logs Protection for local agents talking to their own tools or MCP servers – that is Defender AI agent runtime protection, covered in Parts 1 to 5

The two controls are complementary, not alternatives. Prompt injection protection stops someone attacking the model through Contoso’s network; inline DLP stops Contoso’s IP reaching the model in the first place. Only the second depends on classification, which is why this post exists. Deploy both on the same security profile, and do not present prompt injection protection to a customer as a data protection control.

Test each app yourself. Claude is in the preconfigured list, yet in the inline DLP lab Claude sent typed prompts as binary Protocol Buffers rather than JSON. Check the request content type in the traffic logs before claiming coverage for any app, exactly as the inline DLP validation method describes.

Data at rest versus data in motion: eDiscovery and DLP

DLP stops sensitive content moving from now on. It does not tidy up what is already there. The credentials post made the same point: the connection string emailed eight months ago is still sitting in a mailbox. Finding IP that is already at rest is a separate job, and the tools behave differently by workload.

Location Finding it at rest (eDiscovery search) Stopping it leaving (DLP)
Exchange Online Searchable with SensitiveType, evaluated against the message body and indexed attachments when the item was indexed. A SIT created or changed later does not match older mail until it is reindexed. Images, scanned PDFs and partially indexed items are not evaluated Evaluated as mail is sent and received. Exchange DLP is event-driven, not a scanner of mail already in the mailbox
SharePoint Online Searchable with SensitiveType, including count and confidence ranges such as SensitiveType:"Credit Card Number|5..25" Evaluates files at rest and when they are shared, and can restrict access to them
OneDrive As SharePoint As SharePoint
Teams chat and channel messages Limited. Messages are stored in user and Teams mailboxes and evaluated on message text only, with lower accuracy for short messages. Files shared in Teams follow the SharePoint and OneDrive rules Evaluated as messages are sent. Files shared in Teams are covered by the SharePoint and OneDrive locations
Microsoft 365 Groups The group mailbox follows the Exchange rules; the group site follows the SharePoint rules Covered through the Exchange, SharePoint and OneDrive locations

Two consequences matter for Contoso:

  • Create custom SITs early. A Contoso Project Reference SIT published today will not find project codes in mail indexed last year until those items are reindexed. Every week of delay is a week of email that a search will miss.
  • Search before you enforce. Run an eDiscovery search for the custom SIT, the fingerprint SITs and All Credential Types across all workloads first. It tells you how much IP is already exposed and gives the DLP policy a realistic baseline.

DLP is the opposite side of the same coin. It reads SITs, labels, fingerprints and classifiers in every location it covers – Exchange, SharePoint, OneDrive and Teams, plus devices, Copilot, inline web traffic, Defender for Cloud Apps instances, on-premises repositories and Fabric – and it is the only control that acts at the moment content leaves.

Putting it together for Contoso

Here is how everything above combines around one asset: Project Halcyon, Contoso’s flagship R&D programme.

Layer 1 – Classify

Component Configuration
Label Highly Confidential – Contoso IP, encrypting content and limiting access to the R&D group
Default label Applied to the Project Halcyon SharePoint library
Custom SIT Contoso Project Reference, at High confidence
Fingerprint SIT Contoso Design Specification and Contoso Patent Disclosure templates
Classifiers Pretrained Source Code (for Contoso’s custom-developed apps) and Patents
Auto-labelling Client-side recommendation and service-side policy apply the label when any of the SITs or classifiers above match

Layer 2 – Enforce

Policy Condition Action
DLP-IP-M365 Label, project SIT or fingerprint SIT, shared outside Contoso Block, with override and business justification for Legal
DLP-IP-Endpoint Label, Source Code classifier or fingerprint SIT Block USB, print and upload to personal cloud; audit clipboard
DLP-IP-Copilot Highly Confidential – Contoso IP label Prevent Copilot from processing content
DLP-IP-AIApps Project SIT or Source Code classifier, to All unmanaged AI apps Block, on Edge for Business and Network
Block Credentials and Secrets All Credential Types Block everyone – from the credentials post

Layer 3 – Control the destinations

The Defender and Agent 365 controls from the series sit on top: unsanctioned MCP servers blocked by indicators, agents approved before use, runtime protection inspecting what agents read, and GSA prompt injection protection blocking attacks on browser AI apps. They decide which doors exist; the first two layers decide what is allowed through them.

Now replay the risks. The departing engineer’s USB copy is blocked by Endpoint DLP because the files carry the label or match the Source Code classifier. The roadmap pasted into ChatGPT is blocked inline. Copilot will not ground answers on Halcyon documents. A patent draft emailed to a partner is stopped at Exchange. Every one of those outcomes depends on Layer 1.

Handling the alerts: the Triage Agent in DLP

Layering classifiers has a cost: alerts. A Source Code classifier and a broad fingerprint will produce far more matches than a credential SIT, and a security team that cannot keep up with the queue will eventually stop reading it. The Triage Agent in DLP, a Security Copilot agent in the Purview portal, is Microsoft’s answer to that problem.

Triage Agent in Microsoft Purview DLP - sorting, weighing, explaining and learning from DLP alerts

What it does

  • Sorts the queue. Each alert is placed in Needs attention, Less urgent or Not categorized (alerts it could not triage).
  • Weighs the risk. Its verdict is driven mainly by content risk – the SITs, trainable classifiers and default sensitivity labels that matched – plus exfiltration risk (was the data shared externally?), policy risk (the rule’s mode and actions) and label removal or downgrade.
  • Explains itself. Every triaged alert carries a summary and the risk factors behind the verdict, in both the Purview and Defender portals.
  • Learns from analysts. An analyst can move an alert between categories and add properties such as SITs, file paths or target domains. The feedback applies to that policy, or to all policies.
  • Takes custom instructions (preview). Plain-language guidance raises or lowers priority.
  • Nudges the user (preview). For SharePoint and OneDrive alerts in Needs attention, it can message the person who last changed the file in Teams, asking them to remove the sensitive content. Reminders go out once a day and bundle up to 10 files.

How it benefits Contoso

  • Halcyon alerts first. A custom instruction such as “Prioritise alerts involving Contoso Project Reference, the design specification fingerprint or the Highly Confidential – Contoso IP label” puts IP at the top of the queue, above the noise from built-in PII types.
  • Tuning without rewriting policies. When the Source Code classifier fires on a harmless script, analyst feedback teaches the agent to rank it lower, rather than someone weakening the rule.
  • Oversharing fixed at the source. The Teams reminder asks the engineer who left a design file in an open site to clean it up, without a ticket.
  • Evidence for the board. The Needs attention count is a cleaner measure of real IP risk than raw alert volume.

What to know before you switch it on

  • It only triages alerts from policies scoped to Exchange, Teams, OneDrive, SharePoint and devices. Alerts from the Copilot and inline web traffic policies – the AI routes above – are not triaged.
  • It ignores policies in simulation mode, so it adds nothing until a policy is turned on.
  • It analyses files up to 2 MB, and for alerts with 10 or more files it looks at the top 10 only. Device alerts need evidence collection for file activities turned on.
  • It looks back at most 30 days from the day it is enabled. Allow up to two hours for the first pass.
  • It runs on Security Copilot and consumes SCUs (Security Compute Units) in proportion to alert volume, so provision capacity and watch usage. It also needs Purview pay-as-you-go billing alongside per-seat DLP licensing.
  • Several capabilities are in preview. Confirm the current status in your tenant.

A practical sequence

  1. Find what you have. Data explorer and Activity explorer show where existing SITs and labels already occur and how content moves, before any policy exists. DSPM shows the same through a risk lens, and an eDiscovery search for your custom SITs shows what is already sitting in mailboxes and sites.
  2. Agree the crown jewels with the business. R&D, Legal and Product decide what counts as IP. Security cannot classify what nobody has defined.
  3. Keep the label taxonomy short. Four or five labels people understand beat twelve they ignore.
  4. Build classifiers per asset type, using the crown jewels table: custom SITs for identifiers, fingerprints for templates, EDM for structured lists, classifiers for the rest.
  5. Test before you trust. Use the Test option on each SIT with samples that should and should not match, and check classifier predictions before publishing.
  6. Auto-label in simulation first. Review what service-side auto-labelling would label before letting it apply encryption at scale.
  7. Run DLP in simulation, then with policy tips, then block. Tips teach users what is sensitive; blocks without them generate tickets.
  8. Switch on the Triage Agent once policies are live, with a custom instruction that puts Contoso IP first.
  9. Review regularly. New projects need new codes, templates change, and classifiers drift as the business does.

Limits to know

  • Classification is never complete. Some IP will always be unlabelled and undetectable. Destination controls remain the backstop.
  • Encryption and detection pull in opposite directions. Encrypt too early and content classifiers go blind; rely on the label from that point.
  • Machine learning makes mistakes. Start classifier-based rules in audit or warn mode.
  • Licensing varies by method and location. Several capabilities in this post need E5, E5 Compliance or pay-as-you-go billing. Confirm against your own licence position before designing around them.
  • Features move quickly. Copilot and inline web traffic locations have changed repeatedly in 2026. Verify current behaviour in your tenant.

Wrapping up

Every control in this series is only as good as its ability to recognise what it is protecting. Destination controls decide where data can go; classification decides what the data is; DLP joins the two at every point data moves. For credentials and personal data Microsoft has done most of the classification work for you. For intellectual property, you have to do it yourself, with labels, custom SITs, fingerprints, EDM and classifiers layered together. Do that first, and every other control you have deployed starts to mean something.


Related posts

References

Seรกn O’Farrell | cloud-secure.ai

Microsoft Defender AI agent runtime protection, part 6: moving AI agent governance from Defender into Agent 365

Part 6 cover - Moving AI agent governance from Defender into Agent 365

Series: Part 1 introduced AI agent runtime protection in Microsoft Defender for Endpoint. Part 2 covered the lab build and validation. Part 3 found the agents running on your endpoints. Part 4 blocked an unsanctioned MCP server with a Defender indicator. Part 5 automated it. Part 6 moves from Defender controls on the endpoint to governance in Microsoft Agent 365.

From Defender controls to Agent 365 governance

Parts 1 to 5 of this series were about Defender controls. They covered seeing agents on endpoints, detecting prompt injection, blocking unsanctioned MCP servers and controlling where tools like Claude Code can connect. Those controls act at runtime, on the device, once an agent is already running.

This part moves up a level, to governance and control in Microsoft Agent 365. Agent 365 is where Microsoft now inventories every agent in a tenant, approves them before people can use them, and applies policy when they are published. Entra ID sits underneath it, giving the agents that have an identity their own Conditional Access, ID Protection and access governance.

Defender answers “what is this agent doing right now?” Agent 365 answers the questions that should come first: which agents do we have, who owns them, who approved them, and what are they allowed to reach?

Core concepts

A few terms come up throughout:

  • Agent: in Agent 365, anything in the registry, whatever platform built it: Copilot Studio, Microsoft, a third-party publisher or your own developers.
  • Agent identity: an agent that signs in to Entra with its own identity, much like a service principal. Only these agents can be targeted by Entra Conditional Access, ID Protection and access packages.
  • Agent identity blueprint: the template an agent identity is created from. It sets the identity, permissions, policies and naming for every agent built from it. Copilot Studio has its own blueprint, so every Copilot Studio agent with an identity comes from the same one.
  • Blueprint principal: the blueprint’s object in your tenant. Conditional Access uses it to include or exclude every agent built from that blueprint in one go.
  • Agent user: an agent that also has a user account, so it can work in Teams, Outlook, SharePoint and OneDrive. It is a separate identity type, so a policy for agent identities does not cover agent users.
  • Owner and sponsor: the people accountable for an agent. Owners handle the technical side; sponsors answer for why it exists.
  • User consent: the Entra setting that decides whether ordinary users can grant an app or agent access to their data without an administrator.
Agent identity and access scope

The diagram above shows how these fit together. Owners and sponsors maintain a blueprint. The blueprint creates agent identities, and can create agent users for agents that need Microsoft 365. Conditional Access and ID Protection then evaluate every token request those identities make. The point to take from it: set policy at the blueprint, and every agent built from it is covered.

The diagram below shows the four gates this post is built around. Each one asks a different question, and an agent has to pass all four before it is any use.

Four gates - an agent has to pass all of them to do anything useful
Gate Question Native control Where
1 Who can build an agent? Copilot Studio environments and licensing, Foundry RBAC, Agent ID Developer role, user consent Power Platform, Azure, Entra
2 Is it approved for people to use? Agent and plugin access, user access, policy templates, approval of requests Microsoft 365 admin center (Agent 365)
3 What can it reach? Owners and sponsors, access packages with approval and expiry Entra ID Governance
4 Can it authenticate at all? Conditional Access for agents, plus ID Protection Entra

Gate 2 covers every agent in the registry. Gates 3 and 4 only reach agents with an Entra agent identity, which is why Agent 365 comes first.

What a dev tenant looks like

To write this part I reviewed a Microsoft 365 E7 dev tenant, read-only.

The Agent 365 overview - 318 agents in the registry, nothing pending approval
Agent map - two thirds of the agents are third-party
The same tenant in Entra - only 84 agent identities, from 2 blueprints
What I found Agent 365 Entra ID
Agents 318 in the registry 84 agent identities
Where they come from 214 third-party, 79 Copilot Studio, 23 Microsoft, 2 Agent Builder 81 from the Copilot Studio blueprint, 1 from Purview
Waiting for approval 0 requests –
Governance templates None –
Agent Conditional Access – 2 policies, both report-only

These figures are from a dev tenant. Agent 365 and Entra count agents in different ways, so the totals do not line up exactly between the two portals.

The headline is the gap between the two columns. Most agents in the tenant have no Entra agent identity at all, so Entra’s Conditional Access, ID Protection and access packages cannot see them. Entra says so itself on the Agent identities page: it lists only agents with Entra identities, and points to Agent 365 for the rest. That is why the governance has to start in Agent 365.

The risks

Risk What I saw Why it matters
Agent sprawl Hundreds of agents across several platforms Nobody can review what they cannot count
Agents outside Entra About three quarters of agents had no Entra agent identity Identity controls (CA, ID Protection, access packages) do not reach them
Third-party agents Two thirds of the registry They cannot go through the Agent 365 approval workflow
No approval in use Nothing in the Requests queue Nothing had gone through the approval workflow, so there is no record of anyone signing agents off
Ownerless agents An agent identity with no owner and no sponsor No one to ask what it does, or to switch it off
Standing permissions An agent holding a delegated permission granted by admin consent Access granted once, never reviewed, never expires
Permissive defaults External publishers allowed; no governance templates Agents arrive without policy applied
Controls not enforced Agent CA policies left in report-only Risky agents would be logged, not blocked
Data exposure through users Copilot Studio agents act with the signed-in user’s permissions An over-shared agent exposes whatever its users can reach

None of this is unusual. Agent 365 and Entra Agent ID are new, the defaults are open, and agents have been arriving faster than anyone has been governing them.

Two ways to put the controls in place

Option 1: the portal walkthrough. The rest of this post walks through each control, with screenshots from the dev tenant, in the Microsoft 365 admin center and the Entra admin center. Use it to understand what each setting does, or to apply it by hand in a small tenant.

Option 2: the script. The companion PowerShell script, Invoke-Agent365Governance.ps1, asks for one thing, your tenant ID, and signs you in interactively. It then:

  • Reviews the tenant read-only: every agent identity grouped by blueprint, agents with no owner, agents holding granted permissions, legacy Copilot Studio service principals, and existing agent Conditional Access policies. Everything is exported to CSV.
  • Creates the Gate 4 policies (CA-AGT-001 to 003, plus the optional CA-WID policies for service principals) in report-only mode, skipping any that already exist.

Run it with -ReviewOnly to change nothing, or -WhatIf to see what it would create.

GitHub: Agent365-governance-in-Microsoft-365

The README explains every parameter and the Microsoft 365 and Entra roles the account running it needs. The Agent 365 settings in Gate 2 have no published API yet, so the script cannot set them. The README and the script’s summary list them as manual steps. Gate 2, later in this post, walks through each one with screenshots.

Prerequisites

Licensing

Capability Licence needed
Agent 365 registry, approvals, templates Microsoft Agent 365, included in Microsoft 365 E7 (Learn)
Entra Agent ID (agent identities and blueprints) Included for Microsoft Entra customers
Conditional Access for agents Microsoft 365 E7, or Agent 365 plus Entra ID P1 or Microsoft 365 E3 (Learn)
Risk-based Conditional Access for agents As above, plus Entra ID P2 or Microsoft 365 E5 (Learn)
ID Protection for agents Agent 365 or Microsoft 365 E7 (MC1395007)
Entra ID Governance for agents Microsoft 365 E7, or Agent 365 with Entra ID P1 or Microsoft 365 E3 (Learn)
Conditional Access and ID Protection for ordinary service principals Microsoft Entra Workload ID Premium: standalone, not included in E7 (FAQ)

Roles for the portal walkthrough

Use the least privileged role for each task rather than Global Administrator.

Task Portal Least privileged role
Review the agent registry, approve requests, block agents, assign owners Microsoft 365 admin center > Agents AI Administrator (MC1245636)
Grant admin consent to an agent’s Microsoft Graph application permissions Microsoft 365 admin center or Entra Privileged Role Administrator (MC1245636)
Change Agent settings (agent and plugin access, user access, policy templates) Microsoft 365 admin center > Agents > Settings AI Administrator (MC1245636)
Manage agent identities and blueprints Entra > Agents Agent ID Administrator (Learn)
Create Conditional Access policies for agents Entra > Conditional Access Conditional Access Administrator
Review and act on risky agents Entra > ID Protection Security Operator (Security Reader to view)
Create access packages for agents Entra > ID Governance Identity Governance Administrator
Change user consent settings Entra > Enterprise apps > Consent and permissions Privileged Role Administrator (Learn)
Read agent sign-in logs Entra > Agents > Sign-in logs Reports Reader
Read-only review, as in this post Both Global Reader (check it can open the Agent 365 pages in your tenant)

Tip: Security defaults must be off, or Conditional Access will not apply to agents at all.

Step 1: Take stock

1a. Agent 365: the full inventory

  1. In the Microsoft 365 admin center, browse to Agents > Overview. The cards show the registry total, active users, connected platforms, pending requests, agents at risk and agents without owners.
  2. Open Agents > All agents. The Registry tab lists every agent with its status, platform, risks, users and sessions; filter by Status, Publisher type, Platform or Channel.
  3. Open Agents > Agent map to see the agents clustered by platform. This is the quickest way to show leadership where agents are coming from.
Agents > All agents - the Registry tab

1b. Entra: the agents with an identity

  1. In the Entra admin center, browse to Entra ID > Agents > Overview.
  2. Open Agent identities for the list, and Agent blueprints to see which blueprints they come from.
Entra > Agents > Agent identities - note the banner pointing to Agent 365 for the other agents
Entra > Agents > Agent blueprints - 81 agents from the Copilot Studio blueprint

Compare the two totals. The difference is the number of agents your identity controls cannot see.

1c. Find legacy Copilot Studio service principals

Older Copilot Studio agents use plain service principals rather than agent identities. Their service principals carry consistent tags such as AgenticApp, AIAgentBuilder and power-virtual-agents-<id> (Learn):

<#
.SYNOPSIS
    Lists service principals tagged as Copilot Studio / agentic apps.
.NOTES
    Author: Seรกn O'Farrell
    Website: https://cloud-secure.ai/
#>
Connect-MgGraph -Scopes "Application.Read.All" -NoWelcome

$agentTags = @('AgenticApp', 'AIAgentBuilder', 'AgenticInstance')

$legacyAgents = Get-MgServicePrincipal -All -Property Id, AppId, DisplayName, Tags, CreatedDateTime |
    Where-Object {
        $tags = $_.Tags
        ($tags | Where-Object { $_ -in $agentTags -or $_ -like 'power-virtual-agents-*' })
    }

$legacyAgents |
    Select-Object DisplayName, AppId, CreatedDateTime,
        @{ Name = 'CopilotStudioTag'; Expression = { $_.Tags | Where-Object { $_ -like 'power-virtual-agents-*' } } } |
    Sort-Object CreatedDateTime -Descending |
    Format-Table -AutoSize

Write-Host "๐Ÿ”Ž Found $($legacyAgents.Count) agent-tagged service principals"

Don’t mass-disable. Blocking an agent or disabling a blueprint can break something the business relies on. Triage first, with the owners.

Gate 1: Control who can build

You cannot stop a Copilot Studio agent getting an identity, but you can control who can build agents in the first place (Learn):

Platform Native control
Copilot Studio Block self-service trials, assign Copilot Studio licences only to approved makers, restrict environment creation to Power Platform Administrators
Microsoft Foundry Turn off self-service subscription creation; assign Azure AI Account Owner and Azure AI User only to approved teams
Custom agents Limit the Agent ID Administrator and Agent ID Developer roles
Third-party agents Tighten user consent so users cannot consent to new agent blueprints themselves
Microsoft Teams Control which apps and agents users can add in the Teams admin center

Gate 2: Govern agents in Agent 365 (the main event)

Everything in this gate happens in the Microsoft 365 admin center, under Agents > Settings and Agents > All agents.

Agents > Settings - six settings that govern every agent in the tenant

2a. Agent and plugin access

Decide which kinds of agent users can install. The dev tenant allowed agents from all external publishers, which is the opposite of where most organisations want to start.

  1. Open Agents > Settings > Agent and plugin access.
  2. Choose which types users can install: built by Microsoft, built by your organisation, or built by external publishers.
  3. If you allow external publishers, consider Only certified external publishers rather than All external publishers.
  4. Select Save.
Agent and plugin access - note the option to allow only certified external publishers

2b. User access

Control who can use agents at all: All users, No users, or Specific users or groups. A pilot group is a sensible place to start while the rest of the controls go in. Microsoft notes that wider access can increase cost if you use pay-as-you-go billing.

User access

2c. Policy templates

Policy templates apply licences and policies automatically when an agent is created or added. The dev tenant had none.

  1. Open Agents > Settings > Policy template and select Add a new policy template.
  2. On Details, give it a name and description, then choose What kind of agent can use this policy template? and pick Agents without their own identity or Agents with their own identity (preview).
  3. On Security policies and protections, choose the policies to apply. For agents without their own identity, the dev tenant offered none, so expect this page to vary by agent type and licensing.
  4. Review and create.
Agents > Settings > Policy template - no templates yet
Add Policy template - Details, including the agent type
Security policies and protections

2d. Work the Requests queue

When a maker publishes an agent to the tenant, it should land in Agents > All agents > Requests for approval rather than going straight to users (Learn). An empty queue in a tenant with hundreds of agents is a warning sign, not a sign that all is well.

The Requests queue - empty in a tenant with hundreds of agents

For each request, ask four questions (Learn): does it ask only for what it needs, is the publisher trusted, is the business purpose clear, and does it fit your AI policy? Then approve it with Publish to store, choosing the audience and template, or reject it.

Gap: third-party agents cannot be requested or approved through this workflow. In the dev tenant, that was two thirds of the registry. Your controls for them are Gate 1 (user consent) and Gate 2a (which publishers to allow), plus blocking anything you do not trust.

2e. Review an agent

Select any agent in the registry to open its details. The tabs tell you most of what you need: Details, Users, Data & tools, Security, Permissions and Activity. From here you can also Assign new owner and Block the agent.

Agent details - owner, publisher, last used, and the Entra agent ID

The Security tab is where Agent 365 ties the other products together: Purview protections for the agent’s activity and data, and a link to its Entra identity.

Security tab - Purview and Entra protections for one agent
Permissions tab - this agent holds no Entra permissions of its own

2f. Block, delete and restore

Block stops an agent being surfaced to users. Delete soft-deletes it for 30 days, and you can restore it from Agents > Deleted agents (Learn). Both need a role that can manage agents. They were greyed out for the read-only account I used.

Agents > Deleted agents

Gate 3: Owners, sponsors and access

This gate only applies to agents with an Entra agent identity, which was 84 of the 318 in the dev tenant. For those, Entra adds ownership and access governance. Open one from Entra ID > Agents > Agent identities.

An agent identity - no sponsors, no owners, one permission, and links to its CA policies and access packages

3a. Owners and sponsors

Owners handle the technical side; sponsors are accountable for the agent’s purpose and lifecycle (Learn). Microsoft now requires sponsors when agent identities are created, but older agents can still have none. The one above had neither. Add them under Owners and sponsors, using a Microsoft 365 group as sponsor so ownership survives staff changes.

Owners and sponsors - none found

3b. Permissions and access packages

The same agent held a delegated permission granted by admin consent: access granted once and never reviewed. Check Granted permissions on each agent, and move standing access into access packages, which add approval and an expiry date.

Granted permissions - a delegated permission granted by an administrator
  1. Browse to ID Governance > Entitlement management > Access packages and create a package for a class of agent.
  2. Add the resources it needs: groups, application permissions or Entra roles.
  3. In the request policy, allow agent identities to request it, and require approval.
  4. Set an expiry, such as 90 or 180 days, so access is re-justified (Learn).

Gate 4: Conditional Access and ID Protection

Like Gate 3, this gate only reaches agents with an Entra agent identity or agent user. Everything else is governed in Agent 365.

4a. Conditional Access for agents

Agent policies show up in the normal Conditional Access policy list; filter by Actors: Agents to see them. For agent identities the only condition is agent risk, and the only grant control is Block (Learn).

Conditional Access policies filtered to agents - two, both report-only
A policy blocking high-risk agent identities - still in report-only

The starter set I recommend:

Policy Assign to Condition Control
CA-AGT-001 Block agents from unapproved blueprints All agent identities, excluding approved blueprint principals None Block
CA-AGT-002 Block high-risk agent identities All agent identities Agent risk: High Block
CA-AGT-003 Block high-risk agent users All agent users Agent risk: High Block

To create CA-AGT-002 in the portal:

  1. Browse to Entra ID > Conditional Access > Policies and select New policy. Name it CA-AGT-002 Block high-risk agent identities.
  2. Under Assignments, select Users, agents or workload identities, then under What does this policy apply to? select Agents and All agent identities.
  3. Under Target resources, include All resources.
  4. Under Conditions, set Agent risk to High.
  5. Under Grant, select Block access, set Enable policy to Report-only, and select Create.

CA-AGT-003 is the same, but choose All agent users in step 2. CA-AGT-001 has no condition; instead, under Exclude choose Select individual agent identities and use the Agent blueprint principals tab to exclude the blueprints you approve (Learn). Run all three in report-only for 48 hours, check the results, then switch them on.

4b. ID Protection for agents

ID Protection scores agent risk, and the CA policies above act on it. Check ID Protection > Dashboard for agents flagged for risk, and Risky agents for the detail.

ID Protection dashboard - agents flagged for risk sit alongside user risk
ID Protection > Risky agents

The gap E7 does not cover: Workload ID Premium

Everything so far covers agents with an Entra agent identity. But plenty of agents still authenticate as ordinary service principals: legacy Copilot Studio agents, custom agents built on standard app registrations, automation that never moved to Agent ID, and many third-party apps. Agent Conditional Access and ID Protection for agents do not reach them.

Protecting service principals needs Microsoft Entra Workload ID Premium. It is a standalone product at $3 per workload identity per month, and Microsoft states it is not part of any other SKU, so it is not included in Microsoft 365 E7, Entra ID P2 or the Entra Suite (Workload ID FAQ).

Capability Free Workload ID Premium Why it matters for agents
Sign-in logs and audit trail for service principals Yes Yes You can already see what they do
Managed identities and workload identity federation Yes Yes The way to retire client secrets
Conditional Access for workload identities No Yes Block a service principal outside named locations, or when it is risky
ID Protection for workload identities No Yes Risk detection for leaked credentials and unusual sign-ins
Access reviews for service principals in privileged roles No Yes Re-justify agents and automation holding admin roles
App health recommendations No Yes Flags unused apps and expiring or risky credentials

What it covers, and what it does not

  • Conditional Access applies only to single-tenant service principals registered in your tenant. Multi-tenant and SaaS apps, Microsoft apps and managed identities are excluded, and service principals must be assigned to the policy directly, not through a group (Learn).
  • ID Protection covers both single-tenant and multi-tenant service principals, so it reaches some third-party apps that Conditional Access cannot.
  • As with agents, the only grant control is Block. Conditions are location and service principal risk.

Workload identity protection considerations

  • Separate licensing. These features need Workload ID Premium, which is separate from Entra ID P1 and P2. Having P2 through E5 or E7 does not unlock them.
  • The licence check cannot be worked around. It is enforced by the service, not just the portal, so creating or changing a workload identity policy through PowerShell or Microsoft Graph needs the licence too. Without it, existing policies keep working but cannot be changed (Learn).
  • Same place, different target. Workload identity policies live in the normal Conditional Access policy list. The difference is the assignment: under Users, agents or workload identities you choose Workload identities instead of users and groups, or agents.

Two policies worth having

Policy Assign to Condition Control
CA-WID-001 Block service principals outside trusted locations Selected single-tenant service principals Any location, excluding your named locations Block
CA-WID-002 Block risky service principals Selected single-tenant service principals Service principal risk: High Block
  1. Browse to Entra ID > Conditional Access > Policies and select New policy.
  2. Under Assignments, select Users, agents or workload identities, then under What does this policy apply to? select Workload identities and Select service principals.
  3. Under Target resources, include All resources.
  4. Under Conditions, set Locations (include Any location, exclude your trusted named locations), or Service principal risk.
  5. Under Grant, select Block access, and create the policy in Report-only.

Review the results under Sign-in logs > Service principal sign-ins, and risky service principals under ID Protection > Risky workload identities.

Is it worth it?

If your Step 1 inventory finds custom or legacy agents still running as service principals with client secrets, yes, at least until they move to agent identities or managed identities. A 90-day trial is available. Microsoft’s FAQ is inconsistent on how licences are counted. It quotes a per-identity price, but also says one licence unlocks the features tenant-wide, so confirm the count with your Microsoft partner before buying.

Monitor

Agent sign-ins are under Entra ID > Agents > Sign-in logs, already filtered to Is Agent: Yes. Agent identity sign-ins sit on the Service principal sign-ins tab; agent user sign-ins on the non-interactive tab.

Entra > Agents > Sign-in logs

To see what your report-only agent policies would block:

// Agent sign-ins that a CA-AGT report-only policy would have blocked
union AADServicePrincipalSignInLogs, AADNonInteractiveUserSignInLogs
| where TimeGenerated > ago(2d)
| extend CAP = todynamic(ConditionalAccessPolicies)
| mv-expand CAP
| where tostring(CAP.displayName) startswith "CA-AGT-"
| where tostring(CAP.result) == "reportOnlyFailure"
| summarize WouldBlock = count(), LastSeen = max(TimeGenerated)
    by Policy = tostring(CAP.displayName),
       Identity = coalesce(ServicePrincipalName, UserPrincipalName),
       ResourceDisplayName
| order by WouldBlock desc

Blind spots

Gotcha What happens What to do
Agents without an Entra identity Most of the registry is invisible to CA, ID Protection and access packages Govern them in Agent 365: access settings, user access, approval, block
Third-party agents They cannot be approved through the Requests workflow Restrict external publishers and user consent; block what you do not trust
API keys An agent using an API key never authenticates with Entra (Learn) Move it to an agent identity and retire the key
Legacy Copilot Studio agents Plain service principals, not agent identities Find them with the script in Step 1c and migrate them; protect them meanwhile with Workload ID Premium
Custom agents on app registrations Agent CA does not apply; workload identity CA needs a licence E7 does not include License Workload ID Premium, or move them to agent identities or managed identities
Delegated access Copilot Studio agents act as the user, so permission controls do not limit them Rely on Gate 2 and Power Platform data policies
Security defaults Conditional Access does not apply to agents Replace security defaults with a CA baseline
Report-only forever Policies log but never block Set a date to enforce
Preview features Several agent features are still in preview Recheck status before rolling out to a customer

Checklist

  • Compare the Agent 365 registry total with the Entra agent identity total
  • Find legacy Copilot Studio service principals and plan their migration
  • Gate 1: restrict who can build, and tighten user consent
  • Gate 2: set Agent and plugin access and User access, create a policy template, and work the Requests queue
  • Gate 2: assign owners to ownerless agents; block what nobody will own
  • Gate 3: add sponsors, review granted permissions, move access into access packages
  • Gate 4: deploy CA-AGT-001, 002 and 003 in report-only
  • Monitor: review the report-only results after 48 hours, set an enforcement date, then switch the policies on
  • Service principals: decide on Workload ID Premium for agents and automation that are not agent identities
  • Or run the companion script for the review and Gate 4 policies, then work through the manual steps it lists

More to come

The series started on the endpoint with Defender and now covers governance in Agent 365. Microsoft is moving quickly here, and several features in this post are still in preview. I will update this post, and the script, as they change.


Next in the series: Part 7 tests the Ignite chain in the lab - can an unapproved local agent get its user blocked at sign-in, using only E5? The device route stalls; the identity route works end to end.

The rest of the series

References

Seรกn O’Farrell | cloud-secure.ai

Microsoft Defender AI agent runtime protection: the series guide (parts 1 to 7)

Microsoft Defender AI agent runtime protection series guide, parts 1 to 7

Series guide: seven parts on securing the AI agents in your organisation, from Microsoft Defender for Endpoint on the device, to governance in Microsoft Agent 365, to classifying the data they can reach with Microsoft Purview: what each part covers, and where to start.

AI agents such as Claude Code, GitHub Copilot and Gemini CLI are already on managed endpoints, running with the full rights of the signed-in user and connecting to MCP servers that nobody has reviewed. This series works through what Microsoft Defender for Endpoint can do about that today: detecting prompt injection, finding the agents, and controlling and automatically blocking the servers they talk to. It then moves up a level to Microsoft Agent 365, where you decide which agents exist, who owns them and what they can reach, and finally to Microsoft Purview, where classification decides what data is allowed through once a destination is approved.

Every part is built and tested in a lab or dev tenant, with screenshots of what actually happened, including where the product or the documentation did not behave as expected.

The series at a glance

Part Question it answers What you get
Part 1 What is AI agent runtime protection? How Defender detects prompt injection against local AI agents
Part 2 Does it work, and how do I build it? A lab build, validation, and the gaps in the documentation
Part 3 Which agents are running on my endpoints? The Local agents view, licensing and advanced hunting queries
Part 4 How do I stop an agent reaching an MCP server? Custom domain indicators, network protection and a custom detection rule
Part 5 How do I block every new MCP server automatically? An Azure Automation runbook that blocks by default, with scripts on GitHub
Part 6 How do I govern every agent, not just the ones on endpoints? Agent 365 approval, owners and sponsors, and Conditional Access for agents, with a script on GitHub
Part 7 What can DLP protect if nothing has been classified? Purview classification methods, the types of DLP, and a layered design to protect Contoso’s intellectual property

What each part covers

Part 1: the control for agents already on your endpoints

The starting point: what AI agent runtime protection is, which agents it covers and how it detects prompt injection against agents running locally on your endpoints. If you are new to the topic, start here.

Part 2: building it, proving it, and where the documentation is wrong

The lab build and the validation work behind it. It shows the protection working end to end, and records where the published documentation did not match what the tenant actually served, so you do not lose the same time I did.

Part 3: finding the agents you did not know you had

Visibility before control. The Local agents view in the Defender portal, why discovery is activity based rather than installation based, the licensing split between the inventory and the risk assessment, and a set of advanced hunting queries that go well beyond what the portal shows.

Part 4: controlling where Claude can connect

Runtime protection does not decide which MCP servers an agent may reach. Part 4 closes that gap for a known server: a Defender for Endpoint custom domain indicator, enforced by network protection, blocks Claude Code from an unsanctioned remote MCP server. It covers why the indicator must be the bare domain, why Edge enforces it before network protection does, and a custom detection rule to alert on the blocks.

Part 5: blocking MCP servers you have not approved

An indicator only blocks the domains you list. Part 5 automates it: an Azure Automation runbook with a managed identity runs every hour, finds every new remote endpoint an AI agent has used, and blocks it with a Defender indicator and an alert. Approved servers are permitted with an Allow indicator. It is tested with Claude Code, GitHub Copilot CLI and Gemini CLI (an agent runtime protection does not support), and the scripts are on GitHub.

Part 6: moving AI agent governance from Defender into Agent 365

Parts 1 to 5 act on the device, once an agent is already running. Part 6 moves up to governance in Microsoft Agent 365, where every agent in the tenant is inventoried and approved before people can use it. A dev tenant with 318 agents had only 84 visible to Entra, so most were out of reach of Conditional Access. The post works through four gates: who can build, Agent 365 approval, owners, sponsors and access packages, and Conditional Access and ID Protection for agents. It also covers the Workload ID Premium gap that E7 does not include, and a companion script on GitHub that reviews the tenant and creates the policies in report-only mode.

Part 7: data classification first – protecting Contoso’s intellectual property

Parts 1 to 6 decide where data is allowed to go. Part 7 answers the question that has to come first: what is the data? Once a destination is approved, whether an MCP server, Copilot or an AI app, only a control that recognises the content can stop the wrong data reaching it. The post covers every Purview classification method – sensitivity labels, custom SITs, exact data match, document fingerprinting and trainable classifiers – and the types of DLP that act on them, from Endpoint DLP to inline web traffic and the Copilot location. It walks through how proximity and confidence levels keep a custom SIT from flooding the alert queue, where GSA prompt injection protection fits and where it does not, finding IP already at rest with eDiscovery, and the Triage Agent in DLP. It is the foundation the other six parts stand on.

Where to start

  • New to the topic: read part 1, then part 3 to see what is already running in your estate.
  • Building a lab or a proof of concept: part 2.
  • Need to control MCP servers now: part 4 for a single server, then part 5 to block every new one automatically.
  • Need to know which agents exist and who approved them: part 6.
  • Need to stop sensitive data reaching agents and AI apps you have approved: part 7, the foundation every other control relies on.

More to come

The series is not finished. Microsoft is moving quickly on AI agent security in the Defender portal, and the next parts will follow the new capabilities as they arrive, including the new Sentinel workbook and automation features in the Defender portal. Each one is built and tested in a lab before it is written up.

Follow along on cloud-secure.ai or connect with me on LinkedIn to hear when the next part is published.


The series

Disclaimer: The views in this series are my own. They do not represent my employer, or Microsoft or any other vendor whose products are discussed here.

Seรกn O’Farrell | cloud-secure.ai

Microsoft Defender AI agent runtime protection, part 5: blocking MCP servers you have not approved

Part 5 cover - Blocking MCP servers you have not approved

Series: Part 1 introduced AI agent runtime protection in Microsoft Defender for Endpoint. Part 2 covered the lab build and validation. Part 3 found the agents running on your endpoints. Part 4 blocked an unsanctioned MCP server with a Defender indicator. Part 5 automates it, so every new MCP server is blocked until you approve it.

In part 4 a Defender for Endpoint custom domain indicator, enforced by network protection, stopped Claude Code reaching an unsanctioned remote MCP server. It worked, but it only blocks the domains you list. A developer who adds a new MCP server on a different domain connects to it without anyone noticing.

This part closes that gap with automation. An Azure Automation runbook runs every hour, finds every new remote endpoint an AI agent has used, and blocks it with a Defender indicator and an alert. Approved servers are permitted with an Allow indicator. There is no Sentinel dependency, no app registration and no secret to rotate – just a managed identity, two API permissions and three PowerShell scripts.

The same approach covers any agent, not just the ten or so that runtime protection supports. This post tests it with Claude Code, GitHub Copilot CLI and Gemini CLI, which runtime protection does not support.

Why MCP servers need controlling

A remote MCP server is a third-party service that an AI agent sends data to and takes instructions from. Developers add them in minutes, usually without security, procurement or data protection review – and each one becomes a new processor of your organisation’s data.

Key risks of sending corporate data to unapproved MCP servers

Risk What could happen Risk level
Data exfiltration Prompts, documents, credentials, customer information, source code or other sensitive data could be transmitted to the MCP operator. โ— Critical
Loss of data governance Once information is sent outside approved Microsoft 365 and Azure controls, your organisation may lose control over where it is stored, processed or subsequently transferred. โ— Critical
Unknown data retention The MCP provider may log requests, responses, prompts or tool parameters indefinitely, or use different retention policies from your organisation. โ— High
Credential and token exposure OAuth tokens, API keys, connection strings or other authentication material could inadvertently be exposed to a malicious or poorly designed MCP server. โ— Critical
Excessive permissions An MCP server may be granted access to files, databases, Git repositories, email, APIs or cloud services beyond what the user actually needs. โ— Critical
Malicious tool execution A compromised or malicious MCP server could expose tools designed to manipulate an agent into performing unintended actions. โ— Critical
Prompt and tool injection Content returned by an MCP server can influence an AI agent into invoking additional tools or disclosing information it would not normally provide. โ— High
Supply-chain compromise A legitimate MCP server, its dependencies or its hosting environment could subsequently become compromised. โ— High
Data residency Data may be processed or logged in regions that do not meet organisational, customer or regulatory residency requirements. โ— High
Compliance exposure Sending personal, regulated or customer data to an unapproved service could breach GDPR, contractual obligations or internal security policies. โ— High
Lack of auditability Security teams may have little or no visibility of what users sent to the MCP server or what the server subsequently did with it. โ— High
Shadow AI and shadow IT Users can introduce new third-party processors and integrations without security, procurement or data protection review. โ— High

Controlling which MCP servers agents can reach addresses these risks at the source, and brings two further benefits:

  • Visibility. Every block alert is an inventory entry. You learn which servers your DevOps teams actually use, rather than guessing.
  • Any agent. Runtime protection covers a fixed list of agents. Network indicators apply to every process on every onboarded device, so new and unsupported agents are covered too.

How it works

How the MCP-ServerAutoBlock runbook works
  1. An agent connects to a remote MCP server. Defender for Endpoint records the connection in DeviceNetworkEvents.
  2. Every hour, the Automation account’s managed identity runs an advanced hunting query through Microsoft Graph runHuntingQuery for domains that AI agent processes reached.
  3. The runbook drops the agents’ own service domains (a never-block list), any domain with an Allow indicator and any domain that already has an indicator.
  4. Every domain left gets a Block domain indicator with alert generation, created through the Defender for Endpoint indicators API.
  5. Network protection enforces the block on every onboarded device, and each blocked connection raises an alert.
  6. An administrator approves trusted servers by changing the indicator’s action to Allow. Later runs report them as sanctioned and leave them alone.

The default is deny: anything new is blocked until someone approves it. An IndicatorAction parameter switches the runbook to Audit for a tuning period.

What advanced hunting showed first

Before building anything, I ran the runbook’s hunting logic over 30 days of lab data. It returned 63 domains contacted by agent processes. Only one was a remote MCP server reached directly from the device – mcp.context7.com, already blocked in part 4. The rest taught three lessons that shaped the runbook:

  • claude.exe is two products. Claude Code, the CLI, logs with a plain claude.exe command line. The Claude desktop app is an Electron app, and its traffic comes from helper processes with --type=utility on the command line – hCaptcha, Datadog, Sentry and claudeusercontent.com. The runbook excludes those helper processes, so it assesses Claude Code only. The desktop app’s remote connectors only ever appeared as mcp-proxy.anthropic.com, so the MCP server’s own domain is not visible to the device.
  • VS Code hides the extension. All GitHub Copilot extension traffic leaves through VS Code’s shared network service process. Hunting can attribute a connection to code.exe, never to Copilot, so the whole editor is treated as the agent and its own service domains go on the never-block list.
  • Telemetry is noise. Agent and editor telemetry endpoints (datadoghq.com, sentry.io, exp-tas.com) would otherwise be blocked on the first run. They are on the never-block list.

With those changes, replaying the 30 days of data through the runbook produced no new blocks – the right baseline before adding new MCP servers.

Prerequisites

Requirement Detail
Defender for Endpoint Devices onboarded, network protection in block mode and custom network indicators enabled (part 4)
Azure subscription To host the Automation account
Entra role Global Administrator or Privileged Role Administrator, to grant the API permissions
Azure role Automation Contributor or Contributor on the Automation account
PowerShell 7 With the Microsoft Graph and Az modules, on the administrator’s workstation

Step 1 – Create the Automation account

In the Azure portal, search for Automation Accounts and select Create. On Basics, create a resource group such as rg-mcp-automation, name the account aa-mcp-indicators and pick your region.

Create an Automation Account - Basics tab

On Advanced, leave System assigned ticked. This managed identity is what the runbook authenticates as, so there are no credentials to store.

Create an Automation Account - Advanced tab with System assigned ticked

On Networking, choose Public access. The setting only controls inbound access to the account’s own endpoints, such as webhooks and Hybrid Runbook Workers. The runbook’s outbound calls to Graph and the Defender API work either way. Choose private access if your policy requires Private Link on every PaaS resource.

Create an Automation Account - Networking tab with Public access selected

Select Review + Create > Create.

Step 2 – Confirm the managed identity

Open the account and go to Account Settings > Identity > System assigned. Status should be On. The runbook never needs the object ID – Azure Automation provides the identity’s token endpoint inside every job.

Automation account Identity blade with System assigned status On

Step 3 – Grant the API permissions

The managed identity needs two application permissions:

API Permission Used for
Microsoft Graph ThreatHunting.Read.All Advanced hunting through runHuntingQuery
WindowsDefenderATP Ti.ReadWrite.All Reading and creating indicators. The .All permission lets the runbook see indicators created by people as well as its own.

Hunting goes through Microsoft Graph because Microsoft is retiring the Defender for Endpoint and Defender XDR advanced hunting APIs on 1 February 2027 (MC1220762). Indicators stay on the Defender for Endpoint API.

App roles cannot be assigned to a managed identity in the portal, so the first script does it. Run it from PowerShell 7 and enter the tenant and the Automation account name when prompted:

.\Grant-McpRunbookPermissions.ps1
PowerShell output showing ThreatHunting.Read.All and Ti.ReadWrite.All assigned

The script finds the identity by name and contains no tenant-specific IDs. It is safe to re-run – roles already assigned are skipped. New role assignments can take 15-30 minutes to appear in the identity’s tokens.

Step 4 – Create the runbook

Go to Process Automation > Runbooks > Create. Name it MCP-ServerAutoBlock with runbook type PowerShell.

Create a runbook named MCP-ServerAutoBlock, type PowerShell

The classic runbook experience offers PowerShell 7.2 at most. Support for PowerShell 7.1 and 7.2 in Azure Automation has ended, so the runbook should move to a newer runtime. Newer versions are only available through Runtime environments. On the account Overview, select Try Runtime Environment Experience.

Automation account overview with Try Runtime Environment Experience highlighted

Go to Process Automation > Runtime Environments > Create. The system-generated environments stop at 7.2.

Runtime Environments list showing system-generated environments up to PowerShell 7.2

Name the new environment PowerShell-76, language PowerShell, runtime version 7.6, and leave the default packages. The runbook needs no extra modules. In my tenant 7.6 reported itself as a preview (7.6.0-preview.5). Use 7.4 where it is offered and you need a generally available runtime – the runbook runs unchanged on 7.2, 7.4 and 7.6.

Create a Runtime environment named PowerShell-76 with runtime version 7.6

Open the runbook and select Edit > Edit in portal.

Edit menu with Edit in portal highlighted

Set Runtime Environment to PowerShell-76, paste the contents of MCP-ServerAutoBlock.ps1 and select Save. Do not publish yet.

Runbook editor with PowerShell-76 runtime environment selected and Publish highlighted

What the runbook runs

The core of the runbook is a single advanced hunting query. The agent process list and node.exe markers come from Automation variables, with lab-tested defaults:

let agentProcesses = dynamic(['claude.exe', 'copilot.exe', 'code.exe', 'cursor.exe', 'gemini.exe']);
let nodeMarkers = dynamic(['claude', 'copilot', 'gemini']);
DeviceNetworkEvents
| where Timestamp > ago(2h)
| where isnotempty(RemoteUrl)
| where InitiatingProcessFileName in~ (agentProcesses)
    or (InitiatingProcessFileName =~ "node.exe" and InitiatingProcessCommandLine has_any (nodeMarkers))
| where not(InitiatingProcessFileName =~ "claude.exe" and InitiatingProcessCommandLine has "--type=")
| extend HostPart = iff(RemoteUrl has "://", tostring(parse_url(RemoteUrl).Host), tostring(split(RemoteUrl, "/")[0]))
| extend Domain = tolower(trim_end(@"\.", tostring(split(HostPart, ":")[0])))
| where Domain matches regex @"^[a-z0-9-]+(\.[a-z0-9-]+)+$" and not(Domain matches regex @"^[0-9.]+$")
| summarize FirstSeen = min(Timestamp), Connections = count(), Devices = dcount(DeviceId),
            Processes = make_set(InitiatingProcessFileName, 5) by Domain

Agents that run under node.exe, such as Gemini CLI, are matched on their command line. The runbook then compares the results with the never-block list and the tenant’s existing domain indicators before creating anything.

Parameter Default Purpose
DryRun False Report what would be created without creating anything
LookbackHours 2 Overlaps the hourly schedule so nothing is missed
MaxNewIndicators 20 Safety cap per run
IndicatorAction Block Audit logs and alerts only, for tuning

Step 5 – Dry run in the test pane

Select Test pane, set dryRun to True and select Start. The pre-flight checks decode each token and confirm both app roles are present before the runbook does anything else.

Test pane output for MCP-ServerAutoBlock v1.3.0 dry run with all pre-flight checks passed

With no new agent activity in the last two hours, there is nothing to block – and nothing was created. When new MCP servers appear, they show as Would create (Block) in a dry run.

Step 6 – Publish and schedule

Select Publish > Yes. Scheduled runs always use the published version. Then run the third script, which needs no parameters:

.\New-McpRunbookSchedule.ps1
  1. Enter the tenant ID or domain when prompted, for example contoso.onmicrosoft.com.
  2. Sign in to Azure.
  3. If your account can see more than one subscription, type the number shown next to the subscription that holds the Automation account – for example 1 or 10 – and press Enter.
  4. If more than one Automation account has the runbook, type the number of the right one.

The script creates an hourly schedule starting at the next full hour and links it to the runbook with DryRun set to False, LookbackHours to 2 and IndicatorAction to Block. One hour is the most frequent a schedule can run in Azure Automation.

Runbook Schedules blade showing MCP-ServerAutoBlock-Hourly with status On
Schedule properties - recurring every 1 hour, no expiration

Permitting an approved MCP server

Approval lives in Defender, next to the blocks. In the Defender portal, go to Settings > Endpoints > Indicators > URLs/Domains:

  • Already blocked – open the AI agent endpoint (auto, Block): โ€ฆ indicator, change Action to Allow and save.
  • Approving in advance – select Add item, enter the domain, set Action to Allow and record the owner or change reference in the title.

Every later run reports the domain as Sanctioned (Allow). Two rules apply:

  • Change the action, never delete the indicator. If a Block indicator is deleted, the next run sees the domain again and blocks it again.
  • Use the bare domain. As part 4 showed, network protection only sees the domain name for non-browser processes, so a URL-style indicator never matches.

Network protection can take time to pick up indicator changes on a device – in part 4 the device needed a restart. Plan approvals with that delay in mind.

Defender for Cloud Apps is not the right place for this list. It sanctions apps from its catalogue, and most MCP endpoints are not in the catalogue, so they are never discovered as apps and cannot be sanctioned there.

Seeing it work with three agents

To prove the “any agent” claim, I gave three agents a new remote MCP server each, on domains with no indicator. Only Claude Code is on runtime protection’s supported list – Gemini CLI is not supported at all.

Agent MCP server Process Defender sees
Claude Code https://mcp.deepwiki.com/mcp claude.exe
Gemini CLI https://gitmcp.io/docs node.exe (command line contains gemini)
GitHub Copilot CLI https://huggingface.co/mcp copilot.exe

Claude Code

Add the server for the user, so it is available in every folder:

claude mcp add --scope user --transport http deepwiki https://mcp.deepwiki.com/mcp
claude mcp list
claude mcp list showing context7 failing with a TLS handshake error and deepwiki connected

The list shows both sides of the control in one screen. Context7 fails with EPROTO: The TLS handshake failed – that is network protection enforcing the part 4 indicator. DeepWiki, which nobody has reviewed, connects.

Gemini CLI and GitHub Copilot CLI

Both install from npm, so Node.js comes first:

npm install -g @google/gemini-cli
npm install -g @github/copilot
npm installing Gemini CLI and GitHub Copilot CLI

A note on TLS inspection. In my lab the installs first failed: the Node.js download returned 403 and npm reported SELF_SIGNED_CERT_IN_CHAIN. Both were caused by Entra Internet Access (Global Secure Access) web filtering and TLS inspection on the same device. If you run Global Secure Access, add exclusions for nodejs.org and registry.npmjs.org, or set NODE_USE_SYSTEM_CA=1 so Node.js trusts the Windows certificate store. For this test I paused the client, so the only control in the path was Defender for Endpoint.

Gemini CLI signs in with a Gemini API key from Google AI Studio – its Sign in with Google option is no longer offered for individual accounts. Add GitMCP to %USERPROFILE%\.gemini\settings.json:

{ "mcpServers": { "gitmcp": { "httpUrl": "https://gitmcp.io/docs" } } }
Gemini CLI /mcp showing gitmcp ready with 5 tools

Copilot CLI signs in with /login, and the server is added from PowerShell:

copilot mcp add --transport http huggingface https://huggingface.co/mcp
copilot mcp list
Copilot CLI signed in, adding the huggingface MCP server and listing servers

Note the built-in github-mcp-server. Copilot CLI ships with GitHub’s own MCP server already configured, which matters for the shared-domain point below.

What Defender records

A small lab helper, Invoke-McpAgentTest.ps1, runs each agent non-interactively with a prompt that uses its MCP tool. Each agent connects to its MCP servers as it starts, so the connection is logged even when the tool call itself fails. Minutes later, all three appear in advanced hunting:

DeviceNetworkEvents
| where Timestamp > ago(2h)
| where RemoteUrl has_any ("deepwiki.com", "gitmcp.io", "huggingface.co")
| extend Agent = case(
    InitiatingProcessFileName =~ "claude.exe", "Claude Code",
    InitiatingProcessCommandLine has "gemini", "Gemini CLI",
    InitiatingProcessCommandLine has "copilot", "GitHub Copilot CLI",
    InitiatingProcessFileName)
| summarize FirstSeen = min(Timestamp), Connections = count() by Agent, RemoteUrl, InitiatingProcessFileName
| order by FirstSeen asc
Advanced hunting results showing Claude Code, Gemini CLI and GitHub Copilot CLI connecting to their MCP servers

Three details are worth noticing:

  • Gemini CLI is node.exe. Only the command line identifies it, which is why the runbook matches node.exe agents on command-line markers.
  • Copilot CLI is copilot.exe, even when installed from npm – the package runs a native binary.
  • Each server appears twice, once as a bare domain and once as an https:// URL. The runbook reduces both to the bare domain, so each server gets one indicator. The pwsh.exe rows are the test helper’s own reachability check – PowerShell is not in the agent list, so the runbook ignores them.

What the user sees when a server is blocked

When an agent reaches a blocked domain, network protection drops the connection and Windows shows a notification. This is Context7, blocked by the part 4 indicator, being reached when Claude Code started:

Windows Security notification - This content is blocked by your IT admin - mcp.context7.com

Claude Code connects to every configured MCP server at start-up, so the block – and its alert in the Defender portal – happened before anyone asked it a question. DeepWiki, GitMCP and Hugging Face are now in advanced hunting and match none of the never-block entries, so they are exactly what the runbook’s next hourly run picks up: each gets a Block indicator and an alert, and from then on each agent sees this same notification until an administrator approves the server.

GitHub Copilot and shared domains

GitHub hosts its remote MCP server at api.githubcopilot.com/mcp/, and Copilot CLI includes it as a built-in server. Network protection cannot see the /mcp/ path, so a block on api.githubcopilot.com affects everything on that host. In the lab, Copilot Free traffic from VS Code used api.individual.githubcopilot.com for the Copilot service itself, a different host – but Business and Enterprise plans use other hosts, so do not assume the same split.

For that reason githubcopilot.com is on the never-block list, and the runbook does not block GitHub’s own MCP server. Treat it as approved by default. If you want to block it, test with a manual Block indicator on api.githubcopilot.com first and confirm Copilot itself still works on your plan.

Limits to know

  • Detect, then block. A brand-new server is reachable until it appears in advanced hunting and the next run blocks it – typically within one to two hours. A true pre-emptive allow-list belongs at the network edge, in a proxy or egress firewall.
  • Domain only. The runbook cannot tell an MCP server from any other site an agent reaches. A site Claude Code fetches during a web search can be blocked too. Keep the never-block list tuned, review the alerts, and start on Audit if that risk is too high.
  • Shared hosts. Where an MCP server shares a host with the agent’s own service, blocking one blocks both.
  • Electron hosts. VS Code traffic is attributed to code.exe, not to the extension, and the Claude desktop app’s remote connectors are not visible on the device.
  • Indicator alerts. As part 4 found, the indicator’s own alert ignores the severity set on it. Use the part 4 custom detection rule for tailored alerting.

The scripts

The scripts are in the Defender-mcp-server-autoblock repository on GitHub, each with its own README. None contains tenant-specific IDs.

Script Runs Purpose
MCP-ServerAutoBlock Azure Automation, hourly Hunts, compares and blocks new AI agent endpoints
Grant-McpRunbookPermissions Once, by an administrator Grants the managed identity its two API permissions
New-McpRunbookSchedule Once, by an administrator Creates the hourly schedule and links it to the runbook
Invoke-McpAgentTest Lab only, on a test device Makes Claude Code, Gemini CLI and Copilot CLI call their MCP servers, before and after the block

Wrapping up

Part 4 showed that one indicator can stop an agent reaching one MCP server. Part 5 turns that into a standing control: every new remote endpoint an AI agent uses is found within the hour, blocked by default and raised as an alert, and approval is a single change in the Defender portal. It works for any agent you can name, with nothing more than a managed identity, two API permissions and a scheduled runbook.


The rest of the series

References

Seรกn O’Farrell | cloud-secure.ai