Herramienta de intérprete de código personalizado para agentes (versión preliminar)

Importante

Los elementos marcados (versión preliminar) de este artículo se encuentran actualmente en versión preliminar pública. Esta versión preliminar se proporciona sin un contrato de nivel de servicio y no se recomienda para cargas de trabajo de producción. Es posible que algunas características no se admitan o que tengan funcionalidades restringidas. Para obtener más información, vea Supplemental Terms of Use for Microsoft Azure Previews.

Un intérprete de código personalizado proporciona control total sobre el entorno de tiempo de ejecución para el código de Python generado por el agente. Puede configurar paquetes de Python personalizados, recursos de cómputo y la configuración del entorno de Azure Container Apps. El contenedor de intérpretes de código expone un servidor de Protocolo de contexto de modelo (MCP).

Use un intérprete de código personalizado cuando la herramienta integrada Code Interpreter para agentes no cumple sus requisitos, por ejemplo, cuando necesita paquetes de Python específicos, imágenes de contenedor personalizadas o recursos de proceso dedicados.

Para obtener más información sobre MCP y cómo los agentes se conectan a las herramientas de MCP, consulte Conexión a servidores de protocolo de contexto de modelo (versión preliminar).

Tip

Considere la posibilidad de agregar esta herramienta mediante un cuadro de herramientas. Mediante el uso de un cuadro de herramientas, puede reutilizar la herramienta entre agentes y entornos de ejecución, así como centralizar la administración de credenciales, el control de versiones y la aplicación de directivas a través de un punto de conexión de MCP administrado. Consulte el inicio rápido del cuadro de herramientas.

Requisitos previos

  • CLI de Azure versión 2.60.0 o posterior.

  • Python 3.12 o posterior para el proyecto de ejemplo mantenido.

  • (Opcional) uv para una administración de paquetes Python más rápida.

  • Una suscripción y un grupo de recursos de Azure con las siguientes asignaciones de roles:

    • Foundry User en el proyecto Foundry para configurar y ejecutar el agente después del aprovisionamiento.

      Importante

      Recientemente se cambió el nombre de los roles RBAC de Foundry. Foundry User, Foundry Owner, Foundry Account Owner y Foundry Project Manager se llamaban anteriormente Usuario de Azure AI, Propietario de Azure AI, Propietario de la cuenta de Azure AI y Administrador de proyectos de Azure AI. Es posible que siga viendo los nombres anteriores en algunos lugares mientras se implementa el cambio de nombre. El cambio de nombre no modifica los identificadores de rol y los permisos principales.

    • Foundry Owner en el grupo de recursos de destino únicamente mientras la implementación de ejemplo crea los recursos de Foundry y la conexión del proyecto.

    • Colaborador del entorno administrado de Container Apps en el grupo de recursos de destino únicamente mientras la implementación de ejemplo crea el entorno de Container Apps.

    Active los roles de aprovisionamiento justo a tiempo a través de Microsoft Entra Privileged Identity Management (PIM) y desactive los roles después de la implementación. Los desarrolladores habituales de agentes y los usuarios del entorno de ejecución no necesitan estos roles de aprovisionamiento.

  • Un SDK de Microsoft Foundry. Consulte la guía de inicio rápido para la instalación.

  • Una región compatible con Foundry Agent Service y con Azure Container Apps Dynamic Sessions. Consulte Azure Container Apps regiones de sesiones dinámicas.

Soporte de uso

En este artículo se usa el CLI de Azure y un proyecto de ejemplo ejecutable.

En la tabla siguiente se muestra la compatibilidad con el SDK y la configuración.

compatibilidad con Microsoft Foundry SDK de Python C# SDK SDK de JavaScript SDK de Java REST API Configuración básica del agente Configuración del agente estándar
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ - ✔️

Para obtener la compatibilidad más reciente de SDK y API con las herramientas de agentes, consulte Prácticas recomendadas para usar herramientas en Microsoft Foundry Agent Service.

Compatibilidad con SDK

El intérprete de código personalizado usa el tipo de herramienta MCP. Cualquier SDK que admita herramientas de MCP puede crear un agente de intérprete de código personalizado. El SDK de .NET está actualmente en versión preliminar. Para conocer los pasos de aprovisionamiento de infraestructura (CLI de Azure, Bicep), consulte Crear un agente con intérprete de código personalizado.

Antes de empezar

Este procedimiento aprovisiona la infraestructura de Azure, incluyendo los recursos de Azure Container Apps. Revise los requisitos de costos y gobernanza de Azure de su organización antes de implementar.

Creación de un agente con intérprete de código personalizado

En los pasos siguientes se muestra cómo aprovisionar la infraestructura y crear un agente que use un servidor MCP de intérprete de código personalizado. La configuración de la infraestructura se aplica a todos los idiomas. A continuación se presentan los ejemplos de código específicos del lenguaje.

