快速入門:建立一個工具箱並與託管代理一起使用

重要

本文中標示為預覽的項目目前仍在預覽中。 此預覽版未簽訂服務等級協議,Microsoft 不建議用於生產工作負載。 某些功能可能不被支援或功能受限。 欲了解更多資訊,請參閱 Microsoft Azure 預覽版補充使用條款。

在本快速入門中,您會建置一個工具箱,並從 Python 託管 Agent 取用該工具箱。 工具箱只暴露一個模型上下文協定(MCP)端點,因此代理透過單一連線發現其工具。

Azure 開發者 CLI 與 Visual Studio Code 工作流程使用 Foundry 工具箱範例。 其azure.yaml宣告了 Azure REST API 規範、GitHub、Azure 語言和 Microsoft Foundry 的網頁搜尋、程式碼直譯器和 MCP 來源。 三個專案連線提供已認證來源的憑證與身份設定。

Python SDK 工作流程會建立較小的工具箱,其中包含 Web 搜尋與公開的 Microsoft Learn MCP 伺服器。 它使用範例的代理程式碼,卻不部署範例的額外連接與工具箱宣告。

如果你使用像 GitHub Copilot 這樣的程式代理程式,Microsoft Foundry 技能可以幫助建立工具箱端點,連接到託管代理,並調整範例工具。

先決條件

本快速入門是以託管代理程式工具鏈為基礎。 先完成託管代理快速入門的前置條件,涵蓋 Azure 訂閱、專案角色、Python、Azure 開發者 CLI(azd)以及擴充microsoft.foundry功能。

請使用 azd 1.34.2 或更新版本,以及包含 azure.ai.agents 1.0.0-beta.19 或更新版本的 microsoft.foundry 擴充套件組合。

安裝 Python 3.13 或更新版本,並在初始化前準備範例的外部相依關係:

輸入或存取 如何準備它
GITHUB_MCP_PAT 建立一個 GitHub 個人存取權杖,只包含你打算呼叫的工具所需的儲存庫權限。 請參考 GitHub MCP 伺服器的遠端伺服器設定說明。 請先備妥該值,以便回應初始化提示。
AZURE_LANGUAGE_MCP_ENDPOINT 設置一個 Azure 語言 MCP 端點。 使用完整的端點,包括 /language/mcp?api-version=2025-11-15-preview,而非資源的基礎網址。
Azure Language 存取權 該樣本的 langmcpconn 連線使用 Foundry 專案的受控識別身分。 你需要在部署前具備在 Language 資源上將 認知服務語言擁有者 角色授與該身分的權限。 如果需要,請要求資源擁有者或管理員指派這個角色。 檢視 工具的 Microsoft Entra 驗證。 若為新專案,請在佈建建立其身分識別後完成授與。
Foundry MCP 存取 該範例的foundrymcpconn連線使用呼叫使用者的 Microsoft Entra 身份。 使用者需要存取所選 Foundry 工具所操作的資源。 以使用者身份登入;僅靠服務主體或管理身份憑證無法提供委派的使用者上下文。

此範例不會建立外部的 GitHub 或 Language 資源。 初始化會提示未解決的環境輸入,包括 Token 與 Language 端點,並將這些值儲存在 azd 環境中。 不要提交憑證、.env 檔案或 .azure 檔案。

關於認證設定,請參閱範例的 Microsoft Entra MCP 指南。

關於 Python SDK 路徑,請使用本文後面的 Python 部分,而非 Azure 開發者的 CLI 或 VS Code 工作流程。 該路徑會建立帶有 project_client.toolboxes.create_version(...)的工具箱,然後上傳託管代理程式作為新版本,並依名稱指向該工具箱。

安裝此路徑中使用的 Python 套件:

pip install "azure-ai-projects>=2.3.0" python-dotenv

你需要一個現有的 Foundry 專案,並部署支援聊天的模型。 這個快速入門中的 Python SDK 路徑會建立工具箱和託管代理版本,但它不會為你建立新的 Foundry 專案或建立模型部署。

