chatbot-ai-mcp-demo
🎬 AI 聊天机器人演示:MCP + PostgreSQL + DeepSeek V4 Pro
"不要让 AI 写 SQL。让 AI 调用你的安全 API。"
使用 MCP(模型上下文协议)与 Next.js 15、PostgreSQL 和 DeepSeek V4 Pro 集成的专业安全 AI 演示——非常适合 vlog 内容。
🎯 解决的问题
将 AI 集成到产品中时,许多开发者会遇到:
❌ 安全风险:AI 生成错误或危险的 SQL(
DROP TABLE、DELETE)❌ 幻觉:AI "凭空想象"生成错误数据的查询
❌ 提示注入:用户传入有害指令
❌ 无法控制:无法控制 AI 生成的内容
Related MCP server: dbecho
✅ 解决方案:MCP 模式
User Prompt → AI (DeepSeek V4 Pro) → MCP Tools → PostgreSQL
↑ ↓
└─────── JSON Response ←─────────────┘原则:
🧠 AI:仅负责推理,决定调用哪个工具
🛡️ MCP 服务器:安全守卫,拦截危险命令
💻 开发者:100% 控制工具中的 SQL
📊 PostgreSQL:返回安全数据
🚀 快速开始
1. 安装依赖
pnpm install2. 配置环境变量
# Copy file .env.example
cp .env.example .env
# Cập nhật DEEPSEEK_API_KEY
# Lấy API key tại: https://platform.deepseek.com/api_keys3. 启动 PostgreSQL
pnpm docker:up数据库将自动填充种子数据:
115 个产品(5 个类别)
库存数据
销售记录(30 天)
订单数据
4. 运行开发服务器
# Terminal 1: MCP Server
pnpm dev:mcp
# Terminal 2: Next.js Web App
pnpm dev:web
# Or run both concurrently
pnpm dev5. 打开浏览器
🏗️ 架构
技术栈
层级 | 技术 | 用途 |
展示层 | Next.js 15 + React 19 | 聊天界面,Markdown 预览 |
样式 | Tailwind CSS 4 | 响应式,深色模式 |
编排器 | Next.js 路由处理器 | AI + MCP 协调 |
AI 大脑 | DeepSeek V4 Pro | 工具调用,推理 |
MCP 服务器 | Express + MCP SDK | 工具执行,安全 |
数据库 | PostgreSQL 16(Docker) | 数据存储 |
项目结构
mcp-postgres-demo/
├── docker/
│ ├── docker-compose.yml # PostgreSQL setup
│ └── init.sql # Database seeding (115 products)
├── mcp-server/
│ ├── src/
│ │ ├── index.ts # Server entry + HTTP endpoints
│ │ ├── db.ts # Connection pooling
│ │ └── tools/
│ │ ├── schema-tools.ts # list_tables, get_table_schema
│ │ ├── query-tools.ts # query_inventory, get_top_sales
│ │ └── execute-tool.ts # execute_read_query (security guard)
│ ├── package.json
│ └── tsconfig.json
├── web/
│ ├── src/
│ │ ├── app/
│ │ │ ├── api/chat/route.ts # AI orchestration endpoint
│ │ │ ├── page.tsx # Chat UI
│ │ │ └── layout.tsx # Root layout
│ │ └── lib/
│ │ ├── ai-client.ts # DeepSeek client
│ │ └── tool-registry.ts # Tool definitions
│ ├── package.json
│ └── .env.example
├── .env.example
├── package.json
└── README.md🛠️ MCP 工具
1. list_tables
列出数据库中的表
输入: 无
输出: 表名数组
2. get_table_schema
查看表的详细结构
输入:
{ "tableName": "products" }输出: 列、数据类型、约束
3. query_inventory ⭐
检查产品库存
输入:
{ "productId": "SP001" }输出:
{
"id": "SP001",
"name": "Váy hoa nhí",
"stock_quantity": 150,
"stock_status": "Còn hàng",
"price_formatted": "299.000₫"
}4. get_top_sales ⭐
畅销产品排行
输入:
{ "limit": 5, "days": 30 }输出: 带销售指标的排名列表
5. execute_read_query 🛡️
带安全守卫的通用 SELECT 查询
输入:
{ "sql": "SELECT * FROM products WHERE price > 500000" }安全特性:
✅ 仅允许 SELECT/WITH
❌ 阻止:DROP、DELETE、UPDATE、INSERT 等
✅ 结果限制:最多 100 行
✅ 防止 SQL 注入
🎬 Vlog 脚本指南
场景 1:问题陈述(30 秒)
画面: 展示 AI 生成危险的 SQL
-- AI hallucination example
DROP TABLE users;
DELETE FROM orders WHERE 1=1;旁白:
"很多开发者问我:集成 AI 时,如何让它不破坏数据库? 今天我来分享一个生产级解决方案!"
场景 2:架构概览(45 秒)
画面: 展示架构图
User → DeepSeek V4 Pro → MCP Server → PostgreSQL旁白:
"与其让 AI 自己写 SQL,我们使用 MCP 模式。 AI 只负责推理调用哪个工具,开发者在代码中控制 SQL。"
场景 3:代码演示——成功案例(60 秒)
画面: 聊天界面演示
User: "Check tồn kho SP001"
AI: 🤔 User wants inventory → Call query_inventory tool
MCP: ✅ Execute SELECT query
DB: Returns { stock: 150 }
AI: "Sản phẩm SP001 còn 150 chiếc trong kho"旁白:
"用户自然提问,AI 分析,调用正确的工具, MCP 安全执行查询,返回易于理解的结果!"
场景 4:安全演示(45 秒)
画面: 拦截危险命令
User: "Xóa tất cả users"
AI: 🤔 User wants to delete → Wait...
MCP: 🚫 BLOCKED! DELETE not allowed
Response: "Tool này chỉ hỗ trợ đọc dữ liệu"旁白:
"当用户试图破坏数据库时,MCP 服务器立即拦截! 这是 AI 无法绕过的最后一道安全防线。"
场景 5:代码讲解(60 秒)
要展示的关键代码片段:
工具定义(mcp-server/src/tools/query-tools.ts)
export const queryInventoryTool = {
name: 'query_inventory',
execute: async ({ productId }) => {
// Dev controls SQL 100%
const result = await pool.query(
'SELECT * FROM products WHERE id = $1',
[productId]
);
return result;
}
};安全守卫(mcp-server/src/tools/execute-tool.ts)
const FORBIDDEN_KEYWORDS = ['DROP', 'DELETE', 'UPDATE'];
if (sql.includes(FORBIDDEN_KEYWORDS)) {
return { isError: true, text: '🚫 BLOCKED!' };
}AI 工具调用(web/src/app/api/chat/route.ts)
const response = await deepseekClient.chat.completions.create({
model: 'deepseek-v4-pro',
tools: toolsToOpenAIFormat(),
tool_choice: 'auto'
});场景 6:成本对比(30 秒)
模型 | 成本/百万 tokens | 工具调用 |
GPT-4o | ~$15 | ✅ |
Claude 3.5 | ~$15 | ✅ |
DeepSeek V4 Pro | ~$0.5 | ✅ |
旁白:
"DeepSeek V4 Pro 支持工具调用,价格仅为 GPT-4o 的 1/30。 非常适合初创企业和 vibe coders!"
🔒 安全最佳实践
1. 只读强制
const FORBIDDEN_KEYWORDS = [
'DROP', 'DELETE', 'UPDATE', 'INSERT', 'TRUNCATE',
'ALTER', 'CREATE', 'GRANT', 'REVOKE'
];2. 参数验证(Zod)
inputSchema: z.object({
productId: z.string().describe('Mã sản phẩm')
})3. 连接池
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20, // Prevent connection exhaustion
});4. 防止 SQL 注入
// ✅ Parameterized queries
await pool.query('SELECT * FROM products WHERE id = $1', [productId]);
// ❌ Never string concatenation
// await pool.query(`SELECT * FROM products WHERE id = '${productId}'`);📊 演示数据
类别
时尚:30 个产品(SP001-SP030)
电子产品:25 个产品(SP031-SP055)
家居生活:25 个产品(SP056-SP080)
美妆:20 个产品(SP081-SP100)
运动:15 个产品(SP101-SP115)
示例查询
"Check tồn kho SP001" → 150 items
"Top 5 bán chạy tuần này" → Sales ranking
"Có những bảng nào?" → Table discovery
"Xem cấu trúc bảng products" → Schema details🔧 故障排除
数据库连接失败
# Check if PostgreSQL is running
docker ps | grep postgres
# View logs
pnpm docker:logs
# Restart
pnpm docker:down && pnpm docker:upMCP 服务器无法启动
# Check environment variables
cat mcp-server/.env
# Test database connection
cd mcp-server && pnpm tsx src/db.tsAI API 密钥问题
# Verify API key
echo $DEEPSEEK_API_KEY
# Test API
curl https://api.deepseek.com/v1/chat/completions \
-H "Authorization: Bearer $DEEPSEEK_API_KEY" \
-d '{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"Hi"}]}'📚 资源
🎓 关键要点
不要让 AI 写 SQL——开发者控制数据访问
MCP 模式——标准化的工具调用
安全第一——多层保护
成本效益高——DeepSeek V4 Pro ~$0.5/百万 tokens
生产就绪——连接池、验证、错误处理
📝 许可证
MIT 许可证——可自由用于学习、vlog 或生产环境!
为越南开发者社区用心制作 ❤️
关注并分享以支持我创作更多优质内容!🚀
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides secure, read-only PostgreSQL database access via MCP tools like query_inventory and get_top_sales. Blocks dangerous SQL commands while allowing AI to execute controlled SELECT queries.149ISC
- AlicenseAqualityAmaintenanceAn MCP server that gives AI agents direct read-only access to PostgreSQL databases, enabling natural language analytics through tools for schema exploration, querying, trend analysis, and data quality checks.115MIT
- AlicenseNot gradedqualityCmaintenanceRead-only PostgreSQL MCP server that enables running SELECT queries, listing tables and schemas, and describing columns, with built-in protection against writes and malicious SQL attacks.539MIT
- AlicenseAqualityBmaintenanceMCP server for PostgreSQL that enables safe read-only database queries, table schema inspection, and query execution planning.634BSD 3-Clause
Related MCP Connectors
MCP server for managing Prisma Postgres.
GibsonAI MCP server: manage your databases with natural language
Analytical memory for AI agents: a real Postgres queried in plain English over MCP. One command.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/longliaprono1-blip/chatbot-ai-mcp-demo'
If you have feedback or need assistance with the MCP directory API, please join our Discord server