使用搭載代理的託管 MCP 工具

你可以透過連接遠端 模型情境協定(MCP) 伺服器上的工具來擴充 Microsoft Foundry 代理的功能(請自備 MCP 伺服器端點)。

如何使用模型內容通訊協定工具

本節說明如何建立一個與託管模型情境協定(MCP)伺服器整合的代理程式。 代理可利用由支援 AI 服務管理與執行的 MCP 工具,確保對外部資源的安全且受控存取。

主要功能

  • 託管 MCP 伺服器:MCP 伺服器由 Foundry 託管與管理,免除管理伺服器基礎設施的需求
  • 持久代理:代理在伺服器端建立和存儲,允許進行有狀態對話
  • 工具核准工作流程:MCP 工具調用的可配置核准機制

運作方式

1. 環境設置

此範例需要兩個環境變數:

  • AZURE_FOUNDRY_PROJECT_ENDPOINT: 你的 Foundry 專案端點網址
  • AZURE_FOUNDRY_PROJECT_MODEL_ID:模型部署名稱 (預設為「gpt-4.1-mini」)
var endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
var model = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_MODEL_ID") ?? "gpt-4.1-mini";

2. 代理配置

代理程式會設定特定指示和中繼資料:

const string AgentName = "MicrosoftLearnAgent";
const string AgentInstructions = "You answer questions by searching the Microsoft Learn content only.";

這會建立專門用於使用 Microsoft Learn 文件回答問題的代理程式。

3. MCP工具定義

此範例會建立指向託管 MCP 伺服器的 MCP 工具定義:

var mcpTool = new MCPToolDefinition(
    serverLabel: "microsoft_learn",
    serverUrl: "https://learn.microsoft.com/api/mcp");
mcpTool.AllowedTools.Add("microsoft_docs_search");

重要元件:

  • serverLabel:MCP 伺服器執行個體的唯一識別碼
  • serverUrl:託管 MCP 伺服器的 URL
  • AllowedTools:指定代理程式可以使用 MCP 伺服器中的哪些工具

4. 代理人創建

代理程式是在伺服器端使用 Azure AI Projects SDK 建立的:

var aiProjectClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential());

var agentVersion = await aiProjectClient.AgentAdministrationClient.CreateAgentVersionAsync(
    AgentName,
    new ProjectsAgentVersionCreationOptions(
        new DeclarativeAgentDefinition(model)
        {
            Instructions = AgentInstructions,
            Tools = { mcpTool }
        }));

警告

DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。

這會產生一個版本化代理,具備:

  • Foundry 服務上的生命
  • 可以存取指定的 MCP 工具
  • 可以在多個互動中維護對話狀態

5. 代理檢索和執行

已建立的代理程式會擷取為 AIAgent 實例:

AIAgent agent = aiProjectClient.AsAIAgent(agentVersion);

6. 工具資源配置

此範例會使用核准設定來設定工具資源:

var runOptions = new ChatClientAgentRunOptions()
{
    ChatOptions = new()
    {
        RawRepresentationFactory = (_) => new ThreadAndRunOptions()
        {
            ToolResources = new MCPToolResource(serverLabel: "microsoft_learn")
            {
                RequireApproval = new MCPApproval("never"),
            }.ToToolResources()
        }
    }
};

關鍵配置:

  • MCPToolResource:將 MCP 伺服器執行個體連結至代理程式執行
  • RequireApproval:控制工具調用何時需要使用者核准
    • "never":工具無需批准即可自動執行
    • "always":所有工具調用都需要使用者核准
    • 也可以設定自訂核准規則

7. 代理執行

代理程式會使用問題呼叫,並使用已設定的 MCP 工具執行:

AgentSession session = await agent.CreateSessionAsync();
var response = await agent.RunAsync(
    "Please summarize the Azure AI Agent documentation related to MCP Tool calling?",
    session,
    runOptions);
Console.WriteLine(response);

8. 清理

此範例示範適當的資源清除:

await aiProjectClient.AgentAdministrationClient.DeleteAgentAsync(agent.Id);

小提示

完整可執行範例請參閱 .NET Foundry Agent Hosted MCP 範例

Foundry 透過 Python 代理框架,提供與模型情境協定(MCP)伺服器的無縫整合。 該服務管理 MCP 伺服器託管和執行,消除基礎設施管理,同時提供對外部工具的安全、受控存取。

環境設定

