
Connect the Postgres MCP Server to Aurora as a Read-Only Database User with IAM Database Authentication
A hands-on guide to connecting the AWS Labs Postgres MCP Server to Aurora PostgreSQL as a SELECT-only database user with IAM database authentication. The agent holds no database password, and database privileges stop writes even if the server's read-only mode is turned off. Create, verify, and clean up in about 20 minutes.
You want an AI agent to read data in Aurora PostgreSQL. You want it to total up sales, or to look inside tables during an incident. But it must never write, whatever happens. This article is a hands-on guide for people in that situation.
If you connect the AWS Labs Postgres MCP Server the way its README example shows, the server connects with the master user's secret (that is the default when you don't specify a secret). The agent can then run SQL with the privileges of the master user. In this article, you create a database user that can only run SELECT, and you connect as that user with IAM database authentication and no password. What ultimately stops a write is not the MCP server's setting. It is the database's privileges. At the end, you deliberately configure the MCP server to allow writes and see for yourself that an UPDATE is still blocked.
The whole run, from creation to cleanup, takes about 20 minutes, and the Aurora ACU charge is 0.15 USD at most.
Prerequisites
- Reader: You can manage RDS with the AWS CLI and read IAM policies and SQL. You don't need to have used the Postgres MCP Server before.
- MCP: MCP (Model Context Protocol) is a protocol that lets an AI agent call external tools. The Postgres MCP Server receives SQL from the agent and runs it on the database. This article uses version 1.2.4.
- Your machine: bash,
git, AWS CLI v2,jq,psql,curl(to look up your IP address), Python 3 (to send messages to the MCP server), anduv(to start the MCP server withuvx). I tested in bash on WSL2. The machine must allow outbound connections on port 5432 and over HTTPS.
- AWS: An account with a default VPC, and a profile with permissions close to an administrator's (it creates and deletes an RDS cluster, a security group, and secrets, and it calls the RDS Data API. If you create the role in Step 3, it also creates and deletes an IAM role).
- Cost: An ACU is the unit of capacity in Aurora Serverless v2, and it costs 0.15 USD per ACU-hour in Tokyo (as of 2026-11-11). You are also billed for storage, the public IPv4 address, and the secrets for as long as they exist.
- Scripts: They are in the
postgres-mcp-iam-readonlyfolder of a public repository . Clone the repository, move into that folder, and replace<profile>on line 3 ofenv.shwith your AWS profile name. The Region defaults to Tokyo (ap-northeast-1). Keep the default resource names, such as the cluster name.
- Tested environment: I tested from 2026-11-11 to 11-20 with Aurora PostgreSQL 17.11 in the Tokyo Region. I ran the whole flow, from creation to cleanup, 6 times, and got the same results as the table in Step 5 each time.
The steps at a glance
Step | Command | What it does |
|---|---|---|
1 | ./01_create.sh | Creates a cluster with IAM DB authentication enabled (7 to 8 minutes) |
2 | ./02_dbsetup.sh | Creates a read-only database user |
3 | ./role_create.sh (optional) | Creates an IAM role for the agent |
3 | ./as_role.sh ./03_check_iam.sh | Checks the connection with psql |
4 | ./as_role.sh ./04_mcp_config.sh | Creates the MCP server configuration |
5 | ./as_role.sh ./05_verify_mcp.sh | Checks, through the MCP server, that writes are blocked |
Clean up | ./99_cleanup.sh | Deletes what you created (10 to 15 minutes) |
- Run every command inside the cloned folder, from the same single terminal. Step 1 opens port 5432 only to that terminal's IP address. If you change networks partway through, nothing from Step 3 onward can connect.
- A command prefixed with
./as_role.shruns as the role you create in Step 3, which has only three permissions. If you can't create IAM roles, skiprole_create.sh, drop./as_role.shfrom the later commands, and continue with your own permissions (they must includerds-db:connect, which permissions close to an administrator's do). The SQL results are the same, but you can't confirm that the minimal permissions are enough. If someone else manages IAM for you, the README in this folder explains what to ask them.
- The scripts aren't designed to be rerun. If a script stops partway and you can't continue, delete everything with
./99_cleanup.shand go back to Step 1.
Why stop writes with database privileges, not the server's setting
The Postgres MCP Server has a read-only mode, which is on unless you pass the startup argument
--allow_write_query . However, the README describes this mode as "best-effort defense-in-depth, not a security boundary," and asks you to combine it with a dedicated, least-privilege database role.On top of that, what this mode stops has changed from version to version. Version 1.1.7, which I tried in July 2026, judged by SQL keywords and rejected even a read-only
EXPLAIN ANALYZE as a write. In 1.2.2, the check changed to parsing the SQL, and a read-only EXPLAIN ANALYZE now passes (the change is described in the CHANGELOG . The CHANGELOG has no version numbers, so I confirmed the version from the packages on PyPI).Database privileges don't depend on the MCP server's version. If a database user is allowed only SELECT on tables, the database rejects any direct write to a table, whatever the MCP server lets through. So this article gives the job of stopping writes to the database's privileges (writes that go through a function are the one exception, covered in Step 2).
Choose a connection method
The MCP server can connect to the database in three ways. They differ in the path the SQL takes to the database and in whether a password is needed on the way.
Method (the README's name; --connection_method value in parentheses) | Path | Authentication | Requirements |
|---|---|---|---|
rdsapi ( RDS_API ) | RDS Data API (HTTPS) | IAM ( rds-data:ExecuteStatement ) and a password in Secrets Manager | Enable the Data API on the cluster. You don't need to open port 5432 |
pgwire ( PG_WIRE_PROTOCOL ) | Directly to port 5432 with the PostgreSQL protocol | A password in Secrets Manager | Network access to port 5432 |
pgwire_iam ( PG_WIRE_IAM_PROTOCOL ) | Same as pgwire | A 15-minute token signed with IAM credentials (connecting requires the rds-db:connect permission). Only the user name is read from the secret | Network access to port 5432, IAM DB authentication enabled, and GRANT rds_iam to the database user |
In the next figure, the solid black lines are the path the SQL takes, and the dashed orange lines are the flow of credentials (a password secret or an IAM token).

This article uses
pgwire_iam . It is the only method that lets you connect as a read-only database user without giving the agent's side a single database password (the other two require the agent's side to have permission to read a password secret). IAM decides which IAM principal (an IAM user or role) can connect as which database user, and the database's privileges decide what that user can do after connecting.You can't use
rdsapi , which wouldn't need port 5432, because ExecuteStatement in the RDS Data API requires secretArn . You can't call it without a password secret.The price of choosing
pgwire_iam is that the MCP server needs a path to port 5432. The scripts in this article enable public access for the test. In production, run the MCP server inside the VPC, or create a path with something like Session Manager port forwarding.How it fits together
From the time the MCP server starts until it sends the first SQL, the following happens in order. The numbers match the figure below (arguments that start with
-- are the startup arguments you pass in Step 4, and mcp_readonly is the database user you create in Step 2).- It reads the database user name from the secret passed in
--secret_arn.
- It calls
rds:DescribeDBClustersand checks that--db_endpointis an endpoint of the cluster in--db_cluster_arn.
- It signs an authentication token with the AWS credentials on your machine.
- It connects to port 5432 over TLS as
mcp_readonly, with the token in place of a password.
- Aurora accepts the token only when IAM allows
rds-db:connectfor that combination of IAM principal and database user.
- After the connection is made, the database's privileges decide what can be read or changed.