關於 .NET SDK 路徑,請使用本文後面的 C# 部分,而非 Azure 開發者 CLI 或 VS Code 工作流程。 該路徑會建立帶有 AgentToolboxes.CreateVersion(...)的工具箱,然後上傳 C# 主機代理程式作為新版本,並以名稱指向該工具箱。

你還需要 .NET 10 SDK 或更新版本,以及一個已部署具備聊天功能的 Foundry 專案。

你也需要 Visual Studio Code,並安裝 Microsoft Foundry Toolkit 擴充功能,且已登入 Azure。

步驟 1:初始化託管代理

在終端機中,建立一個空目錄,並將整個範例專案初始化到其中:

mkdir my-toolbox-agent && cd my-toolbox-agent
azd ai agent init --template "https://github.com/microsoft-foundry/foundry-samples/blob/main/samples/python/hosted-agents/agent-framework/responses/04-foundry-toolbox/azure.yaml" --src .

選取或建立 Foundry 專案,並輸入先決條件中備妥的外部輸入值。 若要在現有專案中重用模型部署,請在初始化指令中加入 --model-deployment <existing-deployment-name> 。 範本採用目前沒有提供現有部署選擇器。

這個 --src . 選項選擇的是 專案根目錄,而不是代理來源子目錄。 請留在my-toolbox-agent中(該目錄現在包含azure.yaml),以執行後續的azd命令。 Agent 原始碼仍位於src/agent-framework-agent-with-foundry-toolbox-responses底下。

在配置前請先檢視 azure.yaml 中的模型宣告和代理設定。 若要稍後更改外部輸入,請從此專案根執行 azd env set <name> <value> ;不要執行另一個 azd init。

就 Python Agent 而言,請確保其在azure.yaml中的服務包含PYTHONNOUSERSITE: "1",且須在啟動與部署之前,將其納入現有的env對應中。 不要依賴在應用程式中載入這個設定。 關於相依相容性的指引,請參見「配置 Python 啟動」。

在 Visual Studio Code 中開啟初始化的專案資料夾。 在其內建終端機中執行以下指令。 此工作流程使用範例 azure.yaml 來部署連線、工具箱與代理一起;不要在工具包中建立相同目的的獨立工具箱。

步驟二:建立工具箱

範例將 agent-tools 工具箱宣告為 azure.ai.toolbox 服務。 其 uses 條目參考專案與連線;代理服務則參考工具箱。 編輯 azure.yaml 中的這些宣告以更改工具或連線。

這個工作流程不需要另外的 toolbox.yaml,也不需要手動的 azd ai toolbox create 指令。 下一步是依照依賴順序部署宣告。 僅靠配置本身不會建立工具箱,本地代理啟動也不會產生任何遠端相依。

步驟 3:配置 Azure 資源

現有的 Foundry 專案可能仍需範本宣告的資源,例如模型部署。 檢視設定,然後佈建專案的 Azure 資源,使其受控識別得以存在:

azd provision

部署前,請依先決條件所述,將專案的受控識別授與現有語言資源上的認知服務語言擁有者角色。 請使用專案身份,而非父 Foundry 帳號身份或你自己的使用者身份。 請等待角色指派生效。

接著將連線、工具箱和託管代理一起部署:

azd deploy --all

工具箱部署產生 TOOLBOX_AGENT_TOOLS_MCP_ENDPOINT。 代理人的 env 宣告將此版本化端點映射到 TOOLBOX_ENDPOINT。 請從專案根目錄檢查輸出:

azd env get-value TOOLBOX_AGENT_TOOLS_MCP_ENDPOINT

不要用為個別建立之工具箱的端點覆寫此繫結。

步驟四:在本地運行代理

首先,在步驟 3 完成配置、管理身份授權及部署。 本機 Agent 仍會使用遠端連線和工具箱;azd ai agent run不會建立它們。 此範例會為你處理工具箱連線、標頭和驗證。

  1. 部署遠端相依項目後,從專案根目錄啟動代理程式:

    azd ai agent run
    

    此指令建立虛擬環境,安裝相依關係,並將代理程式服務於 http://localhost:8088。 服務配置提供 FOUNDRY_PROJECT_ENDPOINT、 AZURE_AI_MODEL_DEPLOYMENT_NAME、 TOOLBOX_ENDPOINT。 不要在原始碼 .env 檔案中用佔位值取代這些。

  2. 在另一個終端機中,從同一專案根檢查可用工具並進行網頁搜尋:

    azd ai agent invoke --local "List the tools you can use."
    azd ai agent invoke --local "Find the latest release notes for the Azure CLI on the web."
    

