Condividi tramite


Guida introduttiva: Usare SQL MCP Server con App Azure Container

Diagramma che mostra un server MCP SQL distribuito in App Contenitore di Azure.

Importante

Il server MCP (SQL Model Context Protocol) è in anteprima e questa documentazione e l'implementazione del motore può cambiare. Anche se Generatore API dati versione 1.7 è in anteprima, è necessario usare la versione non definitiva in modo esplicito (ad esempio, 1.7.83-rc) perché le funzionalità MCP non sono ancora incluse nel :latest tag.

Questa guida introduttiva illustra come distribuire SQL MCP Server in App Contenitore di Azure. Dopo la distribuzione, è possibile connettersi a esso da Visual Studio Code (VS Code), Microsoft Foundry o qualsiasi altro client MCP (Model Context Protocol) come endpoint server remoto.

Diagramma di sequenza che mostra il flusso di lavoro per la distribuzione ACA.

Prerequisiti

Sottoscrizione di Azure

È necessaria una sottoscrizione di Azure attiva. Se non è disponibile, creare un account Azure gratuito.

Azure CLI

Installare l'interfaccia della riga di comando di Azure per distribuire le risorse:

winget install Microsoft.AzureCLI

.NET 9+

Questo strumento potrebbe essere già installato. Eseguire dotnet --version e confermare che segnala la versione 9 o successiva.

winget install Microsoft.DotNet.Runtime.9

Interfaccia della riga di comando di Generatore API dati

dotnet new tool-manifest
dotnet tool install microsoft.dataapibuilder --prerelease

Annotazioni

SQL MCP Server è attualmente in versione preliminare. L'uso del --prerelease flag garantisce di ottenere la versione più recente di Data API Builder con tutte le funzionalità usate in questa guida introduttiva.

PowerShell

Installare PowerShell se non è già installato.

dotnet tool install --global PowerShell

Passaggio 1: Creare e distribuire il database SQL di Azure

1. Accedere ad Azure

az login
az account set --subscription "<your-subscription-id>"

2. Impostare le variabili per la distribuzione

$RESOURCE_GROUP = "rg-sql-mcp"
$LOCATION = "eastus"
$SQL_SERVER = "sql-mcp-$(Get-Random -Minimum 1000 -Maximum 9999)"
$SQL_DATABASE = "ProductsDB"
$SQL_ADMIN = "sqladmin"
$SQL_PASSWORD = "<YourStrongPassword123!>"

3. Creare un gruppo di risorse

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

4. Creare SQL Server di Azure

az sql server create \
  --name $SQL_SERVER \
  --resource-group $RESOURCE_GROUP \
  --location $LOCATION \
  --admin-user $SQL_ADMIN \
  --admin-password $SQL_PASSWORD

5. Configurare il firewall per consentire i servizi di Azure

az sql server firewall-rule create \
  --resource-group $RESOURCE_GROUP \
  --server $SQL_SERVER \
  --name AllowAzureServices \
  --start-ip-address 0.0.0.0 \
  --end-ip-address 0.0.0.0

6. Creare il database

az sql db create \
  --resource-group $RESOURCE_GROUP \
  --server $SQL_SERVER \
  --name $SQL_DATABASE \
  --service-objective S0

7. Creare una tabella Products con dati di esempio

Ottieni prima la stringa di connessione:

$CONNECTION_STRING = "Server=tcp:$SQL_SERVER.database.windows.net,1433;Database=$SQL_DATABASE;User ID=$SQL_ADMIN;Password=$SQL_PASSWORD;Encrypt=true;TrustServerCertificate=false;Connection Timeout=30;"

Creare un file create-products.sqldi script SQL:

CREATE TABLE dbo.Products
(
    ProductID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
    ProductName NVARCHAR(100) NOT NULL,
    Category NVARCHAR(50) NOT NULL,
    UnitPrice DECIMAL(10,2) NOT NULL,
    UnitsInStock INT NOT NULL,
    Discontinued BIT NOT NULL DEFAULT 0
);