透過環境變數設定您的 Foundry 專案憑證:

import os
from azure.identity.aio import AzureCliCredential
from agent_framework.foundry import FoundryChatClient

# Required environment variables
os.environ["FOUNDRY_PROJECT_ENDPOINT"] = "https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
os.environ["FOUNDRY_MODEL"] = "gpt-4o-mini"

基本 MCP 集成

使用託管的 MCP 工具建立 Foundry 代理:

import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity.aio import AzureCliCredential

async def basic_foundry_mcp_example():
    """Basic example of Foundry agent with hosted MCP tools."""
    async with AzureCliCredential() as credential:
        client = FoundryChatClient(credential=credential)
        # Create a hosted MCP tool using the client method
        learn_mcp = client.get_mcp_tool(
            name="Microsoft Learn MCP",
            url="https://learn.microsoft.com/api/mcp",
        )

        # Create agent with hosted MCP tool
        async with Agent(
            client=client,
            name="MicrosoftLearnAgent",
            instructions="You answer questions by searching Microsoft Learn content only.",
            tools=[learn_mcp],
        ) as agent:
            # Simple query without approval workflow
            result = await agent.run(
                "Please summarize the Azure AI Agent documentation related to MCP tool calling?"
            )
            print(result.text)

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

多功能工具 MCP 配置

將多個託管的 MCP 工具與單一代理程式搭配使用:

async def multi_tool_mcp_example():
    """Example using multiple hosted MCP tools."""
    async with AzureCliCredential() as credential:
        client = FoundryChatClient(credential=credential)
        # Create multiple MCP tools using the client method
        learn_mcp = client.get_mcp_tool(
            name="Microsoft Learn MCP",
            url="https://learn.microsoft.com/api/mcp",
            approval_mode="never_require",  # Auto-approve documentation searches
        )
        github_mcp = client.get_mcp_tool(
            name="GitHub MCP",
            url="https://api.githubcopilot.com/mcp/",
            approval_mode="always_require",  # Require approval for GitHub operations
            headers={"Authorization": "Bearer github-token"},
        )

        # Create agent with multiple MCP tools
        async with Agent(
            client=client,
            name="MultiToolAgent",
            instructions="You can search documentation and access GitHub repositories.",
            tools=[learn_mcp, github_mcp],
        ) as agent:
            result = await agent.run(
                "Find Azure documentation and also check the latest commits in microsoft/semantic-kernel"
            )
            print(result.text)

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

Python 代理框架與 Foundry 託管的 MCP 功能無縫整合,讓外部工具能安全且可擴展地存取,同時維持生產應用所需的彈性與控制。

小提示

MCP 工具也可以整合進 Microsoft Foundry Toolbox 配置中——這些是有名稱、有版本的伺服器端託管工具集合。 請參閱 Microsoft Foundry 工具箱以獲得管理代理附件及 MCP 消耗指引。

完整範例

# Copyright (c) Microsoft. All rights reserved.

import asyncio
import os

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from dotenv import load_dotenv

"""
MCP GitHub Integration with Personal Access Token (PAT)

This example demonstrates how to connect to GitHub's remote MCP server using a Personal Access
Token (PAT) for authentication. The agent can use GitHub operations like searching repositories,
reading files, creating issues, and more depending on how you scope your token.

Prerequisites:
1. A GitHub Personal Access Token with appropriate scopes
   - Create one at: https://github.com/settings/tokens
   - For read-only operations, you can use more restrictive scopes
2. Environment variables:
   - GITHUB_PAT: Your GitHub Personal Access Token (required)
   - OPENAI_API_KEY: Your OpenAI API key (required)
   - OPENAI_MODEL: Your OpenAI model ID (required)
"""


