Back to home

Integrations · LangChain

Secure database access for your LangChain AI agents

Never hand a LangChain AI agent raw SQL. Let it read through a scoped, read-only retrieval layer, and send every INSERT, UPDATE or DELETE it proposes through an allow/deny check before your code runs the statement.

With Claix this takes two HTTP calls from your tools: Retrieve for reads and Guard for writes. Works with LangGraph, MCP and A2A.

At a glance

What you need in LangChain

What you needWhat to use in LangChainClaix endpoint
Answers from live dataCustom tool (or MCP) that POSTs to RetrievePOST /retrieve/{agent_name}
Safe writesNamed action tool: build SQL → Guard → execute on allowPOST /check-sql
Know what happenedClaix traces + alert webhooksGuard Traces
Emergency stopOps script or admin toolPOST /agents/pause/{agent_id}

The problem

Why a database credential is not enough

A LangChain agent with tools decides which tool to call and with which arguments. If one of those tools is a SQL toolkit, SQLDatabaseChain-style helper, or a raw engine with write permissions, the model can send any statement that credential allows.

A system prompt that says never delete anything is a request to the model, not a restriction on the database. The control has to sit outside the model and give the same answer every time.

Compared

Four ways to connect a LangChain agent to a database

ApproachCan change data?Scoped tables/columns?Typed answers?Write rules?Audit
SQL toolkit (read/write)Anything the role allowsManual GRANTs onlyNoPrompt onlyYour app logs
SQL toolkit (read-only)NoManual GRANTsNoN/AYour app logs
Generic DB MCP serverDependsDependsDependsDependsDepends
Claix Retrieve + GuardOnly after allowPer route and agentYesPlain-English rulesFull traces

How it works

What Claix does for your LangChain agent

  • Retrieve (reads)

    Connect any SQL database with a read-only role. Define routes and agents. Your LangChain tool asks in plain language; Claix answers inside the perimeter you set—typed values your graph can branch on.

  • Guard (writes)

    Write rules in plain English. When the agent proposes a change, your tool calls Guard first. Claix decides; your code executes. No model decides at check time.

  • Traces

    Every query and every verdict stays on record, with optional webhooks when something is blocked.

Setup

Connect your database to LangChain with Claix

Expose named actions, not free-form SQL. The model only fills parameters; your code owns auth, templates and execution.

  1. 01

    Give Claix a read-only role

    Create a dedicated role with SELECT on the tables the agent needs. Connect it so Claix can draft the Data Map.

  2. 02

    Create a route and an agent

    Pick tables and columns, write a short guide, attach the route and choose reasoned mode for typed answers.

  3. 03

    Store the API key outside the prompt

    Environment variable or secrets manager as x-api-key (or Bearer). Never put it in a system prompt or tool description.

  4. 04

    Add a Retrieve tool

    A LangChain @tool that POSTs to /retrieve/{agent_name}. The model only fills the question.

  5. 05

    Write Guard rules

    For example: agents can change reservation status but never delete; no statement may change more than 5 rows.

  6. 06

    Build a guarded write tool

    Named actions only: build a parameterised statement, POST /check-sql, execute only when allowed is true.

  7. 07

    Alerts and kill switch

    Hook Guard denied webhooks into your notifier. Pause with POST /agents/pause/{agent_id}. Cap successful queries per period.

Retrieve

A Retrieve tool the model can call

The model only fills the question; your code owns the URL, auth and response parsing. Prefer MCP? The same agent is reachable as claix.retrieve.ask.

import os
import httpx
from langchain_core.tools import tool

CLAIX_KEY = os.environ["CLAIX_API_KEY"]
RETRIEVE_URL = "https://claix.dev/retrieve/restaurant-ops"

@tool
def ask_database(question: str, format: str = "string") -> str:
    """Ask a question about live operational data."""
    response = httpx.post(
        RETRIEVE_URL,
        headers={"x-api-key": CLAIX_KEY, "Content-Type": "application/json"},
        json={"questions": [{"question": question, "format": format}]},
        timeout=30.0,
    )
    response.raise_for_status()
    answers = response.json().get("ia_response") or []
    return str(answers[0] if answers else "")

