教學:使用 MCP 搭配動態會話(Python)

這很重要

動態會話的平台管理 MCP 伺服器目前處於 預覽階段。 API 版本 2025-02-02-previewmcpServerSettings 屬性可能會變更。

這個教學示範如何在啟用平台管理的 MCP 伺服器後建立一個會話池,連接並遠端執行 Python 程式碼。

獨立的 MCP 伺服器教學不同,你不需要撰寫或部署 MCP 伺服器程式碼。 該平台提供內建的 Python 會話池工具:

工具 Description
launchShell 建立一個新環境並傳回environmentId
runPythonCodeInRemoteEnvironment 在現有環境中執行 Python 程式碼
runShellCommandInRemoteEnvironment 在現有環境中執行 shell 指令

在本教學課程中,您會:

  • 建立一個啟用 MCP 伺服器的 Python 會話池
  • 取得 MCP 端點與 API 金鑰
  • 初始化 MCP 連線並透過 JSON-RPC 執行 Python 程式碼
  • 將 MCP 伺服器連接到 VS Code 中的 GitHub Copilot。

先決條件

Requirement Description
Azure 帳戶 具有有效訂閱的 Azure 帳戶。 免費創建一個
Azure CLI 安裝 Azure CLI
curl curl (大多數 Linux 和 macOS 系統預裝)。
jq JQ JSON 處理器,用於解析 API 回應。
VS Code 具有 GitHub Copilot 延伸模組的 Visual Studio Code (適用於 Copilot 整合區段)。

設定

  1. 更新 Azure CLI 並安裝容器應用擴充功能:

    az upgrade
    az provider register --namespace Microsoft.App
    az extension add --name containerapp --allow-preview true --upgrade
    
  2. 登入並設定您的訂閱:

    az login
    SUBSCRIPTION_ID=$(az account show --query id --output tsv)
    az account set -s $SUBSCRIPTION_ID
    
  3. 為本教學設定變數。 用你的數值替換佔位符:

    RESOURCE_GROUP=<RESOURCE_GROUP_NAME>
    SESSION_POOL_NAME=<SESSION_POOL_NAME>
    LOCATION=<LOCATION>
    
  4. 建立資源群組:

    az group create --name $RESOURCE_GROUP --location $LOCATION
    

建立一個與 MCP 伺服器的 Python 會話池

使用啟用 MCP 的 ARM 範本部署會話池。

  1. 建立名為 deploy.json

    {
        "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
            "name": { "type": "String" },
            "location": { "type": "String" }
        },
        "resources": [
            {
                "type": "Microsoft.App/sessionPools",
                "apiVersion": "2025-02-02-preview",
                "name": "[parameters('name')]",
                "location": "[parameters('location')]",
                "properties": {
                    "poolManagementType": "Dynamic",
                    "containerType": "PythonLTS",
                    "scaleConfiguration": {
                        "maxConcurrentSessions": 5
                    },
                    "sessionNetworkConfiguration": {
                        "status": "EgressEnabled"
                    },
                    "dynamicPoolConfiguration": {
                        "lifecycleConfiguration": {
                            "lifecycleType": "Timed",
                            "coolDownPeriodInSeconds": 300
                        }
                    },
                    "mcpServerSettings": {
                        "isMCPServerEnabled": true
                    }
                }
            }
        ]
    }
    

    備註

    此範本中的關鍵屬性:

    • containerType: "PythonLTS": 建立使用 Python 執行環境的會話。
    • mcpServerSettings.isMCPServerEnabled: true: 啟用平台管理的 MCP 端點。
    • coolDownPeriodInSeconds: 300:工作階段會在閒置 5 分鐘後銷毀。
  2. 部署範本:

使用 ARM 範本建立一個啟用 MCP 伺服器的 Python 會話池。

  1. 建立一個名為 deploy.json 的部署範本文件:

    {
        "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
            "name": { "type": "String" },
            "location": { "type": "String" }
        },
        "resources": [
              {
                "type": "Microsoft.App/sessionPools",
                "apiVersion": "2025-10-02-preview",
                "name": "[parameters('name')]",
                "location": "[parameters('location')]",
                "properties": {
                    "poolManagementType": "Dynamic",
                    "containerType": "PythonLTS", # Set the "containerType" property to "PythonLTS"
                    "scaleConfiguration": {
                        "maxConcurrentSessions": 5
                    },
                    "sessionNetworkConfiguration": {
                        "status": "EgressEnabled"
                    },
                    "dynamicPoolConfiguration": {
                        "lifecycleConfiguration": {
                            "lifecycleType": "Timed",
                            "coolDownPeriodInSeconds": 300
                        }
                    },
                    "mcpServerSettings": { 
                        "isMCPServerEnabled": true # Add the "mcpServerSettings" section to enable the MCP server
                    }
                }
            }
        ]
    }
    
  2. 部署 ARM 範本。

    az deployment group create \
      --resource-group $RESOURCE_GROUP \
      --template-file deploy.json \
      --parameters name=$SESSION_POOL_NAME location=$LOCATION
    

取得 MCP 伺服器端點

