通过 .NET 开始使用 Azure MCP 服务器

Azure MCP 服务器使用模型上下文协议(MCP)来标准化 AI 应用与外部工具和数据源之间的集成,使 AI 系统能够执行上下文感知 Azure 资源的作。

本文介绍如何完成以下任务:

  • 安装和向 Azure MCP 服务器进行身份验证
  • 使用自定义 .NET 客户端连接到 Azure MCP 服务器
  • 运行提示以测试 Azure MCP 服务器作和管理 Azure 资源

先决条件

注释

要通过 Azure MCP 服务器访问的 Azure 资源必须已存在于 Azure 订阅中。 此外,用户帐户必须具有为这些资源分配的必要 RBAC 角色和权限

用于本地开发的登录

Azure MCP 服务器通过 Microsoft Entra ID 使用基于令牌的身份验证提供无缝身份验证体验。 在内部,Azure MCP 服务器使用 DefaultAzureCredentialAzure 标识库 对用户进行身份验证。

需要使用 Azure 帐户登录到本地支持 DefaultAzureCredential 的工具之一,才能使用 Azure MCP 服务器。 使用终端窗口登录,例如 Visual Studio Code 终端:

az login

成功登录到上述工具之一后,Azure MCP 服务器可以自动发现凭据,并使用凭据对 Azure 服务进行身份验证和执行作。

注释

还可以通过 Visual Studio 登录到 Azure。 Azure MCP 服务器只能运行已登录用户有权执行的作。

创建 .NET 主机应用

完成以下步骤以创建 .NET 控制台应用。 该应用连接到 AI 模型,充当连接到 Azure MCP 服务器的 MCP 客户端的主机。

创建项目

  1. 打开要在其中创建项目的空文件夹的终端。

  2. 运行以下命令以创建新的 .NET 控制台应用程序:

    dotnet new console -n MCPHostApp
    
  3. 导航到新建的项目文件夹:

    cd MCPHostApp
    
  4. 在所选编辑器中打开项目文件夹,例如 Visual Studio Code:

    code .
    

添加依赖项

  1. 在终端中运行以下命令,添加所需的 NuGet 包:

    dotnet add package Azure.AI.OpenAI --prerelease
    dotnet add package Azure.Identity
    dotnet add package Microsoft.Extensions.AI --prerelease
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package ModelContextProtocol --prerelease
    
  2. 通过检查 MCPHostApp.csproj 文件来验证是否已添加包。

  3. 运行以下命令来生成项目,并确保一切设置正确:

    dotnet build
    

添加应用代码

Program.cs 的内容替换为以下代码:

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;

// Create an IChatClient
IChatClient client =
    new ChatClientBuilder(
        new AzureOpenAIClient(new Uri("<your-azure-openai-endpoint>"), 
        new DefaultAzureCredential())
        .GetChatClient("gpt-4o").AsIChatClient())
    .UseFunctionInvocation()
    .Build();

// Create the MCP client
var mcpClient = await McpClient.CreateAsync(
    new StdioClientTransport(new()
    {
        Command = "npx",
        Arguments = ["-y", "@azure/mcp@latest", "server", "start"],
        Name = "Azure MCP",
    }));

// Get all available tools from the MCP server
Console.WriteLine("Available tools:");
var tools = await mcpClient.ListToolsAsync();
foreach (var tool in tools)
{
    Console.WriteLine($"{tool}");
}
Console.WriteLine();

// Conversational loop that can utilize the tools
List<ChatMessage> messages = [];
while (true)
{
    Console.Write("Prompt: ");
    messages.Add(new(ChatRole.User, Console.ReadLine()));

    List<ChatResponseUpdate> updates = [];
    await foreach (var update in client
        .GetStreamingResponseAsync(messages, new() { Tools = [.. tools] }))
    {
        Console.Write(update);
        updates.Add(update);
    }
    Console.WriteLine();

    messages.AddMessages(updates);
}

前面的代码完成以下任务:

  • IChatClient使用Microsoft.Extensions.AI库初始化抽象。
  • 创建 MCP 客户端,以使用标准 I/O 传输与 Azure MCP 服务器交互。 提供的 npx 命令和相应的参数下载并启动 Azure MCP 服务器。
  • 从 MCP 服务器检索和显示可用工具的列表,这是标准 MCP 函数。
  • 实现一个聊天循环,该循环处理用户提示并利用工具进行响应。

运行并测试应用

完成以下步骤以测试 .NET 主机应用:

  1. 在打开到项目的根目录中的终端窗口中,运行以下命令以启动应用:

    dotnet run
    
  2. 应用运行后,请输入以下测试提示:

    List all of the resource groups in my subscription
    

    上一提示的输出应类似于以下文本:

    The following resource groups are available for your subscription:
    
    1. **DefaultResourceGroup-EUS** (Location: `eastus`)
    2. **rg-testing** (Location: `centralus`)
    3. **rg-azd** (Location: `eastus2`)
    4. **msdocs-sample** (Location: `southcentralus`)
    14. **ai-testing** (Location: `eastus2`)
    
    Let me know if you need further details or actions related to any of these resource groups!
    
  3. 使用其他相关提示浏览和测试 Azure MCP作,例如:

    List all of the storage accounts in my subscription
    Get the available tables in my storage accounts
    

后续步骤