entra-agent-id
microsoft/skills
使用 Microsoft Graph 测试版 API 为 AI 代理创建和管理支持 OAuth 2.0 的身份。
...展开全部Microsoft Entra 代理 ID
使用 Microsoft Graph 测试版 API 为 AI 代理创建和管理支持 OAuth 2.0 的身份。
预览版 API — 所有代理身份端点均位于
/beta。不适用于/v1.0.
开始之前
搜索 microsoft-docs MCP 中查找最新的代理身份文档:
- 查询:“Microsoft Entra 代理身份设置”
- 验证:API 参数是否与当前预览版的行为一致
概念模型
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
先决条件
PowerShell(建议用于交互式配置)
# Requires PowerShell 7+
Install-Module Microsoft.Graph.Beta.Applications -Scope CurrentUser -Force
Python(用于编程方式的配置)
pip install azure-identity requests
所需的 Entra 角色
以下角色之一:代理身份开发人员、代理身份管理员或应用程序管理员。
环境变量
AZURE_TENANT_ID=
AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
身份验证
⚠️ 不支持 `
DefaultAzureCredential`。Azure CLI 令牌包含Directory.AccessAsUser.All,而代理身份 API 会明确拒绝此类令牌(403 错误)。 您必须使用带有client_credentialsflow,或 通过Connect-MgGraph并使用显式的委托范围。
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(应用程序权限)
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
}
核心工作流
步骤 1:创建代理身份蓝图
必须指定发起人,且发起人必须是“用户”对象——服务主体和组将被拒绝。
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"]
步骤 2:创建 BlueprintPrincipal
此步骤为必选步骤。创建蓝图不会自动创建其 服务主体。若缺少此步骤,代理身份的创建将因以下原因失败:
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()
若实现幂等脚本,请检查并创建 BlueprintPrincipal, 即使 Blueprint 已存在(之前的一次运行可能已创建了 Blueprint, 但在创建 SP 之前发生崩溃)。
步骤 3:创建代理身份
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 参考
| 操作 | 方法 | 端点 | OData 类型 |
|---|---|---|---|
| 创建蓝图 | POST |
/applications |
Microsoft.Graph.AgentIdentityBlueprint |
| 创建蓝图主体 | POST |
/servicePrincipals |
Microsoft.Graph.AgentIdentityBlueprintPrincipal |
| 创建代理身份 | POST |
/servicePrincipals |
Microsoft.Graph.AgentIdentity |
| 列出代理身份 | GET |
/servicePrincipals?$filter=... |
— |
| 删除代理标识 | DELETE |
/servicePrincipals/{id} |
— |
| 删除蓝图 | DELETE |
/applications/{id} |
— |
所有端点均使用基础 URL: https://graph.microsoft.com/beta
所需权限
| 权限 | 用途 |
|---|---|
Application.ReadWrite.All |
蓝图 CRUD(应用程序对象) |
AgentIdentityBlueprint.Create |
创建新的蓝图 |
AgentIdentityBlueprint.ReadWrite.All |
读取/更新蓝图 |
AgentIdentityBlueprintPrincipal.Create |
创建蓝图主体 |
AgentIdentity.Create.All |
创建代理身份 |
AgentIdentity.ReadWrite.All |
读取/更新代理身份 |
共有 18 项与代理身份相关的 Graph 应用程序权限。查看全部:
az ad sp show --id 00000003-0000-0000-c000-000000000000 \
--query "appRoles[?contains(value, 'AgentIdentity')].{id:id, value:value}" -o json
授予管理员同意(应用程序权限所需):
az ad app permission admin-consent --id
如果服务主体尚未完成复制,管理员同意可能会因 404 错误而失败。请以 10–40 秒的间隔重试。
清理
# 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)
最佳实践
- 请务必在创建 Blueprint 之后再创建 BlueprintPrincipal —— 该对象不会自动创建;请对两者均实施幂等性检查
- 使用 User 对象作为发起者——ServicePrincipals 和 Groups 将被拒绝
- 处理权限传播延迟——获得管理员同意后,等待 30–120 秒;遇到 403 错误时,按退避策略重试
- 在每个 Graph 请求中包含
OData-Version: 4.0标头 - 生产环境认证请使用工作负载身份联合(Workload Identity Federation)——本地开发时,请在 Blueprint 中使用客户端密钥(参见 references/oauth2-token-flow.md)
- 在使用 OAuth2 范围控制前,请在 Blueprint 中设置
identifierUris(api://{app-id}) - 切勿使用 Azure CLI 令牌进行 API 调用——它们包含
Directory.AccessAsUser.All,这会导致请求被直接拒绝 - 创建前检查现有资源 — 实现幂等配置
参考资料
| 文件 | 目录 |
|---|---|
| references/oauth2-token-flow.md | 生产环境(托管身份 + WIF)和本地开发环境(客户端密钥)的令牌流 |
| references/known-limitations.md | 按类别整理的 29 个已知问题(源自官方预览版已知问题页面) |
| references/sdk-sidecar.md | Microsoft Entra AgentID SDK — 端点、第三方代理模式、Docker/K8s 部署、安全性 |
外部链接
| 资源 | URL |
|---|---|
| 官方设置指南 | https://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-setup-instructions |
| AI 引导式设置 | https://learn.microsoft.com/en-us/entra/agent-id/identity-platform/agent-id-ai-guided-setup |
| Microsoft Entra AgentID SDK — 概述 | https://learn.microsoft.com/en-us/entra/msidweb/agent-id-sdk/overview |
| Microsoft Entra AgentID SDK — 端点 | 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 |





首页