Registro de la característica de vista previa

Registre la característica del servidor MCP para Azure Container Apps Dynamic Sessions:

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

Obtención del código de ejemplo

Clone el código sample en el repositorio de GitHub y vaya a la carpeta samples/python/prompt-agents/code-interpreter-custom del terminal.

Aprovisionamiento de la infraestructura

El ejemplo de agente directo administrado almacena el punto de conexión MCP del grupo de sesiones en la conexión del proyecto. Las definiciones de la caja de herramientas también requieren el endpoint como server_url. Agregue esta salida al archivo clonado infra.bicep :

output MCP_SERVER_URL string = sessionPool.properties.mcpServerSettings.mcpServerEndpoint

No use poolManagementEndpoint. Ese valor es el punto de conexión de administración de sesiones dinámicas, no el punto de conexión del servidor MCP.

Para aprovisionar la infraestructura, ejecute el comando siguiente mediante el CLI de Azure (az):

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

Nota

La implementación puede tardar hasta una hora, en función del número de instancias en espera que solicite. La asignación dinámica del pool de sesiones es el paso más largo.

Configuración y ejecución del agente

Copie el .env.sample archivo del repositorio en .env. Asigne las salidas de implementación de Bicep a las variables de entorno coincidentes:

salida de Bicep Variable del entorno Se usa para
AZURE_AI_PROJECT_ENDPOINT AZURE_AI_PROJECT_ENDPOINT Punto final de proyecto de Foundry.
AZURE_AI_CONNECTION_ID AZURE_AI_CONNECTION_ID Conexión del proyecto cuyo destino es el servidor MCP del intérprete de código personalizado.
MCP_SERVER_URL MCP_SERVER_URL Punto de conexión mcP del grupo de sesiones requerido por las definiciones del cuadro de herramientas.
AZURE_AI_MODEL_DEPLOYMENT_NAME AZURE_AI_MODEL_DEPLOYMENT_NAME Implementación del modelo de agente.

Los ejemplos insertados usan PROJECT_ENDPOINT para AZURE_AI_PROJECT_ENDPOINT y MCP_CONNECTION_ID para AZURE_AI_CONNECTION_ID. El ejemplo mantenido de agente directo resuelve el objetivo MCP a través de la conexión del proyecto y utiliza https://localhost como URL de marcador de posición obligatoria. Para una caja de herramientas, configure MCP_SERVER_URL para la salida mcpServerEndpoint porque MCPToolboxTool requiere server_url o connector_id incluso cuando también se proporcione una conexión de proyecto.

Instale las dependencias de Python y ejecute el ejemplo mantenido con uno de estos pares de comandos:

uv sync
uv run ./main.py

O bien, cree un entorno virtual e instale los requisitos de protección:

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

Ejemplo de código

En el siguiente ejemplo de Python se muestra cómo crear un agente con una herramienta MCP para un intérprete de código personalizado.

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

Salida esperada

Al ejecutar el ejemplo, verá una salida similar a la siguiente:

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

Uso de un agente hospedado

En este ejemplo se usa FoundryChatClient desde Microsoft Agent Framework y se conecta al punto de conexión mcP del cuadro de herramientas mediante 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())

Ejemplo de código

En el siguiente ejemplo de C#, se muestra cómo crear un agente utilizando una herramienta MCP con un intérprete de código personalizado. Para obtener más información sobre cómo trabajar con herramientas de MCP en .NET, consulte el ejemplo de herramienta MCP en el SDK de Azure para .NET repositorio en 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");

Elimine la versión del cuadro de herramientas después de que el agente ya no haga referencia a ella. Consulte Eliminar una versión de la caja de herramientas para la llamada de .NET verificada.

Salida esperada

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

Uso de un agente hospedado

En este ejemplo se usa la integración de Microsoft Agent Framework AddFoundryToolboxes para conectar el agente hospedado al cuadro de herramientas.

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

Ejemplo de código

En el siguiente ejemplo de TypeScript se muestra cómo crear un agente con una herramienta MCP de un intérprete de código personalizado. Para obtener una versión de JavaScript, consulte el ejemplo de herramienta MCP en el repositorio de SDK de Azure para JavaScript en 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);
});

Salida 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 la mayoría de los agentes, agregue herramientas a través de un cuadro de herramientas y adjunte el cuadro de herramientas al agente como una herramienta MCP. El SDK de Java aún no expone una API para crear una toolbox, así que cree la toolbox usando el ejemplo de Python, API de REST, C# o TypeScript, o el portal de Foundry, y después haga referencia a su punto de conexión MCP desde su agente de Java como un McpTool. En el ejemplo siguiente se adjunta al agente el endpoint de MCP de la caja de herramientas que contiene el intérprete de código personalizado.

Agregue la dependencia a pom.xml:

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

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

Salida esperada

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

