diff --git a/AGENTS.md b/AGENTS.md index bfcca71c..48b12d13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,8 @@ - `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433) - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё -- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd +- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов +- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, list_goals, list_tasks, get_task, create_task, move_task (как доска — запускает агента), list_inbox, answer_question - `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба - `packages/runner` — запуск claude в tmux (`peppa--s`), вачдог, `peppa-hook` diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 389bd600..1049f281 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -9,6 +9,7 @@ import { PeppaError, projectForUser, resolveTask, + revokeApp, } from "@peppa/core"; import { acceptTask, answerAndDeliver, moveTask, provisionProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; @@ -137,3 +138,10 @@ export async function moveTaskCard(f: FormData) { await moveTask(db, ref, to); }); } + +export async function revokeConnectedApp(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await revokeApp(db, user.id, str(f, "clientId")); + }); +} diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index 961c90af..b677f059 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -13,6 +13,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
{user.avatarUrl && } diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx new file mode 100644 index 00000000..c42c8a8e --- /dev/null +++ b/apps/web/app/(app)/settings/page.tsx @@ -0,0 +1,42 @@ +import { connectedApps } from "@peppa/core"; +import { ago, Flash } from "@/components/ui"; +import { publicOrigin, requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { revokeConnectedApp } from "../actions"; + +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string }> }) { + const user = await requireUser(); + const { error } = await searchParams; + const apps = await connectedApps(db, user.id); + const origin = await publicOrigin(); + return ( +
+ +

Настройки

+

MCP для ChatGPT и других клиентов

+

+ Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент + зарегистрируется сам, вы подтвердите доступ на экране Пеппы. +

+ {origin}/mcp +

Подключённые приложения

+ {apps.length === 0 ? ( +

Нет подключённых приложений.

+ ) : ( + apps.map((a) => ( +
+
+ {a.name} +
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
+
+
+ + + +
+
+ )) + )} +
+ ); +} diff --git a/apps/web/app/.well-known/oauth-authorization-server/[[...path]]/route.ts b/apps/web/app/.well-known/oauth-authorization-server/[[...path]]/route.ts new file mode 100644 index 00000000..909d8fe7 --- /dev/null +++ b/apps/web/app/.well-known/oauth-authorization-server/[[...path]]/route.ts @@ -0,0 +1,4 @@ +import { authServerMetadata, json, preflight } from "@/lib/oauth"; + +export const GET = async () => json(await authServerMetadata()); +export const OPTIONS = preflight; diff --git a/apps/web/app/.well-known/oauth-protected-resource/[[...path]]/route.ts b/apps/web/app/.well-known/oauth-protected-resource/[[...path]]/route.ts new file mode 100644 index 00000000..6f96a7b2 --- /dev/null +++ b/apps/web/app/.well-known/oauth-protected-resource/[[...path]]/route.ts @@ -0,0 +1,4 @@ +import { json, preflight, resourceMetadata } from "@/lib/oauth"; + +export const GET = async () => json(await resourceMetadata()); +export const OPTIONS = preflight; diff --git a/apps/web/app/.well-known/openid-configuration/route.ts b/apps/web/app/.well-known/openid-configuration/route.ts new file mode 100644 index 00000000..909d8fe7 --- /dev/null +++ b/apps/web/app/.well-known/openid-configuration/route.ts @@ -0,0 +1,4 @@ +import { authServerMetadata, json, preflight } from "@/lib/oauth"; + +export const GET = async () => json(await authServerMetadata()); +export const OPTIONS = preflight; diff --git a/apps/web/app/auth/callback/route.ts b/apps/web/app/auth/callback/route.ts index 80c8cf80..47a49b49 100644 --- a/apps/web/app/auth/callback/route.ts +++ b/apps/web/app/auth/callback/route.ts @@ -2,7 +2,7 @@ import { exchangeOAuthCode, GiteaClient, upsertUserFromGitea } from "@peppa/core import { loadEnv } from "@peppa/shared"; import { cookies } from "next/headers"; import { NextResponse, type NextRequest } from "next/server"; -import { publicOrigin, sessionCookie, STATE_COOKIE } from "@/lib/auth"; +import { NEXT_COOKIE, publicOrigin, safeNext, sessionCookie, STATE_COOKIE } from "@/lib/auth"; import { db } from "@/lib/db"; export async function GET(req: NextRequest) { @@ -18,7 +18,8 @@ export async function GET(req: NextRequest) { const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`); const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me(); const user = await upsertUserFromGitea(db, me, tokens); - const res = NextResponse.redirect(`${origin}/`); + const res = NextResponse.redirect(`${origin}${safeNext((await cookies()).get(NEXT_COOKIE)?.value)}`); + res.cookies.delete({ name: NEXT_COOKIE, path: "/auth" }); const c = sessionCookie(user.id); res.cookies.set(c.name, c.value, c.options); res.cookies.delete({ name: STATE_COOKIE, path: "/auth" }); diff --git a/apps/web/app/auth/start/route.ts b/apps/web/app/auth/start/route.ts index aeb36d5c..2564e2ea 100644 --- a/apps/web/app/auth/start/route.ts +++ b/apps/web/app/auth/start/route.ts @@ -2,13 +2,15 @@ import { randomBytes } from "node:crypto"; import { oauthAuthorizeUrl } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { NextResponse } from "next/server"; -import { publicOrigin, STATE_COOKIE } from "@/lib/auth"; +import { NEXT_COOKIE, publicOrigin, safeNext, STATE_COOKIE } from "@/lib/auth"; -export async function GET() { +export async function GET(req: Request) { const env = loadEnv(); if (!env.GITEA_OAUTH_CLIENT_ID) return new NextResponse("GITEA_OAUTH_CLIENT_ID is not configured", { status: 500 }); const state = randomBytes(18).toString("base64url"); const res = NextResponse.redirect(oauthAuthorizeUrl(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, `${await publicOrigin()}/auth/callback`, state)); + const next = safeNext(new URL(req.url).searchParams.get("next")); + res.cookies.set(NEXT_COOKIE, next, { httpOnly: true, sameSite: "lax", path: "/auth", maxAge: 600, secure: env.PEPPA_WEB_URL.startsWith("https://") }); res.cookies.set(STATE_COOKIE, state, { httpOnly: true, sameSite: "lax", path: "/auth", maxAge: 600, secure: env.PEPPA_WEB_URL.startsWith("https://") }); return res; } diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index 45389fad..e7a018ae 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -151,3 +151,8 @@ details.add { margin: 4px 0; } ul.tasks li { flex-direction: column; align-items: flex-start; } .board { grid-template-columns: 1fr; } } + +.consent { text-align: left; align-items: stretch; } +.consent h1 { justify-content: flex-start; } +.scopes { margin: 0; padding-left: 20px; } +.mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; } diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 793d1757..096819b0 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -1,18 +1,18 @@ import { redirect } from "next/navigation"; -import { currentUser } from "@/lib/auth"; +import { currentUser, safeNext } from "@/lib/auth"; import { Flash } from "@/components/ui"; export const dynamic = "force-dynamic"; -export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string }> }) { - if (await currentUser()) redirect("/"); - const { error } = await searchParams; +export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) { + const { error, next } = await searchParams; + if (await currentUser()) redirect(safeNext(next)); return (

