Abstract relational database schema grid and data nodes illustrating PostgreSQL MCP server

How to Build a Custom PostgreSQL MCP Server in TypeScript

Connecting artificial intelligence coding assistants directly to your relational database transforms how developers explore schemas and debug data states. Instead of manually exporting table definitions or switching between database clients, developers can ask tools like Cursor or Claude Desktop to inspect database structures directly. To achieve this securely, teams rely on the Model Context Protocol to bridge local AI environments with backend databases.

Understanding foundational concepts from our Model Context Protocol enterprise architecture guide is helpful before writing code. While generic open-source connectors exist, building a custom PostgreSQL server gives you complete control over authentication boundaries, connection limits, and query safety rules.

By the TeckScaler Engineering Team | Published: 2026-11-28

Executive Summary

  • Core Goal: Build a production-grade PostgreSQL Model Context Protocol (MCP) server using TypeScript and the official @modelcontextprotocol/sdk.
  • Database Safety: Enforce read-only transactions at the session level to prevent accidental modifications, drops, or table locks.
  • Strict Validation: Use Zod schemas to validate all tool parameters at runtime before any SQL statement reaches the database connection pool.
  • Connection Management: Implement pg.Pool to reuse database sockets, manage concurrency limits, and shut down cleanly on process termination.
  • Client Configuration: Connect the compiled server directly to Claude Desktop and Cursor using standard I/O transport.

Prerequisites and Project Setup

Before writing the server, ensure you have Node.js version 18 or higher installed on your workstation. You also need access to a running PostgreSQL database instance. Ensure your database user possesses read permissions on the target schema.

Initialize a clean project directory and configure TypeScript for ECMAScript Modules (ESM), which the official @modelcontextprotocol/sdk package requires:

mkdir postgres-mcp-server
cd postgres-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk pg zod dotenv
npm install -D typescript @types/node @types/pg tsx

Create a standard tsconfig.json file in the project root to ensure module imports resolve correctly:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"]
}

Add your database connection details to a .env file in the root directory:

DATABASE_URL=postgresql://read_only_user:secure_password@localhost:5432/analytics_db

Step 1: Initializing the Database Pool and MCP Server

Abstract server transport pipeline representing Model Context Protocol data stream
Illustration: TeckScaler Editorial

Create a new file at src/index.ts. We will configure two core components: a PostgreSQL connection pool and an MCP server instance with declared capabilities.

Using a connection pool prevents socket exhaustion when models issue multiple tool requests in quick succession. Notice that all diagnostic messages must go to stderr, because stdout is reserved exclusively for JSON-RPC communication frames.

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
  ListResourcesRequestSchema,
  ReadResourceRequestSchema,
  ErrorCode,
  McpError
} from "@modelcontextprotocol/sdk/types.js";
import pg from "pg";
import { z } from "zod";
import dotenv from "dotenv";

dotenv.config();

const { Pool } = pg;

// 1. Initialize PostgreSQL connection pool with sensible limits
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 5000,
});

pool.on("error", (err) => {
  console.error("Unexpected database pool error:", err);
});

// 2. Initialize the MCP Server
const server = new Server(
  {
    name: "teckscaler-postgres-mcp",
    version: "1.0.0",
  },
  {
    capabilities: {
      resources: {},
      tools: {},
    },
  }
);

Step 2: Exposing Table Schemas as Read-Only Resources

Resources provide passive context that language models can read without running active queries. Exposing your database schema as a resource lets the agent understand column names, primary keys, and table relationships before crafting queries.

Add resource discovery and read handlers to src/index.ts:

// Register available database schema resources
server.setRequestHandler(ListResourcesRequestSchema, async () => {
  return {
    resources: [
      {
        uri: "postgres://schema/overview",
        name: "Database Table Overview",
        description: "List of all public tables and their primary columns",
        mimeType: "application/json",
      },
    ],
  };
});

// Serve the schema resource data
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  if (request.params.uri !== "postgres://schema/overview") {
    throw new McpError(ErrorCode.InvalidRequest, `Unknown resource URI: ${request.params.uri}`);
  }

const client = await pool.connect();
  try {
    const query = `
      SELECT table_name, column_name, data_type, is_nullable
      FROM information_schema.columns
      WHERE table_schema = 'public'
      ORDER BY table_name, ordinal_position;
    `;
    const result = await client.query(query);
    
    return {
      contents: [
        {
          uri: request.params.uri,
          mimeType: "application/json",
          text: JSON.stringify(result.rows, null, 2),
        },
      ],
    };
  } finally {
    client.release();
  }
});

Step 3: Registering Secure SQL Query Tools with Zod Validation

Tools allow the AI model to execute active queries. To ensure safety, we must validate every parameter with Zod and enforce read-only execution at the database transaction level.

Define the input schema and register the tool:

// Define input schema using Zod
const QueryToolSchema = z.object({
  sql: z.string().min(5).max(2000).describe("The SQL query to execute (SELECT only)"),
  max_rows: z.number().int().min(1).max(50).default(20).describe("Maximum rows to return"),
});

// Expose the tool to the AI client
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "execute_read_query",
        description: "Executes a read-only SQL query against the PostgreSQL database",
        inputSchema: {
          type: "object",
          properties: {
            sql: {
              type: "string",
              description: "Read-only SQL query (SELECT statements only)",
            },
            max_rows: {
              type: "integer",
              default: 20,
              description: "Maximum number of rows to return (capped at 50)",
            },
          },
          required: ["sql"],
        },
      },
    ],
  };
});

