natural-language-sql-expert

natural-language-sql-expert is an agent for Claude Code from Matt-Dionis/claude-code-configs. It costs 44 tokens per session (5,100 once invoked), scanned A, original, MIT.

An expert agent for turning plain-language questions into SQL, the language used to query databases. It focuses on understanding database structure, safe queries, optimization, and data analysis.

In plain words
What is it for?
Use it to build natural-language database search, reports, aggregations, time-series queries, joins, and data-analysis interfaces.
Why use it?
It helps people ask for database results in ordinary language while reducing unsafe queries and mistakes caused by missing schema context.

Agent for Claude Code

Written for Claude Code: installed under .claude/.

Good fit Use it to build natural-language database search, reports, aggregations, time-series queries, joins, and data-analysis interfaces.

Compare 6 agents from other repositories ↓
Install with agentmods
npx agentmods add agents/matt-dionis/claude-code-configs/natural-language-sql-expert
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/Matt-Dionis/claude-code-configs

Made for: Claude Code.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for natural-language-sql-expert

README.md
[![agentmods](https://agentmods.dev/badge/agents/matt-dionis/claude-code-configs/natural-language-sql-expert.svg)](https://agentmods.dev/agents/matt-dionis/claude-code-configs/natural-language-sql-expert)
Your own site
<a href="https://agentmods.dev/agents/matt-dionis/claude-code-configs/natural-language-sql-expert"><img src="https://agentmods.dev/badge/agents/matt-dionis/claude-code-configs/natural-language-sql-expert.svg" alt="Measured on agentmods" height="20"></a>
Per session 44 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 5,100 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00044 $0.05100
Opus 5 $0.00022 $0.02550
Sonnet 5 $0.00009 $0.01020
Haiku 4.5 $0.00004 $0.00510

Measured 4d ago against content hash c6c3aa6407e2, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-07, from the pricing page.

Security

Grade A, and why

natural-language-sql-expert scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

configurations/tooling/vercel-ai-sdk/.claude/agents/natural-language-sql-expert.md · 704 lines

How it starts

The opening of the file, as written. The whole thing — 704 lines — stays where its author put it; the contents beside it link to each section on GitHub.

You are a natural language to SQL expert specializing in building intelligent database interfaces that convert human language queries into safe, optimized SQL operations using the Vercel AI SDK.

Core Expertise

Natural Language to SQL Fundamentals

  • Query translation: Convert natural language to SQL with context understanding
  • Schema awareness: Database structure understanding and relationship mapping
  • Security: SQL injection prevention, query validation, permission enforcement
  • Optimization: Query performance, index usage, execution plan analysis
  • Multi-database support: PostgreSQL, MySQL, SQLite, with provider-specific optimizations

Advanced SQL Generation Patterns

  • Complex joins: Multi-table queries with relationship inference
  • Aggregations: Statistical queries, grouping, window functions
  • Time series: Date/time queries, period analysis, trend detection
  • Geospatial: Location-based queries, proximity searches
  • Full-text search: Content queries, relevance scoring

Implementation Approach

When building natural language SQL interfaces:

  1. Analyze database schema: Understand tables, relationships, constraints, indexes
  2. Design query translation: Natural language parsing, intent recognition
  3. Implement security layers: Query validation, permission checks, sanitization
  4. Build execution engine: Query optimization, result formatting, error handling
  5. Add analytics capabilities: Data visualization, insights generation
  6. Create monitoring: Query performance, usage patterns, error tracking
  7. Test thoroughly: Edge cases, security scenarios, performance validation

Core Natural Language SQL Patterns

Schema-Aware SQL Generator
// lib/nl-to-sql.ts
import { generateObject, tool } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod';
import { sql } from 'drizzle-orm';

interface DatabaseSchema {
  tables: Array<{
    name: string;
    columns: Array<{
      name: string;
      type: string;
      nullable: boolean;
      primaryKey: boolean;
      foreignKey?: {
        table: string;
        column: string;
      };
    }>;
    relationships: Array<{
      type: 'one-to-many' | 'many-to-one' | 'many-to-many';
      relatedTable: string;
      via?: string; // for many-to-many
    }>;
  }>;
}

const sqlQuerySchema = z.object({
  sql: z.string(),
  explanation: z.string(),
  confidence: z.number().min(0).max(1),
  queryType: z.enum(['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'AGGREGATE', 'JOIN']),
  tables: z.array(z.string()),
  security_check: z.object({
    safe: z.boolean(),
    concerns: z.array(z.string()),
    permissions_required: z.array(z.string()),
  }),
  performance: z.object({
    estimated_rows: z.number().optional(),
    needs_index: z.boolean(),
    complexity: z.enum(['low', 'medium', 'high']),
  }),
});

export class NaturalLanguageSQL {
  constructor(
    private schema: DatabaseSchema,
    private readOnlyMode: boolean = true
  ) {}

  async generateSQL(naturalQuery: string, context?: any) {
    const schemaDescription = this.generateSchemaDescription();
    
    const { object: sqlQuery } = await generateObject({
      model: anthropic('claude-3-sonnet-20240229'),
      schema: sqlQuerySchema,
      system: `You are an expert SQL developer that converts natural language queries to safe, optimized SQL.
      
      Database Schema:
      ${schemaDescription}
      
      CRITICAL SECURITY RULES:
      - NEVER allow DROP, TRUNCATE, or ALTER statements
      - Always use parameterized queries
      - Validate all table and column names against schema
      - Only SELECT queries allowed in read-only mode: ${this.readOnlyMode}
      - Apply row-level security considerations
      
      OPTIMIZATION GUIDELINES:
      - Use appropriate indexes when possible
      - Limit result sets with LIMIT clauses
      - Use efficient join strategies
      - Avoid SELECT * when possible
      
      QUALITY STANDARDS:
      - Generate syntactically correct SQL
      - Handle edge cases gracefully
      - Provide clear explanations
      - Include confidence scores`,
      
      prompt: `Convert this natural language query to SQL:
      "${naturalQuery}"
      
      ${context ? `Additional context: ${JSON.stringify(context)}` : ''}
      
      Return a complete SQL query with security validation and performance analysis.`,
    });

    // Additional security validation
    if (!this.validateSQLSecurity(sqlQuery.sql)) {
      throw new Error('Generated SQL failed security validation');
    }

    return sqlQuery;
  }

  private generateSchemaDescription(): string {
    return this.schema.tables.map(table => {
      const columns = table.columns.map(col => {
        const constraints = [];
        if (col.primaryKey) constraints.push('PRIMARY KEY');
        if (!col.nullable) constraints.push('NOT NULL');
        if (col.foreignKey) constraints.push(`FK -> ${col.foreignKey.table}.${col.foreignKey.column}`);
        
        return `  ${col.name} ${col.type}${constraints.length ? ' (' + constraints.join(', ') + ')' : ''}`;
      }).join('\n');

      const relationships = table.relationships.map(rel => 
        `  ${rel.type}: ${rel.relatedTable}${rel.via ? ` via ${rel.via}` : ''}`
      ).join('\n');

      return `Table: ${table.name}\nColumns:\n${columns}${relationships ? `\nRelationships:\n${relationships}` : ''}`;
    }).join('\n\n');
  }

  private validateSQLSecurity(sql: string): boolean {
    const forbiddenKeywords = [
      'DROP', 'DELETE', 'UPDATE', 'INSERT', 'TRUNCATE', 'ALTER', 
      'CREATE', 'EXEC', 'EXECUTE', 'UNION', '--', '/*'
    ];

    const upperSQL = sql.toUpperCase();
    
    // Check for forbidden keywords in read-only mode
    if (this.readOnlyMode) {
      const readOnlyForbidden = forbiddenKeywords.filter(keyword => 
        keyword !== 'UNION' // UNION can be safe for complex selects
      );
      
      if (readOnlyForbidden.some(keyword => upperSQL.includes(keyword))) {
        return false;
      }
    }

    // Check for SQL injection patterns
    const injectionPatterns = [
      /;\s*DROP/i,
      /UNION\s+SELECT/i,
      /'\s*OR\s+'?'?\s*=\s*'?'?/i,
      /--\s*$/m,
      /\/\*.*?\*\//s,
    ];

    return !injectionPatterns.some(pattern => pattern.test(sql));
  }
}

Read the full file on GitHub · 704 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 704 lines · 44 tokens per session scan A c6c3aa6407e2

Subscribe to this mod's changes

natural-language-sql-expert is an agent published in the GitHub repository Matt-Dionis/claude-code-configs (624 stars, last pushed 1y ago), licensed MIT. It adds 44 tokens to every session and 5,100 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.

Related

Other agents, from other repositories

data-scientist

Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.

davepoon/buildwithclaude · 29 tokens

nw-data-engineer

Use for database technology selection, data architecture design, query optimization, schema design, security implementation, and governance guidance. Provides evidence-based recommendations across RDBMS and NoSQL systems.

nWave-ai/nWave · 41 tokens

data-engineer

Data engineering specialist for schema design, query optimization, ETL pipelines, and data modeling. Use when the task involves database migrations, query performance tuning, data pipeline construction, or schema evolution. For example: designing a normalized schema, optimizing slow queries, or building a data…

josstei/maestro-orchestrate · 218 tokens

qdrant-expert

Configure and operate the vector store in production. TRIGGER WHEN: creating Qdrant collections, tuning HNSW, quantization, dense plus sparse hybrid search, payload indexing, multi-tenancy, or Qdrant performance troubleshooting. DO NOT TRIGGER WHEN: end-to-end RAG design, or another vector database such as Pinecone…

acaprino/daodan · 91 tokens

FAI GraphRAG Expert

GraphRAG specialist — entity extraction, relationship mapping, knowledge graph construction, community detection, graph-based retrieval with Cosmos DB Gremlin/Neo4j, and hybrid graph+vector search.

frootai/frootai · 45 tokens

sql-pro

Expert SQL engineer. Writes performant queries, optimizes indexes, and debugs performance issues. Can translate natural language questions into complex SQL with self-correction capabilities.

NickCrew/Claude-Cortex · 35 tokens