Important
この記事で "(プレビュー)" と付記されている項目は、現在、パブリック プレビュー段階です。 このプレビューはサービス レベル アグリーメントなしで提供されており、運用環境ではお勧めしません。 特定の機能はサポート対象ではなく、機能が制限されることがあります。 詳細については、「Microsoft Azure プレビューの使用条件を参照してください。
カスタム コード インタープリターを使用すると、エージェントによって生成されたPython コードのランタイム環境を完全に制御できます。 カスタム Python パッケージ、コンピューティング リソース、Azure Container Apps環境設定を構成できます。 コード インタープリター コンテナーは、モデル コンテキスト プロトコル (MCP) サーバーを公開します。
エージェント用の組み込みの Code インタープリター ツールが要件を満たしていない場合 (たとえば、特定のPython パッケージ、カスタム コンテナー イメージ、専用コンピューティング リソースが必要な場合) には、カスタム コード インタープリターを使用します。
MCP とエージェントが MCP ツールに接続する方法の詳細については、「 モデル コンテキスト プロトコル サーバーへの接続 (プレビュー)」を参照してください。
利用サポート
この記事では、Azure CLIと実行可能なサンプル プロジェクトを使用します。
✔️ (GA) は一般提供を示し、✔️(プレビュー) はパブリック プレビューを示し、ダッシュ (-) は機能が使用できないことを示します。
| Microsoft Foundry のサポート | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | 基本エージェントのセットアップ | 標準エージェントのセットアップ |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ (GA) | ✔️ (プレビュー) | ✔️ (GA) | ✔️ (プレビュー) | ✔️ (GA) | - | ✔️ |
エージェント ツールに対する最新の SDK と API のサポートについては、 Microsoft Foundry Agent Service でツールを使用するためのベスト プラクティスを参照してください。
SDK のサポート
カスタム コード インタープリターでは、MCP ツールの種類が使用されます。 MCP ツールをサポートするすべての SDK で、カスタム コード インタープリター エージェントを作成できます。 .NET SDK と Java SDK は現在プレビュー段階です。 インフラストラクチャのプロビジョニング手順 (Azure CLI、Bicep) については、「カスタム コード インタープリターを使用してエージェントを作成するを参照してください。
[前提条件]
- Azure CLI バージョン 2.60.0 以降。
- (省略可能) uvを使用すると、Pythonパッケージの管理を高速化できます。
- 次のロールの割り当てを持つAzureサブスクリプションとリソース グループ。
- Azure AI Foundry SDK。 インストールについては、 クイック スタート を参照してください。
開始する前に
この手順では、AzureのインフラストラクチャとAzure Container Appsリソースをプロビジョニングします。 デプロイする前に、組織の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 フォルダーに移動します。
インフラストラクチャをプロビジョニングする
インフラストラクチャをプロビジョニングするには、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 にコピーし、デプロイ出力から値を設定します。 これらの値は、リソース グループのAzure ポータルで確認できます。
uv sync または pip install を使用して、Pythonの依存関係をインストールします。 最後に、 ./main.pyを実行します。
コード例
次のPythonサンプルは、カスタム コード インタープリター MCP ツールを使用してエージェントを作成する方法を示しています。
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, MCPTool
# 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()
# Configure the custom code interpreter MCP tool
custom_code_interpreter = MCPTool(
server_label="custom-code-interpreter",
server_url=MCP_SERVER_URL,
project_connection_id=MCP_CONNECTION_ID,
)
# Create an agent with the custom code interpreter
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=[custom_code_interpreter],
),
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)
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
コード例
次の C# サンプルは、カスタム コード インタープリター MCP ツールを使用してエージェントを作成する方法を示しています。 .NETで MCP ツールを使用する方法の詳細については、GitHubの .NET リポジトリのAzure SDKの MCP ツール のサンプルを参照してください。
using Azure.AI.Projects;
using Azure.AI.Projects.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());
// Create agent with custom code interpreter MCP tool
// Code runs in a sandboxed Azure Container Apps session
McpTool tool = ResponseTool.CreateMcpTool(
serverLabel: "custom-code-interpreter",
serverUri: new Uri(mcpServerUrl));
tool.ProjectConnectionId = mcpConnectionId;
PromptAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful assistant that can run Python code to analyze data and solve problems.",
Tools = { tool }
};
AgentVersion agent = projectClient.Agents.CreateAgentVersion(
agentName: "CustomCodeInterpreterAgent",
options: new(agentDefinition));
Console.WriteLine($"Agent created: {agent.Name} (version {agent.Version})");
// Create a response using the agent
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agent.Name);
ResponseResult response = responseClient.CreateResponse(
new([ResponseItem.CreateUserMessageItem("Calculate the factorial of 10 using Python.")]));
Console.WriteLine(response.GetOutputText());
// Clean up
projectClient.Agents.DeleteAgentVersion(
agentName: agent.Name,
agentVersion: agent.Version);
Console.WriteLine("Agent deleted");
想定される出力
Agent created: CustomCodeInterpreterAgent (version 1)
The factorial of 10 is 3,628,800.
Agent deleted
コード例
次の 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();
// Create agent with custom code interpreter MCP tool
// The custom code interpreter uses require_approval: "never" because code
// runs in a sandboxed Azure Container Apps session
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: "custom-code-interpreter",
server_url: MCP_SERVER_URL,
require_approval: "never",
},
],
});
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: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`Response: ${response.output_text}`);
// Clean up
await project.agents.deleteVersion(agent.name, agent.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
依存関係を pom.xmlに追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.0.0-beta.1</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.McpTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.core.util.BinaryData;
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 mcpServerUrl = "https://your-mcp-server-url";
// Optional: set to your project connection ID if your MCP server requires authentication
String mcpConnectionId = "your-mcp-connection-id";
// Create clients to call Foundry API
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// Create custom code interpreter MCP tool
// Uses require_approval: "never" because code runs in a sandboxed Container Apps session
McpTool customCodeInterpreter = new McpTool("custom-code-interpreter")
.setServerUrl(mcpServerUrl)
.setProjectConnectionId(mcpConnectionId)
.setRequireApproval(BinaryData.fromString("\"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(customCodeInterpreter));
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.createWithAgent(
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)
コード例
1. カスタム コード インタープリターを使用してエージェントを作成する
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": "custom-code-interpreter",
"server_url": "<MCP_SERVER_URL>",
"project_connection_id": "<MCP_PROJECT_CONNECTION_ID>",
"require_approval": "never"
}
]
}
}'
2. 応答を作成する
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."
}'
3. クリーンアップ
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/CustomCodeInterpreterAgent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
想定される出力
{
"id": "resp_xxxxxxxxxxxx",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "The factorial of 10 is 3,628,800."
}
]
}
]
}
セットアップを確認する
インフラストラクチャをプロビジョニングし、サンプルを実行した後:
- Azureデプロイが正常に完了したことを確認します。
-
.envファイル内の値を使用して、サンプルが接続されたことを確認します。 - Microsoft Foundry で、エージェントがトレースを使用してツールを呼び出すかどうかを確認します。 詳細については、「 Microsoft Foundry Agent Service でツールを使用するためのベスト プラクティス」を参照してください。
トラブルシューティング
| 問題点 | 想定される原因 | 解決策 |
|---|---|---|
| 機能の登録がまだ保留中です |
az feature register コマンドはRegistering状態を返します。 |
登録が完了するまで待ちます (15 ~ 30 分かかる場合があります)。
az feature show --namespace Microsoft.App --name SessionPoolsSupportMCPで状態を確認します。 次に、 az provider register -n Microsoft.App をもう一度実行します。 |
| アクセス許可エラーでデプロイが失敗する | 必要な役割の割り当てが見つかりません。 | サブスクリプションまたはリソース グループに Azure AI 所有者 ロールと Container Apps ManagedEnvironment Contributor ロールがあることを確認します。 |
| デプロイがリージョン エラーで失敗する | 選択したリージョンでは、動的セッション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 をログに記録したり、ソース管理に保存したりしないでください。
- アクセス許可の対象を最低限に制限します(例:読み取り専用や書き込み専用)。
クリーンアップ
プロビジョニングされたリソースの課金を停止するには、サンプル デプロイによって作成されたリソースを削除します。 この記事で専用のリソース グループを使用した場合は、リソース グループを削除します。