AutomataGet Started

How to Connect Grok Bot to PostgreSQL (Safely, With Read-Only Access)

Connect Grok Bot to PostgreSQL with a read-only role, a table-scoped MCP token and a bearer key. Setup steps, routine ideas, safety limits and fixes.

By , Founder & CEO, Operational Intelligence Inc.

Updated 11 min read

Last updated: November 2026

To connect Grok Bot to PostgreSQL, you add a remote PostgreSQL MCP server to Grok Bot as a custom connector and give it a bearer token. The key safety step happens before that: connect as a read-only Postgres role that can only SELECT from named tables, and use a token scoped to those same tables. Setup takes about 15 to 20 minutes.

This guide uses Automata, a free, MIT-licensed, open-source PostgreSQL MCP server, hosted or self-hosted. The role and safety advice apply to any server; the comparison below covers where others fit better.

What you need

You needDetails
Grok BotThe desktop app, signed in. On a team, an admin's MCP policy can block custom servers.
A PostgreSQL databaseNeon, Supabase, Amazon RDS, Railway or self-hosted, reachable from Automata. A read replica is better than your primary.
AutomataA hosted account at mcp.getautomata.app, or a self-hosted instance with a public HTTPS URL.
About 15 to 20 minutesMost of it is step 1.

How to connect Grok Bot to PostgreSQL

Grok Bot never opens a database connection itself. It calls tools on the MCP server, and the server runs SQL as the role you gave it:

  1. Grok Bot

    MCP client

    • Calls run-query over HTTPS
    • Writes the SQL

    Stops: Actions that need your approval

  2. Automata

    MCP server

    • Bearer token header
    • Table allowlist, from the plan
    • One read-only statement

    Stops: Unshared tables, DDL, custom functions

  3. Read-only role

    Postgres grants

    • SELECT on named tables
    • Masked copies

    Stops: Writes, ungranted tables

  4. PostgreSQL

    Read replica

    • Hot standby
    • Statement timeout

    Stops: Any write, at the server

SELECT … FROM ordersAllowed: Passes every layer and returns a page of rows
SELECT … FROM paymentsRefused: Refused by Automata before a row is read
Every layer can say no on its own. A query refused at any step never reaches your rows.

Each layer can refuse on its own. The role decides what is possible at all; Automata decides which tables this token may reach and refuses anything else before a row is read.

Step 1: Create a read-only Postgres role

Create a dedicated role for Grok Bot. Never connect as a superuser or the owner: a superuser bypasses permission checks and row-level security.

-- A dedicated login with no special powers
CREATE ROLE grok_reader LOGIN PASSWORD '<strong-password>'
  NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS
  CONNECTION LIMIT 5;

-- Let it reach the database and one schema
GRANT CONNECT ON DATABASE app TO grok_reader;
GRANT USAGE ON SCHEMA public TO grok_reader;

-- Grant specific tables, never the whole schema
GRANT SELECT ON public.orders, public.order_items, public.signups TO grok_reader;

-- Read-only by default, and a time limit on every query
ALTER ROLE grok_reader SET default_transaction_read_only = on;
ALTER ROLE grok_reader SET statement_timeout = '15s';

Set a statement_timeout. Grok Bot writes its own SQL, and sooner or later one query will scan more than you expected. Fifteen seconds suits most reporting; raise it if a real report needs more.

Be careful with ALTER DEFAULT PRIVILEGES. It grants access to tables created in the future, so on public next month's payments table would become readable without anyone deciding it should. Use it only on a schema built for sharing:

GRANT USAGE ON SCHEMA reporting TO grok_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA reporting TO grok_reader;

-- Future tables that app_owner creates in reporting are readable too
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA reporting
  GRANT SELECT ON TABLES TO grok_reader;

Share sensitive tables as a copy without the sensitive columns: a materialized view you refresh on a schedule, or a copy table. Column grants and plain views don't work with a table-scoped Automata token: it lists and allows only tables the role can read in full, and it checks the base tables a plain view reads, so a column-granted customers or a view over it is refused.

