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
13 changes: 6 additions & 7 deletions package-lock.json

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

5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@seatable/mcp-seatable",
"version": "1.9.2",
"version": "1.9.3",
"type": "module",
"license": "MIT",
"mcpName": "io.github.seatable/seatable",
Expand Down Expand Up @@ -75,8 +75,7 @@
"pino": "^9.4.0",
"prom-client": "^15.1.3",
"unpdf": "^1.4.0",
"zod": "^3.23.8",
"zod-to-json-schema": "^3.24.6"
"zod": "^4.6.7"
},
"devDependencies": {
"@types/node": "^22.5.4",
Expand Down
4 changes: 1 addition & 3 deletions src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,7 @@ const EnvSchema = z
TRUST_PROXY: z
.string()
.optional()
.transform((v) => v !== '0' && v !== 'false')
.optional()
.default('true'),
.transform((v) => v !== '0' && v !== 'false'),
})
.superRefine((data, ctx) => {
if (data.SEATABLE_MODE === 'managed' && !data.SEATABLE_TOKEN_SECRET) {
Expand Down
7 changes: 2 additions & 5 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
type ListToolsResult,
} from '@modelcontextprotocol/sdk/types.js'
import { z } from 'zod'
import { zodToJsonSchema } from 'zod-to-json-schema'

import { getEnv, parseBases, VERSION } from '../config/env.js'
import type { CodedError } from '../errors.js'
Expand Down Expand Up @@ -48,10 +47,8 @@ import { registerUpsertRows } from './tools/upsertRows.js'

// Helper function to convert Zod schemas to JSON Schema for MCP tools
const getInputSchema = (schema: z.ZodType<object>): ListToolsResult['tools'][0]['inputSchema'] => {
const jsonSchema = zodToJsonSchema(schema, {
target: 'jsonSchema7',
strictUnions: true
})
// io: 'input' describes what callers send, so fields with a default stay optional.
const jsonSchema = z.toJSONSchema(schema, { target: 'draft-7', io: 'input' }) as Record<string, unknown>

if (!('type' in jsonSchema) || jsonSchema.type !== 'object') {
throw new Error(`Invalid input schema: expected an object but got ${
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/addRow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ToolRegistrar } from './types.js'

const InputSchema = z.object({
table: z.string().describe('Target table name'),
row: z.record(z.any()).describe('Row object (column -> value)'),
row: z.record(z.string(), z.any()).describe('Row object (column -> value)'),
})

export const registerAddRow: ToolRegistrar = (server, { client, getInputSchema }) => {
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/addSelectOption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const InputSchema = z.object({
name: z.string().describe('Option label'),
color: z.string().optional().describe('Background color (hex, e.g. "#FF8000")'),
textColor: z.string().optional().describe('Text color (hex, e.g. "#FFFFFF")'),
})).min(1).describe('Array of options to add'),
})).min(1).max(1000).describe('Array of options to add'),
})

/** Names of the options a select column already has. Empty if the column has none yet. */
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/executeSql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { cleanSqlMetadata } from './utils.js'

const InputSchema = z.object({
sql: z.string().describe('UPDATE, DELETE or INSERT statement').refine(sql => sql.trim().length > 0, 'SQL statement cannot be empty'),
parameters: z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional().describe('Values for ? placeholders in the SQL statement'),
parameters: z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).max(1000).optional().describe('Values for ? placeholders in the SQL statement'),
})

export const registerExecuteSql: ToolRegistrar = (server, { client, getInputSchema }) => {
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/findRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export type Where = z.infer<typeof Where>
// Use a loose schema for boundary parsing
const InputSchema = z.object({
table: z.string().describe('Target table name'),
where: z.unknown().describe('Filter predicate (e.g. {"eq":{"field":"Name","value":"foo"}} or shorthand {"Name":"foo"})'),
where: z.unknown().optional().describe('Filter predicate (e.g. {"eq":{"field":"Name","value":"foo"}} or shorthand {"Name":"foo"})'),
page: z.number().int().min(1).optional().default(1).describe('Page number (1-based)'),
page_size: z.number().int().min(1).max(1000).optional().default(100).describe('Rows per page (max 1000)'),
order_by: z.string().optional().describe('Column name to sort by'),
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/querySql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { cleanSqlMetadata } from './utils.js'

const InputSchema = z.object({
sql: z.string().describe('SELECT statement').refine(sql => sql.trim().length > 0, 'SQL query cannot be empty'),
parameters: z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional().describe('Values for ? placeholders in the SQL query'),
parameters: z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).max(1000).optional().describe('Values for ? placeholders in the SQL query'),
})

export const registerQuerySql: ToolRegistrar = (server, { client, getInputSchema }) => {
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/searchRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ToolRegistrar } from './types.js'

const InputSchema = z.object({
table: z.string().describe('Target table name'),
query: z.record(z.any()).describe('Filter object with column name -> value pairs'),
query: z.record(z.string(), z.any()).describe('Filter object with column name -> value pairs'),
})

export const registerSearchRows: ToolRegistrar = (server, { client, getInputSchema }) => {
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/updateRow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ToolRegistrar } from './types.js'

const UpdateItem = z.object({
row_id: z.string().describe('Row ID (_id field) to update'),
values: z.record(z.any()).describe('Column name -> new value pairs'),
values: z.record(z.string(), z.any()).describe('Column name -> new value pairs'),
})

const InputSchema = z.object({
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools/upsertRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ToolRegistrar } from './types.js'

const InputSchema = z.object({
table: z.string().describe('Target table name'),
key_columns: z.array(z.string()).min(1).describe('Columns to match on for finding existing rows'),
key_columns: z.array(z.string()).min(1).max(100).describe('Columns to match on for finding existing rows'),
rows: z.array(z.record(z.string(), z.any())).min(1).max(100).describe('Array of row objects (column name -> value)'),
})

Expand Down
2 changes: 1 addition & 1 deletion src/schema/generic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const GenericColumnSchema = z.object({
id: z.string(),
name: z.string(),
type: GenericColumnType,
options: z.record(z.unknown()).optional(),
options: z.record(z.string(), z.unknown()).optional(),
})
export type GenericColumn = z.infer<typeof GenericColumnSchema>

Expand Down
2 changes: 1 addition & 1 deletion src/schema/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const ColumnSchema = z.object({
key: z.string(),
name: z.string(),
type: z.string(),
data: z.record(z.unknown()).nullable().optional(),
data: z.record(z.string(), z.unknown()).nullable().optional(),
description: z.string().nullable().optional(),
})
const TableSchema = z
Expand Down
51 changes: 51 additions & 0 deletions tests/inputBounds.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { beforeAll, describe, expect, it } from 'vitest'

import { buildServer, SeaTableMCPServer } from '../src/mcp/server'

/*
* Zod collects one issue per failing element, so an unbounded array turns a
* request body into many times its size in issue objects. A single 10 MB call
* killed the process this way. Zod 4 checks .max() before it parses elements,
* but only where a bound is declared, so every array a caller controls needs one.
*/

const callTool = (server: SeaTableMCPServer, name: string, args: Record<string, unknown>) =>
(server as any).handleCallTool({ params: { name, arguments: args } })

const select = { table: 'Table1', column: 'Status' }

const OVERSIZED: Array<[string, string, (n: number) => Record<string, unknown>]> = [
['query_sql', 'parameters', (n) => ({ sql: 'SELECT 1', parameters: new Array(n).fill({}) })],
['execute_sql', 'parameters', (n) => ({ sql: 'DELETE FROM `T`', parameters: new Array(n).fill({}) })],
['upsert_rows', 'key_columns', (n) => ({ table: 'T', key_columns: new Array(n).fill(0), rows: [{ a: 1 }] })],
['add_select_options', 'options', (n) => ({ ...select, options: new Array(n).fill(0) })],
['append_rows', 'rows', (n) => ({ table: 'T', rows: new Array(n).fill(0) })],
]

describe('tool input arrays are bounded', () => {
let server: SeaTableMCPServer

beforeAll(() => {
process.env.SEATABLE_SERVER_URL = 'http://localhost'
process.env.SEATABLE_API_TOKEN = 'test-token'
process.env.SEATABLE_MOCK = 'true'
server = buildServer()
})

it.each(OVERSIZED)('%s rejects an oversized %s with one short error', async (tool, field, args) => {
const result = await callTool(server, tool, args(200_000))

expect(result.isError).toBe(true)
const text = result.content[0].text as string
expect(text).toContain(field)
// One issue about the size, not one per element.
expect(text.length).toBeLessThan(2_000)
})

it.each(OVERSIZED.slice(0, 2))('%s still accepts a normal number of %s', async (tool, _field, _args) => {
const sql = tool === 'query_sql' ? 'SELECT * FROM `Table1` WHERE `Name` = ?' : 'DELETE FROM `Table1` WHERE `Name` = ?'
const result = await callTool(server, tool, { sql, parameters: ['a'] })

expect(result.isError).toBeFalsy()
})
})
92 changes: 92 additions & 0 deletions tests/toolInputSchemas.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { beforeAll, describe, expect, it } from 'vitest'

import { getEnv } from '../src/config/env'
import { getStaticToolDefinitions } from '../src/mcp/server'

/*
* The JSON Schema is what clients see. A field with a default has to stay
* optional: converted from the parsed output instead of the input it becomes
* required, and models start failing on calls that used to work.
*/
const REQUIRED: Record<string, string[]> = {
list_tables: [],
list_rows: ['table'],
get_row: ['table', 'row_id'],
add_row: ['table', 'row'],
append_rows: ['table', 'rows'],
update_rows: ['table', 'updates'],
delete_rows: ['table', 'row_ids'],
find_rows: ['table'],
search_rows: ['table', 'query'],
upsert_rows: ['table', 'key_columns', 'rows'],
link_rows: ['table', 'link_column', 'pairs'],
unlink_rows: ['table', 'link_column', 'pairs'],
get_schema: [],
query_sql: ['sql'],
execute_sql: ['sql'],
list_collaborators: [],
upload_file: ['table', 'column', 'row_id', 'file_name', 'file_data'],
download_file: ['table', 'column', 'row_id'],
create_snapshot: [],
get_row_activities: ['table', 'row_id'],
add_select_options: ['table', 'column', 'options'],
ping_seatable: [],
}

describe('tool input schemas', () => {
let tools: Array<{ name: string; inputSchema: any }>

beforeAll(() => {
process.env.SEATABLE_SERVER_URL = 'http://localhost'
process.env.SEATABLE_API_TOKEN = 'test-token'
process.env.SEATABLE_MOCK = 'true'
tools = getStaticToolDefinitions()
})

it('keep their required fields', () => {
const actual = Object.fromEntries(tools.map((t) => [t.name, t.inputSchema.required ?? []]))
expect(actual).toEqual(REQUIRED)
})

it('are objects that allow additional properties', () => {
// These two declare their schema by hand instead of converting one.
const handWritten = ['list_tables', 'list_collaborators']
for (const { name, inputSchema } of tools) {
expect(inputSchema.type, name).toBe('object')
if (!handWritten.includes(name)) expect(inputSchema.additionalProperties, name).toBe(true)
}
})

it('keep descriptions, defaults and limits', () => {
const findRows = tools.find((t) => t.name === 'find_rows')!.inputSchema.properties
expect(findRows.table.description).toBe('Target table name')
expect(findRows.page.default).toBe(1)
expect(findRows.page_size.maximum).toBe(1000)

const appendRows = tools.find((t) => t.name === 'append_rows')!.inputSchema.properties
expect(appendRows.rows.maxItems).toBe(100)
})
})

describe('TRUST_PROXY', () => {
const withValue = (value: string | undefined) => {
const before = process.env.TRUST_PROXY
if (value === undefined) delete process.env.TRUST_PROXY
else process.env.TRUST_PROXY = value
try {
return getEnv().TRUST_PROXY
} finally {
if (before === undefined) delete process.env.TRUST_PROXY
else process.env.TRUST_PROXY = before
}
}

it('is on unless switched off', () => {
process.env.SEATABLE_SERVER_URL = 'http://localhost'
process.env.SEATABLE_API_TOKEN = 'test-token'
expect(withValue(undefined)).toBe(true)
expect(withValue('true')).toBe(true)
expect(withValue('0')).toBe(false)
expect(withValue('false')).toBe(false)
})
})
Loading