#Databases
Let AI Studio agents and workflows query your own PostgreSQL database. This guide is for the DBA or developer who sets the connection up. It covers the database user to create, connection rules, what the test checks, how queries are limited, optional write access, who can use the database, and the audit log.
#The short version
#1. Requirements
| Requirement | Detail |
|---|---|
| PostgreSQL version | 12 or newer. |
| Network | The host must resolve only to public internet addresses. Private ranges (10.x, 192.168.x, 172.16-31.x, link-local, loopback) are refused, including through IPv6 tricks such as NAT64 or IPv4-mapped addresses. Names such as localhost and names ending in .local, .internal, .localdomain, .localhost or .home.arpa are refused, as are single-label names. |
| Port | 1024 to 65535. Default 5432. |
| TLS | Required. sslmode is verify-full (default) or require. |
| Authentication | The server must use SCRAM-SHA-256. A server that asks for md5 or a cleartext password is refused. |
| Firewall | Allow AI Studio's outgoing IP addresses. The Databases screen in the app shows them. If none are shown, ask your administrator. |
AI Studio resolves the host name and checks every address it gets back. It then connects to the checked address, and repeats the check on every new connection.
#2. Create the read-only user
The Databases screen also shows this SQL, along with tips for common hosting providers (for example Supabase and Neon).
Run this as the database owner or an admin, and replace every <...> value.
-- Run as the database owner/admin. Replace every <...> value.
CREATE ROLE ai_labs_readonly WITH LOGIN PASSWORD '<long-random-password>'
NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 12;
-- Safety defaults (defense in depth; the GRANTs below are the real boundary).
ALTER ROLE ai_labs_readonly SET default_transaction_read_only = on;
ALTER ROLE ai_labs_readonly SET statement_timeout = '15s';
ALTER ROLE ai_labs_readonly SET idle_in_transaction_session_timeout = '30s';
GRANT CONNECT ON DATABASE <your_database> TO ai_labs_readonly;
-- Repeat for each schema the agent may read:
GRANT USAGE ON SCHEMA <your_schema> TO ai_labs_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA <your_schema> TO ai_labs_readonly;
ALTER DEFAULT PRIVILEGES FOR ROLE <role_that_creates_tables> IN SCHEMA <your_schema>
GRANT SELECT ON TABLES TO ai_labs_readonly;
-- To hide sensitive columns, grant only the columns the agent needs instead:
-- GRANT SELECT (id, status, total) ON <your_schema>.<table> TO ai_labs_readonly;
-- PostgreSQL 14 or older (or upgraded clusters):
-- REVOKE CREATE ON SCHEMA public FROM PUBLIC;| Statement | Effect |
|---|---|
CREATE ROLE ... LOGIN | A login user with no admin powers: not a superuser, cannot create databases or roles, cannot replicate, cannot bypass row-level security, at most 12 connections at once. |
ALTER ROLE ... SET | Sessions start read-only, a statement stops after 15 s, and an idle open transaction ends after 30 s. |
GRANT CONNECT | It may connect to your database. |
GRANT USAGE + GRANT SELECT | It may read the tables that exist now in that schema. |
ALTER DEFAULT PRIVILEGES | It may also read tables that <role_that_creates_tables> creates later. |
You can rename the role. Use a long random password, and make sure the server stores it as SCRAM-SHA-256 (password_encryption = scram-sha-256, the default since PostgreSQL 14). Row-level security policies apply to this user like any other.
#3. Connection fields
In the app you fill in these fields. You can give a connection URI, separate fields, or both. Separate fields win over the URI.
| Field | Description |
|---|---|
connection_uri | Optional postgresql:// URI or key=value string, at most 4096 characters. Only host, port, dbname, user, password and sslmode are accepted. Any other parameter is refused, naming it. Multi-host strings are refused. |
host | Public host name or IP address. |
port | 1024 to 65535. Default 5432. |
database | Database name. |
username | The user you created. |
password | Never shown again after you save it. Stored encrypted. |
sslmode | verify-full (default) or require. |
ca_cert_pem | Optional PEM CA certificate(s) to verify the server with verify-full. Without it, the usual public certificate authorities are trusted. Private keys are refused. Leave it empty to remove it. |
| Acknowledge unverified TLS | Required to save sslmode=require. |
label | A name for the connection, 1 to 100 characters, unique among your connections. Agents see it as the database's name. |
allowed_schemas | Schemas agents may see. Leave empty for every schema the user can read. At most 100. |
max_rows | Highest number of rows one query may return to an agent. 1 to 5500, default 100. |
statement_timeout_ms | Time limit for one query. 1000 to 60000, default 15000. |
verify-full encrypts the connection and checks that the server's certificate matches the host name. Use it whenever you can. If your provider uses its own certificate authority (AWS RDS, Google Cloud SQL, Supabase), paste its CA certificate in ca_cert_pem.
require encrypts but does not check who the server is. Someone who can intercept the traffic could pose as your database, so AI Studio saves it only after you acknowledge this in the app.
#4. What the connection test checks
When you save a connection, AI Studio runs a test and saves it only if it passes.
Step (key) | Checks |
|---|---|
network | The host resolves only to allowed public addresses. |
connect | A TLS connection and SCRAM login work. Timeouts are retried once (serverless databases can take a moment to wake). |
server | Server version (12 or newer), whether it is a read replica, TLS version. |
privileges | What the user is allowed to do. |
schemas | Which schemas and how many tables and views the user can read. |
Each step reports pass, warn, fail or skip with a message.
Refused outright (step privileges fails,): superuser, BYPASSRLS, REPLICATION, and membership in pg_write_all_data, pg_read_server_files, pg_write_server_files, pg_execute_server_program, pg_signal_backend, rds_superuser, cloudsqlsuperuser, azure_pg_admin, neon_superuser or supabase_admin.
Needs your acknowledgement (you must acknowledge it before saving): INSERT, UPDATE, DELETE or TRUNCATE on any table or view (up to 20 are listed), owning tables or views, or CREATE in a schema or in the database.
Warnings only: CREATEROLE, CREATEDB, membership in pg_maintain, pg_monitor, pg_read_all_settings, pg_read_all_stats, pg_create_subscription or pg_checkpoint. The report also lists notable extensions or untrusted languages (for example dblink, postgres_fdw, plpython3u) and the number of readable tables with row-level security.
When the connect or network step fails, the app shows why:
| Reason | Message shown | What to do |
|---|---|---|
blocked_host | Why the host is not allowed | Use a public host name. |
timeout | Timed out connecting ... | Check host, port and that AI Studio's IPs are allowed. |
unreachable | Could not reach the database server ... | Same as above. |
tls | Could not establish a verified TLS connection ... | Check the TLS mode and CA certificate. |
auth | The database rejected the username or password. | Check the credentials. |
auth_method | ... The database user needs a SCRAM-SHA-256 password. | Reset the password with password_encryption = scram-sha-256. |
database_missing | The database does not exist on this server. | Check the database name. |
too_many_connections | ... too many connections for this user. | Raise the user's connection limit or close other sessions. |
unknown | Could not connect to the database. | Check all of the above. |
Driver error text is never returned, so the test cannot be used to probe other servers.
#5. Manage connections
In the app you can edit a connection, re-run its test, see which schemas it exposes, and delete it. Before you delete one, the app shows which of your agents use it.
- Changing the label, allowed schemas, row cap or timeout saves at once, with no test.
- Changing any connection field (host, port, database, user, password,
sslmode, CA certificate) runs the test again first. You do not need to retype the password to change another field. - Switching to
sslmode=requireneeds your acknowledgement again.
A connection has one of these states:
| Result | New status |
|---|---|
| Test passes | active |
| Login, TLS, missing database or blocked host | needs_reconnect |
| A blocked privilege is found | disabled |
| The user has gained write privileges that were not acknowledged when saved | disabled |
If the database rejects the saved credentials while an agent is using it, the connection is set to needs_reconnect too. Update the credentials or re-run the test in the app. After you delete a connection, also drop or rotate the database user on your server.
#6. Grant a database to an agent
A connection does nothing until you grant it to an agent, in the agent's settings in the app. Only the owner of both the agent and the connection can grant. An agent you share with others does not let them grant or change its databases.
For each granted database you can:
- Narrow the schemas for this agent. They must be inside the connection's allowed schemas, if it has any.
- Turn on write access for this agent (see Write access). It is off by default.
You can grant up to 20 databases to one agent.
#7. What the agent can do
A granted agent gets these tools:
| Tool | What it does |
|---|---|
postgres_list_tables | Lists tables and views, with approximate row counts and comments. No row data. |
postgres_describe_table | Columns, types, keys, enum values, indexes and references, for up to 5 tables. No row data. |
postgres_run_query | Runs one read-only query and returns rows. |
postgres_explain_query | Shows the query plan (EXPLAIN, not executed). |
The agent sees table and column names and comments. Use comments (COMMENT ON TABLE ...) to explain your data to it.
#How a query is run
Every query goes through the same envelope, on a fresh transaction:
BEGIN ... READ ONLY.- Transaction-local settings:
statement_timeout(the connection's value),lock_timeout2 s,idle_in_transaction_session_timeout(statement timeout plus 10 s),TimeZoneUTC,search_pathlimited to the allowed schemas. On PostgreSQL 17 and newer, alsotransaction_timeout. - The query, wrapped as
SELECT * FROM (<query>) AS _q LIMIT <n>and sent as one statement with bound parameters. ROLLBACK. NeverCOMMIT.
Before it is sent, the query is parsed with PostgreSQL's own parser and refused unless:
- it is exactly one
SELECT,WITH ... SELECT,VALUESorTABLEstatement, at most 20,000 characters; - it contains no data-modifying statement (also inside
WITH), noSELECT ... INTO, noFOR UPDATEorFOR SHARE; - it calls no function with side effects or file or network access, for example
set_config,pg_sleep,pg_read_file,pg_notify,nextval,pg_advisory_*,lo_*,dblink*,query_to_xmland similar; - every schema-qualified table is inside the allowed schemas.
Views and functions can still read other schemas, which is why the database user's grants remain the real boundary.
#Limits
Database row caps
Rows returned to an agent in one query. Linear scale.
| Limit | Value |
|---|---|
| Rows per query | The agent asks for a number; default 50. Never more than the connection's max_rows. |
| Result size sent to the model | At most 60 columns, 300 characters per cell, about 32,000 bytes in total. Larger results are cut and marked truncated. |
| Query time | The connection's statement_timeout_ms (default 15 s, at most 60 s). |
| Lock wait | 2 s. |
| Connection attempt | 10 s. |
| Database calls per agent run | 30. |
| Failed calls in a row | After 4, the agent is told to stop retrying and explain the problem. |
| Connections from one AI Studio server to one database | Up to 3 kept open briefly during conversations (closed after 5 minutes idle). Background runs connect directly. |
Query results are marked as untrusted data for the model, so text stored in your tables is not followed as instructions.
#8. Who can use a granted database
| Where the agent runs | Uses the database? |
|---|---|
| The owner's own chat with the agent | Yes. |
| A sub-agent called from that chat | Only if the sub-agent has its own grant. |
| A schedule or webhook trigger owned by the agent's owner | Yes, read-only. |
| The agent's public API, with a key the agent's owner created | Yes, read-only. Anyone holding that key can make the agent query the database. |
| The public API with a key someone else created | No. |
| Other people chatting with a shared agent | No. |
| Slack | No. |
| Agent evaluations | No. |
| Workflows | Only llm steps with use_databases: true. Such a step sees every active connection of the workflow's owner, with no per-agent grant, read-only. Works for manual runs and the owner's triggers. |
#9. Optional: write access
An agent can insert, update and delete rows only when all of these are true:
- The database user has
INSERT/UPDATE/DELETEon the tables (and you acknowledged this when saving the connection). - You turned on write access for the connection on that agent.
- You (the owner) are chatting with the agent yourself. Write tools are never available to triggers, the public API, sub-agents or workflows.
The agent then also gets postgres_insert, postgres_update and postgres_delete. It never writes SQL for these: it names a table, columns and values, and AI Studio builds one parameterized statement.
| Rule | Detail |
|---|---|
| Insert | At most 100 rows per call, all with the same columns, at most 60 columns. |
| Update and delete | Need a where of column = value pairs (all must match). There is no way to change every row. |
| Row limit | If a call would change more than 100 rows (or the connection's max_rows, if lower), it is rolled back and changes nothing. |
| Commit | Each successful call is committed at once. |
| Schemas | The table must be inside the allowed schemas. |
CREATE ROLE ai_labs_writer WITH LOGIN PASSWORD '<long-random-password>'
NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 12;
GRANT CONNECT ON DATABASE <your_database> TO ai_labs_writer;
GRANT USAGE ON SCHEMA <your_schema> TO ai_labs_writer;
GRANT SELECT ON ALL TABLES IN SCHEMA <your_schema> TO ai_labs_writer;
-- Only the tables the agent may change:
GRANT INSERT, UPDATE, DELETE ON <your_schema>.<table> TO ai_labs_writer;
-- Needed if inserts use serial / identity columns:
GRANT USAGE ON ALL SEQUENCES IN SCHEMA <your_schema> TO ai_labs_writer;#10. Audit log
Every database call an agent or workflow makes is logged, including refused ones. The log keeps the SQL (encrypted), the outcome and the row count. It never keeps result rows. For write calls it keeps the parameterized SQL, not the values.
The connection's owner can read the log in the app. Each entry shows:
| Field | Values |
|---|---|
surface | Where the call came from: owner_chat, sub_agent, agent_scheduled, agent_triggered, public_api, workflow_manual, workflow_scheduled, workflow_triggered. |
statement_type | select, explain, catalog (table listing or description), insert, update or delete. |
status | ok, error, timeout, policy_block (refused by the SQL checks or a write row limit) or denied (no grant, connection not active, not allowed here). |
agent_id | Empty for workflow calls. |
Each connection also sets a PostgreSQL application_name such as ai-labs/agent-17, ai-labs/workflow or ai-labs/test-<id>, so you can find these sessions in pg_stat_activity and your server logs.