Claude Function Calling: Querying External Databases
What "function calling with a database" actually means
Claude's function calling (Anthropic calls it tool use) lets the model decide when it needs external data, then it emits a structured request instead of a free-text guess. Your code intercepts that request, runs the actual database query, and feeds the result back to Claude so it can write a grounded answer. The model never touches your database directly — it only produces arguments for a function you define, and you stay in full control of execution, validation, and security.
This pattern solves the most common problem with LLMs and data: hallucinated numbers. Instead of asking Claude to guess "how many orders did customer X place last month," you give it a query_orders tool. Claude fills in the parameters (customer ID, date range), your backend runs the real SQL or NoSQL query, and Claude summarizes the actual rows returned.
The core loop
Every Claude + database integration follows the same four-step cycle:
- Send the user's message plus a
toolsarray describing your database functions. - Claude replies with a
tool_useblock containing the function name and arguments (not an SQL string — structured parameters you define). - Your server executes the real query against Postgres, MySQL, MongoDB, or whatever you run, with proper parameterization.
- You send the result back as a
tool_result, and Claude produces the final natural-language answer.
Defining the tool schema
Keep the schema narrow. Don't let Claude write raw SQL unless you've sandboxed it heavily — instead, expose specific, safe operations:
{
"name": "get_customer_orders",
"description": "Fetch orders for a customer within a date range",
"input_schema": {
"type": "object",
"properties": {
"customer_id": { "type": "string" },
"start_date": { "type": "string", "format": "date" },
"end_date": { "type": "string", "format": "date" }
},
"required": ["customer_id"]
}
}
This forces Claude to produce structured, validated input. Your handler maps get_customer_orders to a parameterized query — never string concatenation.
Executing the query safely
async function getCustomerOrders({ customer_id, start_date, end_date }) {
const query = `
SELECT id, total, status, created_at
FROM orders
WHERE customer_id = $1
AND created_at BETWEEN $2 AND $3
ORDER BY created_at DESC
LIMIT 50
`;
const { rows } = await pool.query(query, [
customer_id,
start_date ?? "1970-01-01",
end_date ?? new Date().toISOString(),
]);
return rows;
}
Always parameterize, always cap row counts, and never let the model's arguments reach raw SQL execution. Validate customer_id against the authenticated session before running anything.
Handling the tool_use response
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
tools: [orderTool],
messages: [{ role: "user", content: "How much did customer C-204 spend in March?" }],
}),
});
const data = await response.json();
const toolUse = data.content.find(b => b.type === "tool_use");
if (toolUse) {
const result = await getCustomerOrders(toolUse.input);
// send tool_result back in a follow-up request with role "tool"
}
The second round-trip includes a tool_result block referencing toolUse.id, and Claude's next reply is the final summary grounded in real numbers.
Why route this through an API layer
If you're already running Claude access through a Claude subscription rather than a raw Anthropic API key, you need an HTTPS endpoint that behaves like a standard API — proper auth, streaming, and tool support — to build this loop reliably. That's exactly what SubToAPI does: it turns your existing Claude access into application keys (sub_live_...) you can call from a backend, with full tool use support and streaming for long-running query chains. See the quickstart or the messages reference for the exact request shape.
Design decisions that matter
One tool per operation, not one tool for "run any query." Giving Claude a generic execute_sql function is tempting but dangerous — it invites injection-style exploits even without classic SQL injection syntax, because the model is now your query author. Scope each tool to a specific, auditable operation.
Return structured results, not raw dumps. Summarize large result sets before sending them back as a tool result — Claude performs better reasoning over 20 clean rows than over a 500-row JSON blob, and you save tokens.
Set hard limits server-side. LIMIT 50, timeouts, and row caps should live in your query code, not in instructions you hope Claude follows.
Log every tool call. Since Claude decides when to query the database, you want an audit trail of which tool, which arguments, and which user triggered it — useful for debugging and for compliance.
Handle empty results gracefully. If the query returns zero rows, send that back explicitly as the tool_result rather than an error — Claude will correctly tell the user "no orders found" instead of guessing.
Multi-step queries
Complex questions sometimes need more than one database call — for example, "compare this customer's spend to the account average." Claude can request two tools in sequence across the loop: first get_customer_orders, then get_account_average, chaining tool_use/tool_result pairs until it has enough data to answer. Your execution loop just needs to keep running until Claude's response contains no more tool_use blocks.
questions
Can Claude write and run SQL directly against my database? No, and you shouldn't let it. Claude only produces structured arguments for a tool you define; your backend code executes the actual query with parameterized statements, keeping full control over what's allowed.
What's the difference between function calling and RAG for database access? RAG retrieves and injects context before the model responds; function calling lets Claude decide mid-conversation that it needs specific, parameterized data and request it on demand, which is better for precise, structured lookups like order totals or inventory counts.
Do I need an Anthropic API key to build this, or can I use my Claude subscription? You can build the full tool-use loop using SubToAPI, which exposes your existing Claude subscription as a standard HTTPS API with application keys — no separate Anthropic API account required. Check pricing for plan details.