Azure MCP サーバーでは、モデル コンテキスト プロトコル (MCP) を使用して、AI アプリと外部ツールとデータ ソース間の統合を標準化し、AI システムが Azure リソースをコンテキスト認識する操作を実行できるようにします。
この記事では、次のタスクを完了する方法について説明します。
- Azure MCP サーバーをインストールして認証する
- Visual Studio Code で GitHub Copilot エージェント モードを使用して Azure MCP Server に接続する
- プロンプトを実行して Azure MCP Server の操作をテストし、Azure リソースと対話する
[前提条件]
- アクティブなサブスクリプションを持つ Azure アカウント
- Visual Studio Code
- GitHub Copilot Visual Studio Code 拡張機能
注
Azure MCP Server でアクセスする予定の Azure リソースは、Azure サブスクリプション内に既に存在している必要があります。 さらに、ユーザー アカウントには、これらのリソースに必要な RBAC ロールとアクセス許可 が割り当てられている必要があります。
Azure MCP サーバーをインストールする
Visual Studio Code で Azure MCP サーバーをインストールするには、次のいずれかのオプションを選択します。
ユーザー設定に Azure MCP Server for Visual Studio Code をインストールするには、次のリンクを選択します。
Visual Studio Code 内でインストール オプションの一覧が開きます。 [ サーバーのインストール ] を選択して、サーバー構成をユーザー設定に追加します。
GitHub Copilot を開き、[エージェント モード] を選択します。 エージェント モードの詳細については、 Visual Studio Code のドキュメントを参照してください。
ツールの一覧を更新して、使用可能なオプションとして Azure MCP サーバーを表示します。
プロンプトを使用して Azure MCP サーバーをテストする
GitHub Copilot を開き、[エージェント モード] を選択します。
エージェントが Azure MCP Server ツール (Azure リソース グループの一覧表示など) を使用するように求めるプロンプトを入力します。
Azure MCP サーバーを認証するために、Copilot はブラウザーを使用して Azure にサインインするように求めます。
注
Azure CLI などの他のローカル ツールを使用して既に認証されている場合、Copilot は Azure へのサインインを求めるメッセージを表示しません。
Copilot は、プロンプトに必要な Azure MCP サーバー操作を実行するためのアクセス許可を要求します。 [ 続行] を選択するか、矢印を使用して、より具体的な動作を選択します。
- 現在のセッション では、常に現在の GitHub Copilot エージェント モード セッションで操作が実行されます。
- 現在のワークスペース では、常に現在の Visual Studio Code ワークスペースに対してコマンドが実行されます。
- 常に許可すると 、GitHub Copilot エージェント モード セッションまたは Visual Studio Code ワークスペースに対して常に実行するように操作が設定されます。
前のプロンプトの出力は、次のテキストのようになります。
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!
次のような関連する他のプロンプトを使用して、Azure MCP 操作を調査してテストします。
List all of the storage accounts in my subscription Get the available tables in my storage accounts
この記事では、次のタスクを完了する方法について説明します。
- Azure MCP サーバーをインストールして認証する
- カスタム .NET クライアントを使用して Azure MCP サーバーに接続する
- プロンプトを実行して Azure MCP Server の操作をテストし、Azure リソースを管理する
[前提条件]
- アクティブなサブスクリプションを持つ Azure アカウント
- .NET 9.0
- Node.js
注
Azure MCP Server でアクセスする予定の Azure リソースは、Azure サブスクリプション内に既に存在している必要があります。 さらに、ユーザー アカウントには、これらのリソースに必要な RBAC ロールとアクセス許可 が割り当てられている必要があります。
ローカル開発へのログイン
Azure MCP Server は、Microsoft Entra ID を使用したトークン ベースの認証を使用したシームレスな認証エクスペリエンスを提供します。 内部的には、Azure MCP Server は DefaultAzureCredential
からのを使用してユーザーを認証します。
Azure MCP Server を使用するには、Azure アカウントでローカルに DefaultAzureCredential
でサポートされているツールのいずれかにサインインする必要があります。 Visual Studio Code ターミナルなどのターミナル ウィンドウを使用してサインインします。
az login
上記のいずれかのツールに正常にサインインすると、Azure MCP Server は資格情報を自動的に検出し、それらを使用して Azure サービスの認証と操作を実行できます。
注
Visual Studio を使用して Azure にサインインすることもできます。 Azure MCP Server は、サインインしているユーザーが実行するアクセス許可を持つ操作のみを実行できます。
.NET ホスト アプリを作成する
.NET コンソール アプリを作成するには、次の手順を実行します。 アプリは AI モデルに接続し、Azure MCP サーバーに接続する MCP クライアントのホストとして機能します。
プロジェクトを作成する
プロジェクトを作成する空のフォルダーにターミナルを開きます。
次のコマンドを実行して、新しい .NET コンソール アプリケーションを作成します。
dotnet new console -n MCPHostApp
新しく作成したプロジェクト フォルダーに移動します。
cd MCPHostApp
Visual Studio Code など、任意のエディターでプロジェクト フォルダーを開きます。
code .
依存関係を追加する
ターミナルで次のコマンドを実行して、必要な 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
MCPHostApp.csproj
ファイルを確認して、パッケージが追加されたことを確認します。次のコマンドを実行してプロジェクトをビルドし、すべてが正しく設定されていることを確認します。
dotnet build
アプリ コードを追加する
Program.cs
の内容を次のコードに置き換えます。
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;
// 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 McpClientFactory.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 ホスト アプリをテストするには、次の手順を実行します。
プロジェクトのルートを開くターミナル ウィンドウで、次のコマンドを実行してアプリを起動します。
dotnet run
アプリが実行されたら、次のテスト プロンプトを入力します。
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!
次のような関連する他のプロンプトを使用して、Azure MCP 操作を調査してテストします。
List all of the storage accounts in my subscription Get the available tables in my storage accounts
この記事では、次のタスクを完了する方法について説明します。
- Azure MCP サーバーをインストールして認証する
- カスタム Python クライアントを使用して Azure MCP サーバーに接続する
- プロンプトを実行して Azure MCP Server の操作をテストし、Azure リソースを管理する
[前提条件]
- アクティブなサブスクリプションを持つ Azure アカウント
- Python 3.9 以降 がローカルにインストールされている
- ローカルにインストールされた Node.js
注
Azure MCP Server でアクセスする予定の Azure リソースは、Azure サブスクリプション内に既に存在している必要があります。 さらに、ユーザー アカウントには、これらのリソースに必要な RBAC ロールとアクセス許可 が割り当てられている必要があります。
ローカル開発へのログイン
Azure MCP Server は、Microsoft Entra ID を使用したトークン ベースの認証を使用したシームレスな認証エクスペリエンスを提供します。 内部的には、Azure MCP Server は DefaultAzureCredential
からのを使用してユーザーを認証します。
Azure MCP Server を使用するには、Azure アカウントでローカルに DefaultAzureCredential
でサポートされているツールのいずれかにサインインする必要があります。 Visual Studio Code ターミナルなどのターミナル ウィンドウを使用してサインインします。
az login
上記のいずれかのツールに正常にサインインすると、Azure MCP Server は資格情報を自動的に検出し、それらを使用して Azure サービスの認証と操作を実行できます。
注
Visual Studio を使用して Azure にサインインすることもできます。 Azure MCP Server は、サインインしているユーザーが実行するアクセス許可を持つ操作のみを実行できます。
Python アプリを作成する
Python アプリを作成するには、次の手順を実行します。 アプリは AI モデルに接続し、Azure MCP サーバーに接続する MCP クライアントのホストとして機能します。
プロジェクトを作成する
任意のエディター内で空のフォルダーを開きます。
requirements.txt
という名前の新しいファイルを作成し、次のライブラリの依存関係を追加します。mcp azure-identity openai logging
同じフォルダーに、
.env
という名前の新しいファイルを作成し、次の環境変数を追加します。AZURE_OPENAI_ENDPOINT=<your-azure-openai-endpoint> AZURE_OPENAI_MODEL=<your-model-deployment-name>
main.py
という名前の空のファイルを作成して、アプリのコードを保持します。
環境を作成して依存関係をインストールする
新しいフォルダーでターミナルを開き、アプリ用の Python 仮想環境を作成します。
python -m venv venv
仮想環境をアクティブ化します。
venv\Scripts\activate
requirements.txt
から依存関係をインストールします。pip install -r requirements.txt
アプリ コードを追加する
次のコードを使用して、 Main.py
の内容を更新します。
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
import json, os, logging, asyncio
from dotenv import load_dotenv
# Setup logging and load environment variables
logger = logging.getLogger(__name__)
load_dotenv()
# Azure OpenAI configuration
AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
AZURE_OPENAI_MODEL = os.getenv("AZURE_OPENAI_MODEL", "gpt-4o")
# Initialize Azure credentials
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
async def run():
# Initialize Azure OpenAI client
client = AzureOpenAI(
azure_endpoint=AZURE_OPENAI_ENDPOINT,
api_version="2024-04-01-preview",
azure_ad_token_provider=token_provider
)
# MCP client configurations
server_params = StdioServerParameters(
command="npx",
args=["-y", "@azure/mcp@latest", "server", "start"],
env=None
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# List available tools
tools = await session.list_tools()
for tool in tools.tools: print(tool.name)
# Format tools for Azure OpenAI
available_tools = [{
"type": "function",
"function": {
"name": tool.name,
"description": tool.description,
"parameters": tool.inputSchema
}
} for tool in tools.tools]
# Start conversational loop
messages = []
while True:
try:
user_input = input("\nPrompt: ")
messages.append({"role": "user", "content": user_input})
# First API call with tool configuration
response = client.chat.completions.create(
model = AZURE_OPENAI_MODEL,
messages = messages,
tools = available_tools)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
function_args = json.loads(tool_call.function.arguments)
result = await session.call_tool(tool_call.function.name, function_args)
# Add the tool response to the messages
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": tool_call.function.name,
"content": result.content,
})
else:
logger.info("No tool calls were made by the model")
# Get the final response from the model
final_response = client.chat.completions.create(
model = AZURE_OPENAI_MODEL,
messages = messages,
tools = available_tools)
for item in final_response.choices:
print(item.message.content)
except Exception as e:
logger.error(f"Error in conversation loop: {e}")
print(f"An error occurred: {e}")
if __name__ == "__main__":
import asyncio
asyncio.run(run())
上記のコードでは、次のタスクを実行します。
- ログ記録を設定し、
.env
ファイルから環境変数を読み込みます。 -
azure-identity
ライブラリとopenai
ライブラリを使用して Azure OpenAI クライアントを構成します。 - 標準の I/O トランスポートを使用して、Azure MCP サーバーと対話するように MCP クライアントを初期化します。
- MCP サーバーから使用可能なツールの一覧を取得して表示します。
- ユーザー プロンプトの処理、ツールの利用、ツール呼び出しの処理を行う会話ループを実装します。
アプリを実行してテストする
.NET ホスト アプリをテストするには、次の手順を実行します。
プロジェクトのルートを開くターミナル ウィンドウで、次のコマンドを実行してアプリを起動します。
python main.py
アプリが実行されたら、次のテスト プロンプトを入力します。
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!
次のような関連する他のプロンプトを使用して、Azure MCP 操作を調査してテストします。
List all of the storage accounts in my subscription Get the available tables in my storage accounts