WebsitePlatform Login

MCP Database Tool

Enable AI assistants to query and analyze your databases

MCP Database Tool

The MCP Database tool enables your AI assistants to directly query and analyze data from your databases, making it powerful for business intelligence, reporting, and data-driven insights.

Overview

The Database tool provides:

  • Secure database access through MCP protocol
  • Read-only queries for safety
  • Multiple database support (PostgreSQL, MySQL, SQLite)
  • Intelligent query generation by AI
  • Result formatting in tables, charts, or summaries

Supported Databases

PostgreSQL

  • Version 12+
  • Full SQL support
  • JSON/JSONB queries
  • Array operations
  • Window functions

MySQL

  • Version 5.7+
  • Standard SQL queries
  • JSON support (5.7+)
  • Full-text search

SQLite

  • Version 3.35+
  • Local file databases
  • In-memory databases
  • Lightweight queries

Configuration

Basic Setup

  1. In Assistant Editor:

    tools:
      - type: mcp
        name: database
        config:
          connection_string: ${DATABASE_URL}
          database_type: postgresql
          allowed_operations: ["SELECT"]
  2. Connection String Format:

    PostgreSQL:

    postgresql://username:password@host:5432/database

    MySQL:

    mysql://username:password@host:3306/database

    SQLite:

    sqlite:///path/to/database.db

Advanced Configuration

tools:
  - type: mcp
    name: database
    config:
      connection_string: ${DATABASE_URL}
      database_type: postgresql
      allowed_operations: ["SELECT", "WITH"]
      
      # Query limits
      max_rows: 1000
      timeout: 30  # seconds
      
      # Schema restrictions
      allowed_schemas: ["public", "analytics"]
      allowed_tables: ["sales", "customers", "products"]
      
      # Security
      enable_explain: true
      log_queries: true

Security Features

Query Restrictions

Allowed Operations:

  • SELECT - Read data
  • WITH - Common Table Expressions
  • EXPLAIN - Query plans (optional)

Blocked Operations:

  • INSERT, UPDATE, DELETE
  • DROP, CREATE, ALTER
  • GRANT, REVOKE
  • Transaction control

Access Control

  1. Table-Level Permissions:

    allowed_tables: 
      - "sales_data"
      - "customer_view"  # Use views for sensitive data
  2. Column-Level Security:

    -- Create a view hiding sensitive columns
    CREATE VIEW customer_view AS
    SELECT id, name, email, country
    FROM customers;
    -- Exclude: ssn, credit_card, etc.
  3. Row-Level Security:

    # Use database RLS or filtered views
    connection_string: ${DB_URL_WITH_RLS_USER}

Usage Examples

Business Analytics

User: "What were our top 10 products by revenue last quarter?"

Assistant generates:

SELECT 
    p.product_name,
    SUM(s.quantity * s.unit_price) as revenue,
    COUNT(DISTINCT s.order_id) as order_count
FROM sales s
JOIN products p ON s.product_id = p.id
WHERE s.order_date >= '2024-01-01' 
  AND s.order_date < '2024-04-01'
GROUP BY p.product_name
ORDER BY revenue DESC
LIMIT 10;

Customer Insights

User: "Show me customer churn rate by month"

Assistant generates:

WITH monthly_cohorts AS (
    SELECT 
        DATE_TRUNC('month', first_purchase) as cohort_month,
        customer_id,
        DATE_TRUNC('month', last_purchase) as last_active
    FROM (
        SELECT 
            customer_id,
            MIN(order_date) as first_purchase,
            MAX(order_date) as last_purchase
        FROM orders
        GROUP BY customer_id
    ) customer_activity
)
SELECT 
    cohort_month,
    COUNT(DISTINCT customer_id) as total_customers,
    COUNT(DISTINCT CASE 
        WHEN last_active < cohort_month + INTERVAL '3 months' 
        THEN customer_id 
    END) as churned_customers,
    ROUND(100.0 * COUNT(DISTINCT CASE 
        WHEN last_active < cohort_month + INTERVAL '3 months' 
        THEN customer_id 
    END) / COUNT(DISTINCT customer_id), 2) as churn_rate
FROM monthly_cohorts
GROUP BY cohort_month
ORDER BY cohort_month;

Data Quality Checks

User: "Check for data quality issues in our orders table"

Assistant generates multiple queries:

-- Check for nulls in critical fields
SELECT 
    COUNT(*) as total_rows,
    SUM(CASE WHEN customer_id IS NULL THEN 1 ELSE 0 END) as null_customers,
    SUM(CASE WHEN order_date IS NULL THEN 1 ELSE 0 END) as null_dates,
    SUM(CASE WHEN total_amount IS NULL THEN 1 ELSE 0 END) as null_amounts
