エージェント用のカスタム コード インタープリター ツール (プレビュー)

重要

この記事でマークされている項目 (プレビュー) は、現在パブリック プレビュー段階です。 このプレビューはサービス レベル アグリーメントなしで提供されており、運用環境のワークロードにはお勧めしません。 特定の機能がサポートされていないか、機能が制限されている可能性があります。 詳細については、「Microsoft Azure プレビューの使用条件を参照してください。

カスタム コード インタープリターを使用すると、エージェントによって生成されたPython コードのランタイム環境を完全に制御できます。 カスタム Python パッケージ、コンピューティング リソース、Azure Container Apps環境設定を構成できます。 コード インタープリター コンテナーは、モデル コンテキスト プロトコル (MCP) サーバーを公開します。

エージェント用の組み込みの Code インタープリター ツールが要件を満たしていない場合 (たとえば、特定のPython パッケージ、カスタム コンテナー イメージ、専用コンピューティング リソースが必要な場合) には、カスタム コード インタープリターを使用します。

MCP とエージェントが MCP ツールに接続する方法の詳細については、「 モデル コンテキスト プロトコル サーバーへの接続 (プレビュー)」を参照してください。

Tip

ツールボックスを使用してこのツールを追加することを検討 してください。 ツールボックスを使用すると、エージェントとランタイム間でツールを再利用できるほか、マネージド MCP エンドポイントを介して資格情報の管理、バージョン管理、ポリシーの適用を一元化できます。 ツールボックスの クイック スタートを参照してください。

前提 条件

  • Azure CLI バージョン 2.60.0 以降。

  • 保守対象のサンプル プロジェクトには、Python 3.12 以降が必要です。

  • (省略可能) uvを使用すると、Pythonパッケージの管理を高速化できます。

  • 次のロールの割り当てを持つAzureサブスクリプションとリソース グループ。

    • プロビジョニング後にエージェントを構成して実行するための Foundry プロジェクトの Foundry ユーザー

      重要

      Foundry RBAC ロールの名前が最近変更されました。 Foundry User, Foundry Owner, Foundry Account Owner、および Foundry Project Manager は、以前は、AZURE AI ユーザー、Azure AI 所有者、Azure AI アカウント所有者、および AZURE AI Project Manager という名前でした。 名前の変更がロールアウトされている間、以前の名前が表示される場合があります。ロール ID とコア アクセス許可は、名前の変更によって変更されません。

    • サンプル デプロイで Foundry リソースとプロジェクト接続が作成される間のみ、対象のリソース グループに対する Foundry Owner が必要です。

    • Container Apps ManagedEnvironment Contributor は、サンプル デプロイによって Container Apps 環境が作成される間のみ、対象のリソース グループに対して必要です。

    Microsoft Entra Privileged Identity Management (PIM) を通じてプロビジョニング ロールをジャスト イン タイムでアクティブ化し、デプロイ後に非アクティブ化します。 日常のエージェント開発者とランタイム ユーザーは、これらのプロビジョニング ロールを必要としません。

  • Microsoft Foundry SDK。 インストールについては、 クイック スタート を参照してください。

  • Foundry Agent Service と Azure Container Apps 動的セッションの両方でサポートされているリージョン。 Azure Container Apps の動的セッション リージョンを参照してください。

使用サポート

この記事では、Azure CLIと実行可能なサンプル プロジェクトを使用します。

次の表に、SDK とセットアップのサポートを示します。

Microsoft Foundry のサポート Python SDK C# SDK JavaScript SDK Java SDK REST API 基本的なエージェントのセットアップ 標準エージェントのセットアップ
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ - ✔️

エージェント ツールに対する最新の SDK と API のサポートについては、「 Foundry Agent Service Microsoft でツールを使用するためのベスト プラクティスを参照してください。

SDK のサポート

カスタム コード インタープリターでは、MCP ツールの種類が使用されます。 MCP ツールをサポートするすべての SDK で、カスタム コード インタープリター エージェントを作成できます。 .NET SDK は現在プレビュー段階です。 インフラストラクチャのプロビジョニング手順 (Azure CLI、Bicep) については、「カスタム コード インタープリターを使用してエージェントを作成するを参照してください。

