Prompt
How do I give an AI agent access to my database?
Latest observation
There are a few common ways, depending on how much access the agent needs and how safe you want it to be.
1) Use a database tool / function
The safest pattern is to not give the model direct database credentials.
Instead, give the AI agent a tool that your backend controls:
- The agent asks a tool like
run_sql(query)orget_customer_orders(customer_id) - Your server validates the request
- Your server executes it against the database
- Your server returns only the needed results
This keeps credentials and access control on your side.
2) Create a restricted read-only database user
If the agent only needs to query data:
- Create a dedicated DB user
- Grant read-only permissions
- Restrict it to specific schemas/tables/views
- Prefer views over raw tables for sensitive data
Example idea:
- Allowed:
SELECTonanalytics.orders_view - Not allowed:
INSERT,UPDATE,DELETE,DROP
3) Put an API layer in front of the database
Instead of letting the AI generate SQL directly, expose endpoints like:
GET /customers/{id}GET /orders?customer_id=...
Then let the AI call those endpoints. This is often easier to secure and monitor than raw SQL access.
4) Use a retrieval layer for “knowledge” access
If the agent mainly needs to answer questions from database content:
- Periodically sync database data into a vector store or search index
- Let the agent retrieve relevant records via embeddings/search
- Keep the live database separate from the model
This is better for Q&A than for transactional actions.
5) If you do allow SQL, sandbox it heavily
If the agent must write SQL:
- Use a read-only user unless writes are absolutely necessary
- Validate SQL AST or use an allowlist of query patterns
- Block dangerous statements:
DROP,ALTER,UPDATE,DELETE,INSERT,COPY, etc. - Set query timeouts and row limits
- Log every query
- Run in a separate environment or replica if possible
Recommended architecture
For most cases:
AI agent → your backend tool/API → database
Not: AI agent → direct DB connection
That gives you:
- credential protection
- auditing
- row/table-level access control
- query validation
- easier revocation
Practical checklist
- Decide if the agent needs read-only or read/write access
- Create a dedicated service account
- Restrict permissions to the minimum needed
- Add a middle layer (tool/API) if possible
- Log and monitor all access
- Use environment secrets management
- Add rate limits and query limits
- Test with fake/sandbox data first
If you want, I can show you:
- a secure architecture diagram,
- example code for a tool that queries Postgres/MySQL, or
- how to do this with a specific agent framework like OpenAI tools, LangChain, or CrewAI.