---
title: "microsoft/azure-skills"
description: "Official agent plugin providing skills and MCP server configurations for Azure scenarios."
source: https://github.com/microsoft/azure-skills
ref: main
license: MIT
licenseName: "MIT License"
canonical: https://skillsdocs.com/microsoft/azure-skills
base: https://github.com/microsoft/azure-skills/blob/main/
chapters: 41
inlined: 41
withheld: 0
words: 28304
updated: 2026-08-11T11:15:25Z
generator: "Skills Docs"
---

> **microsoft/azure-skills** — every Agent Skill in this repository, inlined verbatim.
>
> Canonical HTML: https://skillsdocs.com/microsoft/azure-skills
> Per-chapter Markdown: https://skillsdocs.com/microsoft/azure-skills/<skill>.md
> Machine manifest: https://skillsdocs.com/microsoft/azure-skills/.well-known/agent-skills/index.json
> JSON: https://skillsdocs.com/api/v1/books/microsoft/azure-skills
> Install: `npx skills add microsoft/azure-skills`
> Upstream: https://github.com/microsoft/azure-skills @ `main`
> Licence: MIT
>
> Content is mirrored from GitHub and © its authors, served unmodified. Takedown: https://github.com/DreambaseAI/skillsdocs/issues/new?labels=takedown&title=Takedown+request

# microsoft/azure-skills

Official agent plugin providing skills and MCP server configurations for Azure scenarios.

- **Chapters:** 41
- **Inlined:** 41 (licence detected)
- **Words:** 28,304
- **Reading time:** 131 min
- **Stars:** 1,367

## Table of contents

1. [azure-kusto-graph](https://skillsdocs.com/microsoft/azure-skills/azure-kusto-graph.md) — Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), sh…
2. [azure-kusto-irql-graph](https://skillsdocs.com/microsoft/azure-skills/azure-kusto-irql-graph.md) — Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Grap…
3. [azure-kusto-irql](https://skillsdocs.com/microsoft/azure-skills/azure-kusto-irql.md) — Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable I…
4. [airunway-aks-setup](https://skillsdocs.com/microsoft/azure-skills/airunway-aks-setup.md) — Set up AI Runway on AKS — from bare cluster to running model. Covers cluster verification, controller install, GPU assessment, provider setup, and first deploy…
5. [appinsights-instrumentation](https://skillsdocs.com/microsoft/azure-skills/appinsights-instrumentation.md) — Guidance for instrumenting webapps with Azure Application Insights. Provides telemetry patterns, SDK setup, and configuration references. WHEN: how to instrume…
6. [azure-ai](https://skillsdocs.com/microsoft/azure-skills/azure-ai.md) — Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. W…
7. [azure-aigateway](https://skillsdocs.com/microsoft/azure-skills/azure-aigateway.md) — Configure Azure API Management as an AI Gateway for AI models, MCP tools, and agents. WHEN: semantic caching, token limit, content safety, load balancing, AI m…
8. [azure-app-onboard-prereq](https://skillsdocs.com/microsoft/azure-skills/azure-app-onboard-prereq.md) — Assess whether source code is ready to deploy to Azure — the check BEFORE infrastructure work. Evaluates build health, app completeness, dependencies and local…
9. [deploy](https://skillsdocs.com/microsoft/azure-skills/deploy.md) — No description.
10. [prepare](https://skillsdocs.com/microsoft/azure-skills/prepare.md) — No description.
11. [scaffold](https://skillsdocs.com/microsoft/azure-skills/scaffold.md) — No description.
12. [azure-app-onboard](https://skillsdocs.com/microsoft/azure-skills/azure-app-onboard.md) — End-to-end orchestrator: from a business idea, app idea, or existing app to running Azure deployment with cost estimates and pre-deploy approval. Analyzes your…
13. [azure-cloud-migrate](https://skillsdocs.com/microsoft/azure-skills/azure-cloud-migrate.md) — Assess and migrate cross-cloud workloads to Azure with reports and code conversion. Supports Lambda→Functions, Beanstalk/Heroku/App Engine→App Service, Fargate…
14. [azure-compliance](https://skillsdocs.com/microsoft/azure-skills/azure-compliance.md) — Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance valida…
15. [azure-compute](https://skillsdocs.com/microsoft/azure-skills/azure-compute.md) — Azure VM/VMSS router. WHEN: create / provision / deploy / spin-up VM, recommend VM size, compare VM pricing, VMSS, scale set, autoscale, burstable, lightweight…
16. [azure-cost](https://skillsdocs.com/microsoft/azure-skills/azure-cost.md) — Azure cost management: query costs, forecast spending, optimize to reduce waste. WHEN: "Azure costs", "Azure bill", "cost breakdown", "how much am I spending",…
17. [azure-deploy](https://skillsdocs.com/microsoft/azure-skills/azure-deploy.md) — Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when t…
18. [azure-diagnostics](https://skillsdocs.com/microsoft/azure-skills/azure-diagnostics.md) — Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service,…
19. [azure-enterprise-infra-planner](https://skillsdocs.com/microsoft/azure-skills/azure-enterprise-infra-planner.md) — Architect and provision enterprise Azure infrastructure from workload descriptions. For cloud architects and platform engineers planning networking, identity,…
20. [azure-kubernetes-app-deploy](https://skillsdocs.com/microsoft/azure-skills/azure-kubernetes-app-deploy.md) — Use when deploying an existing web application or API to an already-running Azure Kubernetes Service cluster. Detects the framework, generates a Dockerfile and…
21. [azure-kubernetes-automatic-readiness](https://skillsdocs.com/microsoft/azure-skills/azure-kubernetes-automatic-readiness.md) — Assess Kubernetes workloads and cluster configuration for AKS Automatic compatibility. Identifies incompatibilities, generates fixes, and guides migration from…
22. [azure-kubernetes](https://skillsdocs.com/microsoft/azure-skills/azure-kubernetes.md) — Plan, create, and configure production-ready Azure Kubernetes Service (AKS) clusters. Covers Day-0 checklist, SKU selection (Automatic vs Standard), networking…
23. [azure-kusto](https://skillsdocs.com/microsoft/azure-skills/azure-kusto.md) — Query and analyze data in Azure Data Explorer (Kusto/ADX) using KQL for log analytics, telemetry, and time series analysis. WHEN: KQL queries, Kusto database q…
24. [azure-messaging](https://skillsdocs.com/microsoft/azure-skills/azure-messaging.md) — Troubleshoot and resolve issues with Azure Messaging SDKs for Event Hubs and Service Bus. Covers connection failures, authentication errors, message processing…
25. [azure-prepare](https://skillsdocs.com/microsoft/azure-skills/azure-prepare.md) — Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) work…
26. [azure-quotas](https://skillsdocs.com/microsoft/azure-skills/azure-quotas.md) — Check/manage Azure quotas and usage across providers. For deployment planning, capacity validation, region selection. WHEN: "check quotas", "service limits", "…
27. [azure-reliability](https://skillsdocs.com/microsoft/azure-skills/azure-reliability.md) — Assess and improve the reliability posture of PaaS Applications (Azure Functions and Azure App Service). Scans deployed resources for zone redundancy, ZRS stor…
28. [azure-resource-lookup](https://skillsdocs.com/microsoft/azure-skills/azure-resource-lookup.md) — List, find, and show Azure resources across subscriptions or resource groups. Handles prompts like "list the websites in my subscription", "list my web apps",…
29. [azure-resource-visualizer](https://skillsdocs.com/microsoft/azure-skills/azure-resource-visualizer.md) — Analyze Azure resource groups and generate detailed Mermaid architecture diagrams showing the relationships between individual resources. WHEN: create architec…
30. [azure-storage](https://skillsdocs.com/microsoft/azure-skills/azure-storage.md) — Azure Storage Services including Blob Storage, File Shares, Queue Storage, Table Storage, and Data Lake. Answers questions about storage access tiers (hot, coo…
31. [azure-upgrade](https://skillsdocs.com/microsoft/azure-skills/azure-upgrade.md) — Assess and upgrade Azure workloads between plans, tiers, or SKUs, or modernize Azure SDK dependencies in source code. WHEN: upgrade Consumption to Flex Consump…
32. [azure-validate](https://skillsdocs.com/microsoft/azure-skills/azure-validate.md) — Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity p…
33. [entra-agent-id](https://skillsdocs.com/microsoft/azure-skills/entra-agent-id.md) — Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token…
34. [entra-app-registration](https://skillsdocs.com/microsoft/azure-skills/entra-app-registration.md) — Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure…
35. [finetuning](https://skillsdocs.com/microsoft/azure-skills/finetuning.md) — Fine-tune models on Microsoft Foundry using SFT (supervised), DPO (preference), or RFT (reinforcement with graders). Covers dataset preparation, training job s…
36. [capacity](https://skillsdocs.com/microsoft/azure-skills/capacity.md) — Discovers available Azure OpenAI model capacity across regions and projects. Analyzes quota limits, compares availability, and recommends optimal deployment lo…
37. [customize](https://skillsdocs.com/microsoft/azure-skills/customize.md) — Interactive guided deployment flow for Azure OpenAI models with full customization control. Step-by-step selection of model version, SKU (GlobalStandard/Standa…
38. [preset](https://skillsdocs.com/microsoft/azure-skills/preset.md) — Intelligently deploys Azure OpenAI models to optimal regions by analyzing capacity across all available regions. Automatically checks current region first and…
39. [deploy-model](https://skillsdocs.com/microsoft/azure-skills/deploy-model.md) — Unified Azure OpenAI model deployment skill with intelligent intent-based routing. Handles quick preset deployments, fully customized deployments (version/SKU/…
40. [microsoft-foundry](https://skillsdocs.com/microsoft/azure-skills/microsoft-foundry.md) — Deploy, evaluate, fine-tune, and manage Foundry agents end-to-end with azd: hosted agent scaffold/run/deploy, prompt agent create, batch eval, continuous eval,…
41. [python-appservice-deploy](https://skillsdocs.com/microsoft/azure-skills/python-appservice-deploy.md) — Deploy Python (Flask/Django/FastAPI) code to Azure App Service Linux. WHEN: "Flask App Service", "Django App Service", "FastAPI App Service", "deploy Python to…


## Front matter

_The repository README, verbatim except that relative links are resolved against https://github.com/microsoft/azure-skills/blob/main/._

# Azure Skills Plugin

Azure work is not just a code problem. It is a decision problem: which service fits this app, what needs to be validated before deployment, which tools should run, and what guardrails matter. The Azure Skills Plugin packages Azure expertise and MCP-backed execution together so compatible coding agents can do real Azure work instead of giving generic cloud advice.

**[Explore the Azure Skills site](https://microsoft.github.io/azure-skills/)**
**[Landing page maintenance guide](https://github.com/microsoft/azure-skills/blob/main/landing-page/README.md)**

**[Install the plugin](#install-in-60-seconds)**

## One install, three layers of capability

### Azure skills: the brain

This plugin ships **curated Azure skills** that teach an agent how Azure work gets done. They provide workflows, decision trees, and guardrails for scenarios such as:

- **Build, deploy, and evolve** with `azure-prepare`, `azure-validate`, `azure-deploy`, `azure-upgrade`, `azure-enterprise-infra-planner`, `azure-hosted-copilot-sdk`, `azure-kubernetes`, and `airunway-aks-setup`
- **Troubleshoot, monitor, and govern** with `azure-diagnostics`, `appinsights-instrumentation`, `azure-compliance`, `azure-resource-lookup`, and `azure-quotas`
- **Optimize architecture and cost** with `azure-cost`, `azure-compute`, `azure-resource-visualizer`, and `azure-cloud-migrate`
- **Work across data, AI, identity, and platform services** with `azure-ai`, `azure-aigateway`, `azure-storage`, `azure-kusto`, `azure-messaging`, `azure-rbac`, `entra-app-registration`, and `microsoft-foundry`

### Azure MCP Server: the hands

The plugin wires in the **Azure MCP Server**, which gives your agent **200+ structured tools across 40+ Azure services**. That is the execution layer for listing resources, checking prices, querying logs, diagnosing issues, and driving real Azure workflows.

### Foundry MCP: the AI specialist

The plugin also includes **Foundry MCP** for Microsoft Foundry scenarios such as model discovery, model deployment, and agent workflows.

## Why this plugin is different

This is not a prompt pack. It is a packaged Azure capability layer:

- **Skills** teach the agent when to use Azure workflows and what to avoid.
- **MCP tools** let the agent act on live Azure and Foundry resources.
- **The plugin** keeps the guidance layer and execution layer aligned in one install.
- **Multi-host support** lets you use the same Azure capability across environments such as GitHub Copilot in VS Code, Copilot CLI, Claude Code, and other compatible hosts.

## What you get

| Component | What it adds | Examples |
| --- | --- | --- |
| **Azure skills** | Azure expertise, workflows, and guardrails | Prepare, validate, deploy, diagnostics, cost, AI, RBAC |
| **Azure MCP Server** | Live Azure tooling | Resource inventory, monitoring, pricing, storage, databases, messaging |
| **Foundry MCP** | Microsoft Foundry workflows | Model catalog, deployments, agents, evaluations |

The plugin payload lives in `.github/plugins/azure-skills/`, and the included MCP configuration shows how Azure and Foundry connectivity are wired for compatible hosts.

## Install in 60 seconds

### Prerequisites

Before you install, make sure you have:

- An Azure account or subscription
- **Node.js 18+** available on your PATH (`npx` is used to start the MCP servers)
- **Azure CLI** installed and authenticated with `az login`
- **Azure Developer CLI** installed and authenticated with `azd auth login` if you plan to use deployment workflows

### APM (one install, multiple harnesses)

The Azure Skills Plugin is multi-harness. If you use [APM](https://github.com/microsoft/apm), one command installs it across GitHub Copilot, Claude Code, Cursor, OpenCode, Codex, and Gemini from a single `apm.yml`:

```bash
apm install microsoft/azure-skills
```

### GitHub Copilot CLI

**Add the marketplace** (first time only):

```
/plugin marketplace add microsoft/azure-skills
```

**Install the plugin**:

```
/plugin install azure@azure-skills
```

**Update the plugin**:

```
/plugin update azure@azure-skills
```

### VS Code

Install the **Azure MCP** extension from the Visual Studio Marketplace:

👉 [Azure MCP Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azure-mcp-server)

The Azure MCP extension will also install a companion extension that brings the Azure skills into VS Code. Together they configure the Azure MCP Server, Foundry MCP, and the full skills layer automatically.

> **Note:** The skills extension requires **Git CLI** to be installed on your machine. If you don't have it, ask Copilot to help you install Git for your OS.

### Claude Code

**Install the plugin** — either run:

```bash
/plugin install azure@claude-plugins-official
```

Or run `/plugin` and search for "azure" in the marketplace:

![Claude Code plugin discovery showing the Azure plugin](https://github.com/microsoft/azure-skills/blob/main/assets/azure-plugin-in-claude.png)

**Update the plugin**:

```bash
/plugin update azure@claude-plugins-official
```

### Gemini CLI

**Install the extension**:

```bash
gemini extensions install https://github.com/microsoft/azure-skills
```

### Cursor

You can install the Azure plugin from the [Cursor Marketplace](https://cursor.com/marketplace/azure) or directly from Cursor settings by navigating to **Settings** > **Plugins** and searching for "Azure":

![Cursor Plugins](https://github.com/microsoft/azure-skills/blob/main/assets/cursor-plugins.png)

### Codex CLI

**Add the marketplace** (first time only):

```bash
codex plugin marketplace add microsoft/azure-skills
```

**Install the plugin**:

Browse plugins using `/plugins` and install `azure`:

![Codex Plugins](https://github.com/microsoft/azure-skills/blob/main/assets/codex-plugins.png)

![Codex Install Plugin](https://github.com/microsoft/azure-skills/blob/main/assets/codex-install-plugin.png)

**Enable or disable skills**:

You can choose to enable or disable specific skills by running `/skills` in Codex and selecting the appropriate option:

![Codex Enable Disable Skills](https://github.com/microsoft/azure-skills/blob/main/assets/codex-enable-disable-skills.png)

> **Note:** A plugin installed from Codex CLI is also available in the Codex app.

### IntelliJ IDEA

#### Prerequisites

Before installing Azure skills in IntelliJ IDEA, ensure you have:
- **Node.js 18+** installed on your system with `npx` available on your PATH
- **Git** installed and accessible from the command line

You can verify these prerequisites by running:
```bash
npx --version
git --version
```

#### Step 1: Install GitHub Copilot Plugin

1. Open IntelliJ IDEA
2. Go to **File** > **Settings** (on Windows/Linux) or **IntelliJ IDEA** > **Preferences** (on macOS)
3. Navigate to **Plugins** in the left sidebar
4. Search for "GitHub Copilot" in the Marketplace tab
5. Install the [GitHub Copilot plugin](https://plugins.jetbrains.com/plugin/17718-github-copilot--your-ai-pair-programmer) (requires version 1.5.64-242 or higher)
6. Restart IntelliJ IDEA when prompted

#### Step 2: Enable Skills for GitHub Copilot

1. Open IntelliJ IDEA settings/preferences again
2. Navigate to **Tools** > **GitHub Copilot** > **Chat**
3. Check the **"Enable Skills"** checkbox
4. Click **Apply** and **OK**

![alt text](https://github.com/microsoft/azure-skills/blob/main/assets/intellij-enable-azure-skills.png)

#### Step 3: Install Azure Skills

**Option 1: Install Azure Toolkit For IntelliJ Plugin**

1. **Install the Azure Toolkit plugin** from the JetBrains Marketplace:
   👉 [Azure Toolkit for IntelliJ](https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij)
   
2. **Restart IntelliJ IDEA** to complete the plugin installation

3. **Install Azure Skills** when prompted:
   - After restarting, you'll see a notification offering to install Azure Skills
   - Click **Install** to add the Azure skills to your environment
   - See screenshot below for reference

   ![alt text](https://github.com/microsoft/azure-skills/blob/main/assets/intellij-install-skills-notification.png)

4. **Verify installation** by opening the GitHub Copilot chat window and typing:
   ```
   /skill:azure
   ```
   This will display all available Azure skills you can now use in your projects.

   ![alt text](https://github.com/microsoft/azure-skills/blob/main/assets/intellij-verify-azure-skills.png)


**Option 2:** Install Azure Skills manually

1. Open a terminal or command prompt
2. Run the following command to install Azure skills globally for GitHub Copilot:

   ```bash
   npx skills add https://github.com/microsoft/azure-skills/tree/main/.github/plugins/azure-skills/skills -a github-copilot -g -y
   ```

   **Command explanation:**
   - `npx skills add` - Uses the skills CLI to add a new skills package
   - The GitHub URL points to the Azure skills directory in this repository
   - `-a github-copilot` - Specifies the skills are for GitHub Copilot
   - `-g` - Installs the skills globally (available across all projects)
   - `-y` - Automatically accepts prompts during installation

3. Wait for the installation to complete. You should see confirmation that the Azure skills have been successfully added.

## Sovereign Cloud Configuration

By default, the Azure MCP server connects to the Azure Public Cloud. If you use a sovereign cloud (Azure China Cloud or Azure US Government), you need to configure the MCP server to use the appropriate cloud environment.

### Copilot CLI

After installing the plugin, Azure MCP server should be configured for copilot as well. You can list the configured MCP servers by running `/mcp show`

![MCP Servers](https://github.com/microsoft/azure-skills/blob/main/assets/mcp_servers.png)

Edit the Azure MCP server named `azure` from `plugin:azure` to add the `--cloud` argument. Execute `/mcp edit azure`. Navigate to the `Command` section to add the `--cloud` argument, use `AzureChinaCloud` to access Azure China Cloud, and use `AzureUSGovernment` to access Azure US Government Cloud.

![Edit MCP Server](https://github.com/microsoft/azure-skills/blob/main/assets/edit_mcp_server.png)

Before starting the MCP server, ensure your local CLI tools are authenticated against the correct cloud:

| Cloud | Azure CLI | Azure PowerShell | Azure Developer CLI |
|-------|-----------|-----------------|---------------------|
| China | `az cloud set --name AzureChinaCloud && az login` | `Connect-AzAccount -Environment AzureChinaCloud` | `azd config set cloud.name AzureChinaCloud && azd auth login` |
| US Government | `az cloud set --name AzureUSGovernment && az login` | `Connect-AzAccount -Environment AzureUSGovernment` | `azd config set cloud.name AzureUSGovernment && azd auth login` |

For more details, see [Connect to sovereign clouds](https://learn.microsoft.com/azure/developer/azure-mcp-server/how-to/connect-sovereign-clouds) in the Azure MCP Server documentation.

## Verify the installation

After install, try three quick checks.

### 1. Verify the skills layer

Ask:

> What Azure services would I need to deploy this project?

You should get structured Azure guidance, not just a generic cloud answer.

### 2. Verify Azure MCP

Ask:

> List my Azure resource groups.

You should see a real tool-backed response from your Azure account.

### 3. Verify Foundry MCP

Ask:

> What AI models are available in Microsoft Foundry?

You should get a Foundry-backed response rather than a generic summary.

## Authentication

The recommended authentication path is Azure CLI:

```bash
az login
```

If you plan to deploy with `azd`, also run:

```bash
azd auth login
```

You can also authenticate with service principal credentials:

**Bash/Zsh**

```bash
export AZURE_TENANT_ID="your-tenant-id"
export AZURE_CLIENT_ID="your-client-id"
export AZURE_CLIENT_SECRET="your-client-secret"
```

**PowerShell**

```powershell
$env:AZURE_TENANT_ID = "your-tenant-id"
$env:AZURE_CLIENT_ID = "your-client-id"
$env:AZURE_CLIENT_SECRET = "your-client-secret"
```

When the agent runs inside Azure, the Azure MCP Server can also use managed identity.

## Prompts to try

Once the plugin is installed, try prompts like these:

- `Prepare this app for Azure.`
- `Validate my Azure deployment files before I run azd up.`
- `Deploy this project to Azure Container Apps.`
- `List my Azure storage accounts.`
- `Find cost savings across my Azure subscription.`
- `Troubleshoot why my container app is failing health probes.`
- `What role should I assign to let this managed identity read blobs?`
- `What AI models are available in Microsoft Foundry?`

## Repository layout

If you are exploring or customizing the plugin source, the key pieces are:

- `.github/plugins/azure-skills/skills/` - the Azure skill definitions
- `.github/plugins/azure-skills/.mcp.json` - included MCP configuration for Azure and Foundry
- `landing-page/` - Astro GitHub Pages site source and maintenance guide
- `README.md` - high-level overview and install guide for the plugin

## Troubleshooting

### The agent is not using Azure skills

- Make sure the plugin installed successfully in your host
- Confirm the Azure skills directory is present
- Reload or restart your host so it re-indexes plugins and MCP configuration

### MCP tools are not showing up

- Verify Node.js is installed and `npx` works
- Check that the Azure and Foundry MCP entries were added for your host
- Restart MCP servers or reload the host after configuration changes

### Azure commands fail with auth errors

- Re-run `az login`
- Re-run `azd auth login` for deployment scenarios
- Make sure the correct Azure subscription is selected

## Learn more

- [Azure MCP Server documentation](https://learn.microsoft.com/azure/developer/azure-mcp-server/)
- [Azure documentation](https://learn.microsoft.com/azure)
- [Azure CLI reference](https://learn.microsoft.com/cli/azure/)

## Telemetry

To disable Azure MCP telemetry collection, set:

```bash
export AZURE_MCP_COLLECT_TELEMETRY=false
```

## Contribution

This repository is automatically sync'ed from https://github.com/microsoft/GitHub-Copilot-for-Azure. If you would like to contribute to Azure skills, please open PR's there. Thank you!

---

<!-- chapter:begin slug=azure-kusto-graph position=1 -->

## 1. azure-kusto-graph

- **Source:** https://github.com/microsoft/azure-skills/blob/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-graph/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-graph/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-kusto-graph.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (3), referenced from this skill's directory:
  - `references/EXAMPLES.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-graph/references/EXAMPLES.md
  - `references/KUSTO_EXPLORER_LAUNCH.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-graph/references/KUSTO_EXPLORER_LAUNCH.md
  - `references/SCENARIOS.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-graph/references/SCENARIOS.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-kusto-graph
description: "Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Kusto Graph Semantics

Build transient and persistent graphs from tabular data using KQL graph operators. This skill translates natural language into the edges-first graph construction pattern and graph query operators.

## Activation Triggers

Use this skill when the user:
- Wants to build a graph from tabular data (`make-graph`)
- Asks to find patterns, paths, or relationships in data
- Mentions `graph-match`, `graph-shortest-paths`, `graph-to-table`, `graph-mark-components`
- Wants to create a persistent graph model or snapshot
- Says "build a graph", "find the shortest path", "find connected components", "show relationships"
- Asks about transient vs persistent graphs

**Not a natural-language-to-KQL converter.** The input should generally be a working KQL query whose results the user wants converted to a graph, plus a natural-language description of the desired graph structure. Basic NL source requests are supported only when they map directly to a known table with obvious columns. For general NL-to-KQL conversion, use a dedicated query-generation skill (available separately).

**Complementary skills:**
- `azure-kusto-irql` -- composable security query primitives that produce the tabular inputs for graphs
- `azure-kusto-irql-graph` -- IRQL's `Lift_To_Graph` JSON mapping system for richly-typed, icon-decorated graphs in Kusto Explorer

## The Edges-First Approach

The fundamental pattern for building graphs in Kusto:

```
1. Define your EDGES       -> src --> dest, with relationship type/properties
2. Define your NODE LOOKUPS -> display names, types, properties for each node ID
3. Union edge types         -> if you have multiple relationship types
4. Union node lookups       -> if you have multiple node types
5. Call make-graph          -> edges | make-graph Source --> Target with nodes on nodeId
```

This is how to think in `make-graph`. Edges are the relationships you care about. Nodes are lookup tables that give those IDs a face -- display names, types, properties.

## Graph Operators Reference

### `make-graph` -- Build a graph from tables

```kql
Edges | make-graph SourceId --> TargetId with Nodes on NodeId
```

- `Edges`: tabular source where each row is an edge
- `SourceId --> TargetId`: columns containing source and target node IDs
- `with Nodes on NodeId`: optional node property table joined by ID
- Supports multiple node tables: `with Nodes1 on Id1, Nodes2 on Id2`
- Nodes appearing in edges but missing from the node table get empty properties

### `graph-match` -- Find patterns

```kql
G | graph-match (a)-[e]->(b) where <constraints> project <output>
```

Pattern notation:

| Element | Named | Anonymous |
|---|---|---|
| Node | `(n)` | `()` |
| Edge left->right | `-[e]->` | `-->` |
| Edge right->left | `<-[e]-` | `<--` |
| Any direction | `-[e]-` | `--` |
| Variable length | `-[e*1..5]->` | `-[*1..5]->` |

Multi-hop patterns: `(a)-[e1]->(b)-[e2]->(c)`
Star patterns: `(a)--(center)--(b), (c)--(center)--(d)`
Cycles control: `cycles = all | none | unique_edges` (default: `unique_edges`)

### `graph-shortest-paths` -- Find shortest paths

```kql
G | graph-shortest-paths (start)-[e*1..20]->(end)
      where start.name == "Alice" and end.name == "Server01"
      project Path = e, Length = array_length(e)
```

- Requires at least one variable-length edge
- `output = any` (default, one path per pair) or `output = all` (all equal-length shortest paths)
- Variable-length edge properties returned as dynamic arrays

### `graph-to-table` -- Export graph to tables

```kql
G | graph-to-table nodes                                     // export nodes
G | graph-to-table edges                                     // export edges
G | graph-to-table nodes as N, edges as E                    // export both
G | graph-to-table nodes with_node_id=Id                     // include node hash ID
G | graph-to-table edges with_source_id=Src with_target_id=Tgt  // include edge endpoint IDs
```

### `graph-mark-components` -- Find connected components

```kql
G | graph-mark-components with_component_id=ComponentId
  | graph-to-table nodes
  | summarize Members = make_list(name) by ComponentId
```

Assigns a `ComponentId` to each node. Nodes in the same connected component share the same ID.

### `graph()` function -- Query persistent graphs

```kql
graph("MyGraphModel")                              // latest snapshot
graph("MyGraphModel", "Snapshot_2025_01")           // specific snapshot
graph("MyGraphModel", true)                         // transient from model definition
```

## Transient Graphs

Created dynamically during query execution. No setup required. Ideal for ad-hoc analysis, exploration, and prototyping.

### Template: Basic two-entity graph

```kql
// 1. Define edges
let edges = <SourceTable>
    | summarize <aggregations> by SourceCol, TargetCol;
// 2. Define node lookups
let source_nodes = edges
    | distinct SourceCol
    | project nodeId = SourceCol, label = SourceCol, nodeType = "<SourceType>";
let target_nodes = edges
    | distinct TargetCol
    | project nodeId = TargetCol, label = TargetCol, nodeType = "<TargetType>";
let all_nodes = union source_nodes, target_nodes;
// 3. Build and query the graph
edges
| make-graph SourceCol --> TargetCol with all_nodes on nodeId
| graph-match (s)-[e]->(t)
    where <constraints>
    project Source = s.label, Target = t.label, <edge properties>
```

### Template: Multi-relationship graph

```kql
// Multiple edge types -> union them with a common schema
let auth_edges = AuthEvents
    | project Source = username, Target = hostname, edgeType = "authenticates", ts = timestamp;
let net_edges = NetworkEvents
    | project Source = src_ip, Target = url, edgeType = "connects", ts = timestamp;
let all_edges = union auth_edges, net_edges;
// Node lookups from all sources
let user_nodes = Employees | project nodeId = username, label = name, nodeType = "User";
let host_nodes = AuthEvents | distinct hostname | project nodeId = hostname, label = hostname, nodeType = "Host";
let all_nodes = union user_nodes, host_nodes;
all_edges
| make-graph Source --> Target with all_nodes on nodeId
```

## Persistent Graphs

For large-scale, reusable graphs. Stored in database metadata. Support snapshots for historical comparison.

> **Safety:** Creating or altering graph models and snapshots modifies the database. Always show the exact command and confirm with the user before executing `.create-or-alter graph_model` or `.make graph_snapshot`.

### Step 1: Create a graph model

```kql
.create-or-alter graph_model SecurityGraph
{
  "Schema": {
    "Nodes": {
      "User": {"name": "string", "role": "string"},
      "Host": {"hostname": "string"},
      "IP":   {"ip": "string"}
    },
    "Edges": {
      "AuthenticatesTo": {"timestamp": "datetime", "result": "string"},
      "ConnectsFrom":    {"timestamp": "datetime"}
    }
  },
  "Definition": {
    "Steps": [
      {
        "Kind": "AddNodes",
        "Query": "Employees | project name, role",
        "NodeIdColumn": "name",
        "Labels": ["User"]
      },
      {
        "Kind": "AddNodes",
        "Query": "AuthenticationEvents | distinct hostname | project hostname",
        "NodeIdColumn": "hostname",
        "Labels": ["Host"]
      },
      {
        "Kind": "AddEdges",
        "Query": "AuthenticationEvents | project username, hostname, timestamp, result",
        "SourceColumn": "username",
        "TargetColumn": "hostname",
        "Labels": ["AuthenticatesTo"]
      }
    ]
  }
}
```

### Step 2: Create a snapshot

```kql
.make graph_snapshot SecurityGraph Snapshot_2025_07
```

### Step 3: Query the snapshot

```kql
graph("SecurityGraph")
| graph-match (user)-[auth]->(host)
    where user.role == "Admin" and auth.result == "Failed Login"
    project User = user.name, Host = host.hostname, Time = auth.timestamp
```

### Management commands

> **Safety:** All control commands below modify or delete database objects. Never execute `.drop`, `.create-or-alter graph_model`, or `.make graph_snapshot` automatically. Always show the exact command, cluster, database, and affected object, then require explicit user confirmation before execution.

```kql
.show graph_models                        // list all models
.show graph_model SecurityGraph           // show model details
.show graph_snapshots SecurityGraph       // list snapshots
.drop graph_snapshot SecurityGraph Snapshot_2025_07  // delete a snapshot (CONFIRM FIRST)
.drop graph_model SecurityGraph           // delete model and all snapshots (CONFIRM FIRST)
```

## Transient vs Persistent: When to Use Which

| Factor | Transient (`make-graph`) | Persistent (`graph()`) |
|---|---|---|
| Setup | None -- inline in query | Create model + snapshot |
| Lifetime | Query execution only | Stored in database metadata |
| Data freshness | Always current | Snapshot at creation time |
| Scale | Limited by query memory | Enterprise-scale |
| Reuse | Rebuilt every query | Shared across users/queries |
| Best for | Ad-hoc hunts, prototyping | Production workflows, dashboards |

## Security & Threat Hunting Examples

### Authentication graph: who logged into what from where

```kql
let auth_edges = AuthenticationEvents
    | summarize
        logins = count(),
        fails = countif(result == "Failed Login")
      by src_ip, username, hostname;
let ip_nodes = auth_edges | distinct src_ip
    | project nodeId = src_ip, label = src_ip, nodeType = "IP";
let user_nodes = auth_edges | distinct username
    | project nodeId = username, label = username, nodeType = "User";
let host_nodes = auth_edges | distinct hostname
    | project nodeId = hostname, label = hostname, nodeType = "Host";
let all_nodes = union ip_nodes, user_nodes, host_nodes;
// IP -> User edges
let ip_user = auth_edges
    | project Source = src_ip, Target = username, logins, fails;
// User -> Host edges
let user_host = auth_edges
    | project Source = username, Target = hostname, logins, fails;
union ip_user, user_host
| make-graph Source --> Target with all_nodes on nodeId
| graph-match (ip)-[e1]->(user)-[e2]->(host)
    where e2.fails > 20
    project
        IP = ip.label,
        User = user.label,
        Host = host.label,
        Failures = e2.fails
| order by Failures desc
```

### Lateral movement detection: users sharing compromised hosts

```kql
// Pattern: (user1)-[auth1]->(host)<-[auth2]-(user2)
// Two users both failing on the same host = possible credential spray
let edges = AuthenticationEvents
    | summarize fails = countif(result == "Failed Login"), logins = count()
      by username, hostname;
let nodes = union
    (edges | distinct username | project nodeId = username, nodeType = "User"),
    (edges | distinct hostname | project nodeId = hostname, nodeType = "Host");
edges
| make-graph username --> hostname with nodes on nodeId
| graph-match (u1)-[e1]->(h)<-[e2]-(u2)
    where u1.nodeId != u2.nodeId and e1.fails > 10 and e2.fails > 10
    project
        User1 = u1.nodeId, User2 = u2.nodeId,
        SharedHost = h.nodeId,
        User1Fails = e1.fails, User2Fails = e2.fails
| distinct User1, SharedHost, User2, User1Fails, User2Fails
| order by User1Fails + User2Fails desc
```

### Shortest attack path

```kql
let edges = SecurityEvents
    | project Source = source_entity, Target = target_entity, action, timestamp;
let nodes = union
    (edges | distinct Source | project nodeId = Source),
    (edges | distinct Target | project nodeId = Target);
edges
| make-graph Source --> Target with nodes on nodeId
| graph-shortest-paths (start)-[e*1..10]->(end)
    where start.nodeId == "ExternalIP_1.2.3.4" and end.nodeId == "DatabaseServer"
    project
        PathLength = array_length(e),
        Actions = e.action,
        Hops = e.Target
```

### Connected components: find isolated clusters

```kql
let edges = NetworkFlows
    | project Source = src_ip, Target = dst_ip;
let nodes = union
    (edges | distinct Source | project nodeId = Source),
    (edges | distinct Target | project nodeId = Target);
edges
| make-graph Source --> Target with nodes on nodeId
| graph-mark-components with_component_id = ComponentId
| graph-to-table nodes
| summarize Members = make_list(nodeId), Size = count() by ComponentId
| order by Size desc
```

### Visualize in Kusto Explorer

End a query at `make-graph` (without piping to `graph-match`) to trigger Kusto Explorer's interactive graph visualization window:

```kql
edges
| make-graph Source --> Target with all_nodes on nodeId
// <- stop here. Kusto Explorer renders the graph visually.
```

To flatten back to a table for dashboards or export, pipe through `graph-match | project` or `graph-to-table`.

## Using with IRQL

When working with security data, consider using IRQL selectors (`Get_*`) from the `azure-kusto-irql` skill as the data source. IRQL gives you a unified schema without memorizing raw table names or column mappings. For rich visualization with icons and node folding, the `azure-kusto-irql-graph` skill's `Lift_To_Graph` is the faster path.

| Approach | Best For |
|---|---|
| Raw `make-graph` (this skill) | Full control, persistent models, shortest paths, connected components, custom schemas |
| `Lift_To_Graph` (`azure-kusto-irql-graph`) | Quick icon-decorated visualization in Kusto Explorer, node folding |
| IRQL `Get_*` -> `make-graph` | IRQL's unified schema as input, then raw graph operators for analysis |
| IRQL `Get_*` -> `Lift_To_Graph` -> `Graph_Render_View` | Fastest path from question to visual graph |

> **Note:** `Lift_To_Graph`, `Graph_Render_View`, and `Graph_Fold_By_Property` are stored functions, not built-in operators. They are pre-deployed on the kc7001 example cluster but may need deployment on other clusters. See `azure-kusto-irql-graph/references/DEPLOY_IRQL_FUNCTIONS.md` for function definitions and deployment instructions.

### Example: IRQL selectors -> make-graph -> shortest path

IRQL handles the data retrieval; `make-graph` handles the graph analysis. This finds the shortest path from an external IP to a mail server through auth events:

```kql
// IRQL provides unified columns (ClientIp, Hostname, Username, Result)
let auth = Get_Event_Authentication_All
    | where Result == "Failed Login";
let edges = auth
    | summarize Failures = count() by ClientIp, Hostname;
let nodes = union
    (edges | distinct ClientIp | project nodeId = ClientIp, nodeType = "IP"),
    (edges | distinct Hostname | project nodeId = Hostname, nodeType = "Host");
edges
| make-graph ClientIp --> Hostname with nodes on nodeId
| graph-shortest-paths (src)-[e*1..5]->(dest)
    where src.nodeType == "IP" and dest.nodeId == "MAIL-SERVER01"
    project
        SourceIP = src.nodeId,
        PathLength = array_length(e),
        Hops = e.Hostname
```

### Example: IRQL selectors -> make-graph -> connected components

Find clusters of IPs and domains that are interconnected -- potential C2 infrastructure:

```kql
let dns = Get_Dns_All;
let edges = dns | project Source = ClientIp, Target = Domain;
let nodes = union
    (edges | distinct Source | project nodeId = Source, nodeType = "IP"),
    (edges | distinct Target | project nodeId = Target, nodeType = "Domain");
edges
| make-graph Source --> Target with nodes on nodeId
| graph-mark-components with_component_id = ComponentId
| graph-to-table nodes
| summarize
    IPs = make_set_if(nodeId, nodeType == "IP"),
    Domains = make_set_if(nodeId, nodeType == "Domain"),
    Size = count()
  by ComponentId
| where Size > 3
| order by Size desc
```

### Example: IRQL + make-graph integration

See [references/EXAMPLES.md](references/EXAMPLES.md) for multi-source investigation graphs combining IRQL selectors with `make-graph`, and `Lift_To_Graph` visual graph examples.

## Practical Usage Scenarios

See [references/SCENARIOS.md](references/SCENARIOS.md) for full worked examples including:
- Reachability analysis (shortest paths to critical assets)
- Network segmentation validation (connected components)
- Blast radius of compromised accounts (variable-length path matching)
- Persistent graph models for SOC teams (graph_model + snapshots)

## MCP Tools Used

| Tool | Purpose |
|------|---------|
| `kusto_query` | Execute KQL queries including `make-graph`, `graph-match`, and management commands |
| `kusto_table_schema_get` | Discover table columns before building edge/node projections |
| `kusto_cluster_list` | List available ADX clusters |
| `kusto_database_list` | List databases in a cluster |

## Opening Queries in Kusto Explorer (Windows Only)

> **Optional convenience feature.** The default workflow is to output the KQL in chat and let the user copy it into Kusto Explorer or the VS Code Kusto extension manually. Auto-launch is opt-in only.

### Default: Output KQL in Chat

Always output the complete KQL with Step 1 (connect) and Step 2 (query) clearly labeled:

```
// Step 1: Connect to your cluster (skip if already connected)
// Example: uncomment to connect to the KC7 training cluster
// #connect cluster('kc7001.eastus.kusto.windows.net').database('ValdyTimes')
// Or replace with your own cluster:
// #connect cluster('<YOUR_CLUSTER>').database('<YOUR_DATABASE>')

// Step 2: Run the query below
<KQL_QUERY ending at make-graph>
```

Then immediately below, output an **ADX Web Explorer version** that appends `| graph-to-table nodes as N, edges as E` since ADX Web Explorer cannot render `make-graph` directly:

```
// ADX Web Explorer version (tabular output):
<SAME_QUERY>
| graph-to-table nodes as N, edges as E
```

This ensures the output works in both Kusto Explorer (graph visualization) and ADX Web Explorer (tabular results) without the user having to modify anything.

### Optional: Save and Launch

If the user asks to save or open the query in Kusto Explorer, follow the procedure in [references/KUSTO_EXPLORER_LAUNCH.md](references/KUSTO_EXPLORER_LAUNCH.md). Key rules:

- **Always** use `ask_user` to confirm before writing files or launching executables
- **Always** display the file contents in chat so the user can review before opening
- **Never** use shell interpolation or here-strings — write files via `Set-Content`/`Add-Content`
- **Never** encode queries into browser URLs
- On macOS/Linux, save the `.kql` file and suggest the VS Code Kusto extension or ADX Web Explorer

For `make-graph` visualization (the graph window), the query must **end at `make-graph`** — do not pipe to `graph-match`. Kusto Explorer only opens the graph visualization window when the output is a graph object, not a table.

<!-- chapter:end slug=azure-kusto-graph -->

---

<!-- chapter:begin slug=azure-kusto-irql-graph position=2 -->

## 2. azure-kusto-irql-graph

- **Source:** https://github.com/microsoft/azure-skills/blob/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql-graph/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql-graph/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-kusto-irql-graph.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (3), referenced from this skill's directory:
  - `references/DEPLOY_IRQL_FUNCTIONS.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql-graph/references/DEPLOY_IRQL_FUNCTIONS.md
  - `references/EXAMPLES.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql-graph/references/EXAMPLES.md
  - `references/KUSTO_EXPLORER_LAUNCH.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql-graph/references/KUSTO_EXPLORER_LAUNCH.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-kusto-irql-graph
description: "Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# IRQL Graph Functions -- Query Results to Visualization

Apply the IRQL graph function family to tabular results. Given a KQL or IRQL query and the user's graph description, generate a `Lift_To_Graph` mapping and compose only the stored graph functions needed to visualize, fold, extract, or enrich the graph in Kusto Explorer. The source query does not need to use IRQL.

## Scope and Routing

| Request | Use |
|---|---|
| Turn supplied KQL/IRQL rows into an icon-decorated visual graph | This skill: `Lift_To_Graph` + `Graph_Render_View` |
| Fold nodes or apply `Extract_Node_*`, `Enrich_Node_*`, or `Enrich_Graph_*` | This skill |
| Use `make-graph`, `graph-match`, shortest paths, connected components, graph models, or snapshots | `azure-kusto-graph` |
| Author a non-trivial KQL/IRQL investigation from natural language | A Kusto or IRQL query-generation skill, then this skill |

If a request mixes visualization and native graph analysis, use this skill for the lift/render portion and `azure-kusto-graph` for operator semantics. Do not replace graph-lift functions with a hand-built edges-first graph unless the user asks for native graph operators.

## Input Contract

- **Preferred input**: a working KQL/IRQL query that produces tabular results, plus a natural-language description of the desired nodes, edges, labels, icons, extracts, enrichments, or folds.
- This skill is **not a natural-language-to-KQL or NL-to-IRQL converter**. It transforms existing query results into graph visualizations. For general NL-to-KQL or NL-to-IRQL conversion, use a dedicated query-generation skill (available separately).
- Preserve the supplied query's retrieval, joins, filters, and aggregations. Add only projections or synthetic IDs required by the graph mapping.
- A basic natural-language source request is supported only when it maps directly to one known table or IRQL `Get_*` selector with obvious columns and simple filters. State the assumed source, and do not invent joins, schema, or investigation logic.
- For non-trivial query construction, use a separate Kusto/IRQL query-generation skill first, then apply this skill to its output.
- If no query or output schema is available and the source is not trivial, request the KQL query or its result columns before generating a mapping.

## Activation Triggers

Use this skill when the user:
- Supplies KQL/IRQL results and asks for an IRQL graph visualization or mapping
- Mentions `Lift_To_Graph`, `Graph_Render_View`, or `Graph_Fold_By_Property`
- Asks for icon-decorated node/edge mappings in Kusto Explorer
- Wants to fold/collapse nodes by a shared property
- Requests graph extraction or enrichment through `Extract_Node_*`, `Enrich_Node_*`, or `Enrich_Graph_*`

Do not activate this skill solely for `graph-match`, graph paths/components, persistent graphs, or generic `make-graph` construction; those belong to `azure-kusto-graph`.

**Not a natural-language-to-KQL/IRQL converter.** The input should generally be a working KQL or IRQL query whose results need graph visualization. Basic NL source requests work only for trivial single-table/selector cases. For general NL-to-KQL or NL-to-IRQL, use a dedicated query-generation skill (available separately).

## Environment

- **Cluster**: `https://kc7001.eastus.kusto.windows.net`
- **Databases**: `ValdyTimes`, `JoJosHospital` (graph functions pre-deployed)
- **Rendering**: Kusto Explorer desktop app (make-graph visualization window)
- **Tool**: `kusto_query` (via Azure MCP Server)

### Function Preflight

`Lift_To_Graph` and `Graph_Render_View` are stored functions, not built-in Kusto operators. Before generating or running a lift pipeline against a target database, check what is deployed:

```kql
.show functions
| where Name in~ ("Lift_To_Graph", "Graph_Render_View", "Graph_Fold_By_Property")
| project Name
```

- `Lift_To_Graph` and `Graph_Render_View` are required.
- `Graph_Fold_By_Property` is required only when folding is requested.
- Check any `Extract_Node_*`, `Enrich_Node_*`, or `Enrich_Graph_*` function before using it; omit optional enrichment when unavailable unless the user wants it deployed.
- If a required function is missing and you have permission to alter the database, **ask the user for confirmation before deploying**. Then use the `.create-or-alter function` definitions in [references/DEPLOY_IRQL_FUNCTIONS.md](references/DEPLOY_IRQL_FUNCTIONS.md). Run the relevant `.create-or-alter` block, then rerun the preflight check to confirm.
- If you do not have alter permissions, tell the user which functions are missing and point them to `references/DEPLOY_IRQL_FUNCTIONS.md` for manual deployment.

## IRQL Graph Function Family

### `Lift_To_Graph(T, mappingJson)`

Transforms any tabular KQL result into a unified node + edge table.

**Input**: Any table `T` + a JSON mapping string.
**Output**: Rows with `EntityType` = `"node"` or `"edge"`, ready for `make-graph`.

### `Graph_Render_View(T)`

Takes `Lift_To_Graph` output, splits nodes/edges, and calls `make-graph` to open Kusto Explorer's graph window.

### `Graph_Fold_By_Property(T, NodeType, PropertyName)`

Collapses nodes of a given type sharing a property value into a single node. Rewires edges automatically.

### Graph Extraction and Enrichment Functions

These are additional stored functions that must already be deployed on the target database. They are **not** bundled in `references/DEPLOY_IRQL_FUNCTIONS.md`. Use `.show functions` to verify availability before including in a pipeline.

| Function | Operation | Key Property |
|---|---|---|
| `Extract_Node_Email_Sender_Domain(T, displayName)` | Adds `Domain` to node props | `EmailSender` |
| `Extract_Node_Employee_Firstname(T, displayName)` | Adds `Firstname` to node props | `Name` |
| `Extract_Node_Event_Network_Domain(T, displayName)` | Adds `DomainName` to node props | `Url` |
| `Enrich_Node_Ip_Employee(T, displayName)` | Adds employee info to IP nodes | `ClientIp` |
| `Enrich_Node_Username_Employee(T, displayName)` | Adds employee info to user nodes | `Username` |
| `Enrich_Node_Event_Authentication_Username(T, displayName)` | Adds auth context | `Username` |
| `Enrich_Node_Ip_Domain(T, displayName)` | Adds DNS domains | `ClientIp` |
| `Enrich_Node_Ip_Event_NetworkOutbound(T, displayName)` | Adds outbound events | `ClientIp` |
| `Enrich_Graph_Ip_Employee(T, mappingJson)` | Expands graph with employee nodes | `ClientIp` |
| `Enrich_Graph_Username_Employee(T, mappingJson)` | Expands graph with employee nodes | `Username` |
| `Enrich_Graph_Event_Authentication_Username(T, mappingJson)` | Expands with auth nodes | `Username` |

## Mapping JSON Schema

The JSON mapping has two arrays: `node_types` and `edges`.

### `node_types[]`

| Field | Required | Description |
|---|---|---|
| `type` | Yes | Node type label (e.g. `"User"`, `"Host"`, `"IP"`) |
| `id` | Yes | Prefix for node ID; usually same as type |
| `key` | Yes | Column name whose value becomes the node's identity |
| `props` | Yes | Array of columns to carry as node properties |
| `defaults` | No | Object of fallback values for null/empty properties |
| `defIcon` | No | Default icon URL for this node type |
| `displayName` | No | Column to use for display label (defaults to `id`) |
| `color` | No | Column to source color from |
| `size` | No | Column to source size from |

### `edges[]`

| Field | Required | Description |
|---|---|---|
| `type` | Yes | Edge type label (e.g. `"AuthenticatesTo"`, `"SentEmail"`) |
| `source` | Yes | `{"id": "<prefix>", "type": "<NodeType>"}` |
| `target` | Yes | `{"id": "<prefix>", "type": "<NodeType>"}` |
| `props` | No | Array of columns to carry as edge properties |
| `displayName` | No | Column for edge label |
| `color` | No | Column for edge color |

### Icon Repository

Use icons from `https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/`:
- IP: `Public-IP-Addresses-(Classic).svg`
- Host/VM: `Virtual-Machine.svg`
- User: `Users.svg`
- Email: `Mailbox.svg` (or `azure-cds/command-1070-Mail.svg`)
- Process: `App-Services.svg`
- File: `Storage-Accounts.svg`
- Alert: `Activity-Log.svg`
- Domain: `DNS-Zones.svg`

## Mapping Generation Rules

Given the supplied query columns and the user's graph description, generate the mapping JSON by:

1. **Identify entities** -> each distinct noun becomes a `node_type`
2. **Identify relationships** -> each verb/preposition becomes an `edge`
3. **Map to columns** -> use actual columns produced by the supplied query; never assume unavailable columns
4. **Set direction** -> source is the actor, target is the acted-upon
5. **Add properties** -> include columns relevant to investigation (timestamps, results, hashes)
6. **Assign icons** -> pick from the icon set above based on entity type

### Column Reference (IRQL unified schema)

| Entity | Key Column | Available Props |
|---|---|---|
| User | `Username` | `Username`, `Name`, `Role`, `Email` |
| Host | `Hostname` | `Hostname` |
| IP | `ClientIp` | `ClientIp` |
| Email Message | `Subject` | `EnvTime`, `Subject`, `Verdict`, `Url` |
| Sender | `EmailSender` | `EmailSender`, `Domain` |
| Recipient | `EmailRecipient` | `EmailRecipient` |
| Process | `ProcessName` | `EnvTime`, `ProcessName`, `ProcessCommandLine`, `ProcessHash` |
| File | `Filename` | `EnvTime`, `Filename`, `Path`, `Sha256` |
| Domain | `DomainName` | `DomainName` |
| Auth Event | (synthetic ID) | `EnvTime`, `UserAgent`, `Result`, `Description` |

## Function Selection

1. Start with the supplied KQL/IRQL tabular pipeline.
2. Use `Lift_To_Graph(mapping)` to create graph entities.
3. Add `Extract_Node_*`, `Enrich_Node_*`, or `Enrich_Graph_*` only when requested and compatible with the mapped keys.
4. Add `Graph_Fold_By_Property()` only when grouping/collapse is requested.
5. End visual output with `Graph_Render_View()`.
6. Preflight the exact stored functions selected for the pipeline.

## Pipeline Pattern

```kql
// 1. Preserve the supplied KQL or IRQL query
<input query>
// 2. Lift to graph
| invoke Lift_To_Graph(<mapping_json>)
// 3. Optionally extract or enrich graph entities
| invoke <Extract_Node_* | Enrich_Node_* | Enrich_Graph_*>()
// 4. Optionally fold nodes when requested
| invoke Graph_Fold_By_Property("<NodeType>", "<PropertyName>")
// 5. Render
| invoke Graph_Render_View()
```

## Examples

For additional prompts and worked examples, see [references/EXAMPLES.md](references/EXAMPLES.md).

### Authentication graph: IP -> AuthEvent -> User -> Host

**Input query**: `Get_Event_Authentication_All | where Result == "Failed Login" | take 200`

**Graph request**: "Show IPs, authentication events, users, and hosts; fold events by result."

```kql
let auth_mapping = '{"node_types":[{"type":"SrcIp","id":"SrcIp","key":"ClientIp","props":["ClientIp"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Public-IP-Addresses-(Classic).svg"},{"type":"Host","id":"Host","key":"Hostname","props":["Hostname"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Virtual-Machine.svg"},{"type":"User","id":"User","key":"Username","props":["Username"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Users.svg"},{"type":"AuthEvent","id":"AuthEvent","key":"AuthEventId","props":["AuthEventId","EnvTime","UserAgent","Result","Description"],"defaults":{"Result":"unknown"},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Activity-Log.svg"}],"edges":[{"type":"RequestsAuth","source":{"id":"SrcIp","type":"SrcIp"},"target":{"id":"AuthEvent","type":"AuthEvent"},"props":["EnvTime"]},{"type":"TargetsUser","source":{"id":"AuthEvent","type":"AuthEvent"},"target":{"id":"User","type":"User"},"props":["EnvTime"]},{"type":"AgainstHost","source":{"id":"AuthEvent","type":"AuthEvent"},"target":{"id":"Host","type":"Host"},"props":["EnvTime"]}]}';
Get_Event_Authentication_All
| extend AuthEventId = strcat(Username, "_", Hostname, "_", EnvTime)
| where Result == "Failed Login"
| take 200
| invoke Lift_To_Graph(auth_mapping)
| invoke Graph_Fold_By_Property("AuthEvent", "Result")
| invoke Graph_Render_View()
```

### Email graph: Sender -> Message -> Recipient

**Input query**: `Get_Email_All | take 400`

**Graph request**: "Visualize sender-to-message-to-recipient flow and fold messages by verdict."

```kql
let mail_mapping = '{"node_types":[{"type":"EmailMessage","id":"Message","key":"Subject","props":["EnvTime","Subject","Verdict"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Media-File.svg"},{"type":"Sender","id":"Email","key":"EmailSender","props":["EmailSender"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-cds/command-1070-Mail.svg"},{"type":"Recipient","id":"Email","key":"EmailRecipient","props":["EmailRecipient"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-cds/command-1070-Mail.svg"}],"edges":[{"type":"SentBy","source":{"id":"Message","type":"EmailMessage"},"target":{"id":"Email","type":"Sender"},"props":["EnvTime","Verdict"]},{"type":"DeliveredTo","source":{"id":"Message","type":"EmailMessage"},"target":{"id":"Email","type":"Recipient"},"props":["EnvTime","Verdict"]}]}';
Get_Email_All
| take 400
| invoke Lift_To_Graph(mail_mapping)
| invoke Graph_Fold_By_Property("EmailMessage", "Verdict")
| invoke Graph_Render_View()
```

### Suspicious domain investigation (end-to-end)

**Basic source request**: "Use outbound network events for these suspicious domains and graph IP-to-domain connections enriched with employee names."

This is the limited fallback: one known selector, one extractor, and one direct filter.

```kql
let suspicious_domain_mapping = '{"node_types":[{"type":"IP","id":"IP","key":"ClientIp","props":["ClientIp"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Public-IP-Addresses-(Classic).svg"},{"type":"Domain","id":"Domain","key":"DomainName","props":["DomainName"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/DNS-Zones.svg"}],"edges":[{"type":"ConnectsTo","source":{"id":"IP","type":"IP"},"target":{"id":"Domain","type":"Domain"},"props":["EnvTime"]}]}';
Get_Event_NetworkOutbound
| invoke Extract_Event_Network_Domain()
| where DomainName has_any ("raisinkanes.com", "nothing-to-see-here.net", "totally-legit-domain.com")
| invoke Lift_To_Graph(suspicious_domain_mapping)
| invoke Enrich_Node_Ip_Employee("Name")
| invoke Graph_Fold_By_Property("Domain", "DomainName")
| invoke Graph_Render_View()
```

### Process execution graph: User -> Process -> ParentProcess

**Input query**: `Get_Event_Process_All | where ProcessCommandLine has "powershell" | take 300`

**Graph request**: "Visualize process, parent process, host, and user relationships."

```kql
let proc_mapping = '{"node_types":[{"type":"Process","id":"Proc","key":"ProcessName","props":["ProcessName","ProcessCommandLine","ProcessHash"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/App-Services.svg"},{"type":"ParentProcess","id":"Proc","key":"ParentProcessName","props":["ParentProcessName","ParentProcessHash"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/App-Services.svg"},{"type":"Host","id":"Host","key":"Hostname","props":["Hostname"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Virtual-Machine.svg"},{"type":"User","id":"User","key":"Username","props":["Username"],"defaults":{},"defIcon":"https://raw.githubusercontent.com/benc-uk/icon-collection/master/azure-icons/Users.svg"}],"edges":[{"type":"SpawnedBy","source":{"id":"Proc","type":"Process"},"target":{"id":"Proc","type":"ParentProcess"},"props":["EnvTime"]},{"type":"RanOn","source":{"id":"Proc","type":"Process"},"target":{"id":"Host","type":"Host"},"props":["EnvTime"]},{"type":"ExecutedBy","source":{"id":"Proc","type":"Process"},"target":{"id":"User","type":"User"},"props":["EnvTime"]}]}';
Get_Event_Process_All
| where ProcessCommandLine has "powershell"
| take 300
| invoke Lift_To_Graph(proc_mapping)
| invoke Graph_Render_View()
```

## Query Results -> Mapping Translation

When the user supplies a query and describes the graph:

1. Inspect the query's final output columns
2. Parse the entity nouns and relationship verbs
3. Generate the mapping JSON using only those columns
4. Preserve the supplied pipeline and append `Lift_To_Graph()`
5. Include `Graph_Render_View()` at the end
6. If the user mentions grouping/collapsing and the function exists, add `Graph_Fold_By_Property()`

Output the complete KQL -- the supplied query plus mapping JSON inline as a string `let` binding -- after the required-function preflight passes. Clearly mark unverified function dependencies when the target database cannot be checked.

## Opening Queries in Kusto Explorer (Windows Only)

> **Optional convenience feature.** The default workflow is to output the KQL in chat and let the user copy it into Kusto Explorer or the VS Code Kusto extension manually. Auto-launch is opt-in only.

Always output the complete KQL query in the chat response with Step 1 (connect) and Step 2 (query) clearly labeled:

```
// Step 1: Connect to your cluster (skip if already connected)
// Example: uncomment to connect to the KC7 training cluster
// #connect cluster('kc7001.eastus.kusto.windows.net').database('ValdyTimes')
// Or replace with your own cluster:
// #connect cluster('<YOUR_CLUSTER>').database('<YOUR_DATABASE>')

// Step 2: Run the query below
<KQL_QUERY>
```

If the user asks to save or open in Kusto Explorer, follow the procedure in [references/KUSTO_EXPLORER_LAUNCH.md](references/KUSTO_EXPLORER_LAUNCH.md). Key rules:

- Use `ask_user` to confirm before writing files or launching executables
- Display file contents in chat so the user can review before opening
- Never use shell interpolation or here-strings — write files via `Set-Content`/`Add-Content`
- Never encode queries into browser URLs
- On macOS/Linux, save the `.kql` file and suggest the VS Code Kusto extension or ADX Web Explorer

<!-- chapter:end slug=azure-kusto-irql-graph -->

---

<!-- chapter:begin slug=azure-kusto-irql position=3 -->

## 3. azure-kusto-irql

- **Source:** https://github.com/microsoft/azure-skills/blob/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-kusto-irql.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (2), referenced from this skill's directory:
  - `references/EXAMPLES.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql/references/EXAMPLES.md
  - `references/KUSTO_EXPLORER_LAUNCH.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/.github/plugins/azure-kusto-graph-skills/skills/azure-kusto-irql/references/KUSTO_EXPLORER_LAUNCH.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-kusto-irql
description: "Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# IRQL -- Incident Response Query Language

Compose IRQL function pipelines from selector, extractor, and enricher building blocks. IRQL wraps raw KQL security tables behind intent-revealing, composable functions so analysts (and LLMs) can express hunts without memorizing schemas, cluster locations, or join keys.

## Activation Triggers

Use this skill when the user:
- Explicitly mentions IRQL, `Get_*`, `Extract_*`, or `Enrich_*` functions
- Says "use IRQL" or "write an IRQL query"
- Requests a composable hunting pipeline using known IRQL selectors

Do **not** activate for generic security queries (e.g. "find failed logins") unless the user explicitly asks for IRQL. Route those to `azure-kusto` instead.

**Not a natural-language-to-IRQL converter.** This skill composes IRQL function pipelines and may handle basic natural-language requests that map directly to known selectors and simple filters. For general NL-to-KQL or NL-to-IRQL conversion, use a dedicated query-generation skill (available separately).

## IRQL Function Preflight

Before generating a pipeline, verify IRQL is available on the target database:

```kql
.show functions
| where Name startswith "Get_" or Name startswith "Extract_" or Name startswith "Enrich_"
| project Name
```

If no IRQL functions are found, inform the user that IRQL is not deployed on the target database and suggest using `azure-kusto` for raw KQL queries instead. IRQL functions are a prerequisite -- this skill does not deploy base IRQL selectors.

## What IRQL Is

IRQL is a **function-based dialect on top of KQL**. It provides:

1. **Unified schema** -- disparate security tables project into consistent column names regardless of the underlying data source
2. **Composability** -- small functions chain via `| invoke` to build complex hunts from simple steps
3. **Portability** -- the same IRQL pipeline works across different clusters/databases; only the `Get_*` primitives need re-pointing

IRQL is not a separate language. It's KQL functions you invoke. Any valid KQL works alongside IRQL functions.

## Deploying IRQL

IRQL functions are stored KQL functions (`.create-or-alter function`). They must already be deployed to the target database before this skill can generate pipelines.

**Public example cluster** (functions pre-deployed):
- Cluster: `https://kc7001.eastus.kusto.windows.net`
- Databases: `ValdyTimes`, `JoJosHospital`

To port IRQL to a new cluster/database, create `Get_*` selectors that project your source tables into the unified schema (column names below), then deploy extractors and enrichers. The extractors and enrichers work unchanged as long as the input schema matches.

## Function Catalog

### 1. Selectors -- `Get_*`

Return projected, schema-unified views of source tables. Use the minimal form by default; use `_All` when extra columns are needed.

| Function | Columns |
|---|---|
| `Get_Event_Authentication` | `EnvTime`, `Hostname`, `ClientIp`, `Username`, `Result` |
| `Get_Event_Authentication_All` | + `Description`, `UserAgent`, `PasswordHash` |
| `Get_Email` | `EnvTime`, `EmailSender`, `EmailRecipient`, `Subject`, `Url` |
| `Get_Email_All` | + `ReplyTo`, `Verdict` |
| `Get_Employees` | `Name`, `ClientIp`, `Email`, `Username`, `Hostname`, `Role` |
| `Get_Employees_All` | + `HireDate`, `UserAgent`, `Domain` |
| `Get_Event_FileCreation` | `EnvTime`, `Hostname`, `Filename`, `Path` |
| `Get_Event_FileCreation_All` | + `Username`, `Sha256`, `ProcessName` |
| `Get_Event_NetworkInbound` | `EnvTime`, `ClientIp`, `Url` |
| `Get_Event_NetworkInbound_All` | + `Method`, `UserAgent`, `StatusCode` |
| `Get_Event_NetworkOutbound` | `EnvTime`, `ClientIp`, `Url` |
| `Get_Event_NetworkOutbound_All` | + `Method`, `UserAgent` |
| `Get_Dns_All` | `EnvTime`, `Domain`, `ClientIp` |
| `Get_Event_Process` | `EnvTime`, `ProcessCommandLine`, `ProcessName`, `Hostname`, `Username` |
| `Get_Event_Process_All` | + `ParentProcessName`, `ParentProcessHash`, `ProcessHash` |
| `Get_SecurityAlerts_All` | `EnvTime`, `AlertType`, `Severity`, `Description`, `Indicators` |
| `Get_Network_Connection_All` | `EnvTime`, `SourceIp`, `SourcePort`, `DestinationIp`, `DestinationPort`, `Protocol`, `Bytes` |

### 2. Extractors -- `Extract_*`

Derive a new column from an existing one. Invoke after a selector.

| Function | Input Column | Adds |
|---|---|---|
| `Extract_Email_Sender_Domain(T)` | `EmailSender` | `Domain` |
| `Extract_Employee_Firstname(T)` | `Name` | `Firstname` |
| `Extract_Event_Network_Domain(T)` | `Url` | `DomainName` |

### 3. Enrichers -- `Enrich_*`

Left-join helpers that attach context from a related table.

| Function | Key Column | Enriches With |
|---|---|---|
| `Enrich_Event_Authentication_Username(T)` | `Username` | Auth events for user |
| `Enrich_Ip_Employee(T)` | `ClientIp` | Employee identity from IP |
| `Enrich_Username_Employee(T)` | `Username` | Employee identity from username |
| `Enrich_Ip_Domain(T)` | `ClientIp` | DNS domains resolved to IP |
| `Enrich_Ip_Event_NetworkOutbound(T)` | `ClientIp` | Outbound network from IP |
| `Enrich_Ip_Network_Connection(T)` | `ClientIp` | Network flows from IP |

### 4. External Enrichment

| Function | Source | Requirement |
|---|---|---|
| `Enrich_Sha256_VirusTotal(T)` | VirusTotal file report | API key + callout policy |
| `Get_CISA_KEV()` / `Enrich_CISA_KEV(T)` | CISA KEV catalog | Callout policy |

## Composition Rules

```
Selector -> Extract -> Filter -> Enrich -> Summarize/Project
```

1. **Start with a Selector**: `Get_Event_Authentication`, `Get_Email`, etc.
2. **Extract** derived fields: `| invoke Extract_Email_Sender_Domain()`
3. **Filter** to the signal: `| where Result == "Failed Login"`
4. **Enrich** with context: `| invoke Enrich_Username_Employee()`
5. **Summarize / project** the answer

Always pipe (`|`) between steps. Extractors and Enrichers use `| invoke FunctionName()`.

## Query Generation Guidelines

- Use the **minimal selector** unless extra columns are needed -> then `_All`
- Chain extractors before enrichers (extractors add columns enrichers may key on)
- Place `where` filters as early as possible
- Use `summarize` for aggregations, `project` for final column selection
- End with `order by` + `take` to limit output

## Examples

For additional prompts and worked examples, see [references/EXAMPLES.md](references/EXAMPLES.md).

### Brute-force detection
```kql
Get_Event_Authentication
| where Result == "Failed Login"
| summarize FailedCount = count() by Username
| where FailedCount > 19
| invoke Enrich_Username_Employee()
| project Username, Name, Role, Email, FailedCount
| order by FailedCount desc
```

### Phishing triage by recipient seniority
```kql
Get_Email
| invoke Extract_Email_Sender_Domain()
| project EnvTime, EmailSender, Domain, Username = EmailRecipient, Subject, Url
| invoke Enrich_Username_Employee()
| extend Seniority = case(
    Role has_any ("CEO", "Chief", "Director", "VP", "President"), 3,
    Role has_any ("Manager", "Lead", "Senior"), 2,
    1)
| summarize
    TotalEmails = count(),
    SeniorityScore = sum(Seniority),
    Recipients = make_set(Name, 50),
    DistinctRecipients = dcount(Username)
  by Domain
| where DistinctRecipients >= 2
| order by SeniorityScore desc
| take 20
```

### Post-exploitation pivot from an indicator
```kql
let victims =
    Get_Event_FileCreation_All
    | where Filename has "<INDICATOR>"
    | distinct Hostname;
Get_Event_Process
| where Hostname in (victims)
| where ProcessCommandLine has_any ("rundll32", "regsvr32", "powershell", "systeminfo")
| project EnvTime, Hostname, Username, ProcessName, ProcessCommandLine
| order by EnvTime asc
```

### Suspicious outbound traffic enriched with identity
```kql
Get_Event_NetworkOutbound
| invoke Extract_Event_Network_Domain()
| where DomainName has_any ("<SUSPICIOUS_DOMAIN_1>", "<SUSPICIOUS_DOMAIN_2>")
| invoke Enrich_Ip_Employee()
| project EnvTime, Name, Role, DomainName, Url, ClientIp
| order by EnvTime desc
```

### External IP authentication anomaly
```kql
Get_Event_Authentication_All
| where not(ClientIp startswith "10.") and not(ClientIp startswith "192.168.")
| summarize
    Attempts = count(),
    Failures = countif(Result == "Failed Login"),
    Users = make_set(Username)
  by ClientIp
| order by Failures desc
| take 20
```

## MCP Tools Used

| Tool | Purpose |
|------|---------|
| `kusto_query` | Execute IRQL pipelines against a Kusto database |
| `kusto_table_schema_get` | Discover available tables and columns |
| `kusto_cluster_list` | List available ADX clusters |
| `kusto_database_list` | List databases in a cluster |

## Opening Queries in Kusto Explorer (Windows Only)

> **Optional convenience feature.** The default workflow is to output the KQL in chat and let the user copy it into Kusto Explorer or the VS Code Kusto extension manually. Auto-launch is opt-in only.

Always output the complete KQL query in the chat response with Step 1 (connect) and Step 2 (query) clearly labeled:

```
// Step 1: Connect to your cluster (skip if already connected)
// Example: uncomment to connect to the KC7 training cluster
// #connect cluster('kc7001.eastus.kusto.windows.net').database('ValdyTimes')
// Or replace with your own cluster:
// #connect cluster('<YOUR_CLUSTER>').database('<YOUR_DATABASE>')

// Step 2: Run the query below
<KQL_QUERY>
```

If the user asks to save or open in Kusto Explorer, follow the procedure in [references/KUSTO_EXPLORER_LAUNCH.md](references/KUSTO_EXPLORER_LAUNCH.md). Key rules:

- Use `ask_user` to confirm before writing files or launching executables
- Display file contents in chat so the user can review before opening
- Never use shell interpolation or here-strings — write files via `Set-Content`/`Add-Content`
- Never encode queries into browser URLs
- On macOS/Linux, save the `.kql` file and suggest the VS Code Kusto extension or ADX Web Explorer
- For graph visualization from IRQL data, see `azure-kusto-graph` and `azure-kusto-irql-graph`

<!-- chapter:end slug=azure-kusto-irql -->

---

<!-- chapter:begin slug=airunway-aks-setup position=4 -->

## 4. airunway-aks-setup

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/airunway-aks-setup/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/airunway-aks-setup.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (10), referenced from this skill's directory:
  - `references/gpu-profiles.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/gpu-profiles.md
  - `references/model-sizing.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/model-sizing.md
  - `references/powershell-notes.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/powershell-notes.md
  - `references/steps/step-1-verify.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/steps/step-1-verify.md
  - `references/steps/step-2-controller.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/steps/step-2-controller.md
  - `references/steps/step-3-gpu.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/steps/step-3-gpu.md
  - `references/steps/step-4-provider.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/steps/step-4-provider.md
  - `references/steps/step-5-deploy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/steps/step-5-deploy.md
  - `references/steps/step-6-summary.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/steps/step-6-summary.md
  - `references/troubleshooting.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/airunway-aks-setup/references/troubleshooting.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: airunway-aks-setup
description: "Set up AI Runway on AKS — from bare cluster to running model. Covers cluster verification, controller install, GPU assessment, provider setup, and first deployment. WHEN: \"setup AI Runway\", \"onboard AKS cluster\", \"install AI Runway\", \"airunway setup\", \"deploy model to AKS\", \"GPU inference on AKS\", \"KAITO setup on AKS\", \"run LLM on AKS\", \"vLLM on AKS\", \"set up model serving on AKS\", \"AI Runway controller\"."
license: MIT
metadata:
  author: Microsoft
  version: "1.1.1"
argument-hint: "[skip-to-step N]"
---

# AI Runway AKS Setup

This skill walks users from a bare Kubernetes cluster to a running AI model deployment. Follow each step in sequence unless the user provides `skip-to-step N` to resume from a specific phase.

> **Cost awareness:** GPU node pools incur significant compute charges (A100-80GB can cost $3–5+/hr). Confirm the user understands cost implications before provisioning GPU resources.

## Prerequisites

This skill assumes an AKS cluster already exists. If the user does not have a cluster, hand off to the `azure-kubernetes` skill first to provision one (with a GPU node pool unless CPU-only inference is acceptable), then return here.

## Quick Reference

| Property | Value |
|----------|-------|
| Best for | End-to-end AI Runway onboarding on AKS |
| CLI tools | `kubectl`, `make`, `curl` |
| MCP tools | None |
| Related skills | `azure-kubernetes` (cluster setup), `azure-diagnostics` (troubleshooting) |

## When to Use This Skill

Use this skill when the user wants to:
- Set up AI Runway on an existing AKS cluster from scratch
- Install the AI Runway controller and CRDs
- Assess GPU hardware compatibility for model deployment
- Choose and install an inference provider (KAITO, Dynamo, KubeRay)
- Deploy their first AI model to AKS via AI Runway
- Resume a partially-complete AI Runway setup from a specific step

## MCP Tools

This skill uses no MCP tools. All cluster operations are performed directly via `kubectl` and `make`.

## Rules

1. Execute steps in sequence — load the reference for each step as you reach it
2. Report cluster state at each step: ✓ healthy, ✗ missing/failed
3. Ask for user confirmation before any install or deployment action
4. If a step is already complete, report status and skip to the next step
5. If the user provides `skip-to-step N`, start at step N; assume prior steps are complete

## Steps

| # | Step | Reference |
|---|------|-----------|
| 1 | **Cluster Verification** — context check, node inventory, GPU detection | [step-1-verify.md](references/steps/step-1-verify.md) |
| 2 | **Controller Installation** — CRD + controller deployment | [step-2-controller.md](references/steps/step-2-controller.md) |
| 3 | **GPU Assessment** — detect GPU models, flag dtype/attention constraints | [step-3-gpu.md](references/steps/step-3-gpu.md) |
| 4 | **Provider Setup** — recommend and install inference provider | [step-4-provider.md](references/steps/step-4-provider.md) |
| 5 | **First Deployment** — pick a model, deploy, verify Ready | [step-5-deploy.md](references/steps/step-5-deploy.md) |
| 6 | **Summary** — recap, smoke test, next steps | [step-6-summary.md](references/steps/step-6-summary.md) |

## Error Handling

| Error / Symptom | Likely Cause | Remediation |
|-----------------|--------------|-------------|
| No kubeconfig context | Not connected to a cluster | Run `az aks get-credentials` or equivalent |
| Controller in CrashLoopBackOff | Config or RBAC issue | `kubectl logs -n airunway-system -l control-plane=controller-manager --previous` |
| Provider not ready | Image pull or RBAC issue | `kubectl logs <pod-name> -n <namespace>` for the provider pod |
| ModelDeployment stuck in Pending | GPU scheduling failure or provider not ready | `kubectl describe modeldeployment <name> -n <namespace>` events |
| `bfloat16` errors at inference | T4 or V100 lacks bfloat16 support | Add `--dtype float16` to serving args |

For full error handling and rollback procedures, see [troubleshooting.md](references/troubleshooting.md).

<!-- chapter:end slug=airunway-aks-setup -->

---

<!-- chapter:begin slug=appinsights-instrumentation position=5 -->

## 5. appinsights-instrumentation

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/appinsights-instrumentation/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/appinsights-instrumentation.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (12), referenced from this skill's directory:
  - `examples/appinsights.bicep` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/examples/appinsights.bicep
  - `LICENSE.txt` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/LICENSE.txt
  - `references/aspnetcore.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/aspnetcore.md
  - `references/auto.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/auto.md
  - `references/container-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/container-apps.md
  - `references/nodejs.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/nodejs.md
  - `references/python.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/python.md
  - `references/sdk/azure-monitor-opentelemetry-exporter-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/sdk/azure-monitor-opentelemetry-exporter-java.md
  - `references/sdk/azure-monitor-opentelemetry-exporter-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/sdk/azure-monitor-opentelemetry-exporter-py.md
  - `references/sdk/azure-monitor-opentelemetry-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/sdk/azure-monitor-opentelemetry-py.md
  - `references/sdk/azure-monitor-opentelemetry-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/references/sdk/azure-monitor-opentelemetry-ts.md
  - `scripts/appinsights.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/appinsights-instrumentation/scripts/appinsights.ps1

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: appinsights-instrumentation
description: "Guidance for instrumenting webapps with Azure Application Insights. Provides telemetry patterns, SDK setup, and configuration references. WHEN: how to instrument app, App Insights SDK, telemetry patterns, what is App Insights, Application Insights guidance, instrumentation examples, APM best practices."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# AppInsights Instrumentation Guide

This skill provides **guidance and reference material** for instrumenting webapps with Azure Application Insights.

> **⛔ ADDING COMPONENTS?**
>
> If the user wants to **add App Insights to their app**, invoke **azure-prepare** instead.
> This skill provides reference material—azure-prepare orchestrates the actual changes.

## When to Use This Skill

- User asks **how** to instrument (guidance, patterns, examples)
- User needs SDK setup instructions
- azure-prepare invokes this skill during research phase
- User wants to understand App Insights concepts

## When to Use azure-prepare Instead

- User says "add telemetry to my app"
- User says "add App Insights" 
- User wants to modify their project
- Any request to change/add components

## Prerequisites

The app in the workspace must be one of these kinds

- An ASP.NET Core app hosted in Azure
- A Node.js app hosted in Azure

## Guidelines

### Collect context information

Find out the (programming language, application framework, hosting) tuple of the application the user is trying to add telemetry support in. This determines how the application can be instrumented. Read the source code to make an educated guess. Confirm with the user on anything you don't know. You must always ask the user where the application is hosted (e.g. on a personal computer, in an Azure App Service as code, in an Azure App Service as container, in an Azure Container App, etc.). 

### Prefer auto-instrument if possible

If the app is a C# ASP.NET Core app hosted in Azure App Service, use [AUTO guide](references/auto.md) to help user auto-instrument the app.

### Manually instrument

Manually instrument the app by creating the AppInsights resource and update the app's code. 

#### Create AppInsights resource

Use one of the following options that fits the environment.

- Add AppInsights to existing Bicep template. See [examples/appinsights.bicep](examples/appinsights.bicep) for what to add. This is the best option if there are existing Bicep template files in the workspace.
- Use Azure CLI. See [scripts/appinsights.ps1](scripts/appinsights.ps1) for what Azure CLI command to execute to create the App Insights resource.

No matter which option you choose, recommend the user to create the App Insights resource in a meaningful resource group that makes managing resources easier. A good candidate will be the same resource group that contains the resources for the hosted app in Azure.

#### Modify application code

- If the app is an ASP.NET Core app, see [ASPNETCORE guide](references/aspnetcore.md) for how to modify the C# code.
- If the app is a Node.js app, see [NODEJS guide](references/nodejs.md) for how to modify the JavaScript/TypeScript code.
- If the app is a Python app, see [PYTHON guide](references/python.md) for how to modify the Python code.

## SDK Quick References

- **OpenTelemetry Distro**: [Python](references/sdk/azure-monitor-opentelemetry-py.md) | [TypeScript](references/sdk/azure-monitor-opentelemetry-ts.md)
- **OpenTelemetry Exporter**: [Python](references/sdk/azure-monitor-opentelemetry-exporter-py.md) | [Java](references/sdk/azure-monitor-opentelemetry-exporter-java.md)

## Platform-Specific Guides

- **Container Apps**: [Observability Guide](references/container-apps.md)

<!-- chapter:end slug=appinsights-instrumentation -->

---

<!-- chapter:begin slug=azure-ai position=6 -->

## 6. azure-ai

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-ai/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-ai.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (15), referenced from this skill's directory:
  - `references/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/auth-best-practices.md
  - `references/sdk/azure-ai-contentsafety-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-contentsafety-java.md
  - `references/sdk/azure-ai-contentsafety-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-contentsafety-py.md
  - `references/sdk/azure-ai-contentsafety-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-contentsafety-ts.md
  - `references/sdk/azure-ai-document-intelligence-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-document-intelligence-dotnet.md
  - `references/sdk/azure-ai-document-intelligence-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-document-intelligence-ts.md
  - `references/sdk/azure-ai-openai-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-openai-dotnet.md
  - `references/sdk/azure-ai-transcription-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-transcription-py.md
  - `references/sdk/azure-ai-translation-text-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-translation-text-py.md
  - `references/sdk/azure-ai-translation-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-translation-ts.md
  - `references/sdk/azure-ai-vision-imageanalysis-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-vision-imageanalysis-java.md
  - `references/sdk/azure-ai-vision-imageanalysis-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-ai-vision-imageanalysis-py.md
  - `references/sdk/azure-search-documents-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-search-documents-dotnet.md
  - `references/sdk/azure-search-documents-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-search-documents-py.md
  - `references/sdk/azure-search-documents-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-ai/references/sdk/azure-search-documents-ts.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-ai
description: "Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure AI Services

## Services

| Service | Use When | MCP Tools | CLI |
|---------|----------|-----------|-----|
| AI Search | Full-text, vector, hybrid search | `azure__search` | `az search` |
| Speech | Speech-to-text, text-to-speech | `azure__speech` | - |
| OpenAI | GPT models, embeddings, DALL-E | - | `az cognitiveservices` |
| Document Intelligence | Form extraction, OCR | - | - |

## MCP Server (Preferred)

When Azure MCP is enabled:

### AI Search
- `azure__search` with command `search_index_list` - List search indexes
- `azure__search` with command `search_index_get` - Get index details
- `azure__search` with command `search_query` - Query search index

### Speech
- `azure__speech` with command `speech_transcribe` - Speech to text
- `azure__speech` with command `speech_synthesize` - Text to speech

**If Azure MCP is not enabled:** Run `/azure:setup` or enable via `/mcp`.

## AI Search Capabilities

| Feature | Description |
|---------|-------------|
| Full-text search | Linguistic analysis, stemming |
| Vector search | Semantic similarity with embeddings |
| Hybrid search | Combined keyword + vector |
| AI enrichment | Entity extraction, OCR, sentiment |

## Speech Capabilities

| Feature | Description |
|---------|-------------|
| Speech-to-text | Real-time and batch transcription |
| Text-to-speech | Neural voices, SSML support |
| Speaker diarization | Identify who spoke when |
| Custom models | Domain-specific vocabulary |

## SDK Quick References

For programmatic access to these services, see the condensed SDK guides:

- **AI Search**: [Python](references/sdk/azure-search-documents-py.md) | [TypeScript](references/sdk/azure-search-documents-ts.md) | [.NET](references/sdk/azure-search-documents-dotnet.md)
- **OpenAI**: [.NET](references/sdk/azure-ai-openai-dotnet.md)
- **Vision**: [Python](references/sdk/azure-ai-vision-imageanalysis-py.md) | [Java](references/sdk/azure-ai-vision-imageanalysis-java.md)
- **Transcription**: [Python](references/sdk/azure-ai-transcription-py.md)
- **Translation**: [Python](references/sdk/azure-ai-translation-text-py.md) | [TypeScript](references/sdk/azure-ai-translation-ts.md)
- **Document Intelligence**: [.NET](references/sdk/azure-ai-document-intelligence-dotnet.md) | [TypeScript](references/sdk/azure-ai-document-intelligence-ts.md)
- **Content Safety**: [Python](references/sdk/azure-ai-contentsafety-py.md) | [TypeScript](references/sdk/azure-ai-contentsafety-ts.md) | [Java](references/sdk/azure-ai-contentsafety-java.md)

## Service Details

For deep documentation on specific services:

- AI Search indexing and queries -> [Azure AI Search documentation](https://learn.microsoft.com/azure/search/search-what-is-azure-search)
- Speech transcription patterns -> [Azure AI Speech documentation](https://learn.microsoft.com/azure/ai-services/speech-service/overview)

<!-- chapter:end slug=azure-ai -->

---

<!-- chapter:begin slug=azure-aigateway position=7 -->

## 7. azure-aigateway

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-aigateway/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-aigateway.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (8), referenced from this skill's directory:
  - `references/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/auth-best-practices.md
  - `references/patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/patterns.md
  - `references/policies.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/policies.md
  - `references/sdk/azure-ai-contentsafety-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/sdk/azure-ai-contentsafety-py.md
  - `references/sdk/azure-ai-contentsafety-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/sdk/azure-ai-contentsafety-ts.md
  - `references/sdk/azure-mgmt-apimanagement-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/sdk/azure-mgmt-apimanagement-dotnet.md
  - `references/sdk/azure-mgmt-apimanagement-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/sdk/azure-mgmt-apimanagement-py.md
  - `references/troubleshooting.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-aigateway/references/troubleshooting.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-aigateway
description: "Configure Azure API Management as an AI Gateway for AI models, MCP tools, and agents. WHEN: semantic caching, token limit, content safety, load balancing, AI model governance, MCP rate limiting, jailbreak detection, add Azure OpenAI backend, add AI Foundry model, test AI gateway, LLM policies, configure AI backend, token metrics, AI cost control, convert API to MCP, import OpenAPI to gateway."
license: MIT
metadata:
  author: Microsoft
  version: "3.2.1"
compatibility: Requires Azure CLI (az) for configuration and testing
---

# Azure AI Gateway

Configure Azure API Management (APIM) as an AI Gateway for governing AI models, MCP tools, and agents.

> **To deploy APIM**, use the **azure-prepare** skill. See [APIM deployment guide](https://learn.microsoft.com/azure/api-management/get-started-create-service-instance).

## When to Use This Skill

| Category | Triggers |
|----------|----------|
| **Model Governance** | "semantic caching", "token limits", "load balance AI", "track token usage" |
| **Tool Governance** | "rate limit MCP", "protect my tools", "configure my tool", "convert API to MCP" |
| **Agent Governance** | "content safety", "jailbreak detection", "filter harmful content" |
| **Configuration** | "add Azure OpenAI backend", "configure my model", "add AI Foundry model" |
| **Testing** | "test AI gateway", "call OpenAI through gateway" |

---

## Quick Reference

| Policy | Purpose | Details |
|--------|---------|---------|
| `azure-openai-token-limit` | Cost control | [Model Policies](references/policies.md#token-rate-limiting) |
| `azure-openai-semantic-cache-lookup/store` | 60-80% cost savings | [Model Policies](references/policies.md#semantic-caching) |
| `azure-openai-emit-token-metric` | Observability | [Model Policies](references/policies.md#token-metrics) |
| `llm-content-safety` | Safety & compliance | [Agent Policies](references/policies.md#content-safety) |
| `rate-limit-by-key` | MCP/tool protection | [Tool Policies](references/policies.md#request-rate-limiting) |

---

## Get Gateway Details

```bash
# Get gateway URL
az apim show --name <apim-name> --resource-group <rg> --query "gatewayUrl" -o tsv

# List backends (AI models)
az apim backend list --service-name <apim-name> --resource-group <rg> \
  --query "[].{id:name, url:url}" -o table

# Get subscription key
az apim subscription keys list \
  --service-name <apim-name> --resource-group <rg> --subscription-id <sub-id>
```

---

## Test AI Endpoint

```bash
GATEWAY_URL=$(az apim show --name <apim-name> --resource-group <rg> --query "gatewayUrl" -o tsv)

curl -X POST "${GATEWAY_URL}/openai/deployments/<deployment>/chat/completions?api-version=2024-02-01" \
  -H "Content-Type: application/json" \
  -H "Ocp-Apim-Subscription-Key: <key>" \
  -d '{"messages": [{"role": "user", "content": "Hello"}], "max_tokens": 100}'
```

---

## Common Tasks

### Add AI Backend

See [references/patterns.md](references/patterns.md#pattern-1-add-ai-model-backend) for full steps.

```bash
# Discover AI resources
az cognitiveservices account list --query "[?kind=='OpenAI']" -o table

# Create backend
az apim backend create --service-name <apim> --resource-group <rg> \
  --backend-id openai-backend --protocol http --url "https://<aoai>.openai.azure.com/openai"

# Grant access (managed identity)
az role assignment create --assignee <apim-principal-id> \
  --role "Cognitive Services User" --scope <aoai-resource-id>
```

### Apply AI Governance Policy

Recommended policy order in `<inbound>`:

1. **Authentication** - Managed identity to backend
2. **Semantic Cache Lookup** - Check cache before calling AI
3. **Token Limits** - Cost control
4. **Content Safety** - Filter harmful content
5. **Backend Selection** - Load balancing
6. **Metrics** - Token usage tracking

See [references/policies.md](references/policies.md#combining-policies) for complete example.

---

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Token limit 429 | Increase `tokens-per-minute` or add load balancing |
| No cache hits | Lower `score-threshold` to 0.7 |
| Content false positives | Increase category thresholds (5-6) |
| Backend auth 401 | Grant APIM "Cognitive Services User" role |

See [references/troubleshooting.md](references/troubleshooting.md) for details.

---

## References

- [**Detailed Policies**](references/policies.md) - Full policy examples
- [**Configuration Patterns**](references/patterns.md) - Step-by-step patterns
- [**Troubleshooting**](references/troubleshooting.md) - Common issues
- [AI-Gateway Samples](https://github.com/Azure-Samples/AI-Gateway)
- [GenAI Gateway Docs](https://learn.microsoft.com/azure/api-management/genai-gateway-capabilities)

## SDK Quick References

- **Content Safety**: [Python](references/sdk/azure-ai-contentsafety-py.md) | [TypeScript](references/sdk/azure-ai-contentsafety-ts.md)
- **API Management**: [Python](references/sdk/azure-mgmt-apimanagement-py.md) | [.NET](references/sdk/azure-mgmt-apimanagement-dotnet.md)

<!-- chapter:end slug=azure-aigateway -->

---

<!-- chapter:begin slug=azure-app-onboard-prereq position=8 -->

## 8. azure-app-onboard-prereq

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-app-onboard-prereq/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-app-onboard-prereq.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (15), referenced from this skill's directory:
  - `references/build-check.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/build-check.md
  - `references/cloud-sdk-migration.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/cloud-sdk-migration.md
  - `references/completeness-check.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/completeness-check.md
  - `references/component-mapping.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/component-mapping.md
  - `references/dependency-compatibility.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/dependency-compatibility.md
  - `references/deployability-check.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/deployability-check.md
  - `references/prereq-artifacts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/prereq-artifacts.md
  - `references/prereq-schemas.ts` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/prereq-schemas.ts
  - `references/readiness-gate.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/readiness-gate.md
  - `references/remediation-protocol.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/remediation-protocol.md
  - `references/session-protocol.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/session-protocol.md
  - `references/session-schemas.ts` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/session-schemas.ts
  - `references/subagent-starter-scaffold.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/subagent-starter-scaffold.md
  - `references/subscription-resolution.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/subscription-resolution.md
  - `references/zero-code-path.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard-prereq/references/zero-code-path.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-app-onboard-prereq
description: "Assess whether source code is ready to deploy to Azure — the check BEFORE infrastructure work. Evaluates build health, app completeness, dependencies and local services, stack compatibility, and deployment feasibility. Answers questions about what your app needs before it can be deployed — frameworks, dependencies, and configuration. Checks whether dependencies are compatible and identifies deployment blockers and unsupported frameworks. WHEN: \"evaluate my repo\", \"is my app ready to deploy\", \"what does my app need to deploy\", \"what do I need before deploying\", \"does my app need\", \"can I ship this to Azure\", \"scan my repo for issues\", \"is this app deployable\", \"check if my app is ready for Azure\", \"do I need a Dockerfile\", \"what's blocking my deployment\", \"are there any blockers\", \"are my dependencies compatible\", \"does Azure support my framework\", \"what needs to change before deploying\", \"check my app configuration\"."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure App Onboard Prereq — Repository Evaluation

Evaluate a user's repository for build health, app completeness, and Azure deployment feasibility — before infrastructure planning. Produces per-component verdicts (PASS/WARN/FAIL) consumed by downstream phases.

> **Orchestrator relationship:** Called by `azure-app-onboard` at Step 3, or standalone for code readiness checks. When called by orchestrator, return control to `azure-app-onboard` after writing artifacts — do NOT invoke downstream phases directly.

Phase 1 of 4 in AppOnboard pipeline. Session: `.copilot-azure/sessions/{session-id}/`. Reads `context.json`. Writes `components[]`, `repo{}`, `detectedInfra[]`. Produces `prereq-output.json`. Schema: [`prereq-schemas.ts`](references/prereq-schemas.ts) — `PrereqOutput`, `BuildRequirements`. Direct entry supported.

## When NOT to Use

| Signal | Redirect |
|--------|----------|
| Validate infrastructure (Bicep/TF/azure.yaml) | **azure-validate** |
| Generate IaC | **azure-prepare** |
| End-to-end idea-to-production | **azure-app-onboard** |
| Run `azd up` or deploy | **azure-deploy** |

## Rules

> ⛔ **ABSOLUTE PROHIBITION — `npm install`, `npm test`, `npx jest`, `pytest`, and ALL install/build/test commands are NEVER allowed.**
> Under NO circumstances may you run `npm install`, `npm test`, `npx jest`, `pip install`, `pytest`, `dotnet build`, `dotnet restore`, `dotnet test`, `go mod download`, `cargo build`, or ANY package-manager install, build, or test command during the prereq phase. Do NOT run test suites to verify code — check for test config files statically instead. The prereq phase is read-only evaluation + static-only verification.
> **ONLY exception — two sanctioned contexts, both consent-gated:** (a) code the agent **modified** during migration/remediation (see [remediation-protocol.md](references/remediation-protocol.md) step 6), or (b) code the agent **wrote** from scratch on the zero-code path (see [zero-code-path.md](references/zero-code-path.md)). In either case, install/build/test runs ONLY via the user-confirmed build-validation gate ([build-check.md](references/build-check.md) Step 3), after the user answers that specific per-command consent prompt. General prior consent never counts.

1. ⛔ **Full pipeline (Steps 1–8), no exceptions.** All prompts → Step 1 directly. Answer specific questions AS PART OF findings (Step 5), not before.
2. ⛔ **No sub-agents for evaluation.** 3-axis evaluation is inline. **Exception**: zero-code-path scaffolding (Step 2).
3. Code/destructive modifications require `ask_user`. Max 3 questions before results. Direct entry: don't repeat orchestrator's intent questions.

## MCP Tools

| Tool | Purpose |
|------|---------|
| `mcp_azure_mcp_get_azure_bestpractices` | Validate detected stack patterns against Azure best practices |
| `mcp_azure_mcp_extension_cli_install` | Check/install required CLI tools (az, azd, func) |

## Workflow

### Step 1: Session Check

**Orchestrator entry:** Session exists — read `context.json`, proceed to Step 2.

**Direct entry:** Check `.copilot-azure/sessions/active-session.json`:
- **Exists** → ⛔ read [session-protocol.md](references/session-protocol.md) for resume/fresh gate. Do NOT proceed until user answers.
- **Missing** → create session: generate UUID, `New-Item -ItemType Directory -Path ".copilot-azure/sessions/{uuid}" -Force`, write `context.json` + `active-session.json` via `create` tool.

Then: `az account show` → merge `{id, name, tenantId}` into `context.json.azure`. ⛔ Session MUST exist on disk before any scanning.

### Step 2: Scan Workspace

Scan for project files. Detect components, `repo{}`, `detectedInfra[]`, `detectedServices[]`. Classify Terraform providers. Check CLI availability. Stack detection conflicts: user explicit statement wins (write to `context.json`, mark scan as override); scan-only → confirm with user; multiple stacks → show all and ask (see [component-mapping.md](references/component-mapping.md)); no code → [zero-code-path.md](references/zero-code-path.md).

> If no project files, no Dockerfile, AND no index.html → ⛔ read [zero-code-path.md](references/zero-code-path.md).

> ⛔ **Cloud SDK early gate.** Grep for `aws-sdk|@aws-sdk|boto3|google-cloud|@google-cloud|firebase`. If functional deps found → read [cloud-sdk-migration.md](references/cloud-sdk-migration.md), then `ask_user`: **"Redirect to Azure Cloud Migrate"** (set `routeToSkill: "azure-cloud-migrate"`) · **"Continue evaluation anyway"** (finish readiness eval + SDK→Azure mapping, then STOP at Step 8 — no plan until the deps are swapped) · **"Cancel"**.

### Step 3: Per-Component Evaluation

| Sub-step | Action | Reference |
|----------|--------|-----------|
| 3.1 | **Build check** | ⛔ **You MUST read [build-check.md](references/build-check.md)** |
| 3.2 | **Completeness check** | ⛔ **You MUST read [completeness-check.md](references/completeness-check.md)** |
| 3.3 | **Deployability check** | ⛔ **You MUST read [deployability-check.md](references/deployability-check.md)** |
| 3.3a | **Component mapping** (conditional) | Read [component-mapping.md](references/component-mapping.md) ONLY IF >1 project manifest found (monorepo) |

Populate `buildRequirements` per component after evaluation. Verdict propagation, tier rules, and f1Viable aggregation are in [readiness-gate.md](references/readiness-gate.md) and the individual check references.

### Step 4: Write Artifacts + Readiness Gate

⛔ Verify `context.json` exists on disk. Read [readiness-gate.md](references/readiness-gate.md) (verdicts, tiers, batch-then-approve, fast-track) then [prereq-artifacts.md](references/prereq-artifacts.md) (write procedures, schemas).

### Step 5: Present Findings

Per [readiness-gate.md § Present Findings](references/readiness-gate.md) — show verdicts grouped by severity before proceeding.

### Step 6: Remediation (conditional)

⛔ **You MUST read [remediation-protocol.md](references/remediation-protocol.md)** IF any ❌ FAIL verdict, 🔧 Recommended Fix, or ⚠️ WARN with `fixPhase: "prereq"` exists. Contains remediation loop, static verification, re-eval mandate, post-remediation artifact updates, and the build-validation consent gate. If all verdicts are ✅ PASS or ⚠️ WARN without `fixPhase: "prereq"`, skip to Step 7.

### Step 7: Write Final State

`completedPhases` already has `"prereq"` + `currentPhase: null` (from Step 4). Then:

> ⛔ **Write `lastScanCommit`.** Run `git rev-parse HEAD` and store the full 40-character SHA as `context.json.repo.lastScanCommit`. Required — staleness guard in Step 1 compares to HEAD on resume to detect changes.

### Step 8: Route

⛔ **Mandatory — do NOT skip this step.**

> **Routing fields:** All routing writes `routeToSkill` and `routeReason` to `context.json`.

> **Post-remediation context:** If Step 6 ran, lead the routing prompt with: "Remediation complete — {N} issues fixed, your app is now {overallHealth}."

> ⛔ **Evaluate rows top to bottom — first match wins.**

| # | Condition | Action |
|---|-----------|--------|
| 1 | `routeToSkill` set (any entry) | `ask_user`: "Redirect to {routeToSkill}" / "Not now". ⛔ Pipeline stops — do NOT proceed to architecture planning. |
| 2 | `cloudSdkFindings[]` non-empty (user chose "Continue evaluation anyway") | Present the cloud-SDK → Azure swap mapping as 🔶 blockers, then `ask_user` with this exact prompt: **"🔶 Cloud SDK migration required — these dependencies must be swapped before this app can deploy to Azure. (Redirect to azure-cloud-migrate / Stop — swap manually and re-run)"** — Redirect sets `routeToSkill: "azure-cloud-migrate"`, Stop halts. ⛔ Pipeline stops — do NOT proceed to architecture planning, and do NOT offer a "continue to prepare" option; the app can't deploy until the deps are swapped. |
| 3 | Orchestrator + no `routeToSkill` | Tell the user: "✅ Your app has been evaluated and is ready — let's plan your Azure deployment." Then invoke `azure-app-onboard`. ⛔ Do NOT stop, do NOT wait for user input, do NOT narrate internal handoffs. The user already consented to the full pipeline at scope triage. |
| 4 | Direct + ready/readyWithCaveats + no Azure infra | `ask_user`: "Deploy to Azure (full pipeline)" → invoke `azure-app-onboard` / "Not now" |
| 5 | Direct + ready/readyWithCaveats + existing Azure infra | `ask_user`: "Start fresh" → invoke `azure-app-onboard` / "Use existing infra" → invoke `azure-prepare` / "Not now" |
| 6 | Direct + blocked | Report blocker summary + "Fix and re-run." |

Severity tiers (🛑🔶❌🔧⚠️✅) are defined in [readiness-gate.md](references/readiness-gate.md).

## Outputs

| Artifact | Location | Consumer |
|----------|----------|----------|
| Session context | `context.json` → `components[]`, `repo{}`, `detectedInfra[]`, `detectedServices[]` | All downstream phases |
| Prereq output | `prereq-output.json` | prepare phase (via `azure-app-onboard`) |
| Readiness report | `.copilot-azure/sessions/{uuid}/readiness-report.md` | User (offline reference) |

<!-- chapter:end slug=azure-app-onboard-prereq -->

---

<!-- chapter:begin slug=deploy position=9 -->

## 9. deploy

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-app-onboard/deploy/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/deploy.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (15), referenced from this skill's directory:
  - `references/approval-gate-template.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/approval-gate-template.md
  - `references/blocked-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/blocked-patterns.md
  - `references/code-deployment-appservice.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/code-deployment-appservice.md
  - `references/code-deployment-container-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/code-deployment-container-apps.md
  - `references/code-deployment-swa.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/code-deployment-swa.md
  - `references/database-post-deploy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/database-post-deploy.md
  - `references/deploy-checklist-template.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/deploy-checklist-template.md
  - `references/deploy-safety.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/deploy-safety.md
  - `references/deploy-schemas.ts` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/deploy-schemas.ts
  - `references/error-classification.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/error-classification.md
  - `references/health-check-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/health-check-patterns.md
  - `references/mcp-tools.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/mcp-tools.md
  - `references/portal-links.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/portal-links.md
  - `references/preflight-checks.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/preflight-checks.md
  - `references/subagent-preflight.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/deploy/references/subagent-preflight.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

# Deploy — IaC Execution & Health Verification

## Quick Reference

| Property | Value |
|----------|-------|
| Best for | Executing validated IaC against Azure, health-checking deployed resources |
| Inputs | `prepare-plan.json` + `scaffold-manifest.json` from `.copilot-azure/sessions/{id}/` |
| Outputs | `deploy-result.json` written to session directory |
| Parent | [azure-app-onboard](../SKILL.md) |

## When to Use This Skill

Invoked by the `azure-app-onboard` orchestrator at Phase 4 when `scaffold-manifest.json` exists with `files[]` and `validationResult`. Not directly user-routable.

> **Return to orchestrator:** When complete, return control to `azure-app-onboard` for handoff (Step 10). Do NOT start new phases.

## When NOT to Use

| Scenario | Use Instead |
|----------|-------------|
| Plan architecture, map services, estimate costs | [prepare](../prepare/SKILL.md) |
| Generate IaC files from a plan | `azure-app-onboard` Step 7 (scaffold) |
| Run `azd up` or execute existing deployment templates | `azure-deploy` |
| Debug a running app after deployment | `azure-diagnostics` |
| Optimize existing Azure spending | `azure-cost` |

## Workflow

> ⛔ **Sub-agent delegation is MANDATORY for Step 0.** Read `subagent-preflight.md`, then dispatch as a `task` with the **COMPLETE and UNMODIFIED** template text between `<<<TEMPLATE_START>>>` / `<<<TEMPLATE_END>>>` delimiters. Do NOT summarize or rewrite the template — the sub-agent needs every "Read [file]" instruction to produce a correct `deploy-checklist.md`. Append session artifact data AFTER the template block. If your next action after reading the template is anything other than `task`, you are executing it inline instead of delegating.

> ⛔ **Healing loop:** ask user after 3 attempts, then every 5 (counter = `healingAttempts[].length`).

> ⛔ **Region lock:** Before `az deployment` retry, compare `--location` against `prepare-plan.json.deploymentVariables.location`. If changed → re-approval gate required. Update plan after approval.

> ⛔ **After compaction or any `az deployment`/`az webapp deploy`/`az acr build`/failed health check: re-read `deploy-checklist.md`.** If missing → fill from [`deploy-checklist-template.md`](references/deploy-checklist-template.md). On significant context loss: also re-read this SKILL.md.

| # | Step | Action | Artifact | Reference |
|---|------|--------|----------|-----------|
| 0 | **Dispatch preflight sub-agent** | ⛔ **You MUST dispatch [`subagent-preflight.md`](references/subagent-preflight.md) as a `task`.** ⛔ agent_type: `"task"` — NEVER `"general-purpose"`. Read the template, then your NEXT action MUST be `task`. If after reading the template your next action is `powershell`, `view`, or anything other than `task`, STOP — you are executing inline instead of delegating. Writes `deploy-checklist.md`. **`view` it immediately after return.** | `deploy-checklist.md` | ⛔ **You MUST read [`subagent-preflight.md`](references/subagent-preflight.md)** |
| 1 | **Read upstream artifacts** | Load `prepare-plan.json` + `scaffold-manifest.json`. Check `validationResult`. Resolve subscription + deployment variables. | — | — |
| 3 | **Preflight checks** | Auth, **mandatory what-if preview**, RBAC, RG per `deploy-checklist.md` § Preflight. | — | ⛔ **You MUST read `deploy-checklist.md`** (re-read if compaction occurred) |
| 4 | **Deploy approval gate** | Present cost + resource summary per `deploy-checklist.md` § Deploy approval gate format. | — | — |
| 5b | **Write deploy-result.json skeleton** | ⛔ Read [`deploy-schemas.ts`](references/deploy-schemas.ts), write skeleton (`status: "in-progress"`). Must exist BEFORE first `az` command. | `deploy-result.json` | ⛔ **You MUST read [`deploy-schemas.ts`](references/deploy-schemas.ts)** |
| 6 | **Execute deployment** | ⛔ **BEFORE `az deployment sub create`:** Generate portal link — `$dn="{deploymentName}"; $r="/subscriptions/{subId}/providers/Microsoft.Resources/deployments/$dn"; $l="https://portal.azure.com/#view/Microsoft_Azure_Resources/DeploymentDetails.MenuView/~/overview/id/$($r.Replace('/','%2F'))"; Write-Output "LINK=$l"`. ⛔ **Auto-open link in browser:** `Start-Process $l 2>$null`. Print bare URL in chat (ctrl-clickable).<br>Auto-generate ALL `@secure()` params (`openssl rand -base64 32 \| tr -d '/+='`), NEVER `ask_user` for passwords; on retry reuse from `deploy-secrets.env` or Key Vault — NEVER regenerate (see deploy-safety.md § Deploy Checklist). THEN deploy IaC. | — | ⛔ **You MUST read `deploy-checklist.md`** § Execute deployment |
| 6b | **Deploy application code** | ⛔ Deploy code for EVERY service in `prepare-plan.json.services[]`. Follow `deploy-checklist.md` § Code deploy. | — | ⛔ **You MUST read `deploy-checklist.md`** § Code deploy |
| 7 | **Health-check + SCM re-disable** | HTTP GET per endpoint (max 3 iterations). ⛔ **Multi-service apps:** Also inspect the response body for error patterns (`connection refused`, `MODULE_NOT_FOUND`, `localhost`, `SET-IN-DEPLOY-PHASE`) — HTTP 200 alone does not mean functional when the app depends on another service or KV secrets. Then ⛔ for EVERY App Service/Functions app run BOTH commands — no exceptions: `az rest --method put --url "/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{app}/basicPublishingCredentialsPolicies/scm?api-version=2023-12-01" --headers "Content-Type=application/json" --body '{"properties":{"allow":false}}'` then verify: `az rest --method get --url "/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{app}/basicPublishingCredentialsPolicies/scm?api-version=2023-12-01" --query properties.allow -o tsv` (must return `false`). | `deploy-result.json` full | ⛔ **You MUST read `deploy-checklist.md`** § Health check |
| 8 | **Finalize artifacts** | ⛔ Read [`deploy-schemas.ts`](references/deploy-schemas.ts). ⛔ Re-read `deploy-checklist.md` § Artifact verification — follow ALL 5 checks. ⛔ **No "live"/handoff message until you overwrite the skeleton `deploy-result.json`** — flip `status` off `"in-progress"` (→ `succeeded`/`failed`) and fill healthStatus, endpoints, completedUtc, deploymentNames, healingAttempts. Write `deployment-summary.md` (status table + health + portal link(s) + cleanup commands — same content as your handoff message). Update `context.json` — add `"deploy"` to `completedPhases`, `currentPhase: null`, `lastModifiedUtc`. Read back to confirm `status != "in-progress"` and `"deploy"` ∈ `completedPhases`. ⛔ **Then STOP — return to orchestrator. No further CLI commands.** | `deploy-result.json` final + `deployment-summary.md` + `context.json` update | ⛔ **You MUST read [`deploy-schemas.ts`](references/deploy-schemas.ts)** + ⛔ **Re-read `deploy-checklist.md` § Artifact verification** |
| 9 | **Error handling + healing** | ⛔ **Only if Steps 6/6b/7 returned nonzero exit code or health check failed.** Skip entirely on clean deploys. Classify errors, healing loop, PLAN_LEVEL_CHANGE re-approval per `deploy-checklist.md` § During healing. ⛔ **Even on unrecoverable failure:** write `deploy-result.json` with `status: "failed"` and `errorDetails` before returning to orchestrator — the artifact must always exist. | — | ⛔ **You MUST read [`error-classification.md`](references/error-classification.md)** |

<!-- chapter:end slug=deploy -->

---

<!-- chapter:begin slug=prepare position=10 -->

## 10. prepare

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-app-onboard/prepare/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/prepare.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (12), referenced from this skill's directory:
  - `references/deploy-strategy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/deploy-strategy.md
  - `references/mcp-tools.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/mcp-tools.md
  - `references/naming-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/naming-patterns.md
  - `references/prepare-schemas.ts` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/prepare-schemas.ts
  - `references/pricing-guide-services.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/pricing-guide-services.md
  - `references/pricing-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/pricing-guide.md
  - `references/service-mapping.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/service-mapping.md
  - `references/sku-matrix.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/sku-matrix.md
  - `references/sku-quota-validation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/sku-quota-validation.md
  - `references/subagent-pricing.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/subagent-pricing.md
  - `references/subagent-quota.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/subagent-quota.md
  - `references/validation-rubric.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/prepare/references/validation-rubric.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

# Prepare — Architecture Planning & Cost Estimation

## Quick Reference

| Property | Value |
|----------|-------|
| Best for | Mapping app components to Azure services with cost estimation and quota validation |
| Inputs | `prereq-output.json` + `context.json` from `.copilot-azure/sessions/{id}/` |
| Outputs | `prepare-plan.json` written to session directory |
| Parent | [azure-app-onboard](../SKILL.md) |

## When to Use This Skill

Invoked by the `azure-app-onboard` orchestrator at Phase 2 when `prereq-output.json` exists. Not directly user-routable.

> **Return to orchestrator:** When complete, return control to `azure-app-onboard`. Do NOT directly invoke scaffold or deploy.

## When NOT to Use

| Scenario | Use Instead |
|----------|-------------|
| Code readiness or prereq scanning | `azure-app-onboard` Step 3 (prereq) |
| IaC generation from a completed plan | `azure-app-onboard` Step 7 (scaffold) |
| Deploying resources to Azure | `azure-app-onboard` Step 9 (deploy) |
| Optimizing existing Azure spend | `azure-cost` |
| Estimating VM-specific costs | `azure-compute` |
| Enterprise landing zone architecture | `azure-enterprise-infra-planner` |

## MCP Tools

| Tool | Purpose |
|------|----------|
| `mcp_azure_mcp_pricing` / `azure-pricing` (router → `command: pricing_get`) | Cost estimation (inline — see Step 6). Fallback: dispatch [`subagent-pricing.md`](references/subagent-pricing.md) |
| `mcp_azure_mcp_policy` | Subscription policy constraints |
| `az rest` | Quota validation (via sub-agent — see Step 5) |
| `mcp_azure_mcp_cloudarchitect` → `cloudarchitect_design` | WAF-aligned architecture design |
| `mcp_azure_mcp_wellarchitectedframework` | Per-service WAF guidance |
| `mcp_azure_mcp_advisor` → `advisor_recommendation_list` | Optimization recommendations |

## Workflow

| # | Step | Action | Reference |
|---|------|--------|-----------|
| 1 | **Read session state** | Load `prereq-output.json` + `context.json`. Resolve subscription | Cross-ref [subscription-resolution.md](../references/subscription-resolution.md) if needed |
| 2 | **Query policy constraints** | Inline MCP: fetch policy + advisor recommendations | `mcp_azure_mcp_policy` + `mcp_azure_mcp_advisor` |
| 3 | **Map components to services** | Per-component Azure service selection, Dockerfile routing, deploy-as-is | ⛔ **You MUST read [service-mapping.md](references/service-mapping.md) and [deploy-strategy.md](references/deploy-strategy.md)** |
| 4 | **Select SKUs + WAF analysis** | Budget-aware SKU selection, inline WAF service guidance | ⛔ **You MUST read [sku-matrix.md](references/sku-matrix.md)** |
| 5 | **Validate quotas + region capacity** | ⛔ Read [`subagent-quota.md`](references/subagent-quota.md) → dispatch as `task` (NEXT action MUST be `task`, ⛔ agent_type: `"task"` — NEVER `"general-purpose"`). Copy the **COMPLETE and UNMODIFIED** template text into the task prompt between `<<<TEMPLATE_START>>>` / `<<<TEMPLATE_END>>>` delimiters — do NOT summarize. Append the caller-provided inputs listed in [`subagent-quota.md`](references/subagent-quota.md)'s Input table AFTER the template block. ⛔ **After dispatching, proceed to Step 6 (cost estimation) while the subagent runs. Do NOT run quota checks yourself — the subagent handles it. Collect subagent results before Step 9 (write plan).** | ⛔ **You MUST read [`subagent-quota.md`](references/subagent-quota.md)** |
| 6 | **Estimate costs** | ⛔ **You MUST read [pricing-guide.md](references/pricing-guide.md)** for methodology, then [pricing-guide-services.md](references/pricing-guide-services.md) for per-service filters. Call the pricing router (`mcp_azure_mcp_pricing`/`azure-pricing`) with `command: "pricing_get"` + a `parameters{}` object inline per paid service. If MCP unavailable or fails → ⛔ Read [`subagent-pricing.md`](references/subagent-pricing.md) → dispatch as `task` (NEXT action MUST be `task`, ⛔ agent_type: `"task"` — NEVER `"general-purpose"`). Copy the **COMPLETE and UNMODIFIED** template text into the task prompt between `<<<TEMPLATE_START>>>` / `<<<TEMPLATE_END>>>` delimiters — do NOT summarize. Append data (services[], region, budget tier) AFTER the template block. Write results to `prepare-plan.json.costEstimate`. | [pricing-guide.md](references/pricing-guide.md) |
| 7 | **Generate naming** | Centralized naming: suffix, prefix, all resource names | ⛔ **You MUST read [naming-patterns.md](references/naming-patterns.md)** |
| 8 | **Determine IaC format** | Existing non-Azure `.tf` → `ask_user` Bicep vs TF, write to `overrides[].iacFormat`. No `.tf` → default Bicep. | (inline) |
| 9 | **Write prepare-plan.json** | Per `PreparePlan` schema. Include postDeployRecommendations, deploymentVariables | ⛔ **You MUST read [prepare-schemas.ts](references/prepare-schemas.ts)** for `PreparePlan` schema |
| 10 | **Return summary** | Structured summary for orchestrator approval gate | (inline — 1 line) |
| 11 | **Validate plan** | 4-dimension check: Goal Alignment, WAF Alignment, Dependency Completeness, Deployment Viability. Fix inline on failure, document tradeoffs in `assumptions[]`. | All must pass before writing |

### Step 5 — Post-Quota Validation

> ⛔ **NEVER present a region without checking quota first.** Skipping quota validation causes cascading deploy failures and extended healing loops.
> ⛔ If plan includes PostgreSQL/MySQL, verify `offerRestrictionsVerified: true` — if false/missing, region is blocked. Do NOT proceed to scaffold with unchecked DB services.
> ⛔ **Free ≠ unlimited.** Every compute SKU — including F1, Consumption, and Serverless tiers — has a per-subscription, per-region quota. Do NOT skip quota checks because a SKU is free.
> ⛔ After region fallback, update ALL `services[].region` in `prepare-plan.json`. Do not leave stale values.

## Error Handling

| Error | Remediation |
|-------|-------------|
| Pricing API 400 | Verify `--sku` included. Free tiers: skip API |
| MCP pricing unavailable | Dispatch [`subagent-pricing.md`](references/subagent-pricing.md) as `task` fallback (uses direct HTTP to `prices.azure.com`) |
| Prereq output missing | Trigger prereq backfill |
| Quota check fails | Fall back to best-effort estimate + disclaimer |
| Override conflicts | Re-run from Step 3 with new constraints |

<!-- chapter:end slug=prepare -->

---

<!-- chapter:begin slug=scaffold position=11 -->

## 11. scaffold

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-app-onboard/scaffold/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/scaffold.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (26), referenced from this skill's directory:
  - `references/bicep-app-service.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/bicep-app-service.md
  - `references/bicep-container-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/bicep-container-apps.md
  - `references/bicep-patterns-data.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/bicep-patterns-data.md
  - `references/bicep-patterns-security.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/bicep-patterns-security.md
  - `references/bicep-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/bicep-patterns.md
  - `references/bicep-swa.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/bicep-swa.md
  - `references/cicd-pipelines.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/cicd-pipelines.md
  - `references/dockerfile-generation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/dockerfile-generation.md
  - `references/env-var-secrets.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/env-var-secrets.md
  - `references/error-handling.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/error-handling.md
  - `references/iac-generation-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/iac-generation-rules.md
  - `references/mcp-tools.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/mcp-tools.md
  - `references/rbac-roles.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/rbac-roles.md
  - `references/scaffold-healing-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/scaffold-healing-rules.md
  - `references/scaffold-schemas.ts` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/scaffold-schemas.ts
  - `references/self-healing.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/self-healing.md
  - `references/self-review-checklist.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/self-review-checklist.md
  - `references/self-review-procedure.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/self-review-procedure.md
  - `references/subagent-iac-gen.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/subagent-iac-gen.md
  - `references/subagent-review.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/subagent-review.md
  - `references/subagent-validate.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/subagent-validate.md
  - `references/terraform-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/terraform-patterns.md
  - `references/validation-and-manifest.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/validation-and-manifest.md
  - `references/waf-checklist.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/scaffold/references/waf-checklist.md
  - …and 2 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/scaffold

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

# Azure App Onboard Scaffold — IaC Generation + Self-Review

Generate deployment-ready infrastructure code from an architecture plan, verify it with adversarial self-review, and bridge to validation — all without deploying.

## Quick Reference

| Property | Value |
|----------|-------|
| Parent | [azure-app-onboard](../SKILL.md) |
| Best for | Turning `prepare-plan.json` service list into Bicep templates with secure-by-default patterns |
| Inputs | `prepare-plan.json` (services, naming, quotas), `context.json` (overrides, components, repo info) |
| Outputs | `scaffold-manifest.json`, generated IaC files in `infra/` |
| Pipeline position | Phase 3 of 4: prereq → prepare → **scaffold** → deploy |
| IaC format | Bicep (v1 default). Terraform when existing `.tf` detected or user override. |

## When to Use This Skill

Invoked by the `azure-app-onboard` orchestrator at Phase 3 when `prepare-plan.json` exists with `services[]`. Not directly user-routable in v1.

> **Return to orchestrator:** When complete, return control to `azure-app-onboard`. Do NOT directly invoke deploy — the orchestrator manages phase transitions.

## When NOT to Use

| Scenario | Use Instead |
|----------|-------------|
| User-triggered IaC (no `prepare-plan.json`) | `azure-prepare` |
| Subscription-scope landing zones | `azure-enterprise-infra-planner` |
| Execute deployment (`azd up`) | `azure-deploy` (do NOT invoke from AppOnboard pipeline) |

## MCP Tools

> See [shared tools](../references/mcp-tool-reference.md) for cross-phase tools and global parameters. See [scaffold tools](references/mcp-tools.md) for full parameter tables.

| Tool | Sub-command | Purpose | Parameters |
|------|-----------|---------|------------|
| `mcp_azure_mcp_bicepschema` | `bicepschema_get` | ARM resource type schemas | `resource_type` (Required), `api_version` (Optional) |
| `mcp_bicep_list_avm_metadata` | *(flat)* | AVM module catalog | None |
| `mcp_bicep_get_bicep_best_practices` | *(flat)* | Bicep best practices | None |
| `mcp_bicep_get_az_resource_type_schema` | *(flat)* | ARM resource type JSON schema | `azResourceType`, `apiVersion` (Required) |
| `mcp_bicep_build_bicep` | *(flat)* | Validate `.bicep` files (self-review L3) | `filePath` (Required) |
| `mcp_bicep_format_bicep_file` | *(flat)* | Format `.bicep` files (LF enforcement) | `filePath` (Required) |
| `mcp_azure_mcp_deploy` | `deploy_iac_rules_get` | IaC best practices and rules | `deployment-tool`, `iac-type`, `resource-types` |
| `mcp_azure_mcp_deploy` | `deploy_pipeline_guidance_get` | CI/CD pipeline config | `is-azd-project`, `pipeline-platform`, `deploy-option` |
| `mcp_azure_mcp_get_azure_bestpractices` | `get_azure_bestpractices_get` | SDK/Functions best practices | `resource`, `action` |
| `mcp_azure_mcp_azureterraformbestpractices` | *(flat)* | Terraform patterns (TF path only) | `resource_type` (Required) |

## Workflow

**Session folder:** `.copilot-azure/sessions/{uuid}/` — reads `prepare-plan.json` + `context.json`, writes `scaffold-manifest.json`.

### DETECT (Steps 1–4)

1. **Read `prepare-plan.json`** — verify `services[]` exists, read `naming` config (especially `naming.resourcePrefix`, `naming.suffix`, `naming.resources[]`). Read resource group name from `context.json.azure.resourceGroup`. ⛔ **Use EXACTLY these names in generated IaC — do NOT invent names, derive them from `environmentName`, or append your own suffixes.** ⛔ **Use EXACTLY the names from `prepare-plan.json.naming.resources[]` as Bicep parameters. Do NOT derive names with `take()`, `substring()`, or string manipulation. The plan is the source of truth.** Missing → trigger prepare backfill via `azure-app-onboard` orchestrator.
2. **Read `context.json`** — check `overrides[]` for `iacFormat` preference, `detectedInfra[]` for existing `.tf`, `detectedInfraProvider` for cloud provider classification.
3. **Check workspace for existing IaC** — ⛔ **Skip** if `context.json.overrides[]` contains `ignoreExistingInfra: true`. Otherwise:
   - **Azure IaC** (`.bicep`, `azure.yaml`, `.tf` with `azurerm`): `ask_user` → "Start fresh" (rename `infra/` to `infra.bak/`) or "Use existing" (route to `azure-prepare`, stop pipeline).
   - **Non-Azure IaC** (`.tf` with GCP/AWS): respect `context.json.overrides[].iacFormat` from prepare. Default: Bicep alongside existing TF.
   - **Unknown TF** (`detectedInfraProvider.terraform` == `"unknown"`): ask user which provider before routing.
   - **No IaC**: continue.
4. **Determine compute targets** — Check which compute targets are in the plan (App Service/Functions, Container Apps, or both) and whether PostgreSQL/Redis is present. Do NOT read any reference files — pass this info to the sub-agent at Step 5.
4b. **Pre-check API versions (main thread)** — MCP tool access is unreliable in `task` agents — call these in the main thread before dispatching. Call `mcp_bicep_list_az_resource_types_for_provider` (or `bicep-list_az_resource_types_for_provider`) once per provider namespace in `prepare-plan.json.services[]` (e.g., `Microsoft.Web`, `Microsoft.App`, `Microsoft.DBforPostgreSQL`, `Microsoft.Cache`, `Microsoft.KeyVault`, `Microsoft.ContainerRegistry`). Extract the latest GA API version (no `-preview`) for each resource type. Build an `apiVersions` map and pass it to the IaC gen sub-agent at Step 5. Fallback: if MCP unavailable, run `az provider show --namespace {ns} --query "resourceTypes[?resourceType=='{type}'].apiVersions[?!contains(@, 'preview')] | [0][0]" -o tsv` per resource type — this filters to GA-only and picks the latest. Pass `"MCP unavailable"` only if both MCP AND CLI fail. Sub-agent still validates generated Bicep via `az bicep build`.

### ACTION (Steps 5–12)

> ⛔ **File boundary:** NEVER modify files outside `infra/`, `.copilot-azure/`. Scaffold only writes files — no install/build commands.

> ⛔ **Sub-agent delegation is MANDATORY for Steps 5, 6–9, and 10–12.** Each step reads its `subagent-*.md` template, then dispatches a `task` call. Do NOT read any reference file not explicitly named in these steps.
>
> ⛔ **Dispatch type: `task` ONLY — NEVER `general-purpose`.** `general-purpose` leaks sub-agent context into the main thread, accelerating compaction and evicting the orchestrator workflow. `task` isolates sub-agent context.
>
> ⛔ **How to dispatch — VERBATIM COPY required:**
> 1. `view` the `subagent-*.md` template file
> 2. Your **NEXT action MUST be a `task` tool call** — not `view`, `powershell`, `create`, or ANY other tool
> 3. The task prompt MUST contain the **COMPLETE and UNMODIFIED** template text. Copy the template between `<<<TEMPLATE_START>>>` / `<<<TEMPLATE_END>>>` delimiters exactly as shown below. Do NOT summarize, paraphrase, reword, or omit ANY part of it — the sub-agent needs every "Read [file]" and "Do:" instruction to produce correct output
> 4. AFTER the template block, append the data sections (plan JSON, overrides, etc.)
>
> **Anti-pattern (causes regressions):** Writing your OWN prompt that lists workflow steps or describes what to generate. The template already contains the complete workflow — your job is to COPY it, not rewrite it.

5. **IaC generation** — ⛔ **You MUST dispatch [`subagent-iac-gen.md`](references/subagent-iac-gen.md) as a `task`.** ⛔ agent_type: `"task"` — NEVER `"general-purpose"`.
   ```
   <<<TEMPLATE_START>>>
   {paste the ENTIRE content of subagent-iac-gen.md here — unmodified}
   <<<TEMPLATE_END>>>

   ## Data (appended by orchestrator)
   ### prepare-plan.json
   {full JSON}
   ### context.json.overrides
   {overrides array}
   ### prereq-output.json.buildRequirements
   {buildRequirements object}
   ### prereq-output.json.warnings[]
   {warnings array}
   ### Compute targets
   {App Service/Functions, Container Apps, or both + whether PostgreSQL/Redis present}
   ### apiVersions
   {map from Step 4b, e.g. {"Microsoft.KeyVault/vaults": "2023-07-01", ...} — or "MCP unavailable" if skipped}
   ### Working directory
   {absolute path}
   ```
   - **Expect:** IaC files written to `infra/`, file list returned for `scaffold-manifest.json.files[]`
   - The tag `app-onboard-skill: 'true'` MUST appear verbatim in generated Bicep.

5b. **Deploy checklist (parallel with Step 5)** — Dispatch as a `task` **in parallel** with the IaC gen subagent above. ⛔ agent_type: `"task"` — NEVER `"general-purpose"`.
   ```
   <<<TEMPLATE_START>>>
   You are a deploy-checklist generator. Do NOT invoke any skills.

   1. Read the deploy-checklist-template at: plugin/skills/azure-app-onboard/deploy/references/deploy-checklist-template.md
   2. Fill in {placeholders} with real values from prepare-plan.json (appName, rgName, subscriptionId, sessionId).
   3. Delete sections that don't apply to this deployment's compute target (e.g., remove App Service section for Container Apps deploys). The template section headers indicate which to delete.
   4. Write the result to the session folder using the `create` tool. This file survives conversation compaction — deploy re-reads it after every long-running command.
   <<<TEMPLATE_END>>>

   ## Data (appended by orchestrator)
   ### prepare-plan.json
   {full JSON}
   ### Session path
   {.copilot-azure/sessions/{uuid}/}
   ### Compute targets
   {App Service, Container Apps, Static Web Apps, or combination}
   ```
   - **Expect:** `deploy-checklist.md` written to session folder. If this subagent fails, the validate subagent (Steps 10b–12.5) will catch the missing file.

6–9. **Self-review** — ⛔ **You MUST dispatch [`subagent-review.md`](references/subagent-review.md) as a `task`.** ⛔ agent_type: `"task"` — NEVER `"general-purpose"`.
   ```
   <<<TEMPLATE_START>>>
   {paste the ENTIRE content of subagent-review.md here — unmodified}
   <<<TEMPLATE_END>>>

   ## Data (appended by orchestrator)
   ### Generated IaC files
   {full content of every .bicep/.tf file}
   ### prepare-plan.json (services, naming, deploymentVariables)
   {relevant sections}
   ### prereq-output.json.warnings[]
   {warnings array}
   ```
   - **Expect:** findings JSON → write to `scaffold-manifest.json.selfReview`
   - FLAGGED at L1/L3 → fix IaC before proceeding

### VALIDATE → MANIFEST → APPROVE (Steps 10–12.5)

10a. **Format IaC (main thread)** — For each `.bicep` file in `infra/` (including `modules/`): call `mcp_bicep_format_bicep_file` (or `bicep-format_bicep_file`) with `{ filePath: "<absolute path>" }`.This enforces LF line endings via the `bicepconfig.json` written during IaC generation. Fallback: skip if unavailable.

10a-conf. **Conformance gate (main thread — MANDATORY for Bicep)** — ⛔ **Skip this entire step when the scaffold emitted Terraform** (`infra/main.bicep` absent) — these checks are Bicep-only (Terraform is syntax-validated via `terraform validate` in the validate subagent). Otherwise run the conformance script from this skill's `scripts/` dir; it deterministically catches ARM-rejected values `az bicep build` can't (invalid Bicep values, wrong DB version, reserved DB login, `enablePurgeProtection`):
   ```
   {scaffoldDir}/scripts/scaffold-conformance.ps1 -SessionPath ".copilot-azure/sessions/{uuid}" -InfraPath infra   # pwsh (preferred)
   bash {scaffoldDir}/scripts/scaffold-conformance.sh ".copilot-azure/sessions/{uuid}" infra                       # bash (only if pwsh unavailable; needs jq for the plan-dependent checks)
   ```
   ⛔ **Prefer the `.ps1` when `pwsh` is available** — it runs every check unconditionally. The `.sh` twin skips the plan-dependent checks (`DB-VERSION-MATCH`, `SERVICES-COMPLETE`, `DB-NAME-PRESENT`, `WARN-FIXED`) when `jq` is absent.
   ⛔ Any BLOCK failure → fix the IaC, re-run (max 3); never present the deploy gate with an open BLOCK. Run it here in the main thread — do NOT delegate to the validate subagent or hand-judge the result when a shell exists. Pass the JSON to the validate subagent for `scaffold-manifest.json.conformance`.

10b–12.5. **Validation + manifest** — ⛔ **You MUST dispatch [`subagent-validate.md`](references/subagent-validate.md) as a `task`.** ⛔ agent_type: `"task"` — NEVER `"general-purpose"`.
   ```
   <<<TEMPLATE_START>>>
   {paste the ENTIRE content of subagent-validate.md here — unmodified}
   <<<TEMPLATE_END>>>

   ## Data (appended by orchestrator)
   ### IaC file paths
   {list of generated files}
   ### Self-review findings (from Steps 6–9)
   {findings JSON}
   ### prepare-plan.json
   {full JSON}
   ### prereq-output.json.warnings[]
   {warnings array}
   ### prereq-output.json.healthEndpoint
   {detected health path string or null}
   ### Conformance result
   {JSON from Step 10a-conf}
   ### Session path
   {.copilot-azure/sessions/{uuid}/}
   ```
   - **Expect:** `scaffold-manifest.json` with `validationResult`, deploy checklist generated
   - Verify `deploy-checklist.md` exists (written at Step 5b) — if missing, create NOW from [`deploy-checklist-template.md`](../deploy/references/deploy-checklist-template.md). Verify `deploy-result.json` exists — if missing, create from [`deploy-schemas.ts`](../deploy/references/deploy-schemas.ts).
   - ⛔ **Verify `context.json` update (main-thread — do NOT delegate).** Read `.copilot-azure/sessions/{uuid}/context.json`. If `completedPhases` does not include `"scaffold"` OR `currentPhase` is not `"deploy"`, write it yourself via `edit` / `create`: append `"scaffold"` to `completedPhases`, set `currentPhase` to `"deploy"`, update `lastModifiedUtc` to current UTC ISO 8601. This is a phase-boundary write required by [pipeline-rules.md](../references/pipeline-rules.md) — do not skip it.
   - ⛔ **Return to orchestrator for Step 8 (Deploy Approval Gate).** YOUR NEXT ACTION MUST BE presenting the Deploy Gate per orchestrator SKILL.md — do NOT write a "summary of generated files" message, do NOT emit a completion report. The Deploy Gate prompt (`🚀 Ready to deploy? ...`) is the ONLY correct next output.

## Self-Healing Loop

On validation failure → read [`scaffold-healing-rules.md`](references/scaffold-healing-rules.md) (healing cadence, PLAN_LEVEL_CHANGE, artifact consistency). Do NOT pre-read.

## Error Handling

- **Missing `prepare-plan.json`:** trigger backfill via orchestrator.
- **Existing IaC:** handled in DETECT Step 3.
- **MCP unavailable:** fall back to reference patterns, flag as "unverified."
- FLAGGED findings and healing exhaustion: see [scaffold-healing-rules.md](references/scaffold-healing-rules.md).

<!-- chapter:end slug=scaffold -->

---

<!-- chapter:begin slug=azure-app-onboard position=12 -->

## 12. azure-app-onboard

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-app-onboard/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-app-onboard.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (11), referenced from this skill's directory:
  - `references/approval-gates.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/approval-gates.md
  - `references/azd-template-routing.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/azd-template-routing.md
  - `references/handoff-protocol.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/handoff-protocol.md
  - `references/iac-resources.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/iac-resources.md
  - `references/intent-gathering.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/intent-gathering.md
  - `references/mcp-tool-reference.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/mcp-tool-reference.md
  - `references/pipeline-rules-runtime.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/pipeline-rules-runtime.md
  - `references/pipeline-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/pipeline-rules.md
  - `references/session-protocol.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/session-protocol.md
  - `references/session-schemas.ts` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/session-schemas.ts
  - `references/subscription-resolution.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-app-onboard/references/subscription-resolution.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-app-onboard
description: "End-to-end orchestrator: from a business idea, app idea, or existing app to running Azure deployment with cost estimates and pre-deploy approval. Analyzes your app, auto-detects the right Azure services, scaffolds infrastructure code, and deploys — tailored to your app, not a template. Handles moving existing apps to Azure without rewriting or with minimal changes. WHEN: bring your app to Azure, plan my app, cost to run, is my code ready to deploy, deploy my app to the cloud, deploy all my services, what Azure services do I need, plan my Azure deployment, deploy my new app to Azure, one-click deploy, I have an app and want it on Azure, migrate my app to Azure, help me get started, build an app, no code yet, starter project. DO NOT USE FOR: use azd for deployment(use azure-deploy), optimizing existing costs (use azure-cost), code readiness checks only (use azure-app-onboard-prereq)."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.2"
---

# Azure App Onboard

> ⛔ **Every repo goes through the full pipeline (Steps 1–10). No exceptions.** Do not skip steps, refuse, or short-circuit based on what you recognize. Follow the Workflow table below sequentially — read each step's references before acting.

## Quick Reference

| Property | Value |
|----------|-------|
| Best for | Developers who know what to build but not which Azure services to use |
| Inputs | Business idea or existing codebase, budget/scale preferences (optional) |
| Outputs | Architecture plan, cost estimate, IaC files, deployed Azure resources |
| Phases | Discover → Architect → Scaffold → Deploy (self-contained, no external skill calls) |

## When to Use This Skill

- Deploy existing code without knowing which Azure services to use
- Check if your existing code is ready to deploy to Azure
- Move an existing app to Azure without rewriting or with minimal changes
- Get cost estimates before committing to infrastructure
- Understand architecture decisions and rejected alternatives
- Get answers to Azure architecture or service selection questions (e.g., "What database should I use?")
- Get guided Azure onboarding without prior experience

## When NOT to Use

| Scenario | Use Instead |
|----------|-------------|
| Run `azd up` or execute an existing deployment | `azure-deploy` |
| Optimize existing Azure spend | `azure-cost` |
| Generate Bicep/Terraform for a known architecture | `azure-prepare` |
| Validate infrastructure or run preflight checks | `azure-validate` |
| Troubleshoot a running Azure deployment | `azure-diagnostics` |
| Deploy to or manage AKS/Kubernetes directly | `azure-kubernetes` |
| Look up or list existing Azure resources | `azure-resource-lookup` |

## Pipeline Rules

> ⛔ **You MUST read [`references/pipeline-rules.md`](references/pipeline-rules.md) at the start of every AppOnboard session.** It contains approval gates, phase lifecycle, session artifacts, deploy-as-is, and security baseline rules.

## Workflow

> ⛔ **Deploy recovery:** After deploy gate approval OR before any `az deployment`/`az webapp deploy`/`az acr build` — if you haven't read `deploy/SKILL.md`, read `.copilot-azure/sessions/{id}/deploy-checklist.md` first, then `deploy/SKILL.md`. ⛔ NEVER invoke `{"skill": "azure-deploy"}` — that is a DIFFERENT skill for a DIFFERENT workflow.

> ⛔ **Post-scaffold transition (MANDATORY):** Immediately after `scaffold-manifest.json` is written, YOUR NEXT ACTION MUST be Step 8 (Deploy Approval Gate) — NOT a summary report, NOT a "here are the generated files" message, NOT a completion signal. Confirm `context.json` has `completedPhases: [...,"scaffold"]` + `currentPhase: "deploy"` (update it yourself if the scaffold subagent didn't). Re-read [approval-gates.md § Deploy Gate](references/approval-gates.md) if evicted from context (scaffold reference loading is heavy), then present the exact prompt: **"🚀 Ready to deploy? (Yes / Run manually / Edit plan / Cancel)"**. This gate is the LAST content in your response — wait for the user's reply.

| # | Step | Action | Reference |
|---|------|--------|-----------|
| 1 | **Session check + Azure login** | Create/resume session, verify Azure CLI auth, resolve subscription + user identity | ⛔ **You MUST read [session-protocol.md](references/session-protocol.md)** |
| 2 | **Scope triage** | Check azd markers, triage question. Empty workspace or code-only (no infra) → Step 3 directly. | ⛔ Read [intent-gathering.md](references/intent-gathering.md) § Scope Triage |
| 3 | **Prereq scan** | ⛔ Skip if `completedPhases` includes `"prereq"`. Otherwise: invoke `{"skill": "azure-app-onboard-prereq"}`. Write `prereq-output.json`, update `context.json`. **Halt if:** `overallHealth: "blocked"` OR `routeToSkill` set. | |
| 4 | **Gather intent** | Present prereq results, confirm stack + Azure services, ask remaining questions. | ⛔ Read [intent-gathering.md](references/intent-gathering.md) § After Prereq Returns |
| 5 | **Plan architecture** | Write `prepare-plan.json`. | ⛔ **You MUST read [prepare/SKILL.md](prepare/SKILL.md)** |
| 6 | **Scaffold approval gate** | Display plan for user approval BEFORE generating any files. | ⛔ Read [approval-gates.md](references/approval-gates.md) § Scaffold Gate |
| 7 | **Scaffold** | Generate IaC, self-review. Write `scaffold-manifest.json`. Update `context.json`. | ⛔ **You MUST read [scaffold/SKILL.md](scaffold/SKILL.md)** |
| 8 | **Deploy approval gate** | Display validation summary. ⛔ After approval: FIRST read deploy-checklist.md → deploy/SKILL.md. NEVER `{"skill": "azure-deploy"}`. | ⛔ Read [approval-gates.md](references/approval-gates.md) § Deploy Gate |
| 9 | **Deploy** | Execute IaC, health-check. Write `deploy-result.json`. | ⛔ **You MUST read [deploy/SKILL.md](deploy/SKILL.md)** |
| 10 | **Handoff** | Surface deployment identity, cleanup commands, next steps. | ⛔ **You MUST read [`handoff-protocol.md`](references/handoff-protocol.md)** |

## Error Handling

| Error | Remediation |
|-------|-------------|
| Phase fails | Halt, report phase + error. User decides: retry, skip, abort. |
| MCP server unavailable | Skip affected checks, add disclaimer to `costEstimate.assumptions[]` and every approval gate. |
| Missing RBAC | Report required role + `az role assignment` command. |

> **Shared references:** [MCP tools](references/mcp-tool-reference.md) (cross-phase tool parameters) | [IaC resources](references/iac-resources.md) (Azure resource docs for troubleshooting)

<!-- chapter:end slug=azure-app-onboard -->

---

<!-- chapter:begin slug=azure-cloud-migrate position=13 -->

## 13. azure-cloud-migrate

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-cloud-migrate/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-cloud-migrate.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (30), referenced from this skill's directory:
  - `references/services/app-service/app-engine-to-app-service.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/app-service/app-engine-to-app-service.md
  - `references/services/app-service/assessment.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/app-service/assessment.md
  - `references/services/app-service/beanstalk-to-app-service.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/app-service/beanstalk-to-app-service.md
  - `references/services/app-service/code-migration.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/app-service/code-migration.md
  - `references/services/app-service/global-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/app-service/global-rules.md
  - `references/services/app-service/heroku-to-app-service.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/app-service/heroku-to-app-service.md
  - `references/services/container-apps/assessment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/assessment-guide.md
  - `references/services/container-apps/cloudrun-assessment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/cloudrun-assessment-guide.md
  - `references/services/container-apps/cloudrun-deployment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/cloudrun-deployment-guide.md
  - `references/services/container-apps/cloudrun-to-container-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/cloudrun-to-container-apps.md
  - `references/services/container-apps/deployment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/deployment-guide.md
  - `references/services/container-apps/fargate-assessment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/fargate-assessment-guide.md
  - `references/services/container-apps/fargate-deployment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/fargate-deployment-guide.md
  - `references/services/container-apps/fargate-to-container-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/fargate-to-container-apps.md
  - `references/services/container-apps/k8s-to-container-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/k8s-to-container-apps.md
  - `references/services/container-apps/spring-apps-to-aca.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/spring-apps-to-aca.md
  - `references/services/container-apps/spring-assessment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/spring-assessment-guide.md
  - `references/services/container-apps/spring-dependency-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/spring-dependency-patterns.md
  - `references/services/container-apps/spring-deployment-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/container-apps/spring-deployment-guide.md
  - `references/services/functions/assessment.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/functions/assessment.md
  - `references/services/functions/code-migration.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/functions/code-migration.md
  - `references/services/functions/global-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/functions/global-rules.md
  - `references/services/functions/lambda-to-functions.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/functions/lambda-to-functions.md
  - `references/services/functions/runtimes/csharp.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cloud-migrate/references/services/functions/runtimes/csharp.md
  - …and 6 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-cloud-migrate

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-cloud-migrate
description: "Assess and migrate cross-cloud workloads to Azure with reports and code conversion. Supports Lambda→Functions, Beanstalk/Heroku/App Engine→App Service, Fargate/Kubernetes/Cloud Run/Spring Boot→Container Apps. WHEN: migrate Lambda to Functions, AWS to Azure, migrate Beanstalk, migrate Heroku, migrate App Engine, Cloud Run migration, Fargate to ACA, ECS/Kubernetes/GKE/EKS to Container Apps, Spring Boot to Container Apps, cross-cloud migration."
license: MIT
metadata:
  author: Microsoft
  version: "1.3.1"
---

# Azure Cloud Migrate

> This skill handles **assessment and code migration** of existing cloud workloads to Azure.

## Rules

1. Follow phases sequentially — do not skip
2. Generate assessment before any code migration
3. Load the scenario reference and follow its rules
4. Use `mcp_azure_mcp_get_azure_bestpractices` and `mcp_azure_mcp_documentation` MCP tools
5. Use the latest supported runtime for the target service
6. Destructive actions require `ask_user` — [functions global-rules](references/services/functions/global-rules.md) | [app-service global-rules](references/services/app-service/global-rules.md)
7. **Report progress to user** — During long-running operations (deployments, image pushes), provide resource-level status updates so the user is never left waiting without feedback — see [workflow-details.md](references/workflow-details.md)
8. **Audit service discovery in app code** — Kubernetes DNS names (e.g., `http://order-service:3001`) do not resolve in Container Apps. During assessment, scan source code for hardcoded hostnames/ports in HTTP clients and flag them for env-var-driven URL injection

## Migration Scenarios

| Source | Target | Reference |
|--------|--------|-----------|
| AWS Lambda | Azure Functions | [lambda-to-functions.md](references/services/functions/lambda-to-functions.md) ([assessment](references/services/functions/assessment.md), [code-migration](references/services/functions/code-migration.md)) |
| AWS Elastic Beanstalk | Azure App Service | [beanstalk-to-app-service.md](references/services/app-service/beanstalk-to-app-service.md) |
| Heroku | Azure App Service | [heroku-to-app-service.md](references/services/app-service/heroku-to-app-service.md) |
| Google App Engine | Azure App Service | [app-engine-to-app-service.md](references/services/app-service/app-engine-to-app-service.md) |
| AWS Fargate (ECS) | Azure Container Apps | [fargate-to-container-apps.md](references/services/container-apps/fargate-to-container-apps.md) ([assessment](references/services/container-apps/fargate-assessment-guide.md), [deployment](references/services/container-apps/fargate-deployment-guide.md)) |
| Kubernetes (GKE/EKS/Self-hosted) | Azure Container Apps | [k8s-to-container-apps.md](references/services/container-apps/k8s-to-container-apps.md) |
| GCP Cloud Run | Azure Container Apps | [cloudrun-to-container-apps.md](references/services/container-apps/cloudrun-to-container-apps.md) |
| Spring Boot (Azure Spring Apps/VMs) | Azure Container Apps | [spring-apps-to-aca.md](references/services/container-apps/spring-apps-to-aca.md) |

> No matching scenario? Use `mcp_azure_mcp_documentation` and `mcp_azure_mcp_get_azure_bestpractices` tools.

## Output Directory

All output goes to `<workspace-root-basename>-azure/` at workspace root, where `<workspace-root-basename>` is the name of the top-level workspace directory itself (NOT a subdirectory within it). Never modify the source directory.

## Steps

1. **Create** `<workspace-root-basename>-azure/` at workspace root
2. **Assess** — Analyze source, map services, generate report using the scenario-specific assessment guide → [functions assessment](references/services/functions/assessment.md) | [app-service assessment](references/services/app-service/assessment.md)
3. **Migrate** — Convert code/config using the scenario-specific migration guide → [functions code-migration](references/services/functions/code-migration.md) | [app-service code-migration](references/services/app-service/code-migration.md)
4. **Ask User** — "Migration complete. Test locally or deploy to Azure?"
5. **Hand off** to azure-prepare for infrastructure, testing, and deployment

Track progress in `migration-status.md` — see [workflow-details.md](references/workflow-details.md).

<!-- chapter:end slug=azure-cloud-migrate -->

---

<!-- chapter:begin slug=azure-compliance position=14 -->

## 14. azure-compliance

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-compliance/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-compliance.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (15), referenced from this skill's directory:
  - `references/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/auth-best-practices.md
  - `references/azqr-recommendations.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/azqr-recommendations.md
  - `references/azqr-remediation-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/azqr-remediation-patterns.md
  - `references/azure-keyvault-expiration-audit.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/azure-keyvault-expiration-audit.md
  - `references/azure-quick-review.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/azure-quick-review.md
  - `references/azure-resource-graph.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/azure-resource-graph.md
  - `references/sdk/azure-keyvault-certificates-rust.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-keyvault-certificates-rust.md
  - `references/sdk/azure-keyvault-keys-rust.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-keyvault-keys-rust.md
  - `references/sdk/azure-keyvault-keys-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-keyvault-keys-ts.md
  - `references/sdk/azure-keyvault-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-keyvault-py.md
  - `references/sdk/azure-keyvault-secrets-rust.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-keyvault-secrets-rust.md
  - `references/sdk/azure-keyvault-secrets-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-keyvault-secrets-ts.md
  - `references/sdk/azure-security-keyvault-keys-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-security-keyvault-keys-dotnet.md
  - `references/sdk/azure-security-keyvault-keys-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-security-keyvault-keys-java.md
  - `references/sdk/azure-security-keyvault-secrets-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compliance/references/sdk/azure-security-keyvault-secrets-java.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-compliance
description: "Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Compliance & Security Auditing

## Quick Reference

| Property | Details |
|---|---|
| Best for | Compliance scans, security audits, Key Vault expiration checks |
| Primary capabilities | Comprehensive Resources Assessment, Key Vault Expiration Monitoring |
| MCP tools | azqr, subscription and resource group listing, Key Vault item inspection |

## When to Use This Skill

- Run azqr or Azure Quick Review for compliance assessment
- Validate Azure resource configuration against best practices
- Identify orphaned or misconfigured resources
- Audit Key Vault keys, secrets, and certificates for expiration

## Skill Activation Triggers

Activate this skill when user wants to:
- Check Azure compliance or best practices
- Assess Azure resources for configuration issues
- Run azqr or Azure Quick Review
- Identify orphaned or misconfigured resources
- Review Azure security posture
- "Show me expired certificates/keys/secrets in my Key Vault"
- "Check what's expiring in the next 30 days"
- "Audit my Key Vault for compliance"
- "Find secrets without expiration dates"
- "Check certificate expiration dates"

## Prerequisites

- Authentication: user is logged in to Azure via `az login`
- Permissions to read resource configuration and Key Vault metadata

## Assessments

| Assessment | Reference |
|------------|-----------|
| Comprehensive Compliance (azqr) | [references/azure-quick-review.md](references/azure-quick-review.md) |
| Key Vault Expiration | [references/azure-keyvault-expiration-audit.md](references/azure-keyvault-expiration-audit.md) |
| Resource Graph Queries | [references/azure-resource-graph.md](references/azure-resource-graph.md) |

## MCP Tools

| Tool | Purpose |
|------|---------|
| `mcp_azure_mcp_extension_azqr` | Run azqr compliance scans |
| `mcp_azure_mcp_subscription_list` | List available subscriptions |
| `mcp_azure_mcp_group_list` | List resource groups |
| `keyvault_key_list` | List all keys in vault |
| `keyvault_key_get` | Get key details including expiration |
| `keyvault_secret_list` | List all secrets in vault |
| `keyvault_secret_get` | Get secret details including expiration |
| `keyvault_certificate_list` | List all certificates in vault |
| `keyvault_certificate_get` | Get certificate details including expiration |

## Assessment Workflow

1. Select scope (subscription or resource group) for Comprehensive Resources Assessment.
2. Run azqr and capture output artifacts.
3. Analyze Scan Results and summarize findings and recommendations.
4. Review Key Vault Expiration Monitoring output for keys, secrets, and certificates.
5. Classify issues and propose remediation or fix steps for each finding.

### Priority Classification

| Priority | Guidance |
|---|---|
| Critical | Immediate remediation required for high-impact exposure |
| High | Resolve within days to reduce risk |
| Medium | Plan a resolution in the next sprint |
| Low | Track and fix during regular maintenance |

## Error Handling

| Error | Message | Remediation |
|---|---|---|
| Authentication required | "Please login" | Run `az login` and retry |
| Access denied | "Forbidden" | Confirm permissions and fix role assignments |
| Missing resource | "Not found" | Verify subscription and resource group selection |

## Best Practices

- Run compliance scans on a regular schedule (weekly or monthly)
- Track findings over time and verify remediation effectiveness
- Separate compliance reporting from remediation execution
- Keep Key Vault expiration policies documented and enforced

## SDK Quick References

For programmatic Key Vault access, see the condensed SDK guides:

- **Key Vault (Python)**: [Secrets/Keys/Certs](references/sdk/azure-keyvault-py.md)
- **Secrets**: [TypeScript](references/sdk/azure-keyvault-secrets-ts.md) | [Rust](references/sdk/azure-keyvault-secrets-rust.md) | [Java](references/sdk/azure-security-keyvault-secrets-java.md)
- **Keys**: [.NET](references/sdk/azure-security-keyvault-keys-dotnet.md) | [Java](references/sdk/azure-security-keyvault-keys-java.md) | [TypeScript](references/sdk/azure-keyvault-keys-ts.md) | [Rust](references/sdk/azure-keyvault-keys-rust.md)
- **Certificates**: [Rust](references/sdk/azure-keyvault-certificates-rust.md)

<!-- chapter:end slug=azure-compliance -->

---

<!-- chapter:begin slug=azure-compute position=15 -->

## 15. azure-compute

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-compute/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-compute.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (40), referenced from this skill's directory:
  - `references/retail-prices-api.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/references/retail-prices-api.md
  - `references/vm-families.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/references/vm-families.md
  - `references/vm-quotas.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/references/vm-quotas.md
  - `references/vmss-guide.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/references/vmss-guide.md
  - `workflows/capacity-reservation/capacity-reservation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/capacity-reservation/capacity-reservation.md
  - `workflows/capacity-reservation/references/association-disassociation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/capacity-reservation/references/association-disassociation.md
  - `workflows/capacity-reservation/references/capacity-reservation-overview.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/capacity-reservation/references/capacity-reservation-overview.md
  - `workflows/essential-machine-management/essential-machine-management.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/essential-machine-management/essential-machine-management.md
  - `workflows/essential-machine-management/references/emm-enable-flow-portal-guidance.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/essential-machine-management/references/emm-enable-flow-portal-guidance.md
  - `workflows/essential-machine-management/references/emm-enable-flow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/essential-machine-management/references/emm-enable-flow.md
  - `workflows/essential-machine-management/references/emm-overview.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/essential-machine-management/references/emm-overview.md
  - `workflows/essential-machine-management/references/emm-prerequisites.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/essential-machine-management/references/emm-prerequisites.md
  - `workflows/vm-creator/examples/bicep/main.bicep` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/examples/bicep/main.bicep
  - `workflows/vm-creator/examples/bicep/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/examples/bicep/README.md
  - `workflows/vm-creator/examples/terraform/main.tf` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/examples/terraform/main.tf
  - `workflows/vm-creator/examples/terraform/outputs.tf` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/examples/terraform/outputs.tf
  - `workflows/vm-creator/examples/terraform/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/examples/terraform/README.md
  - `workflows/vm-creator/examples/terraform/variables.tf` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/examples/terraform/variables.tf
  - `workflows/vm-creator/references/delivery-options/github-pr.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/references/delivery-options/github-pr.md
  - `workflows/vm-creator/references/delivery-options/index.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/references/delivery-options/index.md
  - `workflows/vm-creator/references/delivery-options/print.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/references/delivery-options/print.md
  - `workflows/vm-creator/references/delivery-options/save-local.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/references/delivery-options/save-local.md
  - `workflows/vm-creator/references/depth-probe/beginner.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/references/depth-probe/beginner.md
  - `workflows/vm-creator/references/depth-probe/cost-deep.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-compute/workflows/vm-creator/references/depth-probe/cost-deep.md
  - …and 16 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-compute

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-compute
description: "Azure VM/VMSS router. WHEN: create / provision / deploy / spin-up VM, recommend VM size, compare VM pricing, VMSS, scale set, autoscale, burstable, lightweight server, website, backend, GPU, machine learning, HPC simulation, dev/test, workload, family, load balancer, Flexible orchestration, Uniform orchestration, cost estimate, capacity reservation (CRG), reserve, guarantee capacity, pre-provision, CRG association, CRG disassociation, machine enrollment (EMM), Essential Machine Management, monitor. PREFER OVER mcp__azure__get_azure_bestpractices for VM create intents — use compute_vm_list-skus / compute_vm_list-images / compute_vm_check-quota."
license: MIT
metadata:
  author: Microsoft
  version: "2.5.1"
---

# Azure Compute Skill

Routes Azure VM and Virtual Machine Scale Set (VMSS) requests to the right workflow.

## When to Use This Skill

- User wants to **recommend, compare, or price** a VM or VMSS
- User wants to **create, provision, or deploy** a VM or VMSS
- User asks about **Capacity Reservation Groups** (CRG) — reserve, guarantee capacity, pre-provision
- User asks about **Essential Machine Management** (EMM) — machine enrollment, monitor

**Disambiguate with `azure-prepare`:** if the user wants to deploy an **application** (Docker service, web app, API, serverless workload), route to `azure-prepare`. `vm-creator` is for **bare VM/VMSS infrastructure** only.

## Routing

**Mandatory workflow-first routing:** never route directly to `references/*` files. First classify the user intent below, open the matched workflow file, then load only the reference files that workflow requests. Reference files are supporting material, not entry points. If the intent is unclear, ask a clarifying question to disambiguate between the workflows.

| Workflow | File | Use when |
|---|---|---|
| **VM Recommender** | [vm-recommender.md](workflows/vm-recommender/vm-recommender.md) | User asks which VM/VMSS to choose, whether to use VMSS/autoscaling, wants pricing, or wants to compare options |
| **VM Creator** | [vm-creator.md](workflows/vm-creator/vm-creator.md) | User wants to create, provision, or deploy a bare VM or VMSS (not an app deployment) |
| **Capacity Reservation** | [capacity-reservation.md](workflows/capacity-reservation/capacity-reservation.md) | User needs to reserve / guarantee VM capacity (CRG create / associate / disassociate) |
| **Essential Machine Management** | [essential-machine-management.md](workflows/essential-machine-management/essential-machine-management.md) | User asks about EMM / machine enrollment / monitor |

<!-- chapter:end slug=azure-compute -->

---

<!-- chapter:begin slug=azure-cost position=16 -->

## 16. azure-cost

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-cost/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-cost.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (22), referenced from this skill's directory:
  - `cost-forecast/error-handling.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-forecast/error-handling.md
  - `cost-forecast/examples.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-forecast/examples.md
  - `cost-forecast/guardrails.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-forecast/guardrails.md
  - `cost-forecast/request-body-schema.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-forecast/request-body-schema.md
  - `cost-forecast/workflow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-forecast/workflow.md
  - `cost-optimization/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/auth-best-practices.md
  - `cost-optimization/azure-aks-anomalies.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/azure-aks-anomalies.md
  - `cost-optimization/azure-aks-cost-addon.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/azure-aks-cost-addon.md
  - `cost-optimization/azure-quick-review.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/azure-quick-review.md
  - `cost-optimization/azure-resource-graph.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/azure-resource-graph.md
  - `cost-optimization/report-template.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/report-template.md
  - `cost-optimization/sdk/azure-resource-manager-redis-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/sdk/azure-resource-manager-redis-dotnet.md
  - `cost-optimization/services/redis/azure-cache-for-redis.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/services/redis/azure-cache-for-redis.md
  - `cost-optimization/services/storage/azure-storage.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/services/storage/azure-storage.md
  - `cost-optimization/workflow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-optimization/workflow.md
  - `cost-query/dimensions-by-scope.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-query/dimensions-by-scope.md
  - `cost-query/error-handling.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-query/error-handling.md
  - `cost-query/examples.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-query/examples.md
  - `cost-query/guardrails.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-query/guardrails.md
  - `cost-query/request-body-schema.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-query/request-body-schema.md
  - `cost-query/workflow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/cost-query/workflow.md
  - `references/tools-and-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-cost/references/tools-and-best-practices.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-cost
description: "Azure cost management: query costs, forecast spending, optimize to reduce waste. WHEN: \"Azure costs\", \"Azure bill\", \"cost breakdown\", \"how much am I spending\", \"forecast spending\", \"optimize costs\", \"reduce spending\", \"orphaned resources\", \"rightsize VMs\", \"cost spike\", \"reduce storage costs\", \"AKS cost\". DO NOT USE FOR: deploying resources, provisioning, diagnostics, or security audits."
license: MIT
metadata:
  author: Microsoft
  version: "1.3.1"
---

# Azure Cost Management Skill

Query historical costs, forecast future spending, optimize to reduce waste.

## Routing

| User Intent | Workflow |
|-------------|----------|
| Understand current costs | [Cost Query](cost-query/workflow.md) |
| Reduce costs / find waste | [Cost Optimization](cost-optimization/workflow.md) |
| Project future costs | [Cost Forecast](cost-forecast/workflow.md) |

## Quick Reference

| Property | Value |
|----------|-------|
| **Query API** | `POST {scope}/providers/Microsoft.CostManagement/query?api-version=2023-11-01` |
| **Forecast API** | `POST {scope}/providers/Microsoft.CostManagement/forecast?api-version=2023-11-01` |
| **Required Role** | Cost Management Reader + Monitoring Reader + Reader (on target scope) |

## Scope Patterns

- Subscription: `/subscriptions/<id>`
- Resource Group: `/subscriptions/<id>/resourceGroups/<name>`
- Management Group: `/providers/Microsoft.Management/managementGroups/<id>`
- Billing Account: `/providers/Microsoft.Billing/billingAccounts/<id>`

## Service-Specific Optimization

- [Redis](cost-optimization/services/redis/azure-cache-for-redis.md)
- [Storage](cost-optimization/services/storage/azure-storage.md)

## References

- [MCP Tools, Best Practices, Safety](references/tools-and-best-practices.md)
- [SDK: Redis .NET](cost-optimization/sdk/azure-resource-manager-redis-dotnet.md)

<!-- chapter:end slug=azure-cost -->

---

<!-- chapter:begin slug=azure-deploy position=17 -->

## 17. azure-deploy

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-deploy/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-deploy.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (40), referenced from this skill's directory:
  - `references/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/auth-best-practices.md
  - `references/global-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/global-rules.md
  - `references/live-role-verification.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/live-role-verification.md
  - `references/pre-deploy-checklist.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/pre-deploy-checklist.md
  - `references/recipes/azcli/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azcli/errors.md
  - `references/recipes/azcli/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azcli/README.md
  - `references/recipes/azcli/verify.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azcli/verify.md
  - `references/recipes/azd/ef-migrations.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/ef-migrations.md
  - `references/recipes/azd/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/errors.md
  - `references/recipes/azd/functions-deploy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/functions-deploy.md
  - `references/recipes/azd/post-deployment.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/post-deployment.md
  - `references/recipes/azd/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/README.md
  - `references/recipes/azd/scripts/apply-migrations.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/scripts/apply-migrations.ps1
  - `references/recipes/azd/scripts/apply-migrations.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/scripts/apply-migrations.sh
  - `references/recipes/azd/scripts/grant-and-migrate.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/scripts/grant-and-migrate.ps1
  - `references/recipes/azd/scripts/grant-and-migrate.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/scripts/grant-and-migrate.sh
  - `references/recipes/azd/sql-entra-auth.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/sql-entra-auth.md
  - `references/recipes/azd/sql-managed-identity.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/sql-managed-identity.md
  - `references/recipes/azd/verify.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/azd/verify.md
  - `references/recipes/bicep/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/bicep/errors.md
  - `references/recipes/bicep/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/bicep/README.md
  - `references/recipes/bicep/verify.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/bicep/verify.md
  - `references/recipes/cicd/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/cicd/errors.md
  - `references/recipes/cicd/examples/azdo-azd.yml` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-deploy/references/recipes/cicd/examples/azdo-azd.yml
  - …and 16 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-deploy

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-deploy
description: "Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: \"run azd up\", \"run azd deploy\", \"execute deployment\", \"push to production\", \"push to cloud\", \"go live\", \"ship it\", \"bicep deploy\", \"terraform apply\", \"publish to Azure\", \"launch on Azure\". DO NOT USE WHEN: \"create and deploy\", \"build and deploy\", \"create a new app\", \"set up infrastructure\", \"create and deploy to Azure using Terraform\" — use azure-prepare for these."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Deploy

> **AUTHORITATIVE GUIDANCE — MANDATORY COMPLIANCE**
>
> **PREREQUISITE**: The **azure-validate** skill **MUST** be invoked and completed with status `Validated` BEFORE executing this skill.

> **⛔ STOP — PREREQUISITE CHECK REQUIRED**
> Before proceeding, verify BOTH prerequisites are met:
>
> 1. **azure-prepare** was invoked and completed → `.azure/deployment-plan.md` exists
> 2. **azure-validate** was invoked and passed → plan status = `Validated`
>
> If EITHER is missing, **STOP IMMEDIATELY**:
> - No plan? → Invoke **azure-prepare** skill first
> - Status not `Validated`? → Invoke **azure-validate** skill first
>
> **⛔ DO NOT MANUALLY UPDATE THE PLAN STATUS**
>
> You are **FORBIDDEN** from changing the plan status to `Validated` yourself. Only the **azure-validate** skill is authorized to set this status after running actual validation checks. If you update the status without running validation, deployments will fail.
>
> **DO NOT ASSUME** the app is ready. **DO NOT SKIP** validation to save time. Skipping steps causes deployment failures. The complete workflow ensures success:
>
> `azure-prepare` → `azure-validate` → `azure-deploy`

## Triggers

Activate this skill when user wants to:
- Execute deployment of an already-prepared application (azure.yaml and infra/ exist)
- Push updates to an existing Azure deployment
- Run `azd up`, `azd deploy`, or `az deployment` on a prepared project
- Ship already-built code to production
- Deploy an application that already includes API Management (APIM) gateway infrastructure

> **Scope**: This skill executes deployments. It does not create applications, generate infrastructure code, or scaffold projects. For those tasks, use **azure-prepare**.

> **APIM / AI Gateway**: Use this skill to deploy applications whose APIM/AI gateway infrastructure was already created during **azure-prepare**. For creating or changing APIM resources, see [APIM deployment guide](https://learn.microsoft.com/azure/api-management/get-started-create-service-instance). For AI governance policies, invoke **azure-aigateway** skill.

## Rules

1. Run after azure-prepare and azure-validate
2. `.azure/deployment-plan.md` must exist with status `Validated`
3. **Pre-deploy checklist required** — [Pre-Deploy Checklist](references/pre-deploy-checklist.md)
4. ⛔ **Destructive actions require `ask_user`** — [global-rules](references/global-rules.md)
5. **Scope: deployment execution only** — This skill owns execution of `azd up`, `azd deploy`, `terraform apply`, and `az deployment` commands. These commands are run through this skill's error recovery and verification pipeline.

---

## Steps

| # | Action | Reference |
|---|--------|-----------|
| 1 | **Check Plan** — Read `.azure/deployment-plan.md`, verify status = `Validated` AND **Validation Proof** section is populated | `.azure/deployment-plan.md` |
| 2 | **Pre-Deploy Checklist** — MUST complete ALL steps | [Pre-Deploy Checklist](references/pre-deploy-checklist.md) |
| 3 | **Load Recipe** — Based on `recipe.type` in `.azure/deployment-plan.md` | [recipes/README.md](references/recipes/README.md) |
| 4 | **RBAC Health Check** — For Container Apps + ACR with managed identity: run `azd provision --no-prompt`, then verify `AcrPull` role has propagated before proceeding (see checklist) | [Pre-Deploy Checklist — Container Apps RBAC](references/pre-deploy-checklist.md#container-apps--acr--pre-deploy-rbac-health-check) |
| 5 | **Execute Deploy** — Follow recipe steps | Recipe README |
| 6 | **Post-Deploy** — Configure SQL managed identity and apply EF migrations if applicable | [Post-Deployment](references/recipes/azd/post-deployment.md) |
| 7 | **Handle Errors** — See recipe's `errors.md` | — |
| 8 | **Verify Success** — Confirm deployment completed and endpoints are accessible | [Verification](references/recipes/azd/verify.md) |
| 9 | **Live Role Verification** — Query Azure to confirm provisioned RBAC roles are correct and sufficient | [live-role-verification.md](references/live-role-verification.md) |
| 10 | **Report Results** — Present deployed endpoint URLs to the user as fully-qualified `https://` links | [Verification](references/recipes/azd/verify.md) |

> **⛔ URL FORMAT RULE**
>
> When presenting endpoint URLs to the user, you **MUST** always use fully-qualified URLs with the `https://` scheme (e.g. `https://myapp.azurewebsites.net`, not `myapp.azurewebsites.net`). Many Azure CLI commands return bare hostnames without a scheme — always prepend `https://` before presenting them.

> **⛔ VALIDATION PROOF CHECK**
>
> When checking the plan, verify the **Validation Proof** section (Section 7) contains actual validation results with commands run and timestamps. If this section is empty, validation was bypassed — invoke **azure-validate** skill first.

## SDK Quick References

- **Azure Developer CLI**: [azd](references/sdk/azd-deployment.md)
- **Azure Identity**: [Python](references/sdk/azure-identity-py.md) | [.NET](references/sdk/azure-identity-dotnet.md) | [TypeScript](references/sdk/azure-identity-ts.md) | [Java](references/sdk/azure-identity-java.md)

## MCP Tools

| Tool | Purpose |
|------|---------|
| `mcp_azure_mcp_subscription_list` | List available subscriptions |
| `mcp_azure_mcp_group_list` | List resource groups in subscription |
| `mcp_azure_mcp_azd` | Execute AZD commands |
| `azure__role` | List role assignments for live RBAC verification (step 9) |

## References

- [Troubleshooting](references/troubleshooting.md) - Common issues and solutions
- [Post-Deployment Steps](references/recipes/azd/post-deployment.md) - SQL + EF Core setup

<!-- chapter:end slug=azure-deploy -->

---

<!-- chapter:begin slug=azure-diagnostics position=18 -->

## 18. azure-diagnostics

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-diagnostics/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-diagnostics.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (48), referenced from this skill's directory:
  - `references/app-service/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/references/app-service/README.md
  - `references/azure-resource-graph.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/references/azure-resource-graph.md
  - `references/container-apps/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/references/container-apps/README.md
  - `references/functions/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/references/functions/README.md
  - `references/kql-queries.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/references/kql-queries.md
  - `scripts/aks-baseline.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/aks-baseline.ps1
  - `scripts/aks-baseline.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/aks-baseline.sh
  - `scripts/appservice-diagnostics.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/appservice-diagnostics.ps1
  - `scripts/appservice-diagnostics.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/appservice-diagnostics.sh
  - `scripts/containerapp-diagnostics.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/containerapp-diagnostics.ps1
  - `scripts/containerapp-diagnostics.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/containerapp-diagnostics.sh
  - `scripts/run-ig.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/run-ig.ps1
  - `scripts/run-ig.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/run-ig.sh
  - `scripts/test-messaging-connectivity.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/test-messaging-connectivity.ps1
  - `scripts/test-messaging-connectivity.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/scripts/test-messaging-connectivity.sh
  - `troubleshooting/aks/aks-troubleshooting.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/aks-troubleshooting.md
  - `troubleshooting/aks/general-diagnostics.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/general-diagnostics.md
  - `troubleshooting/aks/load-balancer-and-ingress.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/load-balancer-and-ingress.md
  - `troubleshooting/aks/network-policy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/network-policy.md
  - `troubleshooting/aks/networking.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/networking.md
  - `troubleshooting/aks/node-issues.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/node-issues.md
  - `troubleshooting/aks/pod-failures.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/pod-failures.md
  - `troubleshooting/aks/references/aks-mcp.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/references/aks-mcp.md
  - `troubleshooting/aks/references/command-flows.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-diagnostics/troubleshooting/aks/references/command-flows.md
  - …and 24 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-diagnostics

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-diagnostics
description: "Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, troubleshoot functions, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, service bus dead letter."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.5"
---

# Azure Diagnostics

> **AUTHORITATIVE GUIDANCE — MANDATORY COMPLIANCE**
>
> This document is the **official source** for debugging and troubleshooting Azure production issues. Follow these instructions to diagnose and resolve common Azure service problems systematically.

## Triggers

Activate this skill when user wants to:
- Debug or troubleshoot production issues
- Diagnose errors in Azure services
- Analyze application logs or metrics
- Fix image pull, cold start, or health probe issues
- Investigate why Azure resources are failing
- Find root cause of application errors
- Troubleshoot App Service issues (high CPU, deployment failures, crashes, slow responses, TLS/custom domains)
- Respond to prompts like "troubleshoot app service", "app service high CPU", or "app service deployment failure"
- Troubleshoot Azure Function Apps (invocation failures, timeouts, binding errors)
- Find the App Insights or Log Analytics workspace linked to a Function App
- Troubleshoot AKS clusters, nodes, pods, ingress, or Kubernetes networking issues
- Troubleshoot Azure VM connectivity issues (RDP/SSH failures, port 3389/22 timeouts, NSG or firewall blocking, credential resets)
- Troubleshoot Azure Messaging SDK issues (Event Hubs, Service Bus connection failures, AMQP errors, message lock issues)

## Rules

1. Start with systematic diagnosis flow
2. Use AppLens (MCP) for AI-powered diagnostics when available
3. Check resource health before deep-diving into logs
4. Select appropriate troubleshooting guide based on service type
5. Document findings and attempted remediation steps
6. Route AKS incidents to the dedicated AKS troubleshooting document

---

## Quick Diagnosis Flow

1. **Identify symptoms** - What's failing?
2. **Check resource health** - Is Azure healthy?
3. **Review logs** - What do logs show?
4. **Analyze metrics** - Performance patterns?
5. **Investigate recent changes** - What changed?

---

## Troubleshooting Guides by Service

| Service | Common Issues | Reference |
|---------|---------------|-----------|
| **Container Apps** | Image pull failures, cold starts, health probes, port mismatches | [container-apps/](references/container-apps/README.md) |
| **App Service** | High CPU, deployment failures, crashes, slow responses, TLS/custom domains | [app-service/](references/app-service/README.md) |
| **Function Apps** | App details, invocation failures, timeouts, binding errors, cold starts, missing app settings | [functions/](references/functions/README.md) |
| **AKS** | Cluster access, nodes, `kube-system`, scheduling, crash loops, ingress, DNS, upgrades | [AKS Troubleshooting](troubleshooting/aks/aks-troubleshooting.md) |
| **Compute** | VM RDP/SSH connectivity, NSG/firewall blocks, credential resets, VM agent/tooling issues | [VM Connectivity Troubleshooting](troubleshooting/compute/vm-troubleshooting.md) |
| **Messaging** | Event Hubs & Service Bus SDK errors, AMQP failures, message lock, connectivity | [Messaging Troubleshooting](troubleshooting/messaging/README.md) |

---

## Routing

- Keep Container Apps and Function Apps diagnostics in this parent skill.
- Route active AKS incidents, AKS-specific intake, evidence gathering, and remediation guidance to [AKS Troubleshooting](troubleshooting/aks/aks-troubleshooting.md).
- Route Azure VM RDP/SSH connectivity, NSG/firewall, credential reset, and VM agent troubleshooting to [VM Connectivity Troubleshooting](troubleshooting/compute/vm-troubleshooting.md).
- Route Azure Messaging SDK troubleshooting (Event Hubs, Service Bus) to [Messaging Troubleshooting](troubleshooting/messaging/README.md).

---

## Quick Reference

### Common Diagnostic Commands

```bash
# Check resource health
az resource show --ids RESOURCE_ID
# View activity log
az monitor activity-log list -g RG --max-events 20
# Container Apps logs
az containerapp logs show --name APP -g RG --follow
# Function App logs (query App Insights traces)
az monitor app-insights query --apps APP-INSIGHTS -g RG \
  --analytics-query "traces | where timestamp > ago(1h) | order by timestamp desc | take 50"
```

### AppLens (MCP Tools)

For AI-powered diagnostics, use:
```
mcp_azure_mcp_applens
  intent: "diagnose issues with <resource-name>"
  command: "diagnose"
  parameters:
    resourceId: "<resource-id>"

Provides:
- Automated issue detection
- Root cause analysis
- Remediation recommendations
```

### Azure Monitor (MCP Tools)

For querying logs and metrics:
```
mcp_azure_mcp_monitor
  intent: "query logs for <resource-name>"
  command: "logs_query"
  parameters:
    workspaceId: "<workspace-id>"
    query: "<KQL-query>"
```

See [kql-queries.md](references/kql-queries.md) for common diagnostic queries.

---

## Check Azure Resource Health

### Using MCP

```
mcp_azure_mcp_resourcehealth
  intent: "check health status of <resource-name>"
  command: "get"
  parameters:
    resourceId: "<resource-id>"
```

### Using CLI

```bash
# Check specific resource health
az resource show --ids RESOURCE_ID

# Check recent activity
az monitor activity-log list -g RG --max-events 20
```

---

## References

- [KQL Query Library](references/kql-queries.md)
- [Azure Resource Graph Queries](references/azure-resource-graph.md)
- [App Service Troubleshooting](references/app-service/README.md)
- [Function Apps Troubleshooting](references/functions/README.md)
- [VM Connectivity Troubleshooting](troubleshooting/compute/vm-troubleshooting.md)
- [Messaging Troubleshooting](troubleshooting/messaging/README.md)

<!-- chapter:end slug=azure-diagnostics -->

---

<!-- chapter:begin slug=azure-enterprise-infra-planner position=19 -->

## 19. azure-enterprise-infra-planner

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-enterprise-infra-planner/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-enterprise-infra-planner.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (39), referenced from this skill's directory:
  - `references/bicep-generation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/bicep-generation.md
  - `references/constraints/ai-ml.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/ai-ml.md
  - `references/constraints/compute-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/compute-apps.md
  - `references/constraints/compute-infra.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/compute-infra.md
  - `references/constraints/data-analytics.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/data-analytics.md
  - `references/constraints/data-relational.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/data-relational.md
  - `references/constraints/messaging.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/messaging.md
  - `references/constraints/monitoring.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/monitoring.md
  - `references/constraints/networking-connectivity.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/networking-connectivity.md
  - `references/constraints/networking-core.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/networking-core.md
  - `references/constraints/networking-traffic.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/networking-traffic.md
  - `references/constraints/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/README.md
  - `references/constraints/security.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/constraints/security.md
  - `references/deployment.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/deployment.md
  - `references/pairing-checks.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/pairing-checks.md
  - `references/phases/1-extract-insights.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/phases/1-extract-insights.md
  - `references/phases/2-research-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/phases/2-research-best-practices.md
  - `references/phases/3-research-resources.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/phases/3-research-resources.md
  - `references/phases/4-generate-plan.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/phases/4-generate-plan.md
  - `references/phases/5-verify.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/phases/5-verify.md
  - `references/phases/6-generate-iac.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/phases/6-generate-iac.md
  - `references/phases/7-deploy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/phases/7-deploy.md
  - `references/resources/ai-ml.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/resources/ai-ml.md
  - `references/resources/compute-apps.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-enterprise-infra-planner/references/resources/compute-apps.md
  - …and 15 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-enterprise-infra-planner

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-enterprise-infra-planner
description: "Architect and provision enterprise Azure infrastructure from workload descriptions. For cloud architects and platform engineers planning networking, identity, security, compliance, and multi-resource topologies with WAF alignment. Generates Bicep or Terraform directly (no azd). WHEN: 'plan Azure infrastructure', 'architect Azure landing zone', 'design hub-spoke network', 'plan multi-region DR topology', 'set up VNets firewalls and private endpoints', 'subscription-scope Bicep deployment', 'Azure Backup for VM workloads'. PREFER azure-prepare FOR app-centric workflows."
license: MIT
metadata:
  author: Microsoft
  version: "1.3.1"
---

# Azure Enterprise Infra Planner

## When to Use This Skill

Activate this skill when user wants to:
- Plan enterprise Azure infrastructure from a workload or architecture description
- Architect a landing zone, hub-spoke network, or multi-region topology
- Design networking infrastructure: VNets, subnets, firewalls, private endpoints, VPN gateways
- Plan identity, RBAC, and compliance-driven infrastructure
- Generate Bicep or Terraform for subscription-scope or multi-resource-group deployments
- Plan disaster recovery, failover, or cross-region high-availability topologies

## Quick Reference

| Property | Details |
|---|---|
| MCP tools | `insights_get`, `get_azure_bestpractices_get`, `wellarchitectedframework_serviceguide_get`, `microsoft_docs_fetch`, `microsoft_docs_search`, `bicepschema_get` |
| CLI commands | `az deployment group create`, `az bicep build`, `az resource list`, `terraform init`, `terraform plan`, `terraform validate`, `terraform apply` |
| Output schema | [schema.md](references/schema.md) |
| Key references | [workflow.md](references/workflow.md), [waf-checklist.md](references/waf-checklist.md), [resources/](references/resources/README.md), [constraints/](references/constraints/README.md) |

## Workflow (Start Here)

Follow the step-by-step instructions in [workflow.md](references/workflow.md) to execute the 7 phases of infrastructure planning and provisioning.

## MCP Tools

| Tool | Purpose |
|------|---------|
| `insights_get` | Retrieve insights about the user's existing Azure environment to guide planning decisions |
| `get_azure_bestpractices_get` | Azure best practices for code generation, operations, and deployment |
| `wellarchitectedframework_serviceguide_get` | WAF service guide for a specific Azure service |
| `microsoft_docs_search` | Search Microsoft Learn for relevant documentation chunks |
| `microsoft_docs_fetch` | Fetch full content of a Microsoft Learn page by URL |
| `bicepschema_get` | Bicep schema definition for any Azure resource type (latest API version) |

## Error Handling

| Error | Cause | Fix |
|---|---|---|
| MCP tool error or not available | Tool call timeout, connection error, or tool doesn't exist | Retry once; fall back to reference files and notify user if unresolved |
| Plan approval missing | `meta.status` is not `approved` | Stop and prompt user for approval before IaC generation or deployment |
| IaC validation failure | `az bicep build` or `terraform validate` returns errors | Fix the generated code and re-validate; notify user if unresolved |
| Pairing constraint violation | Incompatible SKU or resource combination | Fix in plan before proceeding to IaC generation |
| Infra plan or IaC files not found | Files written to wrong location or not created | Verify files exist at `<project-root>/.azure/` and `<project-root>/infra/`; if missing, re-create the files by following [workflow.md](references/workflow.md) exactly |

<!-- chapter:end slug=azure-enterprise-infra-planner -->

---

<!-- chapter:begin slug=azure-kubernetes-app-deploy position=20 -->

## 20. azure-kubernetes-app-deploy

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-kubernetes-app-deploy.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (41), referenced from this skill's directory:
  - `knowledge-packs/frameworks/aspnet-core.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/aspnet-core.md
  - `knowledge-packs/frameworks/django.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/django.md
  - `knowledge-packs/frameworks/express.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/express.md
  - `knowledge-packs/frameworks/fastapi.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/fastapi.md
  - `knowledge-packs/frameworks/flask.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/flask.md
  - `knowledge-packs/frameworks/go.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/go.md
  - `knowledge-packs/frameworks/nestjs.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/nestjs.md
  - `knowledge-packs/frameworks/nextjs.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/nextjs.md
  - `knowledge-packs/frameworks/spring-boot.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/knowledge-packs/frameworks/spring-boot.md
  - `phases/quick-deploy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/phases/quick-deploy.md
  - `references/base-images.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/references/base-images.md
  - `references/detection.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/references/detection.md
  - `references/rollback.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/references/rollback.md
  - `references/safeguards.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/references/safeguards.md
  - `references/workload-identity.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/references/workload-identity.md
  - `templates/dockerfiles/dotnet.Dockerfile` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/dotnet.Dockerfile
  - `templates/dockerfiles/dotnet.dockerignore` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/dotnet.dockerignore
  - `templates/dockerfiles/go.Dockerfile` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/go.Dockerfile
  - `templates/dockerfiles/go.dockerignore` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/go.dockerignore
  - `templates/dockerfiles/java.Dockerfile` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/java.Dockerfile
  - `templates/dockerfiles/java.dockerignore` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/java.dockerignore
  - `templates/dockerfiles/node.Dockerfile` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/node.Dockerfile
  - `templates/dockerfiles/node.dockerignore` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/node.dockerignore
  - `templates/dockerfiles/python.Dockerfile` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-app-deploy/templates/dockerfiles/python.Dockerfile
  - …and 17 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-kubernetes-app-deploy

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-kubernetes-app-deploy
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
description: "Use when deploying an existing web application or API to an already-running Azure Kubernetes Service cluster. Detects the framework, generates a Dockerfile and Kubernetes manifests, validates against AKS Deployment Safeguards, and deploys with verification. WHEN: deploy app to AKS, deploy to existing AKS cluster, containerize app for Kubernetes, generate K8s manifests for Azure, set up CI/CD for AKS, my AKS deployment is failing safeguard checks, I have a Django/Express/Spring Boot app to run on AKS. DO NOT USE FOR: creating or provisioning an AKS cluster (use azure-kubernetes), assessing migration to AKS Automatic (use azure-kubernetes-automatic-readiness), or deploying to non-AKS targets like Web Apps, Container Apps, or Functions."
---

# Deploy to AKS

**Use when:** deploying a web app/API to AKS; containerizing for Kubernetes; generating manifests; AKS CI/CD; DS001–DS013 failures.

**Not for:** provisioning clusters (`azure-kubernetes`), AKS Automatic readiness (`azure-kubernetes-automatic-readiness`), non-AKS targets.

## Workflow

Requires: existing AKS cluster, `az login`, `kubectl` configured. Follow `phases/quick-deploy.md`. On failure: `references/rollback.md`.

## References

- [detection.md](./references/detection.md) — framework/port/health detection
- [safeguards.md](./references/safeguards.md) — DS001-DS013 checklist
- [workload-identity.md](./references/workload-identity.md) — Workload Identity setup
- [rollback.md](./references/rollback.md) — recovery procedures
- [base-images.md](./references/base-images.md) — base image policy and `<LATEST_STABLE_*>` resolution

## Knowledge Packs

Load `knowledge-packs/frameworks/<framework>.md` per detected framework. Available: `spring-boot`, `express`, `nextjs`, `fastapi`, `django`, `nestjs`, `aspnet-core`, `go`, `flask`

## Templates

`templates/` (dockerfiles/, k8s/, github-actions/, mermaid/).

<!-- chapter:end slug=azure-kubernetes-app-deploy -->

---

<!-- chapter:begin slug=azure-kubernetes-automatic-readiness position=21 -->

## 21. azure-kubernetes-automatic-readiness

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-kubernetes/azure-kubernetes-automatic-readiness/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-automatic-readiness/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-kubernetes-automatic-readiness.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (4), referenced from this skill's directory:
  - `references/common-fixes.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-automatic-readiness/references/common-fixes.md
  - `references/constraint-spec-v1.yaml` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-automatic-readiness/references/constraint-spec-v1.yaml
  - `references/mcp-integration.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-automatic-readiness/references/mcp-integration.md
  - `references/migration-guide-summary.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/azure-kubernetes-automatic-readiness/references/migration-guide-summary.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-kubernetes-automatic-readiness
license: MIT
metadata:
  author: Microsoft
  version: "1.0.1"
description: "Assess Kubernetes workloads and cluster configuration for AKS Automatic compatibility. Identifies incompatibilities, generates fixes, and guides migration from AKS Standard to AKS Automatic. WHEN: migrate to AKS Automatic, check AKS Automatic readiness, validate manifests for Automatic, assess cluster for Automatic compatibility, fix deployment for Automatic compatibility, identify AKS Automatic migration blockers, is my cluster ready for AKS Automatic."
---

# AKS Automatic Readiness Assessment

> **AUTHORITATIVE GUIDANCE — MANDATORY COMPLIANCE**
>
> This skill assesses existing AKS clusters or local manifests for AKS Automatic compatibility.
> For creating a new AKS Automatic cluster, use the `azure-kubernetes` skill instead.
> See [constraint spec](./references/constraint-spec-v1.yaml) for all safeguard rules, [common fixes](./references/common-fixes.md) for YAML patterns, [migration guide](./references/migration-guide-summary.md) for end-to-end steps, and [MCP integration](./references/mcp-integration.md) for tool details and fallback handling.

You are an AKS Automatic compatibility assessment agent. Your job is to evaluate whether Kubernetes workloads and cluster configurations are compatible with [AKS Automatic](https://learn.microsoft.com/en-us/azure/aks/intro-aks-automatic), identify issues, and help users fix them.

AKS Automatic enforces **Deployment Safeguards** (21 active policies, some deny, some warn only), **Pod Security Standards** (Baseline mandatory, Restricted optional), **2 active webhook mutators** that auto-fix certain fields at admission (resource-requests defaults and anti-affinity/topology-spread), and **23 cluster-level configuration requirements**.

## Quick Reference
| Property | Value |
|----------|-------|
| Best for | AKS Automatic migration readiness and manifest validation |
| MCP Tools | `mcp_azure_mcp_aks` |
| Related skills | azure-kubernetes (cluster creation), azure-diagnostics (live troubleshooting), azure-validate (readiness checks) |

## When to Use This Skill
- "Can I migrate to AKS Automatic?"
- "Check my cluster readiness for Automatic"
- "Validate manifests against AKS Automatic constraints"
- "Fix my deployment for Automatic compatibility"
- "Identify AKS Automatic migration blockers"
- Any mention of AKS Automatic + (migration | readiness | compatibility | assessment | validation)

## Routing Rules

### Route to `azure-kubernetes` instead:
- "Create an AKS cluster" / "What are AKS best practices?" / "How do I deploy to AKS?"
- General cluster creation, configuration, scaling, or AKS operations

### Route to `azure-diagnostics` instead:
- "My pod is crashing" / "Debug my AKS cluster" / "Why is my deployment failing?"
- Live troubleshooting, debugging, error diagnosis on a running cluster

## Guardrails — READ FIRST

1. **Read-only**: NEVER modify cluster state. Assessment is read-only. Do not run `kubectl apply`, `az aks update`, or any command that changes the cluster.
2. **No secrets**: Do NOT transmit, display, or include in diffs: Secret data values, ConfigMap data values, environment variable values from `valueFrom.secretKeyRef`, service account tokens, or connection strings.
3. **User approval for file changes**: Present every fix as a diff. The user must explicitly accept before you write to any file.
4. **Scope boundaries**: Route cluster creation/deletion questions → `azure-kubernetes` skill. Route live troubleshooting → `azure-diagnostics` skill.

## MCP Tools
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `mcp_azure_mcp_aks` | AKS MCP entry point — call `discover` first, then use the assessment action name returned in the response | `subscriptionId`, `resourceGroupName`, `resourceName`, `scope` |

## Workflow

### Step 1: Determine Scope

Ask the user what they want to assess:

**Option A — Cluster-connected assessment (via AKS MCP)**
Use when the user has a connected cluster context (subscription + resource group + cluster name).

**Option B — Offline manifest validation**
Use when the user has local Kubernetes manifests, Helm charts, or Kustomize overlays in their workspace. Search for files containing `apiVersion:` and `kind:` matching Deployment, StatefulSet, DaemonSet, Job, CronJob, Pod, Service, PodDisruptionBudget, or StorageClass. For Helm charts, look for `Chart.yaml` and rendered templates under `templates/`.

**Option C — Single manifest check**
If the user pastes or points to a single YAML manifest, validate it directly without asking for scope.

### Step 2: Run Assessment

#### Cluster-Connected Mode

Call the AKS MCP tool — this is the preferred path. Always call `discover` first to get the available actions, then use the assessment action name returned in the response:

```javascript
// Step 1: Discover available actions
mcp_azure_mcp_aks({ action: "discover" })

// Step 2: Use the assessment action name from the discover response
mcp_azure_mcp_aks({
  action: "<action-from-discover>",
  subscriptionId: "<subscription-id>",
  resourceGroupName: "<resource-group>",
  resourceName: "<cluster-name>",
  scope: {
    excludeNamespaces: ["kube-system", "gatekeeper-system"],
    workloadTypes: ["Deployment", "StatefulSet", "DaemonSet", "CronJob", "Job"]
  }
})
```

**Required permissions:**
- `Microsoft.ContainerService/managedClusters/read`
- `Microsoft.ContainerService/managedClusters/listClusterUserCredential/action`

For large clusters (500+ workloads), the API may return HTTP 202 with a `Location` header. Poll the location URL using the `Retry-After` interval until a 200 response is received.

**Parsing the MCP response:**
1. **`summary`** — aggregate counts: `compatible`, `requiresChanges`, `incompatible`, `autoFixed`, `totalWorkloads`, `clusterConfigIssues`
2. **`clusterConfiguration`** — cluster-level issues with `constraintId`, `severity`, `remediation` (az CLI commands), and `documentationUrl`
3. **`workloads[]`** — per-workload array, each with `name`, `namespace`, `kind`, `overallStatus`, and `issues[]`

Each issue in `workloads[].issues[]` contains: `constraintId`, `severity` (`incompatible`/`requiresChanges`/`autoFixed`/`informational`), `description`, `field` (JSON Pointer), `suggestedPatch` (JSON Patch for deterministic fixes), `remediationGuide` (for LLM-reasoned fixes).

#### Fallback Chain

```
1. MCP tool (mcp_azure_mcp_aks)  → preferred, live cluster data
   ↓ fails (tool not found — Azure MCP server not configured)
2. Offline validation            → works on local manifests without any cluster
```

If `mcp_azure_mcp_aks` is not available, inform the user:
> "The Azure MCP server is not configured in your editor. To enable live cluster assessment, follow the setup guide at [aka.ms/azure-mcp-setup](https://aka.ms/azure-mcp-setup). For now, I can validate your local manifests offline."

Then proceed to offline mode.

#### Offline Mode

Load the constraint spec from `references/constraint-spec-v1.yaml` and evaluate each manifest. The check field tells you what to check for and what fields to check. The fix field will tell you any allowed values and possible fixes. You should evaluate each of the safeguards with each of the manifests to determine if the manifests are compatible. Suggest any fixes that are needed.

Key Checks: 
**Per container** (containers, initContainers, ephemeralContainers):
- Resource requests/limits → `safeguard-container-resource-requests`
- Readiness and liveness probes → `safeguard-probes-configured` *(warning-only — not blocked at admission; treat as informational)*
- Image tag not `:latest` → `safeguard-images-no-latest`
- `securityContext.privileged` not true → `safeguard-no-privileged-containers`
- `capabilities.add` only adds allowed capabilities → `safeguard-container-capabilities`
- `seccompProfile` is RuntimeDefault/Localhost → `safeguard-allowed-seccomp-profiles`
- no `host` field in any container probes and lifecycle hooks → `safeguard-host-probes`

**Per pod spec:**
- `hostPID`/`hostIPC` not true → `safeguard-block-host-namespaces` (incompatible)
- `hostNetwork`/`hostPort` not true → `safeguard-host-network-ports` (incompatible)
- No `hostPath` volumes → `safeguard-no-host-path-volumes` (incompatible)

**Per workload type:**
- Deployments/StatefulSets with replicas > 1: podAntiAffinity or topologySpreadConstraints → `safeguard-pod-enforce-antiaffinity`
- StorageClass: CSI provisioner (not in-tree) → `safeguard-csi-driver-storage-class`


### Severity Classification

| Severity | Meaning | Action |
|----------|---------|--------|
| `incompatible` | Fundamental architecture issue; cannot run on Automatic without redesign | Must fix before migration — flag prominently |
| `requiresChanges` | Manifest changes needed; will be denied at admission | Generate fix diffs |
| `autoFixed` | AKS Automatic will mutate this at admission; no user action needed | Informational — show what will change |
| `informational` | No enforcement | Mention briefly |

### Step 3: Present Findings

Always start with the summary:

```
## AKS Automatic Readiness Assessment

| Status | Count |
|--------|-------|
| ✅ Compatible | X workloads |
| ⚠️ Requires changes | Y workloads |
| ❌ Incompatible | Z workloads |
| 🔧 Auto-fixed by Automatic | W workloads |
| 🏗️ Cluster config issues | N issues |
```

Grouping: ≤ 10 issues → list individually; > 10 → group by constraint ID. Always show **incompatible** first (migration blockers), then **requiresChanges**, then **autoFixed**, then cluster config.

Per-issue format:
```
### ❌ [constraint-id] — Short description
**Severity:** incompatible | requiresChanges
**Affected:** namespace/resource-name (Kind)
**Current:** <what the manifest has>
**Required:** <what AKS Automatic requires>
**Fix:** <remediation summary>
**Docs:** <documentation URL>
```

### Step 4: Offer Fixes

**Deterministic fixes** (have `suggestedPatch` — generate YAML diff directly):
- `safeguard-container-resource-requests` — add `resources.requests`
- `safeguard-container-capabilities` — remove `capabilities.add`
- `safeguard-allowed-seccomp-profiles` — patch only when `seccompProfile.type: Unconfined` is present, or when the MCP `suggestedPatch` explicitly requires a seccomp change
- `safeguard-enforce-apparmor` — add AppArmor annotation
- `safeguard-csi-driver-storage-class` — replace in-tree provisioner

Use patterns in `references/common-fixes.md` and generate a before/after diff. Starting resource values use safe defaults — VPA (enabled on Automatic) will auto-tune after deployment.

**LLM-reasoned fixes** (require app context; use `remediationGuide`):
- `safeguard-images-no-latest` — correct tag is user- and release-specific; ask the user: _"What specific version tag or SHA digest should I pin this image to?"_ Do not guess
- `safeguard-pod-enforce-antiaffinity` — needs app labels for selector
- `safeguard-no-host-path-volumes` — replacement depends on what hostPath is used for
- `safeguard-block-host-namespaces` — may require architecture redesign
- `safeguard-host-network-ports` — needs alternative networking approach

For incompatible findings (e.g., hostPath volumes), explain the issue and propose alternatives. For log-collection hostPath, suggest: Azure Monitor Container Insights (recommended, auto-enabled), Azure Files CSI volume, emptyDir, or sidecar pattern.

**Fix application flow:**
1. Generate the fix as a YAML diff
2. Show the diff with explanation
3. Wait for explicit approval: "apply", "edit", or "skip"
4. On approval, apply the change to the file
5. Move to the next finding

If the user says "fix all" or "apply all deterministic fixes", first generate a single combined diff containing all eligible `suggestedPatch`-based fixes, show that combined diff with an explanation, and wait for one explicit approval before applying any writes. After approval, apply the batched changes and then suggest re-validation.

### Step 5: Recommend Next Steps

**All issues resolved (or only autoFixed remaining):**
```
Your workloads are ready for AKS Automatic! Next steps:
1. Review auto-fixed items — AKS Automatic will mutate N fields at admission.
2. Apply cluster configuration changes (see cluster config issues above).
3. Perform the SKU switch — follow the migration guide.
4. Verify — after migration, check all workloads are running and healthy.
```
See `references/migration-guide-summary.md` for the full migration checklist.

**Incompatible findings remain:** List blockers and offer three options: redesign workloads, keep on a separate AKS Standard cluster, or use Automatic for compatible + Standard for incompatible workloads.

**Cluster config issues remain (Day-0 decisions):** API Server VNet Integration, node pool OS SKU (requires recreating system node pools), and ephemeral OS disks require a new cluster — redirect to `azure-kubernetes` skill for cluster creation help.

## Error Handling

| Error / Symptom | Likely Cause | Remediation |
|-----------------|--------------|-------------|
| MCP tool call fails or times out | Invalid credentials or subscription context | Verify `az login`, confirm active subscription with `az account show`; if MCP remains unavailable, continue with offline validation using local or exported manifests and the bundled constraint spec |
| HTTP 403 on assessment action | Missing permission | Ensure caller has sufficient RBAC access to read and assess the cluster via AKS APIs |
| API returns HTTP 202 | Large cluster (500+ workloads) — async operation | Poll the `Location` header URL using `Retry-After` interval |
| Helm chart uses Go templating — cannot evaluate | Template values not resolved | Ask user for rendered output (`helm template`) or values files |
| Constraint spec version mismatch | Skill bundles spec v1.1.1 (2026-03-15) | Note version in output; recommend re-running after spec update |

## Reference Files

| File | When to load |
|------|--------------|
| `references/constraint-spec-v1.yaml` | Always load for offline validation — all constraint IDs, severities, and fix patterns |
| `references/common-fixes.md` | When generating deterministic fixes — before/after YAML patterns |
| `references/migration-guide-summary.md` | When user asks about migration steps or after assessment is complete |
| `references/mcp-integration.md` | When troubleshooting MCP tool calls or debugging the fallback chain |

> ⚠️ **Warning:** This skill bundles **constraint spec v1.1.1** (2026-03-15), covering 23 cluster-level constraints, 21 active Deployment Safeguards policies (9 best practices policies, 12 Pod Security Standards policies), and 2 active mutators. Always note the spec version in assessment output.

<!-- chapter:end slug=azure-kubernetes-automatic-readiness -->

---

<!-- chapter:begin slug=azure-kubernetes position=22 -->

## 22. azure-kubernetes

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-kubernetes/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-kubernetes.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (5), referenced from this skill's directory:
  - `references/azure-aks-autoscaler.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/references/azure-aks-autoscaler.md
  - `references/azure-aks-rightsizing.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/references/azure-aks-rightsizing.md
  - `references/azure-aks-spot.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/references/azure-aks-spot.md
  - `references/azure-aks-vpa.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/references/azure-aks-vpa.md
  - `references/cli-reference.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kubernetes/references/cli-reference.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-kubernetes
license: MIT
metadata:
  author: Microsoft
  version: "1.2.2"
description: "Plan, create, and configure production-ready Azure Kubernetes Service (AKS) clusters. Covers Day-0 checklist, SKU selection (Automatic vs Standard), networking options (private API server, Azure CNI Overlay, egress configuration), security, and operations (autoscaling, upgrade strategy, cost analysis). WHEN: create AKS environment, provision AKS, enable AKS observability, design AKS networking, choose AKS SKU, secure AKS, optimize AKS, AKS spot nodes, AKS cluster-autoscaler, rightsize AKS pod, pod rightsizing, over-provisioned AKS pod, pod resource requests and limits, Vertical Pod Autoscaler, VPA recommendations."
---

# Azure Kubernetes Service

> **AUTHORITATIVE GUIDANCE — MANDATORY COMPLIANCE**
>
> This skill produces a **recommended AKS cluster configuration** based on user requirements, distinguishing **Day-0 decisions** (networking, API server — hard to change later) from **Day-1 features** (can enable post-creation). See [CLI reference](./references/cli-reference.md) for commands.

## Quick Reference
| Property | Value |
|----------|-------|
| Best for | AKS cluster planning and Day-0 decisions |
| MCP Tools | `mcp_azure_mcp_aks` |
| CLI | `az aks create`, `az aks show`, `kubectl get`, `kubectl describe` |
| Related skills | azure-kubernetes-app-deploy (deploy an app to an existing cluster), azure-diagnostics (troubleshooting AKS), azure-validate (readiness checks), azure-kubernetes-automatic-readiness (migrate existing cluster to AKS Automatic) |

## When to Use This Skill
Activate this skill when user wants to:
- Create a new AKS cluster
- Plan AKS cluster configuration for production workloads
- Design AKS networking (API server access, pod IP model, egress)
- Set up AKS identity and secrets management
- Configure AKS governance (Azure Policy, Deployment Safeguards)
- Enable AKS observability (Container Insights, Managed Prometheus, Grafana)
- Define AKS upgrade and patching strategy
- Understand AKS Automatic vs Standard SKU differences
- Get a Day-0 checklist for AKS cluster setup and configuration

> **Deploying an application to an existing cluster?** This skill provisions and
> configures the *cluster*. To containerize an app and deploy it to a cluster
> that already exists (Dockerfile + manifests + Deployment Safeguards), use the
> `azure-kubernetes-app-deploy` sub-skill instead.

## Rules
1. Start with the user's requirements for provisioning compute, networking, security, and other settings.
2. Use the `azure` MCP server and select `mcp_azure_mcp_aks` first to discover the exact AKS-specific MCP tools surfaced by the client. Choose the smallest discovered AKS tool that fits the task, and fall back to Azure CLI (`az aks`) only when the needed functionality is not exposed through the AKS MCP surface.
3. Determine if AKS Automatic or Standard SKU is more appropriate based on the user's need for control vs convenience. Default to AKS Automatic unless specific customizations are required.
4. Document decisions and rationale for cluster configuration choices, especially for Day-0 decisions that are hard to change later (networking, API server access).


## Required Inputs (Ask only what’s needed)
If the user is unsure, use safe defaults.
- AKS environment type: dev/test or production
- Region(s), availability zones, preferred node VM sizes
- Expected scale (node/cluster count, workload size)
- Networking requirements (API server access, pod IP model, ingress/egress control)
- Security and identity requirements, including image registry
- Upgrade and observability preferences
- Cost constraints

## Workflow

### 1. Cluster Type
- **AKS Automatic** (default): Best for most production workloads, provides a curated experience with pre-configured best practices for security, reliability, and performance. Use unless you have specific custom requirements for networking, autoscaling, or node pool configurations not supported by Node Auto-Provisioning (NAP).
- **AKS Standard**: Use if you need full control over environment configuration, which requires additional overhead to set up and manage.

### 2. Networking (Pod IP, Egress, Ingress, Dataplane)

**Pod IP Model** (Key Day-0 decision):
- **Azure CNI Overlay** (recommended): pod IPs from private overlay range, not VNet-routable, scales to large environments and good for most workloads
- **Azure CNI (VNet-routable)**: pod IPs directly from VNet (pod subnet or node subnet), use when pods must be directly addressable from VNet or on-prem
  - Docs: https://learn.microsoft.com/azure/aks/azure-cni-overlay

**Dataplane & Network Policy**:
- **Azure CNI powered by Cilium** (recommended): eBPF-based for high-performance packet processing, network policies, and observability

**Egress**:
- **Static Egress Gateway** for stable, predictable outbound IPs
- For restricted egress: UDR + Azure Firewall or NVA

**Ingress**:
- **App Routing addon with Gateway API** — recommended default for HTTP/HTTPS workloads
- **Istio service mesh with Gateway API** - for advanced traffic management, mTLS, canary releases
- **Application Gateway for Containers** — for L7 load balancing with WAF integration

**DNS**:
- Enable **LocalDNS** on all node pools for reliable, performant DNS resolution

### 3. Security
- Use **Microsoft Entra ID** everywhere (control plane, Workload Identity for pods, node access). Avoid static credentials.
- Azure Key Vault via **Secrets Store CSI Driver** for secrets
- Enable **Azure Policy** + **Deployment Safeguards**
- Enable **Encryption at rest** for etcd/API server; **in-transit** for node-to-node
- Allow only signed, policy-approved images (Azure Policy + Ratify), prefer **Azure Container Registry**
- **Isolation**: Use namespaces, network policies, scoped logging

### 4. Observability
- Use Managed Prometheus and Container Insights with Grafana for AKS observability (logs + metrics).
- Enable Diagnostic Settings to collect control plane logs and audit logs in a Log Analytics workspace for security monitoring and troubleshooting.
- For other monitoring and troubleshooting tools, use features like the Agentic CLI for AKS, Application Insights, Resource Health Center, AppLens detectors, and Azure Advisors.

### 5. Upgrades & Patching
- Configure **Maintenance Windows** for controlled upgrade timing
- Enable **auto-upgrades** for control plane and node OS to stay up-to-date with security patches and Kubernetes versions
- Consider **LTS versions** for enterprise stability (2-year support) by upgrading your AKS environment to the Premium tier
- **Fleet upgrades**: Use **AKS Fleet Manager** for staged rollout across test to production environments

### 6. Performance
- Use **Ephemeral OS disks** (`--node-osdisk-type Ephemeral`) for faster node startup
- Select **Azure Linux** as node OS (smaller footprint, faster boot)
- Enable **KEDA** for event-driven autoscaling beyond HPA

### 7. Node Pools & Compute
- **Dedicated system node pool**: At least 2 nodes, tainted for system workloads only (`CriticalAddonsOnly`)
- Enable **Node Auto Provisioning (NAP)** on all pools for cost savings and responsive scaling
- Use **latest generation SKUs (v5/v6)** for host-level optimizations
- **Avoid B-series VMs** — burstable SKUs cause performance/reliability issues
- Use SKUs with **at least 4 vCPUs** for production workloads
- Set **topology spread constraints** to distribute pods across hosts/zones per SLO

### 8. Reliability
- Deploy across **3 Availability Zones** (`--zones 1 2 3`)
- Use **Standard tier** for zone-redundant control plane + 99.95% SLA for API server availability
- Enable **Microsoft Defender for Containers** for runtime protection
- Configure **PodDisruptionBudgets** for all production workloads
- Use **topology spread constraints** to ensure pod distribution across failure domains

### 9. Cost Controls
- Use **Spot node pools** for batch/interruptible workloads (up to 90% savings)
- **Stop/Start** dev/test clusters: `az aks stop/start`
- Consider **Reserved Instances** or **Savings Plans** for steady-state workloads

**Deep-dive scenarios** — load only the relevant reference file:

| Scenario | Trigger Keywords | Reference |
|----------|-----------------|-----------|
| Pod Rightsizing | over-provisioned pods, CPU requests, memory requests, rightsize workloads | [azure-aks-rightsizing.md](./references/azure-aks-rightsizing.md) |
| VPA Setup | vertical pod autoscaler, VPA recommendations, VPA enable | [azure-aks-vpa.md](./references/azure-aks-vpa.md) |
| Cluster Autoscaler | idle nodes, CAS off, enable autoscaler, scale-down profile, node utilization | [azure-aks-autoscaler.md](./references/azure-aks-autoscaler.md) |
| Spot Node Pools | Spot VMs, Spot nodes, batch workloads, cheaper nodes | [azure-aks-spot.md](./references/azure-aks-spot.md) |

> **Disambiguation:** If a prompt matches multiple rows (e.g., "cheaper nodes" could suggest both Spot and autoscaler), prefer the most specific match. If ambiguous, ask the user to clarify their intent before loading a reference file.

## Guardrails / Safety
- Do not request or output secrets (tokens, keys).
- Do not ask the user to paste subscription IDs. Discover subscription and resource scope via MCP tools (e.g., list subscriptions, list resource groups) or `az account show` / `az account list` so the agent can resolve context without exposing identifiers.
- If requirements are ambiguous for day-0 critical decisions, ask the user clarifying questions. For day-1 enabled features, propose 2–3 safe options with tradeoffs and choose a conservative default.
- Do not promise zero downtime; advise workload safeguards (PDBs, probes, replicas) and staged upgrades along with best practices for reliability and performance.

## MCP Tools
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `mcp_azure_mcp_aks` | AKS MCP entry point used to discover the exact AKS-specific tools exposed by the client | Discover the callable AKS tool first, then use that tool's parameters |

## Error Handling
| Error / Symptom | Likely Cause | Remediation |
|-----------------|--------------|-------------|
| MCP tool call fails or times out | Invalid credentials, subscription, or AKS context | Verify `az login`, confirm the active subscription context with `az account show`, and check the target resource group without echoing subscription identifiers back to the user |
| Quota exceeded | Regional vCPU or resource limits | Request quota increase or select different region/VM SKU |
| Networking conflict (IP exhaustion) | Pod subnet too small for overlay/CNI | Re-plan IP ranges; may require cluster recreation (Day-0) |
| Workload Identity not working | Missing OIDC issuer or federated credential | Enable `--enable-oidc-issuer --enable-workload-identity`, configure federated identity |

<!-- chapter:end slug=azure-kubernetes -->

---

<!-- chapter:begin slug=azure-kusto position=23 -->

## 23. azure-kusto

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-kusto/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-kusto/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-kusto.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-kusto
description: "Query and analyze data in Azure Data Explorer (Kusto/ADX) using KQL for log analytics, telemetry, and time series analysis. WHEN: KQL queries, Kusto database queries, Azure Data Explorer, ADX clusters, log analytics, time series data, IoT telemetry, anomaly detection."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Data Explorer (Kusto) Query & Analytics

Execute KQL queries and manage Azure Data Explorer resources for fast, scalable big data analytics on log, telemetry, and time series data.

## Skill Activation Triggers

**Use this skill immediately when the user asks to:**
- "Query my Kusto database for [data pattern]"
- "Show me events in the last hour from Azure Data Explorer"
- "Analyze logs in my ADX cluster"
- "Run a KQL query on [database]"
- "What tables are in my Kusto database?"
- "Show me the schema for [table]"
- "List my Azure Data Explorer clusters"
- "Aggregate telemetry data by [dimension]"
- "Create a time series chart from my logs"

**Key Indicators:**
- Mentions "Kusto", "Azure Data Explorer", "ADX", or "KQL"
- Log analytics or telemetry analysis requests
- Time series data exploration
- IoT data analysis queries
- SIEM or security analytics tasks
- Requests for data aggregation on large datasets
- Performance monitoring or APM queries

## Overview

This skill enables querying and managing Azure Data Explorer (Kusto), a fast and highly scalable data exploration service optimized for log and telemetry data. Azure Data Explorer provides sub-second query performance on billions of records using the Kusto Query Language (KQL).

Key capabilities:
- **Query Execution**: Run KQL queries against massive datasets
- **Schema Exploration**: Discover tables, columns, and data types
- **Resource Management**: List clusters and databases
- **Analytics**: Aggregations, time series, anomaly detection, machine learning

## Core Workflow

1. **Discover Resources**: List available clusters and databases in subscription
2. **Explore Schema**: Retrieve table structures to understand data model
3. **Query Data**: Execute KQL queries for analysis, filtering, aggregation
4. **Analyze Results**: Process query output for insights and reporting

## Query Patterns

### Pattern 1: Basic Data Retrieval
Fetch recent records from a table with simple filtering.

**Example KQL**:
```kql
Events
| where Timestamp > ago(1h)
| take 100
```

**Use for**: Quick data inspection, recent event retrieval

### Pattern 2: Aggregation Analysis
Summarize data by dimensions for insights and reporting.

**Example KQL**:
```kql
Events
| summarize count() by EventType, bin(Timestamp, 1h)
| order by count_ desc
```

**Use for**: Event counting, distribution analysis, top-N queries

### Pattern 3: Time Series Analytics
Analyze data over time windows for trends and patterns.

**Example KQL**:
```kql
Telemetry
| where Timestamp > ago(24h)
| summarize avg(ResponseTime), percentiles(ResponseTime, 50, 95, 99) by bin(Timestamp, 5m)
| render timechart
```

**Use for**: Performance monitoring, trend analysis, anomaly detection

### Pattern 4: Join and Correlation
Combine multiple tables for cross-dataset analysis.

**Example KQL**:
```kql
Events
| where EventType == "Error"
| join kind=inner (
    Logs
    | where Severity == "Critical"
) on CorrelationId
| project Timestamp, EventType, LogMessage, Severity
```

**Use for**: Root cause analysis, correlated event tracking

### Pattern 5: Schema Discovery
Explore table structure before querying.

**Tools**: `kusto_table_schema_get`

**Use for**: Understanding data model, query planning

## Key Data Fields

When executing queries, common field patterns:
- **Timestamp**: Time of event (datetime) - use `ago()`, `between()`, `bin()` for time filtering
- **EventType/Category**: Classification field for grouping
- **CorrelationId/SessionId**: For tracing related events
- **Severity/Level**: For filtering by importance
- **Dimensions**: Custom properties for grouping and filtering

## Result Format

Query results include:
- **Columns**: Field names and data types
- **Rows**: Data records matching query
- **Statistics**: Row count, execution time, resource utilization
- **Visualization**: Chart rendering hints (timechart, barchart, etc.)

## KQL Best Practices

**🟢 Performance Optimized:**
- Filter early: Use `where` before joins and aggregations
- Limit result size: Use `take` or `limit` to reduce data transfer
- Time filters: Always filter by time range for time series data
- Indexed columns: Filter on indexed columns first

**🔵 Query Patterns:**
- Use `summarize` for aggregations instead of `count()` alone
- Use `bin()` for time bucketing in time series
- Use `project` to select only needed columns
- Use `extend` to add calculated fields

**🟡 Common Functions:**
- `ago(timespan)`: Relative time (ago(1h), ago(7d))
- `between(start .. end)`: Range filtering
- `startswith()`, `contains()`, `matches regex`: String filtering
- `parse`, `extract`: Extract values from strings
- `percentiles()`, `avg()`, `sum()`, `max()`, `min()`: Aggregations

## Best Practices

- Always include time range filters to optimize query performance
- Use `take` or `limit` for exploratory queries to avoid large result sets
- Leverage `summarize` for aggregations instead of client-side processing
- Store frequently-used queries as functions in the database
- Use materialized views for repeated aggregations
- Monitor query performance and resource consumption
- Apply data retention policies to manage storage costs
- Use streaming ingestion for real-time analytics (< 1 second latency)
- Integrate with Azure Monitor for operational insights

## MCP Tools Used

| Tool | Purpose |
|------|---------|
| `kusto_cluster_list` | List all Azure Data Explorer clusters in a subscription |
| `kusto_database_list` | List all databases in a specific Kusto cluster |
| `kusto_query` | Execute KQL queries against a Kusto database |
| `kusto_table_schema_get` | Retrieve schema information for a specific table |

**Required Parameters**:
- `subscription`: Azure subscription ID or display name
- `cluster`: Kusto cluster name (e.g., "mycluster")
- `database`: Database name
- `query`: KQL query string (for query operations)
- `table`: Table name (for schema operations)

**Optional Parameters**:
- `resource-group`: Resource group name (for listing operations)
- `tenant`: Azure AD tenant ID

## Fallback Strategy: Azure CLI Commands

If Azure MCP Kusto tools fail, timeout, or are unavailable, use Azure CLI commands as fallback.

### CLI Command Reference

| Operation | Azure CLI Command |
|-----------|-------------------|
| List clusters | `az kusto cluster list --resource-group <rg-name>` |
| List databases | `az kusto database list --cluster-name <cluster> --resource-group <rg-name>` |
| Show cluster | `az kusto cluster show --name <cluster> --resource-group <rg-name>` |
| Show database | `az kusto database show --cluster-name <cluster> --database-name <db> --resource-group <rg-name>` |

### KQL Query via Azure CLI

For queries, use the Kusto REST API or direct cluster URL:
```bash
az rest --method post \
  --url "https://<cluster>.<region>.kusto.windows.net/v1/rest/query" \
  --body "{ \"db\": \"<database>\", \"csl\": \"<kql-query>\" }"
```

### When to Fallback

Switch to Azure CLI when:
- MCP tool returns timeout error (queries > 60 seconds)
- MCP tool returns "service unavailable" or connection errors
- Authentication failures with MCP tools
- Empty response when database is known to have data

## Common Issues

- **Access Denied**: Verify database permissions (Viewer role minimum for queries)
- **Query Timeout**: Optimize query with time filters, reduce result set, or increase timeout
- **Syntax Error**: Validate KQL syntax - common issues: missing pipes, incorrect operators
- **Empty Results**: Check time range filters (may be too restrictive), verify table name
- **Cluster Not Found**: Check cluster name format (exclude ".kusto.windows.net" suffix)
- **High CPU Usage**: Query too broad - add filters, reduce time range, limit aggregations
- **Ingestion Lag**: Streaming data may have 1-30 second delay depending on ingestion method

## Use Cases

- **Log Analytics**: Application logs, system logs, audit logs
- **IoT Analytics**: Sensor data, device telemetry, real-time monitoring
- **Security Analytics**: SIEM data, threat detection, security event correlation
- **APM**: Application performance metrics, user behavior, error tracking
- **Business Intelligence**: Clickstream analysis, user analytics, operational KPIs

<!-- chapter:end slug=azure-kusto -->

---

<!-- chapter:begin slug=azure-messaging position=24 -->

## 24. azure-messaging

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-messaging/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-messaging/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-messaging.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-messaging
description: "Troubleshoot and resolve issues with Azure Messaging SDKs for Event Hubs and Service Bus. Covers connection failures, authentication errors, message processing issues, and SDK configuration problems. WHEN: event hub SDK error, service bus SDK issue, messaging connection failure, AMQP error, event processor host issue, message lock lost, message lock expired, lock renewal, lock renewal batch, send timeout, receiver disconnected, SDK troubleshooting, azure messaging SDK, event hub consumer, service bus queue issue, topic subscription error, enable logging event hub, service bus logging, eventhub python, servicebus java, eventhub javascript, servicebus dotnet, event hub checkpoint, event hub not receiving messages, service bus dead letter, batch processing lock, session lock expired, idle timeout, connection inactive, link detach, slow reconnect, session error, duplicate events, offset reset, receive batch."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Messaging SDK Troubleshooting

## Quick Reference

| Property | Value |
|----------|-------|
| **Services** | Azure Event Hubs, Azure Service Bus |
| **MCP Tools** | `mcp_azure_mcp_eventhubs`, `mcp_azure_mcp_servicebus` |
| **Best For** | Diagnosing SDK connection, auth, and message processing issues |

## When to Use This Skill

- SDK connection failures, auth errors, or AMQP link errors
- Idle timeout, connection inactivity, or slow reconnection after disconnect
- AMQP link detach or detach-forced errors
- Message lock lost, message lock expired, lock renewal failures, or batch lock timeouts
- Session lock lost, session lock expired, or session receiver errors
- Event processor or message handler stops processing
- Duplicate events or checkpoint offset resets
- SDK configuration questions (retry, prefetch, batch size, receive batch behavior)

## MCP Tools

| Tool | Command | Use |
|------|---------|-----|
| `mcp_azure_mcp_eventhubs` | Namespace/hub ops | List namespaces, hubs, consumer groups |
| `mcp_azure_mcp_servicebus` | Queue/topic ops | List namespaces, queues, topics, subscriptions |
| `mcp_azure_mcp_monitor` | `logs_query` | Query diagnostic logs with KQL |
| `mcp_azure_mcp_resourcehealth` | `get` | Check service health status |
| `mcp_azure_mcp_documentation` | Doc search | Search Microsoft Learn for troubleshooting docs |

## Diagnosis Workflow

1. **Identify the SDK and version** — Check the prompt for SDK and version clues; if not stated, proceed with diagnosis and ask later if needed
2. **Check resource health** — Use `mcp_azure_mcp_resourcehealth` to verify the namespace is healthy
3. **Review the error message** — Match against language-specific troubleshooting guide
4. **Look up documentation** — Use `mcp_azure_mcp_documentation` to search Microsoft Learn for the error or topic
5. **Check configuration** — Verify connection string, entity name, consumer group
6. **Recommend fix** — Apply remediation, citing documentation found


## Troubleshooting Guides

Connectivity, SDK, and auth troubleshooting guides are located in the azure-diagnostics skill under `troubleshooting/messaging/`.

## References

- Use `mcp_azure_mcp_documentation` to search Microsoft Learn for latest guidance.

<!-- chapter:end slug=azure-messaging -->

---

<!-- chapter:begin slug=azure-prepare position=25 -->

## 25. azure-prepare

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-prepare/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-prepare.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (163), referenced from this skill's directory:
  - `references/analyze.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/analyze.md
  - `references/apim.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/apim.md
  - `references/architecture.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/architecture.md
  - `references/aspire.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/aspire.md
  - `references/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/auth-best-practices.md
  - `references/azure-context.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/azure-context.md
  - `references/functional-verification.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/functional-verification.md
  - `references/generate.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/generate.md
  - `references/global-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/global-rules.md
  - `references/plan-template.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/plan-template.md
  - `references/recipe-selection.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipe-selection.md
  - `references/recipes/azcli/commands.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azcli/commands.md
  - `references/recipes/azcli/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azcli/README.md
  - `references/recipes/azcli/scripts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azcli/scripts.md
  - `references/recipes/azd/aspire.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azd/aspire.md
  - `references/recipes/azd/azure-yaml.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azd/azure-yaml.md
  - `references/recipes/azd/docker.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azd/docker.md
  - `references/recipes/azd/iac-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azd/iac-rules.md
  - `references/recipes/azd/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azd/README.md
  - `references/recipes/azd/terraform.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/azd/terraform.md
  - `references/recipes/bicep/patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/bicep/patterns.md
  - `references/recipes/bicep/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/bicep/README.md
  - `references/recipes/terraform/patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/terraform/patterns.md
  - `references/recipes/terraform/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-prepare/references/recipes/terraform/README.md
  - …and 139 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-prepare

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-prepare
description: "Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure."
license: MIT
metadata:
  author: Microsoft
  version: "1.3.1"
---

# Azure Prepare

> **AUTHORITATIVE GUIDANCE — MANDATORY COMPLIANCE**
>
> This document is the **official, canonical source** for preparing applications for Azure deployment. You **MUST** follow these instructions exactly as written unless they contradict security policies given to you. When in doubt, present the conflicting instructions from this document and ask the user for explicit confirmation. Do not improvise, infer, or substitute steps.

---

## Triggers

Activate this skill when user wants to:
- Create a new application
- Add services or components to an existing app
- Make updates or changes to existing application
- Modernize or migrate an application
- Set up Azure infrastructure
- Deploy to Azure or host on Azure
- Create and deploy to Azure (including Terraform-based deployment requests)

## Rules

1. **Plan first — MANDATORY** — You MUST physically write an initial `.azure/deployment-plan.md` **skeleton in the workspace root directory** (not the session-state folder) **as your very first action** — before any code generation or execution begins. Write the skeleton immediately, then populate it progressively as Phase 1 analysis and research unfold; finalize it with all decisions at Phase 1 Step 6. This file must exist on disk throughout. azure-validate and azure-deploy depend on it and will fail without it. Do not skip or defer this step.
2. **Get approval** — Present plan to user before execution
3. **Research before generating** — Load references and invoke related skills
4. **Update plan progressively** — Mark steps complete as you go
5. **Validate before deploy** — Invoke azure-validate before azure-deploy
6. **Confirm Azure context** — Use `ask_user` for subscription and location per [Azure Context](references/azure-context.md)
7. ❌ **Destructive actions require `ask_user`** — [Global Rules](references/global-rules.md)
8. ⛔ **NEVER delete user project or workspace directories** — When adding features to an existing project, MODIFY existing files. `azd init -t <template>` is for NEW projects only; do NOT run `azd init -t` in an existing workspace. Plain `azd init` (without a template argument) may be used in existing workspaces when appropriate. File deletions within a project (e.g., removing build artifacts or temp files) are permitted when appropriate, but NEVER delete the user's project or workspace directory itself. See [Global Rules](references/global-rules.md).
9. **Scope: preparation only** — This skill generates infrastructure code and configuration files. Deployment execution (`azd up`, `azd deploy`, `terraform apply`) is handled by the **azure-deploy** skill, which provides built-in error recovery and deployment verification.
10. ⛔ **SQL Server Bicep: NEVER generate `administratorLogin` or `administratorLoginPassword`** — not in direct properties, not in conditional/ternary branches, not anywhere in the file. Always use Entra-only authentication (`azureADOnlyAuthentication: true`) unconditionally. See [references/services/sql-database/bicep.md](references/services/sql-database/bicep.md).
11. **Remove stale template IaC after conversion** — If you converted Bicep templates from the selected `azd` template into Terraform templates, remove the Bicep templates that were introduced by that `azd` template and are now fully replaced by Terraform equivalents. Do not remove user-authored Bicep files. Only remove those template-provided Bicep files after the Terraform IaC is complete and Terraform has been selected as the deployment path. Before handing off to azure-validate skill, keep only the IaC templates required by the chosen deployment path.

---

## ❌ PLAN-FIRST WORKFLOW — MANDATORY

> **YOU MUST CREATE A PLAN BEFORE DOING ANY WORK**
>
> 1. **STOP** — Do not generate any code, infrastructure, or configuration yet
> 2. **CREATE SKELETON** - Write an initial `.azure/deployment-plan.md` skeleton to disk **immediately** (before any code generation or execution begins), then populate it progressively as Phase 1 steps 1-5 reveal details; finalize it at Step 6
> 3. **CONFIRM** — Present the completed plan to the user and get approval
> 4. **EXECUTE** — Only after approval, execute the plan step by step
>
> The `.azure/deployment-plan.md` file is the **source of truth** for this workflow and for azure-validate and azure-deploy skills. Without it, those skills will fail.
>
> ⚠️ **CRITICAL: `.azure/deployment-plan.md` must be WRITTEN TO DISK inside the workspace root** (e.g., `<workspace-root>/.azure/deployment-plan.md`), not in the session-state folder. Use a file-write tool to create this file. This is the deployment plan artifact read by azure-validate and azure-deploy. **You MUST create this file — do not proceed without it.** 
> ⚠️ **CRITICAL: You must create the file with the name `.azure/deployment-plan.md` as is**. You must not use other names such as `.azure/plan.md`.
>
> ⛔ **Critical:** Skipping the plan file creation will cause azure-validate and azure-deploy to fail. This requirement has no exceptions.

---

## ❌ STEP 0: Specialized Technology Check — MANDATORY FIRST ACTION

**BEFORE starting Phase 1**, check if the user's prompt OR workspace codebase matches a specialized technology that has a dedicated skill with tested templates. If matched, **invoke that skill FIRST** — then resume azure-prepare for validation and deployment.

### Check 1: Prompt keywords

| Prompt keywords | Invoke FIRST |
|----------------|-------------|
| Python + App Service (e.g., "deploy Python to App Service", "Flask on Azure App Service", "publish Python web app to App Service") | **python-appservice-deploy** |
| Lambda, AWS Lambda, migrate AWS, migrate GCP, Lambda to Functions, migrate from AWS, migrate from GCP | **azure-cloud-migrate** |
| Azure Functions, function app, serverless function, timer trigger, HTTP trigger, func new | Stay in **azure-prepare** — prefer Azure Functions templates in Step 4 |
| APIM, API Management, API gateway, deploy APIM | Stay in **azure-prepare** — see [APIM Deployment Guide](references/apim.md) |
| AI gateway, AI gateway policy, AI gateway backend, AI gateway configuration | **azure-aigateway** |
| workflow, orchestration, multi-step, pipeline, fan-out/fan-in, saga, long-running process, durable, order processing | Stay in **azure-prepare** — select **durable** recipe in Step 4. **MUST** load [durable.md](references/services/functions/durable.md), [DTS reference](references/services/durable-task-scheduler/README.md), and [DTS Bicep patterns](references/services/durable-task-scheduler/bicep.md). |

> ⚠️ Check the user's **prompt text** — not just existing code. Critical for greenfield projects with no codebase to scan. See [full routing table](references/specialized-routing.md).

After the specialized skill completes, **resume azure-prepare** at Phase 1 Step 4 (Select Recipe) for remaining infrastructure, validation, and deployment.

---

## Phase 1: Planning (BLOCKING — Complete Before Any Execution)

Create `.azure/deployment-plan.md` by completing these steps. Do NOT generate any artifacts until the plan is approved.

| # | Action | Reference |
|---|--------|-----------|
| 0 | If the prompt matches a specialized technology with a dedicated skill, invoke that skill first | [specialized-routing.md](references/specialized-routing.md) |
| 1 | **Analyze Workspace** — Determine mode: NEW, MODIFY, or MODERNIZE | [analyze.md](references/analyze.md) |
| 2 | **Gather Requirements** — Classification, scale, budget | [requirements.md](references/requirements.md) |
| 3 | **Scan Codebase** — Identify components, technologies, dependencies | [scan.md](references/scan.md) |
| 4 | **Select Recipe** — Choose AZD (default), AZCLI, Bicep, or Terraform | [recipe-selection.md](references/recipe-selection.md) |
| 5 | **Plan Architecture** — Select stack + map components to Azure services | [architecture.md](references/architecture.md) |
| 6 | **Finalize Plan (MANDATORY)** - Use a file-write tool to finalize `.azure/deployment-plan.md` with all decisions from steps 1-5. Update the skeleton written at the start of Phase 1 with the complete content. The file must be fully populated before you present the plan to the user. | [plan-template.md](references/plan-template.md) |
| 7 | **Present Plan** — Show plan to user and ask for approval | `.azure/deployment-plan.md` |
| 8 | **Destructive actions require `ask_user`** | [Global Rules](references/global-rules.md) |

---

> **❌ STOP HERE** — Do NOT proceed to Phase 2 until the user approves the plan.

---

## Phase 2: Execution (Only After Plan Approval)

Execute the approved plan. Update `.azure/deployment-plan.md` status after each step.

| # | Action | Reference |
|---|--------|-----------|
| 1 | **Research Components** — Load service references + invoke related skills | [research.md](references/research.md) |
| 2 | **Confirm Azure Context** — Detect and confirm subscription + location and check the resource provisioning limit | [Azure Context](references/azure-context.md) |
| 3 | **Generate Artifacts** — Create infrastructure and configuration files | [generate.md](references/generate.md) |
| 4 | **Harden Security** — Apply security best practices | [security.md](references/security.md) |
| 5 | **Functional Verification** — Verify the app works (UI + backend), locally if possible | [functional-verification.md](references/functional-verification.md) |
| 6 | **⛔ Update Plan (MANDATORY before hand-off)** — Use the `edit` tool to change the Status in `.azure/deployment-plan.md` to `Ready for Validation`. You **MUST** complete this edit **BEFORE** invoking azure-validate. Do NOT skip this step. | `.azure/deployment-plan.md` |
| 7 | **⛔ MANDATORY Hand Off** — Invoke **azure-validate** skill. Your preparation work is done. Do NOT run `azd up`, `azd deploy`, or any deployment command directly — all deployment execution is handled by azure-deploy after azure-validate completes. **PREREQUISITE:** Step 6 must be completed first — `.azure/deployment-plan.md` status must say `Ready for Validation`. | — |

---

## Outputs

| Artifact | Location |
|----------|----------|
| **Plan** | `.azure/deployment-plan.md` |
| Infrastructure | `./infra/` |
| AZD Config | `azure.yaml` (AZD only) |
| Dockerfiles | `src/<component>/Dockerfile` |

---

## SDK Quick References

- **Azure Developer CLI**: [azd](references/sdk/azd-deployment.md)
- **Azure Identity**: [Python](references/sdk/azure-identity-py.md) | [.NET](references/sdk/azure-identity-dotnet.md) | [TypeScript](references/sdk/azure-identity-ts.md) | [Java](references/sdk/azure-identity-java.md)
- **App Configuration**: [Python](references/sdk/azure-appconfiguration-py.md) | [TypeScript](references/sdk/azure-appconfiguration-ts.md) | [Java](references/sdk/azure-appconfiguration-java.md)

---

## Next

> **⛔ MANDATORY NEXT STEP — DO NOT SKIP**
>
> After completing preparation, you **MUST** invoke **azure-validate** before any deployment attempt. Do NOT skip validation. Do NOT go directly to azure-deploy. Do NOT run `azd up` or any deployment command directly. The workflow is:
>
> `azure-prepare` → `azure-validate` → `azure-deploy`
>
> **⛔ BEFORE invoking azure-validate**, you MUST use the `edit` tool to update `.azure/deployment-plan.md` status to `Ready for Validation`. If the plan status has not been updated, the validation will fail.
>
> This applies to ALL deployment scenarios including containerized apps, Container Apps, App Service, Azure Functions, static sites, and any other Azure target. No exceptions.
>
> Skipping validation leads to deployment failures. Be patient and follow the complete workflow for the highest success outcome.

**→ Update plan status to `Ready for Validation`, then invoke azure-validate**

<!-- chapter:end slug=azure-prepare -->

---

<!-- chapter:begin slug=azure-quotas position=26 -->

## 26. azure-quotas

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-quotas/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-quotas/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-quotas.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (4), referenced from this skill's directory:
  - `references/advanced-commands.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-quotas/references/advanced-commands.md
  - `references/commands.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-quotas/references/commands.md
  - `scripts/check-quota.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-quotas/scripts/check-quota.ps1
  - `scripts/check-quota.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-quotas/scripts/check-quota.sh

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-quotas
description: "Check/manage Azure quotas and usage across providers. For deployment planning, capacity validation, region selection. WHEN: \"check quotas\", \"service limits\", \"current usage\", \"request quota increase\", \"quota exceeded\", \"validate capacity\", \"regional availability\", \"provisioning limits\", \"vCPU limit\", \"how many vCPUs available in my subscription\"."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---


# Azure Quotas - Service Limits & Capacity Management

> **AUTHORITATIVE GUIDANCE** — Follow these instructions exactly for quota management and capacity validation.

## Overview

**What are Azure Quotas?**

Azure quotas (also called service limits) are the maximum number of resources you can deploy in a subscription. Quotas:
- Prevent accidental over-provisioning
- Ensure fair resource distribution across Azure
- Represent **available capacity** in each region
- Can be increased (adjustable quotas) or are fixed (non-adjustable)

**Key Concept:** **Quotas = Resource Availability**

If you don't have quota, you cannot deploy resources. Always check quotas when planning deployments or selecting regions.

## When to Use This Skill

Invoke this skill when:

- **Planning a new deployment** - Validate capacity before deployment
- **Selecting an Azure region** - Compare quota availability across regions
- **Troubleshooting quota exceeded errors** - Check current usage vs limits
- **Requesting quota increases** - Submit increase requests via CLI or Portal
- **Comparing regional capacity** - Find regions with available quota
- **Validating provisioning limits** - Ensure deployment won't exceed quotas

## Quick Reference

| **Property** | **Details** |
|--------------|-------------|
| **Primary Tool** | Azure CLI (`az quota`) - **USE THIS FIRST, ALWAYS** |
| **Extension Required** | `az extension add --name quota` (MUST install first) |
| **Key Commands** | `az quota list`, `az quota show`, `az quota usage list`, `az quota usage show` |
| **Complete CLI Reference** | [commands.md](./references/commands.md) |
| **Azure Portal** | [My quotas](https://portal.azure.com/#blade/Microsoft_Azure_Capacity/QuotaMenuBlade/myQuotas) - Use only as fallback |
| **REST API** | Microsoft.Quota provider - **Unreliable, do NOT use first** |
| **MCP Server** | `azure-quota` MCP server — **NEVER use this. It is unreliable. Always use `az quota` CLI instead.** |
| **Required Permission** | Reader (view) or Quota Request Operator (manage) |

> **⚠️ ALWAYS USE CLI FIRST**
>
> REST API and Portal can show misleading "No Limit" values — this does **not** mean unlimited capacity. It means the quota API doesn't support that resource type. Always start with `az quota` commands; fall back to [Azure service limits docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits) if CLI returns `BadRequest`.
>
> For complete CLI reference, see [commands.md](./references/commands.md).

## Quota Types

| **Type** | **Adjustability** | **Approval** | **Examples** |
|----------|-------------------|--------------|--------------|
| **Adjustable** | Can increase via Portal/CLI/API | Usually auto-approved | VM vCPUs, Public IPs, Storage accounts |
| **Non-adjustable** | Fixed limits | Cannot be changed | Subscription-wide hard limits |

**Important:** Requesting quota increases is **free**. You only pay for resources you actually use, not for quota allocation.

## Understanding Resource Name Mapping

**⚠️ CRITICAL:** There is **NO 1:1 mapping** between ARM resource types and quota resource names.

### Example Mappings

| ARM Resource Type | Quota Resource Name |
|-------------------|---------------------|
| `Microsoft.App/managedEnvironments` | `ManagedEnvironmentCount` |
| `Microsoft.Compute/virtualMachines` | `standardDSv3Family`, `cores`, `virtualMachines` |
| `Microsoft.Network/publicIPAddresses` | `PublicIPAddresses`, `IPv4StandardSkuPublicIpAddresses` |

### Discovery Workflow

**Never assume the quota resource name from the ARM type.** Always use this workflow:

1. **List all quotas** for the resource provider:
   ```bash
   az quota list --scope /subscriptions/<id>/providers/<ProviderNamespace>/locations/<region>
   ```

2. **Match by `localizedValue`** (human-readable description) to find the relevant quota

3. **Use the `name` field** (not ARM resource type) in subsequent commands:
   ```bash
   az quota show --resource-name ManagedEnvironmentCount --scope ...
   az quota usage show --resource-name ManagedEnvironmentCount --scope ...
   ```

> **📖 Detailed mapping examples and workflow:** See [commands.md - Resource Name Mapping](./references/commands.md#resource-name-mapping)

## Scripts

Pre-built scripts handle quota extension installation, usage queries, and capacity calculation. Use these instead of constructing commands manually. A single call returns limits, usage, and available capacity.

| Script | Purpose | Usage |
|--------|---------|-------|
| `scripts/check-quota.ps1` | Returns limit, usage, and available capacity for all quotas (or a single quota when resource name is provided) | Primary script for quota checks |
| `scripts/check-quota.sh` | Same as above (bash) | Primary script for quota checks |

## Core Workflows

### Workflow 1: Check Quota for a Specific Resource

**Scenario:** Verify quota limits and current usage before deployment

Run the script with the resource provider and region. It returns a table of **all** quotas with their limit, current usage, and available capacity in a single call:

```powershell
.\scripts\check-quota.ps1 -ResourceProvider <provider> -Region <region>
```
```bash
./scripts/check-quota.sh <provider> <region>
```

To check a single resource, add the resource name:

```powershell
.\scripts\check-quota.ps1 -ResourceProvider <provider> -Region <region> -ResourceName <resource-name>
```
```bash
./scripts/check-quota.sh <provider> <region> <resource-name>
```

**Example:**

```powershell
.\scripts\check-quota.ps1 -ResourceProvider Microsoft.Compute -Region eastus
```

**Example Output:**

| Resource | Region | Limit | Usage | Available |
|----------|--------|-------|-------|-----------|
| cores | eastus | 100 | 50 | 50 |
| standardDSv3Family | eastus | 350 | 50 | 300 |
| virtualMachines | eastus | 25000 | 5 | 24995 |
| ... | ... | ... | ... | ... |

> **📖 See also:** [az quota show](./references/commands.md#az-quota-show), [az quota usage show](./references/commands.md#az-quota-usage-show)

### Workflow 2: Compare Quotas Across Regions

**Scenario:** Find the best region for deployment based on available capacity

```bash
# Define candidate regions
REGIONS=("eastus" "eastus2" "westus2" "centralus")
VM_FAMILY="standardDSv3Family"
SUBSCRIPTION_ID="<subscription-id>"

# Check quota availability across regions
for region in "${REGIONS[@]}"; do
  echo "=== Checking $region ==="
  
  # Get limit
  LIMIT=$(az quota show \
    --resource-name $VM_FAMILY \
    --scope "/subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.Compute/locations/$region" \
    --query "properties.limit.value" -o tsv)
  
  # Get current usage
  USAGE=$(az quota usage show \
    --resource-name $VM_FAMILY \
    --scope "/subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.Compute/locations/$region" \
    --query "properties.usages.value" -o tsv)
  
  # Calculate available
  AVAILABLE=$((LIMIT - USAGE))
  
  echo "Region: $region | Limit: $LIMIT | Usage: $USAGE | Available: $AVAILABLE"
done
```

> **📖 See also:** [commands.md](./references/commands.md#az-quota-show) for full scripted multi-region loop patterns

### Workflow 3: Request Quota Increase

**Scenario:** Current quota is insufficient for deployment

```bash
# Request increase for VM quota
az quota update \
  --resource-name standardDSv3Family \
  --scope /subscriptions/<subscription-id>/providers/Microsoft.Compute/locations/eastus \
  --limit-object value=500 \
  --resource-type dedicated

# Check request status
az quota request status list \
  --scope /subscriptions/<subscription-id>/providers/Microsoft.Compute/locations/eastus
```

**Approval Process:**
- Most adjustable quotas are auto-approved within minutes
- Some requests require manual review (hours to days)
- Non-adjustable quotas require Azure Support ticket

> **📖 See also:** [az quota update](./references/commands.md#az-quota-update), [az quota request status](./references/advanced-commands.md#az-quota-request-status-list)

### Workflow 4: List All Quotas for Planning

**Scenario:** Understand all quotas for a resource provider in a region

```bash
# List all compute quotas in East US (table format)
az quota list \
  --scope /subscriptions/<subscription-id>/providers/Microsoft.Compute/locations/eastus \
  --output table

# List all network quotas
az quota list \
  --scope /subscriptions/<subscription-id>/providers/Microsoft.Network/locations/eastus \
  --output table

# List all Container Apps quotas
az quota list \
  --scope /subscriptions/<subscription-id>/providers/Microsoft.App/locations/eastus \
  --output table
```

> **📖 See also:** [az quota list](./references/commands.md#az-quota-list)

## Troubleshooting

### Common Errors

| **Error** | **Cause** | **Solution** |
|-----------|-----------|--------------|
| REST API "No Limit" | Misleading — not unlimited | Use CLI instead; see warning in Quick Reference |
| `ExtensionNotFound` | Quota extension not installed | `az extension add --name quota` |
| `BadRequest` | Resource provider not supported by quota API | Check [service limits docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits) |
| `MissingRegistration` | Microsoft.Quota provider not registered | `az provider register --namespace Microsoft.Quota` |
| `QuotaExceeded` | Deployment would exceed quota | Request increase or choose different region |
| `InvalidScope` | Incorrect scope format | Use pattern: `/subscriptions/<id>/providers/<namespace>/locations/<region>` |
| CLI commands fail entirely | Auth, extension, or environment issue | Verify Azure CLI login (`az account show`), reinstall quota extension, check network. Do NOT use the `azure-quota` MCP server — it is unreliable. |

### Unsupported Resource Providers

**Known unsupported providers:**
- ❌ Microsoft.DocumentDB (Cosmos DB) - Use Portal or [Cosmos DB limits docs](https://learn.microsoft.com/en-us/azure/cosmos-db/concepts-limits)

**Confirmed working providers:**
- ✅ Microsoft.Compute (VMs, disks, cores)
- ✅ Microsoft.Network (VNets, IPs, load balancers)
- ✅ Microsoft.App (Container Apps)
- ✅ Microsoft.Storage (storage accounts)
- ✅ Microsoft.MachineLearningServices (ML compute)

> **📖 See also:** [Troubleshooting Guide](./references/commands.md#troubleshooting)

## Additional Resources

| Resource | Link |
|----------|------|
| **CLI Commands Reference** | [commands.md](./references/commands.md) - Complete syntax, parameters, examples |
| **Azure Quotas Overview** | [Microsoft Learn](https://learn.microsoft.com/en-us/azure/quotas/quotas-overview) |
| **Service Limits Documentation** | [Azure subscription limits](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits) |
| **Azure Portal - My Quotas** | [Portal Link](https://portal.azure.com/#blade/Microsoft_Azure_Capacity/QuotaMenuBlade/myQuotas) |
| **Request Quota Increases** | [How to request increases](https://learn.microsoft.com/en-us/azure/quotas/quickstart-increase-quota-portal) |

## Best Practices

1. ✅ **Always check quotas before deployment** - Prevent quota exceeded errors
2. ✅ **Run `az quota list` first** - Discover correct quota resource names
3. ✅ **Compare regions** - Find regions with available capacity
4. ✅ **Account for growth** - Request 20% buffer above immediate needs
5. ✅ **Use table output for overview** - `--output table` for quick scanning
6. ✅ **Monitor usage trends** - Set up alerts at 80% threshold (via Portal)

<!-- chapter:end slug=azure-quotas -->

---

<!-- chapter:begin slug=azure-reliability position=27 -->

## 27. azure-reliability

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-reliability/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-reliability.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (12), referenced from this skill's directory:
  - `references/configure-health-probes.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/configure-health-probes.md
  - `references/configure-multi-region.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/configure-multi-region.md
  - `references/configure-storage.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/configure-storage.md
  - `references/configure-zone-redundancy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/configure-zone-redundancy.md
  - `references/health-probe-checks.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/health-probe-checks.md
  - `references/iac-patching-bicep.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/iac-patching-bicep.md
  - `references/iac-patching-terraform.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/iac-patching-terraform.md
  - `references/multi-region-checks.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/multi-region-checks.md
  - `references/services/app-service/reliability.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/services/app-service/reliability.md
  - `references/services/functions/reliability.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/services/functions/reliability.md
  - `references/storage-redundancy-checks.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/storage-redundancy-checks.md
  - `references/zone-redundancy-checks.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-reliability/references/zone-redundancy-checks.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-reliability
description: "Assess and improve the reliability posture of PaaS Applications (Azure Functions and Azure App Service). Scans deployed resources for zone redundancy, ZRS storage, health probes, and multi-region failover. Presents a feature-pivoted checklist, then drives staged remediation (CLI or IaC patches) end-to-end with user confirmation. WHEN: \"assess reliability\", \"check reliability\", \"zone redundant\", \"multi-region failover\", \"high availability\", \"disaster recovery\", \"single points of failure\", \"reliability posture\", \"resiliency\"."
license: MIT
metadata:
  author: Microsoft
  version: "1.1.1"
---

# Azure Reliability Assessment & Configuration

## Quick Reference

| Property | Details |
|---|---|
| Best for | Reliability posture assessment, zone redundancy enablement, multi-region failover setup |
| Primary capabilities | Reliability assessment table, Zone Redundancy Configuration, Multi-Region IaC Generation |
| Supported services | Azure Functions, App Service (Container Apps planned for a future version) |
| MCP tools | Azure Resource Graph queries, Azure CLI commands |

## When to Use This Skill

Activate this skill when user wants to:
- "Assess my Function app's reliability"
- "Assess my Web app's reliability"
- "Check the reliability of my resource group" (App Service and Functions resources only)
- "Is my app zone redundant?" (App Service and Functions resources only)
- "Is my app service plan zone redundant?" 
- "Make my app zone redundant" (App Service and Functions resources only)
- "Make my app service plan zone redundant"
- "Set up multi-region failover for my app" (App Service and Functions resources only)
- "Check my reliability posture"
- "Find single points of failure" (App Service and Functions resources only)
- "Enable high availability for my app" (App Service and Functions resources only)
- "Check disaster recovery readiness"
- "Improve my app's resilience" (App Service and Functions resources only)

> **Scope note:** This skill currently covers **Azure Functions and Azure App Service** only. If the user asks about Azure Container Apps reliability, acknowledge that support is planned but not yet available, and only proceed with the parts that apply to App Service and Functions resources in scope.

## Prerequisites

- Authentication: user is logged in to Azure via `az login`
- Permissions: Reader access on target subscription/resource group (for assessment)
- Permissions: Contributor access (for configuration changes)
- Azure Resource Graph extension: `az extension add --name resource-graph`

## MCP Tools

| Tool | Purpose |
|------|---------|
| `mcp_azure_mcp_extension_cli_generate` | Generate `az` CLI commands for resource queries and configuration |
| `mcp_azure_mcp_subscription_list` | List available subscriptions |
| `mcp_azure_mcp_group_list` | List resource groups |

Primary query method: Azure Resource Graph via `az graph query` (requires `az extension add --name resource-graph`).

## Assessment Workflow

### Phase 1: Discover Resources

1. **Identify scope** — Ask user for resource group, subscription, or app name
2. **Query Azure Resource Graph** to discover all resources in scope
3. **Classify resources** by service type (Functions, Storage, etc.). If non-Functions compute (App Service sites that aren't Function Apps, Container Apps) is found, **note it but do not deep-dive** — those services are planned for a future version of this skill.

**Important:** Always scope queries to the user's specified resource group or subscription. Add these filters to every Resource Graph query:
- Resource group: `| where resourceGroup =~ '<rg-name>'`
- Subscription: Use `--subscriptions <sub-id>` flag on `az graph query`
- App name: `| where name =~ '<app-name>'`

### Phase 2: Assess Reliability

Two-step assessment: **platform-level discovery first, then per-service deep dive.**

**Step 1 — Platform discovery (find what's there).** Use these to enumerate resources in scope and detect cross-cutting reliability gaps:

| Platform check | Reference |
|---|---|
| Zone redundancy — discovery | [references/zone-redundancy-checks.md](references/zone-redundancy-checks.md) |
| Storage redundancy (cross-service) | [references/storage-redundancy-checks.md](references/storage-redundancy-checks.md) |
| Multi-region & global load balancers | [references/multi-region-checks.md](references/multi-region-checks.md) |
| Front Door / Traffic Manager / App Insights probes | [references/health-probe-checks.md](references/health-probe-checks.md) |

**Step 2 — Per-service deep dive.** For each compute resource discovered in Step 1, load the matching service reference. The service reference is the single source of truth for that service's plan/SKU rules, assessment queries, CLI commands, IaC patches (Bicep + Terraform + AVM), and reporting hints.

This skill version ships **only the Azure Functions and App Service** per-service references. Other compute services are listed below explicitly so the dispatch logic is unambiguous: if a resource matches an unsupported row, do **not** attempt to load a reference, fabricate CLI commands, or generate IaC patches for it.

| Service detected | Reference |
|---|---|
| Azure Functions (`microsoft.web/serverfarms` with `kind contains 'functionapp'`) | [references/services/functions/reliability.md](references/services/functions/reliability.md) |
| Azure App Service (non-Functions sites: `microsoft.web/sites` without `kind contains 'functionapp'`, `microsoft.web/serverfarms` without `kind contains 'functionapp'`) | [references/services/app-service/reliability.md](references/services/app-service/reliability.md) |
| Azure Container Apps (`microsoft.app/containerapps`, `microsoft.app/managedenvironments`) | ⚪ Not yet shipped — planned for a future version |

> **Handling unsupported services:** If a resource matches an unsupported row above, surface it in the discovery summary, mark it as `⚪ not assessed (planned)` in the Phase 3 table, and skip the per-service remediation steps for it. Do **not** attempt to fabricate CLI commands or IaC patches for those services.

### Phase 3: Generate Reliability Checklist

Present findings as a **feature-pivoted** table: one row per reliability feature (Zone redundancy on compute, Zone-redundant storage, Health probes, Multi-region failover), with a single status indicator and the **specific resources** that are relevant to that feature. This avoids the noise of one-row-per-resource with mostly `n/a` cells. Do **not** assign numeric scores or grades.

```
🔍 Reliability Assessment — {scope}
─────────────────────────────────────────────────────────────────────────────────────────────
Reliability Feature              Status      Resources
─────────────────────────────────────────────────────────────────────────────────────────────
Zone redundancy — compute        🔴 OFF      • plan-web-ii5trxva2ark4 (P1v3)
                                              • plan-ii5trxva2ark4 (FC1)

Zone-redundant storage           🔴 GRS      • stii5trxva2ark4 (defaulted; no SKU set in IaC)

Health probes                    🔴 OFF      • func-api-ii5trxva2ark4 — needs code change (FC1)
                                              • app-web-ii5trxva2ark4 — no health check path

Multi-region failover            🔴 OFF      • Single region (eastus) only — Front Door not configured
─────────────────────────────────────────────────────────────────────────────────────────────

Want me to fix the 🔴 items? I'll do the quick wins first (App
plan zone redundancy + health checks on supported plans), then ask before
storage migration and multi-region setup. (yes/no)
```

**Rules for the table:**

- **Four feature rows, in this order:** Zone redundancy — compute · Zone-redundant storage · Health probes · Multi-region failover. Omit a row entirely only if no resource in scope could ever apply to it.
- **Status column** is one symbol + one short word, no other characters:
  - `🟢 ON` — feature is fully enabled across all relevant resources in scope
  - `🟡 PARTIAL` — some resources have it, some don't (or partial config like liveness-only)
  - `🔴 OFF` — feature is missing on all relevant resources
  - For storage, replace `OFF` with the current SKU when relevant (`🔴 LRS`, `🔴 GRS`, `🟢 ZRS`, `🟢 GZRS`). When no SKU is set in IaC, label as `🔴 GRS` (ARM/AVM default) and note that in the resource line.
- **Resources column** lists only what's relevant to that feature, one bullet per resource:
  - For "needs fixing" resources, include a short inline reason (`(FC1)`, `(defaulted; no SKU set)`, `liveness only`, `needs code change (FC1)`).
  - For resources that are **already ON** for that feature, mention them on the same row with `— already ON` so the user sees credit for what's right.
- **Do not** include `n/a`, `—`, or empty cells. If a feature doesn't apply to any resource in scope, drop the row.
- **Do not** include numeric scores, grades, or point totals.
- End the assessment with a **single yes/no question** that kicks off the staged remediation flow. Do not enumerate the per-resource fix list here — the user will see it after they say yes (Configuration Workflow Step 1).

> **UX Note:** If the assessment finds the app **already has** all core reliability features (zone redundancy, ZRS/GZRS storage, health probes), skip the fix-it question and jump straight to Configuration Workflow [Step 3](#step-3-both-paths-multi-region-followup--ask-and-wait) (Multi-region follow-up). Do **NOT** start any multi-region work without explicit consent.

## Configuration Workflow

When user wants to **fix** findings from the assessment:

> **⛔ ALWAYS confirm with user before executing changes.** Show what will change, any cost implications, and any destructive actions (e.g., environment recreation).

### Step 1: Present Fix Plan + Choose Path

After assessment, if user says "fix it" / "improve my reliability" / "enable zone redundancy":

1. List each fixable finding with the specific action
2. Flag any cost implications or breaking changes
3. **Ask user which path they want:**

```
I'll start with the quick wins (no downtime, fast):

1. ✏️  Enable zone redundancy on plan-ii5trxva2ark4 (Flex Consumption — no cost change)
2. ✏️  Set health check path to /api/health on func-api-ii5trxva2ark4

Then, separately, I'll ask if you want to upgrade storage:

3. 🕒  Upgrade stii5trxva2ark4 from LRS → ZRS (small cost increase, migration takes hours)
   — Required for full zone redundancy, but I'll confirm with you before starting.

How would you like to apply these changes?

  A) Fix now — Run az CLI commands against your live resources (immediate, one-time)
  B) Patch my IaC — Update your Bicep/Terraform files so changes persist across deploys

(If you use azd or Terraform, option B is recommended so `azd up` won't overwrite changes.)
```

### Path A: Fix Now (CLI)

Run fixes against live resources using `az` CLI commands. **Quick wins first, then ask before the slow storage migration.**

The exact CLI commands per service live in the per-service references — pick the one(s) matching the resources discovered in Phase 2:

| Fix | Reference |
|---|---|
| Enable zone redundancy / configure health probes (Functions) | [references/services/functions/reliability.md](references/services/functions/reliability.md) |
| Enable zone redundancy / configure health probes (App Service) | [references/services/app-service/reliability.md](references/services/app-service/reliability.md) |
| Upgrade storage replication (cross-service) | [references/configure-storage.md](references/configure-storage.md) |
| Set up multi-region (cross-service) | [references/configure-multi-region.md](references/configure-multi-region.md) |
| Platform overview / verification | [references/configure-zone-redundancy.md](references/configure-zone-redundancy.md), [references/configure-health-probes.md](references/configure-health-probes.md) |

**Execution order — always quick wins first:**

1. **Zone redundancy on compute** (fast, in-place property update on the App's plan).
2. **Health probes** (Premium / Dedicated only — in-place; for FC1 / Consumption, follow the consent gate in [configure-health-probes.md](references/configure-health-probes.md)).
3. **Verify** the compute changes succeeded before doing anything else.
4. **⛔ STOP — Ask about storage upgrade.** Compute is now zone-redundant, but storage may still be LRS or GRS. Ask the user explicitly:

   ```
   ✅ Compute is now zone-redundant.

   To be **fully zone-redundant**, your storage account also needs to be upgraded:
     • stii5trxva2ark4: currently `Standard_LRS` → needs `Standard_ZRS`

   ⚠️  This is a live storage redundancy conversion:
      • Takes hours to days depending on data volume
      • Small ongoing cost increase (~$0.01/GB/month more)
      • Only supported for Standard general-purpose v2 accounts

   Do you want me to start the storage migration now? (yes / no / later)
   ```

   - **yes** → run `az storage account update --sku Standard_ZRS` (or `migration start` if needed); poll `az storage account show --query sku.name` until it reports `Standard_ZRS`.
   - **no / later** → leave storage as-is; note in the re-assessment that ZR storage remains a gap.

5. **Multi-region** — do NOT auto-run. Handled in **Step 3** below as an explicit follow-up after re-assessment.

> **⚠️ Warning:** If the user uses `azd up` or `terraform apply` later, CLI-only changes may be overwritten by the IaC definitions. Recommend also patching IaC after CLI fixes.

### Path B: Patch IaC

Update the user's Bicep or Terraform files so reliability settings are persistent.

**Step 1: Detect IaC type**
1. Look for `infra/` folder in project root
2. If not found, check project root for `*.bicep` or `*.tf` files
3. If still not found, ask user: "Where are your IaC files located?"
4. Check for `*.bicep` files → use Bicep patching
5. Check for `*.tf` files → use Terraform patching
6. If both exist, ask user which to patch
7. If no IaC exists, fall back to Path A (CLI) and inform user

**Step 2: Classify each fix by risk level**

| Fix | Risk Level | What Happens |
|-----|-----------|--------------|
| Zone redundancy (App plan) | 🟢 Safe patch | In-place property update on next deploy |
| Storage LRS → ZRS | 🟡 Pre-migration required | Live storage migration must complete before the IaC SKU change can deploy. **Never bundle with safe patches** — use the two-deploy flow in Steps 3–5. |
| Health check path (Basic/Standard/Premium / Dedicated) | 🟢 Safe patch | In-place update, but causes app restart |
| Health check path (FC1 / Consumption) | ⚪ Code-only — ask first | `healthCheckPath` is unsupported. Adding a health endpoint requires adding an HTTP-triggered `/api/health` function to **app code**. **Always ask the user for explicit consent before touching source code.** Do **not** patch IaC. |

**Step 3: Apply patches in two deploys (quick wins first)**

The IaC patching framework (detection, AVM-module guidance, deploy-order rule, storage SKU patch) lives in:

| IaC Type | Framework reference |
|---|---|
| Bicep | [references/iac-patching-bicep.md](references/iac-patching-bicep.md) |
| Terraform | [references/iac-patching-terraform.md](references/iac-patching-terraform.md) |

The actual **per-service compute patches** (Function App plan ZR, App Service Plan ZR, etc.) live in the per-service references — load the matching service file from Phase 2 for the exact Bicep / Terraform / AVM snippets. Only Azure Functions and App Service have per-service references in this skill version; Container Apps is out of scope.

**Deploy 1 — Quick wins only.** Patch the 🟢 Safe items (zone redundancy on the App Service/Function App plan, health probes on Basic/Standard/Premium / Dedicated). Do **NOT** include the storage SKU patch in this deploy.

After patching, **the skill runs the deploy itself** (do not stop and tell the user to run it). Detect the deployment tool and confirm once before executing:

```
📦 Patches applied to your IaC. Ready to deploy:
   Tool detected: azd (found azure.yaml)
   Command:       azd up

Proceed with deployment? (yes / no)
```

On **yes**, run the appropriate command, stream output back to the user, and continue to the next step on success:
- AZD project (has `azure.yaml`): `azd up`
- Bicep-only: `az deployment group create --resource-group <rg> --template-file infra/main.bicep --parameters @infra/main.parameters.json`
- Terraform: `terraform plan -out tfplan` → (show plan summary) → `terraform apply tfplan`

On **no**, stop and report the patched files; do not proceed to Step 4 / Re-Assess.

If deployment fails, surface the error and stop — do not continue to the storage step.

**⛔ STOP — Ask about storage upgrade before Deploy 2.** After Deploy 1 succeeds, ask the user explicitly:

```
✅ Quick-win patches deployed. Compute is now zone-redundant.

To be **fully zone-redundant**, your storage account also needs to be upgraded:
  • stii5trxva2ark4: currently `Standard_LRS` → needs `Standard_ZRS`

⚠️  This is a two-part change:
   1. Live storage migration (`az storage account migration start`) — takes hours to days
   2. A second deploy to update your IaC's storage SKU to match

Do you want me to start the storage migration now? (yes / no / later)
```

- **yes** → the skill runs the migration command itself, polls until complete, then patches the storage SKU in IaC and runs **Deploy 2** (now a no-op confirmation). The user does not need to run anything manually.
- **no / later** → leave the storage SKU patch unapplied. Note in the re-assessment that ZR storage remains a gap; suggest revisiting later.

**Step 4: Storage migration (only if user said yes in Step 3)**

The skill runs these commands itself — do not ask the user to run them. Show progress as you go:

```
🔄 Starting storage migration (this can take up to 72 hours)...

   az storage account migration start --name stii5trxva2ark4 \
     --resource-group rg-example --sku Standard_ZRS --no-wait

   Polling: az storage account show --name stii5trxva2ark4 --query sku.name
   ...
   ✅ Migration complete: sku.name = Standard_ZRS
```

For very long migrations, you may surface a checkpoint to the user ("this is still running, check back later") rather than blocking the entire conversation.

**Step 5: Deploy 2 — storage SKU patch**

After the migration completes, the skill patches the storage SKU in IaC and runs the same deploy command as Step 3 (e.g. `azd up`). This deploy is a no-op confirmation that the IaC matches the live state. Confirm once with the user before executing, then run it directly.

### Step 2 (both paths): Re-Assess

After changes are applied (CLI) or deployed (IaC), automatically re-run the assessment and show the **same feature-pivoted table** as Phase 3, with each feature row's status updated to reflect the new state. Briefly call out what changed since the previous run.

```
🔄 Reliability Re-Assessment — rg-eventhubs-python-jan13 (eastus)
───────────────────────────────────────────────────────────────────────────────────────
Reliability Feature              Status      Resources
───────────────────────────────────────────────────────────────────────────────────────
Zone redundancy — compute        🟢 ON       • plan-ii5trxva2ark4 (FC1)              — now ON
                                             • plan-web-ii5trxva2ark4 (P1v3)         — now ON

Zone-redundant storage           🟢 ZRS      • stii5trxva2ark4                       — GRS → ZRS

Health probes                    🟡 PARTIAL  • func-api-ii5trxva2ark4                — still off (FC1, code change declined)
                                             • app-web-ii5trxva2ark4                 — now ON

Multi-region failover            🔴 OFF      • Single region (eastus) only
───────────────────────────────────────────────────────────────────────────────────────

What changed: Function App and App Service plan zone redundancy, storage replication and health probes on App Service.
(Multi-region offered next — see Step 3.)
```

### Step 3 (both paths): Multi-region follow-up — ASK and WAIT

Multi-region is a significant cost/complexity step. Do **NOT** start it automatically. After re-assessment, only if **all core single-region reliability features are 🟢 ON** (zone-redundant compute, ZRS/GZRS storage, health probes), explicitly ask the user and **wait for their response** before doing anything:

```
🟢 Your app is now fully zone-redundant in {region}.

The next step (optional) is multi-region failover with Azure Front Door:
   • Deploys compute + storage in a second region (paired region recommended)
   • Adds Azure Front Door for global load balancing with health-probe-driven failover
   • Protects against full region outages
   • Estimated additional cost: ~2x compute (active-passive); Front Door ~$35/month base

Do you want me to set up multi-region failover now? (yes / no / later)
```

- **yes** → proceed with [references/configure-multi-region.md](references/configure-multi-region.md). Confirm secondary region choice with the user, then:
  1. Generate the multi-region IaC (Bicep / Terraform additions for the secondary region + Front Door).
  2. Confirm once with the user: `📦 Multi-region IaC generated. Ready to deploy with \`azd up\`. Proceed? (yes / no)`
  3. On **yes**, **the skill runs the deploy itself** (`azd up` / `az deployment group create` / `terraform apply`) and streams output. Do not stop and tell the user to run it.
  4. After successful deploy, run a final re-assessment so the user sees Multi-region failover flip to 🟢 ON.
- **no / later** → leave the deployment as-is. Note that single-region zone-redundant is a reliable end state; multi-region can be revisited anytime.

> **⛔ Do not skip the wait.** Do not generate multi-region IaC, deploy a Front Door, or modify any files until the user has explicitly said yes. If core reliability is not yet all 🟢, do **not** ask about multi-region — finish the core gaps first.

## Priority Classification

| Priority | Criteria | Action |
|---|---|---|
| Critical | No zone redundancy AND production workload | Fix immediately |
| High | LRS storage on zone-redundant compute | Fix within days |
| Medium | No multi-region (single region but zone-redundant) | Plan for next sprint |
| Low | Missing health probes or monitoring gaps | Track and fix |

## Error Handling

| Error | Message | Remediation |
|---|---|---|
| Authentication required | "Please login" | Run `az login` and retry |
| Access denied | "Forbidden" | Confirm Reader/Contributor role assignment |
| Plan doesn't support ZR | "Upgrade required" | Inform user of plan upgrade path + cost delta |
| Region doesn't support AZ | "Region limitation" | Suggest supported regions |

## Best Practices

- Run reliability assessments after every significant infrastructure change
- Test failover scenarios periodically (at least quarterly)

## Skill Boundaries

| Action | This skill does | Hand off to |
|---|---|---|
| Assess reliability posture | ✅ Yes | — |
| Recommend improvements | ✅ Yes | — |
| Enable zone redundancy (CLI commands) | ✅ Yes | — |
| Patch Bicep/Terraform for reliability | ✅ Yes | — |
| Generate multi-region IaC | ✅ Yes (additions for the secondary region + Front Door) | `azure-prepare` for full new-app IaC scaffolding |
| Deploy IaC for reliability changes | ✅ Yes (runs `azd up` / `terraform apply` / `az deployment` itself, after user confirmation) | `azure-deploy` for general/non-reliability deploys |
| Validate pre-deployment | Reliability checks only | `azure-validate` for full validation |

<!-- chapter:end slug=azure-reliability -->

---

<!-- chapter:begin slug=azure-resource-lookup position=28 -->

## 28. azure-resource-lookup

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-resource-lookup/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-resource-lookup/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-resource-lookup.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (1), referenced from this skill's directory:
  - `references/azure-resource-graph.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-resource-lookup/references/azure-resource-graph.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-resource-lookup
description: "List, find, and show Azure resources across subscriptions or resource groups. Handles prompts like \"list the websites in my subscription\", \"list my web apps\", \"show my app services\", \"list virtual machines\", \"list my VMs\", \"show storage accounts\", \"find container apps\", and \"what resources do I have\". USE FOR: list websites, list web apps, list app services, show websites in subscription, resource inventory, find resources by tag, tag analysis, orphaned resource discovery (not for cost analysis), unattached disks, count resources by type, cross-subscription lookup, and Azure Resource Graph queries. DO NOT USE FOR: deploying/changing resources (use azure-deploy), cost optimization (use azure-cost), or non-Azure clouds."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Resource Lookup

List, find, and discover Azure resources of any type across subscriptions and resource groups. Use Azure Resource Graph (ARG) for fast, cross-cutting queries when dedicated MCP tools don't cover the resource type.

## When to Use This Skill

Use this skill when the user wants to:
- **List resources** of any type (VMs, web apps, storage accounts, container apps, databases, etc.)
- **Show resources** in a specific subscription or resource group
- Query resources **across multiple subscriptions** or resource types
- Find **orphaned resources** (unattached disks, unused NICs, idle IPs)
- Discover resources **missing required tags** or configurations
- Get a **resource inventory** spanning multiple types
- Find resources in a **specific state** (unhealthy, failed provisioning, stopped)
- Answer "**what resources do I have?**" or "**show me my Azure resources**"
- **List web apps, websites, or App Services**

> ⚠️ **Warning:** App Service / Web Apps have no dedicated MCP `list` command. Prompts like "list websites", "list web apps", or "list app services" **must** route through this skill to use Azure Resource Graph.

> 💡 **Tip:** For single-resource-type queries, first check if a dedicated MCP tool can handle it (see routing table below). If none exists, use Azure Resource Graph.

## Quick Reference

| Property | Value |
|----------|-------|
| **Query Language** | KQL (Kusto Query Language subset) |
| **CLI Command** | `az graph query -q "<KQL>" -o table` |
| **Extension** | `az extension add --name resource-graph` |
| **MCP Tool** | `extension_cli_generate` with intent for `az graph query` |
| **Best For** | Cross-subscription queries, orphaned resources, tag audits |

## MCP Tools

| Tool | Purpose | When to Use |
|------|---------|-------------|
| `extension_cli_generate` | Generate `az graph query` commands | Primary tool — generate ARG queries from user intent |
| `mcp_azure_mcp_subscription_list` | List available subscriptions | Discover subscription scope before querying |
| `mcp_azure_mcp_group_list` | List resource groups | Narrow query scope |

## Workflow

### Step 1: Check for a Dedicated MCP Tool

For single-resource-type queries, check if a dedicated MCP tool can handle it:

| Resource Type | MCP Tool | Coverage |
|---|---|---|
| Virtual Machines | `compute` | ✅ Full — list, details, sizes |
| Storage Accounts | `storage` | ✅ Full — accounts, blobs, tables |
| Cosmos DB | `cosmos` | ✅ Full — accounts, databases, queries |
| Key Vault | `keyvault` | ⚠️ Partial — secrets/keys only, no vault listing |
| SQL Databases | `sql` | ⚠️ Partial — requires resource group name |
| Container Registries | `acr` | ✅ Full — list registries |
| Kubernetes (AKS) | `aks` | ✅ Full — clusters, node pools |
| App Service / Web Apps | `appservice` | ❌ No list command — use ARG |
| Container Apps | — | ❌ No MCP tool — use ARG |
| Event Hubs | `eventhubs` | ✅ Full — namespaces, hubs |
| Service Bus | `servicebus` | ✅ Full — queues, topics |

If a dedicated tool is available with full coverage, use it. Otherwise proceed to Step 2.

### Step 2: Generate the ARG Query

Use `extension_cli_generate` to build the `az graph query` command:

```yaml
mcp_azure_mcp_extension_cli_generate
  intent: "query Azure Resource Graph to <user's request>"
  cli-type: "az"
```

See [Azure Resource Graph Query Patterns](references/azure-resource-graph.md) for common KQL patterns.

### Step 3: Execute and Format Results

Run the generated command. Use `--query` (JMESPath) to shape output:

```bash
az graph query -q "<KQL>" --query "data[].{name:name, type:type, rg:resourceGroup}" -o table
```

Use `--first N` to limit results. Use `--subscriptions` to scope.

## Error Handling

| Error | Cause | Fix |
|-------|-------|-----|
| `resource-graph extension not found` | Extension not installed | `az extension add --name resource-graph` |
| `AuthorizationFailed` | No read access to subscription | Check RBAC — need Reader role |
| `BadRequest` on query | Invalid KQL syntax | Verify table/column names; use `=~` for case-insensitive type matching |
| Empty results | No matching resources or wrong scope | Check `--subscriptions` flag; verify resource type spelling |

## Constraints

- ✅ **Always** use `=~` for case-insensitive type matching (types are lowercase)
- ✅ **Always** scope queries with `--subscriptions` or `--first` for large tenants
- ✅ **Prefer** dedicated MCP tools for single-resource-type queries
- ❌ **Never** use ARG for real-time monitoring (data has slight delay)
- ❌ **Never** attempt mutations through ARG (read-only)

<!-- chapter:end slug=azure-resource-lookup -->

---

<!-- chapter:begin slug=azure-resource-visualizer position=29 -->

## 29. azure-resource-visualizer

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-resource-visualizer/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-resource-visualizer/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-resource-visualizer.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (3), referenced from this skill's directory:
  - `assets/example-diagram.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-resource-visualizer/assets/example-diagram.md
  - `assets/template-architecture.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-resource-visualizer/assets/template-architecture.md
  - `references/azure-resource-graph.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-resource-visualizer/references/azure-resource-graph.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-resource-visualizer
description: "Analyze Azure resource groups and generate detailed Mermaid architecture diagrams showing the relationships between individual resources. WHEN: create architecture diagram, visualize Azure resources, show resource relationships, generate Mermaid diagram, analyze resource group, diagram my resources, architecture visualization, resource topology, map Azure infrastructure."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Resource Visualizer - Architecture Diagram Generator

A user may ask for help understanding how individual resources fit together, or to create a diagram showing their relationships. Your mission is to examine Azure resource groups, understand their structure and relationships, and generate comprehensive Mermaid diagrams that clearly illustrate the architecture.

## Core Responsibilities

1. **Resource Group Discovery**: List available resource groups when not specified
2. **Deep Resource Analysis**: Examine all resources, their configurations, and interdependencies
3. **Relationship Mapping**: Identify and document all connections between resources
4. **Diagram Generation**: Create detailed, accurate Mermaid diagrams
5. **Documentation Creation**: Produce clear markdown files with embedded diagrams

## Workflow Process

### Step 1: Resource Group Selection

If the user hasn't specified a resource group:

1. Use your tools to query available resource groups. If you do not have a tool for this, use `az`.
2. Present a numbered list of resource groups with their locations
3. Ask the user to select one by number or name
4. Wait for user response before proceeding

If a resource group is specified, validate it exists and proceed.

### Step 2: Resource Discovery & Analysis

For bulk resource discovery across subscriptions, use Azure Resource Graph queries. See [Azure Resource Graph Queries](references/azure-resource-graph.md) for cross-subscription inventory and relationship discovery patterns.

Once you have the resource group:

1. **Query all resources** in the resource group using Azure MCP tools or `az`.
2. **Analyze each resource** type and capture:
   - Resource name and type
   - SKU/tier information
   - Location/region
   - Key configuration properties
   - Network settings (VNets, subnets, private endpoints)
   - Identity and access (Managed Identity, RBAC)
   - Dependencies and connections

3. **Map relationships** by identifying:
   - **Network connections**: VNet peering, subnet assignments, NSG rules, private endpoints
   - **Data flow**: Apps → Databases, Functions → Storage, API Management → Backends
   - **Identity**: Managed identities connecting to resources
   - **Configuration**: App Settings pointing to Key Vaults, connection strings
   - **Dependencies**: Parent-child relationships, required resources

> **Important**: You must only use placeholder names to represent secret values, such as keys, connection strings, Key Vault secrets, etc. Use meaningful placeholder names to represent each secret in the diagram. Never put secret values in the resource diagram.

### Step 3: Diagram Construction

Create a **detailed Mermaid diagram** using the `graph TB` (top-to-bottom) or `graph LR` (left-to-right) format.

See [example-diagram.md](./assets/example-diagram.md) for a complete sample architecture diagram.

**Key Diagram Requirements:**

- **Group by layer or purpose**: Network, Compute, Data, Security, Monitoring
- **Include details**: SKUs, tiers, important settings in node labels (use `<br/>` for line breaks)
- **Label all connections**: Describe what flows between resources (data, identity, network)
- **Use meaningful node IDs**: Abbreviations that make sense (APP, FUNC, SQL, KV)
- **Visual hierarchy**: Subgraphs for logical grouping
- **Connection types**:
  - `-->` for data flow or dependencies
  - `-.->` for optional/conditional connections
  - `==>` for critical/primary paths

**Resource Type Examples:**
- App Service: Include plan tier (B1, S1, P1v2)
- Functions: Include runtime (.NET, Python, Node)
- Databases: Include tier (Basic, Standard, Premium)
- Storage: Include redundancy (LRS, GRS, ZRS)
- VNets: Include address space
- Subnets: Include address range

### Step 4: File Creation

Use [template-architecture.md](./assets/template-architecture.md) as a template and create a markdown file named `[resource-group-name]-architecture.md` with:

1. **Header**: Resource group name, subscription, region
2. **Summary**: Brief overview of the architecture (2-3 paragraphs)
3. **Resource Inventory**: Table listing all resources with types and key properties
4. **Architecture Diagram**: The complete Mermaid diagram
5. **Relationship Details**: Explanation of key connections and data flows
6. **Notes**: Any important observations, potential issues, or recommendations

## Operating Guidelines

### Quality Standards

- **Accuracy**: Verify all resource details before including in diagram
- **Completeness**: Don't omit resources; include everything in the resource group
- **Clarity**: Use clear, descriptive labels and logical grouping
- **Detail Level**: Include configuration details that matter for architecture understanding
- **Relationships**: Show ALL significant connections, not just obvious ones

### Tool Usage Patterns

1. **Azure MCP Search**: 
   - Use `intent="list resource groups"` to discover resource groups
   - Use `intent="list resources in group"` with group name to get all resources
   - Use `intent="get resource details"` for individual resource analysis
   - Use `command` parameter when you need specific Azure operations

2. **File Creation**:
   - Always create in workspace root or a `docs/` folder if it exists
   - Use clear, descriptive filenames: `[rg-name]-architecture.md`
   - Ensure Mermaid syntax is valid (test syntax mentally before output)

3. **Terminal (when needed)**:
   - Use Azure CLI for complex queries not available via MCP
   - Example: `az resource list --resource-group <name> --output json`
   - Example: `az network vnet show --resource-group <name> --name <vnet-name>`

### Constraints & Boundaries

**Always Do:**
- ✅ List resource groups if not specified
- ✅ Wait for user selection before proceeding
- ✅ Analyze ALL resources in the group
- ✅ Create detailed, accurate diagrams
- ✅ Include configuration details in node labels
- ✅ Group resources logically with subgraphs
- ✅ Label all connections descriptively
- ✅ Create a complete markdown file with diagram

**Never Do:**
- ❌ Skip resources because they seem unimportant
- ❌ Make assumptions about resource relationships without verification
- ❌ Create incomplete or placeholder diagrams
- ❌ Omit configuration details that affect architecture
- ❌ Proceed without confirming resource group selection
- ❌ Generate invalid Mermaid syntax
- ❌ Modify or delete Azure resources (read-only analysis)

### Edge Cases & Error Handling

- **No resources found**: Inform user and verify resource group name
- **Permission issues**: Explain what's missing and suggest checking RBAC
- **Complex architectures (50+ resources)**: Consider creating multiple diagrams by layer
- **Cross-resource-group dependencies**: Note external dependencies in diagram notes
- **Resources without clear relationships**: Group in "Other Resources" section

## Output Format Specifications

### Mermaid Diagram Syntax
- Use `graph TB` (top-to-bottom) for vertical layouts
- Use `graph LR` (left-to-right) for horizontal layouts (better for wide architectures)
- Subgraph syntax: `subgraph "Descriptive Name"`
- Node syntax: `ID["Display Name<br/>Details"]`
- Connection syntax: `SOURCE -->|"Label"| TARGET`

### Markdown Structure
- Use H1 for main title
- Use H2 for major sections
- Use H3 for subsections
- Use tables for resource inventories
- Use bullet lists for notes and recommendations
- Use code blocks with `mermaid` language tag for diagrams

## Success Criteria

A successful analysis includes:
- ✅ Valid resource group identified
- ✅ All resources discovered and analyzed
- ✅ All significant relationships mapped
- ✅ Detailed Mermaid diagram with proper grouping
- ✅ Complete markdown file created
- ✅ Clear, actionable documentation
- ✅ Valid Mermaid syntax that renders correctly
- ✅ Professional, architect-level output

Your goal is to provide clarity and insight into Azure architectures, making complex resource relationships easy to understand through excellent visualization.

<!-- chapter:end slug=azure-resource-visualizer -->

---

<!-- chapter:begin slug=azure-storage position=30 -->

## 30. azure-storage

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-storage/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-storage.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (13), referenced from this skill's directory:
  - `references/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/auth-best-practices.md
  - `references/sdk-usage.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk-usage.md
  - `references/sdk/azure-data-tables-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-data-tables-java.md
  - `references/sdk/azure-data-tables-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-data-tables-py.md
  - `references/sdk/azure-storage-blob-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-blob-java.md
  - `references/sdk/azure-storage-blob-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-blob-py.md
  - `references/sdk/azure-storage-blob-rust.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-blob-rust.md
  - `references/sdk/azure-storage-blob-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-blob-ts.md
  - `references/sdk/azure-storage-file-datalake-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-file-datalake-py.md
  - `references/sdk/azure-storage-file-share-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-file-share-py.md
  - `references/sdk/azure-storage-file-share-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-file-share-ts.md
  - `references/sdk/azure-storage-queue-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-queue-py.md
  - `references/sdk/azure-storage-queue-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-storage/references/sdk/azure-storage-queue-ts.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-storage
description: "Azure Storage Services including Blob Storage, File Shares, Queue Storage, Table Storage, and Data Lake. Answers questions about storage access tiers (hot, cool, cold, archive), when to use each tier, and tier comparison. Provides object storage, SMB file shares, async messaging, NoSQL key-value, and big data analytics. Includes lifecycle management. USE FOR: blob storage, file shares, queue storage, table storage, data lake, upload files, download blobs, storage accounts, access tiers, storage tiers, hot cool cold archive, storage tier comparison, when to use storage tiers, lifecycle management, Azure Storage concepts. DO NOT USE FOR: SQL databases, Cosmos DB (use azure-prepare), messaging with Event Hubs or Service Bus (use azure-messaging)."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Storage Services

## Services

| Service | Use When | MCP Tools | CLI |
|---------|----------|-----------|-----|
| Blob Storage | Objects, files, backups, static content | `azure__storage` | `az storage blob` |
| File Shares | SMB file shares, lift-and-shift | - | `az storage file` |
| Queue Storage | Async messaging, task queues | - | `az storage queue` |
| Table Storage | NoSQL key-value (consider Cosmos DB) | - | `az storage table` |
| Data Lake | Big data analytics, hierarchical namespace | - | `az storage fs` |

## MCP Server (Preferred)

When Azure MCP is enabled:

- `azure__storage` with command `storage_account_list` - List storage accounts
- `azure__storage` with command `storage_container_list` - List containers in account
- `azure__storage` with command `storage_blob_list` - List blobs in container
- `azure__storage` with command `storage_blob_get` - Download blob content
- `azure__storage` with command `storage_blob_put` - Upload blob content

**If Azure MCP is not enabled:** Run `/azure:setup` or enable via `/mcp`.

## CLI Fallback

```bash
# List storage accounts
az storage account list --output table

# List containers
az storage container list --account-name ACCOUNT --output table

# List blobs
az storage blob list --account-name ACCOUNT --container-name CONTAINER --output table

# Download blob
az storage blob download --account-name ACCOUNT --container-name CONTAINER --name BLOB --file LOCAL_PATH

# Upload blob
az storage blob upload --account-name ACCOUNT --container-name CONTAINER --name BLOB --file LOCAL_PATH
```

## Storage Account Tiers

| Tier | Use Case | Performance |
|------|----------|-------------|
| Standard | General purpose, backup | Milliseconds |
| Premium | Databases, high IOPS | Sub-millisecond |

## Blob Access Tiers

| Tier | Access Frequency | Cost |
|------|-----------------|------|
| Hot | Frequent | Higher storage, lower access |
| Cool | Infrequent (30+ days) | Lower storage, higher access |
| Cold | Rare (90+ days) | Lower still |
| Archive | Rarely (180+ days) | Lowest storage, rehydration required |

## Redundancy Options

| Type | Durability | Use Case |
|------|------------|----------|
| LRS | 11 nines | Dev/test, recreatable data |
| ZRS | 12 nines | Regional high availability |
| GRS | 16 nines | Disaster recovery |
| GZRS | 16 nines | Best durability |

## Service Details

For deep documentation on specific services:

- Blob storage patterns and lifecycle -> [Blob Storage documentation](https://learn.microsoft.com/azure/storage/blobs/storage-blobs-overview)
- File shares and Azure File Sync -> [Azure Files documentation](https://learn.microsoft.com/azure/storage/files/storage-files-introduction)
- Queue patterns and poison handling -> [Queue Storage documentation](https://learn.microsoft.com/azure/storage/queues/storage-queues-introduction)

## SDK Quick References

For building applications with Azure Storage SDKs, see the condensed guides:

- **Blob Storage**: [Python](references/sdk/azure-storage-blob-py.md) | [TypeScript](references/sdk/azure-storage-blob-ts.md) | [Java](references/sdk/azure-storage-blob-java.md) | [Rust](references/sdk/azure-storage-blob-rust.md)
- **Queue Storage**: [Python](references/sdk/azure-storage-queue-py.md) | [TypeScript](references/sdk/azure-storage-queue-ts.md)
- **File Shares**: [Python](references/sdk/azure-storage-file-share-py.md) | [TypeScript](references/sdk/azure-storage-file-share-ts.md)
- **Data Lake**: [Python](references/sdk/azure-storage-file-datalake-py.md)
- **Tables**: [Python](references/sdk/azure-data-tables-py.md) | [Java](references/sdk/azure-data-tables-java.md)

For full package listing across all languages, see [SDK Usage Guide](references/sdk-usage.md).

## Azure SDKs

For building applications that interact with Azure Storage programmatically, Azure provides SDK packages in multiple languages (.NET, Java, JavaScript, Python, Go, Rust). See [SDK Usage Guide](references/sdk-usage.md) for package names, installation commands, and quick start examples.

<!-- chapter:end slug=azure-storage -->

---

<!-- chapter:begin slug=azure-upgrade position=31 -->

## 31. azure-upgrade

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-upgrade/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-upgrade.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (30), referenced from this skill's directory:
  - `references/global-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/global-rules.md
  - `references/languages/java/bom-migration/bom-gradle-settings.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/bom-migration/bom-gradle-settings.md
  - `references/languages/java/bom-migration/bom-gradle-toml.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/bom-migration/bom-gradle-toml.md
  - `references/languages/java/bom-migration/bom-gradle.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/bom-migration/bom-gradle.md
  - `references/languages/java/bom-migration/bom-maven.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/bom-migration/bom-maven.md
  - `references/languages/java/bom-migration/bom-migration.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/bom-migration/bom-migration.md
  - `references/languages/java/bom-migration/bom-validation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/bom-migration/bom-validation.md
  - `references/languages/java/INSTRUCTION.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/INSTRUCTION.md
  - `references/languages/java/package-specific/com.microsoft.azure.eventprocessorhost.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/package-specific/com.microsoft.azure.eventprocessorhost.md
  - `references/languages/java/package-specific/com.microsoft.azure.management.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/package-specific/com.microsoft.azure.management.md
  - `references/languages/java/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/README.md
  - `references/languages/java/rules/efficiency.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/rules/efficiency.md
  - `references/languages/java/rules/execution-guidelines.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/rules/execution-guidelines.md
  - `references/languages/java/rules/review-code-changes.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/rules/review-code-changes.md
  - `references/languages/java/rules/troubleshooting.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/rules/troubleshooting.md
  - `references/languages/java/rules/upgrade-strategy.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/rules/upgrade-strategy.md
  - `references/languages/java/rules/upgrade-success-criteria.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/rules/upgrade-success-criteria.md
  - `references/languages/java/scripts/upgrade_bom.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/scripts/upgrade_bom.py
  - `references/languages/java/templates/PLAN_TEMPLATE.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/templates/PLAN_TEMPLATE.md
  - `references/languages/java/templates/PROGRESS_TEMPLATE.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/templates/PROGRESS_TEMPLATE.md
  - `references/languages/java/templates/SUMMARY_TEMPLATE.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/templates/SUMMARY_TEMPLATE.md
  - `references/languages/java/workflow/phase-1-precheck.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/workflow/phase-1-precheck.md
  - `references/languages/java/workflow/phase-2-plan.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/workflow/phase-2-plan.md
  - `references/languages/java/workflow/phase-3-execute.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-upgrade/references/languages/java/workflow/phase-3-execute.md
  - …and 6 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-upgrade

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-upgrade
description: "Assess and upgrade Azure workloads between plans, tiers, or SKUs, or modernize Azure SDK dependencies in source code. WHEN: upgrade Consumption to Flex Consumption, upgrade Azure Functions plan, change hosting plan, function app SKU, migrate App Service to Container Apps, modernize legacy Azure Java SDKs (com.microsoft.azure to com.azure), migrate Azure Cache for Redis (ACR/ACRE) to Azure Managed Redis (AMR)."
license: MIT
compatibility: python3.10+
metadata:
  author: Microsoft
  version: "1.2.1"
---

# Azure Upgrade

> This skill handles **assessment and automated upgrades** of existing Azure workloads from one Azure service, hosting plan, or SKU to another — all within Azure. This includes plan/tier upgrades (e.g. Consumption → Flex Consumption), cross-service migrations (e.g. App Service → Container Apps), and SKU changes. It also covers **Azure SDK for Java source-code modernization** (e.g. legacy Java `com.microsoft.azure.*` → modern `com.azure.*`). This is NOT for cross-cloud migration — use `azure-cloud-migrate` for that.

## Triggers

| User Intent | Example Prompts |
|-------------|-----------------|
| Upgrade Azure Functions plan | "Upgrade my function app from Consumption to Flex Consumption" |
| Change hosting tier | "Move my function app to a better plan" |
| Assess upgrade readiness | "Is my function app ready for Flex Consumption?" |
| Automate plan migration | "Automate the steps to upgrade my Functions plan" |
| Modernize legacy Azure Java SDK | "Migrate legacy Azure SDKs for Java", "Upgrade legacy Azure Java SDK", "Migrate my Java project from com.microsoft.azure to com.azure" |
| Migrate Azure Cache for Redis (ACR/OSS) to Azure Managed Redis (AMR) | "Migrate my Redis cache to AMR", "ACR to AMR", "OSS to AMR", "Upgrade my Premium P2 cache to Managed Redis", "Pick an AMR SKU", "Convert my Redis IaC template to AMR" |
| Migrate Azure Cache for Redis Enterprise (ACRE) to Azure Managed Redis (AMR) | "Migrate my Enterprise_E10 cache to AMR", "ACRE to AMR", "Update my ACRE IaC template for AMR", "Migrate EnterpriseFlash to AMR", "Migrate my geo-replicated Enterprise Redis" |

## Rules

1. Follow phases sequentially — do not skip
2. Generate an assessment before any upgrade operations
3. Load the scenario reference and follow its rules
4. Use `mcp_azure_mcp_get_azure_bestpractices` and `mcp_azure_mcp_documentation` MCP tools
5. Destructive actions require `ask_user` — [global-rules](references/global-rules.md)
6. Always confirm the target plan/SKU with the user before proceeding
7. Never delete or stop the original app without explicit user confirmation
8. All automation scripts must be idempotent and resumable

## Upgrade Scenarios

| Source | Target | Reference |
|--------|--------|-----------|
| Azure Functions Consumption Plan | Azure Functions Flex Consumption Plan | [consumption-to-flex.md](references/services/functions/consumption-to-flex.md) |
| Legacy Azure Java SDK (`com.microsoft.azure.*`) | Modern Azure Java SDK (`com.azure.*`) | [languages/java/README.md](references/languages/java/README.md) |
| Azure Cache for Redis (ACR/OSS) Basic/Standard/Premium | Azure Managed Redis (AMR) | [services/redis/redis-to-amr.md](references/services/redis/redis-to-amr.md) |
| Azure Cache for Redis Enterprise (ACRE) / Enterprise Flash | Azure Managed Redis (AMR) | [services/redis/redis-to-amr.md](references/services/redis/redis-to-amr.md) |

> SDK upgrade scenarios (e.g. Java legacy → modern) run a **source-code modernization flow** that is distinct from Azure service/plan/SKU upgrades: follow the scenario reference, **not** the Steps below.

> No matching scenario? Use `mcp_azure_mcp_documentation` and `mcp_azure_mcp_get_azure_bestpractices` tools to research the upgrade path.

## MCP Tools

| Tool | Purpose |
|------|---------|
| `mcp_azure_mcp_get_azure_bestpractices` | Get Azure best practices for the target service |
| `mcp_azure_mcp_documentation` | Look up Azure documentation for upgrade scenarios |
| `mcp_azure_mcp_appservice` | Query App Service and Functions plan details |
| `mcp_azure_mcp_applicationinsights` | Verify monitoring configuration |

## Steps

1. **Identify** — Determine the source and target Azure plans/SKUs. Ask user to confirm.
2. **Assess** — Analyze existing app for upgrade readiness → load scenario reference (e.g., [consumption-to-flex.md](references/services/functions/consumption-to-flex.md))
3. **Pre-migrate** — Collect settings, identities, configs from the existing app
4. **Upgrade** — Execute the automated upgrade steps (create new resources, migrate settings, deploy code)
5. **Validate** — Hit the function app default URL to confirm the app is reachable, then verify endpoints and monitoring
6. **Ask User** — "Upgrade complete. Would you like to verify performance, clean up the old app, or update your IaC?"
7. **Hand off** to `azure-validate` for deep validation or `azure-deploy` for CI/CD setup

Track progress in `upgrade-status.md` inside the workspace root.

## References

- [Global Rules](references/global-rules.md)
- [Workflow Details](references/workflow-details.md)
- **Functions**
  - [Consumption to Flex Consumption](references/services/functions/consumption-to-flex.md)
  - [Assessment](references/services/functions/assessment.md)
  - [Automation Scripts](references/services/functions/automation.md)
- **Redis**
  - [Redis (ACR or ACRE) to AMR Migration](references/services/redis/redis-to-amr.md) — routes to dedicated [amr-migration-skill](https://github.com/AzureManagedRedis/amr-migration-skill) (ACR/OSS) or [acre-to-amr-migration-skill](https://github.com/AzureManagedRedis/acre-to-amr-migration-skill) (Enterprise)
- **Java SDK Migration Templates**
  - [Plan Template](references/languages/java/templates/PLAN_TEMPLATE.md)
  - [Progress Template](references/languages/java/templates/PROGRESS_TEMPLATE.md)
  - [Summary Template](references/languages/java/templates/SUMMARY_TEMPLATE.md)

## Next

After upgrade is validated, hand off to:
- `azure-validate` — for thorough post-upgrade validation
- `azure-deploy` — if the user wants to set up CI/CD for the new app

<!-- chapter:end slug=azure-upgrade -->

---

<!-- chapter:begin slug=azure-validate position=32 -->

## 32. azure-validate

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/azure-validate/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/azure-validate.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (26), referenced from this skill's directory:
  - `references/aspire-functions-secrets.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/aspire-functions-secrets.md
  - `references/global-rules.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/global-rules.md
  - `references/policy-validation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/policy-validation.md
  - `references/recipes/azcli/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azcli/errors.md
  - `references/recipes/azcli/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azcli/README.md
  - `references/recipes/azd/aspire.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azd/aspire.md
  - `references/recipes/azd/environment.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azd/environment.md
  - `references/recipes/azd/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azd/errors.md
  - `references/recipes/azd/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azd/README.md
  - `references/recipes/azd/scripts/set-aspire-aca-env.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azd/scripts/set-aspire-aca-env.ps1
  - `references/recipes/azd/scripts/set-aspire-aca-env.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/azd/scripts/set-aspire-aca-env.sh
  - `references/recipes/bicep/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/bicep/errors.md
  - `references/recipes/bicep/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/bicep/README.md
  - `references/recipes/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/README.md
  - `references/recipes/scripts/validate-deployment.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/scripts/validate-deployment.ps1
  - `references/recipes/scripts/validate-deployment.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/scripts/validate-deployment.sh
  - `references/recipes/terraform/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/terraform/errors.md
  - `references/recipes/terraform/README.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/terraform/README.md
  - `references/recipes/terraform/scripts/validate-terraform.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/terraform/scripts/validate-terraform.ps1
  - `references/recipes/terraform/scripts/validate-terraform.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/recipes/terraform/scripts/validate-terraform.sh
  - `references/region-availability.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/region-availability.md
  - `references/role-verification.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/role-verification.md
  - `references/scripts/scan-aspire-functions-secrets.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/scripts/scan-aspire-functions-secrets.ps1
  - `references/scripts/scan-aspire-functions-secrets.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/azure-validate/references/scripts/scan-aspire-functions-secrets.sh
  - …and 2 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/azure-validate

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: azure-validate
description: "Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.2"
---

# Azure Validate

> **AUTHORITATIVE GUIDANCE** — Follow these instructions exactly unless they contradict security policies given to you.

> **⛔ STOP — PREREQUISITE CHECK REQUIRED**
>
> Before proceeding, verify this prerequisite is met:
>
> **azure-prepare** was invoked and completed → `.azure/deployment-plan.md` exists with status `Approved` or later
>
> If the plan is missing, **STOP IMMEDIATELY** and invoke **azure-prepare** first.
>
> The complete workflow ensures success:
>
> `azure-prepare` → `azure-validate` → `azure-deploy`

## Triggers

- Check if app is ready to deploy
- Validate azure.yaml or Bicep
- Run preflight checks
- Troubleshoot deployment errors

## Rules

1. Run after azure-prepare, before azure-deploy
2. All checks must pass—do not deploy with failures
3. ⛔ **Destructive actions require `ask_user`** — [global-rules](references/global-rules.md)

## Steps

Run the workflow script and follow its instructions. It walks you through each validation step one at a time, recording progress in `.azure/validate-status.json`. Use [references/scripts/workflow.ps1](references/scripts/workflow.ps1) on Windows or [references/scripts/workflow.sh](references/scripts/workflow.sh) on macOS/Linux.

Start by calling the script **without** the completed-step argument:

```bash
pwsh references/scripts/workflow.ps1 -WorkspacePath <workspace-path>
# macOS/Linux: bash references/scripts/workflow.sh --workspace-path <workspace-path>
```

Each run prints the next action and the value to pass next. Perform the action, then re-run with that value (`-CompletedStep <value>` for pwsh, `--completed-step <value>` for bash). Repeat until it reports the azure-validate workflow is complete.

The steps reference recipe details in [references/recipes/README.md](references/recipes/README.md) and role checks in [references/role-verification.md](references/role-verification.md).

> **⛔ VALIDATION AUTHORITY**
>
> This skill is the officially verified way to set plan status to `Validated`. You MUST follow the script's instructions to completion before setting status to `Validated`.
> Do NOT set status to `Validated` without doing so.

---

> **⚠️ NEXT STEP — DEPENDS ON USER INTENT**
>
> After ALL validations pass, check whether the user asked to deploy:
> - **If the user explicitly requested deployment**, you **MUST** invoke **azure-deploy** to execute it. Do NOT run `azd up`, `azd deploy`, or any deployment commands directly — let azure-deploy handle execution.
> - **If the user only asked to validate or prepare** (not deploy), STOP after recording proof and setting status to `Validated`. Report the validation results and do NOT invoke azure-deploy.
>
> If any validation failed, fix the issues and re-run azure-validate before proceeding.

<!-- chapter:end slug=azure-validate -->

---

<!-- chapter:begin slug=entra-agent-id position=33 -->

## 33. entra-agent-id

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/entra-agent-id/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-agent-id/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/entra-agent-id.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (6), referenced from this skill's directory:
  - `references/known-limitations.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-agent-id/references/known-limitations.md
  - `references/oauth2-token-flow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-agent-id/references/oauth2-token-flow.md
  - `references/obo-blueprint-setup.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-agent-id/references/obo-blueprint-setup.md
  - `references/runtime-token-exchange.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-agent-id/references/runtime-token-exchange.md
  - `references/sdk-sidecar-deployment.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-agent-id/references/sdk-sidecar-deployment.md
  - `references/sdk-sidecar.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-agent-id/references/sdk-sidecar.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: entra-agent-id
description: "Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmi_path, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmi_path token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry)."
license: MIT
metadata:
  author: Microsoft
  version: "1.1.1"
---

# Microsoft Entra Agent ID

Create and manage OAuth 2.0-capable identities for AI agents using Microsoft Graph. Every agent instance gets a distinct identity, audit trail, and independently-scoped permission grants.

## Quick Reference

| Property | Value |
|----------|-------|
| Service | Microsoft Entra Agent ID |
| API | Microsoft Graph (`https://graph.microsoft.com/v1.0`) |
| Required role | Agent Identity Developer, Agent Identity Administrator, or Application Administrator |
| Object model | Blueprint (application) → BlueprintPrincipal (SP) → Agent Identity (SP) |
| Runtime exchange | Two-step `fmi_path` exchange (autonomous and OBO) |
| .NET helper | `Microsoft.Identity.Web.AgentIdentities` |
| Polyglot helper | Microsoft Entra SDK for AgentID (sidecar container) |

## When to Use This Skill

- Provisioning a new Agent Identity Blueprint and BlueprintPrincipal
- Creating per-instance Agent Identities under a Blueprint
- Configuring credentials (FIC, Managed Identity, or client secret) on the Blueprint
- Implementing the two-step `fmi_path` runtime token exchange (autonomous or OBO)
- Cross-tenant agent token flows
- Deploying the Microsoft Entra SDK for AgentID sidecar for polyglot agents (Python, Node, Go, Java)
- Granting per-Agent-Identity application (`appRoleAssignments`) or delegated (`oauth2PermissionGrants`) permissions
- Diagnosing Agent ID errors such as `AADSTS82001`, `AADSTS700211`, or `PropertyNotCompatibleWithAgentIdentity`

## MCP Tools

| Tool | Use |
|------|-----|
| `mcp_azure_mcp_documentation` | Search Microsoft Learn for current Agent ID setup, Graph API shapes, and SDK configuration |

There is no dedicated Agent Identity MCP server today. This skill guides direct Microsoft Graph API calls (PowerShell or Python `requests`). Use `mcp_azure_mcp_documentation` to verify request bodies and endpoints against current docs before running.

## Before You Start

Use the `mcp_azure_mcp_documentation` tool to search Microsoft Learn for current Agent ID documentation:
- "Microsoft Entra Agent ID setup instructions"
- "Microsoft Entra SDK for AgentID"

Verify request bodies and endpoints against the installed SDK version — Graph API shapes evolve.

## Conceptual Model

```
Agent Identity Blueprint (application)         ← one per agent type/project
  └── BlueprintPrincipal (service principal)    ← MUST be created explicitly
        ├── Agent Identity (SP): agent-1        ← one per agent instance
        ├── Agent Identity (SP): agent-2
        └── Agent Identity (SP): agent-3
```

| Concept | Description |
|---------|-------------|
| **Blueprint** | Application object that defines a type/class of agent. Holds credentials (secret, certificate, federated identity). |
| **BlueprintPrincipal** | Service principal for the Blueprint in the tenant. Not auto-created. |
| **Agent Identity** | Service-principal-only identity for a single agent instance. Cannot hold its own credentials. |
| **Sponsor** | A User (or Group, for Agent Identity) who is responsible for the identity. Required on creation. |

## Prerequisites

### Required Entra Roles

One of: **Agent Identity Developer**, **Agent Identity Administrator**, or **Application Administrator**.

### PowerShell (interactive setup)

```powershell
# PowerShell 7+
Install-Module Microsoft.Graph.Applications -Scope CurrentUser -Force
```

### Python (programmatic provisioning)

```bash
pip install azure-identity requests
```

## Authentication

> **`DefaultAzureCredential` is not supported.** Azure CLI tokens carry `Directory.AccessAsUser.All`, which Agent Identity APIs hard-reject (403). Use a dedicated app registration with `client_credentials`, or `Connect-MgGraph` with explicit delegated scopes.

### PowerShell (delegated)

```powershell
Connect-MgGraph -Scopes @(
    "AgentIdentityBlueprint.Create",
    "AgentIdentityBlueprint.ReadWrite.All",
    "AgentIdentityBlueprintPrincipal.Create",
    "AgentIdentity.Create.All",
    "User.Read"
)
```

### Python (application)

```python
import os, requests
from azure.identity import ClientSecretCredential

credential = ClientSecretCredential(
    tenant_id=os.environ["AZURE_TENANT_ID"],
    client_id=os.environ["AZURE_CLIENT_ID"],
    client_secret=os.environ["AZURE_CLIENT_SECRET"],
)
token = credential.get_token("https://graph.microsoft.com/.default")

GRAPH = "https://graph.microsoft.com/v1.0"
headers = {
    "Authorization": f"Bearer {token.token}",
    "Content-Type": "application/json",
    "OData-Version": "4.0",
}
```

## Core Workflow

### Step 1: Create Agent Identity Blueprint

Use the typed endpoint. Sponsors must be **Users** at Blueprint creation. This snippet assumes the `requests` client and `headers` dict from the Python authentication block above.

```python
import subprocess
import requests

user_id = subprocess.run(
    ["az", "ad", "signed-in-user", "show", "--query", "id", "-o", "tsv"],
    capture_output=True, text=True, check=True,
).stdout.strip()

blueprint_body = {
    "displayName": "My Agent Blueprint",
    "sponsors@odata.bind": [
        f"https://graph.microsoft.com/v1.0/users/{user_id}"
    ],
}
resp = requests.post(
    f"{GRAPH}/applications/microsoft.graph.agentIdentityBlueprint",
    headers=headers, json=blueprint_body,
)
resp.raise_for_status()

blueprint = resp.json()
app_id = blueprint["appId"]
blueprint_obj_id = blueprint["id"]
```

### Step 2: Create BlueprintPrincipal

> Mandatory. Creating a Blueprint does NOT auto-create its service principal. Skipping this step produces:
> `400: The Agent Blueprint Principal for the Agent Blueprint does not exist.`

```python
sp_body = {"appId": app_id}
resp = requests.post(
    f"{GRAPH}/servicePrincipals/microsoft.graph.agentIdentityBlueprintPrincipal",
    headers=headers, json=sp_body,
)
resp.raise_for_status()
```

Make your provisioning scripts idempotent — always check for the BlueprintPrincipal even when the Blueprint already exists.

### Step 3: Create Agent Identities

Sponsors for an Agent Identity may be **Users or Groups**.

```python
agent_body = {
    "displayName": "my-agent-instance-1",
    "agentIdentityBlueprintId": app_id,
    "sponsors@odata.bind": [
        f"https://graph.microsoft.com/v1.0/users/{user_id}"
    ],
}
resp = requests.post(
    f"{GRAPH}/servicePrincipals/microsoft.graph.agentIdentity",
    headers=headers, json=agent_body,
)
resp.raise_for_status()
agent = resp.json()
agent_sp_id = agent["id"]
```

## Runtime Authentication

Agents authenticate at runtime using credentials configured on the **Blueprint** (not on the Agent Identity — Agent Identities can't hold credentials).

| Option | Use case | Credential on Blueprint |
|--------|----------|------------------------|
| **Managed Identity + WIF** | Production (Azure-hosted) | Federated Identity Credential |
| **Client secret** | Local dev / testing | Password credential |
| **Microsoft Entra SDK for AgentID** | Polyglot / 3P agents | Sidecar container acquires tokens over HTTP |

For the two-step `fmi_path` exchange (parent token → per-Agent-Identity Graph token) that gives each agent instance a distinct `sub` claim and audit trail, see [references/runtime-token-exchange.md](references/runtime-token-exchange.md).

For OBO (agent acting on behalf of a user), see [references/obo-blueprint-setup.md](references/obo-blueprint-setup.md).

For the containerized polyglot auth sidecar (Python, Node, Go, Java — no SDK embedding), see [references/sdk-sidecar.md](references/sdk-sidecar.md).

For MI+WIF and client-secret setup details, see [references/oauth2-token-flow.md](references/oauth2-token-flow.md).

### .NET quick path

For .NET services, use **`Microsoft.Identity.Web.AgentIdentities`** — it handles Federated Identity Credential management and the two-step exchange for you. See the package README at `github.com/AzureAD/microsoft-identity-web` under `src/Microsoft.Identity.Web.AgentIdentities/`.

## Granting Permissions (Per Agent Identity)

Agent Identities support both application permissions (autonomous) and delegated permissions (OBO). Grants are scoped **per Agent Identity**, not to the BlueprintPrincipal.

### Application permissions (autonomous)

```python
graph_sp = requests.get(
    f"{GRAPH}/servicePrincipals?$filter=appId eq '00000003-0000-0000-c000-000000000000'",
    headers=headers,
).json()["value"][0]

user_read_all = next(r for r in graph_sp["appRoles"] if r["value"] == "User.Read.All")

requests.post(
    f"{GRAPH}/servicePrincipals/{agent_sp_id}/appRoleAssignments",
    headers=headers,
    json={
        "principalId": agent_sp_id,
        "resourceId": graph_sp["id"],
        "appRoleId": user_read_all["id"],
    },
).raise_for_status()
```

### Delegated permissions (OBO)

```python
from datetime import datetime, timedelta, timezone

expiry = (datetime.now(timezone.utc) + timedelta(days=3650)).strftime("%Y-%m-%dT%H:%M:%SZ")

requests.post(
    f"{GRAPH}/oauth2PermissionGrants",
    headers=headers,
    json={
        "clientId": agent_sp_id,
        "consentType": "AllPrincipals",
        "resourceId": graph_sp["id"],
        "scope": "User.Read Tasks.ReadWrite Mail.Send",
        "expiryTime": expiry,
    },
).raise_for_status()
```

Browser-based admin consent URLs do not work for Agent Identities — use `oauth2PermissionGrants` for programmatic delegated consent.

## Cross-Tenant Agent Identities

Blueprints can be multi-tenant (`signInAudience: AzureADMultipleOrgs`). When exchanging tokens cross-tenant:

> **Step 1 of the parent token exchange MUST target the Agent Identity's home tenant**, not the Blueprint's. Wrong tenant → `AADSTS700211: No matching federated identity record found`.

See [references/runtime-token-exchange.md](references/runtime-token-exchange.md) for full cross-tenant examples.

## API Reference

| Operation | Method | Endpoint |
|-----------|--------|----------|
| Create Blueprint | `POST` | `/applications/microsoft.graph.agentIdentityBlueprint` |
| Create BlueprintPrincipal | `POST` | `/servicePrincipals/microsoft.graph.agentIdentityBlueprintPrincipal` |
| Create Agent Identity | `POST` | `/servicePrincipals/microsoft.graph.agentIdentity` |
| Add FIC to Blueprint | `POST` | `/applications/{id}/microsoft.graph.agentIdentityBlueprint/federatedIdentityCredentials` |
| List Agent Identities | `GET` | `/servicePrincipals/microsoft.graph.agentIdentity` |
| Grant app permission | `POST` | `/servicePrincipals/{id}/appRoleAssignments` |
| Grant delegated permission | `POST` | `/oauth2PermissionGrants` |
| Delete Agent Identity | `DELETE` | `/servicePrincipals/{id}` |
| Delete Blueprint | `DELETE` | `/applications/{id}` |

Base URL: `https://graph.microsoft.com/v1.0`.

## Required Graph Permissions

| Permission | Purpose |
|-----------|---------|
| `AgentIdentityBlueprint.Create` | Create Blueprints |
| `AgentIdentityBlueprint.ReadWrite.All` | Read/update Blueprints |
| `AgentIdentityBlueprintPrincipal.Create` | Create BlueprintPrincipals |
| `AgentIdentity.Create.All` | Create Agent Identities |
| `AgentIdentity.ReadWrite.All` | Read/update Agent Identities |
| `Application.ReadWrite.All` | Blueprint CRUD on application objects |
| `AppRoleAssignment.ReadWrite.All` | Grant application permissions |
| `DelegatedPermissionGrant.ReadWrite.All` | Grant delegated permissions |

Grant admin consent (required for application permissions):

```bash
az ad app permission admin-consent --id <client-id>
```

After admin consent, tokens may not include new claims for 30–120 seconds — retry with exponential backoff.

## Best Practices

1. **Always create BlueprintPrincipal after Blueprint** — not auto-created.
2. **Use typed endpoints** (`/applications/microsoft.graph.agentIdentityBlueprint`) instead of raw `/applications` with `@odata.type`.
3. **Credentials live on the Blueprint** — Agent Identities can't hold secrets/certs (`PropertyNotCompatibleWithAgentIdentity`).
4. **Include `OData-Version: 4.0`** on every Graph request.
5. **Use Workload Identity Federation for production** — client secrets only for local dev.
6. **Set `identifierUris: ["api://{appId}"]` on the Blueprint** before OAuth2 scope resolution.
7. **Never use Azure CLI tokens** for Agent Identity APIs — `Directory.AccessAsUser.All` causes hard 403.
8. **Use `fmi_path`** with `client_credentials` — NOT RFC 8693 `urn:ietf:params:oauth:grant-type:token-exchange` (returns `AADSTS82001`).
9. **Always use `/.default` scope** in both steps of the exchange — individual scopes fail.
10. **Step 1 targets the Agent Identity's home tenant** in cross-tenant flows.
11. **Grant permissions per Agent Identity**, not to the BlueprintPrincipal.
12. **Handle permission-propagation delays** — retry 403s with 30–120s backoff after admin consent.
13. **Keep the Entra SDK for AgentID on localhost** — never expose via LoadBalancer or Ingress.

## Troubleshooting

| Error | Cause | Fix |
|-------|-------|-----|
| `AADSTS82001` | Used RFC 8693 token-exchange grant | Use `client_credentials` with `fmi_path` |
| `AADSTS700211` | Step 1 parent token targeted wrong tenant | Target Agent Identity's home tenant |
| `AADSTS50013` | OBO user token targets Graph, not Blueprint | Use `api://{blueprint_app_id}/access_as_user` |
| `AADSTS65001` | Missing grant or used individual scopes | Use `/.default` and verify `oauth2PermissionGrants` |
| `403 Authorization_RequestDenied` | No grant on this Agent Identity | Add via `appRoleAssignments` or `oauth2PermissionGrants` |
| `PropertyNotCompatibleWithAgentIdentity` | Tried to add credential to Agent Identity SP | Put credentials on the Blueprint |
| `Agent Blueprint Principal does not exist` | BlueprintPrincipal not created | Step 2 of the Core Workflow |
| `AADSTS650051` on admin consent | SP already exists from partial consent | Grant directly via `appRoleAssignments` |

## References

| File | Contents |
|------|----------|
| [references/runtime-token-exchange.md](references/runtime-token-exchange.md) | Two-step `fmi_path` exchange: autonomous + OBO, cross-tenant |
| [references/oauth2-token-flow.md](references/oauth2-token-flow.md) | MI + WIF (production) and client secret (local dev) |
| [references/obo-blueprint-setup.md](references/obo-blueprint-setup.md) | Configuring the Blueprint as an OAuth2 API for OBO |
| [references/sdk-sidecar.md](references/sdk-sidecar.md) | Microsoft Entra SDK for AgentID — architecture, configuration, endpoints |
| [references/sdk-sidecar-deployment.md](references/sdk-sidecar-deployment.md) | SDK code patterns (Python/TypeScript), Docker/Kubernetes manifests, security, troubleshooting |
| [references/known-limitations.md](references/known-limitations.md) | Documented gaps organized by category |

### External Links

| Resource | URL |
|----------|-----|
| Agent ID Setup Guide | https://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-setup-instructions |
| AI-Guided Setup | https://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-ai-guided-setup |
| Microsoft Entra SDK for AgentID | https://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/overview |
| Microsoft.Identity.Web.AgentIdentities (.NET) | https://github.com/AzureAD/microsoft-identity-web/blob/master/src/Microsoft.Identity.Web.AgentIdentities/README.AgentIdentities.md |

<!-- chapter:end slug=entra-agent-id -->

---

<!-- chapter:begin slug=entra-app-registration position=34 -->

## 34. entra-app-registration

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/entra-app-registration/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/entra-app-registration.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (16), referenced from this skill's directory:
  - `references/api-permissions.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/api-permissions.md
  - `references/auth-best-practices.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/auth-best-practices.md
  - `references/BICEP-EXAMPLE.bicep` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/BICEP-EXAMPLE.bicep
  - `references/cli-commands.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/cli-commands.md
  - `references/console-app-example.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/console-app-example.md
  - `references/first-app-registration.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/first-app-registration.md
  - `references/oauth-flows.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/oauth-flows.md
  - `references/sdk/azure-identity-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/azure-identity-dotnet.md
  - `references/sdk/azure-identity-java.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/azure-identity-java.md
  - `references/sdk/azure-identity-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/azure-identity-py.md
  - `references/sdk/azure-identity-rust.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/azure-identity-rust.md
  - `references/sdk/azure-identity-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/azure-identity-ts.md
  - `references/sdk/azure-keyvault-py.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/azure-keyvault-py.md
  - `references/sdk/azure-keyvault-secrets-ts.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/azure-keyvault-secrets-ts.md
  - `references/sdk/microsoft-azure-webjobs-extensions-authentication-events-dotnet.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/sdk/microsoft-azure-webjobs-extensions-authentication-events-dotnet.md
  - `references/troubleshooting.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/entra-app-registration/references/troubleshooting.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: entra-app-registration
description: "Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.1"
---

## Overview

Microsoft Entra ID (formerly Azure Active Directory) is Microsoft's cloud-based identity and access management service. App registrations allow applications to authenticate users and access Azure resources securely.

### Key Concepts

| Concept | Description |
|---------|-------------|
| **App Registration** | Configuration that allows an app to use Microsoft identity platform |
| **Application (Client) ID** | Unique identifier for your application |
| **Tenant ID** | Unique identifier for your Azure AD tenant/directory |
| **Client Secret** | Password for the application (confidential clients only) |
| **Redirect URI** | URL where authentication responses are sent |
| **API Permissions** | Access scopes your app requests |
| **Service Principal** | Identity created in your tenant when you register an app |

### Application Types

| Type | Use Case |
|------|----------|
| **Web Application** | Server-side apps, APIs |
| **Single Page App (SPA)** | JavaScript/React/Angular apps |
| **Mobile/Native App** | Desktop, mobile apps |
| **Daemon/Service** | Background services, APIs |

## Core Workflow

### Step 1: Register the Application

Create an app registration in the Azure portal or using Azure CLI.

**Portal Method:**
1. Navigate to Azure Portal → Microsoft Entra ID → App registrations
2. Click "New registration"
3. Provide name, supported account types, and redirect URI
4. Click "Register"

**CLI Method:** See [references/cli-commands.md](references/cli-commands.md)
**IaC Method:** See [references/BICEP-EXAMPLE.bicep](references/BICEP-EXAMPLE.bicep)

It's highly recommended to use the IaC to manage Entra app registration if you already use IaC in your project, need a scalable solution for managing lots of app registrations or need fine-grained audit history of the configuration changes. 

### Step 2: Configure Authentication

Set up authentication settings based on your application type.

- **Web Apps**: Add redirect URIs, enable ID tokens if needed
- **SPAs**: Add redirect URIs, enable implicit grant flow if necessary
- **Mobile/Desktop**: Use `http://localhost` or custom URI scheme
- **Services**: No redirect URI needed for client credentials flow

### Step 3: Configure API Permissions

Grant your application permission to access Microsoft APIs or your own APIs.

**Common Microsoft Graph Permissions:**
- `User.Read` - Read user profile
- `User.ReadWrite.All` - Read and write all users
- `Directory.Read.All` - Read directory data
- `Mail.Send` - Send mail as a user

**Details:** See [references/api-permissions.md](references/api-permissions.md)

### Step 4: Create Client Credentials (if needed)

For confidential client applications (web apps, services), create a client secret, certificate or federated identity credential.

**Client Secret:**
- Navigate to "Certificates & secrets"
- Create new client secret
- Copy the value immediately (only shown once)
- Store securely (Key Vault recommended)

**Certificate:** For production environments, use certificates instead of secrets for enhanced security. Upload certificate via "Certificates & secrets" section.

**Federated Identity Credential:** For dynamically authenticating the confidential client to Entra platform.

### Step 5: Implement OAuth Flow

Integrate the OAuth flow into your application code.

**See:**
- [references/oauth-flows.md](references/oauth-flows.md) - OAuth 2.0 flow details
- [references/console-app-example.md](references/console-app-example.md) - Console app implementation

## Common Patterns

### Pattern 1: First-Time App Registration

Walk user through their first app registration step-by-step.

**Required Information:**
- Application name
- Application type (web, SPA, mobile, service)
- Redirect URIs (if applicable)
- Required permissions

**Script:** See [references/first-app-registration.md](references/first-app-registration.md)

### Pattern 2: Console Application with User Authentication

Create a .NET/Python/Node.js console app that authenticates users.

**Required Information:**
- Programming language (C#, Python, JavaScript, etc.)
- Authentication library (MSAL recommended)
- Required permissions

**Example:** See [references/console-app-example.md](references/console-app-example.md)

### Pattern 3: Service-to-Service Authentication

Set up daemon/service authentication without user interaction.

**Required Information:**
- Service/app name
- Target API/resource
- Whether to use secret or certificate

**Implementation:** Use Client Credentials flow (see [references/oauth-flows.md#client-credentials-flow](references/oauth-flows.md#client-credentials-flow))

## MCP Tools and CLI

### Azure CLI Commands

| Command | Purpose |
|---------|---------|
| `az ad app create` | Create new app registration |
| `az ad app list` | List app registrations |
| `az ad app show` | Show app details |
| `az ad app permission add` | Add API permission |
| `az ad app credential reset` | Generate new client secret |
| `az ad sp create` | Create service principal |

**Complete reference:** See [references/cli-commands.md](references/cli-commands.md)

### Microsoft Authentication Library (MSAL)

MSAL is the recommended library for integrating Microsoft identity platform.

**Supported Languages:**
- .NET/C# - `Microsoft.Identity.Client`
- JavaScript/TypeScript - `@azure/msal-browser`, `@azure/msal-node`
- Python - `msal`

**Examples:** See [references/console-app-example.md](references/console-app-example.md)

## Security Best Practices

| Practice | Recommendation |
|----------|---------------|
| **Never hardcode secrets** | Use environment variables, Azure Key Vault, or managed identity |
| **Rotate secrets regularly** | Set expiration, automate rotation |
| **Use certificates over secrets** | More secure for production |
| **Least privilege permissions** | Request only required API permissions |
| **Enable MFA** | Require multi-factor authentication for users |
| **Use managed identity** | For Azure-hosted apps, avoid secrets entirely |
| **Validate tokens** | Always validate issuer, audience, expiration |
| **Use HTTPS only** | All redirect URIs must use HTTPS (except localhost) |
| **Monitor sign-ins** | Use Entra ID sign-in logs for anomaly detection |

## SDK Quick References

- **Azure Identity**: [Python](references/sdk/azure-identity-py.md) | [.NET](references/sdk/azure-identity-dotnet.md) | [TypeScript](references/sdk/azure-identity-ts.md) | [Java](references/sdk/azure-identity-java.md) | [Rust](references/sdk/azure-identity-rust.md)
- **Key Vault (secrets)**: [Python](references/sdk/azure-keyvault-py.md) | [TypeScript](references/sdk/azure-keyvault-secrets-ts.md)
- **Auth Events**: [.NET](references/sdk/microsoft-azure-webjobs-extensions-authentication-events-dotnet.md)

## References

- [OAuth Flows](references/oauth-flows.md) - Detailed OAuth 2.0 flow explanations
- [CLI Commands](references/cli-commands.md) - Azure CLI reference for app registrations
- [Console App Example](references/console-app-example.md) - Complete working examples
- [First App Registration](references/first-app-registration.md) - Step-by-step guide for beginners
- [API Permissions](references/api-permissions.md) - Understanding and configuring permissions
- [Troubleshooting](references/troubleshooting.md) - Common issues and solutions

## External Resources

- [Microsoft Identity Platform Documentation](https://learn.microsoft.com/entra/identity-platform/)
- [OAuth 2.0 and OpenID Connect protocols](https://learn.microsoft.com/entra/identity-platform/v2-protocols)
- [MSAL Documentation](https://learn.microsoft.com/entra/msal/)
- [Microsoft Graph API](https://learn.microsoft.com/graph/)

<!-- chapter:end slug=entra-app-registration -->

---

<!-- chapter:begin slug=finetuning position=35 -->

## 35. finetuning

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/microsoft-foundry/finetuning/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/finetuning.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (33), referenced from this skill's directory:
  - `references/agentic-rft.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/agentic-rft.md
  - `references/dataset-formats.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/dataset-formats.md
  - `references/deployment.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/deployment.md
  - `references/evaluation.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/evaluation.md
  - `references/grader-design.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/grader-design.md
  - `references/hyperparameters.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/hyperparameters.md
  - `references/large-file-uploads.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/large-file-uploads.md
  - `references/platform-gotchas.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/platform-gotchas.md
  - `references/reward-hacking.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/reward-hacking.md
  - `references/training-curves.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/training-curves.md
  - `references/training-types.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/training-types.md
  - `references/vision-fine-tuning.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/references/vision-fine-tuning.md
  - `scripts/calibrate_grader.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/calibrate_grader.py
  - `scripts/check_training.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/check_training.py
  - `scripts/cleanup.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/cleanup.py
  - `scripts/common.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/common.py
  - `scripts/convert_dataset.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/convert_dataset.py
  - `scripts/deploy_model.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/deploy_model.py
  - `scripts/evaluate_model.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/evaluate_model.py
  - `scripts/generate_distillation_data.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/generate_distillation_data.py
  - `scripts/monitor_training.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/monitor_training.py
  - `scripts/score_dataset.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/score_dataset.py
  - `scripts/submit_training.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/submit_training.py
  - `scripts/validate/__init__.py` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/finetuning/scripts/validate/__init__.py
  - …and 9 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/finetuning

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: finetuning
description: "Fine-tune models on Microsoft Foundry using SFT (supervised), DPO (preference), or RFT (reinforcement with graders). Covers dataset preparation, training job submission, deployment, and evaluation. USE FOR: fine-tune, SFT, DPO, RFT, training data, grader, distillation, fine-tuned model, training job, large file upload, calibrate grader, deploy fine-tuned model, evaluate fine-tuned model. DO NOT USE FOR: general model deployment without fine-tuning (use deploy-model), agent creation (use agents), prompt optimization without training (use prompt-optimizer)."
license: MIT
metadata:
  author: Microsoft
  version: "0.0.0-placeholder"
---

# Fine-Tuning on Microsoft Foundry

Fine-tune models using SFT (supervised), DPO (preference), or RFT (reinforcement with graders). Covers dataset prep, training, deployment, and evaluation.

## When to Use

Use this sub-skill when the user asks about:
- Fine-tuning a model (SFT, DPO, or RFT)
- Preparing, validating, or formatting training data
- Submitting, monitoring, or diagnosing training jobs
- Calibrating graders or pass thresholds for RFT
- Deploying or evaluating a fine-tuned model
- Choosing between training types (SFT vs DPO vs RFT)
- Distillation, synthetic data generation, or dataset quality scoring
- Large file uploads for training data
- Cleaning up fine-tuning resources (files, deployments)

**Do NOT use for:** General model deployment without fine-tuning (use deploy-model), agent creation (use agents), prompt optimization without training (use prompt-optimizer).

## Workflows

| Stage | Guide |
|-------|-------|
| **Quick start** | [workflows/quickstart.md](workflows/quickstart.md) |
| **Full pipeline** | [workflows/full-pipeline.md](workflows/full-pipeline.md) |
| **Create data** | [workflows/dataset-creation.md](workflows/dataset-creation.md) |
| **Iterate** | [workflows/iterative-training.md](workflows/iterative-training.md) |
| **Diagnose** | [workflows/diagnose-poor-results.md](workflows/diagnose-poor-results.md) |

## References

| Topic | File |
|-------|------|
| SFT vs DPO vs RFT | [references/training-types.md](references/training-types.md) |
| Hyperparameters | [references/hyperparameters.md](references/hyperparameters.md) |
| Data formats | [references/dataset-formats.md](references/dataset-formats.md) |
| Grader design (RFT) | [references/grader-design.md](references/grader-design.md) |
| Reward hacking | [references/reward-hacking.md](references/reward-hacking.md) |
| Agentic RFT (tools) | [references/agentic-rft.md](references/agentic-rft.md) |
| Deployment | [references/deployment.md](references/deployment.md) |
| Training curves | [references/training-curves.md](references/training-curves.md) |
| Evaluation | [references/evaluation.md](references/evaluation.md) |
| Vision fine-tuning | [references/vision-fine-tuning.md](references/vision-fine-tuning.md) |
| Large file uploads | [references/large-file-uploads.md](references/large-file-uploads.md) |
| Platform gotchas | [references/platform-gotchas.md](references/platform-gotchas.md) |

## Scripts

| Script | Purpose |
|--------|---------|
| `scripts/submit_training.py` | Submit SFT/DPO/RFT jobs |
| `scripts/monitor_training.py` | Poll job until completion |
| `scripts/calibrate_grader.py` | Find optimal RFT pass_threshold |
| `scripts/check_training.py` | Analyze curves, list checkpoints |
| `scripts/deploy_model.py` | Deploy via ARM REST API |
| `scripts/evaluate_model.py` | LLM judge evaluation |
| `scripts/convert_dataset.py` | Convert between SFT/DPO/RFT formats |
| `scripts/generate_distillation_data.py` | Generate synthetic training data |
| `scripts/score_dataset.py` | Quality scoring on training data |
| `scripts/cleanup.py` | Delete old files and deployments |
| `scripts/validate/` | Data validators (SFT, DPO, RFT) + stats |

## Rules

1. **Always baseline first** — evaluate the base model before fine-tuning
2. **Validate data** before submitting — run `scripts/validate/validate_sft.py`
3. **Calibrate RFT graders** — target 25-50% failure rate on the base model
4. **Evaluate checkpoints** — don't blindly deploy the final one
5. **Measure token cost** alongside accuracy when comparing models

## Quick Reference

| Task | Command |
|------|---------|
| Validate SFT data | `python scripts/validate/validate_sft.py data.jsonl` |
| Submit SFT job | `python scripts/submit_training.py --model gpt-4.1-mini --training-file train.jsonl --validation-file val.jsonl --type sft` |
| Monitor job | `python scripts/monitor_training.py --job-id ftjob-xxx` |
| Analyze curves | `python scripts/check_training.py --job-id ftjob-xxx` |
| Deploy model | `python scripts/deploy_model.py --model-id ft:gpt-4.1-mini:... --name my-eval` |
| Evaluate model | `python scripts/evaluate_model.py --deployment-name my-eval --test-file test.jsonl` |

## Error Handling

| Error | Cause | Fix |
|-------|-------|-----|
| "API version not supported" | Older `openai` SDK on `/v1/` endpoint | Upgrade to `openai>=1.0` |
| "does not support fine-tuning with Standard TrainingType" | OSS model needs `globalStandard` | Use `--use-rest` flag or script auto-falls back |
| Job stuck in post-training eval | Under-provisioned tool endpoint (RFT) | Scale to S2+, enable Always On |
| "DeploymentNotReady" after ARM succeeds | ARM/data-plane race condition | Delete and recreate deployment, wait 5 min |
| Content safety block at deployment | PII-dense training data | Remove problematic document types |

<!-- chapter:end slug=finetuning -->

---

<!-- chapter:begin slug=capacity position=36 -->

## 36. capacity

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/microsoft-foundry/models/deploy-model/capacity/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/capacity/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/capacity.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (4), referenced from this skill's directory:
  - `scripts/discover_and_rank.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/capacity/scripts/discover_and_rank.ps1
  - `scripts/discover_and_rank.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/capacity/scripts/discover_and_rank.sh
  - `scripts/query_capacity.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/capacity/scripts/query_capacity.ps1
  - `scripts/query_capacity.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/capacity/scripts/query_capacity.sh

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: capacity
description: "Discovers available Azure OpenAI model capacity across regions and projects. Analyzes quota limits, compares availability, and recommends optimal deployment locations based on capacity requirements. USE FOR: find capacity, check quota, where can I deploy, capacity discovery, best region for capacity, multi-project capacity search, quota analysis, model availability, region comparison, check TPM availability. DO NOT USE FOR: actual deployment (hand off to preset or customize after discovery), quota increase requests (direct user to Azure Portal), listing existing deployments."
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
---

# Capacity Discovery

Finds available Azure OpenAI model capacity across all accessible regions and projects. Recommends the best deployment location based on capacity requirements.

## Quick Reference

| Property | Description |
|----------|-------------|
| **Purpose** | Find where you can deploy a model with sufficient capacity |
| **Scope** | All regions and projects the user has access to |
| **Output** | Ranked table of regions/projects with available capacity |
| **Action** | Read-only analysis — does NOT deploy. Hands off to preset or customize |
| **Authentication** | Azure CLI (`az login`) |

## When to Use This Skill

- ✅ User asks "where can I deploy gpt-4o?"
- ✅ User specifies a capacity target: "find a region with 10K TPM for gpt-4o"
- ✅ User wants to compare availability: "which regions have gpt-4o available?"
- ✅ User got a quota error and needs to find an alternative location
- ✅ User asks "best region and project for deploying model X"

**After discovery → hand off to [preset](../preset/SKILL.md) or [customize](../customize/SKILL.md) for actual deployment.**

## Scripts

Pre-built scripts handle the complex REST API calls and data processing. Use these instead of constructing commands manually.

| Script | Purpose | Usage |
|--------|---------|-------|
| `scripts/discover_and_rank.ps1` | Full discovery: capacity + projects + ranking | Primary script for capacity discovery |
| `scripts/discover_and_rank.sh` | Same as above (bash) | Primary script for capacity discovery |
| `scripts/query_capacity.ps1` | Raw capacity query (no project matching) | Quick capacity check or version listing |
| `scripts/query_capacity.sh` | Same as above (bash) | Quick capacity check or version listing |

## Workflow

### Phase 1: Validate Prerequisites

```bash
az account show --query "{Subscription:name, SubscriptionId:id}" --output table
```

### Phase 2: Identify Model and Version

Extract model name from user prompt. If version is unknown, query available versions:

```powershell
.\scripts\query_capacity.ps1 -ModelName <model-name>
```
```bash
./scripts/query_capacity.sh <model-name>
```

This lists available versions. Use the latest version unless user specifies otherwise.

### Phase 3: Run Discovery

Run the full discovery script with model name, version, and minimum capacity target:

```powershell
.\scripts\discover_and_rank.ps1 -ModelName <model-name> -ModelVersion <version> -MinCapacity <target>
```
```bash
./scripts/discover_and_rank.sh <model-name> <version> <min-capacity>
```

> 💡 The script automatically queries capacity across ALL regions, cross-references with the user's existing projects, and outputs a ranked table sorted by: meets target → project count → available capacity.

### Phase 3.5: Validate Subscription Quota

After discovery identifies candidate regions, validate that the user's subscription actually has available quota in each region. Model capacity (from Phase 3) shows what the platform can support, but subscription quota limits what this specific user can deploy.

```powershell
# For each candidate region from discovery results:
$usageData = az cognitiveservices usage list --location <region> --subscription $SUBSCRIPTION_ID -o json 2>$null | ConvertFrom-Json

# Check quota for each SKU the model supports
# Quota names follow pattern: OpenAI.<SKU>.<model-name>
$usageEntry = $usageData | Where-Object { $_.name.value -eq "OpenAI.<SKU>.<model-name>" }

if ($usageEntry) {
  $quotaAvailable = $usageEntry.limit - $usageEntry.currentValue
} else {
  $quotaAvailable = 0  # No quota allocated
}
```
```bash
# For each candidate region from discovery results:
usage_json=$(az cognitiveservices usage list --location <region> --subscription "$SUBSCRIPTION_ID" -o json 2>/dev/null)

# Extract quota for specific SKU+model
quota_available=$(echo "$usage_json" | jq -r --arg name "OpenAI.<SKU>.<model-name>" \
  '.[] | select(.name.value == $name) | .limit - .currentValue')
```

**Annotate discovery results:**

Add a "Quota Available" column to the ranked output from Phase 3:

| Region | Available Capacity | Meets Target | Projects | Quota Available |
|--------|-------------------|--------------|----------|-----------------|
| eastus2 | 120K TPM | ✅ | 3 | ✅ 80K |
| westus3 | 90K TPM | ✅ | 1 | ❌ 0 (at limit) |
| swedencentral | 100K TPM | ✅ | 0 | ✅ 100K |

Regions/SKUs where `quotaAvailable = 0` should be marked with ❌ in the results. If no region has available quota, hand off to the [quota skill](../../../quota/quota.md) for increase requests and troubleshooting.

### Phase 4: Present Results and Hand Off

After the script outputs the ranked table (now annotated with quota info), present it to the user and ask:

1. 🚀 **Quick deploy** to top recommendation with defaults → route to [preset](../preset/SKILL.md)
2. ⚙️ **Custom deploy** with version/SKU/capacity/RAI selection → route to [customize](../customize/SKILL.md)
3. 📊 **Check another model** or capacity target → re-run Phase 2
4. ❌ Cancel

### Phase 5: Confirm Project Before Deploying

Before handing off to preset or customize, **always confirm the target project** with the user. See the [Project Selection](../SKILL.md#project-selection-all-modes) rules in the parent router.

If the discovery table shows a sample project for the chosen region, suggest it as the default. Otherwise, query projects in that region and let the user pick.

## Error Handling

| Error | Cause | Resolution |
|-------|-------|------------|
| "No capacity found" | Model not available or all at quota | Hand off to [quota skill](../../../quota/quota.md) for increase requests and troubleshooting |
| Script auth error | `az login` expired | Re-run `az login` |
| Empty version list | Model not in region catalog | Try a different region: `./scripts/query_capacity.sh <model> "" eastus` |
| "No projects found" | No AI Services resources | Guide to `project/create` skill or Azure Portal |

## Related Skills

- **[preset](../preset/SKILL.md)** — Quick deployment after capacity discovery
- **[customize](../customize/SKILL.md)** — Custom deployment after capacity discovery
- **[quota](../../../quota/quota.md)** — For quota viewing, increase requests, and troubleshooting quota errors, defer to this skill instead of duplicating guidance

<!-- chapter:end slug=capacity -->

---

<!-- chapter:begin slug=customize position=37 -->

## 37. customize

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/microsoft-foundry/models/deploy-model/customize/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/customize/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/customize.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (3), referenced from this skill's directory:
  - `EXAMPLES.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/customize/EXAMPLES.md
  - `references/customize-guides.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/customize/references/customize-guides.md
  - `references/customize-workflow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/customize/references/customize-workflow.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: customize
description: "Interactive guided deployment flow for Azure OpenAI models with full customization control. Step-by-step selection of model version, SKU (GlobalStandard/Standard/ProvisionedManaged), capacity, RAI policy (content filter), and advanced options (dynamic quota, priority processing, spillover). USE FOR: custom deployment, customize model deployment, choose version, select SKU, set capacity, configure content filter, RAI policy, deployment options, detailed deployment, advanced deployment, PTU deployment, provisioned throughput. DO NOT USE FOR: quick deployment to optimal region (use preset)."
license: MIT
metadata:
  author: Microsoft
  version: "1.0.1"
---

# Customize Model Deployment

Interactive guided workflow for deploying Azure OpenAI models with full customization control over version, SKU, capacity, content filtering, and advanced options.

## Quick Reference

| Property | Description |
|----------|-------------|
| **Flow** | Interactive step-by-step guided deployment |
| **Customization** | Version, SKU, Capacity, RAI Policy, Advanced Options |
| **SKU Support** | GlobalStandard, Standard, ProvisionedManaged, DataZoneStandard |
| **Best For** | Precise control over deployment configuration |
| **Authentication** | Azure CLI (`az login`) |
| **Tools** | Azure CLI, MCP tools (optional) |

## When to Use This Skill

Use this skill when you need **precise control** over deployment configuration:

- ✅ **Choose specific model version** (not just latest)
- ✅ **Select deployment SKU** (GlobalStandard vs Standard vs PTU)
- ✅ **Set exact capacity** within available range
- ✅ **Configure content filtering** (RAI policy selection)
- ✅ **Enable advanced features** (dynamic quota, priority processing, spillover)
- ✅ **PTU deployments** (Provisioned Throughput Units)

**Alternative:** Use `preset` for quick deployment to the best available region with automatic configuration.

### Comparison: customize vs preset

| Feature | customize | preset |
|---------|---------------------|----------------------------|
| **Focus** | Full customization control | Optimal region selection |
| **Version Selection** | User chooses from available | Uses latest automatically |
| **SKU Selection** | User chooses (GlobalStandard/Standard/PTU) | GlobalStandard only |
| **Capacity** | User specifies exact value | Auto-calculated (50% of available) |
| **RAI Policy** | User selects from options | Default policy only |
| **Region** | Current region first, falls back to all regions if no capacity | Checks capacity across all regions upfront |
| **Use Case** | Precise deployment requirements | Quick deployment to best region |

## Prerequisites

- Azure subscription with Cognitive Services Contributor or Owner role
- Microsoft Foundry project resource ID (format: `/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/{account}/projects/{project}`)
- Azure CLI installed and authenticated (`az login`)
- Optional: Set `PROJECT_RESOURCE_ID` environment variable

## Workflow Overview

### Complete Flow (14 Phases)

```
1. Verify Authentication
2. Get Project Resource ID
3. Verify Project Exists
4. Get Model Name (if not provided)
5. List Model Versions → User Selects
6. List SKUs for Version → User Selects
7. Get Capacity Range → User Configures
   7b. If no capacity: Cross-Region Fallback → Query all regions → User selects region/project
8. List RAI Policies → User Selects
9. Configure Advanced Options (if applicable)
10. Configure Version Upgrade Policy
11. Generate Deployment Name
12. Review Configuration
13. Execute Deployment & Monitor
```

### Fast Path (Defaults)

If user accepts all defaults (latest version, GlobalStandard SKU, recommended capacity, default RAI policy, standard upgrade policy), deployment completes in ~5 interactions.

---

## Phase Summaries

> ⚠️ **MUST READ:** Before executing any phase, load [references/customize-workflow.md](references/customize-workflow.md) for the full scripts and implementation details. The summaries below describe *what* each phase does — the reference file contains the *how* (CLI commands, quota patterns, capacity formulas, cross-region fallback logic).

| Phase | Action | Key Details |
|-------|--------|-------------|
| **1. Verify Auth** | Check `az account show`; prompt `az login` if needed | Verify correct subscription is active |
| **2. Get Project ID** | Read `PROJECT_RESOURCE_ID` env var or prompt user | ARM resource ID format required |
| **3. Verify Project** | Parse resource ID, call `az cognitiveservices account show` | Extracts subscription, RG, account, project, region |
| **4. Get Model** | List models via `az cognitiveservices account list-models` | User selects from available or enters custom name |
| **5. Select Version** | Query versions for chosen model | Recommend latest; user picks from list |
| **6. Select SKU** | Query model catalog + subscription quota, show only deployable SKUs | ⚠️ Never hardcode SKU lists — always query live data |
| **7. Configure Capacity** | Query capacity API, validate min/max/step, user enters value | Cross-region fallback if no capacity in current region |
| **8. Select RAI Policy** | Present content filter options | Default: `Microsoft.DefaultV2` |
| **9. Advanced Options** | Dynamic quota (GlobalStandard), priority processing (PTU), spillover | SKU-dependent availability |
| **10. Upgrade Policy** | Choose: OnceNewDefaultVersionAvailable / OnceCurrentVersionExpired / NoAutoUpgrade | Default: auto-upgrade on new default |
| **11. Deployment Name** | Auto-generate unique name, allow custom override | Validates format: `^[\w.-]{2,64}$` |
| **12. Review** | Display full config summary, confirm before proceeding | User approves or cancels |
| **13. Deploy & Monitor** | `az cognitiveservices account deployment create`, poll status | Timeout after 5 min; show endpoint + portal link |


---

## Error Handling

### Common Issues and Resolutions

| Error | Cause | Resolution |
|-------|-------|------------|
| **Model not found** | Invalid model name | List available models with `az cognitiveservices account list-models` |
| **Version not available** | Version not supported for SKU | Select different version or SKU |
| **Insufficient quota** | Capacity > available quota | Skill auto-searches all regions; fails only if no region has quota |
| **SKU not supported** | SKU not available in region | Cross-region fallback searches other regions automatically |
| **Capacity out of range** | Invalid capacity value | **PREVENTED**: Skill validates min/max/step at input (Phase 7) |
| **Deployment name exists** | Name conflict | Auto-incremented name generation |
| **Authentication failed** | Not logged in | Run `az login` |
| **Permission denied** | Insufficient permissions | Assign Cognitive Services Contributor role |
| **Capacity query fails** | API/permissions/network error | **DEPLOYMENT BLOCKED**: Will not proceed without valid quota data |

### Troubleshooting Commands

```bash
# Check deployment status
az cognitiveservices account deployment show --name <account> --resource-group <rg> --deployment-name <name>

# List all deployments
az cognitiveservices account deployment list --name <account> --resource-group <rg> -o table

# Check quota usage
az cognitiveservices usage list --name <account> --resource-group <rg>

# Delete failed deployment
az cognitiveservices account deployment delete --name <account> --resource-group <rg> --deployment-name <name>
```

---

## Selection Guides & Advanced Topics

> For SKU comparison tables, PTU sizing formulas, and advanced option details, load [references/customize-guides.md](references/customize-guides.md).

**SKU selection:** GlobalStandard (production/HA) → Standard (dev/test) → ProvisionedManaged (high-volume/guaranteed throughput) → DataZoneStandard (data residency).

**Capacity:** TPM-based SKUs range from 1K (dev) to 100K+ (large production). PTU-based use formula: `(Input TPM × 0.001) + (Output TPM × 0.002) + (Requests/min × 0.1)`.

**Advanced options:** Dynamic quota (GlobalStandard only), priority processing (PTU only, extra cost), spillover (overflow to backup deployment).

---

## Related Skills

- **preset** - Quick deployment to best region with automatic configuration
- **microsoft-foundry** - Parent skill for all Microsoft Foundry operations
- **[quota](../../../quota/quota.md)** — For quota viewing, increase requests, and troubleshooting quota errors, defer to this skill instead of duplicating guidance
- **rbac** - Manage permissions and access control

---

## Notes

- Set `PROJECT_RESOURCE_ID` environment variable to skip prompt
- Not all SKUs available in all regions; capacity varies by subscription/region/model
- Custom RAI policies can be configured in Azure Portal
- Automatic version upgrades occur during maintenance windows
- Use Azure Monitor and Application Insights for production deployments

<!-- chapter:end slug=customize -->

---

<!-- chapter:begin slug=preset position=38 -->

## 38. preset

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/microsoft-foundry/models/deploy-model/preset/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/preset/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/preset.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (3), referenced from this skill's directory:
  - `EXAMPLES.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/preset/EXAMPLES.md
  - `references/preset-workflow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/preset/references/preset-workflow.md
  - `references/workflow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/preset/references/workflow.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: preset
description: "Intelligently deploys Azure OpenAI models to optimal regions by analyzing capacity across all available regions. Automatically checks current region first and shows alternatives if needed. USE FOR: quick deployment, optimal region, best region, automatic region selection, fast setup, multi-region capacity check, high availability deployment, deploy to best location. DO NOT USE FOR: custom SKU selection (use customize), specific version selection (use customize), custom capacity configuration (use customize), PTU deployments (use customize)."
license: MIT
metadata:
  author: Microsoft
  version: "1.0.1"
---

# Deploy Model to Optimal Region

Automates intelligent Azure OpenAI model deployment by checking capacity across regions and deploying to the best available option.

## What This Skill Does

1. Verifies Azure authentication and project scope
2. Checks capacity in current project's region
3. If no capacity: analyzes all regions and shows available alternatives
4. Filters projects by selected region
5. Supports creating new projects if needed
6. Deploys model with GlobalStandard SKU
7. Monitors deployment progress

## Prerequisites

- Azure CLI installed and configured
- Active Azure subscription with Cognitive Services read/create permissions
- Microsoft Foundry project resource ID (`PROJECT_RESOURCE_ID` env var or provided interactively)
  - Format: `/subscriptions/{sub-id}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/{account}/projects/{project}`
  - Found in: Microsoft Foundry portal → Project → Overview → Resource ID

## Quick Workflow

### Fast Path (Current Region Has Capacity)
```
1. Check authentication → 2. Get project → 3. Check current region capacity
→ 4. Deploy immediately
```

### Alternative Region Path (No Capacity)
```
1. Check authentication → 2. Get project → 3. Check current region (no capacity)
→ 4. Query all regions → 5. Show alternatives → 6. Select region + project
→ 7. Deploy
```

---

## Deployment Phases

| Phase | Action | Key Commands |
|-------|--------|-------------|
| 1. Verify Auth | Check Azure CLI login and subscription | `az account show`, `az login` |
| 2. Get Project | Parse `PROJECT_RESOURCE_ID` ARM ID, verify exists | `az cognitiveservices account show` |
| 3. Get Model | List available models, user selects model + version | `az cognitiveservices account list-models` |
| 4. Check Current Region | Query capacity using GlobalStandard SKU | `az rest --method GET .../modelCapacities` |
| 5. Multi-Region Query | If no local capacity, query all regions | Same capacity API without location filter |
| 6. Select Region + Project | User picks region; find or create project | `az cognitiveservices account list`, `az cognitiveservices account create` |
| 7. Deploy | Generate unique name, calculate capacity (50% available, min 50 TPM), create deployment | `az cognitiveservices account deployment create` |

For detailed step-by-step instructions, see [workflow reference](references/workflow.md).

---

## Error Handling

| Error | Symptom | Resolution |
|-------|---------|------------|
| Auth failure | `az account show` returns error | Run `az login` then `az account set --subscription <id>` |
| No quota | All regions show 0 capacity | Defer to the [quota skill](../../../quota/quota.md) for increase requests and troubleshooting; check existing deployments; try alternative models |
| Model not found | Empty capacity list | Verify model name with `az cognitiveservices account list-models`; check case sensitivity |
| Name conflict | "deployment already exists" | Append suffix to deployment name (handled automatically by `generate_deployment_name` script) |
| Region unavailable | Region doesn't support model | Select a different region from the available list |
| Permission denied | "Forbidden" or "Unauthorized" | Verify Cognitive Services Contributor role: `az role assignment list --assignee <user>` |

---

## Advanced Usage

```bash
# Custom capacity
az cognitiveservices account deployment create ... --sku-capacity <value>

# Check deployment status
az cognitiveservices account deployment show --name <acct> --resource-group <rg> --deployment-name <name> --query "{Status:properties.provisioningState}"

# Delete deployment
az cognitiveservices account deployment delete --name <acct> --resource-group <rg> --deployment-name <name>
```

## Notes

- **SKU:** GlobalStandard only — **API Version:** 2024-10-01 (GA stable)

---

## Related Skills

- **microsoft-foundry** - Parent skill for Microsoft Foundry operations
- **[quota](../../../quota/quota.md)** — For quota viewing, increase requests, and troubleshooting quota errors, defer to this skill
- **azure-quick-review** - Review Azure resources for compliance
- **azure-cost-estimation** - Estimate costs for Azure deployments
- **azure-validate** - Validate Azure infrastructure before deployment

<!-- chapter:end slug=preset -->

---

<!-- chapter:begin slug=deploy-model position=39 -->

## 39. deploy-model

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/microsoft-foundry/models/deploy-model/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/deploy-model.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (3), referenced from this skill's directory:
  - `scripts/generate_deployment_url.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/scripts/generate_deployment_url.ps1
  - `scripts/generate_deployment_url.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/scripts/generate_deployment_url.sh
  - `TEST_PROMPTS.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/models/deploy-model/TEST_PROMPTS.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: deploy-model
description: "Unified Azure OpenAI model deployment skill with intelligent intent-based routing. Handles quick preset deployments, fully customized deployments (version/SKU/capacity/RAI policy), and capacity discovery across regions and projects. USE FOR: deploy model, deploy gpt, create deployment, model deployment, deploy openai model, set up model, provision model, find capacity, check model availability, where can I deploy, best region for model, capacity analysis. DO NOT USE FOR: listing existing deployments (use foundry_models_deployments_list MCP tool), deleting deployments, agent creation (use agent/create), project creation (use project/create)."
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
---

# Deploy Model

> **Scope — read this first.** This skill creates model deployments **out-of-band** via Azure CLI / MCP / portal. For azd-managed Foundry projects (those scaffolded from `azd ai agent init`), declare deployments in `azure.yaml services.ai-project.deployments[]` instead — `azd ai agent init` writes the entry from the sample manifest and `azd provision` creates the deployment through Bicep. See [foundry-agent/create/create-hosted.md](../../foundry-agent/create/create-hosted.md) for the Golden Path. Use this skill only for: (a) Foundry projects not managed by an azd project, (b) ad-hoc deployments outside the azd lifecycle.

Unified entry point for all Azure OpenAI model deployment workflows. Analyzes user intent and routes to the appropriate deployment mode.

## Quick Reference

| Mode | When to Use | Sub-Skill |
|------|-------------|-----------|
| **Preset** | Quick deployment, no customization needed | [preset/SKILL.md](preset/SKILL.md) |
| **Customize** | Full control: version, SKU, capacity, RAI policy | [customize/SKILL.md](customize/SKILL.md) |
| **Capacity Discovery** | Find where you can deploy with specific capacity | [capacity/SKILL.md](capacity/SKILL.md) |

## Intent Detection

Analyze the user's prompt and route to the correct mode:

```
User Prompt
    │
    ├─ Simple deployment (no modifiers)
    │  "deploy gpt-4o", "set up a model"
    │  └─> PRESET mode
    │
    ├─ Customization keywords present
    │  "custom settings", "choose version", "select SKU",
    │  "set capacity to X", "configure content filter",
    │  "PTU deployment", "with specific quota"
    │  └─> CUSTOMIZE mode
    │
    ├─ Capacity/availability query
    │  "find where I can deploy", "check capacity",
    │  "which region has X capacity", "best region for 10K TPM",
    │  "where is this model available"
    │  └─> CAPACITY DISCOVERY mode
    │
    └─ Ambiguous (has capacity target + deploy intent)
       "deploy gpt-4o with 10K capacity to best region"
       └─> CAPACITY DISCOVERY first → then PRESET or CUSTOMIZE
```

### Routing Rules

| Signal in Prompt | Route To | Reason |
|------------------|----------|--------|
| Just model name, no options | **Preset** | User wants quick deployment |
| "custom", "configure", "choose", "select" | **Customize** | User wants control |
| "find", "check", "where", "which region", "available" | **Capacity** | User wants discovery |
| Specific capacity number + "best region" | **Capacity → Preset** | Discover then deploy quickly |
| Specific capacity number + "custom" keywords | **Capacity → Customize** | Discover then deploy with options |
| "PTU", "provisioned throughput" | **Customize** | PTU requires SKU selection |
| "optimal region", "best region" (no capacity target) | **Preset** | Region optimization is preset's specialty |

### Multi-Mode Chaining

Some prompts require two modes in sequence:

**Pattern: Capacity → Deploy**
When a user specifies a capacity requirement AND wants deployment:
1. Run **Capacity Discovery** to find regions/projects with sufficient quota
2. Present findings to user
3. Ask: "Would you like to deploy with **quick defaults** or **customize settings**?"
4. Route to **Preset** or **Customize** based on answer

> 💡 **Tip:** If unsure which mode the user wants, default to **Preset** (quick deployment). Users who want customization will typically use explicit keywords like "custom", "configure", or "with specific settings".

## Project Selection (All Modes)

Before any deployment, resolve which project to deploy to. This applies to **all** modes (preset, customize, and after capacity discovery).

### Resolution Order

1. **Check `PROJECT_RESOURCE_ID` env var** — if set, use it as the default
2. **Check user prompt** — if user named a specific project or region, use that
3. **If neither** — query the user's projects and suggest the current one

### Confirmation Step (Required)

**Always confirm the target before deploying.** Show the user what will be used and give them a chance to change it:

```
Deploying to:
  Project:  <project-name>
  Region:   <region>
  Resource: <resource-group>

Is this correct? Or choose a different project:
  1. ✅ Yes, deploy here (default)
  2. 📋 Show me other projects in this region
  3. 🌍 Choose a different region
```

If user picks option 2, show top 5 projects in that region:

```
Projects in <region>:
  1. project-alpha (rg-alpha)
  2. project-beta (rg-beta)
  3. project-gamma (rg-gamma)
  ...
```

> ⚠️ **Never deploy without showing the user which project will be used.** This prevents accidental deployments to the wrong resource.

## Pre-Deployment Validation (All Modes)

Before presenting any deployment options (SKU, capacity), always validate both of these:

1. **Model supports the SKU** — query the model catalog to confirm the selected model+version supports the target SKU:
   ```bash
   az cognitiveservices model list --location <region> --subscription <sub-id> -o json
   ```
   Filter for the model, extract `.model.skus[].name` to get supported SKUs.

2. **Subscription has available quota** — check that the user's subscription has unallocated quota for the SKU+model combination:
   ```bash
   az cognitiveservices usage list --location <region> --subscription <sub-id> -o json
   ```
   Match by usage name pattern `OpenAI.<SKU>.<model-name>` (e.g., `OpenAI.GlobalStandard.gpt-4o`). Compute `available = limit - currentValue`.

> ⚠️ **Warning:** Only present options that pass both checks. Do NOT show hardcoded SKU lists — always query dynamically. SKUs with 0 available quota should be shown as ❌ informational items, not selectable options.

> 💡 **Quota management:** For quota increase requests, usage monitoring, and troubleshooting quota errors, defer to the [quota skill](../../quota/quota.md) instead of duplicating that guidance inline.

## Prerequisites

All deployment modes require:
- Azure CLI installed and authenticated (`az login`)
- Active Azure subscription with deployment permissions
- Microsoft Foundry project resource ID (or agent will help discover it via `PROJECT_RESOURCE_ID` env var)

## Sub-Skills

- **[preset/SKILL.md](preset/SKILL.md)** — Quick deployment to optimal region with sensible defaults
- **[customize/SKILL.md](customize/SKILL.md)** — Interactive guided flow with full configuration control
- **[capacity/SKILL.md](capacity/SKILL.md)** — Discover available capacity across regions and projects

<!-- chapter:end slug=deploy-model -->

---

<!-- chapter:begin slug=microsoft-foundry position=40 -->

## 40. microsoft-foundry

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/microsoft-foundry/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/microsoft-foundry.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (134), referenced from this skill's directory:
  - `.gitignore` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/.gitignore
  - `foundry-agent/agent-optimizer/agent-optimizer.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/agent-optimizer/agent-optimizer.md
  - `foundry-agent/agent-optimizer/references/azd-setup.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/agent-optimizer/references/azd-setup.md
  - `foundry-agent/agent-optimizer/references/eval-yaml.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/agent-optimizer/references/eval-yaml.md
  - `foundry-agent/agent-optimizer/references/optimize-workflow.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/agent-optimizer/references/optimize-workflow.md
  - `foundry-agent/agent-optimizer/references/python-patterns.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/agent-optimizer/references/python-patterns.md
  - `foundry-agent/agent-optimizer/references/scaffold.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/agent-optimizer/references/scaffold.md
  - `foundry-agent/azd-guidance/azd-guidance.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/azd-guidance/azd-guidance.md
  - `foundry-agent/azd-guidance/references/azd-ai-cli.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/azd-guidance/references/azd-ai-cli.md
  - `foundry-agent/cicd/cicd.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/cicd/cicd.md
  - `foundry-agent/create/create-hosted.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/create-hosted.md
  - `foundry-agent/create/create-prompt.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/create-prompt.md
  - `foundry-agent/create/quick-start-hosted.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/quick-start-hosted.md
  - `foundry-agent/create/references/enable-incoming-a2a.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/enable-incoming-a2a.md
  - `foundry-agent/create/references/foundry-tool-catalog.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/foundry-tool-catalog.md
  - `foundry-agent/create/references/guardrails/guardrail-api-create.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/guardrails/guardrail-api-create.md
  - `foundry-agent/create/references/guardrails/guardrail-attach.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/guardrails/guardrail-attach.md
  - `foundry-agent/create/references/guardrails/guardrail-manage.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/guardrails/guardrail-manage.md
  - `foundry-agent/create/references/local-run.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/local-run.md
  - `foundry-agent/create/references/sdk-operations.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/sdk-operations.md
  - `foundry-agent/create/references/skills/skill-attach.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/skills/skill-attach.md
  - `foundry-agent/create/references/skills/skill-manage.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/skills/skill-manage.md
  - `foundry-agent/create/references/skills/skill-toolbox-attach.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/skills/skill-toolbox-attach.md
  - `foundry-agent/create/references/tools/prompt-agent/agent-tools.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/microsoft-foundry/foundry-agent/create/references/tools/prompt-agent/agent-tools.md
  - …and 110 more, listed in https://skillsdocs.com/api/v1/books/microsoft/azure-skills/skills/microsoft-foundry

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: microsoft-foundry
description: "Deploy, evaluate, fine-tune, and manage Foundry agents end-to-end with azd: hosted agent scaffold/run/deploy, prompt agent create, batch eval, continuous eval, prompt optimizer, Agent Optimizer scaffold, agent.yaml, dataset curation from traces, model fine-tuning (SFT/DPO/RFT). USE FOR: azd ai agent, azd provision/deploy, deploy agent, hosted agent, create agent, add tool to agent, invoke agent, evaluate agent, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, agent optimizer, deploy model, Foundry project, RBAC, role assignment, permissions, quota, capacity, region, troubleshoot agent, deployment failure, AI Services, create Foundry resource, provision, knowledge index, customize deployment, onboard, availability, fine-tune, SFT, DPO, RFT, training-data, grader, distillation, fine-tuned model, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure-prepare)."
license: MIT
metadata:
  author: Microsoft
  version: "1.2.4"
---

# Microsoft Foundry Skill

This skill helps developers work with Microsoft Foundry resources, covering model discovery and deployment, complete dev lifecycle of AI agent, evaluation workflows, and troubleshooting.

## Pre-Execution Requirements

Follow each applicable subsection below before starting its corresponding action or workflow.

### Dependency Check and Setup

**MANDATORY:** As the first step after this skill loads, run the dependency check and setup script below from this skill's root and wait for it to finish before continuing. The script checks first and installs only missing dependencies; it does not reinstall dependencies that are already available.

**You MUST complete this check before reading or entering any sub-skill, workflow, or workflow-specific reference.**

```bash
./scripts/check-and-setup-dependencies.sh     # macOS / Linux
./scripts/check-and-setup-dependencies.ps1    # Windows (pwsh)
```

Strictly follow the script output for subsequent actions.

### Workflow Guidance

**MANDATORY:** Before executing ANY workflow-specific steps, you MUST read the corresponding sub-skill document. Do not call workflow-specific MCP tools for a workflow without reading its skill document. This applies even if you already know the MCP tool parameters — the skill document contains required workflow steps, pre-checks, and validation logic that must be followed. This rule applies on every new user message that triggers a different workflow, even if the skill is already loaded.

### Foundry MCP

**MANDATORY:** Before using Foundry MCP operations, call the Azure MCP `foundry` tool and inspect the available Foundry MCP tools and related parameters. Treat this as the discovery/help step for MCP-based workflows.

### azd

**MANDATORY:** Before executing ANY azd command, you MUST read [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) and strictly follow the shared rules defined in it, especially the `AZURE_DEV_USER_AGENT` setting rules.

## Sub-Skills

This skill includes specialized sub-skills for specific workflows. **When a sub-skill matches the task, strictly follow its workflow:**

| Sub-Skill | When to Use | Reference |
|-----------|-------------|-----------|
| **deploy** | Deploy hosted agents to Foundry, smoke-test a deployment, create or update prompt agents, and manage agent versions and multi-environment deploys. | [deploy](foundry-agent/deploy/deploy.md) |
| **cicd** | Set up a CI/CD deployment pipeline for a Foundry agent. | [cicd](foundry-agent/cicd/cicd.md) |
| **invoke** | Send messages to an agent, single or multi-turn conversations | [invoke](foundry-agent/invoke/invoke.md) |
| **routine** | Schedule or event-trigger Foundry agents with routines; use `azd` for CRUD, enable/disable, manual dispatch, and viewing past runs, or define routines in `azure.yaml`. | [routine](foundry-agent/routine/routine.md) |
| **invocations-ws** | Build, deploy, and connect to hosted agents that speak the `invocations_ws` duplex WebSocket protocol — voice agents, real-time streams, and signaling for out-of-band media transports. | [invocations-ws](foundry-agent/invocations-ws/invocations-ws.md) |
| **observe** | Evaluate agent quality, run batch evals, analyze failures, optimize prompts, improve agent instructions, compare versions, set up CI/CD monitoring, and enable continuous production evaluation | [observe](foundry-agent/observe/observe.md) |
| **trace** | Query traces, analyze latency/failures, correlate eval results to specific responses via App Insights `customEvents` | [trace](foundry-agent/trace/trace.md) |
| **troubleshoot** | View hosted agent logs, query telemetry, diagnose failures | [troubleshoot](foundry-agent/troubleshoot/troubleshoot.md) |
| **create (quick start)** | Create a new hosted Foundry agent from scratch end-to-end — scaffold, provision or use an existing Foundry project, deploy, and smoke-test. Do not use for any work on existing code. For anything not covered by the quickstart, use **create**. | [create/quick-start-hosted.md](foundry-agent/create/quick-start-hosted.md) |
| **create** | Use when the standard end-to-end happy path (quick start) doesn't fit. Create a new Foundry agent, update code of an existing agent, continue development of an existing agent, wire connections at scaffold time, use advanced setup or A2A (Agent2Agent), or recover from a failed quickstart run. | [create](foundry-agent/create/create-hosted.md) |
| **agent-optimizer** | Make existing Python hosted-agent code optimization-ready, configure eval.yaml, run Agent Optimizer jobs, apply candidates locally, and deploy through azd after review. | [agent-optimizer](foundry-agent/agent-optimizer/agent-optimizer.md) |
| **eval-datasets** | Harvest production traces into evaluation datasets, manage dataset versions and splits, track evaluation metrics over time, detect regressions, and maintain full lineage from trace to deployment. Use for: create dataset from traces, dataset versioning, evaluation trending, regression detection, dataset comparison, eval lineage. | [eval-datasets](foundry-agent/eval-datasets/eval-datasets.md) |
| **project/create** | Creating a new Microsoft Foundry project for hosting agents and models. Use when onboarding to Foundry or setting up new infrastructure. | [project/create/create-foundry-project.md](project/create/create-foundry-project.md) |
| **resource/create** | Creating Azure AI Services multi-service resource (Foundry resource) using Azure CLI. Use when manually provisioning AI Services resources with granular control. | [resource/create/create-foundry-resource.md](resource/create/create-foundry-resource.md) |
| **private-network** | Answer questions about Foundry network isolation **and** deploy Foundry with VNet isolation (BYO VNet, Managed VNet, hybrid). Covers architecture concepts, template selection, deployment, and post-deployment validation. | [resource/private-network/private-network.md](resource/private-network/private-network.md) |
| **models/deploy-model** | Unified model deployment with intelligent routing. Handles quick preset deployments, fully customized deployments (version/SKU/capacity/RAI), and capacity discovery across regions. Routes to sub-skills: `preset` (quick deploy), `customize` (full control), `capacity` (find availability). | [models/deploy-model/SKILL.md](models/deploy-model/SKILL.md) |
| **quota** | Managing quotas and capacity for Microsoft Foundry resources. Use when checking quota usage, troubleshooting deployment failures due to insufficient quota, requesting quota increases, or planning capacity. | [quota/quota.md](quota/quota.md) |
| **rbac** | Managing RBAC permissions, role assignments, managed identities, and service principals for Microsoft Foundry resources. Use for access control, auditing permissions, and CI/CD setup. | [rbac/rbac.md](rbac/rbac.md) |
| **finetuning** | Fine-tune models on Microsoft Foundry — SFT distillation, DPO preference optimization, RFT with graders and tool calling. Dataset preparation, grader calibration, training, checkpoint selection, deployment, evaluation. Use for: fine-tune, SFT, DPO, RFT, training data, grader, distillation, fine-tuned model, large file upload. | [finetuning/SKILL.md](finetuning/SKILL.md) |
| **azd-guidance** | Provide shared azd knowledge and guidance for managing Foundry agents. Read this first for any workflows related to azd. | [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) |

> 💡 **Tip:** For a complete onboarding flow: `project/create` (public) or `private-network` (VNet isolation) → `models/deploy-model` → agent workflows (`create` → `deploy` → `invoke`).

> 💡 **Fine-Tuning:** Use `finetuning` for all model customization — SFT distillation, DPO preference optimization, and RFT with graders. Includes quickstart, grader calibration, and training curve analysis.

> 💡 **Model Deployment:** Use `models/deploy-model` for all deployment scenarios — it intelligently routes between quick preset deployment, customized deployment with full control, and capacity discovery across regions.

> 💡 **Prompt Optimization:** For requests like "optimize my prompt" or "improve my agent instructions," load [observe](foundry-agent/observe/observe.md) and use the `prompt_optimize` MCP tool through that eval-driven workflow.

## Infrastructure Lifecycle

Match user intent to the correct infrastructure workflow.

| User Intent | Workflow |
|-------------|---------|
| "Create Foundry" / "Set up Foundry" (ambiguous) | Use `AskUserQuestion`: (a) just an AI Services resource, (b) a project with public access, or (c) a project with network isolation? Route: (a) → [resource/create](resource/create/create-foundry-resource.md), (b) → [project/create](project/create/create-foundry-project.md), (c) → [private-network](resource/private-network/private-network.md) |
| Set up Foundry with VNet isolation | [private-network](resource/private-network/private-network.md) |
| Create a Foundry project (public) | [project/create](project/create/create-foundry-project.md) |
| Create a bare Foundry resource | [resource/create](resource/create/create-foundry-resource.md) |

## Agent Development Lifecycle

Match user intent to the correct agent workflow. Read each sub-skill in order before executing.

| User Intent | Workflow (read in order) |
|-------------|------------------------|
| Create a new hosted agent end-to-end (scaffold + deploy + test) | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → [quick-start-hosted](foundry-agent/create/quick-start-hosted.md) (self-contained end-to-end) |
| Anything beyond the standard quickstart (existing code, migration, re-hosting, deployment customization, scaffold-time connections, A2A (Agent2Agent), recovery) | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → [create](foundry-agent/create/create-hosted.md) → [deploy](foundry-agent/deploy/deploy.md) → [invoke](foundry-agent/invoke/invoke.md) |
| Optimize existing Python hosted agent | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → [agent-optimizer](foundry-agent/agent-optimizer/agent-optimizer.md) → scaffold/review → eval.yaml → optimize → apply candidate → deploy → invoke |
| Deploy an agent (code already exists) | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → deploy (includes eval-suite setup) → invoke → observe (evaluate/optimize) |
| Update/redeploy an agent after code changes | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → deploy (includes eval-suite setup) → invoke → observe (evaluate/optimize) |
| Set up a CI/CD deployment pipeline for a hosted agent | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → cicd |
| Invoke/test/chat with an agent | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → invoke |
| Schedule/event-trigger an agent, or CRUD/enable/disable/dispatch a routine | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → routine |
| Optimize / improve agent prompt or instructions | observe (Step 4: Optimize) |
| Evaluate and optimize agent (full loop) | observe |
| Enable continuous evaluation monitoring | observe (Step 6: CI/CD & Monitoring) |
| Troubleshoot an agent issue | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → invoke → troubleshoot |
| Fix a broken agent (troubleshoot + redeploy) | [dependency check and setup](#dependency-check-and-setup) → [azd-guidance](foundry-agent/azd-guidance/azd-guidance.md) → invoke → troubleshoot → apply fixes → deploy → invoke |

## Agent: .foundry Workspace Standard

Every agent source folder can keep Foundry-specific cache and overlay state under `.foundry/`:

```text
<agent-root>/
  .foundry/
    agent-metadata.yaml
    agent-metadata.prod.yaml
    suites/
    datasets/
    evaluators/
    results/
```

- In azd projects, derive deployment context (project endpoint, agent name/version, ACR, App Insights) from `azure.yaml` plus `azd env get-values`; do not duplicate those values in metadata when azd already provides them.
- `agent-metadata.yaml` is the preferred local/dev overlay for non-azd values, remote Foundry suite references, local cache paths, result summaries, and explicit overrides. Optional sidecar files such as `agent-metadata.prod.yaml` can hold a single prod or CI-targeted overlay without mixing multiple environments in one file.
- `suites/`, `datasets/`, and `evaluators/` are local cache folders. Reuse them when they are current, and ask before refreshing or overwriting them.
- See [Agent Metadata Contract](references/agent-metadata-contract.md) for the canonical schema and workflow rules.

## Agent: Setup References

- [Standard Agent Setup](references/standard-agent-setup.md) — advanced setup for production workloads that need data-residency control (bring-your-own Cosmos DB / Storage / AI Search via a Foundry capability host). The default `azd ai agent` flow uses **Basic Agent Setup** and does **not** provision `capabilityHosts/agents` — do not flag its absence as a bug. For default post-provision state, see the "Expected env-var fingerprint" section in [foundry-agent/create/create-hosted.md](foundry-agent/create/create-hosted.md).

## Agent: Common Project Context Resolution

Agent skills should run this step **only when they need configuration values they don't already have**. If a value (for example, agent root, environment, project endpoint, or agent name) is already known from the user's message or a previous skill in the same session, skip resolution for that value.

### Step 1: Discover Agent Roots and azd Context

First check whether the workspace has `azure.yaml` with services using `host: azure.ai.agent`.

- **One azd agent service** -> use that service's `project` folder as the agent root.
- **Multiple azd agent services** -> require the user to choose the target service/folder.
- **No azd agent service** -> search the workspace for `.foundry/` folders that contain `agent-metadata.yaml` or `agent-metadata.<env>.yaml`.
  - **One match** -> use that agent root.
  - **Multiple matches** -> require the user to choose the target agent folder.
  - **No matches** -> for create/deploy workflows, seed a new `.foundry/` folder during setup; for all other workflows, stop and ask the user which agent source folder to initialize.

After selecting an agent root, keep all local `.foundry` cache inspection, source inspection, evaluator suggestions, dataset suggestions, and prompt-optimization context inside that folder only. Do **not** scan sibling agent folders unless the user explicitly switches roots.

### Step 2: Resolve Environment and Deployment Context

If `azure.yaml` is present, resolve the azd environment first:

1. Environment explicitly named by the user
2. `AZURE_ENV_NAME` from `azd env get-values`
3. azd default environment from `.azure/config.json`
4. Environment already selected earlier in the session

Run `azd env get-values` for the selected environment when project/deployment values are not already known. Prefer azd values for deployment context:

| azd Variable | Resolves To |
|-------------|-------------|
| `AZURE_AI_PROJECT_ENDPOINT` or `AZURE_AIPROJECT_ENDPOINT` | Project endpoint |
| `AGENT_<SERVICE>_NAME` | Agent name for the selected azd service |
| `AGENT_<SERVICE>_VERSION` | Agent version for the selected azd service |
| `AZURE_CONTAINER_REGISTRY_NAME` or `AZURE_CONTAINER_REGISTRY_ENDPOINT` | ACR registry name / image URL prefix |
| `APPLICATIONINSIGHTS_CONNECTION_STRING` | App Insights connection string for trace workflows |
| `AZURE_SUBSCRIPTION_ID`, `AZURE_RESOURCE_GROUP`, `AZURE_AI_ACCOUNT_NAME`, `AZURE_AI_PROJECT_NAME` | Azure resource lookup and Playground links |

When azd supplies these values, use them as the source of truth and do not copy them into `.foundry/agent-metadata*.yaml` on metadata writes.

### Step 3: Select Metadata Overlay and Resolve Environment

Inside the selected agent root, choose the metadata file in this order:
1. Metadata filename or path explicitly provided by the user or workflow
2. If an explicit environment is already known and `.foundry/agent-metadata.<env>.yaml` exists, use that file
3. `.foundry/agent-metadata.yaml`
4. If multiple metadata files remain and no rule above selects one, prompt the user to choose

Read the selected metadata file and resolve any remaining environment choice in this order:
1. Environment explicitly named by the user
2. If the selected metadata file defines exactly one environment, use it
3. Environment already selected earlier in the session
4. `defaultEnvironment` from metadata

If the selected metadata file still contains multiple environments and none of the rules above selects one, prompt the user to choose. Keep the selected agent root, metadata file, environment, and whether context came from azd or metadata visible in every workflow summary.

If the selected environment exposes older `testSuites[]` metadata but not `evaluationSuites[]`, treat `testSuites[]` as the source for this session and normalize each entry in memory to the `evaluationSuites[]` shape before continuing. If the metadata is older still and only exposes legacy `testCases[]`, normalize that list the same way. Preserve dataset and evaluator fields, keep any existing `tags`, and map legacy `priority` to `tags.tier` only when `tags.tier` is missing: `P0` -> `smoke`, `P1` -> `regression`, `P2` -> `coverage`.

### Step 4: Resolve eval.yaml Local Evaluation Intent

If `eval.yaml` exists in the selected agent root, parse it before generating new suites:

- `agent.name` -> target agent candidate; verify it matches the selected azd/metadata agent before using it.
- `dataset.local_uri` -> local seed dataset candidate; legacy `dataset_file` may be normalized in memory.
- `dataset.name` / `dataset.version` -> registered dataset candidate.
- `validation_dataset` -> optional validation dataset candidate.
- `evaluators[]` -> candidate Foundry evaluator names; verify with `evaluator_catalog_get` before treating them as remote evaluators.
- `name` -> local eval/suite candidate; verify remotely before persisting as `suiteName`.
- `options.eval_model`, `options.optimization_model`, `options.max_candidates`, `options.optimization_config.model_search_space`, `options.pass_threshold`, `max_samples`, `trace_days`, and `generation_instruction` -> setup defaults.

Treat `eval.yaml` as local evaluation intent, not proof that a Foundry suite exists. Persist synced suite/dataset/evaluator references to `.foundry` only after remote lookup or registration succeeds.

### Step 5: Resolve Common Configuration

Layer sources in this order:

1. Explicit user input and values already selected in the session
2. azd environment values for deployment context
3. `.foundry/agent-metadata*.yaml` overlay values and remote suite/cache references
4. `azure.yaml` and `eval.yaml` local source configuration
5. User prompts for anything still missing

If azd and metadata both provide the same value and they differ, stop and ask which source is authoritative. If they match, use the azd value and avoid rewriting the duplicate on future metadata writes.

| Effective Value | Preferred Source | Used By |
|-----------------|------------------|---------|
| Project endpoint | azd env | deploy, invoke, observe, trace, troubleshoot |
| Agent name/version | azd agent variables, then `azure.yaml` | invoke, observe, trace, troubleshoot |
| ACR | azd env | deploy |
| Evaluation suites and cache paths | `.foundry/agent-metadata*.yaml` | observe, eval-datasets |
| Local seed dataset/evaluator intent | `eval.yaml` | observe, eval-datasets |

### Step 6: Write Metadata Overlay (Create/Deploy/Observe Only)

On any metadata write (deploy, auto-setup, dataset refresh, or trace-to-dataset update), persist only non-derivable overlay/cache state in the selected metadata file:

- azd binding (`azd.environmentName`, `azd.service`) when useful for future resolution
- `evaluationSuites[]` with remote suite/dataset/evaluator references and local cache paths
- `lastEval`, result files, comparison summaries, or explicit non-azd overrides

Do not copy azd-owned deployment values into metadata when azd already provides them. If the selected file is a preferred single-environment file, rewrite only that one environment block. If the selected file is a legacy multi-environment file, rewrite only the selected environment block. Never copy or merge environments across sibling metadata files automatically. If the selected environment still uses older `testSuites[]` or legacy `testCases[]`, rewrite it to `evaluationSuites[]` and remove migrated `priority` fields from the rewritten entries.

### Step 7: Collect Missing Values

Use the `ask_user` or `askQuestions` tool **only for values not resolved** from the user's message, session context, metadata, or azd bootstrap. Common values skills may need:
- **Agent root** — Target azd service project folder or folder containing `.foundry/agent-metadata*.yaml`
- **Metadata file** — `agent-metadata.yaml` for local/dev, or an explicit sidecar such as `agent-metadata.prod.yaml`
- **Environment** — azd environment, `dev`, `prod`, or another environment key from metadata
- **Project endpoint** — Microsoft Foundry project endpoint URL
- **Agent name** — Name of the target agent

> 💡 **Tip:** If the user already provides the agent path, environment, project endpoint, or agent name, extract it directly — do not ask again.

## Agent: Agent Types

All agent skills support two agent types:

| Type | Kind | Description |
|------|------|-------------|
| **Prompt** | `"prompt"` | LLM-based agents backed by a model deployment |
| **Hosted** | `"hosted"` | Container-based agents running custom code |

Treat an `azure.yaml` service with `host: azure.ai.agent` as Hosted. Use `agent_get` only when the type cannot be resolved from project context.

## Tool Usage Conventions

- Use the `ask_user` or `askQuestions` tool whenever collecting information from the user
- Use the `task` or `runSubagent` tool to delegate long-running or independent sub-tasks (e.g., env var scanning, status polling, Dockerfile generation)
- Prefer azd for Hosted Agents and Foundry MCP for Prompt Agents.
- Reference official Microsoft documentation URLs instead of embedding CLI command syntax

## Additional Resources

- [Foundry Hosted Agents](https://learn.microsoft.com/azure/ai-foundry/agents/concepts/hosted-agents?view=foundry)
- [Foundry Agent Runtime Components](https://learn.microsoft.com/azure/ai-foundry/agents/concepts/runtime-components?view=foundry)

## SDK Quick Reference

- [Python](references/sdk/foundry-sdk-py.md)

## Network Isolation Errors

Applies to **any** call against a Foundry project or its parent Foundry account — Foundry MCP tools, `azd`, `az` CLI, `curl`, REST, or SDK.

If an error matches `Public access is disabled` / `PublicNetworkAccessDisabled` / `403 Forbidden` from a private endpoint / connection timeout / the project endpoint FQDN resolves to a public IP, this typically means the parent Foundry account has `publicNetworkAccess=Disabled` or `Enabled from selected IP addresses`, and the current shell is outside its VNet.

Only if the error is ambiguous, confirm against the Foundry account using a management-plane call (works from anywhere with reader access):

```bash
az cognitiveservices account show \
  --name <account> --resource-group <rg> \
  --query "properties.{publicNetworkAccess:publicNetworkAccess, networkAcls:networkAcls, privateEndpointConnections:privateEndpointConnections[].properties.privateLinkServiceConnectionState.status}"
```

`publicNetworkAccess: "Disabled"` — or `"Enabled"` together with non-empty `networkAcls.ipRules` / `virtualNetworkRules` — confirms isolation. If `publicNetworkAccess: "Enabled"` and `networkAcls` is empty, the failure is a caller-side network issue (e.g. Private DNS resolving the FQDN to a public IP from inside a VNet with a private endpoint), not an account-config issue.

If it's indeed a network isolation issue, supported connection options are documented in [Choose a secure connection method to Foundry](https://learn.microsoft.com/azure/foundry/how-to/configure-private-link#choose-a-secure-connection-method-to-foundry).

> ℹ️ Foundry MCP tools cannot reach a VNet-isolated project even from inside the VNet.

<!-- chapter:end slug=microsoft-foundry -->

---

<!-- chapter:begin slug=python-appservice-deploy position=41 -->

## 41. python-appservice-deploy

- **Source:** https://github.com/microsoft/azure-skills/blob/main/skills/python-appservice-deploy/SKILL.md
- **Raw:** https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/SKILL.md
- **Markdown:** https://skillsdocs.com/microsoft/azure-skills/python-appservice-deploy.md
- **Licence:** MIT — https://spdx.org/licenses/MIT.html

Bundled files (12), referenced from this skill's directory:
  - `references/create-app.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/create-app.md
  - `references/deploy-azcli.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/deploy-azcli.md
  - `references/deploy-azd.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/deploy-azd.md
  - `references/detect.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/detect.md
  - `references/errors.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/errors.md
  - `references/post-deploy-message.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/post-deploy-message.md
  - `references/startup-commands.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/startup-commands.md
  - `references/transient-retry.md` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/references/transient-retry.md
  - `scripts/generate-app-name.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/scripts/generate-app-name.ps1
  - `scripts/generate-app-name.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/scripts/generate-app-name.sh
  - `scripts/retry-az-create.ps1` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/scripts/retry-az-create.ps1
  - `scripts/retry-az-create.sh` — https://raw.githubusercontent.com/microsoft/azure-skills/main/skills/python-appservice-deploy/scripts/retry-az-create.sh

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: python-appservice-deploy
description: "Deploy Python (Flask/Django/FastAPI) code to Azure App Service Linux. WHEN: \"Flask App Service\", \"Django App Service\", \"FastAPI App Service\", \"deploy Python to App Service\". DO NOT USE FOR: Container Apps, Functions, non-Python, Terraform/Bicep/IaC, full infra — use azure-prepare."
license: MIT
metadata:
  author: Microsoft
  version: "1.1.1"
---

# Python on Azure App Service — Code Deploy

Deploys Python (Flask, Django, FastAPI, generic) code to Azure App Service Linux (P0v3, Python 3.14). Creates RG + Plan + Web App if missing. Hand off to `azure-prepare` for VNet, Key Vault, databases, or IaC.

**MCP tools used**: `mcp_azure_mcp_subscription_list`, `mcp_azure_mcp_group_list`, `mcp_azure_mcp_appservice`, `mcp_azure_mcp_azd` (when `azure.yaml` is present).

## Workflow

1. **Resolve context — smart defaults, minimal prompts.** Only the app name is interactive; RG (`<app>-rg`), Plan (`<app>-plan`), region (current `az` default or `eastus2`), subscription are derived. [create-app.md](references/create-app.md) §1.
2. **Detect framework** (advisory, never blocks). [detect.md](references/detect.md).
3. **Choose path** — `azure.yaml` host: appservice → [deploy-azd.md](references/deploy-azd.md); else [deploy-azcli.md](references/deploy-azcli.md).
4. **Ensure RG → Plan (`P0v3 --is-linux`) → Web App (`--runtime "PYTHON:3.14"`)** exist. On transient ARM errors, follow [transient-retry.md](references/transient-retry.md). [create-app.md](references/create-app.md).
5. **Set startup** — Flask/Django: none (Oryx auto-detects). FastAPI: always `python -m uvicorn main:app --host 0.0.0.0`. Other: warn. [startup-commands.md](references/startup-commands.md).
6. **Set `SCM_DO_BUILD_DURING_DEPLOYMENT=true`**.
7. **Deploy** — `azd deploy` or `az webapp deploy --type zip --track-status false`.
8. **STOP. Print the post-deploy message** ([post-deploy-message.md](references/post-deploy-message.md)) and end the turn.

### Hard rules

- ⛔ **NO POST-DEPLOY VERIFICATION** — after deploy returns, do not run `az webapp log tail`, `curl`, `Invoke-WebRequest`, or any health probe. App Service needs 2–3 min to warm; a quiet log or early 5xx is not failure.
- ⛔ **SHELL SAFETY** — for `--runtime` always use `"PYTHON:3.14"` (colon). Never `"PYTHON|3.14"` (pipe is a shell operator).
- ⛔ **NEVER `az webapp up`** — deprecated. Use Step 7 commands.
- ✅ **URL FORMAT** — present endpoints as `https://...` URLs.

## Error Handling

See [errors.md](references/errors.md) for the full symptom → cause → fix matrix. Quick triage: missing plan/app → re-run Step 4; container ping timeout on 8000 → fix startup (Step 5); `ModuleNotFoundError` after deploy → ensure Step 6 ran, redeploy.

<!-- chapter:end slug=python-appservice-deploy -->
