IMV MCP usage guide
During development, you can use IDEs such as Cursor and Qoder to call IMV MCP (Model Context Protocol) tools in natural language within your coding environment to create, monitor, diagnose, and optimize incremental materialized views (IMVs, also known as real-time materialized views) on AnalyticDB for PostgreSQL instances.
IMV MCP overview
MCP (Model Context Protocol) is an open standard protocol that provides large language models (LLMs) with standardized access to external tools. IMV MCP tools combine AnalyticDB for PostgreSQL IMV management with AI agents for full lifecycle management through natural language. Key benefits:
Natural language interaction: Create, monitor, and optimize IMVs by using conversational commands.
Context awareness: The AI agent understands your project structure and database schema.
All-in-one IDE experience: Manage IMVs without leaving your development environment.
Secure and controlled: Read-only diagnostics are separated from write operations. Destructive operations require user confirmation.
Prerequisites
An AI model with agent capabilities is configured in Cursor, Qoder, Codex, or Claude Code.
Node.js is installed. Version v26.0.0 or later is recommended. You can run
node -vto check whether the required version is installed.An AccessKey pair with DataAPI permissions is available. The required permissions include
ExecuteStatement,CreateSecret,DeleteSecret, andListSecrets. IfIMV_REGION_IDis not configured, theDescribeDBInstanceAttributepermission is also required.An AnalyticDB for PostgreSQL instance with the real-time materialized view feature enabled is available. The feature is enabled by default. Database credentials with the minimum required privileges are required.
Configure IMV MCP
The following environment variables are used to configure IMV MCP:
Variable | Required | Description |
ALIBABA_CLOUD_ACCESS_KEY_ID | Yes | The AccessKey ID used to authenticate API requests. |
ALIBABA_CLOUD_ACCESS_KEY_SECRET | Yes | The AccessKey secret used to authenticate API requests. |
ALIBABA_CLOUD_SECURITY_TOKEN | No | The STS token for temporary credential authentication. Required only when you use temporary credentials. |
IMV_DB_INSTANCE_ID | Yes | The ID of the AnalyticDB for PostgreSQL instance, for example, |
IMV_DB_USERNAME | Yes | The username used to connect to the database. |
IMV_DB_PASSWORD | Yes | The password used to connect to the database. |
IMV_DATABASE | No | The default target database. If not specified, the default database is used. |
Cursor
Navigate to Cursor Setting > Tools & Integrations > MCP Tools. Click New MCP Server to open the
.cursor/mcp.jsonfile.Add the following configuration to the file:
{ "mcpServers": { "imv-mcp": { "command": "npx", "args": ["-y", "@adbpg-imv/imv-mcp-server@latest"], "env": { "ALIBABA_CLOUD_ACCESS_KEY_ID": "<yourAccessKeyID>", "ALIBABA_CLOUD_ACCESS_KEY_SECRET": "<yourAccessKeySecret>", "IMV_DB_INSTANCE_ID": "<your-instance-id>", "IMV_DB_USERNAME": "<your-db-user>", "IMV_DB_PASSWORD": "<your-db-password>" } } } }Save the file.
imv-mcpappears in the MCP Tools list.
Qoder
Navigate to Preferences > Qoder Settings > MCP Server. Click +ADD to open the
mcp.jsonfile.Add the same JSON configuration as Cursor.
{ "mcpServers": { "imv-mcp": { "command": "npx", "args": ["-y", "@adbpg-imv/imv-mcp-server@latest"], "env": { "ALIBABA_CLOUD_ACCESS_KEY_ID": "<yourAccessKeyID>", "ALIBABA_CLOUD_ACCESS_KEY_SECRET": "<yourAccessKeySecret>", "IMV_DB_INSTANCE_ID": "<your-instance-id>", "IMV_DB_USERNAME": "<your-db-user>", "IMV_DB_PASSWORD": "<your-db-password>" } } } }Save the file.
imv-mcpappears in the MCP Server list.
Codex
After installing Codex, run the following command in the terminal:
codex mcp add imv-mcp \
--env ALIBABA_CLOUD_ACCESS_KEY_ID="<yourAccessKeyID>" \
--env ALIBABA_CLOUD_ACCESS_KEY_SECRET="<yourAccessKeySecret>" \
--env IMV_DB_INSTANCE_ID="<your-instance-id>" \
--env IMV_DB_USERNAME="<your-db-user>" \
--env IMV_DB_PASSWORD="<your-db-password>" \
-- npx -y @adbpg-imv/imv-mcp-server@latestIf the database password contains special characters such as * or $, enclose the password value in double quotes.
Claude Code
After installing Claude Code, run the following command in the terminal:
claude mcp add imv-mcp \
--env ALIBABA_CLOUD_ACCESS_KEY_ID="<yourAccessKeyID>" \
--env ALIBABA_CLOUD_ACCESS_KEY_SECRET="<yourAccessKeySecret>" \
--env IMV_DB_INSTANCE_ID="<your-instance-id>" \
--env IMV_DB_USERNAME="<your-db-user>" \
--env IMV_DB_PASSWORD="<your-db-password>" \
-- npx -y @adbpg-imv/imv-mcp-server@latestTool list
IMV MCP provides tools in four categories. Monitoring and diagnostics tools and metadata query tools are read-only. IMV lifecycle tools and DDL operation tools are write tools. Destructive operations require user confirmation.
Monitoring and diagnostics (read-only)
Tool | Description |
imv_latency | Queries the latency and pending rows for each base table pipeline. |
imv_error_log | Returns recent incremental maintenance error records. |
imv_incremental_stat | Returns performance statistics, including total duration, compute duration, apply duration, and delta rows. |
imv_is_ready | Checks whether the most recent create, replace, or refresh operation is completed. |
adbpg_diagnose_skew_single | Detects data skew for a single object. |
Metadata query (read-only)
Tool | Description |
imv_list_all | Lists all IMV names in reverse chronological order. |
imv_stat_single | Returns the size, row count, storage type, creation time, last refresh time, and access popularity of an IMV. |
imv_dependency | Queries the upstream and downstream dependency graph with nested IMV expansion. |
imv_get_viewdef | Returns the SQL definition of an IMV. |
adbpg_list_columns | Lists all columns of a table or materialized view. |
adbpg_list_indexes | Lists all indexes on an object. |
adbpg_index_definition | Returns the CREATE INDEX statement for an index. |
adbpg_uniqueness_ratio | Calculates the uniqueness ratio of a column. |
imv_optimize | Provides index and distribution key optimization diagnosis. |
IMV lifecycle (write)
Tool | Description |
imv_init_ddl | Initializes the DDL environment. This operation is idempotent. |
imv_create | Creates a new IMV. This is an asynchronous operation. Use |
imv_replace | Replaces the IMV definition by using CREATE OR REPLACE. |
imv_refresh_self | Performs a full READABLE refresh on a single IMV. |
imv_drop | Drops a materialized view. CASCADE is disabled. |
imv_alter_maintain_index | Atomically replaces the incremental maintenance index. |
DDL operations (write)
Tool | Description |
adbpg_create_index | Creates a B-tree index. |
adbpg_drop_index | Drops an index. |
adbpg_relation_alter_access_method | Changes the storage engine, for example, from heap to beam. |
adbpg_relation_alter_distributed | Modifies the distribution key or switches to REPLICATED. |
adbpg_relation_alter_rename | Renames a table, materialized view, or index. |
Examples
After configuring IMV MCP, you can manage IMVs through natural language in your IDE's Agent dialog.
Create an IMV
User instruction: Provide the SQL statement and the target IMV name.
The agent automatically calls a series of creation tools and proactively optimizes configurations such as the distribution key.
┌─ User ─────────────────────────────────────────────────
│ Create an IMV named imv_order_summary with the
│ following SQL:
│
│ SELECT
│ o.order_id,
│ o.customer_id,
│ o.order_date,
│ SUM(l.quantity * l.price) AS total_amount
│ FROM orders o
│ JOIN lineitem l ON o.order_id = l.order_id
│ GROUP BY o.order_id, o.customer_id, o.order_date
└──────────────────────────────────────────────────────
┌─ Agent ──────────────────────────────────────────────
│ I will create this IMV for you. First, initialize the
│ DDL environment, then create the view.
│
│ ⚙ Calling tool: imv_init_ddl
│ ✓ DDL environment is ready.
│
│ ⚙ Calling tool: imv_create
│ Parameters: name=imv_order_summary, sql=SELECT o.order_id, ...
│ ✓ Creation task submitted, waiting for readiness...
│
│ ⚙ Calling tool: imv_is_ready
│ Parameters: name=imv_order_summary
│ ✓ IMV is ready and can be queried.
│
│ ⚙ Calling tool: imv_optimize
│ Parameters: name=imv_order_summary
│ → Recommendation: Change the distribution key from the
│ default random distribution to (order_id) to improve
│ JOIN locality during incremental maintenance.
│
│ Calling tool: adbpg_relation_alter_distributed
│ Parameters: name=imv_order_summary, distributed_by=order_id
│ ✓ Distribution key adjusted to (order_id).
│
│ Summary: IMV imv_order_summary has been successfully
│ created and distribution key optimization is complete.
└──────────────────────────────────────────────────────List all IMVs
User instruction: List all IMVs in the current database.
The agent parses your intent and calls the imv_list_all tool to return all IMV names in the current database in reverse chronological order.
┌─ User ─────────────────────────────────────────────────
│ List all IMVs in the current database
──────────────────────────────────────────────────────
┌─ Agent ─────────────────────────────────────────────
│ Calling tool: imv_list_all
│
│ The current database has 4 IMVs (in reverse
│ chronological order):
│
│ # Name Created
│ 1 imv_order_summary 2025-06-15 14:30:00
│ 2 imv_daily_revenue 2025-05-20 09:15:00
│ 3 imv_customer_stats 2025-04-10 16:45:00
│ 4 imv_product_inventory 2025-03-01 11:00:00
└──────────────────────────────────────────────────────Check IMV status
User instruction: Check the size, last refresh time, and access frequency of imv_order_summary.
The agent calls the imv_stat_single tool to return the total size, estimated row count, creation time, last full refresh time, and access scan count.
┌─ User ─────────────────────────────────────────────────
│ How big is imv_order_summary, when was it last
│ refreshed, and how often is it accessed?
└──────────────────────────────────────────────────────
┌─ Agent ──────────────────────────────────────────────
│ ⚙ Calling tool: imv_stat_single
│ Parameters: name=imv_order_summary
│
│ Status of imv_order_summary:
│
│ Total size: 256 MB
│ Estimated rows: 1,820,000
│ Storage engine: heap
│ Created: 2025-06-15 14:30:00
│ Last full refresh: 2025-07-01 02:00:00
│ Access scan count: 3,472
│
│ This view has a moderate size and high access
│ frequency. Incremental maintenance is running normally.
└──────────────────────────────────────────────────────Diagnose refresh errors
User instruction: Why is my IMV not refreshing recently?
The agent calls imv_error_log to retrieve recent incremental maintenance error records and combines imv_incremental_stat statistics to identify the bottleneck. The following is a common example where dirty data causes a type conversion error that blocks incremental maintenance.
┌─ User ─────────────────────────────────────────────────
│ Why is my imv_daily_revenue not refreshing recently?
└──────────────────────────────────────────────────────
┌─ Agent ──────────────────────────────────────────────
│ Let me check the error log and maintenance statistics.
│
│ ⚙ Calling tool: imv_error_log
│ Parameters: name=imv_daily_revenue
│
│ Found the most recent error record:
│
│ Time: 2025-07-10 03:15:22
│ Error: ERROR: invalid input syntax for type numeric:
│ "N/A" (base table sales, column amount)
│ Impact: Incremental maintenance pipeline blocked
│ since this time.
│
│ ⚙ Calling tool: imv_incremental_stat
│ Parameters: name=imv_daily_revenue
│
│ Last successful maintenance: 2025-07-10 03:00:05
│ Current pending delta: 48,350 rows
│
│ Root cause: The amount column in the sales base table
│ received an invalid value "N/A", causing a type
│ conversion error during incremental maintenance and
│ blocking the pipeline. After fixing the dirty data,
│ use imv_refresh_self to perform a full refresh and
│ restore the incremental pipeline.
──────────────────────────────────────────────────────Check latency and optimize
User instruction: Check whether any or all IMVs have data latency.
The agent calls imv_latency to return the latency in seconds and unconsumed pending delta rows for each base table pipeline. For IMVs with detected latency, the agent first expands the full dependency tree (including nested sub-IMVs) via imv_dependency, then calls imv_optimize on each IMV in the tree for diagnosis. Diagnosis is automatically routed by view size: for small views (single segment data volume < 1 GB), the agent can independently perform precise evaluation of candidate indexes and provide recommendations directly. In this scenario, index and distribution key adjustments (imv_alter_maintain_index / adbpg_relation_alter_distributed) can be executed by the agent directly. For large views, the agent lists candidate solutions, informs you of the evaluation time, and executes the evaluation only after your confirmation. Landing adjustments also require your approval.
┌─ User ─────────────────────────────────────────────────
│ Check whether all IMVs have data latency
└──────────────────────────────────────────────────────
┌─ Agent ──────────────────────────────────────────────
│ ⚙ Calling tool: imv_latency
│
│ The following IMVs have latency:
│
│ IMV Name Base Table Latency Pending
│ imv_customer_stats customers 45s 12,300
│ imv_customer_stats orders 128s 85,600
│
│ All other IMVs have normal latency (< 5s).
│
│ I will perform further diagnosis on imv_customer_stats.
│
│ ⚙ Calling tool: imv_dependency
│ Parameters: name=imv_customer_stats, depth=2
│ → Dependency tree:
│ imv_customer_stats
│ ├── Base table: customers
│ ├── Base table: orders
│ └── Nested IMV: imv_order_agg (sub-view)
│ └── Base table: lineitem
│
│ Calling tool: imv_optimize
│ Parameters: name=imv_customer_stats
│ → This view has 420 MB per segment (< 1 GB), performing
│ automatic precise evaluation...
│
│ Diagnosis result:
│ The current incremental maintenance index is
│ (customer_id), but the incremental JOIN key is
│ (order_id), causing a full table scan of the orders
│ delta on each maintenance. Recommendation: Change the
│ incremental maintenance index to (order_id), which is
│ expected to reduce maintenance time by approximately
│ 70%.
│
│ ⚙ Calling tool: imv_alter_maintain_index
│ Parameters: name=imv_customer_stats, columns=order_id
│ ✓ Incremental maintenance index replaced with (order_id).
│
│ ⚙ Calling tool: imv_optimize
│ Parameters: name=imv_order_agg
│ → Sub-view imv_order_agg is already optimally configured.
│
│ Summary: The root cause of latency for
│ imv_customer_stats was that the incremental maintenance
│ index did not align with the JOIN key. Optimization is
│ complete. Subsequent maintenance latency is expected to
│ return to normal levels.
└──────────────────────────────────────────────────────Benefits
Focus on business development: Spend more time on business logic instead of managing infrastructure.
Simplified workflow: Manage IMVs through IDE conversations instead of switching between multiple tools.
Prevent misoperations: Read and write operations are separated. Destructive operations require confirmation.
Faster issue resolution: Diagnose latency, errors, and performance issues in one place.
FAQ
Why do I receive an Instance.NotFound error?
Check whether IMV_REGION_ID matches the region of your instance. Alternatively, remove IMV_REGION_ID to enable automatic region lookup. Also verify that the AccessKey pair belongs to the Alibaba Cloud account that owns the instance.
Why does my password not work in the command line?
If the password starts with * or contains special characters such as $ or !, enclose the password value in double quotes.
Why do tools not take effect after I change the configuration?
Some IDEs do not automatically restart the MCP service after a configuration change. Disable and then re-enable imv-mcp in the IDE to apply the changes.
How do I verify AccessKey permissions?
Make sure the account associated with the AccessKey pair has the required DataAPI permissions: ExecuteStatement, CreateSecret, DeleteSecret, and ListSecrets. You can use the AliyunGPDBFullAccess system policy or create a custom policy with the required permissions.