DEV Community

Cover image for Let your AI agent explore your data safely: read-only SQL, approved writes, an audit log and nightly backups
CloudHike Team
CloudHike Team

Posted on

Let your AI agent explore your data safely: read-only SQL, approved writes, an audit log and nightly backups

This is week 7 of Build with CloudHike, a weekly series where we build a small, real-world app with an AI coding agent and let CloudHike handle the backend.

New here? Week 1 built a referral waitlist, week 2 moved slow AI work into background jobs, week 3 built a file-sharing app with presigned uploads, week 4 connected every major AI editor to one project, week 5 built a members-only SaaS with real auth flows, and week 6 sent email from your own domain. Each post stands on its own, so you can start right here.

Your agent writes better code when it can see the real data. "Why is this dashboard number wrong?" is a much easier question when the agent can list the tables, read the columns and run a select against the actual database, instead of guessing from your schema file. The problem is the other half of that sentence: the same connection string that lets it read can also let it UPDATE without a WHERE.

Most setups give you two bad options: paste rows into the chat by hand, or hand the agent a full-power connection string and hope. This week we take a third path with CloudHike Postgres over MCP: the agent explores with read-only tools on every plan, writes only through one Pro tool that your editor asks you to approve, every write lands in the audit log, and a nightly backup with a safe restore sits behind all of it.

Every tool, limit and setting below comes from the live MCP docs, Postgres docs and Projects docs.

What we're building

A Next.js app called order-desk with a small orders database, and a safe routine for letting an agent work on it:

  • Two tables, customers and orders, created by migrations in the app's code and filled with seed data that has a few deliberately messy rows
  • The database explorer in the dashboard, so you can see the same data the agent sees, with the SQL editor left read-only
  • Agent exploration with list_tables, describe_table and query_database, which runs every statement in a read-only transaction
  • A backup before any change, with the Backup now button
  • A data fix with execute_sql (Pro), where your editor asks before it runs, plus the Free-plan route for the same fix
  • The audit log on the Usage page, where the write shows up as postgres.sql-write
  • A restore drill, so you know exactly what happens before you need it for real

Here's how it maps to CloudHike:

  • Postgres (DATABASE_URL, plus DIRECT_URL on pooled databases). A Postgres 16 database per project, with a built-in explorer, SQL editor and nightly backups
  • The MCP server: read-only database tools on every plan, and execute_sql on Pro only
  • Nothing can be deleted through MCP: deleting projects and services stays in the dashboard

What you need

  • A CloudHike account. Every new account gets $10 in free credits (eligible accounts, valid for 90 days), plus an extra $5 with the code TUBEGURUJI5, and no card is needed. The Free plan allows 2 projects and a 500 MB database on a shared server, which is plenty for this.
  • Cursor or Claude Code (Codex, VS Code, Windsurf and Gemini CLI work too; see week 4).
  • Node.js, for a Next.js app.
  • Optional: the Pro plan for Step 7. Everything else works on Free, and Step 7 shows the Free route too.

Step 1: Connect CloudHike to your agent (once)

