OpenAI MCP Server + PostgreSQL MCP Server

Intermediate45 minutes
Use Cases

Common Use Cases

  • Natural language data queries
  • Automated report generation
  • Anomaly explanation
  • Data-driven insights
Before You Begin

Prerequisites

  • OpenAI API key
  • PostgreSQL database with data
  • Node.js 18+
Walkthrough

Step-by-Step Guide

1

Connect Both MCP Servers

Set up OpenAI and PostgreSQL MCP Servers with their respective credentials.

2

Expose Database Schema

Query the database schema and provide it as context for the AI model.

async function getSchemaContext() {
  const tables = await postgres.query("SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema='public'");
  return tables.rows.map(r => `${r.table_name}.${r.column_name} (${r.data_type})`).join("\n");
}
3

Generate SQL from Natural Language

Use OpenAI to convert natural language questions into SQL queries.

4

Execute and Format Results

Run the generated SQL and format results for human consumption.

async function askDatabase(question) {
  const schema = await getSchemaContext();
  const sql = await openai.chat({
    messages: [{ role: "system", content: `You are a SQL expert. Schema:\n${schema}\nGenerate only SQL, no explanation.` }, { role: "user", content: question }]
  });
  const results = await postgres.query(sql);
  return formatResults(results.rows);
}
5

Add Safety Guardrails

Validate generated SQL is read-only and doesn't access sensitive tables.

Examples

Code Examples

typescript
Safe Query Executor
async function safeQuery(sql) {
  const forbidden = ["DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE"];
  if (forbidden.some(cmd => sql.toUpperCase().includes(cmd))) {
    throw new Error("Write operations are not allowed");
  }
  return await postgres.query(sql);
}
Help

Troubleshooting

How do I prevent SQL injection?+
What if the AI generates incorrect SQL?+
Can it handle complex joins?+

Quick Info

DifficultyIntermediate
Time Estimate45 minutes
Tools
OpenAI MCP ServerPostgreSQL MCP Server

Need Integration Help?

Our team can implement this integration for you.

Get in Touch