For production, use a read replica. default_transaction_read_only is a default a session can change; a hot standby refuses writes at the server and keeps reports off your primary. The Claude read-only guide covers masked copies, row-level security and verifying the role.

Step 2: Add the database to Automata

Hosted: sign up at mcp.getautomata.app/signup; the free plan's one connection is enough. Self-hosted: deploy from the GitHub repo. Grok Bot connects from its own cloud computer, so the instance needs a public HTTPS URL.

Create a PostgreSQL database connection and paste the role's connection string, ideally pointing at the replica:

postgresql://grok_reader:<password>@replica.example.com:5432/app?sslmode=require

Automata tests the connection before saving. Percent-encode @ or # in the password (%40, %23). On Supabase, use the Session pooler string, not the IPv6-only db.<ref>.supabase.co host. On RDS, allow Automata in the security group. On Railway, use the public URL unless Automata runs in the same project.

Step 3: Mint a scoped token

Create a connector token for Grok Bot (New connector token):

  • Name: such as grok-bot, so you recognize it when revoking.
  • Expires: 30 or 90 days.
  • Actions: leave the defaults. PostgreSQL tokens start read-only: get-database-info, list-tables, describe-table and run-query. Writes need the separate run-statement tool, which is off unless you enable it. Leave it off.
  • Tables: choose Only selected tables and pick the tables you granted in step 1. Names are case-sensitive.

Click Create token and copy it. Automata shows it once and stores only a SHA-256 hash.

Step 4: Add Automata to Grok Bot and test it

These steps follow xAI's Grok Bot computer and apps docs, checked November 2026. The general walkthrough, including OAuth servers, is in How to add a custom MCP server to Grok Bot.

  1. In the Grok Bot desktop app, open Connect apps in the sidebar and choose Add a custom connector at the bottom.
  2. Enter a Name that says which database it reaches, such as Automata Orders DB.
  3. For Type, choose the remote HTTPS option and enter the Server URL: https://mcp.getautomata.app/mcp (or your self-hosted URL ending in /mcp).
  4. Add an HTTP header named Authorization with the value Bearer <connector-token>.
  5. Choose Add plugin.
Name:          Automata Orders DB
Server URL:    https://mcp.getautomata.app/mcp
HTTP header:   Authorization: Bearer <connector-token>

You can also ask the Bot in chat to "add a custom MCP server" and enter the token in its masked secret card. Never paste the token into the chat.

URL-only fallback: Automata also accepts https://mcp.getautomata.app/mcp/<connector-token>. Prefer the header, since URLs end up in logs more often.

Test it. Ask: "Which tools does Automata Orders DB give you?" A read-only token shows four. If run-statement appears, the token can write; go back to step 3. Then type @, attach the connector, and try:

  • "List the tables you can see."
  • "How many signups did we get each day last week?"

Now ask for a table you didn't share, such as payments. Automata refuses before any row is read:

This connector token is not scoped to public.payments. The tables it may reach are:
public.orders, public.order_items, public.signups. Ask the account owner to add
public.payments to the token's allowed tables, or rewrite the query to use only the
tables above.

The check reads the query plan, so a view or CTE that reaches payments is refused too.

Things to ask Grok Bot

Grok Bot's edge over a chat window is routines: describe a job and a schedule in plain words, and results arrive in the Bot's chat. Manage them on the Bot's Details tab. These prompts are starting points, not promises. Each one only works for tables on the token's allowlist, so the churn report needs a subscriptions table and the email example needs customers. Check the SQL in the first few runs before you trust the numbers.

  1. Morning sales summary. "Every weekday at 8am, use Automata Orders DB to report yesterday's orders, revenue and average order value, compared with the same weekday last week. Flag anything more than 20% off."
  2. Threshold alert. "Every hour from 9am to 6pm, check how many orders have been pending for more than 2 hours. Only message me if there are more than 10."
  3. Weekly churn report. "Every Monday at 9am, list customers whose subscription was cancelled last week, grouped by plan, and the total monthly revenue lost."
  4. Signup funnel check. "How many people signed up in the last 30 days, and how many of them placed a first order within 7 days? Show the SQL you used."
  5. Database plus WhatsApp. With the Grok Bot WhatsApp connector added too: "Find the order numbers customers mentioned in the Support WhatsApp group today and look up their status in the orders table."
  6. Database plus email. With an email connection: "Pull this month's top 10 customers by revenue and draft a thank-you email to each. Save them as drafts."

