entra-agent-id
microsoft/skills
Crea y gestiona identidades compatibles con OAuth 2.0 para agentes de IA mediante la API beta de Microsoft Graph.
...Expandir todoMicrosoft Entra Agent ID
Crea y gestiona identidades compatibles con OAuth 2.0 para agentes de IA mediante la API beta de Microsoft Graph.
API en versión preliminar: todos los puntos finales de Agent Identity se encuentran
/betasolo. No está disponible en/v1.0.
Antes de empezar
Buscar microsoft-docs en MCP la documentación más reciente sobre la identidad de agente:
- Consulta: «Configuración de la identidad de agente de Microsoft Entra»
- Comprueba que los parámetros de la API se ajusten al comportamiento actual de la versión preliminar
Modelo conceptual
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
Requisitos previos
PowerShell (recomendado para la configuración interactiva)
# Requires PowerShell 7+
Install-Module Microsoft.Graph.Beta.Applications -Scope CurrentUser -Force
Python (para el aprovisionamiento mediante programación)
pip install azure-identity requests
Roles de Entra necesarios
Una de las siguientes: desarrollador de identidades de agente, administrador de identidades de agente o administrador de aplicaciones.
Variables de entorno
AZURE_TENANT_ID=
AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
Autenticación
⚠️ NO se admite «
DefaultAzureCredential». Los tokens de la CLI de Azure contienenDirectory.AccessAsUser.All, que las API de Agent Identity rechazan explícitamente (403). DEBES utilizar un registro de aplicación dedicado conclient_credentialsflow o conectarse a través deConnect-MgGraphcon ámbitos delegados explícitos.
PowerShell (permisos delegados)
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 (permisos de aplicación)
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
}
Flujo de trabajo básico
Paso 1: Crear un modelo de identidad de agente
Se requieren patrocinadores, que deben ser objetos «User»; se rechazan los objetos «ServicePrincipal» y «Group».
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"]
Paso 2: Crear BlueprintPrincipal
Este paso es obligatorio. La creación de un Blueprint NO genera automáticamente su entidad de servicio. Sin ello, la creación de la identidad del agente falla con el siguiente mensaje:
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()
Si se implementan scripts idempotentes, compruebe si existe el BlueprintPrincipal y créelo incluso si el Blueprint ya existe (es posible que una ejecución anterior haya creado el Blueprint pero se haya bloqueado antes de crear el SP).
Paso 3: Crear identidades de agente
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()
Referencia de la API
| Operación | Método | Punto final | Tipo OData |
|---|---|---|---|
| Crear Blueprint | POST |
/applications |
Microsoft.Graph.AgentIdentityBlueprint |
| Crear BlueprintPrincipal | POST |
/servicePrincipals |
Microsoft.Graph.AgentIdentityBlueprintPrincipal |
| Crear identidad de agente | POST |
/servicePrincipals |
Microsoft.Graph.AgentIdentity |
| Listar identidades de agente | GET |
/servicePrincipals?$filter=... |
— |
| Eliminar identidad de agente | DELETE |
/servicePrincipals/{id} |
— |
| Eliminar plantilla | DELETE |
/applications/{id} |
— |
Todos los puntos finales utilizan la URL base: https://graph.microsoft.com/beta
Permisos necesarios
| Permiso | Finalidad |
|---|---|
Application.ReadWrite.All |
CRUD de plantillas (objetos de la aplicación) |
AgentIdentityBlueprint.Create |
Crear nuevos Blueprints |
AgentIdentityBlueprint.ReadWrite.All |
Leer/actualizar Blueprints |
AgentIdentityBlueprintPrincipal.Create |
Crear BlueprintPrincipals |
AgentIdentity.Create.All |
Crear identidades de agente |
AgentIdentity.ReadWrite.All |
Leer/actualizar identidades de agente |
Hay 18 permisos de aplicación de Graph específicos para identidades de agente. Descúbrelos todos:
az ad sp show --id 00000003-0000-0000-c000-000000000000 \
--query "appRoles[?contains(value, 'AgentIdentity')].{id:id, value:value}" -o json
Conceder el consentimiento de administrador (requerido para los permisos de aplicación):
az ad app permission admin-consent --id
El consentimiento de administrador puede fallar con un error 404 si la entidad de servicio no se ha replicado. Vuelve a intentarlo con un intervalo de espera de entre 10 y 40 segundos.
Limpieza
# 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)
Prácticas recomendadas
- Crea siempre BlueprintPrincipal después de Blueprint —no se crea automáticamente—; implementa comprobaciones idempotentes en ambos
- Utiliza objetos «User» como patrocinadores; se rechazan los «ServicePrincipals» y los «Groups»
- Gestiona los retrasos en la propagación de permisos: tras el consentimiento del administrador, espera entre 30 y 120 s; vuelve a intentarlo con un tiempo de espera en caso de error 403
- Incluye el encabezado «
OData-Version: 4.0» en cada solicitud a Graph - Utiliza Workload Identity Federation para la autenticación en producción; para el desarrollo local, utiliza un secreto de cliente en el Blueprint (véase references/oauth2-token-flow.md)
- Configurar «
identifierUris» en el Blueprint antes de utilizar el ámbito de OAuth2 (api://{app-id}) - Nunca utilices tokens de la CLI de Azure para llamadas a la API, ya que contienen
Directory.AccessAsUser.Alllo cual se rechaza de forma automática - Comprueba si existen recursos antes de crearlos: implementa un aprovisionamiento idempotente
Referencias
| Archivo | Contenido |
|---|---|
| referencias/oauth2-token-flow.md | Flujos de tokens en producción (identidad gestionada + WIF) y en desarrollo local (secreto de cliente) |
| referencias/limitaciones-conocidas.md | 29 problemas conocidos organizados por categoría (de la página oficial de problemas conocidos de la versión preliminar) |
| references/sdk-sidecar.md | SDK de Microsoft Entra para AgentID: puntos de conexión, patrones de agentes de terceros, implementación en Docker/K8s, seguridad |
Enlaces externos
| Recurso | URL |
|---|---|
| Guía oficial de configuración | https://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-setup-instructions |
| Configuración guiada por IA | https://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-ai-guided-setup |
| SDK de Microsoft Entra para AgentID: descripción general | https://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/overview |
| SDK de Microsoft Entra para AgentID: puntos finales | https://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/endpoints |
---
name: entra-agent-id
description: Create and manage OAuth2-capable identities for AI agents using Microsoft Graph beta API.
---
# 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)
```powershell
# Requires PowerShell 7+
Install-Module Microsoft.Graph.Beta.Applications -Scope CurrentUser -Force
```
### Python (for programmatic provisioning)
```bash
pip install azure-identity requests
```
### Required Entra Roles
One of: **Agent Identity Developer**, **Agent Identity Administrator**, or **Application Administrator**.
## Environment Variables
```bash
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)
```powershell
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)
```python
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.
```python
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.`
```python
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
```python
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
| Operation | Method | Endpoint | OData Type |
|-----------|--------|----------|------------|
| Create Blueprint | `POST` | `/applications` | `Microsoft.Graph.AgentIdentityBlueprint` |
| Create BlueprintPrincipal | `POST` | `/servicePrincipals` | `Microsoft.Graph.AgentIdentityBlueprintPrincipal` |
| Create Agent Identity | `POST` | `/servicePrincipals` | `Microsoft.Graph.AgentIdentity` |
| List Agent Identities | `GET` | `/servicePrincipals?$filter=...` | — |
| Delete Agent Identity | `DELETE` | `/servicePrincipals/{id}` | — |
| Delete Blueprint | `DELETE` | `/applications/{id}` | — |
All endpoints use base URL: `https://graph.microsoft.com/beta`
## Required Permissions
| Permission | Purpose |
|-----------|---------|
| `Application.ReadWrite.All` | Blueprint CRUD (application objects) |
| `AgentIdentityBlueprint.Create` | Create new Blueprints |
| `AgentIdentityBlueprint.ReadWrite.All` | Read/update Blueprints |
| `AgentIdentityBlueprintPrincipal.Create` | Create BlueprintPrincipals |
| `AgentIdentity.Create.All` | Create Agent Identities |
| `AgentIdentity.ReadWrite.All` | Read/update Agent Identities |
There are **18 Agent Identity-specific** Graph application permissions. Discover all:
```bash
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):
```bash
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
```python
# 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](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
| File | Contents |
|------|----------|
| [references/oauth2-token-flow.md](references/oauth2-token-flow.md) | Production (Managed Identity + WIF) and local dev (client secret) token flows |
| [references/known-limitations.md](references/known-limitations.md) | 29 known issues organized by category (from official preview known-issues page) |
| [references/sdk-sidecar.md](references/sdk-sidecar.md) | Microsoft Entra SDK for AgentID — endpoints, 3P agent patterns, Docker/K8s deployment, security |
### External Links
| Resource | URL |
|----------|-----|
| Official 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 — Overview | https://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/overview |
| Microsoft Entra SDK for AgentID — Endpoints | https://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/endpoints |
Todos los archivos
0 archivosInstalar entra-agent-id
Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.
Descargar ZIPClona el repositorio y copia los archivos de la habilidad a tu proyecto.
git clone https://github.com/microsoft/skills/tree/main/.github/skills/entra-agent-id # Copy SKILL.md to your .claude/skills/ directory
Copiar





Hogar
