MODULE 01 FULL DOCS

Securely Chat with Your Data

Connect ChatGPT, Claude, Cursor, or any AI agent to your enterprise database through DreamFactory, with full access controls and audit logging. No code required.

~15 min read
Beginner
Hands-on Tutorial

💬 Overview

This module shows you how to connect any AI agent (ChatGPT, Claude, Cursor, Copilot, or a custom tool) to your enterprise database through DreamFactory. Once connected, anyone in your organization can ask plain English questions about company data and get instant answers.

No SQL knowledge. No code. No waiting for a data analyst to run a report. Just open your AI agent, ask a question, and get the data you need.

What You'll Build

By the end of this guide, you'll have:

  • A DreamFactory MCP service connected to your database
  • OAuth-based authentication for secure AI agent access
  • An AI agent (ChatGPT, Claude, Cursor, etc.) querying live enterprise data
  • RBAC policies controlling exactly which data the AI can access
  • Full audit logging of every query the AI makes
🎬

Watch the CTO Demo

DreamFactory CTO Kevin McGahey walks through this exact workflow in a 12-minute video, going from zero to querying a live sales database with ChatGPT. Watch the demo →

Who This Is For

  • Business users who want to query company data without SQL
  • IT administrators setting up secure AI access to databases
  • Data teams looking to democratize access to reports and metrics
  • Developers evaluating AI-to-database integration patterns

📧 The Scenario

Your CEO sends an email:

✉️

"I need a breakdown of our customer data by region. Which regions have the most customers? What does our sales pipeline look like? I need this for a board meeting tomorrow."

Normally, this triggers a chain: you email the data team, they write SQL queries, pull the data into a spreadsheet, format it, and send it back. That takes hours, maybe days.

With DreamFactory and an AI agent, the answer takes about 30 seconds:

  1. Open ChatGPT (or Claude, Cursor, or any AI agent)
  2. Ask: "Show me a breakdown of customers by region"
  3. Get a formatted table with the data, pulled live from your database
  4. Follow up: "Which of those regions had the most sales last quarter?"
  5. Get the refined answer instantly

The AI never touches your database directly. Every query flows through DreamFactory's security layer, which enforces access controls, logs every request, and rate-limits usage.

🏗️ How It Works

The architecture has three layers. The AI agent never connects directly to your database. DreamFactory sits in the middle, acting as an AI Data Gateway.

🤖
AI Agent
ChatGPT, Claude, Cursor, Copilot
MCP Protocol / OAuth
🛡️
DreamFactory
RBAC + Audit + Rate Limiting
Secure SQL
💾
Your Database
MySQL, PostgreSQL, SQL Server, etc.

What the AI Data Gateway Does

LayerFunctionDetails
AuthenticationVerify AI agent identityOAuth 2.0 tokens, API keys, or session-based auth
AuthorizationEnforce data access policiesRole-based access control (RBAC) per table, column, and row
Query TranslationConvert natural language to SQLAI agent writes queries; DreamFactory validates and executes
Rate LimitingPrevent abuseConfigurable limits per user, role, or service
Audit LoggingRecord every interactionFull request/response logging with timestamps and user IDs
⚠️

Why Not Connect AI Directly to Your Database?

Without a security layer, an AI agent with direct database access could execute arbitrary SQL, including DROP TABLE or SELECT * on sensitive data. DreamFactory ensures every query is validated against your access policies before execution.

1 Create an MCP Service

1

Enable the MCP Server in DreamFactory

~1 min

DreamFactory 7.4+ includes a built-in MCP (Model Context Protocol) server. MCP is the standard protocol that AI agents use to discover and interact with external tools, in this case your database.

Navigate to Services > Create > MCP in your DreamFactory admin panel:

DreamFactory AI Services section showing MCP Server services
The AI Services section in DreamFactory, where you create and manage MCP services that bridge AI agents to your APIs.

Configure the service:

  • Service Name: Choose a descriptive name (e.g., sales-data-mcp)
  • Label: Human-readable label for the admin panel
  • Description: Brief description of what data this service exposes
  • Active: Toggle on to enable the service
💡

What is MCP?

Model Context Protocol (MCP) is an open standard that lets AI agents discover and use external tools. Think of it like USB for AI, a universal connector. DreamFactory's MCP server exposes your database tables as well as file storage services (S3, Azure Blob, SFTP) as tools that any MCP-compatible AI can use. For a deep dive into MCP, see Module 02.

2 Configure Your Database Connection

2

Connect DreamFactory to Your Database

~2 min

If you haven't already connected a database to DreamFactory, go to Services > Create > Database and add your connection.

DreamFactory database services configuration
DreamFactory database service configuration: connecting to your enterprise database

DreamFactory supports all major databases:

DatabaseConnection TypeNotes
SQL Databases
MySQL / MariaDBNative driverMost common for web apps
PostgreSQLNative driverAdvanced features, JSON support
SQL ServerNative driverEnterprise standard, Active Directory integration
OracleOCI driverEnterprise, requires Oracle client
SQLiteFile-basedGreat for demos and prototyping
IBM DB2 / FirebirdNative driverLegacy enterprise databases
NoSQL Databases
MongoDBNative driverNoSQL document store
DynamoDBAWS SDKAWS managed NoSQL, key-value and document
Cassandra / CouchDBNative driverDistributed NoSQL stores
Cloud / Data Warehouse
SnowflakeODBC/NativeCloud data warehouse, analytics workloads
AWS RedshiftPostgreSQL wire protocolAWS columnar data warehouse
SAP HANAODBC driverIn-memory enterprise platform
DatabricksODBC/JDBCLakehouse analytics platform
Azure SQLNative driverAzure-managed SQL Server

Once connected, DreamFactory auto-discovers your schema (tables, columns, relationships). The MCP service will expose these as tools that your AI agent can use. Beyond databases, DreamFactory can also expose file storage services (such as S3, Azure Blob, and SFTP) through MCP, giving your AI agent access to documents and files alongside structured data.

Already Have a Database Service?

If you've already set up a database service in DreamFactory (e.g., from Module 08), you can reuse it. The MCP service connects to your existing database services, so there is no need to reconfigure.

3 Set Up Authentication

3

Configure OAuth for AI Agent Access

~2 min

Your AI agent needs credentials to authenticate with DreamFactory. The recommended approach is OAuth 2.0, which gives you token-based access with expiration and revocation.

Create a Role for AI Access

First, create a role that defines what data the AI agent can see. Navigate to Roles in the admin panel:

DreamFactory role-based access control configuration
Configuring RBAC: define exactly which tables and columns the AI can access

Best practices for AI agent roles:

  • Read-only access: AI agents should never be able to INSERT, UPDATE, or DELETE
  • Table filtering: Only expose the tables relevant to the use case
  • Column masking: Hide sensitive columns (SSN, credit card numbers, etc.)
  • Row-level filtering: Restrict data by business unit, region, or user context

Generate OAuth Credentials

Create an API key and assign it to the AI role. The AI agent will use this key to authenticate via OAuth:

OAuth Flow
# 1. AI agent requests access token
POST /oauth/token
{
  "grant_type": "client_credentials",
  "client_id": "your-ai-agent-client-id",
  "client_secret": "your-client-secret"
}

# 2. DreamFactory returns a scoped token
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600
}

# 3. AI agent uses token for MCP requests
# Token inherits the role's access policies
🚨

Never Use Admin Credentials for AI Agents

Always create a dedicated role with minimal permissions. Admin credentials give the AI unrestricted access to every table and operation, which is a serious security risk.

4 Connect Your AI Agent

4

Point Your AI Agent at DreamFactory

~1 min

The final step is connecting your AI agent to the DreamFactory MCP endpoint. You'll need the MCP server URL and OAuth credentials from your DreamFactory configuration:

DreamFactory MCP Server configuration with OAuth credentials
MCP Server configuration: copy the endpoint URL and OAuth credentials your AI agent needs to connect.

The exact connection steps depend on your AI agent:

ChatGPT (Custom GPTs)

In the GPT Builder, add your DreamFactory instance as an MCP server action. ChatGPT will automatically discover the available tools (your database tables) and use them to answer questions.

Claude Desktop

Add the MCP server to your Claude Desktop configuration:

JSON claude_desktop_config.json
{
  "mcpServers": {
    "dreamfactory-sales": {
      "url": "https://your-instance.dreamfactory.com/mcp/my-ai-service",
      "auth": {
        "type": "oauth2",
        "client_id": "your-client-id",
        "client_secret": "your-client-secret"
      }
    }
  }
}

Any MCP-Compatible Agent

Any tool that supports MCP can connect to DreamFactory. The MCP protocol is standardized, so your DreamFactory endpoint works the same way regardless of which AI agent connects to it.

🎉

Setup Complete!

Your AI agent is now connected to your database through DreamFactory. Every query is authenticated, authorized, and logged. Try asking a question about your data.

📖

Official Documentation

For the latest MCP connection instructions, see the official MCP Server documentation.

🔍 Your First Query

With everything connected, open your AI agent and ask a natural language question about your data. Here's what a typical conversation looks like:

Conversation ChatGPT + DreamFactory
You:    How many customers do we have in each region?

AI:     I'll query the customers table grouped by region.

         | Region        | Customer Count |
         |---------------|---------------|
         | North America | 1,247         |
         | Europe        | 893           |
         | Asia Pacific  | 634           |
         | Latin America | 412           |
         | Middle East   | 198           |

         You have 3,384 total customers across 5 regions.
         North America leads with 36.8% of all customers.

