将代理作为 MCP 工具使用

本教程介绍如何通过模型上下文协议(MCP)将代理公开为工具,以便其他支持 MCP 工具的系统可以使用它。

先决条件

有关先决条件,请参阅本教程中的 “创建并运行简单的代理 ”步骤。

安装 NuGet 包

若要将 Microsoft Agent Framework 与 Azure OpenAI 配合使用,需要安装以下 NuGet 包:

dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

若要添加对通过模型上下文协议(MCP)托管工具的支持,请添加以下 NuGet 包

dotnet add package Microsoft.Extensions.Hosting --prerelease
dotnet add package ModelContextProtocol --prerelease

将代理作为 MCP 工具使用

可以通过将AIAgent包装在函数中,并使用McpServerTool将其公开为 MCP 工具。 然后,需要将其注册到 MCP 服务器。 这允许代理被任何 MCP 兼容的客户端调用为工具。

首先,创建一个智能体,将其作为 MCP 工具公开。

using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using OpenAI;

AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .CreateAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

将代理转换为函数工具,然后变成 MCP 工具。 代理名称和说明将用作 mcp 工具名称和说明。

using ModelContextProtocol.Server;

McpServerTool tool = McpServerTool.Create(agent.AsAIFunction());

设置 MCP 服务器以侦听通过标准输入/输出传入的请求并公开 MCP 工具:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;

HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithTools([tool]);

await builder.Build().RunAsync();

这将启动一个 MCP 服务器,该服务器通过 MCP 协议将代理公开为工具。

本教程介绍如何通过模型上下文协议(MCP)将代理公开为工具,以便其他支持 MCP 工具的系统可以使用它。

先决条件

有关先决条件和安装 Python 包,请参阅本教程中的 “创建并运行简单代理 ”步骤。

将代理公开为 MCP 服务器

可以使用该方法 as_mcp_server() 将代理公开为 MCP 服务器。 这允许代理被任何 MCP 兼容的客户端调用为工具。

首先,创建一个将作为 MCP 服务器公开的代理程序。 还可以将工具添加到代理:

from typing import Annotated
from agent_framework.openai import OpenAIResponsesClient

def get_specials() -> Annotated[str, "Returns the specials from the menu."]:
    return """
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        """

def get_item_price(
    menu_item: Annotated[str, "The name of the menu item."],
) -> Annotated[str, "Returns the price of the menu item."]:
    return "$9.99"

# Create an agent with tools
agent = OpenAIResponsesClient().create_agent(
    name="RestaurantAgent",
    description="Answer questions about the menu.",
    tools=[get_specials, get_item_price],
)

将代理转换为 MCP 服务器。 代理名称和说明将用作 MCP 服务器元数据:

# Expose the agent as an MCP server
server = agent.as_mcp_server()

设置 MCP 服务器以侦听通过标准输入/输出传入的请求:

import anyio
from mcp.server.stdio import stdio_server

async def run():
    async def handle_stdin():
        async with stdio_server() as (read_stream, write_stream):
            await server.run(read_stream, write_stream, server.create_initialization_options())

    await handle_stdin()

if __name__ == "__main__":
    anyio.run(run)

这将启动一个 MCP 服务器,该服务器通过 MCP 协议公开代理,允许 MCP 兼容的客户端(如 VS Code GitHub Copilot 代理)使用它。

后续步骤