logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

postgre-data-bridge-mcp

Facilitates AI agent connectivity to a PostgreSQL data store, orchestrating SQL execution and retrieving relational metadata via a codified interface. It ensures immediate data accessibility and robust management of connectivity failures.

Author

postgre-data-bridge-mcp logo

endaoment

No License

Quick Info

GitHub GitHub Stars 1
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

apispostgresqlpostgresmodels postgresqlapis httppostgres mcp

Model Context Protocol PostgreSQL Adapter

This module implements a server adhering to the Model Context Protocol (MCP) specifically engineered to interface with a PostgreSQL relational database system. It empowers large language models (LLMs) to securely interact with operational data stores using a structured communication format.

Core Capabilities

  • Establishes PostgreSQL connectivity leveraging connection pooling mechanisms.
  • Adheres strictly to the Model Context Protocol specification for model consumption.
  • Exposes database schema structures (tables, views) as addressable information resources.
  • Permits the dispatch of arbitrary SQL commands, incorporating automatic execution retry policies.
  • Implements sophisticated error management for connection loss and operational faults.

Prerequisites for Deployment

  • Runtime environment: Node.js version 20 or newer.
  • Target service: An operational PostgreSQL instance.
  • Necessary access rights and authentication credentials for the database.

Deployment Instructions

  1. Obtain a local copy of the source code repository:

bash git clone cd

  1. Install requisite project dependencies:

bash npm install

Configuration Methodology

The service prioritizes fetching database connection parameters from a .env file situated in the root project directory. These details must be serialized as a JSON string assigned to the DB_CREDENTIALS environment variable:

  1. Construct the environment file:

bash touch .env

  1. Populate it with connection specifics:

bash export DB_CREDENTIALS='{"DB_USER":"","DB_PASSWORD":"","DB_HOST":"","DB_PORT":"5433","DB_NAME":""}'

Fallback Configuration Strategy (Shell Profiles)

Should the .env file be absent, or if the primary credential variable is unset, the server initiates a search across standard shell initialization scripts in the following sequence:

  1. ~/.zshrc
  2. ~/.bashrc
  3. ~/.bash_profile
  4. ~/.profile

This cascading lookup is optimized for environments where standard environment variable loading might be inconsistent, such as within specific sandboxed AI execution contexts (e.g., Cursor MCP environment).

To establish persistent configuration in a shell startup file:

  1. Open the relevant shell configuration file (e.g., nano ~/.zshrc).
  2. Append the export command with your actual database credentials.

The server automatically detects and utilizes these values if the primary .env method fails.

Alternative Credential Variable Specification

Users can override the default DB_CREDENTIALS variable name by utilizing the --credentials-var command-line argument during execution:

bash node server.js --credentials-var MY_CUSTOM_DB_CREDS

In this scenario, the custom variable (MY_CUSTOM_DB_CREDS) must be defined in the .env file or the environment.

Option Synthesis

Command-line switches can be combined for comprehensive control:

bash

Set custom variable source and enable detailed operational output

node server.js --credentials-var CUSTOM_CONFIG --verbose

Concise argument syntax is also supported

node server.js -c CUSTOM_CONFIG -v

Execution

Initiate the MCP data bridge service:

bash

Direct execution via Node

node server.js

Execution via npm script

npm start

Verbosity Control

The default execution profile is quiet, reporting only critical failures. To activate comprehensive logging of all operations, use the verbose flag:

bash

Enable verbose logging

node server.js --verbose

Via npm (note the argument separator needed for npm to pass flags)

npm start -- --verbose

The -v shorthand provides the same verbose output:

bash node server.js -v

The startup sequence involves: 1. A preliminary connectivity check against the database. 2. Launching the MCP server instance utilizing the standard input/output (stdio) communication channel. 3. Actively monitoring and servicing requests originating from associated AI agents.

Cursor AI Integration

This service is fully compliant with the MCP standard, enabling seamless integration with Cursor IDE's AI features.

Automated Setup

A boilerplate .cursor/mcp.json file is bundled to facilitate automatic discovery within Cursor projects.

Manual Integration Steps

To manually register the service within Cursor:

  1. Navigate to Cursor Settings → Features → Model Context Protocol (MCP).
  2. Select the option to "+ Add New MCP Server".
  3. Input the following parameters:
  4. Identifier Name: Postgres Data Bridge
  5. Transport Type: stdio
  6. Execution Command: node /absolute/path/to/server.js

Consult the official Cursor documentation on MCP for exhaustive details on protocol integration.

Exposed Functionality (Tools)

The server furnishes the following callable methods to connected AI agents:

  • query: A mechanism to submit and process SQL statements, incorporating fault tolerance through retries.

Data Access (Resources)

The adapter maps accessible database tables directly into queryable resources, permitting AI models to:

  • Catalog all existing relations within the database schema.
  • Request and inspect detailed structural metadata for any given table.

Resilience and Fault Tolerance

The implementation incorporates:

  • Built-in logic for connection re-establishment attempts.
  • Verbose and precise error reporting.
  • Procedures for clean, graceful termination of the service process.

Diagnostic Guide

