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

Microsoft Defender AI agent runtime protection, part 4: controlling where Claude can connect

Microsoft Defender AI agent runtime protection, part 4: controlling where Claude can connect

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 closes a gap the first three exposed: controlling where Claude can connect.

Microsoftโ€™s AI agent runtime protection supports around ten local agents. Defender discovers more than fifty. And none of that decides which remote MCP servers an agent is allowed to reach. This post closes that gap for Claude, with a control most organisations already own - and because the control works at network level rather than inside the agent, the same technique applies to any agent a developer installs.

Every remote MCP server an agent uses is an outbound connection from a developer laptop to a service nobody reviewed. Part 3 query 7 lists them. A Defender for Endpoint custom URL/domain indicator, enforced by network protection, blocks that connection at network level. It does not care which process is asking - Claude here, GitHub Copilot in a later part. A custom detection rule, running every hour, then raises the alert you want and can respond automatically.

At a glance

What it doesWhat it does not do
Blocks any process, including any AI agent, from reaching an unsanctioned remote MCP server Inspect prompts or stop prompt injection - that remains runtime protectionโ€™s job
Records the block on the device, in advanced hunting and in the incident queue Control local (stdio) MCP servers, which make no network connection
Raises a meaningful alert every hour, with automated response actions, through a custom detection rule Separate an MCP server from another service on the same domain - it blocks at domain level

What I learned the hard way

  • Test in Edge and you prove nothing. Edge enforced the indicator hours before network protection did. Every agent kept connecting until the device restarted.
  • Use the bare domain. For HTTPS from anything other than Edge, network protection only sees the domain. A URL with a scheme or path matches in Edge and never for an agent.
  • The agent will not tell the user. Claude reported a TLS handshake error and blamed the URL, a proxy or a firewall.
  • The indicatorโ€™s alert follows its own rules. It ignored the severity and category I set - which is why the detection rule matters.

The control depends only on stable, generally available Defender for Endpoint features: indicators, network protection and the DeviceEvents table. The moving parts are delivery timing, alert behaviour, and the AgentsInfo and exposure graph schemas, which differ from their published documentation and change during preview. The detection logic in this post avoids those tables for that reason.

1. Prerequisites

Two settings decide whether this works at all. Microsoft Edge enforces indicators through SmartScreen, but every other process - including every AI agent - relies on network protection. If network protection is off or in audit mode, your indicator will block the browser and nothing else.

Set network protection to block mode. I used the Defender Antivirus policy in Intune; on the device, EnableNetworkProtection should return 1:

Get-MpPreference | Select-Object EnableNetworkProtection
Intune Defender Antivirus policy with Enable Network Protection set to Enabled (block mode)

Then turn on custom network indicators under Settings > Endpoints > General > Optional features. Without it, indicators save but network protection never enforces them.

Custom network indicators switched on in Defender optional features

2. The test: an agent with a remote MCP server

I used Claude Code because it was already in the lab, but the agent is incidental - the indicator does not care which process makes the connection. For the MCP server I chose Context7, a public documentation server on its own dedicated domain, so blocking it breaks nothing else.

claude mcp add --transport http --scope user context7 https://mcp.context7.com/mcp
Registering Context7 as a remote HTTP MCP server in Claude Code at user scope

Inside Claude Code, /mcp confirms the server is connected. Both of its tools are marked open-world: they reach outside the machine, which is exactly the traffic an indicator can act on.

The /mcp command in Claude Code showing Context7 connected

Before blocking anything, confirm the endpoint is reachable from a non-browser process. A JSON reply - even an error - means the connection got through.

Invoke-WebRequest https://mcp.context7.com/mcp -UseBasicParsing
PowerShell reaching Context7 and receiving a JSON reply

Keep this test to hand. Once the indicator is in place (section 3), the loop below repeats it every 10 minutes and stops the moment the connection is blocked - a server reply of any kind, even an error, counts as not blocked yet. It also reports how long the block took to arrive.

$start = Get-Date
do {
    try {
        Invoke-WebRequest https://mcp.context7.com/mcp -UseBasicParsing -ErrorAction Stop | Out-Null
        Write-Host "$(Get-Date -Format HH:mm) - reached server, not blocked yet"
        $blocked = $false
    }
    catch {
        if ($_.Exception.Response) {
            Write-Host "$(Get-Date -Format HH:mm) - server replied ($($_.Exception.Response.StatusCode)), not blocked yet"
            $blocked = $false
        }
        else {
            Write-Host "$(Get-Date -Format HH:mm) - BLOCKED: $($_.Exception.Message)" -ForegroundColor Green
            $blocked = $true
        }
    }
    if (-not $blocked) { Start-Sleep -Seconds 600 }
} until ($blocked)
Write-Host "Time to block: $([math]::Round(((Get-Date) - $start).TotalMinutes)) minutes"

Do not expect it to be quick. Microsoft documents up to 48 hours for a new URL or domain indicator to reach a device, with most taking effect in under two. In my lab, Edge enforced the indicator within about four hours, but network protection did not block PowerShell or Claude until I restarted the device, roughly twelve hours after creating it. Section 4 covers why. Leave the window open, and keep the device awake so the loop is not interrupted.

