From 13a1bcd43a2f71ad77c7c7b852081fc5dd224633 Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 12:05:33 +0300 Subject: [PATCH 1/8] feat: rate limit signed-in registrations per user instead of per IP Users behind a shared IP (an MCP client, the same wifi) no longer share one limit, and a fresh SSO session cannot reset it. Anonymous requests are still limited by IP. The worker now receives the exact key to delete so the key format lives in one place. Co-Authored-By: Claude Opus 5.5 --- .../mutations/claimRegistrationToken.test.ts | 53 ++++++++++++++++++- .../mutations/createRegistration.test.ts | 7 ++- .../src/plugins/EventRegistrationPlugin.ts | 16 ++++-- @app/server/src/plugins/RateLimitPlugin.ts | 28 ++++++++-- .../registration__delete_rate_limit_key.ts | 9 +--- 5 files changed, 93 insertions(+), 20 deletions(-) diff --git a/@app/server/__tests__/mutations/claimRegistrationToken.test.ts b/@app/server/__tests__/mutations/claimRegistrationToken.test.ts index 95f36ca71..a4c82ce5c 100644 --- a/@app/server/__tests__/mutations/claimRegistrationToken.test.ts +++ b/@app/server/__tests__/mutations/claimRegistrationToken.test.ts @@ -1,12 +1,16 @@ import { ClaimRegistrationTokenDocument } from "@app/graphql" +import { ExecutionResult } from "graphql" import { asRoot, createEventDataAndLogin, + createSession, deleteTestData, + poolFromUrl, runGraphQLQuery, setup, teardown, + TEST_DATABASE_URL, } from "../helpers" beforeEach(deleteTestData) @@ -75,7 +79,7 @@ describe("ClaimRegistrationToken", () => { expect(registrationRows[0].email).toBeNull() const rateLimitId = `${eventId}:${quotaId}` - const redisKey = `rate-limit:claimRegistrationToken:${rateLimitId}:${req.ip}` + const redisKey = `rate-limit:claimRegistrationToken:${rateLimitId}:ip:${req.ip}` const value = await redisClient.get(redisKey) // Redis should contain rate limit value after calling @@ -85,6 +89,53 @@ describe("ClaimRegistrationToken", () => { ) }) + it("rate limits a signed-in user per user, not per session", async () => { + const { events, quotas, users, session } = await createEventDataAndLogin() + const eventId = events[0].id + const quotaId = quotas[0].id + const userId = users[0].id + + const pool = poolFromUrl(TEST_DATABASE_URL!) + const client = await pool.connect() + let otherSession: Awaited> + try { + otherSession = await createSession(client, userId) + } finally { + client.release() + } + + const claim = (sessionId: string) => + runGraphQLQuery( + ClaimRegistrationTokenDocument, + { input: { eventId, quotaId } }, + { user: { sessionId } }, + (json) => json, + true, + false + ) + + for (let i = 0; i < 3; i++) { + const json = (await claim(session.uuid)) as ExecutionResult + expect(json.errors).toBeFalsy() + } + + // A fresh session for the same user must not reset the limit. + await runGraphQLQuery( + ClaimRegistrationTokenDocument, + { input: { eventId, quotaId } }, + { user: { sessionId: otherSession.uuid } }, + async (json, { redisClient }) => { + expect(json.errors).toBeTruthy() + expect(json.errors![0].extensions.exception.code).toEqual("RLIMIT") + + const key = `rate-limit:claimRegistrationToken:${eventId}:${quotaId}:user:${userId}` + expect(await redisClient.get(key)).toEqual("3") + }, + true, + false + ) + }) + it("can't claim a token when eventId is incorrect", async () => { const { quotas } = await createEventDataAndLogin() const quotaId = quotas[0].id diff --git a/@app/server/__tests__/mutations/createRegistration.test.ts b/@app/server/__tests__/mutations/createRegistration.test.ts index c36e82bf2..735022058 100644 --- a/@app/server/__tests__/mutations/createRegistration.test.ts +++ b/@app/server/__tests__/mutations/createRegistration.test.ts @@ -112,9 +112,8 @@ describe("CreateRegistration", () => { expect(rateLimitjobs).toHaveLength(1) const [rateLimitJob] = rateLimitjobs - expect(rateLimitJob.payload).toMatchObject({ - eventId: eventId, - ipAddress: req.ip, + expect(rateLimitJob.payload).toEqual({ + key: `rate-limit:claimRegistrationToken:${eventId}:${quotaId}:ip:${req.ip}`, }) const confirmationEmailJobs = await getJobs( @@ -153,7 +152,7 @@ describe("CreateRegistration", () => { // Redis should not contain a rate limiting key after // successful registration const rateLimitId = `${eventId}:${quotaId}` - const key = `rate-limit:claimRegistrationToken:${rateLimitId}:127.1.1.1` + const key = `rate-limit:claimRegistrationToken:${rateLimitId}:ip:127.1.1.1` const value = await redisClient.get(key) expect(value).toEqual(null) // TODO: Figure out a way to test gdpr__delete_event_registrations diff --git a/@app/server/src/plugins/EventRegistrationPlugin.ts b/@app/server/src/plugins/EventRegistrationPlugin.ts index 8fb42023d..23a53f37e 100644 --- a/@app/server/src/plugins/EventRegistrationPlugin.ts +++ b/@app/server/src/plugins/EventRegistrationPlugin.ts @@ -2,6 +2,8 @@ import { makeWrapResolversPlugin } from "graphile-utils" import { OurGraphQLContext } from "../middleware/installPostGraphile" +import { constructRateLimitKey, rateLimitRequester } from "./RateLimitPlugin" + const EventRegistrationPlugin = makeWrapResolversPlugin({ Mutation: { createRegistration: { @@ -22,8 +24,16 @@ const EventRegistrationPlugin = makeWrapResolversPlugin({ const result = await resolve() const workerUtils = context.workerUtils - const ipAddress = context.ipAddress const { eventId, quotaId } = args.input + const requester = await rateLimitRequester( + pgClient, + context.ipAddress + ) + const key = constructRateLimitKey( + "claimRegistrationToken", + `${eventId}:${quotaId}`, + requester + ) // After successfull registration delete the rate limit key from redis. // Awaiting here ensures the job row is committed before this resolver @@ -32,9 +42,7 @@ const EventRegistrationPlugin = makeWrapResolversPlugin({ // unawaited fire-and-forget pattern raced the test queries that // immediately read the queue. await workerUtils.addJob("registration__delete_rate_limit_key", { - eventId, - quotaId, - ipAddress, + key, }) // Return the result of our original mutation diff --git a/@app/server/src/plugins/RateLimitPlugin.ts b/@app/server/src/plugins/RateLimitPlugin.ts index 70bf7868e..544be13ef 100644 --- a/@app/server/src/plugins/RateLimitPlugin.ts +++ b/@app/server/src/plugins/RateLimitPlugin.ts @@ -1,4 +1,5 @@ import { makeWrapResolversPlugin } from "graphile-utils" +import { PoolClient } from "pg" import { OurGraphQLContext } from "../middleware/installPostGraphile" @@ -9,12 +10,30 @@ if (!process.env.NODE_ENV) { // 30 minutes timeout const RATE_LIMIT_TIMEOUT = 30 -function constructRateLimitKey( +/** + * Signed-in users are limited per user rather than per session: with Keycloak + * SSO a fresh session costs a single redirect, so a per-session limit could be + * reset at will. current_user_id() also proves the session still exists; a + * stale cookie falls back to the IP address like an anonymous request. + */ +export async function rateLimitRequester( + pgClient: PoolClient, + ipAddress: string +) { + const { + rows: [row], + } = await pgClient.query<{ user_id: string | null }>( + "select app_public.current_user_id() as user_id" + ) + return row?.user_id ? `user:${row.user_id}` : `ip:${ipAddress}` +} + +export function constructRateLimitKey( fieldName: string, id: string, - ipAddress: string + requester: string ) { - return `rate-limit:${fieldName}:${id}:${ipAddress}` + return `rate-limit:${fieldName}:${id}:${requester}` } class RateLimitException extends Error { @@ -49,7 +68,8 @@ function rateLimitResolver( // to set a rate limit key to redis const result = await resolve() - const key = constructRateLimitKey(fieldName, rateLimitId, ipAddress) + const requester = await rateLimitRequester(pgClient, ipAddress) + const key = constructRateLimitKey(fieldName, rateLimitId, requester) const current = Number(await redisClient.get(key)) if (current >= limit) { diff --git a/@app/worker/src/tasks/registration__delete_rate_limit_key.ts b/@app/worker/src/tasks/registration__delete_rate_limit_key.ts index bc7d07f8c..b7a9b7277 100644 --- a/@app/worker/src/tasks/registration__delete_rate_limit_key.ts +++ b/@app/worker/src/tasks/registration__delete_rate_limit_key.ts @@ -3,9 +3,7 @@ import Redis from "ioredis" import type { Task } from "graphile-worker" interface Payload { - eventId: string - quotaId: string - ipAddress: string + key: string } const isTest = process.env.NODE_ENV === "test" @@ -15,10 +13,7 @@ const task: Task = async (inPayload, _helpers) => { const client = new Redis(url) try { const payload: Payload = inPayload as any - const { eventId, quotaId, ipAddress } = payload - - const key = `rate-limit:claimRegistrationToken:${eventId}:${quotaId}:${ipAddress}` - client.del(key) + await client.del(payload.key) } finally { await client.quit() } From 8af458586bd2807f28b75e3b19424f3f3f822b24 Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 12:05:33 +0300 Subject: [PATCH 2/8] feat: add an MCP server for browsing events and registering /mcp is an OAuth-protected Streamable HTTP endpoint. MCP clients sign in with Prodeko accounts against Keycloak (client ilmo-mcp); each verified access token maps to an app_private.sessions row of kind mcp, so RLS, ownership and the existing GraphQL plugins apply exactly as on the web. Tools: list_events, get_event and register_to_event, which validates answers before claiming a spot and rolls the claim back if registration fails. A dev realm with both clients is available via `docker compose --profile keycloak up -d`. Co-Authored-By: Claude Opus 5.5 --- .../app_private/functions/login.test.ts | 8 + @app/db/migrations/current/3-mcp-sessions.sql | 35 ++ ...03127d6ee13d7cb8b2cea72e34568a1fdf.graphql | 59 +++ ...f92cd684511dce76c2b624187013be4600.graphql | 43 ++ @app/graphql/client.json | 4 +- @app/graphql/codegen.yml | 4 +- @app/graphql/server.json | 4 +- @app/server/__tests__/mcp/auth.test.ts | 149 +++++++ .../server/__tests__/mcp/registration.test.ts | 128 ++++++ @app/server/package.json | 5 +- @app/server/src/app.ts | 1 + @app/server/src/mcp/auth.ts | 193 +++++++++ @app/server/src/mcp/operations.graphql | 69 +++ @app/server/src/mcp/registration.ts | 117 +++++ @app/server/src/mcp/server.ts | 231 ++++++++++ @app/server/src/middleware/index.ts | 2 + .../src/middleware/installCSRFProtection.ts | 5 + @app/server/src/middleware/installMcp.ts | 155 +++++++ .../src/middleware/installPostGraphile.ts | 9 + @app/worker/crontab | 1 + .../sessions__delete_inactive_mcp_sessions.ts | 16 + docker-compose.yml | 15 + docker/keycloak/realm-dev.json | 152 +++++++ pnpm-lock.yaml | 402 +++++++++++++++++- 24 files changed, 1799 insertions(+), 8 deletions(-) create mode 100644 @app/db/migrations/current/3-mcp-sessions.sql create mode 100644 @app/graphql/.persisted_operations/2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf.graphql create mode 100644 @app/graphql/.persisted_operations/bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600.graphql create mode 100644 @app/server/__tests__/mcp/auth.test.ts create mode 100644 @app/server/__tests__/mcp/registration.test.ts create mode 100644 @app/server/src/mcp/auth.ts create mode 100644 @app/server/src/mcp/operations.graphql create mode 100644 @app/server/src/mcp/registration.ts create mode 100644 @app/server/src/mcp/server.ts create mode 100644 @app/server/src/middleware/installMcp.ts create mode 100644 @app/worker/src/tasks/sessions__delete_inactive_mcp_sessions.ts create mode 100644 docker/keycloak/realm-dev.json diff --git a/@app/db/__tests__/app_private/functions/login.test.ts b/@app/db/__tests__/app_private/functions/login.test.ts index a72382c7b..e7e872005 100644 --- a/@app/db/__tests__/app_private/functions/login.test.ts +++ b/@app/db/__tests__/app_private/functions/login.test.ts @@ -37,7 +37,9 @@ it("can login with username+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } @@ -53,7 +55,9 @@ it("can login with uSeRnAmE+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } @@ -69,7 +73,9 @@ it("can login with email+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } @@ -85,7 +91,9 @@ it("can login with EmAiL+password", () => expect(snapshotSafe(session)).toMatchInlineSnapshot(` { "created_at": "[DATE]", + "kind": "web", "last_active": "[DATE]", + "oauth_sid": null, "user_id": "[ID]", "uuid": "[UUID]", } diff --git a/@app/db/migrations/current/3-mcp-sessions.sql b/@app/db/migrations/current/3-mcp-sessions.sql new file mode 100644 index 000000000..0ad951916 --- /dev/null +++ b/@app/db/migrations/current/3-mcp-sessions.sql @@ -0,0 +1,35 @@ +/* + * MCP requests authenticate with a Keycloak access token instead of a session + * cookie. The server turns each verified token into an ordinary + * app_private.sessions row so that current_user_id(), RLS and the ownership + * triggers work unchanged, and so that the database keeps identifying users by + * an unguessable session id rather than by a raw user id (see the comment on + * current_user_id). + * + * One MCP session exists per Keycloak session (`oauth_sid`, the token's `sid` + * claim): token refreshes reuse it. The rows are derived state — the server + * recreates one on the next request if it is gone — so inactive MCP sessions + * can be deleted aggressively by the sessions__delete_inactive_mcp_sessions + * task. + */ + +alter table app_private.sessions + add column if not exists kind text not null default 'web', + add column if not exists oauth_sid text; + +alter table app_private.sessions drop constraint if exists sessions_kind_check; +alter table app_private.sessions + add constraint sessions_kind_check check (kind in ('web', 'mcp')); + +alter table app_private.sessions drop constraint if exists sessions_oauth_sid_check; +alter table app_private.sessions + add constraint sessions_oauth_sid_check check ((kind = 'mcp') = (oauth_sid is not null)); + +drop index if exists app_private.sessions_mcp_oauth_sid_key; +create unique index sessions_mcp_oauth_sid_key + on app_private.sessions (oauth_sid) where kind = 'mcp'; + +comment on column app_private.sessions.kind is + E'How the session was established: web (session cookie) or mcp (Keycloak access token on /mcp).'; +comment on column app_private.sessions.oauth_sid is + E'Keycloak session id (the access token sid claim) of an mcp session.'; diff --git a/@app/graphql/.persisted_operations/2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf.graphql b/@app/graphql/.persisted_operations/2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf.graphql new file mode 100644 index 000000000..b01e57dce --- /dev/null +++ b/@app/graphql/.persisted_operations/2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf.graphql @@ -0,0 +1,59 @@ +fragment McpEventSummary on Event { + id + slug + name + location + eventStartTime + eventEndTime + registrationStartTime + registrationEndTime + signupOpen + signupUpcoming + ownerOrganization { + name + __typename + } + category { + name + __typename + } + __typename +} +query McpEvent($slug: String!) { + currentUser { + name + primaryEmail + __typename + } + eventBySlug(slug: $slug) { + ...McpEventSummary + description + isDraft + openQuotaSize + quotas(orderBy: POSITION_ASC) { + nodes { + id + title + size + registrations { + totalCount + __typename + } + __typename + } + __typename + } + eventQuestions(orderBy: POSITION_ASC) { + nodes { + id + type + label + isRequired + data + __typename + } + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/.persisted_operations/bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600.graphql b/@app/graphql/.persisted_operations/bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600.graphql new file mode 100644 index 000000000..c3b9a18ef --- /dev/null +++ b/@app/graphql/.persisted_operations/bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600.graphql @@ -0,0 +1,43 @@ +fragment McpEventSummary on Event { + id + slug + name + location + eventStartTime + eventEndTime + registrationStartTime + registrationEndTime + signupOpen + signupUpcoming + ownerOrganization { + name + __typename + } + category { + name + __typename + } + __typename +} +query McpEvents { + signupOpenEvents: events( + filter: {signupOpen: {equalTo: true}, isDraft: {equalTo: false}} + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC] + ) { + nodes { + ...McpEventSummary + __typename + } + __typename + } + signupUpcomingEvents: events( + filter: {signupUpcoming: {equalTo: true}, isDraft: {equalTo: false}} + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_START_TIME_ASC] + ) { + nodes { + ...McpEventSummary + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/client.json b/@app/graphql/client.json index c68ae7607..9405913fb 100644 --- a/@app/graphql/client.json +++ b/@app/graphql/client.json @@ -59,5 +59,7 @@ "SettingsPassword": "4ccd52e00c526690ac5b44ca911534e96f936acd4ff02a2785d9932bbe11ff6c", "UnlinkUserAuthentication": "efef5d154b91120114a5ae97193bb83daee1223c150c8bda2d6655a47482fb70", "UpdateUser": "f3860479c8aaf60b1901dca62029b57c96953064a5a65a4ed92cf8e5173ed441", - "VerifyEmail": "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1" + "VerifyEmail": "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1", + "McpEvents": "bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600", + "McpEvent": "2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf" } \ No newline at end of file diff --git a/@app/graphql/codegen.yml b/@app/graphql/codegen.yml index 0f185f9bb..7917255a3 100644 --- a/@app/graphql/codegen.yml +++ b/@app/graphql/codegen.yml @@ -1,6 +1,8 @@ overwrite: true schema: "../../data/schema.graphql" -documents: "../client/src/**/*.graphql" +documents: + - "../client/src/**/*.graphql" + - "../server/src/**/*.graphql" hooks: afterAllFileWrite: - node scripts/addToPersistedOperations.mjs diff --git a/@app/graphql/server.json b/@app/graphql/server.json index ae4556691..952cc79d1 100644 --- a/@app/graphql/server.json +++ b/@app/graphql/server.json @@ -59,5 +59,7 @@ "4ccd52e00c526690ac5b44ca911534e96f936acd4ff02a2785d9932bbe11ff6c": "query SettingsPassword {\n currentUser {\n id\n hasPassword\n primaryEmail\n __typename\n }\n}", "efef5d154b91120114a5ae97193bb83daee1223c150c8bda2d6655a47482fb70": "mutation UnlinkUserAuthentication($id: UUID!) {\n deleteUserAuthentication(input: {id: $id}) {\n user {\n id\n userAuthenticationsList(first: 50) {\n id\n identifier\n service\n createdAt\n __typename\n }\n __typename\n }\n __typename\n }\n}", "f3860479c8aaf60b1901dca62029b57c96953064a5a65a4ed92cf8e5173ed441": "mutation UpdateUser($id: UUID!, $patch: UserPatch!) {\n updateUser(input: {id: $id, patch: $patch}) {\n clientMutationId\n user {\n id\n name\n username\n __typename\n }\n __typename\n }\n}", - "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1": "mutation VerifyEmail($id: UUID!, $token: String!) {\n verifyEmail(input: {userEmailId: $id, token: $token}) {\n success\n query {\n currentUser {\n id\n isVerified\n __typename\n }\n __typename\n }\n __typename\n }\n}" + "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1": "mutation VerifyEmail($id: UUID!, $token: String!) {\n verifyEmail(input: {userEmailId: $id, token: $token}) {\n success\n query {\n currentUser {\n id\n isVerified\n __typename\n }\n __typename\n }\n __typename\n }\n}", + "bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600": "fragment McpEventSummary on Event {\n id\n slug\n name\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n signupOpen\n signupUpcoming\n ownerOrganization {\n name\n __typename\n }\n category {\n name\n __typename\n }\n __typename\n}\nquery McpEvents {\n signupOpenEvents: events(\n filter: {signupOpen: {equalTo: true}, isDraft: {equalTo: false}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC]\n ) {\n nodes {\n ...McpEventSummary\n __typename\n }\n __typename\n }\n signupUpcomingEvents: events(\n filter: {signupUpcoming: {equalTo: true}, isDraft: {equalTo: false}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_START_TIME_ASC]\n ) {\n nodes {\n ...McpEventSummary\n __typename\n }\n __typename\n }\n}", + "2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf": "fragment McpEventSummary on Event {\n id\n slug\n name\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n signupOpen\n signupUpcoming\n ownerOrganization {\n name\n __typename\n }\n category {\n name\n __typename\n }\n __typename\n}\nquery McpEvent($slug: String!) {\n currentUser {\n name\n primaryEmail\n __typename\n }\n eventBySlug(slug: $slug) {\n ...McpEventSummary\n description\n isDraft\n openQuotaSize\n quotas(orderBy: POSITION_ASC) {\n nodes {\n id\n title\n size\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n eventQuestions(orderBy: POSITION_ASC) {\n nodes {\n id\n type\n label\n isRequired\n data\n __typename\n }\n __typename\n }\n __typename\n }\n}" } \ No newline at end of file diff --git a/@app/server/__tests__/mcp/auth.test.ts b/@app/server/__tests__/mcp/auth.test.ts new file mode 100644 index 000000000..da8f2c91f --- /dev/null +++ b/@app/server/__tests__/mcp/auth.test.ts @@ -0,0 +1,149 @@ +import { randomUUID } from "crypto" + +import { McpAuthError, resolveMcpSession } from "../../src/mcp/auth" +import { + deleteTestData, + poolFromUrl, + setup, + teardown, + TEST_DATABASE_URL, +} from "../helpers" + +beforeEach(deleteTestData) +beforeAll(setup) +afterAll(teardown) + +const logger = { debug: () => {}, warn: () => {}, error: () => {} } +const pool = poolFromUrl(TEST_DATABASE_URL!) + +function claims(overrides: Record = {}) { + const sub = randomUUID() + return { + sub, + sid: randomUUID(), + email: `testuser_${sub.slice(0, 8)}@example.com`, + email_verified: true, + name: "Testi Käyttäjä", + ...overrides, + } +} + +async function sessionRow(uuid: string) { + const { + rows: [row], + } = await pool.query( + `select s.kind, s.oauth_sid, s.user_id, ua.identifier + from app_private.sessions s + join app_public.user_authentications ua + on ua.user_id = s.user_id and ua.service = 'keycloak' + where s.uuid = $1`, + [uuid] + ) + return row +} + +describe("resolveMcpSession", () => { + it("registers a new identity and creates an mcp session for its sid", async () => { + const c = claims() + const sessionId = await resolveMcpSession(pool, c, logger) + + const row = await sessionRow(sessionId) + expect(row).toMatchObject({ + kind: "mcp", + oauth_sid: c.sid, + identifier: c.sub, + }) + }) + + it("reuses the session for the same Keycloak session", async () => { + const c = claims() + const first = await resolveMcpSession(pool, c, logger) + const second = await resolveMcpSession(pool, c, logger) + expect(second).toEqual(first) + + const third = await resolveMcpSession( + pool, + { ...c, sid: randomUUID() }, + logger + ) + expect(third).not.toEqual(first) + expect((await sessionRow(third)).user_id).toEqual( + (await sessionRow(first)).user_id + ) + }) + + it("leaves the web login's stored secrets alone for a linked identity", async () => { + const c = claims() + await resolveMcpSession(pool, c, logger) + await pool.query( + `update app_private.user_authentication_secrets uas + set details = '{"id_token": "web-login-hint"}' + from app_public.user_authentications ua + where ua.id = uas.user_authentication_id and ua.identifier = $1`, + [c.sub] + ) + + await resolveMcpSession(pool, { ...c, sid: randomUUID() }, logger) + + const { + rows: [secret], + } = await pool.query( + `select uas.details from app_private.user_authentication_secrets uas + join app_public.user_authentications ua on ua.id = uas.user_authentication_id + where ua.identifier = $1`, + [c.sub] + ) + expect(secret.details).toEqual({ id_token: "web-login-hint" }) + }) + + it("refuses to create a user from an unverified email", async () => { + await expect( + resolveMcpSession(pool, claims({ email_verified: false }), logger) + ).rejects.toBeInstanceOf(McpAuthError) + }) + + it("refuses a token without a sid", async () => { + await expect( + resolveMcpSession(pool, claims({ sid: undefined }), logger) + ).rejects.toBeInstanceOf(McpAuthError) + }) + + it("refuses a Keycloak session that already belongs to another user", async () => { + const a = claims() + await resolveMcpSession(pool, a, logger) + await expect( + resolveMcpSession(pool, claims({ sid: a.sid }), logger) + ).rejects.toBeInstanceOf(McpAuthError) + }) + + it("refuses an identity that resolves to a break-glass account", async () => { + const c = claims() + await resolveMcpSession(pool, c, logger) + const { + rows: [{ user_id: userId }], + } = await pool.query( + `select user_id from app_public.user_authentications where identifier = $1`, + [c.sub] + ) + const { + rows: [original], + } = await pool.query( + "select username from app_public.users where id = $1", + [userId] + ) + await pool.query( + "update app_public.users set username = 'toimari' where id = $1", + [userId] + ) + try { + await expect( + resolveMcpSession(pool, { ...c, sid: randomUUID() }, logger) + ).rejects.toBeInstanceOf(McpAuthError) + } finally { + await pool.query( + "update app_public.users set username = $1 where id = $2", + [original.username, userId] + ) + } + }) +}) diff --git a/@app/server/__tests__/mcp/registration.test.ts b/@app/server/__tests__/mcp/registration.test.ts new file mode 100644 index 000000000..3672d7d8e --- /dev/null +++ b/@app/server/__tests__/mcp/registration.test.ts @@ -0,0 +1,128 @@ +import { McpEventQuery, QuestionType } from "@app/graphql" + +import { + richTextToPlain, + validateRegistration, +} from "../../src/mcp/registration" + +type McpEvent = NonNullable + +const event = { + signupOpen: true, + quotas: { nodes: [{ id: "quota-1" }] }, + eventQuestions: { + nodes: [ + { + id: "q-text", + type: QuestionType.Text, + label: { fi: "Allergiat", en: "Allergies" }, + isRequired: false, + data: null, + }, + { + id: "q-radio", + type: QuestionType.Radio, + label: { fi: "Koko", en: "Size" }, + isRequired: true, + data: [ + { fi: "Pieni", en: "Small" }, + { fi: "Iso", en: "Large" }, + ], + }, + { + id: "q-checkbox", + type: QuestionType.Checkbox, + label: { fi: "Lähde", en: "Source" }, + isRequired: false, + data: [ + { fi: "Kaveri", en: "Friend" }, + { fi: "Muu", en: "Other" }, + ], + }, + ], + }, +} as unknown as McpEvent + +const valid = { + quotaId: "quota-1", + firstName: "Testi", + lastName: "Henkilö", + email: "testi@example.com", + answers: { "q-radio": "Iso", "q-checkbox": ["Friend", "Muu"] }, +} + +describe("validateRegistration", () => { + it("accepts a valid registration with options in either language", () => { + expect(validateRegistration(event, valid)).toEqual([]) + }) + + it("rejects a closed event and a quota of another event", () => { + expect( + validateRegistration( + { ...event, signupOpen: false }, + { ...valid, quotaId: "other" } + ) + ).toEqual([ + "Registration for this event is not open.", + "quotaId is not one of this event's quotas.", + ]) + }) + + it("rejects names with spaces and missing names", () => { + expect( + validateRegistration(event, { + ...valid, + firstName: "Anna Maria", + lastName: "", + }) + ).toEqual(["firstName must not contain spaces.", "lastName is required."]) + }) + + it("requires required questions and known question ids", () => { + expect( + validateRegistration(event, { ...valid, answers: { unknown: "x" } }) + ).toEqual([ + "Answer unknown does not match a question of this event.", + '"Size" is required.', + ]) + }) + + it("rejects answers that are not options or have the wrong shape", () => { + expect( + validateRegistration(event, { + ...valid, + answers: { + "q-text": ["not", "a", "string"], + "q-radio": "Medium", + "q-checkbox": "Friend", + }, + }) + ).toEqual([ + '"Allergies" expects a string.', + '"Size" expects exactly one of: Pieni, Small, Iso, Large.', + '"Source" expects a list of options from: Kaveri, Friend, Muu, Other.', + ]) + }) +}) + +describe("richTextToPlain", () => { + it("joins paragraphs and nested leaves", () => { + expect( + richTextToPlain([ + { + type: "paragraph", + children: [{ text: "Hello " }, { text: "world" }], + }, + { type: "paragraph", children: [{ text: "" }] }, + { + type: "bulleted-list", + children: [{ type: "list-item", children: [{ text: "Item" }] }], + }, + ]) + ).toEqual("Hello world\n\nItem") + }) + + it("returns an empty string for missing content", () => { + expect(richTextToPlain(undefined)).toEqual("") + }) +}) diff --git a/@app/server/package.json b/@app/server/package.json index ca28ad3d7..7489514b5 100644 --- a/@app/server/package.json +++ b/@app/server/package.json @@ -28,6 +28,7 @@ "@graphile/persisted-operations": "^0.1.1", "@graphile/pg-pubsub": "^4.12.3", "@graphile/subscriptions-lds": "^4.12.3", + "@modelcontextprotocol/sdk": "^1.32.1", "@types/graphql-upload": "^8.0.11", "@zxcvbn-ts/core": "^2.0.4", "@zxcvbn-ts/language-common": "^2.0.1", @@ -48,6 +49,7 @@ "helmet": "^8.0.0", "html-to-text": "^8.2.1", "ioredis": "^5.2.2", + "jose": "^5.10.0", "lodash": "^4.17.21", "mjml": "^4.13.0", "mock-req": "^0.2.0", @@ -63,7 +65,8 @@ "slugify": "^1.6.5", "source-map-support": "^0.5.21", "tslib": "^2.6.0", - "uuid": "^8.3.2" + "uuid": "^8.3.2", + "zod": "^4.6.7" }, "devDependencies": { "@faker-js/faker": "^9.3.0", diff --git a/@app/server/src/app.ts b/@app/server/src/app.ts index fc236c61c..56d542191 100644 --- a/@app/server/src/app.ts +++ b/@app/server/src/app.ts @@ -115,6 +115,7 @@ export async function makeApp({ await app.register(installCypressServerCommand) } await app.register(middleware.installPostGraphile) + await app.register(middleware.installMcp) await app.register(middleware.installFileUpload) // Needs to be last diff --git a/@app/server/src/mcp/auth.ts b/@app/server/src/mcp/auth.ts new file mode 100644 index 000000000..098e95e15 --- /dev/null +++ b/@app/server/src/mcp/auth.ts @@ -0,0 +1,193 @@ +import { createRemoteJWKSet, JWTPayload, jwtVerify } from "jose" +import { Pool, PoolClient } from "pg" + +import { + BREAK_GLASS_USERNAMES, + mapKeycloakClaims, + RequestLogger, +} from "../utils/keycloak" + +export class McpAuthError extends Error { + constructor( + message: string, + readonly oauthError: + | "invalid_token" + | "insufficient_scope" = "invalid_token" + ) { + super(message) + } +} + +export function mcpResourceUrl() { + return `${process.env.ROOT_URL}/mcp` +} + +export function mcpEnabled() { + return !!process.env.KEYCLOAK_ISSUER +} + +type Jwks = ReturnType +let jwksPromise: Promise | null = null + +/** + * Lazy, memoized discovery like getKeycloakConfig: a Keycloak outage must not + * stop the server from booting, and a failed attempt is retried on the next + * request. The web login's discovery is not reused because it needs the web + * client's credentials, which /mcp has no business depending on. + */ +function getJwks(): Promise { + if (!jwksPromise) { + const issuer = process.env.KEYCLOAK_ISSUER! + jwksPromise = fetch(`${issuer}/.well-known/openid-configuration`) + .then(async (res) => { + if (!res.ok) { + throw new Error(`keycloak discovery failed with HTTP ${res.status}`) + } + const metadata = (await res.json()) as { + issuer?: string + jwks_uri?: string + } + if (metadata.issuer !== issuer || !metadata.jwks_uri) { + throw new Error("keycloak discovery document does not match issuer") + } + return createRemoteJWKSet(new URL(metadata.jwks_uri)) + }) + .catch((e) => { + jwksPromise = null + throw e + }) + } + return jwksPromise +} + +export async function verifyAccessToken(token: string): Promise { + const jwks = await getJwks() + let payload: JWTPayload + try { + ;({ payload } = await jwtVerify(token, jwks, { + issuer: process.env.KEYCLOAK_ISSUER!, + audience: mcpResourceUrl(), + })) + } catch { + throw new McpAuthError("The access token is invalid or expired.") + } + // Keycloak marks access tokens with typ Bearer; an ID token or refresh token + // that somehow carried our audience must still not authenticate. + if (payload.typ !== "Bearer") { + throw new McpAuthError("The token is not an access token.") + } + return payload +} + +async function resolveUserId( + client: PoolClient, + claims: JWTPayload, + logger: RequestLogger +): Promise { + const sub = claims.sub! + const { + rows: [linked], + } = await client.query<{ user_id: string }>( + `select user_id from app_public.user_authentications + where service = 'keycloak' and identifier = $1`, + [sub] + ) + // An already linked identity must not go through link_or_register_user: + // that function overwrites the stored auth secrets, which hold the web + // login's id token used as the Keycloak logout hint. + if (linked) return linked.user_id + + let profile + try { + profile = mapKeycloakClaims(claims as Record, logger) + } catch { + throw new McpAuthError( + "The access token is missing the email claim; check the ilmo-mcp client scopes." + ) + } + if (!profile.emailVerified) { + throw new McpAuthError( + "Your Prodeko account email address is not verified." + ) + } + const { + rows: [user], + } = await client.query<{ id: string }>( + `select id from app_private.link_or_register_user($1, $2, $3, $4, $5)`, + [ + null, + "keycloak", + sub, + JSON.stringify({ + username: profile.usernameSuggestion, + email: profile.email, + name: profile.name, + }), + JSON.stringify({}), + ] + ) + return user.id +} + +/** + * Maps a verified access token to an app_private.sessions row, creating the + * user on first use exactly like the web SSO callback would. The session id + * never leaves the server. + */ +export async function resolveMcpSession( + rootPgPool: Pool, + claims: JWTPayload, + logger: RequestLogger +): Promise { + const sid = typeof claims.sid === "string" ? claims.sid : null + if (!claims.sub || !sid) { + throw new McpAuthError("The access token has no sub or sid claim.") + } + + const client = await rootPgPool.connect() + let rollbackFailed = false + try { + await client.query("begin") + const userId = await resolveUserId(client, claims, logger) + + const { + rows: [user], + } = await client.query<{ username: string }>( + "select username from app_public.users where id = $1", + [userId] + ) + if (BREAK_GLASS_USERNAMES.includes(String(user.username).toLowerCase())) { + logger.error( + { userId, sub: claims.sub }, + "mcp: refusing a keycloak identity that resolves to a break-glass account" + ) + throw new McpAuthError("This account cannot use the MCP server.") + } + + const { + rows: [session], + } = await client.query<{ uuid: string; user_id: string }>( + `insert into app_private.sessions (user_id, kind, oauth_sid) + values ($1, 'mcp', $2) + on conflict (oauth_sid) where kind = 'mcp' + do update set last_active = now() + returning uuid, user_id`, + [userId, sid] + ) + if (session.user_id !== userId) { + throw new McpAuthError("The Keycloak session belongs to another user.") + } + await client.query("commit") + return session.uuid + } catch (e) { + try { + await client.query("rollback") + } catch (rollbackError) { + rollbackFailed = true + logger.error({ err: rollbackError }, "mcp: session rollback failed") + } + throw e + } finally { + client.release(rollbackFailed) + } +} diff --git a/@app/server/src/mcp/operations.graphql b/@app/server/src/mcp/operations.graphql new file mode 100644 index 000000000..7eb68ec96 --- /dev/null +++ b/@app/server/src/mcp/operations.graphql @@ -0,0 +1,69 @@ +fragment McpEventSummary on Event { + id + slug + name + location + eventStartTime + eventEndTime + registrationStartTime + registrationEndTime + signupOpen + signupUpcoming + ownerOrganization { + name + } + category { + name + } +} + +query McpEvents { + signupOpenEvents: events( + filter: { signupOpen: { equalTo: true }, isDraft: { equalTo: false } } + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC] + ) { + nodes { + ...McpEventSummary + } + } + signupUpcomingEvents: events( + filter: { signupUpcoming: { equalTo: true }, isDraft: { equalTo: false } } + orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_START_TIME_ASC] + ) { + nodes { + ...McpEventSummary + } + } +} + +query McpEvent($slug: String!) { + currentUser { + name + primaryEmail + } + eventBySlug(slug: $slug) { + ...McpEventSummary + description + isDraft + openQuotaSize + quotas(orderBy: POSITION_ASC) { + nodes { + id + title + size + registrations { + totalCount + } + } + } + eventQuestions(orderBy: POSITION_ASC) { + nodes { + id + type + label + isRequired + data + } + } + } +} diff --git a/@app/server/src/mcp/registration.ts b/@app/server/src/mcp/registration.ts new file mode 100644 index 000000000..fb3fcdbcc --- /dev/null +++ b/@app/server/src/mcp/registration.ts @@ -0,0 +1,117 @@ +import { McpEventQuery, QuestionType } from "@app/graphql" + +type McpEvent = NonNullable + +export type AnswerValue = string | string[] + +export interface RegistrationInput { + quotaId: string + firstName: string + lastName: string + email: string + answers: Record +} + +function optionLabels(data: McpEvent["eventQuestions"]["nodes"][0]["data"]) { + const labels = new Set() + for (const option of data ?? []) { + if (option?.fi) labels.add(option.fi) + if (option?.en) labels.add(option.en) + } + return labels +} + +/** + * Mirrors the database checks so that a doomed request is answered before + * claimRegistrationToken spends one of the requester's rate-limited attempts. + * It is stricter than the database in one respect: radio and checkbox answers + * must be one of the question's options, as they always are on the web form. + */ +export function validateRegistration( + event: McpEvent, + input: RegistrationInput +): string[] { + const errors: string[] = [] + + if (!event.signupOpen) { + errors.push("Registration for this event is not open.") + } + if (!event.quotas.nodes.some((q) => q.id === input.quotaId)) { + errors.push("quotaId is not one of this event's quotas.") + } + for (const [field, value] of [ + ["firstName", input.firstName], + ["lastName", input.lastName], + ] as const) { + if (!value) errors.push(`${field} is required.`) + else if (/\s/.test(value)) errors.push(`${field} must not contain spaces.`) + } + + const questions = new Map(event.eventQuestions.nodes.map((q) => [q.id, q])) + for (const questionId of Object.keys(input.answers)) { + if (!questions.has(questionId)) { + errors.push( + `Answer ${questionId} does not match a question of this event.` + ) + } + } + + for (const question of event.eventQuestions.nodes) { + const label = question.label.en || question.label.fi + const answer = input.answers[question.id] + if (answer === undefined) { + if (question.isRequired) errors.push(`"${label}" is required.`) + continue + } + const options = optionLabels(question.data) + switch (question.type) { + case QuestionType.Text: + if (typeof answer !== "string") { + errors.push(`"${label}" expects a string.`) + } else if (question.isRequired && !answer.trim()) { + errors.push(`"${label}" is required.`) + } + break + case QuestionType.Radio: + if (typeof answer !== "string" || !options.has(answer)) { + errors.push( + `"${label}" expects exactly one of: ${[...options].join(", ")}.` + ) + } + break + case QuestionType.Checkbox: + if ( + !Array.isArray(answer) || + answer.some((a) => typeof a !== "string" || !options.has(a)) + ) { + errors.push( + `"${label}" expects a list of options from: ${[...options].join(", ")}.` + ) + } else if (question.isRequired && answer.length === 0) { + errors.push(`"${label}" requires at least one option.`) + } + break + } + } + + return errors +} + +interface RichTextNode { + text?: string + children?: RichTextNode[] +} + +function nodeText(node: RichTextNode): string { + if (typeof node.text === "string") return node.text + return (node.children ?? []).map(nodeText).join("") +} + +/** Flattens the editor's Slate document into paragraphs of plain text. */ +export function richTextToPlain(nodes: unknown): string { + if (!Array.isArray(nodes)) return "" + return nodes + .map((n) => nodeText(n as RichTextNode)) + .filter(Boolean) + .join("\n\n") +} diff --git a/@app/server/src/mcp/server.ts b/@app/server/src/mcp/server.ts new file mode 100644 index 000000000..d6bbbcc73 --- /dev/null +++ b/@app/server/src/mcp/server.ts @@ -0,0 +1,231 @@ +import { + ClaimRegistrationTokenDocument, + ClaimRegistrationTokenMutation, + CreateEventRegistrationDocument, + CreateEventRegistrationMutation, + McpEventDocument, + McpEventQuery, + McpEventsDocument, + McpEventsQuery, + McpEventSummaryFragment, +} from "@app/graphql" +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" +import { CallToolResult } from "@modelcontextprotocol/sdk/types.js" +import { DocumentNode } from "graphql" +import { z } from "zod" + +import { richTextToPlain, validateRegistration } from "./registration" + +/** + * Runs one GraphQL operation as the MCP user. Every call passed to + * `transaction` shares a single database transaction, which is rolled back + * when the callback throws. + */ +export type RunGraphQL = ( + document: DocumentNode, + variables?: Record +) => Promise + +export interface GraphQLRunner { + transaction(fn: (run: RunGraphQL) => Promise): Promise +} + +export class ToolError extends Error {} + +function json(value: unknown): CallToolResult { + return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] } +} + +function toolError(message: string): CallToolResult { + return { isError: true, content: [{ type: "text", text: message }] } +} + +async function withToolErrors( + fn: () => Promise +): Promise { + try { + return await fn() + } catch (e) { + if (e instanceof ToolError) return toolError(e.message) + throw e + } +} + +function summary(event: McpEventSummaryFragment) { + return { + slug: event.slug, + name: event.name, + organizer: event.ownerOrganization?.name ?? null, + category: event.category?.name ?? null, + location: event.location, + eventStartTime: event.eventStartTime, + eventEndTime: event.eventEndTime, + registrationStartTime: event.registrationStartTime, + registrationEndTime: event.registrationEndTime, + signupOpen: !!event.signupOpen, + } +} + +async function fetchEvent(runner: GraphQLRunner, slug: string) { + const data = await runner.transaction((run) => + run(McpEventDocument, { slug }) + ) + if (!data.eventBySlug) { + throw new ToolError(`No published event with slug "${slug}".`) + } + return { event: data.eventBySlug, currentUser: data.currentUser } +} + +export function createMcpServer(runner: GraphQLRunner) { + const server = new McpServer({ name: "ilmo", version: "1.0.0" }) + + server.registerTool( + "list_events", + { + title: "List events", + description: + "Lists published Prodeko events whose registration is open now or opens later. Names are given in Finnish (fi) and English (en); times are ISO 8601.", + annotations: { readOnlyHint: true }, + }, + () => + withToolErrors(async () => { + const data = await runner.transaction((run) => + run(McpEventsDocument) + ) + return json({ + registrationOpen: data.signupOpenEvents?.nodes.map(summary) ?? [], + registrationUpcoming: + data.signupUpcomingEvents?.nodes.map(summary) ?? [], + }) + }) + ) + + server.registerTool( + "get_event", + { + title: "Get event", + description: + "Returns one event with its description, quotas (with how many have registered) and the registration questions. Call this before register_to_event: it lists the quota ids, the question ids and the allowed answer options.", + inputSchema: { slug: z.string().describe("Event slug from list_events") }, + annotations: { readOnlyHint: true }, + }, + ({ slug }) => + withToolErrors(async () => { + const { event, currentUser } = await fetchEvent(runner, slug) + return json({ + ...summary(event), + description: { + fi: richTextToPlain(event.description?.fi), + en: richTextToPlain(event.description?.en), + }, + quotas: event.quotas.nodes.map((q) => ({ + id: q.id, + title: q.title, + size: q.size, + registered: q.registrations.totalCount, + })), + openQuotaSize: event.openQuotaSize, + questions: event.eventQuestions.nodes.map((q) => ({ + id: q.id, + type: q.type, + label: q.label, + required: q.isRequired, + options: q.data?.filter(Boolean) ?? null, + })), + answerFormat: + "answers maps question id to a string for TEXT and RADIO questions and to a list of strings for CHECKBOX questions. RADIO and CHECKBOX answers must be option labels, in either language.", + you: { + name: currentUser?.name ?? null, + email: currentUser?.primaryEmail ?? null, + }, + }) + }) + ) + + server.registerTool( + "register_to_event", + { + title: "Register to event", + description: + "Registers a person to an event quota. Registrations are first come, first served: when the quota is full the person is placed in the open quota or the queue, and the result says which. A confirmation email with a link for editing or cancelling the registration is sent to the given email address. Confirm the details with the user before calling this.", + inputSchema: { + slug: z.string().describe("Event slug"), + quotaId: z.string().describe("Quota id from get_event"), + firstName: z.string().describe("First name, no spaces"), + lastName: z.string().describe("Last name, no spaces"), + email: z + .string() + .email() + .optional() + .describe("Defaults to the signed-in user's primary email"), + answers: z + .record(z.string(), z.union([z.string(), z.array(z.string())])) + .optional() + .describe("Question id to answer, see get_event"), + }, + annotations: { readOnlyHint: false, destructiveHint: false }, + }, + (args) => + withToolErrors(async () => { + const { event, currentUser } = await fetchEvent(runner, args.slug) + const email = args.email ?? currentUser?.primaryEmail + if (!email) { + throw new ToolError( + "No email given and the signed-in user has no primary email." + ) + } + const input = { + quotaId: args.quotaId, + firstName: args.firstName, + lastName: args.lastName, + email, + answers: args.answers ?? {}, + } + const errors = validateRegistration(event, input) + if (errors.length > 0) { + throw new ToolError( + `Registration not sent:\n- ${errors.join("\n- ")}` + ) + } + + const registration = await runner.transaction(async (run) => { + const claim = await run( + ClaimRegistrationTokenDocument, + { input: { eventId: event.id, quotaId: input.quotaId } } + ) + const registrationToken = + claim.claimRegistrationToken?.claimRegistrationTokenOutput + ?.registrationToken + if (!registrationToken) { + throw new ToolError("Claiming a registration spot failed.") + } + const created = await run( + CreateEventRegistrationDocument, + { + input: { + ...input, + eventId: event.id, + registrationToken, + }, + } + ) + return created.createRegistration?.registration + }) + if (!registration) { + throw new ToolError("Registration failed.") + } + + return json({ + registered: true, + event: event.name, + quota: registration.quota?.title ?? null, + status: registration.status, + position: registration.position, + email, + note: "IN_QUOTA means a confirmed spot, IN_OPEN_QUOTA a spot in the shared open quota, IN_QUEUE a place in the waiting list. A confirmation email was sent.", + }) + }) + ) + + return server +} diff --git a/@app/server/src/middleware/index.ts b/@app/server/src/middleware/index.ts index a62aa6bfd..4ef881eab 100644 --- a/@app/server/src/middleware/index.ts +++ b/@app/server/src/middleware/index.ts @@ -5,6 +5,7 @@ import installFileUpload from "./installFileUpload" import installHealth from "./installHealth" import installHelmet from "./installHelmet" import installKeycloak from "./installKeycloak" +import installMcp from "./installMcp" import installPassport from "./installPassport" import installPostGraphile from "./installPostGraphile" import installRedis from "./installRedis" @@ -22,6 +23,7 @@ export { installHealth, installHelmet, installKeycloak, + installMcp, installPassport, installPostGraphile, installRedis, diff --git a/@app/server/src/middleware/installCSRFProtection.ts b/@app/server/src/middleware/installCSRFProtection.ts index 137cce20e..421f07d96 100644 --- a/@app/server/src/middleware/installCSRFProtection.ts +++ b/@app/server/src/middleware/installCSRFProtection.ts @@ -65,6 +65,11 @@ const CSRFProtection: FastifyPluginAsync = async (app) => { ) { // Bypass CSRF for GraphiQL in dev done() + } else if (request.url === "/mcp" || request.url.startsWith("/mcp?")) { + // /mcp authenticates with a bearer token and never reads the session + // cookie, so there is no ambient credential for a cross-site request to + // ride on. + done() } else if (request.method === "POST") { // Add CSRF protection to POST requests app.csrfProtection(request, reply, done) diff --git a/@app/server/src/middleware/installMcp.ts b/@app/server/src/middleware/installMcp.ts new file mode 100644 index 000000000..3864dd5a8 --- /dev/null +++ b/@app/server/src/middleware/installMcp.ts @@ -0,0 +1,155 @@ +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js" +import { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify" +import fp from "fastify-plugin" +import { graphql, print } from "graphql" +import { PoolClient } from "pg" +import { withPostGraphileContext } from "postgraphile" + +import { + McpAuthError, + mcpEnabled, + mcpResourceUrl, + resolveMcpSession, + verifyAccessToken, +} from "../mcp/auth" +import { + createMcpServer, + GraphQLRunner, + RunGraphQL, + ToolError, +} from "../mcp/server" + +import { OurGraphQLContext } from "./installPostGraphile" + +const PROTECTED_RESOURCE_METADATA_PATH = + "/.well-known/oauth-protected-resource/mcp" + +function unauthorized(reply: FastifyReply, error?: McpAuthError) { + const params = [ + `resource_metadata="${process.env.ROOT_URL}${PROTECTED_RESOURCE_METADATA_PATH}"`, + ] + if (error) { + params.push( + `error="${error.oauthError}"`, + `error_description="${error.message.replace(/"/g, "'")}"` + ) + } + return reply + .code(401) + .header("WWW-Authenticate", `Bearer ${params.join(", ")}`) + .send({ error: error?.oauthError ?? "unauthorized" }) +} + +const InstallMcp: FastifyPluginAsync = async (app) => { + if (!mcpEnabled()) { + app.log.warn("KEYCLOAK_ISSUER not set; /mcp disabled") + return + } + + // RFC 9728: tells the MCP client which authorization server issues tokens + // for this resource. The root path serves the same document for clients + // that do not insert the resource path. + const protectedResourceMetadata = async () => ({ + resource: mcpResourceUrl(), + authorization_servers: [process.env.KEYCLOAK_ISSUER], + scopes_supported: ["openid", "profile", "email"], + bearer_methods_supported: ["header"], + }) + app.get(PROTECTED_RESOURCE_METADATA_PATH, protectedResourceMetadata) + app.get("/.well-known/oauth-protected-resource", protectedResourceMetadata) + + const handler = async (request: FastifyRequest, reply: FastifyReply) => { + const header = request.headers.authorization + const token = header?.startsWith("Bearer ") ? header.slice(7) : null + if (!token) return unauthorized(reply) + + let sessionId: string + try { + const claims = await verifyAccessToken(token) + sessionId = await resolveMcpSession(app.rootPgPool, claims, request.log) + } catch (e) { + if (e instanceof McpAuthError) return unauthorized(reply, e) + request.log.error({ err: e }, "mcp: authentication failed") + return reply.code(503).send({ error: "temporarily_unavailable" }) + } + + const schema = await app.postgraphile.getGraphQLSchema() + const context: Omit = { + sessionId, + ipAddress: request.ip, + rootPgPool: app.rootPgPool, + redisClient: app.redis, + workerUtils: app.workerUtils, + login: async () => { + throw new Error("login is not available over MCP") + }, + logout: async () => { + throw new Error("logout is not available over MCP") + }, + isSsoSession: () => false, + logger: request.log, + } + + const runner: GraphQLRunner = { + // withPostGraphileContext is typed for a GraphQL result but resolves to + // whatever its callback returns. + transaction: (fn: (run: RunGraphQL) => Promise) => + withPostGraphileContext( + { + pgPool: app.authPgPool, + pgSettings: { + role: process.env.DATABASE_VISITOR, + "jwt.claims.session_id": sessionId, + }, + }, + async (pgContext) => { + // withPostGraphileContext commits even when the callback throws, + // so a failed registration would keep the spot it just claimed. + // Rolling back to this savepoint leaves the commit nothing to do. + const { pgClient } = pgContext as { pgClient: PoolClient } + await pgClient.query("savepoint mcp_transaction") + try { + return (await fn(async (document, variables) => { + const result = await graphql({ + schema, + source: print(document), + contextValue: { ...pgContext, ...context }, + variableValues: variables, + }) + if (result.errors?.length) { + // Database and plugin errors carry the user-facing message + // the web form shows; anything else stays in the log. + const [error] = result.errors + request.log.warn({ err: error }, "mcp: graphql error") + throw new ToolError(error.message) + } + return result.data as any + })) as any + } catch (e) { + await pgClient.query("rollback to savepoint mcp_transaction") + throw e + } + } + ) as Promise, + } + + const server = createMcpServer(runner) + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }) + reply.raw.on("close", () => { + transport.close() + server.close() + }) + reply.hijack() + await server.connect(transport) + await transport.handleRequest(request.raw, reply.raw, request.body) + } + + app.post("/mcp", handler) + app.get("/mcp", handler) + app.delete("/mcp", handler) +} + +export default fp(InstallMcp) diff --git a/@app/server/src/middleware/installPostGraphile.ts b/@app/server/src/middleware/installPostGraphile.ts index 594c0213b..fcaa55526 100644 --- a/@app/server/src/middleware/installPostGraphile.ts +++ b/@app/server/src/middleware/installPostGraphile.ts @@ -14,6 +14,7 @@ import { resolve } from "node:path" import { Pool, PoolClient } from "pg" import { enhanceHttpServerWithSubscriptions, + HttpRequestHandler, makePluginHook, Middleware, postgraphile, @@ -45,6 +46,12 @@ import { RequestLogger } from "./installKeycloak" const PostGraphileUploadFieldPlugin = require("postgraphile-plugin-upload-field") +declare module "fastify" { + export interface FastifyInstance { + postgraphile: HttpRequestHandler + } +} + export interface OurGraphQLContext { pgClient: PoolClient sessionId: string | null @@ -436,6 +443,8 @@ const Postgraphphile: FastifyPluginAsync = async (app) => { }) ) + app.decorate("postgraphile", middleware) + app.options( middleware.graphqlRoute, convertHandler(middleware.graphqlRouteHandler) diff --git a/@app/worker/crontab b/@app/worker/crontab index b24615f34..67b1acf34 100644 --- a/@app/worker/crontab +++ b/@app/worker/crontab @@ -15,3 +15,4 @@ # * * * * * task ?opts {payload} * * * * * gdpr__delete_event_registrations * * * * * registration__delete_unfinished_registrations +*/15 * * * * sessions__delete_inactive_mcp_sessions diff --git a/@app/worker/src/tasks/sessions__delete_inactive_mcp_sessions.ts b/@app/worker/src/tasks/sessions__delete_inactive_mcp_sessions.ts new file mode 100644 index 000000000..b85464758 --- /dev/null +++ b/@app/worker/src/tasks/sessions__delete_inactive_mcp_sessions.ts @@ -0,0 +1,16 @@ +import type { Task } from "graphile-worker" + +// An MCP session is recreated from the next valid access token, so deleting an +// idle one costs nothing but a row insert. +const INACTIVITY_TIMEOUT_MINUTES = 60 + +const task: Task = async (_, { query }) => { + await query( + `delete from app_private.sessions + where kind = 'mcp' + and last_active < now() - interval '1 minute' * $1`, + [INACTIVITY_TIMEOUT_MINUTES] + ) +} + +export default task diff --git a/docker-compose.yml b/docker-compose.yml index 8f7d07c93..06cf5412c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -25,6 +25,21 @@ services: log_directory=/var/lib/postgresql/data/logs -c log_rotation_age=60 -c log_truncate_on_rotation=on -c log_filename=server_log.hour.%H%M + # Optional local SSO + MCP auth: `docker compose --profile keycloak up -d`. + # The realm is imported from the fixture when the container is created; + # `docker compose --profile keycloak up -d --force-recreate keycloak` reloads it. + keycloak: + profiles: ["keycloak"] + image: quay.io/keycloak/keycloak:26.0 + command: start-dev --import-realm --http-port=8190 + environment: + KC_BOOTSTRAP_ADMIN_USERNAME: admin + KC_BOOTSTRAP_ADMIN_PASSWORD: admin + volumes: + - ./docker/keycloak/realm-dev.json:/opt/keycloak/data/import/realm-dev.json:ro + ports: + - "8190:8190" + volumes: db-volume: cache-volume: diff --git a/docker/keycloak/realm-dev.json b/docker/keycloak/realm-dev.json new file mode 100644 index 000000000..53fd04129 --- /dev/null +++ b/docker/keycloak/realm-dev.json @@ -0,0 +1,152 @@ +{ + "realm": "ilmo-dev", + "enabled": true, + "sslRequired": "none", + "registrationAllowed": false, + "resetPasswordAllowed": false, + "rememberMe": false, + "verifyEmail": false, + "loginWithEmailAllowed": true, + "duplicateEmailsAllowed": false, + "bruteForceProtected": false, + "accessTokenLifespan": 300, + "ssoSessionIdleTimeout": 1800, + "ssoSessionMaxLifespan": 36000, + "roles": { + "realm": [ + { + "name": "ilmo-admin", + "description": "Maps to app_public.users.is_admin; the name is ILMO_ADMIN_ROLE in @app/server/src/utils/keycloak.ts" + } + ] + }, + "clients": [ + { + "clientId": "ilmo-dev", + "name": "ilmokilke (dev)", + "enabled": true, + "protocol": "openid-connect", + "publicClient": false, + "bearerOnly": false, + "secret": "ilmo-dev-secret", + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "frontchannelLogout": false, + "redirectUris": ["http://localhost:5678/auth/keycloak/callback"], + "webOrigins": ["http://localhost:5678"], + "attributes": { + "pkce.code.challenge.method": "S256", + "post.logout.redirect.uris": "http://localhost:5678/" + }, + "protocolMappers": [ + { + "name": "realm roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "consentRequired": false, + "config": { + "claim.name": "realm_access.roles", + "jsonType.label": "String", + "multivalued": "true", + "access.token.claim": "true", + "id.token.claim": "true", + "userinfo.token.claim": "false" + } + }, + { + "name": "locale", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "user.attribute": "locale", + "claim.name": "locale", + "jsonType.label": "String", + "multivalued": "false", + "aggregate.attrs": "false", + "access.token.claim": "true", + "id.token.claim": "true", + "userinfo.token.claim": "false" + } + } + ] + }, + { + "clientId": "ilmo-mcp", + "name": "ilmokilke MCP (dev)", + "description": "Public client for MCP clients. Access tokens carry the /mcp resource as audience.", + "enabled": true, + "protocol": "openid-connect", + "publicClient": true, + "bearerOnly": false, + "consentRequired": true, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "frontchannelLogout": false, + "redirectUris": [ + "http://localhost:33418/callback", + "http://localhost:6274/oauth/callback", + "http://localhost:6274/oauth/callback/debug" + ], + "webOrigins": ["http://localhost:6274"], + "attributes": { + "pkce.code.challenge.method": "S256", + "consent.screen.text": "Ilmon MCP-palvelin voi lukea tapahtumia ja ilmoittaa sinut tapahtumiin puolestasi. / The ilmo MCP server can read events and register you to events on your behalf." + }, + "protocolMappers": [ + { + "name": "mcp audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-mapper", + "consentRequired": false, + "config": { + "included.custom.audience": "http://localhost:5678/mcp", + "access.token.claim": "true", + "id.token.claim": "false" + } + } + ] + } + ], + "users": [ + { + "username": "dev-member", + "enabled": true, + "emailVerified": true, + "email": "dev-member@example.com", + "firstName": "Dev", + "lastName": "Member", + "attributes": { "locale": ["fi"] }, + "requiredActions": [], + "credentials": [ + { + "type": "password", + "value": "dev-member-password", + "temporary": false + } + ] + }, + { + "username": "dev-admin", + "enabled": true, + "emailVerified": true, + "email": "dev-admin@example.com", + "firstName": "Dev", + "lastName": "Admin", + "attributes": { "locale": ["en"] }, + "requiredActions": [], + "realmRoles": ["ilmo-admin"], + "credentials": [ + { + "type": "password", + "value": "dev-admin-password", + "temporary": false + } + ] + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d935534db..b8d0d8c59 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -378,7 +378,7 @@ importers: version: 8.20.0 jest: specifier: ^29.7.0 - version: 29.7.0(@types/node@18.19.130)(babel-plugin-macros@3.1.0)(ts-node@10.9.2(@types/node@18.19.130)(typescript@5.9.3)) + version: 29.7.0(@types/node@22.19.17)(babel-plugin-macros@3.1.0)(ts-node@10.8.2(@types/node@22.19.17)(typescript@5.7.3)) lodash: specifier: ^4.17.21 version: 4.18.1 @@ -568,6 +568,9 @@ importers: '@graphile/subscriptions-lds': specifier: ^4.12.3 version: 4.14.1(bufferutil@4.1.0)(postgraphile-core@4.14.1(graphql@15.10.2)(pg@8.20.0))(utf-8-validate@5.0.10) + '@modelcontextprotocol/sdk': + specifier: ^1.32.1 + version: 1.32.1(zod@4.6.7) '@types/graphql-upload': specifier: ^8.0.11 version: 8.0.12 @@ -628,6 +631,9 @@ importers: ioredis: specifier: ^5.2.2 version: 5.10.1 + jose: + specifier: ^5.10.0 + version: 5.10.0 lodash: specifier: ^4.17.21 version: 4.18.1 @@ -676,6 +682,9 @@ importers: uuid: specifier: ^8.3.2 version: 8.3.2 + zod: + specifier: ^4.6.7 + version: 4.6.7 devDependencies: '@faker-js/faker': specifier: ^9.3.0 @@ -2136,6 +2145,12 @@ packages: peerDependencies: react: '*' + '@hono/node-server@2.1.5': + resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==} + engines: {node: '>=20'} + peerDependencies: + hono: ^4 || ^5.0.0-0 + '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -2437,6 +2452,16 @@ packages: resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==} engines: {node: '>=8'} + '@modelcontextprotocol/sdk@1.32.1': + resolution: {integrity: sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==} + engines: {node: '>=18'} + peerDependencies: + '@cfworker/json-schema': ^4.1.1 + zod: ^3.25 || ^4.0 + peerDependenciesMeta: + '@cfworker/json-schema': + optional: true + '@next/bundle-analyzer@16.2.4': resolution: {integrity: sha512-EAA9xTDv0P1IiUcZaASJJPkNDjRvL7OMTha6XN8MBzALYGfn7I52Mn7vRiyjVfNrtUPi2qiacY+eFVXe3lKCXA==} @@ -3677,6 +3702,10 @@ packages: abstract-logging@2.0.1: resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==} + accepts@2.0.0: + resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} + engines: {node: '>= 0.6'} + acorn-import-attributes@1.9.5: resolution: {integrity: sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==} peerDependencies: @@ -4111,6 +4140,10 @@ packages: resolution: {integrity: sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + body-parser@2.3.0: + resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} + engines: {node: '>=18'} + boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} @@ -4484,16 +4517,28 @@ packages: resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==} engines: {node: '>= 0.6'} + content-disposition@2.0.1: + resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==} + engines: {node: '>=18'} + content-type@1.0.5: resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} engines: {node: '>= 0.6'} + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + convert-source-map@1.9.0: resolution: {integrity: sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==} convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + cookie-signature@1.2.2: + resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==} + engines: {node: '>=6.6.0'} + cookie@0.4.2: resolution: {integrity: sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==} engines: {node: '>= 0.6'} @@ -4502,6 +4547,10 @@ packages: resolution: {integrity: sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==} engines: {node: '>= 0.6'} + cookie@0.7.2: + resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} + engines: {node: '>= 0.6'} + cookie@1.1.1: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} @@ -4518,6 +4567,10 @@ packages: core-util-is@1.0.2: resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==} + cors@2.8.6: + resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} + engines: {node: '>= 0.10'} + cosmiconfig@7.1.0: resolution: {integrity: sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==} engines: {node: '>=10'} @@ -5140,6 +5193,10 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} + etag@1.8.1: + resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} + engines: {node: '>= 0.6'} + eventemitter2@6.4.7: resolution: {integrity: sha512-tYUSVOGeQPKt/eC1ABfhHy5Xd96N3oIijJvN3O9+TsC28T5V9yX9oEfEK5faP0EFSNVOG97qtAS68GBrQB2hDg==} @@ -5153,6 +5210,14 @@ packages: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} + eventsource-parser@3.1.1: + resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} + engines: {node: '>=18.0.0'} + + eventsource@3.0.7: + resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} + engines: {node: '>=18.0.0'} + execa@4.1.0: resolution: {integrity: sha512-j5W0//W7f8UxAn8hXVnwG8tLwdiUy4FJLcSupCg6maBYZDpyBvTApK7KyuI4bKj8KOh1r2YH+6ucuYtJv1bTZA==} engines: {node: '>=10'} @@ -5184,6 +5249,16 @@ packages: exponential-backoff@3.1.3: resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==} + express-rate-limit@8.7.1: + resolution: {integrity: sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==} + engines: {node: '>= 16'} + peerDependencies: + express: '>= 4.11' + + express@5.3.0: + resolution: {integrity: sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==} + engines: {node: '>= 18'} + extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} @@ -5295,6 +5370,10 @@ packages: resolution: {integrity: sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==} engines: {node: '>= 0.8'} + finalhandler@2.1.1: + resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==} + engines: {node: '>= 18.0.0'} + find-cache-dir@4.0.0: resolution: {integrity: sha512-9ZonPT4ZAK4a+1pUPVPZJapbi7O5qbbJPdYw/NOQWZZbVLdDTYM3A4R9z/DpAM08IDaFGsvPgiGZ82WEwUDWjg==} engines: {node: '>=14.16'} @@ -5355,10 +5434,18 @@ packages: forwarded-parse@2.1.2: resolution: {integrity: sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==} + forwarded@0.2.0: + resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} + engines: {node: '>= 0.6'} + fp-and-or@0.1.4: resolution: {integrity: sha512-+yRYRhpnFPWXSly/6V4Lw9IfOV26uu30kynGJ03PW+MnjOEQe45RZ141QcS0aJehYBYA50GfCDnsRbFJdhssRw==} engines: {node: '>=10'} + fresh@2.0.0: + resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} + engines: {node: '>= 0.8'} + fs-capacitor@6.2.0: resolution: {integrity: sha512-nKcE1UduoSKX27NSZlg879LdQc94OtbOsEmKMN2MBNudXREvijRKx2GEBsTMTfws+BrbkJoEuynbGSVRSpauvw==} engines: {node: '>=10'} @@ -5734,6 +5821,10 @@ packages: resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==} engines: {node: '>=0.10.0'} + hono@4.13.13: + resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==} + engines: {node: '>=16.9.0'} + hosted-git-info@4.1.0: resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==} engines: {node: '>=10'} @@ -5944,6 +6035,10 @@ packages: resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==} engines: {node: '>= 12'} + ipaddr.js@1.9.1: + resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} + engines: {node: '>= 0.10'} + ipaddr.js@2.3.0: resolution: {integrity: sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg==} engines: {node: '>= 10'} @@ -6086,6 +6181,9 @@ packages: resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==} engines: {node: '>=0.10.0'} + is-promise@4.0.0: + resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} + is-reference@1.2.1: resolution: {integrity: sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==} @@ -6412,6 +6510,9 @@ packages: json-schema-traverse@1.0.0: resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + json-schema-typed@8.0.2: + resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} + json-schema@0.4.0: resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==} @@ -6696,6 +6797,10 @@ packages: resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==} engines: {node: '>= 0.6'} + media-typer@1.1.1: + resolution: {integrity: sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==} + engines: {node: '>= 0.8'} + mensch@0.3.4: resolution: {integrity: sha512-IAeFvcOnV9V0Yk+bFhYR07O3yNina9ANIN5MoXBKYJ/RLYPurd2d0yw14MDhpr9/momp0WofT1bPUh3hkzdi/g==} @@ -6703,6 +6808,10 @@ packages: resolution: {integrity: sha512-Cl0yeeIrko6d94KpUo1M+0X1sB14ikoaqlIGuTH1fW4I+E3+YljL54/hb/BWmVfrV9tTV9zU04+xjw08Fh2WkA==} engines: {node: '>=14.16'} + merge-descriptors@2.0.0: + resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} + engines: {node: '>=18'} + merge-stream@2.0.0: resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} @@ -6735,6 +6844,10 @@ packages: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} + mime-types@3.0.2: + resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} + engines: {node: '>=18'} + mime@2.6.0: resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} engines: {node: '>=4.0.0'} @@ -6993,6 +7106,10 @@ packages: resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==} engines: {node: '>= 0.6'} + negotiator@1.1.0: + resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} + engines: {node: '>=18'} + neo-async@2.6.2: resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} @@ -7425,6 +7542,9 @@ packages: resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} engines: {node: 18 || 20 || >=22} + path-to-regexp@8.4.2: + resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} + path-type@4.0.0: resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} engines: {node: '>=8'} @@ -7516,6 +7636,10 @@ packages: resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} engines: {node: '>= 6'} + pkce-challenge@5.0.1: + resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} + engines: {node: '>=16.20.0'} + pkg-dir@4.2.0: resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==} engines: {node: '>=8'} @@ -7647,6 +7771,10 @@ packages: proto-list@1.2.4: resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==} + proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} + engines: {node: '>= 0.10'} + proxy-from-env@1.0.0: resolution: {integrity: sha512-F2JHgJQ1iqwnHDcQjVBsq3n/uoaFL+iPW/eAeL7kVxy/2RrWaN4WroKjjvbsoRtv0ftelNyC01bjRhn/bhcf4A==} @@ -7694,6 +7822,10 @@ packages: resolution: {integrity: sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==} engines: {node: '>=0.6'} + qs@6.16.1: + resolution: {integrity: sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==} + engines: {node: '>=0.6'} + querystringify@2.2.0: resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==} @@ -7718,10 +7850,18 @@ packages: resolution: {integrity: sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==} engines: {node: '>=0.12'} + range-parser@1.3.0: + resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} + engines: {node: '>= 0.6'} + raw-body@2.5.3: resolution: {integrity: sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==} engines: {node: '>= 0.8'} + raw-body@3.0.2: + resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==} + engines: {node: '>= 0.10'} + rc-cascader@3.34.0: resolution: {integrity: sha512-KpXypcvju9ptjW9FaN2NFcA2QH9E9LHKq169Y0eWtH4e/wHQ5Wh5qZakAgvb8EKZ736WZ3B0zLLOBsrsja5Dag==} peerDependencies: @@ -8256,6 +8396,10 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true + router@2.2.0: + resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} + engines: {node: '>= 18'} + run-async@2.4.1: resolution: {integrity: sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==} engines: {node: '>=0.12.0'} @@ -8351,9 +8495,17 @@ packages: engines: {node: '>=10'} hasBin: true + send@1.2.1: + resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} + engines: {node: '>= 18'} + sentence-case@3.0.4: resolution: {integrity: sha512-8LS0JInaQMCRoQ7YUytAo/xUu5W2XnQxV2HI/6uM6U7CITS1RqPElr30V6uIqyMKM9lJGRVFy5/4CuzcixNYSg==} + serve-static@2.2.1: + resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} + engines: {node: '>= 18'} + set-blocking@2.0.0: resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==} @@ -8411,6 +8563,10 @@ packages: resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} engines: {node: '>= 0.4'} + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} + engines: {node: '>= 0.4'} + signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} @@ -9010,6 +9166,10 @@ packages: resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} engines: {node: '>= 0.6'} + type-is@2.1.0: + resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} + engines: {node: '>= 18'} + typed-array-buffer@1.0.3: resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} engines: {node: '>= 0.4'} @@ -9191,6 +9351,10 @@ packages: resolution: {integrity: sha512-Z6Uz+TYwEqE7ZN50gwn+1LCVo9ZVrpxRPOhOLnncYkY1ZzOYtrX8Fwf/rFktZ8R5mJms6EZf5TqNOMeZmnPq9Q==} engines: {node: '>=12'} + vary@1.1.2: + resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} + engines: {node: '>= 0.8'} + verror@1.10.0: resolution: {integrity: sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==} engines: {'0': node >=0.6.0} @@ -9435,6 +9599,14 @@ packages: resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==} engines: {node: '>=18'} + zod-to-json-schema@3.25.2: + resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} + peerDependencies: + zod: ^3.25.28 || ^4 + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + snapshots: '@0no-co/graphql.web@1.2.0(graphql@15.10.2)': @@ -11504,6 +11676,10 @@ snapshots: dependencies: react: 18.2.0 + '@hono/node-server@2.1.5(hono@4.13.13)': + dependencies: + hono: 4.13.13 + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -11879,6 +12055,28 @@ snapshots: '@lukeed/ms@2.0.2': {} + '@modelcontextprotocol/sdk@1.32.1(zod@4.6.7)': + dependencies: + '@hono/node-server': 2.1.5(hono@4.13.13) + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + content-type: 1.0.5 + cors: 2.8.6 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.1 + express: 5.3.0 + express-rate-limit: 8.7.1(express@5.3.0) + hono: 4.13.13 + jose: 6.2.8 + json-schema-typed: 8.0.2 + pkce-challenge: 5.0.1 + raw-body: 3.0.2 + zod: 4.6.7 + zod-to-json-schema: 3.25.2(zod@4.6.7) + transitivePeerDependencies: + - supports-color + '@next/bundle-analyzer@16.2.4(bufferutil@4.1.0)(utf-8-validate@5.0.10)': dependencies: webpack-bundle-analyzer: 4.10.1(bufferutil@4.1.0)(utf-8-validate@5.0.10) @@ -13297,6 +13495,11 @@ snapshots: abstract-logging@2.0.1: {} + accepts@2.0.0: + dependencies: + mime-types: 3.0.2 + negotiator: 1.1.0 + acorn-import-attributes@1.9.5(acorn@8.16.0): dependencies: acorn: 8.16.0 @@ -13809,6 +14012,20 @@ snapshots: transitivePeerDependencies: - supports-color + body-parser@2.3.0: + dependencies: + bytes: 3.1.2 + content-type: 2.1.0 + debug: 4.4.3(supports-color@8.1.1) + http-errors: 2.0.1 + iconv-lite: 0.7.2 + on-finished: 2.4.1 + qs: 6.16.1 + raw-body: 3.0.2 + type-is: 2.1.0 + transitivePeerDependencies: + - supports-color + boolbase@1.0.0: {} boxen@7.1.1: @@ -14254,16 +14471,24 @@ snapshots: dependencies: safe-buffer: 5.2.1 + content-disposition@2.0.1: {} + content-type@1.0.5: {} + content-type@2.1.0: {} + convert-source-map@1.9.0: {} convert-source-map@2.0.0: {} + cookie-signature@1.2.2: {} + cookie@0.4.2: {} cookie@0.5.0: {} + cookie@0.7.2: {} + cookie@1.1.1: {} copy-to-clipboard@3.3.3: @@ -14278,6 +14503,11 @@ snapshots: core-util-is@1.0.2: {} + cors@2.8.6: + dependencies: + object-assign: 4.1.1 + vary: 1.1.2 + cosmiconfig@7.1.0: dependencies: '@types/parse-json': 4.0.2 @@ -14855,7 +15085,7 @@ snapshots: eslint-import-resolver-node@0.3.10: dependencies: - debug: 3.2.7(supports-color@5.5.0) + debug: 3.2.7(supports-color@8.1.1) is-core-module: 2.16.1 resolve: 2.0.0-next.6 transitivePeerDependencies: @@ -14863,7 +15093,7 @@ snapshots: eslint-module-utils@2.12.1(@typescript-eslint/parser@8.59.1(eslint@9.39.4(jiti@2.6.1))(typescript@5.7.3))(eslint-import-resolver-node@0.3.10)(eslint@9.39.4(jiti@2.6.1)): dependencies: - debug: 3.2.7(supports-color@5.5.0) + debug: 3.2.7(supports-color@8.1.1) optionalDependencies: '@typescript-eslint/parser': 8.59.1(eslint@9.39.4(jiti@2.6.1))(typescript@5.7.3) eslint: 9.39.4(jiti@2.6.1) @@ -14883,7 +15113,7 @@ snapshots: array.prototype.findlastindex: 1.2.6 array.prototype.flat: 1.3.3 array.prototype.flatmap: 1.3.3 - debug: 3.2.7(supports-color@5.5.0) + debug: 3.2.7(supports-color@8.1.1) doctrine: 2.1.0 eslint: 9.39.4(jiti@2.6.1) eslint-import-resolver-node: 0.3.10 @@ -15056,6 +15286,8 @@ snapshots: esutils@2.0.3: {} + etag@1.8.1: {} + eventemitter2@6.4.7: {} eventemitter3@3.1.2: {} @@ -15068,6 +15300,12 @@ snapshots: events@3.3.0: {} + eventsource-parser@3.1.1: {} + + eventsource@3.0.7: + dependencies: + eventsource-parser: 3.1.1 + execa@4.1.0: dependencies: cross-spawn: 7.0.6 @@ -15114,6 +15352,47 @@ snapshots: exponential-backoff@3.1.3: {} + express-rate-limit@8.7.1(express@5.3.0): + dependencies: + debug: 4.4.3(supports-color@8.1.1) + express: 5.3.0 + ip-address: 10.2.0 + transitivePeerDependencies: + - supports-color + + express@5.3.0: + dependencies: + accepts: 2.0.0 + body-parser: 2.3.0 + content-disposition: 2.0.1 + content-type: 2.1.0 + cookie: 0.7.2 + cookie-signature: 1.2.2 + debug: 4.4.3(supports-color@8.1.1) + depd: 2.0.0 + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + finalhandler: 2.1.1 + fresh: 2.0.0 + http-errors: 2.0.1 + merge-descriptors: 2.0.0 + mime-types: 3.0.2 + on-finished: 2.4.1 + once: 1.4.0 + parseurl: 1.3.3 + proxy-addr: 2.0.8 + qs: 6.16.1 + range-parser: 1.3.0 + router: 2.2.0 + send: 1.2.1 + serve-static: 2.2.1 + statuses: 2.0.2 + type-is: 2.1.0 + vary: 1.1.2 + transitivePeerDependencies: + - supports-color + extend@3.0.2: {} extract-files@11.0.0: {} @@ -15251,6 +15530,17 @@ snapshots: transitivePeerDependencies: - supports-color + finalhandler@2.1.1: + dependencies: + debug: 4.4.3(supports-color@8.1.1) + encodeurl: 2.0.0 + escape-html: 1.0.3 + on-finished: 2.4.1 + parseurl: 1.3.3 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + find-cache-dir@4.0.0: dependencies: common-path-prefix: 3.0.0 @@ -15318,8 +15608,12 @@ snapshots: forwarded-parse@2.1.2: {} + forwarded@0.2.0: {} + fp-and-or@0.1.4: {} + fresh@2.0.0: {} + fs-capacitor@6.2.0: {} fs-capacitor@8.0.0: {} @@ -15804,6 +16098,8 @@ snapshots: dependencies: parse-passwd: 1.0.0 + hono@4.13.13: {} + hosted-git-info@4.1.0: dependencies: lru-cache: 6.0.0 @@ -16086,6 +16382,8 @@ snapshots: ip-address@10.2.0: {} + ipaddr.js@1.9.1: {} + ipaddr.js@2.3.0: {} is-absolute@1.0.0: @@ -16211,6 +16509,8 @@ snapshots: is-plain-object@5.0.0: {} + is-promise@4.0.0: {} + is-reference@1.2.1: dependencies: '@types/estree': 1.0.8 @@ -16817,6 +17117,8 @@ snapshots: json-schema-traverse@1.0.0: {} + json-schema-typed@8.0.2: {} + json-schema@0.4.0: {} json-sort-cli@2.1.11: @@ -17136,6 +17438,8 @@ snapshots: media-typer@0.3.0: {} + media-typer@1.1.1: {} + mensch@0.3.4: {} meow@11.0.0: @@ -17153,6 +17457,8 @@ snapshots: type-fest: 3.13.1 yargs-parser: 21.1.1 + merge-descriptors@2.0.0: {} + merge-stream@2.0.0: {} merge2@1.4.1: {} @@ -17174,6 +17480,10 @@ snapshots: dependencies: mime-db: 1.52.0 + mime-types@3.0.2: + dependencies: + mime-db: 1.54.0 + mime@2.6.0: {} mime@3.0.0: {} @@ -17611,6 +17921,10 @@ snapshots: negotiator@0.6.4: {} + negotiator@1.1.0: + dependencies: + content-type: 2.1.0 + neo-async@2.6.2: {} net@1.0.2: {} @@ -18135,6 +18449,8 @@ snapshots: lru-cache: 11.3.5 minipass: 7.1.3 + path-to-regexp@8.4.2: {} + path-type@4.0.0: {} pend@1.2.0: {} @@ -18224,6 +18540,8 @@ snapshots: pirates@4.0.7: {} + pkce-challenge@5.0.1: {} + pkg-dir@4.2.0: dependencies: find-up: 4.1.0 @@ -18379,6 +18697,11 @@ snapshots: proto-list@1.2.4: {} + proxy-addr@2.0.8: + dependencies: + forwarded: 0.2.0 + ipaddr.js: 1.9.1 + proxy-from-env@1.0.0: {} proxy-from-env@1.1.0: {} @@ -18420,6 +18743,11 @@ snapshots: dependencies: side-channel: 1.1.0 + qs@6.16.1: + dependencies: + es-define-property: 1.0.1 + side-channel: 1.1.1 + querystringify@2.2.0: {} queue-microtask@1.2.3: {} @@ -18437,6 +18765,8 @@ snapshots: discontinuous-range: 1.0.0 ret: 0.1.15 + range-parser@1.3.0: {} + raw-body@2.5.3: dependencies: bytes: 3.1.2 @@ -18444,6 +18774,13 @@ snapshots: iconv-lite: 0.4.24 unpipe: 1.0.0 + raw-body@3.0.2: + dependencies: + bytes: 3.1.2 + http-errors: 2.0.1 + iconv-lite: 0.7.2 + unpipe: 1.0.0 + rc-cascader@3.34.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0): dependencies: '@babel/runtime': 7.29.2 @@ -19113,6 +19450,16 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.60.2 fsevents: 2.3.3 + router@2.2.0: + dependencies: + debug: 4.4.3(supports-color@8.1.1) + depd: 2.0.0 + is-promise: 4.0.0 + parseurl: 1.3.3 + path-to-regexp: 8.4.2 + transitivePeerDependencies: + - supports-color + run-async@2.4.1: {} run-async@3.0.0: {} @@ -19210,12 +19557,37 @@ snapshots: semver@7.7.4: {} + send@1.2.1: + dependencies: + debug: 4.4.3(supports-color@8.1.1) + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + fresh: 2.0.0 + http-errors: 2.0.1 + mime-types: 3.0.2 + ms: 2.1.3 + on-finished: 2.4.1 + range-parser: 1.3.0 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + sentence-case@3.0.4: dependencies: no-case: 3.0.4 tslib: 2.8.1 upper-case-first: 2.0.2 + serve-static@2.2.1: + dependencies: + encodeurl: 2.0.0 + escape-html: 1.0.3 + parseurl: 1.3.3 + send: 1.2.1 + transitivePeerDependencies: + - supports-color + set-blocking@2.0.0: {} set-cookie-parser@2.7.2: {} @@ -19323,6 +19695,14 @@ snapshots: side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 + side-channel@1.1.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + signal-exit@3.0.7: {} signal-exit@4.1.0: {} @@ -19957,6 +20337,12 @@ snapshots: media-typer: 0.3.0 mime-types: 2.1.35 + type-is@2.1.0: + dependencies: + content-type: 2.1.0 + media-typer: 1.1.1 + mime-types: 3.0.2 + typed-array-buffer@1.0.3: dependencies: call-bound: 1.0.4 @@ -20143,6 +20529,8 @@ snapshots: value-or-promise@1.0.12: {} + vary@1.1.2: {} + verror@1.10.0: dependencies: assert-plus: 1.0.0 @@ -20437,3 +20825,9 @@ snapshots: yocto-queue@1.2.2: {} yoctocolors-cjs@2.1.3: {} + + zod-to-json-schema@3.25.2(zod@4.6.7): + dependencies: + zod: 4.6.7 + + zod@4.6.7: {} From 2ee22ab4be5f46fa6da7b69177b7b7a15ecf901e Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 12:22:56 +0300 Subject: [PATCH 3/8] fix: give dev realm users the default roles so MCP clients get offline tokens Users imported with an explicit realmRoles list do not receive default-roles-ilmo-dev, which carries offline_access; Claude Code requests that scope and the code exchange was refused. Co-Authored-By: Claude Opus 5.5 --- docker/keycloak/realm-dev.json | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/docker/keycloak/realm-dev.json b/docker/keycloak/realm-dev.json index 53fd04129..34ef489b0 100644 --- a/docker/keycloak/realm-dev.json +++ b/docker/keycloak/realm-dev.json @@ -120,7 +120,9 @@ "email": "dev-member@example.com", "firstName": "Dev", "lastName": "Member", - "attributes": { "locale": ["fi"] }, + "attributes": { + "locale": ["fi"] + }, "requiredActions": [], "credentials": [ { @@ -128,7 +130,8 @@ "value": "dev-member-password", "temporary": false } - ] + ], + "realmRoles": ["default-roles-ilmo-dev"] }, { "username": "dev-admin", @@ -137,9 +140,11 @@ "email": "dev-admin@example.com", "firstName": "Dev", "lastName": "Admin", - "attributes": { "locale": ["en"] }, + "attributes": { + "locale": ["en"] + }, "requiredActions": [], - "realmRoles": ["ilmo-admin"], + "realmRoles": ["default-roles-ilmo-dev", "ilmo-admin"], "credentials": [ { "type": "password", From c321eb1ae9c3085cfecaed026c8e324dc2de26cb Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 13:41:06 +0300 Subject: [PATCH 4/8] fix: answer GET and DELETE on /mcp with 405 The server is stateless, so there is no standalone SSE stream or session to delete. Passing GET to the transport left the request hanging without a status line, which claude.ai surfaced as an unexpected error. Co-Authored-By: Claude Opus 5.5 --- @app/server/src/middleware/installMcp.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/@app/server/src/middleware/installMcp.ts b/@app/server/src/middleware/installMcp.ts index 3864dd5a8..bf7cce953 100644 --- a/@app/server/src/middleware/installMcp.ts +++ b/@app/server/src/middleware/installMcp.ts @@ -148,8 +148,21 @@ const InstallMcp: FastifyPluginAsync = async (app) => { } app.post("/mcp", handler) - app.get("/mcp", handler) - app.delete("/mcp", handler) + + // The server is stateless: there is no standalone SSE stream to open and no + // session to delete. Handing GET to the transport left the request hanging + // without a status line, which clients such as claude.ai report as an error. + const methodNotAllowed = async (_: FastifyRequest, reply: FastifyReply) => + reply + .code(405) + .header("Allow", "POST") + .send({ + jsonrpc: "2.0", + error: { code: -32000, message: "Method not allowed." }, + id: null, + }) + app.get("/mcp", methodNotAllowed) + app.delete("/mcp", methodNotAllowed) } export default fp(InstallMcp) From 83273c6c13a833d466a1c78c3383f7e30fc68604 Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 13:56:14 +0300 Subject: [PATCH 5/8] test: cover MCP access token verification and the /mcp routes A broken audience or issuer check would silently accept tokens issued to any other client in the realm, which manual testing with valid tokens cannot see. Co-Authored-By: Claude Opus 5.5 --- @app/server/__tests__/mcp/installMcp.test.ts | 154 +++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 @app/server/__tests__/mcp/installMcp.test.ts diff --git a/@app/server/__tests__/mcp/installMcp.test.ts b/@app/server/__tests__/mcp/installMcp.test.ts new file mode 100644 index 000000000..255a8f920 --- /dev/null +++ b/@app/server/__tests__/mcp/installMcp.test.ts @@ -0,0 +1,154 @@ +import { createServer, Server } from "http" +import { AddressInfo } from "net" + +import { fastify, FastifyInstance } from "fastify" +import { exportJWK, generateKeyPair, JWTPayload, KeyLike, SignJWT } from "jose" + +import { + McpAuthError, + mcpResourceUrl, + verifyAccessToken, +} from "../../src/mcp/auth" +import installMcp from "../../src/middleware/installMcp" + +let issuerServer: Server +let issuer: string +let signingKey: KeyLike +let foreignKey: KeyLike +let app: FastifyInstance +const savedIssuer = process.env.KEYCLOAK_ISSUER + +beforeAll(async () => { + const keys = await generateKeyPair("RS256") + signingKey = keys.privateKey + foreignKey = (await generateKeyPair("RS256")).privateKey + const jwk = { + ...(await exportJWK(keys.publicKey)), + kid: "test", + alg: "RS256", + } + + // Stands in for Keycloak: the discovery document and the realm's JWKS. + issuerServer = createServer((req, res) => { + res.setHeader("content-type", "application/json") + if (req.url === "/realms/test/.well-known/openid-configuration") { + res.end(JSON.stringify({ issuer, jwks_uri: `${issuer}/certs` })) + } else if (req.url === "/realms/test/certs") { + res.end(JSON.stringify({ keys: [jwk] })) + } else { + res.statusCode = 404 + res.end("{}") + } + }) + await new Promise((resolve) => + issuerServer.listen(0, "127.0.0.1", resolve) + ) + const { port } = issuerServer.address() as AddressInfo + issuer = `http://127.0.0.1:${port}/realms/test` + process.env.KEYCLOAK_ISSUER = issuer + + app = fastify() + await app.register(installMcp) + await app.ready() +}) + +afterAll(async () => { + await app.close() + await new Promise((resolve) => issuerServer.close(resolve)) + process.env.KEYCLOAK_ISSUER = savedIssuer +}) + +function token( + overrides: JWTPayload = {}, + { + key = signingKey, + expiresIn = "5m", + }: { key?: KeyLike; expiresIn?: string } = {} +) { + return new SignJWT({ + typ: "Bearer", + sub: "test-sub", + sid: "test-sid", + ...overrides, + }) + .setProtectedHeader({ alg: "RS256", kid: "test" }) + .setIssuer((overrides.iss as string) ?? issuer) + .setAudience((overrides.aud as string) ?? mcpResourceUrl()) + .setIssuedAt() + .setExpirationTime(expiresIn) + .sign(key) +} + +describe("verifyAccessToken", () => { + it("accepts an access token issued for the MCP resource", async () => { + const payload = await verifyAccessToken(await token()) + expect(payload).toMatchObject({ sub: "test-sub", sid: "test-sid" }) + }) + + it.each([ + ["another audience", () => token({ aud: "https://other.prodeko.org" })], + [ + "another issuer", + () => token({ iss: "https://evil.example/realms/test" }), + ], + ["an ID token", () => token({ typ: "ID" })], + ["an expired token", () => token({}, { expiresIn: "-1m" })], + ["a token signed with another key", () => token({}, { key: foreignKey })], + ])("rejects %s", async (_, make) => { + await expect(verifyAccessToken(await make())).rejects.toBeInstanceOf( + McpAuthError + ) + }) + + it("rejects a malformed token", async () => { + await expect(verifyAccessToken("not-a-jwt")).rejects.toBeInstanceOf( + McpAuthError + ) + }) +}) + +describe("/mcp routes", () => { + const metadataUrl = `${process.env.ROOT_URL}/.well-known/oauth-protected-resource/mcp` + + it("serves protected resource metadata pointing at the issuer", async () => { + const res = await app.inject({ + method: "GET", + url: "/.well-known/oauth-protected-resource/mcp", + }) + expect(res.statusCode).toBe(200) + expect(res.json()).toMatchObject({ + resource: mcpResourceUrl(), + authorization_servers: [issuer], + }) + }) + + it("answers a request without a token with 401 and the metadata pointer", async () => { + const res = await app.inject({ method: "POST", url: "/mcp", payload: {} }) + expect(res.statusCode).toBe(401) + expect(res.headers["www-authenticate"]).toBe( + `Bearer resource_metadata="${metadataUrl}"` + ) + }) + + it("answers a token for another audience with invalid_token", async () => { + const res = await app.inject({ + method: "POST", + url: "/mcp", + payload: {}, + headers: { + authorization: `Bearer ${await token({ aud: "https://other.prodeko.org" })}`, + }, + }) + expect(res.statusCode).toBe(401) + expect(res.headers["www-authenticate"]).toContain('error="invalid_token"') + }) + + it.each(["GET", "DELETE"] as const)( + "answers %s with 405 instead of holding the connection open", + async (method) => { + const res = await app.inject({ method, url: "/mcp" }) + expect(res.statusCode).toBe(405) + expect(res.headers.allow).toBe("POST") + } + ) +}) From c5707c166889a20819ca8941a8a1d07cbc828a33 Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 13:56:52 +0300 Subject: [PATCH 6/8] docs: document the MCP server, its Keycloak client and local testing Co-Authored-By: Claude Opus 5.5 --- docs/keycloak-sso.md | 5 ++ docs/mcp.md | 143 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 148 insertions(+) create mode 100644 docs/mcp.md diff --git a/docs/keycloak-sso.md b/docs/keycloak-sso.md index 0f0d2d707..315aa8031 100644 --- a/docs/keycloak-sso.md +++ b/docs/keycloak-sso.md @@ -123,6 +123,11 @@ Finally copy the client secret into the ilmo secret store as For local development, register a second client in membership-registry's dev Keycloak with redirect URI `http://localhost:5678/auth/keycloak/callback` and point `KEYCLOAK_ISSUER` at `http://localhost:8180/realms/membership-registry`. +The repository also ships a self-contained dev realm, started with +`docker compose --profile keycloak up -d`; see `docs/mcp.md`. + +The MCP server at `/mcp` uses a second, public client, `ilmo-mcp`. Its setup is +in `docs/mcp.md`. ## Break-glass login diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 000000000..c63b35a2d --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,143 @@ +# MCP server + +Ilmo serves a [Model Context Protocol](https://modelcontextprotocol.io) server +at `https://ilmo.prodeko.org/mcp`. It lets an AI assistant such as Claude list +events and register the signed-in member to them. Members sign in with their +Prodeko account through Keycloak, the same login the web app uses. + +Tools: + +- `list_events` — published events whose registration is open or upcoming. +- `get_event` — one event with its description, quotas and registration + questions. +- `register_to_event` — registers to a quota. Answers are validated before a + spot is claimed, and a failed registration releases the spot it claimed. + +Editing or cancelling a registration is not available over MCP; the confirmation +email's link does that, as on the web. + +## Using it + +### claude.ai, Claude Desktop and mobile + +Settings → Connectors → **Add custom connector**: + +| Field | Value | +| -------------- | ----------------------------------------------------------- | +| Name | `Ilmo` | +| URL | `https://ilmo.prodeko.org/mcp` (exactly, no trailing slash) | +| Authentication | **Sign in now** | +| OAuth client | **Use your own OAuth client**, client ID `ilmo-mcp` | +| Client secret | empty | +| Transport | Streamable HTTP | + +Connect, sign in with the Prodeko account and accept the consent screen. The +sign-in lasts 30 days, after which Claude asks to sign in again. + +### Claude Code + +```sh +claude mcp add --transport http ilmo https://ilmo.prodeko.org/mcp \ + --client-id ilmo-mcp --callback-port 33418 +``` + +Then run `/mcp`, choose ilmo → Authenticate. The callback port is fixed because +Keycloak matches redirect URIs exactly. + +## Registering the Keycloak client + +The MCP server needs its own client, `ilmo-mcp`, in the `membership-registry` +realm. It is separate from the web client `ilmokilke`: it is public, because MCP +clients run on members' machines or in Claude's service and cannot keep a +secret, and its access tokens carry the MCP resource as their audience so that +`/mcp` accepts no token issued to another client of the realm. + +The labels below are those of the Keycloak 26 admin console. + +1. **Realm settings → Sessions**: Offline Session Max Limited **Enabled**, with + Offline Session Max longer than 30 days. Without this flag Keycloak ignores + the client-level maximum below. The flag applies to every client's offline + tokens, so check that no other client needs offline tokens without a lifespan + before turning it on. +2. **Realm settings → User registration → Default roles** must contain + `offline_access`. Claude requests that scope, and the code exchange fails + with "Offline tokens not allowed for the user or client" for a member without + the role. Roles are owned by membership-registry; add it there. +3. **Clients → Create client** + - General settings: Client type OpenID Connect, Client ID `ilmo-mcp`, Name + `Ilmokilke MCP`, Always Display in Console on (members can revoke it from + the account console). + - Capability config: Client authentication **off**, Authorization off, only + **Standard Flow** enabled, PKCE method **S256**. + - Login settings: Home URL `https://ilmo.prodeko.org`; Valid redirect URIs + `https://claude.ai/api/mcp/auth_callback` (claude.ai, Desktop, mobile) and + `http://localhost:33418/callback` (Claude Code); Web origins empty. +4. **Settings → Login settings**: Consent required **on**, Display client on + screen on, Client consent screen text "Ilmon MCP-palvelin voi lukea + tapahtumia ja ilmoittaa sinut tapahtumiin puolestasi. / The ilmo MCP server + can read events and register you to events on your behalf." +5. **Advanced → Advanced settings**: Client Offline Session Idle **30 days**, + Client Offline Session Max **30 days**. +6. **Client scopes → `ilmo-mcp-dedicated` → Configure a new mapper → Audience**: + Included Custom Audience `https://ilmo.prodeko.org/mcp`, Add to access token + on, Add to ID token off. A hardcoded audience is used instead of Audience + Resolve because the latter adds client IDs only, from client roles, and with + Full scope allowed would put ilmo's audience into other clients' tokens too. +7. **Client scopes**: `basic`, `email`, `profile` as Default and + `offline_access` as Optional. +8. **Client scopes → Evaluate**: pick a member, add `offline_access` to the + scope parameter and open Generated access token. It must contain + `"aud": "https://ilmo.prodeko.org/mcp"`, `"typ": "Bearer"`, `sid`, `email` + and `"email_verified": true`; ilmo refuses tokens without them. + +If a WAF or IP filter sits in front of `id.prodeko.org` or `ilmo.prodeko.org`, +allow Anthropic's egress range `160.79.104.0/21`: claude.ai fetches Keycloak's +discovery document and tokens from its servers. + +Ilmo itself needs no new configuration: `/mcp` is enabled whenever +`KEYCLOAK_ISSUER` is set, and until the client exists every request is simply +answered with 401. + +## How it works + +- `/mcp` is a stateless Streamable HTTP endpoint (`installMcp.ts`). Requests + without a valid token get 401 with a `resource_metadata` pointer to + `/.well-known/oauth-protected-resource/mcp`, which names Keycloak as the + authorization server. +- The token's signature, issuer, audience, expiry and `typ` are verified against + Keycloak's JWKS (`mcp/auth.ts`). +- The token's `sub` resolves to the ilmo user through + `app_public.user_authentications`. A member who has never signed in is created + with `link_or_register_user`, like the web SSO callback does; an already + linked identity skips it, because that function overwrites the stored id token + the web logout relies on. Break-glass accounts are refused. +- Each Keycloak session (`sid`) maps to one `app_private.sessions` row of kind + `mcp`. Tools run the regular GraphQL operations as that session, so RLS, + ownership columns, rate limiting, the registration queue and the confirmation + email behave exactly as on the web. The session id never leaves the server. + Rows idle for an hour are deleted by `sessions__delete_inactive_mcp_sessions` + and recreated on the next request. +- `claimRegistrationToken` is rate limited per user for signed-in requests (per + IP for anonymous ones), so members whose requests all come from Claude's IP + range do not share one limit. + +## Local development + +`docker compose --profile keycloak up -d` starts a Keycloak with the realm in +`docker/keycloak/realm-dev.json`: the web client `ilmo-dev`, the MCP client +`ilmo-mcp` and the users `dev-member` / `dev-member-password` and `dev-admin` / +`dev-admin-password`. Set + +```sh +KEYCLOAK_ISSUER=http://localhost:8190/realms/ilmo-dev +``` + +in `.env` to enable `/mcp`; web SSO stays off until `KEYCLOAK_CLIENT_ID` and +`KEYCLOAK_CLIENT_SECRET` are set as well. Then add the server to Claude Code +with `http://localhost:5678/mcp` and the flags above. + +claude.ai cannot reach `localhost`. Testing it locally needs public tunnels to +both ilmo and Keycloak, with `ROOT_URL`, `KEYCLOAK_ISSUER`, Keycloak's hostname +and the client's audience and redirect URIs switched to the tunnel URLs for the +duration of the test. Turn `ENABLE_CYPRESS_COMMANDS` off and replace the +Keycloak admin password before opening a tunnel. From 067cd1a96456f18fc11757a8b88299e987d4c369 Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 16:35:46 +0300 Subject: [PATCH 7/8] feat: let admins create draft events over MCP Adds list_event_options and create_event, listed and run only when the access token carries the ilmo-admin realm role, so revoking the role in Keycloak applies on the next request; the database's is_admin check still applies. Events are always created as drafts for an admin to review and publish in the admin UI. MCP does not write is_admin, because ilmo-mcp lacks full scope and a missing role scope mapping would otherwise demote every admin. Co-Authored-By: Claude Opus 5.5 --- ...c22705211dfdb1f60642912a58c4954b44.graphql | 22 ++ @app/graphql/client.json | 1 + @app/graphql/server.json | 1 + @app/server/__tests__/mcp/events.test.ts | 205 ++++++++++++++++++ @app/server/src/mcp/auth.ts | 13 ++ @app/server/src/mcp/events.ts | 152 +++++++++++++ @app/server/src/mcp/operations.graphql | 18 ++ @app/server/src/mcp/server.ts | 135 +++++++++++- @app/server/src/middleware/installMcp.ts | 5 +- docker/keycloak/realm-dev.json | 6 + docs/mcp.md | 29 ++- 11 files changed, 580 insertions(+), 7 deletions(-) create mode 100644 @app/graphql/.persisted_operations/f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44.graphql create mode 100644 @app/server/__tests__/mcp/events.test.ts create mode 100644 @app/server/src/mcp/events.ts diff --git a/@app/graphql/.persisted_operations/f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44.graphql b/@app/graphql/.persisted_operations/f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44.graphql new file mode 100644 index 000000000..abc70cbb7 --- /dev/null +++ b/@app/graphql/.persisted_operations/f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44.graphql @@ -0,0 +1,22 @@ +query McpEventOptions { + organizations { + nodes { + id + name + __typename + } + __typename + } + eventCategories(orderBy: NAME_ASC) { + nodes { + id + name + ownerOrganization { + id + __typename + } + __typename + } + __typename + } +} \ No newline at end of file diff --git a/@app/graphql/client.json b/@app/graphql/client.json index 9405913fb..a7613675c 100644 --- a/@app/graphql/client.json +++ b/@app/graphql/client.json @@ -61,5 +61,6 @@ "UpdateUser": "f3860479c8aaf60b1901dca62029b57c96953064a5a65a4ed92cf8e5173ed441", "VerifyEmail": "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1", "McpEvents": "bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600", + "McpEventOptions": "f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44", "McpEvent": "2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf" } \ No newline at end of file diff --git a/@app/graphql/server.json b/@app/graphql/server.json index 952cc79d1..1798009e9 100644 --- a/@app/graphql/server.json +++ b/@app/graphql/server.json @@ -61,5 +61,6 @@ "f3860479c8aaf60b1901dca62029b57c96953064a5a65a4ed92cf8e5173ed441": "mutation UpdateUser($id: UUID!, $patch: UserPatch!) {\n updateUser(input: {id: $id, patch: $patch}) {\n clientMutationId\n user {\n id\n name\n username\n __typename\n }\n __typename\n }\n}", "37dc92ddb2ef943241e08bdfa7ee71c207fc876df739992d93ded6b9e76819d1": "mutation VerifyEmail($id: UUID!, $token: String!) {\n verifyEmail(input: {userEmailId: $id, token: $token}) {\n success\n query {\n currentUser {\n id\n isVerified\n __typename\n }\n __typename\n }\n __typename\n }\n}", "bff9fa131f81cd8910d662b816d207f92cd684511dce76c2b624187013be4600": "fragment McpEventSummary on Event {\n id\n slug\n name\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n signupOpen\n signupUpcoming\n ownerOrganization {\n name\n __typename\n }\n category {\n name\n __typename\n }\n __typename\n}\nquery McpEvents {\n signupOpenEvents: events(\n filter: {signupOpen: {equalTo: true}, isDraft: {equalTo: false}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_END_TIME_ASC]\n ) {\n nodes {\n ...McpEventSummary\n __typename\n }\n __typename\n }\n signupUpcomingEvents: events(\n filter: {signupUpcoming: {equalTo: true}, isDraft: {equalTo: false}}\n orderBy: [IS_HIGHLIGHTED_DESC, REGISTRATION_START_TIME_ASC]\n ) {\n nodes {\n ...McpEventSummary\n __typename\n }\n __typename\n }\n}", + "f7628c3bb9d2c33edc0ed649e869f4c22705211dfdb1f60642912a58c4954b44": "query McpEventOptions {\n organizations {\n nodes {\n id\n name\n __typename\n }\n __typename\n }\n eventCategories(orderBy: NAME_ASC) {\n nodes {\n id\n name\n ownerOrganization {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}", "2703b7592181b359bf05cb2ab656c103127d6ee13d7cb8b2cea72e34568a1fdf": "fragment McpEventSummary on Event {\n id\n slug\n name\n location\n eventStartTime\n eventEndTime\n registrationStartTime\n registrationEndTime\n signupOpen\n signupUpcoming\n ownerOrganization {\n name\n __typename\n }\n category {\n name\n __typename\n }\n __typename\n}\nquery McpEvent($slug: String!) {\n currentUser {\n name\n primaryEmail\n __typename\n }\n eventBySlug(slug: $slug) {\n ...McpEventSummary\n description\n isDraft\n openQuotaSize\n quotas(orderBy: POSITION_ASC) {\n nodes {\n id\n title\n size\n registrations {\n totalCount\n __typename\n }\n __typename\n }\n __typename\n }\n eventQuestions(orderBy: POSITION_ASC) {\n nodes {\n id\n type\n label\n isRequired\n data\n __typename\n }\n __typename\n }\n __typename\n }\n}" } \ No newline at end of file diff --git a/@app/server/__tests__/mcp/events.test.ts b/@app/server/__tests__/mcp/events.test.ts new file mode 100644 index 000000000..40385106c --- /dev/null +++ b/@app/server/__tests__/mcp/events.test.ts @@ -0,0 +1,205 @@ +import { McpEventOptionsQuery, QuestionType } from "@app/graphql" +import { Client } from "@modelcontextprotocol/sdk/client/index.js" +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js" + +import { tokenGrantsAdmin } from "../../src/mcp/auth" +import { + createEventInput, + eventSlug, + NewEvent, + plainToRichText, + validateNewEvent, +} from "../../src/mcp/events" +import { createMcpServer, GraphQLRunner } from "../../src/mcp/server" + +const options = { + organizations: { nodes: [{ id: "org-1", name: "PoRa" }] }, + eventCategories: { + nodes: [ + { + id: "cat-1", + name: { fi: "Liikunta" }, + ownerOrganization: { id: "org-1" }, + }, + { id: "cat-2", name: { fi: "Muu" }, ownerOrganization: { id: "org-2" } }, + ], + }, +} as McpEventOptionsQuery + +const valid: NewEvent = { + organizationId: "org-1", + categoryId: "cat-1", + name: { fi: "Testitapahtuma", en: "Test event" }, + description: { fi: "Ensimmäinen.\n\nToinen\nrivi." }, + location: "Otaniemi", + eventStartTime: "2026-12-01T23:30:00+02:00", + eventEndTime: "2026-12-02T02:00:00+02:00", + registrationStartTime: "2026-11-01T12:00:00+02:00", + registrationEndTime: "2026-11-30T12:00:00+02:00", + openQuotaSize: 0, + isHighlighted: false, + quotas: [{ title: { fi: "Kaikki" }, size: 10 }], + questions: [ + { type: QuestionType.Text, label: { fi: "Allergiat" }, required: false }, + { + type: QuestionType.Radio, + label: { fi: "Koko" }, + required: true, + options: [{ fi: "S" }, { fi: "M", en: "M" }], + }, + ], +} + +describe("validateNewEvent", () => { + it("accepts a valid event", () => { + expect(validateNewEvent(valid, options)).toEqual([]) + }) + + it("rejects a category of another organization and unknown ids", () => { + expect( + validateNewEvent({ ...valid, categoryId: "cat-2" }, options) + ).toEqual(["The category belongs to another organization."]) + expect( + validateNewEvent( + { ...valid, organizationId: "nope", categoryId: "nope" }, + options + ) + ).toEqual([ + "organizationId is not an organization.", + "categoryId is not an event category.", + ]) + }) + + it("rejects inconsistent times, missing quotas and option mismatches", () => { + expect( + validateNewEvent( + { + ...valid, + description: { fi: " " }, + eventEndTime: valid.eventStartTime, + registrationEndTime: valid.eventStartTime, + quotas: [], + questions: [ + { + type: QuestionType.Text, + label: { fi: "a" }, + required: false, + options: [{ fi: "x" }], + }, + { + type: QuestionType.Checkbox, + label: { fi: "b" }, + required: false, + }, + ], + }, + options + ) + ).toEqual([ + "A description in Finnish or English is required.", + "The event must end after it starts.", + "Registration must close before the event starts.", + "Give at least one quota or an open quota size above zero.", + "Question 1: TEXT questions take no options.", + "Question 2: CHECKBOX questions need options.", + ]) + }) +}) + +describe("createEventInput", () => { + it("always creates a draft and maps quotas, questions and texts", () => { + const input = createEventInput(valid) + expect(input.event).toMatchObject({ + isDraft: true, + slug: "2026-12-1-testitapahtuma", + name: { fi: "Testitapahtuma", en: "Test event" }, + description: { + fi: [ + { type: "paragraph", children: [{ text: "Ensimmäinen." }] }, + { type: "paragraph", children: [{ text: "Toinen rivi." }] }, + ], + }, + ownerOrganizationId: "org-1", + categoryId: "cat-1", + }) + expect(input.quotas).toEqual([ + { position: 0, title: { fi: "Kaikki" }, size: 10 }, + ]) + expect(input.questions).toEqual([ + { + position: 0, + type: "TEXT", + label: { fi: "Allergiat" }, + isRequired: false, + data: null, + }, + { + position: 1, + type: "RADIO", + label: { fi: "Koko" }, + isRequired: true, + data: [{ fi: "S" }, { fi: "M", en: "M" }], + }, + ]) + }) +}) + +describe("eventSlug", () => { + it("uses the start date in Finnish time", () => { + // 22:30 UTC on Nov 30 is already Dec 1 in Helsinki + expect(eventSlug({ fi: "Pikkujoulut" }, "2026-11-30T22:30:00Z")).toBe( + "2026-12-1-pikkujoulut" + ) + }) +}) + +describe("plainToRichText", () => { + it("drops empty paragraphs", () => { + expect(plainToRichText("\n\nYksi\n\n\n\n")).toEqual([ + { type: "paragraph", children: [{ text: "Yksi" }] }, + ]) + }) +}) + +describe("admin tools", () => { + it("are granted only by the ilmo-admin realm role in the token", () => { + expect(tokenGrantsAdmin({ realm_access: { roles: ["ilmo-admin"] } })).toBe( + true + ) + expect( + tokenGrantsAdmin({ realm_access: { roles: ["offline_access"] } }) + ).toBe(false) + expect(tokenGrantsAdmin({})).toBe(false) + }) + + it.each([ + [false, ["list_events", "get_event", "register_to_event"]], + [ + true, + [ + "list_events", + "get_event", + "register_to_event", + "list_event_options", + "create_event", + ], + ], + ])("are listed only for admins (isAdmin: %s)", async (isAdmin, expected) => { + const runner: GraphQLRunner = { + transaction: () => Promise.reject(new Error("not used")), + } + const server = createMcpServer(runner, { isAdmin }) + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair() + const client = new Client({ name: "test", version: "0" }) + await server.connect(serverTransport) + await client.connect(clientTransport) + try { + const { tools } = await client.listTools() + expect(tools.map((t) => t.name)).toEqual(expected) + } finally { + await client.close() + await server.close() + } + }) +}) diff --git a/@app/server/src/mcp/auth.ts b/@app/server/src/mcp/auth.ts index 098e95e15..ac0295763 100644 --- a/@app/server/src/mcp/auth.ts +++ b/@app/server/src/mcp/auth.ts @@ -3,6 +3,7 @@ import { Pool, PoolClient } from "pg" import { BREAK_GLASS_USERNAMES, + ILMO_ADMIN_ROLE, mapKeycloakClaims, RequestLogger, } from "../utils/keycloak" @@ -26,6 +27,18 @@ export function mcpEnabled() { return !!process.env.KEYCLOAK_ISSUER } +/** + * Admin tools require the realm role in the token itself, so revoking it in + * Keycloak takes effect on the next request. The database's own is_admin + * check still applies on top. MCP never writes is_admin: ilmo-mcp does not + * have full scope, so a missing role scope mapping would otherwise demote + * every admin. + */ +export function tokenGrantsAdmin(claims: JWTPayload) { + const roles = (claims.realm_access as { roles?: unknown } | undefined)?.roles + return Array.isArray(roles) && roles.includes(ILMO_ADMIN_ROLE) +} + type Jwks = ReturnType let jwksPromise: Promise | null = null diff --git a/@app/server/src/mcp/events.ts b/@app/server/src/mcp/events.ts new file mode 100644 index 000000000..678aa63eb --- /dev/null +++ b/@app/server/src/mcp/events.ts @@ -0,0 +1,152 @@ +import { + CreateEventInput, + McpEventOptionsQuery, + QuestionType, +} from "@app/graphql" +import slugify from "slugify" + +export interface Translated { + fi: string + en?: string +} + +export interface NewEvent { + organizationId: string + categoryId: string + name: Translated + description: { fi?: string; en?: string } + location: string + eventStartTime: string + eventEndTime: string + registrationStartTime: string + registrationEndTime: string + openQuotaSize: number + isHighlighted: boolean + quotas: { title: Translated; size: number }[] + questions: { + type: QuestionType + label: Translated + required: boolean + options?: Translated[] + }[] +} + +function translated(value: Translated) { + return value.en ? { fi: value.fi, en: value.en } : { fi: value.fi } +} + +/** Plain text to the editor's Slate document: blank lines separate paragraphs. */ +export function plainToRichText(text: string) { + return text + .split(/\n\s*\n/) + .map((p) => p.replace(/\s*\n\s*/g, " ").trim()) + .filter(Boolean) + .map((p) => ({ type: "paragraph", children: [{ text: p }] })) +} + +/** + * Same shape as the admin form's slug (getEventSlug in @app/components): the + * start date as YYYY-M-D in Finnish time, then the Finnish name. + */ +export function eventSlug(name: Translated, eventStartTime: string) { + const parts = new Intl.DateTimeFormat("en-CA", { + timeZone: "Europe/Helsinki", + year: "numeric", + month: "numeric", + day: "numeric", + }).formatToParts(new Date(eventStartTime)) + const part = (type: string) => + Number(parts.find((p) => p.type === type)!.value) + const day = `${part("year")}-${part("month")}-${part("day")}` + return slugify(`${day}-${name.fi}`, { lower: true }) +} + +type Options = NonNullable + +export function validateNewEvent(event: NewEvent, options: Options): string[] { + const errors: string[] = [] + const time = (field: keyof NewEvent) => + new Date(event[field] as string).getTime() + + if ( + !options.organizations?.nodes.some((o) => o.id === event.organizationId) + ) { + errors.push("organizationId is not an organization.") + } + const category = options.eventCategories?.nodes.find( + (c) => c.id === event.categoryId + ) + if (!category) { + errors.push("categoryId is not an event category.") + } else if (category.ownerOrganization?.id !== event.organizationId) { + errors.push("The category belongs to another organization.") + } + + if (!event.description.fi?.trim() && !event.description.en?.trim()) { + errors.push("A description in Finnish or English is required.") + } + if (time("eventStartTime") >= time("eventEndTime")) { + errors.push("The event must end after it starts.") + } + if (time("registrationStartTime") >= time("registrationEndTime")) { + errors.push("Registration must close after it opens.") + } + if (time("registrationEndTime") >= time("eventStartTime")) { + errors.push("Registration must close before the event starts.") + } + if (event.quotas.length === 0 && event.openQuotaSize < 1) { + errors.push("Give at least one quota or an open quota size above zero.") + } + + event.questions.forEach((q, i) => { + const options = q.options ?? [] + if (q.type === QuestionType.Text && options.length > 0) { + errors.push(`Question ${i + 1}: TEXT questions take no options.`) + } + if (q.type !== QuestionType.Text && options.length === 0) { + errors.push(`Question ${i + 1}: ${q.type} questions need options.`) + } + }) + + return errors +} + +export function createEventInput(event: NewEvent): CreateEventInput { + const description: Record> = {} + if (event.description.fi?.trim()) { + description.fi = plainToRichText(event.description.fi) + } + if (event.description.en?.trim()) { + description.en = plainToRichText(event.description.en) + } + + return { + event: { + slug: eventSlug(event.name, event.eventStartTime), + name: translated(event.name), + description, + location: event.location, + eventStartTime: event.eventStartTime, + eventEndTime: event.eventEndTime, + registrationStartTime: event.registrationStartTime, + registrationEndTime: event.registrationEndTime, + isHighlighted: event.isHighlighted, + isDraft: true, + openQuotaSize: event.openQuotaSize, + ownerOrganizationId: event.organizationId, + categoryId: event.categoryId, + }, + quotas: event.quotas.map((q, position) => ({ + position, + title: translated(q.title), + size: q.size, + })), + questions: event.questions.map((q, position) => ({ + position, + type: q.type, + label: translated(q.label), + isRequired: q.required, + data: q.type === QuestionType.Text ? null : q.options!.map(translated), + })), + } +} diff --git a/@app/server/src/mcp/operations.graphql b/@app/server/src/mcp/operations.graphql index 7eb68ec96..a388ad5fd 100644 --- a/@app/server/src/mcp/operations.graphql +++ b/@app/server/src/mcp/operations.graphql @@ -36,6 +36,24 @@ query McpEvents { } } +query McpEventOptions { + organizations { + nodes { + id + name + } + } + eventCategories(orderBy: NAME_ASC) { + nodes { + id + name + ownerOrganization { + id + } + } + } +} + query McpEvent($slug: String!) { currentUser { name diff --git a/@app/server/src/mcp/server.ts b/@app/server/src/mcp/server.ts index d6bbbcc73..a34fa93f7 100644 --- a/@app/server/src/mcp/server.ts +++ b/@app/server/src/mcp/server.ts @@ -1,19 +1,25 @@ import { ClaimRegistrationTokenDocument, ClaimRegistrationTokenMutation, + CreateEventDocument, + CreateEventMutation, CreateEventRegistrationDocument, CreateEventRegistrationMutation, McpEventDocument, + McpEventOptionsDocument, + McpEventOptionsQuery, McpEventQuery, McpEventsDocument, McpEventsQuery, McpEventSummaryFragment, + QuestionType, } from "@app/graphql" import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { CallToolResult } from "@modelcontextprotocol/sdk/types.js" import { DocumentNode } from "graphql" import { z } from "zod" +import { createEventInput, validateNewEvent } from "./events" import { richTextToPlain, validateRegistration } from "./registration" /** @@ -76,7 +82,10 @@ async function fetchEvent(runner: GraphQLRunner, slug: string) { return { event: data.eventBySlug, currentUser: data.currentUser } } -export function createMcpServer(runner: GraphQLRunner) { +export function createMcpServer( + runner: GraphQLRunner, + { isAdmin }: { isAdmin: boolean } +) { const server = new McpServer({ name: "ilmo", version: "1.0.0" }) server.registerTool( @@ -227,5 +236,129 @@ export function createMcpServer(runner: GraphQLRunner) { }) ) + if (isAdmin) registerAdminTools(server, runner) + return server } + +const translatedSchema = z.object({ + fi: z.string().min(1), + en: z.string().min(1).optional(), +}) + +const datetimeSchema = z.iso + .datetime({ offset: true }) + .describe("ISO 8601 with a UTC offset, e.g. 2026-11-07T10:00:00+02:00") + +function registerAdminTools(server: McpServer, runner: GraphQLRunner) { + server.registerTool( + "list_event_options", + { + title: "List organizers and categories", + description: + "Admin only. Lists the organizations that can organize events and the event categories of each, with the ids create_event needs.", + annotations: { readOnlyHint: true }, + }, + () => + withToolErrors(async () => { + const data = await runner.transaction((run) => + run(McpEventOptionsDocument) + ) + const categories = data.eventCategories?.nodes ?? [] + const organizations = [...(data.organizations?.nodes ?? [])].sort( + (a, b) => a.name.localeCompare(b.name, "fi") + ) + return json( + organizations.map((o) => ({ + id: o.id, + name: o.name, + categories: categories + .filter((c) => c.ownerOrganization?.id === o.id) + .map((c) => ({ id: c.id, name: c.name })), + })) + ) + }) + ) + + server.registerTool( + "create_event", + { + title: "Create event (draft)", + description: + "Admin only. Creates an event as an unpublished draft with its quotas and registration questions. An admin reviews and publishes it in the ilmo admin UI; the result links there. Confirm the details with the user before calling this. Finnish texts are required, English ones optional.", + inputSchema: { + organizationId: z.string().describe("From list_event_options"), + categoryId: z + .string() + .describe("A category of that organization, from list_event_options"), + name: translatedSchema, + description: z + .object({ fi: z.string().optional(), en: z.string().optional() }) + .describe("Plain text; separate paragraphs with a blank line"), + location: z.string().min(1), + eventStartTime: datetimeSchema, + eventEndTime: datetimeSchema, + registrationStartTime: datetimeSchema, + registrationEndTime: datetimeSchema.describe( + "Must be before eventStartTime" + ), + openQuotaSize: z + .number() + .int() + .min(0) + .default(0) + .describe( + "Extra spots shared by all quotas once a quota is full; 0 for none" + ), + isHighlighted: z.boolean().default(false), + quotas: z + .array( + z.object({ title: translatedSchema, size: z.number().int().min(1) }) + ) + .default([]), + questions: z + .array( + z.object({ + type: z.enum(QuestionType), + label: translatedSchema, + required: z.boolean().default(false), + options: z + .array(translatedSchema) + .optional() + .describe("Answer options for RADIO and CHECKBOX questions"), + }) + ) + .default([]), + }, + annotations: { readOnlyHint: false, destructiveHint: false }, + }, + (args) => + withToolErrors(async () => { + const options = await runner.transaction((run) => + run(McpEventOptionsDocument) + ) + const errors = validateNewEvent(args, options) + if (errors.length > 0) { + throw new ToolError(`Event not created:\n- ${errors.join("\n- ")}`) + } + + const data = await runner.transaction((run) => + run(CreateEventDocument, { + input: createEventInput(args), + }) + ) + const event = data.createEvent?.event + if (!event) throw new ToolError("Creating the event failed.") + + return json({ + created: true, + isDraft: true, + id: event.id, + slug: event.slug, + name: event.name, + editUrl: `${process.env.ROOT_URL}/admin/event/update/${event.id}`, + note: "The event is a draft and not visible to members. Review it at editUrl and publish it there.", + }) + }) + ) +} diff --git a/@app/server/src/middleware/installMcp.ts b/@app/server/src/middleware/installMcp.ts index bf7cce953..b1391b5be 100644 --- a/@app/server/src/middleware/installMcp.ts +++ b/@app/server/src/middleware/installMcp.ts @@ -10,6 +10,7 @@ import { mcpEnabled, mcpResourceUrl, resolveMcpSession, + tokenGrantsAdmin, verifyAccessToken, } from "../mcp/auth" import { @@ -64,9 +65,11 @@ const InstallMcp: FastifyPluginAsync = async (app) => { if (!token) return unauthorized(reply) let sessionId: string + let isAdmin: boolean try { const claims = await verifyAccessToken(token) sessionId = await resolveMcpSession(app.rootPgPool, claims, request.log) + isAdmin = tokenGrantsAdmin(claims) } catch (e) { if (e instanceof McpAuthError) return unauthorized(reply, e) request.log.error({ err: e }, "mcp: authentication failed") @@ -133,7 +136,7 @@ const InstallMcp: FastifyPluginAsync = async (app) => { ) as Promise, } - const server = createMcpServer(runner) + const server = createMcpServer(runner, { isAdmin }) const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true, diff --git a/docker/keycloak/realm-dev.json b/docker/keycloak/realm-dev.json index 34ef489b0..9eff7e9a3 100644 --- a/docker/keycloak/realm-dev.json +++ b/docker/keycloak/realm-dev.json @@ -153,5 +153,11 @@ } ] } + ], + "scopeMappings": [ + { + "client": "ilmo-mcp", + "roles": ["ilmo-admin"] + } ] } diff --git a/docs/mcp.md b/docs/mcp.md index c63b35a2d..b1f44ca17 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13,8 +13,22 @@ Tools: - `register_to_event` — registers to a quota. Answers are validated before a spot is claimed, and a failed registration releases the spot it claimed. -Editing or cancelling a registration is not available over MCP; the confirmation -email's link does that, as on the web. +Admins also get: + +- `list_event_options` — organizations and their event categories, with the ids + `create_event` needs. +- `create_event` — creates an event with its quotas and questions. The event is + always an unpublished draft; an admin reviews and publishes it in the admin + UI, which the result links to. + +Admin tools are listed and run only when the access token carries the +`ilmo-admin` realm role, so revoking the role in membership-registry takes +effect on the next request. The database's own `users.is_admin` check applies on +top, and MCP never writes that flag: an admin must have signed in to the web app +since getting the role. + +Editing or cancelling a registration, and editing or publishing an event, are +not available over MCP. ## Using it @@ -83,12 +97,17 @@ The labels below are those of the Keycloak 26 admin console. on, Add to ID token off. A hardcoded audience is used instead of Audience Resolve because the latter adds client IDs only, from client roles, and with Full scope allowed would put ilmo's audience into other clients' tokens too. -7. **Client scopes**: `basic`, `email`, `profile` as Default and +7. **Client scopes**: `basic`, `email`, `profile`, `roles` as Default and `offline_access` as Optional. -8. **Client scopes → Evaluate**: pick a member, add `offline_access` to the +8. **Client scopes → `ilmo-mcp-dedicated` → Scope**: if Full scope allowed is + off, **Assign role** → realm role `ilmo-admin`. Without it admins' tokens + omit the role and the admin tools stay hidden. Do not turn Full scope allowed + on instead; it would put every realm role into these tokens. +9. **Client scopes → Evaluate**: pick a member, add `offline_access` to the scope parameter and open Generated access token. It must contain `"aud": "https://ilmo.prodeko.org/mcp"`, `"typ": "Bearer"`, `sid`, `email` - and `"email_verified": true`; ilmo refuses tokens without them. + and `"email_verified": true`; ilmo refuses tokens without them. For an admin, + `realm_access.roles` must also contain `ilmo-admin`. If a WAF or IP filter sits in front of `id.prodeko.org` or `ilmo.prodeko.org`, allow Anthropic's egress range `160.79.104.0/21`: claude.ai fetches Keycloak's From 713b70566afc2d4d90dbee4a68417f0167d45e9a Mon Sep 17 00:00:00 2001 From: Henri Salmi Date: Sat, 17 Oct 2026 17:03:48 +0300 Subject: [PATCH 8/8] chore: commit current migrations as 000005 Production applies committed migrations only, so the MCP session columns and the pending admin organization policy and quota deletion fixes from #67 and #69 would otherwise never reach it. Every part is idempotent, so a database that already ran them from current is unaffected. Co-Authored-By: Claude Opus 5.5 --- .../000005.sql} | 59 +++++++++++++++++++ @app/db/migrations/current/1-current.sql | 17 +----- @app/db/migrations/current/3-mcp-sessions.sql | 35 ----------- data/schema.sql | 38 +++++++++++- 4 files changed, 95 insertions(+), 54 deletions(-) rename @app/db/migrations/{current/2-delete-omitted-quotas-and-questions.sql => committed/000005.sql} (60%) delete mode 100644 @app/db/migrations/current/3-mcp-sessions.sql diff --git a/@app/db/migrations/current/2-delete-omitted-quotas-and-questions.sql b/@app/db/migrations/committed/000005.sql similarity index 60% rename from @app/db/migrations/current/2-delete-omitted-quotas-and-questions.sql rename to @app/db/migrations/committed/000005.sql index 220ed34d7..e082760e7 100644 --- a/@app/db/migrations/current/2-delete-omitted-quotas-and-questions.sql +++ b/@app/db/migrations/committed/000005.sql @@ -1,3 +1,25 @@ +--! Previous: sha1:eafce160dd3a8ec859a47bc11b5c9117cc07fd8e +--! Hash: sha1:d86e34f82d1579f1b5f6f91bd24ccb41f19b5d53 + +--! split: 1-current.sql +/* + * Admins manage every organization, the same way `manage_admin` on + * `app_public.events` and `app_public.registrations` already lets them manage + * every event. Without this, `update_owner` is the only route to updating an + * organization, so changing one's settings requires an `is_owner` row in + * `organization_memberships` — which admins have no reason to hold, and which + * nobody holds for an organization they did not create. + * + * Membership keeps its own meaning: the way a non-admin is given rights over a + * single organization's events. + */ + +drop policy if exists manage_admin on app_public.organizations; + +create policy manage_admin on app_public.organizations + for all using (app_public.current_user_is_admin()); + +--! split: 2-delete-omitted-quotas-and-questions.sql /* * The admin UI sends an event's kept quotas with their ids and newly added * quotas with a null id. Deletion of omitted quotas is detected with @@ -109,3 +131,40 @@ begin return v_ret; end; $$ language plpgsql volatile security invoker set search_path = pg_catalog, public, pg_temp; + +--! split: 3-mcp-sessions.sql +/* + * MCP requests authenticate with a Keycloak access token instead of a session + * cookie. The server turns each verified token into an ordinary + * app_private.sessions row so that current_user_id(), RLS and the ownership + * triggers work unchanged, and so that the database keeps identifying users by + * an unguessable session id rather than by a raw user id (see the comment on + * current_user_id). + * + * One MCP session exists per Keycloak session (`oauth_sid`, the token's `sid` + * claim): token refreshes reuse it. The rows are derived state — the server + * recreates one on the next request if it is gone — so inactive MCP sessions + * can be deleted aggressively by the sessions__delete_inactive_mcp_sessions + * task. + */ + +alter table app_private.sessions + add column if not exists kind text not null default 'web', + add column if not exists oauth_sid text; + +alter table app_private.sessions drop constraint if exists sessions_kind_check; +alter table app_private.sessions + add constraint sessions_kind_check check (kind in ('web', 'mcp')); + +alter table app_private.sessions drop constraint if exists sessions_oauth_sid_check; +alter table app_private.sessions + add constraint sessions_oauth_sid_check check ((kind = 'mcp') = (oauth_sid is not null)); + +drop index if exists app_private.sessions_mcp_oauth_sid_key; +create unique index sessions_mcp_oauth_sid_key + on app_private.sessions (oauth_sid) where kind = 'mcp'; + +comment on column app_private.sessions.kind is + E'How the session was established: web (session cookie) or mcp (Keycloak access token on /mcp).'; +comment on column app_private.sessions.oauth_sid is + E'Keycloak session id (the access token sid claim) of an mcp session.'; diff --git a/@app/db/migrations/current/1-current.sql b/@app/db/migrations/current/1-current.sql index 67a36aa4f..8da533983 100644 --- a/@app/db/migrations/current/1-current.sql +++ b/@app/db/migrations/current/1-current.sql @@ -1,16 +1 @@ -/* - * Admins manage every organization, the same way `manage_admin` on - * `app_public.events` and `app_public.registrations` already lets them manage - * every event. Without this, `update_owner` is the only route to updating an - * organization, so changing one's settings requires an `is_owner` row in - * `organization_memberships` — which admins have no reason to hold, and which - * nobody holds for an organization they did not create. - * - * Membership keeps its own meaning: the way a non-admin is given rights over a - * single organization's events. - */ - -drop policy if exists manage_admin on app_public.organizations; - -create policy manage_admin on app_public.organizations - for all using (app_public.current_user_is_admin()); +-- Enter migration here diff --git a/@app/db/migrations/current/3-mcp-sessions.sql b/@app/db/migrations/current/3-mcp-sessions.sql deleted file mode 100644 index 0ad951916..000000000 --- a/@app/db/migrations/current/3-mcp-sessions.sql +++ /dev/null @@ -1,35 +0,0 @@ -/* - * MCP requests authenticate with a Keycloak access token instead of a session - * cookie. The server turns each verified token into an ordinary - * app_private.sessions row so that current_user_id(), RLS and the ownership - * triggers work unchanged, and so that the database keeps identifying users by - * an unguessable session id rather than by a raw user id (see the comment on - * current_user_id). - * - * One MCP session exists per Keycloak session (`oauth_sid`, the token's `sid` - * claim): token refreshes reuse it. The rows are derived state — the server - * recreates one on the next request if it is gone — so inactive MCP sessions - * can be deleted aggressively by the sessions__delete_inactive_mcp_sessions - * task. - */ - -alter table app_private.sessions - add column if not exists kind text not null default 'web', - add column if not exists oauth_sid text; - -alter table app_private.sessions drop constraint if exists sessions_kind_check; -alter table app_private.sessions - add constraint sessions_kind_check check (kind in ('web', 'mcp')); - -alter table app_private.sessions drop constraint if exists sessions_oauth_sid_check; -alter table app_private.sessions - add constraint sessions_oauth_sid_check check ((kind = 'mcp') = (oauth_sid is not null)); - -drop index if exists app_private.sessions_mcp_oauth_sid_key; -create unique index sessions_mcp_oauth_sid_key - on app_private.sessions (oauth_sid) where kind = 'mcp'; - -comment on column app_private.sessions.kind is - E'How the session was established: web (session cookie) or mcp (Keycloak access token on /mcp).'; -comment on column app_private.sessions.oauth_sid is - E'Keycloak session id (the access token sid claim) of an mcp session.'; diff --git a/data/schema.sql b/data/schema.sql index 80709ee2a..258451d32 100644 --- a/data/schema.sql +++ b/data/schema.sql @@ -471,10 +471,28 @@ CREATE TABLE app_private.sessions ( uuid uuid DEFAULT gen_random_uuid() NOT NULL, user_id uuid NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, - last_active timestamp with time zone DEFAULT now() NOT NULL + last_active timestamp with time zone DEFAULT now() NOT NULL, + kind text DEFAULT 'web'::text NOT NULL, + oauth_sid text, + CONSTRAINT sessions_kind_check CHECK ((kind = ANY (ARRAY['web'::text, 'mcp'::text]))), + CONSTRAINT sessions_oauth_sid_check CHECK (((kind = 'mcp'::text) = (oauth_sid IS NOT NULL))) ); +-- +-- Name: COLUMN sessions.kind; Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON COLUMN app_private.sessions.kind IS 'How the session was established: web (session cookie) or mcp (Keycloak access token on /mcp).'; + + +-- +-- Name: COLUMN sessions.oauth_sid; Type: COMMENT; Schema: app_private; Owner: - +-- + +COMMENT ON COLUMN app_private.sessions.oauth_sid IS 'Keycloak session id (the access token sid claim) of an mcp session.'; + + -- -- Name: login(public.citext, text); Type: FUNCTION; Schema: app_private; Owner: - -- @@ -3277,7 +3295,7 @@ begin select array( select id from app_public.event_questions as q where q.event_id = event_id - and q.id not in (select id from unnest(questions)) + and q.id not in (select id from unnest(questions) where id is not null) ) into v_question_ids_to_delete; @@ -3342,7 +3360,7 @@ begin select array( select id from app_public.quotas as q where q.event_id = event_id - and q.id not in (select id from unnest(quotas)) + and q.id not in (select id from unnest(quotas) where id is not null) ) into v_quota_ids_to_delete; @@ -4201,6 +4219,13 @@ CREATE INDEX registration_secrets_quota_id_idx ON app_private.registration_secre CREATE INDEX registration_secrets_registration_id_idx ON app_private.registration_secrets USING btree (registration_id); +-- +-- Name: sessions_mcp_oauth_sid_key; Type: INDEX; Schema: app_private; Owner: - +-- + +CREATE UNIQUE INDEX sessions_mcp_oauth_sid_key ON app_private.sessions USING btree (oauth_sid) WHERE (kind = 'mcp'::text); + + -- -- Name: sessions_user_id_idx; Type: INDEX; Schema: app_private; Owner: - -- @@ -5065,6 +5090,13 @@ CREATE POLICY manage_admin ON app_public.event_questions USING (app_public.curre CREATE POLICY manage_admin ON app_public.events USING (app_public.current_user_is_admin()); +-- +-- Name: organizations manage_admin; Type: POLICY; Schema: app_public; Owner: - +-- + +CREATE POLICY manage_admin ON app_public.organizations USING (app_public.current_user_is_admin()); + + -- -- Name: quotas manage_admin; Type: POLICY; Schema: app_public; Owner: - --