部署完成後,取得會話池的 MCP 端點 URL。

MCP_ENDPOINT=$(az rest --method GET --uri "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.App/sessionPools/$SESSION_POOL_NAME" --uri-parameters api-version=2025-10-02-preview --query "properties.mcpServerSettings.mcpServerEndpoint" -o tsv)

取得 MCP 伺服器憑證

平台管理的 MCP 伺服器透過 HTTP 標頭使用 API 金鑰認證 x-ms-apikey 。 此認證方法與標準會話池管理 API 所使用的承載憑證認證不同。

API_KEY=$(az rest --method POST --uri "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.App/sessionPools/$SESSION_POOL_NAME/fetchMCPServerCredentials" --uri-parameters api-version=2025-10-02-preview --query "apiKey" -o tsv)

警告

把 API 金鑰當作秘密來處理。 不要提交至程式碼管理系統,也不要公開分享。 金鑰會驗證所有對您工作階段集區的 MCP 工具叫用。

初始化 MCP 伺服器

發送 JSON-RPC 請求以建立 MCP 連線:

curl -sS -X POST "$MCP_ENDPOINT" \
    -H "Content-Type: application/json" \
    -H "x-ms-apikey: $API_KEY" \
    -d '{ "jsonrpc": "2.0", "id": "1", "method": "initialize" }'

你應該會看到包含以下回覆:

  • protocolVersion2025-03-26
  • serverInfo.nameMicrosoft Container Apps MCP Server
  • capabilities.tools{ "call": true, "list": true }

啟動 Python 環境

建立新的 Python 環境:

ENVIRONMENT_RESPONSE=$(curl -sS -X POST "$MCP_ENDPOINT" \
    -H "Content-Type: application/json" \
    -H "x-ms-apikey: $API_KEY" \
    -d '{ "jsonrpc": "2.0", "id": "2", "method": "tools/call", "params": { "name": "launchShell", "arguments": {} } }')

echo $ENVIRONMENT_RESPONSE

從回應中的environmentId欄位中擷取structuredContent。 你需要這個 ID 才能用於所有後續指令。

ENVIRONMENT_ID=$(echo $ENVIRONMENT_RESPONSE | jq -r '.result.structuredContent.environmentId')
echo $ENVIRONMENT_ID

備註

launchShell 工具會產生唯一的環境識別碼。 實際的工作階段是「延遲」分配。 當你執行第一個命令時,工作階段集區會指派一個 Hyper-V 隔離的容器來處理它。

執行 Python 指令

要在遠端環境中執行 Python 程式碼,請使用前一步的步驟 $ENVIRONMENT_ID

curl -sS -X POST "$MCP_ENDPOINT" \
    -H "Content-Type: application/json" \
    -H "x-ms-apikey: $API_KEY" \
    -d '{
        "jsonrpc": "2.0",
        "id": "3",
        "method": "tools/call",
        "params": {
            "name": "runPythonCodeInRemoteEnvironment",
            "arguments": {
                "environmentId": "'"$ENVIRONMENT_ID"'",
                "pythonCode": "import sys; print(f\"Python {sys.version}\")"
            }
        }
    }'

回覆包含stdoutstructuredContent欄位中的指令結果。

試試一個更複雜的例子:

curl -sS -X POST "$MCP_ENDPOINT" \
    -H "Content-Type: application/json" \
    -H "x-ms-apikey: $API_KEY" \
    -d '{
        "jsonrpc": "2.0",
        "id": "4",
        "method": "tools/call",
        "params": {
            "name": "runPythonCodeInRemoteEnvironment",
            "arguments": {
                "environmentId": "'"$ENVIRONMENT_ID"'",
                "pythonCode": "import math\nresults = {n: math.factorial(n) for n in range(1, 11)}\nfor k, v in results.items():\n    print(f\"{k}! = {v}\")"
            }
        }
    }'

在 VS Code 中連接 GitHub Copilot

你可以將會話池 MCP 伺服器連接到 GitHub Copilot,以便在程式碼執行環境中提供自然語言介面。

  1. 在你的專案中創作 .vscode/mcp.json

    {
        "servers": {
            "aca-python-sessions": {
                "type": "http",
                "url": "<MCP_ENDPOINT>",
                "headers": {
                    "x-ms-apikey": "<API_KEY>"
                }
            }
        }
    }
    

    <MCP_ENDPOINT><API_KEY>替換為先前步驟的數值。

    警告

    不要把 MCP API 金鑰提交給原始碼控制。 在生產環境中使用環境變數或秘密管理器。 將 .vscode/mcp.json 添加到你的 .gitignore

  2. 打開 VS Code,然後在客服模式下開啟 Copilot Chat

  3. 驗證 aca-python-sessions 會出現在工具清單中。

  4. 用以下提示來測試:

    • 「啟動 Python 環境並計算前 20 個費波那契數列」
    • 「執行一個 Python 腳本,擷取 https://api.github.com 並列印回應標頭」

清理資源

完成這個教學後,移除你創建的資源以避免產生費用。

az group delete --resource-group $RESOURCE_GROUP