Access PolarDB PostgreSQL Agentic Database via MCP Server

Updated at:

This topic describes how to connect to the PolarDB PostgreSQL Agentic Database MCP Server by using API key authentication. After you connect, an AI Agent can call database management tools over the MCP protocol and use natural language to manage projects, branches, SQL execution, schema browsing, and Lakebase object storage without configuring database endpoints, accounts, or passwords.

Note

If you have any questions about PolarDB PostgreSQL Agentic Database features, search for the DingTalk group ID to join the consultation group. DingTalk group ID: 175205010586

Background information

The PolarDB PostgreSQL Agentic Database MCP Server uses an API key authentication mechanism to ensure trusted identities and controlled operation scopes.

Credential

Description

How to obtain

API key

The key has the format pagc_key_xxx and includes cluster ID and tenant ID information.

Create it in the Alibaba Cloud console.

Bearer token

Provide the API key in the MCP client configuration as Authorization: Bearer <API_Key>.

Use the API key described above.

An API key embeds the AgenticDB cluster and tenant information. On the first connection, MCP Server automatically validates the key format, parses the payload, and performs remote verification. After verification succeeds, a session is created, and subsequent calls run within that session context. Neither the AI Agent nor its user ever accesses database endpoints, accounts, or passwords.

Scope of application

  • An PolarDB PostgreSQL Agentic Database cluster has been created, and an API key (pagc_key_xxx) has been obtained.

  • An MCP-compatible client has been downloaded and installed, such as Qoder, Hermes, Cursor, or Claude Desktop/CLI.

Step 1: Obtain an API key

  1. Log on to the PolarDB console.

  2. In the left-side navigation pane, choose AgenticDB Cluster List > PostgreSQL to go to the AgenticDB Clusters page.

  3. Select an activated AgenticDB cluster and go to the Configuration and Management > API Key Management page.

  4. Click Create API key. The console generates an API key in the pagc_key_xxx format.

Note
  • Store the API key securely. The console displays it only once when you create it.

  • An API key contains a cluster ID (pagc-xxx) and a tenant ID (t-xxx), which determine the scope of the AI Agent's operations. Each API key can access only resources under its bound cluster and tenant.

Step 2: Configure a local MCP tool

Before you configure the MCP Server, make sure the following prerequisites are met:

  • Node.js >= 20.0.0.

  • An AccessKey ID and AccessKey secret have been obtained for calling PolarDB OpenAPI.

    Click to expand to view how to configurea RAM account with a least privilege policy

    Create an access policy

    1. Log on to the RAM console. In Permissions > Policies, create an access policy for PolarDB PostgreSQL Agentic Database.

    2. On the policy creation page, select Script editor. Paste the following least privilege access policy:

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "polardb:VerifyAgenticDBTenantApiKey",
              "polardb:DescribeAgenticDBProjects",
              "polardb:DescribeAgenticDBProject",
              "polardb:CreateAgenticDBProject",
              "polardb:DeleteAgenticDBProject",
              "polardb:DescribeAgenticDBBranches",
              "polardb:DescribeAgenticDBBranch",
              "polardb:CreateAgenticDBBranch",
              "polardb:DeleteAgenticDBBranch",
              "polardb:DescribeAgenticDBBranchEndpoints",
              "polardb:DescribeDBClusterEndpoints",
              "polardb:DescribePolarFs",
              "polardb:DescribePolarFsAttribute"
            ],
            "Resource": "*"
          }
        ]
      }
    3. Save the access policy and set the policy name to PolarDBPGAgenticDBMinimalAccess.

    Create an AccessKey pair and attach the access policy

    1. In the RAM console, go to the Identities > Users list, and select an existing RAM user or create a new RAM user.

    2. On the RAM user details page, click the Authentication tab and create an AccessKey pair for local development for the user. Securely save the AccessKey ID and AccessKey secret.

      Note

      The AccessKey secret is displayed only when you create it. Do not record real credentials in documentation, source code, or public locations.

    3. On the user's Permissions page, grant permissions and attach the PolarDBPGAgenticDBMinimalAccess access policy.

Add the following entry to the MCP Server configuration in your client. The following example uses a JSON configuration file:

{
  "mcpServers": {
    "polardb-agentic": {
      "command": "npx",
      "args": ["-y", "mcp-server-polardb-agentic@latest"],
      "env": {
        "POLARDB_ACCESS_KEY_ID": "<your-accesskey-id>",
        "POLARDB_ACCESS_KEY_SECRET": "<your-accesskey-secret>",
        "POLARDB_AGENTIC_API_KEY": "pagc_key_xxx"
      }
    }
  }
}

Replace pagc_key_xxx in the configuration with the API key obtained in Step 1, and replace your-accesskey-id and your-accesskey-secret with the AccessKey ID and AccessKey secret that you obtained. After you add the configuration, the client automatically initiates a connection. MCP Server validates the API key and creates a session.

