Aracılar için özel kod yorumlayıcı aracı (önizleme)

Önemli

Bu makalede işaretlenen (önizleme) öğeler şu anda genel önizleme aşamasındadır. Bu önizleme, hizmet düzeyi sözleşmesi olmadan sağlanır ve üretim iş yükleri için önerilmez. Bazı özellikler desteklenmeyebilir veya kısıtlı özelliklere sahip olabilir. Daha fazla bilgi için bkz. Microsoft Azure Önizlemeleri için Uygun Kullanım Koşulları.

Özel kod yorumlayıcısı, ajan tarafından oluşturulan Python kodu için çalışma zamanı ortamı üzerinde tam denetim sağlar. Özel Python paketlerini, işlem kaynaklarını ve Azure Container Apps ortamı ayarlarını yapılandırabilirsiniz. Kod yorumlayıcı kapsayıcısı bir Model Bağlam Protokolü (MCP) sunucusunu kullanıma sunar.

Aracılar için yerleşik Code Yorumlayıcı aracı gereksinimlerinizi karşılamadığında (örneğin, belirli Python paketlerine, özel kapsayıcı görüntülerine veya ayrılmış işlem kaynaklarına ihtiyacınız olduğunda) özel kod yorumlayıcı kullanın.

MCP ve aracıların MCP araçlarına nasıl bağlanacakları hakkında daha fazla bilgi için bkz. Model Bağlam Protokolü sunucularına bağlanma (önizleme).

Tip

Araç kutusu kullanarak bu aracı eklemeyi göz önünde bulundurun. Araç kutusunu kullanarak aracıları ve çalışma zamanlarını yeniden kullanabilir ve yönetilen bir MCP uç noktası aracılığıyla kimlik bilgisi yönetimi, sürüm oluşturma ve ilke zorlamayı merkezi hale getirebilirsiniz. Araç kutusu hızlı başlangıcına bakın.

Önkoşullar

  • Azure CLI sürüm 2.60.0 veya üzeri.

  • Bakımı yapılan örnek proje için 3.12 veya sonraki bir sürümü Python.

  • (İsteğe bağlı) daha hızlı Python paket yönetimi için uv.

  • Aşağıdaki rol atamalarına sahip bir Azure aboneliği ve kaynak grubu:

    • Sağlamadan sonra aracıyı yapılandırmak ve çalıştırmak için Foundry projesindeki Dökümhane Kullanıcısı.

      Önemli

      Foundry RBAC rolleri yakın zamanda yeniden adlandırıldı. Foundry User, Foundry Owner, Foundry Hesabı Sahibi ve Foundry Project Manager daha önce Azure Yapay Zeka Kullanıcısı, Azure Yapay Zeka Sahibi, Azure Yapay Zeka Hesabı Sahibi ve Azure Yapay Zeka Project Yöneticisi olarak adlandırıldı. Yeniden adlandırma kullanıma sunulmaya devam ederken bazı yerlerde önceki adları görmeye devam edebilirsiniz. Rol kimlikleri ve temel izinler yeniden adlandırma ile değiştirilmez.

    • Yalnızca örnek dağıtım Foundry kaynaklarını ve proje bağlantısını oluştururken hedef kaynak grubundaki Döküm Sahibi.

    • Container Apps ManagedEnvironment Katkıda Bulunanı hedef kaynak grubunda yalnızca örnek dağıtım Container Apps ortamını oluştururken kullanılır.

    Sağlama rollerini Microsoft Entra Privileged Identity Management (PIM) aracılığıyla tam zamanında etkinleştirin ve dağıtımdan sonra devre dışı bırakın. Günlük aracı geliştiricilerin ve çalışma zamanı kullanıcılarının bu sağlama rollerine ihtiyacı yoktur.

  • Microsoft Döküm SDK'sı. Yükleme için hızlı başlangıç bölümüne bakın.

Kullanım desteği

Bu makalede Azure CLI ve çalıştırılabilir bir örnek proje kullanılmaktadır.

Aşağıdaki tabloda SDK ve kurulum desteği gösterilmektedir.

Microsoft Foundry desteği Python SDK'sı C# SDK'sı JavaScript SDK'sı Java SDK'sı REST API Temel aracı kurulumu Standart ajan kurulumu
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ - ✔️

En son SDK ve API desteği için, Microsoft Foundry Agent Service'de araçları kullanmaya yönelik en iyi uygulamaları inceleyin.

SDK desteği

