Skip to content

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

ralph(M15-115): Per-module fixes: packages/core/src/modules/mcp - R13, R16 and the findings no rule covers

ralph4537efdc3085
diff --git a/packages/core/src/modules/mcp/mcp.routes.ts b/packages/core/src/modules/mcp/mcp.routes.ts
index 333e92317..6e3270690 100644
--- a/packages/core/src/modules/mcp/mcp.routes.ts
+++ b/packages/core/src/modules/mcp/mcp.routes.ts
@@ -1,16 +1,17 @@
-// MCP's stateless POST transport, mounted at `/mcp` (M5-007, ADR-015 entry
-// 2). NAMED GAP, same as gsc.routes.ts / import.routes.ts / assistant.routes.ts:
-// not yet reachable — main.ts does not mount `dashboardRoutes` until a real
-// `AppDeps` exists (P3/P4/P8).
+// MCP's stateless POST transport, mounted at `/mcp` (M5-007, ADR-015 entry 2).
//
// `ctx.services.mcp` carries this module's factory the same as every other
// module now (M10-004) — `mcp.service.ts`'s own header explains why that
// file is now safe to reach through `ctx.services` instead of this route's
// former one-off `loadMcpService()`.
//
-// Rate limiting (V1: 60/min via Fastify's activateRateLimiter) is not wired
-// here yet — nothing reaches this route until dashboardRoutes mounts, so it
-// is a port task for whenever that happens, not a gap specific to MCP.
+// OPEN GAP: V1's 60/min rate limit (Fastify's activateRateLimiter) is still
+// not ported, and the route IS live — `apps/api/src/main.ts` mounts
+// `dashboardRoutes` for every non-worker role. So an unauthenticated caller
+// can drive one argon2 verify per request: `src/auth.ts` caches a *correct*
+// secret for 5 minutes under a key containing that secret's hash, which a
+// wrong secret misses every time. Porting the limiter is a task for whoever
+// owns the HTTP surface; nothing in this module can do it.
//
// The JSON-RPC body comes off the CONTEXT, not from `request.json()`: Elysia
// has already consumed the stream by the time the handler runs, and reading it
diff --git a/packages/core/src/modules/mcp/mcp.service.test.ts b/packages/core/src/modules/mcp/mcp.service.test.ts
index 2604191de..7746ca0db 100644
--- a/packages/core/src/modules/mcp/mcp.service.test.ts
+++ b/packages/core/src/modules/mcp/mcp.service.test.ts
@@ -27,7 +27,11 @@ import {
expect,
it,
mock,
+ spyOn,
} from 'bun:test';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
import type { ServiceDeps, Services } from '../../services';
const actualRedis = await import('@openpanel/redis');
@@ -111,6 +115,10 @@ const READ_CLIENT = {
organizationId: 'org-1',
};
+// Captured before any `spyOn` replaces it, so a recording spy can still
+// deliver the message for real.
+const realSend = InMemoryTransport.prototype.send;
+
function post(token: string | undefined, body: unknown) {
return handleStatelessMcpRequest(deps, services, token, body);
}
@@ -245,6 +253,83 @@ describe('handleStatelessMcpRequest — protocol', () => {
});
});
+ it('closes the ephemeral server — and with it the transport pair it opened', async () => {
+ // ADR-022 R16. `spyOn` calls through, so the close still really happens.
+ const closeSpy = spyOn(McpServer.prototype, 'close');
+ try {
+ const res = await post(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 6,
+ method: 'tools/list',
+ });
+
+ expect(res.status).toBe(200);
+ expect(closeSpy).toHaveBeenCalledTimes(1);
+ } finally {
+ closeSpy.mockRestore();
+ }
+ });
+
+ it('closes the ephemeral server even when the transport throws', async () => {
+ const closeSpy = spyOn(McpServer.prototype, 'close');
+ const sendSpy = spyOn(InMemoryTransport.prototype, 'send');
+ sendSpy.mockImplementation(() => {
+ throw new Error('transport exploded');
+ });
+
+ try {
+ await expect(
+ post(VALID_TOKEN, { jsonrpc: '2.0', id: 7, method: 'tools/list' })
+ ).rejects.toThrow('transport exploded');
+ expect(closeSpy).toHaveBeenCalledTimes(1);
+ } finally {
+ sendSpy.mockRestore();
+ closeSpy.mockRestore();
+ }
+ });
+
+ it('pins the synthetic handshake: protocol version, proxy client info, order', async () => {
+ const sent: JSONRPCMessage[] = [];
+ const sendSpy = spyOn(InMemoryTransport.prototype, 'send');
+ sendSpy.mockImplementation(function sendAndRecord(
+ this: InMemoryTransport,
+ message: JSONRPCMessage
+ ) {
+ sent.push(message);
+ return realSend.call(this, message);
+ });
+
+ try {
+ const res = await post(VALID_TOKEN, {
+ jsonrpc: '2.0',
+ id: 9,
+ method: 'tools/list',
+ });
+ expect(res.status).toBe(200);
+ } finally {
+ sendSpy.mockRestore();
+ }
+
+ // Client-side traffic only; the server's replies come back via onmessage.
+ const fromClient = sent.filter(
+ (message) => 'method' in message && message.method !== undefined
+ );
+ expect(fromClient.slice(0, 3)).toEqual([
+ {
+ jsonrpc: '2.0',
+ id: '__mcp_init__',
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'mcp-proxy', version: '0' },
+ },
+ },
+ { jsonrpc: '2.0', method: 'notifications/initialized' },
+ { jsonrpc: '2.0', id: 9, method: 'tools/list' },
+ ] as JSONRPCMessage[]);
+ });
+
it('re-authenticates from scratch on every call — no session survives between requests', async () => {
const first = await post(VALID_TOKEN, {
jsonrpc: '2.0',
diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.ts
index 650e6e630..c7985a885 100644
--- a/packages/core/src/modules/mcp/mcp.service.ts
+++ b/packages/core/src/modules/mcp/mcp.service.ts
@@ -33,8 +33,17 @@ import type { McpToolDeps } from './src/tools/shared';
export type { McpAuthContext } from './src/auth';
export { extractToken, McpAuthError } from './src/auth';
+/**
+ * The wire constants of the synthetic handshake. They are a CONTRACT with
+ * whatever client is on the other end of `/mcp`, not an implementation
+ * detail: `mcp.service.test.ts` pins them, because bumping
+ * `@modelcontextprotocol/sdk` does not bump them and nothing else would
+ * notice if it did.
+ */
const MCP_PROTOCOL_VERSION = '2024-11-05';
const MCP_PROXY_CLIENT_INFO = { name: 'mcp-proxy', version: '0' };
+/** JSON-RPC id of the synthetic `initialize`; never leaves this process. */
+const SYNTHETIC_INITIALIZE_ID = '__mcp_init__';
export interface McpHttpResult {
status: number;
@@ -125,32 +134,56 @@ async function runOnEphemeralServer(
const server = createMcpServer(tools);
await server.connect(serverTransport);
- if (!isInitializeRequest) {
- await new Promise<void>((resolve, reject) => {
- clientTransport.onmessage = () => resolve();
- clientTransport
- .send({
- jsonrpc: '2.0',
- id: '__mcp_init__',
- method: 'initialize',
- params: {
- protocolVersion: MCP_PROTOCOL_VERSION,
- capabilities: {},
- clientInfo: MCP_PROXY_CLIENT_INFO,
- },
- })
- .catch(reject);
- });
- // No response expected for this notification.
- await clientTransport.send({
- jsonrpc: '2.0',
- method: 'notifications/initialized',
+ try {
+ if (!isInitializeRequest) {
+ await completeSyntheticHandshake(clientTransport);
+ }
+
+ return await new Promise<JSONRPCMessage>((resolve, reject) => {
+ clientTransport.onmessage = resolve;
+ clientTransport.send(message).catch(reject);
});
+ } finally {
+ // ADR-022 R16: this function opened the pair, so this function closes it.
+ // `server.close()` closes `serverTransport`, and an InMemoryTransport
+ // closes its linked peer, so one call tears down both ends — and with
+ // them the SDK's response handlers and in-flight abort controllers,
+ // which a dropped-on-the-floor server would have kept alive until GC.
+ await server.close();
}
+}
- return await new Promise<JSONRPCMessage>((resolve, reject) => {
- clientTransport.onmessage = resolve;
- clientTransport.send(message).catch(reject);
+/**
+ * Fast-forward a brand-new server to its ready state.
+ *
+ * ORDER-SENSITIVE: the `initialize` response and the `notifications/initialized`
+ * that follows it must both be consumed here, before the caller installs the
+ * real response resolver — otherwise the handshake's own traffic resolves the
+ * caller's promise. It works because `InMemoryTransport` delivers synchronously
+ * and the SDK sends nothing unsolicited.
+ */
+async function completeSyntheticHandshake(
+ clientTransport: InMemoryTransport
+): Promise<void> {
+ await new Promise<void>((resolve, reject) => {
+ clientTransport.onmessage = () => resolve();
+ clientTransport
+ .send({
+ jsonrpc: '2.0',
+ id: SYNTHETIC_INITIALIZE_ID,
+ method: 'initialize',
+ params: {
+ protocolVersion: MCP_PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: MCP_PROXY_CLIENT_INFO,
+ },
+ })
+ .catch(reject);
+ });
+ // No response expected for this notification.
+ await clientTransport.send({
+ jsonrpc: '2.0',
+ method: 'notifications/initialized',
});
}
diff --git a/packages/core/src/modules/mcp/src/integration/tools.test.ts b/packages/core/src/modules/mcp/src/integration/tools.test.ts
index da8b4125c..ac0f96664 100644
--- a/packages/core/src/modules/mcp/src/integration/tools.test.ts
+++ b/packages/core/src/modules/mcp/src/integration/tools.test.ts
@@ -17,6 +17,13 @@
* get_page_performance also calls getSettingsForProject (Postgres) — real,
* not mocked, which is why setupPostgresFixtures runs alongside the
* ClickHouse fixture.
+ *
+ * The fixture import reaches SEVEN levels up, out of this package and into the
+ * repository root's `test/fixtures.ts`. That is deliberate and it is the one
+ * exception to `packages/core/test/preload.ts`'s "core does not import from the
+ * V1 root test directory" — which is a statement about `preload.ts` keeping
+ * `test/databases.ts` in step by hand, not a rule this suite breaks silently.
+ * Copying the seeder here would fork the schema the golden harness seeds from.
*/
import { afterAll, beforeAll, describe, expect, it, mock } from 'bun:test';
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/overview.ts b/packages/core/src/modules/mcp/src/tools/analytics/overview.ts
index 8d9e60664..677514d5f 100644
--- a/packages/core/src/modules/mcp/src/tools/analytics/overview.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/overview.ts
@@ -2,6 +2,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { getAnalyticsOverviewCore } from '../../../../overview/overview.service';
import {
+ MAX_SERIES_POINTS,
type McpToolDeps,
projectIdSchema,
resolveDateRange,
@@ -23,15 +24,6 @@ const POINTS_PER_DAY: Record<Interval, number> = {
month: 1 / 30,
};
-/**
- * The most points we'll return in one series.
- *
- * A 30-day range at `interval: "hour"` is 720 points of 8 metrics each. That is
- * not a chart an LLM can read — it's a wall of numbers that buries the summary
- * the caller actually asked for.
- */
-const MAX_SERIES_POINTS = 180;
-
const SERIES_COLUMNS = [
'date',
'unique_visitors',
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.ts
index 880b6142d..ea26f49b5 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
@@ -14,6 +14,12 @@ import {
const DEFAULT_PERFORMANCE_LIMIT = 25;
const MAX_PERFORMANCE_LIMIT = 500;
+/**
+ * Rows fetched before sorting in memory. The service sorts by sessions only,
+ * so every other `sortBy` needs a wide enough head to re-rank — at the cost
+ * of reading rows the caller will never see.
+ */
+const PAGE_SCAN_LIMIT = 1000;
/**
* Thresholds the tool used to stamp onto every row as a `seo_signals` object of
@@ -72,14 +78,22 @@ export function registerPagePerformanceTools(
endDate,
timezone,
search,
- limit: 1000, // fetch more, sort+slice in memory for flexibility
+ limit: PAGE_SCAN_LIMIT,
});
const col = sortBy ?? 'sessions';
const dir = sortOrder === 'asc' ? 1 : -1;
- const sorted = [...pages].sort(
- (a, b) => dir * ((a[col] ?? 0) < (b[col] ?? 0) ? -1 : 1)
- );
+ // Ties must compare 0. A comparator that answers "greater" for equal
+ // values violates the contract and leaves tied rows in an
+ // engine-dependent order.
+ const sorted = [...pages].sort((a, b) => {
+ const left = a[col] ?? 0;
+ const right = b[col] ?? 0;
+ if (left === right) {
+ return 0;
+ }
+ return dir * (left < right ? -1 : 1);
+ });
return {
seo_thresholds: SEO_THRESHOLDS,
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
index 0157a14e8..ae1f52166 100644
--- a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts
@@ -13,8 +13,10 @@ import {
getReportsByDashboardId,
} from '../../../../report/report.service';
import { getChartStartEndDate } from '../../../../report/src/chart-dates';
+import { requireDashboard } from '../dashboard-access';
import { dashboardBaseUrl } from '../dashboard-links';
import {
+ MAX_SERIES_POINTS,
type McpToolDeps,
projectIdSchema,
resolveProjectId,
@@ -28,7 +30,6 @@ const MAX_SERIES_LIMIT = 200;
/** How many series get their full per-date values in the pivoted `data` block. */
const DEFAULT_PLOTTED_SERIES = 5;
const MAX_PLOTTED_SERIES = 25;
-const MAX_DATA_POINTS = 180;
function reportUrl(
config: CoreConfig,
@@ -104,8 +105,8 @@ function shapeChart(
dates.sort();
const trimmedDates =
- dates.length > MAX_DATA_POINTS
- ? dates.slice(dates.length - MAX_DATA_POINTS)
+ dates.length > MAX_SERIES_POINTS
+ ? dates.slice(dates.length - MAX_SERIES_POINTS)
: dates;
const byDate = plotted.map((serie) => {
@@ -190,10 +191,12 @@ export function registerReportTools(
async ({ projectId: inputProjectId, dashboardId }) =>
withErrorHandling(deps, async () => {
const projectId = await resolveProjectId(deps, context, inputProjectId);
+ // Bind the id to the project BEFORE reading, the way every other
+ // dashboard/report tool here does: the post-hoc check this replaced
+ // let a foreign dashboard holding zero reports answer with a normal
+ // empty table instead of an error.
+ await requireDashboard(deps, projectId, dashboardId);
const reports = await getReportsByDashboardId(deps, dashboardId);
- if (reports.some((r) => r.projectId !== projectId)) {
- throw new Error('Dashboard does not belong to this project');
- }
const rows = reports.map((r) => ({
id: r.id,
name: r.name,
@@ -303,7 +306,7 @@ 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(
+async function runReport(
deps: ServiceDeps,
input: {
organizationId: string;
@@ -365,59 +368,3 @@ export async function runReport(
}
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(
- 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;
- endDate: string;
- report: typeof input.config & { projectId: string };
- data: unknown;
-}> {
- const { timezone } = await getSettingsForProject(deps, input.projectId);
- const chartInput = {
- ...input.config,
- projectId: input.projectId,
- timezone,
- } as unknown as Parameters<typeof executeChart>[1];
-
- const meta = {
- chartType: input.config.chartType,
- interval: input.config.interval,
- startDate: input.config.startDate,
- endDate: input.config.endDate,
- report: { ...input.config, projectId: input.projectId },
- };
-
- if (input.config.chartType === 'funnel') {
- return {
- ...meta,
- data: await getFunnel(
- deps,
- chartInput as Parameters<typeof getFunnel>[1]
- ),
- };
- }
- if (input.config.chartType === 'metric') {
- return { ...meta, data: await executeAggregateChart(deps, chartInput) };
- }
- return { ...meta, data: await executeChart(deps, chartInput) };
-}
diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-access.ts b/packages/core/src/modules/mcp/src/tools/dashboard-access.ts
new file mode 100644
index 000000000..a9b8bf6a6
--- /dev/null
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-access.ts
@@ -0,0 +1,23 @@
+import type { ServiceDeps } from '../../../../services';
+import { getDashboardById } from '../../../dashboard/dashboard.service';
+
+/**
+ * Bind a caller-supplied dashboard id to the resolved project.
+ *
+ * Every tool that reads a dashboard's contents must call this FIRST: the
+ * lookup is scoped by `projectId`, so a dashboard belonging to another
+ * project is indistinguishable from one that does not exist. Checking
+ * ownership after the read instead lets an empty foreign dashboard answer
+ * with a normal empty result.
+ */
+export async function requireDashboard(
+ deps: ServiceDeps,
+ projectId: string,
+ dashboardId: string
+) {
+ const dashboard = await getDashboardById(deps, dashboardId, projectId);
+ if (!dashboard) {
+ throw new Error('Dashboard not found');
+ }
+ return dashboard;
+}
diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
index 99e219191..679fc771e 100644
--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts
@@ -3,9 +3,9 @@ import { z } from 'zod';
import type { CoreConfig } from '../../../../config';
import type { ServiceDeps } from '../../../../services';
import { getId } from '../../../../slug-id';
-import { getDashboardById } from '../../../dashboard/dashboard.service';
import { getProjectById } from '../../../project/project.service';
import { zReport } from '../../../report/report.constants';
+import { requireDashboard } from './dashboard-access';
import { dashboardBaseUrl } from './dashboard-links';
import {
type McpToolDeps,
@@ -169,18 +169,6 @@ function reportData(report: z.infer<typeof reportSchema>, dbNull: unknown) {
};
}
-async function requireDashboard(
- deps: ServiceDeps,
- projectId: string,
- dashboardId: string
-) {
- const dashboard = await getDashboardById(deps, dashboardId, projectId);
- if (!dashboard) {
- throw new Error('Dashboard not found');
- }
- return dashboard;
-}
-
async function requireReport(
db: ServiceDeps['db'],
projectId: string,
@@ -277,9 +265,25 @@ function canonicalReportConfig(report: {
};
}
+/**
+ * The tool list an MCP client receives differs by `clientType`: read clients
+ * get the read tools only, root clients get both halves. The split is two
+ * functions rather than an early return inside one, so a tool cannot change
+ * audience by being added on the wrong side of a line.
+ */
export function registerDashboardManagementTools(
server: McpServer,
- { context, deps, dbJsonNull }: McpToolDeps
+ tools: McpToolDeps
+) {
+ registerDashboardReadTools(server, tools);
+ if (tools.context.clientType === 'root') {
+ registerDashboardWriteTools(server, tools);
+ }
+}
+
+function registerDashboardReadTools(
+ server: McpServer,
+ { context, deps }: McpToolDeps
) {
server.tool(
'get_dashboard',
@@ -323,11 +327,12 @@ export function registerDashboardManagementTools(
};
})
);
+}
- if (context.clientType !== 'root') {
- return;
- }
-
+function registerDashboardWriteTools(
+ server: McpServer,
+ { context, deps, dbJsonNull }: McpToolDeps
+) {
server.tool(
'create_dashboard',
'Create a dashboard in the resolved project.',
diff --git a/packages/core/src/modules/mcp/src/tools/gsc/overview.ts b/packages/core/src/modules/mcp/src/tools/gsc/overview.ts
index ce9d79654..4504920f0 100644
--- a/packages/core/src/modules/mcp/src/tools/gsc/overview.ts
+++ b/packages/core/src/modules/mcp/src/tools/gsc/overview.ts
@@ -2,6 +2,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { getGscOverview } from '../../../../gsc/gsc.service';
import {
+ MAX_SERIES_POINTS,
type McpToolDeps,
projectIdSchema,
resolveDateRange,
@@ -11,9 +12,6 @@ import {
zDateRange,
} from '../shared';
-/** A daily series longer than this stops being readable and starts being noise. */
-const MAX_SERIES_POINTS = 180;
-
export function registerGscOverviewTools(
server: McpServer,
{ context, deps }: McpToolDeps
diff --git a/packages/core/src/modules/mcp/src/tools/gsc/pages.ts b/packages/core/src/modules/mcp/src/tools/gsc/pages.ts
index f3fb53e8f..ab7dd9c68 100644
--- a/packages/core/src/modules/mcp/src/tools/gsc/pages.ts
+++ b/packages/core/src/modules/mcp/src/tools/gsc/pages.ts
@@ -2,6 +2,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { getGscPageDetails, getGscPages } from '../../../../gsc/gsc.service';
import {
+ MAX_SERIES_POINTS,
type McpToolDeps,
projectIdSchema,
resolveDateRange,
@@ -14,7 +15,6 @@ import {
const DEFAULT_GSC_LIMIT = 25;
const MAX_GSC_LIMIT = 1000;
-const MAX_TIMESERIES_POINTS = 180;
const DEFAULT_DETAIL_QUERIES = 25;
/**
@@ -93,7 +93,7 @@ export function registerGscPageTools(
return {
page,
timeseries: table(details.timeseries, {
- limit: MAX_TIMESERIES_POINTS,
+ limit: MAX_SERIES_POINTS,
columns: ['date', 'clicks', 'impressions', 'ctr', 'position'],
sortedBy: 'date',
unit: 'days',
diff --git a/packages/core/src/modules/mcp/src/tools/gsc/queries.ts b/packages/core/src/modules/mcp/src/tools/gsc/queries.ts
index 8c08aa51b..d47aae2d8 100644
--- a/packages/core/src/modules/mcp/src/tools/gsc/queries.ts
+++ b/packages/core/src/modules/mcp/src/tools/gsc/queries.ts
@@ -3,6 +3,7 @@ import { z } from 'zod';
import type { GscQueryOpportunity } from '../../../../gsc/gsc.service';
import { getGscQueries, getGscQueryDetails } from '../../../../gsc/gsc.service';
import {
+ MAX_SERIES_POINTS,
type McpToolDeps,
projectIdSchema,
resolveDateRange,
@@ -15,7 +16,6 @@ import {
const DEFAULT_GSC_LIMIT = 25;
const MAX_GSC_LIMIT = 1000;
-const MAX_TIMESERIES_POINTS = 180;
const DEFAULT_DETAIL_PAGES = 25;
const DEFAULT_OPPORTUNITY_LIMIT = 25;
const MAX_OPPORTUNITY_LIMIT = 200;
@@ -221,7 +221,7 @@ export function registerGscQueryTools(
return {
query,
timeseries: table(details.timeseries, {
- limit: MAX_TIMESERIES_POINTS,
+ limit: MAX_SERIES_POINTS,
columns: ['date', 'clicks', 'impressions', 'ctr', 'position'],
sortedBy: 'date',
unit: 'days',
diff --git a/packages/core/src/modules/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.ts
index d80a6cc4f..7ca4c21f9 100644
--- a/packages/core/src/modules/mcp/src/tools/shared.ts
+++ b/packages/core/src/modules/mcp/src/tools/shared.ts
@@ -123,6 +123,16 @@ export function zLimit(defaultLimit: number, max: number) {
*/
export const MAX_RESPONSE_CHARS = 24_000;
+/**
+ * The most points any tool returns in one time series.
+ *
+ * A 30-day range at `interval: "hour"` is 720 points of 8 metrics each — not a
+ * chart an LLM can read, just a wall of numbers burying the summary the caller
+ * asked for. Tools either coarsen the interval to fit this budget or keep the
+ * recent end of the series; one policy, one number.
+ */
+export const MAX_SERIES_POINTS = 180;
+
/**
* A tabular result in columnar form.
*
@@ -301,6 +311,10 @@ function shrinkLargestTable(payload: unknown): boolean {
* to size their own output via `table`, but a tool that returns something
* unexpectedly large must degrade to a smaller answer rather than flood the
* caller's context.
+ *
+ * SIDE EFFECT: shrinking edits `data` IN PLACE. Every caller builds the
+ * payload for this call and discards it afterwards; pass a value you still
+ * need and it comes back truncated.
*/
export function toText(
deps: ServiceDeps,