共用方式為


開始使用 Azure MCP 伺服器

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

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

  • 安裝及驗證 Azure MCP 伺服器
  • 在 Visual Studio Code 中使用 GitHub Copilot 代理程式模式連線到 Azure MCP 伺服器
  • 執行提示以測試 Azure MCP 伺服器作業,並與 Azure 資源互動

先決條件

備註

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

安裝 Azure MCP 伺服器

選取下列其中一個選項,以在 Visual Studio Code 中安裝 Azure MCP 伺服器:

  1. 若要在使用者設定中安裝適用於 Visual Studio Code 的 Azure MCP 伺服器,請選取下列連結:

    在 Visual Studio Code 中使用 NPX 安裝

    Visual Studio Code 內會開啟安裝選項清單。 選取 [安裝伺服器 ] 以將伺服器組態新增至您的用戶設定。

    顯示 Azure MCP 伺服器安裝選項的螢幕快照。

  2. 開啟 GitHub Copilot,然後選取 [代理程式模式]。 若要深入瞭解代理程式模式,請流覽 Visual Studio Code 檔

  3. 重新整理工具清單,以查看 Azure MCP 伺服器作為可用選項:

    顯示 Azure MCP Server 作為 GitHub Copilot 工具的螢幕快照。

使用提示來測試 Azure MCP 伺服器

  1. 開啟 GitHub Copilot,然後選取 [代理程式模式]。

  2. 輸入提示,讓代理程式使用 Azure MCP 伺服器工具,例如 列出我的 Azure 資源群組

  3. 為了驗證 Azure MCP 伺服器,Copilot 會提示您使用瀏覽器登入 Azure。

    備註

    如果您已經透過 Azure CLI 等其他本機工具進行驗證,Copilot 將不會提示您登入 Azure。

  4. Copilot 會要求許可權,以執行提示所需的 Azure MCP 伺服器作業。 選取 [繼續 ] 或使用箭號來選取更特定的行為:

    • 目前的會話 一律會在目前的 GitHub Copilot 代理程式模式會話中執行作業。
    • 目前工作區 一律會執行目前 Visual Studio Code 工作區的指令。
    • 一律允許 將作業設定為一律針對任何 GitHub Copilot 代理程式模式會話或任何 Visual Studio Code 工作區執行。

    螢幕快照,顯示可用來執行 Azure MCP 伺服器作業的選項。

    上一個提示的輸出應該類似下列文字:

    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!
    
  5. 使用其他相關提示探索及測試 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 伺服器作業和管理 Azure 資源

先決條件

備註

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

用於本機開發的登入

Azure MCP 伺服器透過 Microsoft Entra ID,透過令牌型驗證提供順暢的驗證體驗。 在內部,Azure MCP 伺服器會從 DefaultAzureCredential使用 來驗證使用者。

您必須使用 Azure 帳戶登入本機支援的 DefaultAzureCredential 其中一個工具,才能使用 Azure MCP 伺服器。 使用終端機視窗登入,例如 Visual Studio Code 終端機:

az login

成功登入上述其中一個工具之後,Azure MCP 伺服器就可以自動探索您的認證,並使用它們來驗證及執行 Azure 服務上的作業。

備註

您也可以透過Visual Studio登入 Azure。 Azure MCP 伺服器只能執行登入使用者具有執行許可權的作業。

建立 .NET 主機應用程式

完成下列步驟以建立 .NET 控制台應用程式。 應用程式會連線到 AI 模型,並做為連線至 Azure MCP Server 之 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;
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庫。
  • 建立 MCP 用戶端,以使用標準 I/O 傳輸與 Azure 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
    

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

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

先決條件

備註

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

用於本機開發的登入

Azure MCP 伺服器透過 Microsoft Entra ID,透過令牌型驗證提供順暢的驗證體驗。 在內部,Azure MCP 伺服器會從 DefaultAzureCredential使用 來驗證使用者。

您必須使用 Azure 帳戶登入本機支援的 DefaultAzureCredential 其中一個工具,才能使用 Azure MCP 伺服器。 使用終端機視窗登入,例如 Visual Studio Code 終端機:

az login

成功登入上述其中一個工具之後,Azure MCP 伺服器就可以自動探索您的認證,並使用它們來驗證及執行 Azure 服務上的作業。

備註

您也可以透過Visual Studio登入 Azure。 Azure MCP 伺服器只能執行登入使用者具有執行許可權的作業。

建立 Python 應用程式

完成下列步驟以建立 Python 應用程式。 應用程式會連線到 AI 模型,並做為連線至 Azure MCP Server 之 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 伺服器互動。
  • 從 MCP 伺服器擷取並顯示可用的工具清單。
  • 實作交談迴圈來處理使用者提示、利用工具及處理工具呼叫。

執行及測試應用程式

完成下列步驟以測試 .NET 主機應用程式:

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

    python main.py
    
  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
    

後續步驟