對於 VS Code 除錯,請開啟已初始化的專案,並依照範例中的 VS Code 指示操作。 對於 F5 或獨立 Python 執行,請在代理來源資料夾的TOOLBOX_ENDPOINT檔案中將.env設為下列輸出的結果:

azd env get-value TOOLBOX_AGENT_TOOLS_MCP_ENDPOINT

另外,將 AZURE_AI_MODEL_DEPLOYMENT_NAME 和 FOUNDRY_PROJECT_ENDPOINT 設為你的專案端點和模型部署名稱。 不要將 .env 納入版本控制。

步驟 5:部署至 Foundry 代理服務

第三步已經部署了託管代理。 更換工具、連線或代理程式碼後,將所有服務一同部署:

azd deploy --all

此指令會更新工具箱,並使用產生的版本化端點部署代理。 VS Code 僅限代理程式的部署工作流程不會更新工具箱或其連線。

命令執行完成後,輸出內容會顯示代理測試場和代理端點的連結。 呼叫已部署的代理:

azd ai agent invoke "List the tools you can use."

範例使用此部署所產生的版本化端點。 這不需要將 Toolbox 版本設為預設,或重新導向使用舊版的其他代理程式。

Python SDK 路徑

如果你想建立工具箱並部署託管代理版本,使用 Python SDK 而非 Azure 開發者 CLI 或 VS Code 流程,請遵循以下步驟。

1. 建立或選擇 Foundry 專案

  1. 開啟 Foundry 入口網站 並建立一個 Foundry 專案,或選擇現有的專案。
  2. 在專案中,部署一個具備聊天功能的模型,例如 gpt-5.4-mini。
  3. 從 Overview 複製專案端點,並從 Build>Deployments 複製部署名稱。

2. 下載工具箱中的 hosted-agent 範例

複製 Foundry 的範例存放庫:

git clone https://github.com/microsoft-foundry/foundry-samples.git

建立一個部署腳本的工作資料夾。 在該資料夾中,建立內容如下的 .env 檔案:

FOUNDRY_PROJECT_ENDPOINT=<your-project-endpoint>
AZURE_AI_MODEL_DEPLOYMENT_NAME=<your-model-deployment-name>
FOUNDRY_HOSTED_AGENT_NAME=toolbox-agent
TOOLBOX_NAME=my-toolbox
FOUNDRY_SAMPLE_PATH=<full-path-to-foundry-samples/samples/python/hosted-agents/agent-framework/responses/04-foundry-toolbox/src/agent-framework-agent-with-foundry-toolbox-responses>

3. 用 Python 建立工具箱

在與 create_toolbox.py 相同的工作資料夾中建立一個名為 .env 的檔案:

import os

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MCPToolboxTool, WebSearchToolboxTool
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv

load_dotenv()

endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"].rstrip("/")
toolbox_name = os.environ["TOOLBOX_NAME"]

with (
    DefaultAzureCredential() as credential,
    AIProjectClient(endpoint=endpoint, credential=credential) as project_client,
):
    created = project_client.toolboxes.create_version(
        name=toolbox_name,
        description="Toolbox with web search and Microsoft Learn MCP.",
        tools=[
            WebSearchToolboxTool(
                name="web_search",
                search_context_size="medium",
            ),
            MCPToolboxTool(
                server_label="mslearn",
                server_url="https://learn.microsoft.com/api/mcp",
                require_approval="never",
            ),
        ],
    )
    print(f"Created toolbox version {created.version} for {created.name}")

    mcp_endpoint = (
        f"{endpoint}/toolboxes/{created.name}/versions/"
        f"{created.version}/mcp?api-version=v1"
    )
    print(f"Toolbox version: {created.version}")
    print(f"Toolbox MCP endpoint: {mcp_endpoint}")

