Foundational work for the upcoming group-scoped sharing feature.
Schema (migration 0003_groups.sql + drizzle schema):
- memory_access enum ('ro' | 'rw') reserved for Agent B's project_shares
- groups (id, oidc_iss, name, display_name, …) keyed by (oidc_iss, name)
so different IdPs can both have e.g. "platform" without colliding
- user_groups (user_id, group_id, synced_at) PK (user_id, group_id)
Auth (auth.ts + lib/auth/sync-groups.ts):
- jwt callback now syncs `profile.groups` after upserting the user
- syncUserGroupsFromClaim runs in a single tx: upserts each group,
inserts new memberships, deletes ones no longer in the claim
- missing/empty claim → user has zero groups (wipe memberships)
- EntraID GUID-vs-name edge case: we treat whatever strings the claim
emits as names verbatim; groups overage (>200 groups → no claim)
is documented as unsupported in v1
UserContext + JWT (lib/mcp/context.ts, lib/auth/jwt.ts):
- AuthenticatedClaims.groups surfaced from verified JWT payload
- UserContext.groups: string[] — live from OIDC token claim, falls
back to DB snapshot for CLI (HMAC) tokens which carry no claim
- UserContext.defaultProjectKey: optional, set from header
MCP route (app/api/mcp/route.ts):
- reads X-Project-Key header, validates against ProjectKey Zod schema,
400 on invalid; empty/missing leaves defaultProjectKey undefined
- auto-upserts the header-supplied project so first-use works without
a separate project.identify call
Tools (lib/mcp/tools.ts):
- withDefaultProject helper injects ctx.defaultProjectKey when the
caller omits `project`. Per-tool defaultScope hint avoids breaking
snippet.put (user-scope default) while making memory.write
(project-scope default) honor the header
- applied to memory.write/list/search/update and all snippet.* tools
Web UI:
- /settings/groups debug page lists current memberships with synced_at
and a clear empty state pointing at README troubleshooting
- /settings/tokens grows a "Pin to project" dropdown; selected key is
baked into the generated `claude mcp add` snippet as
`--header "X-Project-Key: <key>"`. The JWT itself stays
identity-only — pinning is purely a UX shortcut
- settings landing page links to /settings/groups
- README troubleshooting bullet covers the empty-groups path for
Authentik / EntraID / Keycloak
Refactor:
- extracted resolveProjectId + upsertProject from memory-actions.ts
into lib/projects.ts so the MCP route can reuse upsertProject
Verification:
- pnpm typecheck clean
- SKIP_ENV_VALIDATION=true pnpm build clean; /settings/groups in route table
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
112 lines
3.8 KiB
TypeScript
112 lines
3.8 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { ProjectKey } from "@shared-memory/schemas";
|
|
import { authenticateBearer, UnauthorizedError } from "@/lib/auth/jwt";
|
|
import { userContextFromClaims } from "@/lib/mcp/context";
|
|
import { dispatchMcpMessage } from "@/lib/mcp/server";
|
|
import { upsertProject } from "@/lib/projects";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
|
|
/**
|
|
* MCP streamable-HTTP endpoint.
|
|
*
|
|
* Auth: Bearer token (Authentik-issued JWT). Unauthed requests get 401 with
|
|
* a WWW-Authenticate header pointing at our RFC 9728 resource metadata
|
|
* so MCP clients can discover the authorization server.
|
|
*
|
|
* Body: JSON-RPC 2.0 message (request or notification).
|
|
*
|
|
* Reply: For requests, the JSON-RPC response in the body with
|
|
* `Content-Type: application/json`.
|
|
* For notifications, HTTP 202 with empty body.
|
|
*/
|
|
|
|
export async function POST(req: Request) {
|
|
// ---- auth ----
|
|
let claims;
|
|
try {
|
|
claims = await authenticateBearer(req.headers.get("authorization"));
|
|
} catch (e) {
|
|
if (e instanceof UnauthorizedError) {
|
|
return new NextResponse(JSON.stringify({ error: e.reason }), {
|
|
status: 401,
|
|
headers: {
|
|
"WWW-Authenticate": e.wwwAuthenticate,
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
}
|
|
throw e;
|
|
}
|
|
|
|
// ---- parse body ----
|
|
let body: unknown;
|
|
try {
|
|
body = await req.json();
|
|
} catch {
|
|
return NextResponse.json(
|
|
{ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
// ---- optional X-Project-Key header → default project for this request ----
|
|
// The header lets a client (e.g. a `claude mcp add` snippet generated from
|
|
// /settings/tokens) pin every call to a specific project without having to
|
|
// pass `project` on each tool invocation. Tools that take an optional
|
|
// `project` arg fall back to this when the caller omits it.
|
|
let defaultProjectKey: string | undefined;
|
|
const rawProjectKey = req.headers.get("x-project-key");
|
|
if (rawProjectKey !== null && rawProjectKey !== "") {
|
|
const parsed = ProjectKey.safeParse(rawProjectKey);
|
|
if (!parsed.success) {
|
|
return NextResponse.json(
|
|
{
|
|
error: "invalid X-Project-Key",
|
|
detail: parsed.error.issues.map((i) => i.message).join("; "),
|
|
},
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
defaultProjectKey = parsed.data;
|
|
}
|
|
|
|
// ---- resolve user, dispatch ----
|
|
const ctx = await userContextFromClaims(claims, { defaultProjectKey });
|
|
|
|
// Auto-create the header-supplied project if it doesn't exist yet. This
|
|
// makes pinning via `X-Project-Key` work transparently — the user doesn't
|
|
// have to call `project.identify` first when they paste the generated
|
|
// `claude mcp add` snippet from /settings/tokens.
|
|
if (defaultProjectKey) {
|
|
await upsertProject(ctx.userId, defaultProjectKey);
|
|
}
|
|
|
|
// MCP supports batched requests (array) and single. Handle both.
|
|
if (Array.isArray(body)) {
|
|
const responses = await Promise.all(body.map((m) => dispatchMcpMessage(m, ctx)));
|
|
const filtered = responses.filter((r) => r !== null);
|
|
if (filtered.length === 0) {
|
|
return new NextResponse(null, { status: 202 });
|
|
}
|
|
return NextResponse.json(filtered, { status: 200 });
|
|
}
|
|
|
|
const response = await dispatchMcpMessage(body, ctx);
|
|
if (response === null) {
|
|
// Notification — no body expected.
|
|
return new NextResponse(null, { status: 202 });
|
|
}
|
|
return NextResponse.json(response, { status: 200 });
|
|
}
|
|
|
|
// MCP clients sometimes probe with GET (for SSE). We don't support
|
|
// server-initiated events in Phase 1 — return 405 with a discoverable header.
|
|
export function GET() {
|
|
return new NextResponse(null, {
|
|
status: 405,
|
|
headers: { Allow: "POST" },
|
|
});
|
|
}
|