INSERT INTO dbo.Products (ProductName, Category, UnitPrice, UnitsInStock, Discontinued) VALUES
('Laptop Pro 15', 'Electronics', 1299.99, 45, 0),
('Wireless Mouse', 'Electronics', 29.99, 150, 0),
('Office Chair', 'Furniture', 249.99, 30, 0),
('Standing Desk', 'Furniture', 599.99, 15, 0),
('Coffee Maker', 'Appliances', 89.99, 60, 0),
('Notebook Set', 'Office Supplies', 12.99, 200, 0),
('USB-C Hub', 'Electronics', 49.99, 80, 0),
('Desk Lamp', 'Furniture', 39.99, 100, 0),
('Bluetooth Headphones', 'Electronics', 149.99, 50, 0),
('Water Bottle', 'Office Supplies', 19.99, 120, 0);

Eseguirlo usando VS Code, SQL Server Management Studio o sqlcmd.

Passaggio 2: Configurare SQL MCP Server

1. Creare il dab-config.json

Inizializzare la configurazione:

dab init `
  --database-type mssql `
  --connection-string "@env('MSSQL_CONNECTION_STRING')" `
  --host-mode Production `
  --config dab-config.json

2. Aggiungere l'entità Products con descrizioni

dab add Products `
  --source dbo.Products `
  --permissions "anonymous:read" `
  --description "Product catalog with pricing, category, and inventory information"

3. Fornire al contesto dell'agente di intelligenza artificiale le descrizioni dei campi

Aggiungere descrizioni dei campi per aiutare gli agenti di intelligenza artificiale a comprendere lo schema del database:

dab update Products `
  --fields.name ProductID `
  --fields.description "Unique product identifier" `
  --fields.primary-key true

dab update Products `
  --fields.name ProductName `
  --fields.description "Name of the product"

dab update Products `
  --fields.name Category `
  --fields.description "Product category (Electronics, Furniture, Office Supplies, Appliances)"

dab update Products `
  --fields.name UnitPrice `
  --fields.description "Retail price per unit in USD"

dab update Products `
  --fields.name UnitsInStock `
  --fields.description "Current inventory count available for purchase"

dab update Products `
  --fields.name Discontinued `
  --fields.description "True if product is no longer available for sale"

Passaggio 3: Distribuire SQL MCP Server in App Contenitore di Azure

1. Creare registro Azure Container e creare un'immagine personalizzata

Creare un registro contenitori e creare un'immagine personalizzata con la configurazione incorporata:

$ACR_NAME = "acrsqlmcp$(Get-Random -Minimum 1000 -Maximum 9999)"

az acr create `
  --resource-group $RESOURCE_GROUP `
  --name $ACR_NAME `
  --sku Basic `
  --admin-enabled true

2. Creare un Dockerfile

Creare un file denominato Dockerfile nella stessa cartella di dab-config.json:

FROM mcr.microsoft.com/azure-databases/data-api-builder:1.7.83-rc
COPY dab-config.json /App/dab-config.json

3. Creare e inviare l'immagine

az acr build `
  --registry $ACR_NAME `
  --image sql-mcp-server:1 `
  .

4. Creare un ambiente per Container Apps

$CONTAINERAPP_ENV = "sql-mcp-env"
$CONTAINERAPP_NAME = "sql-mcp-server"

az containerapp env create `
  --name $CONTAINERAPP_ENV `
  --resource-group $RESOURCE_GROUP `
  --location $LOCATION

5. Distribuire il container SQL MCP Server

$ACR_LOGIN_SERVER = az acr show `
  --name $ACR_NAME `
  --query loginServer `
  --output tsv

$ACR_USERNAME = az acr credential show `
  --name $ACR_NAME `
  --query username `
  --output tsv