Connectivity Failures

  1. Initial Connection Failure
  2. Confirm PostgreSQL service status: pg_isready -h localhost -p 5433
  3. Cross-verify credentials stored in the .env file.
  4. Inspect firewall or pg_hba.conf settings to ensure client IP allowance.
  5. Validate connectivity using a standard utility like psql.

  6. Environment Variable Issues

  7. Ensure the configuration file resides in the project root.
  8. Validate that the DB_CREDENTIALS string adheres strictly to valid JSON syntax.
  9. Rule out extraneous whitespace or newline characters within the JSON string.
  10. Test parsing environment variables directly: node -e "console.log(JSON.parse(process.env.DB_CREDENTIALS))" < .env

  11. Runtime Version Mismatch

  12. Check current Node.js version: node -v
  13. Requirement is Node.js 20 or higher.
  14. Upgrade using version manager: nvm install 20 && nvm use 20

Cursor Integration Issues

  1. Server Not Detected by Cursor
  2. Verify the integrity and location of the .cursor/mcp.json configuration file.
  3. Perform a full restart of the Cursor application.
  4. Review Cursor's internal diagnostic logs for startup errors.

  5. Client Instantiation Error ("Failed to create client")

  6. This often signals an immediate service crash upon launch.
  7. Rerun the service with verbose logging activated: node server.js -v
  8. Confirm that the credentials are correctly propagated within the Cursor execution context.

  9. Tooling Panel is Empty

  10. Confirm the bridge service is actively running and producing healthy logs.
  11. Attempt to manually refresh the MCP tooling view within Cursor.
  12. Restart Cursor post-verification.

PostgreSQL Specific Challenges

  1. Authorization Denied Errors
  2. Confirm the database principal possesses requisite permissions on the target relations.
  3. Apply necessary grants: GRANT SELECT ON ALL TABLES IN SCHEMA public TO <username>;

  4. Schema Resolution Errors ("Relation does not exist")

  5. Validate the table name against the schema: \dt <tablename> executed via psql.
  6. Double-check the currently connected database instance.
  7. Verify the user has traversal rights for the associated schema.

  8. Performance Degradation

  9. For extensive result sets, employ LIMIT clauses in generated SQL to mitigate overhead.
  10. Assess database health—consider index optimization or regular VACUUM operations.

Detailed operational insight is accessible by running the adapter with the verbose flag (-v).

Licensing

This project is distributed under the terms of the MIT License.

WIKIPEDIA: XMLHttpRequest (XHR) is an Application Programming Interface defined as a JavaScript object, facilitating the transmission of Hypertext Transfer Protocol (HTTP) requests from a web browser to a server endpoint. Its methods enable browser-based applications to perform server interactions asynchronously after initial page load, subsequently receiving and processing server responses. XHR is a foundational element of Asynchronous JavaScript and XML (Ajax) methodology. Before Ajax, server communication predominantly relied on traditional hyperlink navigation or full-page form submissions, often resulting in complete screen refreshes. These older mechanisms were superseded by the capability XHR introduced.

== Historical Development == The foundational concept for asynchronous communication utilizing an object similar to XMLHttpRequest originated around the year 2000, conceived by engineers developing Microsoft Outlook. This concept was first integrated into the Internet Explorer 5 browser release (1999). Crucially, the initial implementation did not use the standardized XMLHttpRequest identifier. Instead, proprietary object instantiation methods like ActiveXObject("Msxml2.XMLHTTP") and ActiveXObject("Microsoft.XMLHTTP") were employed. By the time Internet Explorer 7 was released (2006), native support for the formal XMLHttpRequest identifier was universally available across the browser suite. The XMLHttpRequest identifier subsequently achieved de facto standard status across all major browser rendering engines, including Mozilla's Gecko (2002), Apple's Safari 1.2 (2004), and Opera 8.0 (2005).

=== Standardization Trajectory === The World Wide Web Consortium (W3C) formally published an initial Working Draft specification for the XMLHttpRequest object on April 5, 2006. This was followed by the Level 2 specification Working Draft on February 25, 2008. Level 2 enhancements introduced functionality for monitoring transfer progress events, enabling cross-origin resource sharing (CORS), and facilitating the handling of raw byte streams. By late 2011, the Level 2 features were integrated back into the primary specification document. Development responsibilities transitioned to the Web Hypertext Application Technology Working Group (WHATWG) at the close of 2012, which now maintains the document as a living specification using Web IDL definitions.

== Operational Usage Pattern == Executing a network request via XMLHttpRequest typically involves adherence to a sequence of programming actions:

  1. Instantiate the necessary XMLHttpRequest object by invoking its constructor.
  2. Invoke the open() method to define the request method (e.g., GET, POST), specify the target Uniform Resource Identifier (URI), and select between synchronous or asynchronous execution mode.
  3. For asynchronous operations, define a callback listener function to be invoked when the request state changes.
  4. Commence the data transfer operation by calling the send() method, optionally passing request body data.
  5. Monitor state transitions within the designated event listener. Upon successful server data return, the information is typically available in the responseText property. When processing concludes, the object transitions to state 4, signifying completion ("done").

Beyond these fundamental steps, XMLHttpRequest provides extensive controls over request construction and response processing. Custom HTTP headers can be appended to modify server behavior. Data can be uploaded to the server via the argument supplied to the send() call. Server responses in JSON format can be automatically deserialized into native JavaScript objects, or processed incrementally as data chunks arrive rather than waiting for the entire payload. Furthermore, requests can be canceled prematurely or configured with a timeout threshold.

== Cross-Origin Interactions ==

During the early evolution of the World Wide Web, limitations were identified that restricted scripts hosted on one domain from arbitrarily accessing resources hosted on a different domain, a security measure implemented to mitigate certain vulnerabilities. This is commonly known as the Same-Origin Policy. XMLHttpRequest, in its initial iteration, strictly enforced this policy, preventing direct cross-domain data fetching, a significant hurdle for building distributed web applications.

See Also

`