DEV Community

Cover image for Building Agentic Apps on Nhost
Max S.
Max S.

Posted on AI-assisted

Building Agentic Apps on Nhost

A common way to add an AI agent to an app is to give the agent its own backend. The app keeps its database and auth. The agent gets a vector database, a worker with a service key, sometimes a queue, and a pile of code that copies data between them.

With one test user you won't notice anything. With real users, that worker can read every row in the database, because nobody ever put rules on the service key.

On Nhost I skipped the second backend. Postgres, Auth, the GraphQL API with its permissions, Storage, Functions and containers all sit in one project, and the agent uses them under the same rules as the rest of the app. Here's how I set it up. Screenshots are from a test project in the Nhost Dashboard.

What the agent needs

An agent reads and writes data, keeps some memory between conversations (usually with embeddings), calls tools, and sometimes runs work that takes minutes. It also acts for a specific person. People forget that last one. Then a user asks the agent about their notes and gets back someone else's.

Permissions on the data

Nhost permissions are set per role and per table, for select, insert, update and delete. Only admin has access by default. Every other role gets access explicitly. A signed-in user has the user role by default, and their ID comes from the access token as X-Hasura-User-Id.

Here's the select rule for the user role on an agent_memories table in my test project. The table stores what the agent remembers about each user: id, user_id, content, created_at, an embeddings column and an outdated flag.

Select permission for the user role on agent_memories: user_id _eq X-Hasura-User-Id, with the embeddings and outdated columns unchecked

The row check limits a user to rows where user_id is their own ID. Below it, the column list lets the user role read id, user_id, content and created_at. embeddings and outdated stay unchecked.

Any GraphQL request sent with a user's access token goes through this rule. Your frontend, a function, a model that wrote the query a second ago: the database doesn't care where it came from. You get that user's rows and the allowed columns.

Tools as Functions

Each .js or .ts file in the ./functions folder of a project becomes an HTTP endpoint at https://<subdomain>.functions.<region>.nhost.run/v1/<path>, with an Express-style req and res. One file per tool works fine.

Forward the caller's Authorization header and the function's GraphQL request runs with the caller's permissions:

// functions/tools/recent-memories.ts
import type { Request, Response } from 'express'
import { createClient } from '@nhost/nhost-js'

const nhost = createClient({
  subdomain: process.env.NHOST_SUBDOMAIN,
  region: process.env.NHOST_REGION,
})

export default async (req: Request, res: Response) => {
  const resp = await nhost.graphql.request(
    {
      query: `query RecentMemories {
        agent_memories(order_by: { created_at: desc }, limit: 20) {
          content
          created_at
        }
      }`,
    },
    { headers: { Authorization: req.headers.authorization ?? '' } },
  )

  res.json(resp.body.data)
}
Enter fullscreen mode Exit fullscreen mode

No where: { user_id: ... } in there. The filter is part of the permission rule, so even if the model asks for every memory in the table, it only gets the caller's rows.

The SDK can also send requests as admin (withAdminSession with the admin secret), and the docs say plainly that admin requests bypass all permissions. I keep that out of any code path a model can trigger. Full stop.

Memory in the same Postgres

Each Nhost project has its own Postgres database, and pgvector is among the supported extensions. Install it from Database → Extensions in the Dashboard or with a migration:

CREATE EXTENSION IF NOT EXISTS vector;
Enter fullscreen mode Exit fullscreen mode

The Database extensions page in the Nhost Dashboard, with pgvector installed

With pgvector in the same database, the embeddings live in the same rows as the text they come from. In agent_memories the embeddings column sits right next to user_id, so the row check covers the vectors along with the text. Nothing to sync.

Search over those vectors needs the same rules, otherwise it's the easiest way I know to hand someone else's data to the wrong user. If you don't want to write that part, Graphite, in the AI section of the Dashboard, can generate embeddings and run semantic search with your permissions applied.

Longer work in Nhost Run

Functions suit short tools. A loop that works on a task for several minutes, a queue worker or a headless browser should run as its own service. Nhost Run deploys a container from a public image, a private registry or the Nhost registry into the same project as the database.

Creating a new Nhost Run service in the Dashboard: name, image, vCPU and memory, replicas

A Run service is on the same network as the rest of the project and reaches it through internal hostnames:

  • Postgres: postgres-service:5432
  • GraphQL: http://hasura-service:8080
  • Auth: http://hasura-auth-service:4000
  • Storage: http://hasura-storage-service:5000

Latency stays low, and traffic between the service and your data has no egress cost. For anything it does on behalf of a user, my agent service still calls GraphQL at http://hasura-service:8080 with that user's token.

Users' own assistants over MCP

Some users will want to reach your app from Claude, Cursor or another MCP client. That's what the Backend MCP Server is for. It ships as the nhost/mcp image and usually gets deployed on Nhost Run.

Users sign in with Nhost Auth, which works as the OAuth2 authorization server. The MCP server checks the user's token and passes it on, so every GraphQL or storage operation runs with that user's existing permissions. Its tools are get-schema, graphql-query, graphql-mutation and an optional read-only storage-download. Setting MCP_ENFORCE_ROLE makes assistants use a dedicated role with narrower access.

Don't mix it up with the CLI MCP server (nhost mcp start). That one is for developers who let Claude Code or Cursor work on the project itself.

Confirmation for sensitive actions

Even when an agent acts in a user's name, I want the user to confirm a password change, a delete or a new personal access token. An agent shouldn't do those on its own.

Nhost Auth handles this with elevated permissions. The user confirms with a security key, an authenticator app, an email code or an SMS code, and their access token then carries an x-hasura-auth-elevated claim with their user ID. Permission rules can check for it. On a notes table, for example, reading can work with user_id eq X-Hasura-User-Id, while insert, update and delete need user_id eq x-hasura-auth-elevated.

With an agent, reads go through as usual and a destructive call fails until the user enters a code. When the access token gets renewed, the claim is gone, and the next destructive call needs a fresh code.

Work that starts from data changes

Some agent work begins with a change in a table: a new support ticket, say, or an edited order. Event triggers send a webhook on insert, update or delete to any HTTP endpoint, including one of your functions, with retries you configure per trigger.

The payload includes session_variables for the user who made the change, with their role and user ID, so the handler knows who it's working for. If the handler switches to admin to get the job done, it has to scope the work to that user ID itself. The database won't do it for you once you're admin.

Before an agent touches real user data, I check four things:

  1. Every table the agent can reach has a row check and a column list for the role it uses.
  2. Every tool forwards the user's Authorization header. No admin secret in anything the model can call.
  3. Embeddings live in the same rows as the data they describe, under the same rules.
  4. Deletes check x-hasura-auth-elevated, and Auth asks for elevation before password changes and new access tokens.

With those four in place, the model can write whatever query it likes, and the answer still only contains what its user was allowed to see.

Top comments (0)