Azure MCP PostgreSQL服务器演示
这是一个演示仓库,将向您展示如何设置 用于Postgres MCP服务器的Azure数据库 它使AI代理能够通过自然语言查询与Azure PostgreSQL数据库进行交互。支持SQL操作、模式发现和具有企业级安全性的数据分析。
此服务器是 Azure MCP服务器。此仓库将向您展示如何启用Postgres特定的功能以及如何连接它 Azure AI 铸造厂 以及其他MCP客户端,通过MCP与Azure Database for Postgres进行交互
特性
- 🔍 SQL操作 -执行查询、管理数据、执行分析
- 📊 架构发现 -自动表和列分析
- 🔐 企业安全 -Azure托管身份和Entra ID身份验证
- 🎯 自然语言 -使用会话式人工智能查询数据库
- 🚀 轻松部署 -一键式Azure部署,具有完整的基础架构
组件
该系统由三个主要部分组成:
- AI铸造代理 (客户端):使用Azure MCP服务器的托管身份对其进行身份验证。
- Azure MCP PostgreSQL服务器 (服务器):在Azure容器应用程序(ACA)中运行,使用ACA托管身份访问PostgreSQL。
- PostgreSQL数据库 (目标):启用Entra ID身份验证的PostgreSQL灵活服务器Azure数据库。
身份分离:使用两个单独的托管身份——客户端MI(AI Foundry)向MCP服务器进行身份验证,而MCP服务器使用自己的ACA MI访问PostgreSQL,确保适当的安全隔离。
先决条件
快速启动部署
使用Azure Developer CLI(azd)部署完整的Azure MCP PostgreSQL服务器基础架构:
第一步:使用azd-up进行部署
最快的入门方法是使用自动部署脚本。
- 第一,克隆 回购:
# Clone the repository
git clone https://github.com/Azure-Samples/azure-postgres-mcp-demo
cd azure-postgres-mcp-demo- 打开 infra/main.parameters.json 并更新这两个值
| 参数 | 说明 |
|---|---|
postgresResourceId | 您要连接到的PostgreSQL灵活服务器的Azure数据库的资源ID |
aifProjectResourceId | 您要使用的Azure AI Foundry项目的资源ID |
a.更新 postgresResourceId 变量以匹配您要访问的Postgres数据库。
"postgresResourceId": {
"value": "/subscriptions//resourceGroups/
/providers/Microsoft.DBforPostgreSQL/flexibleServers/
"
}> \[!注意\] > 在Azure门户中查找您的Azure Database for PostgreSQL订阅ID、资源组和服务器名称: > Screenshot of Azure details page.
b.更新 aifProjectResourceId 变量,以匹配您要使用的AI Foundry项目资源
"aifProjectResourceId": {
"value": "/subscriptions//resourceGroups//providers/Microsoft.CognitiveServices/accounts//projects/"
}> \[!注意\] > 在AI Foundry门户中查找Azure AI Foundry项目名称、订阅ID和父资源名称。通过单击 配置文件图标 → 项目详情: > Screenshot of Azure AI Foundry details.
- 创建一个新的azd环境并进行部署。确保你在主目录中(
azure-postgres-mcp-demo):
azd env new azd up部署 通常需要5-8分钟。部署完成后,azd将输出MCP服务器URL+托管身份信息,您将在接下来的步骤中使用。
此部署创建:
- 运行具有托管身份的MCP服务器的Azure容器应用程序(对PostgreSQL服务器的读取器访问)
- MCP服务器身份验证的Entra ID应用程序注册
- 为AI Foundry分配Entra ID角色,以向MCP服务器进行身份验证
Screenshot of Azure Portal components
步骤2:配置数据库访问
- 使用连接到PostgreSQL服务器
psql或您首选的PostgreSQL客户端:
通过将以下行复制并粘贴到bash终端(WSL、Azure Cloud Shell等)来设置以下环境变量。通过将以下行复制并粘贴到bash终端(WSL、Azure Cloud Shell等)来设置以下环境变量。在中查找您的连接详细信息 连接 Azure门户中Postgres资源中的选项卡:
export PGHOST=
export PGUSER=
export PGPORT=5432
export PGDATABASE=
export PGPASSWORD="$(az account get-access-token --resource https://ossrdbms-aad.database.windows.net --query accessToken --output tsv)" 然后运行:
psql或者,您可以通过 PostgreSQL VSCode扩展
- 为MCP服务器的托管标识创建数据库主体:
SELECT * FROM pgaadauth_create_principal('', false, false);替换 ` (例如。, azmcp-postgres-server-nc3im7asyw`).
> \[!注意\] > 使用 azd env get-values 命令查找 CONTAINER_APP_NAME 价值
- 如果将新表添加到数据库中,则必须授予MCP服务器对新表的权限。
GRANT SELECT ON my_table TO "";对于所有桌子
-- Grant SELECT on all existing tables
GRANT SELECT ON ALL TABLES IN SCHEMA public TO "";
-- Grant SELECT on all future tables
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO "";配置Azure AI Foundry集成
部署MCP服务器后,将其连接到Azure AI Foundry:
通过Azure AI Foundry门户进行连接
- 导航到Azure AI Foundry项目。请使用预览UI:https://aka.ms/nextgen-canary
- 首选 构建 → 创建代理
- 选择 +添加 在工具部分
- 选择 自定义 标签
- 选择 模型上下文协议 作为工具并单击 创建 Find MCP
- 进入
CONTAINER_APP_URL值作为远程MCP服务器端点。这是来自输出的值azd env get-values命令。 - 选择 微软Entra → 项目管理身份 作为身份验证方法 Connect via Entra
- 输入你的 作为观众。这是输出的值
azd env get-values命令。
\[!注意\] 使用azd env get-values命令查找ENTRA_APP_CLIENT_ID价值和CONTAINER_APP_URL
- 向您的代理添加说明。 Agent Instructions
给代理人指示:
You are a helpful agent that can use MCP tools to assist users. Use the available MCP tools to answer questions and perform tasks.
"parameters":
{
"database": "",
"resource-group": "",
"server": "",
"subscription": "",
"table": "",
"user": "",
},
"learn": true测试集成
连接后,使用自然语言查询测试MCP集成。
你可以找到表格。
List all tables in my PostgreSQL database您可以使用自然语言检索记录。
Show me the latest 10 records from the orders tableFind customers who placed orders in the last 30 days您可以进行向量搜索并指定示例查询以提高准确性。
Do a vector search for "product for customer that love to hike"
This is an example of a vector search.
`SELECT id, name, price, embedding azure_openai.create_embeddings(
'text-embedding-3-small',
'query example'
)::vector AS similarity
FROM public.products
ORDER BY similarity
LIMIT 10;AI代理通过MCP服务器自动将这些请求转换为适当的数据库操作。
通过Azure AI Foundry SDK连接
对于程序化访问,请在Python代码中使用以下MCP配置:
- 创建一个
.env文件来自.env.example:
cd client
cp .env.example .env- 更新所有值以运行代理。所有值都可以在Azure AI Foundry项目中找到。
| 变量名称 | 示例值 | 描述 |
|---|---|---|
PROJECT_ENDPOINT | https://example-endpoint.services.ai.azure.com/api/projects/example-project | Azure AI Foundry项目端点 |
MODEL_DEPLOYMENT_NAME | example-model | 部署的AI模型的名称 |
MCP_SERVER_URL | https://example-mcp-server.azurecontainerapps.io | MCP服务器端点URL |
MCP_SERVER_LABEL | example-label | MCP服务器的标签 |
AZURE_OPENAI_API_KEY | your-azure-openai-api-key | Azure OpenAI服务API密钥 |
AZURE_OPENAI_ENDPOINT | https://example-openai-endpoint.openai.azure.com/ | Azure OpenAI服务端点 |
AZURE_OPENAI_API_VERSION | your-api-version | Azure OpenAI的API版本 |
AZURE_SUBSCRIPTION_ID | your-azure-subscription-id | Azure订阅标识符 |
CONNECTION_NAME | your-connection-name | 数据库连接的名称 |
POSTGRES_SERVER | your-postgres-server | PostgreSQL服务器名称 |
POSTGRES_DATABASE | your-postgres-database | PostgreSQL数据库名称 |
POSTGRES_TABLE | your-postgres-table | 目标PostgreSQL表 |
POSTGRES_USER | your-postgres-user | PostgreSQL用户进行身份验证,请在此处使用CONTAINER_APP_NAME |
AZURE_RESOURCE_GROUP | your-azure-resource-group | Azure资源组名称 |
完整SDK示例 在客户端文件夹中
查询示例
基本数据库操作
List all tables in the databaseShow the schema for the 'customers' table Get the first 10 rows from the 'orders' tableCount total records in the 'products' table数据分析
Find customers who placed orders in the last 30 daysShow me the top 5 best-selling products by quantityCalculate average order value by customer segmentAnalyze sales trends by month for this year模式探索
What tables are available in this database?Describe the relationship between orders and customers tablesShow me all foreign key constraints in the databaseFind tables that contain customer information配置
环境变量
客户端配置(.env文件)
检查 .env.示例
身份验证和安全
Azure部署
使用具有以下权限的托管身份:
- PostgreSQL数据库贡献者 目标PostgreSQL服务器上的角色
- Entra ID身份验证 用于安全的数据库访问
故障排除
健康检查
# Check MCP server status
ping https://your-mcp-server.azurecontainerapps.io如果MCP已启动并运行:
64 bytes from X.XXX.XXX.X: icmp_seq=0 ttl=108 time=92.748 ms如果MCP *未运行*:
ping: cannot resolve https://your-mcp-server.azurecontainerapps.io: Unknown host你需要重新跑起来。
常见问题
无法验证Microsoft Entra ID。..名称在租户中不是唯一的
- 错误:您租户中的某个人已经部署了名为的Postgres MCP服务器
azure-mcp-postgres-server
postgres=> SELECT * FROM pgaadauth_create_principal('azure-mcp-postgres-server', false, false);
ERROR: Cannot validate Microsoft Entra ID user "azure-mcp-postgres-server" because its name isn't unique in the tenant.
Make sure it's correct and retry.
CONTEXT: SQL statement "SECURITY LABEL for "pgaadauth" on role "azure-mcp-postgres-server" is 'aadauth'"
PL/pgSQL function pgaadauth_create_principal(text,boolean,boolean) line 23 at EXECUTE- 解决方案:更新acaName infra/main.parameter.json 使用其他名称,然后重新运行部署
azd up
身份验证错误
- 错误:
Unauthorized或Forbidden - 解决方案:验证托管身份配置和PostgreSQL访问权限
连接问题
- 错误:
Connection timeout或Cannot connect to server - 解决方案:检查PostgreSQL防火墙规则和网络配置
权限错误
- 错误:
Permission denied for relation - 解决方案:确保托管标识具有适当的数据库权限
GRANT SELECT ON my_table TO "";调试模式
查看日志
# Stream Container Apps logs
az containerapp logs show -n your-mcp-container-name -g your-resource-group
# Check deployment status
az containerapp show -n your-mcp-container-name -g your-resource-group安全考虑
⚠️ 重要安全通知
此MCP服务器使用Entra ID和托管身份进行安全的PostgreSQL访问:
数据访问和暴露
- 此MCP服务器可访问的任何数据都可能暴露给连接的AI代理
- MCP服务器可以对可访问的数据库和表执行SQL查询
- 连接的代理可以通过自然语言查询请求和接收数据
安全特性
您可以使用以下内容 安全功能 为了保护您的数据:
- 管理身份:容器映像中未存储凭据。
- Microsoft Entra ID身份验证:安全的数据库身份验证。
- RBAC:数据库操作的基于角色的访问控制。
- 行级安全性:行级别的细粒度访问控制。
最佳实践
- 仅向特定模式和表授予数据库权限 AI代理所需
- 使用最小权限原则-不授予广泛的数据库访问权限
- 定期审查和审核授予MCP服务器身份的权限
- 考虑使用专用数据库或模式进行AI代理访问
- 从仅包含非敏感样本数据的专用测试数据库开始。
附录
AI Foundry项目管理的身份验证流程\[需要更新\]
有关AI Foundry项目将如何使用托管身份向Azure MCP服务器进行身份验证的详细信息,包括SDK使用模式。
技术细节
Azure Postgres MCP服务器是 Azure MCP服务器.
架构图
Architecture diagram
其他资源
贡献
开发工作流程
- 分叉和克隆 存储库
- 创建特征分支 从
main - 部署到测试环境
- 提交拉取请求 经过全面测试
如果你想为包括Azure Postgres MCP的Azure MCP服务器做出贡献,请按照以下步骤操作 贡献指南
支持
- 问题:GitHub日志和配置详细信息问题
- 监控:Azure容器应用程序日志和应用程序洞察
