Notatka
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
Ważne
Elementy oznaczone (wersja zapoznawcza) w tym artykule są obecnie dostępne w publicznej wersji zapoznawczej. Ta wersja zapoznawcza jest udostępniana bez umowy dotyczącej poziomu usług i nie zalecamy korzystania z niej w przypadku obciążeń produkcyjnych. Niektóre funkcje mogą nie być obsługiwane lub mogą mieć ograniczone możliwości. Aby uzyskać więcej informacji, zobacz Wygólne warunki użytkowania Microsoft Azure Previews.
Niestandardowy interpreter kodu zapewnia pełną kontrolę nad środowiskiem uruchomieniowym dla wygenerowanego przez agenta kodu Python. Można skonfigurować niestandardowe pakiety Python, zasoby obliczeniowe i środowisko Azure Container Apps. Kontener interpretera kodu uwidacznia serwer MCP (Model Context Protocol).
Użyj niestandardowego interpretera kodu, gdy wbudowane narzędzie interpretera Code dla agentów nie spełnia wymagań — na przykład gdy potrzebujesz określonych pakietów Python, niestandardowych obrazów kontenerów lub dedykowanych zasobów obliczeniowych.
Aby uzyskać więcej informacji na temat programu MCP i sposobu łączenia agentów z narzędziami MCP, zobacz Łączenie z serwerami protokołu kontekstowego modelu (wersja zapoznawcza).
Tip
Rozważ dodanie tego narzędzia za pomocą przybornika. Korzystając z zestawu narzędzi, można ponownie wykorzystywać narzędzie w różnych agentach i środowiskach uruchomieniowych, a także centralizować zarządzanie poświadczeniami, wersjonowanie i egzekwowanie zasad za pośrednictwem zarządzanego punktu końcowego MCP. Zobacz przewodnik szybkiego startu zestawu narzędzi.
Wymagania wstępne
Azure CLI w wersji 2.60.0 lub nowszej.
Python 3.12 lub nowszy dla obsługiwanego przykładowego projektu.
(Opcjonalnie) uv w celu szybszego zarządzania pakietami Python.
Subskrypcja Azure i grupa zasobów z następującymi przypisaniami ról:
użytkownik Foundry w projekcie Foundry do konfigurowania i uruchamiania agenta po zakończeniu aprowizacji.
Ważne
Niedawno zmieniono nazwy ról RBAC w usłudze Foundry. Użytkownik Foundry, właściciel Foundry, właściciel konta Foundry i menedżer projektu Foundry były wcześniej nazywane odpowiednio użytkownikiem Azure AI, właścicielem Azure AI, właścicielem konta Azure AI i menedżerem projektu Azure AI. Poprzednie nazwy mogą być nadal widoczne w niektórych miejscach, podczas gdy zmiana nazwy jest wdrażana. Identyfikatory ról i uprawnienia podstawowe są niezmienione przez zmianę nazwy.
Foundry Owner tylko w docelowej grupie zasobów, podczas gdy przykładowe wdrożenie tworzy zasoby usługi Foundry i połączenie z projektem.
Współautor środowiska zarządzanego usługi Container Apps tylko dla docelowej grupy zasobów, gdy przykładowe wdrożenie tworzy środowisko usługi Container Apps.
Aktywuj role aprowizacji na czas przy użyciu Microsoft Entra Privileged Identity Management (PIM), a po wdrożeniu wyłącz je. Deweloperzy agentów i użytkownicy środowiska uruchomieniowego na co dzień nie potrzebują tych ról związanych z aprowizacją.
Pakiet SDK dla Microsoft Foundry. Zobacz przewodnik Szybki start dotyczący instalacji.
Region obsługiwany zarówno przez usługę Foundry Agent Service, jak i Azure Container Apps Dynamic Sessions. Zobacz regiony usługi Dynamic Sessions w usłudze Azure Container Apps.
Wsparcie użytkowania
W tym artykule użyto Azure CLI i przykładowego projektu możliwego do uruchomienia.
W poniższej tabeli przedstawiono zestaw SDK i obsługę konfiguracji.
| Obsługa Microsoft Foundry | zestaw SDK Python | Zestaw SDK języka C# | Zestaw SDK dla języka JavaScript | zestaw SDK Java | interfejs API REST | Konfiguracja agenta podstawowego | Konfiguracja agenta standardowego |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | - | ✔️ |
Aby uzyskać najnowszą obsługę zestawu SDK i interfejsu API dla narzędzi agentów, zobacz Najlepsze praktyki dotyczące używania narzędzi w usłudze Microsoft Foundry Agent.
Obsługa zestawu SDK
Interpreter niestandardowego kodu używa narzędzia typu MCP. Każdy zestaw SDK obsługujący narzędzia MCP może utworzyć niestandardowego agenta interpretera kodu. Zestaw SDK .NET jest obecnie w wersji zapoznawczej. Aby zapoznać się z krokami aprowizacji infrastruktury (Azure CLI, Bicep), zobacz Utwórz agenta z niestandardowym interpreterem kodu.
Przed rozpoczęciem
Ta procedura tworzy infrastrukturę Azure, w tym zasoby Azure Container Apps. Przed wdrożeniem przejrzyj wymagania dotyczące kosztów Azure i ładu w organizacji.
Tworzenie agenta z niestandardowym interpreterem kodu
W poniższych krokach pokazano, jak aprowizować infrastrukturę i utworzyć agenta korzystającego z niestandardowego serwera MCP interpretera kodu. Konfiguracja infrastruktury ma zastosowanie do wszystkich języków. Poniżej znajdują się przykłady kodu specyficzne dla języka.
Rejestrowanie funkcji w wersji zapoznawczej
Zarejestruj funkcję serwera MCP na potrzeby sesji dynamicznych Azure Container Apps:
az feature register --namespace Microsoft.App --name SessionPoolsSupportMCP
az provider register -n Microsoft.App
Pobieranie przykładowego kodu
Sklonuj kod sample w repozytorium GitHub i przejdź do folderu samples/python/prompt-agents/code-interpreter-custom w terminalu.
Przygotuj infrastrukturę
Obsługiwany przykład z agentem bezpośrednim przechowuje punkt końcowy MCP dla puli sesji w połączeniu projektu. Definicje zestawu narzędzi również wymagają endpointu w postaci server_url. Dodaj te dane wyjściowe do sklonowanego infra.bicep pliku:
output MCP_SERVER_URL string = sessionPool.properties.mcpServerSettings.mcpServerEndpoint
Nie używaj poolManagementEndpoint. Ta wartość to punkt końcowy zarządzania sesjami dynamicznymi, a nie punkt końcowy serwera MCP.
Aby aprowizować infrastrukturę, uruchom następujące polecenie przy użyciu Azure CLI (az):
az deployment group create \
--name custom-code-interpreter \
--subscription <your_subscription> \
--resource-group <your_resource_group> \
--template-file ./infra.bicep
Uwaga
Wdrożenie może potrwać do jednej godziny, w zależności od liczby wystąpień rezerwowych, które zamawiasz. Alokacja puli sesji dynamicznej jest najdłuższym krokiem.
Konfigurowanie i uruchamianie agenta
Skopiuj plik .env.sample z repozytorium do folderu .env. Zamapuj dane wyjściowe wdrożenia Bicep na pasujące zmienne środowiskowe:
| dane wyjściowe Bicep | Zmienna środowiskowa | Używany do |
|---|---|---|
AZURE_AI_PROJECT_ENDPOINT |
AZURE_AI_PROJECT_ENDPOINT |
Punkt końcowy projektu Foundry. |
AZURE_AI_CONNECTION_ID |
AZURE_AI_CONNECTION_ID |
Połączenie projektu, którego celem jest niestandardowy serwer MCP interpretatora kodu. |
MCP_SERVER_URL |
MCP_SERVER_URL |
Punkt końcowy MCP puli sesji wymagany przez definicje zestawu narzędzi. |
AZURE_AI_MODEL_DEPLOYMENT_NAME |
AZURE_AI_MODEL_DEPLOYMENT_NAME |
Wdrażanie modelu agenta. |
W przykładach śródtekstowych używa się PROJECT_ENDPOINT dla AZURE_AI_PROJECT_ENDPOINT oraz MCP_CONNECTION_ID dla AZURE_AI_CONNECTION_ID. Utrzymywany przykład agenta bezpośredniego ustala element docelowy MCP przez połączenie projektu i używa https://localhost jako wymaganego zastępczego adresu URL. W przypadku zestawu narzędzi ustaw MCP_SERVER_URL na dane wyjściowe mcpServerEndpoint, ponieważ MCPToolboxTool wymaga server_url lub connector_id, nawet jeśli podasz również połączenie projektu.
Zainstaluj zależności języka Python i uruchom utrzymywany przykład za pomocą jednej z poniższych par poleceń:
uv sync
uv run ./main.py
Możesz też utworzyć środowisko wirtualne i zainstalować wymagania zaewidencjonowane:
python -m venv .venv
./.venv/bin/pip install -r requirements.txt
./.venv/bin/python ./main.py
Przykład kodu
W poniższym przykładzie Python pokazano, jak utworzyć agenta za pomocą niestandardowego narzędzia MCP interpretera kodu:
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")
Oczekiwane dane wyjściowe
Po uruchomieniu przykładu zobaczysz dane wyjściowe podobne do następujących:
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
Korzystanie z hostowanego agenta
W tym przykładzie użyto FoundryChatClient z platformy Microsoft Agent Framework i połączono się z punktem końcowym MCP zestawu narzędzi za pomocą 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())
Przykład kodu
W poniższym przykładzie w języku C# pokazano, jak utworzyć agenta za pomocą niestandardowego narzędzia MCP interpretera kodu. Aby uzyskać więcej informacji na temat pracy z narzędziami MCP w .NET, zobacz przykład narzędzia MCP w repozytorium Azure SDK dla .NET w 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");
Usuń wersję zestawu narzędzi, gdy agent przestanie się do niej odwoływać. Zobacz Usuwanie wersji przybornika dla zweryfikowanego wywołania .NET.
Oczekiwane dane wyjściowe
Agent created: CustomCodeInterpreterAgent (version 1)
The factorial of 10 is 3,628,800.
Agent deleted
Korzystanie z hostowanego agenta
W tym przykładzie użyto integracji Microsoft Agent Framework AddFoundryToolboxes, aby połączyć hostowanego agenta z zestawem narzędzi.
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();
Przykład kodu
W poniższym przykładzie języka TypeScript pokazano, jak utworzyć agenta za pomocą niestandardowego narzędzia MCP interpretera kodu. Aby zapoznać się z wersją języka JavaScript, zobacz przykład narzędzia MCP w repozytorium Azure SDK dla języka JavaScript w 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);
});
Oczekiwane dane wyjściowe
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
Zalecane: W przypadku większości agentów dodaj narzędzia za pomocą przybornika i dołącz przybornik do agenta jako narzędzie MCP. Java SDK nie udostępnia jeszcze interfejsu API do tworzenia zestawu narzędzi, więc utwórz go na podstawie przykładu w Python, REST API, C# lub TypeScript, albo w portalu Foundry, a następnie odwołaj się do jego punktu końcowego MCP w agencie Java jako McpTool. Poniższy przykład dołącza do agenta punkt końcowy MCP toolboxa, który zawiera niestandardowy interpreter kodu.
Dodaj zależność do elementu pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.4.0</version>
</dependency>
Przykład kodu
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");
}
}
Oczekiwane dane wyjściowe
Agent created: CustomCodeInterpreterAgent (version 1)
Response: The factorial of 10 is 3,628,800.
Agent deleted
Wymagania wstępne
Ustaw następujące zmienne środowiskowe:
-
FOUNDRY_PROJECT_ENDPOINT: adres URL punktu końcowego projektu. -
AGENT_TOKEN: token elementu nośnego dla rozwiązania Foundry.
Uzyskiwanie tokenu dostępu:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Przykład kodu
Utwórz zestaw narzędzi z niestandardowym interpreterem kodu
Dodaj niestandardowy interpreter kodu, tworząc zestaw narzędzi. Następnie podłącz zestaw narzędzi do swojego agenta jako narzędzie MCP. Aby uzyskać więcej informacji, zobacz Co to jest przybornik?
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"
}
]
}'
Zestaw narzędzi udostępnia zgodny z MCP punkt końcowy pod adresem $FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1, gdzie <version> to wersja zwrócona przez poprzednie wywołanie.
Utwórz połączenie z narzędziem zdalnym w przyborniku narzędzi
Utwórz połączenie projektu remote-tool wskazujące na punkt końcowy toolbox. Użyj tokenu Entra użytkownika, aby tożsamość wywołującego została przekazana (odbiorcy 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
Utwórz agenta, który używa zestawu narzędzi
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"
}
]
}
}'
Tworzenie odpowiedzi
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."
}'
Czyszczenie
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"
Oczekiwane dane wyjściowe
{
"id": "resp_xxxxxxxxxxxx",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "The factorial of 10 is 3,628,800."
}
]
}
]
}
Weryfikowanie konfiguracji
Po dostarczeniu infrastruktury i uruchomieniu przykładowego programu:
- Upewnij się, że wdrożenie Azure zostało ukończone pomyślnie.
- Potwierdź, że próba łączy się, używając wartości z pliku
.env. - W Microsoft Foundry sprawdź, czy Twój agent wywołuje narzędzie, używając śledzenia. Aby uzyskać więcej informacji, zobacz Najlepsze praktyki korzystania z narzędzi w usłudze Microsoft Foundry Agent.
Rozwiązywanie problemów
| Kwestia | Prawdopodobna przyczyna | Rozdzielczość |
|---|---|---|
| Rejestracja funkcji wciąż oczekuje | Polecenie az feature register zwraca Registering stan. |
Poczekaj na ukończenie rejestracji (może upłynąć 15–30 minut). Sprawdź stan za pomocą az feature show --namespace Microsoft.App --name SessionPoolsSupportMCP. Następnie uruchom ponownie az provider register -n Microsoft.App. |
| Wdrażanie kończy się niepowodzeniem z powodu błędu uprawnień | Brak wymaganych przypisań ról. | Aby wdrożyć infrastrukturę, aktywuj role Foundry Owner i Container Apps ManagedEnvironment Contributor dla docelowej grupy zasobów za pośrednictwem Microsoft Entra PIM. Dezaktywuj je po wdrożeniu. W przypadku operacji agenta upewnij się, że użytkownik usługi Foundry znajduje się w projekcie Foundry. |
| Wdrażanie kończy się niepowodzeniem z powodu błędu regionu | Wybrany region nie obsługuje Azure Container Apps sesji dynamicznych. | Spróbuj użyć innego regionu. Zobacz regiony Azure Container Apps w celu sprawdzenia obsługiwanych regionów. |
| Agent nie uruchamia narzędzia | Połączenie MCP nie jest poprawnie skonfigurowane lub instrukcje agenta nie monitują o użycie narzędzia. | Skorzystaj z funkcji śledzenia w Microsoft Foundry, aby potwierdzić wywołanie narzędzia. Sprawdź, czy MCP_SERVER_URL pasuje do wdrożonego punktu końcowego aplikacji Container Apps. Zobacz Najlepsze rozwiązania. |
| Limit czasu połączenia serwera MCP | Pula sesji usługi Container Apps nie działa lub nie ma instancji zapasowych. | Sprawdź stan puli sesji w portalu Azure. W razie potrzeby zwiększ standbyInstanceCount w szablonie Bicep. |
| Wykonywanie kodu kończy się niepowodzeniem w kontenerze | Brak pakietów Python w kontenerze niestandardowym. | Zaktualizuj obraz kontenera, aby zawierał wymagane pakiety. Odtwórz i wdroż ponownie kontener. |
| Błąd uwierzytelniania podczas nawiązywania połączenia z serwerem MCP | Poświadczenia połączenia projektu są nieprawidłowe lub wygasły. | Wygeneruj ponownie poświadczenia połączenia i zaktualizuj .env plik. Sprawdź format MCP_PROJECT_CONNECTION_ID. |
Ograniczenia
API nie obsługują bezpośrednio danych wejściowych ani wyjściowych pliku ani korzystania z repozytoriów plików. Aby uzyskać i przesłać dane, należy użyć adresów URL, takich jak adresy URL danych dla małych plików oraz adresy URL z sygnaturą dostępu współdzielonego (SAS) usługi Azure Blob Service dla dużych plików.
Zabezpieczenia
Traktuj wygenerowany kod i jego zależności jako niezaufany. Używaj zatwierdzonego obrazu podstawowego i listy dozwolonych pakietów, uruchamiaj z minimalnymi wymaganymi zasobami obliczeniowymi i uprawnieniami oraz ograniczaj wychodzący ruch sieciowy do niezbędnych miejsc docelowych. Nie należy instalować poufnych danych ani poświadczeń produkcyjnych w sesji.
Jeśli używasz adresów URL SAS do przekazywania danych do lub z środowiska uruchomieniowego:
- Użyj krótkotrwałych tokenów SAS.
- Nie rejestruj adresów URL sygnatur dostępu współdzielonego ani nie przechowuj ich w systemie kontroli wersji.
- Uprawnienia zakresu ogranicz do minimum wymagane (na przykład tylko do odczytu lub tylko do zapisu).
Czyszczenie
Aby zatrzymać rozliczenia dla przydzielonych zasobów, usuń zasoby utworzone przez wdrożenie przykładowe. Jeśli w tym artykule użyto dedykowanej grupy zasobów, usuń grupę zasobów.