開始する前に

この手順では、Azure Container Apps リソースを含む Azure インフラストラクチャをプロビジョニングします。 デプロイする前に、組織のAzureコストとガバナンスの要件を確認します。

カスタム コード インタープリターを使用してエージェントを作成する

次の手順では、インフラストラクチャをプロビジョニングし、カスタム コード インタープリター MCP サーバーを使用するエージェントを作成する方法を示します。 インフラストラクチャのセットアップは、すべての言語に適用されます。 言語固有のコード サンプルを次に示します。

プレビュー機能を登録する

Azure Container Apps動的セッションの MCP サーバー機能を登録します。

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

サンプル コードを取得する

GitHub リポジトリで サンプル コードを複製し、ターミナルの 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

メモ

デプロイには、要求したスタンバイ インスタンスの数に応じて、最大 1 時間かかる場合があります。 動的セッション プールの割り当ては、最も長い手順です。

エージェントを構成して実行する

リポジトリから .env.sample ファイルを .envにコピーします。 Bicep のデプロイ出力を対応する環境変数にマッピングします。

Bicep の出力 環境変数 用途
AZURE_AI_PROJECT_ENDPOINT AZURE_AI_PROJECT_ENDPOINT Foundry プロジェクト エンドポイント。
AZURE_AI_CONNECTION_ID AZURE_AI_CONNECTION_ID カスタム コード インタープリター MCP サーバーをターゲットとする接続をProjectします。
MCP_SERVER_URL MCP_SERVER_URL ツールボックス定義に必要なセッション プール MCP エンドポイント。
AZURE_AI_MODEL_DEPLOYMENT_NAME AZURE_AI_MODEL_DEPLOYMENT_NAME エージェントモデルのデプロイ。

インラインの例では、PROJECT_ENDPOINTAZURE_AI_PROJECT_ENDPOINTを使用し、MCP_CONNECTION_IDAZURE_AI_CONNECTION_IDします。 管理されている直接エージェント サンプルは、プロジェクト接続を介して MCP ターゲットを解決し、必要なプレースホルダー URL として https://localhost を使用します。 ツールボックスの場合は、プロジェクト接続も指定した場合でも、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を使用してツールボックス MCP エンドポイントに接続します。

import asyncio

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.identity import AzureCliCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MCPToolboxTool

PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
MCP_SERVER_URL = "https://your-mcp-server-url"
# Optional: set to your project connection ID if your MCP server requires authentication
MCP_CONNECTION_ID = "your-mcp-connection-id"


async def main() -> None:
    credential = AzureCliCredential()

    # 1. Create the custom code interpreter MCP tool and add it to a toolbox. Using a toolbox is the
    #    recommended way to give agents tools: curate tools once and reuse the
    #    toolbox across agents. See /azure/foundry/agents/concepts/toolbox-overview
    project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
    toolbox = project.toolboxes.create_version(
        name="custom-code-interpreter-toolbox",
        description="Toolbox with the custom code interpreter MCP server",
        tools=[
            MCPToolboxTool(
                server_label="custom-code-interpreter",
                server_url=MCP_SERVER_URL,
                project_connection_id=MCP_CONNECTION_ID,
            )
        ],
    )

    # 2. The toolbox exposes an MCP-compatible endpoint.
    TOOLBOX_MCP_URL = (
        f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
        f"/versions/{toolbox.version}/mcp?api-version=v1"
    )

    # 3. Attach the toolbox to the hosted agent as an MCP tool.
, timeout=120.0)
    toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)

agent = Agent(
        client=FoundryChatClient(credential=credential),
        instructions="You are a helpful assistant that can run Python code to analyze data and solve problems.",
        tools=[toolbox_tool],
    )

    result = await agent.run("Calculate the factorial of 10 using Python.")
    print(result.text)


    project.toolboxes.delete_toolbox_version(
      toolbox_name=toolbox.name,
      version=toolbox.version,
    )


if __name__ == "__main__":
    asyncio.run(main())

コード例

次の C# サンプルは、カスタム コード インタープリター MCP ツールを使用してエージェントを作成する方法を示しています。 .NETで MCP ツールを使用する方法の詳細については、GitHubの .NET リポジトリのAzure SDKの MCP ツール のサンプルを参照してください。

