Skip to main content
Glama
longliaprono1-blip

chatbot-ai-mcp-demo

🎬 KI-Chatbot-Demo: MCP + PostgreSQL + DeepSeek V4 Pro

"Lass KI nicht SQL schreiben. Lass KI deine sichere API aufrufen."

Professionelle Demo für sichere KI-Integration mit MCP (Model Context Protocol) mit Next.js 15, PostgreSQL und DeepSeek V4 Pro – perfekt für Vlog-Content.

🎯 Gelöstes Problem

Bei der KI-Integration in Produkte stoßen viele Entwickler auf:

  • Sicherheitsrisiken: KI erzeugt falsches oder gefährliches SQL (DROP TABLE, DELETE)

  • Halluzinationen: KI "halluziniert" und erstellt falsche Datenabfragen

  • Prompt-Injection: Benutzer übermitteln schädliche Befehle

  • Keine Kontrolle: Keine Kontrolle darüber, was die KI erzeugt

Related MCP server: dbecho

✅ Lösung: MCP-Muster

User Prompt → AI (DeepSeek V4 Pro) → MCP Tools → PostgreSQL
     ↑                                    ↓
     └─────── JSON Response ←─────────────┘

Prinzipien:

  • 🧠 KI: Nur Schlussfolgerungen, entscheidet, welches Tool aufgerufen wird

  • 🛡️ MCP-Server: Sicherheitswächter, blockiert gefährliche Befehle

  • 💻 Entwickler: 100 % Kontrolle über SQL in den Tools

  • 📊 PostgreSQL: Liefert sichere Daten zurück


🚀 Schnellstart

1. Abhängigkeiten installieren

pnpm install

2. Umgebung konfigurieren

# 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_keys

3. PostgreSQL starten

pnpm docker:up

Die Datenbank wird automatisch mit folgenden Daten befüllt:

  • 115 Produkte (5 Kategorien)

  • Inventardaten

  • Verkaufsaufzeichnungen (30 Tage)

  • Bestelldaten

4. Entwicklungsserver starten

# Terminal 1: MCP Server
pnpm dev:mcp

# Terminal 2: Next.js Web App
pnpm dev:web

# Or run both concurrently
pnpm dev

5. Browser öffnen

Zugriff: http://localhost:3000


🏗️ Architektur

Technologie-Stack

Ebene

Technologie

Zweck

Präsentation

Next.js 15 + React 19

Chat-UI, Markdown-Vorschau

Styling

Tailwind CSS 4

Responsiv, Dark Mode

Orchestrierung

Next.js-Route-Handler

KI- und MCP-Koordination

KI-Gehirn

DeepSeek V4 Pro

Tool-Aufrufe, Schlussfolgerungen

MCP-Server

Express + MCP SDK

Tool-Ausführung, Sicherheit

Datenbank

PostgreSQL 16 (Docker)

Datenspeicherung

Projektstruktur

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-Tools

1. list_tables

Listet die Tabellen in der Datenbank auf

Eingabe: Keine
Ausgabe: Array mit Tabellennamen

2. get_table_schema

Detaillierte Struktur einer Tabelle anzeigen

Eingabe:

{ "tableName": "products" }

Ausgabe: Spalten, Datentypen, Constraints

3. query_inventory

Produktbestand prüfen

Eingabe:

{ "productId": "SP001" }

Ausgabe:

{
  "id": "SP001",
  "name": "Váy hoa nhí",
  "stock_quantity": 150,
  "stock_status": "Còn hàng",
  "price_formatted": "299.000₫"
}

4. get_top_sales

Meistverkaufte Produkte

Eingabe:

{ "limit": 5, "days": 30 }

Ausgabe: Rangliste mit Verkaufskennzahlen

5. execute_read_query 🛡️

Generische SELECT-Abfrage mit Sicherheitswächtern

Eingabe:

{ "sql": "SELECT * FROM products WHERE price > 500000" }

Sicherheitsfunktionen:

  • ✅ Nur SELECT/WITH erlaubt

  • ❌ Blockiert: DROP, DELETE, UPDATE, INSERT usw.

  • ✅ Ergebnislimit: maximal 100 Zeilen

  • ✅ SQL-Injection-Schutz


🎬 Vlog-Skript-Anleitung

Szene 1: Problemdarstellung (30 s)

Visuell: KI zeigt, wie gefährliches SQL erzeugt wird

-- AI hallucination example
DROP TABLE users;
DELETE FROM orders WHERE 1=1;

Erzählung:

"Viele Entwickler fragen: Wie verhindere ich bei der KI-Integration, dass sie die Datenbank zerstört? Heute teile ich eine produktionsreife Lösung!"

Szene 2: Architekturübersicht (45 s)

Visuell: Architekturdiagramm zeigen

User → DeepSeek V4 Pro → MCP Server → PostgreSQL

Erzählung:

"Statt die KI SQL selbst schreiben zu lassen, verwenden wir das MCP-Muster. Die KI entscheidet nur, welches Tool aufgerufen wird, der Entwickler kontrolliert das SQL im Code."

Szene 3: Code-Demo – Erfolgsfall (60 s)

Visuell: Chat-UI-Demo

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"

Erzählung:

"Der Benutzer fragt natürlich, die KI analysiert, ruft das richtige Tool auf, MCP führt die Abfrage sicher aus und liefert verständliche Ergebnisse!"

Szene 4: Sicherheitsdemo (45 s)

Visuell: Blockierter gefährlicher Befehl

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"

Erzählung:

"Wenn der Benutzer absichtlich die Datenbank zerstören will, blockiert der MCP-Server sofort! Das ist die letzte Sicherheitsbarriere, die die KI nicht umgehen kann."

Szene 5: Code-Durchlauf (60 s)

Wichtige Code-Ausschnitte zum Zeigen:

  1. Tool-Definition (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;
  }
};
  1. Sicherheitswächter (mcp-server/src/tools/execute-tool.ts)

const FORBIDDEN_KEYWORDS = ['DROP', 'DELETE', 'UPDATE'];

if (sql.includes(FORBIDDEN_KEYWORDS)) {
  return { isError: true, text: '🚫 BLOCKED!' };
}
  1. KI-Tool-Aufruf (web/src/app/api/chat/route.ts)

const response = await deepseekClient.chat.completions.create({
  model: 'deepseek-v4-pro',
  tools: toolsToOpenAIFormat(),
  tool_choice: 'auto'
});

Szene 6: Kostenvergleich (30 s)

Modell

Kosten/1 Mio. Tokens

Tool-Aufrufe

GPT-4o

~15 $

Claude 3.5

~15 $

DeepSeek V4 Pro

~0,5 $

Erzählung:

"DeepSeek V4 Pro unterstützt Tool-Aufrufe und kostet nur 1/30 von GPT-4o. Perfekt für Startups und Vibe-Coder!"


🔒 Sicherheits-Best-Practices

1. Nur-Lese-Durchsetzung

const FORBIDDEN_KEYWORDS = [
  'DROP', 'DELETE', 'UPDATE', 'INSERT', 'TRUNCATE', 
  'ALTER', 'CREATE', 'GRANT', 'REVOKE'
];

2. Parametervalidierung (Zod)

inputSchema: z.object({
  productId: z.string().describe('Mã sản phẩm')
})

3. Verbindungspooling

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20, // Prevent connection exhaustion
});

4. SQL-Injection-Schutz

// ✅ Parameterized queries
await pool.query('SELECT * FROM products WHERE id = $1', [productId]);

// ❌ Never string concatenation
// await pool.query(`SELECT * FROM products WHERE id = '${productId}'`);

📊 Demo-Daten

Kategorien

  • Fashion: 30 Produkte (SP001-SP030)

  • Elektronik: 25 Produkte (SP031-SP055)

  • Wohnen & Leben: 25 Produkte (SP056-SP080)

  • Beauty: 20 Produkte (SP081-SP100)

  • Sport: 15 Produkte (SP101-SP115)

Beispielabfragen

"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

🔧 Fehlerbehebung

Datenbankverbindung fehlgeschlagen

# Check if PostgreSQL is running
docker ps | grep postgres

# View logs
pnpm docker:logs

# Restart
pnpm docker:down && pnpm docker:up

MCP-Server startet nicht

# Check environment variables
cat mcp-server/.env

# Test database connection
cd mcp-server && pnpm tsx src/db.ts

Probleme mit KI-API-Schlüssel

# 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"}]}'

📚 Ressourcen


🎓 Wichtige Erkenntnisse

  1. Lass KI nicht SQL schreiben – Der Entwickler kontrolliert den Datenzugriff

  2. MCP-Muster – Standardisierte Tool-Aufrufe

  3. Sicherheit zuerst – Mehrere Schutzebenen

  4. Kosteneffizient – DeepSeek V4 Pro ~0,5 $/1 Mio. Tokens

  5. Produktionsreif – Verbindungspooling, Validierung, Fehlerbehandlung


📝 Lizenz

MIT-Lizenz – Gerne für Lernen, Vlogs oder Produktion verwenden!


Mit ❤️ für die vietnamesische Entwickler-Community erstellt

Folge und teile, um mich zu unterstützen, damit ich noch mehr hochwertigen Content veröffentlichen kann! 🚀

F
license - not found
Not graded
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

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

  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides 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.
    14
    9
    ISC
  • A
    license
    A
    quality
    A
    maintenance
    An 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.
    11
    5
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Read-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.
    539
    MIT
  • A
    license
    A
    quality
    B
    maintenance
    MCP server for PostgreSQL that enables safe read-only database queries, table schema inspection, and query execution planning.
    6
    34
    BSD 3-Clause

View all related MCP servers

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.

View all MCP Connectors

Latest Blog Posts

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