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, 即使藍圖已存在亦然(先前執行時可能已建立藍圖, 但在建立服務主體前發生當機)。
步驟 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標頭 - 生產環境的身份驗證請使用「工作負載身份聯邦」——本地開發時,請在 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 部署、安全性 |
外部連結
| 資源 | 網址 |
|---|---|
| 官方設定指南 | 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 |
所有檔案
0 個檔案安裝 entra-agent-id
請下載技能檔案,並將其解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/skills/entra-agent-id # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
