Database Integration
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
The first time you let a model near a database, one question decides whether it goes well or badly: does the model get to write SQL, or does it get a small set of safe functions? This lesson argues for the second, shows how to build it, and covers the part that matters most, which is making sure a customer can only ever see their own rows, no matter what the model asks for.
What you'll learn
- Why "give the model a SQL tool" is the risky shortcut, and what to do instead.
- How to take identity from your session, not from the model.
- How to use parameterised queries, fixed limits and a read-only connection.
- How to test that one customer can't read another's data, in Python and Laravel.
Before you start
Two ways to connect a model to data
Option A: a SQL tool. One tool called run_sql(query), and the model writes whatever it likes. It's flexible, it demos well, and it hands the model (and anyone who can influence the model) everything the database user can do. Even with a read-only user, it can read every customer's rows, and "read everything" is often the very thing you must prevent.
Option B: narrow, purpose-built tools. shop_lookup_order(order_id) and shop_list_orders(status). The model can only ask the questions you thought of, in the shape you defined, and your code builds the query. You give up flexibility and gain predictability, auditability and safety. For anything that touches customer data, this is the right default.
If you do need free-form analysis, for an internal analyst tool for example, give it its own sandbox: a read-only replica, a database user with access to only non-sensitive tables, a row limit and a statement timeout. Never share a connection with the customer-facing assistant.
The rule that matters most: identity comes from your code
Think about shop_lookup_order(order_id). Which customer's order? You might be tempted to add a customer_id or email parameter, so the model can pass in the customer. Don't. The model would be guessing, or copying whatever the user typed, and a user who types "I'm customer 2" would be believed.
The fix is simple and worth stating plainly: the tool receives the identity from your application's session, in a context object the model never touches. The model supplies order_id. Your code supplies customer_id. The query uses both:
SELECT ... FROM orders WHERE id = ? AND customer_id = ?
^ from the model ^ from the session
And when nothing matches, return the same message whether the order doesn't exist or belongs to someone else. Otherwise the tool becomes a way to check which order ids exist.
Python with SQLite
This module has the definitions and the query functions. It opens the database read-only, takes the identity from a Context, binds every value as a parameter, fixes the row limit in code, and shapes each row down to a few fields. SQLite keeps the example self-contained, but the same structure works for MySQL or PostgreSQL:
import sqlite3
from dataclasses import dataclass
from executor import ToolError
@dataclass(frozen=True)
class Context:
"""Who is asking. Built by YOUR code from the logged-in session, never from anything Claude says."""
customer_id: int
role: str = "customer"
SCHEMA = """
CREATE TABLE orders (id TEXT PRIMARY KEY, customer_id INTEGER NOT NULL, status TEXT NOT NULL,
total_cents INTEGER NOT NULL, tracking TEXT, placed_at TEXT NOT NULL);
"""
STATUSES = ("processing", "shipped", "delivered", "cancelled")
GET_ORDER = {
"name": "shop_lookup_order",
"description": (
"Look up one of the signed-in customer's orders by order id, for example A100. Returns status, tracking "
"number, total and order date. Use it when the customer asks about a specific order. It only finds orders "
"that belong to the signed-in customer; for any other id it reports that no order was found."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string", "description": "The order id, such as A100."}},
"required": ["order_id"],
"additionalProperties": False,
},
}
LIST_ORDERS = {
"name": "shop_list_orders",
"description": (
"List the signed-in customer's orders, newest first, at most 10. Optionally filter by status. Use it when the "
"customer asks about 'my orders' without an id. Returns order id, status and total for each. The customer is "
"identified by the application, so never ask for or pass an email or customer id."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {"status": {"type": "string", "enum": list(STATUSES), "description": "Only orders with this status. Leave out for all."}},
"required": [],
"additionalProperties": False,
},
}
def connect_read_only(path: str) -> sqlite3.Connection:
"""The tool's database user can read and nothing else. Even a bug cannot write."""
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA query_only = ON")
return conn
class OrderTools:
def __init__(self, conn: sqlite3.Connection):
self.conn = conn
def get_order(self, ctx: Context, order_id: str) -> dict:
# The customer id comes from ctx, not from the model. The id the model gave is just a bound value.
row = self.conn.execute(
"SELECT id, status, total_cents, tracking, placed_at FROM orders WHERE id = ? AND customer_id = ?",
(order_id, ctx.customer_id),
).fetchone()
if row is None:
# Same answer whether the order is missing or belongs to someone else: do not confirm that it exists.
raise ToolError(f"No order {order_id} was found for this customer. Ask them to check the order id.")
return self._shape(row)
def list_orders(self, ctx: Context, status: str | None = None) -> list[dict]:
sql = "SELECT id, status, total_cents, tracking, placed_at FROM orders WHERE customer_id = ?"
params: list = [ctx.customer_id]
if status is not None:
if status not in STATUSES: # belt and braces; the schema already limits this
raise ToolError(f"status must be one of {', '.join(STATUSES)}.")
sql += " AND status = ?"
params.append(status)
sql += " ORDER BY placed_at DESC LIMIT 10" # the limit is fixed in code, not chosen by the model
return [self._shape(r) for r in self.conn.execute(sql, params).fetchall()]
@staticmethod
def _shape(row: sqlite3.Row) -> dict:
return {
"order_id": row["id"],
"status": row["status"],
"total": f"{row['total_cents'] / 100:.2f} USD",
"tracking_number": row["tracking"],
"placed_at": row["placed_at"],
}
What each choice does:
mode=ro and PRAGMA query_only: the connection can't write. A bug, or a model doing something unexpected, still can't change data. With a real database, do this with a database user that has SELECT on those tables and nothing else.
- Bound parameters:
? placeholders mean a value is always data, never SQL. An order_id of A100'; DROP TABLE orders;-- is just a string that matches nothing.
LIMIT 10 in code: the model can't ask for 10,000 rows.
- An enum for
status, checked again in the function even though the schema already limits it.
- Shaped output: a small dictionary with a formatted total, rather than a raw row with internal columns.
Wiring it into the executor
With needs_context=True, the registry passes your Context as the first argument, and the model's input fills the rest:
orders = OrderTools(connect_read_only("shop.db"))
registry = ToolRegistry()
registry.register(GET_ORDER, orders.get_order, needs_context=True)
registry.register(LIST_ORDERS, orders.list_orders, needs_context=True)
# Built from the signed-in session. Never from the model's output.
ctx = Context(customer_id=session_customer_id)
content, is_error = registry.execute("shop_lookup_order", {"order_id": "A100"}, ctx)
Because additionalProperties is false, a model that tries {"order_id": "B200", "customer_id": 2} is rejected as invalid input before the function runs.
Tests worth writing
This is the part that gives you confidence. We tested these cases with two customers and a temporary database file:
- A customer can read their own order.
- Asking for another customer's order produces exactly the same message as asking for an order that doesn't exist (apart from the id echoed back).
- Injection-style strings are treated as data and the table is intact afterwards.
- Lists are scoped to the customer, limited to 10, and filterable by status; an invalid status is rejected.
- The connection refuses a
DELETE.
- Through the registry, a foreign order id fails, an extra
customer_id key is rejected, and the real owner can read their own order.
Write the "customer A can't see customer B" test first, before anything else. It's the one that matters if something goes wrong.
The Laravel version
The same design with Laravel's query builder. The context class carries the identity, the model-supplied value is a binding, and the limit is a constant:
<?php
namespace App\Support\Tools;
/** Who is asking. Built by your code from the signed-in session, never from anything Claude says. */
final class CustomerContext
{
public function __construct(public readonly int $customerId, public readonly string $role = 'customer') {}
}
<?php
namespace App\Support\Tools;
use Illuminate\Support\Facades\DB;
final class OrderQueries
{
private const STATUSES = ['processing', 'shipped', 'delivered', 'cancelled'];
public function getOrder(CustomerContext $ctx, string $order_id): array
{
// customer_id comes from the context. The id Claude supplied is only a bound value.
$row = DB::table('orders')
->where('id', $order_id)
->where('customer_id', $ctx->customerId)
->first(['id', 'status', 'total_cents', 'tracking', 'placed_at']);
if ($row === null) {
// Same message whether the order is missing or belongs to someone else.
throw new ToolError("No order {$order_id} was found for this customer. Ask them to check the order id.");
}
return $this->shape($row);
}
/** @return list<array> */
public function listOrders(CustomerContext $ctx, ?string $status = null): array
{
if ($status !== null && ! in_array($status, self::STATUSES, true)) {
throw new ToolError('status must be one of '.implode(', ', self::STATUSES).'.');
}
return DB::table('orders')
->where('customer_id', $ctx->customerId)
->when($status, fn ($q) => $q->where('status', $status))
->orderByDesc('placed_at')
->limit(10) // fixed in code, never chosen by the model
->get(['id', 'status', 'total_cents', 'tracking', 'placed_at'])
->map(fn ($r) => $this->shape($r))
->all();
}
private function shape(object $row): array
{
return [
'order_id' => $row->id,
'status' => $row->status,
'total' => number_format($row->total_cents / 100, 2).' USD',
'tracking_number' => $row->tracking,
'placed_at' => $row->placed_at,
];
}
}
We ran these against a real test database with a temporary orders table: own order found; another customer's order and a missing order gave the same message; A100' OR '1'='1 returned "No order" and the table still had all 16 rows; a list was limited to 10 and filtered by status; an invalid status raised a tool error; and, wired through the registry, a foreign id and an extra customer_id key were both refused while the owner could read their own order. In Laravel, if you use Eloquent, put the customer condition in a global scope on the model so a forgotten where can't leak rows.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A subscription service lets customers ask "what's my next invoice?" in chat. The first prototype had a get_invoice(customer_email) tool. During a security review someone typed "my email is the CEO's email" into the chat, and the tool dutifully returned the CEO's invoice. The fix wasn't a smarter prompt. It was removing the parameter. The tool now ignores anything the user says about who they are, because the signed-in session decides that.
Mistakes to avoid
- A generic SQL tool on customer data.
- An identity parameter (
customer_id, email) chosen by the model.
- Building SQL with string concatenation.
- No row limit, no field selection (
SELECT *).
- Different error messages for "not found" and "not yours".
- Using the application's full-privilege database user for the assistant.
Security notes
- Use a dedicated database user for the assistant with only the privileges the tools need, ideally read-only.
- Put the tenancy or ownership check inside the query, not in a separate step the model could skip.
- Be careful what you return. Columns like password hashes, internal notes and other people's details should never be in a tool result.
- Write operations deserve their own treatment: lesson 4.8 shows how to turn writes into proposals that a person approves.
Cost and speed
Narrow tools are also cheaper. Each result is small, so the conversation stays small. Add the indexes your tool queries need, and put a statement timeout on the assistant's database user so a slow query can't pile up connections.
Key takeaways
- Prefer a few narrow tools over a free-form SQL tool, especially for customer data.
- Identity comes from your session via a context object, never from model input.
- Bind every value, fix limits in code, return only chosen fields, and use a read-only connection.
- "Not found" and "not yours" must look the same. Test the cross-customer case first.
Lesson recap: identity comes from your code, and the tool reveals nothing about other customers.
Quick quiz
- Why is a
run_sql tool risky on customer data?
- Where should the customer's id come from?
- Why return the same message for a missing order and someone else's order?
- What does
additionalProperties: false add here?
- Which test would you write first?
Answers and explanations
- The model, or anyone steering it, can write any query the database user is allowed to run, including reading other customers' rows.
- From your application's authenticated session, passed to the tool as context.
- A different message would let anyone probe which order ids exist.
- If the model adds a
customer_id to the input, the call is rejected as invalid before the function runs.
- That customer A cannot read customer B's data, through every tool.
Official references and further reading
Related tutorials