diff --git a/README.md b/README.md index 2e43071..799fb07 100644 --- a/README.md +++ b/README.md @@ -48,16 +48,29 @@ MySQL/SQL Server, mixed naming styles and singular/plural table names, columns that look like keys with no ref, isolated tables, missing timestamps, unused enums and wide tables. `GET /api/v1/rules` is the list. -## Ask (pay as you go) - -A person asks a database question in plain words at `/ask/` and -gets an answer grounded in the engine: the schema's summary, every review -finding and exact SQL go into the prompt, and the checker's exact output is -added to convert and review answers. 5 cents per answered question from a -prepaid balance; failures are free. Top up $5/$10/$20 through CoinPay's -hosted checkout (no subscriptions). Everything asked stays on the page, -newest first. Models: c0mpute first through `@profullstack/ai-providers`, -OpenAI/Anthropic fallback when keys are set. +## The DBA agent (Ask, pay as you go) + +A DBA as a service: a database question in plain words gets an answer +grounded in the engine. The schema's summary, every review finding and exact +SQL go into the prompt, and the checker's exact output is added to convert and +review answers. 5 cents per answered question from a prepaid balance; failures +are free. Top up $5/$10/$20 through CoinPay's hosted checkout (no +subscriptions). + +- **People:** the "Ask the DBA agent" button on the home page asks about the + playground's schema in place; `/ask` is the full page with every past answer. + Anyone gets a personal link there (`POST /api/signup`, 5 per IP per hour, + `SIGNUP_CREDIT_CENTS` free credit, default 0). +- **Agents:** `POST /api/ask` + `GET /api/ask/` with + `Authorization: Bearer `, or the MCP tools `ask_dba` / `ask_dba_result` + with the same header on the `/mcp` connection. +- **Models:** c0mpute first through `@profullstack/ai-providers`. OpenAI or + Claude is offered for a question only when its price is at least + `ASK_MIN_MARGIN` (2) x the worst-case cost of the paid call (prompt at 3 + chars/token, all 2,500 output tokens, plus any paid attempt that already + failed). Rates per million tokens: `AI_COST_OPENAI_IN/OUT` (0.25/2, + gpt-5-mini) and `AI_COST_ANTHROPIC_IN/OUT` (0.10/0.50, claude-haiku-5-5); + set them when changing `AI_OPENAI_MODEL` / `AI_ANTHROPIC_MODEL`. Operator (`ADMIN_KEY` from the vault): @@ -99,8 +112,6 @@ https://dbml.db.pit.world. - Human review marketplace: let an agent request a paid review of its schema by a human DBA through c0mpute.com/humans. Not built. -- Optional AI review on c0mpute (off unless a free c0mpute route is available; - no paid AI providers). - Diagram rendering (SVG) of a schema. ## Credits and license diff --git a/package.json b/package.json index eae8925..849242c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dbml.db", - "version": "0.2.0", + "version": "0.3.0", "private": true, "description": "DBML as a service for AI agents: validate, parse, review and convert database schemas over an HTTP API, MCP server and CLI.", "type": "module", diff --git a/src/app.js b/src/app.js index 166dc7b..69bf044 100644 --- a/src/app.js +++ b/src/app.js @@ -192,6 +192,12 @@ export function llmsTxt() { Invalid DBML answers 422 with errors carrying line and column (validate answers 200 with valid:false). Inputs up to ${MAX_INPUT_BYTES / 1024} KiB. ${process.env.RATE_LIMIT_PER_MIN || 60} requests/minute per caller. +## DBA agent (paid, pay as you go) +A plain-words answer to a database question, grounded in the engine's exact findings and SQL. ${process.env.ASK_PRICE_CENTS || 5} cents per answer from a prepaid balance; failures are free. +Token: get a personal link at ${SITE}ask (token = the part after /ask/), top up there. Send "Authorization: Bearer ". +- POST /api/ask {question, schema?} -> 202 {id}; GET /api/ask/ -> {status: working|answered|failed, answer, error} +- MCP: ask_dba {question, schema?, wait_seconds?}, ask_dba_result {id} (same Bearer header on /mcp) + ## Review rules ${RULES.map((r) => `- ${r.id} (${r.severity}): ${r.description}`).join('\n')} diff --git a/src/ask.js b/src/ask.js index 21f28f6..8a63304 100644 --- a/src/ask.js +++ b/src/ask.js @@ -6,11 +6,13 @@ * findings in an answer are exact, not model guesses. * * Models: @profullstack/ai-providers, c0mpute first, OpenAI/Anthropic - * alternating as fallback when keys are configured. + * alternating as fallback when keys are configured. A paid provider is only + * offered for a question when what the asker pays covers at least + * ASK_MIN_MARGIN (default 2) times its worst-case cost (see paidAllowed). */ import { createAiProviders } from '@profullstack/ai-providers'; import { fromSql, review, summarize, toSql, validate } from './dbml.js'; -import { failQuestion, finishQuestion } from './store.js'; +import { failQuestion, finishQuestion, startQuestion, workingQuestion } from './store.js'; export const PRICE_CENTS = () => Number(process.env.ASK_PRICE_CENTS || 5); const MAX_QUESTION = 4000; @@ -139,14 +141,41 @@ export function buildPrompt(question, facts) { return parts.join('\n\n'); } -/** USD per million tokens, by provider; env overrides. c0mpute bills per job, logged as 0 until priced. */ -function rates(provider) { +/** + * USD per million tokens, by provider; env overrides. c0mpute bills per job, + * logged as 0 until priced. Defaults: gpt-5-mini, claude-haiku-5-5 (the + * router's default fallback models). + */ +export function rates(provider) { const env = process.env; - const d = { c0mpute: [0, 0], openai: [0.25, 2], anthropic: [1, 5] }[provider] || [0, 0]; + const d = { c0mpute: [0, 0], openai: [0.25, 2], anthropic: [0.1, 0.5] }[provider] || [0, 0]; const up = String(provider || '').toUpperCase(); return [Number(env[`AI_COST_${up}_IN`] ?? d[0]), Number(env[`AI_COST_${up}_OUT`] ?? d[1])]; } +export const MAX_TOKENS = 2500; +const PAID = ['openai', 'anthropic']; + +/** + * Worst-case cost in micro-USD of one call: the prompt counted at 3 chars a + * token (code tokenizes denser than prose's 4) and every allowed output token. + */ +export function worstCaseMicroUsd(provider, promptChars, maxTokens = MAX_TOKENS) { + const [rin, rout] = rates(provider); + return Math.ceil(promptChars / 3) * rin + maxTokens * rout; +} + +/** + * The paid providers this question may use: price paid must be at least + * ASK_MIN_MARGIN x (paid spend so far on it + this call's worst case). + * c0mpute is always allowed. + */ +export function paidAllowed({ priceCents, promptChars, spentMicroUsd = 0, maxTokens = MAX_TOKENS }) { + const margin = Number(process.env.ASK_MIN_MARGIN || 2); + const paidMicroUsd = priceCents * 10000; + return PAID.filter((p) => margin * (spentMicroUsd + worstCaseMicroUsd(p, promptChars, maxTokens)) <= paidMicroUsd); +} + /** * Drop a model's visible reasoning. Qwen3 can stream its thinking as plain * text ending in ; keep what follows. Text that is only reasoning @@ -166,10 +195,13 @@ export function stripThink(t) { * (its model service exits, or the network is busy), and the router treats * that as final for the call. The retry asks for the other live 4B model. */ -async function answerWithRetry(question, facts, t0) { +async function answerWithRetry(question, facts, t0, priceCents) { const budget = Number(process.env.ASK_BUDGET_MS || 170000); const alternates = (process.env.ASK_RETRY_MODELS || 'qwen3:4b,huihui_ai/qwen3.5-abliterated:4b').split(',').map((m) => m.trim()).filter(Boolean); const user = buildPrompt(question, facts); + const promptChars = SYSTEM.length + user.length; + // Paid spend on this question so far, counted at worst case for calls that failed. + let spent = 0; let last; const delay = Number(process.env.ASK_RETRY_DELAY_MS ?? 8000); const maxAttempts = Number(process.env.ASK_MAX_ATTEMPTS || 8); @@ -177,28 +209,35 @@ async function answerWithRetry(question, facts, t0) { if (attempt > 0) await new Promise((res) => setTimeout(res, delay)); const left = budget - (Date.now() - t0); if (attempt > 0 && left < 45000) break; + const only = ['c0mpute', ...paidAllowed({ priceCents, promptChars, spentMicroUsd: spent })]; + let used = null; try { const r = await getAi(attempt > 0).streamText({ system: SYSTEM, user, - maxTokens: 2500, + only, + maxTokens: MAX_TOKENS, temperature: 0.2, feature: 'ask', timeoutMs: Math.max(30000, left), ...(attempt > 0 ? { models: { c0mpute: alternates[(attempt - 1) % alternates.length] } } : {}), }); + used = r.provider; if (stripThink(r.text)) return r; last = new Error('no answer text (reasoning only or empty)'); } catch (e) { last = e; + // A paid provider may have billed before failing: count the worst case. + for (const a of e?.attempts || []) if (PAID.includes(a.provider)) spent += worstCaseMicroUsd(a.provider, promptChars); console.error('ask attempt failed', attempt, String(e?.message || e).slice(0, 200)); } + if (used && PAID.includes(used)) spent += worstCaseMicroUsd(used, promptChars); } throw last || new Error('no answer'); } /** Run one question to the end. Never throws; records the outcome. */ -export async function runAsk(questionId, question, schemaText) { +export async function runAsk(questionId, question, schemaText, priceCents = PRICE_CENTS()) { const t0 = Date.now(); let facts; try { @@ -208,7 +247,7 @@ export async function runAsk(questionId, question, schemaText) { } const exact = facts.exact.join('\n\n'); try { - const r = await answerWithRetry(question, facts, t0); + const r = await answerWithRetry(question, facts, t0, priceCents); const text = stripThink(r.text); const [rin, rout] = rates(r.provider); const inTok = r.usage?.inputTokens ?? null; @@ -221,7 +260,7 @@ export async function runAsk(questionId, question, schemaText) { outputTokens: outTok, costMicroUsd: Math.round((inTok || 0) * rin + (outTok || 0) * rout), ms: Date.now() - t0, - priceCents: PRICE_CENTS(), + priceCents, }); } catch (e) { console.error('ask failed', questionId, String(e?.message || e).slice(0, 300)); @@ -232,3 +271,20 @@ export async function runAsk(questionId, question, schemaText) { }); } } + +/** + * Start a question for an account: the checks every surface (page, API, MCP) + * shares. Returns {id} or {error, status}. The answer runs in the background. + */ +export function startAsk(account, question, schema) { + const q = String(question ?? ''); + const s = schema == null ? '' : String(schema); + const bad = checkAskInput(q, s); + if (bad) return { error: bad, status: 400 }; + const price = PRICE_CENTS(); + if (account.balance_cents < price) return { error: 'Your balance is too low to ask. Please add money first. You were not charged.', status: 402 }; + if (workingQuestion(account.id)) return { error: 'Still working on your last question. Please wait for it to finish.', status: 409 }; + const id = startQuestion(account.id, q.trim(), s); + const done = runAsk(id, q, s, price); + return { id, done }; +} diff --git a/src/askpage.js b/src/askpage.js index 2fdc5fc..b33e235 100644 --- a/src/askpage.js +++ b/src/askpage.js @@ -137,7 +137,7 @@ export function askPage({ account, questions, priceCents, notice = '', topups = const body = `
You are signed in as ${h(account.name)}. Balance: ${dollars(account.balance_cents)}. Each question costs ${priceWords(priceCents)}.${low ? ' Your balance is too low to ask. Add money below.' : ''}
${notice ? `
${h(notice)}
` : ''} -