The AI agent translated your plain English question into a SQL query, sent it through DreamFactory (which validated it against your access policies), and returned the results in a readable format.

What Happened Behind the Scenes

💬
You Ask
Natural language query
🤖
AI Translates
Generates SQL via MCP
🛡️
DF Validates
RBAC check + audit log
Results
Formatted answer

🔄 Refining Results Through Conversation

The real power of chatting with your data is the ability to refine. You don't get a static report; you have a conversation. Each follow-up question narrows the results further.

Conversation Progressive Refinement
# Query 1: Broad overview
You:    Show me all customers

AI:     Found 134 customers across the database.

# Query 2: Filter by activity
You:    Which of those have active subscriptions?

AI:     89 customers have active subscriptions.

# Query 3: Focus on high value
You:    Show me the ones with annual revenue over $100K

AI:     32 customers with active subscriptions
         and annual revenue exceeding $100,000.

# Query 4: Actionable insight
You:    Sort by renewal date - which ones renew this quarter?

AI:     8 high-value customers renewing in Q1:
         [detailed table with names, revenue, renewal dates]

In four conversational turns, you went from 134 customers to 8 actionable renewal opportunities, information that would have taken a data analyst hours to compile into a report.

📊

134 → 32

Progressive narrowing from broad overview to targeted results

⏱️

~30 Seconds

Total time for four queries vs. hours for a manual report

🔒

100% Governed

Every query validated against RBAC policies and logged

🛡️ Security Controls

Security isn't a bolt-on feature; it's the core reason DreamFactory exists in this architecture. Here's how every query is protected:

Role-Based Access Control (RBAC)

DreamFactory's RBAC system controls exactly what data the AI agent can access:

ControlWhat It DoesExample
Service AccessWhich database services are availableAI can access sales_db but not hr_db
Table FilteringWhich tables within a serviceAI can read customers and orders, not employee_salaries
Column MaskingWhich columns are visibleAI sees customer_name but not ssn or credit_card
Row FilteringWhich rows are returnedAI only sees customers in assigned regions
Verb RestrictionWhich operations are allowedAI can GET (read) but not POST, PUT, DELETE

Audit Logging

Every request the AI agent makes is logged with:

  • Timestamp and request ID
  • Authenticated user/role identity
  • The exact query executed
  • Response data summary (row count, columns returned)
  • Execution time and status code
📋

Compliance Ready

DreamFactory's audit logs provide the paper trail you need for SOC 2, HIPAA, GDPR, and other compliance frameworks. You can prove exactly what data the AI accessed, when, and under whose authority.

Rate Limiting

Prevent AI agents from overwhelming your database with too many requests:

  • Per-role limits: Set maximum requests per minute/hour for AI agent roles
  • Per-service limits: Cap the load on specific database services
  • Burst protection: Prevent sudden spikes from runaway AI loops
DreamFactory rate limiting configuration
Rate limiting configuration: protect your database from excessive AI queries

Best Practices

Security

  • Least privilege: Give AI agents the minimum access they need: read-only, specific tables only
  • Separate roles per use case: Create distinct roles for sales analytics, customer support, finance, etc.
  • Rotate credentials: Use short-lived OAuth tokens and rotate client secrets regularly
  • Monitor audit logs: Review AI query patterns weekly to catch anomalies

Performance

  • Limit result sets: Configure maximum row counts to prevent the AI from pulling entire tables
  • Use views or stored procedures: Pre-aggregate complex data so the AI doesn't need to join many tables (Module 04 covers stored procedures)
  • Index frequently queried columns: If the AI often filters by region or date, ensure those columns are indexed
  • Cache common queries: DreamFactory's caching layer reduces repeated database hits

User Experience

  • Describe your data clearly: Table and column names should be human-readable (the AI uses them for context)
  • Provide table descriptions: DreamFactory lets you add descriptions to services and tables, and the AI reads these to understand your schema
  • Start broad, then refine: Encourage users to ask overview questions first, then drill down

🔧 Troubleshooting

Common Issues

ProblemLikely CauseSolution
AI agent can't connect MCP service not active or OAuth misconfigured Verify the MCP service is active in DreamFactory admin. Check OAuth client ID/secret.
AI returns "access denied" Role doesn't have permission for the requested table Check the role's service access and table permissions in DreamFactory.
AI returns empty results Row-level filter is too restrictive Review the role's row-level security filters. The AI can only see rows that match the filter.
AI queries are slow Missing indexes or large unfiltered result sets Add database indexes on frequently queried columns. Set max row limits in the role config.
AI hallucinates data AI couldn't find the data and guessed Ensure table descriptions are clear. Verify the AI actually queried DreamFactory (check audit logs).

Getting Help

🎬 Watch the Full Demo

DreamFactory CTO Kevin McGahey demonstrates everything in this module, from setup to live queries, in under 12 minutes.