OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M15-003): R6/R15: createMcpServer(deps) and the same shape for the assistant tool runtime - the 'no context' paths get deps from the route that already holds them
ralph7f06335cb26d
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 45ba557aa..ee7644bb5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -205,28 +205,19 @@ export {// somewhere other than a module, which is the thing §18 forbids.export { registerDefaultMetrics } from './metrics';// Moved from apps/api/src/agents/* + packages/trpc/src/agents/filter-command.ts-// (M5-005) — apps/api's `/ai/agents/*` Fastify wrapper and packages/trpc's-// overview router call these. M10-004: `assistant.service.ts` keeps all of-// `./src/app`/`./src/run-context`/`./src/filter-command` behind its OWN-// lazy loaders now (see that file's header) — needed so `createAssistantService`-// can be registered in services.ts without constructing the whole Better-// Agent app at process boot — which is what makes a plain static re-export-// safe here too. `getChatApp`/`getChatRunContext`/`runFilterCommand` are-// one-time-per-process values, so callers resolve them once (apps/api's-// Fastify wrapper does so inside its own already-async route registration)-// and keep the reference.+// (M5-005). M15-003: the chat app, the run context and the filter command all+// take the API's `deps` now, so the barrel carries the factory and the types+// only — `assistant.routes.ts` and `overview.rpc.ts` reach them through+// `ctx.services.assistant`. `ChatApp` is the one type past `AppRouter` that+// crosses into apps/start (`src/agents/client.ts`); it stays a TYPE, so no+// value of this module reaches a browser bundle.export type {ChatApp,ChatRunContext,FilterCommandResult,RunFilterCommandInput,} from './modules/assistant/assistant.service';-export {- createAssistantService,- getChatApp,- getChatRunContext,- runFilterCommand,-} from './modules/assistant/assistant.service';+export { createAssistantService } from './modules/assistant/assistant.service';// Dissolved from @openpanel/auth (M4-007) — apps/api's OAuth callbacks call// these directly; V1's now-deleted @openpanel/trpc auth/share/user/gsc// routers did too, the same way they reached the other dissolved leaf@@ -497,6 +488,141 @@ export type {GscSite,} from './modules/gsc/gsc.service';export { getGscCannibalization } from './modules/gsc/gsc.service';+export { isShuttingDown, setShuttingDown } from './modules/health/src/shutdown';+// 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+// directly, the same way V1 reaches every other dissolved service here.+// packages/db/src/services/import.service.ts is deleted outright: nothing+// else reached it through @openpanel/db's barrel (same as cohort, M5-003).+export type {+ ImportJobProgress,+ ImportStageResult,+ ImportSteps,+ InsertRawEventsResult,+ UpdateImportStatusOptions,+} from './modules/import/import.service';+// The ingestion pipeline (M8-002). apps/api's /track controller, its three+// route hooks and the legacy /event controller are thin delegates over these+// — the same functions core's own `ingestRoutes` calls.+export type {+ BotMatch,+ BotSuspicion,+ DeviceIdentity,+ IncomingEventPayload,+ IncomingEventProducer,+ IngestAuthErrorPayload,+ IngestAuthOutcome,+ IngestBuffers,+ IngestHeaders,+ IngestTransport,+ TrackOutcome,+ TrackRequest,+} from './modules/ingest/ingest.service';+export {+ applyBotSuspicion,+ checkIngestBot,+ detectBot,+ fetchDeviceIdentity,+ getDeviceId,+ getOverrideDeviceId,+ getStringHeaders,+ getTimestamp,+ handleReplay,+ ingestTrack,+ isBot,+ isDuplicatedEvent,+ isDuplicateIngestRequest,+ stripBotProperties,+ summarizeBotSignals,+ validateIngestRequest,+} from './modules/ingest/ingest.service';+// The Kafka consumer and its per-message handler (M8-003), which take the+// kafkajs client, the topic/group names and the retry bounds as arguments —+// the injection seam that used to cross a package boundary and now just+// crosses two files.+export type {+ ConsumerLogger,+ ConsumerMetrics,+ DeadLetterMessage,+ DeadLetterReason,+ EventsBatchHandler,+ EventsBatchHandlerDeps,+ EventsConsumerDeps,+ KafkaConsumerHandle,+} from './modules/ingest/src/consumer';+export {+ createEventsBatchHandler,+ startKafkaEventsConsumer,+} from './modules/ingest/src/consumer';+export { createIncomingEventHandler } from './modules/ingest/src/consumer-handler';+// The readiness probe's two inputs (M9-002). `markEventsActivity` is the+// consumer's `onActivity`; `setShuttingDown` is main.ts's signal handler.+export {+ enableEventsHeartbeat,+ getEventsHeartbeat,+ markEventsActivity,+} from './modules/ingest/src/heartbeat';+export type {+ IncomingEventBindings,+ IncomingEventDelivery,+ IncomingEventDeps,+ IncomingEventMetrics,+ IncomingEventProject,+ IncomingEventSessions,+} from './modules/ingest/src/incoming-event-handler';+export {+ createIncomingEventDeps,+ incomingEvent,+} from './modules/ingest/src/incoming-event-handler';+export { ingestConsumerMetrics } from './modules/ingest/src/ingest.metrics';+// The Kafka transport itself (M11-003): producer, consumer factory, admin/lag+// sampling and every topic/group/retry constant, moved from+// @openpanel/queue's kafka.ts unchanged. It constructs no client at import+// time, so the barrel stays offline-importable.+export type {+ Admin,+ ConsumerGroupLag,+ EachBatchPayload,+ KafkaMessage,+ PartitionLag,+} from './modules/ingest/src/kafka';+export {+ assertKafkaConfigured,+ createKafkaAdmin,+ createKafkaEventsConsumer,+ disconnectKafka,+ KAFKA_BROKERS,+ KAFKA_CONNECTION_TIMEOUT_MS,+ KAFKA_CONSUMER_GROUP,+ KAFKA_EVENTS_DLQ_TOPIC,+ KAFKA_EVENTS_TOPIC,+ KAFKA_HANDLER_MAX_ATTEMPTS,+ KAFKA_HANDLER_RETRY_INITIAL_MS,+ KAFKA_HANDLER_RETRY_MAX_MS,+ KAFKA_HEARTBEAT_INTERVAL_MS,+ KAFKA_MAX_MESSAGES_PER_PARTITION,+ KAFKA_MAX_WAIT_MS,+ KAFKA_MIN_MESSAGES,+ KAFKA_PARTITIONS_CONCURRENT,+ KAFKA_PRODUCER_INITIAL_RETRY_MS,+ KAFKA_PRODUCER_MAX_RETRY_MS,+ KAFKA_PRODUCER_RETRIES,+ KAFKA_REQUEST_TIMEOUT_MS,+ KAFKA_SESSION_TIMEOUT_MS,+ kafkaLogger,+ produceDeadLetterEvent,+ produceIncomingEvent,+ sampleConsumerGroupLag,+} from './modules/ingest/src/kafka';+export type {+ DailyInsightCandidate,+ GetReferrerSpikesInput,+ ReferrerSpikeCluster,+ WeeklyDigestPreview,+ WeeklyDigestResult,+} from './modules/insight/insight.service';+export { explainInsight } from './modules/insight/insight.service';// Moved from packages/trpc/src/routers/integration.ts, plus the Slack OAuth// callback business logic out of// apps/api/src/controllers/webhook.controller.ts (M6-006, ADR-008's module@@ -512,19 +638,31 @@ export { SlackOAuthCallbackError } from './modules/integration/integration.servi// response, the same way it reaches slackInstaller above.export { zSlackAuthResponse } from './modules/integration/src/slack-contract';// packages/mcp absorbed whole (M5-007) — ADR-015 entry 2: stateless-only, so-// there is no SessionManager to manage. `mcp.service.ts` keeps its own-// tool tree (`./src/server`) behind a lazy loader (M10-004, see that file's-// header), which is what makes THIS a safe static export now — unlike the-// `getChatApp`-style TDZ hazard this barrel used to route around here.+// there is no SessionManager to manage. M15-003: the barrel carries the+// factory and the two types only. `handleStatelessMcpRequest` needs the+// API's `deps`, so the app shell reaches MCP the one way it ever did —+// `rest.routes.ts`'s `.use(mcpRoutes(deps))` and `ctx.services.mcp`.export type {McpAuthContext,McpHttpResult,} from './modules/mcp/mcp.service';+export { createMcpService } from './modules/mcp/mcp.service';+// Ported from apps/api's misc controller + apps/worker's cron.ping.ts (M7-008)+// — apps/api's misc controller and the worker's ping cron job call these+// directly, the same way V1 reaches every other dissolved service here.+// `GET /misc/og/clear` and `/misc/favicon/clear` are NOT ported (ADR-015+// entry #6: RULED + DEAD).+export type {+ GeoReport,+ ImageAssetResult,+ PingRecord,+ StatsResult,+} from './modules/misc/misc.service';export {- createMcpService,- extractToken,- handleStatelessMcpRequest,-} from './modules/mcp/mcp.service';+ getFavicon,+ getGeoReport,+ getOgImage,+} from './modules/misc/misc.service';export type {INotificationPayload,INotificationRuleCached,@@ -732,6 +870,18 @@ export {mergeGlobalFilters,onlyReportEvents,} from './modules/report/src/series';+// Moved from packages/db/src/services/salt.service.ts ++// apps/worker/src/jobs/cron.salt.ts (M8-004) — `main.ts` calls+// `createInitialSalts(deps)` directly at boot; `salt.jobs.ts`'s cron handler+// and everything else reach `rotateSalt`/`getSalts` through+// `ctx.services.salt` / the v1-compat singleton instead (M10-004, see+// salt.service.ts's header — `getSalts` is the one export still bare here,+// for the same reason it's bare on the v1-compat seam).+export type { Salts } from './modules/salt/salt.service';+export {+ createInitialSalts,+ createSaltService,+} from './modules/salt/salt.service';// Dissolved from @openpanel/db's services/session.service.ts and// session-context.ts, plus apps/worker's session-end job, reaper and vacuum// (M7-001, ADR-008's module map: session owns "R,S,J") — packages/trpc's@@ -753,6 +903,12 @@ export {SESSION_DISTINCT_FIELDS,transformSession,} from './modules/session/session.service';+// Dissolved from @openpanel/db's services/insights* + referrer-spikes.service+// (M5-001) — apps/worker's insight job files and packages/trpc's insight+// router call these directly, the same way V1 reaches every other dissolved+// service here.+export type { SessionMetricsRedis } from './modules/session/src/session.metrics';+export { registerSessionScrapeMetrics } from './modules/session/src/session.metrics';export {als,getAlsSessionId,@@ -795,194 +951,6 @@ export {getCurrentSubscriptionProduct,toSubscriptionDiscount,} from './modules/subscription/subscription.service';-// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —-// packages/trpc's auth/onboarding routers call `getUserById`/-// `getUserAccount` directly through @openpanel/db's re-export shim, the same-// way they reach every other dissolved service here.-export { createUserService } from './modules/user/user.service';--import {- extractToken as mcpExtractToken,- handleStatelessMcpRequest as mcpHandleStatelessMcpRequest,-} from './modules/mcp/mcp.service';--export async function handleMcpRequest(- query: Record<string, unknown>,- authHeader: string | undefined,- body: unknown-): Promise<{ status: number; body: unknown }> {- const token = mcpExtractToken(query, authHeader);- return mcpHandleStatelessMcpRequest(token, body);-}-export { isShuttingDown, setShuttingDown } from './modules/health/src/shutdown';-// 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-// directly, the same way V1 reaches every other dissolved service here.-// packages/db/src/services/import.service.ts is deleted outright: nothing-// else reached it through @openpanel/db's barrel (same as cohort, M5-003).-export type {- ImportJobProgress,- ImportStageResult,- ImportSteps,- InsertRawEventsResult,- UpdateImportStatusOptions,-} from './modules/import/import.service';-// The ingestion pipeline (M8-002). apps/api's /track controller, its three-// route hooks and the legacy /event controller are thin delegates over these-// — the same functions core's own `ingestRoutes` calls.-export type {- BotMatch,- BotSuspicion,- DeviceIdentity,- IncomingEventPayload,- IncomingEventProducer,- IngestAuthErrorPayload,- IngestAuthOutcome,- IngestBuffers,- IngestHeaders,- IngestTransport,- TrackOutcome,- TrackRequest,-} from './modules/ingest/ingest.service';-export {- applyBotSuspicion,- checkIngestBot,- detectBot,- fetchDeviceIdentity,- getDeviceId,- getOverrideDeviceId,- getStringHeaders,- getTimestamp,- handleReplay,- ingestTrack,- isBot,- isDuplicatedEvent,- isDuplicateIngestRequest,- stripBotProperties,- summarizeBotSignals,- validateIngestRequest,-} from './modules/ingest/ingest.service';-// The Kafka consumer and its per-message handler (M8-003), which take the-// kafkajs client, the topic/group names and the retry bounds as arguments —-// the injection seam that used to cross a package boundary and now just-// crosses two files.-export type {- ConsumerLogger,- ConsumerMetrics,- DeadLetterMessage,- DeadLetterReason,- EventsBatchHandler,- EventsBatchHandlerDeps,- EventsConsumerDeps,- KafkaConsumerHandle,-} from './modules/ingest/src/consumer';-export {- createEventsBatchHandler,- startKafkaEventsConsumer,-} from './modules/ingest/src/consumer';-export { createIncomingEventHandler } from './modules/ingest/src/consumer-handler';-// The readiness probe's two inputs (M9-002). `markEventsActivity` is the-// consumer's `onActivity`; `setShuttingDown` is main.ts's signal handler.-export {- enableEventsHeartbeat,- getEventsHeartbeat,- markEventsActivity,-} from './modules/ingest/src/heartbeat';-export type {- IncomingEventBindings,- IncomingEventDelivery,- IncomingEventDeps,- IncomingEventMetrics,- IncomingEventProject,- IncomingEventSessions,-} from './modules/ingest/src/incoming-event-handler';-export {- createIncomingEventDeps,- incomingEvent,-} from './modules/ingest/src/incoming-event-handler';-export { ingestConsumerMetrics } from './modules/ingest/src/ingest.metrics';-// The Kafka transport itself (M11-003): producer, consumer factory, admin/lag-// sampling and every topic/group/retry constant, moved from-// @openpanel/queue's kafka.ts unchanged. It constructs no client at import-// time, so the barrel stays offline-importable.-export type {- Admin,- ConsumerGroupLag,- EachBatchPayload,- KafkaMessage,- PartitionLag,-} from './modules/ingest/src/kafka';-export {- assertKafkaConfigured,- createKafkaAdmin,- createKafkaEventsConsumer,- disconnectKafka,- KAFKA_BROKERS,- KAFKA_CONNECTION_TIMEOUT_MS,- KAFKA_CONSUMER_GROUP,- KAFKA_EVENTS_DLQ_TOPIC,- KAFKA_EVENTS_TOPIC,- KAFKA_HANDLER_MAX_ATTEMPTS,- KAFKA_HANDLER_RETRY_INITIAL_MS,- KAFKA_HANDLER_RETRY_MAX_MS,- KAFKA_HEARTBEAT_INTERVAL_MS,- KAFKA_MAX_MESSAGES_PER_PARTITION,- KAFKA_MAX_WAIT_MS,- KAFKA_MIN_MESSAGES,- KAFKA_PARTITIONS_CONCURRENT,- KAFKA_PRODUCER_INITIAL_RETRY_MS,- KAFKA_PRODUCER_MAX_RETRY_MS,- KAFKA_PRODUCER_RETRIES,- KAFKA_REQUEST_TIMEOUT_MS,- KAFKA_SESSION_TIMEOUT_MS,- kafkaLogger,- produceDeadLetterEvent,- produceIncomingEvent,- sampleConsumerGroupLag,-} from './modules/ingest/src/kafka';-export type {- DailyInsightCandidate,- GetReferrerSpikesInput,- ReferrerSpikeCluster,- WeeklyDigestPreview,- WeeklyDigestResult,-} from './modules/insight/insight.service';-export { explainInsight } from './modules/insight/insight.service';-// Ported from apps/api's misc controller + apps/worker's cron.ping.ts (M7-008)-// — apps/api's misc controller and the worker's ping cron job call these-// directly, the same way V1 reaches every other dissolved service here.-// `GET /misc/og/clear` and `/misc/favicon/clear` are NOT ported (ADR-015-// entry #6: RULED + DEAD).-export type {- GeoReport,- ImageAssetResult,- PingRecord,- StatsResult,-} from './modules/misc/misc.service';-export {- getFavicon,- getGeoReport,- getOgImage,-} from './modules/misc/misc.service';-// Moved from packages/db/src/services/salt.service.ts +-// apps/worker/src/jobs/cron.salt.ts (M8-004) — `main.ts` calls-// `createInitialSalts(deps)` directly at boot; `salt.jobs.ts`'s cron handler-// and everything else reach `rotateSalt`/`getSalts` through-// `ctx.services.salt` / the v1-compat singleton instead (M10-004, see-// salt.service.ts's header — `getSalts` is the one export still bare here,-// for the same reason it's bare on the v1-compat seam).-export type { Salts } from './modules/salt/salt.service';-export {- createInitialSalts,- createSaltService,-} from './modules/salt/salt.service';-// Dissolved from @openpanel/db's services/insights* + referrer-spikes.service-// (M5-001) — apps/worker's insight job files and packages/trpc's insight-// router call these directly, the same way V1 reaches every other dissolved-// service here.-export type { SessionMetricsRedis } from './modules/session/src/session.metrics';-export { registerSessionScrapeMetrics } from './modules/session/src/session.metrics';// New module (M7-008) — apps/api's tools controller calls these directly,// the same way V1 reaches every other dissolved service here.export type {@@ -995,6 +963,11 @@ export type {SiteCheckResult,} from './modules/tools/src/site-checker';export { runSiteCheck } from './modules/tools/src/site-checker';+// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —+// packages/trpc's auth/onboarding routers call `getUserById`/+// `getUserAccount` directly through @openpanel/db's re-export shim, the same+// way they reach every other dissolved service here.+export { createUserService } from './modules/user/user.service';export { dashboardRoutes, opsRoutes, publicApiRoutes } from './rest.routes';// The RPC base is on the barrel because it is the seam every module's own// `<name>.rpc.ts` builds its router on: ONE tRPC instance (ADR-009), mounteddiff --git a/packages/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.tsindex b5dc68f3d..b459ccaa9 100644--- a/packages/core/src/modules/assistant/assistant.routes.ts+++ b/packages/core/src/modules/assistant/assistant.routes.ts@@ -1,13 +1,5 @@-// Better Agent chat, mounted under `/ai/agents/*` (M5-005). V1's inline-// Fastify wrapper (apps/api/src/app.ts:223-345) stays the LIVE route-// (DELEGATE PATTERN) and already calls `chatApp`/`chatRunContext` via-// `@openpanel/core`'s lazy getters — this route exists to satisfy the module-// map ("H") and to serve core's own (not yet live) `dashboardRoutes`.-//-// NAMED GAP, same as gsc.routes.ts / import.routes.ts: this route is not yet-// reachable. `resolveSession` (http/session.ts) is a P2 stub that always-// returns `null`, so the `session` macro 401s every request; main.ts also-// does not mount `dashboardRoutes` until a real `AppDeps` exists.+// Better Agent chat, mounted under `/ai/agents/*` (M5-005) inside+// `dashboardRoutes` (rest.routes.ts), which `apps/api/src/main.ts` mounts.//// Elysia has no adapter in `@better-agent/adapters` (only express/fastify),// but `BetterAgentApp.handler` already speaks the Web `Request`/`Response`@@ -16,28 +8,17 @@// project-access check below — `chatApp.handler` gets the original,// unconsumed `request` so it can re-read the body itself.//-// The cross-module functions stay dynamically imported, not statically: a-// static import here would race this package's own evaluation the way-// index.ts's header documents for `mcp.service.ts`. M10-009 replaced the one-// `import('@openpanel/core')` hop with direct relative imports of the three-// modules it actually reached (`core-no-self-barrel`). `./assistant.service`-// itself is cheap either way now (M10-004, see that file's header) — kept-// dynamic anyway for symmetry.+// M15-003: this route is where `deps` lives, so everything below it reaches+// Postgres/ClickHouse through `ctx` — the chat app, the conversation lookup+// and the access check included. That is what removed the four lazy loaders+// this file used to open with (ADR-022 R6).import { defineRoutes } from '../../http/define';--function loadCompat() {- return import('../../v1-compat');-}-function loadAccessLookups() {- return import('../../shared/access-lookups');-}-function loadOrganizationService() {- return import('../organization/organization.service');-}-function loadAssistant() {- return import('./assistant.service');-}+import { getProjectAccess } from '../../shared/access-lookups';+import {+ getOrganizationByProjectIdCached,+ getSettingsForProject,+} from '../organization/organization.service';interface RunBody {context?: { projectId?: string; organizationId?: string };@@ -52,11 +33,8 @@ export const assistantRoutes = defineRoutes((app) =>return status(401, { message: 'Sign in required' });}- const { getChatApp, getChatRunContext } = await loadAssistant();- const [chatApp, chatRunContext] = await Promise.all([- getChatApp(),- getChatRunContext(),- ]);+ const chatApp = ctx.services.assistant.getChatApp();+ const chatRunContext = ctx.services.assistant.getChatRunContext();// Parse the URL tail that comes after `/ai/agents/`. Examples:// "claude-sonnet-4-5/run" → run@@ -78,8 +56,8 @@ export const assistantRoutes = defineRoutes((app) =>// A brand-new chat (no row yet) falls through to the agent handler,// whose `ConversationStore.load()` returns null.if (route === 'conversations' && routeId) {- const { getConversationById } = await loadCompat();- const conv = await getConversationById(routeId);+ const conv =+ await ctx.services.conversation.getConversationById(routeId);if (conv && conv.userId !== userId) {return status(404, { message: 'Conversation not found' });}@@ -101,10 +79,6 @@ export const assistantRoutes = defineRoutes((app) =>});}- const [- { getOrganizationByProjectIdCached, getSettingsForProject },- { getProjectAccess },- ] = await Promise.all([loadOrganizationService(), loadAccessLookups()]);const [access, organization, settings] = await Promise.all([getProjectAccess({ projectId, userId }),getOrganizationByProjectIdCached(projectId),diff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.tsindex 738be54ed..759535322 100644--- a/packages/core/src/modules/assistant/assistant.service.ts+++ b/packages/core/src/modules/assistant/assistant.service.ts@@ -4,67 +4,38 @@// lives under ./src — this file is the module's public entry point, the same// shape as insight.service.ts drawing from insight/src/*.//-// V1 keeps running (DELEGATE PATTERN):-// - apps/api/src/agents/app.ts and apps/api/src/agents/run-context.ts-// become re-export shims of `getChatApp`/`getChatRunContext` below. The-// live Fastify route (apps/api/src/app.ts) still mounts `chatApp` and-// wraps the handler in `chatRunContext.run(...)` exactly as before.-// - packages/trpc/src/routers/overview.ts's `runFilterCommand` procedure-// now imports `runFilterCommand` from `@openpanel/core` instead of the-// deleted `../agents/filter-command`.+// M15-003: every export takes `deps`. `./src/app.ts` and+// `./src/filter-command.ts` construct nothing at import time any more, so the+// three lazy loaders that used to stand between this file and them are gone+// (ADR-022 R6/R15) — a static import here builds no agent, opens no provider+// client and reaches no database.//-// M10-004: `createAssistantService(deps)` lands here, which means THIS FILE-// is now statically imported by services.ts — every export below stays-// LAZY (dynamic `import()`) precisely because `./src/app.ts` constructs the-// whole Better Agent app (one `defineAgent` per whitelisted model) at its-// own import time, and `./src/filter-command.ts` reaches this package's own-// barrel. A static top-level `export ... from './src/app'` here would make-// `betterAgent`'s app construction run at PROCESS BOOT (services.ts's own-// module evaluation) instead of on the first real chat/filter request, and-// a static reach into `@openpanel/core` would risk re-entering this-// package's own barrel mid-evaluation (the exact TDZ hazard index.ts's-// header documents for `mcp.service.ts`). `deps` is unused: nothing here-// needs Postgres/ClickHouse/Redis directly — `./src/persistence.ts` reaches-// them through the v1-compat singleton (see that file's header), the same-// way every other bare, no-`Ctx` caller in this wave does.+// The chat app is memoized PER `deps` object rather than per process: a Ctx+// builds one `ServiceDeps` per unit of work (context.ts's+// `installLazyServices`), so two calls inside one chat request share an app+// while two requests do not — the same trade `shared/cacheable-per-deps.ts`+// records for the cross-module caches.import type { ServiceDeps, Services } from '../../services';import type { PageContext } from './assistant.constants';--let _app: Promise<typeof import('./src/app')> | undefined;-function loadApp() {- if (!_app) {- _app = import('./src/app');- }- return _app;-}--let _runContext: Promise<typeof import('./src/run-context')> | undefined;-function loadRunContext() {- if (!_runContext) {- _runContext = import('./src/run-context');- }- return _runContext;-}--let _filterCommand: Promise<typeof import('./src/filter-command')> | undefined;-function loadFilterCommand() {- if (!_filterCommand) {- _filterCommand = import('./src/filter-command');- }- return _filterCommand;-}+import { type ChatApp, createChatApp } from './src/app';+import { runFilterCommand } from './src/filter-command';+import { chatRunContext } from './src/run-context';export type { ChatApp } from './src/app';export type { FilterCommandResult } from './src/filter-command';export type { ChatRunContext } from './src/run-context';-export async function getChatApp() {- return (await loadApp()).chatApp;-}+const appsByDeps = new WeakMap<ServiceDeps, ChatApp>();-export async function getChatRunContext() {- return (await loadRunContext()).chatRunContext;+function chatAppFor(deps: ServiceDeps): ChatApp {+ const existing = appsByDeps.get(deps);+ if (existing) {+ return existing;+ }+ const built = createChatApp(deps);+ appsByDeps.set(deps, built);+ return built;}export interface RunFilterCommandInput {@@ -74,25 +45,15 @@ export interface RunFilterCommandInput {timezone: string;}-export async function runFilterCommand(input: RunFilterCommandInput) {- const { runFilterCommand: run } = await loadFilterCommand();- return run(input);-}--/**- * Ignores BOTH arguments, and takes them only because ADR-022 R3 keeps the- * composition root a flat list: the three members are `@better-agent/core`- * entry points with a fixed signature, and each reaches the database through- * the v1-compat seam its own tools already use — there is nothing here to- * hand a client to.- */export function createAssistantService(- _deps: ServiceDeps,+ deps: ServiceDeps,_services: () => Services) {return {- getChatApp,- getChatRunContext,- runFilterCommand,+ getChatApp: (): ChatApp => chatAppFor(deps),+ getChatRunContext: (): typeof chatRunContext => chatRunContext,+ runFilterCommand: (+ input: RunFilterCommandInput+ ): ReturnType<typeof runFilterCommand> => runFilterCommand(deps, input),};}diff --git a/packages/core/src/modules/assistant/src/app.ts b/packages/core/src/modules/assistant/src/app.tsindex 54e279328..0e3ddf9a1 100644--- a/packages/core/src/modules/assistant/src/app.ts+++ b/packages/core/src/modules/assistant/src/app.ts@@ -1,7 +1,12 @@// Moved from apps/api/src/agents/app.ts (M5-005, ADR-007's module map:-// assistant owns "S"). `apps/api/src/agents/app.ts` becomes a re-export shim-// of `chatApp`/`ChatApp` (DELEGATE PATTERN) — the live Fastify route in-// apps/api/src/app.ts keeps mounting it exactly as before.+// assistant owns "S").+//+// M15-003: the app is BUILT from the `deps` `assistant.routes.ts` already+// holds, not constructed at module scope (ADR-022 R6/R15). Importing this+// file now opens nothing — no provider client, no agent, no conversation+// store — and every tool handler closes over the same `deps`, which is what+// `@better-agent/core`'s context-free tool-handler signature ruled out doing+// as an argument.import { betterAgent, defineAgent } from '@better-agent/core';import {ALLOWED_MODELS,@@ -9,8 +14,9 @@ import {openaiProvider,resolveModel,} from '../../../clients/ai/providers';+import type { ServiceDeps } from '../../../services';import { type ChatAgentContext, chatContextSchema } from './context';-import { prismaConversationStore } from './persistence';+import { createConversationStore } from './persistence';import { buildSystemPrompt } from './prompt';import { composeChatTools } from './tools';@@ -32,14 +38,14 @@ import { composeChatTools } from './tools';* a runtime `validateAgentDefinition` check so misconfigurations* still throw at startup.*/-function createChatAgent(entry: ChatModelEntry) {+function createChatAgent(deps: ServiceDeps, entry: ChatModelEntry) {return defineAgent({name: entry.id,description: `OpenPanel chat assistant (${entry.label})`,model: resolveModel(entry),contextSchema: chatContextSchema,instruction: (context: ChatAgentContext) => buildSystemPrompt(context),- tools: (context: ChatAgentContext) => composeChatTools(context),+ tools: (context: ChatAgentContext) => composeChatTools(deps, context),maxSteps: 20,// Reasoning-capable models (gpt-5.x / o-series) need the// `reasoning.summary` option to stream reasoning text back; the@@ -61,36 +67,43 @@ function createChatAgent(entry: ChatModelEntry) {/*** Dedicated cheap agent for generating 3-5 word conversation titles.- * Called fire-and-forget from the Fastify wrapper after the first- * turn of a new conversation completes.+ * Called fire-and-forget by the route after the first turn of a new+ * conversation completes.*/-const titlerAgent = defineAgent({- name: '__titler',- description: 'Generates concise 3-5 word titles for chat conversations.',- // biome-ignore lint/suspicious/noExplicitAny: OpenAI model id union is open- model: openaiProvider().model('gpt-4.1-mini' as any),- instruction:- 'You generate concise 3-5 word titles for chat conversations. Respond with ONLY the title. No quotes, no punctuation, no trailing period.',- maxSteps: 1,- // biome-ignore lint/suspicious/noExplicitAny: see block comment on createChatAgent-} as any);+function createTitlerAgent() {+ return defineAgent({+ name: '__titler',+ description: 'Generates concise 3-5 word titles for chat conversations.',+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI model id union is open+ model: openaiProvider().model('gpt-4.1-mini' as any),+ instruction:+ 'You generate concise 3-5 word titles for chat conversations. Respond with ONLY the title. No quotes, no punctuation, no trailing period.',+ maxSteps: 1,+ // biome-ignore lint/suspicious/noExplicitAny: see block comment on createChatAgent+ } as any);+}/**- * The single Better Agent app. Exports a `.handler` that the Fastify- * adapter mounts under `/ai/agents/*`. Holds:+ * The Better Agent app for one unit of work. Exposes a `.handler` that+ * `assistant.routes.ts` calls under `/ai/agents/*`. Holds:* - one agent per allowed model* - the Prisma-backed conversation store for persistence* - a dedicated titler agent for conversation titles*- * Auth + project-access are enforced by the Fastify wrapper before- * this handler runs — see `apps/api/src/app.ts`.+ * Auth + project-access are enforced by `assistant.routes.ts` before this+ * handler runs.*/-export const chatApp = betterAgent({- agents: [...ALLOWED_MODELS.map(createChatAgent), titlerAgent],- persistence: {- conversations: prismaConversationStore,- },- baseURL: '/ai/agents',-});+export function createChatApp(deps: ServiceDeps) {+ return betterAgent({+ agents: [+ ...ALLOWED_MODELS.map((entry) => createChatAgent(deps, entry)),+ createTitlerAgent(),+ ],+ persistence: {+ conversations: createConversationStore(deps),+ },+ baseURL: '/ai/agents',+ });+}-export type ChatApp = typeof chatApp;+export type ChatApp = ReturnType<typeof createChatApp>;diff --git a/packages/core/src/modules/assistant/src/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.tsindex dbc031996..d3ba0c7da 100644--- a/packages/core/src/modules/assistant/src/filter-command.ts+++ b/packages/core/src/modules/assistant/src/filter-command.ts@@ -1,7 +1,11 @@-// Moved from packages/trpc/src/agents/filter-command.ts (M5-005). V1's-// packages/trpc/src/routers/overview.ts stays the LIVE `runFilterCommand`-// tRPC procedure (DELEGATE PATTERN) and now imports this module's-// `runFilterCommand` from @openpanel/core instead of a relative path.+// Moved from packages/trpc/src/agents/filter-command.ts (M5-005). The one+// caller is `overview.rpc.ts`'s `runFilterCommand` procedure, which reaches+// it through `ctx.services.assistant`.+//+// M15-003: the agent app and its five tools are BUILT from the `deps` that+// procedure already holds (ADR-022 R6/R15) — importing this file constructs+// nothing, and the tool handlers close over `deps` because+// `@better-agent/core`'s tool-handler signature has no slot for them.import {type AgentToolDefinition,betterAgent,@@ -11,15 +15,14 @@ import {} from '@better-agent/core';import { z } from 'zod';import { resolveModel } from '../../../clients/ai/providers';+import type { ServiceDeps } from '../../../services';import {getDatesFromRange,resolveDateRange as resolveDateRangeCore,} from '../../../shared/date';-import {- getTopPagesCore,- getTrafficBreakdownCore,- listEventNamesCore,-} from '../../../v1-compat';+import { listEventNamesCore } from '../../event/event.service';+import { getTrafficBreakdownCore } from '../../overview/overview.service';+import { getTopPagesCore } from '../../overview/pages.service';import {type IChartEventFilter,type IChartRange,@@ -195,88 +198,94 @@ function defineServerTool<TSchema extends z.ZodTypeAny>(config: {) as AgentToolDefinition;}-const listEventNamesTool = defineServerTool({- name: 'list_event_names',- description:- 'Top 50 event names tracked in this project. Use BEFORE setting `setEventNamesFilter`.',- schema: z.object({}),- handler: async (_input, ctx) => ({- event_names: await listEventNamesCore(ctx.projectId),- }),-});+const listEventNamesTool = (deps: ServiceDeps) =>+ defineServerTool({+ name: 'list_event_names',+ description:+ 'Top 50 event names tracked in this project. Use BEFORE setting `setEventNamesFilter`.',+ schema: z.object({}),+ handler: async (_input, ctx) => ({+ event_names: await listEventNamesCore(deps, ctx.projectId),+ }),+ });-const getTopReferrersTool = defineServerTool({- name: 'get_top_referrers',- description:- "Top traffic sources by `referrer_name` ('Google', 'GitHub', 'Direct') in the user's current date range. Use to translate vague names into exact filter values.",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTrafficBreakdownCore({- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: 'referrer_name',- filters: activeFilters(ctx),- });- return { rows: rows.slice(0, 30) };- },-});+const getTopReferrersTool = (deps: ServiceDeps) =>+ defineServerTool({+ name: 'get_top_referrers',+ description:+ "Top traffic sources by `referrer_name` ('Google', 'GitHub', 'Direct') in the user's current date range. Use to translate vague names into exact filter values.",+ schema: z.object({}),+ handler: async (_input, ctx) => {+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);+ const rows = await getTrafficBreakdownCore(deps, {+ projectId: ctx.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: 'referrer_name',+ filters: activeFilters(ctx),+ });+ return { rows: rows.slice(0, 30) };+ },+ });-const getTopCountriesTool = defineServerTool({- name: 'get_top_countries',- description: "Top countries (ISO-2 codes) in the user's current date range.",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTrafficBreakdownCore({- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: 'country',- filters: activeFilters(ctx),- });- return { rows: rows.slice(0, 50) };- },-});+const getTopCountriesTool = (deps: ServiceDeps) =>+ defineServerTool({+ name: 'get_top_countries',+ description:+ "Top countries (ISO-2 codes) in the user's current date range.",+ schema: z.object({}),+ handler: async (_input, ctx) => {+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);+ const rows = await getTrafficBreakdownCore(deps, {+ projectId: ctx.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: 'country',+ filters: activeFilters(ctx),+ });+ return { rows: rows.slice(0, 50) };+ },+ });-const getTopDevicesTool = defineServerTool({- name: 'get_top_devices',- description:- "Device classes seen in the user's current date range (mobile, desktop, tablet, …).",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTrafficBreakdownCore({- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: 'device',- filters: activeFilters(ctx),- });- return { rows: rows.slice(0, 20) };- },-});+const getTopDevicesTool = (deps: ServiceDeps) =>+ defineServerTool({+ name: 'get_top_devices',+ description:+ "Device classes seen in the user's current date range (mobile, desktop, tablet, …).",+ schema: z.object({}),+ handler: async (_input, ctx) => {+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);+ const rows = await getTrafficBreakdownCore(deps, {+ projectId: ctx.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: 'device',+ filters: activeFilters(ctx),+ });+ return { rows: rows.slice(0, 20) };+ },+ });-const getTopPagesTool = defineServerTool({- name: 'get_top_pages',- description:- "Top pages (paths like '/blog/foo', '/pricing', '/') in the user's current date range. Use to discover the path shape so you can pick the right operator (`startsWith` for sections like /blog, `is` for an exact page, `contains` for fuzzy matching).",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTopPagesCore({- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- filters: activeFilters(ctx),- limit: 50,- });- return { rows };- },-});+const getTopPagesTool = (deps: ServiceDeps) =>+ defineServerTool({+ name: 'get_top_pages',+ description:+ "Top pages (paths like '/blog/foo', '/pricing', '/') in the user's current date range. Use to discover the path shape so you can pick the right operator (`startsWith` for sections like /blog, `is` for an exact page, `contains` for fuzzy matching).",+ schema: z.object({}),+ handler: async (_input, ctx) => {+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);+ const rows = await getTopPagesCore(deps, {+ projectId: ctx.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ filters: activeFilters(ctx),+ limit: 50,+ });+ return { rows };+ },+ });-const FILTER_COMMAND_TOOLS: AgentToolDefinition[] = [+const FILTER_COMMAND_TOOLS: ((deps: ServiceDeps) => AgentToolDefinition)[] = [listEventNamesTool,getTopReferrersTool,getTopCountriesTool,@@ -363,11 +372,7 @@ const filterCommandOutputJsonSchema = z.toJSONSchema({ target: 'draft-07' });-let _app: ReturnType<typeof betterAgent> | null = null;-function getApp() {- if (_app) {- return _app;- }+function createFilterCommandApp(deps: ServiceDeps) {const agent = defineAgent({name: 'filter-command',description: 'OpenPanel filter command bar (one-shot, no persistence).',@@ -379,21 +384,23 @@ function getApp() {strict: true,},instruction: (ctx: FilterCommandContext) => buildInstruction(ctx),- tools: () => FILTER_COMMAND_TOOLS,+ tools: () => FILTER_COMMAND_TOOLS.map((tool) => tool(deps)),maxSteps: 6,// biome-ignore lint/suspicious/noExplicitAny: same dodge as apps/api/src/agents/app.ts} as any);- _app = betterAgent({ agents: [agent] });- return _app;+ return betterAgent({ agents: [agent] });}-export async function runFilterCommand(input: {- query: string;- projectId: string;- pageContext?: PageContext;- timezone: string;-}): Promise<FilterCommandResult> {- const result = (await getApp().run('filter-command', {+export async function runFilterCommand(+ deps: ServiceDeps,+ input: {+ query: string;+ projectId: string;+ pageContext?: PageContext;+ timezone: string;+ }+): Promise<FilterCommandResult> {+ const result = (await createFilterCommandApp(deps).run('filter-command', {input: input.query,context: {projectId: input.projectId,diff --git a/packages/core/src/modules/assistant/src/persistence.ts b/packages/core/src/modules/assistant/src/persistence.tsindex dd2003343..18aed0af3 100644--- a/packages/core/src/modules/assistant/src/persistence.ts+++ b/packages/core/src/modules/assistant/src/persistence.ts@@ -1,16 +1,12 @@import type { ConversationStore } from '@better-agent/core';import type { ConversationItem } from '@better-agent/core/providers';+import type { ServiceDeps } from '../../../services';import { chatRunContext } from './run-context';// `ConversationStore`'s `load`/`save` signatures are @better-agent/core's own// interface — betterAgent calls them with no `Ctx`/`ServiceDeps` to thread-// through, so db access stays a lazy singleton, same as the other bare-// hot-path callers in this wave (M10-004, see v1-compat.ts's header) rather-// than a direct `@openpanel/db` import. GENUINE CYCLE, kept lazy: services.ts-// -> assistant.service.ts -> this file -> v1-compat.ts -> services.ts.-function loadCompatDb() {- return import('../../../v1-compat').then((m) => m.compatDb());-}+// through, so the store is BUILT from the deps the route already holds and+// closes over them (ADR-022 R6/R15)./*** Prisma-backed `ConversationStore` for Better Agent.@@ -56,75 +52,76 @@ function itemToRow(conversationId: string, item: ConversationItem) {};}-export const prismaConversationStore: ConversationStore = {- async load({ conversationId }) {- const db = await loadCompatDb();- const conv = await db.conversation.findUnique({- where: { id: conversationId },- include: {- messages: { orderBy: { createdAt: 'asc' } },- },- });- if (!conv) {- return null;- }-- return {- items: conv.messages.map((m) => m.parts as unknown as ConversationItem),- cursor: conv.updatedAt.getTime(),- };- },-- async save({ conversationId, items }) {- const owner = chatRunContext.getStore();- if (!owner) {- throw new Error(- 'chatRunContext missing during save — the Fastify wrapper must run first'- );- }-- const db = await loadCompatDb();- await db.$transaction(async (tx) => {- await tx.conversation.upsert({+export function createConversationStore(deps: ServiceDeps): ConversationStore {+ const db = deps.db;+ return {+ async load({ conversationId }) {+ const conv = await db.conversation.findUnique({where: { id: conversationId },- create: {- id: conversationId,- projectId: owner.projectId,- organizationId: owner.organizationId,- userId: owner.userId,+ include: {+ messages: { orderBy: { createdAt: 'asc' } },},- update: { updatedAt: new Date() },});+ if (!conv) {+ return null;+ }- const existingCount = await tx.chatMessage.count({- where: { conversationId },- });+ return {+ items: conv.messages.map((m) => m.parts as unknown as ConversationItem),+ cursor: conv.updatedAt.getTime(),+ };+ },- if (items.length >= existingCount) {- // Append-only fast path: Better Agent guarantees prior items- // are immutable, so we can safely insert only the tail.- const newItems = items.slice(existingCount);- if (newItems.length > 0) {- await tx.chatMessage.createMany({- data: newItems.map((item) => itemToRow(conversationId, item)),- });- }- } else {- // Incoming list is shorter than what's stored — an edit,- // retry, or deletion. Rewrite.- await tx.chatMessage.deleteMany({ where: { conversationId } });- if (items.length > 0) {- await tx.chatMessage.createMany({- data: items.map((item) => itemToRow(conversationId, item)),- });- }+ async save({ conversationId, items }) {+ const owner = chatRunContext.getStore();+ if (!owner) {+ throw new Error(+ 'chatRunContext missing during save — the Fastify wrapper must run first'+ );}- });- const updated = await db.conversation.findUnique({- where: { id: conversationId },- select: { updatedAt: true },- });- return { cursor: updated?.updatedAt.getTime() ?? Date.now() };- },-};+ await db.$transaction(async (tx) => {+ await tx.conversation.upsert({+ where: { id: conversationId },+ create: {+ id: conversationId,+ projectId: owner.projectId,+ organizationId: owner.organizationId,+ userId: owner.userId,+ },+ update: { updatedAt: new Date() },+ });++ const existingCount = await tx.chatMessage.count({+ where: { conversationId },+ });++ if (items.length >= existingCount) {+ // Append-only fast path: Better Agent guarantees prior items+ // are immutable, so we can safely insert only the tail.+ const newItems = items.slice(existingCount);+ if (newItems.length > 0) {+ await tx.chatMessage.createMany({+ data: newItems.map((item) => itemToRow(conversationId, item)),+ });+ }+ } else {+ // Incoming list is shorter than what's stored — an edit,+ // retry, or deletion. Rewrite.+ await tx.chatMessage.deleteMany({ where: { conversationId } });+ if (items.length > 0) {+ await tx.chatMessage.createMany({+ data: items.map((item) => itemToRow(conversationId, item)),+ });+ }+ }+ });++ const updated = await db.conversation.findUnique({+ where: { id: conversationId },+ select: { updatedAt: true },+ });+ return { cursor: updated?.updatedAt.getTime() ?? Date.now() };+ },+ };+}diff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.tsindex 572fc16f1..c3c7bc909 100644--- a/packages/core/src/modules/assistant/src/report-runner.ts+++ b/packages/core/src/modules/assistant/src/report-runner.ts@@ -1,14 +1,9 @@// Ported from packages/mcp/src/tools/analytics/reports.ts's `runReport` /// `runReportFromConfig` (M5-005).//-// V1's apps/api/src/agents/tools/{base,report}.ts called these two functions-// straight out of `@openpanel/mcp` — a working cross-package reuse, but one-// core cannot inherit: `@openpanel/mcp` already depends on `@openpanel/core`-// (its auth + session-manager modules), so core importing `@openpanel/mcp`-// back would be a real package cycle (the same shape cohort.service.ts's-// header documents for the now-deleted `@openpanel/queue`). ADR-007 also-// explicitly defers unifying MCP's tool definitions with assistant's, so-// reaching into mcp is not the fix either.+// ADR-007 explicitly defers unifying MCP's tool definitions with assistant's,+// so `modules/mcp/src/tools/analytics/reports.ts` keeps its own copy of this+// dispatch — reaching into another module's tool tree is not the fix.//// The result is a second copy of this dispatch logic, which is exactly the// "four independent wrapper layers over the same 34 *Core functions"@@ -17,14 +12,12 @@// @openpanel/db primitives and must be kept in sync by hand until that debt// is paid down.+import type { ServiceDeps } from '../../../services';import { getChartStartEndDate } from '../../../shared/date';-import {- AggregateChartEngine,- ChartEngine,- getFunnel,- getReportById,- getSettingsForProject,-} from '../../../v1-compat';+import { executeAggregateChart, executeChart } from '../../chart/chart.service';+import { getFunnel } from '../../chart/funnel.service';+import { getSettingsForProject } from '../../organization/organization.service';+import { getReportById } from '../../report/report.service';function reportUrl(organizationId: string,@@ -42,17 +35,20 @@ function reportUrl(/*** Execute a saved report by ID. Dispatches on chart type:* - funnel → getFunnel- * - metric → AggregateChartEngine.execute- * - others → ChartEngine.execute+ * - metric → executeAggregateChart+ * - others → executeChart** Deliberately returns the raw engine output — the chat renderer needs the* full chart, unlike MCP's copy which reshapes it for LLM consumption.*/-export async function runReport(input: {- organizationId: string;- projectId: string;- reportId: string;-}): Promise<+export async function runReport(+ deps: ServiceDeps,+ input: {+ organizationId: string;+ projectId: string;+ reportId: string;+ }+): Promise<| { error: string; reportId: string }| {id: string;@@ -66,7 +62,7 @@ export async function runReport(input: {data: unknown;}> {- const report = await getReportById(input.reportId);+ const report = await getReportById(deps, input.reportId);if (!report) {return { error: 'Report not found', reportId: input.reportId };@@ -79,7 +75,7 @@ export async function runReport(input: {};}- const { timezone } = await getSettingsForProject(input.projectId);+ const { timezone } = await getSettingsForProject(deps, input.projectId);const { startDate, endDate } = getChartStartEndDate(report, timezone);const chartInput = { ...report, startDate, endDate, timezone };@@ -99,12 +95,12 @@ export async function runReport(input: {};if (report.chartType === 'funnel') {- return { ...meta, data: await getFunnel(chartInput) };+ return { ...meta, data: await getFunnel(deps, chartInput) };}if (report.chartType === 'metric') {- return { ...meta, data: await AggregateChartEngine.execute(chartInput) };+ return { ...meta, data: await executeAggregateChart(deps, chartInput) };}- return { ...meta, data: await ChartEngine.execute(chartInput) };+ return { ...meta, data: await executeChart(deps, chartInput) };}/**@@ -112,18 +108,21 @@ export async function runReport(input: {* directly). Used by the `generate_report` / `preview_report_with_changes`* chat tools.*/-export async function runReportFromConfig(input: {- organizationId: string;- projectId: string;- /** Full zReportInput shape, with required startDate/endDate */- config: {- chartType: string;- interval: string;- startDate: string;- endDate: string;- [key: string]: unknown;- };-}): Promise<{+export async function runReportFromConfig(+ deps: ServiceDeps,+ input: {+ organizationId: string;+ projectId: string;+ /** Full zReportInput shape, with required startDate/endDate */+ config: {+ chartType: string;+ interval: string;+ startDate: string;+ endDate: string;+ [key: string]: unknown;+ };+ }+): Promise<{chartType: string;interval: string;startDate: string;@@ -131,12 +130,12 @@ export async function runReportFromConfig(input: {report: typeof input.config & { projectId: string };data: unknown;}> {- const { timezone } = await getSettingsForProject(input.projectId);+ const { timezone } = await getSettingsForProject(deps, input.projectId);const chartInput = {...input.config,projectId: input.projectId,timezone,- } as unknown as Parameters<typeof ChartEngine.execute>[0];+ } as unknown as Parameters<typeof executeChart>[1];const meta = {chartType: input.config.chartType,@@ -149,11 +148,14 @@ export async function runReportFromConfig(input: {if (input.config.chartType === 'funnel') {return {...meta,- data: await getFunnel(chartInput as Parameters<typeof getFunnel>[0]),+ data: await getFunnel(+ deps,+ chartInput as Parameters<typeof getFunnel>[1]+ ),};}if (input.config.chartType === 'metric') {- return { ...meta, data: await AggregateChartEngine.execute(chartInput) };+ return { ...meta, data: await executeAggregateChart(deps, chartInput) };}- return { ...meta, data: await ChartEngine.execute(chartInput) };+ return { ...meta, data: await executeChart(deps, chartInput) };}diff --git a/packages/core/src/modules/assistant/src/tools/base.ts b/packages/core/src/modules/assistant/src/tools/base.tsindex cb47853e2..7f704446d 100644--- a/packages/core/src/modules/assistant/src/tools/base.ts+++ b/packages/core/src/modules/assistant/src/tools/base.ts@@ -1,27 +1,32 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';+import { getFunnelCore } from '../../../chart/funnel.service';import {- findProfilesCore,- getAnalyticsOverviewCore,- getEventPropertyValuesCore,- getFunnelCore,getRetentionCohortCore,getRollingActiveUsersCore,- getTopPagesCore,- getTrafficBreakdownCore,- getUserFlowCore,- listDashboardsCore,+} from '../../../chart/retention.service';+import { getUserFlowCore } from '../../../chart/sankey.service';+import { listDashboardsCore } from '../../../dashboard/dashboard.service';+import {+ getEventPropertyValuesCore,listEventNamesCore,listEventPropertiesCore,- listReportsCore,queryEventsCore,- querySessionsCore,-} from '../../../../v1-compat';+} from '../../../event/event.service';+import {+ getAnalyticsOverviewCore,+ getTrafficBreakdownCore,+} from '../../../overview/overview.service';+import { getTopPagesCore } from '../../../overview/pages.service';+import { findProfilesCore } from '../../../profile/profile.service';import {chartTypes,lineTypes,operators,zReportInput,} from '../../../report/report.constants';+import { listReportsCore } from '../../../report/report.service';+import { querySessionsCore } from '../../../session/session.service';import { runReport, runReportFromConfig } from '../report-runner';import {chatTool,@@ -45,376 +50,393 @@ function objectToZodEnums<K extends string>(// DISCOVERY// ─────────────────────────────────────────────────────────────────-export const listEventNames = chatTool(- {- name: 'list_event_names',- description:- 'Get the top 50 event names tracked in this project. Call this BEFORE referencing event names in generate_report or other tools — never guess at event names.',- schema: z.object({}),- },- async (_input, context) => {- const names = await listEventNamesCore(context.projectId);- return { event_names: names };- }-);--export const listEventProperties = chatTool(- {- name: 'list_event_properties',- description:- 'List fields available for filtering or breaking down events. Returns TWO buckets:\n\n- `columns`: top-level event columns (path, referrer, country, device, browser, os, etc.). Apply to every event. Use the bare name in filters/breakdowns (e.g. `{ name: "path", operator: "endsWith", value: ["/cohorts"] }`).\n- `properties`: custom keys from the event\'s JSON `properties` map. Use prefixed as `properties.<key>` in filters/breakdowns (e.g. `properties.plan`).\n\nCall this before using any field as a filter or breakdown in generate_report. NOTE: dotted sub-keys inside `properties` are rolled up to their root — e.g. all `__query.foo`, `__query.bar`, … are represented by a single `__query` entry, ordered by how many sub-keys roll up under them (most prominent first). To filter on a specific sub-key like `properties.__query.utm_source`, use that exact full key — the rollup is purely a discovery optimization.',- schema: z.object({- eventName: z- .string()- .optional()- .describe(- 'Optional — filter to one event. Omit to list properties across all events.'- ),- }),- },- async ({ eventName }, context) => {- const raw = await listEventPropertiesCore({- projectId: context.projectId,- eventName,- });- return compactEventProperties(raw, { eventName });- }-);--export const getEventPropertyValues = chatTool(- {- name: 'get_event_property_values',- description:- 'List distinct values for a specific event property. Useful when the user wants to filter on something concrete like "country = SE".',- schema: z.object({- eventName: z.string().describe('The event name (e.g. screen_view)'),- propertyKey: z.string().describe('The property key (e.g. path, country)'),- }),- },- async ({ eventName, propertyKey }, context) =>- getEventPropertyValuesCore({- projectId: context.projectId,- eventName,- propertyKey,- })-);+export const listEventNames = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'list_event_names',+ description:+ 'Get the top 50 event names tracked in this project. Call this BEFORE referencing event names in generate_report or other tools — never guess at event names.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const names = await listEventNamesCore(deps, context.projectId);+ return { event_names: names };+ }+ );++export const listEventProperties = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'list_event_properties',+ description:+ 'List fields available for filtering or breaking down events. Returns TWO buckets:\n\n- `columns`: top-level event columns (path, referrer, country, device, browser, os, etc.). Apply to every event. Use the bare name in filters/breakdowns (e.g. `{ name: "path", operator: "endsWith", value: ["/cohorts"] }`).\n- `properties`: custom keys from the event\'s JSON `properties` map. Use prefixed as `properties.<key>` in filters/breakdowns (e.g. `properties.plan`).\n\nCall this before using any field as a filter or breakdown in generate_report. NOTE: dotted sub-keys inside `properties` are rolled up to their root — e.g. all `__query.foo`, `__query.bar`, … are represented by a single `__query` entry, ordered by how many sub-keys roll up under them (most prominent first). To filter on a specific sub-key like `properties.__query.utm_source`, use that exact full key — the rollup is purely a discovery optimization.',+ schema: z.object({+ eventName: z+ .string()+ .optional()+ .describe(+ 'Optional — filter to one event. Omit to list properties across all events.'+ ),+ }),+ },+ async ({ eventName }, context) => {+ const raw = await listEventPropertiesCore(deps, {+ projectId: context.projectId,+ eventName,+ });+ return compactEventProperties(raw, { eventName });+ }+ );++export const getEventPropertyValues = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_event_property_values',+ description:+ 'List distinct values for a specific event property. Useful when the user wants to filter on something concrete like "country = SE".',+ schema: z.object({+ eventName: z.string().describe('The event name (e.g. screen_view)'),+ propertyKey: z+ .string()+ .describe('The property key (e.g. path, country)'),+ }),+ },+ async ({ eventName, propertyKey }, context) =>+ getEventPropertyValuesCore(deps, {+ projectId: context.projectId,+ eventName,+ propertyKey,+ })+ );// ─────────────────────────────────────────────────────────────────// SAVED DASHBOARDS & REPORTS (PREFER THESE OVER generate_report)// ─────────────────────────────────────────────────────────────────-export const listDashboards = chatTool(- {- name: 'list_dashboards',- description:- 'List all dashboards in this project. Each dashboard groups a set of reports the user has built. Use this to discover what already exists before building anything new.',- schema: z.object({}),- },- async (_input, context) => {- const dashboards = await listDashboardsCore({- projectId: context.projectId,- organizationId: context.organizationId,- });- return dashboards.map((d) => ({- ...d,- dashboard_url: dashboardUrl(- context.organizationId,- context.projectId,- `/dashboards/${d.id}`- ),- }));- }-);--export const listReports = chatTool(- {- name: 'list_reports',- description:- 'List the reports inside a dashboard. Returns chart type, range, interval, and event series for each. Use this with get_report_data to fetch real numbers.',- schema: z.object({- dashboardId: z- .string()- .describe('The dashboard ID (from list_dashboards)'),- }),- },- async ({ dashboardId }, context) =>- listReportsCore({- projectId: context.projectId,- dashboardId,- organizationId: context.organizationId,- })-);--export const getReportData = chatTool(- {- name: 'get_report_data',- description:- 'Execute a saved report by ID and return its data. Works for every chart type (linear, bar, area, pie, metric, funnel, retention, etc.). PREFER this over generate_report when the user asks about something a saved report likely already covers.',- schema: z.object({- reportId: z.string().describe('The report ID (from list_reports)'),- }),- },- async ({ reportId }, context) =>- runReport({- organizationId: context.organizationId,- projectId: context.projectId,- reportId,- })-);--export const generateReport = chatTool(- {- name: 'generate_report',- description: [- 'Generate an ad-hoc chart from a report config. Use only when no saved report fits. Always call list_event_names first to verify event names exist; call list_event_properties if you need a breakdown property. ALWAYS supply a concise `title` (3-8 words) describing what the chart shows.',- '',- 'Series are ordered A, B, C, … (based on array index). Use the letter id from a `formula` series like "A / B * 100" for ratios or conversions.',- '',- 'Examples:',- '- **Unique users per day**: one event series with `segment: "user"` + `chartType: "linear"`.',- '- **Revenue per day**: one event series with `segment: "property_sum"` + `property: "revenue"`.',- '- **Conversion rate over time**: two event series (A = completed, B = started) + a `formula` series `"A / B * 100"` with all three visible, or set `hideSeries: ["A","B"]` to show only the rate.',- '- **Period-over-period**: set `previous: true` to overlay the prior period of equal length.',- ].join('\n'),- schema: z.object({- chartType: z- .enum(objectToZodEnums(chartTypes))- .describe(- 'Chart type. See the decision table in the system prompt — pick `linear`/`area` for trends, `bar`/`pie`/`map` for breakdowns, `metric` for a single number, `funnel`/`conversion`/`sankey` for flows, `retention` for cohorts, `histogram` for numeric distributions.'+export const listDashboards = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'list_dashboards',+ description:+ 'List all dashboards in this project. Each dashboard groups a set of reports the user has built. Use this to discover what already exists before building anything new.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const dashboards = await listDashboardsCore(deps, {+ projectId: context.projectId,+ organizationId: context.organizationId,+ });+ return dashboards.map((d) => ({+ ...d,+ dashboard_url: dashboardUrl(+ context.organizationId,+ context.projectId,+ `/dashboards/${d.id}`),- interval: z- .enum(['minute', 'hour', 'day', 'week', 'month'])- .default('day'),- startDate: z.string().describe('ISO date YYYY-MM-DD'),- endDate: z.string().describe('ISO date YYYY-MM-DD'),- series: z- .array(- z.union([- z.object({- type: z.literal('event'),- name: z- .string()- .describe('Event name — verify with list_event_names'),- displayName: z.string().optional(),- segment: z- .enum([- 'event',- 'user',- 'session',- 'group',- 'user_average',- 'one_event_per_user',- 'property_sum',- 'property_average',- 'property_max',- 'property_min',- ])- .default('event')- .optional()- .describe(- [- 'How to segment/aggregate the event:',- '- `event` — every event firing (default, "all events")',- '- `user` — unique users (e.g. for DAU/MAU)',- '- `session` — unique sessions',- '- `group` — unique groups/accounts',- '- `user_average` — average events per user',- '- `one_event_per_user` — count users who did it at least once',- '- `property_sum` / `property_average` / `property_max` / `property_min` — aggregate a numeric property from the event (requires `property`)',- ].join('\n')- ),- property: z- .string()- .optional()- .describe(- 'Numeric property on the event to aggregate. Required when segment is `property_sum`/`average`/`max`/`min`. Example: `revenue`, `duration`, `score`.'- ),- filters: z- .array(- z.object({- name: z- .string()- .describe(- 'Field to filter on — verify with list_event_properties. Use the bare column name for top-level columns (e.g. `path`, `country`, `device`) or `properties.<key>` for custom JSON properties (e.g. `properties.plan`).'- ),- operator: z- .enum(objectToZodEnums(operators))- .describe(- 'One of: is, isNot, contains, doesNotContain, startsWith, endsWith, regex, isNull, isNotNull, gt, lt, gte, lte. `is` is the default for equality (NOT `equals` / `eq` / `==`).'- ),- value: z- .array(- z.union([z.string(), z.number(), z.boolean(), z.null()])- )- .describe(- 'Values to match. Use [] with isNull/isNotNull.'- ),- })- )- .default([])- .optional(),- }),+ }));+ }+ );++export const listReports = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'list_reports',+ description:+ 'List the reports inside a dashboard. Returns chart type, range, interval, and event series for each. Use this with get_report_data to fetch real numbers.',+ schema: z.object({+ dashboardId: z+ .string()+ .describe('The dashboard ID (from list_dashboards)'),+ }),+ },+ async ({ dashboardId }, context) =>+ listReportsCore(deps, {+ projectId: context.projectId,+ dashboardId,+ organizationId: context.organizationId,+ })+ );++export const getReportData = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_report_data',+ description:+ 'Execute a saved report by ID and return its data. Works for every chart type (linear, bar, area, pie, metric, funnel, retention, etc.). PREFER this over generate_report when the user asks about something a saved report likely already covers.',+ schema: z.object({+ reportId: z.string().describe('The report ID (from list_reports)'),+ }),+ },+ async ({ reportId }, context) =>+ runReport(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ reportId,+ })+ );++export const generateReport = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'generate_report',+ description: [+ 'Generate an ad-hoc chart from a report config. Use only when no saved report fits. Always call list_event_names first to verify event names exist; call list_event_properties if you need a breakdown property. ALWAYS supply a concise `title` (3-8 words) describing what the chart shows.',+ '',+ 'Series are ordered A, B, C, … (based on array index). Use the letter id from a `formula` series like "A / B * 100" for ratios or conversions.',+ '',+ 'Examples:',+ '- **Unique users per day**: one event series with `segment: "user"` + `chartType: "linear"`.',+ '- **Revenue per day**: one event series with `segment: "property_sum"` + `property: "revenue"`.',+ '- **Conversion rate over time**: two event series (A = completed, B = started) + a `formula` series `"A / B * 100"` with all three visible, or set `hideSeries: ["A","B"]` to show only the rate.',+ '- **Period-over-period**: set `previous: true` to overlay the prior period of equal length.',+ ].join('\n'),+ schema: z.object({+ chartType: z+ .enum(objectToZodEnums(chartTypes))+ .describe(+ 'Chart type. See the decision table in the system prompt — pick `linear`/`area` for trends, `bar`/`pie`/`map` for breakdowns, `metric` for a single number, `funnel`/`conversion`/`sankey` for flows, `retention` for cohorts, `histogram` for numeric distributions.'+ ),+ interval: z+ .enum(['minute', 'hour', 'day', 'week', 'month'])+ .default('day'),+ startDate: z.string().describe('ISO date YYYY-MM-DD'),+ endDate: z.string().describe('ISO date YYYY-MM-DD'),+ series: z+ .array(+ z.union([+ z.object({+ type: z.literal('event'),+ name: z+ .string()+ .describe('Event name — verify with list_event_names'),+ displayName: z.string().optional(),+ segment: z+ .enum([+ 'event',+ 'user',+ 'session',+ 'group',+ 'user_average',+ 'one_event_per_user',+ 'property_sum',+ 'property_average',+ 'property_max',+ 'property_min',+ ])+ .default('event')+ .optional()+ .describe(+ [+ 'How to segment/aggregate the event:',+ '- `event` — every event firing (default, "all events")',+ '- `user` — unique users (e.g. for DAU/MAU)',+ '- `session` — unique sessions',+ '- `group` — unique groups/accounts',+ '- `user_average` — average events per user',+ '- `one_event_per_user` — count users who did it at least once',+ '- `property_sum` / `property_average` / `property_max` / `property_min` — aggregate a numeric property from the event (requires `property`)',+ ].join('\n')+ ),+ property: z+ .string()+ .optional()+ .describe(+ 'Numeric property on the event to aggregate. Required when segment is `property_sum`/`average`/`max`/`min`. Example: `revenue`, `duration`, `score`.'+ ),+ filters: z+ .array(+ z.object({+ name: z+ .string()+ .describe(+ 'Field to filter on — verify with list_event_properties. Use the bare column name for top-level columns (e.g. `path`, `country`, `device`) or `properties.<key>` for custom JSON properties (e.g. `properties.plan`).'+ ),+ operator: z+ .enum(objectToZodEnums(operators))+ .describe(+ 'One of: is, isNot, contains, doesNotContain, startsWith, endsWith, regex, isNull, isNotNull, gt, lt, gte, lte. `is` is the default for equality (NOT `equals` / `eq` / `==`).'+ ),+ value: z+ .array(+ z.union([+ z.string(),+ z.number(),+ z.boolean(),+ z.null(),+ ])+ )+ .describe(+ 'Values to match. Use [] with isNull/isNotNull.'+ ),+ })+ )+ .default([])+ .optional(),+ }),+ z.object({+ type: z.literal('formula'),+ formula: z+ .string()+ .describe(+ 'Expression referencing other series by letter id. Examples: `A / B * 100` (conversion rate), `A + B` (union total), `A - B` (difference). Earlier series are A, B, C, …'+ ),+ displayName: z.string().optional(),+ hideSeries: z+ .array(z.string())+ .optional()+ .describe(+ 'Letter ids (e.g. ["A", "B"]) of series used by the formula that should be hidden from the chart — useful when you only want to display the computed ratio.'+ ),+ }),+ ])+ )+ .min(1)+ .describe(+ 'At least one series. Mix event series and formula series to compute ratios.'+ ),+ breakdowns: z+ .array(z.object({- type: z.literal('formula'),- formula: z- .string()- .describe(- 'Expression referencing other series by letter id. Examples: `A / B * 100` (conversion rate), `A + B` (union total), `A - B` (difference). Earlier series are A, B, C, …'- ),- displayName: z.string().optional(),- hideSeries: z- .array(z.string())- .optional()- .describe(- 'Letter ids (e.g. ["A", "B"]) of series used by the formula that should be hidden from the chart — useful when you only want to display the computed ratio.'- ),- }),- ])- )- .min(1)- .describe(- 'At least one series. Mix event series and formula series to compute ratios.'- ),- breakdowns: z- .array(- z.object({- name: z.string().describe('Property key to group by'),+ name: z.string().describe('Property key to group by'),+ })+ )+ .default([])+ .optional(),+ // No `.default()` here on purpose: it would make an omitted metric+ // indistinguishable from an explicit `sum`, and the fallback depends on+ // the chart type (see below).+ metric: z+ .enum(['sum', 'count', 'average', 'min', 'max'])+ .optional()+ .describe(+ 'How a series is aggregated for display. Only the metric and map chart types read this; `count` is unique profiles. Omit it unless the user asked for a specific aggregation — metric cards then default to unique profiles.'+ ),+ previous: z+ .boolean()+ .optional()+ .describe(+ 'Overlay the same-length previous period for comparison. Great for "vs last week" / "vs last month" questions.'+ ),+ lineType: z+ .enum(objectToZodEnums(lineTypes))+ .optional()+ .describe(+ 'Line style for linear/area charts. Default to `monotone` unless you have a reason not to.'+ ),+ limit: z+ .number()+ .min(1)+ .max(500)+ .optional()+ .describe(+ 'Top-N limit for bar/pie/sankey. Example: "top 10 pages" → limit: 10.'+ ),+ unit: z+ .string()+ .optional()+ .describe('Y-axis unit suffix, e.g. `%`, `$`, `ms`, `users`.'),+ funnelGroup: z+ .enum(['session', 'profile'])+ .optional()+ .describe(+ 'Only for `chartType: "funnel"`. Whether each funnel step counts by unique session or unique profile. Default is profile.'+ ),+ title: z+ .string()+ .optional()+ .describe(+ 'Short, descriptive card title (3-8 words) — e.g. "Signups per day, last 7 days". Always provide one.'+ ),+ }),+ },+ async (input, context) => {+ // biome-ignore lint/suspicious/noExplicitAny: union discrimination between event/formula series is easier to do explicitly+ const series = (input.series as any[]).map((s: any, i: number) => {+ const id = ALPHABET_IDS[i] ?? String(i + 1);+ if (s?.type === 'formula') {+ return {+ id,+ type: 'formula' as const,+ formula: s.formula,+ displayName: s.displayName,+ ...(Array.isArray(s.hideSeries)+ ? { hideSeries: s.hideSeries }+ : {}),+ };+ }+ return {+ id,+ type: 'event' as const,+ name: s.name,+ displayName: s.displayName ?? s.name,+ segment: s.segment ?? 'event',+ ...(s.property ? { property: s.property } : {}),+ filters: s.filters ?? [],+ };+ });++ const options =+ input.chartType === 'funnel' && input.funnelGroup+ ? { type: 'funnel' as const, funnelGroup: input.funnelGroup }+ : undefined;++ const config = {+ projectId: context.projectId,+ chartType: input.chartType,+ interval: input.interval,+ startDate: input.startDate,+ endDate: input.endDate,+ series,+ breakdowns: (input.breakdowns ?? []).map(+ (b: { name: string }, i: number) => ({+ id: String(i + 1),+ name: b.name,})- )- .default([])- .optional(),- // No `.default()` here on purpose: it would make an omitted metric- // indistinguishable from an explicit `sum`, and the fallback depends on- // the chart type (see below).- metric: z- .enum(['sum', 'count', 'average', 'min', 'max'])- .optional()- .describe(- 'How a series is aggregated for display. Only the metric and map chart types read this; `count` is unique profiles. Omit it unless the user asked for a specific aggregation — metric cards then default to unique profiles.'- ),- previous: z- .boolean()- .optional()- .describe(- 'Overlay the same-length previous period for comparison. Great for "vs last week" / "vs last month" questions.'- ),- lineType: z- .enum(objectToZodEnums(lineTypes))- .optional()- .describe(- 'Line style for linear/area charts. Default to `monotone` unless you have a reason not to.'- ),- limit: z- .number()- .min(1)- .max(500)- .optional()- .describe(- 'Top-N limit for bar/pie/sankey. Example: "top 10 pages" → limit: 10.'- ),- unit: z- .string()- .optional()- .describe('Y-axis unit suffix, e.g. `%`, `$`, `ms`, `users`.'),- funnelGroup: z- .enum(['session', 'profile'])- .optional()- .describe(- 'Only for `chartType: "funnel"`. Whether each funnel step counts by unique session or unique profile. Default is profile.'),- title: z- .string()- .optional()- .describe(- 'Short, descriptive card title (3-8 words) — e.g. "Signups per day, last 7 days". Always provide one.'- ),- }),- },- async (input, context) => {- // biome-ignore lint/suspicious/noExplicitAny: union discrimination between event/formula series is easier to do explicitly- const series = (input.series as any[]).map((s: any, i: number) => {- const id = ALPHABET_IDS[i] ?? String(i + 1);- if (s?.type === 'formula') {+ range: 'custom' as const,+ // A metric card has always shown the total unique count, so an+ // unspecified metric must stay `count` there — `sum` would silently turn+ // "1.2k users" into "45k events".+ metric:+ input.metric ?? (input.chartType === 'metric' ? 'count' : 'sum'),+ previous: input.previous ?? false,+ ...(input.lineType ? { lineType: input.lineType } : {}),+ ...(input.limit ? { limit: input.limit } : {}),+ ...(input.unit ? { unit: input.unit } : {}),+ ...(options ? { options } : {}),+ };++ // Pre-validate against the real report schema so invalid shapes+ // (bad operator, wrong filter value type, unknown chartType) are+ // returned to the model as a structured error, letting the agent+ // loop self-correct instead of producing a broken chart.+ const parsed = zReportInput.safeParse(config);+ if (!parsed.success) {return {- id,- type: 'formula' as const,- formula: s.formula,- displayName: s.displayName,- ...(Array.isArray(s.hideSeries) ? { hideSeries: s.hideSeries } : {}),+ error:+ 'Invalid report config — fix the issues and call generate_report again.',+ issues: parsed.error.issues.map((i) => ({+ path: i.path.join('.'),+ message: i.message,+ })),};}++ const chart = await runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: parsed.data as Parameters<+ typeof runReportFromConfig+ >[1]['config'],+ });return {- id,- type: 'event' as const,- name: s.name,- displayName: s.displayName ?? s.name,- segment: s.segment ?? 'event',- ...(s.property ? { property: s.property } : {}),- filters: s.filters ?? [],- };- });-- const options =- input.chartType === 'funnel' && input.funnelGroup- ? { type: 'funnel' as const, funnelGroup: input.funnelGroup }- : undefined;-- const config = {- projectId: context.projectId,- chartType: input.chartType,- interval: input.interval,- startDate: input.startDate,- endDate: input.endDate,- series,- breakdowns: (input.breakdowns ?? []).map(- (b: { name: string }, i: number) => ({- id: String(i + 1),- name: b.name,- })- ),- range: 'custom' as const,- // A metric card has always shown the total unique count, so an- // unspecified metric must stay `count` there — `sum` would silently turn- // "1.2k users" into "45k events".- metric: input.metric ?? (input.chartType === 'metric' ? 'count' : 'sum'),- previous: input.previous ?? false,- ...(input.lineType ? { lineType: input.lineType } : {}),- ...(input.limit ? { limit: input.limit } : {}),- ...(input.unit ? { unit: input.unit } : {}),- ...(options ? { options } : {}),- };-- // Pre-validate against the real report schema so invalid shapes- // (bad operator, wrong filter value type, unknown chartType) are- // returned to the model as a structured error, letting the agent- // loop self-correct instead of producing a broken chart.- const parsed = zReportInput.safeParse(config);- if (!parsed.success) {- return {- error:- 'Invalid report config — fix the issues and call generate_report again.',- issues: parsed.error.issues.map((i) => ({- path: i.path.join('.'),- message: i.message,- })),+ // Use the model-supplied title when present; the frontend+ // falls back to a derived title from input if this is empty.+ ...(input.title?.trim() ? { name: input.title.trim() } : {}),+ ...chart,};}-- const chart = await runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: parsed.data as Parameters<- typeof runReportFromConfig- >[0]['config'],- });- return {- // Use the model-supplied title when present; the frontend- // falls back to a derived title from input if this is empty.- ...(input.title?.trim() ? { name: input.title.trim() } : {}),- ...chart,- };- }-);+ );// Letter ids for series. Must match the chart engine's expectation// that series are referenced by A, B, C, … in formula expressions.@@ -451,506 +473,518 @@ const ALPHABET_IDS = [// AGGREGATE ANALYTICS — default to current page's filters// ─────────────────────────────────────────────────────────────────-export const getAnalyticsOverview = chatTool(- {- name: 'get_analytics_overview',- description:- "Top-level metrics: unique visitors, total pageviews, sessions, bounce rate, avg session duration, plus an optional time series. Defaults to the user's current date range.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- interval: z- .enum(['hour', 'day', 'week', 'month'])- .default('day')- .optional(),- }),- },- async ({ startDate, endDate, interval }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- return getAnalyticsOverviewCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- interval: interval ?? 'day',- filters: pageContextFilters(pageContext),- });- }-);--export const getTopPages = chatTool(- {- name: 'get_top_pages',- description:- "Top pages ranked by visitors / pageviews. Returns path, sessions, pageviews, bounce rate, avg duration. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const pages = await getTopPagesCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: limit ?? 20,- filters: pageContextFilters(pageContext),- });- return truncateRows(pages, 50);- }-);--export const getTopReferrers = chatTool(- {- name: 'get_top_referrers',- description:- "Traffic source breakdown — by referrer name, type, or UTM source/medium/campaign. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- breakdown: z- .enum(['referrer_name', 'referrer_type', 'referrer'])- .default('referrer_name')- .optional(),- }),- },- async ({ startDate, endDate, breakdown }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const rows = await getTrafficBreakdownCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: (breakdown ?? 'referrer_name') as- | 'referrer_name'- | 'referrer_type'- | 'referrer',- filters: pageContextFilters(pageContext),- });- return truncateRows(rows, 50);- }-);--export const getCountryBreakdown = chatTool(- {- name: 'get_country_breakdown',- description:- "Visitor breakdown by country / region / city. Returns sessions and percentage of total. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- breakdown: z- .enum(['country', 'region', 'city'])- .default('country')- .optional(),- }),- },- async ({ startDate, endDate, breakdown }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const rows = await getTrafficBreakdownCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: (breakdown ?? 'country') as 'country' | 'region' | 'city',- filters: pageContextFilters(pageContext),- });- return truncateRows(rows, 100);- }-);--export const getDeviceBreakdown = chatTool(- {- name: 'get_device_breakdown',- description:- "Visitor breakdown by device / browser / OS. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- breakdown: z- .enum(['device', 'browser', 'os'])- .default('device')- .optional(),- }),- },- async ({ startDate, endDate, breakdown }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const rows = await getTrafficBreakdownCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: (breakdown ?? 'device') as 'device' | 'browser' | 'os',- filters: pageContextFilters(pageContext),- });- return truncateRows(rows, 50);- }-);--export const getRollingActiveUsers = chatTool(- {- name: 'get_rolling_active_users',- description:- 'Rolling active-users trend (DAU/WAU/MAU). Returns BOTH the latest single value AND a renderable chart config (so the UI draws a line chart). Default is DAU over 30 days; pass `windowDays: 7` for WAU or `windowDays: 30` for MAU. ALWAYS supply a concise `title` (3-8 words) that describes what the chart shows.',- schema: z.object({- /**- * The rolling window. 1 = DAU (default), 7 = WAU, 30 = MAU.- */- windowDays: z.number().min(1).max(90).default(1).optional(),- /** Number of days to chart. Defaults to 30. */- days: z.number().min(1).max(365).default(30).optional(),- title: z- .string()- .optional()- .describe(- 'Short, descriptive card title (3-8 words) — e.g. "Monthly active users trend". Always provide one.'- ),- }),- },- async ({ windowDays, days, title }, context) => {- const window = windowDays ?? 1;- const range = days ?? 30;-- // Build a chart config that represents "unique users per day".- // We use a user-segment on `screen_view` — OpenPanel's standard- // pageview event — with a linear chart. The ChartEngine dedupes- // per profile_id because of `segment: 'user'`.- const endDate = new Date().toISOString().slice(0, 10);- const startDate = new Date(Date.now() - (range - 1) * 86_400_000)- .toISOString()- .slice(0, 10);- const label =- window === 1- ? 'DAU'- : window === 7- ? 'WAU'- : window === 30- ? 'MAU'- : `${window}-day active users`;-- const config = {- chartType: 'linear' as const,- interval: 'day' as const,- startDate,- endDate,- range: 'custom' as const,- metric: 'sum' as const,- previous: false,- breakdowns: [],- series: [- {- id: '1',+export const getAnalyticsOverview = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_analytics_overview',+ description:+ "Top-level metrics: unique visitors, total pageviews, sessions, bounce rate, avg session duration, plus an optional time series. Defaults to the user's current date range.",+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ interval: z+ .enum(['hour', 'day', 'week', 'month'])+ .default('day')+ .optional(),+ }),+ },+ async ({ startDate, endDate, interval }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ return getAnalyticsOverviewCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ interval: interval ?? 'day',+ filters: pageContextFilters(pageContext),+ });+ }+ );++export const getTopPages = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_top_pages',+ description:+ "Top pages ranked by visitors / pageviews. Returns path, sessions, pageviews, bounce rate, avg duration. Respects the page's active property filters.",+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async ({ startDate, endDate, limit }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const pages = await getTopPagesCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: limit ?? 20,+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(pages, 50);+ }+ );++export const getTopReferrers = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_top_referrers',+ description:+ "Traffic source breakdown — by referrer name, type, or UTM source/medium/campaign. Respects the page's active property filters.",+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ breakdown: z+ .enum(['referrer_name', 'referrer_type', 'referrer'])+ .default('referrer_name')+ .optional(),+ }),+ },+ async ({ startDate, endDate, breakdown }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await getTrafficBreakdownCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: (breakdown ?? 'referrer_name') as+ | 'referrer_name'+ | 'referrer_type'+ | 'referrer',+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(rows, 50);+ }+ );++export const getCountryBreakdown = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_country_breakdown',+ description:+ "Visitor breakdown by country / region / city. Returns sessions and percentage of total. Respects the page's active property filters.",+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ breakdown: z+ .enum(['country', 'region', 'city'])+ .default('country')+ .optional(),+ }),+ },+ async ({ startDate, endDate, breakdown }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await getTrafficBreakdownCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: (breakdown ?? 'country') as 'country' | 'region' | 'city',+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(rows, 100);+ }+ );++export const getDeviceBreakdown = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_device_breakdown',+ description:+ "Visitor breakdown by device / browser / OS. Respects the page's active property filters.",+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ breakdown: z+ .enum(['device', 'browser', 'os'])+ .default('device')+ .optional(),+ }),+ },+ async ({ startDate, endDate, breakdown }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await getTrafficBreakdownCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: (breakdown ?? 'device') as 'device' | 'browser' | 'os',+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(rows, 50);+ }+ );++export const getRollingActiveUsers = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_rolling_active_users',+ description:+ 'Rolling active-users trend (DAU/WAU/MAU). Returns BOTH the latest single value AND a renderable chart config (so the UI draws a line chart). Default is DAU over 30 days; pass `windowDays: 7` for WAU or `windowDays: 30` for MAU. ALWAYS supply a concise `title` (3-8 words) that describes what the chart shows.',+ schema: z.object({+ /**+ * The rolling window. 1 = DAU (default), 7 = WAU, 30 = MAU.+ */+ windowDays: z.number().min(1).max(90).default(1).optional(),+ /** Number of days to chart. Defaults to 30. */+ days: z.number().min(1).max(365).default(30).optional(),+ title: z+ .string()+ .optional()+ .describe(+ 'Short, descriptive card title (3-8 words) — e.g. "Monthly active users trend". Always provide one.'+ ),+ }),+ },+ async ({ windowDays, days, title }, context) => {+ const window = windowDays ?? 1;+ const range = days ?? 30;++ // Build a chart config that represents "unique users per day".+ // We use a user-segment on `screen_view` — OpenPanel's standard+ // pageview event — with a linear chart. The ChartEngine dedupes+ // per profile_id because of `segment: 'user'`.+ const endDate = new Date().toISOString().slice(0, 10);+ const startDate = new Date(Date.now() - (range - 1) * 86_400_000)+ .toISOString()+ .slice(0, 10);+ const label =+ window === 1+ ? 'DAU'+ : window === 7+ ? 'WAU'+ : window === 30+ ? 'MAU'+ : `${window}-day active users`;++ const config = {+ chartType: 'linear' as const,+ interval: 'day' as const,+ startDate,+ endDate,+ range: 'custom' as const,+ metric: 'sum' as const,+ previous: false,+ breakdowns: [],+ series: [+ {+ id: '1',+ type: 'event' as const,+ name: 'screen_view',+ displayName: label,+ segment: 'user' as const,+ filters: [],+ },+ ],+ };++ const chart = await runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: config as Parameters<typeof runReportFromConfig>[1]['config'],+ });++ // Also keep the rolling summary so the model can quote the+ // single-number "MAU is 205,127" line.+ const summary = await getRollingActiveUsersCore(deps, {+ projectId: context.projectId,+ days: window,+ });++ return {+ // `name` is the title the frontend `ChatReportResult` uses for+ // the card header. The model is asked to supply a `title` —+ // we use it when present, falling back to a generic label.+ name: title?.trim() || `${label} — last ${range} days`,+ label,+ window,+ summary,+ // Keys the frontend report renderer knows about.+ ...chart,+ };+ }+ );++export const getFunnel = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_funnel',+ description:+ 'Multi-step conversion funnel. Returns BOTH a renderable funnel chart AND the numeric breakdown (users per step, conversion rates, drop-off). The UI draws an actual funnel chart. Provide an ordered list of event names — verify with list_event_names first. ALWAYS supply a concise `title` (3-8 words) describing what the funnel measures.',+ schema: z.object({+ steps: z+ .array(z.string())+ .min(2)+ .max(10)+ .describe('Ordered event names. Verify with list_event_names first.'),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ windowHours: z.number().min(1).max(720).default(24).optional(),+ groupBy: z+ .enum(['session_id', 'profile_id'])+ .default('session_id')+ .optional(),+ title: z+ .string()+ .optional()+ .describe(+ 'Short, descriptive card title (3-8 words) — e.g. "Cart to checkout conversion" or "Signup to paid funnel". Always provide one.'+ ),+ }),+ },+ async (+ { steps, startDate, endDate, windowHours, groupBy, title },+ context+ ) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });++ // Raw funnel numbers — step-by-step breakdown for the model to+ // reason about.+ const numbers = await getFunnelCore(deps, {+ projectId: context.projectId,+ steps,+ startDate: range.startDate,+ endDate: range.endDate,+ windowHours,+ groupBy,+ });++ // Chart config — same shape `generate_report` returns, so the+ // frontend's `ChatReportResult` renderer draws an actual funnel+ // chart via `<ReportChart>`.+ const chartConfig = {+ chartType: 'funnel' as const,+ interval: 'day' as const,+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom' as const,+ metric: 'sum' as const,+ previous: false,+ breakdowns: [],+ funnelGroup: groupBy ?? 'session_id',+ funnelWindowSeconds: (windowHours ?? 24) * 3600,+ series: (steps as string[]).map((name: string, i: number) => ({+ id: String(i + 1),type: 'event' as const,- name: 'screen_view',- displayName: label,- segment: 'user' as const,+ name,+ displayName: name,+ segment: 'event' as const,filters: [],- },- ],- };-- const chart = await runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: config as Parameters<typeof runReportFromConfig>[0]['config'],- });-- // Also keep the rolling summary so the model can quote the- // single-number "MAU is 205,127" line.- const summary = await getRollingActiveUsersCore({- projectId: context.projectId,- days: window,- });-- return {- // `name` is the title the frontend `ChatReportResult` uses for- // the card header. The model is asked to supply a `title` —- // we use it when present, falling back to a generic label.- name: title?.trim() || `${label} — last ${range} days`,- label,- window,- summary,- // Keys the frontend report renderer knows about.- ...chart,- };- }-);--export const getFunnel = chatTool(- {- name: 'get_funnel',- description:- 'Multi-step conversion funnel. Returns BOTH a renderable funnel chart AND the numeric breakdown (users per step, conversion rates, drop-off). The UI draws an actual funnel chart. Provide an ordered list of event names — verify with list_event_names first. ALWAYS supply a concise `title` (3-8 words) describing what the funnel measures.',- schema: z.object({- steps: z- .array(z.string())- .min(2)- .max(10)- .describe('Ordered event names. Verify with list_event_names first.'),- startDate: z.string().optional(),- endDate: z.string().optional(),- windowHours: z.number().min(1).max(720).default(24).optional(),- groupBy: z- .enum(['session_id', 'profile_id'])- .default('session_id')- .optional(),- title: z- .string()- .optional()- .describe(- 'Short, descriptive card title (3-8 words) — e.g. "Cart to checkout conversion" or "Signup to paid funnel". Always provide one.'- ),- }),- },- async (- { steps, startDate, endDate, windowHours, groupBy, title },- context- ) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });-- // Raw funnel numbers — step-by-step breakdown for the model to- // reason about.- const numbers = await getFunnelCore({- projectId: context.projectId,- steps,- startDate: range.startDate,- endDate: range.endDate,- windowHours,- groupBy,- });-- // Chart config — same shape `generate_report` returns, so the- // frontend's `ChatReportResult` renderer draws an actual funnel- // chart via `<ReportChart>`.- const chartConfig = {- chartType: 'funnel' as const,- interval: 'day' as const,- startDate: range.startDate,- endDate: range.endDate,- range: 'custom' as const,- metric: 'sum' as const,- previous: false,- breakdowns: [],- funnelGroup: groupBy ?? 'session_id',- funnelWindowSeconds: (windowHours ?? 24) * 3600,- series: (steps as string[]).map((name: string, i: number) => ({- id: String(i + 1),- type: 'event' as const,- name,- displayName: name,- segment: 'event' as const,- filters: [],- })),- };-- const chart = await runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: chartConfig as Parameters<- typeof runReportFromConfig- >[0]['config'],- });-- return {- name: title?.trim() || `Funnel: ${steps.join(' → ')}`,- numbers,- // Keys the frontend report renderer knows about.- ...chart,- };- }-);--export const getRetentionCohort = chatTool(- {- name: 'get_retention_cohort',- description:- 'Weekly active-user retention cohort for the last 12 weeks. Each row is a cohort (the week users were first seen) with cohort size (sum), retained user counts (values) and retained share (percentages) for subsequent weeks; a leading weighted-average row summarises all cohorts.',- schema: z.object({}),- },- async (_input, context) => getRetentionCohortCore(context.projectId)-);--export const getUserFlow = chatTool(- {- name: 'get_user_flow',- description:- 'Sankey-style user navigation flow from a starting event. Returns nodes + links suitable for visualizing common paths.',- schema: z.object({- startEvent: z.string().describe('Event name where the flow starts'),- endEvent: z.string().optional().describe('Required when mode=between'),- mode: z.enum(['after', 'before', 'between']).default('after'),- steps: z.number().min(2).max(10).default(5).optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async (- { startEvent, endEvent, mode, steps, startDate, endDate },- context- ) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- return getUserFlowCore({- projectId: context.projectId,- startEvent,- endEvent,- mode,- steps,- startDate: range.startDate,- endDate: range.endDate,- });- }-);+ })),+ };++ const chart = await runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: chartConfig as Parameters<+ typeof runReportFromConfig+ >[1]['config'],+ });++ return {+ name: title?.trim() || `Funnel: ${steps.join(' → ')}`,+ numbers,+ // Keys the frontend report renderer knows about.+ ...chart,+ };+ }+ );++export const getRetentionCohort = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_retention_cohort',+ description:+ 'Weekly active-user retention cohort for the last 12 weeks. Each row is a cohort (the week users were first seen) with cohort size (sum), retained user counts (values) and retained share (percentages) for subsequent weeks; a leading weighted-average row summarises all cohorts.',+ schema: z.object({}),+ },+ async (_input, context) => getRetentionCohortCore(deps, context.projectId)+ );++export const getUserFlow = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_user_flow',+ description:+ 'Sankey-style user navigation flow from a starting event. Returns nodes + links suitable for visualizing common paths.',+ schema: z.object({+ startEvent: z.string().describe('Event name where the flow starts'),+ endEvent: z.string().optional().describe('Required when mode=between'),+ mode: z.enum(['after', 'before', 'between']).default('after'),+ steps: z.number().min(2).max(10).default(5).optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async (+ { startEvent, endEvent, mode, steps, startDate, endDate },+ context+ ) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ return getUserFlowCore(deps, {+ projectId: context.projectId,+ startEvent,+ endEvent,+ mode,+ steps,+ startDate: range.startDate,+ endDate: range.endDate,+ });+ }+ );// ─────────────────────────────────────────────────────────────────// FREE-FORM QUERIES (escape hatches when nothing else fits)// ─────────────────────────────────────────────────────────────────-export const queryEvents = chatTool(- {- name: 'query_events',- description:- "Free-form query over raw events with filters (path, country, device, browser, OS, referrer, custom properties, profileId, eventNames). Use this when aggregate tools don't cover the question.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- eventNames: z.array(z.string()).optional(),- path: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- os: z.string().optional(),- referrer: z.string().optional(),- referrerName: z.string().optional(),- referrerType: z.string().optional(),- profileId: z.string().optional(),- properties: z.record(z.string(), z.string()).optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async (input, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: input.startDate ?? pageContext?.filters?.startDate,- endDate: input.endDate ?? pageContext?.filters?.endDate,- });- const rows = await queryEventsCore({- projectId: context.projectId,- ...input,- startDate: range.startDate,- endDate: range.endDate,- limit: input.limit ?? 20,- });- return truncateRows(rows, 100);- }-);--export const querySessions = chatTool(- {- name: 'query_sessions',- description:- 'Free-form query over raw sessions with filters (country, device, browser, OS, referrer, profileId).',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- os: z.string().optional(),- referrer: z.string().optional(),- referrerName: z.string().optional(),- referrerType: z.string().optional(),- profileId: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async (input, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: input.startDate ?? pageContext?.filters?.startDate,- endDate: input.endDate ?? pageContext?.filters?.endDate,- });- const rows = await querySessionsCore({- projectId: context.projectId,- ...input,- startDate: range.startDate,- endDate: range.endDate,- limit: input.limit ?? 20,- });- return truncateRows(rows, 100);- }-);--export const findProfiles = chatTool(- {- name: 'find_profiles',- description:- 'Search for user profiles by name, email, country, device, inactivity, minimum sessions, or having performed a specific event.',- schema: z.object({- name: z.string().optional(),- email: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- inactiveDays: z.number().min(1).optional(),- minSessions: z.number().min(1).optional(),- performedEvent: z.string().optional(),- sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async (input, context) => {- const profiles = await findProfilesCore({- projectId: context.projectId,- ...input,- });- return truncateRows(- profiles.map((p) => ({- ...p,- dashboard_url: dashboardUrl(- context.organizationId,- context.projectId,- `/profiles/${p.id}`- ),- })),- 100- );- }-);+export const queryEvents = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'query_events',+ description:+ "Free-form query over raw events with filters (path, country, device, browser, OS, referrer, custom properties, profileId, eventNames). Use this when aggregate tools don't cover the question.",+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ path: z.string().optional(),+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ os: z.string().optional(),+ referrer: z.string().optional(),+ referrerName: z.string().optional(),+ referrerType: z.string().optional(),+ profileId: z.string().optional(),+ properties: z.record(z.string(), z.string()).optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async (input, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: input.startDate ?? pageContext?.filters?.startDate,+ endDate: input.endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await queryEventsCore(deps, {+ projectId: context.projectId,+ ...input,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: input.limit ?? 20,+ });+ return truncateRows(rows, 100);+ }+ );++export const querySessions = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'query_sessions',+ description:+ 'Free-form query over raw sessions with filters (country, device, browser, OS, referrer, profileId).',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ os: z.string().optional(),+ referrer: z.string().optional(),+ referrerName: z.string().optional(),+ referrerType: z.string().optional(),+ profileId: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async (input, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: input.startDate ?? pageContext?.filters?.startDate,+ endDate: input.endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await querySessionsCore(deps, {+ projectId: context.projectId,+ ...input,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: input.limit ?? 20,+ });+ return truncateRows(rows, 100);+ }+ );++export const findProfiles = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'find_profiles',+ description:+ 'Search for user profiles by name, email, country, device, inactivity, minimum sessions, or having performed a specific event.',+ schema: z.object({+ name: z.string().optional(),+ email: z.string().optional(),+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ inactiveDays: z.number().min(1).optional(),+ minSessions: z.number().min(1).optional(),+ performedEvent: z.string().optional(),+ sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async (input, context) => {+ const profiles = await findProfilesCore(deps, {+ projectId: context.projectId,+ ...input,+ });+ return truncateRows(+ profiles.map((p) => ({+ ...p,+ dashboard_url: dashboardUrl(+ context.organizationId,+ context.projectId,+ `/profiles/${p.id}`+ ),+ })),+ 100+ );+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/dashboard.ts b/packages/core/src/modules/assistant/src/tools/dashboard.tsindex 865d6fde8..2aba6330b 100644--- a/packages/core/src/modules/assistant/src/tools/dashboard.ts+++ b/packages/core/src/modules/assistant/src/tools/dashboard.ts@@ -1,14 +1,15 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';import { getChartStartEndDate } from '../../../../shared/date';import {- AggregateChartEngine,- ChartEngine,- getDashboardById,- getFunnel,- getReportsByDashboardId,- getSettingsForProject,-} from '../../../../v1-compat';+ executeAggregateChart,+ executeChart,+} from '../../../chart/chart.service';+import { getFunnel } from '../../../chart/funnel.service';+import { getDashboardById } from '../../../dashboard/dashboard.service';+import { getSettingsForProject } from '../../../organization/organization.service';import type { IChartRange, IInterval } from '../../../report/report.constants';+import { getReportsByDashboardId } from '../../../report/report.service';import { chatTool, dashboardUrl } from './helpers';// Cap on parallel report execution. Real dashboards rarely exceed this,@@ -16,127 +17,136 @@ import { chatTool, dashboardUrl } from './helpers';// timeout or hammer ClickHouse with one request.const MAX_REPORTS_PER_SUMMARY = 30;-export const summarizeDashboard = chatTool(- {- name: 'summarize_dashboard',- description: [- 'Run every report on the current dashboard in parallel and return their data so you can summarize, compare, or explain the dashboard as a whole. Reads dashboardId from the active page context — only works when the user is viewing a dashboard.',- '',- 'Honors the dashboard-level range/interval picker (the OverviewRange + OverviewInterval at the top of the page) so each report runs against the window the user is currently looking at, not its saved default.',- '',- 'Returns: { dashboard, reports: [{ id, name, chartType, startDate, endDate, data | error }] }. Use this once and synthesize across the results — do NOT also call get_report_data for the same reports.',- ].join('\n'),- schema: z.object({}),- },- async (_input, context) => {- const dashboardId = context.pageContext?.ids?.dashboardId;- if (!dashboardId) {- return {- error:- 'No dashboard in current page context. Ask the user to open a dashboard, or use list_dashboards + list_reports + get_report_data instead.',- };- }+export const summarizeDashboard = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'summarize_dashboard',+ description: [+ 'Run every report on the current dashboard in parallel and return their data so you can summarize, compare, or explain the dashboard as a whole. Reads dashboardId from the active page context — only works when the user is viewing a dashboard.',+ '',+ 'Honors the dashboard-level range/interval picker (the OverviewRange + OverviewInterval at the top of the page) so each report runs against the window the user is currently looking at, not its saved default.',+ '',+ 'Returns: { dashboard, reports: [{ id, name, chartType, startDate, endDate, data | error }] }. Use this once and synthesize across the results — do NOT also call get_report_data for the same reports.',+ ].join('\n'),+ schema: z.object({}),+ },+ async (_input, context) => {+ const dashboardId = context.pageContext?.ids?.dashboardId;+ if (!dashboardId) {+ return {+ error:+ 'No dashboard in current page context. Ask the user to open a dashboard, or use list_dashboards + list_reports + get_report_data instead.',+ };+ }- const dashboard = await getDashboardById(dashboardId, context.projectId);- if (!dashboard) {- return { error: 'Dashboard not found', dashboardId };- }+ const dashboard = await getDashboardById(+ deps,+ dashboardId,+ context.projectId+ );+ if (!dashboard) {+ return { error: 'Dashboard not found', dashboardId };+ }- const allReports = await getReportsByDashboardId(dashboardId);- const meta = {- id: dashboard.id,- name: dashboard.name,- dashboard_url: dashboardUrl(- context.organizationId,- context.projectId,- `/dashboards/${dashboard.id}`- ),- };-- if (allReports.length === 0) {- return {- dashboard: meta,- reports: [],- note: 'Dashboard has no reports.',+ const allReports = await getReportsByDashboardId(deps, dashboardId);+ const meta = {+ id: dashboard.id,+ name: dashboard.name,+ dashboard_url: dashboardUrl(+ context.organizationId,+ context.projectId,+ `/dashboards/${dashboard.id}`+ ),};- }- const reports = allReports.slice(0, MAX_REPORTS_PER_SUMMARY);- const truncated = allReports.length > MAX_REPORTS_PER_SUMMARY;+ if (allReports.length === 0) {+ return {+ dashboard: meta,+ reports: [],+ note: 'Dashboard has no reports.',+ };+ }- const { timezone } = await getSettingsForProject(context.projectId);+ const reports = allReports.slice(0, MAX_REPORTS_PER_SUMMARY);+ const truncated = allReports.length > MAX_REPORTS_PER_SUMMARY;- const filters = context.pageContext?.filters;- const overrideRange = filters?.range as IChartRange | undefined;- const overrideStart = filters?.startDate;- const overrideEnd = filters?.endDate;- const overrideInterval = filters?.interval as IInterval | undefined;+ const { timezone } = await getSettingsForProject(deps, context.projectId);- const results = await Promise.all(- reports.map(async (report) => {- try {- // Apply the dashboard's global range picker to each report.- // If both startDate + endDate are set, that wins; otherwise- // the preset range is used. Mirrors how ReportItem behaves- // when the page-level range/interval flow into a report.- const useCustom = !!(overrideStart && overrideEnd);- const merged = {- ...report,- ...(useCustom- ? {- range: 'custom' as IChartRange,- startDate: overrideStart,- endDate: overrideEnd,- }- : overrideRange- ? { range: overrideRange, startDate: null, endDate: null }- : {}),- ...(overrideInterval ? { interval: overrideInterval } : {}),- };+ const filters = context.pageContext?.filters;+ const overrideRange = filters?.range as IChartRange | undefined;+ const overrideStart = filters?.startDate;+ const overrideEnd = filters?.endDate;+ const overrideInterval = filters?.interval as IInterval | undefined;- const { startDate, endDate } = getChartStartEndDate(merged, timezone);- const chartInput = { ...merged, startDate, endDate, timezone };+ const results = await Promise.all(+ reports.map(async (report) => {+ try {+ // Apply the dashboard's global range picker to each report.+ // If both startDate + endDate are set, that wins; otherwise+ // the preset range is used. Mirrors how ReportItem behaves+ // when the page-level range/interval flow into a report.+ const useCustom = !!(overrideStart && overrideEnd);+ const merged = {+ ...report,+ ...(useCustom+ ? {+ range: 'custom' as IChartRange,+ startDate: overrideStart,+ endDate: overrideEnd,+ }+ : overrideRange+ ? { range: overrideRange, startDate: null, endDate: null }+ : {}),+ ...(overrideInterval ? { interval: overrideInterval } : {}),+ };- let data: unknown;- if (report.chartType === 'funnel') {- data = await getFunnel(- chartInput as Parameters<typeof getFunnel>[0]+ const { startDate, endDate } = getChartStartEndDate(+ merged,+ timezone);- } else if (report.chartType === 'metric') {- data = await AggregateChartEngine.execute(chartInput);- } else {- data = await ChartEngine.execute(chartInput);- }+ const chartInput = { ...merged, startDate, endDate, timezone };- return {- id: report.id,- name: report.name,- chartType: report.chartType,- interval: chartInput.interval,- startDate,- endDate,- data,- };- } catch (err) {- return {- id: report.id,- name: report.name,- chartType: report.chartType,- error: err instanceof Error ? err.message : String(err),- };- }- })- );+ let data: unknown;+ if (report.chartType === 'funnel') {+ data = await getFunnel(+ deps,+ chartInput as Parameters<typeof getFunnel>[1]+ );+ } else if (report.chartType === 'metric') {+ data = await executeAggregateChart(deps, chartInput);+ } else {+ data = await executeChart(deps, chartInput);+ }- return {- dashboard: meta,- reports: results,- ...(truncated- ? {- _truncated: true,- note: `Dashboard has ${allReports.length} reports; only the first ${MAX_REPORTS_PER_SUMMARY} were summarized.`,+ return {+ id: report.id,+ name: report.name,+ chartType: report.chartType,+ interval: chartInput.interval,+ startDate,+ endDate,+ data,+ };+ } catch (err) {+ return {+ id: report.id,+ name: report.name,+ chartType: report.chartType,+ error: err instanceof Error ? err.message : String(err),+ };}- : {}),- };- }-);+ })+ );++ return {+ dashboard: meta,+ reports: results,+ ...(truncated+ ? {+ _truncated: true,+ note: `Dashboard has ${allReports.length} reports; only the first ${MAX_REPORTS_PER_SUMMARY} were summarized.`,+ }+ : {}),+ };+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/events.ts b/packages/core/src/modules/assistant/src/tools/events.tsindex c4b727592..e17237734 100644--- a/packages/core/src/modules/assistant/src/tools/events.ts+++ b/packages/core/src/modules/assistant/src/tools/events.ts@@ -1,9 +1,10 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';import {getEventPropertyValuesCore,listEventPropertiesCore,queryEventsCore,-} from '../../../../v1-compat';+} from '../../../event/event.service';import {chatTool,compactEventProperties,@@ -11,154 +12,158 @@ import {truncateRows,} from './helpers';-export const analyzeEventDistribution = chatTool(- {- name: 'analyze_event_distribution',- description:- 'For a set of events (or all events in the current view), break down their frequency, top properties, and top sources. Useful for "which events fire the most?" questions.',- schema: z.object({- eventNames: z.array(z.string()).optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ eventNames, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });+export const analyzeEventDistribution = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'analyze_event_distribution',+ description:+ 'For a set of events (or all events in the current view), break down their frequency, top properties, and top sources. Useful for "which events fire the most?" questions.',+ schema: z.object({+ eventNames: z.array(z.string()).optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ eventNames, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });- const events = await queryEventsCore({- projectId: context.projectId,- eventNames,- startDate: range.startDate,- endDate: range.endDate,- limit: 100,- });+ const events = await queryEventsCore(deps, {+ projectId: context.projectId,+ eventNames,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 100,+ });- // Tally frequency by event name- const frequency = new Map<string, number>();- const byCountry = new Map<string, number>();- const byDevice = new Map<string, number>();- for (const e of events) {- frequency.set(e.name, (frequency.get(e.name) ?? 0) + 1);- if (e.country) {- byCountry.set(e.country, (byCountry.get(e.country) ?? 0) + 1);- }- if (e.device) {- byDevice.set(e.device, (byDevice.get(e.device) ?? 0) + 1);+ // Tally frequency by event name+ const frequency = new Map<string, number>();+ const byCountry = new Map<string, number>();+ const byDevice = new Map<string, number>();+ for (const e of events) {+ frequency.set(e.name, (frequency.get(e.name) ?? 0) + 1);+ if (e.country) {+ byCountry.set(e.country, (byCountry.get(e.country) ?? 0) + 1);+ }+ if (e.device) {+ byDevice.set(e.device, (byDevice.get(e.device) ?? 0) + 1);+ }}- }- const top = (m: Map<string, number>, n: number) =>- Array.from(m.entries())- .sort((a, b) => b[1] - a[1])- .slice(0, n)- .map(([name, count]) => ({ name, count }));+ const top = (m: Map<string, number>, n: number) =>+ Array.from(m.entries())+ .sort((a, b) => b[1] - a[1])+ .slice(0, n)+ .map(([name, count]) => ({ name, count }));- return {- sample_size: events.length,- event_frequency: top(frequency, 20),- top_countries: top(byCountry, 10),- top_devices: top(byDevice, 10),- };- }-);+ return {+ sample_size: events.length,+ event_frequency: top(frequency, 20),+ top_countries: top(byCountry, 10),+ top_devices: top(byDevice, 10),+ };+ }+ );-export const correlateEvents = chatTool(- {- name: 'correlate_events',- description:- 'Find pairs of events that frequently occur in the same session. Returns event pairs ranked by co-occurrence count.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });+export const correlateEvents = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'correlate_events',+ description:+ 'Find pairs of events that frequently occur in the same session. Returns event pairs ranked by co-occurrence count.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });- const events = await queryEventsCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: 100,- });+ const events = await queryEventsCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 100,+ });- // Group events by sessionId, then count co-occurring event-name pairs- const bySession = new Map<string, Set<string>>();- for (const e of events) {- if (!e.session_id) {- continue;- }- if (!bySession.has(e.session_id)) {- bySession.set(e.session_id, new Set());+ // Group events by sessionId, then count co-occurring event-name pairs+ const bySession = new Map<string, Set<string>>();+ for (const e of events) {+ if (!e.session_id) {+ continue;+ }+ if (!bySession.has(e.session_id)) {+ bySession.set(e.session_id, new Set());+ }+ bySession.get(e.session_id)?.add(e.name);}- bySession.get(e.session_id)?.add(e.name);- }- const pairCounts = new Map<string, number>();- for (const eventNames of bySession.values()) {- const list = Array.from(eventNames).sort();- for (let i = 0; i < list.length; i++) {- for (let j = i + 1; j < list.length; j++) {- const key = `${list[i]} + ${list[j]}`;- pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);+ const pairCounts = new Map<string, number>();+ for (const eventNames of bySession.values()) {+ const list = Array.from(eventNames).sort();+ for (let i = 0; i < list.length; i++) {+ for (let j = i + 1; j < list.length; j++) {+ const key = `${list[i]} + ${list[j]}`;+ pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);+ }}}- }- const pairs = Array.from(pairCounts.entries())- .sort((a, b) => b[1] - a[1])- .slice(0, 30)- .map(([pair, count]) => ({ pair, count }));+ const pairs = Array.from(pairCounts.entries())+ .sort((a, b) => b[1] - a[1])+ .slice(0, 30)+ .map(([pair, count]) => ({ pair, count }));- return {- sample_sessions: bySession.size,- top_pairs: pairs,- };- }-);+ return {+ sample_sessions: bySession.size,+ top_pairs: pairs,+ };+ }+ );-export const getEventPropertyDistribution = chatTool(- {- name: 'get_event_property_distribution',- description:- 'Distribution of distinct values for a specific property on a specific event. Use to answer "what countries fire screen_view most?" type questions.',- schema: z.object({- eventName: z.string(),- propertyKey: z.string(),- }),- },- async ({ eventName, propertyKey }, context) => {- const result = await getEventPropertyValuesCore({- projectId: context.projectId,- eventName,- propertyKey,- });- return truncateRows(result.values, 100);- }-);+export const getEventPropertyDistribution = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_event_property_distribution',+ description:+ 'Distribution of distinct values for a specific property on a specific event. Use to answer "what countries fire screen_view most?" type questions.',+ schema: z.object({+ eventName: z.string(),+ propertyKey: z.string(),+ }),+ },+ async ({ eventName, propertyKey }, context) => {+ const result = await getEventPropertyValuesCore(deps, {+ projectId: context.projectId,+ eventName,+ propertyKey,+ });+ return truncateRows(result.values, 100);+ }+ );-export const listPropertiesForEvent = chatTool(- {- name: 'list_properties_for_event',- description:- 'List fields available for filtering / breakdown on a specific event (or all events). Returns `columns` (top-level event columns like `path`, `country`, `device` — use bare name) and `properties` (custom JSON keys — use prefixed as `properties.<key>`). Dotted sub-keys inside `properties` are rolled up to their root (e.g. all `__query.*` become a single `__query`); ordered by how many sub-keys roll up under each root.',- schema: z.object({- eventName: z.string().optional(),- }),- },- async ({ eventName }, context) => {- const raw = await listEventPropertiesCore({- projectId: context.projectId,- eventName,- });- return compactEventProperties(raw, { eventName });- }-);+export const listPropertiesForEvent = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'list_properties_for_event',+ description:+ 'List fields available for filtering / breakdown on a specific event (or all events). Returns `columns` (top-level event columns like `path`, `country`, `device` — use bare name) and `properties` (custom JSON keys — use prefixed as `properties.<key>`). Dotted sub-keys inside `properties` are rolled up to their root (e.g. all `__query.*` become a single `__query`); ordered by how many sub-keys roll up under each root.',+ schema: z.object({+ eventName: z.string().optional(),+ }),+ },+ async ({ eventName }, context) => {+ const raw = await listEventPropertiesCore(deps, {+ projectId: context.projectId,+ eventName,+ });+ return compactEventProperties(raw, { eventName });+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/groups.ts b/packages/core/src/modules/assistant/src/tools/groups.tsindex f1d6fb170..2d42a4b71 100644--- a/packages/core/src/modules/assistant/src/tools/groups.ts+++ b/packages/core/src/modules/assistant/src/tools/groups.ts@@ -1,223 +1,229 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';+import { queryEventsCore } from '../../../event/event.service';import {findGroupsCore,getGroupCore,getGroupMemberProfiles,- queryEventsCore,-} from '../../../../v1-compat';+} from '../../../group/group.service';import { chatTool, dashboardUrl, truncateRows } from './helpers';-export const getGroupFull = chatTool(- {- name: 'get_group_full',- description:- 'One-shot deep dive: group info + member count + first 10 members + recent events from members. CALL THIS FIRST for "tell me about this group".',- schema: z.object({- groupId: z.string().optional(),- }),- },- async ({ groupId }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;- const orgPath = (path = '') =>- dashboardUrl(context.organizationId, context.projectId, path);-- const group = await getGroupCore({- projectId: context.projectId,- groupId: id,- memberLimit: 10,- });-- // Pull a few recent events from any members. We use the- // `profileIds IN (...)` filter on queryEventsCore so the DB does- // the narrowing instead of us post-filtering a generic feed.- const memberIds = group.members.map((m) => m.id);- const recentEvents = memberIds.length- ? await queryEventsCore({- projectId: context.projectId,- profileIds: memberIds,- limit: 10,- })- : [];-- return {- ...group,- recent_events: recentEvents,- dashboard_url: orgPath(`/groups/${id}`),- };- }-);--export const getGroupMembers = chatTool(- {- name: 'get_group_members',- description: 'Paginated list of profiles in this group.',- schema: z.object({- groupId: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- search: z.string().optional(),- }),- },- async ({ groupId, limit, search }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;- const orgPath = (path = '') =>- dashboardUrl(context.organizationId, context.projectId, path);-- const result = await getGroupMemberProfiles({- projectId: context.projectId,- groupId: id,- take: limit ?? 20,- search,- });- return {- group_id: id,- total_count: result.count,- members: result.data.map((p) => ({- ...p,- dashboard_url: orgPath(`/profiles/${p.id}`),- })),- };- }-);--export const getGroupEvents = chatTool(- {- name: 'get_group_events',- description: 'Recent events from members of this group.',- schema: z.object({- groupId: z.string().optional(),- eventNames: z.array(z.string()).optional(),- limit: z.number().min(1).max(100).default(50).optional(),- }),- },- async ({ groupId, eventNames, limit }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;-- const members = await getGroupMemberProfiles({- projectId: context.projectId,- groupId: id,- take: 100,- });- if (members.data.length === 0) {- return { group_id: id, events: [], note: 'Group has no members' };+export const getGroupFull = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_group_full',+ description:+ 'One-shot deep dive: group info + member count + first 10 members + recent events from members. CALL THIS FIRST for "tell me about this group".',+ schema: z.object({+ groupId: z.string().optional(),+ }),+ },+ async ({ groupId }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;+ const orgPath = (path = '') =>+ dashboardUrl(context.organizationId, context.projectId, path);++ const group = await getGroupCore(deps, {+ projectId: context.projectId,+ groupId: id,+ memberLimit: 10,+ });++ // Pull a few recent events from any members. We use the+ // `profileIds IN (...)` filter on queryEventsCore so the DB does+ // the narrowing instead of us post-filtering a generic feed.+ const memberIds = group.members.map((m) => m.id);+ const recentEvents = memberIds.length+ ? await queryEventsCore(deps, {+ projectId: context.projectId,+ profileIds: memberIds,+ limit: 10,+ })+ : [];++ return {+ ...group,+ recent_events: recentEvents,+ dashboard_url: orgPath(`/groups/${id}`),+ };}-- const events = await queryEventsCore({- projectId: context.projectId,- profileIds: members.data.map((m) => m.id),- eventNames,- limit: limit ?? 50,- });-- return truncateRows(events, 100);- }-);--export const getGroupMetrics = chatTool(- {- name: 'get_group_metrics',- description:- 'Aggregate metrics for this group: total members, members active in the last 7d/30d, total revenue (sum of member.revenue), avg sessions per member.',- schema: z.object({- groupId: z.string().optional(),- }),- },- async ({ groupId }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;-- const members = await getGroupMemberProfiles({- projectId: context.projectId,- groupId: id,- take: 1000,- });-- if (members.data.length === 0) {- return { group_id: id, total_members: 0, note: 'Group has no members' };+ );++export const getGroupMembers = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_group_members',+ description: 'Paginated list of profiles in this group.',+ schema: z.object({+ groupId: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ search: z.string().optional(),+ }),+ },+ async ({ groupId, limit, search }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;+ const orgPath = (path = '') =>+ dashboardUrl(context.organizationId, context.projectId, path);++ const result = await getGroupMemberProfiles(deps, {+ projectId: context.projectId,+ groupId: id,+ take: limit ?? 20,+ search,+ });+ return {+ group_id: id,+ total_count: result.count,+ members: result.data.map((p) => ({+ ...p,+ dashboard_url: orgPath(`/profiles/${p.id}`),+ })),+ };}+ );++export const getGroupEvents = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_group_events',+ description: 'Recent events from members of this group.',+ schema: z.object({+ groupId: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ limit: z.number().min(1).max(100).default(50).optional(),+ }),+ },+ async ({ groupId, eventNames, limit }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;++ const members = await getGroupMemberProfiles(deps, {+ projectId: context.projectId,+ groupId: id,+ take: 100,+ });+ if (members.data.length === 0) {+ return { group_id: id, events: [], note: 'Group has no members' };+ }- // Pull events for this group's members over the last 30 days, then- // bucket by 7d vs 30d. `profileIds IN (...)` lets ClickHouse do the- // narrowing — a generic project-wide feed would miss members whose- // activity falls outside the last N raw events.- const memberIds = members.data.map((m) => m.id);- const recentEvents = await queryEventsCore({- projectId: context.projectId,- profileIds: memberIds,- startDate: new Date(Date.now() - 30 * 86_400_000)- .toISOString()- .slice(0, 10),- limit: 1000,- });- const activeIds7d = new Set<string>();- const activeIds30d = new Set<string>();- const sevenDaysAgo = Date.now() - 7 * 86_400_000;- for (const e of recentEvents) {- if (!e.profile_id) {- continue;+ const events = await queryEventsCore(deps, {+ projectId: context.projectId,+ profileIds: members.data.map((m) => m.id),+ eventNames,+ limit: limit ?? 50,+ });++ return truncateRows(events, 100);+ }+ );++export const getGroupMetrics = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_group_metrics',+ description:+ 'Aggregate metrics for this group: total members, members active in the last 7d/30d, total revenue (sum of member.revenue), avg sessions per member.',+ schema: z.object({+ groupId: z.string().optional(),+ }),+ },+ async ({ groupId }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;++ const members = await getGroupMemberProfiles(deps, {+ projectId: context.projectId,+ groupId: id,+ take: 1000,+ });++ if (members.data.length === 0) {+ return { group_id: id, total_members: 0, note: 'Group has no members' };}- activeIds30d.add(e.profile_id);- if (new Date(e.created_at).getTime() >= sevenDaysAgo) {- activeIds7d.add(e.profile_id);++ // Pull events for this group's members over the last 30 days, then+ // bucket by 7d vs 30d. `profileIds IN (...)` lets ClickHouse do the+ // narrowing — a generic project-wide feed would miss members whose+ // activity falls outside the last N raw events.+ const memberIds = members.data.map((m) => m.id);+ const recentEvents = await queryEventsCore(deps, {+ projectId: context.projectId,+ profileIds: memberIds,+ startDate: new Date(Date.now() - 30 * 86_400_000)+ .toISOString()+ .slice(0, 10),+ limit: 1000,+ });+ const activeIds7d = new Set<string>();+ const activeIds30d = new Set<string>();+ const sevenDaysAgo = Date.now() - 7 * 86_400_000;+ for (const e of recentEvents) {+ if (!e.profile_id) {+ continue;+ }+ activeIds30d.add(e.profile_id);+ if (new Date(e.created_at).getTime() >= sevenDaysAgo) {+ activeIds7d.add(e.profile_id);+ }}- }- return {- group_id: id,- total_members: members.count,- active_last_7_days: activeIds7d.size,- active_last_30_days: activeIds30d.size,- };- }-);--export const compareGroups = chatTool(- {- name: 'compare_groups',- description:- 'Compare this group\'s member count and activity to other groups of the same type. Useful in B2B for "is this account active vs the rest?".',- schema: z.object({- groupId: z.string().optional(),- }),- },- async ({ groupId }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;-- const thisGroup = await getGroupCore({- projectId: context.projectId,- groupId: id,- memberLimit: 0,- });-- const peers = await findGroupsCore({- projectId: context.projectId,- type: thisGroup.group.type,- limit: 100,- });-- if (peers.length === 0) {- return { this_group: thisGroup, peers: [], note: 'No peer groups' };+ return {+ group_id: id,+ total_members: members.count,+ active_last_7_days: activeIds7d.size,+ active_last_30_days: activeIds30d.size,+ };}+ );++export const compareGroups = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'compare_groups',+ description:+ 'Compare this group\'s member count and activity to other groups of the same type. Useful in B2B for "is this account active vs the rest?".',+ schema: z.object({+ groupId: z.string().optional(),+ }),+ },+ async ({ groupId }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;++ const thisGroup = await getGroupCore(deps, {+ projectId: context.projectId,+ groupId: id,+ memberLimit: 0,+ });++ const peers = await findGroupsCore(deps, {+ projectId: context.projectId,+ type: thisGroup.group.type,+ limit: 100,+ });++ if (peers.length === 0) {+ return { this_group: thisGroup, peers: [], note: 'No peer groups' };+ }- // `findGroupsCore` returns `IServiceGroup[]` without a memberCount- // — that lives on `IServiceGroupStats` via a separate query. We- // don't fetch it here, so we report peer count + this group's- // count and list a handful of peers without rankings. If "rank by- // members" becomes useful, fetch `getGroupStats` for each peer.- return {- this_group: {- id: thisGroup.group.id,- name: thisGroup.group.name,- member_count: thisGroup.member_count,- },- peer_count: peers.length,- top_peers: peers.slice(0, 5).map((g) => ({- id: g.id,- name: g.name,- })),- };- }-);+ // `findGroupsCore` returns `IServiceGroup[]` without a memberCount+ // — that lives on `IServiceGroupStats` via a separate query. We+ // don't fetch it here, so we report peer count + this group's+ // count and list a handful of peers without rankings. If "rank by+ // members" becomes useful, fetch `getGroupStats` for each peer.+ return {+ this_group: {+ id: thisGroup.group.id,+ name: thisGroup.group.name,+ member_count: thisGroup.member_count,+ },+ peer_count: peers.length,+ top_peers: peers.slice(0, 5).map((g) => ({+ id: g.id,+ name: g.name,+ })),+ };+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.tsindex 20ab35441..25a8519c6 100644--- a/packages/core/src/modules/assistant/src/tools/helpers.ts+++ b/packages/core/src/modules/assistant/src/tools/helpers.ts@@ -18,18 +18,6 @@ import { chatRunContext } from '../run-context';/** Max time a single tool handler is allowed to run. */const TOOL_TIMEOUT_MS = 30_000;-/**- * Chat tool handlers have a fixed signature from `@better-agent/core` — no- * `Ctx`/`ServiceDeps` parameter to thread through, so tools that touch- * Postgres directly (`references.ts`, `insights.ts`) reach it through the- * v1-compat singleton instead of `@openpanel/db` (M10-004, see- * v1-compat.ts's header) — the same pattern every other bare, no-`Ctx`- * caller in this wave uses.- */-export async function loadCompatDb() {- return (await import('../../../../v1-compat')).compatDb();-}-/*** Thin wrapper around `defineTool().server()` that bakes in our typed* agent context and enforces a time ceiling. Three things this givesdiff --git a/packages/core/src/modules/assistant/src/tools/index.ts b/packages/core/src/modules/assistant/src/tools/index.tsindex 5ad7ef94b..7f2b21001 100644--- a/packages/core/src/modules/assistant/src/tools/index.ts+++ b/packages/core/src/modules/assistant/src/tools/index.ts@@ -1,4 +1,5 @@import type { AgentToolDefinition } from '@better-agent/core';+import type { ServiceDeps } from '../../../../services';import type { ChatAgentContext } from '../context';import * as base from './base';import * as dashboard from './dashboard';@@ -13,10 +14,14 @@ import * as seo from './seo';import * as session from './session';import * as ui from './ui';-// Tool arrays are typed loosely as `AgentToolDefinition[]` — without-// this, TypeScript tries to compute the union of every tool's schema +-// result type and hits its instantiation depth limit.-type ToolList = AgentToolDefinition[];+// A tool is BUILT per unit of work, from the `deps` the route already holds:+// `@better-agent/core`'s tool-handler signature has no context parameter, so+// each handler closes over them instead (ADR-022 R6/R15). The lists are typed+// loosely as `(deps) => AgentToolDefinition` — without the cast, TypeScript+// tries to compute the union of every tool's schema + result type and hits+// its instantiation depth limit.+type ToolFactory = (deps: ServiceDeps) => AgentToolDefinition;+type ToolList = ToolFactory[];/*** Always-available base tool set: discovery + saved reports + aggregate@@ -52,7 +57,7 @@ const BASE_TOOLS: ToolList = [// every page, not just the overview.references.listReferences,references.getReferencesAround,-] as AgentToolDefinition[];+] as ToolList;const PROFILE_TOOLS: ToolList = [profile.getProfileFull,@@ -62,7 +67,7 @@ const PROFILE_TOOLS: ToolList = [profile.getProfileJourney,profile.getProfileGroups,profile.compareProfileToAverage,-] as AgentToolDefinition[];+] as ToolList;const SESSION_TOOLS: ToolList = [session.getSessionFull,@@ -72,7 +77,7 @@ const SESSION_TOOLS: ToolList = [session.compareSessionToTypical,session.getSessionReferrerContext,session.getSessionReplaySummary,-] as AgentToolDefinition[];+] as ToolList;const REPORT_EDITOR_TOOLS: ToolList = [report.previewReportWithChanges,@@ -80,14 +85,14 @@ const REPORT_EDITOR_TOOLS: ToolList = [report.compareToPreviousPeriod,report.findAnomaliesInCurrentReport,report.explainFilterImpact,-] as AgentToolDefinition[];+] as ToolList;const PAGES_TOOLS: ToolList = [pages.getPagePerformance,pages.getPageConversions,pages.getEntryExitPages,pages.findDecliningPages,-] as AgentToolDefinition[];+] as ToolList;const SEO_TOOLS: ToolList = [seo.gscGetOverview,@@ -98,20 +103,20 @@ const SEO_TOOLS: ToolList = [seo.gscGetQueryOpportunities,seo.gscGetCannibalization,seo.correlateSeoWithTraffic,-] as AgentToolDefinition[];+] as ToolList;const EVENTS_TOOLS: ToolList = [events.analyzeEventDistribution,events.correlateEvents,events.getEventPropertyDistribution,events.listPropertiesForEvent,-] as AgentToolDefinition[];+] as ToolList;const INSIGHTS_TOOLS: ToolList = [insights.listInsights,insights.explainInsight,insights.findRelatedInsights,-] as AgentToolDefinition[];+] as ToolList;const GROUP_TOOLS: ToolList = [groups.getGroupFull,@@ -119,11 +124,9 @@ const GROUP_TOOLS: ToolList = [groups.getGroupEvents,groups.getGroupMetrics,groups.compareGroups,-] as AgentToolDefinition[];+] as ToolList;-const DASHBOARD_TOOLS: ToolList = [- dashboard.summarizeDashboard,-] as AgentToolDefinition[];+const DASHBOARD_TOOLS: ToolList = [dashboard.summarizeDashboard] as ToolList;// Client-side UI mutators. Available on pages that have user-// settable filters (date range, event names, property filters) so@@ -134,7 +137,7 @@ const UI_TOOLS: ToolList = [ui.applyFilters,ui.setEventNamesFilter,ui.setPropertyFilters,-] as AgentToolDefinition[];+] as ToolList;/*** Compose the chat tool set for a given request. Base tools are always@@ -147,38 +150,45 @@ const UI_TOOLS: ToolList = [* The LLM sees fewer-but-more-focused tools per page, which produces* better tool selection than one giant flat registry.*/-export function composeChatTools(context: ChatAgentContext) {+export function composeChatTools(+ deps: ServiceDeps,+ context: ChatAgentContext+): AgentToolDefinition[] {const page = context.pageContext?.page;const ids = context.pageContext?.ids;+ const build = (...groups: ToolList[]): AgentToolDefinition[] =>+ groups.flat().map((tool) => tool(deps));switch (page) {case 'profileDetail':return ids?.profileId- ? [...BASE_TOOLS, ...PROFILE_TOOLS, ...UI_TOOLS]- : [...BASE_TOOLS, ...UI_TOOLS];+ ? build(BASE_TOOLS, PROFILE_TOOLS, UI_TOOLS)+ : build(BASE_TOOLS, UI_TOOLS);case 'sessionDetail':- return ids?.sessionId ? [...BASE_TOOLS, ...SESSION_TOOLS] : BASE_TOOLS;+ return ids?.sessionId+ ? build(BASE_TOOLS, SESSION_TOOLS)+ : build(BASE_TOOLS);case 'reportEditor':return context.pageContext?.reportDraft- ? [...BASE_TOOLS, ...REPORT_EDITOR_TOOLS]- : BASE_TOOLS;+ ? build(BASE_TOOLS, REPORT_EDITOR_TOOLS)+ : build(BASE_TOOLS);case 'pages':- return [...BASE_TOOLS, ...PAGES_TOOLS, ...UI_TOOLS];+ return build(BASE_TOOLS, PAGES_TOOLS, UI_TOOLS);case 'seo':- return [...BASE_TOOLS, ...SEO_TOOLS, ...UI_TOOLS];+ return build(BASE_TOOLS, SEO_TOOLS, UI_TOOLS);case 'events':- return [...BASE_TOOLS, ...EVENTS_TOOLS, ...UI_TOOLS];+ return build(BASE_TOOLS, EVENTS_TOOLS, UI_TOOLS);case 'insights':- return [...BASE_TOOLS, ...INSIGHTS_TOOLS, ...UI_TOOLS];+ return build(BASE_TOOLS, INSIGHTS_TOOLS, UI_TOOLS);case 'groupDetail':- return ids?.groupId ? [...BASE_TOOLS, ...GROUP_TOOLS] : BASE_TOOLS;+ return ids?.groupId ? build(BASE_TOOLS, GROUP_TOOLS) : build(BASE_TOOLS);case 'dashboard':return ids?.dashboardId- ? [...BASE_TOOLS, ...DASHBOARD_TOOLS, ...UI_TOOLS]- : [...BASE_TOOLS, ...UI_TOOLS];+ ? build(BASE_TOOLS, DASHBOARD_TOOLS, UI_TOOLS)+ : build(BASE_TOOLS, UI_TOOLS);case 'overview':- return [...BASE_TOOLS, ...UI_TOOLS];+ return build(BASE_TOOLS, UI_TOOLS);default:- return BASE_TOOLS;+ return build(BASE_TOOLS);}}diff --git a/packages/core/src/modules/assistant/src/tools/insights.ts b/packages/core/src/modules/assistant/src/tools/insights.tsindex 8da9acd45..e7e8c8360 100644--- a/packages/core/src/modules/assistant/src/tools/insights.ts+++ b/packages/core/src/modules/assistant/src/tools/insights.ts@@ -1,123 +1,127 @@import { z } from 'zod';-import { chatTool, loadCompatDb, truncateRows } from './helpers';+import type { ServiceDeps } from '../../../../services';+import { chatTool, truncateRows } from './helpers';-export const listInsights = chatTool(- {- name: 'list_insights',- description:- 'List active auto-detected insights for this project, sorted by impact. Each has module (geo/devices/referrers/etc.), direction (up/down/flat), severity, and impact score.',- schema: z.object({- limit: z.number().min(1).max(500).default(50).optional(),- moduleKey: z- .string()- .optional()- .describe(- 'Filter by module: geo, devices, referrers, entry-pages, page-trends, exit-pages, traffic-anomalies'- ),- severity: z.enum(['severe', 'moderate', 'low']).optional(),- direction: z.enum(['up', 'down', 'flat']).optional(),- }),- },- async ({ limit, moduleKey, severity, direction }, context) => {- const db = await loadCompatDb();- const insights = await db.projectInsight.findMany({- where: {- projectId: context.projectId,- state: 'active',- ...(moduleKey ? { moduleKey } : {}),- ...(severity ? { severityBand: severity } : {}),- ...(direction ? { direction } : {}),- },- orderBy: { impactScore: 'desc' },- take: limit ?? 50,- });- // Project to a UI/LLM-friendly shape. Order matters: the table- // renderer uses the first string column as the label, and we want- // the human title there — not the UUID.- return truncateRows(- insights.map((i) => ({- title: i.title,- summary: i.summary ?? '',- module: i.moduleKey,- dimension: i.dimensionKey,- direction: i.direction ?? '',- severity: i.severityBand ?? '',- impact: Math.round(i.impactScore),- window: i.windowKind,- // Keep the id LAST so the model can call explain_insight with it,- // but the table won't pick it as the label column.- id: i.id,- })),- 100- );- }-);+export const listInsights = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'list_insights',+ description:+ 'List active auto-detected insights for this project, sorted by impact. Each has module (geo/devices/referrers/etc.), direction (up/down/flat), severity, and impact score.',+ schema: z.object({+ limit: z.number().min(1).max(500).default(50).optional(),+ moduleKey: z+ .string()+ .optional()+ .describe(+ 'Filter by module: geo, devices, referrers, entry-pages, page-trends, exit-pages, traffic-anomalies'+ ),+ severity: z.enum(['severe', 'moderate', 'low']).optional(),+ direction: z.enum(['up', 'down', 'flat']).optional(),+ }),+ },+ async ({ limit, moduleKey, severity, direction }, context) => {+ const db = deps.db;+ const insights = await db.projectInsight.findMany({+ where: {+ projectId: context.projectId,+ state: 'active',+ ...(moduleKey ? { moduleKey } : {}),+ ...(severity ? { severityBand: severity } : {}),+ ...(direction ? { direction } : {}),+ },+ orderBy: { impactScore: 'desc' },+ take: limit ?? 50,+ });+ // Project to a UI/LLM-friendly shape. Order matters: the table+ // renderer uses the first string column as the label, and we want+ // the human title there — not the UUID.+ return truncateRows(+ insights.map((i) => ({+ title: i.title,+ summary: i.summary ?? '',+ module: i.moduleKey,+ dimension: i.dimensionKey,+ direction: i.direction ?? '',+ severity: i.severityBand ?? '',+ impact: Math.round(i.impactScore),+ window: i.windowKind,+ // Keep the id LAST so the model can call explain_insight with it,+ // but the table won't pick it as the label column.+ id: i.id,+ })),+ 100+ );+ }+ );-export const explainInsight = chatTool(- {- name: 'explain_insight',- description:- 'Get a single insight by ID with its full payload (the structured data the dashboard renders) plus its event history (when first detected, version updates).',- schema: z.object({- insightId: z.string(),- }),- },- async ({ insightId }, context) => {- const db = await loadCompatDb();- const insight = await db.projectInsight.findFirst({- where: { id: insightId, projectId: context.projectId },- });- if (!insight) {- return { error: 'Insight not found', insightId };+export const explainInsight = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'explain_insight',+ description:+ 'Get a single insight by ID with its full payload (the structured data the dashboard renders) plus its event history (when first detected, version updates).',+ schema: z.object({+ insightId: z.string(),+ }),+ },+ async ({ insightId }, context) => {+ const db = deps.db;+ const insight = await db.projectInsight.findFirst({+ where: { id: insightId, projectId: context.projectId },+ });+ if (!insight) {+ return { error: 'Insight not found', insightId };+ }+ const events = await db.insightEvent.findMany({+ where: { insightId },+ orderBy: { createdAt: 'desc' },+ take: 20,+ });+ return { insight, events };}- const events = await db.insightEvent.findMany({- where: { insightId },- orderBy: { createdAt: 'desc' },- take: 20,- });- return { insight, events };- }-);+ );-export const findRelatedInsights = chatTool(- {- name: 'find_related_insights',- description:- 'Given one insight, find others that share the same module or dimension. Useful when one insight prompts a "what else is going on with this country/page/device?" follow-up.',- schema: z.object({- insightId: z.string(),- limit: z.number().min(1).max(50).default(10).optional(),- }),- },- async ({ insightId, limit }, context) => {- const db = await loadCompatDb();- const insight = await db.projectInsight.findFirst({- where: { id: insightId, projectId: context.projectId },- });- if (!insight) {- return { error: 'Insight not found', insightId };+export const findRelatedInsights = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'find_related_insights',+ description:+ 'Given one insight, find others that share the same module or dimension. Useful when one insight prompts a "what else is going on with this country/page/device?" follow-up.',+ schema: z.object({+ insightId: z.string(),+ limit: z.number().min(1).max(50).default(10).optional(),+ }),+ },+ async ({ insightId, limit }, context) => {+ const db = deps.db;+ const insight = await db.projectInsight.findFirst({+ where: { id: insightId, projectId: context.projectId },+ });+ if (!insight) {+ return { error: 'Insight not found', insightId };+ }+ const related = await db.projectInsight.findMany({+ where: {+ projectId: context.projectId,+ id: { not: insightId },+ state: 'active',+ OR: [+ { moduleKey: insight.moduleKey },+ { dimensionKey: insight.dimensionKey },+ ],+ },+ orderBy: { impactScore: 'desc' },+ take: limit ?? 10,+ });+ return {+ source_insight: {+ id: insight.id,+ moduleKey: insight.moduleKey,+ dimensionKey: insight.dimensionKey,+ },+ related_count: related.length,+ related,+ };}- const related = await db.projectInsight.findMany({- where: {- projectId: context.projectId,- id: { not: insightId },- state: 'active',- OR: [- { moduleKey: insight.moduleKey },- { dimensionKey: insight.dimensionKey },- ],- },- orderBy: { impactScore: 'desc' },- take: limit ?? 10,- });- return {- source_insight: {- id: insight.id,- moduleKey: insight.moduleKey,- dimensionKey: insight.dimensionKey,- },- related_count: related.length,- related,- };- }-);+ );diff --git a/packages/core/src/modules/assistant/src/tools/pages.ts b/packages/core/src/modules/assistant/src/tools/pages.tsindex c182f7191..17be4c179 100644--- a/packages/core/src/modules/assistant/src/tools/pages.ts+++ b/packages/core/src/modules/assistant/src/tools/pages.ts@@ -1,10 +1,11 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';import {getEntryExitPagesCore,getPageConversionsCore,getPagePerformanceCore,getTopPagesCore,-} from '../../../../v1-compat';+} from '../../../overview/pages.service';import {chatTool,previousPeriod,@@ -12,177 +13,181 @@ import {truncateRows,} from './helpers';-export const getPagePerformance = chatTool(- {- name: 'get_page_performance',- description:- 'Per-page performance metrics with SEO signal flags (high bounce, low engagement, good landing page). Sortable by sessions, pageviews, bounce_rate, or avg_duration.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- search: z.string().optional(),- sortBy: z- .enum(['sessions', 'pageviews', 'bounce_rate', 'avg_duration'])- .default('sessions')- .optional(),- sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async (input, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: input.startDate ?? context.pageContext?.filters?.startDate,- endDate: input.endDate ?? context.pageContext?.filters?.endDate,- });- return getPagePerformanceCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- search: input.search,- sortBy: input.sortBy,- sortOrder: input.sortOrder,- limit: input.limit ?? 50,- });- }-);--export const getPageConversions = chatTool(- {- name: 'get_page_conversions',- description:- 'For a given conversion event, find which pages drive the most conversions. Includes conversion rate per page.',- schema: z.object({- conversionEvent: z- .string()- .describe('The conversion event name (e.g. "signup", "purchase")'),- startDate: z.string().optional(),- endDate: z.string().optional(),- windowHours: z.number().min(1).max(720).default(24).optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async (input, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: input.startDate ?? context.pageContext?.filters?.startDate,- endDate: input.endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await getPageConversionsCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- conversionEvent: input.conversionEvent,- windowHours: input.windowHours,- limit: input.limit ?? 50,- });- return truncateRows(rows, 100);- }-);--export const getEntryExitPages = chatTool(- {- name: 'get_entry_exit_pages',- description:- 'Top entry pages or top exit pages — useful for understanding where users start and where they bounce.',- schema: z.object({- mode: z.enum(['entry', 'exit']),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ mode, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await getEntryExitPagesCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- mode,- });- return truncateRows(rows, 50);- }-);--export const findDecliningPages = chatTool(- {- name: 'find_declining_pages',- description:- 'Find pages where pageview volume dropped vs the immediately preceding period of the same length. Returns each declining page with absolute and percent change.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- minPageviews: z- .number()- .min(1)- .default(50)- .optional()- .describe(- 'Filter out pages with fewer than N pageviews in the previous period'- ),- }),- },- async (input, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: input.startDate ?? context.pageContext?.filters?.startDate,- endDate: input.endDate ?? context.pageContext?.filters?.endDate,- });- const prev = previousPeriod(range.startDate, range.endDate);+export const getPagePerformance = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_page_performance',+ description:+ 'Per-page performance metrics with SEO signal flags (high bounce, low engagement, good landing page). Sortable by sessions, pageviews, bounce_rate, or avg_duration.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ search: z.string().optional(),+ sortBy: z+ .enum(['sessions', 'pageviews', 'bounce_rate', 'avg_duration'])+ .default('sessions')+ .optional(),+ sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async (input, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: input.startDate ?? context.pageContext?.filters?.startDate,+ endDate: input.endDate ?? context.pageContext?.filters?.endDate,+ });+ return getPagePerformanceCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ search: input.search,+ sortBy: input.sortBy,+ sortOrder: input.sortOrder,+ limit: input.limit ?? 50,+ });+ }+ );- const [current, previous] = await Promise.all([- getTopPagesCore({+export const getPageConversions = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_page_conversions',+ description:+ 'For a given conversion event, find which pages drive the most conversions. Includes conversion rate per page.',+ schema: z.object({+ conversionEvent: z+ .string()+ .describe('The conversion event name (e.g. "signup", "purchase")'),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ windowHours: z.number().min(1).max(720).default(24).optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async (input, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: input.startDate ?? context.pageContext?.filters?.startDate,+ endDate: input.endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await getPageConversionsCore(deps, {projectId: context.projectId,startDate: range.startDate,endDate: range.endDate,- limit: 500,+ conversionEvent: input.conversionEvent,+ windowHours: input.windowHours,+ limit: input.limit ?? 50,+ });+ return truncateRows(rows, 100);+ }+ );++export const getEntryExitPages = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_entry_exit_pages',+ description:+ 'Top entry pages or top exit pages — useful for understanding where users start and where they bounce.',+ schema: z.object({+ mode: z.enum(['entry', 'exit']),+ startDate: z.string().optional(),+ endDate: z.string().optional(),}),- getTopPagesCore({+ },+ async ({ mode, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await getEntryExitPagesCore(deps, {projectId: context.projectId,- startDate: prev.startDate,- endDate: prev.endDate,- limit: 500,+ startDate: range.startDate,+ endDate: range.endDate,+ mode,+ });+ return truncateRows(rows, 50);+ }+ );++export const findDecliningPages = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'find_declining_pages',+ description:+ 'Find pages where pageview volume dropped vs the immediately preceding period of the same length. Returns each declining page with absolute and percent change.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ minPageviews: z+ .number()+ .min(1)+ .default(50)+ .optional()+ .describe(+ 'Filter out pages with fewer than N pageviews in the previous period'+ ),}),- ]);+ },+ async (input, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: input.startDate ?? context.pageContext?.filters?.startDate,+ endDate: input.endDate ?? context.pageContext?.filters?.endDate,+ });+ const prev = previousPeriod(range.startDate, range.endDate);++ const [current, previous] = await Promise.all([+ getTopPagesCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 500,+ }),+ getTopPagesCore(deps, {+ projectId: context.projectId,+ startDate: prev.startDate,+ endDate: prev.endDate,+ limit: 500,+ }),+ ]);- // biome-ignore lint/suspicious/noExplicitAny: pages shape varies between engines- const currMap = new Map<string, any>(- (current as Array<{ name?: string; path?: string }>).map((p) => [- String(p.name ?? p.path),- p,- ])- );- const min = input.minPageviews ?? 50;- const declines = (- previous as Array<{- name?: string;- path?: string;- count?: number;- sessions?: number;- }>- )- .filter((p) => (p.count ?? p.sessions ?? 0) >= min)- .map((p) => {- const key = String(p.name ?? p.path);- const curr = currMap.get(key);- const prevCount = Number(p.count ?? p.sessions ?? 0);- const currCount = Number(curr?.count ?? curr?.sessions ?? 0);- const delta = currCount - prevCount;- const pct = prevCount > 0 ? (delta / prevCount) * 100 : 0;- return {- path: key,- previous: prevCount,- current: currCount,- delta,- percent_change: Number(pct.toFixed(1)),- };- })- .filter((row) => row.delta < 0)- .sort((a, b) => a.percent_change - b.percent_change);+ // biome-ignore lint/suspicious/noExplicitAny: pages shape varies between engines+ const currMap = new Map<string, any>(+ (current as Array<{ name?: string; path?: string }>).map((p) => [+ String(p.name ?? p.path),+ p,+ ])+ );+ const min = input.minPageviews ?? 50;+ const declines = (+ previous as Array<{+ name?: string;+ path?: string;+ count?: number;+ sessions?: number;+ }>+ )+ .filter((p) => (p.count ?? p.sessions ?? 0) >= min)+ .map((p) => {+ const key = String(p.name ?? p.path);+ const curr = currMap.get(key);+ const prevCount = Number(p.count ?? p.sessions ?? 0);+ const currCount = Number(curr?.count ?? curr?.sessions ?? 0);+ const delta = currCount - prevCount;+ const pct = prevCount > 0 ? (delta / prevCount) * 100 : 0;+ return {+ path: key,+ previous: prevCount,+ current: currCount,+ delta,+ percent_change: Number(pct.toFixed(1)),+ };+ })+ .filter((row) => row.delta < 0)+ .sort((a, b) => a.percent_change - b.percent_change);- return truncateRows(declines, 50);- }-);+ return truncateRows(declines, 50);+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/profile.ts b/packages/core/src/modules/assistant/src/tools/profile.tsindex 6e2e73e90..747e3f32e 100644--- a/packages/core/src/modules/assistant/src/tools/profile.ts+++ b/packages/core/src/modules/assistant/src/tools/profile.ts@@ -1,314 +1,325 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';+import { queryEventsCore } from '../../../event/event.service';import {findProfilesCore,getProfileById,getProfileMetricsCore,getProfileSessionsCore,getProfileWithEvents,- queryEventsCore,-} from '../../../../v1-compat';+} from '../../../profile/profile.service';import { chatTool, dashboardUrl, truncateRows } from './helpers';-export const getProfileFull = chatTool(- {- name: 'get_profile_full',- description:- 'One-shot deep dive: profile data + lifetime metrics + last 5 sessions + last 10 events. CALL THIS FIRST when the user asks "tell me about this user" — it covers ~80% of follow-up questions in one round trip.',- schema: z.object({- profileId: z- .string()- .optional()- .describe('Defaults to the currently-viewed profile.'),- }),- },- async ({ profileId }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';- const [profile, withEvents, sessions, metrics] = await Promise.all([- getProfileById(id, context.projectId),- getProfileWithEvents(context.projectId, id, 10),- getProfileSessionsCore(context.projectId, id, 5),- getProfileMetricsCore({- projectId: context.projectId,- profileId: id,- }).catch(() => null),- ]);- if (!profile) {- return { error: 'Profile not found', profileId: id };- }- return {- profile,- metrics,- recent_sessions: sessions,- recent_events: withEvents.recent_events,- dashboard_url: dashboardUrl(- context.organizationId,- context.projectId,- `/profiles/${id}`- ),- };- }-);--export const getProfileEvents = chatTool(- {- name: 'get_profile_events',- description:- "Recent events for this profile, optionally filtered by event name or property. Use when get_profile_full doesn't cover the question.",- schema: z.object({- profileId: z.string().optional(),- eventNames: z- .array(z.string())- .optional()- .describe('Filter to specific event names'),- properties: z.record(z.string(), z.string()).optional(),- limit: z.number().min(1).max(100).default(50).optional(),- }),- },- async ({ profileId, eventNames, properties, limit }, context) => {- const events = await queryEventsCore({- projectId: context.projectId,- profileId: profileId || context.pageContext?.ids?.profileId || '',- eventNames,- properties,- limit: limit ?? 50,- });- return truncateRows(events, 100);- }-);--export const getProfileSessions = chatTool(- {- name: 'get_profile_sessions',- description: 'All sessions for this profile, ordered most-recent-first.',- schema: z.object({- profileId: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async ({ profileId, limit }, context) => {- const sessions = await getProfileSessionsCore(- context.projectId,- profileId || context.pageContext?.ids?.profileId || '',- limit ?? 20- );- return truncateRows(- sessions.map((s) => ({- ...s,+export const getProfileFull = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_profile_full',+ description:+ 'One-shot deep dive: profile data + lifetime metrics + last 5 sessions + last 10 events. CALL THIS FIRST when the user asks "tell me about this user" — it covers ~80% of follow-up questions in one round trip.',+ schema: z.object({+ profileId: z+ .string()+ .optional()+ .describe('Defaults to the currently-viewed profile.'),+ }),+ },+ async ({ profileId }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';+ const [profile, withEvents, sessions, metrics] = await Promise.all([+ getProfileById(deps, id, context.projectId),+ getProfileWithEvents(deps, context.projectId, id, 10),+ getProfileSessionsCore(deps, context.projectId, id, 5),+ getProfileMetricsCore(deps, {+ projectId: context.projectId,+ profileId: id,+ }).catch(() => null),+ ]);+ if (!profile) {+ return { error: 'Profile not found', profileId: id };+ }+ return {+ profile,+ metrics,+ recent_sessions: sessions,+ recent_events: withEvents.recent_events,dashboard_url: dashboardUrl(context.organizationId,context.projectId,- `/sessions/${s.id}`+ `/profiles/${id}`),- })),- 100- );- }-);--export const getProfileMetrics = chatTool(- {- name: 'get_profile_metrics',- description:- 'Lifetime metrics for this profile: sessions, screen views, total events, avg/p90 session duration, bounce rate, conversion events, time between sessions, revenue.',- schema: z.object({- profileId: z.string().optional(),- }),- },- async ({ profileId }, context) =>- getProfileMetricsCore({- projectId: context.projectId,- profileId: profileId || context.pageContext?.ids?.profileId || '',- })-);+ };+ }+ );-export const getProfileJourney = chatTool(- {- name: 'get_profile_journey',- description:- 'Chronological narrative of this user\'s journey: first session, key conversion events, last 30 days summary. Designed for "tell me their story" questions — gives the LLM a structured timeline rather than a flat event list.',- schema: z.object({- profileId: z.string().optional(),- sinceDays: z.number().min(1).max(365).default(90).optional(),- maxEvents: z.number().min(5).max(100).default(50).optional(),- }),- },- async ({ profileId, sinceDays, maxEvents }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';- const [profile, events, sessions, metrics] = await Promise.all([- getProfileById(id, context.projectId),- queryEventsCore({- projectId: context.projectId,- profileId: id,- limit: maxEvents ?? 50,+export const getProfileEvents = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_profile_events',+ description:+ "Recent events for this profile, optionally filtered by event name or property. Use when get_profile_full doesn't cover the question.",+ schema: z.object({+ profileId: z.string().optional(),+ eventNames: z+ .array(z.string())+ .optional()+ .describe('Filter to specific event names'),+ properties: z.record(z.string(), z.string()).optional(),+ limit: z.number().min(1).max(100).default(50).optional(),}),- getProfileSessionsCore(context.projectId, id, 20),- getProfileMetricsCore({+ },+ async ({ profileId, eventNames, properties, limit }, context) => {+ const events = await queryEventsCore(deps, {projectId: context.projectId,- profileId: id,- }).catch(() => null),- ]);-- if (!profile) {- return { error: 'Profile not found', profileId: id };+ profileId: profileId || context.pageContext?.ids?.profileId || '',+ eventNames,+ properties,+ limit: limit ?? 50,+ });+ return truncateRows(events, 100);}+ );- // Heuristic: events that look like conversions (purchase, signup,- // checkout, subscribe, upgrade, complete, etc.)- const conversionPattern =- /^(purchase|sign_?up|signup|register|subscribe|checkout|upgrade|complete|paid|conversion)/i;- const keyMoments = events.filter((e) => conversionPattern.test(e.name));-- return {- profile_id: id,- first_seen:- metrics?.firstSeen ?? sessions[sessions.length - 1]?.created_at ?? null,- last_seen: metrics?.lastSeen ?? sessions[0]?.created_at ?? null,- total_sessions: metrics?.sessions ?? sessions.length,- total_events: metrics?.totalEvents ?? events.length,- key_moments: keyMoments.slice(0, 10),- recent_sessions: sessions.slice(0, 5).map((s) => ({- id: s.id,- created_at: s.created_at,- duration: s.duration,- entry_path: s.entry_path,- exit_path: s.exit_path,- is_bounce: s.is_bounce,- country: s.country,- referrer: s.referrer,- })),- recent_events: events.slice(0, 20).map((e) => ({- id: e.id,- name: e.name,- path: e.path,- created_at: e.created_at,- })),- dashboard_url: dashboardUrl(- context.organizationId,+export const getProfileSessions = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_profile_sessions',+ description: 'All sessions for this profile, ordered most-recent-first.',+ schema: z.object({+ profileId: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async ({ profileId, limit }, context) => {+ const sessions = await getProfileSessionsCore(+ deps,context.projectId,- `/profiles/${id}`- ),- };- }-);--export const getProfileGroups = chatTool(- {- name: 'get_profile_groups',- description:- 'Groups (B2B accounts) this profile belongs to. Returns the list of group IDs from the profile record.',- schema: z.object({- profileId: z.string().optional(),- }),- },- async ({ profileId }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';- const profile = await getProfileById(id, context.projectId);- if (!profile) {- return { error: 'Profile not found', profileId: id };+ profileId || context.pageContext?.ids?.profileId || '',+ limit ?? 20+ );+ return truncateRows(+ sessions.map((s) => ({+ ...s,+ dashboard_url: dashboardUrl(+ context.organizationId,+ context.projectId,+ `/sessions/${s.id}`+ ),+ })),+ 100+ );}- return {- profileId: profile.id,- group_count: (profile.groups ?? []).length,- groups: profile.groups ?? [],- };- }-);+ );-export const compareProfileToAverage = chatTool(- {- name: 'compare_profile_to_average',- description:- 'How this profile\'s key metrics compare to the project average — sessions, total events, bounce rate, etc. Returns ratios and "above/below" labels for each metric. Useful for spotting power users vs lurkers.',- schema: z.object({- profileId: z.string().optional(),- }),- },- async ({ profileId }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';-- // Get this profile's metrics + a sample of other profiles' metrics- const [thisMetrics, allProfiles] = await Promise.all([- getProfileMetricsCore({+export const getProfileMetrics = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_profile_metrics',+ description:+ 'Lifetime metrics for this profile: sessions, screen views, total events, avg/p90 session duration, bounce rate, conversion events, time between sessions, revenue.',+ schema: z.object({+ profileId: z.string().optional(),+ }),+ },+ async ({ profileId }, context) =>+ getProfileMetricsCore(deps, {projectId: context.projectId,- profileId: id,- }).catch(() => null),- findProfilesCore({ projectId: context.projectId, limit: 100 }),- ]);+ profileId: profileId || context.pageContext?.ids?.profileId || '',+ })+ );- if (!thisMetrics) {- return { error: 'Profile not found or has no events', profileId: id };- }+export const getProfileJourney = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_profile_journey',+ description:+ 'Chronological narrative of this user\'s journey: first session, key conversion events, last 30 days summary. Designed for "tell me their story" questions — gives the LLM a structured timeline rather than a flat event list.',+ schema: z.object({+ profileId: z.string().optional(),+ sinceDays: z.number().min(1).max(365).default(90).optional(),+ maxEvents: z.number().min(5).max(100).default(50).optional(),+ }),+ },+ async ({ profileId, sinceDays, maxEvents }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';+ const [profile, events, sessions, metrics] = await Promise.all([+ getProfileById(deps, id, context.projectId),+ queryEventsCore(deps, {+ projectId: context.projectId,+ profileId: id,+ limit: maxEvents ?? 50,+ }),+ getProfileSessionsCore(deps, context.projectId, id, 20),+ getProfileMetricsCore(deps, {+ projectId: context.projectId,+ profileId: id,+ }).catch(() => null),+ ]);- // Compute averages from a sample of other profiles. We sample 100- // and compute their metrics in parallel; for a precise project-wide- // average we'd want a dedicated db helper, but this gives the LLM a- // useful comparison without extra schema work.- const sampleIds = allProfiles- .filter((p) => p.id !== id)- .slice(0, 30)- .map((p) => p.id);+ if (!profile) {+ return { error: 'Profile not found', profileId: id };+ }- const sampleMetrics = await Promise.all(- sampleIds.map((sid) =>- getProfileMetricsCore({- projectId: context.projectId,- profileId: sid,- }).catch(() => null)- )- );- const valid = sampleMetrics.filter(- (m): m is NonNullable<typeof m> => m != null- );+ // Heuristic: events that look like conversions (purchase, signup,+ // checkout, subscribe, upgrade, complete, etc.)+ const conversionPattern =+ /^(purchase|sign_?up|signup|register|subscribe|checkout|upgrade|complete|paid|conversion)/i;+ const keyMoments = events.filter((e) => conversionPattern.test(e.name));- if (valid.length === 0) {return {- profile: thisMetrics,- comparison: null,- note: 'No other profiles available for comparison',+ profile_id: id,+ first_seen:+ metrics?.firstSeen ??+ sessions[sessions.length - 1]?.created_at ??+ null,+ last_seen: metrics?.lastSeen ?? sessions[0]?.created_at ?? null,+ total_sessions: metrics?.sessions ?? sessions.length,+ total_events: metrics?.totalEvents ?? events.length,+ key_moments: keyMoments.slice(0, 10),+ recent_sessions: sessions.slice(0, 5).map((s) => ({+ id: s.id,+ created_at: s.created_at,+ duration: s.duration,+ entry_path: s.entry_path,+ exit_path: s.exit_path,+ is_bounce: s.is_bounce,+ country: s.country,+ referrer: s.referrer,+ })),+ recent_events: events.slice(0, 20).map((e) => ({+ id: e.id,+ name: e.name,+ path: e.path,+ created_at: e.created_at,+ })),+ dashboard_url: dashboardUrl(+ context.organizationId,+ context.projectId,+ `/profiles/${id}`+ ),};}+ );- const avg = (sel: (m: (typeof valid)[number]) => number) =>- valid.reduce((s, m) => s + sel(m), 0) / valid.length;+export const getProfileGroups = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_profile_groups',+ description:+ 'Groups (B2B accounts) this profile belongs to. Returns the list of group IDs from the profile record.',+ schema: z.object({+ profileId: z.string().optional(),+ }),+ },+ async ({ profileId }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';+ const profile = await getProfileById(deps, id, context.projectId);+ if (!profile) {+ return { error: 'Profile not found', profileId: id };+ }+ return {+ profileId: profile.id,+ group_count: (profile.groups ?? []).length,+ groups: profile.groups ?? [],+ };+ }+ );++export const compareProfileToAverage = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'compare_profile_to_average',+ description:+ 'How this profile\'s key metrics compare to the project average — sessions, total events, bounce rate, etc. Returns ratios and "above/below" labels for each metric. Useful for spotting power users vs lurkers.',+ schema: z.object({+ profileId: z.string().optional(),+ }),+ },+ async ({ profileId }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';- const project_avg = {- sessions: avg((m) => m.sessions),- totalEvents: avg((m) => m.totalEvents),- screenViews: avg((m) => m.screenViews),- avgSessionDurationMin: avg((m) => m.avgSessionDurationMin),- bounceRate: avg((m) => m.bounceRate),- revenue: avg((m) => m.revenue),- };+ // Get this profile's metrics + a sample of other profiles' metrics+ const [thisMetrics, allProfiles] = await Promise.all([+ getProfileMetricsCore(deps, {+ projectId: context.projectId,+ profileId: id,+ }).catch(() => null),+ findProfilesCore(deps, { projectId: context.projectId, limit: 100 }),+ ]);- const ratio = (- a: number,- b: number- ): { ratio: number; label: 'above' | 'below' | 'equal' } => {- if (b === 0) {- return { ratio: 0, label: a > 0 ? 'above' : 'equal' };+ if (!thisMetrics) {+ return { error: 'Profile not found or has no events', profileId: id };}- const r = a / b;- return {- ratio: Number(r.toFixed(2)),- label: r > 1.05 ? 'above' : r < 0.95 ? 'below' : 'equal',++ // Compute averages from a sample of other profiles. We sample 100+ // and compute their metrics in parallel; for a precise project-wide+ // average we'd want a dedicated db helper, but this gives the LLM a+ // useful comparison without extra schema work.+ const sampleIds = allProfiles+ .filter((p) => p.id !== id)+ .slice(0, 30)+ .map((p) => p.id);++ const sampleMetrics = await Promise.all(+ sampleIds.map((sid) =>+ getProfileMetricsCore(deps, {+ projectId: context.projectId,+ profileId: sid,+ }).catch(() => null)+ )+ );+ const valid = sampleMetrics.filter(+ (m): m is NonNullable<typeof m> => m != null+ );++ if (valid.length === 0) {+ return {+ profile: thisMetrics,+ comparison: null,+ note: 'No other profiles available for comparison',+ };+ }++ const avg = (sel: (m: (typeof valid)[number]) => number) =>+ valid.reduce((s, m) => s + sel(m), 0) / valid.length;++ const project_avg = {+ sessions: avg((m) => m.sessions),+ totalEvents: avg((m) => m.totalEvents),+ screenViews: avg((m) => m.screenViews),+ avgSessionDurationMin: avg((m) => m.avgSessionDurationMin),+ bounceRate: avg((m) => m.bounceRate),+ revenue: avg((m) => m.revenue),};- };- return {- profile: thisMetrics,- project_avg,- comparison: {- sessions: ratio(thisMetrics.sessions, project_avg.sessions),- totalEvents: ratio(thisMetrics.totalEvents, project_avg.totalEvents),- screenViews: ratio(thisMetrics.screenViews, project_avg.screenViews),- avgSessionDurationMin: ratio(- thisMetrics.avgSessionDurationMin,- project_avg.avgSessionDurationMin- ),- bounceRate: ratio(thisMetrics.bounceRate, project_avg.bounceRate),- revenue: ratio(thisMetrics.revenue, project_avg.revenue),- },- sample_size: valid.length,- };- }-);+ const ratio = (+ a: number,+ b: number+ ): { ratio: number; label: 'above' | 'below' | 'equal' } => {+ if (b === 0) {+ return { ratio: 0, label: a > 0 ? 'above' : 'equal' };+ }+ const r = a / b;+ return {+ ratio: Number(r.toFixed(2)),+ label: r > 1.05 ? 'above' : r < 0.95 ? 'below' : 'equal',+ };+ };++ return {+ profile: thisMetrics,+ project_avg,+ comparison: {+ sessions: ratio(thisMetrics.sessions, project_avg.sessions),+ totalEvents: ratio(thisMetrics.totalEvents, project_avg.totalEvents),+ screenViews: ratio(thisMetrics.screenViews, project_avg.screenViews),+ avgSessionDurationMin: ratio(+ thisMetrics.avgSessionDurationMin,+ project_avg.avgSessionDurationMin+ ),+ bounceRate: ratio(thisMetrics.bounceRate, project_avg.bounceRate),+ revenue: ratio(thisMetrics.revenue, project_avg.revenue),+ },+ sample_size: valid.length,+ };+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/references.ts b/packages/core/src/modules/assistant/src/tools/references.tsindex 16cd3e51a..e1003d3b1 100644--- a/packages/core/src/modules/assistant/src/tools/references.ts+++ b/packages/core/src/modules/assistant/src/tools/references.ts@@ -1,10 +1,6 @@import { z } from 'zod';-import {- chatTool,- loadCompatDb,- resolveDateRange,- truncateRows,-} from './helpers';+import type { ServiceDeps } from '../../../../services';+import { chatTool, resolveDateRange, truncateRows } from './helpers';/*** References are manual annotations the user adds — e.g.@@ -21,114 +17,116 @@ import {* if a reference explains it.*/-export const listReferences = chatTool(- {- name: 'list_references',- description:- "List the user's manual references (campaign launches, deploys, announcements, etc.). Use when the user asks about causes of traffic changes or wants to understand what was happening at a specific time. Defaults to the user's current page date range; pass explicit dates to override.",- schema: z.object({- startDate: z- .string()- .optional()- .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),- endDate: z- .string()- .optional()- .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),- search: z- .string()- .optional()- .describe('Optional free-text filter on title/description.'),- limit: z.number().min(1).max(100).default(50).optional(),- }),- },- async ({ startDate, endDate, search, limit }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });+export const listReferences = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'list_references',+ description:+ "List the user's manual references (campaign launches, deploys, announcements, etc.). Use when the user asks about causes of traffic changes or wants to understand what was happening at a specific time. Defaults to the user's current page date range; pass explicit dates to override.",+ schema: z.object({+ startDate: z+ .string()+ .optional()+ .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),+ endDate: z+ .string()+ .optional()+ .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),+ search: z+ .string()+ .optional()+ .describe('Optional free-text filter on title/description.'),+ limit: z.number().min(1).max(100).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, search, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });- const db = await loadCompatDb();- const rows = await db.reference.findMany({- where: {- projectId: context.projectId,- date: {- gte: new Date(range.startDate),- lte: new Date(`${range.endDate}T23:59:59.999Z`),- },- ...(search- ? {- OR: [- { title: { contains: search, mode: 'insensitive' as const } },- {- description: {- contains: search,- mode: 'insensitive' as const,+ const db = deps.db;+ const rows = await db.reference.findMany({+ where: {+ projectId: context.projectId,+ date: {+ gte: new Date(range.startDate),+ lte: new Date(`${range.endDate}T23:59:59.999Z`),+ },+ ...(search+ ? {+ OR: [+ { title: { contains: search, mode: 'insensitive' as const } },+ {+ description: {+ contains: search,+ mode: 'insensitive' as const,+ },},- },- ],- }- : {}),- },- orderBy: { date: 'desc' },- take: limit ?? 50,- });-- return truncateRows(- rows.map((r) => ({- title: r.title,- date: r.date.toISOString().slice(0, 10),- description: r.description ?? '',- id: r.id,- })),- 100- );- }-);+ ],+ }+ : {}),+ },+ orderBy: { date: 'desc' },+ take: limit ?? 50,+ });-export const getReferencesAround = chatTool(- {- name: 'get_references_around',- description:- 'Find references within ±N days of a target date. Perfect for "what was happening around 2026-03-15?" — returns references that might explain a spike or drop.',- schema: z.object({- date: z.string().describe('Target date (YYYY-MM-DD) to search around.'),- daysBefore: z.number().min(0).max(90).default(7).optional(),- daysAfter: z.number().min(0).max(90).default(7).optional(),- }),- },- async ({ date, daysBefore, daysAfter }, context) => {- const target = new Date(date);- if (Number.isNaN(target.getTime())) {- return { error: 'Invalid date', date };+ return truncateRows(+ rows.map((r) => ({+ title: r.title,+ date: r.date.toISOString().slice(0, 10),+ description: r.description ?? '',+ id: r.id,+ })),+ 100+ );}- const before = daysBefore ?? 7;- const after = daysAfter ?? 7;- const start = new Date(target.getTime() - before * 86_400_000);- const end = new Date(target.getTime() + after * 86_400_000);+ );- const db = await loadCompatDb();- const rows = await db.reference.findMany({- where: {- projectId: context.projectId,- date: { gte: start, lte: end },- },- orderBy: { date: 'asc' },- });+export const getReferencesAround = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_references_around',+ description:+ 'Find references within ±N days of a target date. Perfect for "what was happening around 2026-03-15?" — returns references that might explain a spike or drop.',+ schema: z.object({+ date: z.string().describe('Target date (YYYY-MM-DD) to search around.'),+ daysBefore: z.number().min(0).max(90).default(7).optional(),+ daysAfter: z.number().min(0).max(90).default(7).optional(),+ }),+ },+ async ({ date, daysBefore, daysAfter }, context) => {+ const target = new Date(date);+ if (Number.isNaN(target.getTime())) {+ return { error: 'Invalid date', date };+ }+ const before = daysBefore ?? 7;+ const after = daysAfter ?? 7;+ const start = new Date(target.getTime() - before * 86_400_000);+ const end = new Date(target.getTime() + after * 86_400_000);- return {- target_date: date,- window: {- start: start.toISOString().slice(0, 10),- end: end.toISOString().slice(0, 10),- },- references: rows.map((r) => ({- title: r.title,- date: r.date.toISOString().slice(0, 10),- description: r.description ?? '',- id: r.id,- })),- };- }-);+ const db = deps.db;+ const rows = await db.reference.findMany({+ where: {+ projectId: context.projectId,+ date: { gte: start, lte: end },+ },+ orderBy: { date: 'asc' },+ });++ return {+ target_date: date,+ window: {+ start: start.toISOString().slice(0, 10),+ end: end.toISOString().slice(0, 10),+ },+ references: rows.map((r) => ({+ title: r.title,+ date: r.date.toISOString().slice(0, 10),+ description: r.description ?? '',+ id: r.id,+ })),+ };+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/report.ts b/packages/core/src/modules/assistant/src/tools/report.tsindex 19b2af22c..7bf0929ad 100644--- a/packages/core/src/modules/assistant/src/tools/report.ts+++ b/packages/core/src/modules/assistant/src/tools/report.ts@@ -1,178 +1,246 @@import { z } from 'zod';-import { listEventPropertiesCore } from '../../../../v1-compat';+import type { ServiceDeps } from '../../../../services';+import { listEventPropertiesCore } from '../../../event/event.service';import type { IReportInput } from '../../../report/report.constants';import { runReportFromConfig } from '../report-runner';import { chatTool, previousPeriod, resolveDateRange } from './helpers';-export const previewReportWithChanges = chatTool(- {- name: 'preview_report_with_changes',- description:- 'Apply a partial diff to the current report draft, execute it, and return the resulting data + the modified config. Use this to PROPOSE edits — the user can then accept or reject. Pass only the fields you want to change (e.g. { breakdowns: [{ name: "country" }] }).',- schema: z.object({- chartType: z- .enum(['linear', 'bar', 'area', 'histogram', 'pie', 'metric', 'funnel'])- .optional(),- interval: z.enum(['minute', 'hour', 'day', 'week', 'month']).optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- addBreakdown: z- .string()- .optional()- .describe('Property key to add as a breakdown (e.g. "country")'),- removeBreakdown: z- .string()- .optional()- .describe('Property key to remove from breakdowns'),- addEventFilter: z- .object({- seriesIndex: z.number().min(0),- name: z.string(),- operator: z.string(),- value: z.array(z.string()),- })- .optional(),- }),- },- async (input, context) => {- const draft = context.pageContext?.reportDraft as IReportInput | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }+export const previewReportWithChanges = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'preview_report_with_changes',+ description:+ 'Apply a partial diff to the current report draft, execute it, and return the resulting data + the modified config. Use this to PROPOSE edits — the user can then accept or reject. Pass only the fields you want to change (e.g. { breakdowns: [{ name: "country" }] }).',+ schema: z.object({+ chartType: z+ .enum([+ 'linear',+ 'bar',+ 'area',+ 'histogram',+ 'pie',+ 'metric',+ 'funnel',+ ])+ .optional(),+ interval: z.enum(['minute', 'hour', 'day', 'week', 'month']).optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ addBreakdown: z+ .string()+ .optional()+ .describe('Property key to add as a breakdown (e.g. "country")'),+ removeBreakdown: z+ .string()+ .optional()+ .describe('Property key to remove from breakdowns'),+ addEventFilter: z+ .object({+ seriesIndex: z.number().min(0),+ name: z.string(),+ operator: z.string(),+ value: z.array(z.string()),+ })+ .optional(),+ }),+ },+ async (input, context) => {+ const draft = context.pageContext?.reportDraft as+ | IReportInput+ | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }- const range = resolveDateRange({- startDate: input.startDate ?? draft.startDate ?? undefined,- endDate: input.endDate ?? draft.endDate ?? undefined,- });+ const range = resolveDateRange({+ startDate: input.startDate ?? draft.startDate ?? undefined,+ endDate: input.endDate ?? draft.endDate ?? undefined,+ });- const next: IReportInput = {- ...draft,- chartType: input.chartType ?? draft.chartType,- interval: input.interval ?? draft.interval,- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- breakdowns: [...(draft.breakdowns ?? [])],- series: draft.series.map((s) => ({ ...s })),- };+ const next: IReportInput = {+ ...draft,+ chartType: input.chartType ?? draft.chartType,+ interval: input.interval ?? draft.interval,+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ breakdowns: [...(draft.breakdowns ?? [])],+ series: draft.series.map((s) => ({ ...s })),+ };++ if (+ input.addBreakdown &&+ !next.breakdowns.some((b) => b.name === input.addBreakdown)+ ) {+ next.breakdowns.push({+ id: String(next.breakdowns.length + 1),+ name: input.addBreakdown,+ });+ }+ if (input.removeBreakdown) {+ next.breakdowns = next.breakdowns.filter(+ (b) => b.name !== input.removeBreakdown+ );+ }+ if (input.addEventFilter) {+ const idx = input.addEventFilter.seriesIndex;+ const target = next.series[idx];+ if (target && idx >= 0 && target.type === 'event') {+ // biome-ignore lint/suspicious/noExplicitAny: series type is heavily discriminated; filter ops vary+ const series = target as any;+ series.filters = [+ ...(series.filters ?? []),+ {+ id: String((series.filters?.length ?? 0) + 1),+ name: input.addEventFilter.name,+ operator: input.addEventFilter.operator,+ value: input.addEventFilter.value,+ },+ ];+ }+ }- if (- input.addBreakdown &&- !next.breakdowns.some((b) => b.name === input.addBreakdown)- ) {- next.breakdowns.push({- id: String(next.breakdowns.length + 1),- name: input.addBreakdown,+ return runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: next as unknown as Parameters<+ typeof runReportFromConfig+ >[1]['config'],});}- if (input.removeBreakdown) {- next.breakdowns = next.breakdowns.filter(- (b) => b.name !== input.removeBreakdown- );- }- if (input.addEventFilter) {- const idx = input.addEventFilter.seriesIndex;- const target = next.series[idx];- if (target && idx >= 0 && target.type === 'event') {- // biome-ignore lint/suspicious/noExplicitAny: series type is heavily discriminated; filter ops vary- const series = target as any;- series.filters = [- ...(series.filters ?? []),- {- id: String((series.filters?.length ?? 0) + 1),- name: input.addEventFilter.name,- operator: input.addEventFilter.operator,- value: input.addEventFilter.value,- },- ];+ );++export const suggestBreakdowns = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'suggest_breakdowns',+ description:+ 'Look at the events selected in the current draft and suggest 3-5 useful properties to break down by. Returns property keys + how often they appear.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as+ | IReportInput+ | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };}- }- return runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: next as unknown as Parameters<- typeof runReportFromConfig- >[0]['config'],- });- }-);+ const eventNames = draft.series+ .filter((s) => s.type === 'event')+ .map((s) => (s as { name: string }).name);-export const suggestBreakdowns = chatTool(- {- name: 'suggest_breakdowns',- description:- 'Look at the events selected in the current draft and suggest 3-5 useful properties to break down by. Returns property keys + how often they appear.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as IReportInput | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }+ if (eventNames.length === 0) {+ return { suggestions: [], note: 'Draft has no event series' };+ }++ const propsPerEvent = await Promise.all(+ eventNames.map((name) =>+ listEventPropertiesCore(deps, {+ projectId: context.projectId,+ eventName: name,+ })+ )+ );- const eventNames = draft.series- .filter((s) => s.type === 'event')- .map((s) => (s as { name: string }).name);+ // Aggregate property keys across events+ const keyCount = new Map<string, number>();+ for (const r of propsPerEvent) {+ for (const p of r.properties) {+ keyCount.set(p.property_key, (keyCount.get(p.property_key) ?? 0) + 1);+ }+ }- if (eventNames.length === 0) {- return { suggestions: [], note: 'Draft has no event series' };- }+ // Filter out keys that are already used as breakdowns+ const used = new Set((draft.breakdowns ?? []).map((b) => b.name));+ const suggestions = Array.from(keyCount.entries())+ .filter(([k]) => !used.has(k))+ .sort((a, b) => b[1] - a[1])+ .slice(0, 5)+ .map(([key, count]) => ({+ property_key: key,+ present_in_events: count,+ }));- const propsPerEvent = await Promise.all(- eventNames.map((name) =>- listEventPropertiesCore({- projectId: context.projectId,- eventName: name,- })- )- );+ return {+ events_in_draft: eventNames,+ existing_breakdowns: Array.from(used),+ suggestions,+ };+ }+ );- // Aggregate property keys across events- const keyCount = new Map<string, number>();- for (const r of propsPerEvent) {- for (const p of r.properties) {- keyCount.set(p.property_key, (keyCount.get(p.property_key) ?? 0) + 1);+export const compareToPreviousPeriod = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'compare_to_previous_period',+ description:+ 'Run the current draft against the immediately preceding period of the same length, and return both as { current, previous } so the user can see week-over-week / month-over-month change.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as+ | IReportInput+ | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };}- }- // Filter out keys that are already used as breakdowns- const used = new Set((draft.breakdowns ?? []).map((b) => b.name));- const suggestions = Array.from(keyCount.entries())- .filter(([k]) => !used.has(k))- .sort((a, b) => b[1] - a[1])- .slice(0, 5)- .map(([key, count]) => ({ property_key: key, present_in_events: count }));+ const range = resolveDateRange({+ startDate: draft.startDate ?? undefined,+ endDate: draft.endDate ?? undefined,+ });+ const prev = previousPeriod(range.startDate, range.endDate);- return {- events_in_draft: eventNames,- existing_breakdowns: Array.from(used),- suggestions,- };- }-);+ const [current, previous] = await Promise.all([+ runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],+ }),+ runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ startDate: prev.startDate,+ endDate: prev.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],+ }),+ ]);-export const compareToPreviousPeriod = chatTool(- {- name: 'compare_to_previous_period',- description:- 'Run the current draft against the immediately preceding period of the same length, and return both as { current, previous } so the user can see week-over-week / month-over-month change.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as IReportInput | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };+ return { current, previous };}+ );++export const findAnomaliesInCurrentReport = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'find_anomalies_in_current_report',+ description:+ 'Run the current draft and find data points that are unusually high or low (z-score > 2 from rolling mean). Returns the anomalies with their dates and magnitudes.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as+ | IReportInput+ | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }- const range = resolveDateRange({- startDate: draft.startDate ?? undefined,- endDate: draft.endDate ?? undefined,- });- const prev = previousPeriod(range.startDate, range.endDate);+ const range = resolveDateRange({+ startDate: draft.startDate ?? undefined,+ endDate: draft.endDate ?? undefined,+ });- const [current, previous] = await Promise.all([- runReportFromConfig({+ const result = await runReportFromConfig(deps, {organizationId: context.organizationId,projectId: context.projectId,config: {@@ -180,146 +248,107 @@ export const compareToPreviousPeriod = chatTool(startDate: range.startDate,endDate: range.endDate,range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],- }),- runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- startDate: prev.startDate,- endDate: prev.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],- }),- ]);-- return { current, previous };- }-);+ } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],+ });-export const findAnomaliesInCurrentReport = chatTool(- {- name: 'find_anomalies_in_current_report',- description:- 'Run the current draft and find data points that are unusually high or low (z-score > 2 from rolling mean). Returns the anomalies with their dates and magnitudes.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as IReportInput | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }+ // Best-effort anomaly detection on the first series of the result.+ // The data shape varies by chart type — we look for an array of+ // { date, count } points.+ // biome-ignore lint/suspicious/noExplicitAny: chart engine output shape is varied+ const data = result.data as any;+ const series = Array.isArray(data) ? data[0] : data?.series?.[0];+ const points = series?.data ?? [];- const range = resolveDateRange({- startDate: draft.startDate ?? undefined,- endDate: draft.endDate ?? undefined,- });+ if (!Array.isArray(points) || points.length < 5) {+ return {+ note: 'Not enough data points to detect anomalies',+ point_count: points.length ?? 0,+ };+ }- const result = await runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],- });+ const values = points.map((p: { count?: number }) =>+ Number(p.count ?? 0)+ );+ const mean =+ values.reduce((s: number, v: number) => s + v, 0) / values.length;+ const variance =+ values.reduce((s: number, v: number) => s + (v - mean) ** 2, 0) /+ values.length;+ const std = Math.sqrt(variance);- // Best-effort anomaly detection on the first series of the result.- // The data shape varies by chart type — we look for an array of- // { date, count } points.- // biome-ignore lint/suspicious/noExplicitAny: chart engine output shape is varied- const data = result.data as any;- const series = Array.isArray(data) ? data[0] : data?.series?.[0];- const points = series?.data ?? [];+ const anomalies = points+ .map((p: { date?: string; count?: number }, i: number) => {+ const z = std === 0 ? 0 : (Number(p.count ?? 0) - mean) / std;+ return {+ date: p.date,+ value: p.count,+ z_score: Number(z.toFixed(2)),+ index: i,+ };+ })+ .filter((a: { z_score: number }) => Math.abs(a.z_score) > 2);- if (!Array.isArray(points) || points.length < 5) {return {- note: 'Not enough data points to detect anomalies',- point_count: points.length ?? 0,+ mean: Number(mean.toFixed(2)),+ std: Number(std.toFixed(2)),+ point_count: points.length,+ anomalies,};}+ );- const values = points.map((p: { count?: number }) => Number(p.count ?? 0));- const mean =- values.reduce((s: number, v: number) => s + v, 0) / values.length;- const variance =- values.reduce((s: number, v: number) => s + (v - mean) ** 2, 0) /- values.length;- const std = Math.sqrt(variance);-- const anomalies = points- .map((p: { date?: string; count?: number }, i: number) => {- const z = std === 0 ? 0 : (Number(p.count ?? 0) - mean) / std;- return {- date: p.date,- value: p.count,- z_score: Number(z.toFixed(2)),- index: i,- };- })- .filter((a: { z_score: number }) => Math.abs(a.z_score) > 2);-- return {- mean: Number(mean.toFixed(2)),- std: Number(std.toFixed(2)),- point_count: points.length,- anomalies,- };- }-);--export const explainFilterImpact = chatTool(- {- name: 'explain_filter_impact',- description:- 'Run the current draft both with and without its filters, and return both totals so the user can see how much the filters cut down the data.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as IReportInput | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }+export const explainFilterImpact = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'explain_filter_impact',+ description:+ 'Run the current draft both with and without its filters, and return both totals so the user can see how much the filters cut down the data.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as+ | IReportInput+ | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }- const range = resolveDateRange({- startDate: draft.startDate ?? undefined,- endDate: draft.endDate ?? undefined,- });+ const range = resolveDateRange({+ startDate: draft.startDate ?? undefined,+ endDate: draft.endDate ?? undefined,+ });- const filtered = await runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],- });+ const filtered = await runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],+ });- const cleanedSeries = draft.series.map((s) => ({- ...s,- filters: [],- }));+ const cleanedSeries = draft.series.map((s) => ({+ ...s,+ filters: [],+ }));- const unfiltered = await runReportFromConfig({- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- series: cleanedSeries,- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],- });+ const unfiltered = await runReportFromConfig(deps, {+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ series: cleanedSeries,+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],+ });- return {- with_filters: filtered,- without_filters: unfiltered,- };- }-);+ return {+ with_filters: filtered,+ without_filters: unfiltered,+ };+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/seo.ts b/packages/core/src/modules/assistant/src/tools/seo.tsindex b6eedeb43..f87de60fa 100644--- a/packages/core/src/modules/assistant/src/tools/seo.ts+++ b/packages/core/src/modules/assistant/src/tools/seo.ts@@ -1,6 +1,6 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';import {- getTopPagesCore,gscGetCannibalizationCore,gscGetOverviewCore,gscGetPageDetailsCore,@@ -8,269 +8,278 @@ import {gscGetQueryOpportunitiesCore,gscGetTopPagesCore,gscGetTopQueriesCore,-} from '../../../../v1-compat';+} from '../../../gsc/gsc.service';+import { getTopPagesCore } from '../../../overview/pages.service';import { chatTool, resolveDateRange, truncateRows } from './helpers';-export const gscGetOverview = chatTool(- {- name: 'gsc_get_overview',- description:- 'GSC performance over time — clicks, impressions, CTR, average position. Returns a daily/weekly/monthly time series plus totals.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- interval: z.enum(['day', 'week', 'month']).default('day').optional(),- }),- },- async ({ startDate, endDate, interval }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetOverviewCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- interval,- });- }-);--export const gscGetTopQueries = chatTool(- {- name: 'gsc_get_top_queries',- description:- 'Top search queries by clicks. Returns query, clicks, impressions, CTR, position.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await gscGetTopQueriesCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: limit ?? 50,- });- return truncateRows(rows, 100);- }-);--export const gscGetTopPages = chatTool(- {- name: 'gsc_get_top_pages',- description:- 'Top pages by GSC clicks. Returns page URL, clicks, impressions, CTR, position.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await gscGetTopPagesCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: limit ?? 50,- });- return truncateRows(rows, 100);- }-);--export const gscGetQueryDetails = chatTool(- {- name: 'gsc_get_query_details',- description:- 'Time-series + page list for a single query. Use after gsc_get_top_queries to drill into one query.',- schema: z.object({- query: z.string(),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ query, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetQueryDetailsCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- query,- });- }-);+export const gscGetOverview = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'gsc_get_overview',+ description:+ 'GSC performance over time — clicks, impressions, CTR, average position. Returns a daily/weekly/monthly time series plus totals.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ interval: z.enum(['day', 'week', 'month']).default('day').optional(),+ }),+ },+ async ({ startDate, endDate, interval }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetOverviewCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ interval,+ });+ }+ );-export const gscGetPageDetails = chatTool(- {- name: 'gsc_get_page_details',- description:- 'Time-series + ranking queries for a single page URL. Use after gsc_get_top_pages.',- schema: z.object({- page: z.string().describe('Full page URL'),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ page, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetPageDetailsCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- page,- });- }-);+export const gscGetTopQueries = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'gsc_get_top_queries',+ description:+ 'Top search queries by clicks. Returns query, clicks, impressions, CTR, position.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await gscGetTopQueriesCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: limit ?? 50,+ });+ return truncateRows(rows, 100);+ }+ );-export const gscGetQueryOpportunities = chatTool(- {- name: 'gsc_get_query_opportunities',- description:- 'Find low-hanging SEO fruit — queries ranking position 4-20 with high impressions but low clicks. Returns each opportunity with a score and reason.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- minImpressions: z.number().min(1).default(50).optional(),- }),- },- async ({ startDate, endDate, minImpressions }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetQueryOpportunitiesCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- minImpressions,- });- }-);+export const gscGetTopPages = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'gsc_get_top_pages',+ description:+ 'Top pages by GSC clicks. Returns page URL, clicks, impressions, CTR, position.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await gscGetTopPagesCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: limit ?? 50,+ });+ return truncateRows(rows, 100);+ }+ );-export const gscGetCannibalization = chatTool(- {- name: 'gsc_get_cannibalization',- description:- 'Find queries where multiple pages from the same site compete for the same ranking. Each result shows the query and the competing pages.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetCannibalizationCore({- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- });- }-);+export const gscGetQueryDetails = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'gsc_get_query_details',+ description:+ 'Time-series + page list for a single query. Use after gsc_get_top_queries to drill into one query.',+ schema: z.object({+ query: z.string(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ query, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetQueryDetailsCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ query,+ });+ }+ );-export const correlateSeoWithTraffic = chatTool(- {- name: 'correlate_seo_with_traffic',- description:- 'Combine GSC clicks with OpenPanel session data per page. Identifies pages with high SEO traffic but poor conversion (high bounce or low engagement). Run this when the user wants to know "which SEO pages aren\'t converting".',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(100).default(30).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });+export const gscGetPageDetails = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'gsc_get_page_details',+ description:+ 'Time-series + ranking queries for a single page URL. Use after gsc_get_top_pages.',+ schema: z.object({+ page: z.string().describe('Full page URL'),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ page, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetPageDetailsCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ page,+ });+ }+ );- const [gscPages, opPages] = await Promise.all([- gscGetTopPagesCore({+export const gscGetQueryOpportunities = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'gsc_get_query_opportunities',+ description:+ 'Find low-hanging SEO fruit — queries ranking position 4-20 with high impressions but low clicks. Returns each opportunity with a score and reason.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ minImpressions: z.number().min(1).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, minImpressions }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetQueryOpportunitiesCore(deps, {projectId: context.projectId,startDate: range.startDate,endDate: range.endDate,- limit: 200,+ minImpressions,+ });+ }+ );++export const gscGetCannibalization = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'gsc_get_cannibalization',+ description:+ 'Find queries where multiple pages from the same site compete for the same ranking. Each result shows the query and the competing pages.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),}),- getTopPagesCore({+ },+ async ({ startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetCannibalizationCore(deps, {projectId: context.projectId,startDate: range.startDate,endDate: range.endDate,- limit: 200,+ });+ }+ );++export const correlateSeoWithTraffic = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'correlate_seo_with_traffic',+ description:+ 'Combine GSC clicks with OpenPanel session data per page. Identifies pages with high SEO traffic but poor conversion (high bounce or low engagement). Run this when the user wants to know "which SEO pages aren\'t converting".',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(100).default(30).optional(),}),- ]);+ },+ async ({ startDate, endDate, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });- // The OP `getTopPagesCore` and GSC `gscGetTopPagesCore` return- // different row shapes — the fields we actually read are captured- // in these local types, keeping the lookup map typed.- type OpPage = {- name?: string;- path?: string;- sessions?: number;- bounce_rate?: number;- avg_duration?: number;- };- type GscPage = {- page: string;- clicks: number;- impressions: number;- ctr: number;- position: number;- };+ const [gscPages, opPages] = await Promise.all([+ gscGetTopPagesCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 200,+ }),+ getTopPagesCore(deps, {+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 200,+ }),+ ]);- const opByPath = new Map<string, OpPage>();- for (const p of opPages as OpPage[]) {- const key = String(p.name ?? p.path ?? '');- opByPath.set(key, p);- opByPath.set(key.replace(/\/$/, ''), p);- }+ // The OP `getTopPagesCore` and GSC `gscGetTopPagesCore` return+ // different row shapes — the fields we actually read are captured+ // in these local types, keeping the lookup map typed.+ type OpPage = {+ name?: string;+ path?: string;+ sessions?: number;+ bounce_rate?: number;+ avg_duration?: number;+ };+ type GscPage = {+ page: string;+ clicks: number;+ impressions: number;+ ctr: number;+ position: number;+ };- const correlated = (gscPages as GscPage[])- .map((g) => {- const pathOnly = g.page.replace(/^https?:\/\/[^/]+/, '');- const op =- opByPath.get(pathOnly) ?? opByPath.get(pathOnly.replace(/\/$/, ''));- return {- page: g.page,- gsc_clicks: g.clicks,- gsc_impressions: g.impressions,- gsc_ctr: g.ctr,- gsc_position: g.position,- op_sessions: op?.sessions ?? null,- op_bounce_rate: op?.bounce_rate ?? null,- op_avg_duration: op?.avg_duration ?? null,- underperforming:- (op?.bounce_rate ?? 0) > 70 || (op?.avg_duration ?? 99) < 1,- };- })- .sort((a, b) => b.gsc_clicks - a.gsc_clicks);+ const opByPath = new Map<string, OpPage>();+ for (const p of opPages as OpPage[]) {+ const key = String(p.name ?? p.path ?? '');+ opByPath.set(key, p);+ opByPath.set(key.replace(/\/$/, ''), p);+ }- return truncateRows(correlated, limit ?? 30);- }-);+ const correlated = (gscPages as GscPage[])+ .map((g) => {+ const pathOnly = g.page.replace(/^https?:\/\/[^/]+/, '');+ const op =+ opByPath.get(pathOnly) ?? opByPath.get(pathOnly.replace(/\/$/, ''));+ return {+ page: g.page,+ gsc_clicks: g.clicks,+ gsc_impressions: g.impressions,+ gsc_ctr: g.ctr,+ gsc_position: g.position,+ op_sessions: op?.sessions ?? null,+ op_bounce_rate: op?.bounce_rate ?? null,+ op_avg_duration: op?.avg_duration ?? null,+ underperforming:+ (op?.bounce_rate ?? 0) > 70 || (op?.avg_duration ?? 99) < 1,+ };+ })+ .sort((a, b) => b.gsc_clicks - a.gsc_clicks);++ return truncateRows(correlated, limit ?? 30);+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/session.ts b/packages/core/src/modules/assistant/src/tools/session.tsindex e8a61efda..966ae5ad3 100644--- a/packages/core/src/modules/assistant/src/tools/session.ts+++ b/packages/core/src/modules/assistant/src/tools/session.ts@@ -1,276 +1,284 @@import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';+import { queryEventsCore } from '../../../event/event.service';import {getSessionById,- queryEventsCore,querySessionsCore,-} from '../../../../v1-compat';+} from '../../../session/session.service';import { chatTool, dashboardUrl, truncateRows } from './helpers';-export const getSessionFull = chatTool(- {- name: 'get_session_full',- description:- 'One-shot session deep dive: session data + ordered events + path. CALL THIS FIRST for "what happened in this session".',- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const [session, events] = await Promise.all([- getSessionById(id, context.projectId),- queryEventsCore({- projectId: context.projectId,- sessionId: id,- limit: 100,+export const getSessionFull = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_session_full',+ description:+ 'One-shot session deep dive: session data + ordered events + path. CALL THIS FIRST for "what happened in this session".',+ schema: z.object({+ sessionId: z.string().optional(),}),- ]);-- const screenViews = events- .filter((e) => e.name === 'screen_view' && e.path)- .map((e) => ({ path: e.path, created_at: e.created_at }));-- return {- session,- event_count: events.length,- path_length: screenViews.length,- path: screenViews,- events: events.slice(0, 50),- dashboard_url: dashboardUrl(- context.organizationId,- context.projectId,- `/sessions/${id}`- ),- };- }-);--export const getSessionPath = chatTool(- {- name: 'get_session_path',- description: 'The chronological list of pages visited in this session.',- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const events = await queryEventsCore({- projectId: context.projectId,- sessionId: id,- eventNames: ['screen_view'],- limit: 100,- });- const path = events- .filter((e) => e.path)- .map((e) => ({- path: e.path,- origin: e.origin,- created_at: e.created_at,- }));- return { sessionId: id, page_count: path.length, path };- }-);--export const getSessionEvents = chatTool(- {- name: 'get_session_events',- description:- 'All events in this session, optionally filtered by event name.',- schema: z.object({- sessionId: z.string().optional(),- eventNames: z.array(z.string()).optional(),- }),- },- async ({ sessionId, eventNames }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const events = await queryEventsCore({- projectId: context.projectId,- sessionId: id,- eventNames,- limit: 100,- });- return truncateRows(events, 100);- }-);+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const [session, events] = await Promise.all([+ getSessionById(deps, id, context.projectId),+ queryEventsCore(deps, {+ projectId: context.projectId,+ sessionId: id,+ limit: 100,+ }),+ ]);-export const getSimilarSessions = chatTool(- {- name: 'get_similar_sessions',- description:- 'Find sessions with similar device + country + entry path to this one. Returns up to 10. Useful for "is this typical?" questions.',- schema: z.object({- sessionId: z.string().optional(),- limit: z.number().min(1).max(20).default(10).optional(),- }),- },- async ({ sessionId, limit }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(id, context.projectId);+ const screenViews = events+ .filter((e) => e.name === 'screen_view' && e.path)+ .map((e) => ({ path: e.path, created_at: e.created_at }));- const similar = await querySessionsCore({- projectId: context.projectId,- country: session.country ?? undefined,- device: session.device ?? undefined,- limit: (limit ?? 10) + 1,- });- // Drop the session itself- const filtered = similar.filter((s) => s.id !== id).slice(0, limit ?? 10);-- return {- reference: {- id: session.id,- country: session.country,- device: session.device,- entryPath: session.entryPath,- },- similar_sessions: filtered.map((s) => ({- ...s,+ return {+ session,+ event_count: events.length,+ path_length: screenViews.length,+ path: screenViews,+ events: events.slice(0, 50),dashboard_url: dashboardUrl(context.organizationId,context.projectId,- `/sessions/${s.id}`+ `/sessions/${id}`),- })),- };- }-);+ };+ }+ );-export const compareSessionToTypical = chatTool(- {- name: 'compare_session_to_typical',- description:- "Compare this session's duration / event count / screen views against the project averages. Helps spot outliers.",- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(id, context.projectId);+export const getSessionPath = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_session_path',+ description: 'The chronological list of pages visited in this session.',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const events = await queryEventsCore(deps, {+ projectId: context.projectId,+ sessionId: id,+ eventNames: ['screen_view'],+ limit: 100,+ });+ const path = events+ .filter((e) => e.path)+ .map((e) => ({+ path: e.path,+ origin: e.origin,+ created_at: e.created_at,+ }));+ return { sessionId: id, page_count: path.length, path };+ }+ );- // Sample recent sessions to compute project averages.- const sample = await querySessionsCore({- projectId: context.projectId,- limit: 100,- });- if (sample.length === 0) {- return { session, comparison: null };+export const getSessionEvents = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_session_events',+ description:+ 'All events in this session, optionally filtered by event name.',+ schema: z.object({+ sessionId: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ }),+ },+ async ({ sessionId, eventNames }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const events = await queryEventsCore(deps, {+ projectId: context.projectId,+ sessionId: id,+ eventNames,+ limit: 100,+ });+ return truncateRows(events, 100);}+ );- const avg = (sel: (s: (typeof sample)[number]) => number) =>- sample.reduce((s, sess) => s + sel(sess), 0) / sample.length;+export const getSimilarSessions = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_similar_sessions',+ description:+ 'Find sessions with similar device + country + entry path to this one. Returns up to 10. Useful for "is this typical?" questions.',+ schema: z.object({+ sessionId: z.string().optional(),+ limit: z.number().min(1).max(20).default(10).optional(),+ }),+ },+ async ({ sessionId, limit }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await getSessionById(deps, id, context.projectId);- const project_avg = {- duration: avg((s) => s.duration),- event_count: avg((s) => s.event_count),- screen_view_count: avg((s) => s.screen_view_count),- };+ const similar = await querySessionsCore(deps, {+ projectId: context.projectId,+ country: session.country ?? undefined,+ device: session.device ?? undefined,+ limit: (limit ?? 10) + 1,+ });+ // Drop the session itself+ const filtered = similar.filter((s) => s.id !== id).slice(0, limit ?? 10);- const ratio = (a: number, b: number) => {- if (b === 0) {- return { ratio: 0, label: 'equal' as const };- }- const r = a / b;return {- ratio: Number(r.toFixed(2)),- label:- r > 1.05- ? ('above' as const)- : r < 0.95- ? ('below' as const)- : ('equal' as const),+ reference: {+ id: session.id,+ country: session.country,+ device: session.device,+ entryPath: session.entryPath,+ },+ similar_sessions: filtered.map((s) => ({+ ...s,+ dashboard_url: dashboardUrl(+ context.organizationId,+ context.projectId,+ `/sessions/${s.id}`+ ),+ })),};- };+ }+ );- return {- session: {- id: session.id,- duration: session.duration,- event_count: session.eventCount,- screen_view_count: session.screenViewCount,- is_bounce: session.isBounce,- },- project_avg,- comparison: {- duration: ratio(session.duration, project_avg.duration),- event_count: ratio(session.eventCount, project_avg.event_count),- screen_view_count: ratio(- session.screenViewCount,- project_avg.screen_view_count- ),- },- sample_size: sample.length,- };- }-);+export const compareSessionToTypical = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'compare_session_to_typical',+ description:+ "Compare this session's duration / event count / screen views against the project averages. Helps spot outliers.",+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await getSessionById(deps, id, context.projectId);-export const getSessionReferrerContext = chatTool(- {- name: 'get_session_referrer_context',- description:- 'Context about how the user arrived: total traffic this period from the same referrer, plus a few sample sessions from that referrer.',- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(id, context.projectId);+ // Sample recent sessions to compute project averages.+ const sample = await querySessionsCore(deps, {+ projectId: context.projectId,+ limit: 100,+ });+ if (sample.length === 0) {+ return { session, comparison: null };+ }++ const avg = (sel: (s: (typeof sample)[number]) => number) =>+ sample.reduce((s, sess) => s + sel(sess), 0) / sample.length;++ const project_avg = {+ duration: avg((s) => s.duration),+ event_count: avg((s) => s.event_count),+ screen_view_count: avg((s) => s.screen_view_count),+ };++ const ratio = (a: number, b: number) => {+ if (b === 0) {+ return { ratio: 0, label: 'equal' as const };+ }+ const r = a / b;+ return {+ ratio: Number(r.toFixed(2)),+ label:+ r > 1.05+ ? ('above' as const)+ : r < 0.95+ ? ('below' as const)+ : ('equal' as const),+ };+ };- if (!(session.referrer || session.referrerName)) {return {- session_id: id,- referrer: null,- note: 'This session has no referrer (direct traffic).',+ session: {+ id: session.id,+ duration: session.duration,+ event_count: session.eventCount,+ screen_view_count: session.screenViewCount,+ is_bounce: session.isBounce,+ },+ project_avg,+ comparison: {+ duration: ratio(session.duration, project_avg.duration),+ event_count: ratio(session.eventCount, project_avg.event_count),+ screen_view_count: ratio(+ session.screenViewCount,+ project_avg.screen_view_count+ ),+ },+ sample_size: sample.length,};}+ );- const fromSameReferrer = await querySessionsCore({- projectId: context.projectId,- referrerName: session.referrerName ?? undefined,- limit: 20,- });+export const getSessionReferrerContext = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_session_referrer_context',+ description:+ 'Context about how the user arrived: total traffic this period from the same referrer, plus a few sample sessions from that referrer.',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await getSessionById(deps, id, context.projectId);- return {- session_id: id,- referrer: session.referrer,- referrer_name: session.referrerName,- referrer_type: session.referrerType,- total_from_referrer: fromSameReferrer.length,- sample_sessions: fromSameReferrer.slice(0, 5).map((s) => ({- id: s.id,- created_at: s.created_at,- country: s.country,- is_bounce: s.is_bounce,- entry_path: s.entry_path,- })),- };- }-);+ if (!(session.referrer || session.referrerName)) {+ return {+ session_id: id,+ referrer: null,+ note: 'This session has no referrer (direct traffic).',+ };+ }-export const getSessionReplaySummary = chatTool(- {- name: 'get_session_replay_summary',- description:- 'Whether this session has a recorded replay available. Returns metadata if so. If no replay, returns { available: false }.',- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(id, context.projectId);- return {- session_id: id,- available: session.hasReplay ?? false,- replay_url: session.hasReplay- ? dashboardUrl(- context.organizationId,- context.projectId,- `/sessions/${id}`- )- : null,- };- }-);+ const fromSameReferrer = await querySessionsCore(deps, {+ projectId: context.projectId,+ referrerName: session.referrerName ?? undefined,+ limit: 20,+ });++ return {+ session_id: id,+ referrer: session.referrer,+ referrer_name: session.referrerName,+ referrer_type: session.referrerType,+ total_from_referrer: fromSameReferrer.length,+ sample_sessions: fromSameReferrer.slice(0, 5).map((s) => ({+ id: s.id,+ created_at: s.created_at,+ country: s.country,+ is_bounce: s.is_bounce,+ entry_path: s.entry_path,+ })),+ };+ }+ );++export const getSessionReplaySummary = (deps: ServiceDeps) =>+ chatTool(+ {+ name: 'get_session_replay_summary',+ description:+ 'Whether this session has a recorded replay available. Returns metadata if so. If no replay, returns { available: false }.',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await getSessionById(deps, id, context.projectId);+ return {+ session_id: id,+ available: session.hasReplay ?? false,+ replay_url: session.hasReplay+ ? dashboardUrl(+ context.organizationId,+ context.projectId,+ `/sessions/${id}`+ )+ : null,+ };+ }+ );diff --git a/packages/core/src/modules/assistant/src/tools/ui.ts b/packages/core/src/modules/assistant/src/tools/ui.tsindex dcdb11777..5c2a4beef 100644--- a/packages/core/src/modules/assistant/src/tools/ui.ts+++ b/packages/core/src/modules/assistant/src/tools/ui.ts@@ -1,4 +1,5 @@import { type AgentToolDefinition, defineTool } from '@better-agent/core';+import type { ServiceDeps } from '../../../../services';import {applyFiltersSchema,setEventNamesFilterSchema,@@ -13,6 +14,10 @@ import {* by updating the URL params the dashboard's hooks read. Zod schemas* are imported from `assistant.constants.ts` so the frontend handler* types stay in sync with what the LLM calls.+ *+ * Each is exported as a `(deps) => AgentToolDefinition` for uniformity with+ * every other tool bucket (`./index.ts`'s `ToolFactory`); these three touch+ * nothing, so `_deps` is genuinely unused here.*/// Cast to `any` before `.client()` for the same reason `chatTool`@@ -29,7 +34,7 @@ const applyFiltersContract: any = defineTool({schema: applyFiltersSchema,});-export const applyFilters: AgentToolDefinition =+export const applyFilters = (_deps: ServiceDeps): AgentToolDefinition =>applyFiltersContract.client() as AgentToolDefinition;// biome-ignore lint/suspicious/noExplicitAny: see comment on applyFiltersContract@@ -40,7 +45,7 @@ const setPropertyFiltersContract: any = defineTool({schema: setPropertyFiltersSchema,});-export const setPropertyFilters: AgentToolDefinition =+export const setPropertyFilters = (_deps: ServiceDeps): AgentToolDefinition =>setPropertyFiltersContract.client() as AgentToolDefinition;// biome-ignore lint/suspicious/noExplicitAny: see comment on applyFiltersContract@@ -51,5 +56,5 @@ const setEventNamesFilterContract: any = defineTool({schema: setEventNamesFilterSchema,});-export const setEventNamesFilter: AgentToolDefinition =+export const setEventNamesFilter = (_deps: ServiceDeps): AgentToolDefinition =>setEventNamesFilterContract.client() as AgentToolDefinition;diff --git a/packages/core/src/modules/mcp/mcp.service.test.ts b/packages/core/src/modules/mcp/mcp.service.test.tsindex 71c24ecae..47f051366 100644--- a/packages/core/src/modules/mcp/mcp.service.test.ts+++ b/packages/core/src/modules/mcp/mcp.service.test.ts@@ -4,20 +4,19 @@* 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.+ * between requests. This file is that missing layer: the client lookup is a+ * stub on the `Services` handed in, 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.+ * M15-003: `deps` and `services` are now ARGUMENTS, so the Postgres handle+ * and the client lookup are supplied by the test rather than mocked into the+ * module registry. The only surviving `mock.module` calls are for the two+ * process-global seams MCP auth still reaches (`@openpanel/redis`'s+ * `getCache` and argon2 verification), and both are 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 {@@ -29,49 +28,7 @@ import {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/core');-const realClientsService = { ...actualClientsService };-mock.module('@openpanel/core', () => ({- ...realClientsService,- getClientByIdCached: mockGetClientByIdCached,-}));+import type { ServiceDeps, Services } from '../../services';const actualRedis = await import('@openpanel/redis');const realRedis = { ...actualRedis };@@ -88,30 +45,9 @@ mock.module('../../shared/crypto', () => ({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(async () => {- mock.module('../../clients/logger', () => realLogger);- mock.module('@openpanel/core', () => realClientsService);+afterAll(() => {mock.module('@openpanel/redis', () => realRedis);mock.module('../../shared/crypto', () => realCrypto);- mock.module('@openpanel/db/src/prisma-client', () => realPrismaClient);- // Restoring the module registry is not enough: `v1-compat.ts` MEMOIZES the- // fallback `ServiceDeps` the first time anything resolves it, so if that- // happened while the mock above was installed, every later FILE in this- // process keeps the mocked client (bare `bun test` shares one registry).- // Drop the memo too — same reason mcp's dashboard-management.test.ts does.- const { resetV1CompatServicesForTests } = await import('../../v1-compat');- resetV1CompatServicesForTests();});let handleStatelessMcpRequest: typeof import('./mcp.service').handleStatelessMcpRequest;@@ -120,6 +56,47 @@ beforeAll(async () => {({ handleStatelessMcpRequest } = await import('./mcp.service'));});+// 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 mockGetClientByIdCached = mock();++// Real pino would instantiate a pino-pretty transport worker thread whenever+// NODE_ENV isn't 'production' (clients/logger.ts), which intermittently fails+// to spawn under Bun. `deps.logger` is an argument now, so the test simply+// hands in a noop.+const noopLogger = {+ fatal: () => {+ // no-op+ },+ error: () => {+ // no-op+ },+ warn: () => {+ // no-op+ },+ info: () => {+ // no-op+ },+ debug: () => {+ // no-op+ },+ trace: () => {+ // no-op+ },+ child: () => noopLogger,+};++const deps = {+ db: { project: { findUnique: mockFindUnique } },+ logger: noopLogger,+} as unknown as ServiceDeps;++const services = {+ client: { getClientByIdCached: mockGetClientByIdCached },+} as unknown as Services;+const CLIENT_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';const CLIENT_SECRET = 'mysecret';const VALID_TOKEN = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString(@@ -134,6 +111,10 @@ const READ_CLIENT = {organizationId: 'org-1',};+function post(token: string | undefined, body: unknown) {+ return handleStatelessMcpRequest(deps, services, token, body);+}+beforeEach(() => {mockGetClientByIdCached.mockReset();mockGetClientByIdCached.mockResolvedValue(READ_CLIENT);@@ -144,7 +125,7 @@ beforeEach(() => {describe('handleStatelessMcpRequest — auth', () => {it('401s a request with no token, without ever reaching the MCP server', async () => {- const res = await handleStatelessMcpRequest(undefined, {+ const res = await post(undefined, {jsonrpc: '2.0',id: 1,method: 'tools/list',@@ -160,7 +141,7 @@ describe('handleStatelessMcpRequest — auth', () => {it('401s a request with a wrong secret', async () => {mockVerifyPassword.mockResolvedValue(false);- const res = await handleStatelessMcpRequest(VALID_TOKEN, {+ const res = await post(VALID_TOKEN, {jsonrpc: '2.0',id: 1,method: 'tools/list',@@ -172,18 +153,18 @@ describe('handleStatelessMcpRequest — auth', () => {describe('handleStatelessMcpRequest — protocol', () => {it('202s a notification and never runs it through the MCP server', async () => {- const res = await handleStatelessMcpRequest(VALID_TOKEN, {+ const res = await post(VALID_TOKEN, {jsonrpc: '2.0',method: 'notifications/initialized',});- // Authenticated (mock hit) but no `id` — dispatch never happens.+ // Authenticated (stub 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, {+ const res = await post(VALID_TOKEN, {jsonrpc: '2.0',id: 1,method: 'initialize',@@ -209,7 +190,7 @@ describe('handleStatelessMcpRequest — protocol', () => {});it('dispatches tools/list via the synthetic handshake when no prior initialize was sent', async () => {- const res = await handleStatelessMcpRequest(VALID_TOKEN, {+ const res = await post(VALID_TOKEN, {jsonrpc: '2.0',id: 2,method: 'tools/list',@@ -234,7 +215,7 @@ describe('handleStatelessMcpRequest — protocol', () => {types: [],});- const res = await handleStatelessMcpRequest(VALID_TOKEN, {+ const res = await post(VALID_TOKEN, {jsonrpc: '2.0',id: 3,method: 'tools/call',@@ -265,12 +246,12 @@ describe('handleStatelessMcpRequest — protocol', () => {});it('re-authenticates from scratch on every call — no session survives between requests', async () => {- const first = await handleStatelessMcpRequest(VALID_TOKEN, {+ const first = await post(VALID_TOKEN, {jsonrpc: '2.0',id: 4,method: 'tools/list',});- const second = await handleStatelessMcpRequest(VALID_TOKEN, {+ const second = await post(VALID_TOKEN, {jsonrpc: '2.0',id: 5,method: 'tools/list',diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.tsindex d45a9487c..4971ea4af 100644--- a/packages/core/src/modules/mcp/mcp.service.ts+++ b/packages/core/src/modules/mcp/mcp.service.ts@@ -10,46 +10,30 @@// 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.//-// M10-004: `createMcpService(deps)` lands here, which means THIS FILE is now-// statically imported by services.ts. `./src/server`'s `registerAllTools`-// pulls in ~20 tool files that reach this package's own barrel-// (`@openpanel/core`) for cross-module functions, so it stays behind a lazy-// loader — a static top-level import would make services.ts's own module-// evaluation re-enter that barrel mid-evaluation, the exact TDZ hazard-// index.ts's header used to document for this file before it was reached-// only through a dynamic import. `./src/auth` stays a plain static import:-// `extractToken` is synchronous today (`mcp.routes.ts` doesn't await it) and-// auth.ts no longer reaches the barrel at its own top level (M10-004, see-// that file's header) — nothing left to make lazy. `deps` is unused:-// `handleStatelessMcpRequest`'s signature is a hard contract (its own tests-// call it with none) and its tool tree already reaches Postgres/ClickHouse-// through the v1-compat singleton, the same way every other bare, no-`Ctx`-// caller in this wave does.+// M15-003: MCP is NOT a separate process and has no dependency builder of its+// own. `rest.routes.ts` mounts it with `.use(mcpRoutes(deps))`, so the route+// already holds the API's connections; this factory closes over them and+// hands them to `createMcpServer` per request (ADR-022 R6/R15, Carl's+// ruling). The `@modelcontextprotocol/sdk` tool-handler signature has no+// context parameter, which is a CLOSURE problem — solved by building the+// server where `deps` is in hand — not a context problem.import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';-import { createLogger } from '../../clients/logger';import type { ServiceDeps, Services } from '../../services';+import { compatPrisma } from '../../v1-compat';import {authenticateToken,extractToken,type McpAuthContext,McpAuthError,} from './src/auth';+import { createMcpServer } from './src/server';+import type { McpToolDeps } from './src/tools/shared';export type { McpAuthContext } from './src/auth';export { extractToken, McpAuthError } from './src/auth';-let _server: Promise<typeof import('./src/server')> | undefined;-function loadServer() {- if (!_server) {- _server = import('./src/server');- }- return _server;-}--const logger = createLogger({ name: 'mcp' });-const MCP_PROTOCOL_VERSION = '2024-11-05';const MCP_PROXY_CLIENT_INFO = { name: 'mcp-proxy', version: '0' };@@ -58,6 +42,26 @@ export interface McpHttpResult {body: unknown;}+/**+ * `Prisma.DbNull` — the explicit-SQL-NULL sentinel `dashboard-management.ts`+ * writes onto a nullable Json column. A frozen CONSTANT, not a client and not+ * a service graph: nothing about it is per-request, and resolving it opens no+ * connection.+ *+ * It comes off `v1-compat.ts` because that is the ONLY file in this package+ * `core-uses-ctx-not-db-internals` lets import `@openpanel/db`'s Prisma+ * namespace, and `ServiceDeps` has no field for it — the same door+ * `notification.service.ts`, `subscription.service.ts` and+ * `insight/src/store.ts` use for the same sentinel. This is the module's one+ * remaining edge to that file: the tool tree itself reaches Postgres and+ * ClickHouse through `deps`.+ */+let jsonNullSentinel: Promise<unknown> | undefined;+function dbJsonNull(): Promise<unknown> {+ jsonNullSentinel ??= compatPrisma().then((prisma) => prisma.DbNull);+ return jsonNullSentinel;+}+/*** Handle one stateless MCP POST request end-to-end.*@@ -68,15 +72,17 @@ export interface McpHttpResult {* the protocol to this function.*/export async function handleStatelessMcpRequest(+ deps: ServiceDeps,+ services: Services,token: string | undefined,body: unknown): Promise<McpHttpResult> {let context: McpAuthContext;try {- context = await authenticateToken(token);+ context = await authenticateToken(deps, services, token);} catch (err) {if (err instanceof McpAuthError) {- logger.warn({ reason: err.message }, 'MCP auth failed');+ deps.logger.warn({ reason: err.message }, 'MCP auth failed');return { status: 401, body: { error: err.message } };}throw err;@@ -89,16 +95,16 @@ export async function handleStatelessMcpRequest(return { status: 202, body: null };}- logToolCall(message, context);+ logToolCall(deps, message, context);const isInitializeRequest ='method' in message && message.method === 'initialize';const start = Date.now();const response = await runOnEphemeralServer(- context,+ { context, deps, dbJsonNull: await dbJsonNull(), services },message,isInitializeRequest);- logToolResult(message, response, start);+ logToolResult(deps, message, response, start);return { status: 200, body: response };}@@ -112,14 +118,13 @@ export async function handleStatelessMcpRequest(* reach its ready state.*/async function runOnEphemeralServer(- context: McpAuthContext,+ tools: McpToolDeps,message: JSONRPCMessage,isInitializeRequest: boolean): Promise<JSONRPCMessage> {- const { createMcpServer } = await loadServer();const [clientTransport, serverTransport] =InMemoryTransport.createLinkedPair();- const server = createMcpServer(context);+ const server = createMcpServer(tools);await server.connect(serverTransport);if (!isInitializeRequest) {@@ -151,7 +156,11 @@ async function runOnEphemeralServer(});}-function logToolCall(message: JSONRPCMessage, context: McpAuthContext) {+function logToolCall(+ deps: ServiceDeps,+ message: JSONRPCMessage,+ context: McpAuthContext+) {if (!('method' in message &&@@ -165,7 +174,7 @@ function logToolCall(message: JSONRPCMessage, context: McpAuthContext) {name?: string;arguments?: unknown;};- logger.info(+ deps.logger.info({tool: name,params: args,@@ -178,6 +187,7 @@ function logToolCall(message: JSONRPCMessage, context: McpAuthContext) {}function logToolResult(+ deps: ServiceDeps,message: JSONRPCMessage,response: JSONRPCMessage,start: number@@ -190,26 +200,24 @@ function logToolResult(};const isError ='result' in response && (response.result as { isError?: boolean })?.isError;- logger.info(+ deps.logger.info({ tool: name, durationMs: Date.now() - start, isError: isError ?? false },'MCP tool result');}/**- * Ignores BOTH arguments, and takes them only because ADR-022 R3 keeps the- * composition root a flat list: `extractToken` is pure and- * `handleStatelessMcpRequest` hands the request to the- * `@modelcontextprotocol/sdk` server, whose tool handlers have a fixed- * signature with no room for a `deps` argument (docs/TECH_DEBT.md's- * "loaders still standing" table).+ * The MCP tool tree reaches Postgres and ClickHouse through the `deps` this+ * factory closes over — there is no singleton and no "no context" path left+ * (ADR-022 R6). `extractToken` is pure and stays a bare re-export.*/-export function createMcpService(- _deps: ServiceDeps,- _services: () => Services-) {+export function createMcpService(deps: ServiceDeps, services: () => Services) {return {extractToken,- handleStatelessMcpRequest,+ handleStatelessMcpRequest: (+ token: string | undefined,+ body: unknown+ ): Promise<McpHttpResult> =>+ handleStatelessMcpRequest(deps, services(), token, body),};}diff --git a/packages/core/src/modules/mcp/src/auth.test.ts b/packages/core/src/modules/mcp/src/auth.test.tsindex 4a33d6985..46c66f4c0 100644--- a/packages/core/src/modules/mcp/src/auth.test.ts+++ b/packages/core/src/modules/mcp/src/auth.test.ts@@ -25,48 +25,41 @@ const noopLogger = {child: () => noopLogger,};-// 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/core'-);-mock.module('@openpanel/core', () => ({- ...actualClientsService,- getClientByIdCached: mockGetClientByIdCached,-}));-+// M15-003: the client lookup and the logger are ARGUMENTS now — `deps` and+// `services` come from the route, so only `@openpanel/redis`'s process-global+// `getCache` and argon2 verification are still mocked at the specifier the+// source resolves to (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 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,-}));-const actualCrypto = await import('../../../shared/crypto');mock.module('../../../shared/crypto', () => ({...actualCrypto,verifyPassword: mockVerifyPassword,}));+import type { ServiceDeps, Services } from '../../../services';++const deps = { logger: noopLogger } as unknown as ServiceDeps;+const services = {+ client: { getClientByIdCached: mockGetClientByIdCached },+} as unknown as Services;++let authenticate: (+ token: string | undefined+) => ReturnType<typeof import('./auth').authenticateToken>;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'));+ authenticate = (token) => authenticateToken(deps, services, token);});beforeEach(() => {@@ -128,55 +121,51 @@ describe('extractToken', () => {describe('authenticateToken', () => {it('throws McpAuthError when token is missing', async () => {- await expect(authenticateToken(undefined)).rejects.toThrow(McpAuthError);- await expect(authenticateToken(undefined)).rejects.toThrow(+ await expect(authenticate(undefined)).rejects.toThrow(McpAuthError);+ await expect(authenticate(undefined)).rejects.toThrow('Missing authentication token');});it('throws McpAuthError for non-base64 token', async () => {// Buffer.from with invalid base64 doesn't throw — but the decoded result won't have a colon- await expect(authenticateToken('!!!invalid!!!')).rejects.toThrow(- McpAuthError- );+ await expect(authenticate('!!!invalid!!!')).rejects.toThrow(McpAuthError);});it('throws McpAuthError when token has no colon separator', async () => {const token = Buffer.from('nodivider').toString('base64');- await expect(authenticateToken(token)).rejects.toThrow(- 'Invalid token format'- );+ await expect(authenticate(token)).rejects.toThrow('Invalid token format');});it('throws McpAuthError when clientId is not a UUID', async () => {const token = Buffer.from('not-a-uuid:secret').toString('base64');- await expect(authenticateToken(token)).rejects.toThrow(+ await expect(authenticate(token)).rejects.toThrow('Invalid client ID format');});it('throws McpAuthError when clientSecret is empty', async () => {const token = Buffer.from(`${VALID_CLIENT_ID}:`).toString('base64');- await expect(authenticateToken(token)).rejects.toThrow(+ await expect(authenticate(token)).rejects.toThrow('Client secret is required');});it('throws McpAuthError when client is not found', async () => {mockGetClientByIdCached.mockResolvedValue(null);- await expect(authenticateToken(VALID_TOKEN)).rejects.toThrow(+ await expect(authenticate(VALID_TOKEN)).rejects.toThrow('Invalid credentials');});it('throws McpAuthError when client has no stored secret', async () => {mockGetClientByIdCached.mockResolvedValue({ ...baseClient, secret: null });- await expect(authenticateToken(VALID_TOKEN)).rejects.toThrow('no secret');+ await expect(authenticate(VALID_TOKEN)).rejects.toThrow('no secret');});it('throws McpAuthError for write-only clients', async () => {mockGetClientByIdCached.mockResolvedValue({ ...baseClient, type: 'write' });- await expect(authenticateToken(VALID_TOKEN)).rejects.toThrow(+ await expect(authenticate(VALID_TOKEN)).rejects.toThrow('Write-only clients');});@@ -184,14 +173,14 @@ describe('authenticateToken', () => {it('throws McpAuthError when password verification fails', async () => {mockGetClientByIdCached.mockResolvedValue(baseClient);mockVerifyPassword.mockResolvedValue(false);- await expect(authenticateToken(VALID_TOKEN)).rejects.toThrow(+ await expect(authenticate(VALID_TOKEN)).rejects.toThrow('Invalid credentials');});it('returns read client context on success', async () => {mockGetClientByIdCached.mockResolvedValue(baseClient);- const ctx = await authenticateToken(VALID_TOKEN);+ const ctx = await authenticate(VALID_TOKEN);expect(ctx).toEqual({projectId: 'proj-123',organizationId: 'org-456',@@ -205,7 +194,7 @@ describe('authenticateToken', () => {type: 'root',projectId: null,});- const ctx = await authenticateToken(VALID_TOKEN);+ const ctx = await authenticate(VALID_TOKEN);expect(ctx).toEqual({projectId: null,organizationId: 'org-456',@@ -217,7 +206,7 @@ describe('authenticateToken', () => {mockGetClientByIdCached.mockResolvedValue(baseClient);// Simulate cache returning true without calling verifyPasswordmockGetCache.mockResolvedValue(true);- const ctx = await authenticateToken(VALID_TOKEN);+ const ctx = await authenticate(VALID_TOKEN);expect(ctx.clientType).toBe('read');expect(mockVerifyPassword).not.toHaveBeenCalled();});@@ -231,7 +220,7 @@ describe('authenticateToken', () => {return fn();});- await authenticateToken(VALID_TOKEN);+ await authenticate(VALID_TOKEN);expect(capturedKey).toContain(`mcp:auth:${VALID_CLIENT_ID}:`);expect(capturedKey).not.toContain(VALID_SECRET);expect(capturedKey).not.toContain(diff --git a/packages/core/src/modules/mcp/src/auth.ts b/packages/core/src/modules/mcp/src/auth.tsindex e4a4aef4b..08bff91eb 100644--- a/packages/core/src/modules/mcp/src/auth.ts+++ b/packages/core/src/modules/mcp/src/auth.ts@@ -1,21 +1,8 @@import { createHash } from 'node:crypto';import { getCache } from '@openpanel/redis';-import { createLogger } from '../../../clients/logger';+import type { ServiceDeps, Services } from '../../../services';import { verifyPassword } from '../../../shared/crypto';-const logger = createLogger({ name: 'mcp:auth' });--// GENUINE CYCLE, kept lazy: `mcp.service.ts` statically imports this file-// (`extractToken` must stay synchronous — its own caller doesn't await it),-// and v1-compat.ts imports services.ts, which registers `createMcpService`.-// services.ts -> mcp.service.ts -> this file -> v1-compat.ts -> services.ts;-// the dynamic import is what keeps it a cycle ESM can evaluate. M10-009: the-// hop goes to the seam directly rather than through this package's own barrel-// (`core-no-self-barrel`) — same cycle, one module shorter.-function loadClientService() {- return import('../../../v1-compat');-}-export interface McpAuthContext {/*** Fixed project ID for read clients.@@ -44,8 +31,11 @@ export class McpAuthError extends Error {* - root clients get null projectId + organizationId (multi-project access)*/export async function authenticateToken(+ deps: ServiceDeps,+ services: Services,token: string | undefined): Promise<McpAuthContext> {+ const logger = deps.logger;if (!token) {throw new McpAuthError('Missing authentication token');}@@ -89,8 +79,7 @@ export async function authenticateToken(throw new McpAuthError('Client secret is required');}- const { getClientByIdCached } = await loadClientService();- const client = await getClientByIdCached(clientId);+ const client = await services.client.getClientByIdCached(clientId);if (!client) {logger.warn({ clientId }, 'MCP auth: client not found');throw new McpAuthError('Invalid credentials');diff --git a/packages/core/src/modules/mcp/src/integration/tools.test.ts b/packages/core/src/modules/mcp/src/integration/tools.test.tsindex a624f694e..da8b4125c 100644--- a/packages/core/src/modules/mcp/src/integration/tools.test.ts+++ b/packages/core/src/modules/mcp/src/integration/tools.test.ts@@ -20,6 +20,7 @@*/import { afterAll, beforeAll, describe, expect, it, mock } from 'bun:test';+import type { McpToolDeps } from '../tools/shared';const TEST_PROJECT_ID = 'mcp-integration-test';const TEST_ORG_ID = 'mcp-integration-org';@@ -91,20 +92,22 @@ beforeAll(async () => {await fixtures.setupPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);await fixtures.setupFixtures(TEST_PROJECT_ID);- // The mcp tools call core's chart/report functions as bare barrel exports- // (they have no `Ctx`), so they go through the V1 compat seam, which- // `main.ts` registers at boot and a test must register itself (M10-003).- const { setV1CompatServices } = await import('../../../../v1-compat');+ // M15-003: the tools take `deps`/`services` as arguments, so the suite+ // builds the same graph `mcp.routes.ts` hands them at runtime — no compat+ // seam, no process-global registration.const { testServiceDeps } = await import('../../../../../test/service-deps');- setV1CompatServices(await testServiceDeps());+ const { createServices } = await import('../../../../services');+ const deps = await testServiceDeps();+ TOOLS = {+ context: CTX,+ dbJsonNull: null,+ deps,+ services: createServices(deps),+ };}, 30_000);afterAll(async () => {const fixtures = await import('../../../../../../../test/fixtures');- const { resetV1CompatServicesForTests } = await import(- '../../../../v1-compat'- );- resetV1CompatServicesForTests();await fixtures.teardownFixtures(TEST_PROJECT_ID);await fixtures.teardownPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);});@@ -115,6 +118,9 @@ const CTX = {clientType: 'read' as const,};+/** What `createMcpServer` hands every tool at runtime. Built in `beforeAll`. */+let TOOLS: McpToolDeps;+function makeServer() {const handlers = new Map<string, (input: unknown) => Promise<unknown>>();return {@@ -158,7 +164,7 @@ function rowsOf(result: { columns: string[]; rows: unknown[][] }): any[] {describe('list_event_names', () => {it('returns { event_names: string[] }', async () => {const server = makeServer();- registerEventNameTools(server as any, CTX);+ registerEventNameTools(server as any, TOOLS);const res = await server.invoke('list_event_names', {projectId: TEST_PROJECT_ID,});@@ -169,7 +175,7 @@ describe('list_event_names', () => {describe('list_event_properties', () => {it('returns { columns, properties }', async () => {const server = makeServer();- registerPropertyValueTools(server as any, CTX);+ registerPropertyValueTools(server as any, TOOLS);const res = await server.invoke('list_event_properties', {projectId: TEST_PROJECT_ID,});@@ -182,7 +188,7 @@ describe('list_event_properties', () => {describe('get_event_property_values', () => {it('returns { event, property, values }', async () => {const server = makeServer();- registerPropertyValueTools(server as any, CTX);+ registerPropertyValueTools(server as any, TOOLS);const res = await server.invoke('get_event_property_values', {projectId: TEST_PROJECT_ID,eventName: 'purchase',@@ -199,7 +205,7 @@ describe('get_event_property_values', () => {describe('query_events', () => {it('returns all 8 fixture events', async () => {const server = makeServer();- registerEventTools(server as any, CTX);+ registerEventTools(server as any, TOOLS);const res = await server.invoke('query_events', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -210,7 +216,7 @@ describe('query_events', () => {it('filters by eventName — only returns purchase events', async () => {const server = makeServer();- registerEventTools(server as any, CTX);+ registerEventTools(server as any, TOOLS);const res = await server.invoke('query_events', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -226,7 +232,7 @@ describe('query_events', () => {it('filters by profileId — returns only alice events', async () => {const server = makeServer();- registerEventTools(server as any, CTX);+ registerEventTools(server as any, TOOLS);const res = await server.invoke('query_events', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -242,7 +248,7 @@ describe('query_events', () => {it('filters by browser', async () => {const server = makeServer();- registerEventTools(server as any, CTX);+ registerEventTools(server as any, TOOLS);const res = await server.invoke('query_events', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -261,7 +267,7 @@ describe('query_events', () => {describe('query_sessions', () => {it('returns all 3 fixture sessions', async () => {const server = makeServer();- registerSessionTools(server as any, CTX);+ registerSessionTools(server as any, TOOLS);const res = await server.invoke('query_sessions', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -272,7 +278,7 @@ describe('query_sessions', () => {it('filters by profileId — charlie has 2 sessions', async () => {const server = makeServer();- registerSessionTools(server as any, CTX);+ registerSessionTools(server as any, TOOLS);const res = await server.invoke('query_sessions', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -288,7 +294,7 @@ describe('query_sessions', () => {it('filters by browser', async () => {const server = makeServer();- registerSessionTools(server as any, CTX);+ registerSessionTools(server as any, TOOLS);const res = await server.invoke('query_sessions', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -306,7 +312,7 @@ describe('query_sessions', () => {describe('find_profiles', () => {it('returns all 3 fixture profiles', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('find_profiles', {projectId: TEST_PROJECT_ID,});@@ -315,7 +321,7 @@ describe('find_profiles', () => {it('filters by email partial match', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('find_profiles', {projectId: TEST_PROJECT_ID,email: 'alice@',@@ -327,7 +333,7 @@ describe('find_profiles', () => {it('filters by name — matches first_name and last_name', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const byFirst = await server.invoke('find_profiles', {projectId: TEST_PROJECT_ID,name: 'Charlie',@@ -345,7 +351,7 @@ describe('find_profiles', () => {it('filters by country property', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('find_profiles', {projectId: TEST_PROJECT_ID,country: 'SE',@@ -357,7 +363,7 @@ describe('find_profiles', () => {it('inactiveDays=7 excludes alice (active 2 days ago) but includes bob (no events)', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('find_profiles', {projectId: TEST_PROJECT_ID,inactiveDays: 7,@@ -370,7 +376,7 @@ describe('find_profiles', () => {it('minSessions=2 returns only charlie (has 2 sessions)', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('find_profiles', {projectId: TEST_PROJECT_ID,minSessions: 2,@@ -382,7 +388,7 @@ describe('find_profiles', () => {it('performedEvent=purchase returns only charlie', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('find_profiles', {projectId: TEST_PROJECT_ID,performedEvent: 'purchase',@@ -399,7 +405,7 @@ describe('find_profiles', () => {describe('get_profile', () => {it('returns correct profile and events for charlie', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('get_profile', {projectId: TEST_PROJECT_ID,profileId: FIXTURE.profiles.charlie,@@ -413,7 +419,7 @@ describe('get_profile', () => {describe('get_profile_sessions', () => {it('returns 2 sessions for charlie', async () => {const server = makeServer();- registerProfileTools(server as any, CTX);+ registerProfileTools(server as any, TOOLS);const res = await server.invoke('get_profile_sessions', {projectId: TEST_PROJECT_ID,profileId: FIXTURE.profiles.charlie,@@ -429,7 +435,7 @@ describe('get_profile_sessions', () => {describe('get_profile_metrics', () => {it('returns exact metrics for charlie', async () => {const server = makeServer();- registerProfileMetricTools(server as any, CTX);+ registerProfileMetricTools(server as any, TOOLS);const res = await server.invoke('get_profile_metrics', {projectId: TEST_PROJECT_ID,profileId: FIXTURE.profiles.charlie,@@ -448,7 +454,7 @@ describe('get_profile_metrics', () => {it('returns metrics for alice', async () => {const server = makeServer();- registerProfileMetricTools(server as any, CTX);+ registerProfileMetricTools(server as any, TOOLS);const res = await server.invoke('get_profile_metrics', {projectId: TEST_PROJECT_ID,profileId: FIXTURE.profiles.alice,@@ -466,7 +472,7 @@ describe('get_profile_metrics', () => {describe('list_group_types', () => {it('returns { types: [] } (no groups in fixtures)', async () => {const server = makeServer();- registerGroupTools(server as any, CTX);+ registerGroupTools(server as any, TOOLS);const res = await server.invoke('list_group_types', {projectId: TEST_PROJECT_ID,});@@ -478,7 +484,7 @@ describe('list_group_types', () => {describe('find_groups', () => {it('returns an empty table (no groups in fixtures)', async () => {const server = makeServer();- registerGroupTools(server as any, CTX);+ registerGroupTools(server as any, TOOLS);const res = await server.invoke('find_groups', {projectId: TEST_PROJECT_ID,});@@ -490,7 +496,7 @@ describe('find_groups', () => {describe('get_group', () => {it('returns not-found error for unknown group', async () => {const server = makeServer();- registerGroupTools(server as any, CTX);+ registerGroupTools(server as any, TOOLS);const res = await server.invoke('get_group', {projectId: TEST_PROJECT_ID,groupId: 'nonexistent',@@ -505,7 +511,7 @@ describe('get_group', () => {describe('get_analytics_overview', () => {it('returns summary with numeric metric fields and a series array', async () => {const server = makeServer();- registerOverviewTools(server as any, CTX);+ registerOverviewTools(server as any, TOOLS);const res = await server.invoke('get_analytics_overview', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -519,7 +525,7 @@ describe('get_analytics_overview', () => {describe('get_top_pages', () => {it('returns array including /shop and /home from fixtures', async () => {const server = makeServer();- registerPageTools(server as any, CTX);+ registerPageTools(server as any, TOOLS);const res = await server.invoke('get_top_pages', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -535,7 +541,7 @@ describe('get_top_pages', () => {describe('get_entry_exit_pages', () => {it('returns entry pages array', async () => {const server = makeServer();- registerPageTools(server as any, CTX);+ registerPageTools(server as any, TOOLS);const res = await server.invoke('get_entry_exit_pages', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -548,7 +554,7 @@ describe('get_entry_exit_pages', () => {it('returns exit pages array', async () => {const server = makeServer();- registerPageTools(server as any, CTX);+ registerPageTools(server as any, TOOLS);const res = await server.invoke('get_entry_exit_pages', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -563,7 +569,7 @@ describe('get_entry_exit_pages', () => {describe('get_page_performance', () => {it('returns a page table plus the shared seo thresholds', async () => {const server = makeServer();- registerPagePerformanceTools(server as any, CTX);+ registerPagePerformanceTools(server as any, TOOLS);const res = await server.invoke('get_page_performance', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -584,7 +590,7 @@ describe('get_page_performance', () => {describe('get_top_referrers', () => {it('returns a columnar table', async () => {const server = makeServer();- registerTrafficTools(server as any, CTX);+ registerTrafficTools(server as any, TOOLS);const res = await server.invoke('get_top_referrers', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -599,7 +605,7 @@ describe('get_top_referrers', () => {describe('get_country_breakdown', () => {it('returns US as country in fixtures', async () => {const server = makeServer();- registerTrafficTools(server as any, CTX);+ registerTrafficTools(server as any, TOOLS);const res = await server.invoke('get_country_breakdown', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -614,7 +620,7 @@ describe('get_country_breakdown', () => {describe('get_device_breakdown', () => {it('returns desktop in fixtures', async () => {const server = makeServer();- registerTrafficTools(server as any, CTX);+ registerTrafficTools(server as any, TOOLS);const res = await server.invoke('get_device_breakdown', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -631,7 +637,7 @@ describe('get_device_breakdown', () => {describe('get_funnel', () => {it('detects charlie completing session_start → purchase', async () => {const server = makeServer();- registerFunnelTools(server as any, CTX);+ registerFunnelTools(server as any, TOOLS);const res = await server.invoke('get_funnel', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -655,7 +661,7 @@ describe('get_funnel', () => {it('returns zero completions for an impossible funnel order', async () => {const server = makeServer();- registerFunnelTools(server as any, CTX);+ registerFunnelTools(server as any, TOOLS);const res = await server.invoke('get_funnel', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -669,7 +675,7 @@ describe('get_funnel', () => {describe('get_user_flow', () => {it('returns nodes and links for flow after session_start', async () => {const server = makeServer();- registerUserFlowTools(server as any, CTX);+ registerUserFlowTools(server as any, TOOLS);const res = await server.invoke('get_user_flow', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -687,7 +693,7 @@ describe('get_user_flow', () => {it('returns error when mode=between without endEvent', async () => {const server = makeServer();- registerUserFlowTools(server as any, CTX);+ registerUserFlowTools(server as any, TOOLS);const res = await server.invoke('get_user_flow', {projectId: TEST_PROJECT_ID,startDate: '2000-01-01',@@ -703,7 +709,7 @@ describe('get_user_flow', () => {describe('get_rolling_active_users', () => {it('returns DAU series (may be empty — dau_mv not auto-populated)', async () => {const server = makeServer();- registerActiveUserTools(server as any, CTX);+ registerActiveUserTools(server as any, TOOLS);const res = await server.invoke('get_rolling_active_users', {projectId: TEST_PROJECT_ID,days: 1,@@ -715,7 +721,7 @@ describe('get_rolling_active_users', () => {it('uses correct label for WAU and MAU', async () => {const server = makeServer();- registerActiveUserTools(server as any, CTX);+ registerActiveUserTools(server as any, TOOLS);const wau = await server.invoke('get_rolling_active_users', {projectId: TEST_PROJECT_ID,days: 7,@@ -732,7 +738,7 @@ describe('get_rolling_active_users', () => {describe('get_weekly_retention_series', () => {it('returns array of { date, active_users, retained_users, retention } rows', async () => {const server = makeServer();- registerActiveUserTools(server as any, CTX);+ registerActiveUserTools(server as any, TOOLS);const res = await server.invoke('get_weekly_retention_series', {projectId: TEST_PROJECT_ID,});@@ -749,7 +755,7 @@ describe('get_weekly_retention_series', () => {describe('get_retention_cohort', () => {it('returns weighted-average + per-cohort matrix rows', async () => {const server = makeServer();- registerRetentionTools(server as any, CTX);+ registerRetentionTools(server as any, TOOLS);const res = await server.invoke('get_retention_cohort', {projectId: TEST_PROJECT_ID,});@@ -768,7 +774,7 @@ describe('get_retention_cohort', () => {describe('get_user_last_seen_distribution', () => {it('returns alice and charlie in active_last_7_days bucket', async () => {const server = makeServer();- registerEngagementTools(server as any, CTX);+ registerEngagementTools(server as any, TOOLS);const res = await server.invoke('get_user_last_seen_distribution', {projectId: TEST_PROJECT_ID,});@@ -786,7 +792,7 @@ describe('get_user_last_seen_distribution', () => {it('returns the raw histogram when includeDistribution is set', async () => {const server = makeServer();- registerEngagementTools(server as any, CTX);+ registerEngagementTools(server as any, TOOLS);const res = await server.invoke('get_user_last_seen_distribution', {projectId: TEST_PROJECT_ID,includeDistribution: true,diff --git a/packages/core/src/modules/mcp/src/server.ts b/packages/core/src/modules/mcp/src/server.tsindex ac7977b92..580fe9490 100644--- a/packages/core/src/modules/mcp/src/server.ts+++ b/packages/core/src/modules/mcp/src/server.ts@@ -1,17 +1,19 @@import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import type { McpAuthContext } from './auth';import { registerAllTools } from './tools/index';+import type { McpToolDeps } from './tools/shared';const SERVER_NAME = 'OpenPanel';const SERVER_VERSION = '1.0.0';/**- * Create a fully configured McpServer instance for a given auth context.+ * Create a fully configured McpServer for one authenticated request.*- * Each authenticated session gets its own server instance with tools- * pre-bound to the session's project/organization context.+ * The API owns every connection (ADR-022 R6/R15, Carl's ruling): the server+ * is bootstrapped from the `deps` `mcp.routes.ts` already holds, and each+ * tool handler CLOSES OVER them — the SDK's tool-handler signature has no+ * context parameter, which is a closure problem, not a context problem.*/-export function createMcpServer(context: McpAuthContext): McpServer {+export function createMcpServer(tools: McpToolDeps): McpServer {const server = new McpServer({name: SERVER_NAME,@@ -24,7 +26,7 @@ export function createMcpServer(context: McpAuthContext): McpServer {});- registerAllTools(server, context);+ registerAllTools(server, tools);return server;}diff --git a/packages/core/src/modules/mcp/src/tools/analytics/active-users.ts b/packages/core/src/modules/mcp/src/tools/analytics/active-users.tsindex 9737abca2..343d2ea70 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/active-users.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/active-users.ts@@ -3,9 +3,9 @@ import { z } from 'zod';import {getRetentionSeries,getRollingActiveUsers,-} from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+} from '../../../../chart/retention.service';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,table,@@ -30,7 +30,7 @@ function mostRecent<T>(rows: T[], take: number): T[] {export function registerActiveUserTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_rolling_active_users',@@ -46,10 +46,10 @@ export function registerActiveUserTools(limit: zLimit(DEFAULT_DAILY_POINTS, MAX_DAILY_POINTS),},async ({ projectId: inputProjectId, days, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = limit ?? DEFAULT_DAILY_POINTS;- const data = await getRollingActiveUsers({ projectId, days });+ const data = await getRollingActiveUsers(deps, { projectId, days });const recent = mostRecent(data, take);return {window_days: days,@@ -84,10 +84,10 @@ export function registerActiveUserTools(limit: zLimit(DEFAULT_WEEKLY_POINTS, MAX_WEEKLY_POINTS),},async ({ projectId: inputProjectId, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = limit ?? DEFAULT_WEEKLY_POINTS;- const data = await getRetentionSeries({ projectId });+ const data = await getRetentionSeries(deps, { projectId });const recent = mostRecent(data, take);return {...(data.length > recent.lengthdiff --git a/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.tsindex 1bb5102d6..42c15d30e 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts@@ -1,30 +1,75 @@-import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ mock,+} from 'bun:test';+import type { ServiceDeps } from '../../../../../services';+import type { McpToolDeps } from '../shared';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).-// The retention/project loaders both resolve through this same specifier now-// (M9-CLEANUP-001) — one mock.module call, not two, or the second replaces-// the whole module and drops the first override.-const actualCore = await import('@openpanel/core');-mock.module('@openpanel/core', () => ({- ...actualCore,+// Mocked at the specifier the source imports resolve to — a whole-barrel+// replacement would drop every other export those modules carry for any+// other file sharing this process (bun:test only isolates modules per file+// under `--isolate`; see AGENTS.md). Restored in `afterAll` from a+// plain-object snapshot taken BEFORE the first `mock.module` call: restoring+// via the live `await import(...)` binding is a no-op once mocked.+const actualRetention = await import('../../../../chart/retention.service');+const realRetention = { ...actualRetention };+mock.module('../../../../chart/retention.service', () => ({+ ...realRetention,getRetentionLastSeenSeries: mockGetRetentionLastSeenSeries,+}));++const actualProjectService = await import(+ '../../../../project/project.service'+);+const realProjectService = { ...actualProjectService };+mock.module('../../../../project/project.service', () => ({+ ...realProjectService,resolveClientProjectId: mock(- ({ clientProjectId }: { clientProjectId: string }) =>+ (_deps: unknown, { clientProjectId }: { clientProjectId: string }) =>Promise.resolve(clientProjectId)),}));+afterAll(() => {+ mock.module('../../../../chart/retention.service', () => realRetention);+ mock.module('../../../../project/project.service', () => realProjectService);+});+let registerEngagementTools: typeof import('./engagement').registerEngagementTools;beforeAll(async () => {({ registerEngagementTools } = await import('./engagement'));});+const noopLogger = {+ fatal: () => {+ // no-op+ },+ error: () => {+ // no-op+ },+ warn: () => {+ // no-op+ },+ info: () => {+ // no-op+ },+ debug: () => {+ // no-op+ },+ trace: () => {+ // no-op+ },+ child: () => noopLogger,+};+// 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() {@@ -53,6 +98,14 @@ const READ_CTX = {clientType: 'read' as const,};+/** What `createMcpServer` hands every tool at runtime. */+const TOOLS: McpToolDeps = {+ context: READ_CTX,+ dbJsonNull: null,+ deps: { logger: noopLogger } as unknown as ServiceDeps,+ services: {} as McpToolDeps['services'],+};+beforeEach(() => {mockGetRetentionLastSeenSeries.mockReset();});@@ -71,7 +124,7 @@ describe('get_user_last_seen_distribution — bucketing', () => {]);const server = makeServer() as any;- registerEngagementTools(server, READ_CTX);+ registerEngagementTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,})) as any;@@ -89,7 +142,7 @@ describe('get_user_last_seen_distribution — bucketing', () => {mockGetRetentionLastSeenSeries.mockResolvedValue([]);const server = makeServer() as any;- registerEngagementTools(server, READ_CTX);+ registerEngagementTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,})) as any;@@ -104,7 +157,7 @@ describe('get_user_last_seen_distribution — bucketing', () => {mockGetRetentionLastSeenSeries.mockResolvedValue([{ days: 1, users: 5 }]);const server = makeServer() as any;- registerEngagementTools(server, READ_CTX);+ registerEngagementTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,})) as any;@@ -123,7 +176,7 @@ describe('get_user_last_seen_distribution — bucketing', () => {]);const server = makeServer() as any;- registerEngagementTools(server, READ_CTX);+ registerEngagementTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,includeDistribution: true,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts b/packages/core/src/modules/mcp/src/tools/analytics/engagement.tsindex a5f14a001..2abc16609 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getRetentionLastSeenSeries } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getRetentionLastSeenSeries } from '../../../../chart/retention.service';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,table,@@ -14,7 +14,7 @@ const MAX_DISTRIBUTION_ROWS = 200;export function registerEngagementTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_user_last_seen_distribution',@@ -30,9 +30,9 @@ export function registerEngagementTools(),},async ({ projectId: inputProjectId, includeDistribution }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const raw = await getRetentionLastSeenSeries({ projectId });+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const raw = await getRetentionLastSeenSeries(deps, { projectId });// Bucket into meaningful segments for easier readinglet active_0_7 = 0;diff --git a/packages/core/src/modules/mcp/src/tools/analytics/event-names.ts b/packages/core/src/modules/mcp/src/tools/analytics/event-names.tsindex 5c2b88e1f..6e8366f20 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/event-names.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/event-names.ts@@ -1,7 +1,7 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import { getTopEventNames } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getTopEventNames } from '../../../../event/event.service';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,withErrorHandling,@@ -9,7 +9,7 @@ import {export function registerEventNameTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('list_event_names',@@ -18,9 +18,9 @@ export function registerEventNameTools(projectId: projectIdSchema(context),},async ({ projectId: inputProjectId }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const names = await getTopEventNames(projectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const names = await getTopEventNames(deps, projectId);return { event_names: names };}));diff --git a/packages/core/src/modules/mcp/src/tools/analytics/events.ts b/packages/core/src/modules/mcp/src/tools/analytics/events.tsindex d2a29c1e5..436e4016c 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/events.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/events.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { queryEventsCore } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { queryEventsCore } from '../../../../event/event.service';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,table,@@ -15,7 +15,10 @@ 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) {+export function registerEventTools(+ server: McpServer,+ { context, deps }: McpToolDeps+) {server.tool('query_events',`Query raw analytics events with optional filters. Returns individual event records as a columnar table. Defaults to the last 30 days and the ${DEFAULT_EVENT_LIMIT} most relevant events, with a commonly-useful field set — pass \`fields\` to add columns like origin, city, or sdk_name.`,@@ -72,10 +75,10 @@ export function registerEventTools(server: McpServer, context: McpAuthContext) {limit: zLimit(DEFAULT_EVENT_LIMIT, MAX_EVENT_LIMIT),},async ({ projectId: inputProjectId, fields, ...input }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = input.limit ?? DEFAULT_EVENT_LIMIT;- const events = await queryEventsCore({+ const events = await queryEventsCore(deps, {...input,projectId,limit: take + 1,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/funnel.ts b/packages/core/src/modules/mcp/src/tools/analytics/funnel.tsindex 7b71040f5..cac2eb6dc 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/funnel.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/funnel.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getFunnelCore } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getFunnelCore } from '../../../../chart/funnel.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -12,7 +12,7 @@ import {export function registerFunnelTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_funnel',@@ -52,10 +52,10 @@ export function registerFunnelTools(windowHours,groupBy,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);- return getFunnelCore({+ return getFunnelCore(deps, {projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/groups.ts b/packages/core/src/modules/mcp/src/tools/analytics/groups.tsindex edb21bc3f..3623ed00e 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/groups.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/groups.ts@@ -5,9 +5,9 @@ import {getGroupList,getGroupMemberProfiles,getGroupTypes,-} from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+} from '../../../../group/group.service';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,table,@@ -35,7 +35,10 @@ const MEMBER_COLUMNS = ['lastSeenAt',] as const;-export function registerGroupTools(server: McpServer, context: McpAuthContext) {+export function registerGroupTools(+ server: McpServer,+ { context, deps }: McpToolDeps+) {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.',@@ -43,9 +46,9 @@ export function registerGroupTools(server: McpServer, context: McpAuthContext) {projectId: projectIdSchema(context),},async ({ projectId: inputProjectId }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const types = await getGroupTypes(projectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const types = await getGroupTypes(deps, projectId);return { types };}));@@ -68,10 +71,10 @@ export function registerGroupTools(server: McpServer, context: McpAuthContext) {limit: zLimit(DEFAULT_GROUP_LIMIT, MAX_GROUP_LIMIT),},async ({ projectId: inputProjectId, type, search, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = limit ?? DEFAULT_GROUP_LIMIT;- const groups = await getGroupList({+ const groups = await getGroupList(deps, {projectId,type,search,@@ -95,12 +98,12 @@ export function registerGroupTools(server: McpServer, context: McpAuthContext) {memberLimit: zLimit(DEFAULT_MEMBER_LIMIT, MAX_MEMBER_LIMIT),},async ({ projectId: inputProjectId, groupId, memberLimit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = memberLimit ?? DEFAULT_MEMBER_LIMIT;const [group, members] = await Promise.all([- getGroupById(groupId, projectId),- getGroupMemberProfiles({+ getGroupById(deps, groupId, projectId),+ getGroupMemberProfiles(deps, {projectId,groupId,take,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/overview.ts b/packages/core/src/modules/mcp/src/tools/analytics/overview.tsindex bb4eedd07..8d9e60664 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/overview.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/overview.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getAnalyticsOverviewCore } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getAnalyticsOverviewCore } from '../../../../overview/overview.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -86,7 +86,7 @@ function fitInterval(export function registerOverviewTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_analytics_overview',@@ -114,12 +114,12 @@ export function registerOverviewTools(interval,includeSeries,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const fitted = fitInterval(interval ?? 'day', startDate, endDate);- const result = await getAnalyticsOverviewCore({+ const result = await getAnalyticsOverviewCore(deps, {projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.tsindex 15121e32d..38dbad5fd 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts@@ -1,30 +1,75 @@-import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ mock,+} from 'bun:test';+import type { ServiceDeps } from '../../../../../services';+import type { McpToolDeps } from '../shared';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).-// The pages/project loaders both resolve through this same specifier now-// (M9-CLEANUP-001) — one mock.module call, not two, or the second replaces-// the whole module and drops the first override.-const actualCore = await import('@openpanel/core');-mock.module('@openpanel/core', () => ({- ...actualCore,+// Mocked at the specifier the source imports resolve to — a whole-barrel+// replacement would drop every other export those modules carry for any+// other file sharing this process (bun:test only isolates modules per file+// under `--isolate`; see AGENTS.md). Restored in `afterAll` from a+// plain-object snapshot taken BEFORE the first `mock.module` call: restoring+// via the live `await import(...)` binding is a no-op once mocked.+const actualPagesService = await import('../../../../overview/pages.service');+const realPagesService = { ...actualPagesService };+mock.module('../../../../overview/pages.service', () => ({+ ...realPagesService,getPageConversionsCore: mockGetPageConversionsCore,+}));++const actualProjectService = await import(+ '../../../../project/project.service'+);+const realProjectService = { ...actualProjectService };+mock.module('../../../../project/project.service', () => ({+ ...realProjectService,resolveClientProjectId: mock(- ({ clientProjectId }: { clientProjectId: string }) =>+ (_deps: unknown, { clientProjectId }: { clientProjectId: string }) =>Promise.resolve(clientProjectId)),}));+afterAll(() => {+ mock.module('../../../../overview/pages.service', () => realPagesService);+ mock.module('../../../../project/project.service', () => realProjectService);+});+let registerPageConversionTools: typeof import('./page-conversions').registerPageConversionTools;beforeAll(async () => {({ registerPageConversionTools } = await import('./page-conversions'));});+const noopLogger = {+ fatal: () => {+ // no-op+ },+ error: () => {+ // no-op+ },+ warn: () => {+ // no-op+ },+ info: () => {+ // no-op+ },+ debug: () => {+ // no-op+ },+ trace: () => {+ // no-op+ },+ child: () => noopLogger,+};+function makeServer() {let handler: ((input: unknown) => Promise<unknown>) | null = null;return {@@ -51,6 +96,14 @@ const READ_CTX = {clientType: 'read' as const,};+/** What `createMcpServer` hands every tool at runtime. */+const TOOLS: McpToolDeps = {+ context: READ_CTX,+ dbJsonNull: null,+ deps: { logger: noopLogger } as unknown as ServiceDeps,+ services: {} as McpToolDeps['services'],+};+/** Re-hydrate the columnar table the tool returns into row objects. */function rowsOf(result: { columns: string[]; rows: unknown[][] }): any[] {return result.rows.map((row) =>@@ -78,7 +131,7 @@ describe('get_page_conversions — output structure', () => {mockGetPageConversionsCore.mockResolvedValue([makePage()]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'sign_up',@@ -98,7 +151,7 @@ describe('get_page_conversions — output structure', () => {mockGetPageConversionsCore.mockResolvedValue([makePage()]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'purchase',@@ -114,7 +167,7 @@ describe('get_page_conversions — output structure', () => {mockGetPageConversionsCore.mockResolvedValue([]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'sign_up',@@ -131,13 +184,14 @@ describe('get_page_conversions — arguments forwarding', () => {mockGetPageConversionsCore.mockResolvedValue([]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'trial_started',});expect(mockGetPageConversionsCore).toHaveBeenCalledWith(+ expect.any(Object),expect.objectContaining({ conversionEvent: 'trial_started' }));});@@ -146,13 +200,14 @@ describe('get_page_conversions — arguments forwarding', () => {mockGetPageConversionsCore.mockResolvedValue([]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'sign_up',});expect(mockGetPageConversionsCore).toHaveBeenCalledWith(+ expect.any(Object),expect.objectContaining({ windowHours: 24 }));});@@ -161,7 +216,7 @@ describe('get_page_conversions — arguments forwarding', () => {mockGetPageConversionsCore.mockResolvedValue([]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'sign_up',@@ -169,6 +224,7 @@ describe('get_page_conversions — arguments forwarding', () => {});expect(mockGetPageConversionsCore).toHaveBeenCalledWith(+ expect.any(Object),expect.objectContaining({ windowHours: 168 }));const result = (await server.invoke({@@ -184,13 +240,14 @@ describe('get_page_conversions — arguments forwarding', () => {mockGetPageConversionsCore.mockResolvedValue([]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'sign_up',});expect(mockGetPageConversionsCore).toHaveBeenCalledWith(+ expect.any(Object),expect.objectContaining({ limit: 26 }));});@@ -199,13 +256,14 @@ describe('get_page_conversions — arguments forwarding', () => {mockGetPageConversionsCore.mockResolvedValue([]);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'sign_up',});expect(mockGetPageConversionsCore).toHaveBeenCalledWith(+ expect.any(Object),expect.objectContaining({ projectId: 'proj-1' }));});@@ -219,7 +277,7 @@ describe('get_page_conversions — total_pages count', () => {mockGetPageConversionsCore.mockResolvedValue(pages);const server = makeServer() as any;- registerPageConversionTools(server, READ_CTX);+ registerPageConversionTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,conversionEvent: 'sign_up',diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.tsindex 33d46ad13..440813d43 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getPageConversionsCore } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getPageConversionsCore } from '../../../../overview/pages.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -17,7 +17,7 @@ const MAX_CONVERSION_LIMIT = 500;export function registerPageConversionTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_page_conversions',@@ -49,11 +49,11 @@ export function registerPageConversionTools(windowHours,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const take = limit ?? DEFAULT_CONVERSION_LIMIT;- const pages = await getPageConversionsCore({+ const pages = await getPageConversionsCore(deps, {projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.tsindex 1ba88cc41..36bde3936 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts@@ -7,42 +7,51 @@ import {it,mock,} from 'bun:test';+import type { ServiceDeps } from '../../../../../services';+import type { McpToolDeps } from '../shared';const mockGetTopPages = mock();const mockGetSettingsForProject = mock(() =>Promise.resolve({ timezone: 'UTC' }));-// 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).-// The organization/project loaders resolve through this same specifier-// (M9-CLEANUP-001) — one mock.module call, not two, or each later call-// replaces the whole module and drops the earlier overrides.-const actualCore = await import('@openpanel/core');-mock.module('@openpanel/core', () => ({- ...actualCore,+// M15-003: the tool reads the pages service off the `services` graph handed+// in with `deps`, so `getTopPages` is a plain stub on TOOLS below rather than+// a module mock. Only the two sibling module functions this file drives are+// still replaced, each at the specifier the source imports resolve to — a+// whole-barrel replacement would drop every other export those modules carry+// for any other file sharing this process (bun:test only isolates modules per+// file under `--isolate`; see AGENTS.md) — and each is restored in `afterAll`+// from a plain-object snapshot taken BEFORE the first `mock.module` call,+// since restoring via the live `await import(...)` binding is a no-op once+// mocked.+const actualOrganizationService = await import(+ '../../../../organization/organization.service'+);+const realOrganizationService = { ...actualOrganizationService };+mock.module('../../../../organization/organization.service', () => ({+ ...realOrganizationService,getSettingsForProject: mockGetSettingsForProject,+}));++const actualProjectService = await import(+ '../../../../project/project.service'+);+const realProjectService = { ...actualProjectService };+mock.module('../../../../project/project.service', () => ({+ ...realProjectService,resolveClientProjectId: mock(- ({ clientProjectId }: { clientProjectId: string }) =>+ (_deps: unknown, { clientProjectId }: { clientProjectId: string }) =>Promise.resolve(clientProjectId)),}));-// M10-005: `PagesService` is no longer a class the tool constructs — the tool-// resolves the pages service through `../shared`'s one compat hop, so that is-// what this file stubs. Spread-actual: every other helper in `../shared` is-// live for whatever else shares this process.-const actualShared = await import('../shared');-mock.module('../shared', () => ({- ...actualShared,- loadCompatPagesService: async () => ({ getTopPages: mockGetTopPages }),-}));-afterAll(() => {- mock.module('../shared', () => actualShared);- mock.module('@openpanel/core', () => actualCore);+ mock.module(+ '../../../../organization/organization.service',+ () => realOrganizationService+ );+ mock.module('../../../../project/project.service', () => realProjectService);});let registerPagePerformanceTools: typeof import('./page-performance').registerPagePerformanceTools;@@ -71,12 +80,44 @@ function makeServer() {};}+const noopLogger = {+ fatal: () => {+ // no-op+ },+ error: () => {+ // no-op+ },+ warn: () => {+ // no-op+ },+ info: () => {+ // no-op+ },+ debug: () => {+ // no-op+ },+ trace: () => {+ // no-op+ },+ child: () => noopLogger,+};+const READ_CTX = {projectId: 'proj-1',organizationId: 'org-1',clientType: 'read' as const,};+/** What `createMcpServer` hands every tool at runtime. */+const TOOLS: McpToolDeps = {+ context: READ_CTX,+ dbJsonNull: null,+ deps: { logger: noopLogger } as unknown as ServiceDeps,+ services: {+ pages: { getTopPages: mockGetTopPages },+ } as unknown as McpToolDeps['services'],+};+/** Re-hydrate the columnar table the tool returns into row objects. */function rowsOf(result: { columns: string[]; rows: unknown[][] }): any[] {return result.rows.map((row) =>@@ -107,7 +148,7 @@ describe('get_page_performance — seo thresholds', () => {mockGetTopPages.mockResolvedValue([makePage({ bounce_rate: 80 })]);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,})) as any;@@ -126,7 +167,7 @@ describe('get_page_performance — seo thresholds', () => {]);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,})) as any;@@ -152,7 +193,7 @@ describe('get_page_performance — sorting', () => {mockGetTopPages.mockResolvedValue([...pages]);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,})) as any;@@ -166,7 +207,7 @@ describe('get_page_performance — sorting', () => {mockGetTopPages.mockResolvedValue([...pages]);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,sortBy: 'bounce_rate',@@ -182,7 +223,7 @@ describe('get_page_performance — sorting', () => {mockGetTopPages.mockResolvedValue([...pages]);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,sortBy: 'bounce_rate',@@ -198,7 +239,7 @@ describe('get_page_performance — sorting', () => {mockGetTopPages.mockResolvedValue([...pages]);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,limit: 2,@@ -220,7 +261,7 @@ describe('get_page_performance — metadata', () => {mockGetTopPages.mockResolvedValue(manyPages);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,limit: 5,@@ -241,7 +282,7 @@ describe('get_page_performance — metadata', () => {mockGetTopPages.mockResolvedValue([]);const server = makeServer() as any;- registerPagePerformanceTools(server, READ_CTX);+ registerPagePerformanceTools(server, TOOLS);const result = (await server.invoke({projectId: READ_CTX.projectId,})) as any;diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.tsindex 40e8aa605..880b6142d 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts@@ -1,9 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getSettingsForProject } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getSettingsForProject } from '../../../../organization/organization.service';import {- loadCompatPagesService,+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -30,7 +29,7 @@ const SEO_THRESHOLDS = {export function registerPagePerformanceTools(server: McpServer,- context: McpAuthContext+ { context, deps, services }: McpToolDeps) {server.tool('get_page_performance',@@ -63,18 +62,11 @@ export function registerPagePerformanceTools(sortOrder,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);- const { timezone } = await getSettingsForProject(projectId);- // Resolved per call, not once at module scope: a module-scope binding- // would freeze 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 = await loadCompatPagesService();-- const pages = await pagesService.getTopPages({+ const { timezone } = await getSettingsForProject(deps, projectId);+ const pages = await services.pages.getTopPages({projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/pages.ts b/packages/core/src/modules/mcp/src/tools/analytics/pages.tsindex dcaa86805..625970bed 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/pages.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/pages.ts@@ -3,9 +3,9 @@ import { z } from 'zod';import {getEntryExitPagesCore,getTopPagesCore,-} from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+} from '../../../../overview/pages.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -49,7 +49,10 @@ function pageTable(rows: PageRow[], limit: number) {});}-export function registerPageTools(server: McpServer, context: McpAuthContext) {+export function registerPageTools(+ server: McpServer,+ { context, deps }: McpToolDeps+) {server.tool('get_top_pages',`Get the most visited pages ranked by sessions, with pageview counts. Defaults to the top ${DEFAULT_PAGE_LIMIT} pages.`,@@ -59,11 +62,11 @@ export function registerPageTools(server: McpServer, context: McpAuthContext) {limit: zLimit(DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT),},async ({ projectId: inputProjectId, startDate: sd, endDate: ed, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const take = limit ?? DEFAULT_PAGE_LIMIT;- const rows = await getTopPagesCore({+ const rows = await getTopPagesCore(deps, {projectId,startDate,endDate,@@ -93,11 +96,11 @@ export function registerPageTools(server: McpServer, context: McpAuthContext) {mode,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const take = limit ?? DEFAULT_PAGE_LIMIT;- const rows = await getEntryExitPagesCore({+ const rows = await getEntryExitPagesCore(deps, {projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/profile-metrics.ts b/packages/core/src/modules/mcp/src/tools/analytics/profile-metrics.tsindex 1e2f039dc..0b6fb35a3 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/profile-metrics.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/profile-metrics.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getProfileMetrics } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getProfileMetrics } from '../../../../profile/profile.service';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,withErrorHandling,@@ -10,7 +10,7 @@ import {export function registerProfileMetricTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_profile_metrics',@@ -20,9 +20,9 @@ export function registerProfileMetricTools(profileId: z.string().describe('The profile ID to get metrics for'),},async ({ projectId: inputProjectId, profileId }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const raw = await getProfileMetrics(profileId, projectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const raw = await getProfileMetrics(deps, profileId, projectId);if (!raw) {return { error: 'Profile not found or has no events', profileId };}diff --git a/packages/core/src/modules/mcp/src/tools/analytics/profiles.ts b/packages/core/src/modules/mcp/src/tools/analytics/profiles.tsindex d78fe1648..a8d6399ab 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/profiles.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/profiles.ts@@ -4,10 +4,10 @@ import {findProfilesCore,getProfileSessionsCore,getProfileWithEvents,-} from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+} from '../../../../profile/profile.service';import { dashboardBaseUrl, profileUrl } from '../dashboard-links';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,table,@@ -35,7 +35,7 @@ const PROFILE_COLUMNS = [export function registerProfileTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('find_profiles',@@ -89,10 +89,10 @@ export function registerProfileTools(limit: zLimit(DEFAULT_PROFILE_LIMIT, MAX_PROFILE_LIMIT),},async ({ projectId: inputProjectId, ...input }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = input.limit ?? DEFAULT_PROFILE_LIMIT;- const profiles = await findProfilesCore({+ const profiles = await findProfilesCore(deps, {...input,projectId,limit: take + 1,@@ -120,10 +120,15 @@ export function registerProfileTools(eventLimit: zLimit(DEFAULT_EVENT_LIMIT, 100),},async ({ projectId: inputProjectId, profileId, eventLimit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = eventLimit ?? DEFAULT_EVENT_LIMIT;- const result = await getProfileWithEvents(projectId, profileId, take);+ const result = await getProfileWithEvents(+ deps,+ projectId,+ profileId,+ take+ );if (!result.profile) {return { error: 'Profile not found', profileId };}@@ -153,10 +158,11 @@ export function registerProfileTools(limit: zLimit(DEFAULT_SESSION_LIMIT, 100),},async ({ projectId: inputProjectId, profileId, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = limit ?? DEFAULT_SESSION_LIMIT;const sessions = await getProfileSessionsCore(+ deps,projectId,profileId,take + 1diff --git a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts b/packages/core/src/modules/mcp/src/tools/analytics/property-values.tsindex f48a2cca7..56062ee76 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts@@ -4,9 +4,8 @@ import { z } from 'zod';import { chQuery } from '../../../../../shared/ch-query';import { TABLE_NAMES } from '../../../../../shared/ch-tables';import { EVENT_COLUMNS } from '../../../../event/event.service';-import type { McpAuthContext } from '../../auth';import {- loadCompatChScope,+ type McpToolDeps,projectIdSchema,resolveProjectId,withErrorHandling,@@ -70,7 +69,7 @@ function compactPropertyKeys(export function registerPropertyValueTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('list_event_properties',@@ -86,9 +85,8 @@ export function registerPropertyValueTools(limit: zLimit(DEFAULT_PROPERTY_LIMIT, MAX_PROPERTY_LIMIT),},async ({ projectId: inputProjectId, eventName, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const deps = await loadCompatChScope();+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);// GROUP BY rather than DISTINCT so the epv_keys projection can serve// this (a multi-column DISTINCT cannot be matched against an// aggregating projection); `name` tie-breaks the ORDER BY so the@@ -136,9 +134,8 @@ export function registerPropertyValueTools(limit: zLimit(DEFAULT_VALUE_LIMIT, MAX_VALUE_LIMIT),},async ({ projectId: inputProjectId, eventName, propertyKey, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const deps = await loadCompatChScope();+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = limit ?? DEFAULT_VALUE_LIMIT;// The MV holds one row per (property, value, day), so the same value// recurs across the window — dedupe before counting against the limit,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts b/packages/core/src/modules/mcp/src/tools/analytics/reports.tsindex 39cd3a86b..01e3a3aee 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts@@ -1,18 +1,20 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';+import type { ServiceDeps } from '../../../../../services';import { getChartStartEndDate } from '../../../../../shared/date';import {- AggregateChartEngine,- ChartEngine,- getFunnel,+ executeAggregateChart,+ executeChart,+} from '../../../../chart/chart.service';+import { getFunnel } from '../../../../chart/funnel.service';+import { getSettingsForProject } from '../../../../organization/organization.service';+import {getReportById,getReportsByDashboardId,- getSettingsForProject,-} from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+} from '../../../../report/report.service';import { dashboardBaseUrl } from '../dashboard-links';import {- loadCompatDb,+ type McpToolDeps,projectIdSchema,resolveProjectId,table,@@ -146,7 +148,7 @@ function shapeChart(export function registerReportTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('list_dashboards',@@ -155,9 +157,9 @@ export function registerReportTools(projectId: projectIdSchema(context),},async ({ projectId: inputProjectId }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const db = await loadCompatDb();+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const db = deps.db;const dashboards = await db.dashboard.findMany({where: { projectId },orderBy: { createdAt: 'desc' },@@ -178,9 +180,9 @@ export function registerReportTools(dashboardId: z.string().describe('The dashboard ID to list reports for'),},async ({ projectId: inputProjectId, dashboardId }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const reports = await getReportsByDashboardId(dashboardId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const reports = await getReportsByDashboardId(deps, dashboardId);if (reports.some((r) => r.projectId !== projectId)) {throw new Error('Dashboard does not belong to this project');}@@ -242,9 +244,9 @@ export function registerReportTools(),},async ({ projectId: inputProjectId, reportId, seriesLimit, plotSeries }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- const result = await runReport({+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const result = await runReport(deps, {organizationId: context.organizationId,projectId,reportId,@@ -293,11 +295,14 @@ export function registerReportTools(* 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;- projectId: string;- reportId: string;-}): Promise<+export async function runReport(+ deps: ServiceDeps,+ input: {+ organizationId: string;+ projectId: string;+ reportId: string;+ }+): Promise<| { error: string; reportId: string }| {id: string;@@ -311,7 +316,7 @@ export async function runReport(input: {data: unknown;}> {- const report = await getReportById(input.reportId);+ const report = await getReportById(deps, input.reportId);if (!report) {return { error: 'Report not found', reportId: input.reportId };@@ -324,7 +329,7 @@ export async function runReport(input: {};}- const { timezone } = await getSettingsForProject(input.projectId);+ const { timezone } = await getSettingsForProject(deps, input.projectId);const { startDate, endDate } = getChartStartEndDate(report, timezone);const chartInput = { ...report, startDate, endDate, timezone };@@ -344,30 +349,33 @@ export async function runReport(input: {};if (report.chartType === 'funnel') {- return { ...meta, data: await getFunnel(chartInput) };+ return { ...meta, data: await getFunnel(deps, chartInput) };}if (report.chartType === 'metric') {- return { ...meta, data: await AggregateChartEngine.execute(chartInput) };+ return { ...meta, data: await executeAggregateChart(deps, chartInput) };}- return { ...meta, data: await ChartEngine.execute(chartInput) };+ return { ...meta, data: await executeChart(deps, chartInput) };}/*** Execute an ad-hoc report config (no DB lookup — config is supplied directly).* Used by `generate_report` tool in chat.*/-export async function runReportFromConfig(input: {- organizationId: string;- projectId: string;- /** Full zReportInput shape, with required startDate/endDate */- config: {- chartType: string;- interval: string;- startDate: string;- endDate: string;- [key: string]: unknown;- };-}): Promise<{+export async function runReportFromConfig(+ deps: ServiceDeps,+ input: {+ organizationId: string;+ projectId: string;+ /** Full zReportInput shape, with required startDate/endDate */+ config: {+ chartType: string;+ interval: string;+ startDate: string;+ endDate: string;+ [key: string]: unknown;+ };+ }+): Promise<{chartType: string;interval: string;startDate: string;@@ -375,12 +383,12 @@ export async function runReportFromConfig(input: {report: typeof input.config & { projectId: string };data: unknown;}> {- const { timezone } = await getSettingsForProject(input.projectId);+ const { timezone } = await getSettingsForProject(deps, input.projectId);const chartInput = {...input.config,projectId: input.projectId,timezone,- } as unknown as Parameters<typeof ChartEngine.execute>[0];+ } as unknown as Parameters<typeof executeChart>[1];const meta = {chartType: input.config.chartType,@@ -393,11 +401,14 @@ export async function runReportFromConfig(input: {if (input.config.chartType === 'funnel') {return {...meta,- data: await getFunnel(chartInput as Parameters<typeof getFunnel>[0]),+ data: await getFunnel(+ deps,+ chartInput as Parameters<typeof getFunnel>[1]+ ),};}if (input.config.chartType === 'metric') {- return { ...meta, data: await AggregateChartEngine.execute(chartInput) };+ return { ...meta, data: await executeAggregateChart(deps, chartInput) };}- return { ...meta, data: await ChartEngine.execute(chartInput) };+ return { ...meta, data: await executeChart(deps, chartInput) };}diff --git a/packages/core/src/modules/mcp/src/tools/analytics/retention.ts b/packages/core/src/modules/mcp/src/tools/analytics/retention.tsindex 3356310b6..1c1409e6d 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/retention.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/retention.ts@@ -1,7 +1,7 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import { getRetentionCohortCore } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getRetentionCohortCore } from '../../../../chart/retention.service';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,withErrorHandling,@@ -9,7 +9,7 @@ import {export function registerRetentionTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_retention_cohort',@@ -18,9 +18,9 @@ export function registerRetentionTools(projectId: projectIdSchema(context),},async ({ projectId: inputProjectId }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);- return getRetentionCohortCore(projectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ return getRetentionCohortCore(deps, projectId);}));}diff --git a/packages/core/src/modules/mcp/src/tools/analytics/sessions.ts b/packages/core/src/modules/mcp/src/tools/analytics/sessions.tsindex f94d74b16..062a98288 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/sessions.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/sessions.ts@@ -1,9 +1,9 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { querySessionsCore } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { querySessionsCore } from '../../../../session/session.service';import { dashboardBaseUrl } from '../dashboard-links';import {+ type McpToolDeps,projectIdSchema,resolveProjectId,table,@@ -18,7 +18,7 @@ const MAX_SESSION_LIMIT = 100;export function registerSessionTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('query_sessions',@@ -56,10 +56,10 @@ export function registerSessionTools(limit: zLimit(DEFAULT_SESSION_LIMIT, MAX_SESSION_LIMIT),},async ({ projectId: inputProjectId, fields, ...input }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const take = input.limit ?? DEFAULT_SESSION_LIMIT;- const sessions = await querySessionsCore({+ const sessions = await querySessionsCore(deps, {...input,projectId,limit: take + 1,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/traffic.ts b/packages/core/src/modules/mcp/src/tools/analytics/traffic.tsindex b52d6276d..73e3c7461 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/traffic.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/traffic.ts@@ -1,9 +1,9 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getTrafficBreakdownCore } from '../../../../../v1-compat';import type { TrafficColumn } from '../../../../overview/overview.service';-import type { McpAuthContext } from '../../auth';+import { getTrafficBreakdownCore } from '../../../../overview/overview.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -58,7 +58,7 @@ function breakdownTable(rows: BreakdownRow[], limit: number, unit: string) {export function registerTrafficTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_top_referrers',@@ -89,10 +89,10 @@ export function registerTrafficTools(breakdown,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);- const rows = await getTrafficBreakdownCore({+ const rows = await getTrafficBreakdownCore(deps, {projectId,startDate,endDate,@@ -126,10 +126,10 @@ export function registerTrafficTools(breakdown,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);- const rows = await getTrafficBreakdownCore({+ const rows = await getTrafficBreakdownCore(deps, {projectId,startDate,endDate,@@ -165,10 +165,10 @@ export function registerTrafficTools(breakdown,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);- const rows = await getTrafficBreakdownCore({+ const rows = await getTrafficBreakdownCore(deps, {projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/user-flow.ts b/packages/core/src/modules/mcp/src/tools/analytics/user-flow.tsindex 5f208524e..46fc41ed1 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/user-flow.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/user-flow.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getUserFlowCore } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getUserFlowCore } from '../../../../chart/sankey.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -17,7 +17,7 @@ const MAX_FLOW_NODES = 500;export function registerUserFlowTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_user_flow',@@ -72,11 +72,11 @@ export function registerUserFlowTools(include,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const take = limit ?? DEFAULT_FLOW_NODES;- const flow = await getUserFlowCore({+ const flow = await getUserFlowCore(deps, {projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-links.ts b/packages/core/src/modules/mcp/src/tools/dashboard-links.tsindex ffb7c684f..4064c0949 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-links.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-links.ts@@ -1,7 +1,11 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import type { McpAuthContext } from '../auth';-import { projectIdSchema, resolveProjectId, withErrorHandling } from './shared';+import {+ type McpToolDeps,+ projectIdSchema,+ resolveProjectId,+ withErrorHandling,+} from './shared';export function dashboardBaseUrl() {return (@@ -29,7 +33,7 @@ export function sessionUrl(export function registerDashboardLinkTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('get_dashboard_urls',@@ -60,8 +64,8 @@ export function registerDashboardLinkTools(dashboardId,reportId,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const base = `${dashboardBaseUrl()}/${context.organizationId}/${projectId}`;const urls: Record<string, string> = {diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.tsindex 5995c4f76..2b82a8f96 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts@@ -31,68 +31,96 @@ const mockDb = {},};+const noopLogger = {+ fatal: () => {+ // no-op+ },+ error: () => {+ // no-op+ },+ warn: () => {+ // no-op+ },+ info: () => {+ // no-op+ },+ debug: () => {+ // no-op+ },+ trace: () => {+ // no-op+ },+ child: () => noopLogger,+};+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,+// M15-003: Postgres arrives on `deps.db` (see TOOLS below), so the only+// module mocks left are the three sibling functions this file asserts calls+// against. Each is replaced at the specifier the source imports resolve to —+// a whole-barrel replacement would drop every other export those modules+// carry for any other file sharing this process (bun:test only isolates+// modules per file under `--isolate`; see AGENTS.md) — and each is restored+// in `afterAll` from a plain-object snapshot taken BEFORE the first+// `mock.module` call, since restoring via the live `await import(...)`+// binding is a no-op once mocked.+const actualDashboardService = await import(+ '../../../dashboard/dashboard.service'+);+const realDashboardService = { ...actualDashboardService };+mock.module('../../../dashboard/dashboard.service', () => ({+ ...realDashboardService,+ getDashboardById: mockGetDashboardById,}));-// The dashboard/project/id loaders all resolve through this same-// @openpanel/core specifier now (M9-CLEANUP-001) — one mock.module call, not-// three, or each later call replaces the whole module and drops the earlier-// overrides.-const actualCore = await import('@openpanel/core');-mock.module('@openpanel/core', () => ({- ...actualCore,- getDashboardById: mockGetDashboardById,+const actualProjectService = await import('../../../project/project.service');+const realProjectService = { ...actualProjectService };+mock.module('../../../project/project.service', () => ({+ ...realProjectService,getProjectById: mockGetProjectById,resolveClientProjectId: mock(- ({- clientProjectId,- inputProjectId,- }: {- clientProjectId: string | null;- inputProjectId?: string;- }) => Promise.resolve(clientProjectId ?? inputProjectId)+ (+ _deps: unknown,+ {+ clientProjectId,+ inputProjectId,+ }: {+ clientProjectId: string | null;+ inputProjectId?: string;+ }+ ) => Promise.resolve(clientProjectId ?? inputProjectId)),+}));++const actualSlugId = await import('../../../../shared/slug-id');+const realSlugId = { ...actualSlugId };+mock.module('../../../../shared/slug-id', () => ({+ ...realSlugId,getId: mockGetId,}));let registerDashboardManagementTools: typeof import('./dashboard-management').registerDashboardManagementTools;beforeAll(async () => {- // `loadCompatDb` (./shared) reaches Postgres through v1-compat.ts's- // memoized fallback singleton — a process-lifetime cache once resolved,- // so an earlier test file's `bun test` (no `--isolate`) run can have- // already resolved it against a DIFFERENT `@openpanel/db/src/prisma-client`- // mock (or none at all). Reset it so this file's own mock above is what- // gets picked up.- const { resetV1CompatServicesForTests } = await import(- '../../../../v1-compat'- );- resetV1CompatServicesForTests();({ registerDashboardManagementTools } = await import('./dashboard-management'));});-afterAll(async () => {- const { resetV1CompatServicesForTests } = await import(- '../../../../v1-compat'+afterAll(() => {+ mock.module(+ '../../../dashboard/dashboard.service',+ () => realDashboardService);- resetV1CompatServicesForTests();+ mock.module('../../../project/project.service', () => realProjectService);+ mock.module('../../../../shared/slug-id', () => realSlugId);});+import type { ServiceDeps } from '../../../../services';import type { McpAuthContext } from '../auth';+import type { McpToolDeps } from './shared';type Handler = (input: any) => Promise<any>;@@ -230,7 +258,13 @@ beforeEach(() => {function register(context: McpAuthContext = ROOT_CONTEXT) {const server = makeServer();- registerDashboardManagementTools(server as any, context);+ const tools: McpToolDeps = {+ context,+ dbJsonNull: { kind: 'DbNull' },+ deps: { db: mockDb, logger: noopLogger } as unknown as ServiceDeps,+ services: {} as McpToolDeps['services'],+ };+ registerDashboardManagementTools(server as any, tools);return server;}@@ -322,6 +356,7 @@ describe('dashboard management project binding', () => {});expect(mockGetDashboardById).toHaveBeenCalledWith(+ expect.any(Object),'dashboard-1','project-1');diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.tsindex b6f82825d..31b84c3b6 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts@@ -1,13 +1,13 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';+import type { ServiceDeps } from '../../../../services';import { getId } from '../../../../shared/slug-id';-import { getDashboardById, getProjectById } from '../../../../v1-compat';+import { getDashboardById } from '../../../dashboard/dashboard.service';+import { getProjectById } from '../../../project/project.service';import { zReport } from '../../../report/report.constants';-import type { McpAuthContext } from '../auth';import { dashboardBaseUrl } from './dashboard-links';import {- loadCompatDb,- loadCompatPrisma,+ type McpToolDeps,projectIdSchema,resolveProjectId,withErrorHandling,@@ -143,7 +143,8 @@ function reportUrl(// `dbNull` is `Prisma.DbNull` (an explicit SQL NULL on a nullable Json// column), threaded in as `unknown` rather than importing `@openpanel/db`// here — same shape notification.service.ts's `isValidPayload` uses for the-// same sentinel. Callers resolve it via `loadCompatPrisma()` (./shared).+// same sentinel. It arrives on `McpToolDeps.dbJsonNull`, resolved once by+// `mcp.service.ts` when it builds the server (ADR-022 R6).function reportData(report: z.infer<typeof reportSchema>, dbNull: unknown) {return {name: report.name,@@ -165,8 +166,12 @@ function reportData(report: z.infer<typeof reportSchema>, dbNull: unknown) {};}-async function requireDashboard(projectId: string, dashboardId: string) {- const dashboard = await getDashboardById(dashboardId, projectId);+async function requireDashboard(+ deps: ServiceDeps,+ projectId: string,+ dashboardId: string+) {+ const dashboard = await getDashboardById(deps, dashboardId, projectId);if (!dashboard) {throw new Error('Dashboard not found');}@@ -174,7 +179,7 @@ async function requireDashboard(projectId: string, dashboardId: string) {}async function requireReport(- db: Awaited<ReturnType<typeof loadCompatDb>>,+ db: ServiceDeps['db'],projectId: string,reportId: string) {@@ -264,7 +269,7 @@ function canonicalReportConfig(report: {export function registerDashboardManagementTools(server: McpServer,- context: McpAuthContext+ { context, deps, dbJsonNull }: McpToolDeps) {server.tool('get_dashboard',@@ -274,10 +279,10 @@ export function registerDashboardManagementTools(dashboardId: z.string().describe('The dashboard ID to retrieve'),},async ({ projectId: inputProjectId, dashboardId }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const projectId = await resolveProjectId(context, inputProjectId);- const dashboard = await requireDashboard(projectId, dashboardId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const dashboard = await requireDashboard(deps, projectId, dashboardId);const reports = await db.report.findMany({where: { dashboardId, projectId },include: { layout: true },@@ -319,10 +324,10 @@ export function registerDashboardManagementTools(name: z.string().describe('The dashboard name'),},async ({ projectId: inputProjectId, name }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const projectId = await resolveProjectId(context, inputProjectId);- const project = await getProjectById(projectId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const project = await getProjectById(deps, projectId);if (!project) {throw new Error('Project not found');}@@ -357,10 +362,10 @@ export function registerDashboardManagementTools(name: z.string().describe('The new dashboard name'),},async ({ projectId: inputProjectId, dashboardId, name }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const projectId = await resolveProjectId(context, inputProjectId);- await requireDashboard(projectId, dashboardId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ await requireDashboard(deps, projectId, dashboardId);const dashboard = await db.dashboard.update({where: { id: dashboardId },data: { name },@@ -388,10 +393,10 @@ export function registerDashboardManagementTools(.describe('Delete all reports in the dashboard before deleting it'),},async ({ projectId: inputProjectId, dashboardId, forceDelete }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const projectId = await resolveProjectId(context, inputProjectId);- const dashboard = await requireDashboard(projectId, dashboardId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const dashboard = await requireDashboard(deps, projectId, dashboardId);try {await db.$transaction(async (transaction) => {@@ -461,16 +466,15 @@ export function registerDashboardManagementTools(report: reportSchema.describe('The saved report configuration'),},async ({ projectId: inputProjectId, dashboardId, report }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const { DbNull } = await loadCompatPrisma();- const projectId = await resolveProjectId(context, inputProjectId);- const dashboard = await requireDashboard(projectId, dashboardId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ const dashboard = await requireDashboard(deps, projectId, dashboardId);const created = await db.report.create({data: {projectId: dashboard.projectId,dashboardId,- ...reportData(report, DbNull),+ ...reportData(report, dbJsonNull),},});@@ -489,14 +493,13 @@ export function registerDashboardManagementTools(report: reportSchema.describe('The complete saved report configuration'),},async ({ projectId: inputProjectId, reportId, report }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const { DbNull } = await loadCompatPrisma();- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);await requireReport(db, projectId, reportId);const updated = await db.report.update({where: { id: reportId },- data: reportData(report, DbNull),+ data: reportData(report, dbJsonNull),});return {@@ -513,9 +516,9 @@ export function registerDashboardManagementTools(reportId: z.string().uuid().describe('The report ID to delete'),},async ({ projectId: inputProjectId, reportId }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);await requireReport(db, projectId, reportId);const deleted = await db.report.delete({ where: { id: reportId } });@@ -534,10 +537,9 @@ export function registerDashboardManagementTools(reportId: z.string().uuid().describe('The report ID to duplicate'),},async ({ projectId: inputProjectId, reportId }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const { DbNull } = await loadCompatPrisma();- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);const report = await requireReport(db, projectId, reportId);const duplicate = await db.report.create({data: {@@ -555,7 +557,7 @@ export function registerDashboardManagementTools(previous: report.previous,unit: report.unit,metric: report.metric,- options: report.options ?? DbNull,+ options: report.options ?? dbJsonNull,visibleSeries: report.visibleSeries,startDate: report.startDate,endDate: report.endDate,@@ -580,9 +582,9 @@ export function registerDashboardManagementTools(layout: layoutSchema.describe('The report grid layout'),},async ({ projectId: inputProjectId, reportId, layout }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);await requireReport(db, projectId, reportId);return db.reportLayout.upsert({where: { reportId },@@ -602,10 +604,10 @@ export function registerDashboardManagementTools(.describe('The dashboard whose layouts should reset'),},async ({ projectId: inputProjectId, dashboardId }) =>- withErrorHandling(async () => {- const db = await loadCompatDb();- const projectId = await resolveProjectId(context, inputProjectId);- await requireDashboard(projectId, dashboardId);+ withErrorHandling(deps, async () => {+ const db = deps.db;+ const projectId = await resolveProjectId(deps, context, inputProjectId);+ await requireDashboard(deps, projectId, dashboardId);const result = await db.reportLayout.deleteMany({where: {report: {diff --git a/packages/core/src/modules/mcp/src/tools/gsc/cannibalization.ts b/packages/core/src/modules/mcp/src/tools/gsc/cannibalization.tsindex 25536cca9..c23321e29 100644--- a/packages/core/src/modules/mcp/src/tools/gsc/cannibalization.ts+++ b/packages/core/src/modules/mcp/src/tools/gsc/cannibalization.ts@@ -1,7 +1,6 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import { getGscCannibalization } from '../../../../gsc/gsc.service';-import type { McpAuthContext } from '../../auth';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -31,7 +30,7 @@ const PAGE_COLUMNS = [export function registerGscCannibalizationTools(server: McpServer,- context: McpAuthContext+ { context, deps, services }: McpToolDeps) {server.tool('gsc_get_cannibalization',@@ -49,11 +48,15 @@ export function registerGscCannibalizationTools(pagesPerQuery,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const pageCap = pagesPerQuery ?? DEFAULT_PAGES_PER_QUERY;- const rows = await getGscCannibalization(projectId, startDate, endDate);+ const rows = await services.gsc.getCannibalization(+ projectId,+ startDate,+ endDate+ );// Positional tuples rather than page objects: the five keys are stated// once in `page_columns` instead of on every page of every query.diff --git a/packages/core/src/modules/mcp/src/tools/gsc/overview.ts b/packages/core/src/modules/mcp/src/tools/gsc/overview.tsindex 7d71111a6..ce9d79654 100644--- a/packages/core/src/modules/mcp/src/tools/gsc/overview.ts+++ b/packages/core/src/modules/mcp/src/tools/gsc/overview.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getGscOverview } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getGscOverview } from '../../../../gsc/gsc.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -16,7 +16,7 @@ const MAX_SERIES_POINTS = 180;export function registerGscOverviewTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('gsc_get_overview',@@ -44,10 +44,11 @@ export function registerGscOverviewTools(interval,includeSeries,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const data = await getGscOverview(+ deps,projectId,startDate,endDate,diff --git a/packages/core/src/modules/mcp/src/tools/gsc/pages.ts b/packages/core/src/modules/mcp/src/tools/gsc/pages.tsindex a722f3c6f..f3fb53e8f 100644--- a/packages/core/src/modules/mcp/src/tools/gsc/pages.ts+++ b/packages/core/src/modules/mcp/src/tools/gsc/pages.ts@@ -1,8 +1,8 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getGscPageDetails, getGscPages } from '../../../../../v1-compat';-import type { McpAuthContext } from '../../auth';+import { getGscPageDetails, getGscPages } from '../../../../gsc/gsc.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -25,7 +25,7 @@ const GSC_ADDITIVE = ['clicks', 'impressions'] as const;export function registerGscPageTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('gsc_get_top_pages',@@ -36,13 +36,14 @@ export function registerGscPageTools(limit: zLimit(DEFAULT_GSC_LIMIT, MAX_GSC_LIMIT),},async ({ projectId: inputProjectId, startDate: sd, endDate: ed, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);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(+ deps,projectId,startDate,endDate,@@ -79,10 +80,11 @@ export function registerGscPageTools(page,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const details = await getGscPageDetails(+ deps,projectId,page,startDate,diff --git a/packages/core/src/modules/mcp/src/tools/gsc/queries.ts b/packages/core/src/modules/mcp/src/tools/gsc/queries.tsindex 5cef5a0f4..8c08aa51b 100644--- a/packages/core/src/modules/mcp/src/tools/gsc/queries.ts+++ b/packages/core/src/modules/mcp/src/tools/gsc/queries.ts@@ -1,9 +1,9 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import { getGscQueries, getGscQueryDetails } from '../../../../../v1-compat';import type { GscQueryOpportunity } from '../../../../gsc/gsc.service';-import type { McpAuthContext } from '../../auth';+import { getGscQueries, getGscQueryDetails } from '../../../../gsc/gsc.service';import {+ type McpToolDeps,projectIdSchema,resolveDateRange,resolveProjectId,@@ -94,7 +94,7 @@ function computeOpportunities(export function registerGscQueryTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('gsc_get_top_queries',@@ -105,12 +105,13 @@ export function registerGscQueryTools(limit: zLimit(DEFAULT_GSC_LIMIT, MAX_GSC_LIMIT),},async ({ projectId: inputProjectId, startDate: sd, endDate: ed, limit }) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);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(+ deps,projectId,startDate,endDate,@@ -149,11 +150,12 @@ export function registerGscQueryTools(minImpressions,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const take = limit ?? DEFAULT_OPPORTUNITY_LIMIT;const queries = await getGscQueries(+ deps,projectId,startDate,endDate,@@ -206,10 +208,11 @@ export function registerGscQueryTools(query,limit,}) =>- withErrorHandling(async () => {- const projectId = await resolveProjectId(context, inputProjectId);+ withErrorHandling(deps, async () => {+ const projectId = await resolveProjectId(deps, context, inputProjectId);const { startDate, endDate } = resolveDateRange(sd, ed);const details = await getGscQueryDetails(+ deps,projectId,query,startDate,diff --git a/packages/core/src/modules/mcp/src/tools/index.ts b/packages/core/src/modules/mcp/src/tools/index.tsindex 531a12aa9..d3e44afe0 100644--- a/packages/core/src/modules/mcp/src/tools/index.ts+++ b/packages/core/src/modules/mcp/src/tools/index.ts@@ -1,5 +1,4 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import type { McpAuthContext } from '../auth';import { registerActiveUserTools } from './analytics/active-users';import { registerEngagementTools } from './analytics/engagement';import { registerEventNameTools } from './analytics/event-names';@@ -25,49 +24,47 @@ import { registerGscOverviewTools } from './gsc/overview';import { registerGscPageTools } from './gsc/pages';import { registerGscQueryTools } from './gsc/queries';import { registerProjectTools } from './projects';+import type { McpToolDeps } from './shared';-export function registerAllTools(- server: McpServer,- context: McpAuthContext-): void {+export function registerAllTools(server: McpServer, tools: McpToolDeps): void {// Project access — always call first to discover available projects- registerProjectTools(server, context);- registerDashboardLinkTools(server, context);- registerDashboardManagementTools(server, context);- registerReportTools(server, context);+ registerProjectTools(server, tools);+ registerDashboardLinkTools(server, tools);+ registerDashboardManagementTools(server, tools);+ registerReportTools(server, tools);// Analytics — discovery (call these first to understand the data)- registerEventNameTools(server, context);- registerPropertyValueTools(server, context);+ registerEventNameTools(server, tools);+ registerPropertyValueTools(server, tools);// Analytics — event data- registerEventTools(server, context);- registerSessionTools(server, context);+ registerEventTools(server, tools);+ registerSessionTools(server, tools);// Analytics — profiles- registerProfileTools(server, context);- registerProfileMetricTools(server, context);+ registerProfileTools(server, tools);+ registerProfileMetricTools(server, tools);// Analytics — groups (B2B)- registerGroupTools(server, context);+ registerGroupTools(server, tools);// Analytics — aggregated metrics- registerOverviewTools(server, context);- registerActiveUserTools(server, context);- registerPageTools(server, context);- registerPagePerformanceTools(server, context);- registerPageConversionTools(server, context);- registerTrafficTools(server, context);+ registerOverviewTools(server, tools);+ registerActiveUserTools(server, tools);+ registerPageTools(server, tools);+ registerPagePerformanceTools(server, tools);+ registerPageConversionTools(server, tools);+ registerTrafficTools(server, tools);// Analytics — user behavior- registerFunnelTools(server, context);- registerRetentionTools(server, context);- registerEngagementTools(server, context);- registerUserFlowTools(server, context);+ registerFunnelTools(server, tools);+ registerRetentionTools(server, tools);+ registerEngagementTools(server, tools);+ registerUserFlowTools(server, tools);// Google Search Console- registerGscOverviewTools(server, context);- registerGscPageTools(server, context);- registerGscQueryTools(server, context);- registerGscCannibalizationTools(server, context);+ registerGscOverviewTools(server, tools);+ registerGscPageTools(server, tools);+ registerGscQueryTools(server, tools);+ registerGscCannibalizationTools(server, tools);}diff --git a/packages/core/src/modules/mcp/src/tools/projects.ts b/packages/core/src/modules/mcp/src/tools/projects.tsindex f8f545fda..b245db900 100644--- a/packages/core/src/modules/mcp/src/tools/projects.ts+++ b/packages/core/src/modules/mcp/src/tools/projects.ts@@ -1,10 +1,9 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import type { McpAuthContext } from '../auth';-import { loadCompatDb, withErrorHandling } from './shared';+import { type McpToolDeps, withErrorHandling } from './shared';export function registerProjectTools(server: McpServer,- context: McpAuthContext+ { context, deps }: McpToolDeps) {server.tool('list_projects',@@ -13,8 +12,8 @@ export function registerProjectTools(: 'Returns the single project this client has access to.',{},async () =>- withErrorHandling(async () => {- const db = await loadCompatDb();+ withErrorHandling(deps, async () => {+ const db = deps.db;if (context.clientType === 'root') {const projects = await db.project.findMany({diff --git a/packages/core/src/modules/mcp/src/tools/shared.test.ts b/packages/core/src/modules/mcp/src/tools/shared.test.tsindex 23a1e2eec..3581f1d0a 100644--- a/packages/core/src/modules/mcp/src/tools/shared.test.ts+++ b/packages/core/src/modules/mcp/src/tools/shared.test.ts@@ -6,10 +6,27 @@ import {it,setSystemTime,} from 'bun:test';-import { resolveClientProjectId } from '@openpanel/core';+import type { ServiceDeps } from '../../../../services';+import { resolveClientProjectId } from '../../../project/project.service';import type { McpAuthContext } from '../auth';import { MAX_RESPONSE_CHARS, resolveDateRange, table, toText } from './shared';+const noop = () => undefined;+/** Neither subject under test here touches a connection: `resolveClientProjectId`+ * short-circuits before its one Postgres read for both cases below, and+ * `toText` only logs when it cannot shrink. */+const deps = {+ logger: {+ fatal: noop,+ error: noop,+ warn: noop,+ info: noop,+ debug: noop,+ trace: noop,+ child: () => deps.logger,+ },+} as unknown as ServiceDeps;+const READ_CTX: McpAuthContext = {projectId: 'proj-abc',organizationId: 'org-1',@@ -56,7 +73,7 @@ describe('resolveDateRange', () => {describe('resolveClientProjectId', () => {it('returns the context projectId for read clients, ignoring any input', async () => {await expect(- resolveClientProjectId({+ resolveClientProjectId(deps, {clientType: READ_CTX.clientType,clientProjectId: READ_CTX.projectId,organizationId: READ_CTX.organizationId,@@ -64,7 +81,7 @@ describe('resolveClientProjectId', () => {})).resolves.toBe('proj-abc');await expect(- resolveClientProjectId({+ resolveClientProjectId(deps, {clientType: READ_CTX.clientType,clientProjectId: READ_CTX.projectId,organizationId: READ_CTX.organizationId,@@ -75,7 +92,7 @@ describe('resolveClientProjectId', () => {it('throws for root clients when no projectId is provided', async () => {await expect(- resolveClientProjectId({+ resolveClientProjectId(deps, {clientType: ROOT_CTX.clientType,clientProjectId: ROOT_CTX.projectId,organizationId: ROOT_CTX.organizationId,@@ -162,10 +179,10 @@ describe('table', () => {describe('toText', () => {const parse = (data: unknown) =>- JSON.parse(toText(data).content[0].text) as Record<string, unknown>;+ JSON.parse(toText(deps, data).content[0].text) as Record<string, unknown>;it('serializes compactly — no indentation', () => {- const { text } = toText({ a: 1, b: [1, 2] }).content[0];+ const { text } = toText(deps, { a: 1, b: [1, 2] }).content[0];expect(text).toBe('{"a":1,"b":[1,2]}');});@@ -175,7 +192,7 @@ describe('toText', () => {sessions: i,}));const oversized = table(rows, { limit: 5000 });- const { text } = toText(oversized).content[0];+ const { text } = toText(deps, oversized).content[0];expect(text.length).toBeLessThanOrEqual(MAX_RESPONSE_CHARS);const parsed = JSON.parse(text) as { rows: unknown[]; note: string };expect(parsed.rows.length).toBeLessThan(5000);diff --git a/packages/core/src/modules/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.tsindex 443b9c3a9..d80a6cc4f 100644--- a/packages/core/src/modules/mcp/src/tools/shared.ts+++ b/packages/core/src/modules/mcp/src/tools/shared.ts@@ -1,60 +1,31 @@import { z } from 'zod';-import { createLogger } from '../../../../clients/logger';-import type { ServiceDeps } from '../../../../services';-import {- compatDb,- compatPrisma,- compatServiceDeps,- pagesService,- resolveClientProjectId,-} from '../../../../v1-compat';+import type { ServiceDeps, Services } from '../../../../services';+import { resolveClientProjectId } from '../../../project/project.service';import type { McpAuthContext } from '../auth';-const logger = createLogger({ name: 'mcp' });-/**- * MCP's tool handlers have a fixed signature from `@modelcontextprotocol/sdk`- * — there is no `Ctx`/`ServiceDeps` parameter to thread through, so the few- * tools that still touch Postgres/ClickHouse directly (`projects.ts`,- * `dashboard-management.ts`, `analytics/property-values.ts`,- * `analytics/page-performance.ts`, `analytics/reports.ts`) reach them through- * the v1-compat singleton instead of `@openpanel/db` (M10-004, see- * v1-compat.ts's header) — the same pattern every other bare, no-`Ctx`- * caller in this wave uses.+ * What every MCP tool handler closes over.*- * M12-006 made the seam a static import (ADR-007: no lazy loaders). It always- * could be: this module already value-imported `resolveClientProjectId` from- * the same file, so the dynamic form deferred nothing and only hid the edge.- * The v1-compat seam itself is still lazy where it matters — it constructs no- * database until a caller asks for one.+ * `@modelcontextprotocol/sdk`'s tool-handler signature has no context+ * parameter, so the API's connections cannot be threaded through it as an+ * argument. They are captured in a CLOSURE instead, when the per-request+ * server is built from the `deps` the route already holds (ADR-022 R6/R15,+ * Carl's ruling: `createMcpServer(deps)`).*/-export function loadCompatDb() {- return compatDb();-}--/** `dashboard-management.ts`'s only need from `@openpanel/db`: the- * `Prisma.DbNull` sentinel for an explicit SQL NULL on a nullable Json- * column, not a client — same seam as `loadCompatDb`. */-export function loadCompatPrisma() {- return compatPrisma();-}--/** `analytics/property-values.ts` reads ClickHouse through core's own- * `chQuery` (shared/ch-query.ts), which wants the scope's client AND its- * logger rather than a bare client — same seam, widened to what a read- * needs. */-export function loadCompatChScope(): Promise<- Pick<ServiceDeps, 'ch' | 'logger'>-> {- return compatServiceDeps();-}--/** `analytics/page-performance.ts` used to construct its own `PagesService`- * per call to dodge a module-singleton mocking hazard; since M10-005 there is- * no singleton and no class, so it reaches the bare, v1-compat-wrapped pages- * service instead. */-export function loadCompatPagesService() {- return Promise.resolve(pagesService);+export interface McpToolDeps {+ /** The API's connections. Postgres and ClickHouse are reached from here. */+ deps: ServiceDeps;+ /** The live service graph, for a sibling module's behaviour. */+ services: Services;+ /** The authenticated MCP caller. */+ context: McpAuthContext;+ /**+ * `Prisma.DbNull` — the explicit-SQL-NULL sentinel for a nullable Json+ * column. A frozen constant, not a client: `ServiceDeps` has no field for+ * it and `core-uses-ctx-not-db-internals` forbids importing it here, so+ * `mcp.service.ts` resolves it once and hands it in with the rest.+ */+ dbJsonNull: unknown;}/**@@ -62,10 +33,11 @@ export function loadCompatPagesService() {* Thin adapter so tool files don't repeat the full argument object every call.*/export function resolveProjectId(+ deps: ServiceDeps,context: McpAuthContext,inputProjectId: string | undefined): Promise<string> {- return resolveClientProjectId({+ return resolveClientProjectId(deps, {clientType: context.clientType,clientProjectId: context.projectId,organizationId: context.organizationId,@@ -330,7 +302,10 @@ function shrinkLargestTable(payload: unknown): boolean {* unexpectedly large must degrade to a smaller answer rather than flood the* caller's context.*/-export function toText(data: unknown): {+export function toText(+ deps: ServiceDeps,+ data: unknown+): {content: [{ type: 'text'; text: string }];} {let text = JSON.stringify(data);@@ -340,7 +315,7 @@ export function toText(data: unknown): {}if (text.length > MAX_RESPONSE_CHARS) {- logger.warn(+ deps.logger.warn({ chars: text.length },'MCP response exceeded size limit with no shrinkable table');@@ -359,14 +334,15 @@ export function toText(data: unknown): {* Wrap a tool handler to catch errors and return them as MCP error content.*/export async function withErrorHandling<T>(+ deps: ServiceDeps,fn: () => Promise<T>): Promise<{ content: [{ type: 'text'; text: string }]; isError?: boolean }> {try {const result = await fn();- return toText(result);+ return toText(deps, result);} catch (err) {const message = err instanceof Error ? err.message : String(err);- logger.error({ err }, `MCP tool error: ${message}`);+ deps.logger.error({ err }, `MCP tool error: ${message}`);return {content: [{ type: 'text' as const, text: `Error: ${message}` }],isError: true,diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.tsindex 4a289e1da..936e87543 100644--- a/packages/core/src/modules/overview/overview.rpc.ts+++ b/packages/core/src/modules/overview/overview.rpc.ts@@ -45,15 +45,6 @@ import {zGetUserJourneyInput,} from './overview.service';-// Lazy, not a static import: the assistant module's chatApp chain reaches-// deep into @openpanel/db (see index.ts's own `loadAssistant()` for the full-// story) — a static import here would pull that chain into this module's-// evaluation, and this module is itself a static import of-// rpc.router.ts/index.ts's own barrel.-function loadFilterCommand() {- return import('../assistant/src/filter-command');-}-function requireLogin(userId: string | null | undefined): string {if (!userId) {throw new TRPCAccessError('Not authenticated');@@ -432,8 +423,7 @@ export const overviewRouter = createTRPCRouter({.mutation(async ({ ctx, input }) => {await requireReadAccess(ctx, input.projectId);const { timezone } = await getSettingsForProject(ctx, input.projectId);- const { runFilterCommand } = await loadFilterCommand();- return runFilterCommand({+ return ctx.services.assistant.runFilterCommand({query: input.query,projectId: input.projectId,pageContext: input.pageContext,