執行腳本:

python create_toolbox.py

樣本託管 Agent 可以從TOOLBOX_ENDPOINT或從FOUNDRY_PROJECT_ENDPOINT加上TOOLBOX_NAME解析工具箱。 此路徑使用 TOOLBOX_NAME,因此你不需要將版本控制端點存於 .env。

4. 使用 Python 部署託管代理

在與 deploy_toolbox_agent.py 相同的工作資料夾中建立一個名為 .env 的檔案:

import os
import tempfile
import time
import zipfile
from pathlib import Path

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    AgentEndpointConfig,
    CodeConfiguration,
    CodeDependencyResolution,
    FixedRatioVersionSelectionRule,
    HostedAgentDefinition,
    ProtocolConfiguration,
    ProtocolVersionRecord,
    ResponsesProtocolConfiguration,
    VersionSelector,
)
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv

load_dotenv()

endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
model_name = os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"]
agent_name = os.environ.get("FOUNDRY_HOSTED_AGENT_NAME", "toolbox-agent")
toolbox_name = os.environ["TOOLBOX_NAME"]
sample_path = Path(os.environ["FOUNDRY_SAMPLE_PATH"]).resolve()


def create_code_zip(source_dir: Path) -> Path:
    zip_path = Path(tempfile.gettempdir()) / f"{agent_name}.zip"
    excluded = {".git", ".venv", "__pycache__", ".env"}

    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zip_file:
        for path in source_dir.rglob("*"):
            if not path.is_file():
                continue
            if any(part in excluded for part in path.parts):
                continue
            zip_file.write(path, path.relative_to(source_dir))

    return zip_path


def wait_for_active_version(project_client: AIProjectClient, version: str) -> None:
    for attempt in range(60):
        time.sleep(10)
        details = project_client.agents.get_version(
            agent_name=agent_name,
            agent_version=version,
        )
        status = details["status"]
        print(f"Provisioning status: {status} (attempt {attempt + 1}/60)")

        if status == "active":
            return

        if status == "failed":
            raise RuntimeError(f"Hosted agent provisioning failed: {dict(details)}")

    raise RuntimeError("Timed out waiting for the hosted agent version to become active.")


code_zip_path = create_code_zip(sample_path)

with (
    code_zip_path.open("rb") as code_stream,
    DefaultAzureCredential() as credential,
    AIProjectClient(endpoint=endpoint, credential=credential) as project_client,
):
    original_agent_endpoint = None
    created = None

    try:
        created = project_client.agents.create_version_from_code(
            agent_name=agent_name,
            description="Hosted agent with Foundry Toolbox integration.",
            definition=HostedAgentDefinition(
                cpu="1",
                memory="2Gi",
                code_configuration=CodeConfiguration(
                    runtime="python_3_13",
                    entry_point=["python", "main.py"],
                    dependency_resolution=CodeDependencyResolution.REMOTE_BUILD,
                ),
                environment_variables={
                    "FOUNDRY_PROJECT_ENDPOINT": endpoint,
                    "AZURE_AI_MODEL_DEPLOYMENT_NAME": model_name,
                    "TOOLBOX_NAME": toolbox_name,
                    "PYTHONNOUSERSITE": "1",
                },
                protocol_versions=[
                    ProtocolVersionRecord(protocol="responses", version="2.0.0")
                ],
            ),
            code=code_stream,
        )

        print(f"Created hosted agent version {created.version}")
        wait_for_active_version(project_client, created.version)

        original_agent_endpoint = project_client.agents.get(
            agent_name=agent_name
        ).agent_endpoint

        project_client.agents.update_details(
            agent_name=agent_name,
            agent_endpoint=AgentEndpointConfig(
                version_selector=VersionSelector(
                    version_selection_rules=[
                        FixedRatioVersionSelectionRule(
                            agent_version=created.version,
                            traffic_percentage=100,
                        ),
                    ]
                ),
                protocol_configuration=ProtocolConfiguration(
                    responses=ResponsesProtocolConfiguration()
                ),
            ),
        )

        with project_client.get_openai_client(agent_name=agent_name) as openai_client:
            response = openai_client.responses.create(
                input=(
                    "How do I create a hosted agent in Microsoft Foundry? "
                    "Use the Microsoft Learn documentation."
                ),
            )
            if response.status != "completed":
                raise RuntimeError(f"Agent invocation failed: {response.error}")
            print(response.output_text)
    finally:
        if original_agent_endpoint is not None:
            project_client.agents.update_details(
                agent_name=agent_name,
                agent_endpoint=original_agent_endpoint,
            )

        if created is not None:
            project_client.agents.delete_version(
                agent_name=agent_name,
                agent_version=created.version,
                force=True,
            )

