entra-agent-id

Crear y gestionar identidades compatibles con OAuth2 para agentes de IA usando la API beta de Microsoft Graph.

npx skills add https://github.com/microsoft/agent-skills --skill entra-agent-id

Microsoft Entra Agent ID

Create and manage OAuth2-capable identities for AI agents using Microsoft Graph beta API.

Preview API — All Agent Identity endpoints are under /beta only. Not available in /v1.0.

Before You Start

Search microsoft-docs MCP for the latest Agent ID documentation:

  • Query: "Microsoft Entra agent identity setup"
  • Verify: API parameters match current preview behavior

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

Prerequisites

PowerShell (recommended for interactive setup)

# Requires PowerShell 7+
Install-Module Microsoft.Graph.Beta.Applications -Scope CurrentUser -Force

Python (for programmatic provisioning)

pip install azure-identity requests

Required Entra Roles

One of: Agent Identity Developer, Agent Identity Administrator, or Application Administrator.

Environment Variables

AZURE_TENANT_ID=<your-tenant-id>
AZURE_CLIENT_ID=<app-registration-client-id>
AZURE_CLIENT_SECRET=<app-registration-secret>

Authentication

⚠️ DefaultAzureCredential is NOT supported. Azure CLI tokens contain Directory.AccessAsUser.All, which Agent Identity APIs explicitly reject (403). You MUST use a dedicated app registration with client_credentials flow or connect via Connect-MgGraph with explicit delegated scopes.

PowerShell (delegated permissions)

Connect-MgGraph -Scopes @(
    "AgentIdentityBlueprint.Create",
    "AgentIdentityBlueprint.ReadWrite.All",
    "AgentIdentityBlueprintPrincipal.Create",
    "User.Read"
)
Set-MgRequestContext -ApiVersion beta

$currentUser = (Get-MgContext).Account
$userId = (Get-MgUser -UserId $currentUser).Id

Python (application permissions)

import os
import 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/beta"
headers = {
    "Authorization": f"Bearer {token.token}",
    "Content-Type": "application/json",
    "OData-Version": "4.0",  # Required for all Agent Identity API calls
}

Core Workflow

Step 1: Create Agent Identity Blueprint

Sponsors are required and must be User objects — ServicePrincipals and Groups are rejected.

import subprocess

# Get sponsor user ID (client_credentials has no user context, so use az CLI)
result = subprocess.run(
    ["az", "ad", "signed-in-user", "show", "--query", "id", "-o", "tsv"],
    capture_output=True, text=True, check=True,
)
user_id = result.stdout.strip()

