Azure MCP サーバーでは、モデル コンテキスト プロトコル (MCP) を使用して、AI アプリと外部ツールとデータ ソース間の統合を標準化し、AI システムが Azure リソースをコンテキスト認識する操作を実行できるようにします。
この記事では、次のタスクを完了する方法について説明します。
- Azure MCP サーバーをインストールして認証する
- カスタム Python クライアントを使用して Azure MCP サーバーに接続する
- プロンプトを実行して Azure MCP Server の操作をテストし、Azure リソースを管理する
[前提条件]
- アクティブなサブスクリプションを持つ Azure アカウント
- Python 3.9 以降 がインストールされている
- Node.js LTS がインストールされている
注
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 プロトコルを実行するローカル プロセス) に接続する 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\activaterequirements.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 クライアントを初期化します。
- Azure MCP サーバーから使用可能なツール (MCP 登録済み Azure 操作) の一覧を取得して表示します。
- ユーザー プロンプトの処理、ツールの利用、ツール呼び出しの処理を行う会話ループを実装します。
構成パラメーター:
| パラメーター | Description | Example |
|---|---|---|
AZURE_OPENAI_ENDPOINT |
Azure OpenAI サービス エンドポイント | https://your-resource.openai.azure.com/ |
AZURE_OPENAI_MODEL |
モデル展開名 | gpt-4o |
| トークン スコープ | Azure Cognitive Services OAuth スコープ | https://cognitiveservices.azure.com/.default |
| 認証 |
DefaultAzureCredential (Azure CLI、マネージド ID、またはその他の資格情報チェーン) を使用します |
Azure ID のドキュメントを参照する |
| 必要な RBAC | Azure OpenAI リソースの Cognitive Services ユーザー ロールまたはそれに相当するロール | Azure portal または CLI を使用して割り当てられる |
アプリを実行してテストする
Python アプリをテストするには、次の手順を実行します。
プロジェクトのルートを開くターミナル ウィンドウで、次のコマンドを実行してアプリを起動します。
python main.py成功確認: アプリには、使用可能な Azure MCP サーバー ツールの一覧が表示され、
Prompt:入力が表示されます。アプリが実行されたら、次のテスト プロンプトを入力します。
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