Özel kod yorumlayıcısı MCP araç türünü kullanır. MCP araçlarını destekleyen tüm SDK'lar özel bir kod yorumlayıcı aracısı oluşturabilir. .NET SDK şu anda önizleme aşamasındadır. Altyapı sağlama adımları (Azure CLI, Bicep) için bkz. Özel kod yorumlayıcıyla aracı oluşturma.

Başlamadan önce

Bu yordam, Azure Container Apps kaynakları da dahil olmak üzere Azure altyapı sağlar. Dağıtmadan önce kuruluşunuzun Azure maliyet ve idare gereksinimlerini gözden geçirin.

Özel kod yorumlayıcı ile aracı oluşturma

Aşağıdaki adımlarda altyapının nasıl sağlanıp özel kod yorumlayıcı MCP sunucusu kullanan bir aracı oluşturulacağı gösterilmektedir. Altyapı kurulumu tüm diller için geçerlidir. Dile özgü kod örnekleri aşağıdadır.

Önizleme özelliğini kaydetme

Azure Container Apps Dinamik Oturumlar için MCP sunucusu özelliğini kaydedin:

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

Örnek kodu alma

GitHub deposundaki sample kodunu kopyalayın ve terminalinizde samples/python/prompt-agents/code-interpreter-custom klasörüne gidin.

Altyapıyı sağlama

Bakımlı doğrudan aracı örneği, proje bağlantısında oturum havuzu MCP uç noktasını depolar. Araç kutusu tanımları da uç noktayı olarak server_urlgerektirir. Bu çıkışı kopyalanan infra.bicep dosyaya ekleyin:

output MCP_SERVER_URL string = sessionPool.properties.mcpServerSettings.mcpServerEndpoint

kullanmayın poolManagementEndpoint. Bu değer MCP sunucu uç noktası değil Dinamik Oturumlar yönetim uç noktasıdır.

Altyapıyı sağlamak için Azure CLI (az) kullanarak aşağıdaki komutu çalıştırın:

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

Not

İstediğiniz bekleme örneği sayısına bağlı olarak dağıtım bir saate kadar sürebilir. Dinamik oturum havuzu tahsisi en uzun adımdır.

Aracıyı yapılandırma ve çalıştırma

Depodaki .env.sample dosyayı öğesine .envkopyalayın. Bicep dağıtım çıkışlarını eşleşen ortam değişkenleriyle eşleyin:

çıktıyı Bicep Ortam değişkeni Kullanım amacı
AZURE_AI_PROJECT_ENDPOINT AZURE_AI_PROJECT_ENDPOINT Dökümhane proje uç noktası.
AZURE_AI_CONNECTION_ID AZURE_AI_CONNECTION_ID Hedefi özel kod yorumlayıcısı MCP sunucusu olan bağlantı Project.
MCP_SERVER_URL MCP_SERVER_URL Araç kutusu tanımları için gereken oturum havuzu MCP uç noktası.
AZURE_AI_MODEL_DEPLOYMENT_NAME AZURE_AI_MODEL_DEPLOYMENT_NAME Aracı modeli dağıtımı.

Satır içi örneklerde ve MCP_CONNECTION_ID için AZURE_AI_PROJECT_ENDPOINTAZURE_AI_CONNECTION_IDkullanılırPROJECT_ENDPOINT. Bakımlı doğrudan aracı örneği, proje bağlantısı aracılığıyla MCP hedefini çözümler ve gerekli yer tutucu URL'si olarak kullanır https://localhost . Bir araç kutusu içinmcpServerEndpoint, bir proje bağlantısı sağladığınızda veya connector_id gerektiğinden server_url çıkışa MCPToolboxTool ayarlayınMCP_SERVER_URL.

Python bağımlılıklarını yükleyin ve bakımı yapılan örneği şu komut çiftlerinden biriyle çalıştırın:

uv sync
uv run ./main.py

Veya bir sanal ortam oluşturup iade edilmiş gereksinimleri yükleyin:

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

Kod örneği

Aşağıdaki Python örneği, özel kod yorumlayıcı MCP aracısıyla aracı oluşturma işlemini gösterir:

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

Beklenen çıkış

Örneği çalıştırdığınızda şuna benzer bir çıkış görürsünüz:

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

Barındırılan aracı kullanma

Bu örnek, Microsoft Agent Framework'ten kullanır FoundryChatClient ve kullanarak MCPStreamableHTTPToolmcp uç noktasına bağlanır.

import asyncio
import httpx

from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential, get_bearer_token_provider
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"


