Ferramenta personalizada de interpretação de código para agentes (pré-visualização)

Importante

Os itens marcados (pré-visualização) neste artigo encontram-se atualmente em pré-visualização pública. Esta pré-visualização é fornecida sem um acordo de nível de serviço, e não a recomendamos para cargas de trabalho em produção. Certas funcionalidades podem não ser suportadas ou podem ter capacidades limitadas. Para mais informações, consulte Termos de Utilização Suplementares para Microsoft Azure Pré-visualizações.

Um interpretador de código personalizado dá-lhe controlo total sobre o ambiente de execução para código Python gerado por agentes. Podes configurar pacotes de Python personalizados, recursos de computação e definições de ambiente Azure Container Apps. O contentor do interpretador de código expõe um servidor Model Context Protocol (MCP).

Use um interpretador de código personalizado quando a ferramenta incorporada Code Interpreter para agentes não cumprir os seus requisitos — por exemplo, quando precisa de pacotes de Python específicos, imagens personalizadas de contentores ou recursos de computação dedicados.

Para mais informações sobre o MCP e como os agentes se conectam às ferramentas MCP, consulte Connect to Model Context Protocol servers (pré-visualização).

Tip

Considera adicionar esta ferramenta usando uma caixa de ferramentas. Ao utilizar uma caixa de ferramentas, pode reutilizar a ferramenta entre agentes e runtimes, bem como centralizar a gestão de credenciais, versionamento e aplicação de políticas através de um endpoint MCP gerido. Veja o guia de início rápido da caixa de ferramentas.

Pré-requisitos

  • CLI do Azure versão 2.60.0 ou posterior.

  • Python 3.12 ou posterior para o projeto de exemplo mantido.

  • (Opcional) uv para uma gestão Python de pacotes mais rápida.

  • Um grupo de subscrição e recursos do Azure com as seguintes atribuições de funções:

    • Utilizador do Foundry no projeto Foundry para configurar e executar o agente após o provisionamento.

      Importante

      As funções RBAC do Foundry foram recentemente renomeadas. Foundry User, Foundry Owner, Foundry Account Owner e Foundry Project Manager foram anteriormente nomeados Azure AI User, Azure AI Owner, Azure AI Account Owner e Azure AI Project Manager. Poderá ainda ver os nomes anteriores em alguns locais enquanto esta alteração de nome está a ser implementada. Os IDs das funções e as permissões principais não são alterados por esta mudança de nome.

    • O Proprietário da Fundição está apenas no grupo de recursos alvo enquanto a implementação da amostra cria os recursos da Fundição e a ligação ao projeto.

    • Contribuidor do Ambiente Gerido do Container Apps apenas no grupo de recursos de destino, enquanto a implementação de exemplo cria o ambiente do Container Apps.

    Ative as funções de aprovisionamento just-in-time com o Microsoft Entra Privileged Identity Management (PIM) e desative-as após a implementação. Os desenvolvedores de agentes do dia a dia e os utilizadores de runtime não precisam destes papéis de provisionamento.

  • Um SDK da Microsoft Foundry. Consulte o quickstart para a instalação.

  • Uma região suportada tanto pelo Foundry Agent Service como pelo Azure Container Apps Dynamic Sessions. Consulte as regiões do Azure Container Apps Dynamic Sessions.

Suporte de utilização

Este artigo utiliza a CLI do Azure e um projeto de exemplo executável.

A tabela seguinte mostra o suporte para SDK e configuração.

Suporte ao Microsoft Foundry Python SDK C# SDK SDK de JavaScript SDK de Java API REST Configuração básica do agente Configuração padrão do agente
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ - ✔️

Para o suporte mais recente a SDK e API para ferramentas de agentes, consulte Melhores práticas para usar ferramentas no Microsoft Foundry Agent Service.

Suporte a SDK

O interpretador de código personalizado utiliza o tipo de ferramenta MCP. Qualquer SDK que suporte ferramentas MCP pode criar um agente interpretador de código personalizado. O SDK .NET está atualmente em fase de pré-visualização. Para os passos de provisionamento de infraestrutura (CLI do Azure, Bicep), veja Criar um agente com interpretador de código personalizado.

Antes de começares

Este procedimento prevê infraestrutura Azure, incluindo recursos Azure Container Apps. Revise os requisitos de custo e governação do Azure da sua organização antes de implementar.

Crie um agente com um interpretador de código personalizado

Os passos seguintes mostram como provisionar a infraestrutura e criar um agente que utilize um servidor MCP interpretador de código personalizado. A configuração da infraestrutura aplica-se a todas as línguas. Seguem-se exemplos de código específicos da linguagem.

Registe-se na funcionalidade de pré-visualização

Registe a funcionalidade do servidor MCP para Azure Container Apps Dynamic Sessions:

az feature register --namespace Microsoft.App --name SessionPoolsSupportMCP
az provider register -n Microsoft.App

Obtenha o código de exemplo