Ask a database question

+

Ask the DBA agent

For example: "What is wrong with my schema?" or "Convert this to MySQL."

@@ -155,17 +155,42 @@ ${topups ? `

Add money

You pay on the CoinPay page, with crypto or PayPal. Your balance goes up when the payment arrives. Nothing renews by itself.

` : ''} -
Keep this page bookmarked: the link is your sign-in. If you lose it, ask Anthony for a new one. About dbml.db
+
Keep this page bookmarked: the link is your sign-in and the only way back to your balance and answers. About dbml.db
`; return shell(`Ask: ${account.name}`, body, JS); } export function askSignedOut() { - const body = `

Ask a database question

-

To ask a question you need your personal link. It signs you in by itself, no password.

-

If you do not have it, ask Anthony to send it to you, then bookmark that page.

+ const body = `

Ask the DBA agent

+

Ask anything about your database schema in plain words. The AI DBA agent answers from an exact check of your schema, so table names, findings and SQL are real, not guesses.

+

You need a personal link: it signs you in by itself, no password. Get one here, then bookmark the page it opens.

+ + + + +
+
+

Already have a link? Open it again and you are back.

About dbml.db

`; - return shell('Ask', body, ''); + const js = ``; + return shell('Ask', body, js); } function shell(title, body, js) { diff --git a/src/askroutes.js b/src/askroutes.js index 88a2989..89a655a 100644 --- a/src/askroutes.js +++ b/src/askroutes.js @@ -3,6 +3,7 @@ * * GET /ask/ personal link: signs in (cookie) and shows the page * GET /ask the page for a signed-in browser + * POST /api/signup {name?} -> {link}: a new account and personal link (self-serve) * GET /api/me name, balance, price, history, last schema * POST /api/ask {question, schema} -> {id}; answered in the background * GET /api/ask/ {status, answer, error, elapsed_ms} @@ -17,7 +18,7 @@ import { timingSafeEqual, createHash } from 'node:crypto'; import { getCookie, setCookie } from 'hono/cookie'; import { CoinPay, readWebhook, verifyWebhook } from '@profullstack/coinpay-onboard'; -import { checkAskInput, PRICE_CENTS, runAsk } from './ask.js'; +import { PRICE_CENTS, startAsk } from './ask.js'; import { askPage, askSignedOut } from './askpage.js'; import { SITE } from './pages.js'; import { @@ -73,6 +74,19 @@ function adminOk(c) { const link = (token) => `${SITE}ask/${token}`; +/** New accounts per caller IP (first X-Forwarded-For hop) per hour. */ +const signups = new Map(); +function signupAllowed(c) { + const ip = (c.req.header('x-forwarded-for') || '').split(',')[0].trim() || 'local'; + const now = Date.now(); + const hits = (signups.get(ip) || []).filter((t) => now - t < 3600_000); + if (hits.length >= Number(process.env.SIGNUPS_PER_HOUR || 5)) return false; + hits.push(now); + signups.set(ip, hits); + if (signups.size > 10000) signups.clear(); + return true; +} + export function mountAsk(app) { app.get('/ask', (c) => { const account = me(c); @@ -88,6 +102,16 @@ export function mountAsk(app) { return renderFor(c, account); }); + app.post('/api/signup', async (c) => { + if (me(c)) return c.json({ error: 'You already have an account in this browser.', signed_in: true }, 409); + if (!signupAllowed(c)) return c.json({ error: 'Too many new accounts from here. Please try again in an hour.' }, 429); + const b = await c.req.json().catch(() => ({})); + const name = String(b?.name || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60) || 'dbml.db user'; + const { account, token } = createAccount(name, Math.max(0, Math.trunc(Number(process.env.SIGNUP_CREDIT_CENTS || 0)))); + remember(c, token); + return c.json({ link: link(token), name: account.name, balance_cents: account.balance_cents, price_cents: PRICE_CENTS() }, 201); + }); + app.get('/api/me', (c) => { const account = me(c); if (!account) return c.json({ error: 'not signed in' }, 401); @@ -109,19 +133,9 @@ export function mountAsk(app) { } catch { return c.json({ error: 'Something went wrong sending the question. Please try again.' }, 400); } - const question = String(body?.question ?? ''); - const schema = body?.schema == null ? '' : String(body.schema); - const bad = checkAskInput(question, schema); - if (bad) return c.json({ error: bad }, 400); - const price = PRICE_CENTS(); - if (account.balance_cents < price) { - return c.json({ error: 'Your balance is too low to ask. Please add money below. You were not charged.' }, 402); - } - if (workingQuestion(account.id)) { - return c.json({ error: 'Still working on your last question. Please wait for it to finish.' }, 409); - } - const id = startQuestion(account.id, question.trim(), schema); - void runAsk(id, question, schema); + const r = startAsk(account, body?.question, body?.schema); + if (r.error) return c.json({ error: r.error }, r.status); + const { id } = r; return c.json({ id, status: 'working' }, 202); }); diff --git a/src/mcp.js b/src/mcp.js index 4fa48f8..2b2f285 100644 --- a/src/mcp.js +++ b/src/mcp.js @@ -4,6 +4,8 @@ import { z } from 'zod'; import { fromSql, format, InputError, parse, review, RULES, SQL_EXPORT_DIALECTS, SQL_IMPORT_DIALECTS, summarize, toSql, validate, } from './dbml.js'; +import { PRICE_CENTS, startAsk } from './ask.js'; +import { accountByToken, getAccount, getQuestion } from './store.js'; import { SYNTAX } from './syntax.js'; import { VERSION } from './version.js'; @@ -22,11 +24,25 @@ const run = (fn) => async (args) => { export const TOOL_NAMES = [ 'validate_dbml', 'parse_dbml', 'summarize_dbml', 'review_dbml', 'format_dbml', 'dbml_to_sql', 'sql_to_dbml', 'list_review_rules', 'dbml_syntax', + 'ask_dba', 'ask_dba_result', ]; +const NO_TOKEN = 'ask_dba is paid (pay as you go from a prepaid balance). Send your dbml.db personal token as "Authorization: Bearer " on the MCP connection. Get one at https://dbml.db.pit.world/ask (the part of the link after /ask/).'; + +function questionView(q, accountId) { + return { + id: q.id, + status: q.status, + answer: q.answer, + error: q.error, + charged_cents: q.charged_cents, + balance_cents: getAccount(accountId)?.balance_cents ?? null, + }; +} + const dbmlArg = z.string().describe('The schema in DBML (https://dbml.dbdiagram.io/docs)'); -export function buildMcpServer() { +export function buildMcpServer({ token = null } = {}) { const server = new McpServer( { name: 'dbml.db', version: VERSION }, { @@ -34,7 +50,8 @@ export function buildMcpServer() { 'dbml.db builds, validates, converts and reviews database schemas written in DBML. ' + 'Typical loop: write DBML (dbml_syntax has the cheat sheet), validate_dbml until valid (errors carry line/column), ' + 'review_dbml and fix the findings, then dbml_to_sql for the target database. sql_to_dbml imports existing DDL. ' + - 'All tools are deterministic and free; no AI model is called.', + 'Those tools are deterministic and free; no AI model is called. ' + + 'ask_dba is the paid DBA agent: a plain-words answer to a database question, grounded in the same engine (needs a Bearer token and a balance).', }, ); @@ -86,12 +103,40 @@ export function buildMcpServer() { inputSchema: {}, }, run(() => SYNTAX)); + server.registerTool('ask_dba', { + description: `Ask the DBA agent a database question about a schema (DBML or SQL DDL): what is wrong, how to index, how to migrate, SQL for a dialect. The answer is written by an AI model given the review engine's exact findings and SQL, with that exact output appended. Paid: ${PRICE_CENTS()} cents per answer from the token's prepaid balance; failures are free. Waits up to wait_seconds, then returns status "working" and an id for ask_dba_result.`, + inputSchema: { + question: z.string().describe('The question, in plain words'), + schema: z.string().optional().describe('DBML or SQL CREATE TABLE statements'), + wait_seconds: z.number().int().min(0).max(170).default(150).describe('How long to wait for the answer'), + }, + }, async ({ question, schema, wait_seconds: wait }) => { + const account = accountByToken(token); + if (!account) return fail(NO_TOKEN); + const r = startAsk(account, question, schema); + if (r.error) return fail(r.error); + await Promise.race([r.done, new Promise((res) => setTimeout(res, wait * 1000).unref?.())]); + return text(questionView(getQuestion(r.id), account.id)); + }); + + server.registerTool('ask_dba_result', { + description: 'The status and answer of an ask_dba question by id.', + inputSchema: { id: z.string() }, + }, async ({ id }) => { + const account = accountByToken(token); + if (!account) return fail(NO_TOKEN); + const q = getQuestion(id); + if (!q || q.account_id !== account.id) return fail('not found'); + return text(questionView(q, account.id)); + }); + return server; } /** MCP over streamable HTTP, stateless, JSON responses. */ export async function handleMcp(request) { - const server = buildMcpServer(); + const m = /^Bearer\s+(\S+)$/i.exec(request.headers.get('authorization') || ''); + const server = buildMcpServer({ token: m ? m[1] : null }); const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); await server.connect(transport); try { diff --git a/src/pages.js b/src/pages.js index abcc286..d9d1d27 100644 --- a/src/pages.js +++ b/src/pages.js @@ -72,6 +72,10 @@ button.primary{background:var(--acc);color:#0b0d0a;border-color:var(--acc);font- table{border-collapse:collapse;width:100%;font-size:14px}td,th{border-bottom:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top} .sev-error{color:var(--err)}.sev-warning{color:var(--warn)}.sev-info{color:var(--info)} .tablewrap{overflow-x:auto} +.dba{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px;margin:18px 0} +.dba textarea{min-height:90px;font-family:inherit;font-size:16px} +.dba .who{color:var(--mute);margin:6px 0} +#dbaout{white-space:pre-wrap;min-height:0;max-height:none} .askbig{display:inline-block;margin:14px 0 4px;padding:18px 28px;font-size:24px;font-weight:800;background:var(--acc);color:#0b0d0a;border-radius:14px;text-decoration:none} `; @@ -180,16 +184,87 @@ const PLAYGROUND_JS = ``; +const priceText = () => { + const c = Number(process.env.ASK_PRICE_CENTS || 5); + return c < 100 ? `${c} cents` : `$${(c / 100).toFixed(2)}`; +}; + export async function homePage() { const body = `

DBML for AI agents

Build, validate, review and convert database schemas written in DBML. One HTTP API, an MCP server at /mcp and a CLI, so an agent can model a schema, get errors with line and column, fix what the review finds, and ship SQL for Postgres, MySQL, SQL Server or Oracle. Free, no account.

-

Ask a question about your schema

-

Ask in plain words and get an answer checked against your actual schema. Pay as you go: 5 cents a question, with a personal link and a prepaid balance.

+

Ask the DBA agent

+

A DBA as a service: an AI agent that answers database questions in plain words, grounded in an exact check of your schema (the same review engine as the API), so table names, findings and SQL are real. Pay as you go: ${h(priceText())} a question from a prepaid balance, no subscription. Agents can ask it too, over the API and MCP.

Validate + parse

Syntax and semantic errors with line/column, or a JSON model of every table, column, index, ref and enum.

@@ -211,11 +286,27 @@ export async function homePage() { +
Press Review.
+
+

Ask the DBA agent

+

Ask about the schema in the playground above: what is wrong with it, how to index it, how to migrate it, the SQL for your database. ${h(priceText())} per answer; a failed answer is free.

+

Checking your account...

+ +
+ + + + + +
+ +
+

Connect an agent

{
   "mcpServers": {
@@ -253,8 +344,16 @@ ${endpoint('GET', '/api/v1/syntax', '', 'DBML cheat sheet (text)')}
 

An invalid schema answers 422 with errors: [{message, line, column, end_line, end_column, code}]. A bad request (missing field, unknown dialect) answers 400.

curl -s ${h(SITE)}api/v1/dbml-to-sql?dialect=mysql --data-binary @schema.dbml -H 'content-type: text/plain'
+

DBA agent (paid)

+

A plain-words answer to a database question, written by an AI model that is handed the engine's exact summary, findings and SQL first. ${h(priceText())} per answer from a prepaid balance; failures are free. Get a personal token at /ask (the part of the link after /ask/), add money there, then:

+
curl -s ${h(SITE)}api/ask -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \\
+  -d '{"question":"What would you index?","schema":"Table users { id int [pk] }"}'      # {id}
+curl -s ${h(SITE)}api/ask/$ID -H "authorization: Bearer $TOKEN"                        # {status, answer}
+

Over MCP: send the same Authorization: Bearer header on the connection and call ask_dba (waits for the answer) or ask_dba_result.

+
claude mcp add --transport http dbml ${h(SITE)}mcp --header "Authorization: Bearer $TOKEN"
+

MCP server

-

Streamable HTTP (stateless, JSON responses) at ${h(SITE)}mcp. No key. Tools:

+

Streamable HTTP (stateless, JSON responses) at ${h(SITE)}mcp. No key, except for the paid ask_dba tools. Tools:

    ${TOOL_NAMES.map((t) => `
  • ${t}
  • `).join('')}
claude mcp add --transport http dbml ${h(SITE)}mcp

Over stdio (for clients without HTTP transport): npx -y @profullstack/dbml mcp. It proxies to this server.

diff --git a/test/ask.test.js b/test/ask.test.js index 9c12fa7..f1f7938 100644 --- a/test/ask.test.js +++ b/test/ask.test.js @@ -25,9 +25,11 @@ Table orders { let calls = 0; let mode = 'ok'; +let lastReq = null; setAi({ async streamText(req) { calls++; + lastReq = req; if (mode === 'fail') throw new Error('no node'); return { text: `hmmThe orders.user_id column needs an index. (${req.user.includes('[unindexed_foreign_key]') ? 'grounded' : 'not grounded'})`, provider: 'c0mpute', model: 'qwen3:4b', usage: { inputTokens: 100, outputTokens: 20, estimated: true } }; }, @@ -176,6 +178,8 @@ test('page detection matches the server rule', () => { test('home page has the Ask button and the from-sql guard', async () => { const html = await (await app.request('/')).text(); assert.match(html, /href="\/ask"/); + assert.match(html, /id="dba"/); + assert.match(html, /id="todba"/); assert.match(html, /That's DBML\. Paste SQL/); assert.match(html, /Load an SQL example/); }); @@ -195,3 +199,62 @@ test('model reasoning is stripped; reasoning-only text is not an answer', async assert.equal(stripThink("Okay, let's tackle this question. The user wants"), ''); assert.equal(stripThink('Your schema is missing a primary key.'), 'Your schema is missing a primary key.'); }); + +test('paid fallback only when the price covers 2x its worst-case cost', async () => { + const { paidAllowed, worstCaseMicroUsd } = await import('../src/ask.js'); + // 5 cents = 50,000 micro-USD. gpt-5-mini worst case on a 9k-char prompt ~ 5.75k. + assert.deepEqual(paidAllowed({ priceCents: 5, promptChars: 9000 }), ['openai', 'anthropic']); + // 1 cent = 10,000: OpenAI (2 x ~5.75k) no longer fits, Haiku 5.5 (2 x ~1.55k) does. + assert.deepEqual(paidAllowed({ priceCents: 1, promptChars: 9000 }), ['anthropic']); + assert.deepEqual(paidAllowed({ priceCents: 0, promptChars: 9000 }), []); + // Paid spend already burned on this question counts against the margin. + const w = worstCaseMicroUsd('openai', 9000); + assert.equal(paidAllowed({ priceCents: 5, promptChars: 9000, spentMicroUsd: 25000 - w + 1 }).includes('openai'), false); + // A pricier model configured by env is guarded too. + process.env.AI_COST_ANTHROPIC_IN = '4'; + process.env.AI_COST_ANTHROPIC_OUT = '20'; + assert.deepEqual(paidAllowed({ priceCents: 5, promptChars: 9000 }), ['openai']); + delete process.env.AI_COST_ANTHROPIC_IN; + delete process.env.AI_COST_ANTHROPIC_OUT; +}); + +test('each model call carries the allowed provider list, c0mpute first', async () => { + await admin(`/admin/api/accounts/${accountId}/credit`, { cents: 10 }); + const r = await askAndWait('What is wrong?', SCHEMA); + assert.equal(r.status, 'answered'); + assert.deepEqual(lastReq.only, ['c0mpute', 'openai', 'anthropic']); +}); + +test('self-serve signup: a personal link, cookie, no free credit by default, rate limited', async () => { + const r = await app.request('/api/signup', { method: 'POST', headers: { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9' }, body: '{"name":"Dana"}' }); + assert.equal(r.status, 201); + const j = await r.json(); + assert.match(j.link, /\/ask\/[A-Za-z0-9_-]{40,}$/); + assert.equal(j.balance_cents, 0); + const cookie = r.headers.get('set-cookie').split(';')[0]; + const me = await (await app.request('/api/me', { headers: { cookie } })).json(); + assert.equal(me.name, 'Dana'); + const ask = await app.request('/api/ask', { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: '{"question":"hi"}' }); + assert.equal(ask.status, 402); + for (let i = 0; i < 4; i++) await app.request('/api/signup', { method: 'POST', headers: { 'x-forwarded-for': '203.0.113.9' }, body: '{}' }); + const limited = await app.request('/api/signup', { method: 'POST', headers: { 'x-forwarded-for': '203.0.113.9' }, body: '{}' }); + assert.equal(limited.status, 429); +}); + +test('MCP ask_dba: needs a token, answers and charges with one', async () => { + const call = (args, auth) => app.request('/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...(auth ? { authorization: `Bearer ${auth}` } : {}) }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'ask_dba', arguments: args } }), + }).then((r) => r.json()); + const anon = await call({ question: 'hi' }); + assert.equal(anon.result.isError, true); + assert.match(anon.result.content[0].text, /Bearer/); + await admin(`/admin/api/accounts/${accountId}/credit`, { cents: 10 }); + const before = getAccount(accountId).balance_cents; + const ok = await call({ question: 'What is wrong?', schema: SCHEMA, wait_seconds: 10 }, token); + const out = JSON.parse(ok.result.content[0].text); + assert.equal(out.status, 'answered'); + assert.match(out.answer, /orders\.user_id/); + assert.equal(getAccount(accountId).balance_cents, before - 5); +});