using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var mcpServerUrl = "https://your-mcp-server-url";
// Optional: set to your project connection ID if your MCP server requires authentication
var mcpConnectionId = "your-mcp-connection-id";

// Create project client to call Foundry API
AIProjectClient projectClient = new(
    endpoint: new Uri(projectEndpoint),
    tokenProvider: new DefaultAzureCredential());

// Add the custom code interpreter MCP server to a toolbox. Using a toolbox is the
// recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
// Code runs in a sandboxed Azure Container Apps session.
McpTool customCodeInterpreter = ResponseTool.CreateMcpTool(
    serverLabel: "custom-code-interpreter",
    serverUri: new Uri(mcpServerUrl));
customCodeInterpreter.ProjectConnectionId = mcpConnectionId;

ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
    .GetAgentToolboxes().CreateToolboxVersion(
        toolboxName: "custom-code-interpreter-toolbox",
        tools: [ProjectsAgentTool.AsProjectTool(customCodeInterpreter)],
        description: "Toolbox with the custom code interpreter MCP server");

// The toolbox exposes an MCP-compatible endpoint.
var toolboxMcpUrl = new Uri(
    $"{projectEndpoint}/toolboxes/{toolboxVersion.Name}" +
    $"/versions/{toolboxVersion.Version}/mcp?api-version=v1");

// Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
//    azd ai connection create custom-code-interpreter-toolbox-conn \
//      --kind remote-tool \
//      --target "<toolboxMcpUrl>" \
//      --auth-type user-entra-token \
//      --audience https://ai.azure.com
var toolboxConnectionName = "custom-code-interpreter-toolbox-conn";

McpTool toolboxTool = ResponseTool.CreateMcpTool(
    serverLabel: "toolbox",
    serverUri: toolboxMcpUrl,
    toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
        GlobalMcpToolCallApprovalPolicy.NeverRequireApproval));
toolboxTool.ProjectConnectionId = toolboxConnectionName;

DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
    Instructions = "You are a helpful assistant that can run Python code to analyze data and solve problems.",
    Tools = { toolboxTool }
};

AgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName: "CustomCodeInterpreterAgent",
    options: new(agentDefinition));

Console.WriteLine($"Agent created: {agent.Name} (version {agent.Version})");

// Create a response using the agent
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agent.Name);

ResponseResult response = responseClient.CreateResponse(
    new([ResponseItem.CreateUserMessageItem("Calculate the factorial of 10 using Python.")]));

Console.WriteLine(response.GetOutputText());

// Clean up
projectClient.AgentAdministrationClient.DeleteAgentVersion(
    agentName: agent.Name,
    agentVersion: agent.Version);
Console.WriteLine("Agent deleted");

エージェントが参照しなくなったツールボックスバージョンを削除します。 検証済みの.NET呼び出しについては、「ツールボックスのバージョンを削除する」を参照してください。

予期される出力

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

ホストされているエージェントを使用する

このサンプルでは、Microsoft Agent Framework AddFoundryToolboxes統合を使用して、ホストされているエージェントをツールボックスに接続します。

using System;
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;

const string AgentInstructions = "You are a helpful assistant that can run Python code to analyze data and solve problems.";
const string AgentName = "CustomCodeInterpreterAgent";

string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
    ?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";
string mcpServerUrl = "https://your-mcp-server-url";
string mcpConnectionId = "your-mcp-connection-id";

DefaultAzureCredential credential = new();

// 1. Create the custom code interpreter MCP tool and add it to a toolbox. Using a toolbox is the
//    recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(
    endpoint: new Uri(projectEndpoint),
    tokenProvider: credential);
McpTool customCodeInterpreter = ResponseTool.CreateMcpTool(
    serverLabel: "custom-code-interpreter",
    serverUri: new Uri(mcpServerUrl));
customCodeInterpreter.ProjectConnectionId = mcpConnectionId;
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
    .GetAgentToolboxes().CreateToolboxVersion(
        toolboxName: "custom-code-interpreter-toolbox",
        tools: [ProjectsAgentTool.AsProjectTool(customCodeInterpreter)],
        description: "Toolbox with the custom code interpreter MCP server");

// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
    model: deploymentName,
    instructions: "You are a helpful assistant with access to the toolbox tools.",
    name: "hosted-toolbox-agent");

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);

var app = builder.Build();
app.MapFoundryResponses();
app.Run();

コード例

次の TypeScript サンプルは、カスタム コード インタープリター MCP ツールを使用してエージェントを作成する方法を示しています。 JavaScript バージョンについては、GitHubの 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> は前の呼び出しによって返されたバージョンです。

ツールボックスへのリモート ツール接続を作成する

ツールボックス エンドポイントを指すリモート ツール プロジェクト接続を作成します。 呼び出し元の ID が渡されるようにユーザー 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 Agent Service におけるツール使用のベストプラクティス」を参照してください。

トラブルシューティング

問題 考えられる原因 解決方法
機能の登録がまだ保留中です az feature register コマンドはRegistering状態を返します。 登録が完了するまで待ちます (15 ~ 30 分かかる場合があります)。 az feature show --namespace Microsoft.App --name SessionPoolsSupportMCPで状態を確認します。 その後、az provider register -n Microsoft.App をもう一度実行します。
アクセス許可エラーでデプロイが失敗する 必要なロールの割り当てが見つかりません。 インフラストラクチャのデプロイでは、ターゲット リソース グループの Foundry 所有者Container Apps ManagedEnvironment 共同作成者を、MICROSOFT ENTRA PIM を介してアクティブ化します。 デプロイ後に非アクティブ化します。 エージェント操作の場合は、 Foundry プロジェクトに Foundry ユーザー があることを確認します。
デプロイがリージョン エラーで失敗する 選択したリージョンでは、動的セッションAzure Container Appsサポートされていません。 別のリージョンを試してください。 サポートされているリージョンについては、Azure Container Apps リージョンを参照してください。
エージェントがツールを呼び出さない MCP 接続が正しく構成されていないか、エージェントの指示でツールの使用を求められません。 Microsoft Foundry でトレースを使用して、ツールの呼び出しを確認します。 MCP_SERVER_URLがデプロイされた Container Apps エンドポイントと一致するかどうかを確認します。 ベスト プラクティスを参照してください。
MCP サーバー接続タイムアウト Container Apps セッション プールが実行されていないか、スタンバイ インスタンスがありません。 Azure ポータルでセッション プールの状態を確認します。 必要に応じて、Bicep テンプレートで standbyInstanceCount を増やします。
コンテナーでのコードの実行が失敗する カスタム コンテナー Pythonパッケージがありません。 必要なパッケージを含むようにコンテナー イメージを更新します。 コンテナーを再構築して再デプロイします。
MCP サーバーへの接続に関する認証エラー プロジェクト接続の資格情報が無効であるか、有効期限が切れています。 接続資格情報を再生成し、 .env ファイルを更新します。 MCP_PROJECT_CONNECTION_ID形式を確認します。

制限

API は、ファイルの入力や出力、またはファイル ストアの使用を直接サポートしていません。 データの送受信を行うには、小さなファイルにはデータURLを、大きなファイルにはAzure Blob Serviceの共有アクセス署名(SAS)URLなどを使用する必要があります。

セキュリティ

生成されたコードとその依存関係を信頼されていないものとして扱います。 承認済みの基本イメージとパッケージ許可リストを使用し、必要最小限のコンピューティングとアクセス許可で実行し、必要な宛先への送信ネットワーク アクセスを制限します。 機密データや運用資格情報をセッションにマウントしないでください。

SAS URL を使用してランタイムにデータを渡す場合、またはランタイムからデータを渡す場合:

  • 有効期間の短い SAS トークンを使用します。
  • SAS URL をログに記録したり、ソース管理に保存したりしないでください。
  • アクセス許可のスコープを最低限必要に限るようにしてください (例えば、読み取り専用または書き込み専用など)。

クリーンアップ

プロビジョニングされたリソースの課金を停止するには、サンプル デプロイによって作成されたリソースを削除します。 この記事で専用のリソース グループを使用した場合は、リソース グループを削除します。