Clone o código de exemplo exemplo no repositório GitHub e navegue até à pasta samples/python/prompt-agents/code-interpreter-custom no seu terminal.

Fornecer a infraestrutura

O exemplo de agente direto mantido armazena o endpoint MCP do conjunto de sessões na ligação ao projeto. As definições da caixa de ferramentas também exigem que o endpoint seja server_url. Adicione esta saída ao ficheiro clonado infra.bicep :

output MCP_SERVER_URL string = sessionPool.properties.mcpServerSettings.mcpServerEndpoint

Não use poolManagementEndpoint. Esse valor é o endpoint de gestão das Sessões Dinâmicas, não o endpoint do servidor MCP.

Para provisionar a infraestrutura, execute o seguinte comando usando o CLI do Azure (az):

az deployment group create \
    --name custom-code-interpreter \
    --subscription <your_subscription> \
    --resource-group <your_resource_group> \
    --template-file ./infra.bicep

Nota

A implementação pode demorar até uma hora, dependendo do número de instâncias em espera que solicitar. A alocação dinâmica do pool de sessões é o passo mais longo.

Configure e execute o agente

Copie o .env.sample ficheiro do repositório para .env. Mapeie as saídas de implementação do Bicep para as variáveis de ambiente correspondentes:

Saída do Bicep Variável de ambiente Usado para
AZURE_AI_PROJECT_ENDPOINT AZURE_AI_PROJECT_ENDPOINT Endpoint do projeto Foundry.
AZURE_AI_CONNECTION_ID AZURE_AI_CONNECTION_ID Ligação ao Project cujo destino é o servidor MCP do interpretador de código personalizado.
MCP_SERVER_URL MCP_SERVER_URL Endpoint MCP do conjunto de sessões exigido pelas definições da toolbox.
AZURE_AI_MODEL_DEPLOYMENT_NAME AZURE_AI_MODEL_DEPLOYMENT_NAME Implementação do modelo de agente.

Os exemplos em linha usam PROJECT_ENDPOINT para AZURE_AI_PROJECT_ENDPOINT e MCP_CONNECTION_ID para AZURE_AI_CONNECTION_ID. O exemplo de agente direto mantido resolve o destino MCP através da ligação ao projeto e utiliza https://localhost como URL de marcador de posição obrigatória. Para uma toolbox, defina MCP_SERVER_URL para a saída mcpServerEndpoint porque MCPToolboxTool requer server_url ou connector_id mesmo quando também fornece uma ligação ao projeto.

Instale as dependências de Python e execute o exemplo mantido com um destes pares de comandos:

uv sync
uv run ./main.py

Ou criar um ambiente virtual e instalar os requisitos de check-in:

python -m venv .venv
./.venv/bin/pip install -r requirements.txt
./.venv/bin/python ./main.py

Exemplo de código

O seguinte exemplo de Python mostra como criar um agente com uma ferramenta MCP personalizada para interpretar código:

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")

Produção esperada

Quando executa a amostra, vê uma saída semelhante a:

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

Use um agente hospedado

Este exemplo utiliza FoundryChatClient do Microsoft Agent Framework e liga-se ao endpoint MCP da toolbox usando FoundryToolbox.

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())

Exemplo de código

O exemplo seguinte de C# mostra como criar um agente com uma ferramenta MCP personalizada para interpretar código. Para mais informações sobre como trabalhar com ferramentas MCP em .NET, consulte o exemplo de ferramenta MCP na SDK do Azure para .NET repositório sobre GitHub.

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");

Apague a versão da caixa de ferramentas quando o agente deixar de lhe fazer referência. Ver Eliminar uma versão da caixa de ferramentas para a chamada .NET verificada.

Produção esperada

Agent created: CustomCodeInterpreterAgent (version 1)
The factorial of 10 is 3,628,800.
Agent deleted

Use um agente hospedado

Este exemplo utiliza a integração com o Microsoft Agent Framework AddFoundryToolboxes para ligar o agente alojado à toolbox.

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();

Exemplo de código

O exemplo seguinte de TypeScript mostra como criar um agente com uma ferramenta MCP de interpretação de código personalizada. Para uma versão em JavaScript, consulte o exemplo da ferramenta MCP no repositório SDK do Azure de JavaScript sobre GitHub.

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);
});

Produção esperada

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

Recomendado: Para a maioria dos agentes, adiciona ferramentas através de uma caixa de ferramentas e liga a caixa de ferramentas ao teu agente como uma ferramenta MCP. O SDK Java ainda não expõe uma API de criação de toolbox, por isso cria a toolbox usando o exemplo de Python, REST, C# ou TypeScript, ou o portal Foundry, e depois faz referência ao endpoint MCP do teu agente Java como um McpTool. O exemplo seguinte associa o endpoint MCP da toolbox que contém o interpretador de código personalizado ao agente.

Adicione a dependência ao seu pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.4.0</version>
</dependency>

Exemplo de código

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");
    }
}

Produção esperada

Agent created: CustomCodeInterpreterAgent (version 1)
Response: The factorial of 10 is 3,628,800.
Agent deleted

