Files
drinktracker/src/app/api/mcp/route.ts
JP 4fd339dabc Add MCP server so Claude and ChatGPT can read and write drink data
Exposes the collection over the Model Context Protocol at /api/mcp, with 22
tools covering drinks, ratings, bar inventory, recipes, wishlist and taste
preferences, plus search/fetch aliases for ChatGPT's deep-research mode.

Authentication is a bearer token, the app's first header-borne credential -
every other route derives identity from the NextAuth cookie, which a machine
client cannot present. /api/mcp sits under the middleware's /api exclusion so
it can answer a JSON 401 with an RFC 9728 WWW-Authenticate challenge instead
of an HTML redirect to /login.

Tokens are stored as a SHA-256 hash rather than plaintext like Invite.token
and PasswordReset.token. Those are single-use and short-lived; this one is
long-lived and grants read/write over a whole collection, and the nightly
pg_dump keeps 14 days of history. Not encrypt(), which is reversible AES and
right only for outbound keys we must replay; not bcrypt, which cannot be
indexed and would turn verification into a table scan per request.

verifyMcpToken joins User.status on every call, mirroring the jwt callback, so
suspending a member kills their MCP access immediately rather than leaving the
token as a documented way to outlive suspension. It fails closed on a database
error, deliberately unlike the jwt callback, which keeps the session because a
throw there would sign out every user at once.

No tool reaches the Switchboard gateway. Claude and ChatGPT are language
models already, so they can reason over a bar inventory without the app paying
to do it a second time, and a remote client looping a vision call is not a
failure mode worth having. Account deletion, restore, gateway keys, admin
routes and shared-list creation are excluded too.

The OAuth models ship now but are unused; the token endpoint will write the
same McpAccessToken rows, so adding it later touches no verification code.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 04:29:54 +00:00

110 lines
3.8 KiB
TypeScript

import { createHash } from "crypto"
import { createMcpHandler, withMcpAuth } from "mcp-handler"
import { rateLimit } from "@/lib/rate-limit"
import { verifyMcpToken } from "@/lib/mcp/auth"
import {
MCP_SERVER_NAME,
MCP_SERVER_VERSION,
mcpBaseUrl,
} from "@/lib/mcp/config"
import { registerTools } from "@/lib/mcp/server"
/**
* The MCP endpoint.
*
* Lives under /api deliberately: the middleware matcher in src/middleware.ts
* excludes /api precisely because `authorized` answers with an HTML redirect to
* /login, and an MCP client needs a JSON 401 with a WWW-Authenticate challenge.
* Authentication here is a bearer token, never the session cookie.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource"
const baseHandler = createMcpHandler(registerTools, {
serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },
verboseLogs: process.env.NODE_ENV !== "production",
})
const authedHandler = withMcpAuth(baseHandler, verifyMcpToken, {
required: true,
resourceMetadataPath: RESOURCE_METADATA_PATH,
// Pinned rather than derived from proxy headers. See src/lib/mcp/config.ts -
// the app binds 0.0.0.0:3000 behind a reverse proxy, so a request-derived
// origin sends clients to an unreachable metadata URL.
resourceUrl: mcpBaseUrl(),
})
/**
* A wildcard origin is safe here only because this endpoint authenticates with an
* Authorization header and never a cookie. Do not add Access-Control-Allow-
* Credentials, and do not add session-cookie auth as a fallback: either one turns
* this into a CSRF hole that any website could drive on a logged-in user's behalf.
*/
const CORS_HEADERS: Record<string, string> = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers":
"Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID",
"Access-Control-Expose-Headers": "Mcp-Session-Id, WWW-Authenticate",
"Access-Control-Max-Age": "86400",
}
function withCors(response: Response): Response {
for (const [key, value] of Object.entries(CORS_HEADERS)) {
response.headers.set(key, value)
}
return response
}
/**
* Throttled on a hash of the presented credential, so it works before any
* database lookup and a malformed token cannot be used to probe for free.
*
* Deliberately not enforced inside verifyMcpToken: returning undefined there
* produces a 401, which tells the client to go and re-authenticate - the wrong
* answer to "slow down", and one that would send Claude around the OAuth loop
* repeatedly. Note src/lib/rate-limit.ts is a module-scope Map: per process and
* reset by every deploy. Correct for the single systemd process this runs as;
* under multiple workers the effective limit becomes N times looser.
*/
function throttle(request: Request): Response | null {
const bearer = request.headers
.get("authorization")
?.replace(/^Bearer\s+/i, "")
.trim()
const key = bearer
? `mcp:${createHash("sha256").update(bearer).digest("hex").slice(0, 16)}`
: "mcp:anonymous"
const { success } = rateLimit(key, 120, 60_000)
if (success) return null
return withCors(
new Response(
JSON.stringify({ error: "Too many requests. Please slow down." }),
{
status: 429,
headers: { "content-type": "application/json", "retry-after": "60" },
}
)
)
}
async function handle(request: Request): Promise<Response> {
const throttled = throttle(request)
if (throttled) return throttled
return withCors(await authedHandler(request))
}
export const GET = handle
export const POST = handle
export const DELETE = handle
export function OPTIONS(): Response {
return withCors(new Response(null, { status: 204 }))
}