Azure MCP 伺服器會使用模型內容通訊協定 (MCP) 來標準化 AI 應用程式與外部工具和資料來源之間的整合,讓 AI 系統能夠執行內容感知 Azure 資源的作業。
在本文中,您將瞭解如何完成下列工作:
- 安裝並驗證 Azure MCP 伺服器
- 使用自訂 Python 用戶端連線到 Azure MCP 伺服器
- 執行提示以測試 Azure MCP 伺服器作業並管理 Azure 資源
先決條件
- 具有作用中訂用帳戶的 Azure 帳戶
- 已安裝 Python 3.9 或更高版本
- Node.js 已安裝 LTS
備註
您想要使用 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 伺服器只能執行登入使用者具有執行權限的作業。
建立 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 用戶端。 - 初始化 MCP 用戶端,以使用標準 I/O 傳輸與 Azure 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