peppa/apps/web/app/mcp/route.ts
Асель 39367b1d82 PEP-8: remote MCP for ChatGPT with Peppa as OAuth 2.1 server
- OAuth: RFC 8414/9728 metadata, RFC 7591 dynamic registration,
  authorization code + PKCE S256 with a consent screen after Gitea login,
  refresh token rotation; tokens and codes stored hashed; revoke in web
- /mcp: stateless Streamable HTTP, Bearer → user; PM tools from
  @peppa/mcp/manager: projects, goals, tasks, create, move (board
  semantics, starts agents), inbox, answer/accept — owner-scoped
- login keeps ?next= through Gitea OAuth; Settings page with MCP URL and
  connected apps
- 5 new tests (53 e2e total, green); verified on prod as a client:
  DCR → consent → token → MCP over HTTPS → revoke → 401
- OpenSpec: pep-8 archived into spec remote-mcp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:38:09 +05:00

37 lines
1.6 KiB
TypeScript

import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { getUser, 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) return unauthorized();
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;