Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ Available metrics:
| `mcp_http_requests_total{method, status}` | Counter | HTTP requests by method and status code |
| `mcp_rate_limit_exceeded_total{type}` | Counter | Rate limit rejections (global/per_ip/per_token) |
| `mcp_auth_validations_total{result}` | Counter | Auth validations (success/failure/cache_hit) |
| `mcp_sql_failures_total{tool, reason}` | Counter | Failed `query_sql`/`execute_sql` calls (e.g. `subquery`, `join`, `wrong_statement_update`, `unknown_name`, `seatable_error`) |
| `mcp_sql_failures_total{tool, reason}` | Counter | Failed `query_sql`/`execute_sql` calls (e.g. `subquery`, `join`, `wrong_statement_update`, `unknown_name`, `invalid_value`, `seatable_error`) |
| `mcp_active_sessions` | Gauge | Currently active HTTP sessions |
| `mcp_active_connections` | Gauge | Currently active connections |
| `seatable_api_requests_total{operation, status}` | Counter | SeaTable API calls by operation |
Expand All @@ -302,6 +302,7 @@ AI models often write MySQL- or PostgreSQL-style SQL that SeaTable does not acce
| 1. Constructs SeaTable SQL never supports are rejected before the request | `IN (SELECT …)`, `JOIN`, `UNION`, `WITH`, `OVER (…)`, two statements | `subquery`, `join`, `set_operation`, `cte`, `window_function`, `multiple_statements` |
| 2. Wrong statement type for the tool | `UPDATE` sent to `query_sql`, `SELECT` sent to `execute_sql`, `DROP` | `wrong_statement_<kind>`, e.g. `wrong_statement_update`, `wrong_statement_other` |
| 3. SeaTable rejects the statement | table or column name that doesn't exist | `unknown_name`, with a hint to call `get_schema` |
| | value that doesn't fit the column, e.g. an unknown select option or `15.01.2026` as a date | `invalid_value`, with a hint on options and date format |
| | unknown function, syntax error | `seatable_error`, plus `hints` if MySQL function names were used |

