重要
本文中標示為預覽的項目目前仍在預覽中。 此預覽版未簽訂服務等級協議,Microsoft 不建議用於生產工作負載。 某些功能可能不被支援或功能受限。 欲了解更多資訊,請參閱Microsoft Azure預覽補充使用條款。
自訂的程式碼直譯器讓你能完全掌控代理生成的 Python 程式碼執行環境。 你可以設定自訂的Python套件、運算資源,以及 Azure 容器應用程式 環境設定。 程式碼直譯器容器會暴露一個模型情境協定(MCP)伺服器。
當內建的Code Interpreter for agents 不符合需求時,請使用自訂的程式碼直譯器,例如需要特定的Python套件、自訂容器映像檔或專用運算資源。
欲了解更多關於 MCP 及代理如何連接 MCP 工具的資訊,請參閱 「連接模型情境協定伺服器(預覽)」。
先決條件
Azure CLI 版本 2.60.0 或更新版本。
維護的範例專案則使用 Python 3.12 或更新版本。
(可選)uv以加快Python套件管理。
一個包含以下角色分配的 Azure 訂閱與資源群組:
在 Foundry 專案中的Foundry 使用者,用於在佈建後設定及執行代理程式。
重要
Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。
Foundry Owner 僅限於目標資源群組,而範例部署會建立 Foundry 資源與專案連線。
僅在樣本部署建立容器應用程式環境時,才需要目標資源群組上的容器應用程式受控環境參與者角色。
透過 Microsoft Entra Privileged Identity Management (PIM) 即時啟用佈建角色,並在部署後將其停用。 日常代理開發者和執行時使用者不需要這些配置角色。
Microsoft Foundry SDK。 請參考 安裝快速入門 。
一個由 Foundry Agent Service 和 Azure 容器應用程式 Dynamic Sessions 共同支援的區域。 請參閱 Azure 容器應用程式動態工作階段區域。
使用支援
本文使用 Azure CLI 及可執行的範例專案。
下表顯示 SDK 與設定支援。
| Microsoft Foundry 支援 | Python SDK | C# SDK | JavaScript SDK | Java 開發套件 | REST API | 基本代理設定 | 標準代理設定 |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | - | ✔️ |
如需最新的 SDK 與 API 支援,請參閱 Microsoft Foundry 代理服務中工具使用的最佳實務 。
SDK 支援
自訂程式碼直譯器使用 MCP 工具類型。 任何支援 MCP 工具的 SDK 都能建立自訂的程式碼直譯代理程式。 .NET SDK 目前處於預覽階段。 關於基礎架構配置步驟(Azure CLI、Bicep),請參見 建立包含自訂程式碼直譯器的代理程式。
在你開始之前
此程序會配置 Azure 基礎設施,包括 Azure 容器應用程式 資源。 部署前請檢視貴組織的 Azure 成本與治理需求。
建立一個帶有自訂程式碼直譯器的代理程式
以下步驟說明如何配置基礎設施,並建立使用自訂程式碼直譯器 MCP 伺服器的代理程式。 基礎架構設定適用於所有語言。 接著附上語言專屬的程式碼範例。
註冊預覽功能
註冊 Azure 容器應用程式 動態會話的 MCP 伺服器功能:
az feature register --namespace Microsoft.App --name SessionPoolsSupportMCP
az provider register -n Microsoft.App
取得範例程式碼
在 GitHub repo 中複製
基礎設施配置
受維護的直接代理範例會將工作階段集區 MCP 端點儲存於專案連線中。 工具箱定義也要求端點為 server_url。 將下列輸出內容加入已複製的 infra.bicep 檔案中:
output MCP_SERVER_URL string = sessionPool.properties.mcpServerSettings.mcpServerEndpoint
請勿使用 poolManagementEndpoint。 這個值是動態會話管理端點,而非 MCP 伺服器端點。
要配置基礎設施,請使用Azure CLI (az)執行以下指令:
az deployment group create \
--name custom-code-interpreter \
--subscription <your_subscription> \
--resource-group <your_resource_group> \
--template-file ./infra.bicep
註
部署時間可能長達一小時,視你申請的待命實例數量而定。 動態會話池的分配是整個過程中最耗時的一步。
設定並執行代理程式
將檔案從儲存庫複製 .env.sample 到 .env。 將 Bicep 部署輸出映射到相符的環境變數:
| Bicep 輸出 | 環境變數 | 用於 |
|---|---|---|
AZURE_AI_PROJECT_ENDPOINT |
AZURE_AI_PROJECT_ENDPOINT |
Foundry 的專案端點。 |
AZURE_AI_CONNECTION_ID |
AZURE_AI_CONNECTION_ID |
Project 連線,其目標是自訂程式碼直譯器 MCP 伺服器。 |
MCP_SERVER_URL |
MCP_SERVER_URL |
工具箱定義所需的 Session pool MCP 端點。 |
AZURE_AI_MODEL_DEPLOYMENT_NAME |
AZURE_AI_MODEL_DEPLOYMENT_NAME |
代理模型部署。 |
行內範例對 AZURE_AI_PROJECT_ENDPOINT 使用 PROJECT_ENDPOINT,對 AZURE_AI_CONNECTION_ID 使用 MCP_CONNECTION_ID。 目前維護中的直接 Agent 樣本會透過專案連線解析 MCP 目標,並使用https://localhost作為必要的預留位置 URL。 對於工具箱而言,請將 MCP_SERVER_URL 設為 mcpServerEndpoint 輸出,因為 MCPToolboxTool 需要 server_url 或 connector_id,即使您也提供了專案連線。
安裝 Python 相依套件,並使用以下其中一組指令來執行目前維護中的範例:
uv sync
uv run ./main.py
或建立虛擬環境並安裝已登記的需求:
python -m venv .venv
./.venv/bin/pip install -r requirements.txt
./.venv/bin/python ./main.py
程式碼範例
以下 Python 範例展示了如何使用自訂的程式碼直譯器 MCP 工具建立代理:
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MCPTool, MCPToolboxTool, PromptAgentDefinition
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
MCP_SERVER_URL = "https://your-mcp-server-url"
# Optional: set to your project connection ID if your MCP server requires authentication
MCP_CONNECTION_ID = "your-mcp-connection-id"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Add the custom code interpreter MCP server to a toolbox. Using a toolbox is the
# recommended way to give agents tools: you curate tools once and reuse the toolbox
# across agents. See /azure/foundry/agents/concepts/toolbox-overview
toolbox = project.toolboxes.create_version(
name="custom-code-interpreter-toolbox",
description="Toolbox with the custom code interpreter MCP server",
tools=[
MCPToolboxTool(
server_label="custom-code-interpreter",
server_url=MCP_SERVER_URL,
project_connection_id=MCP_CONNECTION_ID,
)
],
)
# The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# Create a remote-tool project connection that points at the toolbox endpoint.
# Use a user Entra token so the caller's identity is passed through
# (audience https://ai.azure.com). Create the connection once, for example with
# the Azure Developer CLI:
#
# azd ai connection create custom-code-interpreter-toolbox-conn \
# --kind remote-tool \
# --target "<TOOLBOX_MCP_URL>" \
# --auth-type user-entra-token \
# --audience https://ai.azure.com
TOOLBOX_CONNECTION_NAME = "custom-code-interpreter-toolbox-conn"
# Create an agent that uses the toolbox as an MCP tool
agent = project.agents.create_version(
agent_name="CustomCodeInterpreterAgent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant that can run Python code to analyze data and solve problems.",
tools=[
MCPTool(
server_label="toolbox",
server_url=TOOLBOX_MCP_URL,
require_approval="never",
project_connection_id=TOOLBOX_CONNECTION_NAME,
)
],
),
description="Agent with custom code interpreter for data analysis.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
# Test the agent with a simple calculation
response = openai.responses.create(
input="Calculate the factorial of 10 using Python.",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Response: {response.output_text}")
# Clean up
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
project.toolboxes.delete_toolbox_version(
toolbox_name=toolbox.name,
version=toolbox.version,
)
print("Agent deleted")
預期產出
當你執行取樣時,你會看到類似的輸出:
Agent created (id: agent-xxxxxxxxxxxx, name: CustomCodeInterpreterAgent, version: 1)
Response: The factorial of 10 is 3,628,800. I calculated this using Python's math.factorial() function.
Agent deleted
使用託管代理
此範例使用 FoundryChatClient Microsoft 代理框架,並透過 FoundryToolbox連接工具箱 MCP 端點。
import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.identity import AzureCliCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MCPToolboxTool
PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
MCP_SERVER_URL = "https://your-mcp-server-url"
# Optional: set to your project connection ID if your MCP server requires authentication
MCP_CONNECTION_ID = "your-mcp-connection-id"
async def main() -> None:
credential = AzureCliCredential()
# 1. Create the custom code interpreter MCP tool and add it to a toolbox. Using a toolbox is the
# recommended way to give agents tools: curate tools once and reuse the
# toolbox across agents. See /azure/foundry/agents/concepts/toolbox-overview
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
toolbox = project.toolboxes.create_version(
name="custom-code-interpreter-toolbox",
description="Toolbox with the custom code interpreter MCP server",
tools=[
MCPToolboxTool(
server_label="custom-code-interpreter",
server_url=MCP_SERVER_URL,
project_connection_id=MCP_CONNECTION_ID,
)
],
)
# 2. The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# 3. Attach the toolbox to the hosted agent as an MCP tool.
, timeout=120.0)
toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)
agent = Agent(
client=FoundryChatClient(credential=credential),
instructions="You are a helpful assistant that can run Python code to analyze data and solve problems.",
tools=[toolbox_tool],
)
result = await agent.run("Calculate the factorial of 10 using Python.")
print(result.text)
project.toolboxes.delete_toolbox_version(
toolbox_name=toolbox.name,
version=toolbox.version,
)
if __name__ == "__main__":
asyncio.run(main())
程式碼範例
以下的 C# 範例展示了如何使用自訂的程式碼直譯器 MCP 工具來建立代理程式。 欲了解更多關於在 .NET 中使用 MCP 工具的資訊,請參閱 GitHub .NET 倉庫Azure SDK中的 MCP 工具範例。
using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var mcpServerUrl = "https://your-mcp-server-url";
// Optional: set to your project connection ID if your MCP server requires authentication
var mcpConnectionId = "your-mcp-connection-id";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Add the custom code interpreter MCP server to a toolbox. Using a toolbox is the
// recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
// Code runs in a sandboxed Azure Container Apps session.
McpTool customCodeInterpreter = ResponseTool.CreateMcpTool(
serverLabel: "custom-code-interpreter",
serverUri: new Uri(mcpServerUrl));
customCodeInterpreter.ProjectConnectionId = mcpConnectionId;
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
.GetAgentToolboxes().CreateToolboxVersion(
toolboxName: "custom-code-interpreter-toolbox",
tools: [ProjectsAgentTool.AsProjectTool(customCodeInterpreter)],
description: "Toolbox with the custom code interpreter MCP server");
// The toolbox exposes an MCP-compatible endpoint.
var toolboxMcpUrl = new Uri(
$"{projectEndpoint}/toolboxes/{toolboxVersion.Name}" +
$"/versions/{toolboxVersion.Version}/mcp?api-version=v1");
// Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create custom-code-interpreter-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
var toolboxConnectionName = "custom-code-interpreter-toolbox-conn";
McpTool toolboxTool = ResponseTool.CreateMcpTool(
serverLabel: "toolbox",
serverUri: toolboxMcpUrl,
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
GlobalMcpToolCallApprovalPolicy.NeverRequireApproval));
toolboxTool.ProjectConnectionId = toolboxConnectionName;
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful assistant that can run Python code to analyze data and solve problems.",
Tools = { toolboxTool }
};
AgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "CustomCodeInterpreterAgent",
options: new(agentDefinition));
Console.WriteLine($"Agent created: {agent.Name} (version {agent.Version})");
// Create a response using the agent
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agent.Name);
ResponseResult response = responseClient.CreateResponse(
new([ResponseItem.CreateUserMessageItem("Calculate the factorial of 10 using Python.")]));
Console.WriteLine(response.GetOutputText());
// Clean up
projectClient.AgentAdministrationClient.DeleteAgentVersion(
agentName: agent.Name,
agentVersion: agent.Version);
Console.WriteLine("Agent deleted");
當代理不再引用工具箱版本時,刪除它。 請參閱刪除工具箱版本以了解驗證過的 .NET 呼叫。
預期產出
Agent created: CustomCodeInterpreterAgent (version 1)
The factorial of 10 is 3,628,800.
Agent deleted
使用託管代理
本範例使用 Microsoft Agent Framework AddFoundryToolboxes 整合,將託管代理程式與工具箱連接。
using System;
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
const string AgentInstructions = "You are a helpful assistant that can run Python code to analyze data and solve problems.";
const string AgentName = "CustomCodeInterpreterAgent";
string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";
string mcpServerUrl = "https://your-mcp-server-url";
string mcpConnectionId = "your-mcp-connection-id";
DefaultAzureCredential credential = new();
// 1. Create the custom code interpreter MCP tool and add it to a toolbox. Using a toolbox is the
// recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: credential);
McpTool customCodeInterpreter = ResponseTool.CreateMcpTool(
serverLabel: "custom-code-interpreter",
serverUri: new Uri(mcpServerUrl));
customCodeInterpreter.ProjectConnectionId = mcpConnectionId;
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
.GetAgentToolboxes().CreateToolboxVersion(
toolboxName: "custom-code-interpreter-toolbox",
tools: [ProjectsAgentTool.AsProjectTool(customCodeInterpreter)],
description: "Toolbox with the custom code interpreter MCP server");
// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant with access to the toolbox tools.",
name: "hosted-toolbox-agent");
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);
var app = builder.Build();
app.MapFoundryResponses();
app.Run();
程式碼範例
以下 TypeScript 範例展示了如何使用自訂的程式碼直譯器 MCP 工具建立代理程式。 關於 JavaScript 版本,請參閱 GitHub Azure SDK for JavaScript repository 中的 MCP 工具範例。
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const MCP_SERVER_URL = "https://your-mcp-server-url";
export async function main(): Promise<void> {
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Add the custom code interpreter MCP server to a toolbox. Using a toolbox is
// the recommended way to give agents tools. Code runs in a sandboxed Azure
// Container Apps session, so the tool uses require_approval: "never".
// See /azure/foundry/agents/concepts/toolbox-overview
const toolbox = await project.toolboxes.createVersion(
"custom-code-interpreter-toolbox",
[
{
type: "mcp",
server_label: "custom-code-interpreter",
server_url: MCP_SERVER_URL,
require_approval: "never",
},
],
{ description: "Toolbox with the custom code interpreter MCP server" },
);
// The toolbox exposes an MCP-compatible endpoint.
const toolboxMcpUrl =
`${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
`/versions/${toolbox.version}/mcp?api-version=v1`;
// Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create custom-code-interpreter-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionName = "custom-code-interpreter-toolbox-conn";
// Create an agent that uses the toolbox as an MCP tool
const agent = await project.agents.createVersion("CustomCodeInterpreterAgent", {
kind: "prompt",
model: "gpt-5-mini",
instructions:
"You are a helpful assistant that can run Python code to analyze data and solve problems.",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "never",
project_connection_id: toolboxConnectionName,
},
],
});
console.log(`Agent created (name: ${agent.name}, version: ${agent.version})`);
// Send a request to the agent
const response = await openai.responses.create(
{
input: "Calculate the factorial of 10 using Python.",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`Response: ${response.output_text}`);
// Clean up
await project.agents.deleteVersion(agent.name, agent.version);
await project.toolboxes.deleteVersion(toolbox.name, toolbox.version);
console.log("Agent deleted");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
預期產出
Agent created (name: CustomCodeInterpreterAgent, version: 1)
Response: The factorial of 10 is 3,628,800. I calculated this using Python's math.factorial() function.
Agent deleted
Tip
建議:對大多數代理程式來說,請透過工具箱新增工具,並將該工具箱作為 MCP 工具附加到您的代理程式。 Java SDK 目前還沒有公開工具箱建立 API,所以你可以用 Python、REST API、C# 或 TypeScript 範例,或 Foundry 入口網站來建立工具箱,然後從你的 Java 代理中引用其 MCP 端點作為 McpTool。 以下範例將包含自訂程式碼直譯器的工具箱 MCP 端點附加到代理程式上。
新增相依性至您的pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.4.0</version>
</dependency>
程式碼範例
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.McpTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Collections;
public class CustomCodeInterpreterExample {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
String toolboxMcpUrl = projectEndpoint + "/toolboxes/custom-code-interpreter-toolbox/versions/1/mcp?api-version=v1";
// Set to the remote-tool project connection that points at the toolbox MCP endpoint.
String toolboxConnectionId = "custom-code-interpreter-toolbox-conn";
// Create clients to call Foundry API
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// Attach the toolbox MCP endpoint as an MCP tool.
// Uses require_approval: "never" because code runs in a sandboxed Container Apps session.
McpTool toolboxTool = new McpTool("toolbox")
.setServerUrl(toolboxMcpUrl)
.setProjectConnectionId(toolboxConnectionId)
.setRequireApproval("never");
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini")
.setInstructions("You are a helpful assistant that can run Python code to analyze data and solve problems.")
.setTools(Collections.singletonList(toolboxTool));
AgentVersionDetails agent = agentsClient.createAgentVersion(
"CustomCodeInterpreterAgent", agentDefinition);
System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());
// Create a response
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Calculate the factorial of 10 using Python."));
System.out.println("Response: " + response.output());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
System.out.println("Agent deleted");
}
}
預期產出
Agent created: CustomCodeInterpreterAgent (version 1)
Response: The factorial of 10 is 3,628,800.
Agent deleted
先決條件
設定以下環境變數:
-
FOUNDRY_PROJECT_ENDPOINT: 你的專案端點網址。 -
AGENT_TOKEN:Foundry 的持有人權杖。
取得存取權憑證:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
程式碼範例
用自訂程式碼直譯器建立工具箱
透過建立工具箱來新增自訂的程式碼直譯器。 接著,將工具箱作為 MCP 工具附加到你的代理人身上。 欲了解更多資訊,請參閱 「什麼是工具箱?」
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"description": "Toolbox with the custom code interpreter MCP server",
"tools": [
{
"type": "mcp",
"server_label": "custom-code-interpreter",
"server_url": "<MCP_SERVER_URL>",
"project_connection_id": "<MCP_PROJECT_CONNECTION_ID>",
"require_approval": "never"
}
]
}'
工具箱在 處暴露一個與 MCP 相容的端點 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1,其中 <version> 是前一次呼叫回傳的版本。
建立與工具箱的遠端工具連線
建立一個遠端工具專案連線,指向工具箱端點。 使用使用者 Entra 權杖,以便呼叫者的身分識別得以傳遞 (對象https://ai.azure.com):
azd ai connection create custom-code-interpreter-toolbox-conn \
--kind remote-tool \
--target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1" \
--auth-type user-entra-token \
--audience https://ai.azure.com
建立一個能使用工具箱的代理人
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"name": "CustomCodeInterpreterAgent",
"definition": {
"kind": "prompt",
"model": "<MODEL_DEPLOYMENT>",
"instructions": "You are a helpful assistant that can run Python code to analyze data and solve problems.",
"tools": [
{
"type": "mcp",
"server_label": "toolbox",
"server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1",
"require_approval": "never",
"project_connection_id": "custom-code-interpreter-toolbox-conn"
}
]
}
}'
建立回應
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent_reference": {"type": "agent_reference", "name": "CustomCodeInterpreterAgent"},
"input": "Calculate the factorial of 10 using Python."
}'
清理
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/CustomCodeInterpreterAgent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
curl -X DELETE \
"$FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
預期產出
{
"id": "resp_xxxxxxxxxxxx",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "The factorial of 10 is 3,628,800."
}
]
}
]
}
確認你的設定
在你配置好基礎架構並執行樣本後:
- 確認 Azure 部署已成功完成。
- 確認範例已使用您
.env檔案中的值進行連線。 - 在 Microsoft Foundry 中,使用追蹤確認 Agent 會呼叫工具。 欲了解更多資訊,請參閱 Microsoft Foundry Agent Service 使用工具的最佳實務。
故障排除
| 問題 | 可能的原因 | 解決方法 |
|---|---|---|
| 功能註冊仍在等待中 | 指令 az feature register 會回傳 Registering 狀態。 |
等待報名完成(大約需要15到30分鐘)。 請用az feature show --namespace Microsoft.App --name SessionPoolsSupportMCP檢查狀態。 然後再跑一次az provider register -n Microsoft.App。 |
| 部署失敗且權限錯誤 | 缺少必要的角色分配。 | 進行基礎結構部署時,請透過 Microsoft Entra PIM 在目標資源群組上啟用 Foundry Owner 和 Container Apps ManagedEnvironment Contributor。 部署後停用它們。 關於代理操作,請確認你在 Foundry 專案中有 Foundry 使用者 。 |
| 部署失敗,區域錯誤 | 所選區域不支援 Azure 容器應用程式 動態會話。 | 試試不同的地區。 請參見Azure 容器應用程式區域以了解支援區域。 |
| 代理不會調用該工具 | MCP 連線設定不正確,或是代理指令沒有提示使用工具。 | 在 Microsoft Foundry 中使用追蹤來確認工具調用。 確認 MCP_SERVER_URL 與您已部署的容器應用端點相符。 請參閱最佳實務。 |
| MCP 伺服器連線逾時 | 容器應用程式的會話池沒有在執行,或者沒有備用實例。 | 請查看 Azure 入口網站中的會話池狀態。 如果需要,可以在你的Bicep模板中增加standbyInstanceCount。 |
| 容器中程式碼執行失敗 | 自訂容器中缺少 Python 套件。 | 更新你的容器映像檔,加入所需的套件。 重建並重新部署容器。 |
| 連接至 MCP 伺服器的認證錯誤 | 專案連線憑證無效或已過期。 | 重新建立連線憑證並更新 .env 檔案。 請確認MCP_PROJECT_CONNECTION_ID格式。 |
限制
這些 API 並不直接支援檔案輸入或輸出,或是檔案儲存的使用。 要取得資料進出,必須使用 URL,例如小檔案使用資料 URL,大型檔案則使用 Azure Blob 服務共享存取簽章(SAS)URL。
安全性
將產生的程式碼及其相依關係視為不可信。 使用核准的基礎映像與套件允許清單,使用最低所需的運算與權限,並限制外發網路存取至指定目的地。 不要將敏感資料或生產憑證掛載到會話中。
如果你使用 SAS URL 以傳輸數據進出運行時環境:
- 使用短期的 SAS 代幣。
- 不要記錄 SAS 的 URL,也不要將它們儲存在原始碼管理中。
- 範圍權限限制在最低要求範圍內(例如唯讀或唯寫)。
清理
若要停止對已配置資源計費,請刪除範例部署所產生的資源。 如果你使用了專門的資源群組來閱讀這篇文章,請刪除該資源群組。