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>
This commit is contained in:
parent
65311a462e
commit
39367b1d82
@ -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-<task>-s<id>`), вачдог, `peppa-hook`
|
||||
|
||||
@ -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"));
|
||||
});
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
<nav>
|
||||
<Link href="/">Входящие</Link>
|
||||
<Link href="/projects/new">Новый проект</Link>
|
||||
<Link href="/settings">Настройки</Link>
|
||||
</nav>
|
||||
<div className="me">
|
||||
{user.avatarUrl && <img src={user.avatarUrl} alt="" width={24} height={24} />}
|
||||
|
||||
42
apps/web/app/(app)/settings/page.tsx
Normal file
42
apps/web/app/(app)/settings/page.tsx
Normal file
@ -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 (
|
||||
<section className="narrow">
|
||||
<Flash error={error} />
|
||||
<h1>Настройки</h1>
|
||||
<h2>MCP для ChatGPT и других клиентов</h2>
|
||||
<p>
|
||||
Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент
|
||||
зарегистрируется сам, вы подтвердите доступ на экране Пеппы.
|
||||
</p>
|
||||
<code className="mcp-url">{origin}/mcp</code>
|
||||
<h2>Подключённые приложения</h2>
|
||||
{apps.length === 0 ? (
|
||||
<p className="empty">Нет подключённых приложений.</p>
|
||||
) : (
|
||||
apps.map((a) => (
|
||||
<article key={a.clientId} className="card row">
|
||||
<div className="grow">
|
||||
<b>{a.name}</b>
|
||||
<div className="muted">с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}</div>
|
||||
</div>
|
||||
<form action={revokeConnectedApp}>
|
||||
<input type="hidden" name="clientId" value={a.clientId} />
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button className="danger">Отозвать</button>
|
||||
</form>
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,4 @@
|
||||
import { authServerMetadata, json, preflight } from "@/lib/oauth";
|
||||
|
||||
export const GET = async () => json(await authServerMetadata());
|
||||
export const OPTIONS = preflight;
|
||||
@ -0,0 +1,4 @@
|
||||
import { json, preflight, resourceMetadata } from "@/lib/oauth";
|
||||
|
||||
export const GET = async () => json(await resourceMetadata());
|
||||
export const OPTIONS = preflight;
|
||||
4
apps/web/app/.well-known/openid-configuration/route.ts
Normal file
4
apps/web/app/.well-known/openid-configuration/route.ts
Normal file
@ -0,0 +1,4 @@
|
||||
import { authServerMetadata, json, preflight } from "@/lib/oauth";
|
||||
|
||||
export const GET = async () => json(await authServerMetadata());
|
||||
export const OPTIONS = preflight;
|
||||
@ -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" });
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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; }
|
||||
|
||||
@ -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 (
|
||||
<main className="login">
|
||||
<h1>🐷 Peppa</h1>
|
||||
<p className="muted">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p>
|
||||
<Flash error={error} />
|
||||
<a className="button primary" href="/auth/start">Войти через Gitea</a>
|
||||
<a className="button primary" href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
36
apps/web/app/mcp/route.ts
Normal file
36
apps/web/app/mcp/route.ts
Normal file
@ -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;
|
||||
35
apps/web/app/oauth/authorize/actions.ts
Normal file
35
apps/web/app/oauth/authorize/actions.ts
Normal file
@ -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<string, string>, 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") ?? "")));
|
||||
}
|
||||
71
apps/web/app/oauth/authorize/page.tsx
Normal file
71
apps/web/app/oauth/authorize/page.tsx
Normal file
@ -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<string, string | undefined>;
|
||||
|
||||
/** OAuth consent screen: who asks, what they get, allow / deny. */
|
||||
export default async function Authorize({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const p = await searchParams;
|
||||
const user = await currentUser();
|
||||
if (!user) redirect(`/login?next=${encodeURIComponent(`/oauth/authorize?${new URLSearchParams(p as Record<string, string>)}`)}`);
|
||||
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 (
|
||||
<main className="login consent">
|
||||
<h1>🐷 Peppa</h1>
|
||||
{error || !client ? (
|
||||
<p className="flash">Запрос авторизации некорректен: {error}</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
<b>{client.name}</b> <span className="muted">({host})</span> просит доступ к Пеппе от имени <b>{user.login}</b>.
|
||||
</p>
|
||||
<ul className="scopes">
|
||||
<li>видеть ваши проекты, цели, задачи и вопросы агентов;</li>
|
||||
<li>создавать задачи и двигать карточки — перенос в «В работе» запускает агента;</li>
|
||||
<li>отвечать на вопросы агентов и принимать ревью.</li>
|
||||
</ul>
|
||||
<p className="muted">Отозвать доступ можно в «Настройки → Подключённые приложения».</p>
|
||||
<div className="row">
|
||||
<form action={approve}>
|
||||
<Hidden p={p} />
|
||||
<button className="primary">Разрешить</button>
|
||||
</form>
|
||||
<form action={deny}>
|
||||
<Hidden p={p} />
|
||||
<button>Отклонить</button>
|
||||
</form>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function Hidden({ p }: { p: Params }) {
|
||||
return (
|
||||
<>
|
||||
{(["client_id", "redirect_uri", "code_challenge", "code_challenge_method", "response_type", "scope", "state"] as const).map((k) => (
|
||||
<input key={k} type="hidden" name={k} value={p[k] ?? ""} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
27
apps/web/app/oauth/register/route.ts
Normal file
27
apps/web/app/oauth/register/route.ts
Normal file
@ -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;
|
||||
17
apps/web/app/oauth/token/route.ts
Normal file
17
apps/web/app/oauth/token/route.ts
Normal file
@ -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<string, string> = type.includes("application/json")
|
||||
? ((await req.json().catch(() => ({}))) as Record<string, string>)
|
||||
: 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;
|
||||
@ -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 {
|
||||
|
||||
33
apps/web/lib/oauth.ts
Normal file
33
apps/web/lib/oauth.ts
Normal file
@ -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<string, string> = {}) =>
|
||||
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" },
|
||||
});
|
||||
@ -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;
|
||||
|
||||
@ -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",
|
||||
|
||||
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-12
|
||||
@ -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] → клиенты без токенов дешёвые; чистка неиспользуемых позже.
|
||||
@ -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 запросил задачу напрямую.
|
||||
@ -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** получает «не найдено»
|
||||
@ -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`
|
||||
48
openspec/specs/remote-mcp/spec.md
Normal file
48
openspec/specs/remote-mcp/spec.md
Normal file
@ -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** получает «не найдено»
|
||||
@ -10,3 +10,4 @@ export * from "./telegram.ts";
|
||||
export * from "./crypto.ts";
|
||||
export * from "./gitea.ts";
|
||||
export * from "./users.ts";
|
||||
export * from "./oauth.ts";
|
||||
|
||||
181
packages/core/src/oauth.ts
Normal file
181
packages/core/src/oauth.ts
Normal file
@ -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<OAuthClient> {
|
||||
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<OAuthClient | null> {
|
||||
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<OAuthClient> {
|
||||
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<string> {
|
||||
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<TokenResponse> {
|
||||
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<string, string | undefined>): Promise<TokenResponse> {
|
||||
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<string, { clientId: string; name: string; since: Date; lastUsedAt: Date | null }>();
|
||||
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<number> {
|
||||
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;
|
||||
}
|
||||
34
packages/db/migrations/0006_crazy_stellaris.sql
Normal file
34
packages/db/migrations/0006_crazy_stellaris.sql
Normal file
@ -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;
|
||||
1231
packages/db/migrations/meta/0006_snapshot.json
Normal file
1231
packages/db/migrations/meta/0006_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -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<string[]>().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),
|
||||
|
||||
@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
150
packages/mcp/src/manager.ts
Normal file
150
packages/mcp/src/manager.ts
Normal file
@ -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<BoardColumn, string> = { 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<S extends z.ZodRawShape>(name: string, description: string, inputSchema: S, readOnly: boolean, run: (a: z.infer<z.ZodObject<S>>) => Promise<string>) {
|
||||
server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: readOnly, openWorldHint: false } }, (async (a: z.infer<z.ZodObject<S>>): Promise<Result> => {
|
||||
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;
|
||||
}
|
||||
@ -14,6 +14,7 @@
|
||||
"@peppa/runner": "workspace:*",
|
||||
"@peppa/shared": "workspace:*",
|
||||
"drizzle-orm": "0.45.4",
|
||||
"@peppa/bot": "workspace:*"
|
||||
"@peppa/bot": "workspace:*",
|
||||
"@peppa/mcp": "workspace:*"
|
||||
}
|
||||
}
|
||||
|
||||
127
packages/testkit/test/oauth.test.ts
Normal file
127
packages/testkit/test/oauth.test.ts
Normal file
@ -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<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let stranger: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
|
||||
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<string, unknown> = {}) => {
|
||||
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/);
|
||||
});
|
||||
});
|
||||
15
pnpm-lock.yaml
generated
15
pnpm-lock.yaml
generated
@ -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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user