FROM orders;

-- Check for duplicates
SELECT order_id, COUNT(*) as duplicate_count
FROM orders
GROUP BY order_id
HAVING COUNT(*) > 1;

-- Check for invalid values
SELECT COUNT(*) as negative_amounts
FROM orders
WHERE total_amount < 0;

Best Practices

1. Use Read-Only Credentials

-- Create a read-only user
CREATE USER mcp_reader WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE mydb TO mcp_reader;
GRANT USAGE ON SCHEMA public TO mcp_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_reader;

2. Create Analytics Views

-- Pre-aggregate common queries
CREATE MATERIALIZED VIEW daily_sales_summary AS
SELECT 
    DATE(order_date) as sale_date,
    COUNT(*) as order_count,
    SUM(total_amount) as revenue,
    AVG(total_amount) as avg_order_value
FROM orders
GROUP BY DATE(order_date);

-- Refresh periodically
REFRESH MATERIALIZED VIEW daily_sales_summary;

3. Implement Query Logging

config:
  log_queries: true
  log_destination: "audit_log"
  include_results: false  # Don't log sensitive data

4. Set Appropriate Timeouts

config:
  timeout: 30  # Kill queries after 30 seconds
  statement_timeout: "30s"  # PostgreSQL specific

Performance Optimization

Query Optimization

  1. Use Indexes:

    -- Create indexes for common query patterns
    CREATE INDEX idx_orders_date ON orders(order_date);
    CREATE INDEX idx_orders_customer ON orders(customer_id);
  2. Limit Result Sets:

    config:
      max_rows: 1000  # Prevent accidental large queries
      default_limit: 100  # Add LIMIT if not specified
  3. Connection Pooling:

    config:
      pool_size: 5
      max_overflow: 10
      pool_timeout: 30

Monitoring

Track Usage:

  • Query count per assistant
  • Average query time
  • Most frequent queries
  • Error rates

Alert on:

  • Slow queries (>10s)
  • Failed connections
  • Permission errors
  • Result set limits hit

Common Use Cases

1. Sales Dashboard

Assistant: "Sales Performance Analyst"
Tools: Database + Charts
Use: Real-time sales metrics and visualizations

2. Customer Support

Assistant: "Support Agent Helper"
Tools: Database + Memory
Use: Look up customer information and history

3. Inventory Management

Assistant: "Inventory Analyst"
Tools: Database + Alerts
Use: Monitor stock levels and predict shortages

4. Financial Reporting

Assistant: "Financial Reporter"
Tools: Database + Document Generation
Use: Create automated financial reports

Troubleshooting

Connection Issues

Error: "Connection refused"

  • Check connection string format
  • Verify network access
  • Confirm database is running
  • Check firewall rules

Error: "Authentication failed"

  • Verify credentials
  • Check user permissions
  • Ensure SSL/TLS if required

Query Issues

Error: "Permission denied"

  • User lacks SELECT permission
  • Table not in allowed_tables
  • Schema not in allowed_schemas

Error: "Query timeout"

  • Optimize query performance
  • Increase timeout setting
  • Add appropriate indexes
  • Consider materialized views

Performance Issues

Slow Queries:

  1. Run EXPLAIN on the query
  2. Check for missing indexes
  3. Analyze table statistics
  4. Consider query rewriting

High Load:

  1. Implement connection pooling
  2. Use read replicas
  3. Cache frequent queries
  4. Schedule heavy queries off-peak

Advanced Features

Query Templates

config:
  templates:
    daily_revenue: |
      SELECT DATE(order_date) as date, 
             SUM(total_amount) as revenue
      FROM orders
      WHERE order_date >= :start_date
      GROUP BY DATE(order_date)

Caching

config:
  cache:
    enabled: true
    ttl: 300  # 5 minutes
    max_size: 100  # queries

Multi-Database Support

tools:
  - type: mcp
    name: database
    alias: "sales_db"
    config:
      connection_string: ${SALES_DB_URL}
      
  - type: mcp
    name: database  
    alias: "analytics_db"
    config:
      connection_string: ${ANALYTICS_DB_URL}

Security Checklist

  • Use read-only database user
  • Implement connection encryption
  • Set query timeouts
  • Log all queries for audit
  • Restrict schemas/tables
  • Use views for sensitive data
  • Regular security reviews
  • Monitor for anomalies

Learn More