3. Creating the custom indicator

Go to Settings > Endpoints > Rules > Indicators, open the URLs/Domains tab and select Add item.

Defender Indicators page with the URLs/Domains tab and Add item

Indicator

Enter the bare domain: mcp.context7.com. For HTTPS from anything other than Edge, network protection only sees the domain name in the TLS handshake - never the scheme or the path. Enter a full URL and it will match in Edge and silently fail for every agent. The portal confirms the type as Domain, which is what you want to see.

Indicator page with mcp.context7.com recognised as indicator type Domain

Action: the possible controls

This page is where the indicator becomes a control.

ActionWhat it does
Allow Never block the domain, overriding other policies. This is how you sanction an MCP server.
Audit Allow the connection and record it. The right starting point in production.
Warn Show a warning the user can bypass. Designed for browsers; for agents with no browser interface, Block is the predictable choice.
Block execution Stop the connection. Used in this test.
Indicator Action page showing Allow, Audit, Warn and Block execution

Alert details and scope

Tick Generate alert so the SOC sees the block, and scope the indicator to a device group - start with the group built from the Part 3 discovery queries. Section 6 shows what Defender actually did with these alert settings.

Indicator alert details: Generate alert, Medium severity, Suspicious activity, recommended actions
Indicator scope set to a specific device group

Save, and the indicator appears in the list with its action, severity and scope.

The saved mcp.context7.com indicator in the URLs/Domains list

4. Proving the block - and the trap

This is the section I would have wanted before starting. A few hours after creating the indicator, I browsed to the domain in Edge and got the โ€œblocked by your organizationโ€ page. Advanced hunting agreed: a SmartScreen warning with Experience CustomBlockList.

Advanced hunting showing Edge blocked by SmartScreen with Experience CustomBlockList

It looked finished. It was not. At the same moment, PowerShell, curl and Chrome on the same device were still reaching the server. Edge checks indicators against the cloud on every visit; network protection works from a list downloaded to the device, and that list had not picked up the new indicator. Seven hours later it still had not.

A restart fixed it. Straight after, PowerShell failed with a TLS handshake error - which is what a network protection block looks like - while httpbin.org, a control indicator added minutes earlier, was still reachable.

After a restart, PowerShell fails to reach Context7 with a TLS handshake failure while httpbin.org is still reachable

The device event log confirms it was Defender and not a coincidence. Event 1126 is a network protection block, and it names the process and the destination.

Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" |
    Where-Object Id -eq 1126 | Select-Object -First 3 | Format-List TimeCreated, Message
Event 1126 showing network protection blocked pwsh.exe from reaching mcp.context7.com

The lesson: if an indicator works in Edge and not for an agent, restart the device before you start troubleshooting. And never use a browser to prove an indicator protects anything else.

5. Blocking the agent

With the block active, I started a fresh Claude Code session. The MCP server now shows as failed.

The /mcp command in a fresh Claude Code session showing Context7 failed

Asking Claude to use the tool produced the most telling screenshot of the test. Claude reported a TLS handshake error and suggested a wrong URL, a proxy or a TLS-inspecting firewall. Nothing told the user the connection had been blocked by policy. A developer would reasonably spend time fixing their MCP configuration, or raise a ticket about a broken tool. Brief your service desk on what this error means before you deploy.

Claude reporting a TLS handshake error and suggesting a URL, proxy or firewall fault

It also respected the instruction not to fall back to web search, so it did not simply route around the block. When I asked it to check the Defender event log, Claude identified the block itself, declined to work around it, and told the user exactly where in the portal to request an Allow indicator. Helpful - and a preview of the precise, well-informed unblock requests your team will start receiving.

Claude reading the Defender event log, identifying the block and declining to work around it

Advanced hunting shows the agent and PowerShell side by side, with ResponseCategory set to CustomBlockList - proof the block came from the indicator rather than web content filtering or Defender for Cloud Apps.

DeviceEvents
| where Timestamp > ago(1d)
| where RemoteUrl has "context7"
| project Timestamp, ActionType, InitiatingProcessFileName, RemoteUrl, AdditionalFields
| order by Timestamp desc
Advanced hunting showing network protection blocks for claude.exe and pwsh.exe

6. The indicatorโ€™s own alert

The block raised an alert, correlated into an incident, with the device, the user and the blocking process as evidence. The alert story shows the detail an analyst needs.

Alerts queue showing Connection to a custom network indicator alerts
Alert story: Network Filter Lookup Service blocked pwsh.exe from accessing mcp.context7.com

What it did not do was honour the indicatorโ€™s alert settings. It arrived as โ€œConnection to a custom network indicatorโ€, severity Informational, category Command and Control, with Microsoftโ€™s generic recommended actions. Neither the Medium severity, the Suspicious activity category nor my recommended actions appeared. If your SOC triages by severity, these alerts will sit at the bottom of the queue. That is the job of the next section.

7. Running it every hour: the custom detection rule