class _ToolboxAuth(httpx.Auth):
    def __init__(self, token_provider):
        self._token_provider = token_provider

    def auth_flow(self, request):
        request.headers["Authorization"] = "Bearer " + self._token_provider()
        yield request

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.
    token_provider = get_bearer_token_provider(credential, "https://ai.azure.com/.default")
    http_client = httpx.AsyncClient(auth=_ToolboxAuth(token_provider), timeout=120.0)
    mcp_tool = MCPStreamableHTTPTool(
        name="toolbox",
        url=TOOLBOX_MCP_URL,
        http_client=http_client,
        load_prompts=False,
    )

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

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

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


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

Kod örneği

Aşağıdaki C# örneği, özel kod yorumlayıcısı MCP aracısıyla aracı oluşturma işlemini gösterir. .NET'da MCP araçlarıyla çalışma hakkında daha fazla bilgi için GitHub .NET deposu için Azure SDK MCP araç örneğine bakın.

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

Aracı artık başvurmadıktan sonra araç kutusu sürümünü silin. Doğrulanmış .NET çağrısı için bkz. Araç kutusu sürümünü silme.

Beklenen çıkış

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

Barındırılan aracı kullanma

Bu yardımcı bağımlı tümleştirme parçası, barındırılan aracıyı mcp uç noktasına bağlamak için Microsoft Aracı Çerçevesi'ni kullanır. Makale , ve ToolboxHandlerAgentConfigtanımlamıyorToolboxMcpClient. Bakımlı uygulamaları için bkz. Barındırılan aracıyı araç kutusuna bağlama.

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

// 2. The toolbox exposes an MCP-compatible endpoint.
string toolboxMcpEndpoint =
    $"{projectEndpoint}/toolboxes/{toolboxVersion.Name}/versions/{toolboxVersion.Version}/mcp?api-version=v1";

// 3. Attach the toolbox to the hosted agent.
AzureOpenAIClient openAIClient = new(new Uri(openAiEndpoint), credential);
ChatClient chatClient = openAIClient.GetChatClient(deploymentName);

// ToolboxMcpClient discovers toolbox tools via MCP tools/list and calls them via tools/call.
ToolboxMcpClient toolboxClient = new(toolboxMcpEndpoint, credential);

ResponsesServer.Run<ToolboxHandler>(configure: builder =>
{
    builder.Services.AddSingleton(new AgentConfig(
        name: AgentName,
        instructions: AgentInstructions,
        chatClient: chatClient,
        toolboxClient: toolboxClient));
});

Kod örneği

Aşağıdaki TypeScript örneği, özel kod yorumlayıcı MCP aracısıyla aracı oluşturma işlemini gösterir. JavaScript sürümü için GitHub üzerindeki Azure SDK'nın JavaScript deposundaki MCP araç örneğine bakın.

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

Beklenen çıkış

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

Önerilen: Çoğu aracı için bir araç kutusu aracılığıyla araçlar ekleyin ve araç kutusunu aracınıza MCP aracı olarak ekleyin. Java SDK'sı henüz bir araç kutusu oluşturma API'si sunmaz; bu nedenle Python, REST API, C# veya TypeScript örneğini veya Foundry portalını kullanarak araç kutusunu oluşturun ve ardından Java aracınızdan MCP uç noktasına olarak McpToolbaşvurun. Aşağıdaki örnek, aracıya özel kod yorumlayıcısını içeren araç kutusu MCP uç noktasını ekler.

bağımlılığını öğesinin pom.xmliçine ekleyin:

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

Kod örneği

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

Beklenen çıkış

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

Önkoşullar

Şu ortam değişkenlerini ayarlayın:

  • FOUNDRY_PROJECT_ENDPOINT: Proje uç noktası URL'niz.
  • AGENT_TOKEN: Foundry için taşıyıcı kimlik doğrulama belirteci.

Erişim belirteci alma:

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

Kod örneği

Özel kod yorumlayıcı ile araç kutusu oluşturma

Araç kutusu oluşturarak özel kod yorumlayıcısını ekleyin. Ardından araç kutusunu aracınıza MCP aracı olarak ekleyin. Daha fazla bilgi için bkz. Araç kutusu nedir?

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

Araç kutusu, önceki $FOUNDRY_PROJECT_ENDPOINT/toolboxes/custom-code-interpreter-toolbox/versions/<version>/mcp?api-version=v1çağrı tarafından döndürülen sürüm olan <version> konumunda MCP uyumlu bir uç noktayı kullanıma sunar.

Araç kutusuna uzak araç bağlantısı oluşturma

