Data

#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. Read-onlyuserrun the setup SQL 2. Firewallallow egress IPspublic host, TLS 3. Test5 checks, no savePOST /test 4. Savelabel, schemasrow cap, timeout 5. Grantto each agentPUT /databases

#1. Requirements

RequirementDetail
PostgreSQL version12 or newer.
NetworkThe 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.
Port1024 to 65535. Default 5432.
TLSRequired. sslmode is verify-full (default) or require.
AuthenticationThe server must use SCRAM-SHA-256. A server that asks for md5 or a cleartext password is refused.
FirewallAllow 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;
StatementEffect
CREATE ROLE ... LOGINA 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 ... SETSessions start read-only, a statement stops after 15 s, and an idle open transaction ends after 30 s.
GRANT CONNECTIt may connect to your database.
GRANT USAGE + GRANT SELECTIt may read the tables that exist now in that schema.
ALTER DEFAULT PRIVILEGESIt 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.

FieldDescription
connection_uriOptional 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.
hostPublic host name or IP address.
port1024 to 65535. Default 5432.
databaseDatabase name.
usernameThe user you created.
passwordNever shown again after you save it. Stored encrypted.
sslmodeverify-full (default) or require.
ca_cert_pemOptional 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 TLSRequired to save sslmode=require.
labelA name for the connection, 1 to 100 characters, unique among your connections. Agents see it as the database's name.
allowed_schemasSchemas agents may see. Leave empty for every schema the user can read. At most 100.
max_rowsHighest number of rows one query may return to an agent. 1 to 5500, default 100.
statement_timeout_msTime 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
networkThe host resolves only to allowed public addresses.
connectA TLS connection and SCRAM login work. Timeouts are retried once (serverless databases can take a moment to wake).
serverServer version (12 or newer), whether it is a read replica, TLS version.
privilegesWhat the user is allowed to do.
schemasWhich 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:

ReasonMessage shownWhat to do
blocked_hostWhy the host is not allowedUse a public host name.
timeoutTimed out connecting ...Check host, port and that AI Studio's IPs are allowed.
unreachableCould not reach the database server ...Same as above.
tlsCould not establish a verified TLS connection ...Check the TLS mode and CA certificate.
authThe 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_missingThe 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.
unknownCould 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=require needs your acknowledgement again.

A connection has one of these states:

ResultNew status
Test passesactive
Login, TLS, missing database or blocked hostneeds_reconnect
A blocked privilege is founddisabled
The user has gained write privileges that were not acknowledged when saveddisabled

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:

ToolWhat it does
postgres_list_tablesLists tables and views, with approximate row counts and comments. No row data.
postgres_describe_tableColumns, types, keys, enum values, indexes and references, for up to 5 tables. No row data.
postgres_run_queryRuns one read-only query and returns rows.
postgres_explain_queryShows 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

Agent querypostgres_run_query Parserchecks Allowed: one SELECT, WITH, VALUES or TABLEno writes, no side-effect functions, schemas inside the allow-list Refused: policy_block Execution envelope BEGIN READ ONLY local timeouts, path SELECT * FROM (q) LIMIT n ROLLBACK, never commit
The database user's grants remain the real security boundary. These steps are a second layer.

Every query goes through the same envelope, on a fresh transaction:

  1. BEGIN ... READ ONLY.
  2. Transaction-local settings: statement_timeout (the connection's value), lock_timeout 2 s, idle_in_transaction_session_timeout (statement timeout plus 10 s), TimeZone UTC, search_path limited to the allowed schemas. On PostgreSQL 17 and newer, also transaction_timeout.
  3. The query, wrapped as SELECT * FROM (<query>) AS _q LIMIT <n> and sent as one statement with bound parameters.
  4. ROLLBACK. Never COMMIT.

Before it is sent, the query is parsed with PostgreSQL's own parser and refused unless:

  • it is exactly one SELECT, WITH ... SELECT, VALUES or TABLE statement, at most 20,000 characters;
  • it contains no data-modifying statement (also inside WITH), no SELECT ... INTO, no FOR UPDATE or FOR 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_xml and 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.

Agent asks (default)
50
Connection default
100
Write call limit
100
Connection maximum
5500
Read queriesInsert, update, delete
LimitValue
Rows per queryThe agent asks for a number; default 50. Never more than the connection's max_rows.
Result size sent to the modelAt most 60 columns, 300 characters per cell, about 32,000 bytes in total. Larger results are cut and marked truncated.
Query timeThe connection's statement_timeout_ms (default 15 s, at most 60 s).
Lock wait2 s.
Connection attempt10 s.
Database calls per agent run30.
Failed calls in a rowAfter 4, the agent is told to stop retrying and explain the problem.
Connections from one AI Studio server to one databaseUp 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 runsUses the database?
The owner's own chat with the agentYes.
A sub-agent called from that chatOnly if the sub-agent has its own grant.
A schedule or webhook trigger owned by the agent's ownerYes, read-only.
The agent's public API, with a key the agent's owner createdYes, read-only. Anyone holding that key can make the agent query the database.
The public API with a key someone else createdNo.
Other people chatting with a shared agentNo.
SlackNo.
Agent evaluationsNo.
WorkflowsOnly 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:

  1. The database user has INSERT / UPDATE / DELETE on the tables (and you acknowledged this when saving the connection).
  2. You turned on write access for the connection on that agent.
  3. 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.

RuleDetail
InsertAt most 100 rows per call, all with the same columns, at most 60 columns.
Update and deleteNeed a where of column = value pairs (all must match). There is no way to change every row.
Row limitIf a call would change more than 100 rows (or the connection's max_rows, if lower), it is rolled back and changes nothing.
CommitEach successful call is committed at once.
SchemasThe 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:

FieldValues
surfaceWhere the call came from: owner_chat, sub_agent, agent_scheduled, agent_triggered, public_api, workflow_manual, workflow_scheduled, workflow_triggered.
statement_typeselect, explain, catalog (table listing or description), insert, update or delete.
statusok, 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_idEmpty 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.

AI Studio developer documentation. Times are UTC and IDs are opaque strings.