Requisitos previos

Establezca estas variables de entorno:

  • FOUNDRY_PROJECT_ENDPOINT: dirección URL del punto de conexión del proyecto.
  • AGENT_TOKEN: un token de portador para Foundry.

Obtención de un token de acceso:

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

Ejemplo de código

Creación de un cuadro de herramientas con el intérprete de código personalizado

Agregue el intérprete de código personalizado mediante la creación de un cuadro de herramientas. A continuación, adjunta la caja de herramientas al agente como herramienta de MCP. Para obtener más información, consulte ¿Qué es un cuadro de herramientas?

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

El cuadro de herramientas expone un punto de conexión compatible con MCP en $FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1, donde <version> es la versión devuelta por la llamada anterior.

Creación de una conexión de herramienta remota al cuadro de herramientas

Cree una conexión de proyecto para una herramienta remota que apunte al punto de conexión de la caja de herramientas. Use un token de Entra de usuario para que se transfiera la identidad de quien realiza la llamada (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

Creación de un agente que use el cuadro de herramientas

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

Creación de una respuesta

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

Limpieza

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"

Salida esperada

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

Comprobación de la configuración

Después de aprovisionar la infraestructura y ejecutar el ejemplo:

  1. Confirme que la implementación de Azure se completó correctamente.
  2. Confirme que la muestra se conecta mediante los valores en su archivo .env.
  3. En Microsoft Foundry, compruebe que el agente llama a la herramienta mediante el seguimiento. Para obtener más información, consulte Prácticas más detalladas para usar herramientas en Microsoft Foundry Agent Service.

Solución de problemas

Problema Causa probable Resolución
El registro de funcionalidades sigue pendiente El az feature register comando devuelve Registering el estado . Espere a que se complete el registro (puede tardar entre 15 y 30 minutos). Compruebe el estado con az feature show --namespace Microsoft.App --name SessionPoolsSupportMCP. A continuación, vuelva a ejecutar az provider register -n Microsoft.App.
Error de implementación por falta de permiso Faltan asignaciones de roles necesarias. Para la implementación de la infraestructura, active los roles Foundry Owner y Container Apps ManagedEnvironment Contributor en el grupo de recursos de destino mediante Microsoft Entra PIM. Desactivelos después de la implementación. Para las operaciones del agente, confirme que tiene Foundry User en el proyecto de Foundry.
Error de implementación debido a un problema de región La región seleccionada no admite Azure Container Apps sesiones dinámicas. Pruebe otra región. Consulte Azure Container Apps regions para ver las regiones admitidas.
El agente no llama a la herramienta La conexión MCP no está configurada correctamente o las instrucciones del agente no solicitan el uso de la herramienta. Use el seguimiento en Microsoft Foundry para confirmar la invocación de la herramienta. Verifique que el MCP_SERVER_URL coincida con el punto de conexión de las Container Apps implementadas. Consulte Procedimientos recomendados.
Tiempo de espera de conexión del servidor MCP El grupo de sesiones de Container Apps no se está ejecutando o no tiene ninguna instancia en espera. Compruebe el estado del grupo de sesiones en el portal de Azure. Aumente standbyInstanceCount en la plantilla de Bicep si es necesario.
Error en la ejecución del código en el contenedor Faltan paquetes Python en el contenedor personalizado. Actualice la imagen de contenedor para incluir los paquetes necesarios. Recompile y vuelva a implementar el contenedor.
Error de autenticación al conectarse al servidor MCP Las credenciales de conexión del proyecto no son válidas o expiran. Vuelva a generar las credenciales de conexión y actualice el .env archivo. Compruebe el MCP_PROJECT_CONNECTION_ID formato.

Limitaciones

Las API no admiten directamente la entrada o salida de archivos ni el uso de almacenes de archivos. Para enviar y recibir datos, debe utilizar direcciones URL, como las URL de datos para archivos pequeños y las URL de firma de acceso compartido (SAS) de Azure Blob Service para archivos grandes.

Seguridad

Trate el código generado y sus dependencias como que no son de confianza. Utilice una imagen base aprobada y una lista de paquetes permitidos, ejecute con los recursos de cómputo y los permisos mínimos necesarios, y restrinja el acceso saliente a la red a los destinos necesarios. No monte credenciales de producción ni datos confidenciales en la sesión.

Si usa direcciones URL de SAS para pasar datos dentro o fuera del entorno de ejecución:

  • Utilice tokens SAS de corta duración.
  • No registre direcciones URL de SAS ni almacénelas en el control de código fuente.
  • Limita los permisos al mínimo necesario (por ejemplo, solo lectura o solo escritura).

Limpieza

Para detener la facturación de los recursos aprovisionados, elimine los recursos creados por el despliegue de muestra. Si ha usado un grupo de recursos dedicado para este artículo, elimine el grupo de recursos.