blueprint_body = {
    "@odata.type": "Microsoft.Graph.AgentIdentityBlueprint",
    "displayName": "My Agent Blueprint",
    "[email protected]": [
        f"https://graph.microsoft.com/beta/users/{user_id}"
    ],
}
resp = requests.post(f"{GRAPH}/applications", 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

This step is mandatory. Creating a Blueprint does NOT auto-create its service principal. Without this, Agent Identity creation fails with: 400: The Agent Blueprint Principal for the Agent Blueprint does not exist.

sp_body = {
    "@odata.type": "Microsoft.Graph.AgentIdentityBlueprintPrincipal",
    "appId": app_id,
}
resp = requests.post(f"{GRAPH}/servicePrincipals", headers=headers, json=sp_body)
resp.raise_for_status()

If implementing idempotent scripts, check for and create the BlueprintPrincipal even when the Blueprint already exists (a previous run may have created the Blueprint but crashed before creating the SP).

Step 3: Create Agent Identities

agent_body = {
    "@odata.type": "Microsoft.Graph.AgentIdentity",
    "displayName": "my-agent-instance-1",
    "agentIdentityBlueprintId": app_id,
    "[email protected]": [
        f"https://graph.microsoft.com/beta/users/{user_id}"
    ],
}
resp = requests.post(f"{GRAPH}/servicePrincipals", headers=headers, json=agent_body)
resp.raise_for_status()
agent = resp.json()

API Reference

OperationMethodEndpointOData Type
Create BlueprintPOST/applicationsMicrosoft.Graph.AgentIdentityBlueprint
Create BlueprintPrincipalPOST/servicePrincipalsMicrosoft.Graph.AgentIdentityBlueprintPrincipal
Create Agent IdentityPOST/servicePrincipalsMicrosoft.Graph.AgentIdentity
List Agent IdentitiesGET/servicePrincipals?$filter=...
Delete Agent IdentityDELETE/servicePrincipals/{id}
Delete BlueprintDELETE/applications/{id}

All endpoints use base URL: https://graph.microsoft.com/beta

Required Permissions

PermissionPurpose
Application.ReadWrite.AllBlueprint CRUD (application objects)
AgentIdentityBlueprint.CreateCreate new Blueprints
AgentIdentityBlueprint.ReadWrite.AllRead/update Blueprints
AgentIdentityBlueprintPrincipal.CreateCreate BlueprintPrincipals
AgentIdentity.Create.AllCreate Agent Identities
AgentIdentity.ReadWrite.AllRead/update Agent Identities

There are 18 Agent Identity-specific Graph application permissions. Discover all:

az ad sp show --id 00000003-0000-0000-c000-000000000000 \
  --query "appRoles[?contains(value, 'AgentIdentity')].{id:id, value:value}" -o json

Grant admin consent (required for application permissions):

az ad app permission admin-consent --id <client-id>

Admin consent may fail with 404 if the service principal hasn't replicated. Retry with 10–40s backoff.

Cleanup

# Delete Agent Identity
requests.delete(f"{GRAPH}/servicePrincipals/{agent['id']}", headers=headers)

# Delete BlueprintPrincipal (get SP ID first)
sps = requests.get(
    f"{GRAPH}/servicePrincipals?$filter=appId eq '{app_id}'",
    headers=headers,
).json()
for sp in sps.get("value", []):
    requests.delete(f"{GRAPH}/servicePrincipals/{sp['id']}", headers=headers)

# Delete Blueprint
requests.delete(f"{GRAPH}/applications/{blueprint_obj_id}", headers=headers)

Best Practices

  1. Always create BlueprintPrincipal after Blueprint — not auto-created; implement idempotent checks on both
  2. Use User objects as sponsors — ServicePrincipals and Groups are rejected
  3. Handle permission propagation delays — after admin consent, wait 30–120s; retry with backoff on 403
  4. Include OData-Version: 4.0 header on every Graph request
  5. Use Workload Identity Federation for production auth — for local dev, use a client secret on the Blueprint (see references/oauth2-token-flow.md)
  6. Set identifierUris on Blueprint before using OAuth2 scoping (api://{app-id})
  7. Never use Azure CLI tokens for API calls — they contain Directory.AccessAsUser.All which is hard-rejected
  8. Check for existing resources before creating — implement idempotent provisioning

References

FileContents
references/oauth2-token-flow.mdProduction (Managed Identity + WIF) and local dev (client secret) token flows
references/known-limitations.md29 known issues organized by category (from official preview known-issues page)
references/sdk-sidecar.mdMicrosoft Entra SDK for AgentID — endpoints, 3P agent patterns, Docker/K8s deployment, security

External Links

ResourceURL
Official Setup Guidehttps://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-setup-instructions
AI-Guided Setuphttps://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-ai-guided-setup
Microsoft Entra SDK for AgentID — Overviewhttps://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/overview
Microsoft Entra SDK for AgentID — Endpointshttps://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/endpoints

Más skills de microsoft

oss-growth
microsoft
Persona de growth hacker de OSS
official
microsoft-foundry
microsoft
Implementar, evaluar y gestionar agentes de Foundry de extremo a extremo: compilación de Docker, envío a ACR, creación de agente alojado/de prompt, inicio de contenedor, evaluación por lotes, evaluación continua, flujos de trabajo del optimizador de prompts, agent.yaml, curación de conjuntos de datos a partir de trazas. USAR PARA: implementar agente en Foundry, agente alojado, crear agente, invocar agente, evaluar agente, ejecutar evaluación por lotes, evaluación continua, monitoreo continuo, estado de evaluación continua, optimizar prompt, mejorar prompt, optimizador de prompts, optimizar instrucciones del agente, mejorar agente...
officialdevelopmentdevops
azure-ai
microsoft
Útil para Azure AI: Search, Speech, OpenAI, Document Intelligence. Ayuda con búsqueda, búsqueda vectorial/híbrida, voz a texto, texto a voz, transcripción, OCR. CUANDO: AI Search, búsqueda de consultas, búsqueda vectorial, búsqueda híbrida, búsqueda semántica, voz a texto, texto a voz, transcribir, OCR, convertir texto a voz.
officialdevelopmentapi
azure-deploy
microsoft
Ejecuta despliegues en Azure para aplicaciones YA PREPARADAS que tengan archivos .azure/deployment-plan.md e infraestructura existentes. NO uses esta habilidad cuando el usuario solicite CREAR una nueva aplicación — usa azure-prepare en su lugar. Esta habilidad ejecuta comandos azd up, azd deploy, terraform apply y az deployment con recuperación de errores integrada. Requiere .azure/deployment-plan.md de azure-prepare y estado validado de azure-validate. CUANDO: "ejecutar azd up", "ejecutar azd deploy", "ejecutar despliegue",...
officialdevopsaws
azure-storage
microsoft
Servicios de Azure Storage que incluyen Blob Storage, File Shares, Queue Storage, Table Storage y Data Lake. Responde preguntas sobre niveles de acceso de almacenamiento (hot, cool, cold, archive), cuándo usar cada nivel y comparación entre niveles. Proporciona almacenamiento de objetos, recursos compartidos de archivos SMB, mensajería asíncrona, NoSQL clave-valor y análisis de big data. Incluye gestión del ciclo de vida. USAR PARA: blob storage, file shares, queue storage, table storage, data lake, subir archivos, descargar blobs, cuentas de almacenamiento, niveles de acceso,...
officialdevelopmentdatabase
azure-diagnostics
microsoft
Depura problemas de producción en Azure usando AppLens, Azure Monitor, estado de recursos y triaje seguro. CUANDO: depurar problemas de producción, solucionar problemas de App Service, CPU alta en App Service, fallo de implementación de App Service, solucionar problemas de Container Apps, solucionar problemas de Functions, solucionar problemas de AKS, kubectl no puede conectar, fallos de kube-system/CoreDNS, pod pendiente, crashloop, nodo no listo, fallos de actualización, analizar registros, KQL, información, fallos de extracción de imágenes, problemas de arranque en frío, fallos de sondeo de estado,...
officialdevopsdevelopment
azure-prepare
microsoft
Prepara aplicaciones de Azure para el despliegue (infra Bicep/Terraform, azure.yaml, Dockerfiles). Úselo para crear/modernizar o crear+desplegar; no para migración entre nubes (use azure-cloud-migrate). NO USAR PARA: aplicaciones copilot-sdk (use azure-hosted-copilot-sdk). CUANDO: "crear aplicación", "construir aplicación web", "crear API", "crear API HTTP sin servidor", "crear frontend", "crear backend", "construir un servicio", "modernizar aplicación", "actualizar aplicación", "agregar autenticación", "agregar almacenamiento en caché", "alojar en Azure", "crear y...
officialdevelopmentdevops
azure-validate
microsoft
Validación previa al despliegue para la preparación en Azure. Realiza verificaciones exhaustivas de configuración, infraestructura (Bicep o Terraform), asignaciones de roles RBAC, permisos de identidad administrada y requisitos previos antes de desplegar. CUÁNDO: validar mi aplicación, verificar preparación para el despliegue, ejecutar comprobaciones previas, verificar configuración, comprobar si está listo para desplegar, validar azure.yaml, validar Bicep, probar antes de desplegar, solucionar errores de despliegue, validar Azure Functions, validar aplicación de funciones, validar serverless...
officialdevopstesting