執行腳本:

python deploy_toolbox_agent.py

此腳本會將工具箱範例上傳為新的託管代理版本,暫時指向該版本,並以 Microsoft Learn 問題呼叫該版本,完成後還原先前的端點設定。

5. 驗證由工具箱支援的回應

如果你正確設定工具箱,回應顯示託管代理發現了工具箱工具,並透過 Microsoft Learn 文件來回答。

C# SDK 路徑

使用此路徑建立工具箱,並部署 C# 託管代理範例,使用 .NET SDK 取代 Azure 開發者 CLI 或 VS Code 工作流程。

1. 建立或選擇 Foundry 專案

  1. 開啟 Foundry 入口網站 並建立一個 Foundry 專案,或選擇現有的專案。
  2. 在專案中,部署一個具備聊天功能的模型,例如 gpt-4o。
  3. 從 Overview 複製專案端點,並從 Build>Deployments 複製部署名稱。

2. 下載工具箱中的 hosted-agent 範例

複製 Foundry 的範例存放庫:

git clone https://github.com/microsoft-foundry/foundry-samples.git

C# 代管代理程式範例位於 samples/csharp/hosted-agents/agent-framework/foundry-toolbox-server-side/src/foundry-toolbox-server-side-dotnet-agent-framework 之下。 接下來的部署程式碼會在容器上設定以下環境變數:

Variable Description
FOUNDRY_PROJECT_ENDPOINT Foundry 的專案端點。
AZURE_AI_MODEL_DEPLOYMENT_NAME 聊天模式部署名稱。
TOOLBOX_NAME 代理程式連接的工具箱名稱。

3. 用 C 建立工具箱#

建立一個 .NET 控制台應用程式並安裝套件。 Toolbox API 目前處於預覽階段,請安裝預發布 Azure.AI.Projects 套件:

dotnet new console --name create-toolbox
cd create-toolbox
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.Identity

請用以下程式碼替換 Program.cs ,並設 endpoint 為你的專案端點:

using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using OpenAI;
using OpenAI.Responses;

#pragma warning disable AAIP001, OPENAI001

var endpoint = "https://<account>.services.ai.azure.com/api/projects/<project>";
var toolboxName = "my-toolbox";

AIProjectClient projectClient = new(new Uri(endpoint), new DefaultAzureCredential());
AgentToolboxes toolboxes = projectClient.AgentAdministrationClient.GetAgentToolboxes();

ToolboxVersion created = toolboxes.CreateVersion(
    name: toolboxName,
    tools:
    [
        new WebSearchToolboxTool { Name = "web_search", SearchContextSize = WebSearchToolSearchContextSize.Medium },
        new MCPToolboxTool(serverLabel: "mslearn")
        {
            ServerUri = new Uri("https://learn.microsoft.com/api/mcp"),
            ToolCallApprovalPolicy = new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval),
        },
    ],
    description: "Toolbox with web search and Microsoft Learn MCP.");
Console.WriteLine($"Created toolbox version {created.Version} for {created.Name}");

執行應用程式:

dotnet run

範例託管代理程式會從 TOOLBOX_NAME 加上 FOUNDRY_PROJECT_ENDPOINT 解析出工具箱,因此你不需要儲存版本化端點。

4. 使用 C# 部署託管代理程式

建立第二個主控台應用程式來執行部署程式碼:

dotnet new console --name deploy-toolbox-agent
cd deploy-toolbox-agent
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.AI.Extensions.OpenAI
dotnet add package Azure.Identity