Examples

Qoder

In Qoder Desktop, choose Extensions > Connectors, click Add > Paste JSON Configuration, and add the following configuration in the dialog box that appears.

{
  "mcpServers": {
    "polardb-agentic": {
      "command": "npx",
      "args": ["-y", "mcp-server-polardb-agentic@latest"],
      "env": {
        "POLARDB_ACCESS_KEY_ID": "<your-accesskey-id>",
        "POLARDB_ACCESS_KEY_SECRET": "<your-accesskey-secret>",
        "POLARDB_AGENTIC_API_KEY": "pagc_key_xxx"
      }
    }
  }
}

Qoder IDE

Click the profile avatar in the upper-right corner of Qoder IDE and select Qoder IDE Settings. In MCP Services, click Add and add the following configuration.

{
  "mcpServers": {
    "polardb-agentic": {
      "command": "npx",
      "args": ["-y", "mcp-server-polardb-agentic@latest"],
      "env": {
        "POLARDB_ACCESS_KEY_ID": "<your-accesskey-id>",
        "POLARDB_ACCESS_KEY_SECRET": "<your-accesskey-secret>",
        "POLARDB_AGENTIC_API_KEY": "pagc_key_xxx"
      }
    }
  }
}

Claude CLI

  • We recommend that you use the claude mcp add command to add the MCP Server. Run the following command in a terminal:

    claude mcp add polardb-agentic --transport stdio \
      --env POLARDB_ACCESS_KEY_ID=<your-accesskey-id> \
      --env POLARDB_ACCESS_KEY_SECRET=<your-accesskey-secret> \
      --env POLARDB_AGENTIC_API_KEY=pagc_key_xxx \
      -- npx -y mcp-server-polardb-agentic@latest

    After the command succeeds, run claude mcp list to view the configured MCP Server list.

  • You can also directly edit the Claude configuration file: the user-level configuration file is ~/.claude.json, and the project-level configuration file is .claude.json in the project root directory. Add the following JSON under the mcpServers node:

    {
      "mcpServers": {
        "polardb-agentic": {
          "command": "npx",
          "args": ["-y", "mcp-server-polardb-agentic@latest"],
          "env": {
            "POLARDB_ACCESS_KEY_ID": "<your-accesskey-id>",
            "POLARDB_ACCESS_KEY_SECRET": "<your-accesskey-secret>",
            "POLARDB_AGENTIC_API_KEY": "pagc_key_xxx"
          }
        }
      }
    }

After the configuration takes effect, restart the Claude CLI session to connect.

Hermes

Edit ~/.hermes/config.yaml:

mcp_servers:
  polardb_agentic:
    command: "npx"
    args: ["-y", "mcp-server-polardb-agentic@latest"]
    env:
      POLARDB_ACCESS_KEY_ID: "<your-accesskey-id>"
      POLARDB_ACCESS_KEY_SECRET: "<your-accesskey-secret>"
      POLARDB_AGENTIC_API_KEY: "pagc_key_xxx"

Step 3: Verify the connection

After the configuration is complete, a connected status in the client indicates that authentication has succeeded. You can then interact with the AI Agent by using natural language, for example:

  • "List all my projects."

  • "Create a new branch in project my-app."

  • "Show the schema of the users table."

  • "Run SELECT * FROM orders LIMIT 10."

Feature overview

The PolarDB PostgreSQL Agentic Database MCP Server provides the following tool capabilities.

Project management

Tool

Description

Read-only

list_projects

Lists all AgenticDB projects under the current tenant. Supports pagination.

Yes

describe_project

Returns detailed information about a specified project.

Yes

create_project

Creates a project and returns its details and default branch name.

No

delete_project

Deletes a project and all of its data. Requires your confirmation.

No (destructive)

Branch management

Tool

Description

Read-only

list_branches

Lists all branches under the current tenant. Supports project filtering.

Yes

describe_branch

Returns detailed information about a specified branch.

Yes

create_branch

Creates a branch from an existing branch by using an instant fork.

No

delete_branch

Deletes a specified branch. Requires your confirmation.

No (destructive)

get_connection_string

Returns the PostgreSQL connection string of a branch. A compute node is automatically allocated when none exists.

Yes

Schema browsing

Tool

Description

Read-only

get_database_tables

Lists the schema, name, type, and comment of every table in the database.

Yes

describe_table_schema

Returns column definitions, data types, and constraints for a specified table.

Yes

SQL execution

Tool

Description

Read-only

run_sql

Runs a single SQL statement.

No

run_sql_transaction

Atomically runs multiple SQL statements in a single transaction.

No

explain_sql_statement

Uses EXPLAIN ANALYZE to analyze a query execution plan.

Yes

Lakebase object storage

Tool

Description

Read-only

describe_lakebase_instances