Here is what the morning summary might look like:

Grok BotRoutine: weekdays, 8am
  1. Grok Bot:

    Yesterday (Tuesday) vs last Tuesday Orders: 142 (last week 131, +8%) Revenue: $9,870 (last week $9,410, +5%) Average order: $69.51 (last week $71.83, -3%) Nothing is more than 20% off. Refunds were 4 orders, all for the same SKU, so it may be worth a look. Query: SELECT on public.orders, date filter on created_at, grouped by day.

  2. You:

    Which SKU? Show me the four orders.

Illustrative example with made-up numbers. Your output depends on your tables and prompt.

A threshold alert is a scheduled check rather than a live trigger. Routines must be at least five minutes apart, so an hourly check is a reasonable fit:

  1. Routine fires on schedule

    Grok Bot

    Every hour, 9am to 6pm, in the time zone set for the Bot.

  2. Count pending orders

    Automata

    run-query runs one read-only SELECT against the allowed orders table, as grok_reader.

  3. Compare with the threshold

    Grok Bot

    More than 10 pending for over 2 hours? If not, the run ends quietly.

Over the threshold: Grok Bot posts the count and the oldest orders in its chat.
How an 'alert me when X crosses Y' routine works with a read-only token.

Safety: what read-only access does and doesn't stop

Read-only Postgres access for AI is reasonably safe when the limits live outside the model. Here is what each layer covers, and what none of them do:

Which layer protects against which risk
RiskDatabase rolePlan allowlistToken scope
Writes and DDL (DROP, DELETE, UPDATE)Stops itStops itStops it
Reading a table you did not allowPartlyStops itStops it
A runaway query (cross join, huge scan)PartlyPartlyNo
Sensitive columns sent to an AI providerPartlyNoPartly
Prompt injection inside allowed rowsNoNoNo
A leaked password or tokenNoNoPartly
Technical controls cover writes and scope well. They cover data exposure and manipulation much less, which is where your own judgment comes in.

What read-only plus allowlists protect against:

  • Writes and schema changes. The role can't write, run-query runs read-only, and the token has no write tool. No prompt gets past all three.
  • Tables you didn't choose. Unlisted tables are left out of list-tables and their rows are refused, even through views and CTEs. Their names and columns stay visible in the system catalogs.
  • A leaked token. It reaches a few tables and can be revoked alone.

What they don't protect against:

  • Sensitive columns in allowed tables. If customers is allowed, Grok Bot can read its email column. Share a masked copy of the table instead.
  • Data leaving your infrastructure. Read-only stops changes, not disclosure. Every row Grok Bot reads goes to xAI's service.
  • Large result sets. Automata returns one page at a time, but a heavy query still loads your database until statement_timeout stops it. Use a replica.
  • Prompt injection from your own rows. Stored notes or reviews can contain instructions aimed at the AI. Grok Bot's Auto-review is model-based, so keep approvals on for anything that sends, especially when a task mixes database rows with WhatsApp or email tools.
  • Wrong answers. Read-only SQL can still join the wrong column. Ask for the SQL before you act on a number.

Ways to connect Grok Bot to Postgres, compared

OptionRemote URL supportRead-only by defaultTable scopingSetup effortCost
Automata (hosted)Yes, bearer header or /mcp/<token>YesYes, per tokenLow: no server to runFree plan with one connection; Pro $19/month
Automata (self-hosted)Yes, once deployed at a public HTTPS URLYesYes, per tokenMedium: deploy and maintain itFree (MIT), plus hosting
Postgres MCP ProSSE, if you host it publicly and add auth yourselfNo: defaults to unrestricted; restricted mode is opt-inNoMedium to highFree (MIT), plus hosting
DBHubHTTP, if you host it publicly; optional --auth-token bearer auth, off by defaultNo: opt-in via a TOML configNoMediumFree, open source, plus hosting
Export CSVs manuallyNot needed: you upload filesYes, nothing is liveYes: you pick what to exportLow per export, repeated every timeFree

