peppa/apps/web/app/mcp/route.ts
Асель 14916079bc PEP-5/43/47/48: usage and limits, story budgets, factory metrics, audit journal
- PEP-5: statusLine hook (cost, context, 5h/7d limit windows), transcript tokens,
  sessions.usage, usage strip over every page, runner usage, bot /status, MCP get_usage
- PEP-43: project/story budgets in settings, watchdog pause (Escape, question to the PM:
  extend x2 / remove limit / stop), start/resume guard, budget on the story card
- PEP-47: project metrics tab (cycle time, first pass, review returns, questions, runner
  hours, PM wait, limits, spend by week/agent/epic), MCP get_metrics
- PEP-48: event authors (actor columns, AsyncLocalStorage context), question_answered,
  /journal for superadmins, project journal tab, authors in the story feed
- Migration 0007_usage_audit; OpenSpec changes archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:52:13 +05:00

39 lines
1.9 KiB
TypeScript

import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { enterActor, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
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-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;