To limit what a LangChain SQL agent can see, give it a database connection whose account can read only approved tables or views, and expose only those objects to the agent’s schema tools. To enforce access for individual users, apply authorization in the database or a trusted server-side layer for every query; prompts and table allow-lists alone are not security boundaries.
How SQL agents discover and query data
A LangChain SQL agent typically combines a language model with tools that inspect database metadata, generate SQL, validate or execute it, and return results. In LangChain’s SQL agent examples, the SQL database utilities can list tables, inspect table schemas, and execute queries; the agent uses these tools in a loop to answer a question. Exact imports and APIs vary across LangChain versions and integrations, so check the documentation for the installed package.
Schema visibility and data authorization are related but different controls. Schema visibility determines which table names and column definitions the model can inspect. Authorization determines which database operations and rows it can actually access. Hiding a table from a listing tool may reduce accidental use, but it does not prevent a model from guessing its name or issuing SQL directly if the execution connection has permission.
Restrict visible tables and schema tools
Start by narrowing the database objects that the agent can discover. In the SQL database integration, a table allow-list can be configured when initializing the database object; in commonly used versions, this is exposed as include_tables. For example:
db = SQLDatabase.from_uri(
database_uri,
include_tables=["public_orders", "public_products"]
)
Use the API appropriate to your LangChain version, and verify that the table-list and schema-inspection tools honor the restriction. If building custom tools, make their accepted table names explicit and reject any request outside the allow-list. Do not assume that restricting table discovery automatically restricts the SQL execution tool.
- Expose only the tables needed for the task, not every table in the database.
- Prefer purpose-built views that omit confidential columns or combine data at an approved level.
- Keep schema descriptions brief and avoid putting credentials, personal data, or sensitive business notes in comments that tools may retrieve.
- Test both discovery and direct execution paths, including attempts to query an excluded table by name.
A view is often more reliable than relying on the model to ignore columns. If the agent needs product names and stock totals but not supplier contact details, a view containing only the approved fields makes the boundary easier to review.
Enforce permissions in the database
Connect with a dedicated database role that has the minimum privileges required. For a read-only question-answering agent, that normally means granting only read access to approved views or tables, and withholding permissions to alter data, create objects, or access unrelated schemas. The exact commands depend on the database engine; have a database administrator review the grants and test them using the same credentials the application will use.
This is the crucial enforcement layer. If the model generates DELETE, UPDATE, or a query against a restricted table, the database should reject it because the connection lacks permission. A read-only transaction or query checker can be useful defense in depth, but neither should replace least-privilege database grants.
Also consider the scope of the connection. If every user’s request runs with one powerful shared credential, the database sees the application’s identity, not necessarily the end user’s. Per-user authorization must therefore be represented in trusted server-side logic, or passed through a database identity mechanism that the database itself can validate.
Apply user-specific access safely
For multi-user applications, derive the user identity from the authenticated session on the server. Do not ask the model who the user is or trust an identity, tenant ID, or role supplied in the natural-language prompt. Then enforce the user’s allowed data in a database policy, a tenant-specific view, or a server-side query layer.
For example, an application might allow each account to read only orders belonging to its tenant. The server can select a database role or set a validated session context for that request, while a row-level security policy or equivalent database rule filters rows. Support differs by database, and session context must be set safely for every request and cleared or reset when connections are reused from a pool. Otherwise, one user’s context could accidentally affect another request.
- Authenticate the user before calling the agent, then resolve permitted tenants and roles on the server.
- Use parameterized values for filters; do not concatenate user-provided text into SQL.
- Enforce row and column restrictions in database policies or vetted views where practical.
- Keep authorization decisions outside model-generated instructions and validate them on every request.
For stronger separation, separate database roles or connections by tenant or access tier. This can add operational work, but it reduces reliance on a single shared connection and makes permission boundaries easier to audit.
Reduce query risk and protect sensitive output
A read-only role limits damage but does not prevent expensive or overly broad reads. Add operational safeguards appropriate to the database: query timeouts, connection limits, result-size limits, and monitoring for unusual access. A custom query tool can reject multiple statements, disallow operations outside an approved read-only SQL subset, and require limits for large result sets. SQL parsing is complex, so a home-grown string check such as searching for the word “DELETE” is not a dependable security control.
Consider whether the agent needs raw records at all. Aggregated views can reduce exposure of personal or confidential data. Review what the model receives in query results, what gets written to application logs, and whether traces or error messages may retain sensitive values. Return only the fields needed to answer the question, and apply output handling appropriate to the data.
Common mistakes and a practical checklist
The most common misconception is that an allow-list of tables makes access secure. It limits what the agent is encouraged or able to discover through a particular metadata tool; the database connection’s permissions decide what it can actually read. A second mistake is placing access rules in the system prompt. Instructions can guide behavior, but they cannot reliably enforce authorization against generated SQL.
Before deploying, test the boundaries with the real application credential and representative user accounts:
- Confirm only approved objects appear in table-list and schema-inspection results.
- Attempt direct queries against excluded tables and sensitive columns; confirm the database denies them.
- Test cross-tenant requests and verify that row policies or server-side restrictions block them.
- Try write statements and multi-statement input; confirm execution is denied or rejected.
- Check connection-pool behavior, logs, result limits, timeouts, and error responses.
Re-run these tests when schemas, database grants, LangChain packages, tools, or authentication flows change. Security depends on the whole path from user identity to database execution, not on one agent setting.
Frequently Asked Questions
Does include_tables prevent access to other tables?
It is useful for limiting table discovery in the SQL database integration, but it is not a substitute for database permissions. A connection may still query an omitted table unless the database denies access or another trusted execution control blocks it.
Can a prompt make the agent respect user permissions?
A prompt can explain which data the agent should use, but it cannot enforce access. Enforce permissions in database grants, row-level policies, approved views, or trusted server-side code.
How do I keep one user from seeing another user’s rows?
Use authenticated server-side identity and enforce tenant or user filters in a database policy or trusted query layer. Never rely on a user-supplied prompt value as proof of identity.
Should a SQL agent use a read-only database account?
Yes, when its task only requires answers from data. Grant read access only to the required objects; read-only access still needs safeguards against unauthorized reads and costly queries.
Can I hide sensitive columns but keep the table available?
Expose a view containing only approved columns, then grant the agent’s database role access to that view rather than the underlying table where possible.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Ubuntu Voice Dictation: Offline Use, Languages and Setup
- How to Clean Window Sills and Tracks
- Fix iPhone Camera Freezing While Recording in iOS 14
- Stop, Pause, or Delete a ChatGPT Task That Keeps Running
- Install Prime Video as an App on Windows 10
- How to Use Google Maps’ New AI Features