How to Connect CrewAI to a Database Safely (2026)

AAI for Database TeamAUG 07 2026

The safest way to connect CrewAI to a database is to give the crew a narrow tool, not a production password. That tool should accept a business question, call a read-only query layer, and return bounded structured results. Your agents get the data they need without owning unrestricted database access.

You have three practical connection methods: a direct database driver, one of CrewAI's database tools, or a scoped API between CrewAI and the database. Direct access is quick for a local prototype. A read-only API is usually the better production boundary because credentials, schemas, query rules, and audit logs stay outside the agent runtime.

Three ways to connect CrewAI to a database

Method 1: Connect with a database driver

A custom CrewAI tool can open PostgreSQL, MySQL, or another database directly through its Python driver. This gives you full control and adds no intermediary service. It is also the method with the largest security and maintenance burden.

  • Best for: local experiments with a disposable database or one tightly controlled query.
  • You own: credential storage, connection pooling, timeouts, schema discovery, SQL validation, row limits, retries, and audit logs.
  • Main risk: the agent process holds a database credential, and a generated query can be broader or more expensive than intended.
  • If you choose direct access, create a separate read-only database role. Grant access only to approved schemas or views, set a statement timeout, cap returned rows, and reject every statement except SELECT. Never reuse the application's write-capable connection string.

    Method 2: Use a CrewAI database tool

    CrewAI publishes database-oriented tools including NL2SQL, PostgreSQL search, and MySQL search. Its official tools documentation is useful when a supported tool matches your exact job.

    Check what the tool actually does before treating it as a general analytics layer. A RAG search tool retrieves relevant content; it is not the same as running an aggregate business query. An NL2SQL tool may generate SQL, but you still need a safe execution boundary, database permissions, query budgets, and logging.

  • Best for: prototypes already built around CrewAI's tool library.
  • Advantage: less wrapper code and familiar integration with CrewAI agents.
  • Tradeoff: database coverage and behavior vary by tool, while production controls remain your responsibility.
  • Method 3: Put a read-only API between CrewAI and the database

    A database API moves the dangerous parts out of the crew. CrewAI receives a scoped API key and connection ID. The data layer stores the database credential, exposes a sanitized schema, validates read-only queries, limits results, and records what ran.

    AI for Database provides this pattern for PostgreSQL, MySQL, MongoDB, SQLite, Supabase, SQL Server, BigQuery, and other sources. Your CrewAI tool can send either a plain-English question or reviewed SQL. The response returns structured columns, rows, counts, and timing rather than handing the agent a raw database session.

  • Best for: production agents, multiple databases, non-technical teams, or any workflow that needs an audit trail.
  • Advantage: one integration pattern across databases, with scoped keys and read-only guardrails.
  • Tradeoff: one network hop and a service dependency; use timeouts and handle unavailable responses cleanly.
  • Which CrewAI database method should you choose?

    Use a direct driver only when the environment is controlled and you are prepared to own the full safety layer. Use a CrewAI database tool when its documented behavior precisely matches the task. Use a read-only API when the crew will touch production data, serve multiple users, or run without a human reviewing every call.

    For most production teams, the API pattern wins. It separates the agent's reasoning from database authority. That is the important architecture decision; the few lines of wrapper code are the easy part.

    How to connect CrewAI to AI for Database

    Step 1: Create a read-only database account

    Create a dedicated reporting user in your database. Grant it SELECT access only to the schemas, tables, or views the crew needs. Exclude password hashes, private notes, payment details, and other sensitive columns unless the use case explicitly requires them.

    Database permissions remain your final control. A tool-level rule is useful, but it should not be the only thing standing between an autonomous agent and a destructive statement.

    Step 2: Connect the database

    Add the read-only connection in AI for Database. The service inspects table, column, and relationship metadata so the agent does not need to run repeated discovery queries. Test the connection before wiring it into CrewAI.

    Step 3: Create a scoped API key

    Create an afd_ API key with only the scopes your tool needs. Use connections to list sanitized connections and cached schemas. Add chat for plain-English questions, or query when the crew sends reviewed SQL. Do not give an analytics agent workflow or admin scopes it never calls.

    Store the API key in your secret manager or environment configuration. Never paste it into an agent prompt, YAML task description, source repository, log message, or tool result.

    Step 4: Wrap the API as a CrewAI custom tool

    CrewAI supports custom tools through a BaseTool subclass or the @tool decorator. Its current custom-tool guide recommends clear input schemas and typed outputs when results have stable fields.

    import json
    import os
    import requests
    from crewai.tools import tool
    
    @tool("Ask the company database")
    def ask_company_database(question: str) -> str:
        """Answer a business question from the approved database connection."""
        response = requests.post(
            "https://app.aifordatabase.com/api/v1/chat",
            headers={
                "Authorization": f"Bearer {os.environ['AIFD_API_KEY']}",
                "Content-Type": "application/json",
            },
            json={
                "message": question,
                "connectionId": os.environ["AIFD_CONNECTION_ID"],
            },
            timeout=30,
        )
        response.raise_for_status()
        return json.dumps(response.json()["data"])
    

    The description matters because the agent uses it to decide when to call the tool. Keep it narrow: say which database questions are allowed, what the result contains, and what the tool cannot do. Do not describe a read-only analytics tool as a general action tool.

    Step 5: Attach the tool to one specialist agent

    from crewai import Agent
    
    data_analyst = Agent(
        role="Read-only business data analyst",
        goal="Answer approved metric questions using live company data",
        backstory=(
            "You use the database tool for factual metrics. "
            "You never invent missing values or request write operations."
        ),
        tools=[ask_company_database],
        verbose=True,
    )
    

    Give the tool to the agent that needs it, not every agent in the crew. A researcher writing market notes has no reason to see customer tables. Smaller tool sets reduce accidental calls and make permissions easier to explain.

    Step 6: Test the boundary before production

  • Ask an allowed question with a known answer, such as signups yesterday, and compare the result with a trusted report.
  • Ask for a forbidden table or sensitive field and confirm the database role blocks it.
  • Try a write request, an unbounded export, malformed input, and an expensive time range. Confirm each fails safely.
  • Remove the API key, force a timeout, and simulate a service error. The crew should report that data is unavailable rather than invent an answer.
  • Review the query log and verify that the original question, generated SQL, duration, row count, and caller are traceable.
  • Production guardrails that matter

  • Least privilege: one database role and one API key per environment or agent workload.
  • Read-only enforcement: block INSERT, UPDATE, DELETE, DDL, stored procedures, and multi-statement execution.
  • Bounded work: set statement timeouts, row limits, rate limits, and concurrency caps.
  • Data minimization: expose approved views instead of broad base tables when practical.
  • Auditability: log the question, SQL, connection, caller, duration, row count, and outcome without logging secrets.
  • Failure honesty: tell the crew to surface tool errors and missing data, never fill gaps with plausible numbers.
  • Human review: require approval before a result triggers email, Slack, webhooks, payments, or customer-facing actions.
  • If you use MCP instead of REST, the same rules apply—and server trust becomes another boundary. CrewAI's MCP security guidance warns that untrusted servers can expose data, execute code, or inject instructions through tool metadata. Use only servers you operate or fully trust.

    Example CrewAI database tasks

  • Customer success: Which active accounts have declining usage and a renewal in the next 30 days?
  • Product: What percentage of new workspaces used the reporting feature within seven days of signup?
  • Operations: Which paid orders have been stuck in processing for more than two hours?
  • Finance: Show monthly recurring revenue and failed-payment value by plan for the current month.
  • Engineering: Which API endpoints had the largest increase in errors and latency since the latest release?
  • A good task names the metric, population, and time range. The crew can ask follow-up questions, but your semantic definitions should decide what terms such as active account, revenue, and churn mean.

    I need CrewAI to query live data without database passwords. What should I use?

    Use a custom CrewAI tool that calls a scoped, read-only database API. Keep the database password in the data layer, return only bounded structured results, and log every query. This setup gives the crew live answers without turning the agent runtime into a database administrator.

    AI for Database combines that query layer with self-refreshing dashboards and action workflows. The same validated question can become a dashboard panel, while a threshold can send email, Slack, or a webhook without giving CrewAI write access to the source database.

    When AI for Database is the right fit

    Use AI for Database when you want CrewAI to query several database types through one contract, when non-technical teammates also need plain-English access, or when the answers should become live dashboards and monitored actions. It removes the recurring work of building a separate schema, safety, and reporting layer for every database.

    Keep a direct connection when you have one controlled database, reviewed deterministic SQL, and engineers willing to own permissions, pooling, validation, and observability. Not every integration needs another platform. But production agents touching customer data do need a real security boundary.

    Ready to connect CrewAI to a database without handing it production credentials? Create a free AI for Database account, add one read-only connection, and test the first question with a scoped API key.

    Frequently asked questions

    What is the safest way to connect CrewAI to a database?

    Give CrewAI a narrow custom tool that calls a scoped, read-only database API. Keep database credentials outside the agent runtime, limit schemas and rows, and log every query.

    Can CrewAI connect to PostgreSQL, MySQL, or MongoDB?

    Yes. CrewAI can use direct drivers, database-specific tools, or a shared API layer. AI for Database exposes one read-only pattern across PostgreSQL, MySQL, MongoDB, SQLite, Supabase, SQL Server, BigQuery, and more.

    Should a CrewAI agent receive a database connection string?

    Usually no in production. A direct connection can work for controlled prototypes, but a scoped API key reduces credential exposure and centralizes schema access, query limits, and auditing.

    Is MCP or REST better for a CrewAI database integration?

    REST is simple when you need a small, explicit query contract. MCP is useful for tool discovery and multiple capabilities, but only connect to servers you fully trust because tool metadata and server code expand the security boundary.

    Can CrewAI trigger actions from database results?

    Yes, but separate reading from acting. AI for Database can monitor a validated query and send email, Slack, or webhook actions while the source database connection remains read-only.

    Ready to try AI for Database?

    Query your database in plain English. No SQL required. Start free today.