Database Query API Docs

Convert natural language to safe, parameterized PostgreSQL queries. Works as a REST API or MCP server for AI agents.

First time here? You're 60 seconds from your first query.

Get a free API key, pick an example, hit Send. No credit card needed.

1
Enter your email to get a key
2
Pick an example query
3
Hit "Generate SQL"

Quickstart

Three steps to your first query.

1. Get an API Key

No credit card needed. Free tier includes 500 queries/day.

Create Free API Key
sl_live_...

Save this key — it won't be shown again. Use it in the playground →

Or use curl:

bash
curl -X POST https://signallayer-2.polsia.app/api/v1/keys \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com", "name": "My App"}'

2. Generate a Query

Replace YOUR_KEY with the key from step 1.

bash
curl -X POST https://signallayer-2.polsia.app/api/v1/query/generate \
  -H "Authorization: Bearer sl_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Show me all users who signed up this week",
    "schema": {
      "tables": [{
        "name": "users",
        "columns": [
          {"name": "id", "data_type": "serial", "is_primary_key": true},
          {"name": "email", "data_type": "varchar(255)"},
          {"name": "name", "data_type": "varchar(255)"},
          {"name": "created_at", "data_type": "timestamptz"}
        ]
      }]
    }
  }'

3. Use the Result

json — response
{
  "success": true,
  "data": {
    "sql": "SELECT id, email, name, created_at FROM users WHERE created_at >= NOW() - INTERVAL '7 days' ORDER BY created_at DESC LIMIT 100",
    "params": [],
    "explanation": "Retrieves all users who registered within the last 7 days, ordered by most recent first",
    "is_read_only": true,
    "estimated_complexity": "simple"
  }
}

Authentication

All API endpoints (except key creation and docs) require an API key. Pass it via:

Authorization header (recommended)
Authorization: Bearer sl_live_abc123...
x-api-key header (alternative)
x-api-key: sl_live_abc123...
API keys start with sl_live_. Free tier: 500 queries/day, 30/minute. The raw key is only shown once at creation — save it securely.

Try It Live

Try one of these examples:

Interactive Playground

Enter your API key and a natural language question. The generated SQL is ready to execute against your database.

✅ Query generated successfully — SQL is ready to run
Error
Result

                    

Generate Query

POST /api/v1/query/generate

Convert a natural language question into a safe, parameterized PostgreSQL query.

Request Body

ParameterTypeDescription
querystring requiredNatural language question (max 2000 chars)
schemaobject optionalDatabase schema context (tables, columns, relationships)
allow_writeboolean optionalAllow INSERT/UPDATE/DELETE (default: false, Pro only)
max_rowsinteger optionalMax rows in LIMIT clause (default: 100)
target_tablesstring[] optionalFocus generation on specific tables

Example Request

json — request body
{
  "query": "Top 5 customers by total order value",
  "schema": {
    "tables": [
      {
        "name": "customers",
        "columns": [
          { "name": "id", "data_type": "serial", "is_primary_key": true },
          { "name": "name", "data_type": "varchar(255)" },
          { "name": "email", "data_type": "varchar(255)" }
        ]
      },
      {
        "name": "orders",
        "columns": [
          { "name": "id", "data_type": "serial", "is_primary_key": true },
          { "name": "customer_id", "data_type": "integer" },
          { "name": "amount", "data_type": "decimal(10,2)" },
          { "name": "created_at", "data_type": "timestamptz" }
        ]
      }
    ]
  }
}

Response

FieldTypeDescription
data.sqlstringGenerated PostgreSQL query
data.paramsarrayParameterized values ($1, $2, ...)
data.explanationstringPlain English explanation
data.is_read_onlybooleanWhether query is read-only
data.tables_referencedstring[]Tables used in the query
data.safety_flagsstring[]Safety check results
usageobjectToken usage and timing

Common Errors

CodeStatusCause & Fix
INVALID_INPUT400query field missing or empty. Send: {"query": "your question", ...}
INVALID_SCHEMA400Schema malformed. Check: {"tables": [{"name": "...", "columns": [...]}]}
QUERY_TOO_LONG400Query exceeds 2000 chars. Trim your natural language input.
WRITE_REQUIRES_PRO403allow_write: true requires Pro tier. Upgrade →
UNAUTHORIZED401Missing or invalid API key. Check Authorization: Bearer sl_live_... header.

Validate Query

POST /api/v1/query/validate

Check if a SQL query is safe to execute. Detects injection patterns, dangerous statements, and missing safety guards.