Lists Lakebase (PolarFS) instances associated with the current cluster.

Yes

get_lakebase_connection_info

Returns S3 gateway connection information, including the endpoint, credentials, and bucket.

Yes

lakebase_list_objects

Lists objects in a Lakebase instance. Supports prefix filtering and pagination.

Yes

lakebase_upload_object

Uploads text content as an object over the S3 protocol.

No

lakebase_download_object

Downloads and reads an object over the S3 protocol.

Yes

lakebase_delete_object

Deletes an object. Requires your confirmation.

No (destructive)

Daily usage

After the connection is established, the MCP client maintains session state through a session ID, so subsequent requests do not require authentication again. You can use the following natural-language prompts:

  • Create a project: "Create a new project named my-app and add a users table with id, name, email, and created_at columns."

  • Inspect the schema: "Show the full schema of the users table in project my-app."

  • Work with branches: "Create a new development branch named feature-auth from main."

  • Use object storage: "Upload this CSV data to Lakebase and then query it from the database."

Security mechanisms

Layered protections in PolarDB Agentic Database

  • Credential isolation: Database endpoints, accounts, and passwords are encrypted and managed by MCP Server. Connection information never appears in the AI Agent context.

  • Access control: Each API key can operate only on resources in its bound cluster and tenant. Cross-account or cross-cluster access is not allowed.

  • Three-layer key validation: Format validation, payload parsing, remote OpenAPI verification, and consistency checks protect against key forgery and tampering.

  • Destructive-operation protection: Destructive operations such as delete_project, delete_branch, and run_sql containing DROP, DELETE, or TRUNCATE do not run automatically. The AI Agent always asks for your confirmation first.

  • Session isolation: Each session has an independent context (cluster ID and tenant ID), and sessions are fully isolated from one another.

API key management

  • Key format: pagc_key_{base64url(clusterId:tenantId:random)}.{hmac_signature}.

  • Key expiration: You can set an expiration time when you create a key, or configure it never to expire.

  • Key revocation: You can revoke an issued API key at any time in the console.

  • Multiple keys: A tenant can create multiple API keys for different AI Agents or use cases.

Limits and security guidelines

  • The run_sql and run_sql_transaction tools provided by MCP are designed for interactive queries, debugging, and management operations. They are not suitable for high-frequency database access or for database access on an application's critical path. For production workloads, batch processing, or scenarios that require low latency or high reliability, use a database connection string to connect directly from your application client through a database driver, and manage connection pools, timeouts, retries, transactions, and access control.

  • The availability, concurrency, and request frequency of some MCP tools may be subject to traffic shaping, quotas, and server-side rate limiting policies of the underlying OpenAPI.

  • We recommend that you use MCP connections only in controlled development, testing, or IDE workflows. Review and authorize each operation that a large language model (LLM) requests before you run it.

  • We recommend that you store API keys securely, allow only trusted users to use them, and rotate them regularly.

FAQ

  • Q: Do I need to reconfigure the client after an API key expires?

    A: Yes. An expired API key returns a 401 error. Create a new API key in the console and update the client configuration.

  • Q: How do multiple users or AI Agents use the MCP Server?

    A: Each AI Agent uses an independent API key and session. Multiple API keys can be created under the same tenant, so separate users or AI Agents do not interfere with one another.

  • Q: Which operations require manual confirmation?

    A: All operations marked as destructive, including delete_project, delete_branch, SQL containing DROP, DELETE, or TRUNCATE, and lakebase_delete_object, do not run automatically. The AI Agent asks for your confirmation first.

  • Q: Can I restrict the AI Agent to read-only operations?

    A: The current version does not support read-only mode configuration. The AI Agent follows the confirmation flow before running write operations.

  • Q: Which MCP clients are supported?

    A: Clients that implement the MCP stdio protocol are supported, including Qoder, Cursor, Claude Desktop, and Windsurf.

Troubleshooting

Symptom

Possible cause

Resolution

The connection returns 401 Unauthorized: InvalidKeyFormat.

The API key format is invalid.

Verify that the key starts with pagc_key_ and contains a . separator.

The connection returns 401 Unauthorized: InvalidPayload.

The API key payload cannot be parsed.

Verify that you are using the complete API key generated in the console.

The connection returns 401 Unauthorized: KeyNotFound.

The API key does not exist or has been deleted.

Check the key status in the console or create a new key.

The connection returns 401 Unauthorized: KeyExpired.

The API key has expired.

Create a new API key in the console and update the client configuration.

The connection returns 401 Unauthorized: KeyRevoked.

The API key has been revoked.

Create a new API key in the console and update the client configuration.

A tool call reports "instance is being prepared."

A compute node is being allocated.

Wait a few seconds and try again.

The client shows that the connection has dropped.

The session timed out or the server restarted.

Initiate the connection again. The client automatically re-authenticates.