本教學課程說明如何透過模型內容通訊協定 (MCP) 將代理程式公開為工具,以便支援 MCP 工具的其他系統可以使用它。
先決條件
如需必要條件,請參閱本教學課程中的 建立並執行簡式代理程式 步驟。
安裝 NuGet 套件
若要搭配 Azure OpenAI 使用 Microsoft Agent Framework,您必須安裝下列 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 當作 MCP 工具進行公開,方法是將它包裝在函數中並使用 McpServerTool。 然後,您需要向 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 代理程式) 使用它。