async def github_mcp_example() -> None:
    """Example of using GitHub MCP server with PAT authentication."""
    # 1. Load environment variables from .env file if present
    load_dotenv()

    # 2. Get configuration from environment
    github_pat = os.getenv("GITHUB_PAT")
    if not github_pat:
        raise ValueError(
            "GITHUB_PAT environment variable must be set. Create a token at https://github.com/settings/tokens"
        )

    # 3. Create authentication headers with GitHub PAT
    auth_headers = {
        "Authorization": f"Bearer {github_pat}",
    }

    # 4. Create agent with the GitHub MCP tool using instance method
    # The MCP tool manages the connection to the MCP server and makes its tools available
    # Set approval_mode="never_require" to allow the MCP tool to execute without approval
    client = OpenAIChatClient()
    # This hosted MCP tool is executed remotely by OpenAI, not locally by your application.
    github_mcp_tool = client.get_mcp_tool(
        name="GitHub",
        url="https://api.githubcopilot.com/mcp/",
        headers=auth_headers,
        approval_mode="never_require",
    )

    # 5. Create agent with the GitHub MCP tool
    async with Agent(
        client=client,
        name="GitHubAgent",
        instructions=(
            "You are a helpful assistant that can help users interact with GitHub. "
            "You can search for repositories, read file contents, check issues, and more. "
            "Always be clear about what operations you're performing."
        ),
        tools=github_mcp_tool,
    ) as agent:
        # Example 1: Get authenticated user information
        query1 = "What is my GitHub username and tell me about my account?"
        print(f"\nUser: {query1}")
        result1 = await agent.run(query1)
        print(f"Agent: {result1.text}")

        # Example 2: List my repositories
        query2 = "List all the repositories I own on GitHub"
        print(f"\nUser: {query2}")
        result2 = await agent.run(query2)
        print(f"Agent: {result2.text}")


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

託管 MCP 工具

hostedtool 套件提供用於託管工具的標記類型。 這些工具並非在本地執行——它們會通知 AI 服務可以呼叫服務端已設定的 MCP 伺服器。 在 Go 中,透過 OpenAI 回應 API openaiprovider.NewResponsesAgent使用託管的 MCP 工具。

環境設定

透過環境變數配置模型與 MCP 伺服器端點:

endpoint := os.Getenv("MCP_SERVER_URL")
if endpoint == "" {
    endpoint = "https://learn.microsoft.com/api/mcp"
}

deployment := os.Getenv("OPENAI_RESPONSES_MODEL")
if deployment == "" {
    deployment = "gpt-4o-mini"
}

基本的 MCP 整合

import (
    "os"

    "github.com/microsoft/agent-framework-go/agent"
    "github.com/microsoft/agent-framework-go/provider/openaiprovider"
    "github.com/microsoft/agent-framework-go/tool"
    "github.com/microsoft/agent-framework-go/tool/hostedtool"
)

mcpTool := &hostedtool.MCPServer{
    ServerName:        "microsoft_learn",
    ServerDescription: "Search Microsoft Learn documentation.",
    ServerAddress:     endpoint,
    AllowedTools:      []string{"microsoft_docs_search"},
}

a := openaiprovider.NewResponsesAgent(client, openaiprovider.AgentConfig{
    Model:        deployment,
    Instructions: "You answer questions by searching Microsoft Learn content only.",
    Config: agent.Config{
        Name:  "MicrosoftLearnAgent",
        Tools: []tool.Tool{mcpTool},
    },
})

resp, err := a.RunText(ctx, "Summarize the Azure AI Agent documentation for MCP tool calling.").Collect()

認證 MCP 伺服器

對於需要認證的 MCP 伺服器,請設定 Authorization 或提供標頭。 從應用程式的秘密儲存庫或環境載入祕密,避免將它們交到原始碼控制。

githubMCPTool := &hostedtool.MCPServer{
    ServerName:    "github",
    ServerAddress: "https://api.githubcopilot.com/mcp/",
    Authorization: "Bearer " + os.Getenv("GITHUB_PAT"),
}

多台 MCP 伺服器

當模型應該能在不同的遠端工具組中選擇時,提供多個託管 MCP 伺服器宣告:

tools := []tool.Tool{
    &hostedtool.MCPServer{
        ServerName:    "microsoft_learn",
        ServerAddress: "https://learn.microsoft.com/api/mcp",
        AllowedTools:  []string{"microsoft_docs_search"},
    },
    &hostedtool.MCPServer{
        ServerName:    "github",
        ServerAddress: "https://api.githubcopilot.com/mcp/",
        Authorization: "Bearer " + os.Getenv("GITHUB_PAT"),
    },
}

a := openaiprovider.NewResponsesAgent(client, openaiprovider.AgentConfig{
    Model:        deployment,
    Instructions: "You can search Microsoft documentation and GitHub repositories.",
    Config: agent.Config{
        Name:  "MultiToolAgent",
        Tools: tools,
    },
})

Note

託管的 MCP 工具需要支援的提供者,例如 OpenAI 回應 API 透過 openaiprovider.NewResponsesAgent

後續步驟