Step 1: Create a cluster with IAM DB authentication enabled
What to do
Run
./01_create.sh . It takes 7 to 8 minutes until the instance is available. The script creates a security group, the cluster ( cbsr2-iam , with the database appdb ), an instance, and the secret that holds the user name for Step 4 ( cbsr2/mcp_readonly ). It worked if it prints one line with the engine version first and the contents of state.json last (the cluster ARN, the endpoint, and the ARNs of the two secrets).Why
What matters is the following three arguments of the command that creates the cluster.
# 01_create.sh (excerpt)
aws rds create-db-cluster --db-cluster-identifier "$CLUSTER" --engine aurora-postgresql --engine-version "$VER" \
--master-username postgres --manage-master-user-password --database-name "$DB_NAME" \
--serverless-v2-scaling-configuration MinCapacity=0.5,MaxCapacity=2 --vpc-security-group-ids "$SG" \
--backup-retention-period 1 --enable-http-endpoint --enable-iam-database-authentication >/dev/null-
--enable-iam-database-authenticationenables IAM DB authentication.
-
--enable-http-endpoint(the Data API) is there so that the next step can create the database user. Thepgwire_iamconnection doesn't use it.
-
--manage-master-user-passwordhas RDS manage the master user's password in Secrets Manager. The master password is used only for the setup in the next step and is never given to the agent.
Step 2: Create a read-only database user
What to do
Run
./02_dbsetup.sh . It uses the master user's secret and sends the following SQL ( 02_dbsetup.sql ) through the Data API, one statement at a time. For each statement, it prints the SQL after >> and the number of rows updated. It worked if the number is 8 for the INSERT and 0 for the others.CREATE TABLE products (id int PRIMARY KEY, name text NOT NULL, price int NOT NULL);
INSERT INTO products VALUES (1,'apple',120),(2,'banana',80),(3,'cherry',300),(4,'grape',250),(5,'lemon',100),(6,'melon',800),(7,'orange',150),(8,'peach',200);
CREATE USER mcp_readonly WITH LOGIN;
GRANT rds_iam TO mcp_readonly;
GRANT CONNECT ON DATABASE appdb TO mcp_readonly;
GRANT USAGE ON SCHEMA public TO mcp_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;
ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT SELECT ON TABLES TO mcp_readonly;
REVOKE TEMPORARY ON DATABASE appdb FROM PUBLIC;Why
The first two statements are a table for the checks. The next six define the read-only user.
- A user with
GRANT rds_iambecomes a user that connects with IAM DB authentication. You don't set a password.
- It gets three things: connecting to the database, using the schema, and SELECT on tables. It gets no INSERT, UPDATE, or DELETE on any table.
-
ALTER DEFAULT PRIVILEGESautomatically grants SELECT on tables that the master userpostgrescreates later (it is there for when tables are added in production, and this guide doesn't use it).
The last statement,
REVOKE , stops temporary tables. In PostgreSQL, every user has the privilege to create temporary tables ( TEMPORARY ) by default, through PUBLIC ( privileges in the PostgreSQL documentation ). In fact, before I added the REVOKE , mcp_readonly could run CREATE TEMP TABLE and INSERT into that temporary table. It couldn't change data in existing tables, but you couldn't say it could "only read." After the REVOKE , the database rejects it with permission denied to create temporary tables in database "appdb" .When you apply the same setup to your own database, watch for the following three points. I tested each of them.
- Functions that write: When a function that runs with its creator's privileges (
SECURITY DEFINER) does an INSERT, calling it through an MCP server started with--allow_write_queryadded a row. Even without INSERT on the table, the user can write through the function. With the Step 4 configuration it is stopped, because the MCP server runs SQL in a read-only transaction. If you have such functions, remove the privilege to run them withREVOKE EXECUTE ... FROM PUBLIC. The README also recommends settingdefault_transaction_read_only = onfor the database user. With it, the function call was stopped, but through an MCP server started with--allow_write_query, aSETturned it off and the row count went up again. The reliable fix is to remove the privilege to run the function.
- Scope of
REVOKE TEMPORARY: It applies only toappdb, and to every ordinary user of it. For an application that uses temporary tables, grant it back withGRANT TEMPORARY. It doesn't apply to other databases.mcp_readonlycould also connect to the defaultpostgresdatabase and create a temporary table there. In databases you don't use, stop connections as well withREVOKE CONNECT ... FROM PUBLIC.
- Scope of
ALTER DEFAULT PRIVILEGES: It applies only to tables thatpostgrescreates. To let the user read tables that another role creates, you need the same statement for that role.
Step 3: Allow the connection in IAM
What to do
- Run
./role_create.sh(optional). It worked if it prints the role namecbsr2-mcp-readonly-agentfollowed by the names of the three statements it attached (ConnectAsReadOnlyDbUser ReadUserNameSecret ServerStartupClusterCheck).
- Run
./as_role.sh ./03_check_iam.sh. It worked if it prints anassumed-role/cbsr2-mcp-readonly-agent/...ARN as the caller, followed bymcp_readonlyand8(if you didn't create the role, the first line is your own ARN).
A role you just created can take a few seconds before it can be assumed. If
AssumeRole fails, wait a moment and run the command again.Why
Up to Step 2, everything runs with your own permissions, which can create clusters. The rest would also work with those permissions, but then you wouldn't know whether it works with the permissions you actually give the agent. So you create a role with only the following three permissions and run the remaining checks as that role. This is
iam-policy.example.json .{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ConnectAsReadOnlyDbUser",
"Effect": "Allow",
"Action": "rds-db:connect",
"Resource": "arn:aws:rds-db:ap-northeast-1:<account-id>:dbuser:<cluster-resource-id>/mcp_readonly"
},
{
"Sid": "ReadUserNameSecret",
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:ap-northeast-1:<account-id>:secret:cbsr2/mcp_readonly-??????"
},
{
"Sid": "ServerStartupClusterCheck",
"Effect": "Allow",
"Action": "rds:DescribeDBClusters",
"Resource": "arn:aws:rds:ap-northeast-1:<account-id>:cluster:cbsr2-iam"
}
]
}- The first statement is the core. It means "this role can connect to this cluster only as
mcp_readonly."<cluster-resource-id>is not the cluster's name. It is the resource ID that starts withcluster-(role_create.shlooks it up and fills it in).
- The second statement lets the server read the database user name from the secret. The trailing
-??????matches the six characters that Secrets Manager appends to the ARN. If you wrote-*, it would also match a different secret such ascbsr2/mcp_readonly-admin.
- The third statement lets the MCP server check the cluster at startup. At first I left it out and wrote the policy with only two statements.
psqlconnected with that, so I assumed the MCP server would work too, but it exited at startup with AccessDenied. You don't notice this while you run with a broadly privileged profile. It surfaces only when you narrow down to least privilege.
If you ran
role_create.sh as an IAM user, only that user can assume the role (if you ran it as a role, such as with SSO, see the README). 03_check_iam.sh creates a token that is valid for 15 minutes and connects with psql .# 03_check_iam.sh (excerpt)
aws sts get-caller-identity --query Arn --output text
TOKEN=$(aws rds generate-db-auth-token --hostname "$EP" --port 5432 --username "$RO_USER")
PGPASSWORD="$TOKEN" PGSSLMODE=require psql -h "$EP" -U "$RO_USER" -d "$DB_NAME" -At \
-c "SELECT current_user" -c "SELECT count(*) FROM products"You check with
psql before running the MCP server so that you can separate the causes when something fails. If it fails here, the cause is the rds-db:connect permission or the database user's setup. If it passes here and only the MCP server fails, the cause is a permission that only the MCP server uses (the second and third statements) or the MCP server's configuration.Step 4: Configure the MCP server
What to do
Run
./as_role.sh ./04_mcp_config.sh . It worked if it prints the configuration with the values from state.json filled in and saves the same content to mcp.json . mcp.json is the configuration you use to register the MCP server with an AI agent (an MCP client). It has the following shape ( mcp.example.json ), and the real mcp.json contains your own ARNs and endpoint.{
"mcpServers": {
"postgres-readonly": {
"command": "uvx",
"args": [
"awslabs.postgres-mcp-server@1.2.4",
"--connection_method", "PG_WIRE_IAM_PROTOCOL",
"--secret_arn", "arn:aws:secretsmanager:ap-northeast-1:<account-id>:secret:cbsr2/mcp_readonly-<suffix>",
"--db_cluster_arn", "arn:aws:rds:ap-northeast-1:<account-id>:cluster:cbsr2-iam",
"--db_endpoint", "<writer-endpoint>",
"--database", "appdb",
"--region", "ap-northeast-1",
"--db_type", "APG",
"--privilege_check", "enforce"
],
"env": { "AWS_PROFILE": "<profile>", "AWS_REGION": "ap-northeast-1" }
}
}
}If you ran it with
as_role.sh , env has no AWS_PROFILE (because it ran with the role's temporary credentials, not a profile). When you actually register the server with an agent, make the credentials of the Step 3 role available in the environment that runs the agent (this guide doesn't do that). The check script in the next step starts the MCP server directly with the same startup arguments as this file, so there is nothing to register with an MCP client here.Why
Version 1.2.4 has no argument that takes the database user name directly. Even with
pgwire_iam , the user name is read from the secret specified in --secret_arn . Step 1 already created this secret, and its content is {"username":"mcp_readonly","password":"unused"} . IAM authentication doesn't use password . At first I tried a secret that held only the user name, and the MCP server exited as soon as it started. The key is required even though it isn't used. "password":"unused" is the workaround. A user with rds_iam can't log in with a password ( limitations of IAM database authentication ), so even if the content leaks, nobody can connect without the rds-db:connect permission.Three points in the configuration are deliberate choices.
- No
--allow_write_query: This turns on the MCP server's read-only mode. If the MCP server stops a statement before it reaches the database, you find out sooner. Keep it as the first layer of defense, in front of the database's privileges.
-
--privilege_check enforce: If the database user it connected as is a superuser, a member ofrds_superuser, or hasBYPASSRLS, the MCP server refuses the connection (README). If you pass the master user's secret by mistake, you notice at startup. When I tried a configuration that connects as the master user, the server exited withRefusing to start: The MCP server is connecting as an over-privileged Postgres role (a member of rds_superuser).The default,warn, only prints a warning and connects.
- Pin the version with
@1.2.4: Both the read-only mode's checks and the error messages change between versions. To move to a newer version, changeMCP_VERSIONinenv.shand pass the check script in the next step first. I chose 1.2.4 because in 1.2.3, the version before it, the first SQL failed with this connection method (fixed in awslabs/mcp PR #4846 ).
Step 5: Predict, then verify
What to do
05_verify_mcp.sh starts the MCP server and sends MCP messages (JSON-RPC) to it directly, without an LLM. With an LLM in between, the model would decide which SQL gets sent. The script sends the following four sets, and it restarts the MCP server for each set.Startup arguments | SQL sent |
|---|---|
Step 4 configuration | SELECT current_user, count(*) FROM products |
Step 4 configuration | INSERT INTO products VALUES (9,'kiwi',90) |
Step 4 configuration | EXPLAIN ANALYZE SELECT * FROM products WHERE price > 100 |
Step 4 configuration plus --allow_write_query | UPDATE products SET price = price + 1 WHERE id = 1 , then SELECT price FROM products WHERE id = 1 |
Before you run it, predict these three things.
- Which one stops the INSERT: the MCP server or the database?
- Does
EXPLAIN ANALYZErun? (WithANALYZE, the query is actually executed.)
- If you add
--allow_write_queryand turn off the MCP server's read-only mode, does the UPDATE go through?
Once you have your predictions, run
./as_role.sh ./05_verify_mcp.sh . The first run takes a little longer, because uvx downloads the MCP server. First, it prints four summary lines, one per startup. If every line says init_ok= True , the server started. Then it prints the result of each SQL, one per line, in the form {"label":"select","result":{"result":[...]}} . These are the results with 1.2.4.label | SQL sent | Result (inside [...] ) | Passed, or stopped by |
|---|---|---|---|
select | SELECT | {"current_user":"mcp_readonly","count":8} | Passed |
insert | INSERT | {"error":"Statement type not allowed in read-only mode: InsertStmt"} | MCP server |
explain | EXPLAIN ANALYZE | The execution plan ( QUERY PLAN rows, ending with Execution Time ) | Passed |
update | UPDATE (with --allow_write_query ) | {"error":"InsufficientPrivilege: permission denied for table products"} | Database |
price_after | SELECT after the UPDATE | {"price":120} | Passed (the value is unchanged) |
What this shows
Writes are stopped in two places. The INSERT is rejected by the MCP server's read-only mode (the first layer) when it parses the SQL, and it is never sent to the database. When you remove that layer with
--allow_write_query , the UPDATE reaches the database. But permission denied is an error that PostgreSQL returns, and what stopped it is the privileges of mcp_readonly (the second layer). The SELECT right after it shows that the value is still 120. Whether someone adds this argument or forgets to remove it, a direct write to a table doesn't go through.
EXPLAIN ANALYZE ran because what it wraps is a SELECT. MCP server versions 1.2.2 and later judge it to be a read-only statement.If the server doesn't start
When the MCP server fails to start, the summary line says
init_ok= False exit= 1 . The reason isn't printed on the screen, so open verify_select.err , which is created in the same folder (the logs of the other startups go to verify_insert.err and so on). When you write the policy or the secret yourself, these are the two you are most likely to hit.Message in verify_select.err | Cause | Fix |
|---|---|---|
AccessDenied and is not authorized to perform: rds:DescribeDBClusters | The role doesn't have the third statement from Step 3 | Add the third statement |
Secret does not contain password. Available keys: username | The secret has no password key | Add a password key with a value you don't use |
The first one shows up as "
03_check_iam.sh passes, but only the MCP server doesn't start." Note that when you run as the role, this file also contains one WARNING line about an AccessDenied for rds:DescribeDBInstances , even when the server starts successfully. You can ignore it.Clean up
Run
./99_cleanup.sh with your own permissions. Don't prefix it with as_role.sh . If you ran role_create.sh in this folder, it deletes the role, and then it deletes the secret, the instance, the cluster, and the security group, in that order. At the end, it checks whether any of the four, other than the role, are left, and prints [] for each. If all four are [] , you are done. Even if an error occurs partway, the rest of the cleanup continues. It takes 10 to 15 minutes, and for long stretches nothing is printed.state.json , mcp.json , calls_*.json (the SQL that was sent), and verify_* (the responses and logs) remain on your machine. They contain ARNs and the endpoint, so delete them if you don't need them.What I checked before taking this setup to a production database (how to stop heavy queries, how to restrict where connections come from, auditing, token lifetime, and so on) is in PRODUCTION.md in the repository.
Remaining limitation: you still need a path to port 5432
If the RDS Data API supported IAM DB authentication, you could build the same setup without opening port 5432. The Redshift Data API accepts
DbUser and connects with temporary credentials issued under an IAM permission, and RDS Proxy has supported IAM authentication without a password in Secrets Manager since September 2025. I posted a request for the same capability in the RDS Data API on the AWS Builder Center Wishlist. If you think it is needed, please vote.Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article