fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* A REAL supabase-js client, pointed at a real PostgREST, over a real Postgres
|
||||
* with every migration replayed.
|
||||
*
|
||||
* Why this is not the same thing as the pg-real suite: those tests hold a `pg`
|
||||
* Pool and write SQL. The MCP tools do not write SQL. They call
|
||||
* `supabase.from('x').select('a, b:c(d)')`, and the string inside `.select()`
|
||||
* is parsed by PostgREST, not by Postgres. A misspelled column, a resource
|
||||
* embed whose foreign key does not exist, an `or=(...)` whose grammar is
|
||||
* slightly off, a `.contains()` against a non-jsonb column: every one of those
|
||||
* is a runtime 400 from PostgREST that a mocked client answers cheerfully and a
|
||||
* SQL test never reaches.
|
||||
*/
|
||||
import { createHmac } from 'node:crypto'
|
||||
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/** Must match PGRST_JWT_SECRET in tests/tool-pg/docker-compose.yml. */
|
||||
export const TOOL_PG_JWT_SECRET =
|
||||
'super-secret-jwt-token-with-at-least-32-characters-long'
|
||||
|
||||
export const TOOL_PG_REST_URL = process.env.TOOL_PG_REST_URL ?? 'http://127.0.0.1:54330'
|
||||
export const TOOL_PG_DATABASE_URL =
|
||||
process.env.TOOL_PG_DATABASE_URL ?? 'postgresql://postgres:[email protected]:54329/postgres'
|
||||
|
||||
function base64url(input: Buffer | string): string {
|
||||
return Buffer.from(input)
|
||||
.toString('base64')
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand-rolled HS256 rather than a JWT library: this repo is AGPL and audits its
|
||||
* dependency surface, and a signed JWT is three base64url segments and one
|
||||
* HMAC. Not worth a dependency, and definitely not worth one that ships only to
|
||||
* tests.
|
||||
*/
|
||||
export function signServiceRoleJwt(secret = TOOL_PG_JWT_SECRET): string {
|
||||
const header = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))
|
||||
const payload = base64url(
|
||||
JSON.stringify({
|
||||
role: 'service_role',
|
||||
iss: 'tool-pg',
|
||||
// Fixed far-future expiry: the harness is disposable and a clock-derived
|
||||
// value would make an otherwise deterministic suite time-dependent.
|
||||
exp: 4102444800,
|
||||
}),
|
||||
)
|
||||
const signature = base64url(
|
||||
createHmac('sha256', secret).update(`${header}.${payload}`).digest(),
|
||||
)
|
||||
return `${header}.${payload}.${signature}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Service-role client, which is what the MCP server actually uses:
|
||||
* `createServiceClientNoCookies()` on the API-key path. RLS is therefore NOT
|
||||
* the thing under test here; the query grammar is. Tenant isolation on this
|
||||
* surface comes from explicit `.eq('company_id', ...)` discipline, and a tool
|
||||
* that forgets it is exactly the kind of bug these tests can catch.
|
||||
*/
|
||||
/**
|
||||
* `createClient` eagerly constructs a RealtimeClient, which resolves a
|
||||
* WebSocket implementation and throws "native WebSocket not found" on Node 20.
|
||||
* CI runs Node 20; local machines may not, which is exactly the kind of
|
||||
* difference that turns into a green local run and a red CI one.
|
||||
*
|
||||
* Nothing here subscribes to realtime, and RealtimeClient only RESOLVES the
|
||||
* constructor rather than instantiating it, so handing it an inert class is
|
||||
* enough. Bumping the job to Node 22 would work too, but it would make this the
|
||||
* only job in the repo on a different runtime for a feature it never uses.
|
||||
*/
|
||||
class UnusedRealtimeTransport {
|
||||
constructor() {
|
||||
throw new Error('tool-pg: realtime is not used by these tests')
|
||||
}
|
||||
}
|
||||
|
||||
export function createToolPgClient(): SupabaseClient {
|
||||
const key = signServiceRoleJwt()
|
||||
return createClient(TOOL_PG_REST_URL, key, {
|
||||
auth: { persistSession: false, autoRefreshToken: false },
|
||||
db: { schema: 'public' },
|
||||
realtime: { transport: UnusedRealtimeTransport as never },
|
||||
global: {
|
||||
headers: { apikey: key },
|
||||
// supabase-js hard-codes a `/rest/v1` prefix onto every PostgREST
|
||||
// request, because that is where Supabase's own gateway mounts it. A
|
||||
// bare PostgREST serves at the root, so without this rewrite every
|
||||
// query 404s.
|
||||
//
|
||||
// That is not a hypothetical: the first version of this harness omitted
|
||||
// it, all 55 sweep queries 404d, the tools reported the empty response
|
||||
// as "Database error: undefined", and the suite passed green while
|
||||
// exercising nothing at all. The self-test in query-grammar.tool.test.ts
|
||||
// exists to make that failure mode loud.
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
|
||||
const rewritten = url.replace('/rest/v1/', '/').replace(/\/rest\/v1$/, '')
|
||||
return fetch(rewritten, init)
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# Postgres + PostgREST for the MCP tool integration tests.
|
||||
#
|
||||
# The existing pg-real suite talks to Postgres through a raw `pg` Pool, which
|
||||
# is the right shape for testing triggers and RLS in SQL. It is the wrong shape
|
||||
# for testing the MCP tools, because every one of them queries through
|
||||
# supabase-js, and supabase-js speaks PostgREST rather than SQL. The embeds,
|
||||
# the `or=(col.is.null,col.not.in.(...))` forms, the `.contains()` filters and
|
||||
# the column names in `.select()` strings are all resolved by PostgREST at
|
||||
# request time, so a raw-SQL test cannot see any of them.
|
||||
#
|
||||
# That is the gap this stack exists to close: as of 2026-08-27 all 100 files in
|
||||
# extensions/general/mcp-server/__tests__ fake supabase, and query-journal.test.ts
|
||||
# says out loud that its query chain is "exercised by the live MCP smoke test",
|
||||
# which does not exist in CI.
|
||||
services:
|
||||
postgres:
|
||||
# Same image and tag as the pg-real CI job, deliberately: it ships the auth
|
||||
# schema, auth.uid(), the anon/authenticated/service_role roles and the
|
||||
# extensions this repo's migrations need. Plain postgres:15 would not.
|
||||
image: supabase/postgres:15.8.1.060
|
||||
environment:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- '54329:5432'
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U postgres']
|
||||
interval: 3s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
|
||||
postgrest:
|
||||
image: postgrest/postgrest:v12.2.3
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
PGRST_DB_URI: postgres://postgres:postgres@postgres:5432/postgres
|
||||
PGRST_DB_SCHEMAS: public
|
||||
PGRST_DB_ANON_ROLE: anon
|
||||
# Must match TOOL_PG_JWT_SECRET in tests/tool-pg/env.ts. Length matters:
|
||||
# PostgREST refuses a secret shorter than 32 bytes.
|
||||
PGRST_JWT_SECRET: super-secret-jwt-token-with-at-least-32-characters-long
|
||||
# The tools call RPCs and read a lot of rows; the default 1000-row cap
|
||||
# would silently truncate and make a passing test meaningless.
|
||||
PGRST_DB_MAX_ROWS: '100000'
|
||||
PGRST_DB_POOL: '10'
|
||||
ports:
|
||||
- '54330:3000'
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Every read-only MCP tool, run once against a real PostgREST.
|
||||
*
|
||||
* ## What this catches that nothing else does
|
||||
*
|
||||
* A tool's query is half TypeScript and half a string that PostgREST parses at
|
||||
* request time. `select('a, b:c(d)')` names columns and a resource embed;
|
||||
* `or('a.is.null,b.not.in.(1,2)')` is a grammar; `.contains()` requires a jsonb
|
||||
* or array column. All of it is resolved by PostgREST, none of it by the type
|
||||
* system, and a mocked client answers every one of them cheerfully.
|
||||
*
|
||||
* As of 2026-08-27 all 100 files in extensions/general/mcp-server/__tests__
|
||||
* fake supabase; query-journal.test.ts states that its query chain is
|
||||
* "exercised by the live MCP smoke test", and no such test exists in CI. So
|
||||
* this class of bug (a 42703 undefined column, a PGRST200 missing relationship)
|
||||
* reaches production and shows up as an agent-reported failure.
|
||||
*
|
||||
* ## What a failure here means, and what it does not
|
||||
*
|
||||
* This asserts ONLY that the query is well-formed against the real schema. A
|
||||
* tool that legitimately refuses because a required argument is missing, or
|
||||
* because the seeded company has no data, is not a failure: those are filtered
|
||||
* out below. The bar is deliberately narrow so the suite stays honest.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { tools } from '@/extensions/general/mcp-server/server'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
import { createToolPgClient, TOOL_PG_REST_URL } from './client'
|
||||
|
||||
/**
|
||||
* Postgres and PostgREST error codes that mean "this query is malformed", as
|
||||
* opposed to "this request was refused for a domain reason".
|
||||
*/
|
||||
const MALFORMED_QUERY_CODES = new Set([
|
||||
'42703', // undefined_column
|
||||
'42P01', // undefined_table
|
||||
'42883', // undefined_function
|
||||
'42P10', // invalid_column_reference
|
||||
'PGRST100', // parse error in the query-string specifier
|
||||
'PGRST200', // requested embed has no relationship
|
||||
'PGRST202', // requested function not found in the schema cache
|
||||
])
|
||||
|
||||
/**
|
||||
* Errors are captured at the TRANSPORT, not from the thrown Error.
|
||||
*
|
||||
* This matters more than it sounds. Sweeping the tools and inspecting what they
|
||||
* throw looks equivalent and is not: the tools wrap failures in their own prose
|
||||
* and lose the payload doing it, so a real 42703 arrives as the string
|
||||
* "Database error: undefined" and every classifier downstream sees nothing. The
|
||||
* first version of this file passed for exactly that reason while 55 real
|
||||
* queries were failing underneath it.
|
||||
*
|
||||
* Intercepting fetch sees what PostgREST actually said, regardless of how the
|
||||
* calling tool chose to report it.
|
||||
*/
|
||||
interface CapturedFailure {
|
||||
tool: string
|
||||
status: number
|
||||
code: string | null
|
||||
message: string
|
||||
url: string
|
||||
}
|
||||
|
||||
const captured: CapturedFailure[] = []
|
||||
/** Every request that reached PostgREST, failed or not. */
|
||||
let requestCount = 0
|
||||
let currentTool = '(none)'
|
||||
const originalFetch = globalThis.fetch
|
||||
const REST_HOST = TOOL_PG_REST_URL.replace(/^https?:\/\//, '')
|
||||
|
||||
beforeAll(() => {
|
||||
globalThis.fetch = (async (...args: Parameters<typeof fetch>) => {
|
||||
const response = await originalFetch(...args)
|
||||
const url = String(args[0])
|
||||
if (url.includes(REST_HOST)) requestCount += 1
|
||||
if (!response.ok && url.includes(REST_HOST)) {
|
||||
let code: string | null = null
|
||||
let message = ''
|
||||
try {
|
||||
const body = (await response.clone().json()) as { code?: string; message?: string }
|
||||
code = typeof body.code === 'string' ? body.code : null
|
||||
message = typeof body.message === 'string' ? body.message : JSON.stringify(body)
|
||||
} catch {
|
||||
message = await response.clone().text()
|
||||
}
|
||||
captured.push({ tool: currentTool, status: response.status, code, message, url })
|
||||
}
|
||||
return response
|
||||
}) as typeof fetch
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
|
||||
const readTools = tools.filter((t) => t.annotations.readOnlyHint === true)
|
||||
|
||||
let companyId: string
|
||||
let userId: string
|
||||
let client: ReturnType<typeof createToolPgClient>
|
||||
|
||||
beforeAll(async () => {
|
||||
// Constructed ONCE, here, on purpose. Building it inside the sweep loop puts
|
||||
// it inside the per-tool try/catch, so a client that cannot be constructed at
|
||||
// all is swallowed 74 times as a "domain refusal" and the suite reports a
|
||||
// clean sweep having issued zero queries. That is not hypothetical: it is
|
||||
// what this file did on CI, where Node 20 could not give supabase-js a
|
||||
// WebSocket and every createClient threw.
|
||||
client = createToolPgClient()
|
||||
const seeded = await seedCompany()
|
||||
companyId = seeded.companyId
|
||||
userId = seeded.userId
|
||||
}, 30_000)
|
||||
|
||||
describe('MCP read tools against real PostgREST', () => {
|
||||
it('has a non-trivial number of read tools to sweep', () => {
|
||||
// Guards against the filter silently matching nothing after a refactor,
|
||||
// which would turn this whole file into a no-op that always passes.
|
||||
expect(readTools.length).toBeGreaterThan(50)
|
||||
})
|
||||
|
||||
it('detects a malformed query, so that a green sweep means something', async () => {
|
||||
// The self-test that the previous version of this file needed and did not
|
||||
// have. A harness that cannot see a failure reports none, and the sweep
|
||||
// below would then pass forever while the surface it guards rotted.
|
||||
currentTool = '(self-test)'
|
||||
const before = captured.length
|
||||
await client.from('transactions').select('no_such_column_exists').limit(1)
|
||||
currentTool = '(none)'
|
||||
|
||||
const detected = captured.slice(before).filter((f) => f.code && MALFORMED_QUERY_CODES.has(f.code))
|
||||
expect(detected.length, 'a deliberately bad column was not detected').toBeGreaterThan(0)
|
||||
expect(detected[0].code).toBe('42703')
|
||||
|
||||
// Drop the deliberate failure so it cannot pollute the sweep assertion.
|
||||
captured.length = before
|
||||
}, 30_000)
|
||||
|
||||
it('issues no malformed query', async () => {
|
||||
for (const tool of readTools) {
|
||||
currentTool = tool.name
|
||||
try {
|
||||
await tool.execute({ __keyScopes: [] }, companyId, userId, client as never, {
|
||||
type: 'api_key',
|
||||
})
|
||||
} catch {
|
||||
// A domain refusal (missing argument, no data, scope, capability) is
|
||||
// not what this file is about. Only what PostgREST said counts, and
|
||||
// that was captured at the transport above.
|
||||
}
|
||||
}
|
||||
currentTool = '(none)'
|
||||
|
||||
// Proof of life, and it has to be a real number. A sweep that issues
|
||||
// nothing reports no failures and passes, which is how this file lied
|
||||
// twice: once locally when every query 404d on the /rest/v1 prefix, and
|
||||
// once on CI when every client construction threw. Both times the assertion
|
||||
// here was satisfiable without a single request being made.
|
||||
//
|
||||
// 50 is well under the 87 observed on 2026-08-27 and well above anything a
|
||||
// broken harness produces, which is zero.
|
||||
expect(requestCount, 'the sweep barely reached PostgREST').toBeGreaterThan(50)
|
||||
|
||||
const malformed = captured
|
||||
.filter((f) => f.code && MALFORMED_QUERY_CODES.has(f.code))
|
||||
.map((f) => `${f.tool}: ${f.code} ${f.message}`)
|
||||
|
||||
expect([...new Set(malformed)]).toEqual([])
|
||||
}, 300_000)
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Vitest setup for the MCP tool integration project.
|
||||
*
|
||||
* Fails loudly and early if the stack is not up, because the alternative is a
|
||||
* suite that silently passes against nothing. `scripts/tool-pg/reset.sh` brings
|
||||
* it up and replays every migration.
|
||||
*/
|
||||
import { beforeAll } from 'vitest'
|
||||
import { TOOL_PG_REST_URL, TOOL_PG_DATABASE_URL, signServiceRoleJwt } from './client'
|
||||
|
||||
// tests/pg/fixtures.ts builds its rows through a `pg` Pool keyed on
|
||||
// DATABASE_URL. Pointing that at the same database lets this project reuse
|
||||
// seedCompany / insertCompany / insertPostedJournalEntry verbatim instead of
|
||||
// growing a second, divergent set of fixtures.
|
||||
process.env.DATABASE_URL ??= TOOL_PG_DATABASE_URL
|
||||
|
||||
beforeAll(async () => {
|
||||
const jwt = signServiceRoleJwt()
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(`${TOOL_PG_REST_URL}/companies?select=id&limit=1`, {
|
||||
headers: { apikey: jwt, Authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`tool-pg: PostgREST unreachable at ${TOOL_PG_REST_URL}. Run: npm run tools:pg:reset\n${String(err)}`,
|
||||
)
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`tool-pg: PostgREST answered ${response.status} for a trivial read: ${await response.text()}\n` +
|
||||
'The schema is probably missing or stale. Run: npm run tools:pg:reset',
|
||||
)
|
||||
}
|
||||
}, 30_000)
|
||||
Reference in New Issue
Block a user