Функция → мониторинги (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>
49 lines
2.7 KiB
TypeScript
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;
|