How to Set Up Your First Local MCP Server for Databases

Yuvraj Bokhre
11 July 2026LinkedIn
Hero image for How to Set Up Your First Local MCP Server for Databases

Model Context Protocol Database Setup: Connect Your AI Agent to a Real Database (Locally)

You've got an AI agent. You've got a database full of real business data. But the two aren't talking to each other — and every time you want to pull a report or check a record, you're writing raw SQL wrappers or copying data into a prompt. It's painful, and it doesn't scale.

Model Context Protocol (MCP) changes that entirely. MCP is an open standard that lets AI agents — whether they're running inside Cursor IDE, a Python script, or a full automation stack — connect to databases, APIs, and tools through a unified, structured interface. And when you run it locally, you keep your data exactly where it belongs: on your own machine, under your own control.

In this guide, you'll clone and spin up a local PostgreSQL MCP server, configure it against your database, connect it to Cursor IDE and a custom Python agent, and watch your agent query your database in plain English — no raw SQL wrappers required.

What Is MCP and Why Run It Locally?

Model Context Protocol is to AI agents what USB-C is to devices: a single, standardized port for everything. Instead of writing custom integrations for every tool your agent needs to access, you expose those tools through an MCP server, and any MCP-compatible agent or IDE can immediately use them.

Running your MCP server locally matters for three big reasons:

1. Security — Your database credentials and data never leave your machine or your private network.

2. Speed — No round-trips to a cloud middleman. The agent queries your local server in milliseconds.

3. Control — You decide exactly which schemas, tables, and operations are exposed. Nothing more, nothing less.

This aligns directly with Zero To AI's core philosophy: secure, local-first integrations with a human in the loop. You get the power of AI automation without handing over the keys to your business data.

The Three Components Every MCP Server Exposes

Before you write a single line of config, you need to understand what an MCP server actually gives your agent. Every MCP server — including the PostgreSQL one you're about to set up — exposes three standardized component types:

1. Prompts

Pre-defined, parameterized prompt templates your agent can invoke by name. For a database server, this might be summarize_table or explain_schema. You define them once; your agent calls them by name with arguments.

2. Resources

Read-only, URI-addressable data streams. Think of these as "viewable" database artifacts — a table schema, a list of views, or query results formatted as structured data. Resources are perfect for giving an agent context about what's in your database without letting it execute arbitrary commands.

3. Tools

The action layer. Tools are callable functions with typed inputs and outputs. A database MCP server typically exposes tools like query, list_tables, and describe_table. These are what your agent calls to actually do things with your database.

Understanding this three-part model is crucial — it's the mental map that tells you what your agent can see, read, and execute.

Step-by-Step: Setting Up Your Local PostgreSQL MCP Server

Prerequisites

Make sure you have the following installed before starting:

Node.js v18+ (or Python 3.11+ if using a Python-based MCP server)

PostgreSQL running locally (or accessible on your network)

Git

Cursor IDE (optional, for the IDE integration section)

• A PostgreSQL database with at least one table you want to query

Step 1 — Clone the MCP PostgreSQL Server

The official @modelcontextprotocol/server-postgres package is the fastest way to get started. Open your terminal and run:

git clone https://github.com/modelcontextprotocol/servers.git mcp-servers
cd mcp-servers/src/postgres
npm install

Alternatively, if you prefer to install it globally via npm:

npm install -g @modelcontextprotocol/server-postgres

Step 2 — Create Your Configuration File

MCP servers are configured via a JSON file that specifies the server binary, any environment variables, and connection details. Create a file called mcp-config.json in your project root:

{
  "mcpServers": {
    "postgres-local": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://localhost:5432/your_database_name"
      ],
      "env": {
        "PGUSER": "your_db_user",
        "PGPASSWORD": "your_db_password",
        "PGHOST": "localhost",
        "PGPORT": "5432",
        "PGDATABASE": "your_database_name"
      }
    }
  }
}

Replace your_database_name, your_db_user, and your_db_password with your actual PostgreSQL credentials. Keep this file out of version control — add it to your .gitignore immediately.

Security tip: If you use environment variables via a .env file, reference them here with ${VARIABLE_NAME} syntax to avoid hardcoding credentials.

Step 3 — Test the Server Locally

Verify the server starts and connects cleanly:

npx @modelcontextprotocol/server-postgres postgresql://your_db_user:your_db_password@localhost:5432/your_database_name

You should see output confirming the server is running and listing available tools (typically query, list_tables, and describe_table). If you see a connection error, double-check your PostgreSQL pg_hba.conf to ensure local connections are allowed.

Step 4 — Connect to Cursor IDE

Cursor IDE has built-in MCP support. To connect your local server:

1. Open Cursor SettingsMCP Servers.

2. Click Add Server and select Local / Stdio.

3. In the configuration field, paste your mcp-config.json contents (or point Cursor to the file path).