The indicator blocks; the detection rule decides what happens next. A custom detection rule runs an advanced hunting query on a schedule, raises an alert with the title and severity you choose, and can take automated response actions. It also catches blocks from any source - your indicators, Defender for Cloud Apps or web content filtering - as long as the blocked process is an agent.

The query

A detection rule needs Timestamp, ReportId and an impacted asset such as DeviceId in its results. This query returns all three from a single, generally available table. Add the process names of the agents in your estate to the list.

DeviceEvents
| where ActionType == "ExploitGuardNetworkProtectionBlocked"
| where InitiatingProcessFileName in~ ("claude.exe")
| project Timestamp, ReportId, DeviceId, DeviceName,
          InitiatingProcessAccountSid, InitiatingProcessAccountName,
          InitiatingProcessFileName, RemoteUrl, AdditionalFields

Run it in Hunting > Advanced hunting and confirm it returns rows before you build anything on it. Then select Create detection rule.

The detection rule query returning claude.exe blocks, with Create detection rule highlighted

General: name and frequency

Give the rule a name your analysts will recognise, then choose the frequency. The options are Continuous (NRT), every hour, every 3, 12 or 24 hours, or a custom interval. Defender recommends NRT for this query because it reads a single table with no joins.

Detection rule frequency options: Continuous (NRT), Custom, Every hour, Every 3 hours, Every 12 hours

I chose every hour. It gives a predictable cadence for a policy-violation alert, and the 4-hour lookback means a missed run does not lose events. Use NRT if you intend to attach a disruptive action and want it to fire within minutes.

Detection rule General page: name, description, query and Every hour with a 4-hour lookback

Further down the same page, set the severity - Medium for a policy block - tick the Command and Control tactic, and add recommended actions for the analyst. Unlike the indicator, the rule honours all three.

Detection rule severity Medium, MITRE ATT&CK Command and Control, and recommended actions

Alert settings

This is where the rule beats the indicatorโ€™s alert. The title and description accept column values in double braces, so every alert names the agent, the device and the endpoint: AI agent {{InitiatingProcessFileName}} blocked from {{RemoteUrl}}.

Dynamic detection rule alert title and description built from query columns

Entity mapping was filled in automatically from the query: the device from DeviceId, the user from the account SID, and the URL as related evidence. These decide how alerts correlate into incidents.

Detection rule entity mapping: Device to DeviceId, User to InitiatingProcessAccountSid, URL to RemoteUrl

Check the mapping before moving on. If the Device entity points at the wrong column, the alert has no impacted device - and any automated action has nothing to run against.

Incident settings

Leave Include in correlation selected. The ruleโ€™s alerts then join the same incident as the indicatorโ€™s alert for that device and user, so analysts see the whole story in one place.

Detection rule incident settings with Include in correlation selected

Automated actions: the available controls

These run automatically on the entities in each alert. What is available depends on the columns your query returns.

ActionWhat it does
Isolate device Cuts the device off the network except for Defender. The strongest containment, and the most disruptive.
Collect investigation package Gathers forensic data from the device without interrupting the user. A sensible default for this rule.
Run antivirus scan Starts a scan on the device.
Restrict app execution Allows only Microsoft-signed software to run. That stops a third-party agent completely - and almost everything else the developer uses.
Files: Allow/Block, Quarantine Unavailable here, because the query returns no file hash.
Users: Mark user as compromised Unavailable with the SID mapping used here.
Detection rule automated actions: device actions available, file and user actions unavailable

There is no action to block a URL. That is why the indicator does the blocking and the rule handles the response. Start with Collect investigation package, and keep isolation or app restriction for rules you trust completely.

Scope, review and create

Scope the rule to the same device group as the indicator, then review. On creation the rule queries the last 30 days once, so expect alerts for historic blocks straight away.

Detection rule scope set to a specific device group
Detection rule review page: every hour, 4-hour lookback, dynamic alert title

8. Taking this to production

  1. Build the list first. Run Part 3 query 7 to find the remote MCP servers already in use, and decide which are sanctioned.
  2. Allow before you block. Create Allow indicators for sanctioned servers, then Audit for the rest, then Block once you trust what Audit tells you.
  3. Deploy the detection rule alongside. Alert-only to begin with; add automated actions once the alerts are clean.
  4. Brief the service desk. A blocked agent reports a TLS or connection error, not a policy block. Give them the error and the event ID.
  5. Expect unblock requests. Agents will tell users how to ask for an Allow indicator. Have an approval route ready.
  6. Allow for delay. Changes to indicators can take hours to reach network protection, in both directions. An agent can stay blocked after you approve it.

Closing

Runtime protection inspects what an agent reads, for the agents Microsoft supports. Discovery tells you which agents exist. Neither decides where an agent is allowed to connect. A custom indicator does - for Claude in this test, and for any agent that connects over the network - and an hourly detection rule turns each block into an alert with a response attached.

Part 4 is manual by design: someone has to spot a new MCP server and create the indicator. In the next part, an Azure Automation runbook finds new MCP endpoints every hour and creates the indicators for you - with no Sentinel dependency. After that, I run the same control against GitHub Copilot.


The rest of the series

References

Seรกn Oโ€™Farrell | cloud-secure.ai