In every case the model gets an error message that tells it how to restructure the query, e.g. *"Run the inner SELECT on its own first, then pass its values into the outer query"* or *"use mid(str, pos, len) instead of SUBSTRING"*.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@seatable/mcp-seatable",
"version": "1.9.1",
"version": "1.9.2",
"type": "module",
"license": "MIT",
"mcpName": "io.github.seatable/seatable",
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export class SeaTableMCPServer {
'Terminology: use "base" (not database), "table" (not sheet), "row" (not record/entry), "column" (not field), "link" (not relation/relationship).',
'Views are not supported. All tools return all columns. Filter and sort client-side using find_rows or query_sql.',
'Prefer SQL for reading, updating, and deleting data: query_sql for SELECT, execute_sql for UPDATE...WHERE and DELETE...WHERE. One SQL call is much more efficient than fetching row IDs first.',
'Row limits: a SELECT returns only 100 rows unless you add LIMIT (max 10,000), and list_rows returns 100 rows per page by default. Add LIMIT whenever you need all rows, e.g. to count, compare or sum them yourself. A result cut at the default carries a "notice" field.',
'Row limits: a SELECT returns only 100 rows unless you add LIMIT (max 10,000), so LIMIT 100 is no better than none; use LIMIT 10000 to read all rows, and prefer COUNT, SUM and GROUP BY over reading rows to count or sum them yourself. list_rows returns 100 rows per page by default. A result that may be cut carries a "notice" field: follow it before answering.',
'SeaTable SQL is a restricted dialect: no subqueries, no WITH, no UNION, no JOIN keyword, no window functions. Keep each query simple and answer multi-step questions with several queries, passing values from one result into the next via ? parameters.',
'Link columns can\'t be a join condition. GROUP BY the link column, filter with `Link` = \'display value\', or use the link column on the other table (SeaTable creates one on both sides), e.g. WHERE `Orders` IS NULL for rows without linked rows.',
'If a SQL call fails, read the error: it says what is not supported and how to restructure the query. Do not retry with similar syntax.',
Expand Down
1 change: 1 addition & 0 deletions src/mcp/tools/executeSql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ ${SQL_SYNTAX_RULES}

UPDATE limitations:
- SET only accepts literal values (strings, numbers, booleans). No functions (date(), now(), upper()…) and no expressions (Amount + 10) allowed.
- Select columns accept only existing options, spelled exactly (get_schema lists them). Dates need the format YYYY-MM-DD.
- Columns not updatable via SQL: image, file, formula, link, link-formula, geolocation, auto-number, digital-sign, button. Use update_rows or link_rows for those.

INSERT only works with Big Data storage enabled (Enterprise). For non-archived tables, use append_rows instead.`,
Expand Down
12 changes: 4 additions & 8 deletions src/mcp/tools/querySql.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { z } from 'zod'

import { DEFAULT_SQL_LIMIT, hasLimit, runSql, SQL_SYNTAX_RULES } from './sqlCheck.js'
import { runSql, SQL_SYNTAX_RULES, truncationNotice } from './sqlCheck.js'
import { ToolRegistrar } from './types.js'
import { cleanSqlMetadata } from './utils.js'

Expand All @@ -19,7 +19,7 @@ export const registerQuerySql: ToolRegistrar = (server, { client, getInputSchema
${SQL_SYNTAX_RULES}

SELECT rules:
- Returns only 100 rows unless you add LIMIT. Add LIMIT (up to 10,000) whenever you need all rows, e.g. to count, compare or sum them yourself.
- Returns only 100 rows unless you add LIMIT, so LIMIT 100 is no better than none. To read all rows use LIMIT 10000. Prefer COUNT, SUM and GROUP BY over reading rows to count or sum them yourself.
- Aliases (AS) can be used in GROUP BY, HAVING, ORDER BY — but NOT in WHERE.
- Joins: FROM \`T1\`, \`T2\` WHERE \`T1\`.\`col\` = \`T2\`.\`col\` (inner joins only).
- Link columns can't be a join condition: comparing them with another column never matches. Instead GROUP BY the link column (one row per linked row, shown by its display value), filter with \`Link\` = 'display value', or use the link column on the other table (SeaTable creates one on both sides), e.g. WHERE \`Orders\` IS NULL for rows without linked rows.
Expand All @@ -31,16 +31,12 @@ If a query is rejected, find_rows offers client-side filtering as an alternative
async (args: unknown) => {
const { sql, parameters } = InputSchema.parse(args)
const result = await runSql('query_sql', sql, () => client.querySql(sql, parameters))
// SeaTable cuts a SELECT without LIMIT at 100 rows and doesn't say so.
// Models then count, compare or sum an incomplete result without noticing.
const truncated = !hasLimit(sql) && result.results.length === DEFAULT_SQL_LIMIT
const notice = truncationNotice(sql, result.results.length)
return {
content: [{
type: 'text',
text: JSON.stringify({
...(truncated && {
notice: `Only the first ${DEFAULT_SQL_LIMIT} rows were returned (SeaTable's default without LIMIT). The result is probably incomplete: repeat the query with LIMIT (up to 10,000) before counting, comparing or summing rows.`,
}),
...(notice && { notice }),
metadata: cleanSqlMetadata(result.metadata),
results: result.results,
}),
Expand Down
48 changes: 40 additions & 8 deletions src/mcp/tools/sqlCheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,29 @@ export function statementKind(sql: string): StatementKind {
/** Rows SeaTable returns for a SELECT without LIMIT. It does not say when it cut. */
export const DEFAULT_SQL_LIMIT = 100

export function hasLimit(sql: string): boolean {
return /\blimit\s+\d/i.test(stripLiterals(sql))
const MAX_SQL_LIMIT = 10000

/** The row count a statement asks for; LIMIT n and LIMIT offset, n. */
export function sqlLimit(sql: string): number | undefined {
const match = /\blimit\s+(?:\d+\s*,\s*)?(\d+)/i.exec(stripLiterals(sql))
return match ? Number(match[1]) : undefined
}

/**
* A warning when a SELECT may have been cut. Models count, compare or sum such a
* result without noticing: SeaTable doesn't report it, and they often pick
* LIMIT 100 themselves. A smaller LIMIT is a deliberate top-N, so it stays quiet.
*/
export function truncationNotice(sql: string, rowCount: number): string | undefined {
const limit = sqlLimit(sql)
if (limit === undefined) {
if (rowCount !== DEFAULT_SQL_LIMIT) return undefined
return `Only the first ${DEFAULT_SQL_LIMIT} rows were returned (SeaTable's default without LIMIT). The result is probably incomplete: repeat the query with LIMIT (up to ${MAX_SQL_LIMIT.toLocaleString('en-US')}) before counting, comparing or summing rows.`
}
if (limit < DEFAULT_SQL_LIMIT || rowCount !== Math.min(limit, MAX_SQL_LIMIT)) return undefined
return rowCount < MAX_SQL_LIMIT
? `The result has exactly as many rows as LIMIT allows (${rowCount}), so it may be incomplete. Raise LIMIT (up to ${MAX_SQL_LIMIT.toLocaleString('en-US')}) before counting, comparing or summing rows.`
: `The result reached the maximum of ${MAX_SQL_LIMIT.toLocaleString('en-US')} rows per query, so it may be incomplete. Read further with OFFSET, or let SQL do the work with COUNT, SUM and GROUP BY.`
}

const UNSUPPORTED_CONSTRUCTS: Array<{ reason: string; pattern: RegExp; message: string }> = [
Expand Down Expand Up @@ -205,9 +226,20 @@ function recordFailure(tool: SqlTool, sql: string, reasons: string[], hints: str
logger.warn({ tool, reasons, sql_shape: sqlShape(sql), ...(hints.length && { hints }) }, 'SQL statement failed')
}

// In production logs every failed statement was a guessed name, and models
// repeated the same one because SeaTable only says what is missing.
const UNKNOWN_NAME_HINT = 'names must match exactly, including case, spaces and umlauts. Call get_schema to see the exact table and column names before retrying'
// SeaTable's messages say what failed, not how to fix it. In production logs every
// failed statement was a guessed name, and models repeated the same one.
const ERROR_HINTS: Array<{ pattern: RegExp; reason: string; hint: string }> = [
{
pattern: /no such (column|table)/i,
reason: 'unknown_name',
hint: 'names must match exactly, including case, spaces and umlauts. Call get_schema to see the exact table and column names before retrying',
},
{
pattern: /failed to convert value|type mismatch/i,
reason: 'invalid_value',
hint: 'a value does not fit its column type. Select columns accept only existing options, spelled exactly (get_schema lists them); dates need the format YYYY-MM-DD',
},
]

/**
* Check a statement for the given tool and run it. Every failure is counted
Expand All @@ -232,9 +264,9 @@ export async function runSql<T>(tool: SqlTool, sql: string, run: () => Promise<T
try {
return await run()
} catch (err) {
const unknownName = err instanceof Error && /no such (column|table)/i.test(err.message)
const hints = unknownName ? [UNKNOWN_NAME_HINT, ...functionHints(sql)] : functionHints(sql)
recordFailure(tool, sql, [unknownName ? 'unknown_name' : 'seatable_error'], hints)
const known = err instanceof Error ? ERROR_HINTS.find(h => h.pattern.test(err.message)) : undefined
const hints = known ? [known.hint, ...functionHints(sql)] : functionHints(sql)
recordFailure(tool, sql, [known ? known.reason : 'seatable_error'], hints)
if (hints.length && err instanceof Error) {
err.message = `${err.message} Hint: ${hints.join('; ')}.`
}
Expand Down
58 changes: 50 additions & 8 deletions tests/sqlCheck.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { makeError } from '../src/errors'
import { logger } from '../src/logger'
import { buildServer, SeaTableMCPServer } from '../src/mcp/server'
import { registerQuerySql } from '../src/mcp/tools/querySql'
import { registerExecuteSql } from '../src/mcp/tools/executeSql'
import { registerListRows } from '../src/mcp/tools/listRows'
import { assertSupportedSql, functionHints, hasLimit, sqlShape, statementKind, stripLiterals } from '../src/mcp/tools/sqlCheck'
import { assertSupportedSql, functionHints, sqlLimit, sqlShape, statementKind, stripLiterals, truncationNotice } from '../src/mcp/tools/sqlCheck'

describe('stripLiterals', () => {
it('neutralises strings, quoted identifiers and comments', () => {
Expand Down Expand Up @@ -179,6 +180,26 @@ describe('SQL tools', () => {
vi.restoreAllMocks()
})

it.each([
'ERR_BAD_REQUEST: failed to convert value: invalid value',
'ERR_BAD_REQUEST: column Umsatz type mismatch',
])('explains "%s"', async (message) => {
let handler: (args: unknown) => Promise<unknown> = async () => undefined
const client = { querySql: async () => { throw makeError('ERR_BAD_REQUEST', message) } }
registerExecuteSql(
{ registerTool: (_name: string, _config: unknown, h: typeof handler) => { handler = h } },
{ client: client as any, env: {} as any, getInputSchema: (s: unknown) => s },
)
const warn = vi.spyOn(logger, 'warn')
await expect(handler({ sql: "UPDATE `T` SET `S` = 'x'" })).rejects.toMatchObject({
code: 'ERR_BAD_REQUEST',
message: expect.stringContaining('Hint: a value does not fit its column type'),
})
const entry = warn.mock.calls.map(c => c[0] as any).find(e => e?.sql_shape)
expect(entry.reasons).toEqual(['invalid_value'])
vi.restoreAllMocks()
})

it('appends function hints when SeaTable rejects a query', async () => {
let handler: (args: unknown) => Promise<unknown> = async () => undefined
const client = {
Expand Down Expand Up @@ -233,12 +254,33 @@ describe('truncated results', () => {
const rows = (n: number) => Array.from({ length: n }, (_, i) => ({ Nr: i + 1 }))
const querySql = (n: number) => registered(registerQuerySql, { querySql: async () => ({ metadata: [], results: rows(n) }) })

it('detects LIMIT outside literals', () => {
expect(hasLimit('SELECT * FROM t LIMIT 1000')).toBe(true)
expect(hasLimit('select * from t limit 5;')).toBe(true)
expect(hasLimit("SELECT * FROM t WHERE note = 'limit 5'")).toBe(false)
expect(hasLimit('SELECT `Limit 5` FROM t')).toBe(false)
expect(hasLimit('SELECT * FROM t')).toBe(false)
it('reads LIMIT outside literals', () => {
expect(sqlLimit('SELECT * FROM t LIMIT 1000')).toBe(1000)
expect(sqlLimit('select * from t limit 5;')).toBe(5)
expect(sqlLimit('SELECT * FROM t LIMIT 100 OFFSET 200')).toBe(100)
expect(sqlLimit('SELECT * FROM t LIMIT 200, 100')).toBe(100)
expect(sqlLimit("SELECT * FROM t WHERE note = 'limit 5'")).toBeUndefined()
expect(sqlLimit('SELECT `Limit 5` FROM t')).toBeUndefined()
expect(sqlLimit('SELECT * FROM t')).toBeUndefined()
})

it('warns when the result fills an explicit LIMIT of 100 or more', () => {
expect(truncationNotice('SELECT a FROM t LIMIT 100', 100)).toContain('as many rows as LIMIT allows (100)')
expect(truncationNotice('SELECT a FROM t LIMIT 1000', 1000)).toContain('Raise LIMIT')
expect(truncationNotice('SELECT a FROM t LIMIT 100 OFFSET 100', 100)).toContain('Raise LIMIT')
})

it('warns at the maximum of 10,000 rows, even with a higher LIMIT', () => {
expect(truncationNotice('SELECT a FROM t LIMIT 10000', 10000)).toContain('Read further with OFFSET')
expect(truncationNotice('SELECT a FROM t LIMIT 20000', 10000)).toContain('Read further with OFFSET')
})

it('stays quiet for a top-N and for results below the limit', () => {
expect(truncationNotice('SELECT a FROM t ORDER BY a LIMIT 3', 3)).toBeUndefined()
expect(truncationNotice('SELECT a FROM t LIMIT 99', 99)).toBeUndefined()
expect(truncationNotice('SELECT a FROM t LIMIT 100', 8)).toBeUndefined()
expect(truncationNotice('SELECT a FROM t LIMIT 1000', 100)).toBeUndefined()
expect(truncationNotice('SELECT a FROM t', 99)).toBeUndefined()
})

it('adds a notice when a SELECT without LIMIT returns exactly 100 rows', async () => {
Expand All @@ -249,7 +291,7 @@ describe('truncated results', () => {
})

it('adds no notice with LIMIT or fewer rows', async () => {
expect((await (await querySql(100))({ sql: 'SELECT `Nr` FROM `Viele` LIMIT 100' })).notice).toBeUndefined()
expect((await (await querySql(100))({ sql: 'SELECT `Nr` FROM `Viele` LIMIT 1000' })).notice).toBeUndefined()
expect((await (await querySql(99))({ sql: 'SELECT `Nr` FROM `Viele`' })).notice).toBeUndefined()
})

Expand Down
Loading