Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M5-007): mcp module: stateless-POST rebuild per ADR-015 entry 2 + wave checkpoint

ralph2caf2727ceda
diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile
index 389a185f0..c3b4c8cd4 100644
--- a/apps/api/Dockerfile
+++ b/apps/api/Dockerfile
@@ -28,7 +28,6 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json ./apps/api/
# Packages
COPY packages/db/package.json packages/db/
-COPY packages/mcp/package.json packages/mcp/
COPY packages/trpc/package.json packages/trpc/
COPY packages/auth/package.json packages/auth/
COPY packages/json/package.json packages/json/
@@ -94,7 +93,6 @@ COPY --from=build /app/apps/api ./apps/api
# Packages
COPY --from=build /app/packages/db ./packages/db
-COPY --from=build /app/packages/mcp ./packages/mcp
COPY --from=build /app/packages/auth ./packages/auth
COPY --from=build /app/packages/trpc ./packages/trpc
COPY --from=build /app/packages/json ./packages/json
diff --git a/apps/api/package.json b/apps/api/package.json
index b8539ba67..52ee3bfa0 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -32,7 +32,6 @@
"@openpanel/core": "workspace:*",
"@openpanel/db": "workspace:*",
"@openpanel/json": "workspace:*",
- "@openpanel/mcp": "workspace:*",
"@openpanel/payments": "workspace:*",
"@openpanel/queue": "workspace:*",
"@openpanel/redis": "workspace:*",
diff --git a/apps/api/src/routes/mcp.router.ts b/apps/api/src/routes/mcp.router.ts
index 99a8e79d6..c3b6a7175 100644
--- a/apps/api/src/routes/mcp.router.ts
+++ b/apps/api/src/routes/mcp.router.ts
@@ -1,80 +1,39 @@
-import { McpAuthError, authenticateToken, extractToken, handleMcpGet, handleMcpPost, SessionManager } from '@openpanel/mcp';
+// Dissolved into @openpanel/core's mcp module (M5-007): auth, tool
+// dispatch and the streamable-HTTP protocol handling moved to
+// packages/core/src/modules/mcp/mcp.service.ts#handleStatelessMcpRequest.
+// This router stays (DELEGATE PATTERN) for rate limiting and the generic
+// 500 catch — everything protocol-shaped is core's.
+//
+// ADR-015 entry 2 (accepted): MCP is stateless-POST only. GET/SSE, DELETE
+// and the Redis session store (`mcp:session:<uuid>`, the `Mcp-Session-Id`
+// header) are REMOVED here, not delegated — MCP is the one module this wave
+// is allowed to change the endpoint surface of.
+import { handleMcpRequest } from '@openpanel/core';
import type { FastifyPluginAsync } from 'fastify';
import { activateRateLimiter } from '@/utils/rate-limiter';
-/**
- * Singleton session manager — lives for the lifetime of the API process.
- * Exported so graceful shutdown can clean it up.
- */
-export const mcpSessionManager = new SessionManager();
-
const mcpRouter: FastifyPluginAsync = async (fastify) => {
await activateRateLimiter({ fastify, max: 60, timeWindow: '1 minute' });
/**
* POST /mcp
*
- * Handles both session initialization (no Mcp-Session-Id header) and
- * subsequent JSON-RPC messages within an existing session.
- *
- * First request: authenticate via ?token= query param or Authorization: Bearer.
- * Subsequent requests: route by Mcp-Session-Id header.
+ * Every request authenticates via ?token= query param or Authorization:
+ * Bearer and runs on a fresh, per-request MCP server — no session, no
+ * sticky-instance requirement.
*/
await fastify.post('/', async (req, reply) => {
- // Hand off full response control to the MCP transport
- reply.hijack();
- await handleMcpPost(
- mcpSessionManager,
- req.raw,
- reply.raw,
- req.body,
- req.query as Record<string, unknown>,
- );
- });
-
- /**
- * GET /mcp
- *
- * Establishes an SSE stream for server-to-client notifications.
- * Requires Mcp-Session-Id header from a previously initialized session.
- */
- await fastify.get('/', async (req, reply) => {
- reply.hijack();
- await handleMcpGet(mcpSessionManager, req.raw, reply.raw);
- });
-
- /**
- * DELETE /mcp
- *
- * Explicitly close an MCP session and free its resources.
- * Requires the same auth token used to create the session — verified against
- * the session's organizationId to prevent one client closing another's session.
- */
- await fastify.delete('/', async (req, reply) => {
- const sessionId = req.headers['mcp-session-id'] as string | undefined;
- if (!sessionId) {
- return reply.status(400).send({ error: 'Mcp-Session-Id header is required' });
- }
-
- const token = extractToken(req.query as Record<string, unknown>, req.headers.authorization);
- let callerContext;
try {
- callerContext = await authenticateToken(token);
+ const { status, body } = await handleMcpRequest(
+ req.query as Record<string, unknown>,
+ req.headers.authorization,
+ req.body
+ );
+ return reply.status(status).send(body);
} catch (err) {
- return reply.status(401).send({ error: err instanceof McpAuthError ? err.message : 'Unauthorized' });
+ req.log.error({ err }, 'MCP request processing error');
+ return reply.status(500).send({ error: 'Internal server error' });
}
-
- const context = await mcpSessionManager.getContext(sessionId);
- if (!context) {
- return reply.status(404).send({ error: 'Session not found' });
- }
-
- if (context.organizationId !== callerContext.organizationId) {
- return reply.status(403).send({ error: 'Forbidden' });
- }
-
- await mcpSessionManager.close(sessionId);
- return reply.status(200).send({ ok: true });
});
};
diff --git a/apps/api/src/utils/graceful-shutdown.ts b/apps/api/src/utils/graceful-shutdown.ts
index f95592499..b8364341a 100644
--- a/apps/api/src/utils/graceful-shutdown.ts
+++ b/apps/api/src/utils/graceful-shutdown.ts
@@ -13,7 +13,6 @@ import {
} from '@openpanel/redis';
import type { FastifyInstance } from 'fastify';
import { logger } from './logger';
-import { mcpSessionManager } from '@/routes/mcp.router';
let shuttingDown = false;
@@ -48,7 +47,7 @@ export async function shutdown(
const forceExit = setTimeout(() => {
logger.error(
{ signal, forceExitMs },
- 'Graceful shutdown timed out — forcing exit',
+ 'Graceful shutdown timed out — forcing exit'
);
process.exit(exitCode);
}, forceExitMs);
@@ -66,15 +65,7 @@ export async function shutdown(
logger.error({ err: error }, 'Error closing Fastify server');
}
- // Step 3: Destroy MCP sessions
- try {
- await mcpSessionManager.destroy();
- logger.info('MCP sessions closed');
- } catch (error) {
- logger.error({ err: error }, 'Error closing MCP sessions');
- }
-
- // Step 4: Close database connections
+ // Step 3: Close database connections
try {
await db.$disconnect();
logger.info('Database connection closed');
@@ -82,7 +73,7 @@ export async function shutdown(
logger.error({ err: error }, 'Error closing database connection');
}
- // Step 5: Close ClickHouse connections
+ // Step 4: Close ClickHouse connections
try {
await ch.close();
logger.info('ClickHouse connections closed');
@@ -90,7 +81,7 @@ export async function shutdown(
logger.error({ err: error }, 'Error closing ClickHouse connections');
}
- // Step 6: Close Bull queues (graceful shutdown of queue state)
+ // Step 5: Close Bull queues (graceful shutdown of queue state)
try {
await Promise.all([
sessionsQueue.close(),
@@ -102,7 +93,7 @@ export async function shutdown(
logger.error({ err: error }, 'Error closing queue state');
}
- // Step 6.5: Disconnect Kafka producer (no-op if never initialized)
+ // Step 5.5: Disconnect Kafka producer (no-op if never initialized)
try {
await disconnectKafka();
logger.info('Kafka producer disconnected');
@@ -110,7 +101,7 @@ export async function shutdown(
logger.error({ err: error }, 'Error disconnecting Kafka producer');
}
- // Step 7: Close Redis connections
+ // Step 6: Close Redis connections
try {
const redisConnections = [
getRedisCache(),
diff --git a/packages/core/package.json b/packages/core/package.json
index 82ae8262e..23ea0ac0d 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -26,6 +26,7 @@
"@google-cloud/storage": "^7.18.0",
"@hyperdx/node-opentelemetry": "catalog:",
"@maxmind/geoip2-node": "^6.1.0",
+ "@modelcontextprotocol/sdk": "^1.12.0",
"@node-rs/argon2": "^2.0.2",
"@openpanel/common": "workspace:*",
"@openpanel/constants": "workspace:*",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index b0c282393..aec48dc0c 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -274,6 +274,37 @@ export {
selectGscSite,
syncGscData,
} from './modules/gsc/gsc.service';
+
+// packages/mcp absorbed whole (M5-007) — apps/api's mcp.router.ts is the one
+// external caller, delegating the streamable-HTTP POST protocol here
+// (DELEGATE PATTERN). ADR-015 entry 2: stateless-only, so there is no
+// SessionManager to manage.
+//
+// Loaded via dynamic import, NOT a static re-export, for the same reason
+// `getChatApp`/`runFilterCommand` above are: `mcp.service` reaches
+// `@openpanel/db` (auth's client lookup, every analytics tool), and
+// `@openpanel/db/src/buffers/base-buffer.ts` already imports `@openpanel/core`
+// eagerly. A static export here would make this barrel's own evaluation
+// re-enter `@openpanel/db` mid-evaluation — observed as a `PagesService` TDZ
+// ReferenceError two modules away, in a tool file that never otherwise runs
+// at import time.
+let _mcp: Promise<typeof import('./modules/mcp/mcp.service')> | undefined;
+function loadMcp() {
+ if (!_mcp) {
+ _mcp = import('./modules/mcp/mcp.service');
+ }
+ return _mcp;
+}
+
+export async function handleMcpRequest(
+ query: Record<string, unknown>,
+ authHeader: string | undefined,
+ body: unknown
+): Promise<{ status: number; body: unknown }> {
+ const { extractToken, handleStatelessMcpRequest } = await loadMcp();
+ const token = extractToken(query, authHeader);
+ return handleStatelessMcpRequest(token, body);
+}
// Dissolved from @openpanel/db's services/import.service.ts +
// apps/worker's job file + apps/api's /import controller (M5-004) —
// apps/worker's import job file and apps/api's import controller call these
@@ -368,8 +399,9 @@ export type {
} from './shared/access';
export { createAccessChecks } from './shared/access';
// Dissolved from @openpanel/common/server (M4-003) — a still-live V1 package
-// (db, importer, mcp, queue, apps/worker) reaches these the same way apps/api
-// and core itself do, until its own module lands.
+// (db, queue, apps/worker) reaches these the same way apps/api and core
+// itself do, until its own module lands. mcp reaches it as an internal
+// relative import now that it lives inside core (M5-007).
export {
createHash,
generateSalt,
diff --git a/packages/core/src/modules/cohort/cohort.service.test.ts b/packages/core/src/modules/cohort/cohort.service.test.ts
index d70b0d701..4764b517a 100644
--- a/packages/core/src/modules/cohort/cohort.service.test.ts
+++ b/packages/core/src/modules/cohort/cohort.service.test.ts
@@ -9,7 +9,7 @@
// file, src/cohort-sql.test.ts, and need none of this — they take no
// ClickHouse connection.
-import { beforeAll, expect, mock, test } from 'bun:test';
+import { afterAll, beforeAll, expect, mock, test } from 'bun:test';
interface FakeCohort {
id: string;
@@ -52,7 +52,9 @@ const cohort = {
),
};
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
db: { cohort },
}));
@@ -60,37 +62,48 @@ const chQuery = mock(async () => [] as unknown[]);
const chInsert = mock(async (_args: { table: string }) => undefined);
const chCommand = mock(async (_args: { query: string }) => undefined);
const getReplicatedTableName = mock((table: string) => table);
-// `originalCh`/`TABLE_NAMES`/`formatClickhouseDate`/
-// `convertClickhouseDateToJs` and the extra TABLE_NAMES keys are unused here
-// but included because `mock.module` replaces this specifier process-wide
-// (bun runs every test file in one shared module registry without
-// `--isolate` — see AGENTS.md) — gsc.service.test.ts,
-// insight.service.test.ts and import.service.test.ts mock the same path, so
-// every factory must be a superset of every consumer's needs, whichever one
-// ends up registered last.
+// Spread the real module rather than hand-listing every export: `mock.module`
+// replaces this specifier process-wide (bun runs every test file in one
+// shared module registry without `--isolate` — see AGENTS.md), so a partial
+// factory here silently breaks unrelated consumers (gsc/insight/import tests
+// and now the mcp module's) that import an export this file never overrides.
+// `ch` itself is one such export: only `insert`/`command` are what
+// cohort.service.ts exercises, so those two are overridden and every other
+// method (`query`, ...) is spread from the real client — a bare `{ insert,
+// command }` replacement previously stripped `query` from every *other*
+// consumer of this same live-bound singleton (e.g. `@openpanel/db`'s
+// `OverviewService`/`PagesService`, constructed once at that module's own
+// load time) for the rest of the process.
+// A plain-object snapshot, not the live import binding: once `mock.module`
+// below swaps this specifier, `actualClickhouseClient.chQuery` (a namespace
+// binding) reflects the *mocked* value too, so restoring via
+// `actualClickhouseClient` itself in `afterAll` is a no-op — it just spreads
+// back whatever is currently mocked. Snapshotting into a plain object first
+// keeps a real, frozen-in-time copy to restore to.
+const actualClickhouseClient = await import(
+ '@openpanel/db/src/clickhouse/client'
+);
+const realClickhouseClient = { ...actualClickhouseClient };
mock.module('@openpanel/db/src/clickhouse/client', () => ({
- ch: { insert: chInsert, command: chCommand },
- originalCh: {
- query: mock(async () => ({ json: async () => [] as unknown[] })),
- insert: mock(async () => undefined),
- },
+ ...realClickhouseClient,
+ ch: { ...realClickhouseClient.ch, insert: chInsert, command: chCommand },
chQuery,
getReplicatedTableName,
- TABLE_NAMES: {
- events: 'events',
- events_imports: 'events_imports',
- profiles: 'profiles',
- sessions: 'sessions',
- },
- formatClickhouseDate: (date: Date | string) =>
- new Date(date)
- .toISOString()
- .replace('T', ' ')
- .replace(/(\.\d{3})?Z+$/, ''),
- convertClickhouseDateToJs: (date: string) =>
- new Date(`${date.replace(' ', 'T')}Z`),
}));
+// `chQuery`/`ch.insert`/`ch.command` above are fakes stuck in place for the
+// rest of the process once this file's tests finish (`mock.module` has no
+// per-file scope without `--isolate` — see AGENTS.md): the mcp module's
+// integration suite calls the real `chQuery` against a live ClickHouse and
+// silently got `[]` back from this file's leftover mock. Restore the real
+// snapshot so whichever file runs next sees real behavior again.
+afterAll(() => {
+ mock.module(
+ '@openpanel/db/src/clickhouse/client',
+ () => realClickhouseClient
+ );
+});
+
let subject: typeof import('./cohort.service');
beforeAll(async () => {
subject = await import('./cohort.service');
diff --git a/packages/core/src/modules/conversation/conversation.service.test.ts b/packages/core/src/modules/conversation/conversation.service.test.ts
index 21c25dc8d..2d766ef0b 100644
--- a/packages/core/src/modules/conversation/conversation.service.test.ts
+++ b/packages/core/src/modules/conversation/conversation.service.test.ts
@@ -101,7 +101,9 @@ const conversation = {
}),
};
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
db: { conversation },
}));
diff --git a/packages/core/src/modules/gsc/gsc.service.test.ts b/packages/core/src/modules/gsc/gsc.service.test.ts
index e1fbb0159..46fe6a767 100644
--- a/packages/core/src/modules/gsc/gsc.service.test.ts
+++ b/packages/core/src/modules/gsc/gsc.service.test.ts
@@ -4,7 +4,7 @@
// mock below is registered before the subject's first call, not before its
// (side-effect-free) import.
-import { beforeAll, expect, mock, test } from 'bun:test';
+import { afterAll, beforeAll, expect, mock, test } from 'bun:test';
process.env.ENCRYPTION_KEY = 'a'.repeat(64);
@@ -86,7 +86,11 @@ const project = {
),
};
+// Spread the real module — see the clickhouse/client mock below for why a
+// partial factory here is a process-wide hazard, not a local one.
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
db: { gscConnection, project },
}));
@@ -95,37 +99,46 @@ const originalCh = {
query: mock(async () => ({ json: async () => [] as unknown[] })),
insert: mock(async () => undefined),
};
-// `ch`/`getReplicatedTableName`/`formatClickhouseDate`/
-// `convertClickhouseDateToJs` and the extra TABLE_NAMES keys are unused here
-// but included because `mock.module` replaces this specifier process-wide
-// (bun runs every test file in one shared module registry without
-// `--isolate` — see AGENTS.md) — insight.service.test.ts,
-// cohort.service.test.ts and import.service.test.ts mock the same path, so
-// every factory must be a superset of every consumer's needs, whichever one
-// ends up registered last.
+// Spread the real module rather than hand-listing every export: `mock.module`
+// replaces this specifier process-wide (bun runs every test file in one
+// shared module registry without `--isolate` — see AGENTS.md), so a partial
+// factory here silently breaks unrelated consumers (insight/cohort/import
+// tests and now the mcp module's) that import an export this file never
+// overrides. `ch` itself is one such export: gsc.service.ts never calls it
+// (it goes through `originalCh`/`chQuery` — see the file's header), so it is
+// spread wholesale rather than replaced, keeping `query` intact for every
+// *other* consumer of this same live-bound singleton (e.g. `@openpanel/db`'s
+// `OverviewService`/`PagesService`, constructed once at that module's own
+// load time) for the rest of the process.
+// A plain-object snapshot, not the live import binding: once `mock.module`
+// below swaps this specifier, `actualClickhouseClient.chQuery` (a namespace
+// binding) reflects the *mocked* value too, so restoring via
+// `actualClickhouseClient` itself in `afterAll` is a no-op — it just spreads
+// back whatever is currently mocked. Snapshotting into a plain object first
+// keeps a real, frozen-in-time copy to restore to.
+const actualClickhouseClient = await import(
+ '@openpanel/db/src/clickhouse/client'
+);
+const realClickhouseClient = { ...actualClickhouseClient };
mock.module('@openpanel/db/src/clickhouse/client', () => ({
- ch: {
- insert: mock(async () => undefined),
- command: mock(async () => undefined),
- },
+ ...realClickhouseClient,
originalCh,
chQuery,
- getReplicatedTableName: mock((table: string) => table),
- TABLE_NAMES: {
- events: 'events',
- events_imports: 'events_imports',
- profiles: 'profiles',
- sessions: 'sessions',
- },
- formatClickhouseDate: (date: Date | string) =>
- new Date(date)
- .toISOString()
- .replace('T', ' ')
- .replace(/(\.\d{3})?Z+$/, ''),
- convertClickhouseDateToJs: (date: string) =>
- new Date(`${date.replace(' ', 'T')}Z`),
}));
+// `chQuery` above is a fake stuck in place for the rest of the process once
+// this file's tests finish (`mock.module` has no per-file scope without
+// `--isolate` — see AGENTS.md): the mcp module's integration suite calls the
+// real `chQuery` against a live ClickHouse and silently got `[]` back from
+// this file's leftover mock. Restore the real snapshot so whichever file
+// runs next sees real behavior again.
+afterAll(() => {
+ mock.module(
+ '@openpanel/db/src/clickhouse/client',
+ () => realClickhouseClient
+ );
+});
+
// Bypasses the Redis cache-aside entirely — `getGscCannibalization`'s own
// logic is exercised directly, its caching is @openpanel/redis's concern.
// `getRedisCache` is unused here but included for the same cross-file
@@ -149,7 +162,13 @@ mock.module('../auth/auth.service', () => ({
}));
const getSettingsForProject = mock(async () => ({ timezone: 'UTC' }));
+// Spread the real module — see the clickhouse/client mock above for why a
+// partial factory here is a process-wide hazard, not a local one.
+const actualOrganizationService = await import(
+ '@openpanel/db/src/services/organization.service'
+);
mock.module('@openpanel/db/src/services/organization.service', () => ({
+ ...actualOrganizationService,
getSettingsForProject,
}));
@@ -157,7 +176,13 @@ const getChartStartEndDate = mock(() => ({
startDate: '2026-09-01T00:00:00.000Z',
endDate: '2026-09-03T00:00:00.000Z',
}));
+// Spread the real module — see the clickhouse/client mock above for why a
+// partial factory here is a process-wide hazard, not a local one.
+const actualDateService = await import(
+ '@openpanel/db/src/services/date.service'
+);
mock.module('@openpanel/db/src/services/date.service', () => ({
+ ...actualDateService,
getChartStartEndDate,
}));
diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.ts
index 546376c0d..3a9eaba7d 100644
--- a/packages/core/src/modules/import/import.service.test.ts
+++ b/packages/core/src/modules/import/import.service.test.ts
@@ -26,30 +26,29 @@ function stubLogger(): Logger {
const chInsert = mock(async (_opts: { values: unknown[] }) => ({
summary: { written_rows: '2' },
}));
-// `ch.command`/`originalCh`/`chQuery`/`getReplicatedTableName`/
-// `convertClickhouseDateToJs` and the extra TABLE_NAMES keys are unused here
-// but included because `mock.module` replaces this specifier process-wide
-// (bun runs every test file in one shared module registry without
-// `--isolate` — see AGENTS.md) — gsc.service.test.ts, cohort.service.test.ts
-// and insight.service.test.ts mock the same path, so every factory must be a
-// superset of every consumer's needs, whichever one ends up registered last.
+// Spread the real module rather than hand-listing every export: `mock.module`
+// replaces this specifier process-wide (bun runs every test file in one
+// shared module registry without `--isolate` — see AGENTS.md), so a partial
+// factory here silently breaks unrelated consumers (gsc/cohort/insight tests
+// and now the mcp module's) that import an export this file never overrides.
+// `ch` itself is one such export: only `insert` is what import.service.ts
+// exercises, so `command` is stubbed and every other method (`query`, ...) is
+// spread from the real client — a bare `{ insert, command }` replacement
+// previously stripped `query` from every *other* consumer of this same
+// live-bound singleton (e.g. `@openpanel/db`'s `OverviewService`/
+// `PagesService`, constructed once at that module's own load time) for the
+// rest of the process.
+const actualClickhouseClient = await import(
+ '@openpanel/db/src/clickhouse/client'
+);
mock.module('@openpanel/db/src/clickhouse/client', () => ({
+ ...actualClickhouseClient,
ch: {
+ ...actualClickhouseClient.ch,
insert: chInsert,
command: mock(async () => undefined),
},
- originalCh: {
- query: mock(async () => ({ json: async () => [] as unknown[] })),
- insert: mock(async () => undefined),
- },
- chQuery: mock(async () => [] as unknown[]),
getReplicatedTableName: mock((table: string) => table),
- TABLE_NAMES: {
- events: 'events',
- events_imports: 'events_imports',
- profiles: 'profiles',
- sessions: 'sessions',
- },
formatClickhouseDate: (date: Date | string) =>
new Date(date)
.toISOString()
@@ -62,7 +61,9 @@ mock.module('@openpanel/db/src/clickhouse/client', () => ({
const importUpdate = mock(
async (_opts: { where: { id: string }; data: unknown }) => undefined
);
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
db: { import: { update: importUpdate } },
}));
diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.ts
index 99bc77878..198b09cd6 100644
--- a/packages/core/src/modules/insight/insight.service.test.ts
+++ b/packages/core/src/modules/insight/insight.service.test.ts
@@ -18,42 +18,18 @@ const $executeRaw = mock((..._args: unknown[]) => {
executeRawCalls.push(_args);
return Promise.resolve(executeRawReturns.shift() ?? 0);
});
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
db: { $executeRaw },
}));
-// `originalCh`/`chQuery`/`TABLE_NAMES`/`getReplicatedTableName`/
-// `formatClickhouseDate`/`convertClickhouseDateToJs` are unused here but
-// included because `mock.module` replaces this specifier process-wide (bun
-// runs every test file in one shared module registry without `--isolate` —
-// see AGENTS.md) — gsc.service.test.ts, cohort.service.test.ts and
-// import.service.test.ts mock the same path, so every factory must be a
-// superset of every consumer's needs, whichever one ends up registered last.
-mock.module('@openpanel/db/src/clickhouse/client', () => ({
- ch: {
- insert: mock(async () => undefined),
- command: mock(async () => undefined),
- },
- originalCh: {
- query: mock(async () => ({ json: async () => [] })),
- insert: mock(async () => undefined),
- },
- chQuery: mock(async () => []),
- getReplicatedTableName: mock((table: string) => table),
- TABLE_NAMES: {
- events: 'events',
- events_imports: 'events_imports',
- profiles: 'profiles',
- sessions: 'sessions',
- },
- formatClickhouseDate: (date: Date | string) =>
- new Date(date)
- .toISOString()
- .replace('T', ' ')
- .replace(/(\.\d{3})?Z+$/, ''),
- convertClickhouseDateToJs: (date: string) =>
- new Date(`${date.replace(' ', 'T')}Z`),
-}));
+// insight.service.ts never touches ClickHouse directly (it's PG-only, via
+// $executeRaw above), so unlike gsc/cohort/import there is nothing here to
+// mock — and no reason to register a factory for this specifier at all: a
+// hand-rolled one, even a well-intentioned superset, is a standing risk of
+// becoming the partial factory those files warn about the moment someone
+// edits it without re-checking every other consumer.
const spikesQuery = mock(async () => [
{ anchorDate: '2026-09-01', spikes: [] },
@@ -89,11 +65,16 @@ const getRedisCache = mock(() => ({
return Promise.resolve();
}),
}));
-// `cacheable` is unused here but included for the same cross-file
-// mock.module reason as the clickhouse/client mock above.
+// Spread the real module rather than hand-listing every export: `mock.module`
+// replaces this specifier process-wide (bun runs every test file in one
+// shared module registry without `--isolate` — see AGENTS.md), so a partial
+// factory here (this barrel also carries `getCache`, the pub/sub publisher
+// and the run-every helpers) would silently break any other consumer sharing
+// this process — e.g. the mcp module's auth.ts, which calls `getCache`.
+const actualRedis = await import('@openpanel/redis');
mock.module('@openpanel/redis', () => ({
+ ...actualRedis,
getRedisCache,
- cacheable: <T>(fn: T) => fn,
}));
let subject: typeof import('./insight.service');
diff --git a/packages/core/src/modules/mcp/mcp.routes.ts b/packages/core/src/modules/mcp/mcp.routes.ts
new file mode 100644
index 000000000..42889c122
--- /dev/null
+++ b/packages/core/src/modules/mcp/mcp.routes.ts
@@ -0,0 +1,39 @@
+// MCP's stateless POST transport, mounted at `/mcp` (M5-007, ADR-015 entry
+// 2). NAMED GAP, same as gsc.routes.ts / import.routes.ts / assistant.routes.ts:
+// not yet reachable — main.ts does not mount `dashboardRoutes` until a real
+// `AppDeps` exists (P3/P4/P8).
+//
+// `mcp.service` is loaded dynamically for the same reason assistant.routes.ts
+// gives for `assistant.service`: a static top-level import here reaches
+// `@openpanel/db`, which races `@openpanel/db`'s own circular
+// `buffers/base-buffer.ts` -> `@openpanel/core` import.
+//
+// Rate limiting (V1: 60/min via Fastify's activateRateLimiter) is not wired
+// here yet — nothing reaches this route until dashboardRoutes mounts, so it
+// is a port task for whenever that happens, not a gap specific to MCP.
+
+import { defineRoutes } from '../../http/define';
+
+function loadMcpService() {
+ return import('./mcp.service');
+}
+
+export const mcpRoutes = defineRoutes((app) =>
+ app.post('/mcp', async ({ request, set }) => {
+ const { extractToken, handleStatelessMcpRequest } = await loadMcpService();
+
+ const url = new URL(request.url);
+ const token = extractToken(
+ Object.fromEntries(url.searchParams),
+ request.headers.get('authorization') ?? undefined
+ );
+ const body = await request.json();
+
+ const { status, body: responseBody } = await handleStatelessMcpRequest(
+ token,
+ body
+ );
+ set.status = status;
+ return responseBody;
+ })
+);
diff --git a/packages/core/src/modules/mcp/mcp.service.test.ts b/packages/core/src/modules/mcp/mcp.service.test.ts
new file mode 100644
index 000000000..c2009c952
--- /dev/null
+++ b/packages/core/src/modules/mcp/mcp.service.test.ts
@@ -0,0 +1,281 @@
+/**
+ * `auth.test.ts` covers `authenticateToken`/`extractToken` in isolation, and
+ * `src/integration/tools.test.ts` covers tool business logic against real
+ * ClickHouse — neither exercises this file's own logic: turning one HTTP POST
+ * into a real MCP JSON-RPC exchange (auth → ephemeral server → synthetic
+ * initialize handshake → dispatch → response), with no session surviving
+ * between requests. This file is that missing layer: auth is mocked (already
+ * proven elsewhere), everything from `createMcpServer` down — the real SDK
+ * server, `InMemoryTransport`, the wire-format handshake, tool registration
+ * and dispatch — runs for real.
+ *
+ * Mocked at the specifiers the source imports resolve to, not the
+ * '@openpanel/db' / '@openpanel/redis' barrels — a whole-barrel replacement
+ * would drop every other export those barrels carry for any other file
+ * sharing this process (bun:test only isolates modules per file under
+ * `--isolate`; `cd packages/core && bun test` in CI runs without it — see
+ * AGENTS.md). Every mocked specifier is restored in `afterAll` from a
+ * plain-object snapshot taken before the first `mock.module` call — restoring
+ * via the live `await import(...)` binding itself is a no-op once mocked,
+ * since namespace bindings track the current mock.
+ */
+
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
+
+// Real pino (not mocked) instantiates a pino-pretty transport worker thread
+// whenever NODE_ENV isn't 'production' — `createLogger`'s own condition, see
+// clients/logger.ts. That transport intermittently fails to spawn under Bun
+// ("unable to determine transport target for pino-pretty"), and this file
+// exercises `createMcpServer` for real, so every tool module's own
+// `createLogger` call would add to that risk. Noop it out, same as
+// `src/auth.test.ts` already does for the same reason.
+const noopLogger = {
+ fatal: () => {
+ // no-op
+ },
+ error: () => {
+ // no-op
+ },
+ warn: () => {
+ // no-op
+ },
+ info: () => {
+ // no-op
+ },
+ debug: () => {
+ // no-op
+ },
+ trace: () => {
+ // no-op
+ },
+ child: () => noopLogger,
+};
+const actualLogger = await import('../../clients/logger');
+const realLogger = { ...actualLogger };
+mock.module('../../clients/logger', () => ({
+ ...realLogger,
+ createLogger: () => noopLogger,
+}));
+
+const mockGetClientByIdCached = mock();
+const actualClientsService = await import(
+ '@openpanel/db/src/services/clients.service'
+);
+const realClientsService = { ...actualClientsService };
+mock.module('@openpanel/db/src/services/clients.service', () => ({
+ ...realClientsService,
+ getClientByIdCached: mockGetClientByIdCached,
+}));
+
+const actualRedis = await import('@openpanel/redis');
+const realRedis = { ...actualRedis };
+mock.module('@openpanel/redis', () => ({
+ ...realRedis,
+ getCache: async <T>(_key: string, _ttl: number, fn: () => Promise<T>) => fn(),
+}));
+
+const mockVerifyPassword = mock(async () => true);
+const actualCrypto = await import('../../shared/crypto');
+const realCrypto = { ...actualCrypto };
+mock.module('../../shared/crypto', () => ({
+ ...realCrypto,
+ verifyPassword: mockVerifyPassword,
+}));
+
+// Only `list_projects` (the tool this file dispatches through a real
+// `tools/call`) touches Postgres — `db.project.findUnique` is the one method
+// it needs.
+const mockFindUnique = mock();
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
+const realPrismaClient = { ...actualPrismaClient };
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...realPrismaClient,
+ db: { project: { findUnique: mockFindUnique } },
+}));
+
+afterAll(() => {
+ mock.module('../../clients/logger', () => realLogger);
+ mock.module(
+ '@openpanel/db/src/services/clients.service',
+ () => realClientsService
+ );
+ mock.module('@openpanel/redis', () => realRedis);
+ mock.module('../../shared/crypto', () => realCrypto);
+ mock.module('@openpanel/db/src/prisma-client', () => realPrismaClient);
+});
+
+let handleStatelessMcpRequest: typeof import('./mcp.service').handleStatelessMcpRequest;
+
+beforeAll(async () => {
+ ({ handleStatelessMcpRequest } = await import('./mcp.service'));
+});
+
+const CLIENT_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
+const CLIENT_SECRET = 'mysecret';
+const VALID_TOKEN = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString(
+ 'base64'
+);
+
+const READ_CLIENT = {
+ id: CLIENT_ID,
+ type: 'read',
+ secret: 'hashed-secret',
+ projectId: 'proj-1',
+ organizationId: 'org-1',
+};
+
+beforeEach(() => {
+ mockGetClientByIdCached.mockReset();
+ mockGetClientByIdCached.mockResolvedValue(READ_CLIENT);
+ mockVerifyPassword.mockReset();
+ mockVerifyPassword.mockResolvedValue(true);
+ mockFindUnique.mockReset();
+});
+
+describe('handleStatelessMcpRequest — auth', () => {
+ it('401s a request with no token, without ever reaching the MCP server', async () => {
+ const res = await handleStatelessMcpRequest(undefined, {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/list',
+ });
+
+ expect(res).toEqual({
+ status: 401,
+ body: { error: 'Missing authentication token' },
+ });
+ expect(mockGetClientByIdCached).not.toHaveBeenCalled();
+ });
+
+ it('401s a request with a wrong secret', async () => {
+ mockVerifyPassword.mockResolvedValue(false);
+
+ const res = await handleStatelessMcpRequest(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/list',
+ });
+
+ expect(res.status).toBe(401);
+ });
+});
+
+describe('handleStatelessMcpRequest — protocol', () => {
+ it('202s a notification and never runs it through the MCP server', async () => {
+ const res = await handleStatelessMcpRequest(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ method: 'notifications/initialized',
+ });
+
+ // Authenticated (mock hit) but no `id` — dispatch never happens.
+ expect(res).toEqual({ status: 202, body: null });
+ expect(mockGetClientByIdCached).toHaveBeenCalledTimes(1);
+ });
+
+ it('completes a real initialize handshake sent as the request itself', async () => {
+ const res = await handleStatelessMcpRequest(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '0' },
+ },
+ });
+
+ expect(res.status).toBe(200);
+ const body = res.body as {
+ jsonrpc: string;
+ id: number;
+ result: { serverInfo: { name: string; version: string } };
+ };
+ expect(body.jsonrpc).toBe('2.0');
+ expect(body.id).toBe(1);
+ expect(body.result.serverInfo).toEqual({
+ name: 'OpenPanel',
+ version: '1.0.0',
+ });
+ });
+
+ it('dispatches tools/list via the synthetic handshake when no prior initialize was sent', async () => {
+ const res = await handleStatelessMcpRequest(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/list',
+ });
+
+ expect(res.status).toBe(200);
+ const body = res.body as { result: { tools: { name: string }[] } };
+ const names = body.result.tools.map((tool) => tool.name);
+ expect(names).toContain('list_projects');
+ // Every analytics/gsc/dashboard tool module registered — a stand-in for
+ // "the whole real tool tree wired up", not tied to an exact count.
+ expect(names.length).toBeGreaterThan(20);
+ });
+
+ it('dispatches a real tools/call end-to-end — JSON-RPC in, real tool handler out', async () => {
+ mockFindUnique.mockResolvedValue({
+ id: 'proj-1',
+ name: 'My Project',
+ organizationId: 'org-1',
+ eventsCount: 42,
+ domain: null,
+ types: [],
+ });
+
+ const res = await handleStatelessMcpRequest(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 3,
+ method: 'tools/call',
+ params: { name: 'list_projects', arguments: {} },
+ });
+
+ expect(res.status).toBe(200);
+ const body = res.body as {
+ result: { content: [{ type: 'text'; text: string }] };
+ };
+ expect(JSON.parse(body.result.content[0]!.text)).toEqual({
+ clientType: 'read',
+ projects: [
+ {
+ id: 'proj-1',
+ name: 'My Project',
+ organizationId: 'org-1',
+ eventsCount: 42,
+ domain: null,
+ types: [],
+ },
+ ],
+ });
+ expect(mockFindUnique).toHaveBeenCalledWith({
+ where: { id: 'proj-1' },
+ select: expect.any(Object),
+ });
+ });
+
+ it('re-authenticates from scratch on every call — no session survives between requests', async () => {
+ const first = await handleStatelessMcpRequest(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 4,
+ method: 'tools/list',
+ });
+ const second = await handleStatelessMcpRequest(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 5,
+ method: 'tools/list',
+ });
+
+ expect(first.status).toBe(200);
+ expect(second.status).toBe(200);
+ expect(mockGetClientByIdCached).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.ts
new file mode 100644
index 000000000..51f074bc1
--- /dev/null
+++ b/packages/core/src/modules/mcp/mcp.service.ts
@@ -0,0 +1,171 @@
+// Stateless-POST MCP transport (ADR-015 entry 2, M5-007). V1 kept a Redis
+// session store (`mcp:session:<uuid>`, 30-min TTL) and a `Mcp-Session-Id`
+// header that could stand in for the token on every request after the
+// first — both removed here, along with GET/SSE (already an unconditional
+// 405 — deletes nothing that ever worked) and DELETE. Every POST
+// authenticates from scratch and gets its own ephemeral McpServer; nothing
+// survives between requests, so there is no session to store, touch or
+// close, and no cross-instance stickiness requirement.
+//
+// MCP is the one module the wave map allows to change its endpoint surface —
+// every other module in this wave preserves its V1 contract byte-for-byte.
+
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
+import { createLogger } from '../../clients/logger';
+import {
+ authenticateToken,
+ type McpAuthContext,
+ McpAuthError,
+} from './src/auth';
+import { createMcpServer } from './src/server';
+
+export type { McpAuthContext } from './src/auth';
+export { extractToken, McpAuthError } from './src/auth';
+
+const logger = createLogger({ name: 'mcp' });
+
+const MCP_PROTOCOL_VERSION = '2024-11-05';
+const MCP_PROXY_CLIENT_INFO = { name: 'mcp-proxy', version: '0' };
+
+export interface McpHttpResult {
+ status: number;
+ body: unknown;
+}
+
+/**
+ * Handle one stateless MCP POST request end-to-end.
+ *
+ * Auth failures resolve to a 401 result rather than throwing, so the caller
+ * (an HTTP framework's route handler) needs only one catch block for
+ * everything else — matching the DELEGATE PATTERN's V1 controllers, which
+ * keep framework-specific concerns (rate limiting, generic 500s) and hand
+ * the protocol to this function.
+ */
+export async function handleStatelessMcpRequest(
+ token: string | undefined,
+ body: unknown
+): Promise<McpHttpResult> {
+ let context: McpAuthContext;
+ try {
+ context = await authenticateToken(token);
+ } catch (err) {
+ if (err instanceof McpAuthError) {
+ logger.warn({ reason: err.message }, 'MCP auth failed');
+ return { status: 401, body: { error: err.message } };
+ }
+ throw err;
+ }
+
+ const message = body as JSONRPCMessage;
+
+ // Notifications carry no `id` and expect no response.
+ if (!('id' in message)) {
+ return { status: 202, body: null };
+ }
+
+ logToolCall(message, context);
+ const isInitializeRequest =
+ 'method' in message && message.method === 'initialize';
+ const start = Date.now();
+ const response = await runOnEphemeralServer(
+ context,
+ message,
+ isInitializeRequest
+ );
+ logToolResult(message, response, start);
+
+ return { status: 200, body: response };
+}
+
+/**
+ * Every request gets a fresh McpServer over an in-memory transport pair —
+ * the ephemeral-server design already used to be per-session in V1; here it
+ * is simply per-request, with nothing else changing. A real `initialize`
+ * request completes the handshake directly; anything else fast-forwards a
+ * synthetic handshake first, since a brand-new server has no other way to
+ * reach its ready state.
+ */
+async function runOnEphemeralServer(
+ context: McpAuthContext,
+ message: JSONRPCMessage,
+ isInitializeRequest: boolean
+): Promise<JSONRPCMessage> {
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ const server = createMcpServer(context);
+ await server.connect(serverTransport);
+
+ if (!isInitializeRequest) {
+ await new Promise<void>((resolve, reject) => {
+ clientTransport.onmessage = () => resolve();
+ clientTransport
+ .send({
+ jsonrpc: '2.0',
+ id: '__mcp_init__',
+ method: 'initialize',
+ params: {
+ protocolVersion: MCP_PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: MCP_PROXY_CLIENT_INFO,
+ },
+ })
+ .catch(reject);
+ });
+ // No response expected for this notification.
+ await clientTransport.send({
+ jsonrpc: '2.0',
+ method: 'notifications/initialized',
+ });
+ }
+
+ return await new Promise<JSONRPCMessage>((resolve, reject) => {
+ clientTransport.onmessage = resolve;
+ clientTransport.send(message).catch(reject);
+ });
+}
+
+function logToolCall(message: JSONRPCMessage, context: McpAuthContext) {
+ if (
+ !(
+ 'method' in message &&
+ message.method === 'tools/call' &&
+ 'params' in message
+ )
+ ) {
+ return;
+ }
+ const { name, arguments: args } = (message.params ?? {}) as {
+ name?: string;
+ arguments?: unknown;
+ };
+ logger.info(
+ {
+ tool: name,
+ params: args,
+ organizationId: context.organizationId,
+ projectId: context.projectId,
+ clientType: context.clientType,
+ },
+ 'MCP tool call'
+ );
+}
+
+function logToolResult(
+ message: JSONRPCMessage,
+ response: JSONRPCMessage,
+ start: number
+) {
+ if (!('method' in message && message.method === 'tools/call')) {
+ return;
+ }
+ const { name } = (('params' in message && message.params) ?? {}) as {
+ name?: string;
+ };
+ const isError =
+ 'result' in response && (response.result as { isError?: boolean })?.isError;
+ logger.info(
+ { tool: name, durationMs: Date.now() - start, isError: isError ?? false },
+ 'MCP tool result'
+ );
+}
diff --git a/packages/mcp/src/auth.test.ts b/packages/core/src/modules/mcp/src/auth.test.ts
similarity index 73%
rename from packages/mcp/src/auth.test.ts
rename to packages/core/src/modules/mcp/src/auth.test.ts
index 76b7b620d..3ce8c0d83 100644
--- a/packages/mcp/src/auth.test.ts
+++ b/packages/core/src/modules/mcp/src/auth.test.ts
@@ -1,36 +1,84 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const mockGetClientByIdCached = vi.hoisted(() => vi.fn());
-const mockVerifyPassword = vi.hoisted(() => vi.fn());
-const mockGetCache = vi.hoisted(() => vi.fn());
-const noopLogger = vi.hoisted(() => {
- const logger = {
- fatal: () => {},
- error: () => {},
- warn: () => {},
- info: () => {},
- debug: () => {},
- trace: () => {},
- child: () => logger,
- };
- return logger;
-});
+import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+
+const mockGetClientByIdCached = mock();
+const mockVerifyPassword = mock();
+const mockGetCache = mock();
+const noopLogger = {
+ fatal: () => {
+ // no-op
+ },
+ error: () => {
+ // no-op
+ },
+ warn: () => {
+ // no-op
+ },
+ info: () => {
+ // no-op
+ },
+ debug: () => {
+ // no-op
+ },
+ trace: () => {
+ // no-op
+ },
+ child: () => noopLogger,
+};
-vi.mock('@openpanel/db', () => ({
- ClientType: { write: 'write', read: 'read', root: 'root' },
+// Mocked at the specifier the source imports resolve to, not at the
+// '@openpanel/db' / '@openpanel/redis' barrels — a whole-barrel replacement
+// would drop every other export those barrels carry for any other file
+// sharing this process (bun:test only isolates modules per file under
+// `--isolate`; see AGENTS.md).
+const actualClientsService = await import(
+ '@openpanel/db/src/services/clients.service'
+);
+mock.module('@openpanel/db/src/services/clients.service', () => ({
+ ...actualClientsService,
getClientByIdCached: mockGetClientByIdCached,
}));
-vi.mock('@openpanel/core', () => ({
- verifyPassword: mockVerifyPassword,
+const actualRedis = await import('@openpanel/redis');
+mock.module('@openpanel/redis', () => ({
+ ...actualRedis,
+ getCache: mockGetCache,
+}));
+
+// @openpanel/db's barrel eagerly imports @openpanel/core's (buffers/
+// base-buffer.ts, see packages/core/src/index.ts's comment on the mcp
+// loader) — so a partial replacement here breaks that self-referential
+// import for anything auth.ts's own `@openpanel/db` import drags in, not
+// just this file's direct callers.
+const actualLogger = await import('../../../clients/logger');
+mock.module('../../../clients/logger', () => ({
+ ...actualLogger,
createLogger: () => noopLogger,
}));
-vi.mock('@openpanel/redis', () => ({
- getCache: mockGetCache,
+const actualCrypto = await import('../../../shared/crypto');
+mock.module('../../../shared/crypto', () => ({
+ ...actualCrypto,
+ verifyPassword: mockVerifyPassword,
}));
-import { authenticateToken, extractToken, McpAuthError } from './auth';
+let authenticateToken: typeof import('./auth').authenticateToken;
+let extractToken: typeof import('./auth').extractToken;
+let McpAuthError: typeof import('./auth').McpAuthError;
+
+beforeAll(async () => {
+ ({ authenticateToken, extractToken, McpAuthError } = await import('./auth'));
+});
+
+beforeEach(() => {
+ mockGetClientByIdCached.mockReset();
+ mockVerifyPassword.mockReset();
+ mockGetCache.mockReset();
+ // Default: cache calls through to the fn
+ mockGetCache.mockImplementation(
+ (_key: string, _ttl: number, fn: () => Promise<unknown>) => fn()
+ );
+ mockVerifyPassword.mockResolvedValue(true);
+});
const VALID_CLIENT_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
const VALID_SECRET = 'mysecret';
@@ -46,15 +94,6 @@ const baseClient = {
organizationId: 'org-456',
};
-beforeEach(() => {
- vi.clearAllMocks();
- // Default: cache calls through to the fn
- mockGetCache.mockImplementation(
- (_key: string, _ttl: number, fn: () => Promise<unknown>) => fn()
- );
- mockVerifyPassword.mockResolvedValue(true);
-});
-
// ---------------------------------------------------------------------------
// extractToken
// ---------------------------------------------------------------------------
diff --git a/packages/mcp/src/auth.ts b/packages/core/src/modules/mcp/src/auth.ts
similarity index 97%
rename from packages/mcp/src/auth.ts
rename to packages/core/src/modules/mcp/src/auth.ts
index 7f9c66a31..7e488d7a5 100644
--- a/packages/mcp/src/auth.ts
+++ b/packages/core/src/modules/mcp/src/auth.ts
@@ -1,7 +1,8 @@
import { createHash } from 'node:crypto';
-import { createLogger, verifyPassword } from '@openpanel/core';
import { ClientType, getClientByIdCached } from '@openpanel/db';
import { getCache } from '@openpanel/redis';
+import { createLogger } from '../../../clients/logger';
+import { verifyPassword } from '../../../shared/crypto';
const logger = createLogger({ name: 'mcp:auth' });
diff --git a/packages/mcp/src/integration/tools.test.ts b/packages/core/src/modules/mcp/src/integration/tools.test.ts
similarity index 82%
rename from packages/mcp/src/integration/tools.test.ts
rename to packages/core/src/modules/mcp/src/integration/tools.test.ts
index 01441c720..6c171786f 100644
--- a/packages/mcp/src/integration/tools.test.ts
+++ b/packages/core/src/modules/mcp/src/integration/tools.test.ts
@@ -1,49 +1,103 @@
/**
* Integration tests for MCP tools against a real ClickHouse instance.
*
- * CLICKHOUSE_URL is pinned to http://localhost:8123 in vitest.shared.ts —
- * always targets local Docker, never production. Start with: pnpm dock:up
+ * `bunfig.toml`'s preload pins CLICKHOUSE_URL/DATABASE_URL to the isolated
+ * `openpanel_test` databases (never production, never V1's own dev DB) —
+ * bun:test has no vitest-style globalSetup, so this suite bootstraps and
+ * seeds its own fixture (test/fixtures.ts, the same helper V1's
+ * apps/api/src/routes/insights.router.test.ts uses) in beforeAll/afterAll,
+ * under its own project/org id so it can run concurrently with that suite.
*
- * Fixture data (inserted by globalSetup in setup.ts):
+ * Fixture data (test/fixtures.ts's FIXTURE):
* Alice — 3 events: session_start, page_view(/home), session_end — 2 days ago — country: US, browser: Chrome
* Bob — 0 events (inactive) — profile created 90 days ago — country: SE
* Charlie — 5 events: session_start, screen_view, page_view(/shop), purchase, session_end — 5 days ago — browser: Firefox
* 2 sessions (sess-charlie-1 5d ago, sess-charlie-2 10d ago)
*
- * For tools that also call getSettingsForProject (Postgres), we mock only
- * that function — all ClickHouse queries still run for real.
+ * get_page_performance also calls getSettingsForProject (Postgres) — real,
+ * not mocked, which is why setupPostgresFixtures runs alongside the
+ * ClickHouse fixture.
*/
-import { describe, expect, it, vi } from 'vitest';
-
-// Bypass Redis caching — prevents ioredis TCP connections that hang the process
-vi.mock('@openpanel/redis', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@openpanel/redis')>();
- return {
- ...actual,
- getCache: async <T>(_key: string, _ttl: number, fn: () => Promise<T>) =>
- fn(),
- };
+import { afterAll, beforeAll, describe, expect, it, mock } from 'bun:test';
+
+const TEST_PROJECT_ID = 'mcp-integration-test';
+const TEST_ORG_ID = 'mcp-integration-org';
+
+// Bypass Redis caching — prevents a real Redis round trip from gating every
+// assertion. Captured before mock.module runs: unlike vitest's importOriginal,
+// a factory here has no hook back to the real module once mocked.
+const actualRedis = await import('@openpanel/redis');
+mock.module('@openpanel/redis', () => ({
+ ...actualRedis,
+ getCache: async <T>(_key: string, _ttl: number, fn: () => Promise<T>) => fn(),
+}));
+
+let FIXTURE: typeof import('../../../../../../../test/fixtures').FIXTURE;
+let registerActiveUserTools: typeof import('../tools/analytics/active-users').registerActiveUserTools;
+let registerEngagementTools: typeof import('../tools/analytics/engagement').registerEngagementTools;
+let registerEventNameTools: typeof import('../tools/analytics/event-names').registerEventNameTools;
+let registerEventTools: typeof import('../tools/analytics/events').registerEventTools;
+let registerFunnelTools: typeof import('../tools/analytics/funnel').registerFunnelTools;
+let registerGroupTools: typeof import('../tools/analytics/groups').registerGroupTools;
+let registerOverviewTools: typeof import('../tools/analytics/overview').registerOverviewTools;
+let registerPagePerformanceTools: typeof import('../tools/analytics/page-performance').registerPagePerformanceTools;
+let registerPageTools: typeof import('../tools/analytics/pages').registerPageTools;
+let registerProfileMetricTools: typeof import('../tools/analytics/profile-metrics').registerProfileMetricTools;
+let registerProfileTools: typeof import('../tools/analytics/profiles').registerProfileTools;
+let registerPropertyValueTools: typeof import('../tools/analytics/property-values').registerPropertyValueTools;
+let registerRetentionTools: typeof import('../tools/analytics/retention').registerRetentionTools;
+let registerSessionTools: typeof import('../tools/analytics/sessions').registerSessionTools;
+let registerTrafficTools: typeof import('../tools/analytics/traffic').registerTrafficTools;
+let registerUserFlowTools: typeof import('../tools/analytics/user-flow').registerUserFlowTools;
+
+beforeAll(async () => {
+ // Sequential, not Promise.all — concurrent dynamic imports of sibling
+ // modules that all reach into `@openpanel/db`'s barrel raced its class
+ // declarations (a `PagesService` TDZ ReferenceError), so each subject
+ // finishes evaluating before the next one starts.
+ const fixtures = await import('../../../../../../../test/fixtures');
+ ({ registerActiveUserTools } = await import(
+ '../tools/analytics/active-users'
+ ));
+ ({ registerEngagementTools } = await import('../tools/analytics/engagement'));
+ ({ registerEventNameTools } = await import('../tools/analytics/event-names'));
+ ({ registerEventTools } = await import('../tools/analytics/events'));
+ ({ registerFunnelTools } = await import('../tools/analytics/funnel'));
+ ({ registerGroupTools } = await import('../tools/analytics/groups'));
+ ({ registerOverviewTools } = await import('../tools/analytics/overview'));
+ ({ registerPagePerformanceTools } = await import(
+ '../tools/analytics/page-performance'
+ ));
+ ({ registerPageTools } = await import('../tools/analytics/pages'));
+ ({ registerProfileMetricTools } = await import(
+ '../tools/analytics/profile-metrics'
+ ));
+ ({ registerProfileTools } = await import('../tools/analytics/profiles'));
+ ({ registerPropertyValueTools } = await import(
+ '../tools/analytics/property-values'
+ ));
+ ({ registerRetentionTools } = await import('../tools/analytics/retention'));
+ ({ registerSessionTools } = await import('../tools/analytics/sessions'));
+ ({ registerTrafficTools } = await import('../tools/analytics/traffic'));
+ ({ registerUserFlowTools } = await import('../tools/analytics/user-flow'));
+
+ FIXTURE = fixtures.FIXTURE;
+
+ const { bootstrapTestDatabases } = await import(
+ '../../../../../../../test/bootstrap-databases'
+ );
+ await bootstrapTestDatabases();
+ await fixtures.setupPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);
+ await fixtures.setupFixtures(TEST_PROJECT_ID);
+}, 30_000);
+
+afterAll(async () => {
+ const fixtures = await import('../../../../../../../test/fixtures');
+ await fixtures.teardownFixtures(TEST_PROJECT_ID);
+ await fixtures.teardownPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);
});
-import { FIXTURE, TEST_PROJECT_ID } from '../../../../test/global-setup';
-import { registerActiveUserTools } from '../tools/analytics/active-users';
-import { registerEngagementTools } from '../tools/analytics/engagement';
-import { registerEventNameTools } from '../tools/analytics/event-names';
-import { registerEventTools } from '../tools/analytics/events';
-import { registerFunnelTools } from '../tools/analytics/funnel';
-import { registerGroupTools } from '../tools/analytics/groups';
-import { registerOverviewTools } from '../tools/analytics/overview';
-import { registerPagePerformanceTools } from '../tools/analytics/page-performance';
-import { registerPageTools } from '../tools/analytics/pages';
-import { registerProfileMetricTools } from '../tools/analytics/profile-metrics';
-import { registerProfileTools } from '../tools/analytics/profiles';
-import { registerPropertyValueTools } from '../tools/analytics/property-values';
-import { registerRetentionTools } from '../tools/analytics/retention';
-import { registerSessionTools } from '../tools/analytics/sessions';
-import { registerTrafficTools } from '../tools/analytics/traffic';
-import { registerUserFlowTools } from '../tools/analytics/user-flow';
-
const CTX = {
projectId: TEST_PROJECT_ID,
organizationId: 'org-test',
@@ -82,10 +136,7 @@ function makeServer() {
* Tools return `{ columns, rows }` so column names are stated once instead of
* on every row; assertions read better against objects, so we invert it here.
*/
-function rowsOf(result: {
- columns: string[];
- rows: unknown[][];
-}): any[] {
+function rowsOf(result: { columns: string[]; rows: unknown[][] }): any[] {
return result.rows.map((row) =>
Object.fromEntries(result.columns.map((column, i) => [column, row[i]]))
);
@@ -173,9 +224,9 @@ describe('query_events', () => {
});
const events = rowsOf(res);
expect(events.length).toBe(3);
- expect(
- events.every((e) => e.profile_id === FIXTURE.profiles.alice)
- ).toBe(true);
+ expect(events.every((e) => e.profile_id === FIXTURE.profiles.alice)).toBe(
+ true
+ );
});
it('filters by browser', async () => {
diff --git a/packages/mcp/src/server.ts b/packages/core/src/modules/mcp/src/server.ts
similarity index 99%
rename from packages/mcp/src/server.ts
rename to packages/core/src/modules/mcp/src/server.ts
index c1ccae70a..ac7977b92 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/core/src/modules/mcp/src/server.ts
@@ -21,7 +21,7 @@ export function createMcpServer(context: McpAuthContext): McpServer {
capabilities: {
tools: {},
},
- },
+ }
);
registerAllTools(server, context);
diff --git a/packages/mcp/src/tools/analytics/active-users.ts b/packages/core/src/modules/mcp/src/tools/analytics/active-users.ts
similarity index 91%
rename from packages/mcp/src/tools/analytics/active-users.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/active-users.ts
index 4400a3939..ed72d578f 100644
--- a/packages/mcp/src/tools/analytics/active-users.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/active-users.ts
@@ -1,5 +1,5 @@
-import { getRollingActiveUsers, getRetentionSeries } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getRetentionSeries, getRollingActiveUsers } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -27,7 +27,7 @@ function mostRecent<T>(rows: T[], take: number): T[] {
export function registerActiveUserTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_rolling_active_users',
@@ -50,7 +50,14 @@ export function registerActiveUserTools(
const recent = mostRecent(data, take);
return {
window_days: days,
- label: days === 1 ? 'DAU' : days === 7 ? 'WAU' : days === 30 ? 'MAU' : `${days}d active`,
+ label:
+ days === 1
+ ? 'DAU'
+ : days === 7
+ ? 'WAU'
+ : days === 30
+ ? 'MAU'
+ : `${days}d active`,
...(data.length > recent.length
? {
series_note: `Showing the most recent ${recent.length} of ${data.length} days. Raise \`limit\` for more history.`,
@@ -63,7 +70,7 @@ export function registerActiveUserTools(
unit: 'days',
}),
};
- }),
+ })
);
server.tool(
@@ -92,6 +99,6 @@ export function registerActiveUserTools(
unit: 'weeks',
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/columns.ts b/packages/core/src/modules/mcp/src/tools/analytics/columns.ts
similarity index 100%
rename from packages/mcp/src/tools/analytics/columns.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/columns.ts
diff --git a/packages/mcp/src/tools/analytics/engagement.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts
similarity index 57%
rename from packages/mcp/src/tools/analytics/engagement.test.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts
index a5173fdd5..ea3628f06 100644
--- a/packages/mcp/src/tools/analytics/engagement.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts
@@ -1,34 +1,66 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const mockGetRetentionLastSeenSeries = vi.hoisted(() => vi.fn());
-
-vi.mock('@openpanel/db', () => ({
+import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+
+const mockGetRetentionLastSeenSeries = mock();
+
+// Mocked at the specifier the source imports resolve to, not the
+// '@openpanel/db' barrel — a whole-barrel replacement would drop every other
+// export the barrel carries for any other file sharing this process
+// (bun:test only isolates modules per file under `--isolate`; see AGENTS.md).
+const actualRetentionService = await import(
+ '@openpanel/db/src/services/retention.service'
+);
+mock.module('@openpanel/db/src/services/retention.service', () => ({
+ ...actualRetentionService,
getRetentionLastSeenSeries: mockGetRetentionLastSeenSeries,
- resolveClientProjectId: vi.fn(({ clientProjectId }: { clientProjectId: string }) => Promise.resolve(clientProjectId)),
}));
-// Import after mock is set up
-import { registerEngagementTools } from './engagement';
+const actualProjectService = await import(
+ '@openpanel/db/src/services/project.service'
+);
+mock.module('@openpanel/db/src/services/project.service', () => ({
+ ...actualProjectService,
+ resolveClientProjectId: mock(
+ ({ clientProjectId }: { clientProjectId: string }) =>
+ Promise.resolve(clientProjectId)
+ ),
+}));
+
+let registerEngagementTools: typeof import('./engagement').registerEngagementTools;
+
+beforeAll(async () => {
+ ({ registerEngagementTools } = await import('./engagement'));
+});
// Helper: directly invoke the bucketing logic by importing it through a minimal mock server
// We test the bucketing by calling the tool handler directly via a test double McpServer.
function makeServer() {
let handler: ((input: unknown) => Promise<unknown>) | null = null;
return {
- tool: (_name: string, _desc: string, _schema: unknown, fn: (input: unknown) => Promise<unknown>) => {
+ tool: (
+ _name: string,
+ _desc: string,
+ _schema: unknown,
+ fn: (input: unknown) => Promise<unknown>
+ ) => {
handler = fn;
},
invoke: (input: unknown) => {
- if (!handler) throw new Error('tool not registered');
+ if (!handler) {
+ throw new Error('tool not registered');
+ }
return handler(input);
},
};
}
-const READ_CTX = { projectId: 'proj-1', organizationId: 'org-1', clientType: 'read' as const };
+const READ_CTX = {
+ projectId: 'proj-1',
+ organizationId: 'org-1',
+ clientType: 'read' as const,
+};
beforeEach(() => {
- vi.clearAllMocks();
+ mockGetRetentionLastSeenSeries.mockReset();
});
describe('get_user_last_seen_distribution — bucketing', () => {
@@ -36,21 +68,23 @@ describe('get_user_last_seen_distribution — bucketing', () => {
mockGetRetentionLastSeenSeries.mockResolvedValue([
{ days: 0, users: 10 },
{ days: 3, users: 20 },
- { days: 7, users: 5 }, // still in 0-7
- { days: 10, users: 8 }, // 8-14
- { days: 14, users: 2 }, // 8-14
+ { days: 7, users: 5 }, // still in 0-7
+ { days: 10, users: 8 }, // 8-14
+ { days: 14, users: 2 }, // 8-14
{ days: 20, users: 12 }, // 15-30
- { days: 45, users: 6 }, // 31-60
- { days: 90, users: 3 }, // 60+
+ { days: 45, users: 6 }, // 31-60
+ { days: 90, users: 3 }, // 60+
]);
const server = makeServer() as any;
registerEngagementTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ })) as any;
const content = JSON.parse(result.content[0].text);
- expect(content.summary.active_last_7_days).toBe(10 + 20 + 5); // 35
- expect(content.summary.active_8_to_14_days).toBe(8 + 2); // 10
+ expect(content.summary.active_last_7_days).toBe(10 + 20 + 5); // 35
+ expect(content.summary.active_8_to_14_days).toBe(8 + 2); // 10
expect(content.summary.active_15_to_30_days).toBe(12);
expect(content.summary.inactive_31_to_60_days).toBe(6);
expect(content.summary.churned_60_plus_days).toBe(3);
@@ -62,7 +96,9 @@ describe('get_user_last_seen_distribution — bucketing', () => {
const server = makeServer() as any;
registerEngagementTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ })) as any;
const content = JSON.parse(result.content[0].text);
expect(content.summary.total_identified_users).toBe(0);
@@ -75,7 +111,9 @@ describe('get_user_last_seen_distribution — bucketing', () => {
const server = makeServer() as any;
registerEngagementTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ })) as any;
const content = JSON.parse(result.content[0].text);
// One row per distinct "days ago" is unbounded; the buckets answer the
@@ -92,10 +130,10 @@ describe('get_user_last_seen_distribution — bucketing', () => {
const server = makeServer() as any;
registerEngagementTools(server, READ_CTX);
- const result = await server.invoke({
+ const result = (await server.invoke({
projectId: READ_CTX.projectId,
includeDistribution: true,
- }) as any;
+ })) as any;
const content = JSON.parse(result.content[0].text);
expect(content.distribution.columns).toEqual(['days', 'users']);
diff --git a/packages/mcp/src/tools/analytics/engagement.ts b/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts
similarity index 79%
rename from packages/mcp/src/tools/analytics/engagement.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/engagement.ts
index 5e9070c30..a6bafeb7f 100644
--- a/packages/mcp/src/tools/analytics/engagement.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts
@@ -1,5 +1,5 @@
-import { getRetentionLastSeenSeries } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getRetentionLastSeenSeries } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -14,7 +14,7 @@ const MAX_DISTRIBUTION_ROWS = 200;
export function registerEngagementTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_user_last_seen_distribution',
@@ -26,7 +26,7 @@ export function registerEngagementTools(
.default(false)
.optional()
.describe(
- 'Include the raw per-day histogram (one row per distinct "days since last seen"). Off by default — the bucketed summary answers the question in a fraction of the size.',
+ 'Include the raw per-day histogram (one row per distinct "days since last seen"). Off by default — the bucketed summary answers the question in a fraction of the size.'
),
},
async ({ projectId: inputProjectId, includeDistribution }) =>
@@ -42,14 +42,25 @@ export function registerEngagementTools(
let churned_60_plus = 0;
for (const row of raw) {
- if (row.days <= 7) active_0_7 += row.users;
- else if (row.days <= 14) active_8_14 += row.users;
- else if (row.days <= 30) active_15_30 += row.users;
- else if (row.days <= 60) active_31_60 += row.users;
- else churned_60_plus += row.users;
+ if (row.days <= 7) {
+ active_0_7 += row.users;
+ } else if (row.days <= 14) {
+ active_8_14 += row.users;
+ } else if (row.days <= 30) {
+ active_15_30 += row.users;
+ } else if (row.days <= 60) {
+ active_31_60 += row.users;
+ } else {
+ churned_60_plus += row.users;
+ }
}
- const total = active_0_7 + active_8_14 + active_15_30 + active_31_60 + churned_60_plus;
+ const total =
+ active_0_7 +
+ active_8_14 +
+ active_15_30 +
+ active_31_60 +
+ churned_60_plus;
return {
summary: {
@@ -72,6 +83,6 @@ export function registerEngagementTools(
}
: {}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/event-names.ts b/packages/core/src/modules/mcp/src/tools/analytics/event-names.ts
similarity index 93%
rename from packages/mcp/src/tools/analytics/event-names.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/event-names.ts
index 6b547d6d8..e5d4f2553 100644
--- a/packages/mcp/src/tools/analytics/event-names.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/event-names.ts
@@ -1,16 +1,15 @@
-import { getTopEventNames } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getTopEventNames } from '@openpanel/db';
import type { McpAuthContext } from '../../auth';
import {
projectIdSchema,
-
+ resolveProjectId,
withErrorHandling,
- resolveProjectId
} from '../shared';
export function registerEventNameTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'list_event_names',
@@ -23,6 +22,6 @@ export function registerEventNameTools(
const projectId = await resolveProjectId(context, inputProjectId);
const names = await getTopEventNames(projectId);
return { event_names: names };
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/events.ts b/packages/core/src/modules/mcp/src/tools/analytics/events.ts
similarity index 92%
rename from packages/mcp/src/tools/analytics/events.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/events.ts
index 8f248c69a..ee26d4954 100644
--- a/packages/mcp/src/tools/analytics/events.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/events.ts
@@ -1,11 +1,7 @@
-import { queryEventsCore } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { queryEventsCore } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
-import {
- EVENT_COLUMNS_DEFAULT,
- EVENT_COLUMNS_EXTRA,
-} from './columns';
import {
projectIdSchema,
resolveProjectId,
@@ -14,11 +10,11 @@ import {
zDateRange,
zLimit,
} from '../shared';
+import { EVENT_COLUMNS_DEFAULT, EVENT_COLUMNS_EXTRA } from './columns';
const DEFAULT_EVENT_LIMIT = 20;
const MAX_EVENT_LIMIT = 100;
-
export function registerEventTools(server: McpServer, context: McpAuthContext) {
server.tool(
'query_events',
@@ -30,7 +26,7 @@ export function registerEventTools(server: McpServer, context: McpAuthContext) {
.array(z.string())
.optional()
.describe(
- 'Filter by event names (e.g. ["screen_view", "session_start"])',
+ 'Filter by event names (e.g. ["screen_view", "session_start"])'
),
path: z.string().optional().describe('Filter by exact page path'),
country: z
@@ -46,7 +42,10 @@ export function registerEventTools(server: McpServer, context: McpAuthContext) {
.string()
.optional()
.describe('Filter by browser name (e.g. Chrome, Firefox)'),
- os: z.string().optional().describe('Filter by OS name (e.g. Windows, macOS)'),
+ os: z
+ .string()
+ .optional()
+ .describe('Filter by OS name (e.g. Windows, macOS)'),
referrer: z.string().optional().describe('Filter by referrer URL'),
referrerName: z
.string()
@@ -68,7 +67,7 @@ export function registerEventTools(server: McpServer, context: McpAuthContext) {
.array(z.enum(EVENT_COLUMNS_EXTRA))
.optional()
.describe(
- `Extra columns to include beyond the default set (${EVENT_COLUMNS_DEFAULT.join(', ')}). Only request what you need — every extra column costs rows of output.`,
+ `Extra columns to include beyond the default set (${EVENT_COLUMNS_DEFAULT.join(', ')}). Only request what you need — every extra column costs rows of output.`
),
limit: zLimit(DEFAULT_EVENT_LIMIT, MAX_EVENT_LIMIT),
},
@@ -88,6 +87,6 @@ export function registerEventTools(server: McpServer, context: McpAuthContext) {
unit: 'events',
moreAvailable: events.length > take,
});
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/funnel.ts b/packages/core/src/modules/mcp/src/tools/analytics/funnel.ts
similarity index 83%
rename from packages/mcp/src/tools/analytics/funnel.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/funnel.ts
index b8dedc2c1..d33c19b06 100644
--- a/packages/mcp/src/tools/analytics/funnel.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/funnel.ts
@@ -1,20 +1,18 @@
-import { getFunnelCore } from '@openpanel/db';
-
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getFunnelCore } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
projectIdSchema,
resolveDateRange,
-
+ resolveProjectId,
withErrorHandling,
zDateRange,
- resolveProjectId
} from '../shared';
export function registerFunnelTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_funnel',
@@ -27,7 +25,7 @@ export function registerFunnelTools(
.min(2)
.max(10)
.describe(
- 'Ordered list of event names forming the funnel steps (minimum 2, maximum 10)',
+ 'Ordered list of event names forming the funnel steps (minimum 2, maximum 10)'
),
windowHours: z
.number()
@@ -36,17 +34,24 @@ export function registerFunnelTools(
.default(24)
.optional()
.describe(
- 'Time window in hours within which all steps must occur (default: 24 hours)',
+ 'Time window in hours within which all steps must occur (default: 24 hours)'
),
groupBy: z
.enum(['session_id', 'profile_id'])
.default('session_id')
.optional()
.describe(
- '"session_id" counts within-session completions, "profile_id" counts cross-session completions (default: session_id)',
+ '"session_id" counts within-session completions, "profile_id" counts cross-session completions (default: session_id)'
),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, steps, windowHours, groupBy }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ steps,
+ windowHours,
+ groupBy,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
@@ -58,6 +63,6 @@ export function registerFunnelTools(
windowHours,
groupBy,
});
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/groups.ts b/packages/core/src/modules/mcp/src/tools/analytics/groups.ts
similarity index 81%
rename from packages/mcp/src/tools/analytics/groups.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/groups.ts
index edf47d8e0..ef6e8c0a4 100644
--- a/packages/mcp/src/tools/analytics/groups.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/groups.ts
@@ -1,5 +1,10 @@
-import { getGroupById, getGroupList, getGroupMemberProfiles, getGroupTypes } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import {
+ getGroupById,
+ getGroupList,
+ getGroupMemberProfiles,
+ getGroupTypes,
+} from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -15,13 +20,22 @@ const MAX_GROUP_LIMIT = 100;
const DEFAULT_MEMBER_LIMIT = 10;
const MAX_MEMBER_LIMIT = 50;
-const GROUP_COLUMNS = ['id', 'type', 'name', 'createdAt', 'properties'] as const;
-const MEMBER_COLUMNS = ['id', 'firstName', 'lastName', 'email', 'lastSeenAt'] as const;
+const GROUP_COLUMNS = [
+ 'id',
+ 'type',
+ 'name',
+ 'createdAt',
+ 'properties',
+] as const;
+const MEMBER_COLUMNS = [
+ 'id',
+ 'firstName',
+ 'lastName',
+ 'email',
+ 'lastSeenAt',
+] as const;
-export function registerGroupTools(
- server: McpServer,
- context: McpAuthContext,
-) {
+export function registerGroupTools(server: McpServer, context: McpAuthContext) {
server.tool(
'list_group_types',
'List all group types defined in this project (e.g. "company", "team", "account"). Groups represent B2B entities. Call this first to discover what group types exist before querying groups.',
@@ -33,7 +47,7 @@ export function registerGroupTools(
const projectId = await resolveProjectId(context, inputProjectId);
const types = await getGroupTypes(projectId);
return { types };
- }),
+ })
);
server.tool(
@@ -44,7 +58,9 @@ export function registerGroupTools(
type: z
.string()
.optional()
- .describe('Filter by group type (e.g. "company", "team"). Use list_group_types to discover available types.'),
+ .describe(
+ 'Filter by group type (e.g. "company", "team"). Use list_group_types to discover available types.'
+ ),
search: z
.string()
.optional()
@@ -55,14 +71,19 @@ export function registerGroupTools(
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const take = limit ?? DEFAULT_GROUP_LIMIT;
- const groups = await getGroupList({ projectId, type, search, take: take + 1 });
+ const groups = await getGroupList({
+ projectId,
+ type,
+ search,
+ take: take + 1,
+ });
return table(groups.slice(0, take), {
limit: take,
columns: GROUP_COLUMNS,
unit: 'groups',
moreAvailable: groups.length > take,
});
- }),
+ })
);
server.tool(
@@ -101,6 +122,6 @@ export function registerGroupTools(
moreAvailable: members.count > members.data.length,
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/overview.ts b/packages/core/src/modules/mcp/src/tools/analytics/overview.ts
similarity index 95%
rename from packages/mcp/src/tools/analytics/overview.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/overview.ts
index 8100c127a..7ea59f843 100644
--- a/packages/mcp/src/tools/analytics/overview.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/overview.ts
@@ -1,5 +1,5 @@
-import { getAnalyticsOverviewCore } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getAnalyticsOverviewCore } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -54,12 +54,12 @@ const SERIES_COLUMNS = [
function fitInterval(
requested: Interval,
startDate: string,
- endDate: string,
+ endDate: string
): { interval: Interval; note?: string } {
const days =
Math.max(
0,
- (new Date(endDate).getTime() - new Date(startDate).getTime()) / 86_400_000,
+ (new Date(endDate).getTime() - new Date(startDate).getTime()) / 86_400_000
) + 1;
const points = (i: Interval) => Math.ceil(days * POINTS_PER_DAY[i]);
@@ -86,7 +86,7 @@ function fitInterval(
export function registerOverviewTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_analytics_overview',
@@ -104,10 +104,16 @@ export function registerOverviewTools(
.default(true)
.optional()
.describe(
- 'Set false to get only the summary totals and skip the per-interval series. Do this when you just need the headline numbers.',
+ 'Set false to get only the summary totals and skip the per-interval series. Do this when you just need the headline numbers.'
),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, interval, includeSeries }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ interval,
+ includeSeries,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
@@ -141,6 +147,6 @@ export function registerOverviewTools(
unit: 'intervals',
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/page-conversions.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts
similarity index 77%
rename from packages/mcp/src/tools/analytics/page-conversions.test.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts
index bc00c6a60..581c03248 100644
--- a/packages/mcp/src/tools/analytics/page-conversions.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts
@@ -1,15 +1,35 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const mockGetPageConversionsCore = vi.hoisted(() => vi.fn());
-
-vi.mock('@openpanel/db', () => ({
+import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+
+const mockGetPageConversionsCore = mock();
+
+// Mocked at the specifier the source imports resolve to, not the
+// '@openpanel/db' barrel — a whole-barrel replacement would drop every other
+// export the barrel carries for any other file sharing this process
+// (bun:test only isolates modules per file under `--isolate`; see AGENTS.md).
+const actualPagesService = await import(
+ '@openpanel/db/src/services/pages.service'
+);
+mock.module('@openpanel/db/src/services/pages.service', () => ({
+ ...actualPagesService,
getPageConversionsCore: mockGetPageConversionsCore,
- resolveClientProjectId: vi.fn(({ clientProjectId }: { clientProjectId: string }) =>
- Promise.resolve(clientProjectId),
+}));
+
+const actualProjectService = await import(
+ '@openpanel/db/src/services/project.service'
+);
+mock.module('@openpanel/db/src/services/project.service', () => ({
+ ...actualProjectService,
+ resolveClientProjectId: mock(
+ ({ clientProjectId }: { clientProjectId: string }) =>
+ Promise.resolve(clientProjectId)
),
}));
-import { registerPageConversionTools } from './page-conversions';
+let registerPageConversionTools: typeof import('./page-conversions').registerPageConversionTools;
+
+beforeAll(async () => {
+ ({ registerPageConversionTools } = await import('./page-conversions'));
+});
function makeServer() {
let handler: ((input: unknown) => Promise<unknown>) | null = null;
@@ -18,23 +38,29 @@ function makeServer() {
_name: string,
_desc: string,
_schema: unknown,
- fn: (input: unknown) => Promise<unknown>,
+ fn: (input: unknown) => Promise<unknown>
) => {
handler = fn;
},
invoke: (input: unknown) => {
- if (!handler) throw new Error('tool not registered');
+ if (!handler) {
+ throw new Error('tool not registered');
+ }
return handler(input);
},
};
}
-const READ_CTX = { projectId: 'proj-1', organizationId: 'org-1', clientType: 'read' as const };
+const READ_CTX = {
+ projectId: 'proj-1',
+ organizationId: 'org-1',
+ clientType: 'read' as const,
+};
/** Re-hydrate the columnar table the tool returns into row objects. */
function rowsOf(result: { columns: string[]; rows: unknown[][] }): any[] {
return result.rows.map((row) =>
- Object.fromEntries(result.columns.map((column, i) => [column, row[i]])),
+ Object.fromEntries(result.columns.map((column, i) => [column, row[i]]))
);
}
@@ -50,7 +76,7 @@ function makePage(overrides: Record<string, unknown> = {}) {
}
beforeEach(() => {
- vi.clearAllMocks();
+ mockGetPageConversionsCore.mockReset();
});
describe('get_page_conversions — output structure', () => {
@@ -118,7 +144,7 @@ describe('get_page_conversions — arguments forwarding', () => {
});
expect(mockGetPageConversionsCore).toHaveBeenCalledWith(
- expect.objectContaining({ conversionEvent: 'trial_started' }),
+ expect.objectContaining({ conversionEvent: 'trial_started' })
);
});
@@ -133,7 +159,7 @@ describe('get_page_conversions — arguments forwarding', () => {
});
expect(mockGetPageConversionsCore).toHaveBeenCalledWith(
- expect.objectContaining({ windowHours: 24 }),
+ expect.objectContaining({ windowHours: 24 })
);
});
@@ -149,7 +175,7 @@ describe('get_page_conversions — arguments forwarding', () => {
});
expect(mockGetPageConversionsCore).toHaveBeenCalledWith(
- expect.objectContaining({ windowHours: 168 }),
+ expect.objectContaining({ windowHours: 168 })
);
const result = (await server.invoke({
projectId: READ_CTX.projectId,
@@ -171,7 +197,7 @@ describe('get_page_conversions — arguments forwarding', () => {
});
expect(mockGetPageConversionsCore).toHaveBeenCalledWith(
- expect.objectContaining({ limit: 26 }),
+ expect.objectContaining({ limit: 26 })
);
});
@@ -186,7 +212,7 @@ describe('get_page_conversions — arguments forwarding', () => {
});
expect(mockGetPageConversionsCore).toHaveBeenCalledWith(
- expect.objectContaining({ projectId: 'proj-1' }),
+ expect.objectContaining({ projectId: 'proj-1' })
);
});
});
@@ -194,7 +220,7 @@ describe('get_page_conversions — arguments forwarding', () => {
describe('get_page_conversions — total_pages count', () => {
it('reflects the number of pages returned by core', async () => {
const pages = Array.from({ length: 7 }, (_, i) =>
- makePage({ path: `/page-${i}`, unique_converters: 10 - i }),
+ makePage({ path: `/page-${i}`, unique_converters: 10 - i })
);
mockGetPageConversionsCore.mockResolvedValue(pages);
diff --git a/packages/mcp/src/tools/analytics/page-conversions.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.ts
similarity index 88%
rename from packages/mcp/src/tools/analytics/page-conversions.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/page-conversions.ts
index 67ac65609..a049689f4 100644
--- a/packages/mcp/src/tools/analytics/page-conversions.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.ts
@@ -1,5 +1,5 @@
-import { getPageConversionsCore } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getPageConversionsCore } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -15,7 +15,10 @@ import {
const DEFAULT_CONVERSION_LIMIT = 25;
const MAX_CONVERSION_LIMIT = 500;
-export function registerPageConversionTools(server: McpServer, context: McpAuthContext) {
+export function registerPageConversionTools(
+ server: McpServer,
+ context: McpAuthContext
+) {
server.tool(
'get_page_conversions',
`Find which pages drive the most conversions. Given a conversion event (e.g. "sign_up", "purchase"), returns pages ranked by how many unique visitors went on to convert within a configurable time window after the page view. Includes total_visitors and conversion_rate per page. Useful for identifying high-value content and optimizing landing pages. Defaults to the top ${DEFAULT_CONVERSION_LIMIT} pages.`,
@@ -25,7 +28,7 @@ export function registerPageConversionTools(server: McpServer, context: McpAuthC
conversionEvent: z
.string()
.describe(
- 'The event name that counts as a conversion (e.g. "sign_up", "purchase", "trial_started"). Use list_event_names to discover available events.',
+ 'The event name that counts as a conversion (e.g. "sign_up", "purchase", "trial_started"). Use list_event_names to discover available events.'
),
windowHours: z
.number()
@@ -34,7 +37,7 @@ export function registerPageConversionTools(server: McpServer, context: McpAuthC
.default(24)
.optional()
.describe(
- 'How many hours after a page view a conversion still counts (default: 24). Use 1 for same-session, 168 for 7-day window.',
+ 'How many hours after a page view a conversion still counts (default: 24). Use 1 for same-session, 168 for 7-day window.'
),
limit: zLimit(DEFAULT_CONVERSION_LIMIT, MAX_CONVERSION_LIMIT),
},
@@ -65,12 +68,18 @@ export function registerPageConversionTools(server: McpServer, context: McpAuthC
// fetched row just flags that more pages exist.
...table(pages.slice(0, take), {
limit: take,
- columns: ['path', 'origin', 'unique_converters', 'total_visitors', 'conversion_rate'],
+ columns: [
+ 'path',
+ 'origin',
+ 'unique_converters',
+ 'total_visitors',
+ 'conversion_rate',
+ ],
sortedBy: 'unique_converters',
unit: 'pages',
moreAvailable: pages.length > take,
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/page-performance.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts
similarity index 61%
rename from packages/mcp/src/tools/analytics/page-performance.test.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts
index 5aeae05d7..123c674a6 100644
--- a/packages/mcp/src/tools/analytics/page-performance.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts
@@ -1,40 +1,87 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
-const mockGetTopPages = vi.hoisted(() => vi.fn());
-const mockGetSettingsForProject = vi.hoisted(() =>
- vi.fn().mockResolvedValue({ timezone: 'UTC' }),
+const mockGetTopPages = mock();
+const mockGetSettingsForProject = mock(() =>
+ Promise.resolve({ timezone: 'UTC' })
);
-vi.mock('@openpanel/db', () => ({
- PagesService: vi.fn().mockImplementation(() => ({
+// Mocked at the specifier the source imports resolve to, not the
+// '@openpanel/db' barrel — a whole-barrel replacement would drop every other
+// export the barrel carries for any other file sharing this process
+// (bun:test only isolates modules per file under `--isolate`; see AGENTS.md).
+const actualPagesService = await import(
+ '@openpanel/db/src/services/pages.service'
+);
+mock.module('@openpanel/db/src/services/pages.service', () => ({
+ ...actualPagesService,
+ PagesService: mock().mockImplementation(() => ({
getTopPages: mockGetTopPages,
})),
+}));
+
+const actualClickhouseClient = await import(
+ '@openpanel/db/src/clickhouse/client'
+);
+mock.module('@openpanel/db/src/clickhouse/client', () => ({
+ ...actualClickhouseClient,
ch: {},
+}));
+
+const actualOrganizationService = await import(
+ '@openpanel/db/src/services/organization.service'
+);
+mock.module('@openpanel/db/src/services/organization.service', () => ({
+ ...actualOrganizationService,
getSettingsForProject: mockGetSettingsForProject,
- resolveClientProjectId: vi.fn(({ clientProjectId }: { clientProjectId: string }) => Promise.resolve(clientProjectId)),
}));
-import { registerPagePerformanceTools } from './page-performance';
+const actualProjectService = await import(
+ '@openpanel/db/src/services/project.service'
+);
+mock.module('@openpanel/db/src/services/project.service', () => ({
+ ...actualProjectService,
+ resolveClientProjectId: mock(
+ ({ clientProjectId }: { clientProjectId: string }) =>
+ Promise.resolve(clientProjectId)
+ ),
+}));
+
+let registerPagePerformanceTools: typeof import('./page-performance').registerPagePerformanceTools;
+
+beforeAll(async () => {
+ ({ registerPagePerformanceTools } = await import('./page-performance'));
+});
function makeServer() {
let handler: ((input: unknown) => Promise<unknown>) | null = null;
return {
- tool: (_name: string, _desc: string, _schema: unknown, fn: (input: unknown) => Promise<unknown>) => {
+ tool: (
+ _name: string,
+ _desc: string,
+ _schema: unknown,
+ fn: (input: unknown) => Promise<unknown>
+ ) => {
handler = fn;
},
invoke: (input: unknown) => {
- if (!handler) throw new Error('tool not registered');
+ if (!handler) {
+ throw new Error('tool not registered');
+ }
return handler(input);
},
};
}
-const READ_CTX = { projectId: 'proj-1', organizationId: 'org-1', clientType: 'read' as const };
+const READ_CTX = {
+ projectId: 'proj-1',
+ organizationId: 'org-1',
+ clientType: 'read' as const,
+};
/** Re-hydrate the columnar table the tool returns into row objects. */
function rowsOf(result: { columns: string[]; rows: unknown[][] }): any[] {
return result.rows.map((row) =>
- Object.fromEntries(result.columns.map((column, i) => [column, row[i]])),
+ Object.fromEntries(result.columns.map((column, i) => [column, row[i]]))
);
}
@@ -51,7 +98,8 @@ function makePage(overrides: Record<string, unknown> = {}) {
}
beforeEach(() => {
- vi.clearAllMocks();
+ mockGetTopPages.mockReset();
+ mockGetSettingsForProject.mockReset();
mockGetSettingsForProject.mockResolvedValue({ timezone: 'UTC' });
});
@@ -61,7 +109,9 @@ describe('get_page_performance — seo thresholds', () => {
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ })) as any;
const content = JSON.parse(result.content[0].text);
expect(content.seo_thresholds).toEqual({
@@ -78,7 +128,9 @@ describe('get_page_performance — seo thresholds', () => {
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ })) as any;
const content = JSON.parse(result.content[0].text);
// The booleans were pure functions of these two columns, so the columns
@@ -102,7 +154,9 @@ describe('get_page_performance — sorting', () => {
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ })) as any;
const content = JSON.parse(result.content[0].text);
const paths = rowsOf(content).map((p) => p.path);
@@ -114,7 +168,11 @@ describe('get_page_performance — sorting', () => {
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId, sortBy: 'bounce_rate', sortOrder: 'desc' }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ sortBy: 'bounce_rate',
+ sortOrder: 'desc',
+ })) as any;
const content = JSON.parse(result.content[0].text);
const paths = rowsOf(content).map((p) => p.path);
@@ -126,7 +184,11 @@ describe('get_page_performance — sorting', () => {
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId, sortBy: 'bounce_rate', sortOrder: 'asc' }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ sortBy: 'bounce_rate',
+ sortOrder: 'asc',
+ })) as any;
const content = JSON.parse(result.content[0].text);
const paths = rowsOf(content).map((p) => p.path);
@@ -138,7 +200,10 @@ describe('get_page_performance — sorting', () => {
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId, limit: 2 }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ limit: 2,
+ })) as any;
const content = JSON.parse(result.content[0].text);
// 2 kept rows plus the "(other)" rollup for the third.
@@ -151,13 +216,16 @@ describe('get_page_performance — sorting', () => {
describe('get_page_performance — metadata', () => {
it('reports the true total and rolls the tail up so sessions reconcile', async () => {
const manyPages = Array.from({ length: 10 }, (_, i) =>
- makePage({ path: `/page-${i}` }),
+ makePage({ path: `/page-${i}` })
);
mockGetTopPages.mockResolvedValue(manyPages);
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId, limit: 5 }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ limit: 5,
+ })) as any;
const content = JSON.parse(result.content[0].text);
expect(content.total_rows).toBe(10);
@@ -165,7 +233,7 @@ describe('get_page_performance — metadata', () => {
expect(content.rows).toHaveLength(6);
const totalSessions = content.rows.reduce(
(acc: number, row: unknown[]) => acc + (row[2] as number),
- 0,
+ 0
);
expect(totalSessions).toBe(10 * 100);
});
@@ -175,7 +243,9 @@ describe('get_page_performance — metadata', () => {
const server = makeServer() as any;
registerPagePerformanceTools(server, READ_CTX);
- const result = await server.invoke({ projectId: READ_CTX.projectId }) as any;
+ const result = (await server.invoke({
+ projectId: READ_CTX.projectId,
+ })) as any;
const content = JSON.parse(result.content[0].text);
expect(content.rows).toEqual([]);
diff --git a/packages/mcp/src/tools/analytics/page-performance.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts
similarity index 74%
rename from packages/mcp/src/tools/analytics/page-performance.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts
index 1633300ca..6e6d71207 100644
--- a/packages/mcp/src/tools/analytics/page-performance.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts
@@ -1,5 +1,5 @@
-import { PagesService, ch, getSettingsForProject } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { ch, getSettingsForProject, PagesService } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -12,8 +12,6 @@ import {
zLimit,
} from '../shared';
-const pagesService = new PagesService(ch);
-
const DEFAULT_PERFORMANCE_LIMIT = 25;
const MAX_PERFORMANCE_LIMIT = 500;
@@ -31,7 +29,7 @@ const SEO_THRESHOLDS = {
export function registerPagePerformanceTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_page_performance',
@@ -55,11 +53,26 @@ export function registerPagePerformanceTools(
.describe('Sort direction (default: desc)'),
limit: zLimit(DEFAULT_PERFORMANCE_LIMIT, MAX_PERFORMANCE_LIMIT),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, search, sortBy, sortOrder, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ search,
+ sortBy,
+ sortOrder,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
const { timezone } = await getSettingsForProject(projectId);
+ // Constructed per call, not once at module scope: a module-scope
+ // singleton binds `ch`/`PagesService` to whatever was live the first
+ // time this file was imported by *any* test in the process (bun:test
+ // shares one module registry without `--isolate` — see AGENTS.md),
+ // permanently defeating this file's own mocks whenever the
+ // integration suite imports it first.
+ const pagesService = new PagesService(ch);
const pages = await pagesService.getTopPages({
projectId,
@@ -72,7 +85,9 @@ export function registerPagePerformanceTools(
const col = sortBy ?? 'sessions';
const dir = sortOrder === 'asc' ? 1 : -1;
- const sorted = [...pages].sort((a, b) => dir * ((a[col] ?? 0) < (b[col] ?? 0) ? -1 : 1));
+ const sorted = [...pages].sort(
+ (a, b) => dir * ((a[col] ?? 0) < (b[col] ?? 0) ? -1 : 1)
+ );
return {
seo_thresholds: SEO_THRESHOLDS,
@@ -80,12 +95,19 @@ export function registerPagePerformanceTools(
// are ratios, and summing them would produce a confident lie.
...table(sorted, {
limit: limit ?? DEFAULT_PERFORMANCE_LIMIT,
- columns: ['path', 'title', 'sessions', 'pageviews', 'bounce_rate', 'avg_duration'],
+ columns: [
+ 'path',
+ 'title',
+ 'sessions',
+ 'pageviews',
+ 'bounce_rate',
+ 'avg_duration',
+ ],
sum: ['sessions', 'pageviews'],
sortedBy: col,
unit: 'pages',
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/pages.ts b/packages/core/src/modules/mcp/src/tools/analytics/pages.ts
similarity index 94%
rename from packages/mcp/src/tools/analytics/pages.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/pages.ts
index 503a1eac9..82005b304 100644
--- a/packages/mcp/src/tools/analytics/pages.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/pages.ts
@@ -1,6 +1,5 @@
-import { getEntryExitPagesCore, getTopPagesCore } from '@openpanel/db';
-
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getEntryExitPagesCore, getTopPagesCore } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -34,7 +33,13 @@ function pageTable(rows: PageRow[], limit: number) {
const hasRevenue = rows.some((row) => row.revenue !== undefined);
return table(rows.slice(0, limit), {
limit,
- columns: ['path', 'origin', 'sessions', 'pageviews', ...(hasRevenue ? (['revenue'] as const) : [])],
+ columns: [
+ 'path',
+ 'origin',
+ 'sessions',
+ 'pageviews',
+ ...(hasRevenue ? (['revenue'] as const) : []),
+ ],
sortedBy: 'sessions',
unit: 'pages',
moreAvailable: rows.length > limit,
@@ -62,7 +67,7 @@ export function registerPageTools(server: McpServer, context: McpAuthContext) {
limit: take + 1,
});
return pageTable(rows as PageRow[], take);
- }),
+ })
);
server.tool(
@@ -74,7 +79,7 @@ export function registerPageTools(server: McpServer, context: McpAuthContext) {
mode: z
.enum(['entry', 'exit'])
.describe(
- '"entry" for pages visitors land on first, "exit" for pages they leave from',
+ '"entry" for pages visitors land on first, "exit" for pages they leave from'
),
limit: zLimit(DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT),
},
@@ -97,6 +102,6 @@ export function registerPageTools(server: McpServer, context: McpAuthContext) {
limit: take + 1,
});
return { mode, ...pageTable(rows as PageRow[], take) };
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/profile-metrics.ts b/packages/core/src/modules/mcp/src/tools/analytics/profile-metrics.ts
similarity index 96%
rename from packages/mcp/src/tools/analytics/profile-metrics.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/profile-metrics.ts
index b1a81f177..acf41f785 100644
--- a/packages/mcp/src/tools/analytics/profile-metrics.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/profile-metrics.ts
@@ -1,17 +1,16 @@
-import { getProfileMetrics } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getProfileMetrics } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
projectIdSchema,
-
+ resolveProjectId,
withErrorHandling,
- resolveProjectId
} from '../shared';
export function registerProfileMetricTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_profile_metrics',
@@ -43,6 +42,6 @@ export function registerProfileMetricTools(
bounceRate: raw.bounceRate,
revenue: raw.revenue,
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/profiles.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts
similarity index 69%
rename from packages/mcp/src/tools/analytics/profiles.test.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts
index f4a06200a..9dbd3654f 100644
--- a/packages/mcp/src/tools/analytics/profiles.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts
@@ -1,58 +1,59 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const mockChQuery = vi.hoisted(() => vi.fn().mockResolvedValue([]));
-
-// Mock the ClickHouse client WITHOUT importOriginal — using importOriginal
-// causes the real module to be bound into profile.service.ts before the mock
-// factory result is visible, bypassing the chQuery replacement.
-vi.mock('../../../../db/src/clickhouse/client', () => {
- return {
- chQuery: mockChQuery,
- chQueryWithMeta: vi.fn().mockResolvedValue({ data: [], rows: 0 }),
- ch: {},
- originalCh: {},
- createClient: () => ({}),
- withRetry: vi.fn().mockImplementation((fn: () => unknown) => fn()),
- isClickhouseClustered: () => false,
- getReplicatedTableName: (name: string) => name,
- CLICKHOUSE_OPTIONS: {},
- TABLE_NAMES: {
- events: 'events',
- profiles: 'profiles',
- alias: 'profile_aliases',
- self_hosting: 'self_hosting',
- events_bots: 'events_bots',
- dau_mv: 'dau_mv',
- event_names_mv: 'distinct_event_names_mv',
- event_property_values_mv: 'event_property_values_mv',
- cohort_events_mv: 'cohort_events_mv',
- sessions: 'sessions',
- events_imports: 'events_imports',
- session_replay_chunks: 'session_replay_chunks',
- gsc_daily: 'gsc_daily',
- gsc_pages_daily: 'gsc_pages_daily',
- gsc_queries_daily: 'gsc_queries_daily',
- groups: 'groups',
- },
- formatClickhouseDate: (date: Date | string, skipTime = false) => {
- if (skipTime) return new Date(date).toISOString().split('T')[0];
- return new Date(date).toISOString().replace('T', ' ').replace(/(\.\d{3})?Z+$/, '');
- },
- toDate: (str: string) => str,
- convertClickhouseDateToJs: (date: string) => new Date(`${date.replace(' ', 'T')}Z`),
- isClickhouseDefaultMinDate: (date: string) => date.startsWith('1970-01-01') || date.startsWith('1969-12-31'),
- toNullIfDefaultMinDate: () => null,
- };
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
+
+const mockChQuery = mock((..._args: unknown[]) =>
+ Promise.resolve([] as unknown[])
+);
+
+// Mock the ClickHouse client at the specifier profile.service.ts imports —
+// mock.module applies at call time (unlike vitest's hoisted vi.mock), so the
+// mock must be registered before profile.service's first (dynamic) import.
+//
+// Spread the real module rather than hand-listing every export: `mock.module`
+// replaces this specifier process-wide (bun runs every test file in one
+// shared module registry without `--isolate` — see AGENTS.md). A hand-rolled
+// factory here previously left `ch`/`originalCh` empty objects and `TABLE_NAMES`
+// a hand-copied subset — invisible to `findProfilesCore` (it only reaches
+// `chQuery`/`TABLE_NAMES.events`, both covered), but not to every *other*
+// consumer of this same live-bound specifier sharing this process (e.g. the
+// mcp integration suite's real, unmocked service calls) — restored in
+// afterAll below so the leak doesn't outlive this file.
+const actualClickhouseClient = await import(
+ '@openpanel/db/src/clickhouse/client'
+);
+mock.module('@openpanel/db/src/clickhouse/client', () => ({
+ ...actualClickhouseClient,
+ chQuery: mockChQuery,
+}));
+
+afterAll(() => {
+ mock.module('@openpanel/db/src/clickhouse/client', () => ({
+ ...actualClickhouseClient,
+ }));
});
-import { findProfilesCore } from '../../../../db/src/services/profile.service';
+let findProfilesCore: typeof import('@openpanel/db/src/services/profile.service').findProfilesCore;
+
+beforeAll(async () => {
+ ({ findProfilesCore } = await import(
+ '@openpanel/db/src/services/profile.service'
+ ));
+});
function capturedSql(): string {
return mockChQuery.mock.calls[0]?.[0] as string;
}
beforeEach(() => {
- vi.clearAllMocks();
+ mockChQuery.mockClear();
+ mockChQuery.mockResolvedValue([]);
});
describe('findProfilesCore — SQL conditions', () => {
@@ -161,7 +162,10 @@ describe('findProfilesCore — return value', () => {
const fakeProfiles = [{ id: 'p1', first_name: 'Alice' }];
mockChQuery.mockResolvedValueOnce(fakeProfiles);
const result = await findProfilesCore({ projectId: 'proj-1' });
- expect(result).toEqual(fakeProfiles);
+ // findProfilesCore is an opaque passthrough of whatever chQuery resolves
+ // with — the fake row is deliberately partial, so it needs a cast against
+ // the real (fuller) IClickhouseProfile return type.
+ expect(result).toEqual(fakeProfiles as unknown as typeof result);
});
it('returns empty array when no profiles found', async () => {
diff --git a/packages/mcp/src/tools/analytics/profiles.ts b/packages/core/src/modules/mcp/src/tools/analytics/profiles.ts
similarity index 84%
rename from packages/mcp/src/tools/analytics/profiles.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/profiles.ts
index b5c198084..dd16c4d1f 100644
--- a/packages/mcp/src/tools/analytics/profiles.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/profiles.ts
@@ -1,9 +1,12 @@
-import { findProfilesCore, getProfileSessionsCore, getProfileWithEvents } from '@openpanel/db';
-
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import {
+ findProfilesCore,
+ getProfileSessionsCore,
+ getProfileWithEvents,
+} from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
-import { profileUrl, dashboardBaseUrl } from '../dashboard-links';
+import { dashboardBaseUrl, profileUrl } from '../dashboard-links';
import {
projectIdSchema,
resolveProjectId,
@@ -32,7 +35,7 @@ const PROFILE_COLUMNS = [
export function registerProfileTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'find_profiles',
@@ -42,11 +45,10 @@ export function registerProfileTools(
name: z
.string()
.optional()
- .describe('Partial match against first name or last name (e.g. "Carl")'),
- email: z
- .string()
- .optional()
- .describe('Partial email match'),
+ .describe(
+ 'Partial match against first name or last name (e.g. "Carl")'
+ ),
+ email: z.string().optional().describe('Partial email match'),
country: z
.string()
.optional()
@@ -63,7 +65,7 @@ export function registerProfileTools(
.min(1)
.optional()
.describe(
- 'Return only profiles with no activity (events) in the last N days. E.g. 14 = inactive for 2+ weeks.',
+ 'Return only profiles with no activity (events) in the last N days. E.g. 14 = inactive for 2+ weeks.'
),
minSessions: z
.number()
@@ -75,13 +77,15 @@ export function registerProfileTools(
.string()
.optional()
.describe(
- 'Return only profiles that have performed this event at least once (e.g. "purchase", "sign_up")',
+ 'Return only profiles that have performed this event at least once (e.g. "purchase", "sign_up")'
),
sortOrder: z
.enum(['asc', 'desc'])
.default('desc')
.optional()
- .describe('Sort direction for created_at (default: desc = newest first)'),
+ .describe(
+ 'Sort direction for created_at (default: desc = newest first)'
+ ),
limit: zLimit(DEFAULT_PROFILE_LIMIT, MAX_PROFILE_LIMIT),
},
async ({ projectId: inputProjectId, ...input }) =>
@@ -104,7 +108,7 @@ export function registerProfileTools(
moreAvailable: profiles.length > take,
}),
};
- }),
+ })
);
server.tool(
@@ -125,7 +129,11 @@ export function registerProfileTools(
}
return {
profile: result.profile,
- dashboard_url: profileUrl(context.organizationId, projectId, profileId),
+ dashboard_url: profileUrl(
+ context.organizationId,
+ projectId,
+ profileId
+ ),
recent_events: table(result.recent_events, {
limit: take,
columns: EVENT_COLUMNS_DEFAULT,
@@ -133,7 +141,7 @@ export function registerProfileTools(
unit: 'events',
}),
};
- }),
+ })
);
server.tool(
@@ -148,10 +156,18 @@ export function registerProfileTools(
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const take = limit ?? DEFAULT_SESSION_LIMIT;
- const sessions = await getProfileSessionsCore(projectId, profileId, take + 1);
+ const sessions = await getProfileSessionsCore(
+ projectId,
+ profileId,
+ take + 1
+ );
return {
profileId,
- dashboard_url: profileUrl(context.organizationId, projectId, profileId),
+ dashboard_url: profileUrl(
+ context.organizationId,
+ projectId,
+ profileId
+ ),
session_url_template: `${dashboardBaseUrl()}/${context.organizationId}/${projectId}/sessions/{id}`,
...table(sessions.slice(0, take), {
limit: take,
@@ -161,6 +177,6 @@ export function registerProfileTools(
moreAvailable: sessions.length > take,
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/property-values.ts b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
similarity index 91%
rename from packages/mcp/src/tools/analytics/property-values.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
index 021119aad..15643f2f0 100644
--- a/packages/mcp/src/tools/analytics/property-values.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
@@ -1,5 +1,5 @@
-import { EVENT_COLUMNS, TABLE_NAMES, ch, clix } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { ch, clix, EVENT_COLUMNS, TABLE_NAMES } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -31,7 +31,7 @@ const MAX_VALUE_LIMIT = 500;
*/
function compactPropertyKeys(
rows: Array<{ property_key: string }>,
- max: number,
+ max: number
): { properties: string[]; total: number; note?: string } {
const counts = new Map<string, number>();
for (const row of rows) {
@@ -56,7 +56,7 @@ function compactPropertyKeys(
export function registerPropertyValueTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'list_event_properties',
@@ -66,7 +66,9 @@ export function registerPropertyValueTools(
eventName: z
.string()
.optional()
- .describe('Filter to a specific event name. Omit to list properties across all events.'),
+ .describe(
+ 'Filter to a specific event name. Omit to list properties across all events.'
+ ),
limit: zLimit(DEFAULT_PROPERTY_LIMIT, MAX_PROPERTY_LIMIT),
},
async ({ projectId: inputProjectId, eventName, limit }) =>
@@ -98,7 +100,7 @@ export function registerPropertyValueTools(
columns: EVENT_COLUMNS,
...compactPropertyKeys(rows, limit ?? DEFAULT_PROPERTY_LIMIT),
};
- }),
+ })
);
server.tool(
@@ -108,10 +110,14 @@ export function registerPropertyValueTools(
projectId: projectIdSchema(context),
eventName: z
.string()
- .describe('The event name to look up property values for (e.g. "subscription_created")'),
+ .describe(
+ 'The event name to look up property values for (e.g. "subscription_created")'
+ ),
propertyKey: z
.string()
- .describe('The property key to get values for (e.g. "plan", "country", "status")'),
+ .describe(
+ 'The property key to get values for (e.g. "plan", "country", "status")'
+ ),
limit: zLimit(DEFAULT_VALUE_LIMIT, MAX_VALUE_LIMIT),
},
async ({ projectId: inputProjectId, eventName, propertyKey, limit }) =>
@@ -134,7 +140,9 @@ export function registerPropertyValueTools(
const distinct: string[] = [];
const seen = new Set<string>();
for (const row of rows) {
- if (seen.has(row.value)) continue;
+ if (seen.has(row.value)) {
+ continue;
+ }
seen.add(row.value);
distinct.push(row.value);
}
@@ -150,6 +158,6 @@ export function registerPropertyValueTools(
}
: {}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/reports.ts b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
similarity index 96%
rename from packages/mcp/src/tools/analytics/reports.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/reports.ts
index c718bda1c..bbf0865b7 100644
--- a/packages/mcp/src/tools/analytics/reports.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
@@ -285,12 +285,12 @@ export function registerReportTools(
* - metric → AggregateChartEngine.execute
* - others → ChartEngine.execute
*
- * `@openpanel/core`'s assistant module (src/report-runner.ts, M5-005) carries
- * its own copy of this dispatch for its in-app chat tools — core cannot
- * depend on `@openpanel/mcp` (mcp already depends on core), so the reuse this
- * comment used to describe is now two hand-synced copies. Deliberately
- * returns the raw engine output here — the MCP tool reshapes it for LLM
- * consumption, the chat renderer needs the full chart.
+ * The assistant module (`../../assistant/src/report-runner.ts`, M5-005)
+ * carries its own copy of this dispatch for its in-app chat tools — ADR-007
+ * explicitly defers unifying MCP's tool definitions with assistant's (M5-007),
+ * so the two live as hand-synced copies rather than a shared helper.
+ * Deliberately returns the raw engine output here — the MCP tool reshapes it
+ * for LLM consumption, the chat renderer needs the full chart.
*/
export async function runReport(input: {
organizationId: string;
diff --git a/packages/mcp/src/tools/analytics/retention.ts b/packages/core/src/modules/mcp/src/tools/analytics/retention.ts
similarity index 94%
rename from packages/mcp/src/tools/analytics/retention.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/retention.ts
index ac0627178..7b17ff1c8 100644
--- a/packages/mcp/src/tools/analytics/retention.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/retention.ts
@@ -1,16 +1,15 @@
-import { getRetentionCohortCore } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getRetentionCohortCore } from '@openpanel/db';
import type { McpAuthContext } from '../../auth';
import {
projectIdSchema,
-
+ resolveProjectId,
withErrorHandling,
- resolveProjectId
} from '../shared';
export function registerRetentionTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_retention_cohort',
@@ -22,6 +21,6 @@ export function registerRetentionTools(
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
return getRetentionCohortCore(projectId);
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/sessions.ts b/packages/core/src/modules/mcp/src/tools/analytics/sessions.ts
similarity index 96%
rename from packages/mcp/src/tools/analytics/sessions.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/sessions.ts
index e13b5d22e..0e77d174d 100644
--- a/packages/mcp/src/tools/analytics/sessions.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/sessions.ts
@@ -1,12 +1,8 @@
-import { querySessionsCore } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { querySessionsCore } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import { dashboardBaseUrl } from '../dashboard-links';
-import {
- SESSION_COLUMNS_DEFAULT,
- SESSION_COLUMNS_EXTRA,
-} from './columns';
import {
projectIdSchema,
resolveProjectId,
@@ -15,14 +11,14 @@ import {
zDateRange,
zLimit,
} from '../shared';
+import { SESSION_COLUMNS_DEFAULT, SESSION_COLUMNS_EXTRA } from './columns';
const DEFAULT_SESSION_LIMIT = 20;
const MAX_SESSION_LIMIT = 100;
-
export function registerSessionTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'query_sessions',
@@ -55,7 +51,7 @@ export function registerSessionTools(
.array(z.enum(SESSION_COLUMNS_EXTRA))
.optional()
.describe(
- 'Extra columns to include beyond the default set. Only request what you need — every extra column costs rows of output.',
+ 'Extra columns to include beyond the default set. Only request what you need — every extra column costs rows of output.'
),
limit: zLimit(DEFAULT_SESSION_LIMIT, MAX_SESSION_LIMIT),
},
@@ -80,6 +76,6 @@ export function registerSessionTools(
moreAvailable: sessions.length > take,
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/traffic.ts b/packages/core/src/modules/mcp/src/tools/analytics/traffic.ts
similarity index 84%
rename from packages/mcp/src/tools/analytics/traffic.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/traffic.ts
index 1c4765817..07860e9a9 100644
--- a/packages/mcp/src/tools/analytics/traffic.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/traffic.ts
@@ -1,5 +1,5 @@
-import { getTrafficBreakdownCore, type TrafficColumn } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getTrafficBreakdownCore, type TrafficColumn } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -45,7 +45,11 @@ function breakdownTable(rows: BreakdownRow[], limit: number, unit: string) {
return table(rows, {
limit,
columns,
- sum: ['sessions', 'pageviews', ...(hasRevenue ? (['revenue'] as const) : [])],
+ sum: [
+ 'sessions',
+ 'pageviews',
+ ...(hasRevenue ? (['revenue'] as const) : []),
+ ],
sortedBy: 'sessions',
unit,
});
@@ -53,7 +57,7 @@ function breakdownTable(rows: BreakdownRow[], limit: number, unit: string) {
export function registerTrafficTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_top_referrers',
@@ -62,15 +66,28 @@ export function registerTrafficTools(
projectId: projectIdSchema(context),
...zDateRange,
breakdown: z
- .enum(['referrer_name', 'referrer_type', 'referrer', 'utm_source', 'utm_medium', 'utm_campaign'])
+ .enum([
+ 'referrer_name',
+ 'referrer_type',
+ 'referrer',
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ ])
.default('referrer_name')
.optional()
.describe(
- 'How to group referrers: by name (Google, Twitter), type (search, social), full URL, or UTM params',
+ 'How to group referrers: by name (Google, Twitter), type (search, social), full URL, or UTM params'
),
limit: zLimit(DEFAULT_BREAKDOWN_LIMIT, MAX_BREAKDOWN_LIMIT),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, breakdown, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ breakdown,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
@@ -83,9 +100,9 @@ export function registerTrafficTools(
return breakdownTable(
rows as BreakdownRow[],
limit ?? DEFAULT_BREAKDOWN_LIMIT,
- 'sources',
+ 'sources'
);
- }),
+ })
);
server.tool(
@@ -101,7 +118,13 @@ export function registerTrafficTools(
.describe('Geographic grouping level (default: country)'),
limit: zLimit(DEFAULT_BREAKDOWN_LIMIT, MAX_BREAKDOWN_LIMIT),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, breakdown, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ breakdown,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
@@ -114,9 +137,9 @@ export function registerTrafficTools(
return breakdownTable(
rows as BreakdownRow[],
limit ?? DEFAULT_BREAKDOWN_LIMIT,
- 'locations',
+ 'locations'
);
- }),
+ })
);
server.tool(
@@ -130,11 +153,17 @@ export function registerTrafficTools(
.default('device')
.optional()
.describe(
- 'Device dimension: "device" (desktop/mobile/tablet), "browser" (Chrome/Firefox), or "os" (Windows/macOS)',
+ 'Device dimension: "device" (desktop/mobile/tablet), "browser" (Chrome/Firefox), or "os" (Windows/macOS)'
),
limit: zLimit(DEFAULT_BREAKDOWN_LIMIT, MAX_BREAKDOWN_LIMIT),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, breakdown, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ breakdown,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
@@ -147,8 +176,8 @@ export function registerTrafficTools(
return breakdownTable(
rows as BreakdownRow[],
limit ?? DEFAULT_BREAKDOWN_LIMIT,
- 'devices',
+ 'devices'
);
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/analytics/user-flow.ts b/packages/core/src/modules/mcp/src/tools/analytics/user-flow.ts
similarity index 83%
rename from packages/mcp/src/tools/analytics/user-flow.ts
rename to packages/core/src/modules/mcp/src/tools/analytics/user-flow.ts
index 36b179e53..197361fce 100644
--- a/packages/mcp/src/tools/analytics/user-flow.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/user-flow.ts
@@ -1,6 +1,5 @@
-import { getUserFlowCore } from '@openpanel/db';
-
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getUserFlowCore } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -18,7 +17,7 @@ const MAX_FLOW_NODES = 500;
export function registerUserFlowTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_user_flow',
@@ -28,7 +27,9 @@ export function registerUserFlowTools(
...zDateRange,
startEvent: z
.string()
- .describe('The anchor event name. For "after"/"before" mode this is the pivot event; for "between" it is the start.'),
+ .describe(
+ 'The anchor event name. For "after"/"before" mode this is the pivot event; for "between" it is the start.'
+ ),
endEvent: z
.string()
.optional()
@@ -37,7 +38,7 @@ export function registerUserFlowTools(
.enum(['after', 'before', 'between'])
.default('after')
.describe(
- '"after" = what users do after startEvent; "before" = what leads up to startEvent; "between" = paths from startEvent to endEvent.',
+ '"after" = what users do after startEvent; "before" = what leads up to startEvent; "between" = paths from startEvent to endEvent.'
),
steps: z
.number()
@@ -50,19 +51,42 @@ export function registerUserFlowTools(
exclude: z
.array(z.string())
.optional()
- .describe('Event names to exclude from the flow (e.g. noisy system events)'),
+ .describe(
+ 'Event names to exclude from the flow (e.g. noisy system events)'
+ ),
include: z
.array(z.string())
.optional()
.describe('If set, only show these event names in the flow'),
limit: zLimit(DEFAULT_FLOW_NODES, MAX_FLOW_NODES),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, startEvent, endEvent, mode, steps, exclude, include, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ startEvent,
+ endEvent,
+ mode,
+ steps,
+ exclude,
+ include,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
const take = limit ?? DEFAULT_FLOW_NODES;
- const flow = await getUserFlowCore({ projectId, startDate, endDate, startEvent, endEvent, mode, steps, exclude, include });
+ const flow = await getUserFlowCore({
+ projectId,
+ startDate,
+ endDate,
+ startEvent,
+ endEvent,
+ mode,
+ steps,
+ exclude,
+ include,
+ });
// Trim to the highest-volume nodes, then drop links that would dangle —
// a link pointing at a node we cut is worse than no link at all.
@@ -71,7 +95,7 @@ export function registerUserFlowTools(
.slice(0, take);
const kept = new Set(nodes.map((node) => node.id));
const links = flow.links.filter(
- (link) => kept.has(link.source) && kept.has(link.target),
+ (link) => kept.has(link.source) && kept.has(link.target)
);
return {
@@ -99,6 +123,6 @@ export function registerUserFlowTools(
unit: 'links',
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/dashboard-links.ts b/packages/core/src/modules/mcp/src/tools/dashboard-links.ts
similarity index 67%
rename from packages/mcp/src/tools/dashboard-links.ts
rename to packages/core/src/modules/mcp/src/tools/dashboard-links.ts
index c38294a80..ffb7c684f 100644
--- a/packages/mcp/src/tools/dashboard-links.ts
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-links.ts
@@ -1,10 +1,7 @@
-import { } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import type { McpAuthContext } from '../auth';
-import { projectIdSchema, withErrorHandling,
- resolveProjectId
-} from './shared';
+import { projectIdSchema, resolveProjectId, withErrorHandling } from './shared';
export function dashboardBaseUrl() {
return (
@@ -14,29 +11,55 @@ export function dashboardBaseUrl() {
).replace(/\/$/, '');
}
-export function profileUrl(organizationId: string, projectId: string, profileId: string) {
+export function profileUrl(
+ organizationId: string,
+ projectId: string,
+ profileId: string
+) {
return `${dashboardBaseUrl()}/${organizationId}/${projectId}/profiles/${profileId}`;
}
-export function sessionUrl(organizationId: string, projectId: string, sessionId: string) {
+export function sessionUrl(
+ organizationId: string,
+ projectId: string,
+ sessionId: string
+) {
return `${dashboardBaseUrl()}/${organizationId}/${projectId}/sessions/${sessionId}`;
}
export function registerDashboardLinkTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_dashboard_urls',
'Get clickable dashboard URLs for the current project. Returns links to all main sections (overview, events, profiles, sessions, etc.) and optionally deep-links to a specific profile, session, dashboard, or report when their IDs are provided. Use these links to let the user navigate directly to relevant pages.',
{
projectId: projectIdSchema(context),
- profileId: z.string().optional().describe('Profile ID to get a direct link to that profile'),
- sessionId: z.string().optional().describe('Session ID to get a direct link to that session'),
- dashboardId: z.string().optional().describe('Dashboard ID to get a direct link to that dashboard'),
- reportId: z.string().optional().describe('Report ID to get a direct link to that report'),
+ profileId: z
+ .string()
+ .optional()
+ .describe('Profile ID to get a direct link to that profile'),
+ sessionId: z
+ .string()
+ .optional()
+ .describe('Session ID to get a direct link to that session'),
+ dashboardId: z
+ .string()
+ .optional()
+ .describe('Dashboard ID to get a direct link to that dashboard'),
+ reportId: z
+ .string()
+ .optional()
+ .describe('Report ID to get a direct link to that report'),
},
- async ({ projectId: inputProjectId, profileId, sessionId, dashboardId, reportId }) =>
+ async ({
+ projectId: inputProjectId,
+ profileId,
+ sessionId,
+ dashboardId,
+ reportId,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const base = `${dashboardBaseUrl()}/${context.organizationId}/${projectId}`;
@@ -67,6 +90,6 @@ export function registerDashboardLinkTools(
}
return urls;
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/dashboard-management.test.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts
similarity index 79%
rename from packages/mcp/src/tools/dashboard-management.test.ts
rename to packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts
index e546977cf..735dcadb5 100644
--- a/packages/mcp/src/tools/dashboard-management.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts
@@ -1,51 +1,83 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
import { z } from 'zod';
-const mockDb = vi.hoisted(() => ({
- $transaction: vi.fn(),
+const mockDb = {
+ $transaction: mock(),
dashboard: {
- create: vi.fn(),
- findFirst: vi.fn(),
- update: vi.fn(),
- delete: vi.fn(),
+ create: mock(),
+ findFirst: mock(),
+ update: mock(),
+ delete: mock(),
},
report: {
- create: vi.fn(),
- findFirst: vi.fn(),
- findMany: vi.fn(),
- update: vi.fn(),
- delete: vi.fn(),
- deleteMany: vi.fn(),
+ create: mock(),
+ findFirst: mock(),
+ findMany: mock(),
+ update: mock(),
+ delete: mock(),
+ deleteMany: mock(),
},
reportLayout: {
- upsert: vi.fn(),
- deleteMany: vi.fn(),
+ upsert: mock(),
+ deleteMany: mock(),
},
-}));
-
-const mockGetDashboardById = vi.hoisted(() => vi.fn());
-const mockGetProjectById = vi.hoisted(() => vi.fn());
-const mockGetId = vi.hoisted(() => vi.fn());
+};
-vi.mock('@openpanel/db', () => ({
+const mockGetDashboardById = mock();
+const mockGetProjectById = mock();
+const mockGetId = mock();
+
+// Mocked at the specifier the source imports resolve to, not the
+// '@openpanel/db' barrel — a whole-barrel replacement would drop every other
+// export the barrel carries for any other file sharing this process
+// (bun:test only isolates modules per file under `--isolate`; see AGENTS.md).
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
Prisma: { DbNull: { kind: 'DbNull' } },
db: mockDb,
+}));
+
+const actualDashboardService = await import(
+ '@openpanel/db/src/services/dashboard.service'
+);
+mock.module('@openpanel/db/src/services/dashboard.service', () => ({
+ ...actualDashboardService,
getDashboardById: mockGetDashboardById,
+}));
+
+const actualProjectService = await import(
+ '@openpanel/db/src/services/project.service'
+);
+mock.module('@openpanel/db/src/services/project.service', () => ({
+ ...actualProjectService,
getProjectById: mockGetProjectById,
- getId: mockGetId,
- resolveClientProjectId: vi.fn(
+ resolveClientProjectId: mock(
({
clientProjectId,
inputProjectId,
}: {
clientProjectId: string | null;
inputProjectId?: string;
- }) => Promise.resolve(clientProjectId ?? inputProjectId),
+ }) => Promise.resolve(clientProjectId ?? inputProjectId)
),
}));
+const actualIdService = await import('@openpanel/db/src/services/id.service');
+mock.module('@openpanel/db/src/services/id.service', () => ({
+ ...actualIdService,
+ getId: mockGetId,
+}));
+
+let registerDashboardManagementTools: typeof import('./dashboard-management').registerDashboardManagementTools;
+
+beforeAll(async () => {
+ ({ registerDashboardManagementTools } = await import(
+ './dashboard-management'
+ ));
+});
+
import type { McpAuthContext } from '../auth';
-import { registerDashboardManagementTools } from './dashboard-management';
type Handler = (input: any) => Promise<any>;
@@ -57,7 +89,7 @@ function makeServer() {
name: string,
_description: string,
schema: any,
- handler: Handler,
+ handler: Handler
) => {
handlers.set(name, handler);
schemas.set(name, schema);
@@ -139,14 +171,33 @@ const EVENT_WITH_TYPED_COHORT_FILTER = {
};
beforeEach(() => {
- vi.clearAllMocks();
+ mockGetDashboardById.mockReset();
+ mockGetProjectById.mockReset();
+ mockGetId.mockReset();
+ mockDb.$transaction.mockReset();
+ mockDb.dashboard.create.mockReset();
+ mockDb.dashboard.findFirst.mockReset();
+ mockDb.dashboard.update.mockReset();
+ mockDb.dashboard.delete.mockReset();
+ mockDb.report.create.mockReset();
+ mockDb.report.findFirst.mockReset();
+ mockDb.report.findMany.mockReset();
+ mockDb.report.update.mockReset();
+ mockDb.report.delete.mockReset();
+ mockDb.report.deleteMany.mockReset();
+ mockDb.reportLayout.upsert.mockReset();
+ mockDb.reportLayout.deleteMany.mockReset();
+
mockGetDashboardById.mockResolvedValue(DASHBOARD);
mockGetProjectById.mockResolvedValue({
id: 'project-1',
organizationId: 'organization-1',
});
mockGetId.mockResolvedValue('dashboard-2');
- mockDb.dashboard.create.mockResolvedValue({ ...DASHBOARD, id: 'dashboard-2' });
+ mockDb.dashboard.create.mockResolvedValue({
+ ...DASHBOARD,
+ id: 'dashboard-2',
+ });
mockDb.dashboard.findFirst.mockResolvedValue(DASHBOARD);
mockDb.dashboard.update.mockResolvedValue({ ...DASHBOARD, name: 'Renamed' });
mockDb.report.findFirst.mockResolvedValue(REPORT);
@@ -157,7 +208,9 @@ beforeEach(() => {
mockDb.report.deleteMany.mockResolvedValue({ count: 1 });
mockDb.reportLayout.upsert.mockResolvedValue({ reportId: REPORT.id, x: 1 });
mockDb.reportLayout.deleteMany.mockResolvedValue({ count: 1 });
- mockDb.$transaction.mockImplementation(async (callback) => callback(mockDb));
+ mockDb.$transaction.mockImplementation(async (callback: any) =>
+ callback(mockDb)
+ );
});
function register(context: McpAuthContext = ROOT_CONTEXT) {
@@ -206,20 +259,22 @@ describe('dashboard management registration', () => {
metric: 'sum',
lineType: 'monotone',
});
- expect(reportSchema.safeParse({ name: 'Missing series' }).success).toBe(false);
- expect(
- reportSchema.safeParse(validReport({ limit: 10 })).success,
- ).toBe(false);
- expect(
- reportSchema.safeParse(validReport({ offset: 10 })).success,
- ).toBe(false);
+ expect(reportSchema.safeParse({ name: 'Missing series' }).success).toBe(
+ false
+ );
+ expect(reportSchema.safeParse(validReport({ limit: 10 })).success).toBe(
+ false
+ );
+ expect(reportSchema.safeParse(validReport({ offset: 10 })).success).toBe(
+ false
+ );
});
it('requires valid ordered dates for custom ranges', () => {
const reportSchema = register().schema('create_report').report;
expect(
- reportSchema.safeParse(validReport({ range: 'custom' })).success,
+ reportSchema.safeParse(validReport({ range: 'custom' })).success
).toBe(false);
expect(
reportSchema.safeParse(
@@ -227,8 +282,8 @@ describe('dashboard management registration', () => {
range: 'custom',
startDate: '2026-02-30',
endDate: '2026-03-01',
- }),
- ).success,
+ })
+ ).success
).toBe(false);
expect(
reportSchema.safeParse(
@@ -236,8 +291,8 @@ describe('dashboard management registration', () => {
range: 'custom',
startDate: '2026-03-02',
endDate: '2026-03-01',
- }),
- ).success,
+ })
+ ).success
).toBe(false);
});
});
@@ -251,7 +306,10 @@ describe('dashboard management project binding', () => {
dashboardId: 'dashboard-1',
});
- expect(mockGetDashboardById).toHaveBeenCalledWith('dashboard-1', 'project-1');
+ expect(mockGetDashboardById).toHaveBeenCalledWith(
+ 'dashboard-1',
+ 'project-1'
+ );
expect(mockDb.report.findMany).toHaveBeenCalledWith({
where: { dashboardId: 'dashboard-1', projectId: 'project-1' },
include: { layout: true },
@@ -265,7 +323,7 @@ describe('dashboard management project binding', () => {
server.invoke('delete_report', {
projectId: 'project-1',
reportId: 'dashboard-1',
- }),
+ })
).rejects.toThrow();
expect(mockDb.report.findFirst).not.toHaveBeenCalled();
});
@@ -282,7 +340,10 @@ describe('dashboard management project binding', () => {
expect(result.error).toContain('Report not found');
expect(mockDb.report.delete).not.toHaveBeenCalled();
expect(mockDb.report.findFirst).toHaveBeenCalledWith({
- where: { id: '22222222-2222-4222-8222-222222222222', projectId: 'project-1' },
+ where: {
+ id: '22222222-2222-4222-8222-222222222222',
+ projectId: 'project-1',
+ },
});
});
});
@@ -385,7 +446,9 @@ describe('dashboard management behavior', () => {
dashboardId: 'dashboard-1',
});
- expect(result.error).toContain('Cannot delete dashboard with associated reports');
+ expect(result.error).toContain(
+ 'Cannot delete dashboard with associated reports'
+ );
expect(mockDb.$transaction).toHaveBeenCalled();
expect(mockDb.dashboard.delete).not.toHaveBeenCalled();
});
@@ -409,7 +472,7 @@ describe('dashboard management behavior', () => {
where: { reportId: { in: ['11111111-1111-4111-8111-111111111111'] } },
});
expect(
- mockDb.reportLayout.deleteMany.mock.invocationCallOrder[0]!,
+ mockDb.reportLayout.deleteMany.mock.invocationCallOrder[0]!
).toBeLessThan(mockDb.report.deleteMany.mock.invocationCallOrder[0]!);
expect(mockDb.dashboard.delete).toHaveBeenCalledWith({
where: { id: 'dashboard-1' },
@@ -464,7 +527,7 @@ describe('dashboard management behavior', () => {
projectId: 'project-1',
reportId: '11111111-1111-4111-8111-111111111111',
layout: { x: -1, y: 0, w: 4, h: 3 },
- }),
+ })
).rejects.toThrow();
expect(mockDb.reportLayout.upsert).not.toHaveBeenCalled();
diff --git a/packages/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
similarity index 81%
rename from packages/mcp/src/tools/dashboard-management.ts
rename to packages/core/src/modules/mcp/src/tools/dashboard-management.ts
index f3391136f..5bce23ca5 100644
--- a/packages/mcp/src/tools/dashboard-management.ts
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
@@ -1,12 +1,12 @@
+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import {
- Prisma,
db,
getDashboardById,
getId,
getProjectById,
+ Prisma,
} from '@openpanel/db';
import { zReport } from '@openpanel/validation';
-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import type { McpAuthContext } from '../auth';
import { dashboardBaseUrl } from './dashboard-links';
@@ -48,67 +48,69 @@ const reportSchema = zReport
}
});
-const layoutSchema = z.object({
- x: z.number().int().nonnegative(),
- y: z.number().int().nonnegative(),
- w: z.number().int().positive(),
- h: z.number().int().positive(),
- minW: z.number().int().positive().optional(),
- minH: z.number().int().positive().optional(),
- maxW: z.number().int().positive().optional(),
- maxH: z.number().int().positive().optional(),
-}).superRefine((layout, ctx) => {
- if (
- layout.minW !== undefined &&
- layout.maxW !== undefined &&
- layout.maxW < layout.minW
- ) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['maxW'],
- message: 'maxW must be greater than or equal to minW',
- });
- }
- if (layout.minW !== undefined && layout.minW > layout.w) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['minW'],
- message: 'minW must be less than or equal to w',
- });
- }
- if (layout.maxW !== undefined && layout.maxW < layout.w) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['maxW'],
- message: 'maxW must be greater than or equal to w',
- });
- }
- if (
- layout.minH !== undefined &&
- layout.maxH !== undefined &&
- layout.maxH < layout.minH
- ) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['maxH'],
- message: 'maxH must be greater than or equal to minH',
- });
- }
- if (layout.minH !== undefined && layout.minH > layout.h) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['minH'],
- message: 'minH must be less than or equal to h',
- });
- }
- if (layout.maxH !== undefined && layout.maxH < layout.h) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['maxH'],
- message: 'maxH must be greater than or equal to h',
- });
- }
-});
+const layoutSchema = z
+ .object({
+ x: z.number().int().nonnegative(),
+ y: z.number().int().nonnegative(),
+ w: z.number().int().positive(),
+ h: z.number().int().positive(),
+ minW: z.number().int().positive().optional(),
+ minH: z.number().int().positive().optional(),
+ maxW: z.number().int().positive().optional(),
+ maxH: z.number().int().positive().optional(),
+ })
+ .superRefine((layout, ctx) => {
+ if (
+ layout.minW !== undefined &&
+ layout.maxW !== undefined &&
+ layout.maxW < layout.minW
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['maxW'],
+ message: 'maxW must be greater than or equal to minW',
+ });
+ }
+ if (layout.minW !== undefined && layout.minW > layout.w) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['minW'],
+ message: 'minW must be less than or equal to w',
+ });
+ }
+ if (layout.maxW !== undefined && layout.maxW < layout.w) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['maxW'],
+ message: 'maxW must be greater than or equal to w',
+ });
+ }
+ if (
+ layout.minH !== undefined &&
+ layout.maxH !== undefined &&
+ layout.maxH < layout.minH
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['maxH'],
+ message: 'maxH must be greater than or equal to minH',
+ });
+ }
+ if (layout.minH !== undefined && layout.minH > layout.h) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['minH'],
+ message: 'minH must be less than or equal to h',
+ });
+ }
+ if (layout.maxH !== undefined && layout.maxH < layout.h) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['maxH'],
+ message: 'maxH must be greater than or equal to h',
+ });
+ }
+ });
function isValidDateOnly(value: unknown): value is string {
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
@@ -116,14 +118,24 @@ function isValidDateOnly(value: unknown): value is string {
}
const date = new Date(`${value}T00:00:00.000Z`);
- return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
+ return (
+ !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value
+ );
}
-function dashboardUrl(organizationId: string, projectId: string, dashboardId: string) {
+function dashboardUrl(
+ organizationId: string,
+ projectId: string,
+ dashboardId: string
+) {
return `${dashboardBaseUrl()}/${organizationId}/${projectId}/dashboards/${dashboardId}`;
}
-function reportUrl(organizationId: string, projectId: string, reportId: string) {
+function reportUrl(
+ organizationId: string,
+ projectId: string,
+ reportId: string
+) {
return `${dashboardBaseUrl()}/${organizationId}/${projectId}/reports/${reportId}`;
}
@@ -176,7 +188,7 @@ function withDashboardUrl(
organizationId: string;
createdAt: Date;
updatedAt: Date;
- },
+ }
) {
// Explicit fields: getDashboardById includes the full project row, which is
// more than this tool should hand back.
@@ -194,7 +206,7 @@ function withDashboardUrl(
function withReportUrl(
organizationId: string,
projectId: string,
- report: { id: string },
+ report: { id: string }
) {
return {
...report,
@@ -243,7 +255,7 @@ function canonicalReportConfig(report: {
export function registerDashboardManagementTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'get_dashboard',
@@ -264,17 +276,25 @@ export function registerDashboardManagementTools(
id: report.id,
report: canonicalReportConfig(report),
layout: report.layout,
- dashboard_url: reportUrl(context.organizationId, projectId, report.id),
+ dashboard_url: reportUrl(
+ context.organizationId,
+ projectId,
+ report.id
+ ),
}));
return {
- dashboard: withDashboardUrl(context.organizationId, projectId, dashboard),
+ dashboard: withDashboardUrl(
+ context.organizationId,
+ projectId,
+ dashboard
+ ),
reports: reportsWithUrls,
layouts: reportsWithUrls.flatMap((report) =>
- report.layout ? [report.layout] : [],
+ report.layout ? [report.layout] : []
),
};
- }),
+ })
);
if (context.clientType !== 'root') {
@@ -306,11 +326,15 @@ export function registerDashboardManagementTools(
});
return {
- dashboard: withDashboardUrl(context.organizationId, projectId, dashboard),
+ dashboard: withDashboardUrl(
+ context.organizationId,
+ projectId,
+ dashboard
+ ),
reports: [],
layouts: [],
};
- }),
+ })
);
server.tool(
@@ -331,9 +355,13 @@ export function registerDashboardManagementTools(
});
return {
- dashboard: withDashboardUrl(context.organizationId, projectId, dashboard),
+ dashboard: withDashboardUrl(
+ context.organizationId,
+ projectId,
+ dashboard
+ ),
};
- }),
+ })
);
server.tool(
@@ -366,7 +394,9 @@ export function registerDashboardManagementTools(
select: { id: true },
});
if (reports.length > 0 && !forceDelete) {
- throw new Error('Cannot delete dashboard with associated reports');
+ throw new Error(
+ 'Cannot delete dashboard with associated reports'
+ );
}
if (forceDelete && reports.length > 0) {
@@ -400,9 +430,13 @@ export function registerDashboardManagementTools(
return {
deleted: true,
- dashboard: withDashboardUrl(context.organizationId, projectId, dashboard),
+ dashboard: withDashboardUrl(
+ context.organizationId,
+ projectId,
+ dashboard
+ ),
};
- }),
+ })
);
server.tool(
@@ -428,7 +462,7 @@ export function registerDashboardManagementTools(
return {
report: withReportUrl(context.organizationId, projectId, created),
};
- }),
+ })
);
server.tool(
@@ -451,7 +485,7 @@ export function registerDashboardManagementTools(
return {
report: withReportUrl(context.organizationId, projectId, updated),
};
- }),
+ })
);
server.tool(
@@ -471,7 +505,7 @@ export function registerDashboardManagementTools(
deleted: true,
report: withReportUrl(context.organizationId, projectId, deleted),
};
- }),
+ })
);
server.tool(
@@ -511,7 +545,7 @@ export function registerDashboardManagementTools(
return {
report: withReportUrl(context.organizationId, projectId, duplicate),
};
- }),
+ })
);
server.tool(
@@ -519,7 +553,10 @@ export function registerDashboardManagementTools(
'Save or update the grid layout for a report in the resolved project.',
{
projectId: projectIdSchema(context),
- reportId: z.string().uuid().describe('The report ID whose layout should change'),
+ reportId: z
+ .string()
+ .uuid()
+ .describe('The report ID whose layout should change'),
layout: layoutSchema.describe('The report grid layout'),
},
async ({ projectId: inputProjectId, reportId, layout }) =>
@@ -531,7 +568,7 @@ export function registerDashboardManagementTools(
create: { reportId, ...layout },
update: layout,
});
- }),
+ })
);
server.tool(
@@ -539,7 +576,9 @@ export function registerDashboardManagementTools(
'Delete all saved report layouts in a dashboard after binding it to the resolved project.',
{
projectId: projectIdSchema(context),
- dashboardId: z.string().describe('The dashboard whose layouts should reset'),
+ dashboardId: z
+ .string()
+ .describe('The dashboard whose layouts should reset'),
},
async ({ projectId: inputProjectId, dashboardId }) =>
withErrorHandling(async () => {
@@ -557,8 +596,12 @@ export function registerDashboardManagementTools(
return {
dashboardId,
count: result.count,
- dashboard_url: dashboardUrl(context.organizationId, projectId, dashboardId),
+ dashboard_url: dashboardUrl(
+ context.organizationId,
+ projectId,
+ dashboardId
+ ),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/gsc/cannibalization.ts b/packages/core/src/modules/mcp/src/tools/gsc/cannibalization.ts
similarity index 91%
rename from packages/mcp/src/tools/gsc/cannibalization.ts
rename to packages/core/src/modules/mcp/src/tools/gsc/cannibalization.ts
index a397b4d59..28964b882 100644
--- a/packages/mcp/src/tools/gsc/cannibalization.ts
+++ b/packages/core/src/modules/mcp/src/tools/gsc/cannibalization.ts
@@ -21,7 +21,13 @@ const DEFAULT_QUERY_LIMIT = 25;
const MAX_QUERY_LIMIT = 50;
/** Column order for the nested per-page tuples, declared once for the response. */
-const PAGE_COLUMNS = ['page', 'clicks', 'impressions', 'ctr', 'position'] as const;
+const PAGE_COLUMNS = [
+ 'page',
+ 'clicks',
+ 'impressions',
+ 'ctr',
+ 'position',
+] as const;
export function registerGscCannibalizationTools(
server: McpServer,
@@ -65,7 +71,13 @@ export function registerGscCannibalizationTools(
page_columns: PAGE_COLUMNS,
...table(shaped, {
limit: limit ?? DEFAULT_QUERY_LIMIT,
- columns: ['query', 'totalImpressions', 'totalClicks', 'page_count', 'pages'],
+ columns: [
+ 'query',
+ 'totalImpressions',
+ 'totalClicks',
+ 'page_count',
+ 'pages',
+ ],
sum: ['totalImpressions', 'totalClicks'],
sortedBy: 'totalImpressions',
unit: 'queries',
diff --git a/packages/mcp/src/tools/gsc/overview.ts b/packages/core/src/modules/mcp/src/tools/gsc/overview.ts
similarity index 99%
rename from packages/mcp/src/tools/gsc/overview.ts
rename to packages/core/src/modules/mcp/src/tools/gsc/overview.ts
index ec2eed586..4d0c2778c 100644
--- a/packages/mcp/src/tools/gsc/overview.ts
+++ b/packages/core/src/modules/mcp/src/tools/gsc/overview.ts
@@ -34,7 +34,7 @@ export function registerGscOverviewTools(
.default(true)
.optional()
.describe(
- 'Set false to get only the summary totals and skip the per-interval series.',
+ 'Set false to get only the summary totals and skip the per-interval series.'
),
},
async ({
diff --git a/packages/mcp/src/tools/gsc/pages.ts b/packages/core/src/modules/mcp/src/tools/gsc/pages.ts
similarity index 84%
rename from packages/mcp/src/tools/gsc/pages.ts
rename to packages/core/src/modules/mcp/src/tools/gsc/pages.ts
index 5efe6aab2..a089604b6 100644
--- a/packages/mcp/src/tools/gsc/pages.ts
+++ b/packages/core/src/modules/mcp/src/tools/gsc/pages.ts
@@ -1,5 +1,5 @@
-import { getGscPageDetails, getGscPages } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { getGscPageDetails, getGscPages } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -25,7 +25,7 @@ const GSC_ADDITIVE = ['clicks', 'impressions'] as const;
export function registerGscPageTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'gsc_get_top_pages',
@@ -42,7 +42,12 @@ export function registerGscPageTools(
const take = limit ?? DEFAULT_GSC_LIMIT;
// Fetch the full ranked set (capped) so the tail can be rolled up
// rather than silently cut — GSC totals are the whole point here.
- const pages = await getGscPages(projectId, startDate, endDate, MAX_GSC_LIMIT);
+ const pages = await getGscPages(
+ projectId,
+ startDate,
+ endDate,
+ MAX_GSC_LIMIT
+ );
return table(pages, {
limit: take,
columns: ['page', 'clicks', 'impressions', 'ctr', 'position'],
@@ -50,7 +55,7 @@ export function registerGscPageTools(
sortedBy: 'clicks',
unit: 'pages',
});
- }),
+ })
);
server.tool(
@@ -62,14 +67,27 @@ export function registerGscPageTools(
page: z
.string()
.url()
- .describe('The full page URL to get details for (e.g. https://example.com/blog/post)'),
+ .describe(
+ 'The full page URL to get details for (e.g. https://example.com/blog/post)'
+ ),
limit: zLimit(DEFAULT_DETAIL_QUERIES, MAX_GSC_LIMIT),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, page, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ page,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
- const details = await getGscPageDetails(projectId, page, startDate, endDate);
+ const details = await getGscPageDetails(
+ projectId,
+ page,
+ startDate,
+ endDate
+ );
return {
page,
timeseries: table(details.timeseries, {
@@ -86,6 +104,6 @@ export function registerGscPageTools(
unit: 'queries',
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/gsc/queries.ts b/packages/core/src/modules/mcp/src/tools/gsc/queries.ts
similarity index 78%
rename from packages/mcp/src/tools/gsc/queries.ts
rename to packages/core/src/modules/mcp/src/tools/gsc/queries.ts
index 979af3af3..70d68a618 100644
--- a/packages/mcp/src/tools/gsc/queries.ts
+++ b/packages/core/src/modules/mcp/src/tools/gsc/queries.ts
@@ -1,6 +1,6 @@
-import { getGscQueryDetails, getGscQueries } from '@openpanel/db';
-import type { GscQueryOpportunity } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import type { GscQueryOpportunity } from '@openpanel/db';
+import { getGscQueries, getGscQueryDetails } from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import {
@@ -31,7 +31,7 @@ function computeOpportunities(
ctr: number;
position: number;
}>,
- limit: number,
+ limit: number
): GscQueryOpportunity[] {
const ctrBenchmarks: Record<string, number> = {
'1': 0.28,
@@ -43,11 +43,21 @@ function computeOpportunities(
};
function getBenchmark(position: number): number {
- if (position <= 1) return ctrBenchmarks['1'] ?? 0.28;
- if (position <= 2) return ctrBenchmarks['2'] ?? 0.15;
- if (position <= 3) return ctrBenchmarks['3'] ?? 0.11;
- if (position <= 6) return ctrBenchmarks['4-6'] ?? 0.065;
- if (position <= 10) return ctrBenchmarks['7-10'] ?? 0.035;
+ if (position <= 1) {
+ return ctrBenchmarks['1'] ?? 0.28;
+ }
+ if (position <= 2) {
+ return ctrBenchmarks['2'] ?? 0.15;
+ }
+ if (position <= 3) {
+ return ctrBenchmarks['3'] ?? 0.11;
+ }
+ if (position <= 6) {
+ return ctrBenchmarks['4-6'] ?? 0.065;
+ }
+ if (position <= 10) {
+ return ctrBenchmarks['7-10'] ?? 0.035;
+ }
return ctrBenchmarks['11-20'] ?? 0.012;
}
@@ -57,8 +67,7 @@ function computeOpportunities(
const benchmark = getBenchmark(q.position);
const ctrGap = Math.max(0, benchmark - q.ctr);
const opportunity_score =
- Math.round(q.impressions * (1 / q.position) * (1 + ctrGap) * 100) /
- 100;
+ Math.round(q.impressions * (1 / q.position) * (1 + ctrGap) * 100) / 100;
let reason: string;
if (q.position <= 6) {
@@ -73,7 +82,7 @@ function computeOpportunities(
query: q.query,
clicks: q.clicks,
impressions: q.impressions,
- ctr: Math.round(q.ctr * 10000) / 100,
+ ctr: Math.round(q.ctr * 10_000) / 100,
position: Math.round(q.position * 10) / 10,
opportunity_score,
reason,
@@ -85,7 +94,7 @@ function computeOpportunities(
export function registerGscQueryTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'gsc_get_top_queries',
@@ -101,7 +110,12 @@ export function registerGscQueryTools(
const { startDate, endDate } = resolveDateRange(sd, ed);
// Fetch the full ranked set (capped) so the tail can be rolled up
// rather than silently cut.
- const queries = await getGscQueries(projectId, startDate, endDate, MAX_GSC_LIMIT);
+ const queries = await getGscQueries(
+ projectId,
+ startDate,
+ endDate,
+ MAX_GSC_LIMIT
+ );
return table(queries, {
limit: limit ?? DEFAULT_GSC_LIMIT,
columns: ['query', 'clicks', 'impressions', 'ctr', 'position'],
@@ -109,7 +123,7 @@ export function registerGscQueryTools(
sortedBy: 'clicks',
unit: 'queries',
});
- }),
+ })
);
server.tool(
@@ -124,18 +138,29 @@ export function registerGscQueryTools(
.default(50)
.optional()
.describe(
- 'Minimum impression threshold to filter out low-volume queries (default: 50)',
+ 'Minimum impression threshold to filter out low-volume queries (default: 50)'
),
limit: zLimit(DEFAULT_OPPORTUNITY_LIMIT, MAX_OPPORTUNITY_LIMIT),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, minImpressions, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ minImpressions,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
const take = limit ?? DEFAULT_OPPORTUNITY_LIMIT;
- const queries = await getGscQueries(projectId, startDate, endDate, 5000);
+ const queries = await getGscQueries(
+ projectId,
+ startDate,
+ endDate,
+ 5000
+ );
const filtered = queries.filter(
- (q) => q.impressions >= (minImpressions ?? 50),
+ (q) => q.impressions >= (minImpressions ?? 50)
);
// Compute one past the limit so the table can flag that more exist.
const opportunities = computeOpportunities(filtered, take + 1);
@@ -144,13 +169,21 @@ export function registerGscQueryTools(
min_impressions: minImpressions ?? 50,
...table(opportunities.slice(0, take), {
limit: take,
- columns: ['query', 'clicks', 'impressions', 'ctr', 'position', 'opportunity_score', 'reason'],
+ columns: [
+ 'query',
+ 'clicks',
+ 'impressions',
+ 'ctr',
+ 'position',
+ 'opportunity_score',
+ 'reason',
+ ],
sortedBy: 'opportunity_score',
unit: 'opportunities',
moreAvailable: opportunities.length > take,
}),
};
- }),
+ })
);
server.tool(
@@ -161,14 +194,27 @@ export function registerGscQueryTools(
...zDateRange,
query: z
.string()
- .describe('The search query to get details for (e.g. "best analytics tools")'),
+ .describe(
+ 'The search query to get details for (e.g. "best analytics tools")'
+ ),
limit: zLimit(DEFAULT_DETAIL_PAGES, MAX_GSC_LIMIT),
},
- async ({ projectId: inputProjectId, startDate: sd, endDate: ed, query, limit }) =>
+ async ({
+ projectId: inputProjectId,
+ startDate: sd,
+ endDate: ed,
+ query,
+ limit,
+ }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
const { startDate, endDate } = resolveDateRange(sd, ed);
- const details = await getGscQueryDetails(projectId, query, startDate, endDate);
+ const details = await getGscQueryDetails(
+ projectId,
+ query,
+ startDate,
+ endDate
+ );
return {
query,
timeseries: table(details.timeseries, {
@@ -185,6 +231,6 @@ export function registerGscQueryTools(
unit: 'pages',
}),
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/index.ts b/packages/core/src/modules/mcp/src/tools/index.ts
similarity index 97%
rename from packages/mcp/src/tools/index.ts
rename to packages/core/src/modules/mcp/src/tools/index.ts
index 6a879e596..531a12aa9 100644
--- a/packages/mcp/src/tools/index.ts
+++ b/packages/core/src/modules/mcp/src/tools/index.ts
@@ -1,4 +1,3 @@
-import { resolveClientProjectId } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { McpAuthContext } from '../auth';
import { registerActiveUserTools } from './analytics/active-users';
@@ -19,17 +18,17 @@ import { registerRetentionTools } from './analytics/retention';
import { registerSessionTools } from './analytics/sessions';
import { registerTrafficTools } from './analytics/traffic';
import { registerUserFlowTools } from './analytics/user-flow';
+import { registerDashboardLinkTools } from './dashboard-links';
+import { registerDashboardManagementTools } from './dashboard-management';
import { registerGscCannibalizationTools } from './gsc/cannibalization';
import { registerGscOverviewTools } from './gsc/overview';
import { registerGscPageTools } from './gsc/pages';
import { registerGscQueryTools } from './gsc/queries';
-import { registerDashboardLinkTools } from './dashboard-links';
-import { registerDashboardManagementTools } from './dashboard-management';
import { registerProjectTools } from './projects';
export function registerAllTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
): void {
// Project access — always call first to discover available projects
registerProjectTools(server, context);
diff --git a/packages/mcp/src/tools/projects.ts b/packages/core/src/modules/mcp/src/tools/projects.ts
similarity index 97%
rename from packages/mcp/src/tools/projects.ts
rename to packages/core/src/modules/mcp/src/tools/projects.ts
index c21110865..ce95a430d 100644
--- a/packages/mcp/src/tools/projects.ts
+++ b/packages/core/src/modules/mcp/src/tools/projects.ts
@@ -1,11 +1,11 @@
-import { db } from '@openpanel/db';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { db } from '@openpanel/db';
import type { McpAuthContext } from '../auth';
import { withErrorHandling } from './shared';
export function registerProjectTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'list_projects',
@@ -49,6 +49,6 @@ export function registerProjectTools(
clientType: 'read',
projects: project ? [project] : [],
};
- }),
+ })
);
}
diff --git a/packages/mcp/src/tools/shared.test.ts b/packages/core/src/modules/mcp/src/tools/shared.test.ts
similarity index 84%
rename from packages/mcp/src/tools/shared.test.ts
rename to packages/core/src/modules/mcp/src/tools/shared.test.ts
index 6414b87a5..60db42798 100644
--- a/packages/mcp/src/tools/shared.test.ts
+++ b/packages/core/src/modules/mcp/src/tools/shared.test.ts
@@ -1,5 +1,12 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ setSystemTime,
+} from 'bun:test';
import { resolveClientProjectId } from '@openpanel/db';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { McpAuthContext } from '../auth';
import { MAX_RESPONSE_CHARS, resolveDateRange, table, toText } from './shared';
@@ -17,12 +24,11 @@ const ROOT_CTX: McpAuthContext = {
describe('resolveDateRange', () => {
beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2024-03-15T12:00:00.000Z'));
+ setSystemTime(new Date('2024-03-15T12:00:00.000Z'));
});
afterEach(() => {
- vi.useRealTimers();
+ setSystemTime();
});
it('passes through explicit dates unchanged', () => {
@@ -49,27 +55,33 @@ describe('resolveDateRange', () => {
describe('resolveClientProjectId', () => {
it('returns the context projectId for read clients, ignoring any input', async () => {
- await expect(resolveClientProjectId({
- clientType: READ_CTX.clientType,
- clientProjectId: READ_CTX.projectId,
- organizationId: READ_CTX.organizationId,
- inputProjectId: undefined,
- })).resolves.toBe('proj-abc');
- await expect(resolveClientProjectId({
- clientType: READ_CTX.clientType,
- clientProjectId: READ_CTX.projectId,
- organizationId: READ_CTX.organizationId,
- inputProjectId: 'other-proj',
- })).resolves.toBe('proj-abc');
+ await expect(
+ resolveClientProjectId({
+ clientType: READ_CTX.clientType,
+ clientProjectId: READ_CTX.projectId,
+ organizationId: READ_CTX.organizationId,
+ inputProjectId: undefined,
+ })
+ ).resolves.toBe('proj-abc');
+ await expect(
+ resolveClientProjectId({
+ clientType: READ_CTX.clientType,
+ clientProjectId: READ_CTX.projectId,
+ organizationId: READ_CTX.organizationId,
+ inputProjectId: 'other-proj',
+ })
+ ).resolves.toBe('proj-abc');
});
it('throws for root clients when no projectId is provided', async () => {
- await expect(resolveClientProjectId({
- clientType: ROOT_CTX.clientType,
- clientProjectId: ROOT_CTX.projectId,
- organizationId: ROOT_CTX.organizationId,
- inputProjectId: undefined,
- })).rejects.toThrow('projectId is required');
+ await expect(
+ resolveClientProjectId({
+ clientType: ROOT_CTX.clientType,
+ clientProjectId: ROOT_CTX.projectId,
+ organizationId: ROOT_CTX.organizationId,
+ inputProjectId: undefined,
+ })
+ ).rejects.toThrow('projectId is required');
});
});
@@ -131,7 +143,11 @@ describe('table', () => {
});
it('warns that a SQL-capped result is not the full set', () => {
- const result = table(rows, { limit: 4, unit: 'pages', moreAvailable: true });
+ const result = table(rows, {
+ limit: 4,
+ unit: 'pages',
+ moreAvailable: true,
+ });
expect(result.rows).toHaveLength(4);
expect(result.note).toContain('capped query');
});
diff --git a/packages/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.ts
similarity index 99%
rename from packages/mcp/src/tools/shared.ts
rename to packages/core/src/modules/mcp/src/tools/shared.ts
index 15f0bc4cc..ef8cf0513 100644
--- a/packages/mcp/src/tools/shared.ts
+++ b/packages/core/src/modules/mcp/src/tools/shared.ts
@@ -1,6 +1,6 @@
-import { createLogger } from '@openpanel/core';
import { resolveClientProjectId } from '@openpanel/db';
import { z } from 'zod';
+import { createLogger } from '../../../../clients/logger';
import type { McpAuthContext } from '../auth';
const logger = createLogger({ name: 'mcp' });
diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.ts
index 4b1ec6960..874fc00a8 100644
--- a/packages/core/src/rest.routes.ts
+++ b/packages/core/src/rest.routes.ts
@@ -12,6 +12,7 @@ import { assistantRoutes } from './modules/assistant/assistant.routes';
import { gscRoutes } from './modules/gsc/gsc.routes';
import { healthRoutes } from './modules/health/health.routes';
import { importRoutes } from './modules/import/import.routes';
+import { mcpRoutes } from './modules/mcp/mcp.routes';
// ADR-002/ADR-003 pin: @elysiajs/openapi at the 1.4.15 fallback (2.0 is
// NO-GO per spike 6). `specPath` is set explicitly rather than taking the
@@ -35,13 +36,17 @@ export const publicApiRoutes = (deps: AppDeps) =>
new Elysia({ name: 'core/public-api-routes' }).use(importRoutes(deps));
// gsc's callback was the first module to land here (M5-002); assistant's
-// `/ai/agents/*` (M5-005) joined it. Neither is reachable in production yet:
-// main.ts only mounts `dashboardRoutes` once a real `AppDeps` exists
-// (P3/P4/P8) — see each module's own routes.ts header for its named gap.
+// `/ai/agents/*` (M5-005) and mcp's `/mcp` (M5-007) joined it. None is
+// reachable in production yet: main.ts only mounts `dashboardRoutes` once a
+// real `AppDeps` exists (P3/P4/P8) — see each module's own routes.ts header
+// for its named gap. `/gsc` and `/mcp` are dashboard-scope routes absent from
+// the CORS delegator's `corsPaths` allowlist (ADR-002 rule 4) — a quirk to
+// port verbatim when app.ts wires CORS, not something to fix here.
export const dashboardRoutes = (deps: AppDeps) =>
new Elysia({ name: 'core/dashboard-routes' })
.use(gscRoutes(deps))
- .use(assistantRoutes(deps));
+ .use(assistantRoutes(deps))
+ .use(mcpRoutes(deps));
// healthz/metrics/misc share V1's ops surface (http/context.ts's
// UNLOGGED_PATH_PREFIXES) — unauthenticated, uncorsed, unlogged. /metrics and
diff --git a/packages/core/src/shared/encryption.test.ts b/packages/core/src/shared/encryption.test.ts
index 665784e14..1a7bc833e 100644
--- a/packages/core/src/shared/encryption.test.ts
+++ b/packages/core/src/shared/encryption.test.ts
@@ -44,4 +44,18 @@ describe('encryption (single ENCRYPTION_KEY)', () => {
expect(decrypt(encrypt(secret))).toBe(secret);
expect(decryptCredential(encryptCredential(secret))).toBe(secret);
});
+
+ it('decrypt throws a guarded error for a too-short/malformed ciphertext', () => {
+ // Shorter than IV_LENGTH + AUTH_TAG_LENGTH: the tag slice comes back
+ // empty. Bun's setAuthTag validates the length up front and throws a
+ // bare TypeError before this guard existed; the guard normalizes that
+ // to the same descriptive error on both runtimes.
+ const tooShort = Buffer.from('short').toString('base64');
+ expect(() => decrypt(tooShort)).toThrow(
+ 'Invalid encrypted value: expected a 16-byte auth tag, got 0'
+ );
+ expect(() => decrypt('')).toThrow(
+ 'Invalid encrypted value: expected a 16-byte auth tag, got 0'
+ );
+ });
});
diff --git a/packages/core/src/shared/encryption.ts b/packages/core/src/shared/encryption.ts
index fe3140b46..3865d1b0c 100644
--- a/packages/core/src/shared/encryption.ts
+++ b/packages/core/src/shared/encryption.ts
@@ -51,6 +51,14 @@ export function decrypt(ciphertext: string): string {
const iv = buf.subarray(0, IV_LENGTH);
const tag = buf.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH);
const encrypted = buf.subarray(IV_LENGTH + AUTH_TAG_LENGTH);
+ // Bun's setAuthTag validates the tag length up front (Node defers to
+ // final()), so a too-short/malformed ciphertext needs an explicit guard
+ // here to produce the same "malformed input" failure on both runtimes.
+ if (tag.length !== AUTH_TAG_LENGTH) {
+ throw new Error(
+ `Invalid encrypted value: expected a ${AUTH_TAG_LENGTH}-byte auth tag, got ${tag.length}`
+ );
+ }
const decipher = createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(tag);
// Concatenate first, decode once: GCM is a stream cipher, so update() can end
diff --git a/packages/mcp/index.ts b/packages/mcp/index.ts
deleted file mode 100644
index 74f3b3572..000000000
--- a/packages/mcp/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export { createMcpServer } from './src/server';
-export { SessionManager } from './src/session-manager';
-export { authenticateToken, McpAuthError, extractToken } from './src/auth';
-export { handleMcpGet, handleMcpPost } from './src/handler';
-export type { McpAuthContext } from './src/auth';
-
-// Reusable handler logic for the in-app chat (apps/api/src/chat/tools/).
-// These are pure functions, transport-agnostic — they don't touch MCP at all.
-export { runReport, runReportFromConfig } from './src/tools/analytics/reports';
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
deleted file mode 100644
index e0ccabe47..000000000
--- a/packages/mcp/package.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "name": "@openpanel/mcp",
- "version": "0.0.1",
- "type": "module",
- "main": "index.ts",
- "exports": {
- ".": "./index.ts"
- },
- "scripts": {
- "typecheck": "tsc --noEmit",
- "test": "vitest",
- "test:run": "vitest run"
- },
- "dependencies": {
- "@modelcontextprotocol/sdk": "^1.12.0",
- "@openpanel/common": "workspace:*",
- "@openpanel/core": "workspace:*",
- "@openpanel/db": "workspace:*",
- "@openpanel/redis": "workspace:*",
- "@openpanel/validation": "workspace:*",
- "zod": "catalog:"
- },
- "devDependencies": {
- "@openpanel/tsconfig": "workspace:*",
- "@types/node": "catalog:",
- "typescript": "catalog:",
- "vitest": "^1.0.0"
- }
-}
diff --git a/packages/mcp/src/handler.ts b/packages/mcp/src/handler.ts
deleted file mode 100644
index 9c609325d..000000000
--- a/packages/mcp/src/handler.ts
+++ /dev/null
@@ -1,225 +0,0 @@
-import type { IncomingMessage, ServerResponse } from 'node:http';
-import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
-import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
-import { createLogger } from '@openpanel/core';
-import { authenticateToken, extractToken, McpAuthError } from './auth';
-import { createMcpServer } from './server';
-import type { SessionManager } from './session-manager';
-
-const logger = createLogger({ name: 'mcp:handler' });
-
-const MCP_PROTOCOL_VERSION = '2024-11-05';
-
-/**
- * Handle a POST /mcp request.
- *
- * Fully stateless: each request creates a fresh McpServer driven by InMemoryTransport.
- * Auth context is the only thing persisted — stored in Redis by session ID.
- * Works across any number of API instances with no sticky-session requirement.
- *
- * - No session ID: authenticate + must be an `initialize` request → create session in Redis.
- * - Session ID found in Redis: look up context, process request on a fresh server.
- * - Session ID not in Redis: 404 → client reinitializes.
- */
-export async function handleMcpPost(
- sessionManager: SessionManager,
- req: IncomingMessage,
- res: ServerResponse,
- body: unknown,
- query: Record<string, unknown>
-): Promise<void> {
- const sessionId = req.headers['mcp-session-id'] as string | undefined;
- const message = body as JSONRPCMessage;
-
- logger.info(
- {
- sessionId: sessionId ?? 'new',
- method: 'method' in message ? message.method : 'unknown',
- hasAuth: !!(query['token'] || req.headers.authorization),
- },
- 'MCP POST request'
- );
-
- if (sessionId) {
- const context = await sessionManager.getContext(sessionId);
- if (!context) {
- logger.warn({ sessionId }, 'MCP session not found in Redis');
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(
- JSON.stringify({ error: 'Session not found — please reconnect' })
- );
- return;
- }
-
- await sessionManager.touchContext(sessionId);
-
- // Notifications have no `id` and expect no response
- if (!('id' in message)) {
- res.writeHead(202);
- res.end();
- return;
- }
-
- try {
- const response = await processRequest(context, message);
- res.writeHead(200, {
- 'Content-Type': 'application/json',
- 'Mcp-Session-Id': sessionId,
- });
- res.end(JSON.stringify(response));
- } catch (err) {
- logger.error({ err, sessionId }, 'MCP request processing error');
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Internal server error' }));
- }
- return;
- }
-
- // New connection — authenticate and expect `initialize`
- const token = extractToken(query, req.headers.authorization);
-
- try {
- const context = await authenticateToken(token);
-
- if (!('method' in message) || message.method !== 'initialize') {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'First request must be initialize' }));
- return;
- }
-
- const response = await processRequest(context, message, true);
- const newSessionId = sessionManager.generateId();
- await sessionManager.setContext(newSessionId, context);
-
- logger.info(
- {
- sessionId: newSessionId,
- clientType: context.clientType,
- organizationId: context.organizationId,
- projectId: context.projectId,
- },
- 'MCP session created'
- );
-
- res.writeHead(200, {
- 'Content-Type': 'application/json',
- 'Mcp-Session-Id': newSessionId,
- });
- res.end(JSON.stringify(response));
- } catch (err) {
- if (err instanceof McpAuthError) {
- logger.warn({ reason: err.message }, 'MCP auth failed');
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: err.message }));
- } else {
- logger.error({ err }, 'MCP session creation error');
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Internal server error' }));
- }
- }
-}
-
-/**
- * Create a fresh McpServer for each request and process a single JSON-RPC message.
- *
- * For non-initialize requests we fast-forward the server through the MCP
- * initialization handshake (using an internal fake initialize) before dispatching
- * the real message. This keeps the handler stateless while satisfying the SDK's
- * internal state machine.
- */
-async function processRequest(
- context: Parameters<typeof createMcpServer>[0],
- message: JSONRPCMessage,
- isInitialize = false
-): Promise<JSONRPCMessage> {
- if (
- 'method' in message &&
- message.method === 'tools/call' &&
- 'params' in message
- ) {
- const { name, arguments: args } = (message.params ?? {}) as {
- name?: string;
- arguments?: unknown;
- };
- logger.info(
- {
- tool: name,
- params: args,
- organizationId: context.organizationId,
- projectId: context.projectId,
- clientType: context.clientType,
- },
- 'MCP tool call'
- );
- }
- const [clientTransport, serverTransport] =
- InMemoryTransport.createLinkedPair();
- const server = createMcpServer(context);
- await server.connect(serverTransport);
-
- if (!isInitialize) {
- // Fast-forward: send a fake initialize so the server enters its ready state
- await new Promise<void>((resolve, reject) => {
- clientTransport.onmessage = () => resolve();
- clientTransport
- .send({
- jsonrpc: '2.0',
- id: '__mcp_init__',
- method: 'initialize',
- params: {
- protocolVersion: MCP_PROTOCOL_VERSION,
- capabilities: {},
- clientInfo: { name: 'mcp-proxy', version: '0' },
- },
- })
- .catch(reject);
- });
- // Notify the server that initialization is complete (no response expected)
- await clientTransport.send({
- jsonrpc: '2.0',
- method: 'notifications/initialized',
- });
- }
-
- const start = Date.now();
- const response = await new Promise<JSONRPCMessage>((resolve, reject) => {
- clientTransport.onmessage = resolve;
- clientTransport.send(message).catch(reject);
- });
-
- if ('method' in message && message.method === 'tools/call') {
- const { name } = (('params' in message && message.params) ?? {}) as {
- name?: string;
- };
- const isError =
- 'result' in response &&
- (response.result as { isError?: boolean })?.isError;
- logger.info(
- {
- tool: name,
- durationMs: Date.now() - start,
- isError: isError ?? false,
- },
- 'MCP tool result'
- );
- }
-
- return response;
-}
-
-/**
- * SSE is not supported in stateless mode — all communication happens over POST.
- */
-export async function handleMcpGet(
- _sessionManager: SessionManager,
- _req: IncomingMessage,
- res: ServerResponse
-): Promise<void> {
- res.writeHead(405, {
- 'Content-Type': 'application/json',
- Allow: 'POST, DELETE',
- });
- res.end(
- JSON.stringify({ error: 'SSE not supported — use POST for all requests' })
- );
-}
diff --git a/packages/mcp/src/session-manager.test.ts b/packages/mcp/src/session-manager.test.ts
deleted file mode 100644
index 91374b471..000000000
--- a/packages/mcp/src/session-manager.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { McpAuthContext } from './auth';
-
-const mockSetJson = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const mockGetJson = vi.hoisted(() => vi.fn());
-const mockExpire = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const mockDel = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-
-vi.mock('@openpanel/redis', () => ({
- getRedisCache: () => ({
- setJson: mockSetJson,
- getJson: mockGetJson,
- expire: mockExpire,
- del: mockDel,
- }),
-}));
-
-vi.mock('@openpanel/core', () => ({
- createLogger: () => ({
- info: vi.fn(),
- warn: vi.fn(),
- error: vi.fn(),
- }),
-}));
-
-import { SessionManager } from './session-manager';
-
-const CTX: McpAuthContext = {
- projectId: 'proj-1',
- organizationId: 'org-1',
- clientType: 'read',
-};
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('SessionManager', () => {
- describe('generateId', () => {
- it('generates unique UUIDs', () => {
- const sm = new SessionManager();
- const a = sm.generateId();
- const b = sm.generateId();
- expect(a).not.toBe(b);
- expect(a).toMatch(/^[0-9a-f-]{36}$/);
- });
- });
-
- describe('context (Redis)', () => {
- it('stores context in Redis with TTL', async () => {
- const sm = new SessionManager();
- await sm.setContext('sess-1', CTX);
- expect(mockSetJson).toHaveBeenCalledWith(
- 'mcp:session:sess-1',
- 30 * 60,
- CTX
- );
- });
-
- it('retrieves context from Redis', async () => {
- const sm = new SessionManager();
- mockGetJson.mockResolvedValue(CTX);
- const result = await sm.getContext('sess-1');
- expect(result).toEqual(CTX);
- expect(mockGetJson).toHaveBeenCalledWith('mcp:session:sess-1');
- });
-
- it('returns null for missing session', async () => {
- const sm = new SessionManager();
- mockGetJson.mockResolvedValue(null);
- const result = await sm.getContext('missing');
- expect(result).toBeNull();
- });
-
- it('touches TTL on touchContext', async () => {
- const sm = new SessionManager();
- await sm.touchContext('sess-1');
- expect(mockExpire).toHaveBeenCalledWith('mcp:session:sess-1', 30 * 60);
- });
-
- it('deletes context from Redis', async () => {
- const sm = new SessionManager();
- await sm.deleteContext('sess-1');
- expect(mockDel).toHaveBeenCalledWith('mcp:session:sess-1');
- });
- });
-
- describe('close', () => {
- it('deletes session from Redis', async () => {
- const sm = new SessionManager();
- await sm.close('sess-1');
- expect(mockDel).toHaveBeenCalledWith('mcp:session:sess-1');
- });
- });
-
- describe('destroy', () => {
- it('is a no-op (sessions are in Redis, not in-process)', async () => {
- const sm = new SessionManager();
- await expect(sm.destroy()).resolves.toBeUndefined();
- });
- });
-});
diff --git a/packages/mcp/src/session-manager.ts b/packages/mcp/src/session-manager.ts
deleted file mode 100644
index 9a986eed9..000000000
--- a/packages/mcp/src/session-manager.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { randomUUID } from 'node:crypto';
-import { createLogger } from '@openpanel/core';
-import { getRedisCache } from '@openpanel/redis';
-import type { McpAuthContext } from './auth';
-
-const logger = createLogger({ name: 'mcp:sessions' });
-
-const SESSION_TTL_SECONDS = 30 * 60; // 30 minutes
-
-function redisKey(id: string) {
- return `mcp:session:${id}`;
-}
-
-/**
- * Stateless session manager — auth context lives only in Redis.
- *
- * No in-process state: any API instance can handle any request for any session.
- * No sticky sessions required.
- */
-export class SessionManager {
- generateId(): string {
- return randomUUID();
- }
-
- async setContext(id: string, context: McpAuthContext): Promise<void> {
- await getRedisCache().setJson(redisKey(id), SESSION_TTL_SECONDS, context);
- logger.info(
- {
- sessionId: id,
- clientType: context.clientType,
- organizationId: context.organizationId,
- projectId: context.projectId,
- },
- 'MCP session context stored'
- );
- }
-
- getContext(id: string): Promise<McpAuthContext | null> {
- return getRedisCache().getJson<McpAuthContext>(redisKey(id));
- }
-
- async touchContext(id: string): Promise<void> {
- await getRedisCache().expire(redisKey(id), SESSION_TTL_SECONDS);
- }
-
- async deleteContext(id: string): Promise<void> {
- await getRedisCache().del(redisKey(id));
- logger.info({ sessionId: id }, 'MCP session deleted');
- }
-
- async close(id: string): Promise<void> {
- await this.deleteContext(id);
- }
-
- async destroy(): Promise<void> {
- // No-op: sessions are in Redis, not in-process
- }
-}
diff --git a/packages/mcp/tsconfig.json b/packages/mcp/tsconfig.json
deleted file mode 100644
index 2148d7758..000000000
--- a/packages/mcp/tsconfig.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "@openpanel/tsconfig/base.json",
- "compilerOptions": {
- "baseUrl": ".",
- "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json",
- "strictNullChecks": true
- },
- "include": [".", "../../test"],
- "exclude": ["node_modules"]
-}
diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts
deleted file mode 100644
index f87a2039f..000000000
--- a/packages/mcp/vitest.config.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { getSharedVitestConfig } from '../../vitest.shared';
-
-export default getSharedVitestConfig({ __dirname });
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bf08bcfe2..35aaabe01 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -142,9 +142,6 @@ importers:
'@openpanel/json':
specifier: workspace:*
version: link:../../packages/json
- '@openpanel/mcp':
- specifier: workspace:*
- version: link:../../packages/mcp
'@openpanel/payments':
specifier: workspace:*
version: link:../../packages/payments
@@ -1105,6 +1102,9 @@ importers:
'@maxmind/geoip2-node':
specifier: ^6.1.0
version: 6.1.0
+ '@modelcontextprotocol/sdk':
+ specifier: ^1.12.0
'@node-rs/argon2':
specifier: ^2.0.2
version: 2.0.2
@@ -1389,43 +1389,6 @@ importers:
specifier: 'catalog:'
version: 5.9.3
- packages/mcp:
- dependencies:
- '@modelcontextprotocol/sdk':
- specifier: ^1.12.0
- '@openpanel/common':
- specifier: workspace:*
- version: link:../common
- '@openpanel/core':
- specifier: workspace:*
- version: link:../core
- '@openpanel/db':
- specifier: workspace:*
- version: link:../db
- '@openpanel/redis':
- specifier: workspace:*
- version: link:../redis
- '@openpanel/validation':
- specifier: workspace:*
- version: link:../validation
- zod:
- specifier: 'catalog:'
- version: 4.3.6
- devDependencies:
- '@openpanel/tsconfig':
- specifier: workspace:*
- version: link:../../tooling/typescript
- '@types/node':
- specifier: 'catalog:'
- version: 24.10.1
- typescript:
- specifier: 'catalog:'
- version: 5.9.3
- vitest:
- specifier: ^1.0.0
-
packages/payments:
dependencies:
'@polar-sh/sdk':