diff --git a/CLAUDE.md b/CLAUDE.md index 055f374..251635a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -113,6 +113,17 @@ SeaTable SQL behaviour verified against 7.0, which the tool texts rely on: To see how real models use the tools, run the series in `docs/testing-with-models.md`. +### Row IDs and `find_rows` filters + +An answer of "0 rows" reads like a fact, so a request the server can't apply must not end in one. `normalizeWhere()` in `src/mcp/tools/findRows.ts` repairs a filter whose meaning is clear (a JSON string, `{Name: {eq: "x"}}`, `{eq: {column: "Name", value: "x"}}`, aliases such as `=` or `not_in`), and `checkCondition()` reports the rest. `resolveColumns()` corrects the case of a column if only one fits and says so in a `notice`; a typo stays an error. `evalWhere()` compares across types (`"10"` against a number cell as a number) and orders empty cells like SQL, matching none of them. The API returns dates with a time (`2026-08-05T00:00:00+02:00`), so a plain date in a filter compares with the day of the cell, and a date in another format such as `01.08.2026` is reported, as its meaning depends on the locale. Coverage is in `tests/rowLookup.spec.ts`. + +SeaTable's answers for a row ID it doesn't know, verified on SeaTable Cloud. Models tend to pass a visible value such as an auto-number, so `ROW_ID_NOTE` is in every tool description and `withRowIdNote()` adds it to these errors: + +- `get_row`, `download_file`, `upload_file`: `row _id not exits`. `update_rows`: `row not found`. `link_rows`: `Row does not exist`. +- `delete_rows`: `param row_ids invalid` for an ID of another form like `D-0008`, otherwise success with `deleted_rows: 0`. The tool reports that count, not the number of IDs it was given. +- `unlink_rows`: success with `deleted_links_count: 0`. The tool reports `success: false` with a notice. +- `get_row_activities`: an empty list, the same as for an existing row whose activities are past the retention period, which varies. The tool looks up the row on an empty result to tell them apart, and its notice names no period. + ### Server instructions and tool annotations The `instructions` in `src/mcp/server.ts` reach every client, and the SeaTable AI chat plugin (`seatable-plugin-ai-chat`) embeds them in its system prompt instead of keeping its own SQL rules. A change there takes effect for all clients on the next deployment, without a plugin release. If a rule moves here from a client, deploy the server first. diff --git a/package-lock.json b/package-lock.json index 3c14675..42d7856 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@seatable/mcp-seatable", - "version": "1.9.4", + "version": "1.9.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@seatable/mcp-seatable", - "version": "1.9.4", + "version": "1.9.5", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.17.4", diff --git a/package.json b/package.json index b49cd01..4f7dad2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@seatable/mcp-seatable", - "version": "1.9.4", + "version": "1.9.5", "type": "module", "license": "MIT", "mcpName": "io.github.seatable/seatable", diff --git a/src/mcp/server.ts b/src/mcp/server.ts index bd20d28..02672eb 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -44,6 +44,7 @@ import { registerUnlinkRows } from './tools/unlinkRows.js' import { registerUpdateRows } from './tools/updateRow.js' import { registerUploadFile } from './tools/uploadFile.js' import { registerUpsertRows } from './tools/upsertRows.js' +import { ROW_ID_NOTE } from './tools/utils.js' // Helper function to convert Zod schemas to JSON Schema for MCP tools const getInputSchema = (schema: z.ZodType): ListToolsResult['tools'][0]['inputSchema'] => { @@ -79,6 +80,11 @@ const CLIENT_ERROR_CODES = new Set([ 'ERR_FILE_TOO_LARGE', 'ERR_AUTH_EXPIRED', 'ERR_RATE_LIMITED', ]) +/** SeaTable's wordings for an unknown or malformed row ID, one with a typo; "exi" also matches if it gets fixed. */ +function withRowIdNote(message: string): string { + return /row _id not exi|row not found|row does not exist|param row_ids invalid/i.test(message) ? `${message.replace(/\.$/, '')}. ${ROW_ID_NOTE}` : message +} + export class SeaTableMCPServer { private readonly server: Server private readonly client: ClientLike @@ -331,7 +337,7 @@ export class SeaTableMCPServer { content: [{ type: 'text', text: JSON.stringify( - `Error in tool ${toolName}: ${error instanceof Error ? error.message : String(error)}` + `Error in tool ${toolName}: ${withRowIdNote(error instanceof Error ? error.message : String(error))}` ), }], isError: true, diff --git a/src/mcp/tools/deleteRow.ts b/src/mcp/tools/deleteRow.ts index a4ba437..4de5e41 100644 --- a/src/mcp/tools/deleteRow.ts +++ b/src/mcp/tools/deleteRow.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const InputSchema = z.object({ table: z.string().describe('Target table name'), @@ -12,14 +13,26 @@ export const registerDeleteRows: ToolRegistrar = (server, { client, getInputSche 'delete_rows', { title: 'Delete Rows', - description: 'Delete one or more rows from a table by their IDs.', + description: `Delete one or more rows from a table by their IDs. ${ROW_ID_NOTE}`, inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, }, async (args: unknown) => { const { table, row_ids } = InputSchema.parse(args) - await client.deleteRows(table, row_ids) - return { content: [{ type: 'text', text: JSON.stringify({ success: true, deleted_count: row_ids.length }) }] } + const res = await client.deleteRows(table, row_ids) + // SeaTable counts what it deleted, and answers 0 for IDs it doesn't know + const deleted = res.deleted_rows ?? row_ids.length + const notFound = row_ids.length - deleted + return { + content: [{ + type: 'text', + text: JSON.stringify({ + success: notFound === 0, + deleted_count: deleted, + ...(notFound > 0 && { notice: `${notFound} of ${row_ids.length} row IDs matched no row and nothing was deleted for them. ${ROW_ID_NOTE}` }), + }), + }], + } } ) } diff --git a/src/mcp/tools/downloadFile.ts b/src/mcp/tools/downloadFile.ts index 3d12948..ea0733d 100644 --- a/src/mcp/tools/downloadFile.ts +++ b/src/mcp/tools/downloadFile.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const InputSchema = z.object({ table: z.string().describe('Target table name'), @@ -14,7 +15,7 @@ export const registerDownloadFile: ToolRegistrar = (server, { client, getInputSc 'download_file', { title: 'Download File', - description: `Read the content of a file attached to a row in a file or image column. Use get_row first to see available files in the column, then pass the exact file_name to select a specific file. + description: `Read the content of a file attached to a row in a file or image column. Use get_row first to see available files in the column, then pass the exact file_name to select a specific file. ${ROW_ID_NOTE} Returns JSON with: file_name, file_size (bytes), content, content_type, and download_link (only when content_type is "binary_url"). diff --git a/src/mcp/tools/findRows.ts b/src/mcp/tools/findRows.ts index 1a9f4b7..88724bd 100644 --- a/src/mcp/tools/findRows.ts +++ b/src/mcp/tools/findRows.ts @@ -1,5 +1,6 @@ import { z } from 'zod' +import { makeError } from '../../errors.js' import type { SeaTableRow } from '../../seatable/types.js' import { ToolRegistrar } from './types.js' @@ -69,6 +70,43 @@ function get(row: SeaTableRow, path: string): unknown { return (row as any)[path] } +// Models often send values as text. Only plain numbers count: "55,99" and "1,000" +// could mean several things, and Number() would also accept "", "0x10" and "1e3". +function plainNumber(text: string): number | undefined { + return /^-?\d+(\.\d+)?$/.test(text) ? Number(text) : undefined +} + +// The API returns dates with a time, such as 2026-08-05T00:00:00+02:00. Against a +// plain date only the day counts: as text, the cell is never equal to 2026-08-05 +// and is greater than it, as in SQL it is not. +function dayOfCell(cell: unknown, value: unknown): unknown { + const isDay = typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) + return isDay && typeof cell === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(cell) ? cell.slice(0, 10) : cell +} + +/** Is the cell equal to a filter value, which may be of another type? */ +function matchesValue(rawCell: unknown, value: unknown): boolean { + const cell = dayOfCell(rawCell, value) + if (cell === value) return true + if (typeof cell === 'number' && typeof value === 'string') return plainNumber(value) === cell + if (typeof cell === 'string' && typeof value === 'number') return cell === String(value) + if (typeof cell === 'boolean' && typeof value === 'string') return value === String(cell) + return false +} + +/** + * Order a cell against a filter value of another type as numbers. As text, "9.49" + * would be greater than "10". NaN fails every comparison, so what can't be read as + * a number matches nothing, and neither does an empty cell, as in SQL. + */ +function compareToValue(rawCell: unknown, value: unknown): number { + const cell = dayOfCell(rawCell, value) + if (cell === undefined || cell === null || cell === '' || value === undefined || value === null) return NaN + if (typeof cell === 'number' && typeof value === 'string') return cell - (plainNumber(value) ?? NaN) + if (typeof cell === 'string' && typeof value === 'number') return (plainNumber(cell) ?? NaN) - value + return compare(cell, value) +} + export function evalWhere(row: SeaTableRow, where: any): boolean { if (where == null) return true if (where.and) return (where.and as any[]).every((w: any) => evalWhere(row, w)) @@ -77,32 +115,32 @@ export function evalWhere(row: SeaTableRow, where: any): boolean { if (where.eq) { const { field, value } = where.eq - return get(row, field) === value + return matchesValue(get(row, field), value) } if (where.ne) { const { field, value } = where.ne - return get(row, field) !== value + return !matchesValue(get(row, field), value) } if (where.in) { const { field, values } = where.in const v = get(row, field) - return (values as unknown[]).some((x) => x === v) + return (values as unknown[]).some((x) => matchesValue(v, x)) } if (where.gt) { const { field, value } = where.gt - return compare(get(row, field), value) > 0 + return compareToValue(get(row, field), value) > 0 } if (where.gte) { const { field, value } = where.gte - return compare(get(row, field), value) >= 0 + return compareToValue(get(row, field), value) >= 0 } if (where.lt) { const { field, value } = where.lt - return compare(get(row, field), value) < 0 + return compareToValue(get(row, field), value) < 0 } if (where.lte) { const { field, value } = where.lte - return compare(get(row, field), value) <= 0 + return compareToValue(get(row, field), value) <= 0 } if (where.contains) { const { field, value, case_sensitive } = where.contains @@ -132,81 +170,238 @@ export function evalWhere(row: SeaTableRow, where: any): boolean { // Map common operator aliases to canonical DSL operators const OP_ALIASES: Record = { - '=': 'eq', '==': 'eq', '===': 'eq', 'equals': 'eq', - '!=': 'ne', '!==': 'ne', '<>': 'ne', 'not_equal': 'ne', + '=': 'eq', '==': 'eq', '===': 'eq', 'equals': 'eq', 'equal': 'eq', + '!=': 'ne', '!==': 'ne', '<>': 'ne', 'not_equal': 'ne', 'not_equals': 'ne', '>': 'gt', '>=': 'gte', '<': 'lt', '<=': 'lte', - 'like': 'contains', '$eq': 'eq', '$ne': 'ne', '$gt': 'gt', - '$gte': 'gte', '$lt': 'lt', '$lte': 'lte', '$in': 'in', - '$contains': 'contains', + 'like': 'contains', 'startswith': 'starts_with', 'endswith': 'ends_with', + 'nin': 'not_in', 'notin': 'not_in', 'isnull': 'is_null', + 'not_null': 'is_not_null', 'notnull': 'is_not_null', } -// Detect { column/field, op/operator, value } pattern from weaker models -function normalizeFilterObject(where: any): any | null { - const col = where.column ?? where.field ?? where.col - const op = where.op ?? where.operator ?? where.operation - if (typeof col !== 'string' || op == null) return null +const VALUE_OPERATORS = new Set(['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'contains', 'starts_with', 'ends_with']) +const FIELD_OPERATORS = new Set([...VALUE_OPERATORS, 'in', 'not_in', 'is_null', 'is_not_null']) +const OPERATORS = new Set([...FIELD_OPERATORS, 'and', 'or', 'not']) + +function canonicalOperator(name: string): string { + const plain = name.toLowerCase().replace(/^\$/, '') + return OP_ALIASES[plain] ?? plain +} + +const isPlainObject = (v: unknown): v is Record => v !== null && typeof v === 'object' && !Array.isArray(v) +const allOf = (clauses: any[]) => (clauses.length === 1 ? clauses[0] : { and: clauses }) + +/** The canonical condition for an operator, a column and its value or values. */ +function condition(op: string, field: string, value: unknown): any { + if (op === 'in') return { in: { field, values: Array.isArray(value) || value === undefined ? value : [value] } } + if (op === 'not_in') return { not: condition('in', field, value) } + if (op === 'is_null') return { is_null: { field } } + if (op === 'is_not_null') return { not: { is_null: { field } } } + if (Array.isArray(value) && op === 'eq') return condition('in', field, value) + if (Array.isArray(value) && op === 'ne') return condition('not_in', field, value) + return { [op]: { field, value } } +} + +const valueOf = (arg: Record) => ('value' in arg ? arg.value : arg.values) + +/** An operator's argument in any form we can read. What we can't stays as it is, for checkCondition() to report. */ +function conditionFromArg(op: string, arg: any): any { + if (typeof arg === 'string' && (op === 'is_null' || op === 'is_not_null')) return condition(op, arg, undefined) + if (Array.isArray(arg) && arg.length === 2 && typeof arg[0] === 'string') return condition(op, arg[0], arg[1]) + if (!isPlainObject(arg)) return { [op]: arg } + + const hasValue = 'value' in arg || 'values' in arg + const field = arg.field ?? arg.column ?? arg.col ?? (hasValue ? arg.name : undefined) + if (typeof field === 'string') return condition(op, field, valueOf(arg)) + const entries = Object.entries(arg) + if (hasValue || entries.length === 0) return { [op]: arg } + return allOf(entries.map(([column, value]) => condition(op, column, value))) +} + +/** One key of a filter object: an operator or a column. */ +function normalizeEntry(key: string, value: any): any { + const op = canonicalOperator(key) + if (op === 'and' || op === 'or') { + if (Array.isArray(value)) return { [op]: value.map(normalize) } + if (isPlainObject(value)) return { [op]: Object.entries(value).map(([k, v]) => normalizeEntry(k, v)) } + return { [op]: value } + } + if (op === 'not') return { not: normalize(value) } + + if (FIELD_OPERATORS.has(op)) { + const isFilter = isPlainObject(value) || Array.isArray(value) || (typeof value === 'string' && key.toLowerCase().includes('null')) + if (isFilter) return conditionFromArg(op, value) + // "eq" with a plain value is a mistake, a column called "Like" is not + if (key === op) return { [op]: value } + } + if (key.startsWith('$')) return { [op]: value } + // Shaped like a condition, so the key was meant as an operator we don't know + if (isPlainObject(value) && (value.field ?? value.column ?? value.col) !== undefined && ('value' in value || 'values' in value)) return { [op]: value } + + if (Array.isArray(value)) return condition('in', key, value) + if (isPlainObject(value)) { + const entries = Object.entries(value) + const areOperators = entries.length > 0 && entries.every(([k]) => k.startsWith('$') || OPERATORS.has(canonicalOperator(k))) + if (areOperators) return allOf(entries.map(([k, v]) => condition(canonicalOperator(k), key, v))) + } + return condition('eq', key, value) +} + +function invalidWhere() { + return makeError('ERR_VALIDATION', 'where must be an object, e.g. {"eq":{"field":"Name","value":"foo"}} or {"Name":"foo"}') +} + +function parseWhereString(where: string): object { + let parsed: unknown + try { + parsed = JSON.parse(where) + } catch { + throw invalidWhere() + } + if (parsed === null || typeof parsed !== 'object') throw invalidWhere() + return parsed +} + +function invalidCondition(problem: string) { + return makeError('ERR_VALIDATION', `Invalid where: ${problem}. Example: {"eq":{"field":"Name","value":"foo"}}`) +} - const canonicalOp = OP_ALIASES[String(op).toLowerCase()] ?? String(op).toLowerCase() - const val = where.value ?? where.values +/** Reject what evalWhere() couldn't apply. An empty "and" stays valid: it's how {} and [] mean "no filter". */ +function checkCondition(where: any): void { + if (where === null || typeof where !== 'object' || Array.isArray(where)) throw invalidWhere() + const operators = Object.keys(where) + if (operators.length !== 1) throw invalidCondition(`a condition needs exactly one operator, got: ${operators.join(', ')}`) - if (canonicalOp === 'in') return { in: { field: col, values: Array.isArray(val) ? val : [val] } } - if (canonicalOp === 'is_null') return { is_null: { field: col } } - return { [canonicalOp]: { field: col, value: val } } + const operator = operators[0] + const arg = where[operator] + if (operator === 'and' || operator === 'or') { + if (!Array.isArray(arg) || (operator === 'or' && arg.length === 0)) throw invalidCondition(`"${operator}" needs a list of conditions`) + arg.forEach(checkCondition) + return + } + if (operator === 'not') { + checkCondition(arg) + return + } + if (operator !== 'in' && operator !== 'is_null' && !VALUE_OPERATORS.has(operator)) { + throw invalidCondition(`unknown operator "${operator}", use one of ${[...OPERATORS].join(', ')}`) + } + if (typeof arg?.field !== 'string') throw invalidCondition(`"${operator}" needs a field`) + if (operator === 'in' && !Array.isArray(arg.values)) throw invalidCondition('"in" needs a list of values') + if (VALUE_OPERATORS.has(operator)) { + if (arg.value === undefined) throw invalidCondition(`"${operator}" needs a value`) + if (arg.value !== null && typeof arg.value === 'object') throw invalidCondition(`column "${arg.field}" needs a single value for "${operator}", not an object or list`) + } } -// Detect MongoDB-style { ColumnName: { $op: value } } -function normalizeMongoStyle(where: any): any | null { - const entries = Object.entries(where) - if (entries.length === 0) return null - // Every value must be an object with exactly one $-prefixed key - if (!entries.every(([, v]) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 1 && Object.keys(v)[0].startsWith('$'))) return null - - const clauses = entries.map(([field, cond]: [string, any]) => { - const [mongoOp, val] = Object.entries(cond)[0] - const canonicalOp = OP_ALIASES[mongoOp.toLowerCase()] ?? mongoOp.slice(1).toLowerCase() - if (canonicalOp === 'in') return { in: { field, values: Array.isArray(val) ? val : [val] } } - if (canonicalOp === 'is_null') return { is_null: { field } } - return { [canonicalOp]: { field, value: val } } - }) - return clauses.length === 1 ? clauses[0] : { and: clauses } +function renameFields(where: any, names: Map): void { + if (where === undefined || where === null) return + if (where.and || where.or) (where.and ?? where.or).forEach((w: any) => renameFields(w, names)) + else if (where.not) renameFields(where.not, names) + else { + const arg: any = Object.values(where)[0] + arg.field = names.get(arg.field) ?? arg.field + } +} + +/** The columns a checked condition refers to. */ +function fieldsOf(where: any): string[] { + if (where === undefined || where === null) return [] + if (where.and || where.or) return (where.and ?? where.or).flatMap(fieldsOf) + if (where.not) return fieldsOf(where.not) + return [(Object.values(where)[0] as { field: string }).field] } -// Normalize shorthand forms: -// 1) { column, op, value } or { field, operator, value } -> canonical DSL -// 2) { Name: { $eq: "foo" } } (MongoDB-style) -> canonical DSL -// 3) { Name: "foo", Status: "bar" } -> { and: [ { eq: { field:'Name', value:'foo'} }, ... ] } -// 4) { or: [ ... ] } etc. -> recursively normalized +/** + * An unknown column matches no row either. The metadata decides, as a table may + * have no rows; as it is cached, a column created a moment ago still counts if a + * row has it. Tables the metadata doesn't know are left to the lookup of the rows. + * System columns start with an underscore. Returns the names it can correct: SQL + * quotes and a different case, if only one column fits. A typo stays an error. + */ +function resolveColumns(metadata: any, table: string, fields: string[], rows: SeaTableRow[]): Map { + const names = new Map() + const columns: Array<{ name: string }> | undefined = metadata?.tables?.find((t: any) => t.name === table)?.columns + if (!columns) return names + + const known = columns.map((c) => c.name) + const missing: string[] = [] + for (const field of new Set(fields)) { + const name = field.replace(/^`|`$/g, '') + if (name.startsWith('_') || known.includes(name) || rows.some((r) => name in r)) { + if (name !== field) names.set(field, name) + continue + } + const sameCase = known.filter((k) => k.toLowerCase() === name.toLowerCase()) + if (sameCase.length === 1) names.set(field, sameCase[0]) + else missing.push(field) + } + if (missing.length > 0) { + const list = missing.map((f) => `"${f}"`).join(', ') + throw makeError('ERR_SCHEMA_UNKNOWN_COLUMN', `Column ${list} not found in table "${table}". Columns: ${known.join(', ')}`) + } + return names +} + +const DATE_COLUMN_TYPES = new Set(['date', 'ctime', 'mtime']) +const FOREIGN_DATE = /^\d{1,2}[./-]\d{1,2}[./-]\d{2,4}\b/ + +/** + * Dates compare as text, which only works in SeaTable's format: "2026-07-13" is + * greater than "01.08.2026". Which date "01.02.2026" means depends on the locale, + * so this is reported instead of converted. + */ +function checkDateValues(where: any, metadata: any, table: string): void { + if (where === undefined || where === null) return + if (where.and || where.or) return (where.and ?? where.or).forEach((w: any) => checkDateValues(w, metadata, table)) + if (where.not) return checkDateValues(where.not, metadata, table) + + const arg: any = Object.values(where)[0] + const columns: Array<{ name: string; type?: string }> = metadata?.tables?.find((t: any) => t.name === table)?.columns ?? [] + const type = columns.find((c) => c.name === arg.field)?.type + const isDate = (type !== undefined && DATE_COLUMN_TYPES.has(type)) || arg.field === '_ctime' || arg.field === '_mtime' + if (!isDate) return + + const values: unknown[] = arg.values ?? [arg.value] + const foreign = values.find((v) => typeof v === 'string' && FOREIGN_DATE.test(v)) + if (foreign !== undefined) { + throw makeError('ERR_VALIDATION', `Column "${arg.field}" holds dates: use the format YYYY-MM-DD instead of "${foreign}"`) + } +} + +// Reads a filter in the forms models send, as long as the meaning is clear: +// 1) a JSON string -> the object it contains +// 2) { column, op, value } or { field, operator, value }, also without op +// 3) { Name: "foo", Status: "bar" } -> all of them; a list -> in +// 4) { Name: { $eq: "foo" } }, { Name: { eq: "foo" } }, { Betrag: { gt: 1, lt: 9 } } +// 5) { eq: { column: "Name", value: "foo" } }, { eq: { Name: "foo" } }, { eq: ["Name", "foo"] } +// 6) operator aliases such as "=", "EQ", "$eq", "not_in", "is_not_null" +// 7) several operators next to each other -> all of them +// Anything it can't apply is an error: evalWhere() would reject every row, and +// "0 rows" reads like a real answer and sends the model searching elsewhere. export function normalizeWhere(where: any): any { - if (!where || typeof where !== 'object') return where + const normalized = normalize(where) + if (normalized !== undefined && normalized !== null) checkCondition(normalized) + return normalized +} + +function normalize(where: any): any { + if (where === undefined || where === null) return where + if (typeof where === 'string') return normalize(parseWhereString(where)) + if (typeof where !== 'object') throw invalidWhere() // Array of conditions → AND if (Array.isArray(where)) { - const clauses = where.map((w: any) => normalizeWhere(w)) + const clauses = where.map((w: any) => normalize(w)) return clauses.length === 1 ? clauses[0] : { and: clauses } } // { column/field, op, value } pattern - const filterObj = normalizeFilterObject(where) - if (filterObj) return filterObj - - // Canonical DSL operators - const operatorKeys = ['eq','ne','in','gt','gte','lt','lte','contains','starts_with','ends_with','is_null','and','or','not'] - if (operatorKeys.some(k => k in where)) { - if (Array.isArray(where.and)) where.and = where.and.map((w: any) => normalizeWhere(w)) - if (Array.isArray(where.or)) where.or = where.or.map((w: any) => normalizeWhere(w)) - if (where.not) where.not = normalizeWhere(where.not) - return where - } - - // MongoDB-style { Name: { $eq: value } } - const mongoNorm = normalizeMongoStyle(where) - if (mongoNorm) return mongoNorm + const column = where.column ?? where.field ?? where.col + const op = where.op ?? where.operator ?? where.operation + if (typeof column === 'string' && op != null) return condition(canonicalOperator(String(op)), column, valueOf(where)) + if (typeof column === 'string' && 'value' in where) return condition('eq', column, where.value) - // Plain object => conjunction of eq clauses - const entries = Object.entries(where) - const clauses = entries.map(([field, value]) => ({ eq: { field, value } })) - if (clauses.length === 1) return clauses[0] - return { and: clauses } + return allOf(Object.entries(where).map(([key, value]) => normalizeEntry(key, value))) } export const registerFindRows: ToolRegistrar = (server, { client, getInputSchema }) => { @@ -216,8 +411,8 @@ export const registerFindRows: ToolRegistrar = (server, { client, getInputSchema title: 'Find Rows', description: 'Find rows using a predicate DSL. Filtering is performed client-side. ' + - 'where format: {"eq":{"field":"Name","value":"foo"}} or shorthand {"Name":"foo"}. ' + - 'Operators: eq, ne, in, gt, gte, lt, lte, contains, starts_with, ends_with, is_null. ' + + 'where is an object, not a string: {"eq":{"field":"Name","value":"foo"}} or shorthand {"Name":"foo"}. ' + + 'Operators: eq, ne, in, not_in, gt, gte, lt, lte, contains, starts_with, ends_with, is_null, is_not_null. ' + 'Combine with {"and":[...]} or {"or":[...]}. Negate with {"not":{...}}.', inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, @@ -236,13 +431,23 @@ export const registerFindRows: ToolRegistrar = (server, { client, getInputSchema page += 1 } + const fields = [...fieldsOf(normalizedWhere), ...(parsed.order_by ? [parsed.order_by] : [])] + const metadata = fields.length > 0 ? await client.getMetadata() : undefined + const corrected = resolveColumns(metadata, parsed.table, fields, all) + renameFields(normalizedWhere, corrected) + checkDateValues(normalizedWhere, metadata, parsed.table) + const orderBy = parsed.order_by && (corrected.get(parsed.order_by) ?? parsed.order_by) + const notice = corrected.size > 0 + ? [...corrected].map(([from, to]) => `Read column "${from}" as "${to}".`).join(' ') + : undefined + // Apply predicate locally let matched = all.filter((r) => evalWhere(r, normalizedWhere)) // Optional ordering - if (parsed.order_by) { + if (orderBy) { const dir = parsed.direction === 'desc' ? -1 : 1 - matched = matched.sort((a, b) => dir * compare((a as any)[parsed.order_by!], (b as any)[parsed.order_by!])) + matched = matched.sort((a, b) => dir * compare((a as any)[orderBy], (b as any)[orderBy])) } // Paginate locally @@ -256,7 +461,7 @@ export const registerFindRows: ToolRegistrar = (server, { client, getInputSchema content: [ { type: 'text', - text: JSON.stringify({ rows: slice, page: pageOut, page_size: pageSizeOut, total: matched.length }), + text: JSON.stringify({ ...(notice && { notice }), rows: slice, page: pageOut, page_size: pageSizeOut, total: matched.length }), }, ], } diff --git a/src/mcp/tools/getRow.ts b/src/mcp/tools/getRow.ts index 4d9794f..2c58ffe 100644 --- a/src/mcp/tools/getRow.ts +++ b/src/mcp/tools/getRow.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const InputSchema = z.object({ table: z.string().describe('Target table name'), @@ -12,7 +13,7 @@ export const registerGetRow: ToolRegistrar = (server, { client, getInputSchema } 'get_row', { title: 'Get Row', - description: 'Get a row by ID from a table', + description: `Get a row by its ID. ${ROW_ID_NOTE}`, inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, }, diff --git a/src/mcp/tools/getRowActivities.ts b/src/mcp/tools/getRowActivities.ts index 3dbcecb..0c0f1e4 100644 --- a/src/mcp/tools/getRowActivities.ts +++ b/src/mcp/tools/getRowActivities.ts @@ -1,9 +1,10 @@ import { z } from 'zod' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const InputSchema = z.object({ - table: z.string().describe('Table name (used for context in the response)'), + table: z.string().describe('Table name of the row'), row_id: z.string().describe('Row ID to get the activity history for'), page: z.number().int().min(1).default(1).optional().describe('Page number (default 1, 25 activities per page)'), }) @@ -49,23 +50,32 @@ function cleanActivity(activity: any): Record { } } +// The retention period varies, so this names none +const NO_ACTIVITIES_NOTICE = + 'The row exists, but no activities are available. SeaTable keeps row activities only for a limited time, so this does not mean the row was never changed.' + export const registerGetRowActivities: ToolRegistrar = (server, { client, getInputSchema }) => { server.registerTool( 'get_row_activities', { title: 'Get Row Activities', - description: 'Get the change history of a specific row. Returns a list of activities showing who changed what and when, including old and new values. 25 activities per page.', + description: `Get the change history of a specific row. Returns a list of activities showing who changed what and when, including old and new values. 25 activities per page. ${ROW_ID_NOTE}`, inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, }, async (args: unknown) => { - const { row_id, page } = InputSchema.parse(args) + const { table, row_id, page } = InputSchema.parse(args) const result = await client.getRowActivities(row_id, page) const cleaned = result.activities.map(cleanActivity) + // SeaTable answers the same for a wrong ID and for a row whose activities + // are past its retention period. The lookup throws if the row doesn't exist. + const noActivities = result.total_count === 0 + if (noActivities) await client.getRow(table, row_id) return { content: [{ type: 'text', text: JSON.stringify({ + ...(noActivities && { notice: NO_ACTIVITIES_NOTICE }), activities: cleaned, total_count: result.total_count, }), diff --git a/src/mcp/tools/linkRows.ts b/src/mcp/tools/linkRows.ts index aca3060..b32281e 100644 --- a/src/mcp/tools/linkRows.ts +++ b/src/mcp/tools/linkRows.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const InputSchema = z.object({ table: z.string().describe('Source table name'), @@ -13,7 +14,7 @@ export const registerLinkRows: ToolRegistrar = (server, { client, getInputSchema 'link_rows', { title: 'Link Rows', - description: 'Create links between rows via the dedicated links endpoint. This is the ONLY way to create links — link columns cannot be written via add_row or update_rows.', + description: `Create links between rows via the dedicated links endpoint. This is the ONLY way to create links — link columns cannot be written via add_row or update_rows. ${ROW_ID_NOTE}`, inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, }, diff --git a/src/mcp/tools/types.ts b/src/mcp/tools/types.ts index 06e972b..5ceea2f 100644 --- a/src/mcp/tools/types.ts +++ b/src/mcp/tools/types.ts @@ -26,7 +26,7 @@ export interface ClientLike { updateRow(table: string, rowId: string, row: Record): Promise updateRows(table: string, updates: Array<{ row_id: string; row: Record }>): Promise<{ success: boolean }> deleteRow(table: string, rowId: string): Promise<{ success: boolean }> - deleteRows(table: string, rowIds: string[]): Promise<{ success: boolean }> + deleteRows(table: string, rowIds: string[]): Promise<{ success?: boolean; deleted_rows?: number }> searchRows(table: string, query: Record): Promise<{ rows: any[]; page?: number; page_size?: number; total?: number; has_more?: boolean }> // SQL diff --git a/src/mcp/tools/unlinkRows.ts b/src/mcp/tools/unlinkRows.ts index 6e9341c..93e4434 100644 --- a/src/mcp/tools/unlinkRows.ts +++ b/src/mcp/tools/unlinkRows.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const InputSchema = z.object({ table: z.string().describe('Source table name'), @@ -13,7 +14,7 @@ export const registerUnlinkRows: ToolRegistrar = (server, { client, getInputSche 'unlink_rows', { title: 'Unlink Rows', - description: 'Remove links between rows via the dedicated links endpoint. This is the ONLY way to remove links — link columns cannot be modified via update_rows.', + description: `Remove links between rows via the dedicated links endpoint. This is the ONLY way to remove links — link columns cannot be modified via update_rows. ${ROW_ID_NOTE}`, inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, }, @@ -26,7 +27,12 @@ export const registerUnlinkRows: ToolRegistrar = (server, { client, getInputSche pairs: pairs.map((p) => ({ fromRowId: p.from_row_id, toRowId: p.to_row_id })), }) - return { content: [{ type: 'text', text: JSON.stringify(result) }] } + // SeaTable answers success with a count of 0 for rows it doesn't know + const nothingRemoved = result?.deleted_links_count === 0 + const answer = nothingRemoved + ? { ...result, success: false, notice: `No link was removed: these rows don't exist or aren't linked. ${ROW_ID_NOTE}` } + : result + return { content: [{ type: 'text', text: JSON.stringify(answer) }] } } ) } diff --git a/src/mcp/tools/updateRow.ts b/src/mcp/tools/updateRow.ts index 9e34bf2..8396d0f 100644 --- a/src/mcp/tools/updateRow.ts +++ b/src/mcp/tools/updateRow.ts @@ -3,6 +3,7 @@ import { z } from 'zod' import { mapMetadataToGeneric } from '../../schema/map.js' import { validateRowsAgainstSchema } from '../../schema/validate.js' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const UpdateItem = z.object({ row_id: z.string().describe('Row ID (_id field) to update'), @@ -19,7 +20,7 @@ export const registerUpdateRows: ToolRegistrar = (server, { client, getInputSche 'update_rows', { title: 'Update Rows', - description: 'Batch update rows. Rejects unknown columns. Link and file/image columns cannot be modified here — use link_rows/unlink_rows and upload_file instead.', + description: `Batch update rows. Rejects unknown columns. Link and file/image columns cannot be modified here — use link_rows/unlink_rows and upload_file instead. ${ROW_ID_NOTE}`, inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, }, diff --git a/src/mcp/tools/uploadFile.ts b/src/mcp/tools/uploadFile.ts index 693457c..e26a591 100644 --- a/src/mcp/tools/uploadFile.ts +++ b/src/mcp/tools/uploadFile.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import { ToolRegistrar } from './types.js' +import { ROW_ID_NOTE } from './utils.js' const InputSchema = z.object({ table: z.string().describe('Target table name'), @@ -16,7 +17,7 @@ export const registerUploadFile: ToolRegistrar = (server, { client, getInputSche 'upload_file', { title: 'Upload File', - description: 'Upload a file or image to a row. Accepts base64-encoded file data and attaches it to the specified file or image column. By default appends to existing files; set replace=true to overwrite.', + description: `Upload a file or image to a row. Accepts base64-encoded file data and attaches it to the specified file or image column. By default appends to existing files; set replace=true to overwrite. ${ROW_ID_NOTE}`, inputSchema: getInputSchema(InputSchema), annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, }, diff --git a/src/mcp/tools/utils.ts b/src/mcp/tools/utils.ts index 736e9ed..bb6db42 100644 --- a/src/mcp/tools/utils.ts +++ b/src/mcp/tools/utils.ts @@ -1,3 +1,7 @@ +/** For every tool that takes a row ID: models tend to pass a visible value such as an auto-number. */ +export const ROW_ID_NOTE = + 'Row IDs are the internal _id, not a column value such as an auto-number. To find a row by a column value, use query_sql: SELECT * returns the _id too.' + /** Strip redundant and UI-only fields from query_sql metadata. */ export function cleanSqlMetadata(metadata: any): any { if (!Array.isArray(metadata)) return metadata diff --git a/src/seatable/client.ts b/src/seatable/client.ts index 228b8f8..7745fa8 100644 --- a/src/seatable/client.ts +++ b/src/seatable/client.ts @@ -251,7 +251,7 @@ export class SeaTableClient { }) } - async deleteRows(table: string, rowIds: string[]): Promise<{ success: boolean }> { + async deleteRows(table: string, rowIds: string[]): Promise<{ success?: boolean; deleted_rows?: number }> { return this.request('deleteRows', async (http) => { const res = await http.delete('/rows/', { data: { table_name: table, row_ids: rowIds }, diff --git a/tests/rowLookup.spec.ts b/tests/rowLookup.spec.ts new file mode 100644 index 0000000..0b34eea --- /dev/null +++ b/tests/rowLookup.spec.ts @@ -0,0 +1,582 @@ +import { beforeAll, describe, expect, it, vi } from 'vitest' + +import { makeError } from '../src/errors' +import { buildServer, SeaTableMCPServer } from '../src/mcp/server' +import { evalWhere, normalizeWhere } from '../src/mcp/tools/findRows' + +beforeAll(() => { + process.env.SEATABLE_SERVER_URL = 'http://localhost' + process.env.SEATABLE_API_TOKEN = 'test-token' + process.env.SEATABLE_MOCK = 'true' +}) + +function callTool(server: SeaTableMCPServer, name: string, args: Record) { + return (server as any).handleCallTool({ params: { name, arguments: args } }) +} + +// Seen in production: a model passed `where` as a JSON string. Every row then +// evaluated to false, and "0 rows" sent the model searching other tables. +describe('find_rows with a where that is not an object', () => { + const NAME = 'find-rows-string-where' + const where = { or: [{ eq: { field: 'Name', value: NAME } }, { eq: { field: 'Name', value: 'other' } }] } + let server: SeaTableMCPServer + + const find = async (args: Record) => { + const result = await callTool(server, 'find_rows', { table: 'Table1', ...args }) + return { result, text: result.content[0].text as string } + } + + beforeAll(async () => { + server = buildServer() + await callTool(server, 'add_row', { table: 'Table1', row: { Name: NAME } }) + }) + + it('reads a JSON string like the object it contains', async () => { + const { result, text } = await find({ where: JSON.stringify(where) }) + expect(result.isError).toBeUndefined() + expect(JSON.parse(text).total).toBe(1) + }) + + it('reads JSON strings nested in a condition', async () => { + const { text } = await find({ where: { or: [JSON.stringify(where.or[0])] } }) + expect(JSON.parse(text).total).toBe(1) + }) + + it.each([ + ['text that is no JSON', 'Name = foo'], + ['an empty string', ''], + ['a JSON string holding no object', '5'], + ['a number', 5], + ['a boolean', false], + ])('reports %s as an error instead of finding nothing', async (_label, value) => { + const { result, text } = await find({ where: value }) + expect(result.isError).toBe(true) + expect(JSON.parse(text)).toContain('where must be an object, e.g. {"eq":{"field":"Name","value":"foo"}}') + // Logged as the caller's mistake, not as a server error + expect(() => normalizeWhere(value)).toThrowError(expect.objectContaining({ code: 'ERR_VALIDATION' })) + }) + + it('still returns all rows without a where', async () => { + for (const args of [{}, { where: null }]) { + const { result, text } = await find(args) + expect(result.isError).toBeUndefined() + expect(JSON.parse(text).total).toBeGreaterThan(0) + } + }) + + it('still finds nothing when no row matches', async () => { + const { result, text } = await find({ where: { eq: { field: 'Name', value: 'no such name' } } }) + expect(result.isError).toBeUndefined() + expect(JSON.parse(text).total).toBe(0) + }) + + it('normalizeWhere treats a JSON string like its object', () => { + expect(normalizeWhere(JSON.stringify({ Name: 'foo' }))).toEqual(normalizeWhere({ Name: 'foo' })) + }) +}) + +// A malformed filter or an unknown column used to match no row without a word. +describe('find_rows with a filter it cannot apply', () => { + const table = 'Table1' + let server: SeaTableMCPServer + + const find = async (args: Record) => { + const result = await callTool(server, 'find_rows', { table, ...args }) + return { result, text: JSON.parse(result.content[0].text) } + } + + beforeAll(async () => { + server = buildServer() + await callTool(server, 'add_row', { table, row: { Name: 'filter-check' } }) + }) + + it.each([ + ['an unknown operator', { column: 'Name', op: 'matches', value: 'x' }, 'matches'], + ['an unknown operator in MongoDB style', { Name: { $regex: 'x' } }, 'regex'], + ['an unknown operator as the key', { matches: { field: 'Name', value: 'x' } }, 'unknown operator "matches"'], + ['an unknown operator with column', { matches: { column: 'Name', value: 'x' } }, 'unknown operator "matches"'], + ['a condition without a field', { eq: { value: 'x' } }, 'field'], + ['a condition that is no object', { eq: 'x' }, 'field'], + ['a comparison without a value', { eq: { field: 'Name' } }, 'value'], + ['an object as the value', { Name: { foo: 'bar' } }, '"Name" needs a single value'], + ['a list as the value of gt', { gt: { field: 'Name', value: [1, 2] } }, 'single value'], + ['or without conditions', { or: [] }, 'or'], + ['or that is no list', { or: 'x' }, 'or'], + ['a malformed condition inside or', { or: [{ eq: { field: 'Name', value: 'x' } }, { gt: { value: 1 } }] }, 'field'], + ['a malformed condition inside not', { not: { eq: { value: 'x' } } }, 'field'], + ])('reports %s', async (_label, where, expected) => { + const { result, text } = await find({ where }) + expect(result.isError).toBe(true) + expect(text).toContain(expected) + expect(() => normalizeWhere(where)).toThrowError(expect.objectContaining({ code: 'ERR_VALIDATION' })) + }) + + it.each([ + ['eq', { eq: { field: 'Nmae', value: 'x' } }], + ['the shorthand', { Nmae: 'x' }], + ['a nested condition', { and: [{ eq: { field: 'Name', value: 'filter-check' } }, { not: { is_null: { field: 'Nmae' } } }] }], + ])('reports an unknown column in %s and names the existing ones', async (_label, where) => { + const { result, text } = await find({ where }) + expect(result.isError).toBe(true) + expect(text).toContain('Column "Nmae" not found in table "Table1"') + expect(text).toContain('Name') + }) + + it('reports an unknown column in order_by', async () => { + const { result, text } = await find({ order_by: 'Nmae' }) + expect(result.isError).toBe(true) + expect(text).toContain('Column "Nmae" not found') + }) + + it.each([ + ['a system column', { is_null: { field: '_archived' } }], + ['no conditions at all', {}], + ['an empty list', []], + ['the shorthand', { Name: 'filter-check' }], + ['a value of null', { eq: { field: 'Name', value: null } }], + ['operators in the column, op, value form', { column: 'Name', op: '!=', value: 'x' }], + ])('accepts %s', async (_label, where) => { + const { result } = await find({ where }) + expect(result.isError).toBeUndefined() + }) + + it('accepts a column only the rows know, as metadata is cached', async () => { + const stale = new SeaTableMCPServer({ + getMetadata: async () => ({ tables: [{ name: table, columns: [{ name: 'Name' }] }] }), + listRows: async () => ({ rows: [{ _id: 'row_1', Name: 'a', New: 'b' }] }), + } as any) + const result = await callTool(stale, 'find_rows', { table, where: { New: 'b' } }) + expect(result.isError).toBeUndefined() + expect(JSON.parse(result.content[0].text).total).toBe(1) + }) + + it('leaves a table it does not know to the lookup of the rows', async () => { + const result = await callTool(server, 'find_rows', { table: 'NoSuchTable', where: { Name: 'x' } }) + expect(result.isError).toBeUndefined() + }) +}) + +// Weaker models send values as text. Comparing them as text gave wrong results, +// not just missing ones: "9.49" is greater than "10". +describe('find_rows comparing values of different types', () => { + const row = { _id: 'r', Betrag: 9.49, Nummer: '123', Null: null, Done: true } + const matches = (where: any) => evalWhere(row, where) + const cond = (op: string, field: string, value: unknown) => ({ [op]: { field, value } }) + + it.each([ + ['eq', 'Betrag', '9.49', true], + ['eq', 'Betrag', '9.5', false], + ['ne', 'Betrag', '9.49', false], + ['ne', 'Betrag', '9.5', true], + ['gt', 'Betrag', '10', false], + ['gt', 'Betrag', '9', true], + ['gte', 'Betrag', '9.49', true], + ['lt', 'Betrag', '10', true], + ['lt', 'Betrag', '9', false], + ['lte', 'Betrag', '9.49', true], + ])('a number cell: %s %s %s is %s', (op, field, value, expected) => { + expect(matches(cond(op, field, value))).toBe(expected) + }) + + it('in compares the same way', () => { + expect(matches({ in: { field: 'Betrag', values: ['1', '9.49'] } })).toBe(true) + expect(matches({ in: { field: 'Nummer', values: [1, 123] } })).toBe(true) + expect(matches({ in: { field: 'Betrag', values: ['1', '2'] } })).toBe(false) + }) + + it.each(['9,49', 'abc', '', ' ', '0x10', '1e3', 'Infinity', '9.49 '])('does not read %j as a number', (value) => { + expect(evalWhere({ _id: 'r', A: 16, B: 1000, C: 9.49 }, { or: ['A', 'B', 'C'].map((f) => cond('eq', f, value)) })).toBe(false) + expect(matches(cond('gt', 'Betrag', value))).toBe(false) + expect(matches(cond('lt', 'Betrag', value))).toBe(false) + }) + + it('a text cell matches a number only if the text is the same', () => { + expect(matches(cond('eq', 'Nummer', 123))).toBe(true) + expect(matches(cond('ne', 'Nummer', 123))).toBe(false) + expect(evalWhere({ _id: 'r', Nummer: '0123' }, cond('eq', 'Nummer', 123))).toBe(false) + expect(evalWhere({ _id: 'r', Nummer: 'abc' }, cond('eq', 'Nummer', 123))).toBe(false) + }) + + it('a text cell with a number is ordered as a number', () => { + expect(matches(cond('gt', 'Nummer', 99))).toBe(true) + expect(matches(cond('lt', 'Nummer', 99))).toBe(false) + expect(evalWhere({ _id: 'r', Nummer: 'abc' }, cond('gt', 'Nummer', 99))).toBe(false) + }) + + it('a checkbox cell matches the words true and false', () => { + expect(matches(cond('eq', 'Done', 'true'))).toBe(true) + expect(matches(cond('eq', 'Done', 'false'))).toBe(false) + expect(matches(cond('ne', 'Done', 'false'))).toBe(true) + expect(matches(cond('eq', 'Done', 'yes'))).toBe(false) + }) + + it('values of the same type behave as before', () => { + expect(matches(cond('eq', 'Betrag', 9.49))).toBe(true) + expect(matches(cond('gt', 'Betrag', 10))).toBe(false) + expect(matches(cond('eq', 'Nummer', '123'))).toBe(true) + expect(matches(cond('gt', 'Nummer', '1'))).toBe(true) + expect(matches(cond('eq', 'Null', null))).toBe(true) + expect(matches(cond('eq', 'Null', 'null'))).toBe(false) + expect(evalWhere({ _id: 'r', D: '2026-08-05' }, cond('gt', 'D', '2026-07-01'))).toBe(true) + }) +}) + +// What a model clearly means gets repaired: a filter of the wrong shape otherwise +// costs a round, or matches nothing without a word. +describe('find_rows repairing a filter', () => { + const rows = [ + { _id: 'a', Name: 'x', Betrag: 5 }, + { _id: 'b', Name: 'y', Betrag: 10 }, + { _id: 'c', Name: 'z', Betrag: null }, + ] + const ids = (where: unknown) => rows.filter((r) => evalWhere(r, normalizeWhere(where))).map((r) => r._id) + + it.each<[string, unknown, string[]]>([ + ['an operator object under the column', { Name: { eq: 'x' } }, ['a']], + ['the same in MongoDB style', { Name: { $eq: 'x' } }, ['a']], + ['several operators under a column', { Betrag: { gt: 1, lt: 8 } }, ['a']], + ['several in MongoDB style', { Betrag: { $gt: 1, $lt: 8 } }, ['a']], + ['a symbol under the column', { Betrag: { '>': 7 } }, ['b']], + ['column instead of field', { eq: { column: 'Name', value: 'x' } }, ['a']], + ['name instead of field', { eq: { name: 'Name', value: 'x' } }, ['a']], + ['the column as the key', { eq: { Name: 'x' } }, ['a']], + ['several columns as keys', { eq: { Name: 'x', Betrag: 5 } }, ['a']], + ['a field and value pair', { eq: ['Name', 'x'] }, ['a']], + ['a symbol as the operator', { '=': { field: 'Name', value: 'x' } }, ['a']], + ['upper case', { EQ: { field: 'Name', value: 'x' } }, ['a']], + ['a dollar', { $eq: { field: 'Name', value: 'x' } }, ['a']], + ['a word as the operator', { equals: { field: 'Name', value: 'x' } }, ['a']], + ['startswith', { startswith: { field: 'Name', value: 'x' } }, ['a']], + ['two operators at once', { gt: { field: 'Betrag', value: 1 }, lt: { field: 'Betrag', value: 8 } }, ['a']], + ['an operator next to a column', { gt: { field: 'Betrag', value: 1 }, Name: 'x' }, ['a']], + ['or with an object', { or: { Name: 'x', Betrag: 10 } }, ['a', 'b']], + ['or with one condition', { or: { eq: { field: 'Name', value: 'x' } } }, ['a']], + ['and with an object', { and: { Name: 'x', Betrag: 5 } }, ['a']], + ['not with a list', { not: [{ Name: 'x' }, { Betrag: 5 }] }, ['b', 'c']], + ['a list under the column', { Name: ['x', 'y'] }, ['a', 'b']], + ['in with one value', { in: { field: 'Name', values: 'x' } }, ['a']], + ['in with value', { in: { field: 'Name', value: ['x', 'y'] } }, ['a', 'b']], + ['in with the column as the key', { in: { Name: ['x', 'y'] } }, ['a', 'b']], + ['eq with a list', { eq: { field: 'Name', value: ['x', 'y'] } }, ['a', 'b']], + ['ne with a list', { ne: { field: 'Name', value: ['x', 'y'] } }, ['c']], + ['not_in', { not_in: { field: 'Name', values: ['x', 'y'] } }, ['c']], + ['$nin under the column', { Name: { $nin: ['x', 'y'] } }, ['c']], + ['is_null with a column name', { is_null: 'Betrag' }, ['c']], + ['is_null with column', { is_null: { column: 'Betrag' } }, ['c']], + ['is_not_null', { is_not_null: { field: 'Betrag' } }, ['a', 'b']], + ['the column, op, value form with not_in', { column: 'Name', op: 'not_in', value: ['x'] }, ['b', 'c']], + ['the column, op, value form with null', { column: 'Betrag', op: '=', value: null }, ['c']], + ['a repair nested in or', { or: [{ Name: { eq: 'x' } }, { eq: { column: 'Name', value: 'y' } }] }, ['a', 'b']], + ['field and value without an operator', { field: 'Name', value: 'x' }, ['a']], + ])('reads %s', (_label, where, expected) => { + expect(ids(where)).toEqual(expected) + }) + + it('takes a word that only looks like an operator as a column if its value is no filter', () => { + const row = { _id: 'r', Like: 'yes', Null: 'no' } + expect(evalWhere(row, normalizeWhere({ Like: 'yes' }))).toBe(true) + expect(evalWhere(row, normalizeWhere({ Null: 'no' }))).toBe(true) + }) + + describe('column names', () => { + const server = () => new SeaTableMCPServer({ + getMetadata: async () => ({ tables: [{ name: 'T', columns: [{ name: 'Betrag' }, { name: 'Name' }, { name: 'name2' }, { name: 'Doppelt' }, { name: 'doppelt' }] }] }), + listRows: async () => ({ rows: [{ _id: 'a', Betrag: 5, Name: 'x' }, { _id: 'b', Betrag: 7, Name: 'y' }] }), + } as any) + const find = async (args: Record) => { + const result = await callTool(server(), 'find_rows', { table: 'T', ...args }) + return { result, data: JSON.parse(result.content[0].text) } + } + + it('corrects the case of a column and says so', async () => { + const { result, data } = await find({ where: { betrag: 5 } }) + expect(result.isError).toBeUndefined() + expect(data.total).toBe(1) + expect(data.notice).toContain('"betrag"') + expect(data.notice).toContain('"Betrag"') + }) + + it('removes SQL quotes around a column', async () => { + const { data } = await find({ where: { '`Betrag`': 5 } }) + expect(data.total).toBe(1) + }) + + it('corrects a nested column and the sort column', async () => { + const { data } = await find({ where: { or: [{ betrag: 5 }, { not: { NAME: 'x' } }] }, order_by: 'BETRAG', direction: 'desc' }) + expect(data.rows.map((r: any) => r._id)).toEqual(['b', 'a']) + }) + + it('adds no notice when nothing was corrected', async () => { + const { data } = await find({ where: { Betrag: 5 } }) + expect(data).not.toHaveProperty('notice') + }) + + it('does not guess between two columns or at a typo', async () => { + for (const where of [{ DOPPELT: 'x' }, { Nmae: 'x' }]) { + const { result, data } = await find({ where }) + expect(result.isError).toBe(true) + expect(data).toContain('not found in table "T"') + } + }) + }) +}) + +// On a real base, Datum >= "01.08.2026" returned every row with a date: as text, +// "2026-07-13" is greater than "01.08.2026". +describe('find_rows with a date in another format', () => { + const server = () => new SeaTableMCPServer({ + getMetadata: async () => ({ + tables: [{ + name: 'T', + columns: [{ name: 'Datum', type: 'date' }, { name: 'Geändert', type: 'mtime' }, { name: 'Code', type: 'text' }], + }], + }), + listRows: async () => ({ + rows: [ + { _id: 'a', Datum: '2026-07-13', 'Geändert': '2026-07-13T10:00:00+02:00', Code: '01.08.2026' }, + { _id: 'b', Datum: '2026-08-13', 'Geändert': '2026-08-13T10:00:00+02:00', Code: 'x' }, + ], + }), + } as any) + const find = async (where: unknown) => { + const result = await callTool(server(), 'find_rows', { table: 'T', where }) + return { result, data: JSON.parse(result.content[0].text) } + } + + it.each<[string, unknown, string]>([ + ['gte with a German date', { gte: { field: 'Datum', value: '01.08.2026' } }, '01.08.2026'], + ['eq with a German date', { eq: { field: 'Datum', value: '13.07.2026' } }, '13.07.2026'], + ['ne with a German date', { ne: { field: 'Datum', value: '13.07.2026' } }, '13.07.2026'], + ['a short year', { lt: { field: 'Datum', value: '1.8.26' } }, '1.8.26'], + ['slashes', { gt: { field: 'Datum', value: '08/01/2026' } }, '08/01/2026'], + ['dashes, day first', { gt: { field: 'Datum', value: '01-08-2026' } }, '01-08-2026'], + ['a list for in', { in: { field: 'Datum', values: ['2026-07-13', '13.07.2026'] } }, '13.07.2026'], + ['a nested condition', { or: [{ Code: 'x' }, { not: { lt: { field: 'Datum', value: '01.08.2026' } } }] }, '01.08.2026'], + ['a column with a corrected name', { gte: { field: 'datum', value: '01.08.2026' } }, '01.08.2026'], + ['a modification time column', { gte: { field: 'Geändert', value: '01.08.2026' } }, '01.08.2026'], + ])('reports %s and names the format', async (_label, where, value) => { + const { result, data } = await find(where) + expect(result.isError).toBe(true) + expect(data).toContain('YYYY-MM-DD') + expect(data).toContain(value) + }) + + it.each<[string, unknown, number]>([ + ['an ISO date', { gte: { field: 'Datum', value: '2026-08-01' } }, 1], + ['an ISO date with a time', { gte: { field: 'Geändert', value: '2026-08-01T00:00:00' } }, 1], + ['such a text in a text column', { eq: { field: 'Code', value: '01.08.2026' } }, 1], + ['is_null on a date column', { is_null: { field: 'Datum' } }, 0], + ])('accepts %s', async (_label, where, total) => { + const { result, data } = await find(where) + expect(result.isError).toBeUndefined() + expect(data.total).toBe(total) + }) +}) + +// The API returns dates as 2026-08-05T00:00:00+02:00. As text, that never equals +// 2026-08-05 and is greater than it, which moved every boundary by a day. +describe('find_rows comparing a date with a date cell', () => { + const row = { _id: 'r', Datum: '2026-08-05T00:00:00+02:00', Zeit: '2026-08-05T23:30:00.5+02:00', Text: 'abc' } + const matches = (op: string, field: string, value: unknown) => evalWhere(row, { [op]: { field, value } }) + + it.each<[string, string, boolean]>([ + ['eq', '2026-08-05', true], + ['eq', '2026-08-04', false], + ['ne', '2026-08-05', false], + ['ne', '2026-08-04', true], + ['gt', '2026-08-05', false], + ['gt', '2026-08-04', true], + ['gte', '2026-08-05', true], + ['gte', '2026-08-06', false], + ['lt', '2026-08-05', false], + ['lt', '2026-08-06', true], + ['lte', '2026-08-05', true], + ['lte', '2026-08-04', false], + ])('%s %s is %s', (op, value, expected) => { + expect(matches(op, 'Datum', value)).toBe(expected) + expect(matches(op, 'Zeit', value)).toBe(expected) + }) + + it('in compares the same way', () => { + expect(evalWhere(row, { in: { field: 'Datum', values: ['2026-01-01', '2026-08-05'] } })).toBe(true) + }) + + it('leaves a time in the filter and other text as they are', () => { + expect(matches('gt', 'Zeit', '2026-08-05T23:00')).toBe(true) + expect(matches('lt', 'Zeit', '2026-08-05T23:00')).toBe(false) + expect(matches('eq', 'Text', '2026-08-05')).toBe(false) + }) +}) + +// SeaTable returns the number of rows it deleted, also 0 for IDs it doesn't know. +describe('delete_rows reporting what happened', () => { + const del = async (answer: unknown, rowIds: string[]) => { + const server = new SeaTableMCPServer({ deleteRows: async () => answer } as any) + return JSON.parse((await callTool(server, 'delete_rows', { table: 'T', row_ids: rowIds })).content[0].text) + } + + it('reports success if all rows were deleted', async () => { + expect(await del({ deleted_rows: 2 }, ['a', 'b'])).toEqual({ success: true, deleted_count: 2 }) + }) + + it('does not report success for IDs that match no row', async () => { + const data = await del({ deleted_rows: 0 }, ['D-0008', 'D-0009']) + expect(data.success).toBe(false) + expect(data.deleted_count).toBe(0) + expect(data.notice).toContain('2 of 2') + expect(data.notice).toContain('internal _id, not a column value') + }) + + it('reports a partial deletion', async () => { + const data = await del({ deleted_rows: 1 }, ['a', 'D-0008']) + expect(data.success).toBe(false) + expect(data.deleted_count).toBe(1) + expect(data.notice).toContain('1 of 2') + }) + + it('trusts the call if SeaTable reports no count', async () => { + expect(await del({ success: true }, ['a'])).toEqual({ success: true, deleted_count: 1 }) + }) +}) + +// SeaTable answers success with a count of 0 for IDs it doesn't know. +describe('unlink_rows reporting what happened', () => { + const unlink = async (answer: unknown) => { + const server = new SeaTableMCPServer({ deleteLinks: async () => answer } as any) + const result = await callTool(server, 'unlink_rows', { table: 'T', link_column: 'L', pairs: [{ from_row_id: 'a', to_row_id: 'b' }] }) + return JSON.parse(result.content[0].text) + } + + it('does not report success if no link was removed', async () => { + const data = await unlink({ deleted_links_count: 0, success: true }) + expect(data.success).toBe(false) + expect(data.deleted_links_count).toBe(0) + expect(data.notice).toContain('internal _id, not a column value') + }) + + it('leaves a removal as it is', async () => { + expect(await unlink({ deleted_links_count: 1, success: true })).toEqual({ deleted_links_count: 1, success: true }) + }) +}) + +// On a real base, Betrag < 10 also returned the rows without a Betrag. +describe('find_rows ordering empty cells', () => { + const cond = (op: string, value: unknown, cell: unknown = null) => evalWhere({ _id: 'r', A: cell }, { [op]: { field: 'A', value } }) + + it.each(['gt', 'gte', 'lt', 'lte'])('%s never matches an empty cell', (op) => { + for (const value of [10, '10', 'abc', '2026-01-01']) { + expect(cond(op, value, null)).toBe(false) + expect(cond(op, value, undefined)).toBe(false) + expect(cond(op, value, '')).toBe(false) + } + }) + + it.each(['gt', 'gte', 'lt', 'lte'])('%s against null matches nothing', (op) => { + expect(cond(op, null, 5)).toBe(false) + expect(cond(op, null, null)).toBe(false) + }) + + it('still orders filled cells and finds empty ones with is_null and eq', () => { + expect(cond('lt', 10, 5)).toBe(true) + expect(cond('gte', 0, 0)).toBe(true) + expect(evalWhere({ _id: 'r', A: null }, { is_null: { field: 'A' } })).toBe(true) + expect(cond('eq', null, null)).toBe(true) + expect(cond('ne', 10, null)).toBe(true) + }) +}) + +// Seen in production: a model passed the value of an auto-number column as row_id. +describe('tools that take a row ID', () => { + const fakeServer = (error: Error) => { + const fail = async () => { throw error } + return new SeaTableMCPServer({ getRow: fail, downloadFile: fail, getRowActivities: fail } as any) + } + + it.each([ + 'get_row', 'update_rows', 'delete_rows', 'link_rows', 'unlink_rows', + 'get_row_activities', 'download_file', 'upload_file', + ])('%s explains in its description what the ID is', (name) => { + const tool = buildServer().getToolDefinitions().find((t) => t.name === name)! + expect(tool.description).toContain('internal _id, not a column value') + expect(tool.description).toContain('query_sql') + }) + + it.each([ + ['get_row', { table: 'T', row_id: 'D-0008' }], + ['download_file', { table: 'T', column: 'File', row_id: 'D-0008' }], + ])('%s explains how to find the _id when SeaTable does not know the row', async (name, args) => { + const result = await callTool(fakeServer(makeError('ERR_BAD_REQUEST', 'row _id not exits')), name, args) + expect(result.isError).toBe(true) + const text = JSON.parse(result.content[0].text) + expect(text).toContain('row _id not exits') + expect(text).toContain('internal _id, not a column value') + expect(text).toContain('query_sql') + }) + + // SeaTable's wording differs per endpoint, all seen on a real base + it.each(['ERR_BAD_REQUEST: row _id not exits', 'ERR_BAD_REQUEST: row not found', 'ERR_BAD_REQUEST: Row does not exist.', 'ERR_BAD_REQUEST: param row_ids invalid'])( + 'adds the note to "%s"', async (message) => { + const result = await callTool(fakeServer(makeError('ERR_BAD_REQUEST', message)), 'get_row', { table: 'T', row_id: 'x' }) + const text = JSON.parse(result.content[0].text) + expect(text).toContain(message.replace(/\.$/, '')) + expect(text).toContain('internal _id, not a column value') + } + ) + + // An empty history looks the same for a wrong ID and for a row whose + // activities are past SeaTable's retention period, which varies. + describe('get_row_activities without activities', () => { + const history = (overrides: Record) => { + const getRow = vi.fn(async () => ({ _id: 'row_1' })) + const server = new SeaTableMCPServer({ + getRow, + getRowActivities: async () => ({ activities: [], total_count: 0 }), + ...overrides, + } as any) + return { getRow, call: () => callTool(server, 'get_row_activities', { table: 'T', row_id: 'row_1' }) } + } + + it('reports a row that does not exist', async () => { + const { call } = history({ getRow: async () => { throw makeError('ERR_BAD_REQUEST', 'row _id not exits') } }) + const result = await call() + expect(result.isError).toBe(true) + const text = JSON.parse(result.content[0].text) + expect(text).toContain('row _id not exits') + expect(text).toContain('internal _id, not a column value') + }) + + it('says that a row without activities may still have been changed, without naming a period', async () => { + const { call } = history({}) + const result = await call() + expect(result.isError).toBeUndefined() + const data = JSON.parse(result.content[0].text) + expect(data.activities).toEqual([]) + expect(data.total_count).toBe(0) + expect(data.notice).toContain('limited time') + expect(data.notice).toContain('does not mean') + expect(data.notice).not.toMatch(/\d/) + }) + + it('does not look up the row or add a notice if there are activities', async () => { + const { call, getRow } = history({ + getRowActivities: async () => ({ activities: [{ op_type: 'insert_row', detail: {} }], total_count: 1 }), + }) + const data = JSON.parse((await call()).content[0].text) + expect(getRow).not.toHaveBeenCalled() + expect(data.total_count).toBe(1) + expect(data).not.toHaveProperty('notice') + }) + + it('does not look up the row on an empty later page', async () => { + const { call, getRow } = history({ getRowActivities: async () => ({ activities: [], total_count: 30 }) }) + const data = JSON.parse((await call()).content[0].text) + expect(getRow).not.toHaveBeenCalled() + expect(data).not.toHaveProperty('notice') + }) + }) + + it('leaves other errors as they are', async () => { + const result = await callTool(fakeServer(makeError('ERR_RATE_LIMITED', 'Too many requests')), 'get_row', { table: 'T', row_id: 'abc' }) + expect(JSON.parse(result.content[0].text)).toBe('Error in tool get_row: Too many requests') + }) +})