以下列程式碼取代 Program.cs。 將 endpoint、chatModel 和 samplePath 設為您要的值。 samplePath 是您在步驟 2 中複製的 foundry-toolbox-server-side-dotnet-agent-framework 原始碼資料夾完整路徑:

using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using OpenAI.Responses;

#pragma warning disable AAIP001, OPENAI001

var endpoint = "https://<account>.services.ai.azure.com/api/projects/<project>";
var chatModel = "gpt-4o";
var toolboxName = "my-toolbox";
var agentName = "toolbox-agent";
var samplePath =
    @"<path-to-foundry-samples>\samples\csharp\hosted-agents\agent-framework\foundry-toolbox-server-side\src\foundry-toolbox-server-side-dotnet-agent-framework";

AIProjectClient projectClient = new(new Uri(endpoint), new DefaultAzureCredential());
var agentsClient = projectClient.AgentAdministrationClient;

HostedAgentDefinition definition = new(cpu: "1", memory: "2Gi")
{
    Versions = { new ProtocolVersionRecord(ProjectsAgentProtocol.Responses, "2.0.0") },
    CodeConfiguration = new(
        runtime: "dotnet_10",
        entryPoint: ["dotnet", "foundry-toolbox-server-side.dll"],
        dependencyResolution: CodeDependencyResolution.RemoteBuild),
};
definition.EnvironmentVariables.Add("FOUNDRY_PROJECT_ENDPOINT", endpoint);
definition.EnvironmentVariables.Add("AZURE_AI_MODEL_DEPLOYMENT_NAME", chatModel);
definition.EnvironmentVariables.Add("TOOLBOX_NAME", toolboxName);

ProjectsAgentVersion? created = null;
AgentEndpointConfiguration? originalEndpoint = null;
try
{
    created = agentsClient.CreateAgentVersionFromCode(
        agentName, samplePath, new AgentVersionFromCodeMetadata(definition));
    Console.WriteLine($"Created hosted agent version {created.Version}");

    for (var attempt = 1; attempt <= 60; attempt++)
    {
        Thread.Sleep(TimeSpan.FromSeconds(10));
        created = agentsClient.GetAgentVersion(agentName, created.Version);
        Console.WriteLine($"Provisioning status: {created.Status} (attempt {attempt}/60)");
        if (created.Status == AgentVersionStatus.Active) break;
        if (created.Status == AgentVersionStatus.Failed)
            throw new InvalidOperationException("Hosted agent provisioning failed.");
    }

    ProjectsAgentRecord agent = agentsClient.GetAgent(agentName);
    originalEndpoint = agent.AgentEndpoint;
    agentsClient.PatchAgent(agentName, new PatchAgentOptions
    {
        AgentEndpoint = new AgentEndpointConfiguration
        {
            VersionSelector = new([new FixedRatioVersionSelectionRule(created.Version, 100)]),
            ProtocolConfiguration = new() { Responses = new ResponsesProtocolConfiguration() },
        },
    });

    ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient
        .GetProjectResponsesClientForAgentEndpoint(agentName);
    ResponseResult response = responsesClient.CreateResponse(
        "How do I create a hosted agent in Microsoft Foundry? Use the Microsoft Learn documentation.");
    Console.WriteLine(response.GetOutputText());
}
finally
{
    if (originalEndpoint is not null)
        agentsClient.PatchAgent(agentName, new PatchAgentOptions { AgentEndpoint = originalEndpoint });
    if (created is not null)
        agentsClient.DeleteAgentVersion(agentName, created.Version, force: true);
}

執行應用程式:

dotnet run

此程式碼會將工具箱範例上傳為新的主機代理版本,暫時將託管代理指向該版本,並以 Microsoft Learn 問題呼叫該版本,完成後還原先前的端點設定。

5. 驗證由工具箱支援的回應

如果你正確設定工具箱,回應顯示託管代理發現了工具箱工具,並透過 Microsoft Learn 文件來回答。

清理資源

完成後刪除資源,這樣就不會再被收費了。

刪除工具箱。 請將 <deployed-toolbox-name> 替換為針對此快速入門所建立的工具箱名稱:

