mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 16:09:06 +00:00
Moves every `pages/api/**` handler into its TanStack server route under `routes/api/**` and deletes `pages/api/**`, part of the final pass of the TanStack Start migration (FE-3106). Handlers move verbatim and still run through `toWebHandler`, so auth (`apiWrapper`), response shapes and headers are unchanged. Part 2 of the stack. **Depends on:** #53199 **Changed:** - `routes/api/**` – each route now holds its handler (formerly the `pages/api` default export) as a local `nextHandler`/named function. Next-only `config`/`maxDuration` exports are dropped: `vite.config.ts` already sets the function `maxDuration`, and `toWebHandler` parses bodies itself - `routes/api/ai/docs.ts` – Web-native handler inlined, `NextRequest` → `Request` - `lib/api/apiHelpers.ts` – `getPgMetaRedirectUrl` moved here from the old `tables` handler, which the other pg-meta routes imported it from - `eslint.config.cjs`, `.github/CODEOWNERS` – `pages/api` paths → `routes/api` - `tests/routes/api/**`, `lib/api/{generate-v4,rate}.test.ts`, `scripts/__tests__/server-source-maps.test.ts` – call the route's registered handler with a Web `Request` (`tests/lib/server-route.ts`); the MCP query-validation cases now run against the native route **Removed:** - `pages/api/**` (102 files), including the Next twins of the already-native `routes/api/mcp/index.ts` and `functions/$slug/body.ts` - unused `ProjectSettings` types and the `node-mocks-http` dev dependency Parity: every route registers the same methods its handler serves. The exceptions are `check-cname`, `get-ip-address`, `get-utc-time`, `get-s3-keys`, `get-deployment-commit`, `cli-release-version` and `connect`: in Next they answered any method, and their routes register `GET` only, as before this PR. Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Load the table editor, SQL editor and Auth users on a self-hosted build – `/api/platform/**` and `/api/v1/**` respond as before - Use the Assistant and the docs search – `/api/ai/**` streams as before - `GET /api/get-deployment-commit` – same JSON and `Cache-Control` Ran typecheck, ESLint, lint ratchet, knip, Prettier, the TanStack build and the full Studio vitest suite: all pass except `lib/server/configcat.test.ts`, which also fails on `master` in an environment with ConfigCat env vars set. Self-hosted E2E is CI-only. --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
101 lines
3.2 KiB
TypeScript
101 lines
3.2 KiB
TypeScript
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
|
|
import { createSupabaseMcpServer } from '@supabase/mcp-server-supabase'
|
|
import { createFileRoute } from '@tanstack/react-router'
|
|
import { stripIndent } from 'common-tags'
|
|
import { z } from 'zod'
|
|
|
|
import { commaSeparatedStringIntoArray, zBooleanString } from '@/lib/api/apiHelpers'
|
|
import { getSelfHostedPlatform } from '@/lib/api/self-hosted/mcp'
|
|
import { DEFAULT_PROJECT } from '@/lib/constants/api'
|
|
|
|
const supportedFeatureGroupSchema = z.enum([
|
|
'docs',
|
|
'database',
|
|
'development',
|
|
'debugging',
|
|
'feedback',
|
|
])
|
|
|
|
const mcpQuerySchema = z.object({
|
|
features: z
|
|
.string()
|
|
.transform(commaSeparatedStringIntoArray)
|
|
.optional()
|
|
.describe(
|
|
stripIndent`
|
|
A comma-separated list of feature groups to filter tools by. If not provided, all tools are available.
|
|
|
|
The following feature groups are supported: ${supportedFeatureGroupSchema.options.map((group) => `\`${group}\``).join(', ')}.
|
|
`
|
|
)
|
|
.pipe(z.array(supportedFeatureGroupSchema).optional()),
|
|
read_only: zBooleanString()
|
|
.default('false')
|
|
.describe(
|
|
'Indicates whether or not the MCP server should operate in read-only mode. This prevents write operations on any of your databases by executing SQL as a read-only Postgres user.'
|
|
),
|
|
})
|
|
|
|
const POST = async ({ request }: { request: Request }) => {
|
|
const url = new URL(request.url)
|
|
const query = Object.fromEntries(url.searchParams.entries())
|
|
const { error, data } = mcpQuerySchema.safeParse(query)
|
|
|
|
if (error) {
|
|
return new Response(JSON.stringify({ error: error.flatten().fieldErrors }), {
|
|
status: 400,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
}
|
|
|
|
const { features, read_only } = data
|
|
const headers = request.headers
|
|
|
|
const platform = getSelfHostedPlatform({ headers })
|
|
|
|
try {
|
|
const server = createSupabaseMcpServer({
|
|
platform,
|
|
projectId: DEFAULT_PROJECT.ref,
|
|
features,
|
|
readOnly: read_only,
|
|
})
|
|
|
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
sessionIdGenerator: undefined, // Stateless, don't use session management
|
|
enableJsonResponse: true, // Stateless, discourage SSE streams
|
|
})
|
|
|
|
await server.connect(transport)
|
|
return await transport.handleRequest(request)
|
|
} catch (err) {
|
|
// Errors at this point will be due to MCP setup issues. Subsequent
|
|
// errors are handled at the JSON-RPC level inside the protocol.
|
|
if (err instanceof Error) {
|
|
return new Response(JSON.stringify({ error: err.message }), {
|
|
status: 400,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
}
|
|
// `err` here is a non-Error throw, so stringify a safe representation
|
|
// rather than embedding the raw value — a circular/non-serializable
|
|
// object would make JSON.stringify throw inside the catch and turn this
|
|
// into an unhandled 500.
|
|
return new Response(
|
|
JSON.stringify({ error: 'Unable to process MCP request', cause: String(err) }),
|
|
{
|
|
status: 500,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
}
|
|
)
|
|
}
|
|
}
|
|
|
|
export const Route = createFileRoute('/api/mcp/')({
|
|
server: {
|
|
handlers: {
|
|
POST,
|
|
},
|
|
},
|
|
})
|