<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Divyesh Govaerdhanan on Medium]]></title>
        <description><![CDATA[Stories by Divyesh Govaerdhanan on Medium]]></description>
        <link>https://medium.com/@divyeshg94?source=rss-32e75d034c87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kZ2-MkLZkwm_XmWrFWqF0g.jpeg</url>
            <title>Stories by Divyesh Govaerdhanan on Medium</title>
            <link>https://medium.com/@divyeshg94?source=rss-32e75d034c87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:05:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@divyeshg94/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Zero-trust AI agents on Azure, provisioned with Terraform]]></title>
            <link>https://medium.com/microsoft-azure-in-practice/zero-trust-ai-agents-on-azure-provisioned-with-terraform-756ac0c4b7d3?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/756ac0c4b7d3</guid>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[azure-agent]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[microsoft-foundry]]></category>
            <category><![CDATA[ai-agent-security]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 20:28:20 GMT</pubDate>
            <atom:updated>2026-11-03T20:28:20.027Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Five controls every AI agent needs before it touches real data, written as code you can review, version, and prove.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhiMRenWgHPIBVMwCjObaw.png" /><figcaption>Zero Trust AI Agent on Azure with Terraform</figcaption></figure><p>Most AI agent security on Azure lives in the portal. Someone toggles off public access, assigns a role, and tightens a content filter. It works on the day it’s done.</p><p>Then a second environment gets built from memory. A teammate re-enables API keys to debug something and forgets to turn them off. Six months later, nobody can say which agent has which controls, and the audit question “show me” has no good answer.</p><p>Infrastructure as code fixes that. When the security posture is a Terraform file, it’s reviewed in a pull request, it’s identical across environments, and drift shows up in the next plan.</p><p>In this article, you’ll provision a complete zero-trust agent stack on Azure with Terraform: a Microsoft Foundry project, a model deployment, and an agent running on Azure Container Apps. Every control maps to one letter of the AGENT framework, and every control is checked against the live resources at the end.</p><p>The full code is in the companion repo: <a href="https://github.com/divyeshg94/azure-agent-zero-trust-iac">github.com/divyeshg94/azure-agent-zero-trust-iac</a>. It works with both Terraform and OpenTofu.</p><h3>The AGENT framework in one table</h3><p>AGENT is a checklist for securing AI agents on Azure. Each letter is one control, and in this repo each control is one file.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FQAepj%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FQAepj%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FQAepj%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="487" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b52dd26bd36cd2c0a30fa5ed07902be/href">https://medium.com/media/7b52dd26bd36cd2c0a30fa5ed07902be/href</a></iframe><p>One file per pillar is a deliberate choice. A reviewer can open grant.tf and see every permission the agent holds on one screen. In a real platform you&#39;d likely wrap these in modules, but for learning and for review, flat files read better.</p><h3>Before you start</h3><p>You’ll need Terraform 1.11 or later (or OpenTofu 1.11 or later), the Azure CLI, and a subscription where you can create role assignments. You also need model quota in your region. Check it with az cognitiveservices model list --location eastus2.</p><p>This stack targets <strong>AzureRM provider 5.x</strong>, released in July 2026. If you’re used to 4.x, a few things changed that matter here, and I’ll call them out as they come up. The first one shows up in the provider block:</p><pre>provider &quot;azurerm&quot; {<br>  subscription_id = var.subscription_id<br><br># azurerm 5.x registers no resource providers by default.<br>  # Register only what this stack needs, nothing more.<br>  resource_providers_to_register = [<br>    &quot;Microsoft.App&quot;,<br>    &quot;Microsoft.CognitiveServices&quot;,<br>    &quot;Microsoft.Insights&quot;,<br>    &quot;Microsoft.KeyVault&quot;,<br>    &quot;Microsoft.ManagedIdentity&quot;,<br>    &quot;Microsoft.Network&quot;,<br>    &quot;Microsoft.OperationalInsights&quot;,<br>  ]<br>  features {}<br>}</pre><p>In 4.x, the provider tried to register around 60 resource providers on every run. In 5.x, the default is none. That’s a small win for least privilege: the identity running Terraform no longer needs subscription-wide registration rights it never uses.</p><h3>A is for Authenticate: kill the API keys</h3><p>An API key is a password that never expires, can’t be scoped, and doesn’t say who used it. If your agent authenticates with one, anyone who reads the environment variables is your agent.</p><p>The fix is two parts. First, give the agent a managed identity. Second, make the Foundry resource refuse anything else.</p><pre>resource &quot;azurerm_user_assigned_identity&quot; &quot;agent&quot; {<br>  name                = &quot;id-agent-${local.suffix}&quot;<br>  location            = azurerm_resource_group.this.location<br>  resource_group_name = azurerm_resource_group.this.name<br>  tags                = local.tags<br>}<br><br>resource &quot;azurerm_cognitive_account&quot; &quot;foundry&quot; {<br>  name                = &quot;ais-${local.name}&quot;<br>  location            = azurerm_resource_group.this.location<br>  resource_group_name = azurerm_resource_group.this.name<br>  kind                = &quot;AIServices&quot;<br>  sku_name            = &quot;S0&quot;<br>  # Required for Entra ID token auth and for private endpoints.<br>  custom_subdomain_name = &quot;ais-${local.name}&quot;<br>  # Turns this account into a Foundry resource that can hold projects.<br>  project_management_enabled = true<br>  # With local auth off, API keys stop working. Entra ID is the only way in.<br>  local_auth_enabled = false<br>  public_network_access_enabled = false<br>  identity {<br>    type = &quot;SystemAssigned&quot;<br>  }<br>}</pre><p>Three lines carry the weight here.</p><p>kind = &quot;AIServices&quot; with project_management_enabled = true is how you create a current Foundry resource in Terraform. It&#39;s a Cognitive Services account under the hood, and projects live inside it as azurerm_cognitive_account_project.</p><p>custom_subdomain_name looks optional, but it isn&#39;t. Without it, Entra ID token auth and private endpoints both fail. You can&#39;t add it cleanly later either, since changing it forces a new resource.</p><p>local_auth_enabled = false is the line that matters most. The provider default is true. Leave it out and your resource accepts keys, no matter how carefully you wrote the rest.</p><h3>Why user-assigned instead of system-assigned?</h3><p>The Foundry resource itself uses a system-assigned identity, because it lives and dies with the resource. The agent gets a user-assigned identity for a different reason: Terraform can create it, assign its roles, and wait for those roles to exist before the container ever starts. With a system-assigned identity on the container app, the app has to exist first, so its first revision boots with no permissions and fails.</p><p>In your agent code, DefaultAzureCredential picks up this identity through one environment variable, AZURE_CLIENT_ID. No secret is involved at any point.</p><h3>G is for Grant: three roles, three scopes</h3><p>Authentication says who the agent is. Authorization says what it can do, and this is where most agent deployments are far too generous. Contributor on the resource group is common. It lets the agent delete the very resources it runs on.</p><p>This agent needs exactly three things, so it gets exactly three role assignments:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F8i1Pv%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F8i1Pv%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F8i1Pv%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="277" frameborder="0" scrolling="no"><a href="https://medium.com/media/92d8d636a29d2cc79125852a8948f309/href">https://medium.com/media/92d8d636a29d2cc79125852a8948f309/href</a></iframe><pre>locals {<br>  role_ids = {<br>    # Foundry User (formerly Azure AI User)<br>    foundry_user = &quot;53ca6127-db72-4b80-b1b0-d745d6d5456d&quot;<br><br># Key Vault Secrets User<br>    key_vault_secrets_user = &quot;4633458b-17de-408a-b874-0445c86b69e6&quot;<br>    # Monitoring Metrics Publisher<br>    monitoring_metrics_publisher = &quot;3913510d-42f4-4e42-8a64-420c390055eb&quot;<br>  }<br>  role_scope_prefix = &quot;/subscriptions/${var.subscription_id}/providers/Microsoft.Authorization/roleDefinitions&quot;<br>}<br><br>resource &quot;azurerm_role_assignment&quot; &quot;agent_foundry_user&quot; {<br>  scope              = azurerm_cognitive_account_project.agent.id<br>  role_definition_id = &quot;${local.role_scope_prefix}/${local.role_ids.foundry_user}&quot;<br>  principal_id       = azurerm_user_assigned_identity.agent.principal_id<br>  principal_type     = &quot;ServicePrincipal&quot;<br>  description        = &quot;AGENT/Grant: agent identity can use its Foundry project.&quot;<br>}</pre><p>The other two assignments follow the same pattern. Two details are worth stealing for your own code.</p><p><strong>Scope to the project, not the account.</strong> A Foundry account can hold many projects. Assigning Foundry User on the project means a second agent in a second project can’t see this one’s threads, files, or deployments.</p><p><strong>Reference roles by GUID, not by name.</strong> In 2026, Microsoft renamed the Azure AI roles. Azure AI User became Foundry User, Azure AI Owner became Foundry Owner, and so on. <a href="https://learn.microsoft.com/azure/foundry/concepts/rbac-foundry">Microsoft’s docs</a> note that the IDs and permissions didn’t change, but the names did, and you may still see the old names while the rename rolls out. Code that uses role_definition_name = &quot;Azure AI User&quot; is exactly the kind of thing that breaks quietly during a rename. A GUID never changes.</p><p>Setting principal_type = &quot;ServicePrincipal&quot; is a small fix with a real payoff. Without it, Azure tries to look the principal up in Entra ID, and a brand new managed identity often hasn&#39;t replicated yet. Your first apply fails with a principal-not-found error, and your second one works. This line makes the first one work.</p><h3>E is for Encrypt: keep every hop off the internet</h3><p>TLS protects data in transit, and Azure gives you that by default. Zero trust asks a harder question: why is this endpoint on the internet at all? For an agent, the honest answer is usually “it doesn’t need to be.”</p><p>The network has two subnets. One is delegated to Container Apps and runs the agent. The other holds private endpoints for Foundry and Key Vault, behind an NSG that accepts HTTPS from the apps subnet and nothing else.</p><pre>resource &quot;azurerm_subnet&quot; &quot;apps&quot; {<br>  name                 = &quot;snet-apps&quot;<br>  resource_group_name  = azurerm_resource_group.this.name<br>  virtual_network_name = azurerm_virtual_network.this.name<br><br># Workload profile environments need at least a /27. A /23 leaves room to scale.<br>  address_prefixes = [cidrsubnet(var.vnet_address_space, 7, 0)]<br>  delegation {<br>    name = &quot;container-apps&quot;<br>    service_delegation {<br>      name    = &quot;Microsoft.App/environments&quot;<br>      actions = [&quot;Microsoft.Network/virtualNetworks/subnets/join/action&quot;]<br>    }<br>  }<br>}</pre><p>Size this subnet carefully. <a href="https://learn.microsoft.com/azure/container-apps/custom-virtual-networks#subnet">Container Apps can’t resize a subnet</a> after the environment is created. A /27 is the minimum and gives you about 90 Consumption replicas. Outgrowing it means building a new environment.</p><h3>One endpoint, three DNS zones</h3><p>This is the part that catches people. A Foundry resource answers on three hostnames, openai.azure.com, cognitiveservices.azure.com, and services.ai.azure.com, and <a href="https://learn.microsoft.com/azure/private-link/private-endpoint-dns#commercial">each one needs its own private DNS zone</a>.</p><pre>resource &quot;azurerm_private_endpoint&quot; &quot;foundry&quot; {<br>  name                = &quot;pe-foundry-${local.suffix}&quot;<br>  location            = azurerm_resource_group.this.location<br>  resource_group_name = azurerm_resource_group.this.name<br>  subnet_id           = azurerm_subnet.private_endpoints.id<br><br>private_service_connection {<br>    name                           = &quot;foundry&quot;<br>    private_connection_resource_id = azurerm_cognitive_account.foundry.id<br>    subresource_names              = [&quot;account&quot;]<br>    is_manual_connection           = false<br>  }<br>  # One endpoint, three DNS zones. Miss one and some calls leave the VNet.<br>  private_dns_zone_group {<br>    name                 = &quot;foundry&quot;<br>    private_dns_zone_ids = [<br>      azurerm_private_dns_zone.this[&quot;cognitive&quot;].id,<br>      azurerm_private_dns_zone.this[&quot;openai&quot;].id,<br>      azurerm_private_dns_zone.this[&quot;foundry&quot;].id,<br>    ]<br>  }<br>}</pre><p>Most older samples only create privatelink.openai.azure.com, because they were written for Azure OpenAI. With only that zone, chat completions work, but the Agent Service calls on services.ai.azure.com resolve to the public IP and get rejected because public access is off. The error looks like an auth problem. It&#39;s DNS.</p><p>If you’re upgrading from the 4.x provider, note that azurerm_private_dns_zone_virtual_network_link now takes private_dns_zone_id instead of the zone name and resource group. The repo uses the 5.x form.</p><h3>An internal Container Apps environment</h3><p>The last hop is the agent itself. Setting internal_load_balancer_enabled = true puts the environment&#39;s ingress on a private IP inside the VNet.</p><pre>resource &quot;azurerm_container_app_environment&quot; &quot;this&quot; {<br>  name                = &quot;cae-${local.name}&quot;<br>  location            = azurerm_resource_group.this.location<br>  resource_group_name = azurerm_resource_group.this.name<br><br>infrastructure_subnet_id       = azurerm_subnet.apps.id<br>  internal_load_balancer_enabled = var.internal_only<br>  # Logs are routed by a diagnostic setting, so no shared key is needed.<br>  logs_destination = &quot;azure-monitor&quot;<br>  workload_profile {<br>    name                  = &quot;Consumption&quot;<br>    workload_profile_type = &quot;Consumption&quot;<br>  }<br>}</pre><p>You’ll see external_enabled = true on the container app&#39;s ingress later, which looks wrong at first. In an internal environment, &quot;external&quot; means reachable from the VNet, not from the internet. The internal_only variable is the real switch.</p><p>Key Vault gets the same treatment: public_network_access_enabled = false, a private endpoint, and its own privatelink.vaultcore.azure.net zone. It also needs rbac_authorization_enabled = true, which is a required argument in 5.x.</p><h3>N is for Neutralize: guardrails the app can’t skip</h3><p>The first four pillars protect the agent from the outside world. This one protects the outside world, and your data, from the agent.</p><p>Agents have a risk plain chatbots don’t. They read documents, web pages, and tool results, and any of those can carry hidden instructions. That’s indirect prompt injection, and it’s the attack an agent is most likely to meet in production.</p><p>Azure AI Content Safety handles this at the platform layer through a content filter policy. In Terraform, that’s azurerm_cognitive_account_rai_policy:</p><pre>resource &quot;azurerm_cognitive_account_rai_policy&quot; &quot;agent&quot; {<br>  name                 = &quot;agent-strict&quot;<br>  cognitive_account_id = azurerm_cognitive_account.foundry.id<br>  base_policy_name     = &quot;Microsoft.Default&quot;<br><br># Harm categories on both prompt and completion.<br>  # &quot;Low&quot; is the strictest threshold: it blocks low severity and above.<br>  dynamic &quot;content_filter&quot; {<br>    for_each = {<br>      for pair in setproduct([&quot;Hate&quot;, &quot;Sexual&quot;, &quot;Violence&quot;, &quot;SelfHarm&quot;], [&quot;Prompt&quot;, &quot;Completion&quot;]) :<br>      &quot;${pair[0]}-${pair[1]}&quot; =&gt; { name = pair[0], source = pair[1] }<br>    }<br>    content {<br>      name               = content_filter.value.name<br>      source             = content_filter.value.source<br>      filter_enabled     = true<br>      block_enabled      = true<br>      severity_threshold = &quot;Low&quot;<br>    }<br>  }<br>  # Prompt shields. These have no severity threshold.<br>  content_filter {<br>    name           = &quot;Jailbreak&quot;<br>    source         = &quot;Prompt&quot;<br>    filter_enabled = true<br>    block_enabled  = true<br>  }<br>  content_filter {<br>    name           = &quot;Indirect Attack&quot;<br>    source         = &quot;Prompt&quot;<br>    filter_enabled = true<br>    block_enabled  = true<br>  }<br>}</pre><p>The setproduct trick turns four categories times two sources into eight filter blocks without eight copies of the same code. The repo also adds protected material filters for text and code.</p><p>Two gotchas are worth knowing before you write your own. First, filter names are literal strings, and some have spaces: Indirect Attack, Protected Material Text, Protected Material Code. Second, prompt shields don&#39;t take a severity_threshold, so leave it off those blocks.</p><h3>Bind the policy to the deployment</h3><p>A filter policy does nothing until a deployment uses it:</p><pre>resource &quot;azurerm_cognitive_deployment&quot; &quot;chat&quot; {<br>  name                 = var.model_name<br>  cognitive_account_id = azurerm_cognitive_account.foundry.id<br><br>rai_policy_name        = azurerm_cognitive_account_rai_policy.agent.name<br>  version_upgrade_option = &quot;NoAutoUpgrade&quot;<br>  model {<br>    format  = &quot;OpenAI&quot;<br>    name    = var.model_name<br>    version = var.model_version<br>  }<br>  sku {<br>    name     = var.model_sku<br>    capacity = var.model_capacity<br>  }<br>}</pre><p>This is why Neutralize belongs in infrastructure, not application code. The filter is attached to the deployment, so every caller gets it: your agent, a teammate’s notebook, and a script someone writes next year. Nobody can forget to add it.</p><p>NoAutoUpgrade matters for the same reason. A model version change can shift how an agent behaves with its tools. You want that to happen in a pull request, not overnight.</p><p>One honest caveat: a strict filter will block some legitimate requests. Start strict, watch what gets blocked in the Trace queries below, and loosen individual categories with evidence.</p><h3>T is for Trace: one workspace, no shared keys</h3><p>When an agent does something unexpected, the first question is always “what did it actually do?” Trace makes sure that answer exists, in one place, before you need it.</p><p>There’s a trap here that undoes a lot of good work. Log Analytics and Application Insights both default to accepting a shared key. If your observability stack is keyed while everything else is keyless, you’ve just moved the credential, not removed it.</p><pre>resource &quot;azurerm_log_analytics_workspace&quot; &quot;this&quot; {<br>  name                = &quot;log-${local.name}&quot;<br>  location            = azurerm_resource_group.this.location<br>  resource_group_name = azurerm_resource_group.this.name<br>  sku                 = &quot;PerGB2018&quot;<br>  retention_in_days   = var.log_retention_days<br><br>local_authentication_enabled = false<br>}<br><br>resource &quot;azurerm_application_insights&quot; &quot;this&quot; {<br>  name                = &quot;appi-${local.name}&quot;<br>  location            = azurerm_resource_group.this.location<br>  resource_group_name = azurerm_resource_group.this.name<br>  workspace_id        = azurerm_log_analytics_workspace.this.id<br>  application_type    = &quot;other&quot;<br>  local_authentication_enabled = false<br>}</pre><p>With local auth off, telemetry has to arrive with an Entra ID token. That’s why Grant gave the agent the Monitoring Metrics Publisher role. <a href="https://learn.microsoft.com/azure/azure-monitor/app/azure-ad-authentication">Despite the name</a>, it covers all telemetry, not just metrics. The agent also gets one environment variable that tells the SDK to use its identity:</p><pre>env {<br>  name  = &quot;APPLICATIONINSIGHTS_AUTHENTICATION_STRING&quot;<br>  value = &quot;Authorization=AAD;ClientId=${azurerm_user_assigned_identity.agent.client_id}&quot;<br>}</pre><p>This is also why the Container Apps environment uses logs_destination = &quot;azure-monitor&quot; instead of log-analytics. The log-analytics option wires the environment to the workspace with its shared key, and that key is now disabled. A diagnostic setting routes the same logs over Azure Monitor instead.</p><h3>Route everything to one place</h3><p>One for_each sends platform logs from Foundry, Key Vault, and the Container Apps environment to the same workspace:</p><pre>resource &quot;azurerm_monitor_diagnostic_setting&quot; &quot;this&quot; {<br>  for_each = {<br>    foundry  = azurerm_cognitive_account.foundry.id<br>    keyvault = azurerm_key_vault.agent.id<br>    cae      = azurerm_container_app_environment.this.id<br>  }<br><br>name                       = &quot;diag-${each.key}&quot;<br>  target_resource_id         = each.value<br>  log_analytics_workspace_id = azurerm_log_analytics_workspace.this.id<br>  enabled_log {<br>    category_group = &quot;allLogs&quot;<br>  }<br>  enabled_metric {<br>    category = &quot;AllMetrics&quot;<br>  }<br>}</pre><p>In 5.x, the old metric block is gone and enabled_metric replaces it. If you copy a diagnostic setting from an older sample, that&#39;s the first thing that will fail.</p><p>The repo includes starter KQL in queries/agent-trace.kql. Here&#39;s the one I&#39;d put on a dashboard first, Key Vault secret reads by identity:</p><pre>AzureDiagnostics<br>| where TimeGenerated &gt; ago(24h)<br>| where ResourceProvider == &quot;MICROSOFT.KEYVAULT&quot;<br>| where OperationName == &quot;SecretGet&quot;<br>| project TimeGenerated, identity_claim_oid_g, CallerIPAddress, ResultSignature, requestUri_s</pre><p>If any object ID other than the agent’s shows up there, you want to know today, not during an incident review.</p><h3>Deploy it, then prove it</h3><p>The deploy is the usual three commands. Copy terraform.tfvars.example to terraform.tfvars, set your subscription ID, and run:</p><pre>terraform init<br>terraform plan -out tfplan<br>terraform apply tfplan</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*7aLAcdFmbV7WX45w9RilYg.png" /><figcaption>terraform plan</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YksScXJJC0msTopIAYnKFQ.png" /><figcaption>Resources in Azure</figcaption></figure><p>OpenTofu works the same way with tofu in place of terraform. The repo&#39;s GitHub Actions workflow runs fmt, init, and validate against both on every push, plus a Checkov scan.</p><p>Here’s the part most IaC tutorials skip. Declaring a control isn’t the same as having one. A setting can be overridden by policy, changed in the portal, or silently ignored by an API version. So the repo ships scripts/verify.sh, which checks each pillar against the live resources:</p><pre>./scripts/verify.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*XESSECvfmMQbab51_l6pJw.png" /></figure><p>It confirms that Foundry API keys are disabled, the agent identity holds exactly three roles and none of them is Owner or Contributor, Foundry has no public access, Key Vault rejects traffic from outside the VNet, the deployment uses the agent-strict filter, and Foundry logs reach Log Analytics. It exits non-zero on any failure, so you can run it as a pipeline gate after every apply.</p><h3>Things that will surprise you</h3><ul><li><strong>Terraform can’t read your Key Vault secrets.</strong> Public access is off, so data-plane calls from your laptop fail. Create secrets from a pipeline agent inside the VNet.</li><li><strong>You can’t browse to the agent.</strong> With internal_only = true, it&#39;s only reachable from the VNet. Flip it for a demo, then flip it back.</li><li><strong>Destroy doesn’t free the vault name right away.</strong> Purge protection holds it for 7 days. The random suffix keeps redeploys from colliding.</li></ul><h3>Wrapping up</h3><p>Zero trust for AI agents isn’t one setting. It’s five decisions, and each one is easy to get almost right. Writing them as code makes them reviewable, repeatable, and testable.</p><p>Here’s what you built:</p><ol><li><strong>Authenticate</strong>: one managed identity, with API keys disabled at the resource</li><li><strong>Grant</strong>: three role assignments, each on a single resource, referenced by GUID</li><li><strong>Encrypt</strong>: private endpoints with all three Foundry DNS zones, and an internal Container Apps environment</li><li><strong>Neutralize</strong>: a strict content filter with jailbreak and indirect-attack shields, bound to the deployment</li><li><strong>Trace</strong>: keyless Log Analytics and Application Insights, with every component’s logs in one workspace</li></ol><p>Clone the <a href="https://github.com/divyeshg94/azure-agent-zero-trust-iac">companion repo</a>, point container_image at your own agent, and run verify.sh. If something fails, open an issue. I&#39;d like to know which control your environment pushed back on.</p><h3>If this helped</h3><p>If this saved you a debugging session, give it a clap (you can clap up to 50 times) and follow <a href="https://medium.com/@divyeshg94">Microsoft Azure in Practice</a> for more hands-on Azure guides. Questions or a different approach? Leave a response below.</p><p><em>Divyesh Govaerdhanan is a Microsoft MVP in Azure PaaS and the founder of Microsoft Azure in Practice. He builds AI and DevOps tooling on Azure, including </em><a href="https://github.com/divyeshg94/velo"><em>Velo</em></a><em>, an AI-powered DORA metrics extension for Azure DevOps. Connect on </em><a href="https://www.linkedin.com/in/divyeshgovardhanan/"><em>LinkedIn</em></a><em> or </em><a href="https://github.com/divyeshg94"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=756ac0c4b7d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microsoft-azure-in-practice/zero-trust-ai-agents-on-azure-provisioned-with-terraform-756ac0c4b7d3">Zero-trust AI agents on Azure, provisioned with Terraform</a> was originally published in <a href="https://medium.com/microsoft-azure-in-practice">Microsoft Azure in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP on Azure Part 6: Moving a Production MCP Server to the Stateless Spec]]></title>
            <link>https://medium.com/@divyeshg94/mcp-on-azure-part-6-moving-a-production-mcp-server-to-the-stateless-spec-e4461bf2b7b5?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4461bf2b7b5</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[azureops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[mcp-stateless]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 17:43:15 GMT</pubDate>
            <atom:updated>2026-11-01T17:43:15.669Z</atom:updated>
            <content:encoded><![CDATA[<h4>A stateless server still had work to do</h4><p>In <a href="https://medium.com/gitconnected/your-first-mcp-server-in-c-net-build-something-real-in-30-minutes-ea146c8226e2">Part 2</a>, I set Stateless = true on the AzureOps MCP server and called it a production decision. It was. No sticky sessions, no session store, and any Container Apps replica could take any request.</p><p>So when the MCP 2026–07–28 spec shipped and every headline said “sessions are gone,” my first reaction was relief. We had already done the hard part.</p><p>That was about half right.</p><p>On paper, the upgrade is a version bump. The C# SDK team says v2.0 is backward compatible, and a stateless v1 server is already close to what the new spec wants. But the spec changes more than sessions. It adds HTTP headers a gateway can act on, cache hints on tool lists, and a way for a tool to ask the user a question without holding a connection open.</p><p>Each of those lands on something we built earlier in this series: the Container Apps deployment (<a href="https://medium.com/microsoft-azure-in-practice/from-local-to-azure-deploy-your-mcp-server-to-production-78b05bb1e5a9">Part 3</a>), the APIM gateway and per-role tool authorization (<a href="https://medium.com/microsoft-azure-in-practice/securing-your-mcp-server-microsoft-entra-id-azure-api-management-18f6404142e0">Part 4</a>), and the per-user Cosmos DB context (<a href="https://medium.com/microsoft-azure-in-practice/multi-user-mcp-per-user-data-isolation-with-azure-cosmos-db-05209ea0f791">Part 5</a>).</p><p>This part upgrades the real AzureOps server from ModelContextProtocol.AspNetCore 1.3.0 to 2.x. I&#39;ll cover what changed, what I changed, and two places where the new features can quietly weaken your security if you wire them up the obvious way.</p><p>If you run an MCP server on Azure, read this before you bump the package.</p><h3>What changed, mapped to our server</h3><p>The headline change, removing sessions, did nothing for AzureOps. Almost everything else did.</p><p>The <a href="https://modelcontextprotocol.io/specification/2026-07-28/changelog">2026–07–28 changelog</a> is long. I filtered it down to the items that touch a .NET server running behind APIM on Container Apps:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FiMgDJ%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FiMgDJ%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FiMgDJ%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="511" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f814987236dea38fef7f8a7731acd9e/href">https://medium.com/media/1f814987236dea38fef7f8a7731acd9e/href</a></iframe><p>Two rows in that table deserve most of the attention: the new headers and the cache hints. They look like performance features. Used carelessly, they are security bugs.</p><h3>Step 1: Bump the SDK and say what you mean</h3><p>The package change is one line. Pin to the latest 2.x on NuGet rather than a floating version, so a minor release never changes protocol behavior under you.</p><pre>&lt;PackageReference Include=&quot;ModelContextProtocol.AspNetCore&quot; Version=&quot;2.3.0&quot; /&gt;</pre><p>In v1, Stateless defaulted to false. <a href="https://devblogs.microsoft.com/dotnet/announcing-v20-of-the-official-mcp-csharp-sdk/">In v2 it defaults to </a><a href="https://devblogs.microsoft.com/dotnet/announcing-v20-of-the-official-mcp-csharp-sdk/">true</a>, and the old boolean is now a shorthand over a new SessionMode property. Our Part 2 code already set Stateless = true, so it keeps working. I still replaced it:</p><pre>using ModelContextProtocol.AspNetCore;<br><br>builder.Services.AddMcpServer()<br>    .WithHttpTransport(options =&gt;<br>    {<br>        // Explicit on purpose. If the SDK default ever changes again,<br>        // this server&#39;s behavior does not.<br>        options.SessionMode = ModelContextProtocol.AspNetCore.HttpServerSessionMode.Stateless;<br>    })<br>    .WithToolsFromAssembly()<br>    .WithResourcesFromAssembly()<br>    .WithPromptsFromAssembly();</pre><p>The SDK documentation <a href="https://csharp.sdk.modelcontextprotocol.io/v2/concepts/stateless/stateless.html">recommends setting </a><a href="https://csharp.sdk.modelcontextprotocol.io/v2/concepts/stateless/stateless.html">SessionMode explicitly</a> for exactly that reason. It reads better in a code review too: a reviewer sees a decision, not a default.</p><h3>Why I skipped hybrid mode</h3><p>Version 2.3 added HttpServerSessionMode.StatefulForInitializeClients. Older clients get a full session, and 2026-07-28 clients are served statelessly on the same endpoint. Several migration guides recommend it.</p><p>For AzureOps it would be a step backward. We never issued sessions, so no client depends on one. A stateless v2 server still answers the old initialize handshake; it just treats each POST on its own. Switching to hybrid mode would bring back in-memory sessions for older clients, and with them the need for session affinity across Container Apps replicas. We spent Part 3 avoiding exactly that.</p><p>Hybrid mode is for servers that were stateful in v1 and have clients relying on sessions. If you were stateless before, stay stateless.</p><h3>Read the build warnings</h3><p>The upgrade surfaces new diagnostics. Treat them as a checklist, not noise:</p><ul><li>MCP9004: legacy SSE endpoints, now off by default.</li><li>MCP9005: sampling, roots, and MCP logging, now deprecated.</li><li>MCP9006: stateful-only options such as IdleTimeout, which do nothing on a stateless server.</li></ul><p>If MCP9006 shows up on a stateless server, you have dead configuration. Delete it.</p><h3>Check your CORS policy</h3><p>Part 2 used AllowAnyHeader(), so the new headers pass through. If you locked CORS down to a specific header list, add MCP-Protocol-Version, Mcp-Method, Mcp-Name, and any Mcp-Param-* headers your tools declare. This only affects browser-based clients, which is why it&#39;s easy to miss in testing.</p><h3>Step 2: Put the new headers to work in APIM</h3><p>Until now, our APIM gateway from Part 4 could answer one question: is this a valid Entra token for this server? It couldn’t tell which tool was being called. That lived in the JSON-RPC body, and parsing request bodies in a gateway policy is slow and brittle.</p><p>The new spec fixes that. Every Streamable HTTP POST now carries Mcp-Method (for example tools/call) and, for tool calls, Mcp-Name (the tool name). A gateway can route, log, and throttle on headers alone.</p><p>Here is the inbound policy I added on top of the Part 4 token validation. Every user gets a general budget, and the one tool that calls the Azure Resource Manager deployment history API gets a tighter one:</p><pre>&lt;inbound&gt;<br>    &lt;base /&gt;<br>    &lt;validate-azure-ad-token tenant-id=&quot;{{tenant-id}}&quot;<br>                             output-token-variable-name=&quot;jwt&quot;&gt;<br>        &lt;client-application-ids&gt;<br>            &lt;application-id&gt;{{mcp-client-app-id}}&lt;/application-id&gt;<br>        &lt;/client-application-ids&gt;<br>        &lt;audiences&gt;<br>            &lt;audience&gt;{{mcp-server-app-id-uri}}&lt;/audience&gt;<br>        &lt;/audiences&gt;<br>    &lt;/validate-azure-ad-token&gt;<br>&lt;!-- Floor: every caller, every request, keyed on the Entra object ID --&gt;<br>    &lt;rate-limit-by-key calls=&quot;120&quot; renewal-period=&quot;60&quot;<br>        counter-key=&quot;@(((Jwt)context.Variables[&quot;jwt&quot;]).Claims.GetValueOrDefault(&quot;oid&quot;, &quot;unknown&quot;))&quot; /&gt;<br>    &lt;!-- Tighter budget for the ARM-heavy tool --&gt;<br>    &lt;choose&gt;<br>        &lt;when condition=&quot;@(context.Request.Headers.GetValueOrDefault(&quot;Mcp-Name&quot;, &quot;&quot;) == &quot;get_deployment_status&quot;)&quot;&gt;<br>            &lt;rate-limit-by-key calls=&quot;20&quot; renewal-period=&quot;60&quot;<br>                counter-key=&quot;@(((Jwt)context.Variables[&quot;jwt&quot;]).Claims.GetValueOrDefault(&quot;oid&quot;, &quot;unknown&quot;) + &quot;:deployments&quot;)&quot; /&gt;<br>        &lt;/when&gt;<br>    &lt;/choose&gt;<br>&lt;/inbound&gt;</pre><p>Keying on oid keeps this consistent with Part 5, where the same claim is the Cosmos DB partition key. One identity, used the same way at every layer.</p><h3>Don’t trust these headers on their own</h3><p>This is the part most migration posts skip.</p><p>Mcp-Name is sent by the client. The spec keeps the JSON-RPC body as the source of truth, and the server rejects a request whose headers disagree with its body (a HeaderMismatch error). That sounds like it closes the gap. It doesn&#39;t, quite.</p><p>The <a href="https://devblogs.microsoft.com/dotnet/announcing-v20-of-the-official-mcp-csharp-sdk/">SDK team is explicit</a> that servers only enforce the header check once both sides are speaking 2026–07–28. A client that falls back to the old initialize protocol can send any Mcp-Name it likes, or none at all. The server won&#39;t object, because under the old protocol the header means nothing.</p><p>So in the policy above, a client that downgrades walks around the tighter get_deployment_status limit. It still hits the 120-per-minute floor, which is why the floor doesn&#39;t depend on any MCP header.</p><p>Three rules I now follow:</p><ol><li><strong>Never authorize in the gateway based on </strong><strong>Mcp-Name.</strong> Rate-limit with it, log with it, route with it. Authorization stays in the server, where Part 4&#39;s App Role check reads the tool name from the body the server actually executes.</li><li><strong>Keep a floor that ignores MCP headers.</strong> Per-user limits keyed only on the token.</li><li><strong>Once old clients are gone, refuse them at the gateway.</strong> At that point the header becomes trustworthy, because the server guarantees it matches the body.</li></ol><p>The third rule is a short policy, added after token validation:</p><pre>&lt;choose&gt;<br>    &lt;when condition=&quot;@(context.Request.Method == &quot;POST&quot; &amp;&amp; context.Request.Headers.GetValueOrDefault(&quot;MCP-Protocol-Version&quot;, &quot;&quot;) != &quot;2026-07-28&quot;)&quot;&gt;<br>        &lt;return-response&gt;<br>            &lt;set-status code=&quot;400&quot; reason=&quot;MCP 2026-07-28 required&quot; /&gt;<br>        &lt;/return-response&gt;<br>    &lt;/when&gt;<br>&lt;/choose&gt;</pre><p>Don’t turn this on yet. Step 5 shows how to find out whether you can.</p><h3>Step 3: Cacheable tool lists meet per-role tools</h3><p>The new spec lets a server tell clients how long a tools/list result stays fresh (ttlMs) and who may cache it (cacheScope: public or private). It&#39;s the MCP version of Cache-Control, and for most servers it&#39;s a free win. Agents stop re-fetching the same tool list on every turn.</p><p>AzureOps is not most servers.</p><p>In Part 4, some tools required an Entra App Role. I enforced that inside each tool with HttpContext.User.HasClaim(...). The call was blocked, but every user still saw every tool in tools/list. The model would see a tool, try it, get refused, and waste a turn.</p><p>Version 2 of the SDK closes that gap cleanly. Mark tools with [Authorize] and call AddAuthorizationFilters(), and the SDK <a href="https://csharp.sdk.modelcontextprotocol.io/v2/concepts/filters.html">removes unauthorized tools from list results</a> as well as blocking the call:</p><pre>[McpServerTool(Name = &quot;get_deployment_status&quot;)]<br>[Authorize(Roles = &quot;AzureOps.Reader&quot;)]<br>[Description(&quot;Returns recent deployment history for an Azure resource group.&quot;)]<br>public static async Task&lt;DeploymentStatusResult&gt; GetDeploymentStatus(...)</pre><p>This works as long as your JWT setup maps the Entra roles claim to role claims. Microsoft.Identity.Web does this by default.</p><p>Now the trap. The tool list now depends on who is asking. If that list goes out marked public, or with no cacheScope at all, any shared cache is allowed to hand one user&#39;s list to another. The C# SDK&#39;s ListToolsResult docs say a missing cacheScope <a href="https://csharp.sdk.modelcontextprotocol.io/v2/api/ModelContextProtocol.Protocol.ListToolsResult.html">should be treated as </a><a href="https://csharp.sdk.modelcontextprotocol.io/v2/api/ModelContextProtocol.Protocol.ListToolsResult.html">Public</a>. A Reader could be served an Operator&#39;s tool list from a gateway cache, or from a multi-user agent host that caches lists per server.</p><p>The call itself would still fail, because authorization runs on every call. What leaks is metadata: tool names, descriptions, and input schemas for operations that user can’t perform. In an operations tool, that’s a map of what a stolen Operator token could do. Not a breach. Still not something I want to hand out.</p><p>The fix is a list filter that labels the result for what it is:</p><pre>builder.Services.AddMcpServer()<br>    .WithHttpTransport(options =&gt;<br>    {<br>        options.SessionMode = HttpServerSessionMode.Stateless;<br>    })<br>    .AddAuthorizationFilters()<br>    .WithRequestFilters(filters =&gt;<br>    {<br>        filters.AddListToolsFilter(next =&gt; async (context, cancellationToken) =&gt;<br>        {<br>            var result = await next(context, cancellationToken);<br>            // This list varies by App Role, so only the caller&#39;s own client may cache it.<br>            result.CacheScope = CacheScope.Private;<br>            result.TimeToLive = TimeSpan.FromMinutes(5);<br>            return result;<br>        });<br>    })<br>    .WithToolsFromAssembly()<br>    .WithResourcesFromAssembly()<br>    .WithPromptsFromAssembly();</pre><p>Five minutes is my choice, not a rule. Role assignments in Entra don’t change often, and a user who gains a role can reconnect. Pick a number you can explain.</p><p>Two things I kept on purpose:</p><ul><li><strong>The per-call check stays.</strong> The <a href="https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching">caching spec</a> says outright that cacheScope is not an access control. Hiding a tool is a usability feature. The role check that runs on every call is the security feature.</li><li><strong>The runbook resources stay public.</strong> They’re the same for everyone. Marking them private would only throw away cache hits.</li></ul><p>Before you ship, look at the wire, not the code. Call tools/list as two users with different roles and confirm both the different tool lists and &quot;cacheScope&quot;: &quot;private&quot; in each response.</p><h3>Step 4: Ask the user instead of failing</h3><p>In Part 2, I noted that stateless mode rules out elicitation: the server can’t stop mid-tool and ask the user something, because the answer might arrive at a different replica. That was true under the old spec. It isn’t anymore.</p><p>Multi-Round-Trip Requests (MRTR) flip the direction. Instead of the server calling the client, the tool returns a result that says “I need this first.” The client collects the answer and sends the same tools/call again with the answer attached. Nothing is held in server memory between the two calls, so it works on any replica.</p><p>Part 5 gave AzureOps tools a fallback: if the model doesn’t pass a resource group, use the one saved in the user’s Cosmos DB context. That left one ugly case. A new user with no saved default got an error, and the model guessed a resource group name on the next try.</p><p>Now the tool asks:</p><pre>[McpServerTool(Name = &quot;get_deployment_status&quot;)]<br>[Authorize(Roles = &quot;AzureOps.Reader&quot;)]<br>[Description(&quot;Returns recent deployment history for an Azure resource group. &quot; +<br>             &quot;If no resource group is given, uses the user&#39;s saved default.&quot;)]<br>public static async Task&lt;DeploymentStatusResult&gt; GetDeploymentStatus(<br>    McpServer server,<br>    RequestContext&lt;CallToolRequestParams&gt; context,<br>    IHttpContextAccessor http,<br>    IUserContextStore userContext,<br>    DeploymentReader deployments,<br>    [Description(&quot;Resource group name. Optional if the user has a saved default.&quot;)] string? resourceGroup = null,<br>    [Description(&quot;Number of recent deployments to return (max 20)&quot;)] int count = 5,<br>    CancellationToken cancellationToken = default)<br>{<br>    var oid = http.HttpContext!.User.GetObjectId()!;<br>// 1. The user answered on a previous round trip.<br>    if (string.IsNullOrWhiteSpace(resourceGroup) &amp;&amp;<br>        context.Params?.InputResponses?.TryGetValue(&quot;resourceGroup&quot;, out var response) is true)<br>    {<br>        var answer = response.Deserialize(InputResponse.ElicitResultJsonTypeInfo);<br>        if (answer?.IsAccepted is not true)<br>            throw new McpException(&quot;No resource group selected.&quot;);<br>        resourceGroup = answer.Content?.TryGetValue(&quot;resourceGroup&quot;, out var value) is true<br>            ? value.GetString()<br>            : null;<br>        // Remember it, so the question comes up once per user, not once per call.<br>        if (!string.IsNullOrWhiteSpace(resourceGroup))<br>            await userContext.SaveDefaultResourceGroupAsync(oid, resourceGroup, cancellationToken);<br>    }<br>    // 2. Part 5 fallback: the saved default.<br>    if (string.IsNullOrWhiteSpace(resourceGroup))<br>        resourceGroup = (await userContext.GetAsync(oid, cancellationToken))?.DefaultResourceGroup;<br>    // 3. Still nothing. Ask, if this client can answer.<br>    if (string.IsNullOrWhiteSpace(resourceGroup))<br>    {<br>        if (!server.IsMrtrSupported)<br>            throw new McpException(<br>                &quot;No resource group given and no saved default. Pass resourceGroup explicitly.&quot;);<br>        throw new InputRequiredException(<br>            inputRequests: new Dictionary&lt;string, InputRequest&gt;<br>            {<br>                [&quot;resourceGroup&quot;] = InputRequest.ForElicitation(new ElicitRequestParams<br>                {<br>                    Message = &quot;Which resource group should I check? I&#39;ll save it as your default.&quot;,<br>                    RequestedSchema = new()<br>                    {<br>                        Properties =<br>                        {<br>                            [&quot;resourceGroup&quot;] = new ElicitRequestParams.StringSchema<br>                            {<br>                                Title = &quot;Resource group&quot;,<br>                                Description = &quot;For example rg-payments-prod&quot;<br>                            }<br>                        }<br>                    }<br>                })<br>            },<br>            requestState: &quot;select-rg&quot;);<br>    }<br>    return await deployments.GetRecentAsync(resourceGroup, Math.Min(count, 20), cancellationToken);<br>}</pre><p>The IsMrtrSupported branch matters. A client still on the old protocol, talking to a stateless server, can&#39;t be asked anything. The <a href="https://devblogs.microsoft.com/dotnet/announcing-v20-of-the-official-mcp-csharp-sdk/">SDK&#39;s compatibility table</a> lists that combination as unsupported. Those clients get a plain error that tells the model exactly which argument to send.</p><p>An answer from the user is still input. The tool validates it the same way it validates a resourceGroup argument from the model, because that&#39;s all it is.</p><h3>Be careful with requestState</h3><p>InputRequiredException takes a requestState string, and the client sends it back on the retry. It&#39;s tempting to stash things there: a half-built query, a resolved resource ID, a flag that says &quot;already authorized.&quot;</p><p>Don’t. The client controls that string. Anything you read back from it is as trustworthy as a query parameter. I pass a fixed label and nothing else. Everything the tool needs is either in the retried arguments or in Cosmos DB, keyed by the token’s oid.</p><p>If you do need to carry server data across the round trip, protect it with ASP.NET Core Data Protection and bind the purpose to the user’s oid, so one user&#39;s state can&#39;t be replayed as another&#39;s. On Container Apps, that comes with a catch. The retry can land on a different replica, so every replica needs the same key ring. Persist the keys to Blob Storage and protect them with Key Vault. Otherwise you&#39;ll see failures that only show up under scale-out, which is the worst kind to debug.</p><h3>Step 5: Find out which clients are still on the old protocol</h3><p>Steps 2 and 4 both turn on one fact you probably don’t know: how many of your callers have moved to 2026–07–28. VS Code, Foundry agents, custom clients built on older SDKs. They upgrade on their own schedules.</p><p>I didn’t know either, so I measured it before deciding anything.</p><p>The SDK already tags its tracing spans with mcp.protocol.version, according to the <a href="https://csharp.sdk.modelcontextprotocol.io/v2/concepts/stateless/stateless.html">SDK&#39;s observability docs</a>. All it takes is sending those spans to Application Insights:</p><pre>builder.Services.AddOpenTelemetry()<br>    .UseAzureMonitor()<br>    .WithTracing(tracing =&gt; tracing.AddSource(&quot;ModelContextProtocol&quot;));</pre><p>Then one query tells you where you stand:</p><pre>union requests, dependencies<br>| where timestamp &gt; ago(14d)<br>| extend version = tostring(customDimensions[&quot;mcp.protocol.version&quot;])<br>| where isnotempty(version)<br>| summarize calls = count() by version, day = bin(timestamp, 1d)<br>| order by day desc</pre><p>This turns “can we drop old clients?” from a guess into a rule. Mine is simple: when the old protocol shows zero calls for 14 days in a row, I turn on the APIM gate from Step 2. Until then, the gate stays off and the per-user floor does the work.</p><h3>What this doesn’t solve</h3><ul><li><strong>Hiding a tool is not access control.</strong> Step 3 improves what the model sees. The per-call authorization is still what protects you.</li><li><strong>Old clients lose the nice path.</strong> On a stateless server, a client on the old protocol can’t answer an MRTR question. It gets a clear error instead. That’s acceptable for AzureOps. It may not be for you.</li><li><strong>Gateway rules on MCP headers are hints until the gate is on.</strong> Until every client speaks 2026–07–28, a client can lie about Mcp-Name. Plan your limits around that.</li><li><strong>I haven’t adopted Tasks yet.</strong> The new Tasks extension fits long-running ARM operations, but AzureOps tools are all short reads today. That’s a later part.</li></ul><h3>Upgrade checklist</h3><p>If you take one thing from this part, take this list:</p><ol><li>Pin ModelContextProtocol.AspNetCore to the latest 2.x and set SessionMode explicitly.</li><li>If you were stateless in v1, stay stateless. Skip hybrid mode.</li><li>Work through every MCP9004, MCP9005, and MCP9006 warning.</li><li>Add the new MCP headers to any CORS allow-list.</li><li>Use Mcp-Name in APIM for limits and logs, never for authorization.</li><li>Keep a per-user rate limit that ignores MCP headers.</li><li>If your tool list depends on the caller, mark it cacheScope: private, and check the wire to confirm.</li><li>Replace “missing argument” errors with MRTR questions, with a plain-error fallback for old clients.</li><li>Treat requestState as untrusted input.</li><li>Track the protocol version of every call before you block old clients.</li></ol><p>The full source for this part is on GitHub: <a href="https://github.com/divyeshg94/AzureOpsMcpServer/tree/part6">AzureOpsMCPServer</a>.</p><h3>Sources</h3><ul><li><a href="https://modelcontextprotocol.io/specification/2026-07-28/changelog">MCP 2026–07–28 specification changelog</a></li><li><a href="https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching">MCP caching specification (2026–07–28)</a></li><li><a href="https://devblogs.microsoft.com/dotnet/announcing-v20-of-the-official-mcp-csharp-sdk/">Announcing v2.0 of the official MCP C# SDK, .NET Blog</a></li><li><a href="https://csharp.sdk.modelcontextprotocol.io/v2/concepts/stateless/stateless.html">MCP C# SDK: Stateless and stateful mode</a></li><li><a href="https://csharp.sdk.modelcontextprotocol.io/v2/concepts/filters.html">MCP C# SDK: Server filters</a></li><li><a href="https://csharp.sdk.modelcontextprotocol.io/v2/api/ModelContextProtocol.Protocol.ListToolsResult.html">MCP C# SDK: ListToolsResult API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4461bf2b7b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective GitHub Copilot — Part 2: Surviving the Token Era]]></title>
            <link>https://levelup.gitconnected.com/effective-github-copilot-part-2-surviving-the-token-era-dd3e35f73375?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd3e35f73375</guid>
            <category><![CDATA[copilot-usage-dashboard]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-token]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[ai-coding]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 15:27:38 GMT</pubDate>
            <atom:updated>2026-09-08T15:27:38.783Z</atom:updated>
            <content:encoded><![CDATA[<h4>Premium requests are gone. GitHub AI Credits are here. Here’s how to get the maximum out of every credit, without changing how much you pay.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqZ2gF5URIWcM50TZeqIHg.png" /><figcaption>Effective Usage of GitHub Copilot — Part 2</figcaption></figure><p>In <a href="https://levelup.gitconnected.com/a-production-ready-copilot-workflow-for-net-0ad2e7183018">Part 1</a>, I shared a production-ready Copilot workflow for .NET, a copilot-instructions.md template, a prompt catalogue, and a reference codebase that turns Copilot from a fancy autocomplete into a reliable engineering partner.</p><p>Since then, the ground has shifted. On June 1, 2026, GitHub retired the premium request model and moved every Copilot plan to <strong>usage-based billing</strong> built on <strong>GitHub AI Credits</strong>. Your usage is now metered the same way the underlying model APIs are metered: by tokens for input, output, and cached at each model’s published API rates.</p><p>This changes the economics of how you work. Under premium requests, a two-word chat question and a forty-minute agent session across your whole repository cost exactly the same: one request (times a model multiplier). That pricing fiction is over. GitHub said it plainly in the announcement: agentic usage is becoming the default, and the old model was no longer sustainable.</p><p>The good news: nothing about <em>your bill</em> has to change. Base plan prices stayed the same, and the workflow discipline from Part 1 (clear instructions, scoped prompts, deterministic guardrails ) is no longer just a quality practice. It’s now literally how you save money. This article covers how the new billing works, and a practical playbook for getting the most out of your credits.</p><h3>What actually changed on June 1, 2026</h3><p>The mechanics, straight from GitHub’s documentation:</p><ul><li><strong>Premium request units (PRUs) are replaced by GitHub AI Credits.</strong> 1 AI credit = $0.01 USD.</li><li><strong>Usage is calculated from token consumption</strong> — input tokens, output tokens, and cached tokens — using the listed API rate for each model.</li><li><strong>Base plan prices didn’t change.</strong> Pro is still $10/month, Pro+ $39, Max $100, Business $19/user, Enterprise $39/user.</li><li><strong>Code completions and next edit suggestions remain unlimited</strong> on all paid plans. They don’t consume credits at all.</li><li><strong>The fallback model is gone.</strong> Previously, exhausting your premium requests dropped you to a lower-cost model and you kept working. Now, when your credits run out, you either buy more, upgrade, or stop.</li><li><strong>Credits don’t roll over.</strong> Your allowance resets at 00:00 UTC on the 1st of each calendar month, regardless of your subscription date.</li></ul><h3>What each plan includes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ev96RuNNb1aaXMGORGk2cw.png" /></figure><p>Two details worth noticing here.</p><p>First, there’s a new top tier: <strong>Copilot Max</strong> aimed at heavy agentic users. Second, the <strong>flex allotment</strong> is deliberately variable: GitHub describes it as designed to “adapt as the economics of AI evolve.” Your base credits match your subscription price and never change; the flex portion is a buffer that GitHub can tune as model prices move. Plan your workflow around base credits and treat flex as a bonus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dCMB-qcgIdYxE0gL0eOiQ.png" /></figure><p>For organizations, Business ($19/user) and Enterprise ($39/user) credits are <strong>pooled</strong> across the billing entity, one person’s unused allowance is no longer stranded capacity. Admins get budget controls at the enterprise, cost center, and individual level.</p><h3>The new mental model: three levers, one bill</h3><p>Every credit you spend is a function of exactly three things:</p><p><strong>Cost = Model rate × Tokens processed × Number of attempts</strong></p><p>That’s it. Every optimization in the rest of this article pulls on one of those three levers. Let’s look at the model rates first, because the spread is dramatic.</p><h3>Know your rates</h3><p>All prices are per 1 million tokens (from GitHub’s <a href="https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing">model pricing reference</a>, as of August 2026):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F2HaNk%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F2HaNk%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F2HaNk%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="676" frameborder="0" scrolling="no"><a href="https://medium.com/media/92d878b8cacb6ea9fd095aca91335524/href">https://medium.com/media/92d878b8cacb6ea9fd095aca91335524/href</a></iframe><p>Read that table again. The gap between GPT-5.4 nano and Claude Fable 5 is <strong>50x on input and 40x on output</strong>. Routing a documentation update through a frontier reasoning model isn’t a rounding error anymore, it’s a 40x overspend on that task.</p><p>Also note the <strong>cached input</strong> column: on most models, cached tokens cost roughly <strong>10% of fresh input</strong>. That single fact drives several of the tactics below. (One nuance: Anthropic models also bill <em>cache writes</em> separately, e.g., $3.75/M for Sonnet 4.6, so their caching advantage kicks in on reuse, not on the first pass.)</p><h3>The optimization playbook</h3><h3>1. Let the free tier do the heavy lifting</h3><p>Code completions and next edit suggestions are unlimited on every paid plan and consume zero credits. This sounds obvious, but it changes behavior: if you’re about to open chat to ask “write a null check for this parameter,” stop. Type the first few characters and let completions finish it. The muscle memory of “chat for everything” was harmless under premium requests when chat with the base model was unlimited. Now every chat turn meters tokens.</p><p>A useful habit: <strong>completions for code you can start, chat for code you can’t.</strong></p><h3>2. Match the model to the task — and let auto selection earn you 10%</h3><p>GitHub’s own guidance is blunt about this: defaulting to the most capable model for everything often increases token usage <em>without improving the outcome, </em>reasoning models can overthink execution-heavy tasks and introduce unnecessary changes.</p><p>A practical tiering that has worked well for me:</p><ul><li><strong>Lightweight (nano/mini/Flash):</strong> renames, formatting, doc comments, commit messages, simple refactors, test scaffolding.</li><li><strong>Versatile (Sonnet, GPT-5.4, Terra):</strong> day-to-day feature work, executing an already-agreed plan, writing tests against a spec.</li><li><strong>Powerful (Opus, GPT-5.5, Fable):</strong> architecture decisions, gnarly debugging, system design, planning phases. Use them to <em>think</em>, then hand the plan to a cheaper model to <em>type</em>.</li></ul><p>And here’s an easy win most people miss: paid plans get a <strong>10% discount on model costs when using auto model selection</strong> in Copilot Chat, CLI, and the cloud agent. If you don’t have a strong opinion about the model for a given task, auto selection is both the lazier and the cheaper choice.</p><h3>3. Structure sessions to exploit the cache</h3><p>Cached input is ~10x cheaper than fresh input, and agent sessions resend context on every model call. The implications:</p><ul><li><strong>Finish a scoped task in one session.</strong> A single session within a reasonable scope reuses cached context on every iteration. Abandoning and restarting means paying full input price to rebuild the same context.</li><li><strong>But don’t drag one session across unrelated tasks.</strong> A bloated conversation carries every earlier file, log, and dead end into each new call, you’re paying (even at cache rates) for context that adds nothing. When you switch tasks, start fresh.</li></ul><p>The rule of thumb: <strong>one task, one session. New task, new session.</strong></p><h3>4. Research → Plan → Implement, as separate phases</h3><p>This was the backbone of the Part 1 workflow, and GitHub’s optimization guide now recommends exactly this split:</p><ol><li><strong>Research</strong> with a cheap model: explore the codebase, identify the relevant files and dependencies.</li><li><strong>Plan</strong> with a powerful model: produce a detailed, structured spec. This is where frontier reasoning is worth every credit.</li><li><strong>Implement</strong> in a fresh session with a mid-tier model, feeding it only the plan and the files that matter.</li></ol><p>The expensive model never sees your full repository; the cheap model never has to make judgment calls. Each phase operates with only the context it needs. In my experience this is the single biggest lever for agentic work, not because any one phase is cheap, but because it collapses the <em>number of attempts</em>, which is the lever nobody talks about.</p><h3>5. Kill retries with deterministic guardrails</h3><p>The biggest driver of wasted tokens isn’t verbose prompts it’s <strong>failed attempts that compound</strong>. An agent builds on its own incorrect output, drifts, and you burn a second and third session untangling it.</p><p>Guardrails give the agent pass/fail signals it can react to <em>within</em> a session:</p><ul><li><strong>Unit tests</strong> the agent must run after changes</li><li><strong>Linters and analyzers</strong> (for .NET folks: dotnet format, Roslyn analyzers, TreatWarningsAsErrors)</li><li><strong>Build + security scans</strong> wired into the loop</li></ul><p>GitHub’s guidance is explicit that teams investing in these guardrails often reduce <em>total</em> token consumption even though individual steps use slightly more tokens upfront. Paying a few tokens for a dotnet test run is dramatically cheaper than a fresh debugging session tomorrow.</p><h3>6. Audit your copilot-instructions.md it&#39;s billed on every run</h3><p>The instructions file from Part 1 just became a line item. It’s injected into the agent’s context on <strong>every single run</strong>, which cuts both ways:</p><ul><li>A concise, accurate instructions file <em>reduces</em> spend by preventing repeated mistakes and unnecessary exploration.</li><li>A bloated one is a tax on every interaction — and generic filler (“write clean code”, pasted style guides) actively degrades quality by adding noise.</li></ul><p>Keep what earns its tokens: build/test/lint commands, required frameworks and patterns, pitfalls the agent actually repeats, output expectations. Delete the rest. My template from Part 1 fits comfortably under a page, that’s deliberate, and now it’s also frugal.</p><h3>7. Prompt with a stopping condition</h3><p>Vague prompts force the agent to infer intent, explore more files, and make judgment calls, all metered. GitHub’s guidance names three qualities of an efficient prompt, and the third is the one most developers skip:</p><ol><li>A clear task definition (what, where, expected outcome)</li><li>Relevant context upfront (the files, errors, and logs you already know matter)</li><li><strong>A clear stopping condition</strong> — what “done” looks like</li></ol><p>Without a stopping point, agents keep going: extra commits, drive-by refactors, scope creep. Every one of those tokens is billed. “Fix the 500 error in OrdersController.CreateOrder when the request body has no line items; done when the new unit test in OrdersControllerTests passes; don&#39;t touch other endpoints&quot; is a budget instrument, not just a good prompt.</p><h3>8. Watch the sneaky consumers</h3><p>A few things meter credits (or adjacent budgets) in ways that surprise people:</p><ul><li><strong>Copilot code review</strong> bills token consumption in AI credits <em>and</em> consumes GitHub Actions minutes for the agentic infrastructure and the model it uses isn’t disclosed, so costs vary between reviews. Re-running review on every push of a WIP branch adds up twice. Request it when the PR is actually ready.</li><li><strong>Copilot Spaces, Spark, and third-party coding agents</strong> all draw from the same credit pool.</li><li><strong>Long-context tiers</strong>: several models (GPT-5.4, GPT-5.5, Gemini 3.1 Pro) double their input rate once a request crosses their context threshold (200K–272K tokens). Feeding an agent your entire solution doesn’t just cost more linearly, it can push you into a more expensive tier.</li></ul><h3>9. Set budgets before you need them</h3><p>The tooling is there; use it on day one, not after a surprise:</p><ul><li><strong>Individuals:</strong> the usage dashboard shows credit consumption per feature and model. Set an additional-usage budget in Settings → Billing — including $0 if you want a hard stop at your included allowance.</li><li><strong>Copilot CLI:</strong> supports session-level credit limits, so a runaway agentic session caps itself.</li><li><strong>Organizations:</strong> set budgets at enterprise, cost center, and user level, and decide deliberately whether exhausting the pool blocks work or spills into paid usage. Track code review’s Actions consumption by filtering on the copilot-pull-request-reviewer workflow.</li></ul><p>One more thing worth knowing: if you hit your ceiling mid-month, <strong>upgrading costs only the difference</strong> between your current plan and the next tier, and your existing usage counts within the new, larger allowance. If you’re consistently buying overage on Pro, the math usually favors upgrading.</p><h3>Let’s put numbers on it</h3><p>A realistic agent-mode task, fix a bug across three files, with an instructions file, relevant sources, and a few tool-call iterations. Say the session processes ~400K input tokens across iterations (most of it repeated context) and generates ~20K output tokens.</p><p><strong>Careless version: </strong>Frontier model (GPT-5.5 at $5.00/$30.00), restarted once after a bad first attempt, little cache reuse:</p><ul><li>~800K fresh input ≈ $4.00, ~40K output ≈ $1.20 → <strong>~$5.20 = 520 credits</strong></li></ul><p><strong>Disciplined version: </strong>Plan with GPT-5.5 in a short session (~30K in / 3K out ≈ 24 credits), execute with GPT-5.4 ($2.50/$0.25/$15.00) in one session where ~85% of input is cached:</p><ul><li>60K fresh ≈ $0.15, 340K cached ≈ $0.09, 20K output ≈ $0.30 → ~54 credits, <strong>plus</strong> planning ≈ <strong>~78 credits total</strong></li></ul><p>Same task, same quality — arguably better, because the plan was explicit. <strong>Roughly 7x cheaper.</strong> On a Pro plan, one path gives you about three such tasks a month before you’re buying credits; the other gives you around twenty from your monthly allowance.</p><p>The point isn’t the exact numbers, your token counts will differ. The point is that model choice, caching, and attempt count <em>multiply</em>. Optimize all three and an entry-level plan goes a surprisingly long way.</p><h3>The bottom line</h3><p>The shift to token-based billing feels like a loss of innocence, one flat request per question was easy to reason about. But it’s also more honest, and it rewards exactly the habits that were already best practice:</p><ol><li><strong>Free first</strong> — completions and next edit suggestions cost nothing</li><li><strong>Right-size the model</strong> — think with powerful, type with lightweight, default to auto for the 10% discount</li><li><strong>One task, one session</strong> — exploit caching, don’t hoard context</li><li><strong>Plan before you implement</strong> — expensive models for thinking, cheap ones for typing</li><li><strong>Guardrails over retries</strong> — tests and linters are the cheapest tokens you’ll ever spend</li><li><strong>Keep instructions lean</strong> — you pay for them on every run</li><li><strong>Budget before you’re surprised</strong> — dashboards, session limits, spend caps</li></ol><p>If you set up the workflow from Part 1, you’re already most of the way there. The instructions file, the prompt catalogue, the guardrails, they were quality tools in the premium-request era. In the token era, they’re your cost controls too.</p><p><em>If you haven’t read </em><a href="https://levelup.gitconnected.com/a-production-ready-copilot-workflow-for-net-0ad2e7183018"><em>Part 1</em></a><em>, it walks through the full workflow setup, the instructions template, the prompt catalogue, and a reference .NET codebase to try all of this on.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/">GitHub Copilot is moving to usage-based billing — The GitHub Blog</a></li><li><a href="https://docs.github.com/en/copilot/concepts/billing/usage-based-billing-for-individuals">Usage-based billing for individuals — GitHub Docs</a></li><li><a href="https://docs.github.com/copilot/reference/copilot-billing/models-and-pricing">Models and pricing — GitHub Docs</a></li><li><a href="https://docs.github.com/en/copilot/tutorials/optimize-ai-usage">Improving agent quality to optimize AI usage — GitHub Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd3e35f73375" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/effective-github-copilot-part-2-surviving-the-token-era-dd3e35f73375">Effective GitHub Copilot — Part 2: Surviving the Token Era</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-User MCP: Per-User Data Isolation with Azure Cosmos DB]]></title>
            <link>https://medium.com/microsoft-azure-in-practice/multi-user-mcp-per-user-data-isolation-with-azure-cosmos-db-05209ea0f791?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/05209ea0f791</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[rbac-access-control]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 21:21:16 GMT</pubDate>
            <atom:updated>2026-08-02T21:21:16.228Z</atom:updated>
            <content:encoded><![CDATA[<h4>Every authorized caller sees the same subscription data. That’s not multi-user — that’s shared access with a login screen.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UieK2eBdz3B8DeIbH8ucTQ.png" /><figcaption>Multi-User MCP Server</figcaption></figure><p>After <a href="https://medium.com/microsoft-azure-in-practice/securing-your-mcp-server-microsoft-entra-id-azure-api-management-18f6404142e0?sharedUserId=divyeshg94">Part 4</a>, the AzureOps MCP Server has proper authentication. A caller needs a valid Entra ID token and the right App Role to get through. That&#39;s necessary, but it isn&#39;t sufficient.</p><p>Here’s the gap: right now, every tool call requires the caller to pass subscriptionId and resourceGroup as explicit parameters. There&#39;s nothing in the server that ties a caller&#39;s identity to <em>their</em> data. User A can pass User B&#39;s subscription ID and get back User B&#39;s deployment history. The authentication layer verified <em>who</em> they are. It said nothing about <em>what data they&#39;re allowed to see</em>.</p><p>Part 5 fixes this in two ways:</p><p><strong>Per-user context:</strong> Each caller has a saved profile in Cosmos DB, their default subscription, their watched resource groups, their preferences. Tools can load this context automatically instead of requiring parameters every single call.</p><p><strong>Per-user history:</strong> Incident notes, triage logs, and observations are stored per-user, partitioned by their Entra ID identity. User A’s notes are physically separated from User B’s at the database level, not just filtered in application code.</p><p>The result: a server where “check deployment status” works without the caller typing their subscription ID every time, and where every piece of stored data is cryptographically bound to a specific identity.</p><h3>What Changes From Part 4</h3><p>Three additions:</p><ol><li><strong>Azure Cosmos DB</strong> — a NoSQL account with two containers: user-contexts (one document per user, stores preferences) and incident-notes (many per user, stores triage history). Both partitioned by /userId.</li><li><strong>Four new tools</strong> — save_user_context, get_user_context, log_incident_note, get_incident_history. These give the agent a memory layer per user.</li><li><strong>Updated existing tools</strong> — get_deployment_status, get_resource_tags, and check_resource_health now fall back to the caller&#39;s saved context when subscriptionId or resourceGroup are not explicitly provided. The agent can call them with zero parameters if the user has saved their defaults.</li></ol><p>The identity that ties everything together: the oid claim from the Entra ID JWT token. Object ID is stable across sessions, devices, and app registrations — it never changes for a given user in your tenant. We never use sub (subject) for this purpose — it&#39;s app-specific and changes across app registrations.</p><h3>Phase 1 — Provision Cosmos DB</h3><pre>$RG=&quot;rg-azureops-mcp&quot;<br>$COSMOS_ACCOUNT=&quot;azureops-mcp-cosmos&quot;<br>$LOCATION=&quot;eastus&quot;<br><br># Create Cosmos DB account - NoSQL API, serverless for dev/test<br>az cosmosdb create \<br>  --name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --kind GlobalDocumentDB \<br>  --capabilities EnableServerless \<br>  --default-consistency-level Session \<br>  --locations regionName=$LOCATION<br><br># Create database<br>az cosmosdb sql database create \<br>  --account-name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --name &quot;azureops-mcp-db&quot;<br><br># Container 1: user-contexts - one document per user<br>az cosmosdb sql container create \<br>  --account-name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --database-name &quot;azureops-mcp-db&quot; \<br>  --name &quot;user-contexts&quot; \<br>  --partition-key-path &quot;/userId&quot;<br><br># Container 2: incident-notes - many per user<br>az cosmosdb sql container create \<br>  --account-name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --database-name &quot;azureops-mcp-db&quot; \<br>  --name &quot;incident-notes&quot; \<br>  --partition-key-path &quot;/userId&quot;</pre><p>EnableServerless is the right SKU for this workload — tool calls are bursty and infrequent, not sustained high-throughput. You pay per request unit consumed, not per hour of provisioned throughput. For a team of 20 engineers making 500 tool calls per day, serverless costs pennies.</p><h3>1.1 — Grant the Container App Data Plane Access</h3><p>Cosmos DB has two separate RBAC systems: Azure RBAC (what we used in Part 3 for ARM calls) and Cosmos DB data plane RBAC. The Container App’s Managed Identity needs the data plane role — Azure Reader is not enough.</p><pre># Get the Container App&#39;s Managed Identity principal ID<br>$PRINCIPAL_ID=$(az containerapp identity show \<br>  --name azureops-mcp-server \<br>  --resource-group $RG \<br>  --query principalId -o tsv)<br><br># Get the Cosmos DB account resource ID<br>$COSMOS_ID=$(az cosmosdb show \<br>  --name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --query id -o tsv)<br><br># Assign Cosmos DB Built-in Data Contributor (data plane RBAC, not Azure RBAC)<br>az cosmosdb sql role assignment create \<br>  --account-name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --role-definition-name &quot;Cosmos DB Built-in Data Contributor&quot; \<br>  --principal-id $PRINCIPAL_ID \<br>  --scope $COSMOS_ID</pre><p>This is the most common mistake teams make with Cosmos DB + Managed Identity: assigning an Azure RBAC role and wondering why the SDK still returns 403. Azure RBAC controls management-plane operations (creating containers, viewing account settings). Cosmos DB data plane RBAC controls document read and write access. Both are required for full access; this article only needs the data plane role.</p><h3>1.2 — Store the Endpoint as an App Setting</h3><pre>$COSMOS_ENDPOINT=$(az cosmosdb show \<br>  --name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --query documentEndpoint -o tsv)</pre><pre>az containerapp update \<br>  --name azureops-mcp-server \<br>  --resource-group $RG \<br>  --set-env-vars &quot;CosmosDb__Endpoint=$COSMOS_ENDPOINT&quot;</pre><p>No connection string. No account key. The SDK authenticates via DefaultAzureCredential using the endpoint alone.</p><h3>Phase 2 — Update the Codebase</h3><p>All changes in this phase are in the existing AzureOpsMcpServer project. No new project.</p><h3>2.1 — Add Package</h3><pre>dotnet add package Microsoft.Azure.Cosmos --version 3.62.0</pre><h3>2.2 — Update Program.cs</h3><p>Add the CosmosClient registration after the existing ArmClient line:</p><pre>using Microsoft.Azure.Cosmos;<br><br>// Existing<br>builder.Services.AddSingleton(_ =&gt; new ArmClient(new DefaultAzureCredential()));<br>// New: CosmosClient with DefaultAzureCredential - no connection string<br>builder.Services.AddSingleton(_ =&gt;<br>{<br>    var endpoint = builder.Configuration[&quot;CosmosDb:Endpoint&quot;]<br>        ?? throw new InvalidOperationException(&quot;CosmosDb:Endpoint is not configured&quot;);<br>    return new CosmosClient(endpoint, new DefaultAzureCredential());<br>});</pre><p>For local development, add to appsettings.Development.json:</p><pre>{<br>  &quot;CosmosDb&quot;: {<br>    &quot;Endpoint&quot;: &quot;https://azureops-mcp-cosmos.documents.azure.com:443/&quot;<br>  }<br>}</pre><p>Locally, DefaultAzureCredential resolves to your az login session — the same account you used to create the Cosmos DB account. No additional local configuration needed.</p><h3>2.3 — Add Data Models</h3><p>Create Models/UserModels.cs:</p><pre>namespace AzureOpsMcpServer.Models;<br><br>public record UserContext<br>{<br>    // &#39;id&#39; is the Cosmos DB document identifier - must equal UserId for upsert-by-user to work cleanly<br>    public required string Id { get; init; }<br>    // Partition key - the Entra ID Object ID (oid claim), stable across sessions<br>    public required string UserId { get; init; }<br>    public string? DefaultSubscriptionId { get; init; }<br>    public string? DefaultResourceGroup { get; init; }<br>    public List&lt;string&gt; WatchedResourceGroups { get; init; } = [];<br>    public DateTimeOffset LastUpdated { get; init; } = DateTimeOffset.UtcNow;<br>}<br><br>public record IncidentNote<br>{<br>    // Auto-generated unique identifier per note<br>    public required string Id { get; init; }<br>    // Partition key - same Entra ID Object ID<br>    public required string UserId { get; init; }<br>    public required string ResourceGroup { get; init; }<br>    public required string Note { get; init; }<br>    public string? Severity { get; init; }  // P1, P2, P3 - optional<br>    public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow;<br>}</pre><h3>2.4 — Add a User Identity Helper</h3><p>Create Helpers/UserIdentity.cs. This is the single place that extracts the user&#39;s stable identity from the request:</p><p>csharp</p><pre>namespace AzureOpsMcpServer.Helpers;<br><br>public static class UserIdentity<br>{<br>    private const string OidClaimType =<br>        &quot;http://schemas.microsoft.com/identity/claims/objectidentifier&quot;;<br><br>    /// &lt;summary&gt;<br>    /// Extracts the Entra ID Object ID (oid) from the current user&#39;s claims.<br>    /// The oid claim is stable across sessions, devices, and app registrations -<br>    /// it is the correct identifier for per-user data partitioning.<br>    /// Never use &#39;sub&#39; (subject) - it is app-specific and changes across registrations.<br>    /// &lt;/summary&gt;<br>    public static string GetUserId(HttpContext context)<br>    {<br>        var oid = context.User.FindFirst(OidClaimType)?.Value<br>                  ?? context.User.FindFirst(&quot;oid&quot;)?.Value;<br>        return oid ?? throw new UnauthorizedAccessException(<br>            &quot;User Object ID (oid) not found in token. &quot; +<br>            &quot;Ensure the token was issued by Entra ID and includes the oid claim.&quot;);<br>    }<br>    public static string GetDisplayName(HttpContext context)<br>        =&gt; context.User.FindFirst(&quot;preferred_username&quot;)?.Value<br>           ?? context.User.FindFirst(&quot;name&quot;)?.Value<br>           ?? &quot;unknown&quot;;<br>}</pre><h3>2.5 — Add User Context Tools</h3><p>Create Tools/UserContextTools.cs:</p><p>csharp</p><pre>using Microsoft.Azure.Cosmos;<br>using System.ComponentModel;<br>using ModelContextProtocol.Server;<br>using AzureOpsMcpServer.Models;<br>using AzureOpsMcpServer.Helpers;<br><br>namespace AzureOpsMcpServer.Tools;<br>[McpServerToolType]<br>public class UserContextTools(CosmosClient cosmos)<br>{<br>    private const string DatabaseId  = &quot;azureops-mcp-db&quot;;<br>    private const string ContextsId  = &quot;user-contexts&quot;;<br>    private const string NotesId     = &quot;incident-notes&quot;;<br>    private Container Contexts =&gt; cosmos.GetContainer(DatabaseId, ContextsId);<br>    private Container Notes    =&gt; cosmos.GetContainer(DatabaseId, NotesId);<br>    // ─────────────────────────────────────────────────────────────────<br>    // TOOL: Save User Context<br>    // ─────────────────────────────────────────────────────────────────<br>    [McpServerTool(Name = &quot;save_user_context&quot;)]<br>    [Description(<br>        &quot;Saves the caller&#39;s default Azure subscription and resource group. &quot; +<br>        &quot;Once saved, other tools can be called without specifying these parameters each time. &quot; +<br>        &quot;Use this once when the user sets up the assistant for the first time.&quot;)]<br>    public async Task&lt;SaveContextResult&gt; SaveUserContextAsync(<br>        [Description(&quot;Azure subscription ID to set as default&quot;)] string subscriptionId,<br>        [Description(&quot;Resource group name to set as default&quot;)] string resourceGroup,<br>        [Description(&quot;Additional resource groups to watch (optional)&quot;)] List&lt;string&gt;? watchedGroups,<br>        HttpContext httpContext)<br>    {<br>        var userId = UserIdentity.GetUserId(httpContext);<br>        var context = new UserContext<br>        {<br>            Id                    = userId,   // document id = userId → clean upsert<br>            UserId                = userId,<br>            DefaultSubscriptionId = subscriptionId,<br>            DefaultResourceGroup  = resourceGroup,<br>            WatchedResourceGroups = watchedGroups ?? [],<br>            LastUpdated           = DateTimeOffset.UtcNow<br>        };<br>        await Contexts.UpsertItemAsync(context, new PartitionKey(userId));<br>        return new SaveContextResult<br>        {<br>            UserId               = userId,<br>            DisplayName          = UserIdentity.GetDisplayName(httpContext),<br>            DefaultSubscription  = subscriptionId,<br>            DefaultResourceGroup = resourceGroup,<br>            WatchedGroups        = context.WatchedResourceGroups,<br>            Message              = &quot;Context saved. Tools can now be called without explicit parameters.&quot;<br>        };<br>    }<br>    // ─────────────────────────────────────────────────────────────────<br>    // TOOL: Get User Context<br>    // ─────────────────────────────────────────────────────────────────<br>    [McpServerTool(Name = &quot;get_user_context&quot;)]<br>    [Description(<br>        &quot;Retrieves the caller&#39;s saved Azure context - default subscription, &quot; +<br>        &quot;resource group, and watched groups. &quot; +<br>        &quot;Call this to check what defaults are configured before running other tools.&quot;)]<br>    public async Task&lt;UserContextResult&gt; GetUserContextAsync(HttpContext httpContext)<br>    {<br>        var userId = UserIdentity.GetUserId(httpContext);<br>        try<br>        {<br>            var response = await Contexts.ReadItemAsync&lt;UserContext&gt;(<br>                userId, new PartitionKey(userId));<br>            var ctx = response.Resource;<br>            return new UserContextResult<br>            {<br>                UserId               = userId,<br>                DisplayName          = UserIdentity.GetDisplayName(httpContext),<br>                DefaultSubscription  = ctx.DefaultSubscriptionId,<br>                DefaultResourceGroup = ctx.DefaultResourceGroup,<br>                WatchedGroups        = ctx.WatchedResourceGroups,<br>                LastUpdated          = ctx.LastUpdated,<br>                HasContext           = true<br>            };<br>        }<br>        catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)<br>        {<br>            return new UserContextResult<br>            {<br>                UserId      = userId,<br>                DisplayName = UserIdentity.GetDisplayName(httpContext),<br>                HasContext  = false,<br>                Message     = &quot;No saved context found. Call save_user_context to set your defaults.&quot;<br>            };<br>        }<br>    }<br>    // ─────────────────────────────────────────────────────────────────<br>    // TOOL: Log Incident Note<br>    // ─────────────────────────────────────────────────────────────────<br>    [McpServerTool(Name = &quot;log_incident_note&quot;)]<br>    [Description(<br>        &quot;Logs an incident observation or action taken to the caller&#39;s personal history. &quot; +<br>        &quot;Notes are private to each caller and cannot be read by other users. &quot; +<br>        &quot;Use during active incidents to maintain a timestamped record.&quot;)]<br>    public async Task&lt;LogNoteResult&gt; LogIncidentNoteAsync(<br>        [Description(&quot;Resource group where the incident occurred&quot;)] string resourceGroup,<br>        [Description(&quot;The observation, action, or decision to record&quot;)] string note,<br>        [Description(&quot;Incident severity: P1, P2, or P3 (optional)&quot;)] string? severity,<br>        HttpContext httpContext)<br>    {<br>        var userId = UserIdentity.GetUserId(httpContext);<br>        var incidentNote = new IncidentNote<br>        {<br>            Id            = Guid.NewGuid().ToString(),<br>            UserId        = userId,<br>            ResourceGroup = resourceGroup,<br>            Note          = note,<br>            Severity      = severity,<br>            CreatedAt     = DateTimeOffset.UtcNow<br>        };<br>        await Notes.CreateItemAsync(incidentNote, new PartitionKey(userId));<br>        return new LogNoteResult<br>        {<br>            NoteId        = incidentNote.Id,<br>            ResourceGroup = resourceGroup,<br>            Severity      = severity,<br>            LoggedAt      = incidentNote.CreatedAt,<br>            Message       = &quot;Incident note logged to your private history.&quot;<br>        };<br>    }<br>    // ─────────────────────────────────────────────────────────────────<br>    // TOOL: Get Incident History<br>    // ─────────────────────────────────────────────────────────────────<br>    [McpServerTool(Name = &quot;get_incident_history&quot;)]<br>    [Description(<br>        &quot;Returns the caller&#39;s incident note history for a given resource group. &quot; +<br>        &quot;Only returns notes logged by the caller - never returns other users&#39; notes. &quot; +<br>        &quot;Useful for building a timeline of actions taken during an incident.&quot;)]<br>    public async Task&lt;IncidentHistoryResult&gt; GetIncidentHistoryAsync(<br>        [Description(&quot;Resource group to retrieve history for&quot;)] string resourceGroup,<br>        [Description(&quot;Maximum number of recent notes to return (default 10)&quot;)] int limit = 10,<br>        HttpContext httpContext = null!)<br>    {<br>        var userId = UserIdentity.GetUserId(httpContext);<br>        var query = new QueryDefinition(<br>            &quot;SELECT * FROM c WHERE c.userId = @userId AND c.resourceGroup = @rg &quot; +<br>            &quot;ORDER BY c.createdAt DESC OFFSET 0 LIMIT @limit&quot;)<br>            .WithParameter(&quot;@userId&quot;, userId)<br>            .WithParameter(&quot;@rg&quot;, resourceGroup)<br>            .WithParameter(&quot;@limit&quot;, Math.Min(limit, 50));<br>        var notes   = new List&lt;IncidentNote&gt;();<br>        var iterator = Notes.GetItemQueryIterator&lt;IncidentNote&gt;(query,<br>            requestOptions: new QueryRequestOptions<br>            {<br>                PartitionKey = new PartitionKey(userId)  // scoped to caller&#39;s partition<br>            });<br>        while (iterator.HasMoreResults)<br>        {<br>            var page = await iterator.ReadNextAsync();<br>            notes.AddRange(page);<br>        }<br>        return new IncidentHistoryResult<br>        {<br>            UserId        = userId,<br>            ResourceGroup = resourceGroup,<br>            Notes         = notes,<br>            Count         = notes.Count,<br>            Summary       = notes.Count == 0<br>                ? &quot;No incident notes found for this resource group.&quot;<br>                : $&quot;{notes.Count} note(s) found. Most recent: {notes[0].CreatedAt:u}&quot;<br>        };<br>    }<br>}<br>// Result types<br>public record SaveContextResult<br>{<br>    public required string UserId { get; init; }<br>    public required string DisplayName { get; init; }<br>    public required string DefaultSubscription { get; init; }<br>    public required string DefaultResourceGroup { get; init; }<br>    public required List&lt;string&gt; WatchedGroups { get; init; }<br>    public required string Message { get; init; }<br>}<br>public record UserContextResult<br>{<br>    public required string UserId { get; init; }<br>    public required string DisplayName { get; init; }<br>    public string? DefaultSubscription { get; init; }<br>    public string? DefaultResourceGroup { get; init; }<br>    public List&lt;string&gt; WatchedGroups { get; init; } = [];<br>    public DateTimeOffset? LastUpdated { get; init; }<br>    public required bool HasContext { get; init; }<br>    public string? Message { get; init; }<br>}<br>public record LogNoteResult<br>{<br>    public required string NoteId { get; init; }<br>    public required string ResourceGroup { get; init; }<br>    public string? Severity { get; init; }<br>    public required DateTimeOffset LoggedAt { get; init; }<br>    public required string Message { get; init; }<br>}<br>public record IncidentHistoryResult<br>{<br>    public required string UserId { get; init; }<br>    public required string ResourceGroup { get; init; }<br>    public required List&lt;IncidentNote&gt; Notes { get; init; }<br>    public required int Count { get; init; }<br>    public required string Summary { get; init; }<br>}</pre><h3>2.6 — Update Existing Tools to Use Saved Context</h3><p>Update AzureOpsTools.cs to load saved context when parameters are not provided. The key change: subscriptionId and resourceGroup become optional, with a context fallback:</p><pre>[McpServerTool(Name = &quot;get_deployment_status&quot;)]<br>[Description(<br>    &quot;Returns recent deployment history for an Azure resource group. &quot; +<br>    &quot;If subscriptionId and resourceGroup are not provided, loads from the caller&#39;s saved context. &quot; +<br>    &quot;Use save_user_context first to avoid passing parameters every call.&quot;)]<br>public async Task&lt;DeploymentStatusResult&gt; GetDeploymentStatusAsync(<br>    [Description(&quot;Azure subscription ID (optional if saved context exists)&quot;)] string? subscriptionId,<br>    [Description(&quot;Resource group name (optional if saved context exists)&quot;)] string? resourceGroup,<br>    [Description(&quot;Number of recent deployments to return (1–20)&quot;)] int count = 5,<br>    HttpContext httpContext = null!)<br>{<br>    var (resolvedSub, resolvedRg) = await ResolveContextAsync(<br>        subscriptionId, resourceGroup, httpContext);<br><br>// existing implementation - replace hardcoded params with resolved values<br>    var subscription = _arm.GetSubscriptionResource(<br>        SubscriptionResource.CreateResourceIdentifier(resolvedSub));<br>    var rg          = await subscription.GetResourceGroupAsync(resolvedRg);<br>    var deployments = rg.Value.GetArmDeployments();<br>    var results = new List&lt;DeploymentEntry&gt;();<br>    await foreach (var d in deployments.GetAllAsync())<br>    {<br>        if (results.Count &gt;= Math.Min(count, 20)) break;<br>        results.Add(new DeploymentEntry<br>        {<br>            Name            = d.Data.Name,<br>            Status          = d.Data.Properties.ProvisioningState.ToString(),<br>            Timestamp       = d.Data.Properties.Timestamp ?? DateTimeOffset.MinValue,<br>            DurationSeconds = (int)(d.Data.Properties.Duration?.TotalSeconds ?? 0),<br>            TriggeredBy     = d.Data.SystemData?.CreatedBy<br>                              ?? d.Data.Properties.CorrelationId?.ToString()<br>                              ?? &quot;unknown&quot;<br>        });<br>    }<br>    var latest = results.FirstOrDefault();<br>    return new DeploymentStatusResult<br>    {<br>        ResourceGroup = resolvedRg,<br>        Deployments   = results,<br>        Summary       = latest is not null<br>            ? $&quot;Last deployment &#39;{latest.Name}&#39; {latest.Status} at {latest.Timestamp:u}&quot;<br>            : &quot;No deployments found in this resource group&quot;<br>    };<br>}</pre><p>Add the context resolver as a private method on AzureOpsTools:</p><pre>private async Task&lt;(string SubscriptionId, string ResourceGroup)&gt; ResolveContextAsync(<br>    string? subscriptionId,<br>    string? resourceGroup,<br>    HttpContext httpContext)<br>{<br>    if (!string.IsNullOrEmpty(subscriptionId) &amp;&amp; !string.IsNullOrEmpty(resourceGroup))<br>        return (subscriptionId, resourceGroup);<br><br>    // Load from saved context<br>    var userId = UserIdentity.GetUserId(httpContext);<br>    try<br>    {<br>        var response = await _cosmos.GetContainer(&quot;azureops-mcp-db&quot;, &quot;user-contexts&quot;)<br>            .ReadItemAsync&lt;UserContext&gt;(userId, new PartitionKey(userId));<br>        var ctx = response.Resource;<br>        return (<br>            subscriptionId ?? ctx.DefaultSubscriptionId<br>                ?? throw new InvalidOperationException(<br>                    &quot;No subscription ID provided and no default saved. Call save_user_context first.&quot;),<br>            resourceGroup ?? ctx.DefaultResourceGroup<br>                ?? throw new InvalidOperationException(<br>                    &quot;No resource group provided and no default saved. Call save_user_context first.&quot;)<br>        );<br>    }<br>    catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)<br>    {<br>        throw new InvalidOperationException(<br>            &quot;No saved context found. &quot; +<br>            &quot;Either provide subscriptionId and resourceGroup explicitly, &quot; +<br>            &quot;or call save_user_context to set your defaults.&quot;);<br>    }<br>}</pre><p>Update AzureOpsTools constructor to accept CosmosClient:</p><pre>[McpServerToolType]<br>public class AzureOpsTools(ArmClient armClient, CosmosClient cosmos)<br>{<br>    private readonly ArmClient    _arm    = armClient;<br>    private readonly CosmosClient _cosmos = cosmos;<br>    // ... rest unchanged<br>}</pre><p>Apply the same optional-parameter pattern to GetResourceTagsAsync and CheckResourceHealthAsync — both call ResolveContextAsync before proceeding.</p><h3>2.7 — Project Structure</h3><p><strong><em>Source Code: </em></strong><a href="https://github.com/divyeshg94/AzureOpsMcpServer/tree/part5">https://github.com/divyeshg94/AzureOpsMcpServer/tree/part5</a></p><pre>AzureOpsMcpServer/<br>├── Helpers/<br>│   └── UserIdentity.cs             ← ✅ new<br>├── Models/<br>│   └── UserModels.cs               ← ✅ new<br>├── Tools/<br>│   ├── AzureOpsTools.cs            ← ✅ updated (CosmosClient + optional params)<br>│   └── UserContextTools.cs         ← ✅ new (4 new tools)<br>├── Resources/<br>│   └── RunbookResource.cs          ← unchanged<br>├── Prompts/<br>│   └── IncidentPrompt.cs           ← unchanged<br>├── AzureOpsMcpServer.csproj        ← ✅ updated (Cosmos package)<br>└── Program.cs                      ← ✅ updated (CosmosClient registration)</pre><h3>Phase 3 — Validate Locally</h3><h3>3.1 — Grant Local Access to Cosmos DB</h3><p>bash</p><pre>$USER_OID=$(az ad signed-in-user show --query id -o tsv)<br><br>az cosmosdb sql role assignment create \<br>  --account-name $COSMOS_ACCOUNT \<br>  --resource-group $RG \<br>  --role-definition-name &quot;Cosmos DB Built-in Data Contributor&quot; \<br>  --principal-id $USER_OID \<br>  --scope $(az cosmosdb show \<br>    --name $COSMOS_ACCOUNT \<br>    --resource-group $RG \<br>    --query id -o tsv)</pre><h3>3.2 — Start the Server and Test in Sequence</h3><pre>dotnet run</pre><p><strong>Step 1 — Save context (no parameters needed after this):</strong></p><pre>Save my Azure context: subscription {your-sub-id}, <br>resource group rg-payments-prod</pre><p>Expected:</p><pre>{<br>  &quot;userId&quot;: &quot;oid-from-your-token&quot;,<br>  &quot;displayName&quot;: &quot;divyesh@contoso.com&quot;,<br>  &quot;defaultSubscription&quot;: &quot;{your-sub-id}&quot;,<br>  &quot;defaultResourceGroup&quot;: &quot;rg-payments-prod&quot;,<br>  &quot;message&quot;: &quot;Context saved. Tools can now be called without explicit parameters.&quot;<br>}</pre><p><strong>Step 2 — Verify context was stored:</strong></p><pre>What is my saved Azure context?</pre><p><strong>Step 3 — Call tools without parameters:</strong></p><pre>Check the deployment status</pre><p>The agent calls get_deployment_status with no explicit parameters. The server loads the saved context, resolves the subscription and resource group, and returns real deployment data. This is the moment the server changes from a parameter-heavy CLI-style tool into an assistant that knows your environment.</p><p><strong>Step 4 — Log an incident note:</strong></p><pre>Log an incident note for rg-payments-prod: <br>&quot;Rolled back deploy-api-v1.14 at 14:47 UTC. <br>Failure rate dropped from 2.3% to 0.1% within 5 minutes.&quot;<br>Severity P2.</pre><p><strong>Step 5 — Retrieve history:</strong></p><pre>Show my incident history for rg-payments-prod</pre><p><strong>Step 6 — Confirm isolation (multi-user test):</strong> If you have a second Entra ID test account with the App Role assigned, sign in as that account and repeat Steps 1–5 with different data. Then sign back in as the first account and confirm get_incident_history returns only the first account&#39;s notes. The partition key ensures this at the database level — not in application code.</p><h3>Phase 4 — Deploy and Validate</h3><h3>4.1 — Rebuild and Push the Image</h3><pre>az acr build \<br>  --registry azureopsmcpacr \<br>  --image azureops-mcp-server:latest .</pre><h3>4.2 — Trigger Container App to Pull New Image</h3><pre>az containerapp update \<br>  --name azureops-mcp-server \<br>  --resource-group $RG \<br>  --image azureopsmcpacr.azurecr.io/azureops-mcp-server:latest</pre><p>The CosmosDb__Endpoint environment variable was set in Phase 1. The Container App&#39;s Managed Identity already has the Cosmos DB data plane role. No further configuration needed.</p><h3>4.3 — Validate Against Production</h3><p>Same five-step test sequence from Phase 3 — now against the live APIM endpoint. Confirm:</p><ul><li>save_user_context stores to Cosmos DB (verify in Azure Portal → Data Explorer)</li><li>Zero-parameter tool calls resolve from saved context</li><li>Incident notes appear under the correct userId partition in the incident-notes container</li><li>A second test user cannot read the first user’s notes</li></ul><p>✅ <strong>Production checkpoint:</strong> Per-user data isolation is live. Their Entra ID Object ID partitions each caller’s context and history at the Cosmos DB level.</p><h3>The Isolation Guarantee</h3><p>It’s worth being precise about what “isolation” means here, because it matters for how much you can trust this model.</p><p>The partition key (/userId) is the Entra ID Object ID extracted from the validated JWT. That token was issued by Entra ID and validated by APIM before the request reached your code. By the time UserIdentity.GetUserId() runs, the oid claim has been cryptographically verified.</p><p>Every Cosmos DB query in the user context tools includes PartitionKey = new PartitionKey(userId) on the request options. Cosmos DB&#39;s partition isolation means a query scoped to userId=A will never return documents from userId=B — not as a filter, but as a physical storage boundary. Even a bug in the query predicate can&#39;t cross partition boundaries.</p><p>What this model doesn’t provide: <strong>tenant-level isolation</strong> for regulated industries (financial services, healthcare) where different organizations need fully separate Cosmos DB accounts with customer-managed keys and dedicated throughput. For an internal enterprise tool serving users in one tenant, the partition-key-per-user model is the correct level of isolation. For a SaaS product serving external organizations, that’s a different architecture — each organization gets its own Cosmos DB account.</p><h3>What’s Next</h3><p>The server now has authentication, authorization, and per-user data isolation. The next question is: how do you connect this to Microsoft Foundry so the agent can be used beyond VS Code — from Foundry-hosted agents, from Copilot Studio, from the emerging enterprise agent ecosystem?</p><p><strong>Part 6</strong> registers the AzureOps MCP Server in Microsoft Foundry Agent Service — covering the tool registration format, how Foundry discovers and invokes your tools, and how the security model from Part 4 carries forward into the Foundry context.</p><h3>Series Progress</h3><ul><li>✅<a href="https://levelup.gitconnected.com/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c?gi=b8bd1a135134"> Part 1 — Mental model, why MCP matters for Azure</a></li><li>✅<a href="https://medium.com/gitconnected/your-first-mcp-server-in-c-net-build-something-real-in-30-minutes-ea146c8226e2"> Part 2 — First MCP server in C# .NET, tested in GitHub Copilot</a></li><li>✅<a href="https://medium.com/microsoft-azure-in-practice/from-local-to-azure-deploy-your-mcp-server-to-production-78b05bb1e5a9?source=your_stories_outbox---writer_outbox_published-----------------------------------------"> Part 3 — Deployed to Azure Container Apps with Managed Identity</a></li><li>✅<a href="https://medium.com/microsoft-azure-in-practice/securing-your-mcp-server-microsoft-entra-id-azure-api-management-18f6404142e0?sharedUserId=divyeshg94"> Part 4 — Secured with Entra ID + APIM + per-tool App Roles</a></li><li>✅ Part 5 ← You are here</li><li><strong>Part 6</strong> — Register in Microsoft Foundry Agent Service</li><li>Part 7 — Observability with OpenTelemetry + Azure Monitor</li><li>Part 8 — Full E2E production system + cost breakdown + production checklist</li></ul><p><em>Divyesh writes production-grade Azure + Microsoft Foundry guides with real code and real benchmarks. Follow for Part 6 — connecting to Foundry.</em></p><p><em>Part 5 of </em><strong><em>MCP on Azure: From Zero to Production</em></strong><em> — published in [Microsoft Azure in Practice].</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05209ea0f791" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microsoft-azure-in-practice/multi-user-mcp-per-user-data-isolation-with-azure-cosmos-db-05209ea0f791">Multi-User MCP: Per-User Data Isolation with Azure Cosmos DB</a> was originally published in <a href="https://medium.com/microsoft-azure-in-practice">Microsoft Azure in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Your MCP Server: Microsoft Entra ID + Azure API Management]]></title>
            <link>https://medium.com/microsoft-azure-in-practice/securing-your-mcp-server-microsoft-entra-id-azure-api-management-18f6404142e0?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/18f6404142e0</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 02:20:55 GMT</pubDate>
            <atom:updated>2026-07-12T02:21:17.382Z</atom:updated>
            <content:encoded><![CDATA[<h4>Anyone with the URL could call your tools. That ends in this article.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8YANA9pBrn6-WroXnqDIg.png" /><figcaption>Part 4 — Securing Your MCP Server</figcaption></figure><p><a href="https://medium.com/microsoft-azure-in-practice/from-local-to-azure-deploy-your-mcp-server-to-production-78b05bb1e5a9">Part 3</a> left us with a real problem: the AzureOps MCP Server is deployed, returning real Azure data, authenticated to Azure Resource Manager via Managed Identity, and completely open to the internet. Anyone with the Container App URL can invoke get_deployment_status against any subscription ID they want.</p><p>This article closes that gap with two layers that work together, not one silver bullet:</p><p><strong>Layer 1 — Identity:</strong> Microsoft Entra ID issues tokens. Azure API Management validates them before any request reaches your server. No valid token, no access.</p><p><strong>Layer 2 — Network:</strong> The Container App is locked down to accept traffic only from APIM. Even a valid-looking request that bypasses APIM gets dropped at the network level.</p><p>Most MCP security write-ups stop at Layer 1. That leaves a gap: if your Container App’s public URL is still reachable directly, a determined caller can skip APIM entirely. We close both.</p><p>By the end, we’ll also add <strong>per-tool authorization, </strong>so a caller with access to get_deployment_status doesn&#39;t automatically get get_resource_tags. Least privilege, not just least friction.</p><h3>The Architecture</h3><pre>VS Code / Copilot Agent Mode<br>       │<br>       │  1. No token → 401 + WWW-Authenticate header<br>       │  2. Discovers Entra ID via Protected Resource Metadata<br>       │  3. User signs in, gets access token<br>       ▼<br>Microsoft Entra ID  ──issues──&gt;  Access Token (JWT)<br>       │<br>       │  Authorization: Bearer &lt;token&gt;<br>       ▼<br>Azure API Management<br>       │<br>       │  validate-azure-ad-token policy checks:<br>       │  - Token signature &amp; expiry<br>       │  - Correct tenant<br>       │  - Correct client application ID<br>       │<br>       ▼<br>Azure Container App  (network-locked: only accepts traffic from APIM)<br>       │<br>       │  Reads forwarded Authorization header<br>       │  Checks App Role claim before executing tool<br>       ▼<br>   Tool executes → calls ARM via Managed Identity</pre><p>Two identities are in play here, and conflating them is the most common mistake: the <strong>caller’s identity</strong> (validated by Entra ID + APIM, which determines <em>who can invoke which tool</em>) and the <strong>server’s identity</strong> (the Container App’s Managed Identity, used to call Azure Resource Manager). We are not using the On-Behalf-Of token exchange in this article. The tools don’t act <em>as</em> the calling user against Azure Resource Manager. They act as the app, using the same Managed Identity from Part 3. We’re deciding <em>whether to let the call through at all</em> and <em>which tools the caller may use</em>. That’s a deliberate scope decision, not an oversight — OBO adds real complexity for a benefit this scenario doesn’t need.</p><h3>Phase 1 — Register the MCP Server in Entra ID</h3><p>The server needs its own app registration. This represents your API to Entra ID and defines what a caller must present to be granted access.</p><pre># Create the server app registration<br>az ad app create \<br>  --display-name &quot;AzureOps MCP Server&quot; \<br>  --sign-in-audience AzureADMyOrg<br><br>$SERVER_APP_ID=$(az ad app list --display-name &quot;AzureOps MCP Server&quot; --query &quot;[0].appId&quot; -o tsv)<br><br># Set the Application ID URI - this becomes the audience for tokens<br>az ad app update \<br>  --id $SERVER_APP_ID \<br>  --identifier-uris &quot;api://$SERVER_APP_ID&quot;<br><br># Create the service principal<br>az ad sp create --id $SERVER_APP_ID</pre><h3>1.1 — Expose an API Scope</h3><p>This defines the permission a client requests to call your server at all.</p><pre>az ad app update --id $SERVER_APP_ID --set api=&#39;{<br>  &quot;oauth2PermissionScopes&quot;: [{<br>    &quot;id&quot;: &quot;&lt;GENERATE A GUID AND REPLACE&gt;&quot;,<br>    &quot;adminConsentDisplayName&quot;: &quot;Access AzureOps MCP Server&quot;,<br>    &quot;adminConsentDescription&quot;: &quot;Allows the app to call AzureOps MCP tools on behalf of the signed-in user&quot;,<br>    &quot;userConsentDisplayName&quot;: &quot;Access AzureOps MCP Server&quot;,<br>    &quot;userConsentDescription&quot;: &quot;Allow this app to call AzureOps MCP tools&quot;,<br>    &quot;value&quot;: &quot;access_as_user&quot;,<br>    &quot;type&quot;: &quot;User&quot;,<br>    &quot;isEnabled&quot;: true<br>  }]<br>}&#39;</pre><h3>1.2 — Define App Roles for Per-Tool Authorization</h3><p>This is the piece most MCP security articles skip entirely. A valid token proves <em>who</em> the caller is — it doesn’t say <em>which tools</em> they should reach. We define two roles: one for read-only operational visibility, one for FinOps-sensitive tag data.</p><pre>az ad app update --id $SERVER_APP_ID --set appRoles=&#39;[<br>  {<br>    &quot;id&quot;: &quot;a11c2b44-27ad-4be3-87e9-03868835976a&quot;,<br>    &quot;displayName&quot;: &quot;AzureOps.Operations.Read&quot;,<br>    &quot;description&quot;: &quot;Can call deployment status and health check tools&quot;,<br>    &quot;value&quot;: &quot;AzureOps.Operations.Read&quot;,<br>    &quot;allowedMemberTypes&quot;: [&quot;User&quot;, &quot;Application&quot;],<br>    &quot;isEnabled&quot;: true<br>  },<br>  {<br>    &quot;id&quot;: &quot;e1d54777-9aa9-41ad-b26c-79344058a9e2&quot;,<br>    &quot;displayName&quot;: &quot;AzureOps.FinOps.Read&quot;,<br>    &quot;description&quot;: &quot;Can call the resource tag compliance tool&quot;,<br>    &quot;value&quot;: &quot;AzureOps.FinOps.Read&quot;,<br>    &quot;allowedMemberTypes&quot;: [&quot;User&quot;, &quot;Application&quot;],<br>    &quot;isEnabled&quot;: true<br>  }<br>]&#39;</pre><p>Assign yourself the roles for testing:</p><pre>$USER_OBJECT_ID=$(az ad signed-in-user show --query id -o tsv)<br>$SP_OBJECT_ID=$(az ad sp show --id $SERVER_APP_ID --query id -o tsv)<br><br>az rest --method POST \<br>  --uri &quot;https://graph.microsoft.com/v1.0/servicePrincipals/$SP_OBJECT_ID/appRoleAssignedTo&quot; \<br>  --headers &quot;Content-Type=application/json&quot; \<br>  --body &quot;{&#39;principalId&#39;:&#39;$USER_OBJECT_ID&#39;,&#39;resourceId&#39;:&#39;$SP_OBJECT_ID&#39;,&#39;appRoleId&#39;:&#39;e1d54777-9aa9-41ad-b26c-79344058a9e2&#39;}&quot;             </pre><p>In production, you’d assign these roles to Entra security groups, not individual users — group-based assignment scales without per-person app registration changes.</p><p><strong>One thing to watch:</strong> the az ad app update --set appRoles=... command replaces the entire appRoles array. If you&#39;re adding a role to an app that already has roles defined, fetch the existing array first and append to it — running this command twice with different role lists will silently delete the roles from the first run.</p><h3>1.3 — Register VS Code as a Pre-Authorized Client</h3><p>Entra ID doesn’t support OAuth Dynamic Client Registration. Every client that calls your MCP server must be explicitly known — this is the most important limitation to understand before going further. For VS Code / GitHub Copilot, register a separate client app:</p><pre>az ad app create \<br>  --display-name &quot;AzureOps MCP - VS Code Client&quot; \<br>  --is-fallback-public-client true \<br>  --public-client-redirect-uris &quot;http://localhost&quot; &quot;http://127.0.0.1&quot;<br><br>$CLIENT_APP_ID=$(az ad app list --display-name &quot;AzureOps MCP - VS Code Client&quot; --query &quot;[0].appId&quot; -o tsv)<br><br># Pre-authorize this client to call the server&#39;s access_as_user scope<br>$SCOPE_ID=$(az ad app show --id $SERVER_APP_ID --query &quot;api.oauth2PermissionScopes[0].id&quot; -o tsv)<br><br>az ad app update --id &quot;$SERVER_APP_ID&quot; --set api=&quot;{<br>  &#39;preAuthorizedApplications&#39;: [{<br>    &#39;appId&#39;: &#39;$CLIENT_APP_ID&#39;,<br>    &#39;delegatedPermissionIds&#39;: [&#39;$SCOPE_ID&#39;]<br>  }]<br>}&quot;</pre><p>Pre-authorization means VS Code can request a token without the user seeing a separate consent screen for your API — it was already granted when the client was registered.</p><h3>Phase 2 — Configure Azure API Management as the MCP Gateway</h3><pre>az apim create \<br>  --name azureops-apim \<br>  --resource-group $RG \<br>  --publisher-email you@contoso.com \<br>  --publisher-name &quot;Contoso AzureOps&quot; \<br>  --sku-name Developer</pre><p>APIM provisioning takes 30–45 minutes. While it runs, prepare the policy configuration.</p><h3>Phase 3 — Lock Down the Container App Network</h3><p>Before touching APIM, close the direct path. If the Container App’s public URL still works without going through APIM, the auth layer above means nothing.</p><pre>$RG=&quot;rg-azureops-mcp&quot;<br>$ACA_APP=&quot;azureops-mcp-server&quot;<br><br># Get APIM&#39;s outbound IP addresses (after APIM is provisioned in Phase 2)<br>$APIM_IPS=$(az apim show --name azureops-apim \<br>  --resource-group $RG --query &quot;publicIPAddresses&quot; -o tsv)<br><br># Deny all traffic by default, then allow only APIM<br>az containerapp ingress access-restriction set \<br>  --name $ACA_APP \<br>  --resource-group $RG \<br>  --rule-name &quot;allow-apim-only&quot; \<br>  --ip-address &quot;$APIM_IPS/32&quot; \<br>  --action Allow \<br>  --rule-type IPRule<br><br>az containerapp ingress access-restriction set \<br>  --name $ACA_APP \<br>  --resource-group $RG \<br>  --rule-name &quot;deny-all-else&quot; \<br>  --ip-address &quot;0.0.0.0/0&quot; \<br>  --action Deny \<br>  --rule-type IPRule</pre><p>For production, prefer VNet integration with a private endpoint between APIM and the Container App over IP allow-listing — IP-based rules work, but VNet isolation removes the public attack surface entirely. IP rules are the faster path for this article; treat the VNet pattern as the next hardening step once this works end-to-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTa3MtBPvupA4FdRzrDE0g.png" /></figure><h3>3.1 — Import the MCP Server as an APIM Backend API</h3><p>In the Azure Portal: <strong>APIM → APIs → Add API → MCP Server</strong>. Point it at your Container App’s /mcp endpoint. APIM creates the routing automatically — your existing endpoint structure doesn&#39;t change.</p><h3>3.2 — Apply the Entra ID Validation Policy</h3><p>On the imported MCP API, set this inbound policy:</p><pre>&lt;policies&gt;<br>  &lt;inbound&gt;<br>    &lt;validate-azure-ad-token tenant-id=&quot;{your-tenant-id}&quot;<br>                              header-name=&quot;Authorization&quot;<br>                              failed-validation-httpcode=&quot;401&quot;<br>                              failed-validation-error-message=&quot;Unauthorized. Access token is missing or invalid.&quot;&gt;<br>      &lt;client-application-ids&gt;<br>        &lt;application-id&gt;{server-app-id}&lt;/application-id&gt;<br>      &lt;/client-application-ids&gt;<br>    &lt;/validate-azure-ad-token&gt;<br>    &lt;base /&gt;<br>  &lt;/inbound&gt;<br>  &lt;on-error&gt;<br>    &lt;set-header name=&quot;WWW-Authenticate&quot; exists-action=&quot;override&quot;&gt;<br>      &lt;value&gt;@{<br>        return &quot;Bearer resource_metadata=\&quot;https://&quot; + context.Request.OriginalUrl.Host<br>             + &quot;/.well-known/oauth-protected-resource\&quot;&quot;;<br>      }&lt;/value&gt;<br>    &lt;/set-header&gt;<br>    &lt;base /&gt;<br>  &lt;/on-error&gt;<br>&lt;/policies&gt;</pre><p>The on-error block matters as much as the validation itself. When a client calls without a token, MCP clients (VS Code included) expect a 401 with a WWW-Authenticate header pointing them to discovery metadata — without it, the client has no way to know <em>how</em> to authenticate, and the connection just fails silently from the user&#39;s perspective.</p><h3>3.3 — Serve the Protected Resource Metadata Endpoint</h3><p>RFC 9728 requires this exact path — it’s not configurable. Add a new API operation in APIM at /.well-known/oauth-protected-resource with this policy:</p><pre>&lt;policies&gt;<br>  &lt;inbound&gt;<br>    &lt;return-response&gt;<br>      &lt;set-status code=&quot;200&quot; reason=&quot;OK&quot; /&gt;<br>      &lt;set-header name=&quot;Content-Type&quot; exists-action=&quot;override&quot;&gt;<br>        &lt;value&gt;application/json&lt;/value&gt;<br>      &lt;/set-header&gt;<br>      &lt;set-body&gt;@{<br>        return new JObject(<br>          new JProperty(&quot;resource&quot;, &quot;https://&quot; + context.Request.OriginalUrl.Host),<br>          new JProperty(&quot;authorization_servers&quot;, new JArray(<br>            &quot;https://login.microsoftonline.com/{your-tenant-id}/v2.0&quot;<br>          ))<br>        ).ToString();<br>      }&lt;/set-body&gt;<br>    &lt;/return-response&gt;<br>  &lt;/inbound&gt;<br>&lt;/policies&gt;</pre><p>This is the document VS Code reads after receiving the 401 — it tells the client exactly which Entra tenant to authenticate against.</p><h3>Phase 4 — Add Per-Tool Authorization in the Server</h3><p>APIM validates that a caller <em>has</em> a valid token. It doesn’t know your tools well enough to decide <em>which</em> tools the caller should reach — that decision belongs in your code, where the tool definitions live.</p><p>Update Program.cs to read and validate the forwarded token&#39;s claims:</p><pre>using Microsoft.AspNetCore.Authentication.JwtBearer;<br>using Microsoft.IdentityModel.Tokens;<br><br>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>    .AddJwtBearer(options =&gt;<br>    {<br>        options.Authority = $&quot;https://login.microsoftonline.com/{tenantId}/v2.0&quot;;<br>        options.Audience  = $&quot;api://{serverAppId}&quot;;<br>        options.TokenValidationParameters = new TokenValidationParameters<br>        {<br>            ValidateIssuer = true,<br>            ValidateAudience = true<br>        };<br>    });<br>builder.Services.AddAuthorization(options =&gt;<br>{<br>    options.AddPolicy(&quot;OperationsRead&quot;, policy =&gt;<br>        policy.RequireClaim(&quot;roles&quot;, &quot;AzureOps.Operations.Read&quot;));<br>    options.AddPolicy(&quot;FinOpsRead&quot;, policy =&gt;<br>        policy.RequireClaim(&quot;roles&quot;, &quot;AzureOps.FinOps.Read&quot;));<br>});</pre><p>This is intentional defense-in-depth, not redundant work. APIM already rejected unauthenticated callers — this second check confirms the <em>specific</em> role required for the <em>specific</em> tool, directly in the code that owns the tool’s sensitivity. If APIM is ever misconfigured or bypassed, this layer still holds.</p><p>Update each tool to check its required role before executing:</p><pre>[McpServerTool(Name = &quot;get_resource_tags&quot;)]<br>[Description(&quot;Fetches FinOps compliance tags. Requires AzureOps.FinOps.Read role.&quot;)]<br>public async Task&lt;ResourceTagsResult&gt; GetResourceTagsAsync(<br>    [Description(&quot;Azure subscription ID&quot;)] string subscriptionId,<br>    [Description(&quot;Resource group name&quot;)] string resourceGroup,<br>    HttpContext httpContext)<br>{<br>    if (!httpContext.User.HasClaim(&quot;roles&quot;, &quot;AzureOps.FinOps.Read&quot;))<br>    {<br>        throw new UnauthorizedAccessException(<br>            &quot;This tool requires the AzureOps.FinOps.Read role.&quot;);<br>    }<br><br>    // existing implementation unchanged<br>    var subscription = _arm.GetSubscriptionResource(<br>        SubscriptionResource.CreateResourceIdentifier(subscriptionId));<br>    // ...<br>}</pre><p>The HttpContext parameter is automatically populated by the MCP SDK from the current request — no manual wiring required. A caller with AzureOps.Operations.Read but not AzureOps.FinOps.Read will have get_deployment_status and check_resource_health work normally, and get_resource_tags throw a clear, role-specific error.</p><h3>Phase 5 — Validate End-to-End</h3><p>Update .vscode/mcp.json to point at the APIM endpoint instead of the Container App directly:</p><pre>{<br>  &quot;servers&quot;: {<br>    &quot;azureops-mcp&quot;: {<br>      &quot;type&quot;: &quot;http&quot;,<br>      &quot;url&quot;: &quot;https://azureops-apim.azure-api.net/azureops-mcp/mcp&quot;<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aT2YwowHQDcxKR3qbw5qDg.png" /></figure><p>Reload VS Code and open Copilot Chat in agent mode. The first connection attempt should trigger a sign-in prompt — VS Code received the 401 + WWW-Authenticate Header discovered the Entra tenant via the PRM document, and is now requesting a token.</p><p>Sign in with an account that has the AzureOps.Operations.Read role assigned. Run:</p><pre>Check deployment status for subscription {sub-id}, resource group {rg}</pre><p>This should succeed — token validated by APIM, role checked by the server, tool executes.</p><p>Now try:</p><pre>Check FinOps tag compliance for subscription {sub-id}, resource group {rg}</pre><p>If your test account only has AzureOps.Operations.Read, this should fail with the role-specific error. Assign the AzureOps.FinOps.Read role and retry — it should now succeed.</p><p><strong>Confirm the network lock independently</strong> — try calling the Container App’s direct URL (not through APIM) with curl:</p><pre>curl https://{container-app-fqdn}/health</pre><p>This should time out or be refused. If it responds, the access restriction from Phase 2 isn’t applied correctly — go back and verify before considering this production-ready.</p><h3>What This Doesn’t Cover</h3><p>Two things deliberately stayed out of scope here, and you should know why:</p><p><strong>On-Behalf-Of (OBO) flow</strong> — if your tools needed to call Microsoft Graph or another downstream API <em>as the signed-in user</em> (reading their calendar, their SharePoint files), you’d need an OBO token exchange. Our tools only call Azure Resource Manager using the server’s own Managed Identity, so this complexity isn’t needed here. If your use case grows into per-user downstream calls, that’s a deliberate architecture change, not a missing step.</p><p><strong>Arbitrary third-party MCP clients</strong> — because Entra ID doesn’t support Dynamic Client Registration, every client must be pre-registered, as we did for VS Code. If you need to support MCP clients you don’t control, you need an OAuth proxy in front of Entra ID — a real added layer of complexity and risk that’s outside this article’s scope. For an internal enterprise tool used through Copilot and Foundry, pre-authorized clients are the right level of complexity, not a shortcut.</p><h3>What’s Next</h3><p>The server is secured for a single caller’s identity. Part 5 takes the next logical step: <strong>multiple users, each with their own data boundary.</strong> Right now, every authorized caller sees the same Azure subscription and resource groups. Part 5 adds per-user data isolation with Azure Cosmos DB — so a multi-tenant deployment of this server can serve different teams or customers without anyone seeing another’s data.</p><h3>Series Progress</h3><ul><li>✅ <a href="https://medium.com/gitconnected/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c">Part 1 — Mental model, why MCP matters for Azure</a></li><li>✅ <a href="https://medium.com/gitconnected/your-first-mcp-server-in-c-net-build-something-real-in-30-minutes-ea146c8226e2">Part 2 — First MCP server in C# .NET, tested in GitHub Copilot</a></li><li>✅ <a href="https://medium.com/microsoft-azure-in-practice/from-local-to-azure-deploy-your-mcp-server-to-production-78b05bb1e5a9">Part 3 — Deployed to Azure Container Apps with Managed Identity</a></li><li>✅ Part 4 ← You are here</li><li>Part 5 — Multi-user data isolation with Cosmos DB</li><li>Part 6 — Register in Microsoft Foundry Agent Service</li><li>Part 7 — Observability with OpenTelemetry + Azure Monitor</li><li>Part 8 — Full E2E production system + cost breakdown + production checklist</li></ul><p><em>Divyesh writes production-grade Azure + Microsoft Foundry guides with real code and real benchmarks. Follow for Part 5 — multi-tenant data isolation done right.</em></p><p><em>Part 4 of </em><strong><em>MCP on Azure: From Zero to Production</em></strong><em> — published in [Microsoft Azure in Practice].</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18f6404142e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microsoft-azure-in-practice/securing-your-mcp-server-microsoft-entra-id-azure-api-management-18f6404142e0">Securing Your MCP Server: Microsoft Entra ID + Azure API Management</a> was originally published in <a href="https://medium.com/microsoft-azure-in-practice">Microsoft Azure in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Local to Azure: Deploy Your MCP Server to Production]]></title>
            <link>https://medium.com/microsoft-azure-in-practice/from-local-to-azure-deploy-your-mcp-server-to-production-78b05bb1e5a9?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/78b05bb1e5a9</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure-container-apps]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 12:58:25 GMT</pubDate>
            <atom:updated>2026-06-20T12:58:25.461Z</atom:updated>
            <content:encoded><![CDATA[<h4>One codebase. Real Azure data. One deployment target that actually makes sense.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDYN9RDUbJE9qEjQ6isNRw.png" /><figcaption>MCP From Local To Azure — Part 3</figcaption></figure><p>In Part 2, we built the AzureOps MCP Server — three tools, a runbook resource, and an incident triage prompt, all returning simulated data on localhost:5100. Copilot called the tools. It worked locally.</p><p>This article takes that server to production in three stages:</p><ol><li><strong>Replace all simulated data with real Azure SDK calls</strong> — in one place, completely</li><li><strong>Validate locally</strong> against your actual Azure subscription before anything touches cloud infrastructure</li><li><strong>Deploy to Azure Container Apps</strong> — the same codebase, containerized, with Managed Identity throughout</li></ol><p>Azure Functions is covered at the end as an alternative. By the end of this article, you’ll understand why most .NET MCP servers belong on Container Apps, and in which narrow cases Functions is the right call.</p><h3>What Changes From Part 2</h3><p><strong>Static → Dynamic:</strong> Three tools returned hardcoded data. All of it gets replaced with Azure.ResourceManager SDK calls returning real deployment history, real tags, and real health states.</p><p><strong>Managed Identity everywhere:</strong> DefaultAzureCredential handles authentication. Locally, it resolves to your az login session. In Azure, it resolves to the Container App&#39;s system-assigned identity. No secrets, no connection strings, no rotation.</p><p><strong>Async tool methods:</strong> Real SDK calls are async. The tool class becomes an instance type to support constructor injection, and all tool methods become async Task&lt;T&gt;.</p><h3>Phase 1 — Update the Codebase</h3><p>All changes happen in the existing AzureOpsMcpServer project from Part 2. No new project.</p><h3>1.1 — Add Packages</h3><pre>dotnet add package Azure.ResourceManager --version 1.14.0<br>dotnet add package Azure.ResourceManager.Resources --version 1.11.2<br>dotnet add package Azure.ResourceManager.ResourceHealth --version 1.0.0<br>dotnet add package Azure.Identity --version 1.21.0</pre><p>Your .csproj should now look like this:</p><pre>&lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;Azure.Identity&quot; Version=&quot;1.21.0&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Azure.ResourceManager&quot; Version=&quot;1.14.0&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Azure.ResourceManager.ResourceHealth&quot; Version=&quot;1.0.0&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Azure.ResourceManager.Resources&quot; Version=&quot;1.11.2&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Microsoft.AspNetCore.OpenApi&quot; Version=&quot;10.0.3&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Microsoft.Extensions.AI&quot; Version=&quot;10.6.0&quot; /&gt;<br>  &lt;PackageReference Include=&quot;ModelContextProtocol.AspNetCore&quot; Version=&quot;1.4.0&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><h3>1.2 — Update Program.cs</h3><p>Replace Program.cs in full:</p><pre>using Azure.Identity;<br>using Azure.ResourceManager;<br>using ModelContextProtocol.Server;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// ArmClient resolves to az login locally, system-assigned Managed Identity in Azure<br>builder.Services.AddSingleton(_ =&gt; new ArmClient(new DefaultAzureCredential()));<br>builder.Services.AddMcpServer()<br>    .WithHttpTransport(options =&gt; { options.Stateless = true; })<br>    .WithToolsFromAssembly()<br>    .WithResourcesFromAssembly()<br>    .WithPromptsFromAssembly();<br><br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(policy =&gt;<br>    {<br>        policy<br>            .WithOrigins(<br>                &quot;https://vscode.dev&quot;,<br>                &quot;https://*.vscode.dev&quot;<br>            )<br>            .AllowAnyHeader()<br>            .AllowAnyMethod();<br>    });<br>});<br><br>var app = builder.Build();<br>app.UseCors();<br>app.MapMcp(&quot;/mcp&quot;);<br>app.MapGet(&quot;/health&quot;, () =&gt; Results.Ok(new { status = &quot;healthy&quot;, server = &quot;AzureOps MCP&quot; }));<br><br>// app.Run() with no argument reads ASPNETCORE_HTTP_PORTS from the environment.<br>// Local: set to 5100 in launchSettings.json. Container: set to 8080 in Dockerfile.<br>app.Run();</pre><p>Port handling is now clean: app.Run() with no explicit URL reads ASPNETCORE_HTTP_PORTS from the environment. No hardcoded ports, no PORT variable guessing.</p><h3>1.3 — Update launchSettings.json</h3><p>Set the local port in Properties/launchSettings.json:</p><pre>{<br>  &quot;profiles&quot;: {<br>    &quot;http&quot;: {<br>      &quot;commandName&quot;: &quot;Project&quot;,<br>      &quot;dotnetRunMessages&quot;: true,<br>      &quot;launchBrowser&quot;: false,<br>      &quot;applicationUrl&quot;: &quot;http://localhost:5100&quot;,<br>      &quot;environmentVariables&quot;: {<br>        &quot;ASPNETCORE_ENVIRONMENT&quot;: &quot;Development&quot;<br>      }<br>    }<br>  }<br>}</pre><p>This keeps localhost:5100 for local development. The Dockerfile will set 8080 for the container — no code change required between environments.</p><h3>1.4 — Replace AzureOpsTools.cs (Full File)</h3><p>This is the only file where all three tools live. Replace it entirely:</p><pre>using Azure.ResourceManager;<br>using Azure.ResourceManager.Resources;<br>using Azure.ResourceManager.ResourceHealth;<br>using System.ComponentModel;<br>using ModelContextProtocol.Server;<br>using AzureOpsMcpServer.Models;<br><br>namespace AzureOpsMcpServer.Tools;<br><br>[McpServerToolType]<br>public class AzureOpsTools(ArmClient armClient)<br>{<br>    private readonly ArmClient _arm = armClient;<br>    // ─────────────────────────────────────────────────────────────────<br>    // TOOL 1: Deployment Status<br>    // ─────────────────────────────────────────────────────────────────<br>    [McpServerTool(Name = &quot;get_deployment_status&quot;)]<br>    [Description(<br>        &quot;Returns recent deployment history for an Azure resource group. &quot; +<br>        &quot;Includes deployment name, provisioning status (Succeeded/Failed/Running), &quot; +<br>        &quot;timestamp, duration, and correlation ID for tracing. &quot; +<br>        &quot;Use this to understand what changed in an environment before an incident.&quot;)]<br>    public async Task&lt;DeploymentStatusResult&gt; GetDeploymentStatusAsync(<br>        [Description(&quot;Azure subscription ID (GUID format)&quot;)] string subscriptionId,<br>        [Description(&quot;Resource group name to query&quot;)] string resourceGroup,<br>        [Description(&quot;Number of recent deployments to return (1–20)&quot;)] int count = 5)<br>    {<br>        var subscription = _arm.GetSubscriptionResource(<br>            SubscriptionResource.CreateResourceIdentifier(subscriptionId));<br>        var rg = await subscription.GetResourceGroupAsync(resourceGroup);<br>        var deployments = rg.Value.GetArmDeployments();<br>        var results = new List&lt;DeploymentEntry&gt;();<br>        await foreach (var d in deployments.GetAllAsync())<br>        {<br>            if (results.Count &gt;= Math.Min(count, 20)) break;<br>            results.Add(new DeploymentEntry<br>            {<br>                Name            = d.Data.Name,<br>                Status          = d.Data.Properties.ProvisioningState?.ToString() ?? &quot;Unknown&quot;,<br>                Timestamp       = d.Data.Properties.Timestamp ?? DateTimeOffset.MinValue,<br>                DurationSeconds = (int)(d.Data.Properties.Duration?.TotalSeconds ?? 0),<br>                // SystemData.CreatedBy is populated for deployments triggered via portal/CLI/CI<br>                // Falls back to CorrelationId for programmatic deployments<br>                TriggeredBy     = d.Data.SystemData?.CreatedBy<br>                                  ?? d.Data.Properties.CorrelationId?.ToString()<br>                                  ?? &quot;unknown&quot;<br>            });<br>        }<br>        var latest = results.FirstOrDefault();<br>        return new DeploymentStatusResult<br>        {<br>            ResourceGroup = resourceGroup,<br>            Deployments   = results,<br>            Summary       = latest is not null<br>                ? $&quot;Last deployment &#39;{latest.Name}&#39; {latest.Status} at {latest.Timestamp:u}&quot;<br>                : &quot;No deployments found in this resource group&quot;<br>        };<br>    }<br><br>    // ─────────────────────────────────────────────────────────────────<br>    // TOOL 2: Resource Tags<br>    // ─────────────────────────────────────────────────────────────────<br>    [McpServerTool(Name = &quot;get_resource_tags&quot;)]<br>    [Description(<br>        &quot;Fetches all tags on an Azure resource group and identifies missing required FinOps tags. &quot; +<br>        &quot;Required tags: Environment, Owner, CostCenter, Application. &quot; +<br>        &quot;Do NOT use this tool for individual resources - it operates at the resource group level.&quot;)]<br>    public async Task&lt;ResourceTagsResult&gt; GetResourceTagsAsync(<br>        [Description(&quot;Azure subscription ID (GUID format)&quot;)] string subscriptionId,<br>        [Description(&quot;Resource group name to check&quot;)] string resourceGroup)<br>    {<br>        var subscription = _arm.GetSubscriptionResource(<br>            SubscriptionResource.CreateResourceIdentifier(subscriptionId));<br>        var rg = await subscription.GetResourceGroupAsync(resourceGroup);<br>        var tags = rg.Value.Data.Tags ?? new Dictionary&lt;string, string&gt;();<br>        var required = new[] { &quot;Environment&quot;, &quot;Owner&quot;, &quot;CostCenter&quot;, &quot;Application&quot; };<br>        var missingTags = required.Except(tags.Keys, StringComparer.OrdinalIgnoreCase).ToList();<br>        return new ResourceTagsResult<br>        {<br>            ResourceId        = rg.Value.Data.Id.ToString(),<br>            Tags              = new Dictionary&lt;string, string&gt;(tags),<br>            MissingRequiredTags = missingTags,<br>            Compliant         = missingTags.Count == 0,<br>            ComplianceSummary = missingTags.Count == 0<br>                ? &quot;Resource group is fully tagged&quot;<br>                : $&quot;Missing {missingTags.Count} required tag(s): {string.Join(&quot;, &quot;, missingTags)}&quot;<br>        };<br>    }<br><br>    // ─────────────────────────────────────────────────────────────────<br>    // TOOL 3: Resource Health<br>    // ─────────────────────────────────────────────────────────────────<br>    [McpServerTool(Name = &quot;check_resource_health&quot;)]<br>    [Description(<br>        &quot;Returns the current health state of an Azure resource group from Azure Resource Health. &quot; +<br>        &quot;Health states: Available, Degraded, Unavailable, Unknown. &quot; +<br>        &quot;Use this to determine whether degradation is platform-initiated or application-caused.&quot;)]<br>    public async Task&lt;ResourceHealthResult&gt; CheckResourceHealthAsync(<br>        [Description(&quot;Azure subscription ID (GUID format)&quot;)] string subscriptionId,<br>        [Description(&quot;Resource group name to check&quot;)] string resourceGroup)<br>    {<br>        var subscription = _arm.GetSubscriptionResource(<br>            SubscriptionResource.CreateResourceIdentifier(subscriptionId));<br>        var rg = await subscription.GetResourceGroupAsync(resourceGroup);<br>        // GetAvailabilityStatusAsync is an extension method from Azure.ResourceManager.ResourceHealth<br>        // It returns the current availability status for any ARM resource scope<br>        var statusResponse = await _arm.GetAvailabilityStatusAsync(rg.Value.Id);<br>        var data = statusResponse.Value;<br>        return new ResourceHealthResult<br>        {<br>            ResourceType      = &quot;ResourceGroup&quot;,<br>            ResourceName      = resourceGroup,<br>            HealthState       = data.Properties?.AvailabilityState?.ToString() ?? &quot;Unknown&quot;,<br>            ReasonCode        = data.Properties?.ReasonType,<br>            RecommendedAction = data.Properties?.RecommendedActions<br>                                    ?.FirstOrDefault()?.Action,<br>            LastChecked       = DateTimeOffset.UtcNow<br>        };<br>    }<br>}</pre><p>Two naming changes from Part 2: DeployedBy is now TriggeredBy (accurate — ARM exposes SystemData.CreatedBy or CorrelationId, not a free-form deployer name), and the tag comparison now uses StringComparer.OrdinalIgnoreCase so environment and Environment don&#39;t both fail compliance.</p><h3>1.5 — Add .dockerignore</h3><p>Before the Dockerfile. Add .dockerignore at the project root:</p><pre>bin/<br>bin<br>obj/<br>obj<br>.vs/<br>.vs<br>.vscode/<br>*.user<br>.git/<br>.gitignore<br>*.slnx<br>Dockerfile<br>.dockerignore<br>README.md<br>Properties/launchSettings.json</pre><p>Without this, the Docker build context includes bin/, obj/, and local VS config — bloating build times and leaking local configuration into the image.</p><h3>1.6 — Project Structure Check</h3><p><strong><em>Source Code: </em></strong><a href="https://github.com/divyeshg94/AzureOpsMcpServer/tree/part2">https://github.com/divyeshg94/AzureOpsMcpServer/tree/part</a>3</p><pre>AzureOpsMcpServer/<br>├── .vscode/<br>│   └── mcp.json                    ← still points to localhost:5100<br>├── Properties/<br>│   └── launchSettings.json         ← ✅ added (sets local port 5100)<br>├── Tools/<br>│   └── AzureOpsTools.cs            ← ✅ updated (real Azure SDK, async)<br>├── Resources/<br>│   └── RunbookResource.cs          ← unchanged<br>├── Prompts/<br>│   └── IncidentPrompt.cs           ← unchanged<br>├── .dockerignore                   ← ✅ added<br>├── AzureOpsMcpServer.csproj        ← ✅ updated (Azure SDK packages)<br>└── Program.cs                      ← ✅ updated (ArmClient + app.Run())</pre><p>Four files changed or added. Everything else carries forward from Part 2.</p><h3>Phase 2 — Validate Locally</h3><p>Before any infrastructure is provisioned, confirm the SDK calls work against your Azure subscription from your machine. Never deploy code that hasn’t been locally verified against real data.</p><h3>2.1 — Prerequisites</h3><pre># Login<br>az login<br><br># Confirm active subscription<br>az account show --query &quot;{name:name, id:id}&quot; -o table<br><br># Grant yourself Reader on the resource group you&#39;ll test against<br>az role assignment create \<br>  --role &quot;Reader&quot; \<br>  --assignee $(az ad signed-in-user show --query id -o tsv) \<br>  --scope /subscriptions/{your-sub-id}/resourceGroups/{your-rg}</pre><p>Resource Health Reader is a separate built-in role from Reader. Without it, GetAvailabilityStatusAsync returns a 403.</p><h3>2.2 — Start the Server</h3><pre>dotnet run</pre><p>Expected output:</p><pre>info: Microsoft.Hosting.Lifetime[14]<br>      Now listening on: http://localhost:5100</pre><p>Health check:</p><pre>curl http://localhost:5100/health<br># {&quot;status&quot;:&quot;healthy&quot;,&quot;server&quot;:&quot;AzureOps MCP&quot;}</pre><h3>2.3 — Test Each Tool in Copilot</h3><p>Open Copilot Chat (Ctrl+Alt+I), switch to Agent mode, and confirm azureops-mcp is listed in the Tools panel. Run one prompt per tool.</p><p><strong>Tool 1 — Deployment Status:</strong></p><pre>Get the last 3 deployments for subscription {your-sub-id},<br>resource group {your-rg}</pre><p>Expected structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsVRZRcyvS05UtOGvVnYJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBzxGvXWuvWkx_v-zALL9w.png" /></figure><p>Real deployment names, real timestamps from your resource group — Tool 1 is working.</p><p><strong>Tool 2 — Resource Tags:</strong></p><pre>Check FinOps tag compliance for subscription {your-sub-id},<br>resource group {your-rg}</pre><p>Expected structure:</p><pre>{<br>  &quot;resourceId&quot;: &quot;/subscriptions/.../resourceGroups/rg-payments-prod&quot;,<br>  &quot;tags&quot;: { &quot;Environment&quot;: &quot;Production&quot;, &quot;Owner&quot;: &quot;platform-team@contoso.com&quot; },<br>  &quot;missingRequiredTags&quot;: [&quot;CostCenter&quot;, &quot;Application&quot;],<br>  &quot;compliant&quot;: false,<br>  &quot;complianceSummary&quot;: &quot;Missing 2 required tag(s): CostCenter, Application&quot;<br>}</pre><p><strong>Tool 3 — Resource Health:</strong></p><pre>Check the health of resource group {your-rg}<br>in subscription {your-sub-id}</pre><p>Expected structure:</p><pre>{<br>  &quot;resourceType&quot;: &quot;ResourceGroup&quot;,<br>  &quot;resourceName&quot;: &quot;rg-payments-prod&quot;,<br>  &quot;healthState&quot;: &quot;Available&quot;,<br>  &quot;reasonCode&quot;: null,<br>  &quot;recommendedAction&quot;: null,<br>  &quot;lastChecked&quot;: &quot;2026-06-15T10:45:00Z&quot;<br>}</pre><h3>2.4 — Common Errors and Fixes</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FDjIGj%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FDjIGj%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FDjIGj%2Fplain-s.png%3Fv%3D2&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aa1de41d7de8936368edcfd242bf0a6/href">https://medium.com/media/0aa1de41d7de8936368edcfd242bf0a6/href</a></iframe><p>✅ <strong>Local checkpoint:</strong> All three tools return real data from your Azure subscription. Simulated responses are gone. Move to Phase 3.</p><h3>Phase 3 — Deploy to Azure Container Apps</h3><p>The existing ASP.NET Core project deploys to Container Apps with one addition: a Dockerfile. No code restructuring, no new project, no trigger wrappers.</p><h3>3.1 — Add the Dockerfile</h3><p>Add Dockerfile at the project root:</p><pre># Build stage<br>FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build<br>WORKDIR /src<br>COPY [&quot;AzureOpsMcpServer.csproj&quot;, &quot;.&quot;]<br>RUN dotnet restore<br>COPY . .<br>RUN dotnet publish -c Release -o /app/publish<br><br># Runtime stage<br>FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final<br>WORKDIR /app<br><br># Port 8080 — standard for ACA. app.Run() reads ASPNETCORE_HTTP_PORTS automatically.<br>ENV ASPNETCORE_HTTP_PORTS=8080<br>EXPOSE 8080<br><br>COPY --from=build /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;AzureOpsMcpServer.dll&quot;]</pre><p>ASPNETCORE_HTTP_PORTS=8080 is the correct way to set the Kestrel port in a container. It&#39;s read automatically by app.Run() — No code change needed between environments.</p><h3>3.2 — Create Azure Resources</h3><pre># Variables — set these once, use throughout<br>$RG=&quot;rg-azureops-mcp&quot;<br>$LOCATION=&quot;eastus&quot;<br>$ACR=&quot;azureopsmcpacr&quot;<br>$ACA_ENV=&quot;azureops-mcp-env&quot;<br>$ACA_APP=&quot;azureops-mcp-server&quot;<br>$SUB_ID=$(az account show --query id -o tsv)<br><br># Resource group<br>az group create --name $RG --location $LOCATION<br><br># Container Registry (admin disabled - we use Managed Identity for pulls)<br>az acr create --resource-group $RG --name $ACR --sku Basic  --admin-enabled false<br><br># Container Apps environment<br>az containerapp env create --name $ACA_ENV --resource-group $RG --location $LOCATION</pre><h3>3.3 — Build and Push the Image</h3><pre># Build and push directly via ACR Tasks — no local Docker required<br>az acr build --registry $ACR --image azureops-mcp-server:latest .</pre><p>az acr build runs the Docker build in Azure — faster, no local Docker Desktop dependency, and the image never leaves Azure infrastructure.</p><h3>3.4 — Deploy with Managed Identity</h3><p>This is a three-step sequence: create the app with system identity, assign roles, then switch the registry to use that identity. No admin credentials ever touch the deployment.</p><pre>az acr update --name $ACR --admin-enabled true<br>$ACR_PASS = az acr credential show --name $ACR --query &quot;passwords[0].value&quot; -o tsv<br><br># Create app<br>az containerapp create `<br>  --name $ACA_APP --resource-group $RG --environment $ACA_ENV `<br>  --image &quot;$($ACR).azurecr.io/azureops-mcp-server:latest&quot; `<br>  --target-port 8080 --ingress external `<br>  --min-replicas 1 --max-replicas 10 `<br>  --cpu 0.25 --memory 0.5Gi `<br>  --system-assigned `<br>  --registry-server &quot;$($ACR).azurecr.io&quot; `<br>  --registry-username $ACR `<br>  --registry-password $ACR_PASS<br><br># Get MI principal<br>$PRINCIPAL_ID = az containerapp identity show --name $ACA_APP --resource-group $RG --query principalId -o tsv<br><br># AcrPull<br>$ACR_ID = az acr show --name $ACR --query id -o tsv<br>az role assignment create --role AcrPull --assignee $PRINCIPAL_ID --scope $ACR_ID<br><br># Switch to MI, disable admin<br>az containerapp registry set --name $ACA_APP --resource-group $RG --server &quot;$($ACR).azurecr.io&quot; --identity system<br>az acr update --name $ACR --admin-enabled false<br><br># SDK roles<br>az role assignment create --role &quot;Reader&quot; --assignee $PRINCIPAL_ID --scope &quot;/subscriptions/$SUB_ID&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5btW70aPwFT_-QDZ9TaIw.png" /></figure><p>Steps 3 and 4 together complete the Managed Identity loop: the Container App pulls its image from ACR using its own identity, and calls the Azure Management API using that same identity. No secrets anywhere.</p><h3>3.5 — Get the Endpoint</h3><pre>$FQDN=$(az containerapp show \<br>  --name $ACA_APP \<br>  --resource-group $RG \<br>  --query &quot;properties.configuration.ingress.fqdn&quot; -o tsv)</pre><pre>echo &quot;MCP endpoint: https://$FQDN/mcp&quot;<br>echo &quot;Health: https://$FQDN/health&quot;</pre><h3>3.6 — Validate the Deployment</h3><p>Health check first:</p><pre>curl https://$FQDN/health<br># {&quot;status&quot;:&quot;healthy&quot;,&quot;server&quot;:&quot;AzureOps MCP&quot;}</pre><p>Tool discovery:</p><pre>curl -X POST https://$FQDN/mcp \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:1,&quot;method&quot;:&quot;tools/list&quot;,&quot;params&quot;:{}}&#39;</pre><p>Expected: JSON listing all three tools — get_deployment_status, get_resource_tags, check_resource_health.</p><p>Then update .vscode/mcp.json to point at the live endpoint:</p><pre>{<br>  &quot;servers&quot;: {<br>    &quot;azureops-mcp&quot;: {<br>      &quot;type&quot;: &quot;http&quot;,<br>      &quot;url&quot;: &quot;https://{your-fqdn}/mcp&quot;<br>    }<br>  }<br>}</pre><p>Reload VS Code. Run the same three prompts from Phase 2 — now against the live Container App. Confirm all three tools return real Azure data from the deployed endpoint.</p><p>✅ <strong>Production checkpoint:</strong> The same Copilot prompt that returned simulated data in Part 2 now returns real data from a deployed, identity-authenticated Azure Container App. That’s the line crossed.</p><h3>Alternative: Azure Functions</h3><p>If your team already runs a Functions-based codebase, you can deploy MCP tools there using Microsoft.Azure.Functions.Worker.Extensions.Mcp v1.4.0.</p><p>One thing to keep in mind before you go that route: <strong>Azure Functions requires a separate project.</strong> The ASP.NET Core hosting model (WebApplication.CreateBuilder) and the Functions isolated worker model (FunctionsApplication.CreateBuilder) are not compatible in the same project. Each tool becomes a separate [McpToolTrigger]-decorated Function, and the deployment toolchain (func CLI) is different from Container Apps.</p><p>This is not a reason to avoid Functions — it’s a reason to make the choice deliberately.</p><p><strong>Functions are worth a separate project if:</strong></p><ul><li>You’re extending an existing Functions app that already has timers, queues, or other triggers — MCP tools belong alongside those</li><li>You need per-invocation billing granularity at the individual tool level</li><li>Your traffic pattern is genuinely bursty — quiet for hours, spike, then quiet again — and Consumption plan economics matter</li></ul><p><strong>Container Apps is the simpler path if:</strong></p><ul><li>This is a new project (which it is, if you followed Parts 1 and 2)</li><li>You want the same binary running locally and in production with no structural difference</li><li>You need Dapr, custom domains, or non-MCP HTTP endpoints alongside your tools</li></ul><p>Microsoft’s own Microsoft Learn tutorials for deploying .NET MCP servers use Container Apps. That’s not accidental.</p><h3>What’s Still Missing</h3><p>The Container App endpoint is publicly accessible. Anyone with the URL can call your tools with any subscription ID. There’s no authentication, no authorization, no audit trail.</p><p><strong>Part 4</strong> addresses this: Azure API Management in front of the MCP endpoint, Microsoft Entra ID OAuth 2.1 for caller authentication, and per-tool authorization policies so only identities with the right roles can invoke specific tools.</p><p>The security model for MCP has some non-obvious failure modes that most implementations get wrong. Part 4 is specific about what those are.</p><h3>Series Progress</h3><ul><li>✅ <a href="https://medium.com/gitconnected/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c">Part 1 — Mental model, why MCP matters for Azure</a></li><li>✅ <a href="https://medium.com/gitconnected/your-first-mcp-server-in-c-net-build-something-real-in-30-minutes-ea146c8226e2">Part 2 — First MCP server in C# .NET, tested in GitHub Copilot</a></li><li>✅ Part 3 ← You are here</li><li><strong>Part 4</strong> — Secure with Entra ID + APIM</li><li>Part 5 — Multi-user data isolation with Cosmos DB</li><li>Part 6 — Register in Microsoft Foundry Agent Service</li><li>Part 7 — Observability with OpenTelemetry + Azure Monitor</li><li>Part 8 — Full E2E production system + cost breakdown + production checklist</li></ul><p><em>Divyesh writes production-grade Azure + Microsoft Foundry guides with real code and real benchmarks. Follow for Part 4 — security that doesn’t cut corners.</em></p><p><em>Part 3 of </em><strong><em>MCP on Azure: From Zero to Production</em></strong><em> — published in [Microsoft Azure in Practice].</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78b05bb1e5a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microsoft-azure-in-practice/from-local-to-azure-deploy-your-mcp-server-to-production-78b05bb1e5a9">From Local to Azure: Deploy Your MCP Server to Production</a> was originally published in <a href="https://medium.com/microsoft-azure-in-practice">Microsoft Azure in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your First MCP Server in C# (.NET) — Build Something Real in 30 Minutes]]></title>
            <link>https://levelup.gitconnected.com/your-first-mcp-server-in-c-net-build-something-real-in-30-minutes-ea146c8226e2?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea146c8226e2</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 04:04:46 GMT</pubDate>
            <atom:updated>2026-06-08T04:04:46.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your First MCP Server in C# (.NET) — Build Something Real in 30 Minutes</h3><h4>Forget the echo tool. We’re building a server that actually earns its place in an AI workflow.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRZww3rYcgdt_7Mbx2uCtQ.png" /></figure><p>We’re building an <strong>Azure Operational Assistant, </strong>an MCP server with three tools, a resource, and a prompt, all wired around a problem every Azure developer actually has: <em>“What’s happening in my environment right now?”</em></p><p>By the end, you’ll have a working server, tested live inside GitHub Copilot Chat agent mode in VS Code. And the last section will be completely honest about what comes next, because “it works locally” and “it works in production” are very different sentences.</p><p>This is Part 2 of the <strong>MCP on Azure: From Zero to Production</strong> series. If you haven’t read Part 1, the mental model for Host / Client / Server is covered <a href="https://medium.com/gitconnected/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c">here</a>.</p><h3>What We’re Building</h3><p>The AzureOps MCP Server exposes three primitives:</p><p><strong>Tools</strong> (things the AI can <em>do</em>):</p><ul><li>get_deployment_status — Returns the last N deployments for a resource group with their status, timestamp, and duration</li><li>get_resource_tags — Fetches all tags on a given Azure resource ID and flags any missing required tags (useful for FinOps and governance)</li><li>check_resource_health — Returns health state for a given resource type + name combination</li></ul><p><strong>Resource</strong> (data the AI can <em>read</em>):</p><ul><li>azureops://runbooks/{name} — Returns a runbook document for a given incident type (on-call docs, escalation paths, rollback procedures)</li></ul><p><strong>Prompt</strong> (templated interaction):</p><ul><li>incident_triage_prompt — Generates a structured incident triage prompt combining deployment history, health state, and runbook context</li></ul><p>This maps to a real workflow: a developer asks Copilot, <em>“We’re seeing errors on the payments service — what happened?”</em> and the agent autonomously calls all three tools, reads the relevant runbook resource, and returns a structured triage report.</p><p>That’s what MCP is actually for.</p><h3>Prerequisites</h3><ul><li>.NET 9 or .NET 10 (either works; .NET 10 unlocks the dotnet new mcpserver template)</li><li>VS Code with the GitHub Copilot extension (agent mode required — this needs Copilot Pro or above)</li><li>A GitHub account with Copilot access</li></ul><p>No Azure subscription needed for this part. We’re running everything locally. Azure comes in Part 3.</p><h3>Step 1 — Create the Project</h3><p>Create a new ASP.NET Core Web API project. We’re using ASP.NET Core, not a console app, because we’re building for the Streamable HTTP transport from day one. (Most tutorials start with stdio — fine for learning, wrong for where we’re going.)</p><pre>dotnet new web -n AzureOpsMcpServer<br>cd AzureOpsMcpServer</pre><p>Now add the two packages you need:</p><pre>dotnet add package ModelContextProtocol.AspNetCore<br>dotnet add package Microsoft.Extensions.AI</pre><p><strong>Package note for 2026:</strong> The SDK is now stable and split into three packages. You only need ModelContextProtocol.AspNetCore — it pulls in ModelContextProtocol and ModelContextProtocol.Core automatically. No more --prerelease flag needed.</p><p>Your .csproj should reflect:</p><pre>&lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;ModelContextProtocol.AspNetCore&quot; Version=&quot;1.4.0&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Microsoft.Extensions.AI&quot; Version=&quot;10.6.0&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><h3>Step 2 — Wire Up the MCP Server</h3><p>Replace the contents of Program.cs:</p><pre>using ModelContextProtocol.Server;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddMcpServer()<br>    .WithHttpTransport(options =&gt;<br>    {<br>        // Stateless mode: recommended unless you need server-to-client<br>        // requests like sampling or elicitation. Stateless is safe to <br>        // run behind a load balancer - important when we deploy in Part 3.<br>        options.Stateless = true;<br>    })<br>    .WithToolsFromAssembly()<br>    .WithResourcesFromAssembly()<br>    .WithPromptsFromAssembly();<br><br>// CORS is required for Copilot Chat (browser-based) to reach your local server<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(policy =&gt;<br>    {<br>        policy.AllowAnyOrigin()<br>              .AllowAnyHeader()<br>              .AllowAnyMethod();<br>    });<br>});<br><br>var app = builder.Build();<br><br>app.UseCors();<br>app.MapMcp(&quot;/mcp&quot;);   // MCP endpoint lives at /mcp<br>app.MapGet(&quot;/health&quot;, () =&gt; Results.Ok(new { status = &quot;healthy&quot;, server = &quot;AzureOps MCP&quot; }));<br><br>app.Run(&quot;http://localhost:5100&quot;);</pre><p>Three things worth noting here:</p><p>Stateless = true is not just a flag, it&#39;s an architectural decision. Stateless servers don&#39;t maintain per-session state, which means they can scale horizontally behind Azure Container Apps without sticky sessions. We&#39;re writing for production from the start.</p><p>WithToolsFromAssembly(), WithResourcesFromAssembly(), and WithPromptsFromAssembly() scan your assembly at startup and register everything decorated with the appropriate attributes. No manual registration, no service locator.</p><p>MapMcp(&quot;/mcp&quot;) exposes the MCP endpoint at /mcp. When Copilot connects, it hits this endpoint for the protocol handshake, tool discovery, and all subsequent calls.</p><h3>Step 3 — Define Your Tools</h3><p>Create a folder called Tools and add AzureOpsTools.cs:</p><pre>using System.ComponentModel;<br>using ModelContextProtocol.Server;<br><br>namespace AzureOpsMcpServer.Tools;<br><br>[McpServerToolType]<br>public static class AzureOpsTools<br>{<br>    [McpServerTool(Name = &quot;get_deployment_status&quot;)]<br>    [Description(&quot;Returns recent deployment history for an Azure resource group. &quot; +<br>                 &quot;Includes deployment name, status (Succeeded/Failed/Running), &quot; +<br>                 &quot;timestamp, and duration in seconds. Use this to understand &quot; +<br>                 &quot;what changed recently before an incident.&quot;)]<br>    public static DeploymentStatusResult GetDeploymentStatus(<br>        [Description(&quot;The Azure resource group name to query&quot;)] string resourceGroup,<br>        [Description(&quot;Number of recent deployments to return (max 20)&quot;)] int count = 5)<br>    {<br>        // In Part 3 we&#39;ll wire this to the real Azure Management SDK.<br>        // For local testing, we return realistic simulated data.<br>        var deployments = Enumerable.Range(1, Math.Min(count, 20))<br>            .Select(i =&gt; new DeploymentEntry<br>            {<br>                Name = $&quot;deploy-payments-v1.{10 + i}&quot;,<br>                Status = i == 1 ? &quot;Failed&quot; : &quot;Succeeded&quot;,<br>                Timestamp = DateTimeOffset.UtcNow.AddHours(-i * 2),<br>                DurationSeconds = Random.Shared.Next(45, 320),<br>                DeployedBy = i % 2 == 0 ? &quot;github-actions[bot]&quot; : &quot;divyesh@contoso.com&quot;<br>            }).ToList();<br><br>        return new DeploymentStatusResult<br>        {<br>            ResourceGroup = resourceGroup,<br>            Deployments = deployments,<br>            Summary = $&quot;Last deployment &#39;{deployments[0].Name}&#39; {deployments[0].Status} &quot; +<br>                      $&quot;at {deployments[0].Timestamp:u}&quot;<br>        };<br>    }<br><br>    [McpServerTool(Name = &quot;get_resource_tags&quot;)]<br>    [Description(&quot;Fetches all tags on an Azure resource and identifies any missing &quot; +<br>                 &quot;required tags for FinOps and governance compliance. Required tags: &quot; +<br>                 &quot;Environment, Owner, CostCenter, Application.&quot;)]<br>    public static ResourceTagsResult GetResourceTags(<br>        [Description(&quot;Full Azure resource ID (e.g. /subscriptions/{sub}/resourceGroups/{rg}/providers/...)&quot;)] <br>        string resourceId)<br>    {<br>        var requiredTags = new[] { &quot;Environment&quot;, &quot;Owner&quot;, &quot;CostCenter&quot;, &quot;Application&quot; };<br>        <br>        // Simulated: in production this calls Azure Resource Manager via SDK<br>        var presentTags = new Dictionary&lt;string, string&gt;<br>        {<br>            { &quot;Environment&quot;, &quot;Production&quot; },<br>            { &quot;Application&quot;, &quot;payments-service&quot; },<br>            { &quot;Owner&quot;, &quot;platform-team@contoso.com&quot; }<br>            // Note: CostCenter intentionally missing — realistic scenario<br>        };<br><br>        var missingTags = requiredTags.Except(presentTags.Keys).ToList();<br><br>        return new ResourceTagsResult<br>        {<br>            ResourceId = resourceId,<br>            Tags = presentTags,<br>            MissingRequiredTags = missingTags,<br>            Compliant = missingTags.Count == 0,<br>            ComplianceSummary = missingTags.Count == 0<br>                ? &quot;Resource is fully tagged&quot;<br>                : $&quot;Missing {missingTags.Count} required tag(s): {string.Join(&quot;, &quot;, missingTags)}&quot;<br>        };<br>    }<br><br>    [McpServerTool(Name = &quot;check_resource_health&quot;)]<br>    [Description(&quot;Returns the current health state of an Azure resource. &quot; +<br>                 &quot;Health states: Available, Degraded, Unavailable, Unknown. &quot; +<br>                 &quot;Also returns the reason code and recommended action if unhealthy.&quot;)]<br>    public static ResourceHealthResult CheckResourceHealth(<br>        [Description(&quot;The resource type (e.g. &#39;AppService&#39;, &#39;CosmosDB&#39;, &#39;ServiceBus&#39;)&quot;)] <br>        string resourceType,<br>        [Description(&quot;The resource name as it appears in the Azure portal&quot;)] <br>        string resourceName)<br>    {<br>        // Simulated health response — Part 3 wires to Azure Resource Health API<br>        var isHealthy = !resourceName.Contains(&quot;payments&quot;, StringComparison.OrdinalIgnoreCase)<br>                        || Random.Shared.Next(0, 3) != 0;<br><br>        return new ResourceHealthResult<br>        {<br>            ResourceType = resourceType,<br>            ResourceName = resourceName,<br>            HealthState = isHealthy ? &quot;Available&quot; : &quot;Degraded&quot;,<br>            ReasonCode = isHealthy ? null : &quot;PlatformInitiated&quot;,<br>            RecommendedAction = isHealthy ? null : <br>                &quot;Check recent deployments and review Application Insights live metrics. &quot; +<br>                &quot;If degradation persists &gt; 15 minutes, escalate to platform team.&quot;,<br>            LastChecked = DateTimeOffset.UtcNow<br>        };<br>    }<br>}</pre><pre>// Result types — strongly typed outputs matter for LLM comprehension<br>public record DeploymentEntry<br>{<br>    public required string Name { get; init; }<br>    public required string Status { get; init; }<br>    public required DateTimeOffset Timestamp { get; init; }<br>    public required int DurationSeconds { get; init; }<br>    public required string DeployedBy { get; init; }<br>}<br><br>public record DeploymentStatusResult<br>{<br>    public required string ResourceGroup { get; init; }<br>    public required List&lt;DeploymentEntry&gt; Deployments { get; init; }<br>    public required string Summary { get; init; }<br>}<br><br>public record ResourceTagsResult<br>{<br>    public required string ResourceId { get; init; }<br>    public required Dictionary&lt;string, string&gt; Tags { get; init; }<br>    public required List&lt;string&gt; MissingRequiredTags { get; init; }<br>    public required bool Compliant { get; init; }<br>    public required string ComplianceSummary { get; init; }<br>}<br><br>public record ResourceHealthResult<br>{<br>    public required string ResourceType { get; init; }<br>    public required string ResourceName { get; init; }<br>    public required string HealthState { get; init; }<br>    public string? ReasonCode { get; init; }<br>    public string? RecommendedAction { get; init; }<br>    public required DateTimeOffset LastChecked { get; init; }<br>}</pre><p><strong>Why strongly typed return objects matter:</strong> The LLM receives your tool’s output as a serialized JSON blob. Vague string responses force the model to parse freeform text, which degrades reliability. Structured records with clear field names — HealthState, MissingRequiredTags, Summary — give the model crisp, unambiguous data to reason over. This is not a style. It&#39;s how you get consistent agent behavior.</p><h3>Step 4 — Add a Resource</h3><p>Create Resources/RunbookResource.cs:</p><pre>using System.ComponentModel;<br>using ModelContextProtocol.Server;<br>namespace AzureOpsMcpServer.Resources;<br><br>[McpServerResourceType]<br>public static class RunbookResources<br>{<br>    [McpServerResource(<br>        UriTemplate = &quot;azureops://runbooks/{name}&quot;,<br>        Name = &quot;Operational Runbook&quot;,<br>        MimeType = &quot;text/plain&quot;)]<br>    [Description(&quot;Returns the operational runbook for a given incident type. &quot; +<br>                 &quot;Valid names: payment-degradation, database-failover, deployment-rollback&quot;)]<br>    public static string GetRunbook(string name) =&gt; name.ToLowerInvariant() switch<br>    {<br>        &quot;payment-degradation&quot; =&gt; &quot;&quot;&quot;<br>            RUNBOOK: Payment Service Degradation<br>            =====================================<br>            Severity: P1 | Owner: Platform Team | Escalation: #p1-payments<br><br>            IMMEDIATE ACTIONS (&lt; 5 min)<br>            1. Check deployment history for changes in last 4 hours<br>            2. Verify CosmosDB RU consumption in Azure Monitor<br>            3. Check Service Bus dead-letter queue depth<br>            4. Review Application Insights failure rate — threshold: &gt; 0.5%<br><br>            ESCALATION PATH<br>            - 0-15 min: On-call engineer (PagerDuty)  <br>            - 15-30 min: Platform Lead + Product Manager<br>            - 30+ min: VP Engineering + incident bridge open<br><br>            ROLLBACK DECISION<br>            Trigger rollback if: failure rate &gt; 2% sustained for 5 minutes<br>            Rollback command: az deployment group create --rollback-on-error<br>            &quot;&quot;&quot;,<br><br>        &quot;deployment-rollback&quot; =&gt; &quot;&quot;&quot;<br>            RUNBOOK: Deployment Rollback Procedure<br>            =======================================<br>            Severity: P2 | Owner: DevOps | Escalation: #deployments<br><br>            PREREQUISITE CHECKS<br>            1. Confirm the failed deployment name from get_deployment_status<br>            2. Identify the last known-good deployment timestamp<br>            3. Verify rollback target is available in deployment history<br><br>            ROLLBACK STEPS<br>            1. Notify #deployments Slack channel<br>            2. az deployment group create \<br>                 --resource-group &lt;RG&gt; \<br>                 --rollback-on-error<br>            3. Monitor health for 10 minutes post-rollback<br>            4. Open post-mortem within 24 hours<br><br>            SUCCESS CRITERIA<br>            Health state returns to &#39;Available&#39; within 5 minutes of rollback<br>            &quot;&quot;&quot;,<br><br>        &quot;database-failover&quot; =&gt; &quot;&quot;&quot;<br>            RUNBOOK: Cosmos DB Failover Procedure<br>            ======================================<br>            Severity: P1 | Owner: Data Platform | Escalation: #data-incidents<br><br>            WHEN TO USE THIS RUNBOOK<br>            - Cosmos DB region shows Unavailable in Azure Portal<br>            - Write latency &gt; 2000ms sustained for 3+ minutes<br>            - Health API returns 503 for &gt; 2 minutes<br><br>            FAILOVER STEPS  <br>            1. Confirm the affected region in Azure Portal &gt; Cosmos DB &gt; Replicate data globally<br>            2. Trigger manual failover: Portal &gt; Failover &gt; Select secondary region<br>            3. Update connection strings in App Configuration / Key Vault if not using multi-region SDK<br>            4. Verify application can write to new primary region<br><br>            ESTIMATED DOWNTIME: 1-3 minutes for manual failover<br>            &quot;&quot;&quot;,<br><br>        _ =&gt; $&quot;No runbook found for &#39;{name}&#39;. Available runbooks: payment-degradation, database-failover, deployment-rollback&quot;<br>    };<br>}</pre><p>Resources behave differently from tools. The AI <em>reads</em> a resource when it needs context — policy documents, runbooks, and configuration. Notice the URI template azureops://runbooks/{name}: the {name} segment maps to the method parameter. The SDK handles the routing automatically.</p><h3>Step 5 — Add a Prompt</h3><p>Create Prompts/IncidentPrompt.cs:</p><pre>using System.ComponentModel;<br>using ModelContextProtocol.Server;<br><br>namespace AzureOpsMcpServer.Prompts;<br><br>[McpServerPromptType]<br>public static class IncidentPrompts<br>{<br>    [McpServerPrompt(Name = &quot;incident_triage_prompt&quot;, Title = &quot;Azure Incident Triage&quot;)]<br>    [Description(&quot;Generates a structured incident triage prompt. &quot; +<br>                 &quot;Use when an engineer reports a potential incident and needs &quot; +<br>                 &quot;a systematic investigation starting point.&quot;)]<br>    public static string GetIncidentTriagePrompt(<br>        [Description(&quot;The service or resource experiencing issues&quot;)] string serviceName,<br>        [Description(&quot;Brief description of the observed symptoms&quot;)] string symptoms,<br>        [Description(&quot;Resource group to check for recent deployments&quot;)] string resourceGroup)<br>    {<br>        return $&quot;&quot;&quot;<br>            You are an Azure operations assistant. An engineer has reported a potential incident.<br>            SERVICE: {serviceName}<br>            SYMPTOMS: {symptoms}<br>            RESOURCE GROUP: {resourceGroup}<br><br>            Please investigate using the following sequence:<br>            1. Call get_deployment_status for resource group &#39;{resourceGroup}&#39; — look for recent changes<br>            2. Call check_resource_health for &#39;{serviceName}&#39;<br>            3. If the service is &#39;payments&#39; or payment-related, read the runbook at azureops://runbooks/payment-degradation<br>            4. Call get_resource_tags to verify compliance — untagged resources may indicate shadow infrastructure<br><br>            Synthesize findings into:<br>            - LIKELY CAUSE (based on deployment history and health state)<br>            - IMMEDIATE ACTIONS (from runbook and health recommendations)  <br>            - COMPLIANCE STATUS (from tag check)<br>            - CONFIDENCE LEVEL (High / Medium / Low) with reasoning<br><br>            Be specific and actionable. The engineer is in an active incident.<br>            &quot;&quot;&quot;;<br>    }<br>}</pre><p>Prompts are often the most underused MCP primitive, but they’re genuinely powerful in enterprise workflows. Rather than every engineer crafting their own ad-hoc investigation prompt, a defined prompt guarantees a consistent investigation pattern, the same structure, the same tool call sequence, the same output format, every time.</p><h3>Step 6 — Tell VS Code About Your Server</h3><p>In the root of your project, create .vscode/mcp.json:</p><pre>{<br>  &quot;servers&quot;: {<br>    &quot;azureops-mcp&quot;: {<br>      &quot;type&quot;: &quot;http&quot;,<br>      &quot;url&quot;: &quot;http://localhost:5100/mcp&quot;<br>    }<br>  }<br>}</pre><p>This tells VS Code’s GitHub Copilot extension where to find your MCP server. When Copilot’s agent mode starts, it reads this file, connects to your server at the /mcp endpoint, and discovers your tools automatically.</p><h3>Step 7 — Run and Test</h3><p>Start the server:</p><pre>dotnet run</pre><p>You should see:</p><pre>info: Microsoft.Hosting.Lifetime[14]<br>      Now listening on: http://localhost:5100</pre><p>Quick sanity check — hit the health endpoint to confirm it’s running:</p><pre>curl http://localhost:5100/health<br># {&quot;status&quot;:&quot;healthy&quot;,&quot;server&quot;:&quot;AzureOps MCP&quot;}</pre><p>Now open VS Code, open Copilot Chat (Ctrl+Alt+I), and switch to <strong>Agent mode</strong> using the dropdown at the bottom of the chat panel.</p><p>Click the <strong>Tools</strong> button (the wrench icon). You should see azureops-mcp listed with all three tools: get_deployment_status, get_resource_tags, and check_resource_health.</p><p>If the server isn’t appearing, check that dotnet run is still running, and the port matches your mcp.json.</p><h3>Test Prompts to Try</h3><p><strong>Basic tool invocation:</strong></p><pre>Check the deployment status for resource group &quot;rg-payments-prod&quot; <br>and tell me what changed in the last 24 hours.</pre><p>Watch Copilot ask for your permission to run get_deployment_status, then return structured deployment history. It will identify the failed deployment in the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RlZANf1xjvCj-HSdrD1vw.png" /><figcaption>Image created by Author — VS Code Basic Prompt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dv7EFDdGNyD6xxmqw2geUw.png" /><figcaption>Image created by Author — VS Code Basic Prompt</figcaption></figure><p><strong>Multi-tool chain:</strong></p><pre>The payments service is showing errors. Check deployments in <br>&quot;rg-payments-prod&quot;, check health for AppService &quot;payments-api&quot;, <br>and then tell me what you think happened and what I should do first.</pre><p>This triggers all three tools in sequence. The agent orchestrates the tool calls autonomously. You don’t specify the order, Copilot decides based on what makes sense. This is the agentic loop in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUlOg7leduxuP2TXvGwqcg.png" /><figcaption>Image created by Author — VS Code — Multi tool Chain</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38cGnxXpBAMvm03H0qCLwQ.png" /><figcaption>Image created by Author — VS Code — Multi tool Chain</figcaption></figure><p><strong>Resource + tool chain:</strong></p><pre>Get the runbook for &quot;payment-degradation&quot; and then check if the <br>payments-api health state matches any of the escalation conditions <br>described in the runbook.</pre><p>This combines a resource read with a tool call. Copilot reads the runbook text, checks the health tool output, and reasons across both pieces of context.</p><p><strong>Prompt-driven investigation:</strong></p><pre>Use the incident_triage_prompt to investigate: <br>service &quot;payments-api&quot;, <br>symptoms &quot;elevated 500 errors since 14:30 UTC&quot;, <br>resource group &quot;rg-payments-prod&quot;</pre><p>This triggers the structured investigation workflow — all tools get called, the runbook gets read, and you receive a formatted triage report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Hr6Sn0ULnjmoIIr5_jyqA.png" /><figcaption>Image created by Author — VS Code — Prompt Driven</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejPjXPd2Gvd2TokljIYsng.png" /><figcaption>Image created by Author — VS Code — Prompt Driven</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfduO4voa5Naz1aoPcpa_A.png" /><figcaption>Image created by Author — VS Code — Prompt Driven</figcaption></figure><h3>What Just Happened Under the Hood</h3><p>When Copilot calls one of your tools, here’s the exact sequence:</p><ol><li>You type a prompt in agent mode</li><li>Copilot sends your message to the LLM, including the tool schemas discovered from your MCP server</li><li>The LLM decides which tool(s) to call and with what parameters</li><li>Copilot sends a JSON-RPC tools/call request to your server&#39;s /mcp endpoint</li><li>Your .NET method executes, returns the typed result</li><li>The result is serialized to JSON and returned to Copilot</li><li>Copilot feeds the tool result back to the LLM as context</li><li>The LLM generates a response using both the original prompt and the tool output</li></ol><p>Steps 3–7 can be repeated multiple times in a single conversational turn — that’s what “agentic loop” means. The model doesn’t stop after one tool call; it calls as many tools as it needs to answer the question.</p><p>You can watch the raw JSON-RPC traffic if you want to see this in action. In VS Code, open the Output panel and select “GitHub Copilot” from the dropdown. You’ll see the actual tool invocation payloads.</p><h3>Five Things That Will Trip You Up</h3><p><strong>1. The Description matters more than the method name</strong></p><p>The LLM decides <em>which</em> tool to call based on the [Description] text, not the method name. Vague descriptions produce wrong tool calls. Be precise: say what the tool returns, what the parameters mean, and when to use it versus other similar tools.</p><p><strong>2. Stateless vs. stateful and what happens in between</strong></p><p>With Stateless = true, Each tool call is independent. Your tool method has no access to previous calls in the same conversation. If your tools need to share context (e.g., use the output of get_deployment_status inside check_resource_health), the LLM handles that — it carries context in its own conversation window, not your server.</p><p><strong>3. CORS for local Copilot testing</strong></p><p>Without app.UseCors(), GitHub Copilot Chat (which makes requests from a browser context inside VS Code) will get blocked with a CORS error. The server will be &quot;running&quot; but Copilot will silently fail to connect. The AllowAnyOrigin config here is fine for local development; we lock this down in Part 4.</p><p><strong>4. Tool return types and JSON serialization</strong></p><p>Avoid returning object, dynamic, or raw string from tools. The LLM receives JSON, and an ambiguous structure hurts reasoning quality. Use strongly typed records. If you need to return variable shapes, use discriminated unions or a typed envelope with a type discriminator field.</p><p><strong>5. The </strong><strong>.vscode/mcp.json needs to be at the workspace root</strong></p><p>If your mcp.json is inside a subfolder, VS Code won&#39;t discover it automatically. Put it at the root of the folder you opened in VS Code, alongside your .sln or .csproj.</p><h3>It Works Locally — Now What?</h3><p>You have a working MCP server. Three tools, a resource, a prompt. Tested live in Copilot. And the whole thing is genuinely useful, not a toy, and actually useful in a real incident.</p><p>Here’s the honest “now what”:</p><p><strong>What you can’t do yet:</strong></p><ul><li>Share this with your team (it only runs on your machine)</li><li>Use it with real Azure data (tools return simulated responses)</li><li>Secure it (any caller can invoke your tools)</li><li>Scale it (one instance, your local port)</li></ul><p>All four of those get fixed in the next articles.</p><p><strong>Part 3</strong> takes this exact server and deploys it to Azure — Azure Functions vs. Container Apps, with real benchmarks on cold start and cost. We also wired the three tools to the actual Azure Management SDK so they return real data from your subscription.</p><p><strong>Part 4</strong> locks it down: Entra ID authentication so only authorized identities can call your tools, and Azure API Management as the gateway.</p><p>The progression from Part 2 to Part 8 is one continuous codebase. Everything you wrote here is exactly what gets deployed, secured, and observed in the articles ahead.</p><h3>Complete Project Structure</h3><p><strong><em>Source Code: </em></strong><a href="https://github.com/divyeshg94/AzureOpsMcpServer/tree/part2">https://github.com/divyeshg94/AzureOpsMcpServer/tree/part2</a></p><p>Here’s what you should have at this point:</p><pre>AzureOpsMcpServer/<br>├── .vscode/<br>│   └── mcp.json<br>├── Tools/<br>│   └── AzureOpsTools.cs<br>├── Resources/<br>│   └── RunbookResource.cs<br>├── Prompts/<br>│   └── IncidentPrompt.cs<br>├── AzureOpsMcpServer.csproj<br>└── Program.cs</pre><p>One folder per primitive. As the server grows, this keeps things from becoming a maze. No hunting for where a new resource belongs.</p><h3>What’s Next in This Series</h3><ul><li>✅ Part 1 — Mental model, architecture, why MCP matters for Azure. <a href="https://levelup.gitconnected.com/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c">https://levelup.gitconnected.com/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c</a></li><li>✅ Part 2 ← You are here</li><li><strong>Part 3</strong> — Deploy to Azure: Functions vs. Container Apps benchmarks</li><li>Part 4 — Secure with Entra ID + APIM</li><li>Part 5 — Multi-user data isolation with Cosmos DB</li><li>Part 6 — Register in Microsoft Foundry Agent Service</li><li>Part 7 — Observability with OpenTelemetry + Azure Monitor</li><li>Part 8 — Full E2E production system + checklist</li></ul><p>The GitHub repo with the complete series codebase is linked in my profile. Follow along. Each branch corresponds to one article.</p><p><strong>About the author</strong></p><p>Divyesh Govaerdhanan is a Microsoft MVP for Azure PaaS and a Senior Software Engineer specializing in .NET, Azure AI Foundry, and Azure DevOps. He is the founder of the “<a href="https://medium.com/microsoft-azure-in-practice">Microsoft Azure in Practice</a>” publication on Medium and the creator of <a href="https://github.com/divyeshg94/Ingenious.Velo">Velo</a>, an AI-powered DORA metrics extension for Azure DevOps built on GPT-4o and Azure Container Apps.</p><p>He is a top contributor on Microsoft Q&amp;A with 10,000+ reputation points and an active voice in the Azure and .NET communities.</p><p>Follow him on <a href="https://www.linkedin.com/in/divyeshgovardhanan/">LinkedIn</a> and <a href="https://github.com/divyeshg94">GitHub</a> to stay connected.</p><p><em>If this article helped you, consider leaving 50 claps. It helps more engineers in the community find it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea146c8226e2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-first-mcp-server-in-c-net-build-something-real-in-30-minutes-ea146c8226e2">Your First MCP Server in C# (.NET) — Build Something Real in 30 Minutes</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Build 2026 Day 1: The Platform Has Shifted — Here’s What It Means for Azure Developers]]></title>
            <link>https://medium.com/microsoft-azure-in-practice/microsoft-build-2026-day-1-the-platform-has-shifted-heres-what-it-means-for-azure-developers-beacdb0a2d81?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/beacdb0a2d81</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[microsoft-build]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 21:33:24 GMT</pubDate>
            <atom:updated>2026-06-02T21:33:24.990Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Every year, Build tells you where the next 18 months are going. This year, it wasn’t subtle.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCAgKdz3AVRN-1lHcB9hGA.png" /><figcaption>Microsoft Build 2026</figcaption></figure><p>Microsoft Build 2026 kicked off in San Francisco today (02 Jun 2026), and if there’s one thing the announcements make clear, it’s this: the “AI features bolted onto existing products” era is over. What’s replacing it is deeper, more opinionated, and frankly more interesting for anyone building on Azure.</p><p>Here’s an honest breakdown of what matters, what’s still marketing-speak, and what you should actually care about as an Azure developer — ordered by what changes your architecture, not by what Microsoft put first in their press release.</p><h3>The Thing Everyone Missed: OpenClaw, MXC, and the Agent-Native OS</h3><p>Most of today’s coverage will lead with the new models. That’s the wrong place to start. The announcement with the deepest long-term implications for Azure developers — and the one that got the least airtime — is the OS-level agent execution stack Microsoft quietly shipped today.</p><p><strong>Microsoft Execution Containers (MXC)</strong>, now in preview, adds OS-enforced sandboxing for agent execution directly into Windows. You describe the containment policy once; Windows enforces it everywhere your agents run. No custom runtime, no third-party isolation layer — the operating system itself is the trust boundary.</p><p>Built on top of MXC: <strong>OpenClaw on Windows</strong>, enabling multi-step agentic workflows inside those OS-enforced boundaries on local machines. NVIDIA’s <strong>OpenShell</strong> adds policy management, inference routing, and PII obfuscation on the same primitive. Together, they give you a genuinely safe local execution environment and not a sandpit for demos, but a governance-ready surface for production agent workloads.</p><p>Here’s why this matters in concrete terms. Imagine you’re deploying a Copilot agent that processes HR documents or handles financial reconciliation on-device. Today, the risk is that a compromised or misbehaving agent can read outside its scope, exfiltrate data to a sideloaded process, or escalate privileges. MXC closes that surface at the OS layer — the containment is enforced before the agent ever gets to make a bad call. That’s a different class of security guarantee than anything you can achieve in application code.</p><p>And riding on top of all of this: <strong>Microsoft Scout</strong> — a personal work agent built on OpenClaw and Work IQ, rolling out to Frontier customers today. It handles meeting prep, scheduling conflicts, and routine tasks autonomously using Teams and Outlook natively. No new interface. No separate app. It operates from inside the tools your organization already lives in, backed by OS-level containment.</p><p><strong>The honest take:</strong> MXC is the piece that finally makes “local agent execution” a real enterprise story rather than a developer experiment. If you’ve been hesitant to push agent workloads to end-user devices because you couldn’t answer the governance question, this is the architectural answer. Watch the MXC preview closely, this is the primitive that everything else will build on.</p><h3>Microsoft IQ: Finally, Context That Means Something (But We’ve Heard This Before)</h3><p>The headline enterprise announcement is <strong>Microsoft IQ</strong>, now generally available across GitHub Copilot, Microsoft Foundry, and Copilot Studio. It’s a context layer — not a chatbot feature, not a search upgrade, a programmable intelligence foundation that grounds your agents in both enterprise knowledge and world knowledge simultaneously.</p><p>It ships in four components:</p><ul><li><strong>Work IQ</strong> — workplace intelligence derived from Microsoft 365: emails, documents, meetings, org structure, people relationships. The Work IQ APIs go GA on June 16. This is what makes an agent understand <em>how your company operates</em>, not just what’s in a database.</li><li><strong>Fabric IQ</strong> — semantic layer over structured business data. If your BI stack lives in Fabric, your agents can now reason over it natively.</li><li><strong>Foundry IQ</strong> — an orchestration layer that plans retrieval across enterprise knowledge <em>and</em> the live web in a single query path.</li><li><strong>Web IQ</strong> — new today: an AI-first, MCP-native web search stack that Microsoft claims returns relevant passages at nearly 2.5x the speed of the next best alternative. Model-agnostic, which matters for heterogeneous Foundry setups.</li></ul><p><strong>The honest take:</strong> Work IQ deserves a closer look — but with eyes open. Microsoft has promised programmable enterprise context before. Microsoft Graph was supposed to unlock this a decade ago. Then Semantic Kernel’s memory abstractions. Then the original Copilot extensibility model. Each iteration got closer and hit different walls around latency, schema drift, and cross-system identity resolution.</p><p>The difference this time is meaningful but not yet proven: the APIs are GA on June 16 — not in perpetual preview, and the grounding operates at the retrieval-planning layer rather than as a thin wrapper over search. That’s architecturally the right approach. Whether it holds under real enterprise data volume and the inevitable messiness of production M365 tenants is what the next 90 days will tell us. Mark June 16 in your calendar and actually test the Work IQ APIs against your own data before committing to this as a core dependency.</p><h3>MAI Model Family: Seven New Models, One Important Caveat</h3><p>Microsoft’s AI Superintelligence Team shipped a family of <strong>seven new in-house models</strong> today. The headliner is <strong>MAI-Thinking-1</strong> — Microsoft’s first reasoning model, and the one that will attract the most scrutiny.</p><p>It’s a mid-sized model with 35 billion active parameters and a 256K context window, trained entirely from scratch with no distillation from competing models. That last part matters more than the benchmark numbers: the training data is commercially licensed and enterprise-grade. MAI-Thinking-1 has a cleaner answer than almost anything else on the market.</p><p>Microsoft claims it matches Opus 4.6 on SWE-Bench Pro coding tasks and is preferred over Sonnet 4.6 in blind human evaluations run by Surge, their independent rating partner. It’s available in private preview on Azure AI Foundry today.</p><p>One important caveat: Surge was commissioned by Microsoft, and the SWE-Bench Pro results haven’t been independently replicated yet. The benchmark story is compelling on paper — hold your conviction loosely until the community gets hands-on access.</p><p>The rest of the family fills real production gaps. <strong>MAI-Image-2.5</strong> and its Flash variant handle both text-to-image (#3 on Arena AI leaderboard) and image-to-image (#2) workloads — rolling out in PowerPoint and OneDrive today, landing on Foundry with what Microsoft calls market-leading quality per dollar. <strong>MAI Transcribe 1.5</strong> covers 43 languages with streaming on the way. <strong>MAI-Voice-2 + Flash</strong> add 15+ new languages with expanded voice options. <strong>MAI-Code-1</strong> is an inference-efficient coding model tuned specifically for GitHub, already live in Copilot and VS Code.</p><p>Also worth flagging: <strong>Frontier Tuning</strong>, now in private preview, applies reinforcement learning entirely within your compliance boundary, using your own data, domain knowledge, and workflows, so agents can learn how your business actually operates rather than just generalizing from pre-training. This is the feature that turns a capable foundation model into one that genuinely reflects your organization’s processes. If you’re building agents that need to get better over time rather than staying static, Frontier Tuning is where that loop lives.</p><p><strong>The honest take:</strong> The IP-clean training data story is genuinely the strongest card in this hand for enterprise buyers, not the benchmarks. What matters most for Azure developers is that these models are built for Foundry-native deployment: lower latency, tighter governance integration, and no data leaving your Azure boundary. The benchmark claims will be stress-tested by the community quickly. The data lineage story is structurally harder for competitors to replicate.</p><h3>MDASH: Security Finally Catches Up to the Threat</h3><p><strong>Codename MDASH</strong> is Microsoft’s new multi-model agentic security system, and it’s the most architecturally honest answer to a question the industry has been dodging: who secures the agents?</p><p>MDASH deploys 100+ specialized agents to find exploitable bugs — not by pattern-matching against known CVEs, but by reasoning about data flow, business logic, and exploit chains in context. Fixes surface directly in the Defender Portal.</p><p>This pairs with two new open-source governance projects that are worth understanding separately from the product announcement:</p><ul><li><strong>ASSERT</strong> (Adaptive Spec-driven Scoring for Evaluation and Regression Testing) — policy-driven safety evaluation for agents. The significance here is that it’s spec-driven: you write your intent as a policy, ASSERT generates executable evals from it. This closes the gap between what you meant the agent to do and what you can actually test.</li><li><strong>Agent Control Specification</strong> — an open standard for where and how controls apply in the agent execution loop. This matters because right now every framework (Semantic Kernel, LangChain, AutoGen) has its own control surface. A shared specification is how the ecosystem avoids fracturing into incompatible governance models.</li></ul><p><strong>The honest take:</strong> MDASH is the most concrete answer Microsoft has given to the “who secures the agents?” question. The agentic DevSecOps angle, security that reasons about code intent, is the right direction. Whether 100+ agents find what experienced pentesters miss is something we’ll know from practice. The open-source governance layer is the more durable story: if ASSERT and the Agent Control Specification get broad adoption, they become the compliance baseline every enterprise will need to meet.</p><h3>Surface RTX Spark Dev Box: When Does Local Beat Cloud?</h3><p>Hardware at Build is usually an afterthought. This year, it has a real use-case argument behind it.</p><p>The <strong>Surface RTX Spark Dev Box</strong> is powered by NVIDIA RTX Spark and delivers up to one petaflop of AI compute across 128 GB of unified memory. It runs models up to 120B parameters locally with up to a million token context window, with no cloud GPU instances required. Windows Subsystem for Linux 2 (WSL2) ships preconfigured with native GPU passthrough and full CUDA support, alongside VS Code and GitHub Copilot out of the box. Available later this year in the US.</p><p>The honest question to ask is when this makes economic and operational sense over Azure GPU instances. Running a large model continuously on Azure GPU compute runs into thousands of dollars per month for a single always-on workload — costs that compound quickly across a team running multiple experiments in parallel. The Surface RTX Spark Dev Box is a capital expenditure, not an operational one, which changes the calculus for teams running sustained, long-horizon agent pipelines or frequent local fine-tuning experiments. If your team is spinning up GPU instances repeatedly for iteration rather than burst inference, the economics shift in favor of local hardware faster than you’d expect.</p><p><strong>The honest take:</strong> The 128 GB unified memory is the number that actually matters here — that’s what enables running serious parameter counts without hitting the memory wall that makes local inference painful. This isn’t a machine for hobbyist experimentation. It’s for teams running sustained agentic pipelines or local fine-tuning loops who are tired of watching cloud GPU bills scale with iteration count.</p><h3>Microsoft Discovery: A Reference Architecture Worth Studying</h3><p><strong>Microsoft Discovery</strong> is now generally available, an enterprise-grade agentic AI platform for scientific research workflows, built on Azure. Real customers using it in production today: BHP cutting time-to-solution on copper-leaching R&amp;D from years to months, Syensqo accelerating semiconductor materials research, GSK iterating through drug discovery pipelines.</p><p>A free Discovery local app also launched in preview, requiring only a GitHub Copilot account — no enterprise Azure commitment needed to start exploring it.</p><p>The reason this matters beyond the scientific use cases is architectural. Discovery is a fully realized production example of the agentic pattern most teams are trying to build right now: a persistent, domain-grounded agent that runs long, multi-step tool-use loops, maintains memory across sessions, and retrieves information from specialized knowledge sources rather than from general web context. It’s the same pattern you’d implement in Foundry Agent Service — persistent memory, multi-step reasoning chains, domain-specific retrieval grounding, but here Microsoft has shipped it at production scale, with paying enterprise customers validating the approach. Before you design your own long-running agentic workflow architecture, it’s worth understanding how Discovery handles session persistence and retrieval planning.</p><h3>Majorana 2: Why the Numbers Actually Matter</h3><p>Microsoft’s next-generation quantum computing chip, <strong>Majorana 2</strong> closes the event with the longest time horizon, but the headline numbers deserve more than a bullet list.</p><p>The key metric is qubit lifetime: Majorana 2 achieves an average of 20 seconds, with some instances reaching a full minute. To understand why that’s significant, current superconducting qubit generations — the kind that power most commercial quantum computers today — typically achieve coherence times measured in milliseconds, sometimes microseconds. Majorana 2’s 20-second average represents roughly a 20,000x improvement in the metric that most directly constrains what quantum algorithms can actually compute before errors accumulate and the calculation collapses. The 1,000x reliability improvement over Microsoft’s previous generation compounds on top of that. The path to one million qubits on a single chip — with a 2029 target for a scalable quantum machine — becomes plausible under these numbers in a way it simply wasn’t before.</p><p>For Azure developers, the practical implication isn’t immediate. But the developer platform you’re building on today — Foundry, Azure AI services, the MCP tooling ecosystem — is the same platform that will surface quantum compute primitives when they arrive. The teams that understand the abstraction layer early will have a meaningful head start when hybrid classical-quantum workloads become a real architectural option, particularly in chemistry simulation, logistics optimization, and post-quantum cryptography readiness.</p><h3>The Azure Developer Takeaway</h3><p>Strip away the product branding and here’s what Day 1 of Build 2026 actually said:</p><p><strong>1. The OS is now part of your agent architecture.</strong> MXC and OpenClaw mean that Windows is no longer just the environment your agent runs in — it’s an active participant in governance and containment. Design accordingly.</p><p><strong>2. The context layer is the new competitive moat.</strong> Work IQ, Fabric IQ, Foundry IQ — Microsoft is building the plumbing to make enterprise context programmable. Your agents’ differentiator isn’t which model they call; it’s what they know about your organization. June 16 is when you find out if the Work IQ APIs deliver on that.</p><p><strong>3. Model diversity is now a first-class platform feature.</strong> Foundry is explicitly multi-model — MAI models, Anthropic models, Fireworks AI models, all under the same governance wrapper. The right response is to stop defaulting to a single provider and start matching models to workloads intentionally.</p><p><strong>4. The security story is finally coherent.</strong> MDASH, MXC, ASSERT, Agent Control Specification, Agent 365 — there’s now a connected answer to “how do you govern agents in production?” That wasn’t true twelve months ago. Enterprise deployments that stalled on security and governance justification have less cover for delay.</p><p><strong>5. Local execution is a serious architectural option.</strong> MXC sandboxing, OpenClaw, the Surface RTX Spark Dev Box — running governed AI workloads locally is no longer a developer toy. For the right workload profile, it’s now the economically and operationally correct answer.</p><p>Day 2 starts tomorrow. I’ll be watching the Foundry Agent Service deep-dives and the Work IQ API documentation closely — those are the two announcements where the gap between the keynote story and the implementation reality will show up fastest.</p><h3>Further Reading</h3><p>All announcements covered in this article are sourced directly from Microsoft’s official Build 2026 communications, NDA-free and publicly available:</p><ul><li><strong>Microsoft Build 2026 Live Blog</strong> — full Day 1 announcement stream: <a href="https://news.microsoft.com/build-2026-live-blog">news.microsoft.com/build-2026-live-blog</a></li><li><strong>Official Microsoft Blog: “Be Yourself at Work”</strong> — the keynote narrative and product framing: <a href="https://blogs.microsoft.com/blog/2026/06/02/microsoft-build-2026-be-yourself-at-work/">blogs.microsoft.com/blog/2026/06/02/microsoft-build-2026-be-yourself-at-work</a></li><li><strong>Microsoft Build 2026 Homepage</strong> — sessions, demos, and speaker schedule: <a href="https://news.microsoft.com/build-2026/">news.microsoft.com/build-2026</a></li></ul><p><em>Follow along on </em><a href="https://medium.com/@divyeshg94"><em>Medium</em></a><em> and the </em><a href="https://medium.com/microsoft-azure-in-practice"><em>Microsoft Azure in Practice</em></a><em> publication for ongoing coverage.</em></p><p><em>Thoughts on any of these announcements? Drop them in the comments — particularly interested in what others think about MXC’s real-world governance guarantees and whether the Work IQ APIs hold up against messy production M365 tenants.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beacdb0a2d81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microsoft-azure-in-practice/microsoft-build-2026-day-1-the-platform-has-shifted-heres-what-it-means-for-azure-developers-beacdb0a2d81">Microsoft Build 2026 Day 1: The Platform Has Shifted — Here’s What It Means for Azure Developers</a> was originally published in <a href="https://medium.com/microsoft-azure-in-practice">Microsoft Azure in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is MCP and Why Should Every Azure Developer Care?]]></title>
            <link>https://levelup.gitconnected.com/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d65e8eff76c</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Tue, 26 May 2026 15:15:55 GMT</pubDate>
            <atom:updated>2026-05-26T15:15:55.155Z</atom:updated>
            <content:encoded><![CDATA[<h4>Before we write a single line of code, let’s fix the mental model most developers get wrong.</h4><p>There’s a question I kept getting after my Azure AI Foundry articles:</p><p><em>“This agent looks great. But how does it actually talk to my existing systems? My databases, my internal APIs, my business logic?”</em></p><p>Every answer felt like a workaround. Use function calling. Write a custom connector. Wrap it in a REST endpoint. Maintain it separately. Hope it doesn’t break when you swap models.</p><p>That friction has a name now. And there’s a proper fix.</p><p>It’s called the <strong>Model Context Protocol</strong>, and if you’re building anything serious on Azure AI, you’ll be using it whether you plan to or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*prSJ6Y2VSr5or3E_" /><figcaption>Image from <a href="https://modelcontextprotocol.io/">https://modelcontextprotocol.io/</a></figcaption></figure><p>This is Part 1 of a complete series, just the mental model you need before the code makes sense.</p><h3>The Problem MCP Was Built to Solve</h3><p>Before MCP, connecting an AI agent to external tools meant one thing: custom integration work. Every time. For every combination of model and service.</p><p>Say you’re on Azure. Your GPT-4o agent needs to query Cosmos DB. You write a wrapper. A week later, your team wants to test Phi-4 against the same data layer — another wrapper. Mistral gets added to the mix — another one. Now multiply that by every business service you expose: your internal HR API, your order management system, your inventory database.</p><p>This is the <strong>N×M problem</strong>. N models, M tools — every new combination potentially needs new integration work. And the worst part? All that glue code lives outside any standard, which means it breaks silently every time Microsoft updates an SDK or you swap a model.</p><p>Function calling helped. It gave LLMs a structured way to invoke tools. But it didn’t solve the discovery problem, the schema consistency problem, or the fact that your tool definitions were tightly coupled to one model’s API format.</p><p>MCP’s answer is simple: <strong>stop solving this per model and per tool. Define a standard. Let everything speak the same language.</strong></p><h3>What MCP Actually Is</h3><p>The <strong>Model Context Protocol</strong> is an open, vendor-neutral standard that defines exactly how AI models connect to external tools, data sources, and services.</p><p>It was introduced by Anthropic in November 2024. Within months, OpenAI, Google DeepMind, and Microsoft all adopted it. As of 2026, it’s governed by the Linux Foundation and has over 500 public server implementations — GitHub, Slack, PostgreSQL, Notion, Salesforce, and counting.</p><p>At its core, MCP is a client-server protocol built on JSON-RPC 2.0. But the more useful framing for any working developer is this:</p><blockquote><em>MCP is to AI agents what REST is to web services — a shared contract that makes everything interoperable.</em></blockquote><p>Your AI agent doesn’t need to know how your database works. It just needs to know what tools are available. MCP takes care of the rest.</p><h3>The Three Roles: Host, Client, Server</h3><p>This is where most explanations get muddy, so let’s be precise.</p><p>MCP defines three distinct roles in every interaction:</p><h4>The Host</h4><p>The host is the application the user actually interacts with. It’s the “conversation controller.”</p><p>In practice, this is GitHub Copilot Chat in VS Code, Claude Desktop, a custom .NET application you’ve built on top of Azure OpenAI, or a Foundry agent. The host manages the AI model’s context window, decides when to call a tool, routes the user’s message to the model, and feeds results back into the conversation.</p><p><strong>In Azure terms,</strong> your Foundry agent or any .NET app you build around Azure OpenAI is the host.</p><h4>The Client</h4><p>The client lives inside the host. It’s the component responsible for maintaining the actual connection to one or more MCP servers, handling the protocol handshake, sending tool requests, and receiving results.</p><p>You don’t usually write the client from scratch. The SDK handles it. But knowing it exists matters because one host can have multiple clients simultaneously, each connected to a different server.</p><p><strong>In Azure terms,</strong> the MCP client is part of the ModelContextProtocol NuGet package you&#39;ll add to your .NET app.</p><h4>The Server</h4><p>The server is where your actual capabilities live. It exposes tools (functions the AI can call), resources (data the AI can read), and prompts (templated interaction patterns). It receives requests from the client, executes the logic, and returns structured results.</p><p>This is what you’ll be building throughout this series. An MCP server is just an HTTP endpoint with a specific contract — it can be an Azure Function, a Container App, or an ASP.NET Core app. The underlying compute doesn’t matter. The protocol does.</p><p><strong>In Azure terms, </strong>Azure Functions with the MCP extension, or an ASP.NET Core app deployed to Container Apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDaQNfQ0hzMATltOJ0FkXw.png" /><figcaption>Image from Author</figcaption></figure><p>One host. Multiple clients. Multiple servers. Everything discoverable. Everything standardized.</p><h3>MCP vs. Function Calling vs. REST APIs</h3><p>If you’ve been working with Azure OpenAI, you’ve used function calling. Here’s how to think about the difference.</p><p><strong>REST APIs</strong> are how your systems talk to each other. They’re great. MCP doesn’t replace them — your MCP server will probably call your internal REST APIs under the hood.</p><p><strong>Function calling</strong> is how a specific LLM model invokes a specific tool in a specific API format. It works, but it’s tightly coupled. Your tool definitions live in your prompt or API call. They’re not discoverable, not portable across models, and not standardized.</p><p><strong>MCP</strong> is the layer that sits above function calling. It wraps the underlying mechanism in a universal, discoverable protocol. The model still “calls a function” internally, but the discovery, the schema, the authentication, and the result routing all happen through a consistent interface regardless of which model you’re using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjZQgk63xXuehBd07mTHSA.png" /><figcaption>Image from Author</figcaption></figure><p>The honest summary: function calling is a mechanism, MCP is a standard. One you implement per-model, and the other you implement once.</p><p>One important nuance for Azure: while MCP is an open protocol, Azure deployments naturally lean on Entra ID for authentication and Foundry for agent orchestration. The protocol is portable; the auth wiring has Azure-specific dependencies.</p><h3>Why Microsoft Is Betting Big on MCP</h3><p>This isn’t a peripheral feature for Microsoft. It’s an infrastructure-level commitment.</p><p>GitHub Copilot Agent Mode runs on MCP. Copilot Studio integrates MCP servers. Azure Functions has a dedicated MCP extension with its own NuGet bindings. Microsoft Foundry Agent Service has MCP as a first-class tool registration format. The new Azure AI developer certifications launching in 2026 — AI-103 and AI-200 — explicitly cover agentic architectures where MCP is a core component.</p><p>When Microsoft lands on a protocol at this depth across this many products, the signal is clear: this is not experimental. This is the plumbing.</p><p>For Azure developers specifically, this means a few things worth internalizing:</p><p><strong>Your existing Azure Functions become AI-callable tools.</strong> You don’t rewrite anything. You add the MCP extension, define your tools, and suddenly your existing business logic is available to any AI agent that speaks MCP.</p><p><strong>Your Foundry agents get structured tool access.</strong> Instead of a brittle prompt-injected context, your agent discovers and invokes tools with proper schemas, proper auth, and proper error handling.</p><p><strong>Your integrations become more portable.</strong> Build an MCP server once. Use it with Copilot, Foundry, a custom .NET app, or any other MCP-compatible host. The work doesn’t sit locked in a vendor-specific corner.</p><h3>The Two Transports You Need to Know</h3><p>MCP supports two transport modes. You’ll encounter both:</p><p><strong>stdio</strong> — Local inter-process communication. Used for running MCP servers locally, in development, or inside desktop tools like Claude Desktop. Simple, fast, no networking involved. Not useful for cloud deployment.</p><p><strong>Streamable HTTP</strong> — This is what you’ll use in Azure. An HTTP-based transport (POST + Server-Sent Events) that supports remote, scalable MCP servers. This is how your Azure Functions and Container Apps serve as MCP endpoints. It replaced the older SSE-only transport in late 2025.</p><h3>What MCP Primitives Actually Are</h3><p>Your MCP server can expose three types of capabilities:</p><p><strong>Tools</strong> are functions that the AI model can invoke. They take inputs, do something (query a DB, call an API, run a calculation), and return structured outputs. This is what you’ll build most of. In .NET, a tool is just a method decorated with [McpServerTool].</p><p><strong>Resources</strong> are data that the AI can read — documents, database records, file contents. Read-only context the model can pull when it needs information rather than action.</p><p><strong>Prompts</strong> are reusable, parameterized interaction templates. Less common in enterprise scenarios, but useful for standardizing how agents approach certain tasks.</p><p>For this series, we’ll focus almost entirely on Tools. That’s where 90% of real-world MCP work happens.</p><h3>The Honest State of MCP in 2026</h3><p>Let me give you the unfiltered picture, because the hype deserves some grounding.</p><p><strong>What’s genuinely ready:</strong> Building local and remote MCP servers in .NET, C#, Python, and TypeScript. The C# SDK is mature. Azure Functions support is stable. Foundry integration works. GitHub Copilot agent mode uses it daily.</p><p><strong>What you should do today:</strong> Start building. The fundamentals, including tools, transports, and server registration, are stable. The authentication and scaling patterns we’ll cover in this series reflect what actually works in production on Azure, not what the spec theoretically allows.</p><p><strong><em>In Part 2,</em></strong> we write the first tool. Let’s build something.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d65e8eff76c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-is-mcp-and-why-should-every-azure-developer-care-3d65e8eff76c">What Is MCP and Why Should Every Azure Developer Care?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are DORA metrics, and why should your team care?]]></title>
            <link>https://levelup.gitconnected.com/what-are-dora-metrics-and-why-should-your-team-care-d0ede00ad522?source=rss-32e75d034c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0ede00ad522</guid>
            <category><![CDATA[dora-metrics]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <dc:creator><![CDATA[Divyesh Govaerdhanan]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 14:57:21 GMT</pubDate>
            <atom:updated>2026-04-27T14:57:21.787Z</atom:updated>
            <content:encoded><![CDATA[<h4>The 4 numbers that predict whether your engineering team is actually good at delivery</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*u-KSKMdCuuTAPsk5y9_1rw.png" /></figure><p>In 2014, a team of researchers at Google set out to answer a deceptively simple question.</p><p>What separates software teams that are genuinely good at their job from the ones that just think they are?</p><p>They interviewed thousands of engineering organizations over several years. They looked at deployment frequency, incident data, release cadence, and recovery times. They tried to find patterns that predicted not just speed, but stability. Not just shipping often, but shipping well.</p><p>What they found became one of the most cited frameworks in modern engineering: DORA metrics.</p><p>If you’ve been in software development for more than a few years, you’ve almost certainly heard the term. But there’s a gap between knowing what DORA metrics are and actually measuring them on your own team. This article is about closing that gap, specifically for engineers running pipelines in Azure DevOps.</p><h3>The four metrics that actually matter</h3><p>The DORA research identified four key metrics. Each one measures something distinct, and together they give you a surprisingly complete picture of delivery health.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-vlPOt1exsbdNvWT.jpg" /><figcaption>Image from Google DORA Metrics</figcaption></figure><h4>Deployment frequency</h4><p>How often does your team ship code to production?</p><p>This is the most visible metric and often the most misunderstood one. Teams frequently confuse build frequency with deployment frequency. Your CI pipeline running 20 times a day doesn’t mean you’re deploying to production 20 times a day.</p><p>Elite teams deploy multiple times per day. High performers deploy somewhere between once a day and once a week. Medium teams ship weekly to monthly. Low performers are stuck at monthly or less.</p><p>The insight from the research is that deployment frequency is both an output and an enabler. Teams that deploy more frequently have shorter feedback loops. They catch problems sooner, in smaller changesets, where they’re easier to fix.</p><h4>Lead time for changes</h4><p>How long does it take a commit to reach production?</p><p>This metric captures the speed of your entire delivery pipeline, from the moment a developer pushes code to the moment a user can see the effect in production. It includes code review time, CI run duration, test suite execution, any approval gates, and the actual deployment.</p><p>Elite teams get code from a commit to production in under one hour. High performers land in one day or less. Medium is one week to one month. Low performers can be stuck for months.</p><p>Lead time is where you see the real cost of manual approval steps, flaky tests that trigger reruns, and long-running test suites nobody has optimized in years.</p><h4>Change failure rate</h4><p>What percentage of your deployments cause a problem in production?</p><p>This is the stability metric. It includes deployments that triggered an incident, required a hotfix, or had to be rolled back. A low failure rate means your testing and validation are working. A high one means code is reaching production that shouldn’t.</p><p>Elite teams keep this below 5%. High performers stay between 5% and 10%. Anything above 15% puts you in the Low tier.</p><p>This metric has an uncomfortable property: teams with high deployment frequency but poor testing tend to discover it here first. You can ship fast and still ship badly.</p><h4>Mean time to restore</h4><p>When something breaks in production, how long before you’re back?</p><p>This measures operational resilience. Elite teams recover from incidents in under one hour. High performers are under one day. Medium teams need between one day and one week. Low performers are recovering over weeks.</p><p>MTTR is shaped by things that feel unrelated to engineering: how well your runbooks are written, how clearly on-call responsibilities are defined, how good your observability tooling is, and whether engineers can actually find and understand alerts when they fire at 2 am.</p><h3>Why these four, and not something else?</h3><p>The DORA research wasn’t prescriptive. The team didn’t decide in advance that these four metrics mattered. They emerged from the data.</p><p>What the research found is that these four metrics have a specific and unusual property: they balance each other. Deployment Frequency and Lead Time measure speed. Change Failure Rate and MTTR measure stability. Teams that optimize for only one side of the balance tend to look good on two metrics and terrible on the other two.</p><p>A team that ships constantly but never tests properly will have Elite deployment frequency and a catastrophic change failure rate. A team that runs exhaustive quality gates before every release might have a near-zero failure rate but a lead time measured in weeks.</p><p>The goal is to improve all four together. The research found that the best engineering organizations in the world consistently achieve Elite ratings across all four simultaneously. It’s not a tradeoff. The teams that ship fastest also tend to be the most stable.</p><h3>How to actually measure these in Azure DevOps</h3><p>Here’s where most teams get stuck.</p><p>The data exists in Azure DevOps. Every pipeline run, every PR, every deployment is logged. But extracting DORA metrics from that data requires you to make a series of decisions that aren’t obvious.</p><p><strong>For deployment frequency</strong>, you need to decide which pipelines count as production deployments. In most organizations, CI pipelines run on every commit to every branch. You only want to count the ones that actually push to production. That usually means filtering by pipeline name, branch, or stage.</p><p><strong>For lead time</strong>, you need to connect the timestamp of a commit to the timestamp of the production deployment that included it. This sounds straightforward, but in practice, it requires correlating PR merge times with pipeline trigger times with deployment completion times across multiple pipeline runs that may not have a clean 1-to-1 relationship.</p><p><strong>For change failure rate</strong>, you need a definition of “failure.” Azure DevOps tracks pipeline outcomes as succeeded, failed, or canceled. But a deployment that succeeded in the pipeline and then caused an incident in production won’t show up as a failure in your pipeline data. You need to either integrate with your incident management tool or use a proxy metric like rollback rate or hotfix deploy rate.</p><p><strong>For MTTR</strong>, the pipeline data alone is usually not enough. You need incident start times from your monitoring or alerting system and the deployment timestamp that restored service. If you’re not instrumenting that connection deliberately, you don’t have it.</p><p>This is why most teams that try to measure DORA metrics manually give up. Not because they don’t care, but because building the data pipelines to produce accurate numbers is a significant engineering project on its own.</p><h3>What happens when you can’t see the numbers</h3><p>The cost of not measuring is real, it’s just invisible.</p><p>Teams without DORA visibility tend to develop folklore instead. “We ship pretty fast.” “Our failure rate is pretty low.” “We recover quickly when things go wrong.” These beliefs feel accurate because nobody has challenged them with data.</p><p>Then something forces the measurement. A reorg, a performance review, a new engineering director who asks for evidence. And the numbers that come back are rarely what the team expected.</p><p>I’ve seen teams discover their deployment frequency was three times lower than they believed because they were counting builds, not production deployments. I’ve seen teams find out their lead time was measured in days when they assumed it was hours, because code was sitting in an approved-but-not-deployed state for 48 hours waiting for a scheduled release window.</p><p>The gap between perception and reality is one of the most consistent findings in the DORA research. Teams consistently overestimate their own performance until they measure it precisely.</p><h3>DORA benchmarks: where do the thresholds come from?</h3><p>The Elite, High, Medium, and Low tiers come directly from the State of DevOps research reports, updated annually. Here’s what they look like for each metric.</p><p>For Deployment Frequency: Elite is multiple times per day, High is between once per day and once per week, Medium is between once per week and once per month, Low is less than once per month.</p><p>For Lead Time: Elite is under one hour, High is under one day, Medium is between one day and one week, and Low is over one week.</p><p>For Change Failure Rate: Elite is 0 to 5%, High is 5 to 10%, Medium is 10 to 15%, and Low is over 15%.</p><p>For MTTR: Elite is under one hour, High is under one day, Medium is between one day and one week, and Low is over one week.</p><p>These thresholds matter because they give you context. A change failure rate of 12% sounds bad in isolation. Knowing it puts you in the Medium tier, not the Low tier, and that Elite is at 5%, gives you a calibrated sense of how far you are from where you want to be and whether the gap is closable in a single sprint or a single quarter.</p><h3>Getting started in Azure DevOps today</h3><p>If you want to start measuring DORA metrics without building the data pipeline yourself, Velo is a free Azure DevOps extension that does this automatically.</p><p><strong><em>Azure DevOps: </em></strong><a href="https://marketplace.visualstudio.com/items?itemName=IngeniousLabs.velo">https://marketplace.visualstudio.com/items?itemName=IngeniousLabs.velo</a></p><p>Once installed, it registers webhooks for pipeline completions and pull request events. Every build and PR flows into the DORA computation engine in real time. The dashboard shows your current scores across all four metrics, benchmarked against the Elite thresholds, with trend data across 30, 90, and 365-day windows.</p><p>The AI Agent tab, powered by Azure AI Foundry and GPT-4o, reads your actual pipeline data and generates specific recommendations. Not generic advice about trunk-based development. Specific observations about your deployment frequency pattern, your failure rate trend, and which actions are likely to have the highest impact given your current numbers.</p><p>It takes about 5 minutes to connect your Azure DevOps organization and run the first sync. The numbers appear immediately.</p><p>You can install Velo from the Azure DevOps Marketplace. It’s free. The source code is on GitHub.</p><p><strong><em>Source Code:</em></strong> <a href="https://github.com/divyeshg94/Ingenious.Velo">https://github.com/divyeshg94/Ingenious.Velo</a></p><p>If you want to understand how Velo was built, the architectural decisions behind it, and what the real data looked like when I first pointed it at my own pipelines, I wrote the full story here.</p><p><a href="https://medium.com/microsoft-azure-in-practice/i-built-a-tool-to-measure-my-own-team-the-results-were-uncomfortable-cdde80649818">https://medium.com/microsoft-azure-in-practice/i-built-a-tool-to-measure-my-own-team-the-results-were-uncomfortable-cdde80649818</a></p><p>The DORA research found something that often gets lost in the focus on the four metrics themselves.</p><p>The teams that performed best weren’t the ones that set aggressive deployment frequency targets and drove toward them. They were the ones who understood the system they worked in, measured it honestly, identified the constraint holding them back, and addressed it.</p><p>Sometimes the constraint is test coverage. Sometimes it’s a manual approval gate that made sense once and never got removed. Sometimes it’s a monolithic deployment process that needs to be broken up. Sometimes it’s a culture where failures get hidden rather than learned from.</p><p>DORA metrics don’t tell you what to fix. They tell you where to look. The fixing is still human work.</p><p>But you can’t fix what you can’t see. And right now, if you’re running pipelines in Azure DevOps without measuring these four numbers, you’re flying blind in the same way I was.</p><p><em>If this was useful to you, share it with one person on your team who has ever said, “I think our deployment frequency is pretty good.” Help them find out for sure. Read the full Velo build story </em><a href="https://medium.com/microsoft-azure-in-practice/i-built-a-tool-to-measure-my-own-team-the-results-were-uncomfortable-cdde80649818"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0ede00ad522" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-are-dora-metrics-and-why-should-your-team-care-d0ede00ad522">What are DORA metrics, and why should your team care?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>