In the CloudHike dashboard, open Connect MCP in the sidebar (https://cloudhike.dev/dashboard/coding-agent), pick your editor and click Copy with key. That creates your workspace API key the first time and gives you a snippet with the key already filled in. The server is remote (Streamable HTTP), so there's nothing to install.

Claude Code

claude mcp add --transport http --scope user cloudhike https://cloudhike.dev/api/mcp \
  --header "Authorization: Bearer icu_your_api_key"
Enter fullscreen mode Exit fullscreen mode

Run /mcp inside Claude Code to check that it's connected.

Cursor (~/.cursor/mcp.json)

{
  "mcpServers": {
    "cloudhike": {
      "url": "https://cloudhike.dev/api/mcp",
      "headers": {
        "Authorization": "Bearer icu_your_api_key"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Open Cursor Settings → MCP and look for the green dot. Snippets for Codex, VS Code, Windsurf, Gemini CLI and Claude Desktop are in the MCP docs.

Treat the key like a password: keep it in your home folder, not the repo. Revoke on the Connect MCP page disconnects every editor at once.

Step 2: Scaffold the app

npx create-next-app@latest order-desk
cd order-desk
Enter fullscreen mode Exit fullscreen mode

Open the folder in Cursor, or run claude in it.

Step 3: Deploy Postgres and create the tables with migrations

Paste:

Use the cloudhike MCP tools to set up the backend for this app. It's a Next.js app with a small orders database.

Create a CloudHike project called "order-desk". Deploy postgres and wait until it's ready. Put the .env into .env.local, make sure it's git-ignored, and don't show me any secret values. Then call get_docs for "postgres" and follow it:

  • Use Drizzle ORM with node-postgres. Keep one small pool (3 to 5 connections) on globalThis so dev hot reloads reuse it. Use DATABASE_URL for app queries, and DIRECT_URL for migrations if it is in .env.local.
  • Create two tables with a migration: customers (id, email unique, name, created_at) and orders (id, customer_id referencing customers, total_cents integer, status text, created_at).
  • Add a seed script (npm run seed) that inserts about 20 customers and 200 orders. Use the statuses "pending", "paid" and "shipped", but on purpose make a handful of orders use messy values like "Paid", "SHIPPED" and "shipped " with a trailing space, so we have something to find later.
  • Add a page at / that shows the number of orders per status.

Run the migration and the seed. Never print or commit the connection string. Tell me which variable names are in .env.local.

Behind the scenes that's create_project, deploy_services with postgres, wait_for_services, get_environment written straight into .env.local, and get_docs for the Postgres page as Markdown. Schema changes live in migrations in your repo, which is what the docs recommend: they're reviewed and repeatable.

Run npm run dev and open the page. You should see more than three status rows, because of the messy seed data. That's the bug we'll have the agent find.

Step 4: Look at it yourself in the database explorer

Before the agent touches anything, see what it will see. In the dashboard, click Open database on the ready Postgres card. No client to install:

  • Data: pick a schema, search the table list, browse 25 to 250 rows per page, sort, search across a row, and click a row to see or copy it as JSON.
  • SQL Editor: run SQL with results in a grid, save snippets, and keep a per-project history in your browser.
  • Stats: database size, connections, cache hit ratio, uptime, and each table's size, rows and index use.
  • Backups: list, take, download and restore backups. We'll use this in Steps 6 and 9.

The explorer is read-only until you switch off Read-only in the SQL editor. Each query has a 10 second statement timeout and a 3 second lock timeout. Leave it read-only for now and try:

select status, count(*) from orders group by status order by 2 desc;
Enter fullscreen mode Exit fullscreen mode

You'll see the same messy statuses as on your page.

Step 5: Let the agent explore with read-only tools

Three MCP tools are all the agent needs to understand a database, and none of them can change anything:

  • list_tables: schemas, and the tables and views in one schema.
  • describe_table: a table's columns, types, primary key, nullability and defaults.
  • query_database: runs one SQL statement in a read-only transaction, up to 500 rows, with a 10 second timeout.

Because query_database runs in a READ ONLY transaction and takes one statement at a time, the agent cannot change data or tables with it, on any plan. Paste:

Use only the cloudhike read-only database tools (list_tables, describe_table, query_database) on the order-desk project. Don't edit any files.

  1. List the tables in the public schema and describe customers and orders.
  2. Find out why the home page shows more than three statuses. Show me every distinct status value with its count, and make trailing spaces visible (for example by wrapping the value in brackets).
  3. Check for anything else odd: orders whose customer doesn't exist, totals of zero or below, and customers with no orders.
  4. Propose one UPDATE statement that would normalise the statuses, and a migration that would stop new bad values from getting in. Don't run either.

You should get a short report and two proposals, without a single write. If you're curious, ask it to run an UPDATE through query_database. It's a read-only transaction, so the database refuses it.

Two practical notes from the docs:

  • Database tools share a limit of 60 calls per 10 minutes. If you see 429 "Too many requests", wait the time shown. An agent that explores in a few focused queries stays well inside it.
  • Free databases with no connections for 6 hours are stopped. If the agent's queries fail the morning after, click Wake on the Postgres card.

Step 6: Take a backup before you change anything

CloudHike already runs a nightly job at 02:00 that runs pg_dump for every running database. Before a data fix, though, take your own. Open the database, go to the Backups tab and click Backup now.

What you get from the Backups tab:

  • Retention: in the platform's backup storage, backups are kept up to 3 days on Free, 15 on Pro and 30 on Scale. The newest backup is always kept.
  • Your own bucket, if you prefer: you can save backups to your project's own Storage bucket instead, under _backups/postgres/. There you keep them as long as you like, or forever, and they count toward the bucket's size.
  • Download: through a short-lived signed link, so you can keep a copy off the platform.

Step 7: Fix the data with execute_sql (Pro), with your approval

On the Pro plan, the agent also sees execute_sql, which can insert, update, delete and change the schema. Three things make it safe to use:

  • The whole script runs in one transaction, committed only if every statement succeeds.
  • It's marked as destructive, so your editor asks you before running it. Nothing runs until you approve the exact SQL.
  • Every run is written to the audit log as postgres.sql-write.

If you just upgraded, reconnect your editor: the docs say execute_sql only appears after that. Then paste:

Use the cloudhike execute_sql tool on the order-desk project to normalise the order statuses: lowercase them and trim spaces, only for rows where the value would change. Show me the exact SQL before you call the tool, and nothing else in the same script. Afterwards, use query_database to show the distinct statuses and their counts again.

When the approval prompt appears, read the SQL before you approve it. That's the docs' own warning, and it's the whole point of this step. Check that the UPDATE has a WHERE, and that the script is only what you asked for.

Then the second half of the fix, the part that stops it from coming back:

Now add a migration in the app's code (not execute_sql) that adds a check constraint on orders.status allowing only "pending", "paid" and "shipped". Run it, then refresh the home page.

The docs say it plainly: for schema changes, prefer migrations in your app's code so they're reviewed and repeatable. execute_sql is for the one-off data fix; the constraint belongs in your repo.

On the Free plan? execute_sql isn't offered, so the agent stays strictly read-only. Take the UPDATE it proposed in Step 5, open the SQL Editor, switch off Read-only, and run it yourself. With writes allowed, a script runs in one transaction that commits only if every statement succeeds, and statements like DROP, DELETE and UPDATE ask for confirmation first.

Step 8: Read the audit log

Open the project in the dashboard, go to the Usage page and look at the audit log. You should find:

  • postgres.sql-write for every execute_sql run from Step 7.
  • environment.agent-fetch for each time the agent fetched the .env with get_environment in Step 3.
  • Creating projects, deploying services, and revealing or resetting secrets, which are written there too.

That's the record you want when you let an agent near production: what was written, and when, alongside everything else that touched the project's keys.

Step 9: Practise a restore

Restoring isn't an MCP tool. It stays in the dashboard, next to your backups. Doing it once on a test project means you'll know what to expect when it matters.

On the Backups tab, pick the backup you took in Step 6 and restore it. Here's what CloudHike does, per the docs:

  1. It takes a safety backup first, of the database as it is now.
  2. It loads the dump into a new database next to the live one.
  3. It swaps them only after the dump has fully loaded. A failed restore leaves your database untouched.

Run the Step 4 query again in the SQL editor. The messy statuses are back, because you went back to before the fix. Then rerun Step 7, the fix and the migration, to get the clean data back.

Two related details:

  • Testing without touching production. Every project can add a development environment from the switcher under the project name, with its own services, keys and .env. MCP tools take an environment argument for it, so the agent can explore and fix a development copy first.
  • Coming from another provider? Import database on the Data or Backups tab copies a Neon, Supabase or any other Postgres database into this one. It replaces all current data, but takes a backup first ("Before import"), so you can undo it from the same Backups tab.

Step 10: Ship it

On Vercel (or any host), add DATABASE_URL in the project settings, and run migrations with DIRECT_URL if your database has one. In the CloudHike dashboard, Environment → Copy as .env gives you the whole file. Then:

  • Keep the connection string on the server. No NEXT_PUBLIC_ prefix, and don't commit .env.local.
  • Default to read-only. For "why is this number wrong?" questions, query_database is all the agent needs. Save execute_sql for fixes you've reviewed.
  • Read every execute_sql before approving it, and keep schema changes in migrations.
  • Download a backup before big changes, or keep backups in your own bucket if you want longer than the plan's retention.
  • Keep the pool small. One pool per server process, 3 to 5 connections, especially on serverless hosts.

What CloudHike handled

Look back at what you didn't do: you didn't create a read-only database role by hand, write a wrapper that blocks writes, set up a backup cron, or build an approval step for agent SQL. One MCP connection and one Postgres card gave you:

  • a Postgres 16 database with a built-in explorer and SQL editor, read-only until you say otherwise,
  • list_tables, describe_table and query_database, so the agent reads real data in a read-only transaction on every plan,
  • execute_sql on Pro, one transaction, with your editor asking before it runs,
  • an audit log with postgres.sql-write and environment.agent-fetch entries,
  • nightly backups, Backup now, signed downloads, and a restore that only swaps once the dump has fully loaded,
  • and no way to delete projects or services through MCP at all.

On cost: a Free database on the shared server is billed $0.001 per hour (about $0.73 a month) and holds 500 MB; backups cost $0.08 per GB-month. On Pro, your database runs in its own container, has no size limit (disk above 1 GB is $0.40 per GB-month) and keeps backups up to 15 days; Scale keeps them up to 30. Everything comes out of one credit balance. If you outgrow Free, Pro is $10/month with $10 of usage credits included every month and 10 projects, and Scale is $29.99/month with unlimited projects. The details are on the plans and billing page.

Your turn

Run the prompts in order: Step 3 to deploy and seed, Step 5 to explore, Step 6 to back up, Step 7 to fix, then Steps 8 and 9 for the audit log and the restore drill. Then try to break it: ask the agent to sneak an UPDATE into query_database, approve an execute_sql only after reading it, find the entry on the Usage page, and restore your Step 6 backup to watch the messy statuses come back.

👉 Start free at cloudhike.dev. You get $10 in credits at signup, plus $5 more with code TUBEGURUJI5, no card required.

Next week: keep your bill boring. We'll have the agent estimate cost with the plans-and-billing prompt, cache with Redis expiries, set a spend cap and alerts, and look at moving from Free to Pro. Follow along so you don't miss it.

If you try this one, tell me in the comments what your agent found in the messy data, and whether you'd let it run execute_sql on production. I read every comment.

Top comments (0)