你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

自定义代码解释器工具用于代理(预览版)

重要

本文中标记为(预览)的项目目前以公共预览版提供。 此预览版在没有服务级别协议的情况下提供,不建议将其用于生产工作负荷。 某些功能可能不受支持,或者可能具有受限功能。 有关详细信息,请参阅 Microsoft Azure 预览版的使用条款

使用自定义代码解释器可以完全控制代理生成的Python代码的运行时环境。 可以配置自定义Python包、计算资源和 Azure 容器应用 环境设置。 代码解释器容器公开模型上下文协议 (MCP) 服务器。

当用于代理的内置 Code 解释器工具不符合要求时,请使用自定义代码解释器工具(例如,当需要特定的Python包、自定义容器映像或专用计算资源时)。

有关 MCP 以及如何代理连接到 MCP 工具的详细信息,请参阅“连接到模型上下文协议服务器”(预览版)。

Tip

请考虑使用 工具箱添加此工具。 通过使用工具箱,可以跨代理和运行时重复使用该工具,并通过托管 MCP 终结点集中凭据管理、版本管理和策略强制实施。 请参阅 工具箱快速入门

先决条件

  • Azure CLI 2.60.0 或更高版本。

  • 对于维护的示例项目,Python 3.12 或更高版本。

  • (可选)uv用于更快的Python包管理。

  • 具有以下角色分配的Azure订阅和资源组:

    • Foundry 项目中的 Foundry 用户,用于在预配后配置和运行代理。

      重要

      Foundry RBAC 角色最近已更名。 Foundry 用户Foundry 所有者Foundry 帐户所有者Foundry 项目经理之前的名称分别为“Azure AI 用户”、“Azure AI 所有者”、“Azure AI 帐户所有者”和“Azure AI 项目经理”。 在重命名推出时,你仍可能会在某些位置看到以前的名称。重命名后,角色 ID 和核心权限保持不变。

    • 目标资源组中的 Foundry 所有者(仅当示例部署创建 Foundry 资源和项目连接时)

    • 目标资源组上的容器应用 ManagedEnvironment 参与者(仅当示例部署创建容器应用环境时)。

    通过Microsoft Entra Privileged Identity Management(PIM)及时激活预配角色,并在部署后停用它们。 日常代理开发人员和运行时用户不需要这些预配角色。

  • Microsoft Foundry SDK。 请参阅快速入门以进行安装。

  • Foundry 代理服务和Azure 容器应用动态会话支持的区域。 请参阅Azure 容器应用动态会话区域

使用支持

本文使用Azure CLI和可运行的示例项目。

下表显示了 SDK 和设置支持。

Microsoft Foundry 支持 Python SDK C# SDK JavaScript SDK Java SDK 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 存储库中克隆 sample 代码并导航到终端中的 samples/python/prompt-agents/code-interpreter-custom 文件夹。

预配基础结构

维护的直接代理示例将会话池 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 目标为自定义代码解释器 MCP 服务器的项目连接。
MCP_SERVER_URL MCP_SERVER_URL 工具箱定义所需的会话池 MCP 端点。
AZURE_AI_MODEL_DEPLOYMENT_NAME AZURE_AI_MODEL_DEPLOYMENT_NAME 代理模型部署。

内联示例对AZURE_AI_PROJECT_ENDPOINT使用PROJECT_ENDPOINT,对AZURE_AI_CONNECTION_ID使用MCP_CONNECTION_ID。 受维护的直接代理示例通过项目连接解析 MCP 目标,并使用 https://localhost 作为必需的占位符 URL。 对于工具箱,请将 MCP_SERVER_URL 设置为 mcpServerEndpoint 输出,因为 MCPToolboxTool 需要 server_urlconnector_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

使用托管代理

此示例使用来自 Microsoft Agent Framework 的 FoundryChatClient,并使用 FoundryToolbox 连接到 toolbox 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 上的 Azure SDK .NET 存储库的 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 上 JavaScript 存储库Azure SDK中的 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,因此使用 PythonREST APIC#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:项目终结点 URL。
  • 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"
      }
    ]
  }'

工具箱在 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1 处提供了一个与 MCP 兼容的端点,其中 <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."
        }
      ]
    }
  ]
}

验证设置

预配基础结构并运行示例后:

  1. 确认Azure部署成功完成。
  2. 确认示例使用 .env 文件中的值进行连接。
  3. 在 Microsoft Foundry 中,使用跟踪验证你的智能体调用工具。 有关详细信息,请参阅 有关在 Microsoft Foundry 代理服务中使用工具的最佳做法

故障 排除

问题 可能的原因 分辨率
功能注册尚未完成 az feature register 命令返回 Registering 状态。 等待注册完成(可能需要 15-30 分钟)。 使用 az feature show --namespace Microsoft.App --name SessionPoolsSupportMCP 检查状态。 然后再次运行 az provider register -n Microsoft.App
部署失败并出现权限错误 缺少所需的角色分配。 对于基础结构部署,请通过 Microsoft Entra PIM 在目标资源组中激活 Foundry 所有者容器应用 ManagedEnvironment 参与者。 部署后停用它们。 要执行代理操作,请确认你在 Foundry 项目中具有 Foundry User 角色。
部署失败并出现区域错误 所选区域不支持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 或将其存储在源代码管理中。
  • 将权限限定为所需的最低权限(例如,只读或只写)。

清理

若要停止为预配的资源计费,请删除示例部署创建的资源。 如果为本文使用了专用资源组,请删除资源组。