在前几章中,你已经学习了如何使用 Azure AI Foundry Agent Service 创建第一个 AI agent,并探索了 connected agents 的 multi-agent orchestration。这些基础内容为你提供了 basic agent creation、instruction design 和 multi-agent coordination 的构建块。本章代码较多,将进一步探索 advanced capabilities,这些能力会把 agents 从简单 conversational assistants,转变为 tool-using autonomous systems,使其能够与 real-world data、APIs 和 enterprise workflows 交互。
一个没有 tools 的 AI agent,就像一位推理能力很强、但无法访问 patient records、无法开检查单,也无法开处方的医生。Tools 赋予 agents 行动能力——retrieving information、executing code、calling APIs、triggering workflows,以及与 external systems 交互。Azure AI Foundry 提供广泛的 enterprise tool connectivity,截至 2026 年初,支持 built-in tools、通过 OpenAPI specifications 实现 custom integrations、Model Context Protocol(MCP)servers、Azure Functions、Logic Apps 和 browser automation。
本章将覆盖以下主题:
- Understanding the agent tool ecosystem in Azure AI Foundry
- Working with built-in tools: file search, code interpreter, and grounding
- Integrating custom APIs with OpenAPI specification tools
- Connecting to external systems with Model Context Protocol(MCP)
- Using Azure Functions for Stateful Agent Tools
- Automating Enterprise Workflows with Logic Apps Integration
- Advanced Tool Patterns: Chaining, Error Handling, and Governance
- Case Studies: Healthcare Prior Authorization Agent and a Healthcare IT Help Desk Agent
Technical requirements
要跟随本章示例,你需要具备以下条件:
- 一个 active Azure subscription,并已创建 Azure AI Foundry project resource。设置方法请参考第 2 章。
- Python 3.10 或更高版本,并安装以下 packages:
pip install azure-ai-projects azure-ai-agents azure-identity openai python-dotenv
- 在你的 Foundry project 中至少部署一个 model。推荐使用 GPT-4o;如果你的 region 可用,也可以使用 GPT-4.1 或更高版本,因为 model availability 会随 deployment date 而变化。2026 年的读者通常可以访问更新的 models,包括 GPT-4.1 family、GPT-5 family、o-series reasoning models(o3、o4-mini),以及通过 Foundry Model Catalog 提供的 Anthropic Claude models(Claude Sonnet、Claude Opus)。这些都可以替代本章中的 GPT-4o 示例。请根据你所在 region 中可用、并满足 latency 和 cost targets 的最强 model 进行选择。
- 对于 OpenAPI tool 示例:需要一个 REST API endpoint。本章将使用一个 sample healthcare API。
- 对于 MCP 示例:需要一个 GitHub personal access token(classic),并具备 repository read permissions。
- 对于 Azure Functions 示例:需要在本地安装 Azure Functions Core Tools。
Understanding the Agent Tool Ecosystem
Azure AI Foundry Agent Service 提供了一套全面 tools,agents 可以使用这些 tools 完成任务。当 user 发送 query 时,AI model 会识别 intent、判断哪些 tools 相关,并 orchestrate tool calls,从而生成完整 response。理解 tool categories 以及何时使用每一种 tool,对于构建 production-grade agents 至关重要。
Agent tool ecosystem 被组织为三大类:knowledge tools,帮助 agents 访问和检索信息;action tools,使 agents 能够对 external systems 执行 operations;以及 built-in tools,在 agent runtime 中直接提供基础能力。接下来的小节中,我们将先探索 tool calling 的机械工作方式,然后逐一介绍 built-in tools,最后进入 custom integrations,把 agents 连接到组织自己的特定 systems 和 workflows。
How tool calling works
在深入具体 tools 之前,先理解 agents 如何使用 tools 的机制会很有帮助。当 agent 收到 user query 时,底层 model 会将 query 与 available tools 进行评估,并决定是否需要 tool call。如果 model 判断需要 tool,它会生成一个 structured tool call request,并带上 appropriate parameters。Agent runtime 执行 tool,将结果返回给 model,然后 model 将 tool output 纳入自己的 response 中。
那么,model 是如何决定这些 “appropriate parameters” 的?你注册给 agent 的每个 tool 都带有一个 JSON Schema definition,其中定义每个 parameter 的名称、类型,例如 string、integer、enumeration、object 等;是否 required;以及一段简短自然语言 description,说明它代表什么。当 user message 到达时,model 会在一次 forward pass 中执行两个 reasoning steps:首先,它会将 user intent 与 tool description 进行匹配,并判断是否调用该 tool;其次,它会回读 conversation history,包括任何 earlier tool results,并提取或推断满足 schema 的 values。随后,agent runtime 会在 dispatch call 前根据 schema 验证这些 values——如果 required field 缺失或类型错误,runtime 会将 structured error 返回给 model,而 model 通常会向 user 请求 clarification,或用修正后的 payload 重试。
这个过程可能涉及多个连续 tool calls。例如,一个 agent 可能先搜索 Azure AI Search 以查找相关 documents,然后使用 Code Interpreter 分析这些 documents 中的数据,最后通过 OpenAPI 调用 external API 提交结果。Model 会基于自己对任务的理解,自主 orchestrate 整个 flow。
为了更具体地说明,当 model 决定调用某个 tool 时,它会生成如下 JSON 结构化 payload。Agent runtime 会截获该 payload,并将调用派发给对应 tool implementation:
{
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "file_search",
"arguments": "{"query": "diabetes readmission guidelines"}"
}
}
]
}
Runtime 会使用提供的 arguments 执行命名 function,捕获结果,并作为 conversation 中的下一轮返回给 model。随后 model 会判断是否继续发起 tool calls,或生成最终 response。这个 request / response cycle 会不断重复,直到任务完成。
下面的代码展示了如何初始化 Azure AI Foundry SDK client。这是本章所有 agent operations 的基础:
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.agents.models import (
FileSearchTool, CodeInterpreterTool,
MessageTextContent, ListSortOrder
)
# Initialize the project client
credential = DefaultAzureCredential()
project_client = AIProjectClient(
endpoint="https://<your-project>.services.ai.azure.com",
credential=credential
)
这段 initialization code 使用 Microsoft Entra ID,也就是 formerly Azure Active Directory,authentication 连接到你的 Azure AI Foundry project。AIProjectClient 是所有 agent operations 的主要入口,包括 creating agents、managing threads 和 executing runs。
关于命名说明:本章中为了代码简洁,会使用较短的变量名 project。Microsoft 官方 Azure AI Foundry SDK quickstart examples 使用 project_client,以表明该变量是 project 的 API client;两种命名都可以接受。在 production code 中,如果其他 developers 会同时阅读 Microsoft docs,建议使用 project_client。
接下来,我们创建一个带有两个 built-in tools 的 agent。先介绍这两个 tools,是因为它们不需要额外 external infrastructure setup:File Search 让 agent 能从你直接上传到 Foundry project 的 documents 中检索内容;Code Interpreter 会在 managed sandbox 中运行 Python。二者结合覆盖了大量常见 agent tasks,例如 document Q&A、data analysis 和 chart generation,并能让你在添加本章后续 OpenAPI、MCP、Azure Functions 和 Logic Apps integrations 之前,先验证 agent 的端到端循环。
tools parameter 接收 tool definitions list。Agent 的 instructions 应明确引用 available tools,使 model 知道何时以及如何使用它们:
# Create an agent with built-in tools
agent = project.agents.create_agent(
model="gpt-4o",
name="healthcare-analyst",
instructions="""You are a healthcare data analyst.
Use File Search to find relevant clinical documents.
Use Code Interpreter to analyze data and create visualizations.
Always cite your sources and explain your methodology.""",
tools=[
FileSearchTool(),
CodeInterpreterTool()
]
)
print(f"Agent created: {agent.id}")
要与 agent 交互,我们创建一个 thread,也就是 conversation context,添加 message,并执行 run。下面的代码展示了完整 interaction cycle:
# Create a thread and send a message
thread = project.agents.threads.create()
message = project.agents.messages.create(
thread_id=thread.id,
role="user",
content="Analyze the patient readmission data and identify the top risk factors."
)
# Execute the agent
run = project.agents.runs.create_and_process(
thread_id=thread.id,
agent_id=agent.id
)
create_and_process method 会处理完整 execution lifecycle,包括 tool calls、polling 和 result assembly。在 production 中,对于 long-running operations,你通常会使用 create 加 manual polling 或 streaming,以获得更好的控制。下面的代码检索并显示 agent 的 response:
# Retrieve the response
if run.status == "completed":
messages = project.agents.messages.list(
thread_id=thread.id,
order=ListSortOrder.ASCENDING
)
for msg in messages:
if msg.role == "assistant":
for content in msg.content:
if isinstance(content, MessageTextContent):
print(content.text.value)
这个 pattern——initialize client、create agent with tools、create thread、send message、run agent、retrieve response——是本章所有示例的基础。后续每一节都会在这个基础 pattern 上添加新的 tool types。
下面的示例使用 healthcare data analysis scenario,说明 agent 如何在实践中利用 built-in tools。Agent 被授予 File Search 访问权限,用于检索 clinical documents,例如 readmission guidelines 和 care protocols;同时授予 Code Interpreter 访问权限,用于对检索到的数据运行 Python analysis。Clinician-side query,例如 “Analyze the patient readmission data and identify the top risk factors”,会触发 agent 先搜索 indexed clinical documents,然后运行 statistical analysis,最后返回一个 grounded、cited summary。图 8.1 展示了该流程中 agent 的 console output。
图 8.1:Agent with tools responding to a healthcare data analysis query
如图 8.1 所示,agent 自主选择了合适的 built-in tools,按顺序执行它们,并生成一个带 citations 的 grounded response。看过端到端 pattern 后,我们现在逐个讲解 built-in tools,先从 File Search 开始。
Working with Built-in tools
Azure AI Foundry Agent Service 提供多个 built-in tools,不需要 external infrastructure。这些 tools 完全由 platform 管理,是从 development 走向 production 的最快路径。本节将覆盖四个 built-in tools:用于 document retrieval 的 File Search、用于 data analysis 和 code execution 的 Code Interpreter、用于 real-time web information 的 Bing Grounding,以及用于基于现有 indexes 执行 enterprise-grade search 的 Azure AI Search。
File Search
File Search 使 agents 能够使用 semantic search 从 uploaded documents 中检索信息。当你将 files 上传到 vector store 后,Azure AI Foundry 会自动 chunk 内容、生成 embeddings,并让这些 documents 可被 agent 搜索。这是让 agent grounding 到组织 proprietary knowledge 中的最简单方法,而无需构建单独的 Retrieval Augmented Generation(RAG)pipeline。
File Search 实际上是一个 managed RAG pipeline:它执行传统 RAG stack 中需要你自己实现的同样概念步骤,包括 chunking、embedding、vector storage 和 similarity retrieval。传统上,你会使用 Azure AI Search、embedding model 和 custom orchestration code 来实现这些流程。区别在于,使用 File Search 时,Azure AI Foundry 会透明处理 indexing、retrieval 和 prompt augmentation,你只需要提供 documents,agent 负责其余工作。
当你需要为 bounded document set 快速构建一个 managed retrieval layer 时,使用 File Search。当你需要 enterprise-scale indexing、hybrid search,或对 ranking 和 filtering 进行严格控制时,则应选择本章后面会覆盖的 Azure AI Search。
在 healthcare scenarios 中,File Search 特别有价值,因为 agents 需要引用 clinical guidelines、drug interaction databases、formulary documents 或 standard operating procedures。下面的代码展示如何创建 vector store、上传 documents,并将其绑定到 agent:
# Create a vector store for clinical documents
vector_store = project.agents.vector_stores.create(
name="clinical-guidelines"
)
# Upload files to the vector store
file = project.agents.files.upload(
file_path="./data/clinical_guidelines.pdf",
purpose="agents"
)
# Add file to vector store
project.agents.vector_stores.file_batches.create(
vector_store_id=vector_store.id,
file_ids=[file.id]
)
Vector store 填充完成后,我们可以创建一个使用 File Search 的 agent,用 uploaded documents 作为 grounding 来回答问题:
# Create agent with File Search pointing to the vector store
agent = project.agents.create_agent(
model="gpt-4o",
name="clinical-guideline-agent",
instructions="""You are a clinical guidelines specialist.
Answer questions by searching the uploaded clinical guidelines.
Always cite the specific guideline section in your response.
If information is not found in the guidelines, say so clearly.""",
tools=[FileSearchTool()],
tool_resources={
"file_search": {
"vector_store_ids": [vector_store.id]
}
}
)
print(f"Agent created with File Search: {agent.id}")
这里的关键设计决策有两个。第一,vector store 与 agent 分开创建,使多个 agents 可以共享同一 knowledge base。第二,instructions 明确要求 agent 引用 guideline sections,这会提升 response traceability。在 healthcare applications 中,这一点非常关键,因为 clinicians 需要根据 authoritative sources 验证 AI recommendations。
图 8.2:File Search agent returning clinical guideline results with citations
我们已经看到 File Search 如何帮助 agent grounding 到相关 documents 中。接下来,我们探索另一个 built-in tool:Code Interpreter。
Code Interpreter
Code Interpreter 为 agents 提供一个 sandboxed Python execution environment,使其能够编写并运行代码、处理 files、生成 charts,并执行 data analysis。该 sandbox 在 conversation thread 内隔离且有状态,这意味着 variables 和 files 会在同一 thread 的多个 interactions 中保持存在。
对于 healthcare analytics,Code Interpreter 特别适合处理 patient cohort data analysis、生成 statistical summaries、创建 treatment outcomes visualizations,或处理 structured data files。下面的代码创建一个可以分析 uploaded CSV data 的 agent:
# Upload a data file for analysis
data_file = project.agents.files.upload(
file_path="./data/patient_readmissions.csv",
purpose="agents"
)
# Create agent with Code Interpreter
analyst_agent = project.agents.create_agent(
model="gpt-4o",
name="readmission-analyst",
instructions="""You are a healthcare data analyst specializing
in patient readmission analysis. When given data:
1. Load and explore the dataset
2. Identify key patterns and risk factors
3. Create clear visualizations
4. Provide actionable recommendations
Use statistical methods appropriate for healthcare data.""",
tools=[CodeInterpreterTool()],
tool_resources={
"code_interpreter": {
"file_ids": [data_file.id]
}
}
)
当 agent 收到关于数据的问题时,它会自主编写 Python code 来加载 CSV、执行 analysis,并生成 charts。生成的代码会在 secure sandbox 中运行,可访问常见 data science libraries,包括 pandas、numpy、matplotlib 和 scikit-learn。
Code Interpreter 在 Azure 管理的 sandboxed environment 中执行代码。虽然这提供了 security isolation,但也意味着 sandbox 没有 network access,不能调用 external APIs。如果你的 agent 需要将 data analysis 与 external data retrieval 结合,应将 Code Interpreter 与其他 tools 结合,例如 Azure AI Search 或 OpenAPI tools。
Grounding with Bing Search
Bing Grounding tool 通过 Bing Search 让 agents 能够访问 real-time web information。当 agents 需要当前信息,而这些信息不在 uploaded documents 或 internal knowledge bases 中时,这很有价值。例如,查找 FDA 最新 drug safety alerts、检查当前 hospital capacity metrics,或检索 recent clinical trial results。下面的代码创建一个 Bing connection,并将其绑定到 agent:
from azure.ai.agents.models import BingGroundingTool
# Create a Bing Grounding connection in your Foundry project first
# (done via portal: Settings > Connections > + Connection > Bing Search)
bing_tool = BingGroundingTool(
connection_id="<your-bing-connection-id>"
)
agent = project.agents.create_agent(
model="gpt-4o",
name="medical-research-agent",
instructions="""You are a medical research assistant.
Use Bing Search to find the latest clinical research,
drug safety alerts, and medical news.
Always cite your sources with URLs.
Prioritize peer-reviewed sources and official health authorities.""",
tools=[bing_tool]
)
为了让这个场景更具体,考虑一个 clinical decision support scenario:pharmacist 向 agent 提问:“Has there been any new FDA guidance on metformin contraindications, and does our formulary reflect the latest recommendations?” Agent 会使用 File Search 查询 internal formulary documents 中当前的 metformin entry,然后使用 Bing Grounding 检索最新 FDA drug safety communications,最后组合答案,指出 internal policy 和 external guidance 之间是否存在 gaps。下面的代码展示如何将这两个 tools 绑定到单一 agent:
# Create a clinical decision support agent with both tools
clinical_agent = project.agents.create_agent(
model="gpt-4o",
name="clinical-decision-support",
instructions="""You are a clinical decision support assistant.
For medication questions:
1. Use File Search to retrieve the internal formulary entry.
2. Use Bing Grounding to check for recent FDA safety communications.
3. Compare internal policy against external guidance and flag discrepancies.
Always cite both internal and external sources.""",
tools=[
FileSearchTool(vector_store_ids=[vector_store.id]),
BingGroundingTool(connection_id=bing_connection_id),
]
)
两个 tools 注册后,agent 会根据每个 query 自主判断是否查询 internal documents、external web sources,或两者都查询。这种 dual-grounding pattern 对 healthcare use cases 特别有价值,因为 internal policy 必须与快速变化的 external guidance 对齐。
当 agent 判断 user query 需要超出其 training data 的当前信息时,它会自动调用 Bing Search。在 production healthcare applications 中,可以将 Bing Grounding 与 File Search 结合,创建同时引用 internal clinical guidelines 和 external medical literature 的 agents,从而提供全面且最新的 responses。例如,一个 clinical decision support agent 可以通过 File Search 检查 internal formulary documents,同时通过 Bing 验证最新 FDA safety alerts。
Azure AI Search Tool
Azure AI Search 提供 enterprise-grade search capabilities,包括 hybrid search,即结合 vector 和 keyword search;semantic ranking;custom scoring profiles;以及与 existing search indexes 的集成。相比之下,File Search 提供快速方式,让 agents grounding 到 documents 中。
关键区别在于 scale 和 control:Azure AI Search 支持数百万 documents,并提供 fine-grained relevance tuning;而 File Search 更适合用少量 documents 进行 quick prototyping。如果你的组织已经使用 Azure AI Search 作为 knowledge base 或 document repository,那么 Azure AI Search tool 可以将 agent 直接连接到该 index。
下面的代码展示了如何创建 Azure AI Search tool,并将其配置为对 clinical knowledge base 执行 semantic search:
from azure.ai.agents.models import (
AzureAISearchTool,
AzureAISearchQueryType
)
# Create Azure AI Search tool connected to your index
search_tool = AzureAISearchTool(
index_connection_id="<your-search-connection-id>",
index_name="clinical-knowledge-base",
query_type=AzureAISearchQueryType.SEMANTIC,
top_k=5
)
agent = project.agents.create_agent(
model="gpt-4o",
name="clinical-knowledge-agent",
instructions="""You are a clinical knowledge specialist.
Search the clinical knowledge base to answer questions.
Use semantic search to find the most relevant information.
Always provide citations from the search results.""",
tools=[search_tool]
)
query_type parameter 非常重要:Semantic 使用 AI-powered ranking 返回最相关 results;Vector 使用 embedding similarity;Hybrid 则结合两种方法。对于包含 specialized terminology 的 clinical knowledge bases,semantic search 通常提供最佳结果,因为它能理解超越简单 keyword matching 的 medical context。
现在我们已经覆盖 built-in tools:File Search 用于 document grounding,Code Interpreter 用于 data analysis,Bing Grounding 用于 real-time web information,Azure AI Search 用于 enterprise-grade retrieval。下一节将探索如何使用 OpenAPI specifications 将 agents 连接到组织的 custom APIs。这一转变会使 agents 从 information retrieval 进入对 external systems 的 action-taking。
Integrating custom APIs with OpenAPI specification tools
Built-in tools 覆盖了常见 patterns,但 production agents 通常需要与 organization-specific systems 交互,例如 Electronic Health Record(EHR)APIs、claims processing systems、inventory management platforms 或 custom microservices。OpenAPI Specification tool 通过允许你将任何带 OpenAPI,也就是以前称为 Swagger,specification 的 API 暴露为 agent 可调用 tool,实现与 external systems 的集成。本节中,我们将通过 healthcare appointment scheduling 示例,逐步定义 OpenAPI specification、从中创建 tool,并将其连接到 agent。
这种方式非常强大,因为大多数现代 enterprise APIs 已经有 OpenAPI specifications。你不需要编写 custom integration code,只需要将 agent 指向现有 specification,agent 就能自动学习 available endpoints、parameters 和 response formats。
在将 OpenAPI tools 构建进 production agents 之前,有几个 prerequisites 和 limitations 值得注意。Specification 必须是有效的 OpenAPI 3.0 或更高版本,并且你希望 agent 调用的每个 endpoint,都需要准确的 descriptions 和 parameter schemas。Agent 会依赖这些 metadata 决定何时以及如何调用每个 endpoint。Authentication 支持 anonymous endpoints、API keys 和 managed-identity scenarios;带 user-delegated consent 的 OAuth flows 需要通过 Azure API Management 做额外配置。最后,OpenAPI tool calls 会在 agent run 中同步运行,因此 long-running endpoints 应该 streaming results,或包装为 async pattern,本章后面的 Azure Functions section 会覆盖。
Creating an OpenAPI tool
下面示例展示如何创建一个可以与 healthcare appointment scheduling API 交互的 agent。我们首先定义描述 API endpoints 的 OpenAPI specification。在这个案例中,一个 endpoint 用于检查 available slots,另一个用于 booking appointments:
import json
from azure.ai.agents.models import OpenApiTool, OpenApiAnonymousAuthDetails
# Define the OpenAPI spec for a healthcare scheduling API
scheduling_spec = {
"openapi": "3.0.0",
"info": {
"title": "Healthcare Scheduling API",
"version": "1.0.0",
"description": "API for managing patient appointments"
},
"servers": [
{"url": "https://api.healthcare-demo.com/v1"}
],
"paths": {
"/appointments/available": {
"get": {
"operationId": "getAvailableSlots",
"summary": "Get available appointment slots",
"parameters": [
{
"name": "department",
"in": "query",
"required": True,
"schema": {"type": "string"},
"description": "Department name (e.g., cardiology)"
},
{
"name": "date",
"in": "query",
"required": True,
"schema": {"type": "string", "format": "date"},
"description": "Date to check (YYYY-MM-DD)"
}
],
"responses": {
"200": {
"description": "List of available slots"
}
}
}
}
}
}
这定义了 API 的结构。上面的 specification 为了让 integration pattern 更清晰,刻意压缩为单个 endpoint。Production OpenAPI document 通常会包含数十个 endpoints,以及 shared schemas、security definitions 和 server URLs。当构建自己的 OpenAPI tool 时,可以将 agent 指向完整 specification,无论是 inline 还是通过 URL;这里展示的 pattern 完全相同,只是 JSON 更大。现在我们创建 tool,并绑定到 agent:
# Create the OpenAPI tool
openapi_tool = OpenApiTool(
name="scheduling_api",
description="Healthcare appointment scheduling system",
spec=json.dumps(scheduling_spec),
auth=OpenApiAnonymousAuthDetails()
)
# Create agent with the OpenAPI tool
scheduling_agent = project.agents.create_agent(
model="gpt-4o",
name="appointment-scheduler",
instructions="""You are a healthcare appointment scheduling assistant.
Help patients find and book appointments using the scheduling API.
Always confirm the department, date preference, and reason for visit
before searching for available slots.
Present available slots clearly with time and provider information.
Confirm all details before booking an appointment.""",
tools=openapi_tool.definitions
)
print(f"Scheduling agent created: {scheduling_agent.id}")
Agent 的 instructions 明确告诉 model 哪些 API operations 可用,以及何时使用每个 operation:在 booking 前检查 availability,确认 slot 是 open 的,并始终在 response 中包含 confirmation reference。如果没有这些 instructions,model 可能会直接尝试 booking,而不先检查 availability,或返回结果但不引用 reference number。Agent 配置完成后,我们创建 thread、发送 scheduling request,并运行 agent:
OpenApiTool 会包装 JSON specification 和 authentication configuration。在这里使用 anonymous,因为 demo API 没有 auth layer。Production 中应将 OpenApiAnonymousAuthDetails 替换为 managed-identity 或 API-key-based auth object,供 agent runtime 在向 target endpoint 派发 tool calls 时使用。Tool 定义完成后,我们现在可以创建一个使用它来查询和预约 appointments 的 agent。
Agent 现在理解 API 的 capabilities:它知道如何搜索 available slots 和 book appointments。当 patient 说 “I need to see a cardiologist next Tuesday” 时,agent 会自主使用合适的 department 和 date parameters 调用 getAvailableSlots endpoint,展示结果,并在 patient 确认后使用 bookAppointment endpoint。
图 8.3:OpenAPI tool agent showing available cardiology appointment slots
重要说明:对于 production deployments,请用 proper authentication 替换 OpenApiAnonymousAuthDetails()。Azure AI Foundry 支持 Managed Identity authentication(OpenApiManagedAuthDetails)和 connection-based authentication,以实现安全 API access。Anonymous authentication 只应在 development 和 testing 中使用。
借助 OpenAPI tools,你可以将 agents 连接到任何拥有 documented API specification 的 system。不过,许多 third-party platforms 和 developer tools 现在支持一种更新、更动态的 tool integration 方法,称为 Model Context Protocol(MCP)。下一节将探索 MCP 如何通过 auto-discovery 和 standardized communication,将 tool integration 推进一步。
Connecting to external systems with MCP
Model Context Protocol(MCP)提供一种标准化方式,将 agents 连接到任何 MCP-compatible service,包括 third-party platforms、developer tools 和 data sources,而无需编写 custom integration code。OpenAPI tools 适合你控制并能定义 specifications 的 APIs;而理解 MCP 很重要,因为它代表 agent-tool integration 的未来方向。Azure AI Foundry 包含 first-class McpTool class,因此将 agent 连接到 MCP server 只需要 server URL、authentication header 和 permitted tools allow-list,不需要 custom middleware、proxy service 或 protocol translation code。
本节中,我们将解释什么是 MCP,演示如何将 agent 连接到 GitHub MCP server,并介绍 MCP tool calls 所需的 human-in-the-loop approval pattern。
MCP 最初由 Anthropic 提出,现在已在行业内广泛采用。它使用基于 JSON-RPC 的 protocol,即一种使用 JSON messages 的轻量 remote procedure call format,支持 tool auto-discovery。不同于 OpenAPI 中需要手动定义每个 tool 的 parameters 和 endpoints,MCP servers 会动态暴露自己的 capabilities。你的 agent 连接到 MCP server 后,会自动了解有哪些 tools 可用、它们的 parameters,以及如何调用它们。
Azure AI Foundry Agent Service 支持 remote MCP servers,截至 2026 年初,Foundry tool catalog 提供越来越多预配置 MCP integrations,包括 Azure DevOps、GitHub 和其他 enterprise services。
相比构建 bespoke OpenAPI tool,MCP 的实际好处是 auto-discovery 和 portability。MCP server 会发布自己的 tool catalog,所以 agent 会在 connection time 学习 available operations,而不需要你维护静态 specification。当 target system 已经有或很可能会有 MCP server 时,例如 GitHub、Azure DevOps、Notion、Slack 和许多其他平台现在都有 official MCP servers,或者当你希望单一 connection 暴露多个 related tools 时,应优先使用 MCP。当你拥有该 API、需要对 individual endpoint descriptions 做细粒度控制,或 target system 尚未支持 MCP 时,则使用 OpenAPI。
Creating an Agent with MCP tools
下面的代码演示如何将 agent 连接到 GitHub MCP server,使其能够与 repositories、issues 和 pull requests 交互:
from azure.ai.agents.models import McpTool
# Create an MCP tool connecting to GitHub
github_mcp = McpTool(
server_label="github-server",
server_url="https://mcp.github.com/sse",
headers={
"Authorization": "Bearer <your-github-token>"
},
allowed_tools=[
{"name": "get_repository"},
{"name": "list_issues"},
{"name": "create_issue"},
{"name": "get_pull_request"}
]
)
# Create agent with MCP tool
devops_agent = project.agents.create_agent(
model="gpt-4o",
name="devops-assistant",
instructions="""You are a DevOps assistant that helps manage
GitHub repositories. You can:
- Look up repository information and READMEs
- List and search issues
- Create new issues with proper labels
- Review pull request details
Always confirm before creating or modifying any resources.""",
tools=[github_mcp]
)
print(f"DevOps agent created: {devops_agent.id}")
allowed_tools parameter 对 security 非常关键:它限制 agent 可以访问 MCP server 上的哪些 tools。Production 中必须始终遵循 principle of least privilege,只启用 agent 需要的特定 tools。
如果 allowed_tools 被省略或不加限制,agent 会继承 MCP server 暴露的每一项 capability。对于 GitHub 这类 server,这可能包括 repository deletion、force-pushing to protected branches,或 rotating organization secrets。Prompt-injection attack 或过度积极的 model response 可能触发从未打算纳入 agent scope 的破坏性 operations。因此,应将 allowed_tools list 视为 capability manifest,像 review IAM policies 一样进行 review,只有当新 tools 已在 non-production environment 中评估之后,才扩大范围。
Handling MCP tool approvals
MCP tool calls 默认需要 explicit approval,从而提供 human-in-the-loop oversight。当 agent 决定调用 MCP tool 时,run 会进入 requires_action state,需要你的 application 在 execution 继续前 approve 或 reject 该 tool call。在 enterprise environments 中,这一点尤其重要,因为对 external systems 的 automated actions 需要 governance。下面的代码演示 approval polling pattern。首先,我们创建 thread 并启动 run:
from azure.ai.agents.models import (
RequiredMcpToolCall,
SubmitToolApprovalAction,
ToolApproval
)
import time
# Create thread and run
thread = project.agents.threads.create()
project.agents.messages.create(
thread_id=thread.id,
role="user",
content="List the open issues in our healthcare-api repository"
)
run = project.agents.runs.create(
thread_id=thread.id,
agent_id=devops_agent.id
)
接下来,我们轮询 run status,并在 approval requests 到来时处理它们。当 run 需要 action 时,我们检查 tool call details,并提交 approval decision:
# Poll for status and handle approvals
while run.status in ["queued", "in_progress", "requires_action"]:
time.sleep(1)
run = project.agents.runs.get(
thread_id=thread.id,
run_id=run.id
)
if run.status == "requires_action":
tool_calls = run.required_action.submit_tool_outputs.tool_calls
approvals = []
for call in tool_calls:
if isinstance(call, RequiredMcpToolCall):
print(f"MCP approval requested:")
print(f" Server: {call.server_label}")
print(f" Tool: {call.tool_name}")
# Auto-approve read operations; require human review for writes
approvals.append(
ToolApproval(tool_call_id=call.id, approve=True)
)
run = project.agents.runs.submit_tool_outputs(
thread_id=thread.id,
run_id=run.id,
tool_outputs=approvals
)
print(f"Run completed with status: {run.status}")
这种 approval pattern 对 production deployments 至关重要。对于 healthcare 和 financial services applications,应实现能区分 read operations 与 write operations 的 approval logic。Read operations 可以 auto-approved,而 write operations 应要求 human review 或 policy-based approval。这既能确保 audit trails 和 governance compliance,也能让 agents 高效运行。
图 8.4:MCP tool approval flow and GitHub issue search results
MCP 提供标准化 external system integration,OpenAPI 处理 custom API connections,而 Azure Functions 则覆盖需要完全 custom business logic 的场景。Azure Functions 使你能够在 managed serverless environment 中构建 bespoke tool implementations。
在详细进入 Azure Functions 之前,值得先总结一下连接 tools 到 agents 时最常见的问题。下面的表格是一个快速诊断参考,每一行都将 symptom 与 likely cause 和 concrete fix 配对。在 debug 自己项目中的 tool-calling behavior 时,可以回到这张表。
Troubleshooting guide
| Issue | Likely cause | Resolution |
|---|---|---|
| Agent returns function call but no final answer. | Tool output not returned to the model. | Execute the function, then call responses.create with the tool output and previous_response_id to continue. |
| No function call occurs. | Function not in agent definition or poorly named. | Confirm the function tool is added to the agent. Use clear, descriptive names and parameter descriptions. |
| Arguments aren't valid JSON. | Schema mismatch or model generated incorrect information. | Verify JSON schema uses correct types and required properties. Handle parsing errors gracefully in your app. |
| Required fields are missing. | Schema doesn't enforce required properties. | Add a "required": [...] array to your parameter schema. Set strict: true for stricter validation. |
| Tool outputs fail due to expiration. | Run expired,10 minute limit. | Return tool outputs promptly. For slow operations, return a status and poll separately. |
| Function called with the wrong parameters. | Ambiguous function description. | Improve the function description field. Add detailed parameter descriptions with examples. |
| Multiple function calls in one response. | Model determined that multiple functions are needed. | Handle each function call in the output array. Return all results in a single responses.create call. |
| Function not visible in Foundry portal. | Portal doesn't execute function calls. | Test function calling via SDK or REST API. The portal shows agents but doesn't invoke functions. |
Using Azure functions for Stateful Agent Tools
OpenAPI 和 MCP tools 会将 agents 连接到现有 services,而 Azure Functions 则允许你构建 custom tool logic,这些 logic 运行在 fully managed serverless environment 中。本节将探索 Azure Functions 何时是正确的 tool choice,逐步定义一个带 healthcare drug interaction example 的 Azure Function tool,并解释连接 agent runtime 与 function code 的 asynchronous queue-based communication pattern。
当你需要 custom business logic,而这些 logic 并不存在为 standalone API;需要使用 Durable Entities 进行 stateful operations,也就是 Azure Durable Functions 的一项功能,用于跨 invocations 维护 persistent state;或者需要不太适合 REST API 或 MCP server 的 integration patterns 时,Azure Functions 就是正确选择。
对于 healthcare applications,Azure Functions 常用于 validating insurance eligibility、against formulary database 检查 drug interactions,或使用 proprietary algorithms 计算 risk scores。下面的代码定义了一个 Azure Function tool,用于检查 drug interactions:
from azure.ai.agents.models import AzureFunctionTool
# Define an Azure Function tool for drug interaction checking
drug_interaction_tool = AzureFunctionTool(
name="check_drug_interactions",
description="Check for potential drug interactions given a list of medications",
parameters={
"type": "object",
"properties": {
"medications": {
"type": "array",
"items": {"type": "string"},
"description": "List of medication names to check"
},
"patient_age": {
"type": "integer",
"description": "Patient age for age-specific warnings"
}
},
"required": ["medications"]
},
input_queue="drug-interaction-requests",
output_queue="drug-interaction-results",
function_name="DrugInteractionChecker",
function_app_resource_id="/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Web/sites/<function-app>"
)
# Create agent with the Azure Function tool
pharmacist_agent = project.agents.create_agent(
model="gpt-4o",
name="pharmacist-assistant",
instructions="""You are a clinical pharmacist assistant.
When a clinician provides a medication list, check for drug interactions.
Categorize interactions by severity: Critical, Major, Moderate, Minor.
Always recommend consulting a pharmacist for critical interactions.
Never provide dosing recommendations without explicit clinical context.""",
tools=[drug_interaction_tool]
)
AzureFunctionTool definition 命名了 Azure Function,也就是 DrugInteractionChecker,指向 Function App resource,并指定连接 agent 与 function 的两个 Storage Queues:input_queue 用于发送 medication list 和 patient context;output_queue 用于接收 interaction analysis。parameters schema 遵循 JSON Schema conventions,agent runtime 会在 dispatch 前根据该 schema 验证 model 的 tool-call arguments。Tool 定义完成后,我们创建一个使用它作为 pharmacist assistant 的 agent。
Azure Functions 通过 Azure Storage Queues 与 agent 通信:agent 将 tool inputs 发送到 input_queue,并从 output_queue 读取 results。这种 asynchronous pattern 非常适合可能需要几秒钟处理的 tools,例如复杂 database queries,或带 rate limiting 的 external API calls。
我们为 healthcare customers 交付过的具体示例包括:insurance eligibility check,会调用 payer 的 270 / 271 EDI endpoint,并等待最多 8 秒获得 response;drug-interaction lookup,会查询 First Databank 或 Lexicomp 等 clinical decision support service,并应用 enterprise rate-limit policies;longitudinal patient-record retrieval,会从 FHIR server 和 legacy data warehouse 汇聚 encounters,然后返回 unified timeline;以及 claims-history lookup,会通过 integration runtime 从 mainframe join 数据。每个例子都会使 synchronous tool 超过 agent 的默认 timeout,但 queue-based pattern 允许 function 以自己的节奏处理,同时让 agent run 保持 healthy。
与 OpenAPI tools 相比,其关键优势是你可以控制整个 execution environment,从而实现复杂 validation logic、访问 private databases,或集成没有 modern API specifications 的 legacy systems。
我们已经覆盖的每种 tool type 都服务于不同 integration needs:built-in tools 适合 common capabilities;OpenAPI 适合 documented APIs;MCP 适合 standardized third-party services;Azure Functions 适合 custom logic。下一种 tool type,也就是 Logic Apps,将 low-code workflow orchestration 引入这个图景,使 agents 能触发复杂 multi-step business processes。
Automating Enterprise Workflows with Logic Apps
Logic Apps integration 将 low-code workflow orchestration 引入 agent tool ecosystem。这非常适合涉及 approvals、notifications、system integrations 和 conditional logic 的 multi-step business processes。如果从零构建,这些流程需要大量 custom code。
举一个具体例子,考虑 healthcare prior authorization workflow:clinician 下单高成本 imaging procedure;Logic App 接收 agent 的 request;在 SharePoint 中查找 payer 的 medical necessity policy;调用 EHR 的 FHIR endpoint 汇总 patient clinical history;为 utilization-management nurse 打开 Microsoft Teams approval card;根据 approval decision 分支,或者向 payer 提交 278 EDI transaction,或者向 ordering provider 发送 denial-with-reason email;最后通过 Service Bus queue 将 outcome 写回 EHR。
如果直接用 Python 实现这一 orchestration,会把 authentication、retry logic、conditional branching 和 channel-specific notification code 混合进一个脆弱 module 中;用 Logic App 表达它,则能让每个 step 独立 observable,并且可由 integration analyst 而非 developer 编辑。你不需要手写这些 workflows,而是在 Logic Apps designer 中进行可视化设计,并将其暴露为 agent 可以触发的 tools。本节将演示如何将 agent 连接到 prior authorization workflow。
一个常见 healthcare use case 是自动化 prior authorization workflow:当 clinician 下单 procedure 时,agent 检查 eligibility、提交 authorization request、监控 approval status,并将 outcome 通知 care team。使用 Logic Apps tool 之前,需要先在 Foundry project 中创建 connection:进入 Settings > Connected resources > + Connection,选择 Logic Apps,并提供 Logic App 的 resource details。下面的代码将 agent 连接到这样的 workflow:
from azure.ai.agents.models import LogicAppTool
# Connect to a Logic Apps workflow for prior authorization
prior_auth_tool = LogicAppTool(
name="submit_prior_auth",
description="Submit a prior authorization request for a medical procedure",
logic_app_connection_id="<your-logic-app-connection-id>",
workflow_name="PriorAuthorizationWorkflow"
)
auth_agent = project.agents.create_agent(
model="gpt-4o",
name="prior-auth-agent",
instructions="""You are a prior authorization specialist.
When a clinician requests authorization for a procedure:
1. Verify the patient information and procedure details
2. Check if the procedure requires prior authorization
3. Submit the authorization request via the workflow tool
4. Provide the authorization reference number
5. Explain the expected timeline for approval
Always confirm all details before submitting.""",
tools=[prior_auth_tool]
)
Logic Apps 为 400 多个 services 提供 built-in connectors,包括 Dynamics 365、Salesforce、ServiceNow、SAP 和大多数 healthcare platforms。这使其成为将 agents 连接到没有 direct Azure AI Foundry tool support 的 enterprise systems 的最快方式。Logic App 处理 multi-step orchestration,例如 checking eligibility、submitting request、waiting for approval、sending notifications,而 agent 则处理与 clinician 的 natural language interaction。
现在五类 tools 都已经覆盖:built-in tools、OpenAPI、MCP、Azure Functions 和 Logic Apps。下一节将处理在 production agents 中组合这些 tools 时会遇到的 advanced patterns。
Advanced tool patterns
随着 agents 变得更复杂,你会遇到需要组合多个 tools、优雅处理 tool failures,并在规模化条件下治理 tool usage 的 patterns。本节覆盖三个关键 production patterns:multi-tool orchestration、error handling strategies,以及通过 AI Gateway 实现 centralized tool governance。
Combining multiple tools
Production agents 通常需要多个 tools 协同工作。Agent model 会自动处理 tool orchestration:你提供 tools 和 instructions,model 会根据每个 query 判断最佳 tool call sequence。下面的代码展示如何创建一个包含五个 tools 的 agent,并在 instructions 中明确 tool selection rules。
该示例假设前面 sections 中介绍的 tools 已定义并在 scope 中,包括 FileSearchTool、CodeInterpreterTool、search_tool,也就是 Azure AI Search tool、openapi_tool,也就是 scheduling OpenAPI tool,以及 bing_tool,也就是 Bing Grounding tool。在真实项目中,你可以将这些 definitions 放在同一 module 中,也可以从共享 tools package 中 import。
# Create a multi-tool healthcare agent
multi_tool_agent = project.agents.create_agent(
model="gpt-4o",
name="healthcare-copilot",
instructions="""You are a comprehensive healthcare copilot.
Available tools and when to use them:
- File Search: For clinical guidelines and internal documentation
- Code Interpreter: For data analysis and visualizations
- Azure AI Search: For searching the clinical knowledge base
- Scheduling API: For checking and booking appointments
- Bing Search: For latest medical research and drug alerts
Tool selection rules:
1. Start with internal sources (File Search, AI Search) before web search
2. Use Code Interpreter when quantitative analysis is needed
3. Always verify drug information against multiple sources
4. Confirm with the user before taking any booking actions""",
tools=[
FileSearchTool(),
CodeInterpreterTool(),
search_tool,
*openapi_tool.definitions,
bing_tool
],
tool_resources={
"file_search": {"vector_store_ids": [vector_store.id]},
"code_interpreter": {"file_ids": [data_file.id]}
}
)
Instructions 包含明确 tool selection rules,因为 model 需要关于 priority ordering 的指导。如果没有这些 rules,model 可能会用 Bing Search 回答本应从 internal clinical guidelines 中回答的问题,从而返回不够可靠的信息。这种 priority ordering,即 internal sources first、then external,是任何结合 knowledge retrieval tools 的 agent 的最佳实践。
Tool error handling
在 production 中,tools 可能失败:APIs 可能临时不可用,search indexes 可能返回空 results,function timeouts 也可能发生。稳健的 agents 需要优雅处理这些 failures。虽然 Agent Service 会自动处理很多 error scenarios,但你的 instructions 应引导 agent 在 tool 失败时如何响应。下面的代码展示了如何将 error handling guidance 直接嵌入 agent instructions:
error_handling_agent = project.agents.create_agent(
model="gpt-4o",
name="resilient-agent",
instructions="""You are a clinical decision support agent.
Error handling guidelines:
- If File Search returns no results, try Azure AI Search with broader terms
- If an API call fails, inform the user and suggest manual alternatives
- If Code Interpreter encounters a data error, describe the issue clearly
- Never fabricate information if tools return empty results
- If multiple tool failures occur, escalate to a human operator
Always be transparent about tool limitations and failures.""",
tools=[FileSearchTool(), search_tool, CodeInterpreterTool()]
)
关键原则是 transparency:当 tool 返回 no results 时,agents 绝不应 silent fail 或 fabricate information。在 healthcare applications 中,这一点尤其关键,因为 fabricated clinical information 可能导致有害决策。通过将 fallback strategies 直接嵌入 instructions,你可以创建优雅降级的 agents,而不是灾难性失败的 agents。
Tool governance with AI gateway
对于跨 teams 管理多个 agents 的 enterprise deployments,Azure AI Foundry 通过 AI Gateway 提供 centralized tool governance,AI Gateway 可在 Azure AI Foundry 中使用。AI Gateway 是一个 policy enforcement layer,位于 agents 与其 tools 之间,会拦截每次 tool call,并在 call 到达 external system 之前应用 organizational policies。这类似于传统 microservices architectures 中的 API gateway,但专门为 agent tool calls 设计。
核心 governance capabilities 包括:根据 project 或 team policies 控制每个 agent 可以访问哪些 tools;执行 rate limits,以防止过度 API usage;记录所有 tool interactions,以满足 audit 和 compliance requirements;以及对 tool inputs 和 outputs 应用 content safety filters。例如,一个 healthcare organization 可以配置 AI Gateway,确保没有 agent 能将 patient identifiable information(PII)传给 external APIs,除非 destination 在 approved endpoint list 中。这在 regulated industries 中尤其重要,因为 tool interactions 可能受 HIPAA 或类似 audit requirements 约束。
现在,我们已经覆盖完整范围的 agent tools,从 built-in capabilities 到 custom integrations 和 governance。接下来通过两个端到端 case studies,将所有内容组合起来,展示这些 tools 如何在真实 healthcare 和 enterprise scenarios 中协同工作。
Case studies: Healthcare prior authorization agent and healthcare IT help desk agent
下面两个 case studies 展示本章中的 tool patterns 如何在 production 中组合使用。Case Study 1 构建一个 healthcare prior authorization agent,将 Azure AI Search、Logic Apps workflow 和 Code Interpreter 组合起来,自动化一个传统上每次 request 需要 45 分钟的流程。更完整的 production deployment 还会接入 OpenAPI 或 Azure Function tool,用于 EHR clinical-history retrieval,但为了简洁,这里不列出。Case Study 2 构建一个 enterprise IT help desk agent,它使用 MCP tools 集成 GitHub 和 Azure DevOps,同时结合 Azure AI Search。二者共同展示,在不同 regulatory 和 integration constraints 下,tool selection、governance 和 instruction design 如何变化。
Case study 1:Healthcare prior authorization agent
Prior authorization 是 healthcare 中最耗时的 administrative processes 之一,要求 clinicians 和 staff 验证 insurance coverage、检查 medical necessity criteria、提交 documentation,并跨多个 systems 跟踪 approval status。这个 case study 展示如何使用多个 tools 构建一个自动化该 workflow 的 agent。我们将依次走过 problem definition、model selection rationale、code implementation、evaluation methodology 和 key takeaways。
Problem and requirements
一家区域 healthcare network 每天处理 500+ prior authorization requests,希望将平均处理时间从每次 request 45 分钟降至 10 分钟以内。Solution 要求在判断 authorization requirements 时达到高准确率,超过 95%;需要与现有 EHR system 和 payer APIs 集成;并具备完整 audit trail capability,以满足 regulatory compliance。该组织希望 system 同时处理 straightforward authorizations,也就是 auto-process,以及 complex cases,也就是带 supporting documentation 路由给 specialists。
Prior authorization 中 audit trails 很重要,原因有两个具体方面。第一,payer contracts 和 regulators,包括 state insurance commissioners,以及对 Medicare Advantage plans 来说的 CMS,要求任何 adverse determination 都必须由 documented clinical rationale 支撑,并引用所查阅的具体 policy sections。如果没有持久记录哪些 tools 使用了哪些 inputs,就无法在 appeal 时为 denial 辩护。第二,downstream safety reviews 依赖于能够重建 agent 在做 recommendation 前看到的确切 evidence。如果后续发现 harmful outcome 来自 stale 或 missing policy data,audit log 就是 root-cause analysis 的关键。
Model selection
选择 GPT-4o,是因为它拥有强 tool-calling capabilities,并且能够遵循复杂 multi-step instructions。128K context window 可以容纳冗长 clinical documentation,而 model 的 structured output support 可以确保与 downstream APIs 交互时保持一致 data formatting。GPT-4o-mini 曾被考虑用于 cost optimization,但在测试中没有达到 medical necessity determinations 所需的 accuracy threshold。
Tool-calling 是让这个 workflow 可行的核心能力。Prior authorization request 至少触及四个不同 systems of record:payer 的 medical policy index、patient clinical history 所在的 EHR、向 payer 传输 request 的 submission endpoint,以及用于查看类似 CPT codes 历史 approval patterns 的 analytics layer。没有 tool-calling,每个 lookup 都必须由脆弱 deterministic code 在 model 外部 orchestrate;有了 tool-calling,model 可以根据它阅读 clinical documentation 时发现的内容,conditional decide 应查询哪些 sources。正是这种 adaptive orchestration,将 45 分钟的人工流程压缩为 10 分钟以内的 automated resolution。
Implementation
该 agent 使用三个 tools:Azure AI Search 用于 medical necessity criteria 和 payer policies;Logic Apps workflow 用于 authorization submission process;Code Interpreter 用于分析 historical approval patterns。在更完整的 production deployment 中,你还会接入 OpenAPI 或 Azure Function tool,用于 EHR clinical-history retrieval。这里为了简洁省略,但与本章前面 scheduling OpenAPI tool 的 pattern 相同。下面的代码创建 agent,并在 instructions 中定义结构化五步 workflow。每一步都映射到 prior authorization process 中的一个具体阶段:
# Tool 1: Azure AI Search for medical necessity criteria (policy_search defined earlier)
# Tool 2: Code Interpreter for historical approval pattern analysis
# Tool 3: Logic Apps for authorization submission (prior_auth_tool defined earlier)
Agent 的 instructions 编码完整 prior authorization workflow,包括何时 auto-submit、何时 escalate 的 decision points。CPT(Current Procedural Terminology)和 HCPCS(Healthcare Common Procedure Coding System)是用于识别 medical procedures 的标准化 codes,而 ICD-10(International Classification of Diseases, 10th Revision)codes 用于识别 diagnoses:
# Create the prior authorization agent
prior_auth_agent = project.agents.create_agent(
model="gpt-4o",
name="prior-auth-specialist",
instructions="""You are a prior authorization specialist agent.
WORKFLOW:
Step 1: Extract patient ID, insurance plan, procedure code
(CPT/HCPCS), clinical indication, and diagnosis (ICD-10).
Step 2: Search payer policies to determine if prior auth is
required and what medical necessity criteria must be met.
Step 3: Compare clinical indication against payer criteria.
Identify missing documentation and flag potential issues.
Step 4: If criteria are met, submit authorization via workflow
tool. Provide reference number and expected timeline.
Step 5: If criteria are NOT met, list specific deficiencies
and suggest additional documentation needed.
RULES:
- Always verify patient eligibility before proceeding
- Never auto-submit if medical necessity is unclear
- Maintain a complete audit trail of all decisions
- Cite specific policy sections in your determinations""",
tools=[policy_search, CodeInterpreterTool(), prior_auth_tool]
)
这种 instruction detail 对 healthcare applications 至关重要,因为错误可能延误 patient care。每一步都有清晰 decision criteria,rules section 则为 edge cases 建立 guardrails。
图 8.5:Prior authorization agent processing a multi-step workflow with audit trail
Evaluation and results
该 agent 使用 200 个已知 outcomes 的 historical prior authorization cases 进行评估,并通过 custom evaluation pipeline 将 agent decisions 与 human specialist determinations 对比。Evaluation 衡量四个维度:agent 是否正确识别何时需要 authorization;其 medical necessity assessment 是否与 specialist judgment 匹配;end-to-end processing time;以及 documentation checks 的 completeness。
以下结果为说明性结果,代表类似 production deployments 中常见 performance ranges:
- Authorization requirement detection:97% accuracy。
- Medical necessity assessment:与 specialist review 的一致率为 94%。
- Average processing time:7 分钟,原来是 45 分钟。
- Documentation completeness check:96% 的 missing documents 被正确识别。
Semantic search 用于 policy lookup、structured API integration 用于 EHR data、workflow automation 用于 submission,这三者结合形成了一个端到端 solution,可以在没有 human intervention 的情况下处理大多数 authorization requests。
关键结论:Healthcare prior authorization automation 需要多个 tools 协同工作。Agent 的价值不是来自某个单一 tool,而是来自它能将 policy lookup、eligibility verification、medical necessity determination 和 workflow submission orchestrate 成一个 coherent、auditable process。刚开始进行 prior authorization automation 的组织,应先从 policy search 和 medical necessity determination 开始,随后随着对系统信心增强,再逐步添加 EHR integration 和 workflow submission。
Case study 2:Enterprise IT help desk with MCP integration
这个 case study 展示 MCP tools 如何支持与现有 enterprise systems 快速集成。在本例中,我们构建一个 IT helpdesk agent,使其能够与 GitHub 交互进行 issue tracking,并与 Azure DevOps 交互进行 work item management。我们将覆盖 problem definition、model selection、implementation、evaluation 和 key takeaways。
Problem and requirements
一家 healthcare technology company 的 IT support team 每天需要处理 200+ tickets,这些 tickets 分布在 GitHub 上的 open-source projects 和 Azure DevOps 上的 internal systems 中。Support engineers 会花大量时间在不同 platforms 之间切换,以收集 diagnostic information。目标是创建一个 unified agent,可以跨两个 systems 搜索、收集 relevant context,并自动化 routine ticket actions,同时在 public 和 internal systems 之间保持严格 data separation。
Model selection
选择 GPT-4o,是因为它具备更强 tool-calling accuracy,并能管理复杂 multi-tool workflows。Model 强大的 instruction-following capability 对执行 data separation rules 至关重要,即确保 internal system details 永远不会泄露到 public GitHub issues 中。GPT-4o-mini 作为 secondary model 用于 simple ticket classification,通过 model cascading 优化成本。
Implementation
该架构选择 MCP 而不是 OpenAPI,是因为 GitHub 和 Azure DevOps 都提供官方维护的 MCP servers。如果使用 OpenAPI 构建等价集成,就需要编写并维护两个独立 specifications,每个大约 40 个 endpoints;还要实现它们的 authentication flows,并在 GitHub 或 Microsoft 发布 API changes 时更新 specs。使用 MCP 时,agent 会在 connection time 自动发现 available operations,API evolution 则由 upstream maintainers 负责,而不是由我们负责。
对于我们完全拥有的 purely internal API,OpenAPI 仍然是正确选择。但对于与两个快速演进的 third-party platforms 集成,MCP 的 auto-discovery 和 standardized protocol 显著降低了 integration surface。
Agent 使用两个 MCP servers,即 GitHub 和 Azure DevOps,再加上 Azure AI Search 用于 internal knowledge base。下面代码首先定义 MCP tool connections:
from azure.ai.agents.models import McpTool, AzureAISearchTool
# MCP Tool 1: GitHub integration
github_mcp = McpTool(
server_label="github",
server_url="https://mcp.github.com/sse",
headers={"Authorization": "Bearer <github-token>"},
allowed_tools=[
{"name": "list_issues"},
{"name": "get_issue"},
{"name": "create_issue"},
{"name": "search_code"}
]
)
# MCP Tool 2: Azure DevOps integration
devops_mcp = McpTool(
server_label="azure-devops",
server_url="https://mcp.dev.azure.com/sse",
headers={"Authorization": "Bearer <devops-token>"},
allowed_tools=[
{"name": "list_work_items"},
{"name": "get_work_item"},
{"name": "create_work_item"},
{"name": "search_wiki"}
]
)
两个 MCP connections 定义完成后,agent 可以通过相同 standardized protocol 与 GitHub 和 Azure DevOps 交互。最后一块是用于 internal troubleshooting guides 的 knowledge-based search tool。我们使用 Azure AI Search 实现它,而不是 MCP,因为 internal index 并没有暴露为 MCP server。
GitHub MCP tool 通过一个 connection 暴露四个 operations:list issues、get issues、create issues 和 code search。allowed_tools list 将 agent 限制在这四个操作上。GitHub MCP server 会暴露更多 capabilities,例如 repository management、pull requests、releases,但 helpdesk agent 没有业务理由访问它们。接下来,我们为 Azure DevOps 定义等价 connection。
接下来,我们创建 helpdesk agent,绑定三个 tools,并定义一个 structured workflow,用于分类 issues 并将它们路由到合适 platform:
# Knowledge base for troubleshooting guides
kb_search = AzureAISearchTool(
index_connection_id="<search-connection-id>",
index_name="it-knowledge-base",
query_type=AzureAISearchQueryType.SEMANTIC,
top_k=5
)
# Create unified IT helpdesk agent
helpdesk_agent = project.agents.create_agent(
model="gpt-4o",
name="it-helpdesk",
instructions="""You are an IT helpdesk agent.
WORKFLOW:
1. Classify the issue and route appropriately:
- Open-source project → search GitHub first
- Internal system → search Azure DevOps first
- General IT → search knowledge base first
2. Search for existing related issues before creating new ones
3. Provide troubleshooting steps from the knowledge base
4. If unresolved, create a properly categorized ticket
RULES:
- Never expose internal system details in GitHub issues
- Classify severity: P1 (system down), P2 (degraded), P3 (minor)
- For P1 issues, immediately create a work item AND notify
- Always search before creating to avoid duplicate tickets""",
tools=[github_mcp, devops_mcp, kb_search]
)
这个实现展示了 MCP 在快速 multi-platform integration 中的力量。如果没有 MCP,要连接 GitHub 和 Azure DevOps,就需要分别构建 OpenAPI specifications、管理 authentication flows,并为每个平台维护 API version compatibility。使用 MCP 后,两个 integrations 都使用相同 standardized protocol,而且 tool capabilities 会从 servers 自动发现。
图 8.6:IT helpdesk agent searching across GitHub, Azure DevOps, and knowledge base
该实现展示了 MCP 的 standardized protocol 如何将原本三个独立 integration projects,即 GitHub、Azure DevOps 和 internal search,压缩成一个 coherent agent;同时也展示了 Azure AI Search 如何为 MCP servers 无法覆盖的 internal knowledge sources 提供 enterprise-grade retrieval layer。
Evaluation and results
该 agent 在四周 pilot 中与 IT support team 一起评估,时间为 2026 年初,衡量 ticket resolution time、duplicate ticket reduction、first-contact resolution rate 和 engineer context-switching frequency。Metrics 通过 Azure Monitor dashboards 收集,并与 deployment 前四周 baseline period 进行对比。
部署后,IT helpdesk agent 达成了以下 outcomes,这些 outcomes 为说明性结果,基于类似 deployments 中观察到的典型 patterns:
- Average ticket resolution time 显著降低。
- Duplicate ticket creation 因 automated search-before-create 而下降。
- First-contact resolution rate 因 knowledge base integration 得到提升。
- Support engineer context-switching 消除了不必要的 routine queries。
关键结论:MCP integration 显著降低了将 agents 连接到多个 enterprise platforms 所需的 engineering effort。标准化 protocol 意味着你可以通过连接额外 MCP servers 来添加新的 system integrations,而无需修改 agent core logic。对于评估 MCP adoption 的 teams,应从 read-only integrations 开始,例如 searching 和 retrieving data,以建立信心,然后在具备合适 approval workflows 后逐步启用 write operations。
Cleaning up resources
Testing 后,始终清理 agents 和 threads,以避免不必要 resource usage。下面的代码展示 agent development 中应使用的 cleanup pattern:
在 production 中,如果不清理,会在 Foundry project 中留下 orphaned agents、threads 和 attached vector stores。它们都会继续占用 resource quotas,而 vector stores 还会产生 storage cost。对于 long-running services,应在同一 request scope 中成对创建和删除,例如使用 Python context manager,或运行 scheduled cleanup job,删除超过定义 retention window 的 resources。对于 pilots 和 evaluations,应始终使用 identifiable prefix 为 resources 打 tag,使 cleanup queries 能在 run 完成后可靠找到它们。
# Clean up resources after testing
project.agents.threads.delete(thread_id=thread.id)
project.agents.delete_agent(agent_id=helpdesk_agent.id)
print("Resources cleaned up successfully")
并排比较两个 case studies 可以看出,tool selection 由 integration surface 决定,而不是由 model 决定。Prior authorization agent 依赖 Azure AI Search 进行 policy retrieval,依赖 Code Interpreter 分析 historical approval patterns,并依赖 Logic Apps workflow 执行 submission pipeline。这是一个以内部联系统和明确 contracts 为主的 stack。相较之下,IT help desk agent 依赖 MCP servers 集成快速演进的 third-party platforms,例如 GitHub 和 Azure DevOps,并仅将 Azure AI Search 作为 internal knowledge articles 的 grounding layer。
两个 agents 都应用了相同的 governance primitives:least-privilege allow-lists、面向 state-changing operations 的 approval workflows,以及 audit-trail logging。但具体 built-in、OpenAPI、MCP 和 Azure Functions tools 的组合,会随每个 workflow 的需求而变化。因此,在设计 production agent 时,正确问题不是 “我应该使用哪种 tool type?”,而是 “我的 agent 需要的每项 capability,哪种最低开销 integration path 同时满足我的 governance requirements?”
Summary
本章探索了将 AI agents 从 conversational assistants 转变为 tool-using autonomous systems 的 advanced capabilities,使它们能够与 real-world data、APIs 和 enterprise workflows 交互。
最重要的结论包括:
第一,Azure AI Foundry 中的 agent tool ecosystem 覆盖 built-in tools,例如 File Search、Code Interpreter、Bing Grounding、Azure AI Search,以及 action tools,例如 OpenAPI、MCP、Azure Functions、Logic Apps。Production agents 通常会组合多种 tool types 来完成复杂任务。
第二,Model Context Protocol(MCP)代表 agent-tool integration 的重大进步,它用支持 auto-discovery 且跨平台工作的 standard protocol,替代 custom integration code。
第三,通过 AI Gateway 和 explicit approval workflows 实现 tool governance,对 enterprise deployments 至关重要,尤其是在 healthcare 等 regulated industries 中,因为 audit trails 和 access controls 是监管要求。
第四,error handling 和 fallback strategies 应直接嵌入 agent instructions,确保 agents 能 graceful degrade,而不是 silent fail。
Case studies 展示了多 tools 组合会创造复合价值。Prior authorization agent 的有效性不是来自任何单一 tool,而是来自跨 policy search、EHR integration 和 workflow automation 的 orchestrated workflow。同样,IT helpdesk agent 的效率提升来自通过 MCP 对 GitHub、Azure DevOps 和 internal knowledge bases 的 unified access。
下一章中,我们将探索如何确保这些强大 agent capabilities 的安全和负责任运行,覆盖 Azure AI Red Teaming、content filtering、guardrails,以及 production agent deployments 的 continuous monitoring。