Secure AI Apps Start With Functions, Not SQL
13 May 2026Give your AI features a small set of typed functions instead of a database connection. You decide what data leaves each function, and the same functions can power a CLI, a Slack bot, an MCP server and an agent.

tl;dr: Build a typed function layer first. Lock down the database, shape responses with DTOs, redact sensitive fields, and expose only those functions to CLIs, Slack bots, MCP servers and agents. You can swap the AI layer later. The function layer is the part you keep.
Start with functions
When you add AI to a product, you’ll feel the pull to hand the model a database connection and let it write SQL. Most product use cases don’t need text-to-SQL. They need a few predefined functions that do useful things.
Hand the model a connection string and it can write any query its role allows. Hand it functions and it picks from queries you wrote, with results you shaped. Database permissions decide how much damage a bad query can do. Functions decide whether the model can write one at all.
For payments, that might look like:
getLatestPaymentsForClient(clientId)
getFailedPaymentsForClient(clientId)
getClientPaymentSummary(clientId)
Each function does one thing, takes a fixed set of arguments and returns predictable JSON. Give each one typed inputs, typed outputs and a JSDoc comment that says what it’s for. If you’ve read one rule for AI code: fn(args, deps), this is the same shape.
A function with one job and a structured result can sit under anything: a CLI, a Slack bot, an MCP server, an HTTP API or an agent. You know what goes in and what comes out, whoever calls it.
flowchart TD
DB[("Approved data source")]
Core["Core functions<br/>typed inputs, safe outputs"]
CLI["CLI"]
Slack["Slack bot"]
MCP["MCP server"]
API["HTTP API"]
Agents["AI agents"]
DB --> Core
Core --> CLI
Core --> Slack
Core --> MCP
Core --> API
Core --> Agents
One safe layer sits in the middle, and people and machines reach it through whichever surface suits them.
Build the CLI or Slack bot first
Before you add AI, wire up a CLI or a Slack bot. It sounds backwards. It makes you design the interaction model before a model hides the gaps. Start with a menu of domains:
Clients
Payments
Invoices
Orders
Inside each domain the user picks an action: latest payments for a client, failed payments, account summary, recent invoices. They call the same functions an agent would call, through a menu instead of a sentence.
Your first job is making it safe. You can make it clever later.
Least privilege starts at the database
Start with a read-only connection. Better, create a database user that can only read the tables or collections your tooling needs.
If your database holds API keys, secrets, admin data, audit logs or sensitive customer records, your AI tooling shouldn’t reach those tables. That’s your first boundary.
The function is your second. A database user that can read a table doesn’t mean the function should return the whole row. DTOs handle this.
A payment record might have twenty internal fields. The function returns six:
{
"paymentId": "pay_123",
"clientName": "Acme Ltd",
"amount": 1200,
"currency": "GBP",
"status": "paid",
"createdAt": "2026-05-01"
}
Leave out raw metadata, internal IDs and private fields. Include PII only when the use case needs it.
An engineer sees that JSON. A business user sees this in Slack:
Acme Ltd Last payment: £1,200 on 1 May 2026 Status: Paid Outstanding invoices: 2 (£3,400) Open support tickets: 1
The Slack bot renders the same function call for a human. A salesperson pulls it up before a call, a support agent quotes it on a ticket, and an AI agent reads it as context. None of them touch the database.
Database permissions restrict tables and sometimes columns. They can’t shape a response for each use case. DTOs can, and they give you one place to redact. If a value must never reach Slack, the CLI, the MCP server or the model, strip it inside the function. Don’t leave that decision to the AI layer.
Row-level security is the backstop
You might ask whether Postgres row-level security makes the function layer unnecessary. You create a role for the agent, grant it SELECT on a few tables, enable RLS, write a policy and hand over the connection string. Postgres filters every query the agent writes, SELECT * FROM customers included.
RLS works, and you should use it. It filters rows. The rest of the problem stays with you:
- A policy limits which rows a query sees, not what the query costs. An agent that writes a cross join over two large tables will tie up the database.
- Superusers and roles with
BYPASSRLSskip policies. Table owners skip them too unless you runALTER TABLE ... FORCE ROW LEVEL SECURITY. Views run with their owner’s permissions unless you create them withsecurity_invoker = trueon Postgres 15 or later. One wrong role or one old view and your policy stops applying. - RLS hides rows, not columns. You need column-level grants for that, and neither shapes a response for Slack or for a model’s context.
- RLS caps what a hijacked agent can read, but the agent can read anything inside the policy. If a support ticket tells the agent to list every customer email it can see, the agent can write that query. A function that returns six fields can’t.
The setup I’d use keeps the connection inside the function layer. The function sets the scope and Postgres enforces it:
CREATE POLICY client_payments ON payments
FOR SELECT TO tooling_reader
USING (client_id = current_setting('app.client_id')::uuid);
export async function getLatestPaymentsForClient(clientId: string) {
return db.transaction(async (tx) => {
await tx.query("select set_config('app.client_id', $1, true)", [clientId]);
const rows = await tx.query(
'select * from payments order by created_at desc limit 10',
);
return rows.map(toPaymentDto);
});
}
That query has no WHERE clause, and Postgres returns only that client’s payments. If a teammate later breaks a filter in a function, the policy catches it.
This pattern needs the function layer. Give the agent the connection string and it can call set_config itself and pick any client it likes.
MongoDB Atlas has no row-level security. Roles stop at the collection. The closest you get is a view with a $match stage and a custom role that can only run find on that view. Views are read-only, so the first time an agent needs to write, you are building the function layer anyway.
What you’ve built so far
Before any AI, you now have:
- a read-only database user with restricted table access
- row-level policies that catch a function that forgets its filter
- a set of approved functions
- DTOs that expose safe fields only
- redaction at the function boundary
- JSON schemas and types for every input and output
Structured output gives the CLI a bonus. You can pipe it through jq:
payments list --client acme --json | jq '.[] | select(.status == "failed")'
An agent chains tools the same way. If jq can compose your commands, a model can compose your tools.
Add AI one use case at a time
Decide which use cases AI should support before you decide how. You might want a payments agent, a client insights agent, a support agent and a sales agent. Give each one the tools for its job and nothing else. The payments agent gets payment tools. The support agent gets support tools. No agent writes its own queries.
A routing agent at the front can send each request to the right specialist, and each specialist can carry its own instructions and few-shot examples. Factor 1 of the 12-factor agents series covers this step from natural language to tool calls.
TypeScript with Zod, Python with Pydantic, or plain JSON Schema keeps the chain typed end to end. You know what each tool takes, what it returns, and how to validate and document it. Once a function becomes an AI tool, its name, description, schema and return shape all become part of the prompt the model reads. Spend your effort on that layer.
Keep AI off production
Point your AI features and internal tools at something other than the production database.
A read replica is a good first step, because a bad query can’t take down the live application. Change data capture is better. You use CDC or MongoDB change streams to copy events from production into a separate database built for internal tooling, reporting and AI.
The AI app reads that database and can’t write to it. It holds only the fields your tools may use, and it can store redacted or transformed records. If something goes wrong, you revoke one connection string and production stays untouched.
flowchart LR
Prod[("Production database")]
Stream["Change events"]
Tool[("Tooling database<br/>read-only, redacted")]
Core["Core functions"]
Users["CLI / Slack / MCP / Agents"]
Prod -->|CDC or events| Stream
Stream --> Tool
Tool --> Core
Core --> Users
Data flows left to right. Nothing on the right can write back to production.
If you already run an event-driven architecture, the tooling database becomes one more subscriber. Thin events carry a minimal payload and force another lookup. Fat events carry the full approved payload, so the event itself holds what your tools may see. For AI and internal tooling, I’d pick fat events.
Without CDC or events, your application can dual-write to the tooling database. It has gaps, and it still beats giving AI broad access to production.
Log every tool call
You need to see which tools get called, by whom, with what arguments, and what they return. Log which agent called which function, where errors happen, and which calls don’t match the patterns you designed for. Blocking access protects you from what you predicted. Logs show you what you didn’t.
One core package
With this foundation, one function layer serves several teams. Support answers questions faster. Account managers pull client activity without filing tickets. Sales get context before a call. Operations investigate issues without pulling in an engineer.
In the repo, a core package holds the functions, DTOs, schemas, types, redaction, descriptions, OpenAPI specs and MCP tool definitions. Every other package imports it:
/packages
/core
/cli
/slackbot
/mcp-server
/api
/agents
Every surface shares the same logic, DTOs and safety rules. When you add the next interface, AI or otherwise, you write a thin package on top of core and change nothing underneath.