Now, implement the tool execution handler with read-only transaction locks:

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name !== "execute_read_query") {
    throw new McpError(ErrorCode.MethodNotFound, `Tool not found: ${request.params.name}`);
  }

// 1. Validate inputs against Zod schema
  const parsed = QueryToolSchema.safeParse(request.params.arguments);
  if (!parsed.success) {
    throw new McpError(ErrorCode.InvalidParams, `Schema validation failed: ${parsed.error.message}`);
  }

const { sql, max_rows } = parsed.data;

// 2. Reject obvious mutating keywords
  const trimmed = sql.trim().toLowerCase();
  const forbiddenKeywords = ["insert", "update", "delete", "drop", "alter", "truncate", "grant"];
  if (forbiddenKeywords.some((kw) => trimmed.startsWith(kw))) {
    throw new McpError(ErrorCode.InvalidRequest, "Mutating operations are forbidden. Only SELECT queries are permitted.");
  }

// 3. Execute inside an explicit read-only transaction
  const client = await pool.connect();
  try {
    await client.query("BEGIN TRANSACTION READ ONLY;");
    const result = await client.query(`${sql.replace(/;+$/, "")} LIMIT $1;`, [max_rows]);
    await client.query("COMMIT;");

return {
      content: [
        {
          type: "text",
          text: JSON.stringify(
            {
              rows: result.rows,
              rowCount: result.rowCount,
              fields: result.fields.map((f) => ({ name: f.name, dataType: f.dataTypeID })),
            },
            null,
            2
          ),
        },
      ],
    };
  } catch (error) {
    await client.query("ROLLBACK;");
    return {
      isError: true,
      content: [
        {
          type: "text",
          text: `Database execution error: ${(error as Error).message}`,
        },
      ],
    };
  } finally {
    client.release();
  }
});

Step 4: Connecting the Stdio Transport and Graceful Shutdown

To complete the server, initialize the standard I/O transport and bind process signal handlers to close the connection pool cleanly when the host shuts down:

async function startServer() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("PostgreSQL MCP Server started successfully over stdio transport.");
}

// Cleanly handle termination signals
const shutdown = async () => {
  console.error("Shutting down PostgreSQL MCP Server...");
  await pool.end();
  process.exit(0);
};

process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

startServer().catch((err) => {
  console.error("Fatal startup error:", err);
  process.exit(1);
});

Compile your TypeScript code to JavaScript by adding a build script to package.json:

npm run build

Step 5: Configuring Claude Desktop and Cursor

Once compiled, you can connect your custom server to your desktop development tools. Open your claude_desktop_config.json configuration file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json

Add your server under the mcpServers object:

{
  "mcpServers": {
    "local-postgres": {
      "command": "node",
      "args": ["C:/path/to/postgres-mcp-server/dist/index.js"],
      "env": {
        "DATABASE_URL": "postgresql://read_only_user:secure_password@localhost:5432/analytics_db"
      }
    }
  }
}

Restart Claude Desktop. You will see a small hammer icon appear in the chat interface. You can now prompt the assistant: “Inspect our database schema and summarize our active customer orders.” The model will query your server resource, validate column names, and call the read query tool safely.

Production Checklist and Troubleshooting

Issue / SymptomUnderlying Root CauseRecommended Engineering Fix
JSON-RPC Parse ErrorCode wrote unformatted text or console.log to standard outputDirect all application logs strictly to console.error or a local log file
Socket Hangup / TimeoutUnindexed query triggered a full table scan on massive datasetsSet statement_timeout on the database role and enforce query limits
Permission Denied ErrorDatabase user account possesses write privileges on sensitive tablesConnect using a dedicated read-only role with table-level SELECT grants
Module Not Found ErrorNode.js cannot locate compiled dist files or ESM packagesVerify outDir in tsconfig and run npm run build before launching

Frequently Asked Questions

How do I connect Claude Desktop to a local PostgreSQL database?

You configure Claude Desktop’s claude_desktop_config.json file under mcpServers. Specify the node runtime command and point directly to your compiled TypeScript server file along with your database connection environment variables.

Why must MCP servers write diagnostic logs to stderr instead of stdout?

In standard I/O mode, standard output is strictly reserved for JSON-RPC 2.0 protocol message frames. Writing standard console.log statements to stdout corrupts the message packet and crashes the client connection.

Can an MCP server safely enforce read-only database queries?

Yes. Beyond inspecting query strings for keywords like UPDATE or DELETE, production servers wrap execution inside explicit PostgreSQL read-only transactions (BEGIN TRANSACTION READ ONLY) and connect via dedicated read-only database users.

What is the difference between an MCP Tool and an MCP Resource for database access?

Resources provide passive, read-only context such as database schemas, table column types, and foreign key graphs. Tools provide active, parameterized execution functions that accept arguments to query or mutate database records.

Next Steps

Building a custom PostgreSQL server gives your engineering team safe, real-time database context directly within your preferred AI coding tools. Once your read-only gateway operates reliably, consider adding domain-specific parameterized tools that trigger safe business actions. Continue reading our guide on enterprise Model Context Protocol security to protect your production endpoints against prompt injection and unauthorized data access.

Leave a Reply

Your email address will not be published. Required fields are marked *