共用方式為


開始搭配 Python 使用 Azure MCP 伺服器

Azure MCP 伺服器會使用模型內容通訊協定 (MCP) 來標準化 AI 應用程式與外部工具和資料來源之間的整合,讓 AI 系統能夠執行內容感知 Azure 資源的作業。

在本文中,您將瞭解如何完成下列工作:

  • 安裝並驗證 Azure MCP 伺服器
  • 使用自訂 Python 用戶端連線到 Azure MCP 伺服器
  • 執行提示以測試 Azure MCP 伺服器作業並管理 Azure 資源

先決條件

備註

您想要使用 Azure MCP 伺服器存取的 Azure 資源必須已存在於您的 Azure 訂用帳戶中。 此外,您的使用者帳戶必須具有為這些資源指派的必要 RBAC 角色和許可

登入 Azure MCP 伺服器進行本地開發

Azure MCP Server 使用 .NET 的 Azure Identity 函式庫來認證 Microsoft Entra ID。 伺服器支援 兩種認證模式

  • 經紀人模式:使用作業系統的原生認證(類似 Windows Web 帳戶管理器)並搭配 InteractiveBrowserCredential
  • 憑證鏈模式:依序嘗試多種認證方法:環境變數、Visual Studio Code、Visual Studio、Azure CLI、Azure PowerShell、Azure Developer CLI,以及互動式瀏覽器驗證。

請使用以下任一方法登入:

  1. 打開指令面板(Ctrl+Shift+PCmd+Shift+P 在 Mac 上)。
  2. 執行 Azure:登入 並依照提示操作。

登入後,Azure MCP 伺服器可以根據你的權限認證並執行 Azure 服務的操作。

建立 Python 應用程式

請完成以下步驟來建立一個 Python 應用程式(主機應用程式)。 該應用程式連接 AI 模型,並作為 MCP 用戶端的主機,該用戶端連接至 Azure MCP 伺服器(執行 MCP 協定的本地程序)。

建立專案

  1. 在您選擇的編輯器中開啟空白資料夾。

  2. 建立名為的新 requirements.txt 檔案,並新增下列程式庫相依性:

    mcp
    azure-identity
    openai
    logging
    
  3. 在相同的資料夾中,建立名為的新檔案 .env ,並新增下列環境變數:

    AZURE_OPENAI_ENDPOINT=<your-azure-openai-endpoint>
    AZURE_OPENAI_MODEL=<your-model-deployment-name>
    
  4. 建立名為的 main.py 空白檔案,以保存應用程式的程式碼。

建立環境並安裝相依性

  1. 在新資料夾中開啟終端機,並為應用程式建立 Python 虛擬環境:

    python -m venv venv
    
  2. 啟動虛擬環境:

    venv\Scripts\activate
    
  3. 從以下位置安裝 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-identityopenai 程式庫來設定 Azure OpenAI 用戶端。
  • 初始化 MCP 用戶端,以使用標準 I/O 傳輸方式與 Azure 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、托管身份識別或其他憑證鏈) 參見 Azure Identity documentation
所需的 RBAC 認知服務 Azure OpenAI 資源上的使用者角色或等效角色 透過 Azure 入口網站或 CLI 指派

執行並測試應用程式

請完成以下步驟來測試您的 Python 應用程式:

  1. 在開啟專案根目錄的終端機視窗中,執行下列命令來啟動應用程式:

    python main.py
    

    成功驗證:應用程式應該會顯示可用 Azure MCP Server 工具清單,然後顯示輸入 Prompt:

  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
    

後續步驟