Pré-requisitos

Defina estas variáveis de ambiente:

  • FOUNDRY_PROJECT_ENDPOINT: URL do endpoint do seu projeto.
  • AGENT_TOKEN: Um token de autenticação para a Foundry.

Obtenha um token de acesso:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

Exemplo de código

Crie uma caixa de ferramentas com o interpretador de código personalizado

Adicione o interpretador de código personalizado criando uma caixa de ferramentas. Depois, anexa a toolbox ao teu agente como uma ferramenta MCP. Para mais informações, veja O que é uma caixa de ferramentas?

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"
      }
    ]
  }'

A caixa de ferramentas expõe um endpoint compatível com MCP em $FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1, onde <version> é a versão devolvida pela chamada anterior.

Criar uma ligação remota de ferramenta à caixa de ferramentas

Crie uma ligação remota a um projeto de ferramenta que aponte para o endpoint da caixa de ferramentas. Utilize um token de utilizador do Entra para que a identidade do chamador seja transmitida (audience 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

Crie um agente que utilize a caixa de ferramentas

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"
        }
      ]
    }
  }'

Crie uma resposta

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."
  }'

Limpar

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"

Produção esperada

{
  "id": "resp_xxxxxxxxxxxx",
  "output": [
    {
      "type": "message",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "The factorial of 10 is 3,628,800."
        }
      ]
    }
  ]
}

Verifica a tua configuração

Depois de provisionar a infraestrutura e executar a amostra:

  1. Confirme que a implementação do Azure foi concluída com sucesso.
  2. Confirme que a amostra está conectada usando os valores no seu .env ficheiro.
  3. No Microsoft Foundry, verifica se o teu agente chama a ferramenta usando rastreamento. Para mais informações, consulte Boas práticas para usar ferramentas no Microsoft Foundry Agent Service.

Resolução de problemas

Problema Causa provável Resolução
O registo de funcionalidades ainda está pendente O comando az feature register devolve o estado Registering. Espere que o registo termine (pode demorar 15-30 minutos). Verifique o estado com az feature show --namespace Microsoft.App --name SessionPoolsSupportMCP. Depois executa novamente az provider register -n Microsoft.App.
A implementação falha com erro de permissão Faltam atribuições obrigatórias de funções. Para a implementação da infraestrutura, ative o Foundry Owner e o Container Apps ManagedEnvironment Contributor no grupo de recursos alvo através do Microsoft Entra PIM. Desative-os após a missão. Para operações do agente, confirme que dispõe de Foundry User no projeto Foundry.
Falha na implementação devido a erro de região A região selecionada não suporta Azure Container Apps Dynamic Sessions. Experimenta uma região diferente. Veja Azure Container Apps regiones para regiões suportadas.
O agente não chama a ferramenta A ligação MCP não está configurada corretamente, ou as instruções do agente não indicam a utilização da ferramenta. Use o traçado no Microsoft Foundry para confirmar a invocação de ferramentas. Verifica se o MCP_SERVER_URL corresponde ao endpoint do teu Container Apps implementado. Consulte Melhores práticas.
Limite de tempo de conexão ao servidor MCP O pool de sessões de Container Apps não está em execução ou não tem instâncias em espera. Verifique o estado do pool de sessões no portal do Azure. Aumente standbyInstanceCount no seu template Bicep, se necessário.
Execução de código falha no contentor Faltam pacotes Python no contentor personalizado. Atualize a imagem do seu contentor para incluir os pacotes necessários. Reconstrói e redistribui o contentor.
Erro de autenticação ao ligar ao servidor MCP As credenciais de ligação ao projeto são inválidas ou expiradas. Regenera as credenciais de ligação e atualiza o .env ficheiro. Verifica o MCP_PROJECT_CONNECTION_ID formato.

Limitações

As APIs não suportam diretamente entrada ou saída de ficheiros, nem o uso de armazenamentos de ficheiros. Para receber e retirar dados, deve usar URLs, como URLs de dados para ficheiros pequenos e URLs de assinatura de acesso partilhado (SAS) do Azure Blob Service para ficheiros grandes.

Segurança

Trate o código gerado e as suas dependências como não confiáveis. Utilize uma imagem de base aprovada e uma lista de pacotes permitidos, execute com o mínimo de recursos de computação e permissões necessário e restrinja o acesso de saída à rede aos destinos necessários. Não coloque dados sensíveis ou credenciais de produção na sessão.

Se usar URLs SAS para passar dados para dentro ou fora do tempo de execução:

  • Use tokens de SAS de curta duração.
  • Não registes URLs SAS nem as armazene no controlo do código-fonte.
  • Defina as permissões de escopo para o mínimo necessário (por exemplo, apenas leitura ou apenas escrita).

Limpar

Para evitar a faturação pelos recursos provisionados, elimine os recursos criados pela implementação do exemplo. Se usou um grupo de recursos dedicado para este artigo, elimine o grupo de recursos.