Araç kutusu uç noktasına işaret eden bir uzak araç projesi bağlantısı oluşturun. Çağıranın kimliğinin (hedef kitle) geçirilmesi için kullanıcı Entra belirtecini https://ai.azure.comkullanın:

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

Araç kutusunu kullanan bir aracı oluşturma

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

Yanıt oluşturma

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

Temizlemek

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"

Beklenen çıkış

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

Kurulumunuzu doğrulama

Altyapıyı sağladıktan ve örneği çalıştırdıktan sonra:

  1. Azure dağıtımının başarıyla tamamlandığını onaylayın.
  2. Dosyanızdaki .env değerlerini kullanarak örneğin bağlantısını doğrulayın.
  3. Microsoft Foundry'de aracınızın izlemeyi kullanarak aracı çalıştırdığını doğrulayın. Daha fazla bilgi için bkz. Microsoft Foundry Agent Service'te araçları kullanmaya yönelik en iyi yöntemler.

Sorun giderme

Sorunu Olası neden Çözünürlük
Özellik kaydı hala beklemede Komut, az feature register durumunu Registering olarak döndürür. Kaydın tamamlanmasını bekleyin (15-30 dakika sürebilir). az feature show --namespace Microsoft.App --name SessionPoolsSupportMCP ile durumu denetleyin. Ardından az provider register -n Microsoft.App yeniden çalıştırın.
Dağıtım izin hatasıyla başarısız oluyor Gerekli rol atamaları eksik. Altyapı dağıtımı için, Microsoft Entra PIM aracılığıyla hedef kaynak grubunda Döküm Sahibi ve Container Apps ManagedEnvironment Katkıda Bulunanı'nı etkinleştirin. Dağıtımdan sonra devre dışı bırakın. Aracı işlemleri için, Dökümhane projesinde Foundry Kullanıcısı olduğunu doğrulayın.
Dağıtım bölge hatasıyla başarısız oluyor Seçili bölge Azure Container Apps Dinamik Oturumları desteklemiyor. Farklı bir bölge deneyin. Desteklenen bölgeler için bkz. Azure Container Apps bölgeleri.
Aracı aracı çağırmıyor MCP bağlantısı doğru şekilde yapılandırılmamış veya aracı yönergeleri araç kullanımını teşvik etmez. Araç çağrısını onaylamak için Microsoft Foundry'de izlemeyi kullanın. Dağıtılmış olan Container Apps uç noktanızla MCP_SERVER_URL'nin eşleştiğini doğrulayın. Bkz. En iyi yöntemler.
MCP sunucu bağlantı zaman aşımı Container Apps oturum havuzu çalışmıyor ya da bekleme örneği bulunmuyor. Azure portalında oturum havuzu durumunu denetleyin. Bicep şablonunuzda gerekirse standbyInstanceCount değerini artırın.
Kapsayıcıda kod yürütme başarısız oluyor Özel kapsayıcıda eksik Python paketleri. Kapsayıcı görüntünüzü gerekli paketleri içerecek şekilde güncelleştirin. Kapsayıcıyı yeniden derleyin ve yeniden dağıtın.
MCP sunucusuna bağlanırken kimlik doğrulama hatası Proje bağlantısı kimlik bilgileri geçersiz veya süresi dolmuş. Bağlantı kimlik bilgilerini yeniden oluşturup dosyayı güncelleştirin .env . MCP_PROJECT_CONNECTION_ID Biçimi doğrulayın.

Sınırlama

API'ler doğrudan dosya girişini veya çıkışını ya da dosya depolarının kullanımını desteklemez. İçeri ve dışarı veri almak için, küçük dosyalar için veri URL'leri ve büyük dosyalar için Azure Blob Hizmeti paylaşılan erişim imzası (SAS) URL'leri gibi URL'leri kullanmanız gerekir.

Güvenlik

Çalışma zamanına veri geçirmek veya çalışma zamanının dışına veri geçirmek için SAS URL'leri kullanıyorsanız:

  • Kısa süreli SAS belirteçleri kullanın.
  • SAS URL'lerini günlüğe kaydetmeyin veya kaynak denetiminde depolamayın.
  • Kapsam izinlerini gereken en düşük seviyeye indir (örneğin salt okunur veya salt yazma).

Temizlemek

Sağlanan kaynakların faturalamasını durdurmak için örnek dağıtım tarafından oluşturulan kaynakları silin. Bu makale için ayrılmış bir kaynak grubu kullandıysanız kaynak grubunu silin.