$ACR_PASSWORD = az acr credential show `
  --name $ACR_NAME `
  --query "passwords[0].value" `
  --output tsv

az containerapp create `
  --name $CONTAINERAPP_NAME `
  --resource-group $RESOURCE_GROUP `
  --environment $CONTAINERAPP_ENV `
  --image "$ACR_LOGIN_SERVER/sql-mcp-server:1" `
  --registry-server $ACR_LOGIN_SERVER `
  --registry-username $ACR_USERNAME `
  --registry-password $ACR_PASSWORD `
  --target-port 5000 `
  --ingress external `
  --min-replicas 1 `
  --max-replicas 3 `
  --secrets "mssql-connection-string=$CONNECTION_STRING" `
  --env-vars "MSSQL_CONNECTION_STRING=secretref:mssql-connection-string" `
  --cpu 0.5 `
  --memory 1.0Gi

Il gruppo di risorse dovrebbe essere simile all'esempio seguente:

Screenshot del gruppo di risorse del portale di Azure dopo la distribuzione.

6. Ottenere l'URL dell'endpoint MCP

$MCP_URL = az containerapp show `
  --name $CONTAINERAPP_NAME `
  --resource-group $RESOURCE_GROUP `
  --query "properties.configuration.ingress.fqdn" `
  --output tsv

Write-Host "Your MCP Server URL: https://$MCP_URL/mcp"

Salvare questo URL: viene usato per connettersi dai client MCP.

7. Testare la distribuzione

curl "https://$MCP_URL/health"

Dovrebbe essere visualizzata una risposta corretta.

Connettersi dai client MCP

SQL MCP Server è ora distribuito e pronto per l'uso. Ecco come connettersi da vari client:

Visual Studio Code (VS Code)

Seguire la Guida rapida con VS Code e utilizzare l'URL del server MCP distribuito invece di eseguire localmente.

Da Microsoft Foundry

Per aggiungere il server MCP come MCP Tool personalizzato, seguire la Guida rapida con Microsoft Foundry.

Altri clienti MCP

Usare l'URL del server MCP del passaggio 3.6 per connettersi da qualsiasi client compatibile con MCP.

Monitoraggio e risoluzione dei problemi

Visualizzare i log delle app contenitore

az containerapp logs show \
  --name $CONTAINERAPP_NAME \
  --resource-group $RESOURCE_GROUP \
  --follow

Controllare l'integrità dell'endpoint MCP

curl "https://$MCP_URL/health"

Problemi comuni

Errore di connessione non riuscita

  • Verificare che l'ingresso di Container Apps sia impostato su external
  • Verificare che la stringa di connessione SQL sia corretta
  • Controllare le regole del firewall in AZURE SQL

Nessun dato restituito

  • Verificare che la tabella Products sia stata creata e popolata
  • Controllare le autorizzazioni per le entità in dab-config.json
  • Controllare i log dei container apps per errori

Le prestazioni sono lente

  • Prendere in considerazione l'aumento dell'allocazione di CPU/memoria
  • Controllare se è necessario aumentare le repliche
  • Esaminare le metriche di Application Insights

Procedure consigliate per la sicurezza per la produzione

  • Abilitare l'autenticazione - Configurare l'autenticazione con ID Entra di Microsoft anziché l'accesso anonimo
  • Usare le identità gestite - Consentire alle app contenitore di eseguire l'autenticazione a SQL usando l'identità gestita
  • Implementare CORS : limitare i domini che possono accedere al server MCP
  • Abilitare la limitazione della frequenza - Proteggere da abusi
  • Usare Azure Key Vault - Archiviare le stringhe di connessione in modo sicuro
  • Monitorare con Application Insights - Tenere traccia dell'utilizzo e delle prestazioni
  • Limitare le autorizzazioni : concedere solo i livelli di accesso necessari

Pulire le risorse

Al termine, eliminare il gruppo di risorse per rimuovere tutte le risorse:

az group delete --name $RESOURCE_GROUP --yes --no-wait

Script di esempio completo

Ecco uno script di PowerShell completo che esegue tutti i passaggi di questa guida introduttiva. Prima di avviare, aggiornare l'ID tenant, l'ID della sottoscrizione e le variabili della password.

Suggerimento

Per una distribuzione pronta per la produzione con l'autenticazione dell'identità gestita, i controlli di integrità e la pulizia automatica, vedere lo script di ambiente demo del generatore di API dati.

# ============================================
# Variables - UPDATE THESE VALUES
# ============================================
$RESOURCE_GROUP = "rg-sql-mcp"
$LOCATION = "centralus"
$SQL_SERVER = "sql-mcp-$(Get-Random -Minimum 1000 -Maximum 9999)"
$SQL_DATABASE = "ProductsDB"
$SQL_ADMIN = "sqladmin"
$SQL_PASSWORD = "P@ssw0rd!"  # Replace with a strong password
$ACR_NAME = "acrsqlmcp$(Get-Random -Minimum 1000 -Maximum 9999)"
$CONTAINERAPP_ENV = "sql-mcp-env"
$CONTAINERAPP_NAME = "sql-mcp-server"

# ============================================
# Sign in to Azure
# ============================================
az login --tenant "<your-tenant-id>"
az account set --subscription "<your-subscription-id>"

# ============================================
# Check if resource group exists and create unique name
# ============================================
$RG_COUNTER = 0
$ORIGINAL_RG = $RESOURCE_GROUP
while ($true) {
    $RG_EXISTS = az group exists --name $RESOURCE_GROUP
    if ($RG_EXISTS -eq "false") {
        break
    }
    $RG_COUNTER++
    $RESOURCE_GROUP = "$ORIGINAL_RG-$RG_COUNTER"
}
Write-Host "Using resource group: $RESOURCE_GROUP" -ForegroundColor Green

# ============================================
# Step 1: Create Azure SQL Database
# ============================================
az group create --name $RESOURCE_GROUP --location $LOCATION

az sql server create `
  --name $SQL_SERVER `
  --resource-group $RESOURCE_GROUP `
  --location $LOCATION `
  --admin-user $SQL_ADMIN `
  --admin-password $SQL_PASSWORD

az sql server firewall-rule create `
  --resource-group $RESOURCE_GROUP `
  --server $SQL_SERVER `
  --name AllowAzureServices `
  --start-ip-address 0.0.0.0 `
  --end-ip-address 0.0.0.0