azd ai toolbox list
azd ai toolbox delete <deployed-toolbox-name> --force

刪除工具箱後,它的端點就會停止運作。 停止本機代理程式,並移除你為 VS Code 除錯而新增至 src/agent-framework-agent-with-foundry-toolbox-responses/.env 的任何端點。

delete 指令會清除你 azd 環境中產生的端點值。 再次執行 azd deploy --all 會重建在 azure.yaml 中宣告的工具箱。

刪除代理程式及其 Azure 資源:

警告

如果目前 azd 環境建立了 Foundry 專案, azd down 則會永久刪除該專案的資源群組及所有相關資料。 如果你在初始化時選擇了現有專案,則保留 azd down 該專案、其資源群組、託管代理程式及其他快速啟動資源。 要刪除現有專案中不再需要的資源,請分別刪除。

azd down

依名稱刪除工具箱:

import os

from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv

load_dotenv()

with (
    DefaultAzureCredential() as credential,
    AIProjectClient(
        endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
        credential=credential,
    ) as project_client,
):
    project_client.toolboxes.delete(name=os.environ["TOOLBOX_NAME"])

如果你為這個快速入門建立了專用的資源群組或專案,請在不再需要工具箱、聊天部署或託管代理之後,從 Azure 入口網站將其刪除。

部署程式碼已經刪除了託管代理版本,並在完成後還原了之前的端點設定。 要刪除工具箱,請將此程式碼加入安裝( Azure.AI.Projects 預發布版)及 Azure.Identity 套件的主控台應用程式:

using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;

#pragma warning disable AAIP001

var endpoint = "https://<account>.services.ai.azure.com/api/projects/<project>";
var toolboxName = "my-toolbox";

AIProjectClient projectClient = new(new Uri(endpoint), new DefaultAzureCredential());
projectClient.AgentAdministrationClient.GetAgentToolboxes().Delete(toolboxName);
Console.WriteLine($"Deleted toolbox '{toolboxName}'.");

如果你為這個快速入門建立了專用的資源群組或專案,請在不再需要工具箱、聊天部署或託管代理之後,從 Azure 入口網站將其刪除。

Troubleshooting

Issue Solution
azd env set 顯示目前不存在任何專案 從包含 azure.yaml的初始化目錄執行該指令。 使用本文中的命令時,該目錄即為my-toolbox-agent。
初始化需要 GitHub token 或 Language 端點 在先決條件中準備外部輸入值。 完整的 CLI 範例使用的工具來源比 Python SDK 工作流程還多。
tools/list未回傳任何 Microsoft Learn 工具 SDK 路徑請確認工具箱定義包含 mslearn 與 https://learn.microsoft.com/api/mcp。 CLI 範例宣告了不同的工具組合。
代理程式已啟動,但顯示 TOOLBOX_ENDPOINT is set but empty 或沒有可用工具 在執行本地 CLI 前,先在 第 3 步 完成配置、授權與部署。 檢查TOOLBOX_AGENT_TOOLS_MCP_ENDPOINT,以及 Agent 在TOOLBOX_ENDPOINT中的azure.yaml繫結。 移除過時的 .env 覆寫。 VS Code 除錯時,將產生的端點複製到 agent source 資料夾的 .env 檔案。 關於 Python SDK 工作流程,請參閱TOOLBOX_NAME。
某個來源的工具探索失敗 檢查發生失敗的來源的連線狀況、服務可用性和權限。 來源失效可能導致整個工具箱的枚舉無法進行。
對工具箱端點的呼叫會因授權錯誤而失敗 請確認每個請求都包含範圍限定為 https://ai.azure.com/.default 的 Entra 令牌。 範例會為您處理此項。
Connection refused 在本機執行時 確保沒有其他程序使用 port 8088。

你學到了什麼

在這篇快速啟動指南中,您將:

  • 我建立了一個工具箱,將多個工具整合在同一個端點。
  • 使用 Azure Developer CLI 或 Python SDK,透過以 Model Context Protocol 連線的 Python 託管 Agent 取用工具箱。
  • 在本地運行代理程式或遠端驗證,然後部署到 Foundry 代理服務。

後續步驟