🐷 Peppa

Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.

- Войти через Gitea + Войти через Gitea
); } diff --git a/apps/web/app/mcp/route.ts b/apps/web/app/mcp/route.ts new file mode 100644 index 00000000..1ed31626 --- /dev/null +++ b/apps/web/app/mcp/route.ts @@ -0,0 +1,36 @@ +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; diff --git a/apps/web/app/oauth/authorize/actions.ts b/apps/web/app/oauth/authorize/actions.ts new file mode 100644 index 00000000..fb945033 --- /dev/null +++ b/apps/web/app/oauth/authorize/actions.ts @@ -0,0 +1,35 @@ +"use server"; + +import { issueCode } from "@peppa/core"; +import { redirect } from "next/navigation"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; + +const read = (f: FormData) => ({ + clientId: String(f.get("client_id")), + redirectUri: String(f.get("redirect_uri")), + codeChallenge: String(f.get("code_challenge")), + codeChallengeMethod: String(f.get("code_challenge_method")), + responseType: String(f.get("response_type")), + scope: String(f.get("scope") || "") || undefined, +}); + +function back(redirectUri: string, params: Record, state: string) { + const u = new URL(redirectUri); + for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); + if (state) u.searchParams.set("state", state); + return u.toString(); +} + +export async function approve(f: FormData) { + const user = await requireUser(); + const r = read(f); + const code = await issueCode(db, r, user.id); + redirect(back(r.redirectUri, { code }, String(f.get("state") ?? ""))); +} + +export async function deny(f: FormData) { + await requireUser(); + const r = read(f); + redirect(back(r.redirectUri, { error: "access_denied" }, String(f.get("state") ?? ""))); +} diff --git a/apps/web/app/oauth/authorize/page.tsx b/apps/web/app/oauth/authorize/page.tsx new file mode 100644 index 00000000..ce003176 --- /dev/null +++ b/apps/web/app/oauth/authorize/page.tsx @@ -0,0 +1,71 @@ +import { checkAuthorizeRequest, OAuthError, type OAuthClient } from "@peppa/core"; +import { redirect } from "next/navigation"; +import { currentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { approve, deny } from "./actions"; + +export const dynamic = "force-dynamic"; + +type Params = Record; + +/** OAuth consent screen: who asks, what they get, allow / deny. */ +export default async function Authorize({ searchParams }: { searchParams: Promise }) { + const p = await searchParams; + const user = await currentUser(); + if (!user) redirect(`/login?next=${encodeURIComponent(`/oauth/authorize?${new URLSearchParams(p as Record)}`)}`); + let client: OAuthClient | null = null; + let error: string | null = null; + try { + client = await checkAuthorizeRequest(db, { + clientId: p.client_id ?? "", + redirectUri: p.redirect_uri ?? "", + codeChallenge: p.code_challenge ?? "", + codeChallengeMethod: p.code_challenge_method ?? "", + responseType: p.response_type ?? "", + scope: p.scope, + }); + } catch (e) { + error = e instanceof OAuthError ? e.message : (e as Error).message; + } + const host = p.redirect_uri ? new URL(p.redirect_uri).host : ""; + return ( +
+

🐷 Peppa

+ {error || !client ? ( +

Запрос авторизации некорректен: {error}

+ ) : ( + <> +

+ {client.name} ({host}) просит доступ к Пеппе от имени {user.login}. +

+
    +
  • видеть ваши проекты, цели, задачи и вопросы агентов;
  • +
  • создавать задачи и двигать карточки — перенос в «В работе» запускает агента;
  • +
  • отвечать на вопросы агентов и принимать ревью.
  • +
+

Отозвать доступ можно в «Настройки → Подключённые приложения».

+
+
+ + + +
+ + + +
+ + )} +
+ ); +} + +function Hidden({ p }: { p: Params }) { + return ( + <> + {(["client_id", "redirect_uri", "code_challenge", "code_challenge_method", "response_type", "scope", "state"] as const).map((k) => ( + + ))} + + ); +} diff --git a/apps/web/app/oauth/register/route.ts b/apps/web/app/oauth/register/route.ts new file mode 100644 index 00000000..e6b92fc5 --- /dev/null +++ b/apps/web/app/oauth/register/route.ts @@ -0,0 +1,27 @@ +import { OAuthError, registerClient } from "@peppa/core"; +import { db } from "@/lib/db"; +import { json, preflight } from "@/lib/oauth"; + +/** RFC 7591 dynamic client registration. */ +export async function POST(req: Request) { + const body = (await req.json().catch(() => ({}))) as { client_name?: string; redirect_uris?: unknown }; + try { + const c = await registerClient(db, body.client_name, body.redirect_uris); + return json( + { + client_id: c.id, + client_name: c.name, + redirect_uris: c.redirectUris, + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_id_issued_at: Math.floor(c.createdAt.getTime() / 1000), + }, + 201, + ); + } catch (e) { + if (e instanceof OAuthError) return json({ error: e.error, error_description: e.message }, 400); + throw e; + } +} +export const OPTIONS = preflight; diff --git a/apps/web/app/oauth/token/route.ts b/apps/web/app/oauth/token/route.ts new file mode 100644 index 00000000..db9b879b --- /dev/null +++ b/apps/web/app/oauth/token/route.ts @@ -0,0 +1,17 @@ +import { exchangeToken, OAuthError } from "@peppa/core"; +import { db } from "@/lib/db"; +import { json, preflight } from "@/lib/oauth"; + +export async function POST(req: Request) { + const type = req.headers.get("content-type") ?? ""; + const params: Record = type.includes("application/json") + ? ((await req.json().catch(() => ({}))) as Record) + : Object.fromEntries(new URLSearchParams(await req.text())); + try { + return json(await exchangeToken(db, params)); + } catch (e) { + if (e instanceof OAuthError) return json({ error: e.error, error_description: e.message }, e.error === "invalid_client" ? 401 : 400); + throw e; + } +} +export const OPTIONS = preflight; diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts index 73f11960..0ad62a98 100644 --- a/apps/web/lib/auth.ts +++ b/apps/web/lib/auth.ts @@ -6,6 +6,10 @@ import { db } from "./db"; export const SESSION_COOKIE = "peppa_session"; export const STATE_COOKIE = "peppa_oauth_state"; +export const NEXT_COOKIE = "peppa_next"; + +/** Only same-site relative paths are allowed as a post-login destination. */ +export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/"); const SESSION_DAYS = 30; interface SessionPayload { diff --git a/apps/web/lib/oauth.ts b/apps/web/lib/oauth.ts new file mode 100644 index 00000000..3b55cd7c --- /dev/null +++ b/apps/web/lib/oauth.ts @@ -0,0 +1,33 @@ +import { publicOrigin } from "./auth"; + +export async function authServerMetadata() { + const o = await publicOrigin(); + return { + issuer: o, + authorization_endpoint: `${o}/oauth/authorize`, + token_endpoint: `${o}/oauth/token`, + registration_endpoint: `${o}/oauth/register`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: ["peppa"], + }; +} + +export async function resourceMetadata() { + const o = await publicOrigin(); + return { resource: `${o}/mcp`, authorization_servers: [o], scopes_supported: ["peppa"], bearer_methods_supported: ["header"], resource_name: "Peppa" }; +} + +export const json = (body: unknown, status = 200, headers: Record = {}) => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*", ...headers }, + }); + +export const preflight = () => + new Response(null, { + status: 204, + headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Authorization, Content-Type, Mcp-Protocol-Version" }, + }); diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index becb03c4..bd041e4a 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -2,7 +2,7 @@ import type { NextConfig } from "next"; const config: NextConfig = { // Workspace packages ship TypeScript sources. - transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner"], + transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"], }; export default config; diff --git a/apps/web/package.json b/apps/web/package.json index 3f69586a..fa129491 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -17,7 +17,9 @@ "react-dom": "19.3.1", "@peppa/core": "workspace:*", "@peppa/runner": "workspace:*", - "drizzle-orm": "0.45.4" + "drizzle-orm": "0.45.4", + "@peppa/mcp": "workspace:*", + "@modelcontextprotocol/sdk": "1.32.2" }, "devDependencies": { "@types/react": "19.3.0", diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/design.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/design.md new file mode 100644 index 00000000..1ba7fea3 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/design.md @@ -0,0 +1,21 @@ +# Design: PEP-8 + +## Decisions + +1. **Пеппа — свой сервер авторизации** (не Gitea): ChatGPT нужен DCR, а токен должен + ограничиваться проектами пользователя Пеппы. Вход пользователя — существующая cookie + (Gitea OAuth), затем согласие. +2. **Непрозрачные токены** (32 байта, base64url), в БД — HMAC-хэш; без JWT: проверка + всё равно ходит в БД (отзыв). +3. **MCP stateless**: на каждый POST — новый `McpServer` + `WebStandardStreamableHTTPServerTransport` + с `enableJsonResponse`; пользователь берётся из токена. Инструменты PM — модуль + `@peppa/mcp/manager`, тонкие обёртки над core/runner (`moveTask`, `acceptTask`, + `answerAndDeliver`) с `projectForUser`. +4. **Redirect URI** при регистрации — только https или http://localhost/127.0.0.1; + при авторизации — точное совпадение с зарегистрированным. + +## Risks / Trade-offs + +- [Широкий доступ одного токена ко всем проектам пользователя] → согласие явно говорит + об этом; отзыв в вебе. +- [Спам регистраций DCR] → клиенты без токенов дешёвые; чистка неиспользуемых позже. diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/proposal.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/proposal.md new file mode 100644 index 00000000..14865525 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/proposal.md @@ -0,0 +1,41 @@ +# Proposal: PEP-8 — удалённый MCP Пеппы (ChatGPT и др.) + +Задача Пеппы: **PEP-8** · Цель #2 «Мультипользовательская веб-платформа». + +## Why + +PM хочет управлять задачами из ChatGPT: «двинь PEP-3 в работу», «что ждёт моего +ответа?». ChatGPT подключает только удалённые MCP-серверы по HTTPS с OAuth; текущий +MCP Пеппы — локальный stdio для агентов. + +## What Changes + +- Пеппа становится OAuth 2.1 сервером авторизации для своих API: метаданные + (RFC 8414, RFC 9728), динамическая регистрация клиентов (RFC 7591), authorization code + + PKCE S256, refresh-токены с ротацией. Вход — обычный вход Пеппы через Gitea, затем + экран согласия. +- MCP-эндпоинт `https://peppa.telecom.quest/mcp` (Streamable HTTP, без сессий), токен + Bearer. Инструменты PM в рамках проектов пользователя: проекты, цели, задачи + (список/детали/создание), **перенос карточки** (как на доске — запускает/останавливает + агента), входящие вопросы и ответ на них, приёмка ревью. +- Страница «Подключённые приложения» в вебе: список и отзыв доступа. + +Вне scope: MCP для агентов по HTTP (остаётся stdio), скоупы мельче «всё в моих проектах». + +## Capabilities + +### New Capabilities +- `remote-mcp`: OAuth-доступ сторонних клиентов (ChatGPT) к Пеппе и MCP-инструменты PM. + +### Modified Capabilities + +## Impact + +`packages/db` (oauth_clients, oauth_codes, oauth_tokens), `packages/core` (OAuth), +`packages/mcp` (инструменты PM как модуль), `apps/web` (well-known, /oauth/*, /mcp, +согласие, подключённые приложения, `next` при входе), testkit. + +## Решение без вопроса к PM + +Публичный MCP без авторизации отклонён (раскрыл бы проекты всем); OAuth — единственный +вариант, который поддерживает ChatGPT для приватных данных. PM запросил задачу напрямую. diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/specs/remote-mcp/spec.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/specs/remote-mcp/spec.md new file mode 100644 index 00000000..4394b4d2 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/specs/remote-mcp/spec.md @@ -0,0 +1,49 @@ +# Spec Delta: remote-mcp + +## Purpose + +Даёт сторонним MCP-клиентам (ChatGPT и др.) доступ к проектам пользователя Пеппы по OAuth и набор инструментов PM для управления задачами. + +## ADDED Requirements + +### Requirement: Обнаружение и регистрация клиента +Пеппа SHALL публиковать метаданные защищённого ресурса и сервера авторизации и +принимать динамическую регистрацию клиентов с redirect URI по HTTPS (или localhost). + +#### Scenario: Клиент подключается впервые +- **WHEN** клиент обращается к `/mcp` без токена +- **THEN** получает 401 с `WWW-Authenticate`, указывающим на метаданные ресурса, находит по ним сервер авторизации и регистрируется, получая `client_id` + +### Requirement: Авторизация пользователем +Доступ SHALL выдаваться только после входа пользователя Пеппы и явного согласия на +экране, где названо приложение; используется authorization code с PKCE S256. + +#### Scenario: Согласие +- **WHEN** пользователь, войдя через Gitea, нажимает «Разрешить» для приложения +- **THEN** клиент получает код, обменивает его с верным `code_verifier` на access и refresh токены + +#### Scenario: Отказ или подделка +- **WHEN** пользователь нажимает «Отклонить», или код предъявлен повторно, с неверным verifier или другим redirect URI +- **THEN** токены не выдаются + +### Requirement: Токены +Access-токен SHALL действовать 1 час, refresh — 30 дней с ротацией при использовании; +храниться только в виде хэшей; пользователь видит подключённые приложения и может +отозвать доступ, после чего токены приложения не работают. + +#### Scenario: Отзыв +- **WHEN** пользователь отзывает приложение в вебе +- **THEN** следующий запрос этого приложения к `/mcp` получает 401 + +### Requirement: Инструменты PM +MCP SHALL давать инструменты в пределах проектов пользователя: список проектов и целей, +список и детали задач, создание задачи, перенос карточки (Бэклог/В работе/Ревью/Готово — +с теми же последствиями, что на доске), открытые вопросы и ответ на них, приёмка ревью. + +#### Scenario: Двинуть задачу +- **WHEN** клиент вызывает перенос задачи `PEP-3` в «В работе» +- **THEN** задача `in_progress` и по ней запущен агент, как при переносе на доске + +#### Scenario: Чужой проект +- **WHEN** клиент обращается к задаче проекта, которым пользователь не владеет +- **THEN** получает «не найдено» diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/tasks.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/tasks.md new file mode 100644 index 00000000..af8148d6 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/tasks.md @@ -0,0 +1,16 @@ +# Tasks: PEP-8 + +## 1. OAuth + +- [x] 1.1 Таблицы oauth_clients/codes/tokens; core: регистрация, код с PKCE, обмен, refresh с ротацией, проверка access, отзыв; тесты +- [x] 1.2 Веб: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, `/oauth/register`, `/oauth/authorize` (согласие), `/oauth/token`; `next` после входа + +## 2. MCP + +- [x] 2.1 `@peppa/mcp/manager`: инструменты PM; `/mcp` (401 + WWW-Authenticate, Bearer); тест через MCP-клиент +- [x] 2.2 Страница «Подключённые приложения» с отзывом + +## 3. Проверка + +- [x] 3.1 e2e набор зелёный; выкатка; на проде: DCR → согласие в браузере → токен → MCP-клиент двигает задачу; отзыв → 401 +- [x] 3.2 AGENTS.md + инструкция подключения в ChatGPT; `openspec validate` diff --git a/openspec/specs/remote-mcp/spec.md b/openspec/specs/remote-mcp/spec.md new file mode 100644 index 00000000..c5ee809e --- /dev/null +++ b/openspec/specs/remote-mcp/spec.md @@ -0,0 +1,48 @@ +# remote-mcp Specification + +## Purpose +Даёт сторонним MCP-клиентам (ChatGPT и др.) доступ к проектам пользователя Пеппы по OAuth и набор инструментов PM для управления задачами. + +## Requirements + +### Requirement: Обнаружение и регистрация клиента +Пеппа SHALL публиковать метаданные защищённого ресурса и сервера авторизации и +принимать динамическую регистрацию клиентов с redirect URI по HTTPS (или localhost). + +#### Scenario: Клиент подключается впервые +- **WHEN** клиент обращается к `/mcp` без токена +- **THEN** получает 401 с `WWW-Authenticate`, указывающим на метаданные ресурса, находит по ним сервер авторизации и регистрируется, получая `client_id` + +### Requirement: Авторизация пользователем +Доступ SHALL выдаваться только после входа пользователя Пеппы и явного согласия на +экране, где названо приложение; используется authorization code с PKCE S256. + +#### Scenario: Согласие +- **WHEN** пользователь, войдя через Gitea, нажимает «Разрешить» для приложения +- **THEN** клиент получает код, обменивает его с верным `code_verifier` на access и refresh токены + +#### Scenario: Отказ или подделка +- **WHEN** пользователь нажимает «Отклонить», или код предъявлен повторно, с неверным verifier или другим redirect URI +- **THEN** токены не выдаются + +### Requirement: Токены +Access-токен SHALL действовать 1 час, refresh — 30 дней с ротацией при использовании; +храниться только в виде хэшей; пользователь видит подключённые приложения и может +отозвать доступ, после чего токены приложения не работают. + +#### Scenario: Отзыв +- **WHEN** пользователь отзывает приложение в вебе +- **THEN** следующий запрос этого приложения к `/mcp` получает 401 + +### Requirement: Инструменты PM +MCP SHALL давать инструменты в пределах проектов пользователя: список проектов и целей, +список и детали задач, создание задачи, перенос карточки (Бэклог/В работе/Ревью/Готово — +с теми же последствиями, что на доске), открытые вопросы и ответ на них, приёмка ревью. + +#### Scenario: Двинуть задачу +- **WHEN** клиент вызывает перенос задачи `PEP-3` в «В работе» +- **THEN** задача `in_progress` и по ней запущен агент, как при переносе на доске + +#### Scenario: Чужой проект +- **WHEN** клиент обращается к задаче проекта, которым пользователь не владеет +- **THEN** получает «не найдено» diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c29e957c..d755f68a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -10,3 +10,4 @@ export * from "./telegram.ts"; export * from "./crypto.ts"; export * from "./gitea.ts"; export * from "./users.ts"; +export * from "./oauth.ts"; diff --git a/packages/core/src/oauth.ts b/packages/core/src/oauth.ts new file mode 100644 index 00000000..942e7154 --- /dev/null +++ b/packages/core/src/oauth.ts @@ -0,0 +1,181 @@ +// OAuth 2.1 authorization server for Peppa's remote MCP (ChatGPT connectors etc.): +// dynamic client registration, authorization code + PKCE (S256), access/refresh tokens. +import { createHash, randomBytes } from "node:crypto"; +import { oauthClients, oauthCodes, oauthTokens, type Db } from "@peppa/db"; +import { and, desc, eq, gt, isNull } from "drizzle-orm"; +import { hashToken } from "./crypto.ts"; +import { PeppaError } from "./errors.ts"; + +export type OAuthClient = typeof oauthClients.$inferSelect; + +export const ACCESS_TTL_SEC = 3600; +const REFRESH_TTL_SEC = 30 * 86400; +const CODE_TTL_MS = 10 * 60_000; + +export class OAuthError extends PeppaError { + constructor( + readonly error: "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied", + description: string, + ) { + super(description); + } +} + +const random = () => randomBytes(32).toString("base64url"); + +function validRedirect(uri: string): boolean { + try { + const u = new URL(uri); + if (u.hash) return false; + return u.protocol === "https:" || (u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname)); + } catch { + return false; + } +} + +/** RFC 7591 dynamic client registration (public clients, PKCE required). */ +export async function registerClient(db: Db, name: string | undefined, redirectUris: unknown): Promise { + if (!Array.isArray(redirectUris) || !redirectUris.length || !redirectUris.every((u) => typeof u === "string" && validRedirect(u))) { + throw new OAuthError("invalid_redirect_uri", "redirect_uris must be https (or http://localhost) URLs"); + } + const [row] = await db + .insert(oauthClients) + .values({ id: `peppa-${randomBytes(12).toString("base64url")}`, name: (name || "MCP client").slice(0, 100), redirectUris }) + .returning(); + return row!; +} + +export async function getClient(db: Db, id: string): Promise { + const [row] = await db.select().from(oauthClients).where(eq(oauthClients.id, id)); + return row ?? null; +} + +export interface AuthorizeRequest { + clientId: string; + redirectUri: string; + codeChallenge: string; + codeChallengeMethod: string; + responseType: string; + scope?: string; +} + +/** Validates an /authorize request; throws OAuthError (shown to the user, not redirected). */ +export async function checkAuthorizeRequest(db: Db, r: AuthorizeRequest): Promise { + const client = await getClient(db, r.clientId); + if (!client) throw new OAuthError("invalid_client", "Неизвестное приложение (client_id)"); + if (!client.redirectUris.includes(r.redirectUri)) throw new OAuthError("invalid_redirect_uri", "redirect_uri не зарегистрирован для приложения"); + if (r.responseType !== "code") throw new OAuthError("invalid_request", "response_type должен быть code"); + if (r.codeChallengeMethod !== "S256" || !/^[A-Za-z0-9_-]{43,128}$/.test(r.codeChallenge)) { + throw new OAuthError("invalid_request", "Нужен PKCE (code_challenge, метод S256)"); + } + return client; +} + +/** Issues a one-time authorization code after the user consented. */ +export async function issueCode(db: Db, r: AuthorizeRequest, userId: number): Promise { + await checkAuthorizeRequest(db, r); + const code = random(); + await db.insert(oauthCodes).values({ + codeHash: hashToken(code), + clientId: r.clientId, + userId, + redirectUri: r.redirectUri, + codeChallenge: r.codeChallenge, + scope: r.scope ?? null, + expiresAt: new Date(Date.now() + CODE_TTL_MS), + }); + return code; +} + +export interface TokenResponse { + access_token: string; + token_type: "Bearer"; + expires_in: number; + refresh_token: string; + scope?: string; +} + +async function issueTokens(db: Db, clientId: string, userId: number, scope: string | null): Promise { + const access = random(); + const refresh = random(); + await db.insert(oauthTokens).values([ + { tokenHash: hashToken(access), kind: "access", clientId, userId, scope, expiresAt: new Date(Date.now() + ACCESS_TTL_SEC * 1000) }, + { tokenHash: hashToken(refresh), kind: "refresh", clientId, userId, scope, expiresAt: new Date(Date.now() + REFRESH_TTL_SEC * 1000) }, + ]); + return { access_token: access, token_type: "Bearer", expires_in: ACCESS_TTL_SEC, refresh_token: refresh, ...(scope ? { scope } : {}) }; +} + +const s256 = (verifier: string) => createHash("sha256").update(verifier).digest("base64url"); + +/** POST /oauth/token for authorization_code and refresh_token grants. */ +export async function exchangeToken(db: Db, p: Record): Promise { + if (p.grant_type === "authorization_code") { + if (!p.code || !p.client_id || !p.redirect_uri || !p.code_verifier) throw new OAuthError("invalid_request", "code, client_id, redirect_uri and code_verifier are required"); + // Mark used atomically: a replayed code never yields tokens. + const [c] = await db + .update(oauthCodes) + .set({ usedAt: new Date() }) + .where(and(eq(oauthCodes.codeHash, hashToken(p.code)), isNull(oauthCodes.usedAt), gt(oauthCodes.expiresAt, new Date()))) + .returning(); + if (!c) throw new OAuthError("invalid_grant", "code is invalid, expired or already used"); + if (c.clientId !== p.client_id || c.redirectUri !== p.redirect_uri) throw new OAuthError("invalid_grant", "client_id or redirect_uri mismatch"); + if (s256(p.code_verifier) !== c.codeChallenge) throw new OAuthError("invalid_grant", "PKCE verification failed"); + return issueTokens(db, c.clientId, c.userId, c.scope); + } + if (p.grant_type === "refresh_token") { + if (!p.refresh_token) throw new OAuthError("invalid_request", "refresh_token is required"); + const [t] = await db + .update(oauthTokens) + .set({ revokedAt: new Date() }) + .where( + and( + eq(oauthTokens.tokenHash, hashToken(p.refresh_token)), + eq(oauthTokens.kind, "refresh"), + isNull(oauthTokens.revokedAt), + gt(oauthTokens.expiresAt, new Date()), + ), + ) + .returning(); + if (!t || (p.client_id && p.client_id !== t.clientId)) throw new OAuthError("invalid_grant", "refresh_token is invalid"); + return issueTokens(db, t.clientId, t.userId, t.scope); + } + throw new OAuthError("unsupported_grant_type", `grant_type ${p.grant_type ?? "(none)"} is not supported`); +} + +/** Bearer token → { userId, clientId }, or null. */ +export async function verifyAccessToken(db: Db, token: string | undefined | null): Promise<{ userId: number; clientId: string } | null> { + if (!token) return null; + const [t] = await db + .update(oauthTokens) + .set({ lastUsedAt: new Date() }) + .where(and(eq(oauthTokens.tokenHash, hashToken(token)), eq(oauthTokens.kind, "access"), isNull(oauthTokens.revokedAt), gt(oauthTokens.expiresAt, new Date()))) + .returning(); + return t ? { userId: t.userId, clientId: t.clientId } : null; +} + +/** Apps the user has granted access to (live refresh tokens), most recent first. */ +export async function connectedApps(db: Db, userId: number) { + const rows = await db + .select({ clientId: oauthTokens.clientId, name: oauthClients.name, createdAt: oauthTokens.createdAt, lastUsedAt: oauthTokens.lastUsedAt }) + .from(oauthTokens) + .innerJoin(oauthClients, eq(oauthTokens.clientId, oauthClients.id)) + .where(and(eq(oauthTokens.userId, userId), isNull(oauthTokens.revokedAt), gt(oauthTokens.expiresAt, new Date()))) + .orderBy(desc(oauthTokens.createdAt)); + const byClient = new Map(); + for (const r of rows) { + const cur = byClient.get(r.clientId); + if (!cur) byClient.set(r.clientId, { clientId: r.clientId, name: r.name, since: r.createdAt, lastUsedAt: r.lastUsedAt }); + else if (r.lastUsedAt && (!cur.lastUsedAt || r.lastUsedAt > cur.lastUsedAt)) cur.lastUsedAt = r.lastUsedAt; + } + return [...byClient.values()]; +} + +/** Revokes every token of `clientId` for this user. */ +export async function revokeApp(db: Db, userId: number, clientId: string): Promise { + const rows = await db + .update(oauthTokens) + .set({ revokedAt: new Date() }) + .where(and(eq(oauthTokens.userId, userId), eq(oauthTokens.clientId, clientId), isNull(oauthTokens.revokedAt))) + .returning(); + return rows.length; +} diff --git a/packages/db/migrations/0006_crazy_stellaris.sql b/packages/db/migrations/0006_crazy_stellaris.sql new file mode 100644 index 00000000..d458e934 --- /dev/null +++ b/packages/db/migrations/0006_crazy_stellaris.sql @@ -0,0 +1,34 @@ +CREATE TABLE "oauth_clients" ( + "id" text PRIMARY KEY NOT NULL, + "name" text NOT NULL, + "redirect_uris" jsonb NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "oauth_codes" ( + "code_hash" text PRIMARY KEY NOT NULL, + "client_id" text NOT NULL, + "user_id" integer NOT NULL, + "redirect_uri" text NOT NULL, + "code_challenge" text NOT NULL, + "scope" text, + "expires_at" timestamp with time zone NOT NULL, + "used_at" timestamp with time zone +); +--> statement-breakpoint +CREATE TABLE "oauth_tokens" ( + "token_hash" text PRIMARY KEY NOT NULL, + "kind" text NOT NULL, + "client_id" text NOT NULL, + "user_id" integer NOT NULL, + "scope" text, + "expires_at" timestamp with time zone NOT NULL, + "revoked_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "last_used_at" timestamp with time zone +); +--> statement-breakpoint +ALTER TABLE "oauth_codes" ADD CONSTRAINT "oauth_codes_client_id_oauth_clients_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_clients"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "oauth_codes" ADD CONSTRAINT "oauth_codes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "oauth_tokens" ADD CONSTRAINT "oauth_tokens_client_id_oauth_clients_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_clients"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "oauth_tokens" ADD CONSTRAINT "oauth_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action; \ No newline at end of file diff --git a/packages/db/migrations/meta/0006_snapshot.json b/packages/db/migrations/meta/0006_snapshot.json new file mode 100644 index 00000000..c656e4b6 --- /dev/null +++ b/packages/db/migrations/meta/0006_snapshot.json @@ -0,0 +1,1231 @@ +{ + "id": "141bce5b-54a3-438f-b6c9-edf22525ab7b", + "prevId": "62fecad8-73cc-4298-a603-a38021323859", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 3f8f0819..2126e00e 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1794499927803, "tag": "0005_sloppy_blue_marvel", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1794500991061, + "tag": "0006_crazy_stellaris", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index f2390918..f9178bac 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -177,6 +177,39 @@ export const telegramUpdates = pgTable("telegram_updates", { createdAt: createdAt(), }); +/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */ +export const oauthClients = pgTable("oauth_clients", { + id: text("id").primaryKey(), + name: text("name").notNull(), + redirectUris: jsonb("redirect_uris").$type().notNull(), + createdAt: createdAt(), +}); + +/** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */ +export const oauthCodes = pgTable("oauth_codes", { + codeHash: text("code_hash").primaryKey(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + redirectUri: text("redirect_uri").notNull(), + codeChallenge: text("code_challenge").notNull(), + scope: text("scope"), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + usedAt: timestamp("used_at", { withTimezone: true }), +}); + +/** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */ +export const oauthTokens = pgTable("oauth_tokens", { + tokenHash: text("token_hash").primaryKey(), + kind: text("kind", { enum: ["access", "refresh"] }).notNull(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + scope: text("scope"), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + createdAt: createdAt(), + lastUsedAt: timestamp("last_used_at", { withTimezone: true }), +}); + export const projectsRelations = relations(projects, ({ many }) => ({ goals: many(goals), tasks: many(tasks), diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 8ca924af..f38906c2 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -3,13 +3,23 @@ "version": "0.0.0", "private": true, "type": "module", - "bin": { "peppa-mcp": "./bin/peppa-mcp" }, - "scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." }, + "bin": { + "peppa-mcp": "./bin/peppa-mcp" + }, + "scripts": { + "start": "tsx src/index.ts", + "typecheck": "tsc -p ." + }, "dependencies": { "@modelcontextprotocol/sdk": "1.32.2", "@peppa/core": "workspace:*", "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*", - "zod": "4.6.7" + "zod": "4.6.7", + "@peppa/runner": "workspace:*", + "drizzle-orm": "0.45.4" + }, + "exports": { + "./manager": "./src/manager.ts" } } diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts new file mode 100644 index 00000000..6aed54f6 --- /dev/null +++ b/packages/mcp/src/manager.ts @@ -0,0 +1,150 @@ +// PM-side MCP tools for remote clients (ChatGPT connectors etc.), scoped to one Peppa +// user's projects. Served over HTTP by the web app at /mcp; agents keep the stdio server. +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { + createTask, + getProject, + getQuestion, + getTaskDetails, + listGoals, + listTasks, + listUserProjects, + PeppaError, + projectForUser, + resolveTask, + type User, +} from "@peppa/core"; +import { questions, projects, tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, type BoardColumn, type Provider } from "@peppa/runner"; +import { and, asc, eq, isNull } from "drizzle-orm"; +import { z } from "zod"; +import { formatTask } from "./format.ts"; + +type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean }; +const COLUMNS = ["backlog", "in_progress", "review", "done"] as const; +const COLUMN_NAME: Record = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" }; + +export function createManagerServer(db: Db, user: User, webUrl: string): McpServer { + const server = new McpServer({ name: "peppa", version: "0.2.0" }); + + function tool(name: string, description: string, inputSchema: S, readOnly: boolean, run: (a: z.infer>) => Promise) { + server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: readOnly, openWorldHint: false } }, (async (a: z.infer>): Promise => { + try { + return { content: [{ type: "text", text: await run(a) }] }; + } catch (e) { + return { content: [{ type: "text", text: e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}` }], isError: true }; + } + }) as never); + } + + const ownedProject = async (keyOrSlug: string) => projectForUser(db, user.id, (await getProject(db, keyOrSlug).catch(() => { throw new PeppaError("Не найдено"); })).id); + const ownedTask = async (key: string) => { + const ref = await resolveTask(db, key).catch(() => { throw new PeppaError("Не найдено"); }); + await projectForUser(db, user.id, ref.project.id); + return ref; + }; + const taskArg = z.string().describe("Task key, e.g. PEP-3"); + const projectArg = z.string().describe("Project key (e.g. PEP) or slug"); + + tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo, task counts by board column).", {}, true, async () => { + const ps = await listUserProjects(db, user.id); + if (!ps.length) return "No projects yet. Create one at " + webUrl + "/projects/new"; + const lines = []; + for (const p of ps) { + const ts = await listTasks(db, { projectId: p.id }); + const counts = COLUMNS.map((c) => `${COLUMN_NAME[c]} ${ts.filter((t) => columnOf(t.status) === c).length}`).join(", "); + lines.push(`- ${p.key} — ${p.name} (${p.giteaOwner}/${p.giteaRepo}): ${counts}`); + } + return lines.join("\n"); + }); + + tool("list_goals", "List open top-level goals of a project.", { project: projectArg }, true, async ({ project }) => { + const p = await ownedProject(project); + const gs = await listGoals(db, p.id); + return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open goals."; + }); + + tool( + "list_tasks", + "List tasks of a project as a board (Backlog / In progress / Review / Done), optionally one column.", + { project: projectArg, column: z.enum(COLUMNS).optional() }, + true, + async ({ project, column }) => { + const p = await ownedProject(project); + const ts = await listTasks(db, { projectId: p.id }); + const out: string[] = []; + for (const c of column ? [column] : COLUMNS) { + const inCol = ts.filter((t) => columnOf(t.status) === c); + out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (goal #${t.goalId})` : ""} ${t.title}`)); + } + return out.join("\n"); + }, + ); + + tool("get_task", "Get a task: description, goal, status, OpenSpec change, PM questions, progress.", { task: taskArg }, true, async ({ task }) => { + const ref = await ownedTask(task); + return `${formatTask(await getTaskDetails(db, ref))}\n\nWeb: ${webUrl}/t/${ref.key}`; + }); + + tool( + "create_task", + "Create a task in a project (lands in Backlog). Link it to a goal when possible.", + { project: projectArg, title: z.string().min(3), description: z.string().optional(), goal_id: z.number().int().optional() }, + false, + async ({ project, title, description, goal_id }) => { + const p = await ownedProject(project); + const ref = await createTask(db, { projectId: p.id, title, description, goalId: goal_id }); + return `Created ${ref.key}: ${title} (Backlog). ${webUrl}/t/${ref.key}`; + }, + ); + + tool( + "move_task", + "Move a task card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.", + { task: taskArg, to: z.enum(COLUMNS), provider: z.enum(["claude", "codex"]).optional().describe("Agent for in_progress (default claude)") }, + false, + async ({ task, to, provider }) => { + const ref = await ownedTask(task); + const r = await moveTask(db, ref, to, { provider: provider as Provider | undefined }); + return `${ref.key} → ${COLUMN_NAME[to]}${r.started ? ` · agent session #${r.started} started` : ""}${r.stopped ? ` · ${r.stopped} session(s) stopped` : ""}`; + }, + ); + + tool("list_inbox", "Open questions from agents waiting for the user (approvals, questions, permissions, ready-for-review), oldest first.", {}, true, async () => { + const rows = await db + .select({ q: questions, key: projects.key, number: tasks.number, status: tasks.status }) + .from(questions) + .innerJoin(projects, eq(questions.projectId, projects.id)) + .leftJoin(tasks, eq(questions.taskId, tasks.id)) + .where(and(eq(projects.ownerId, user.id), isNull(questions.answeredAt))) + .orderBy(asc(questions.id)); + if (!rows.length) return "Inbox is empty — agents need nothing from you."; + return rows + .map(({ q, key, number, status }) => { + const kind = q.kind === "attention" && status === "review" ? "ready for review (answer 'accept' or a comment)" : q.kind; + return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}`; + }) + .join("\n"); + }); + + tool( + "answer_question", + "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' closes the task, any other text goes back to the agent.", + { question_id: z.number().int(), answer: z.string().min(1) }, + false, + async ({ question_id, answer }) => { + const q = await getQuestion(db, question_id).catch(() => { throw new PeppaError("Не найдено"); }); + await projectForUser(db, user.id, q.projectId); + if (q.answeredAt) return `Already answered (${q.answeredVia}): ${q.answer}`; + if (answer.trim().toLowerCase() === "accept" && (await isReviewQuestion(db, q))) { + const ref = await acceptTask(db, q.id, "web"); + return `${ref.key} accepted → Done`; + } + const { delivered } = await answerAndDeliver(db, q.id, answer, "web"); + return delivered ? "Delivered to the agent session." : "Saved; the session is not running right now."; + }, + ); + + return server; +} diff --git a/packages/testkit/package.json b/packages/testkit/package.json index f8220cca..4a9e15a9 100644 --- a/packages/testkit/package.json +++ b/packages/testkit/package.json @@ -14,6 +14,7 @@ "@peppa/runner": "workspace:*", "@peppa/shared": "workspace:*", "drizzle-orm": "0.45.4", - "@peppa/bot": "workspace:*" + "@peppa/bot": "workspace:*", + "@peppa/mcp": "workspace:*" } } diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts new file mode 100644 index 00000000..eeb62c01 --- /dev/null +++ b/packages/testkit/test/oauth.test.ts @@ -0,0 +1,127 @@ +// PEP-8: OAuth 2.1 server and the PM MCP tools served to remote clients (ChatGPT). +import assert from "node:assert/strict"; +import { createHash, randomBytes } from "node:crypto"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const { createManagerServer } = await import("@peppa/mcp/manager"); + +const REDIRECT = "https://chatgpt.com/connector_platform_oauth_redirect"; +let owner: Awaited>; +let stranger: Awaited>; + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 21, login: "mock-owner" }, { access_token: "x" }); + stranger = await core.upsertUserFromGitea(db, { id: 22, login: "mock-stranger" }, { access_token: "y" }); +}); +after(teardown); + +const pkce = () => { + const verifier = randomBytes(32).toString("base64url"); + return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") }; +}; + +async function authorize(clientId: string, userId: number, challenge: string) { + return core.issueCode(db, { clientId, redirectUri: REDIRECT, codeChallenge: challenge, codeChallengeMethod: "S256", responseType: "code" }, userId); +} + +describe("OAuth server", () => { + test("dynamic registration accepts https/localhost redirects only", async () => { + await assert.rejects(core.registerClient(db, "bad", ["http://evil.example/cb"]), /redirect_uris/); + await assert.rejects(core.registerClient(db, "bad", []), /redirect_uris/); + const c = await core.registerClient(db, "ChatGPT", [REDIRECT, "http://localhost:8765/cb"]); + assert.match(c.id, /^peppa-/); + }); + + test("authorize request validation", async () => { + const c = await core.registerClient(db, "ChatGPT", [REDIRECT]); + const ok = { clientId: c.id, redirectUri: REDIRECT, codeChallenge: pkce().challenge, codeChallengeMethod: "S256", responseType: "code" }; + await core.checkAuthorizeRequest(db, ok); + await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, clientId: "nope" }), /Неизвестное приложение/); + await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, redirectUri: "https://other.example/cb" }), /не зарегистрирован/); + await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, codeChallengeMethod: "plain" }), /PKCE/); + }); + + test("code + PKCE → tokens; replay, wrong verifier and wrong redirect are refused", async () => { + const c = await core.registerClient(db, "ChatGPT", [REDIRECT]); + const { verifier, challenge } = pkce(); + const code = await authorize(c.id, owner.id, challenge); + const base = { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT }; + const t = await core.exchangeToken(db, { ...base, code, code_verifier: verifier }); + assert.equal(t.token_type, "Bearer"); + assert.deepEqual(await core.verifyAccessToken(db, t.access_token), { userId: owner.id, clientId: c.id }); + await assert.rejects(core.exchangeToken(db, { ...base, code, code_verifier: verifier }), /already used/); + + const p2 = pkce(); + const code2 = await authorize(c.id, owner.id, p2.challenge); + await assert.rejects(core.exchangeToken(db, { ...base, code: code2, code_verifier: pkce().verifier }), /PKCE/); + const p3 = pkce(); + const code3 = await authorize(c.id, owner.id, p3.challenge); + await assert.rejects(core.exchangeToken(db, { ...base, redirect_uri: "https://other.example/cb", code: code3, code_verifier: p3.verifier }), /mismatch/); + assert.equal(await core.verifyAccessToken(db, "garbage"), null); + }); + + test("refresh tokens rotate; revoking the app kills its tokens", async () => { + const c = await core.registerClient(db, "ChatGPT revoke", [REDIRECT]); + const { verifier, challenge } = pkce(); + const t1 = await core.exchangeToken(db, { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT, code: await authorize(c.id, owner.id, challenge), code_verifier: verifier }); + const t2 = await core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token, client_id: c.id }); + await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token }), /invalid/, "old refresh token is single use"); + assert.ok(await core.verifyAccessToken(db, t2.access_token)); + assert.ok((await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id)); + assert.ok((await core.revokeApp(db, owner.id, c.id)) > 0); + assert.equal(await core.verifyAccessToken(db, t2.access_token), null); + await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t2.refresh_token }), /invalid/); + assert.ok(!(await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id)); + }); +}); + +async function mcpAs(user: typeof owner) { + const [a, b] = InMemoryTransport.createLinkedPair(); + await createManagerServer(db, user, "https://peppa.test").connect(a); + const client = new Client({ name: "mock-chatgpt", version: "0" }); + await client.connect(b); + const call = async (name: string, args: Record = {}) => { + const r = await client.callTool({ name, arguments: args }); + return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError }; + }; + return { client, call }; +} + +describe("PM tools over MCP", () => { + test("list, create, move (starts an agent), inbox, answer; strangers see nothing", async () => { + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] }); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, owner.id); + const { client, call } = await mcpAs(owner); + const tools = (await client.listTools()).tools; + assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task"]); + assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); + assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); + + assert.match((await call("list_projects")).text, new RegExp(`${p.key} — `)); + const created = await call("create_task", { project: p.key, title: "Из ChatGPT: порт сервиса" }); + assert.match(created.text, new RegExp(`Created ${p.key}-2`)); + assert.match((await call("list_tasks", { project: p.key, column: "backlog" })).text, /Из ChatGPT/); + + const moved = await call("move_task", { task: `${p.key}-2`, to: "in_progress" }); + assert.match(moved.text, /agent session #\d+ started/); + const sid = Number(/#(\d+)/.exec(moved.text)![1]); + const q = await p.waitQuestion(sid, "question"); + assert.match((await call("list_inbox")).text, new RegExp(`#${q.id} ${p.key}-2 · question`)); + assert.match((await call("answer_question", { question_id: q.id, answer: "3000" })).text, /Delivered/); + await p.waitLog("answer reached the agent", (e) => e.ev === "prompt" && String(e.prompt).includes(": 3000")); + + const s = await mcpAs(stranger); + assert.match((await s.call("list_projects")).text, /No projects/); + const denied = await s.call("move_task", { task: `${p.key}-2`, to: "backlog" }); + assert.ok(denied.isError); + assert.match(denied.text, /Не найдено/); + assert.ok((await s.call("answer_question", { question_id: q.id, answer: "x" })).isError); + + assert.match((await call("move_task", { task: `${p.key}-2`, to: "backlog" })).text, /1 session\(s\) stopped/); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a62b0de..3bacea5e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -196,12 +196,18 @@ importers: apps/web: dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.32.2 + version: 1.32.2(zod@4.6.7) '@peppa/core': specifier: workspace:* version: link:../../packages/core '@peppa/db': specifier: workspace:* version: link:../../packages/db + '@peppa/mcp': + specifier: workspace:* + version: link:../../packages/mcp '@peppa/runner': specifier: workspace:* version: link:../../packages/runner @@ -282,9 +288,15 @@ importers: '@peppa/db': specifier: workspace:* version: link:../db + '@peppa/runner': + specifier: workspace:* + version: link:../runner '@peppa/shared': specifier: workspace:* version: link:../shared + drizzle-orm: + specifier: 0.45.4 + version: 0.45.4(postgres@4.1.1) zod: specifier: 4.6.7 version: 4.6.7 @@ -324,6 +336,9 @@ importers: '@peppa/db': specifier: workspace:* version: link:../db + '@peppa/mcp': + specifier: workspace:* + version: link:../mcp '@peppa/runner': specifier: workspace:* version: link:../runner