peppa/apps/web/app/mcp/route.ts
peppa-bot acb6e3fb81
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 34с
peppa/test test: success за 1325с
peppa-ci / ci (pull_request) Successful in 24m11s
PEP-224: статус функций из мониторинга (сведено с main после PEP-225)
Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP,
отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на
WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и
WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с
`observe`, смена сбрасывает кэш статусов.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:00:03 +00:00

49 lines
2.7 KiB
TypeScript

import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { enterActor, FEATURES, featureStatus, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
import { stripAsIs, t as translate } from "@peppa/shared/i18n";
import { createManagerServer } from "@peppa/mcp/manager";
import { publicOrigin } from "@/lib/auth";
import { db } from "@/lib/db";
import { json, preflight } from "@/lib/oauth";
export const dynamic = "force-dynamic";
async function unauthorized() {
const o = await publicOrigin();
return json({ error: "invalid_token", error_description: "Bearer access token required" }, 401, {
"WWW-Authenticate": `Bearer resource_metadata="${o}/.well-known/oauth-protected-resource"`,
});
}
/** Remote MCP (Streamable HTTP, stateless): PM tools scoped to the token's user. */
export async function POST(req: Request) {
const token = req.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i)?.[1];
const auth = await verifyAccessToken(db, token);
const user = auth && (await getUser(db, auth.userId));
if (!user || !(await isUserAllowed(db, user))) return unauthorized();
// PEP-224: a service MCP depends on is down (Observability) — say so plainly instead of failing midway.
// HTTP 200 with a JSON-RPC error: a 5xx is replaced by Cloudflare's own page (PEP-194).
if (featureStatus("mcp").state === "unavailable") {
const body = (await req.clone().json().catch(() => null)) as { id?: unknown } | Array<{ id?: unknown }> | null;
const id = (Array.isArray(body) ? body[0]?.id : body?.id) ?? null;
const text = FEATURES.mcp.unavailableText;
const message = `${stripAsIs(text)} / ${stripAsIs(translate("en", text))}`;
return json({ jsonrpc: "2.0", id, error: { code: -32001, message } }, 200, { "Access-Control-Allow-Origin": "*", "Retry-After": "300" });
}
// PEP-48: everything this request does is done by the user through this OAuth client.
enterActor({ kind: "user", userId: user.id, channel: "mcp", clientId: auth.clientId });
const server = createManagerServer(db, user, await publicOrigin());
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
await server.connect(transport);
const res = await transport.handleRequest(req);
const out = new Response(res.body, res);
out.headers.set("Access-Control-Allow-Origin", "*");
return out;
}
export async function GET(req: Request) {
if (!req.headers.get("authorization")) return unauthorized();
return new Response("Method Not Allowed (stateless server: POST only)", { status: 405, headers: { Allow: "POST" } });
}
export const OPTIONS = preflight;