# Add current client IP to firewall
$MY_IP = (Invoke-RestMethod -Uri 'https://api.ipify.org?format=text')
az sql server firewall-rule create `
  --resource-group $RESOURCE_GROUP `
  --server $SQL_SERVER `
  --name AllowMyIP `
  --start-ip-address $MY_IP `
  --end-ip-address $MY_IP

az sql db create `
  --resource-group $RESOURCE_GROUP `
  --server $SQL_SERVER `
  --name $SQL_DATABASE `
  --service-objective S0

$CONNECTION_STRING = "Server=tcp:$SQL_SERVER.database.windows.net,1433;Database=$SQL_DATABASE;User ID=$SQL_ADMIN;Password=$SQL_PASSWORD;Encrypt=true;TrustServerCertificate=false;Connection Timeout=30;"

# Create sample table using sqlcmd
Write-Host "Creating Products table and sample data..." -ForegroundColor Yellow

$SQL_SCRIPT = @"
CREATE TABLE dbo.Products (
    ProductID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
    ProductName NVARCHAR(100) NOT NULL,
    Category NVARCHAR(50) NOT NULL,
    UnitPrice DECIMAL(10,2) NOT NULL,
    UnitsInStock INT NOT NULL,
    Discontinued BIT NOT NULL DEFAULT 0
);

INSERT INTO dbo.Products (ProductName, Category, UnitPrice, UnitsInStock, Discontinued) VALUES
('Laptop Pro 15', 'Electronics', 1299.99, 45, 0),
('Wireless Mouse', 'Electronics', 29.99, 150, 0),
('Office Chair', 'Furniture', 249.99, 30, 0),
('Standing Desk', 'Furniture', 599.99, 15, 0),
('Coffee Maker', 'Appliances', 89.99, 60, 0);
"@

# Use Invoke-Sqlcmd if available, otherwise skip table creation
try {
    $SQL_SCRIPT | Out-File -FilePath "create-table.sql" -Encoding utf8
    sqlcmd -S "$SQL_SERVER.database.windows.net" -d $SQL_DATABASE -U $SQL_ADMIN -P $SQL_PASSWORD -i "create-table.sql"
    Remove-Item "create-table.sql" -ErrorAction SilentlyContinue
    Write-Host "Products table created successfully!" -ForegroundColor Green
} catch {
    Write-Host "Note: Could not create table automatically. You can create it manually later." -ForegroundColor Yellow
    Write-Host "SQL Script saved for manual execution if needed." -ForegroundColor Yellow
}

# ============================================
# Step 2: Configure SQL MCP Server
# ============================================
# Remove existing config if present
if (Test-Path "dab-config.json") {
    Remove-Item "dab-config.json" -Force
}

dab init `
  --database-type mssql `
  --connection-string "@env('MSSQL_CONNECTION_STRING')" `
  --host-mode Production `
  --config dab-config.json

dab add Products `
  --source dbo.Products `
  --permissions "anonymous:read" `
  --description "Product catalog with pricing, category, and inventory information"

# ============================================
# Step 3: Deploy to Azure Container Apps
# ============================================
az acr create `
  --resource-group $RESOURCE_GROUP `
  --name $ACR_NAME `
  --sku Basic `
  --admin-enabled true

# Create Dockerfile
@"
FROM mcr.microsoft.com/azure-databases/data-api-builder:1.7.83-rc
COPY dab-config.json /App/dab-config.json
"@ | Out-File -FilePath Dockerfile -Encoding utf8

az acr build --registry $ACR_NAME --image sql-mcp-server:1 .

az containerapp env create `
  --name $CONTAINERAPP_ENV `
  --resource-group $RESOURCE_GROUP `
  --location $LOCATION

# Get ACR credentials for initial deployment
$ACR_LOGIN_SERVER = az acr show --name $ACR_NAME --query loginServer --output tsv
$ACR_USERNAME = az acr credential show --name $ACR_NAME --query username --output tsv
$ACR_PASSWORD = az acr credential show --name $ACR_NAME --query "passwords[0].value" --output tsv

az containerapp create `
  --name $CONTAINERAPP_NAME `
  --resource-group $RESOURCE_GROUP `
  --environment $CONTAINERAPP_ENV `
  --image "$ACR_LOGIN_SERVER/sql-mcp-server:1" `
  --registry-server $ACR_LOGIN_SERVER `
  --registry-username $ACR_USERNAME `
  --registry-password $ACR_PASSWORD `
  --target-port 5000 `
  --ingress external `
  --min-replicas 1 `
  --max-replicas 3 `
  --secrets "mssql-connection-string=$CONNECTION_STRING" `
  --env-vars "MSSQL_CONNECTION_STRING=secretref:mssql-connection-string" `
  --cpu 0.5 `
  --memory 1.0Gi

# ============================================
# Output
# ============================================
$MCP_URL = az containerapp show `
  --name $CONTAINERAPP_NAME `
  --resource-group $RESOURCE_GROUP `
  --query "properties.configuration.ingress.fqdn" `
  --output tsv

Write-Host ""
Write-Host "Deployment complete!" -ForegroundColor Green
Write-Host "MCP Server URL: https://$MCP_URL/mcp" -ForegroundColor Cyan
Write-Host "Health check:   https://$MCP_URL/health" -ForegroundColor Cyan