ParameterTypeDescription
sqlstring requiredSQL query to validate
allow_writeboolean optionalAllow write operations (default: false)
json — request body
{
  "sql": "SELECT id, email FROM users WHERE created_at > NOW() - INTERVAL '7 days'"
}

Explain Query

POST /api/v1/query/explain

Get a plain English explanation of what a SQL query does.

ParameterTypeDescription
sqlstring requiredSQL query to explain
schemaobject optionalDatabase schema for better context

Introspect Schema

POST /api/v1/schema/introspect

Connect to a PostgreSQL database and discover its schema — tables, columns, indexes, and foreign key relationships.

ParameterTypeDescription
connection_stringstring requiredPostgreSQL connection string (postgres://...)
schema_namestring optionalSchema to introspect (default: "public")
Connection strings are used transiently and never stored. We recommend using read-only database credentials.

Usage Stats

GET /api/v1/usage?period=30d

Get usage statistics for your API key. Available periods: 24h, 7d, 30d.

MCP Protocol

SignalLayer exposes a Model Context Protocol (MCP) endpoint for direct agent integration. Any MCP-compatible agent can connect and use our tools natively.

Claude Desktop / Cursor / Windsurf config
{
  "mcpServers": {
    "signallayer-db": {
      "url": "https://signallayer-2.polsia.app/api/v1/mcp",
      "headers": {
        "Authorization": "Bearer sl_live_YOUR_KEY"
      }
    }
  }
}

Example MCP Call

JSON-RPC 2.0
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "generate_query",
    "arguments": {
      "query": "Find the top 10 customers by revenue",
      "schema": { "tables": [...] }
    }
  },
  "id": 1
}

MCP Tools

Four tools are available via the MCP endpoint:

generate_query

Convert natural language to safe PostgreSQL. Accepts schema context for accurate results.

introspect_schema

Connect to a database and discover tables, columns, indexes, and relationships.

validate_query

Check SQL safety — detects injection, dangerous statements, missing limits.

explain_query

Get plain English explanation of any SQL query.

Install from GitHub

npm publish is currently pending review. In the meantime, install the MCP server directly from our GitHub repo — works identically.

Option 1 — Clone & run locally

Requires Node.js 18+. Runs the stdio MCP server as a local process.

bash
git clone https://github.com/Polsia-Inc/signallayer-2
cd signallayer-2/packages/mcp-server
npm install
bash — start the server
SIGNALLAYER_API_KEY=sl_live_YOUR_KEY node index.js

Option 2 — Run directly with npx from GitHub

bash
SIGNALLAYER_API_KEY=sl_live_YOUR_KEY npx github:Polsia-Inc/signallayer-2/packages/mcp-server

Claude Desktop config (after cloning)

Add to your claude_desktop_config.json. Replace the path with your actual clone location.

claude_desktop_config.json
{
  "mcpServers": {
    "signallayer": {
      "command": "node",
      "args": ["/path/to/signallayer-2/packages/mcp-server/index.js"],
      "env": {
        "SIGNALLAYER_API_KEY": "sl_live_YOUR_KEY"
      }
    }
  }
}

Cursor / Windsurf config

Same shape — add to your IDE's MCP server config file.

.cursor/mcp.json or .windsurf/mcp.json
{
  "mcpServers": {
    "signallayer": {
      "command": "node",
      "args": ["/path/to/signallayer-2/packages/mcp-server/index.js"],
      "env": {
        "SIGNALLAYER_API_KEY": "sl_live_YOUR_KEY"
      }
    }
  }
}
Coming soon: npm package @signallayer/mcp-server is pending review. Once published, installation will be simply npx @signallayer/mcp-server with no cloning required.

Safety & Validation

Every generated query passes through multiple safety checks:

CheckDescription
Read-only enforcementSELECT only by default. Write ops require explicit allow_write: true
Dangerous statement blockingDROP, TRUNCATE, ALTER, CREATE, GRANT always blocked
Injection detectionDetects common SQL injection patterns (UNION injection, command execution)
Multi-statement preventionOnly single SQL statements allowed (no semicolon stacking)
ParameterizationUser values use $1, $2 params — never interpolated into SQL
Row limitingAutomatic LIMIT clause when not specified (default: 100)
System table flaggingAccess to pg_catalog/information_schema is flagged

Pricing

Free Tier

$0/mo

500 queries/day · 30/min · 3 API keys · Read-only

Pro

$49/mo

10,000 queries/day · 120/min · Unlimited keys · Write ops · Priority support