4. Click Save and restart Cursor.

Once connected, open the Cursor chat panel and try a natural-language query:

"Show me all users who signed up in the last 30 days."

Cursor's agent will call the query tool on your MCP server, translate your English into SQL, execute it against your PostgreSQL database, and return the results — all without you writing a single line of SQL.

Step 5 — Connect a Custom Python Agent

For automation workflows where you need programmatic control, use the mcp Python SDK to build a custom agent:

import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

server_params = StdioServerParameters(
    command="npx",
    args=[
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://localhost:5432/your_database_name"
    ],
    env={
        "PGUSER": "your_db_user",
        "PGPASSWORD": "your_db_password"
    }
)

async def query_database(natural_language_query: str):
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # List available tools
            tools = await session.list_tools()
            print(f"Available tools: {[t.name for t in tools.tools]}")

            # Execute a direct SQL query via the 'query' tool
            result = await session.call_tool(
                "query",
                arguments={"sql": "SELECT * FROM users WHERE created_at > NOW() - INTERVAL '30 days';"}
            )
            return result.content

asyncio.run(query_database("Recent users"))

Install the SDK first:

pip install mcp

This agent connects to your local MCP server over stdio, lists all available tools, and executes a query. You can wrap this in a larger LLM-powered workflow where the model generates the SQL and the agent executes it — with a Human-in-the-Loop approval step before any write operations are committed.

Keeping Humans in the Loop: The Zero To AI Approach

Giving an AI agent database access is powerful. It's also a significant responsibility. At Zero To AI, we believe the right architecture isn't "AI executes freely" — it's Human-in-the-Loop (HITL) orchestration.

Here's what that looks like in practice with your MCP setup:

Read operations (SELECT queries) run automatically — low risk, high frequency.

Write operations (INSERT, UPDATE, DELETE) pause and surface a human approval request before execution.

Schema changes (ALTER, DROP) are blocked entirely or require a separate, explicit unlock workflow.

You can implement this at the agent layer by wrapping session.call_tool() calls with an approval gate — a Slack message, an email, or a simple CLI prompt — before any mutation hits your database. Your data integrity stays intact. Your automation keeps moving.

Troubleshooting Common Issues

"Connection refused" on startup

Ensure PostgreSQL is running (pg_isready or pg_ctl status) and that your pg_hba.conf file allows the connection method you're using (md5 or scram-sha-256 for password auth).

"Tool not found" in Cursor

Restart Cursor after saving the MCP config. Cursor caches server registrations at startup; a cold restart is required to pick up new servers.

Slow query responses

Check that your PostgreSQL indexes are set up correctly for the columns your agent queries most often. MCP doesn't add latency — if responses are slow, the bottleneck is in the database itself.

FAQ

Q: Is it safe to run an MCP server with my production database?

For development and exploration, use a read-only replica or a staging database, not production. If you do connect to production, restrict the PostgreSQL role to SELECT-only privileges for the tables you want the agent to access. Pair this with HITL approval for any write operations, and you have a defensible setup.

Q: Can I expose multiple databases through a single MCP configuration?

Yes. Add multiple entries to the mcpServers object in your mcp-config.json, each with a unique key and its own connection string. Your agent will see them as separate, named servers and can route queries to the appropriate one based on context.

Q: Does MCP work with databases other than PostgreSQL?

Absolutely. The MCP ecosystem includes community-maintained servers for MySQL, SQLite, MongoDB, Supabase, Neon, and more. The configuration pattern is identical — swap out the server package and connection string, and your agent connects the same way. Check the official MCP servers repository for the full list.

What's Next?

You now have a fully functional local MCP server bridging your PostgreSQL database and your AI agents — without sending your data to a third-party service, without writing brittle SQL wrappers, and with a clear path to adding human approval gates for sensitive operations.

The next step? Build a workflow on top of this. Use Zero To AI's HITL orchestration layer to trigger database queries from Slack, surface results in a dashboard, or chain multiple MCP servers together so your agent can cross-reference your CRM data against your product analytics — all in plain English, all under your control.

The database is no longer a black box your AI can't touch. It's a first-class citizen in your automation stack.

Hands-on course
Build the automation, don't just read about it.

Learn to build AI workflows that handle your busywork — live sessions, real projects, zero code.

See the course

Beginner-friendly

Comments

Loading comments…

Leave a comment

Related articles

You may also like these

4,000+ students enrolled

Reading about automation
won’t automate anything.

Build your first working AI agent this week — no code, no developer.

₹1,499₹4,999one-time
Start for ₹1,499Start for ₹1,499

Talk to a mentor
before you start

Not sure which course fits your goals? Our team will review where you are, recommend the right path, and answer every question, so you start with total confidence.

ZERO TO AI
© 2026 Zero to AI — All rights reserved.