Guard

A guarded write tool

Build the statement from a template, check it, then execute only on allow. Use $1/$2 for Postgres and ? for MySQL/MariaDB. Return the denial reason to the agent.

import os
import httpx
from langchain_core.tools import tool

CLAIX_KEY = os.environ["CLAIX_API_KEY"]
CHECK_URL = "https://claix.dev/check-sql"

def run_write(sql: str, params: list) -> dict:
    check = httpx.post(
        CHECK_URL,
        headers={"x-api-key": CLAIX_KEY, "Content-Type": "application/json"},
        json={"sql": sql, "params": params},
        timeout=15.0,
    )
    check.raise_for_status()
    verdict = check.json()
    if verdict.get("allowed") is not True:
        return {"ok": False, "reason": verdict.get("reason")}
    # Only here: execute with your write credential
    return {"ok": True, "decision_id": verdict.get("decision_id")}

@tool
def cancel_reservation(reservation_id: int) -> str:
    """Cancel one reservation by id. Never deletes rows."""
    result = run_write(
        "UPDATE reservations SET status = $1 WHERE id = $2",
        ["cancelled", reservation_id],
    )
    if not result["ok"]:
        return f"Denied: {result.get('reason')}"
    return f"Cancelled reservation {reservation_id}"

Example

A restaurant operations assistant

What the user asksWhat happensResult
How many tables are booked tonight?Retrieve tool with format intA number your graph can use
Is anyone on shift after midnight?Retrieve with format booleantrue/false for the next step
Cancel reservation 4812cancel_reservation tool → GuardAllowed, then your write runs
Delete all reservations from last monthAgent has no free-form DELETE toolCannot run; or Guard denies

Security

Checklist for LangChain agents with database access

  • Read-only for Claix

    Use a read-only role for the Claix connection.

  • No free-form SQL tools

    Expose named actions with templates. Keep the write credential out of the agent’s tool list until after Guard.

  • Fail closed

    Only execute on HTTP 200 with allowed: true.

  • Secrets and limits

    API key in env/secrets; one statement per check; call limits and regular trace review.

Pricing

Pricing and a cost example

Every account gets 30 successful calls per month free, with no card. You only pay for successful calls (HTTP 200).

Retrieve · Claix Managed AI€0.10 / question
Retrieve · your LLM key (BYOK)€0.02 / question
Guard€0.01 / check
EnterpriseSelf-hosted · custom

Example: 1,000 questions and 1,000 write checks ≈ €100 + €10 with managed AI, or €20 + €10 with your own key (before the free 30 and provider tokens).

Frequently asked questions

How do I give a LangChain AI agent access to my database safely?
Connect the database to a controlled layer with a read-only role, expose only specific tables and columns through a Retrieve tool, and run every write through an allow/deny check before your code executes. Claix does this with two HTTP calls from your tools.
Can a LangChain agent delete my database?
It can if you attach a SQL toolkit with delete permissions and rely on the prompt. To prevent it, use a read-only role for reads, expose only named write actions, and require an allow verdict from Guard before any write.
Is the LangChain SQL toolkit enough?
A read-only role is a good baseline. It does not scope columns per agent without hand-written grants, returns untyped rows or free text, and gives you no rules for the writes you will eventually want to allow.
Does Claix replace LangChain?
No. Claix is a controlled retrieval and write-check layer you call from LangChain, LangGraph, MCP or A2A. Your agent framework stays the same.
Does Claix execute the INSERT, UPDATE or DELETE?
No. Retrieve uses a read-only role, and Guard only answers whether a proposed change is allowed. Your LangChain code executes it.
Which databases does it support?
Any SQL database, including Postgres, MySQL and MariaDB, and Postgres-compatible setups such as Supabase.
Can I use my own LLM key?
Yes. With your own key from OpenAI, Google, Anthropic or xAI, the Claix fee drops from €0.10 to €0.02 per question and you pay your provider directly.
Can I self-host it?
Self-hosting is available on the Enterprise plan.

Wire Claix into your LangChain agent

Scoped reads, checked writes, traces and a pause switch. Thirty successful calls per month free—enough to test the full flow.