Postgres MCP Pro and DBHub both default to local stdio. Postgres MCP Pro's docs describe no built-in auth for its SSE or HTTP mode, so a public URL needs an authenticating proxy in front. DBHub has an optional --auth-token bearer token for HTTP, off by default, so turn it on before exposing it. Grok Bot's Command connector type can instead start a stdio server on the Bot's cloud computer, but then your connection string lives there.

Where alternatives fit better: Postgres MCP Pro for index tuning and DBA work (in restricted mode), DBHub for several database engines, CSV exports for a one-off analysis. Postgres MCP Pro's tuning tools are still unmatched, but its last release is v0.3.0 from May 2025, the only commit since January 2026 is an August dependency pin, and its maker's site, crystaldba.ai, no longer resolves. Automata has no tuning tools and refuses queries that call user-defined functions. More in Best PostgreSQL MCP servers.

Troubleshooting

ProblemLikely cause and fix
401 or auth errorsHeader must be exactly Authorization: Bearer <token>. Otherwise the token is wrong, expired or revoked; create a new one.
Connector shows Needs auth or no toolsRe-open it in Connect apps and check the URL ends in /mcp. On a team, check it isn't Disabled by team admin.
Connection refused when saving in AutomataThe database isn't reachable from the internet, or a firewall or security group blocks Automata. On Supabase, use the Session pooler host.
SSL errorsAdd ?sslmode=require to the connection string. Some providers reject non-SSL connections outright.
A table isn't visibleNot on the token's allowlist, or the case differs. permission denied means the role lacks SELECT. A plain view needs its base tables allowed, and the role needs SELECT on them.
Query times outstatement_timeout stopped it. Ask Grok Bot to run it with explain: true, then narrow the query.
Grok Bot answers without queryingType @ and attach the connector, name it in the prompt, and add "Don't answer from memory."

More fixes are in the troubleshooting guide.

Frequently asked questions

How do I connect Grok Bot to PostgreSQL?

Create a read-only Postgres role, add the database to a PostgreSQL MCP server such as Automata, mint a table-scoped token, then add the server in Grok Bot under Connect apps → Add a custom connector with an Authorization: Bearer header.

Can Grok Bot write to my database?

Not with this setup. Automata's PostgreSQL tokens start read-only; writes need a separate run-statement tool with a row cap, off unless you enable it. The read-only role blocks writes in Postgres too.

Is it safe to give Grok Bot database access?

Reasonably, with a read-only role on named tables, a token scoped to the same tables, and ideally a replica. It won't hide sensitive columns in allowed tables, and rows Grok Bot reads go to xAI, so leave regulated data out.

Does this work with Supabase or Neon?

Yes. Any PostgreSQL database Automata can reach works, including Supabase, Neon, RDS and Railway. On Supabase, use the Session pooler connection string. Use sslmode=require everywhere.

Do I need to self-host?

No. Hosted Automata at https://mcp.getautomata.app/mcp works directly. A self-hosted instance needs a public HTTPS URL, because Grok Bot connects from its own cloud computer.

Can Grok Bot run scheduled database reports?

Yes. Ask the Bot to create a routine, such as a daily sales summary at 8am; results post in the Bot's chat. Routines run at least five minutes apart, so alerts are periodic checks, not real-time triggers.

Is it free?

Automata is free and MIT-licensed to self-host, and the hosted service has a free plan with one connection. Pro is $19/month with a 7-day trial and includes 5 users, plus $10 per extra user. Grok Bot itself needs an xAI plan that includes it.

Next steps

Comments

Questions, corrections, or your own setup? Join in below. Pick any name to post.