次の方法で共有


.NET での Azure MCP サーバーの使用を開始する

Azure MCP サーバーでは、モデル コンテキスト プロトコル (MCP) を使用して、AI アプリと外部ツールとデータ ソース間の統合を標準化し、AI システムが Azure リソースをコンテキスト認識する操作を実行できるようにします。

この記事では、次のタスクを完了する方法について説明します。

  • Azure MCP サーバーをインストールして認証する
  • カスタム .NET クライアントを使用して Azure MCP サーバーに接続する
  • プロンプトを実行して Azure MCP Server の操作をテストし、Azure リソースを管理する

[前提条件]

Azure MCP Server でアクセスする予定の Azure リソースは、Azure サブスクリプション内に既に存在している必要があります。 さらに、ユーザー アカウントには、これらのリソースに必要な RBAC ロールとアクセス許可 が割り当てられている必要があります。

ローカル開発のために Azure MCP Server にサインインする

Azure MCP Server は、.NET 用 Azure ID ライブラリを使用して Microsoft Entra ID に対して認証を行います。 サーバーでは、 次の 2 つの認証モードがサポートされています。

  • ブローカー モード: InteractiveBrowserCredentialでオペレーティング システムのネイティブ認証 (Windows Web アカウント マネージャーなど) を使用します。
  • 資格情報チェーン モード: 環境変数、Visual Studio Code、Visual Studio、Azure CLI、Azure PowerShell、Azure Developer CLI、対話型ブラウザー認証など、複数の認証方法を順番に試行します。

次のいずれかの方法を使用してサインインします。

  1. コマンド パレットを開きます (Mac のCtrl+Shift+P または Cmd+Shift+P )。
  2. Azure を実行する: サインインし、指示に従います。

サインイン後、Azure MCP Server は、アクセス許可に基づいて Azure サービスに対する操作を認証して実行できます。

.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抽象化を初期化します。
  • 標準の I/O トランスポートを使用して Azure MCP サーバーと対話する 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
    

次のステップ