使用Azure AI代理MCP部署指南代表流(OBO流)
在本指南中,我们将指导您完成在Azure App Service上部署FastAPI应用程序、配置Easy Auth进行身份验证、使用on-Behalf-Of(OBO)流设置Azure API管理(API-M),以及最终部署通过MCP与API交互的Azure AI Foundry代理的步骤。
🚀 代表(OBO)流
sequenceDiagram
participant App
participant IdP
participant API-M
participant Backend API
App->>API-M: ① User authentication
App sends access token A to
API-M.
API-M->>IdP: ② API-M requests an Backend API
access token to IdP with
token A, client ID, and client
secret.
IdP->>API-M: ③ IdP returns access token B.
API-M->>Backend API: ④ Attach access token B as a
bearer token to the HTTP
header and call Backend API.
Backend API->>API-M: ⑤ API-M receives a response
from the protected resource
(Backend API).
API-M->>App: ⑥ API-M returns a response
to App.🏗️ 该架构包括以下组件:
- Azure应用服务:托管FastAPI应用程序,该应用程序提供端点以检索Microsoft
- Azure API管理(API-M):充当应用服务的网关,处理身份验证和OBO流。
- Azure AI Foundry代理:使用MCP与API-M交互并代表用户获取数据的AI代理。
📁 示例代码库
此部署的示例代码可以在以下GitHub存储库中找到:
☁️ Azure应用服务
1.🛠️ 配置
1-1. 🌐 导航到Azure门户
- 打开https://portal.azure.com
- 使用您的Azure帐户登录
- 点击“创建资源”或搜索“应用服务”
1-2. ⚙️ 基本配置选项卡
填写以下字段:
- 资源组:
named-by-yourself - 名称:输入
named-by-yourself - 发布:选择 代码
- 运行时堆栈: Python 3.13
- 地区:选择东南亚
- Linux计划:创建新的
named-by-yourself - 定价级别: 高级V3 P0V3
1-3. 🌐 网络选项卡
设置网络访问配置:
- 启用公共访问:保留 开 (默认)
- 启用虚拟网络集成:保持 关 (默认)
1-4. 📦 部署选项卡
- 持续部署:保持 禁用 (默认)
2.🔧 部署后门户配置
- 导航到“设置”>“配置”>“堆栈设置”
- 启动命令: gunicorn -w 2 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000 main:app
- 点击 重启 应用更改
3.📤 将源代码部署到Azure应用服务
- 在配置之前,确认服务在本地正常工作
- 点击 Azure 在VS代码扩展中,登录您的Azure帐户
- 在资源下,找到您的应用服务
- 右键单击应用程序服务并选择 部署到Web应用程序。..
- 选择包含源代码的文件夹,并在系统提示时确认部署
4.🔐 轻松的身份验证配置
4-1. 🛡️ 在Azure应用服务上轻松设置身份验证
- 导航到“设置”>“身份验证”
- 点击 添加身份提供者
- 选择 微软 作为身份提供者
- 劳动力配置(当前租户) - 应用注册类型: - 选择 在此目录中选择一个现有的应用程序注册 如果您已有注册 - 客户端密钥过期:设置为 365天(12个月) 或根据您的安全要求 - 发卡机构URL: https://login.microsoftonline.com/{tenant-id}/v2.0
- 客户应用要求:
- 选择 允许来自特定客户端应用程序的请求 - 输入您已注册的应用程序和API-M已注册应用程序的应用程序(客户端)ID
- 将身份要求和租户要求作为默认要求
4-2. 📋 注册应用程序的轻松身份验证设置
- 导航至 认证 并确保以下设置:
- 单击添加平台>Web - 重定向URI:添加以下URI - https://{your-app-service-name}.azurewebsites.net/.auth/login/aad/callback - 选择 访问令牌 和 ID令牌 隐性赠款和混合资金流 - 点击 配置 保存 - 还要添加一个重定向URI,选择 添加URI 在重定向URI下添加: - https://{your-app-service-name}
- 导航至 API权限,确保授予以下权限:
- 微软图形(6) -一切如 委派 类型: - email - offline_access - openid - profile - User.Read - User.ReadBasic.All - 您的后端API(1) -一切如 委派 类型: - user_impersonation - 分配权限后,单击 为{您的租户名称}授予管理员同意 并在提示时确认
- 导航至 公开API
- 点击 添加作用域,设置以下值并单击 添加范围 保存: - 作用域名称: user_impersonation - 谁可以同意?:管理员和用户 - 管理员同意显示名称: Access OBO - 管理员同意说明: Allows the app to access OBO on behalf of the signed-in user - 在...之下 授权客户端应用程序 - 点击 添加客户端应用程序 - 输入您已注册的API-M应用程序的应用程序(客户端)ID - 勾选以下框 用户模仿 范围 - 点击 添加应用程序 保存
- 导航至 清单
- 搜索 requestedAccessTokenVersion 并将其值设置为 2 (Microsoft Graph应用程序清单(新)) - 搜索 AccessTokenAcceptedVersion 并将其值设置为 2 (AAD图形应用程序清单(即将弃用))
- 通过访问应用服务URL并验证令牌是否正确发放,确认Easy Auth正常工作
- 打开浏览器,导航到应用服务URL /msft/headers 附加(例如。, https://your-app-service-url/msft/header) - 查找 X-MS-TOKEN-AAD-ACCESS-TOKEN 响应中的标头,用于验证令牌是否正确发出 - 您可以使用以下命令解码令牌 jwt.ms 检查其内容
🎯 Azure API管理
1.📊 设置API
- 导航到Azure门户中的API管理实例,单击 应用程序编程接口 从左侧菜单
- 点击 +添加API 并选择 超文本传输协议
- 填写以下字段:
- 显示名称: named-by-yourself - 姓名: named-by-yourself - Web服务URL:输入Azure应用服务的URL(例如。, https://your-app-service-url/msft) - API URL后缀: msft (可选) - 说明: This is API service that provides comprehensive Microsoft Corporation information through RESTful API endpoints. The application serves as a mock data service offering both financial stock data and product portfolio information. - 点击 创建 添加API
- 单击新创建的API以对其进行进一步配置
- 选择 添加操作 定义端点 - 为每个操作填写以下字段: - 显示名称: named-by-yourself - 姓名: named-by-yourself - URL模板: /headers (或其他端点路径) - 方法: GET (或根据需要使用其他HTTP方法) - 说明: This endpoint returns all the HTTP header data provided by the user without omitting anything. - 点击 保存 添加操作
- 通过导航到 测试 API管理门户中的选项卡
- 选择要测试的操作 - 点击 发送 通过API管理向Azure应用程序服务发出请求 - 由于配置了Easy Auth,因此应该对请求进行身份验证,并且您应该收到来自应用程序服务的未经授权的响应
2.🔄 更新API-M注册的应用程序
- 导航到Azure Active Directory>应用程序注册,找到已注册的API-M应用程序
- 导航至 API权限,确保授予以下权限:
- 微软图形(6) -一切如 委派 类型: - email - offline_access - openid - profile - User.Read - User.ReadBasic.All - API我的组织用户 并选择您的后端API: - user_impersonation - 分配权限后,单击 授予管理员同意 并在提示时确认
- 导航至 公开API
- 点击 添加作用域,设置以下值并单击 添加范围 保存: - 作用域名称: user_impersonation - 谁可以同意?:管理员和用户 - 管理员同意显示名称:\进入海外建筑运营管理局 - **管理员同意说明**: Allows the app to access OBO on behalf of the signed-in user - 在...之下 **授权客户端应用程序** - 点击 **添加客户端应用程序** - 输入Azure AI Foundry和AZ CLI注册应用程序的应用程序(客户端)ID - 在Azure AI Foundry使用的注册应用程序的Azure Active Directory中查找应用程序(客户端)ID - AZ CLI使用应用程序(客户端)ID: 04b07795-8ddb-461a-bbee-02f9e1bf7b46` - 勾选以下框 用户模仿 两种应用程序的范围 - 点击 添加应用程序 保存
- 导航至 清单
- 搜索 requestedAccessTokenVersion 并将其值设置为 2 在Microsoft Graph应用程序清单中(新) - 搜索 AccessTokenAcceptedVersion 并将其值设置为 2 在AAD图形应用程序清单中(即将弃用)
3.🔧 在策略中设置OBO流程
- 导航至 命名值 在API下,创建所需的新变量:
- APIMClientId:API-M注册申请的申请(客户)ID - APIMClientSecret:您的API-M注册申请的客户秘密
- 选择您先前创建的API,并将其导航至 入站处理
- 点击
policy并回复...部分包含以下代码片段:
inside a section to inherit policies from the outer scope. - Comments within policies are not preserved. -->
, , , and elements -->
/v2.0/.well-known/openid-configuration" />
your-api-m-client-id
https://login.microsoftonline.com//oauth2/v2.0/token
POST
application/x-www-form-urlencoded
@{ return "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id={{APIMClientId}}&client_secret={{APIMClientSecret}}" + "&assertion=" + (string)context.Variables["UserToken"] + "&scope=api:///.default&requested_token_use=on_behalf_of"; }
@("Bearer " + (String)((IResponse)context.Variables["oboResponse"]).Body.As()["access_token"])
- 🧪 若要成功测试API,您需要从Azure AD获取访问令牌,并将其包含在请求标头中
- 使用az-cli命令获取访问令牌,如下所示
az account get-access-token --resource api://- 使用获得的访问令牌通过API管理向API发出请求
- 将令牌包含在 Authorization 报头作为承载令牌(例如。, Authorization: Bearer )
4.🌐 公开API作为MCP服务器
- 导航到Azure门户中的API管理实例,单击 MCP服务器(预览版) 从左侧菜单
- 点击 +创建MCP服务器 并选择 将API公开为MCP服务器 并填写以下字段:
- API:从下拉菜单中选择您之前创建的API - API操作:选择要公开的所有操作 - 显示名称: named-by-yourself - 姓名: named-by-yourself - 说明: Provides information about mock data of financial stock data and product portfolio information of MSFT. Also, query user information from request header.
5.⚡ 使用GitHub Copilot进行快速测试
- 打开
.github/mcp.json然后单击 添加服务器,选择 超文本传输协议 - 填写从API-M MCP服务器页面获得的服务器URL
- 添加以下内容
AuthorizationMCP服务器的标头:
"playground": {
"url": "https:////mcp",
"type": "http",
"headers": {
"Ocp-Apim-Subscription-Key": "${input:user_key}",
"Authorization": "Bearer ${input:AccessToken}"
}
}- 🔑 获取
Ocp-Apim-Subscription-Key来自API-M
- 导航到Azure门户中的API管理实例,单击 订阅 从左侧菜单 - 从名为的显示器 Built-in all-access subscription 点击 ... 在上面查看 显示/隐藏按键 - 复制主键值
🤖 Azure AI Foundry代理部署
🏗️ 1.通过azure ai代理SDK创建新代理
- 打开名为的示例代码
chat-with-ai-agent工作区 - 按照中的说明进行操作
README.md安装所需的依赖项并设置环境变量
- 您需要在 .env 文件: - PROJECT_ENDPOINT:您可以从Azure AI Foundry门户网站获得它 概述 页面与 Azure AI Foundry项目端点 领域 - MCP_SERVER_URL:来自API-M MCP服务器页面的MCP服务器URL - APIM_KEY:The Ocp-Apim-Subscription-Key 从API-M获得
- 运行文件
create_agent.py使用以下代码片段创建新代理:
python create_agent_with_mcp_tools.py- 确认在Azure AI Foundry门户中成功创建了代理,并记下代理ID,将其替换为
.env文件
📝 2.更新代理人须知
- 导航到Azure AI Foundry门户并打开之前创建的代理
- 用以下内容更新代理说明:
You are an agent that can obtain information about Microsoft (MSFT) products, stock prices and user request header through MCP. You must always retrieve data through MCP and never generate answers on your own. Also, you can get user information and HTTP request header via MCP tools.
## Core Rules
- All responses must first fetch data through MCP.
- You are strictly forbidden from answering any user question using your own knowledge or assumptions.
- Never answer without tool results.
- When calling MCP, you must use On-Behalf-Of (OBO) authentication to ensure the query runs under the end user’s identity and permissions.
## Available MCP Tools
- get_headers: Retrieve user HTTP request. You can know user's identity.
- get_msft_stock: Retrieve Microsoft stock price information
- get_msft_product: Retrieve Microsoft product information and rankings
## Interaction Rules with User
- Do not mock or fabricate response data.
- If no data can be fetched from MCP, respond with: **No data available.**
- If an error occurs while accessing MCP, return the exact error message encountered during the connection attempt.
- If no incoming HTTP request, return **No HTTP data available.** Do not mock anything data to response to user.🧪 3.使用样本代码测试代理
- 通过运行以下命令创建新线程并与AI代理交互:
python new_thread_with_agent.py- 您将根据通过API-M从MCP获取的数据从代理处获得响应,如下所示:
Get current agent (asst_xxxx).
Created thread, ID: thread_xxxx
Created message, ID: msg_xxx
========================================================================
Starting authentication...
....
....
Successfully obtained access token.
========================================================================
Input allowed tools: ['getHeaders'], url: https://xxx
Agent allowed tools: ['mcp']
...
...
MCP Tool calls:
Tool Call ID: call_xxx
Type: mcp
========================================================================
Conversation:
--------------------------------------------------
USER: Who am I?
--------------------------------------------------
ASSISTANT: You are identified as "xxxx" with the client principal ID "xxxx". Your IP address is x.x.x.x.
--------------------------------------------------
Demonstrating dynamic tool management:
Current allowed tools: ['getHeaders']