Skip to content

Commit 1dd7cc1

Browse files
committed
fix(mcp)!: an aggregate_records aggregation entry carries its filter to the engine and refuses an undeclared key by name
The entry was a non-strict z.object({ function, field, alias }), so zod stripped a per-aggregation filter (and any other unknown entry key) before the handler ran, and MCP answered the unconditional aggregate where the REST query door answered the filtered one. The entry is now built from the engine's AggregationNodeSchema members, filter included, and closed through strictToolInput. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5kNo4JeL2JoFcPq4SH
1 parent a2e7556 commit 1dd7cc1

2 files changed

Lines changed: 241 additions & 10 deletions

File tree

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `aggregate_records`: each aggregation entry carries its `filter` to the
5+
* engine and refuses an undeclared key by name (#28550).
6+
*
7+
* THE DEFECT. The entry was a plain `z.object({ function, field, alias })`, so
8+
* zod's `.strip` default deleted a per-aggregation `filter` before the handler
9+
* ran. `{ function: 'count', alias: 'n', filter: { status: 'active' } }` beside
10+
* an unfiltered `count` answered the same number twice (5 and 5 on the stock
11+
* showcase), while the REST query door answered 2 and 5 for the same body. An
12+
* unknown entry key (`bogusKey`) was dropped the same way. The top-level
13+
* closure (#16913) never reached inside the array.
14+
*
15+
* WHAT IS PINNED HERE, at the tool layer over a recording bridge: the entry's
16+
* `filter` reaches the bridge byte-for-byte (the bridge hands `aggregations` to
17+
* `engine.aggregate`, which applies it, so nothing in this package evaluates
18+
* it); a malformed filter gets the engine node's own refusal at the door; an
19+
* undeclared entry key is refused by name before the bridge is asked; and the
20+
* advertised JSON Schema declares both facts. The MCP-equals-REST answer over a
21+
* real engine, and the field-permission refusal, are pinned end to end in
22+
* `packages/qa/dogfood/test/showcase-mcp-aggregate-filter.dogfood.test.ts`.
23+
*
24+
* CONTROLS. Entries without a filter reach the bridge exactly as before, and
25+
* the top-level unknown-key posture is unchanged.
26+
*/
27+
28+
import { describe, it, expect, beforeEach } from 'vitest';
29+
30+
import { MCPServerRuntime } from './mcp-server-runtime.js';
31+
import type { McpDataBridge } from './mcp-http-tools.js';
32+
33+
interface RecordingBridge extends McpDataBridge {
34+
calls: any[];
35+
}
36+
37+
function makeBridge(): RecordingBridge {
38+
const calls: any[] = [];
39+
return {
40+
calls,
41+
async listObjects() { return [{ name: 'showcase_project' }]; },
42+
async describeObject(name: string) { return { name, fields: [] }; },
43+
async query(object: string) { return { object, records: [] }; },
44+
async get() { return null; },
45+
async create(object: string) { return { object, id: 'n1' }; },
46+
async update(object: string, id: string) { return { object, id }; },
47+
async remove(object: string, id: string) { return { object, id, success: true }; },
48+
async aggregate(object: string, opts: any) {
49+
calls.push([object, opts]);
50+
return [{ n: 2, all: 5 }];
51+
},
52+
};
53+
}
54+
55+
let nextId = 1;
56+
57+
async function rpc(runtime: MCPServerRuntime, bridge: RecordingBridge, method: string, params?: unknown) {
58+
const body = { jsonrpc: '2.0', id: nextId++, method, ...(params === undefined ? {} : { params }) };
59+
const req = new Request('http://localhost/api/v1/mcp', {
60+
method: 'POST',
61+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
62+
body: JSON.stringify(body),
63+
});
64+
const res = await runtime.handleHttpRequest(req, { bridge, parsedBody: body });
65+
return (await res.json()) as any;
66+
}
67+
68+
async function aggregate(runtime: MCPServerRuntime, bridge: RecordingBridge, args: Record<string, unknown>) {
69+
const json = await rpc(runtime, bridge, 'tools/call', { name: 'aggregate_records', arguments: args });
70+
const text = json.result?.content?.map((c: any) => c.text).join('\n') ?? json.error?.message ?? '';
71+
return { refused: json.result?.isError === true || Boolean(json.error), text: String(text) };
72+
}
73+
74+
describe('aggregate_records — the aggregation entry (#28550)', () => {
75+
let runtime: MCPServerRuntime;
76+
let bridge: RecordingBridge;
77+
78+
beforeEach(() => {
79+
runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
80+
bridge = makeBridge();
81+
});
82+
83+
it('the reported call: an entry `filter` reaches the bridge unchanged, beside an unfiltered sibling', async () => {
84+
const aggregations = [
85+
{ function: 'count', alias: 'n', filter: { status: 'active' } },
86+
{ function: 'count', alias: 'all' },
87+
];
88+
const { refused, text } = await aggregate(runtime, bridge, { objectName: 'showcase_project', aggregations });
89+
expect(refused, text).toBe(false);
90+
expect(bridge.calls).toHaveLength(1);
91+
expect(bridge.calls[0][0]).toBe('showcase_project');
92+
// Exactly what was sent: the filter on the first entry, none on the second.
93+
expect(bridge.calls[0][1].aggregations).toEqual(aggregations);
94+
});
95+
96+
it('an operator filter reaches the bridge as sent', async () => {
97+
const aggregations = [
98+
{ function: 'sum', field: 'budget', alias: 'big', filter: { budget: { $gte: 1000 }, status: { $in: ['active', 'planning'] } } },
99+
];
100+
const { refused, text } = await aggregate(runtime, bridge, {
101+
objectName: 'showcase_project',
102+
aggregations,
103+
groupBy: ['status'],
104+
where: { owner: 'u1' },
105+
});
106+
expect(refused, text).toBe(false);
107+
expect(bridge.calls[0][1]).toMatchObject({ aggregations, groupBy: ['status'], where: { owner: 'u1' } });
108+
});
109+
110+
it('CONTROL — entries without a filter reach the bridge exactly as before', async () => {
111+
const aggregations = [
112+
{ function: 'count', alias: 'n' },
113+
{ function: 'sum', field: 'budget', alias: 'total' },
114+
];
115+
const { refused, text } = await aggregate(runtime, bridge, { objectName: 'showcase_project', aggregations });
116+
expect(refused, text).toBe(false);
117+
expect(bridge.calls[0][1].aggregations).toEqual(aggregations);
118+
});
119+
120+
it('an undeclared entry key is refused by name, and the bridge is never asked', async () => {
121+
const { refused, text } = await aggregate(runtime, bridge, {
122+
objectName: 'showcase_project',
123+
aggregations: [{ function: 'count', alias: 'n', bogusKey: 1 }],
124+
});
125+
expect(refused).toBe(true);
126+
expect(text).toContain('bogusKey');
127+
expect(bridge.calls).toHaveLength(0);
128+
});
129+
130+
it('an entry `where` is refused, and the refusal names `filter` as the spelling to send', async () => {
131+
const { refused, text } = await aggregate(runtime, bridge, {
132+
objectName: 'showcase_project',
133+
aggregations: [{ function: 'count', alias: 'n', where: { status: 'active' } }],
134+
});
135+
expect(refused).toBe(true);
136+
expect(text).toContain('where');
137+
expect(text).toContain('filter');
138+
expect(bridge.calls).toHaveLength(0);
139+
});
140+
141+
it('the retired `distinct` entry key is refused, not dropped', async () => {
142+
const { refused, text } = await aggregate(runtime, bridge, {
143+
objectName: 'showcase_project',
144+
aggregations: [{ function: 'sum', field: 'budget', alias: 's', distinct: true }],
145+
});
146+
expect(refused).toBe(true);
147+
expect(text).toContain('distinct');
148+
expect(bridge.calls).toHaveLength(0);
149+
});
150+
151+
it('a filter that is not a filter object is refused at the door by the engine node\'s own shape', async () => {
152+
for (const filter of ["status = 'active'", ['status', '=', 'active'], 7]) {
153+
const { refused } = await aggregate(runtime, bridge, {
154+
objectName: 'showcase_project',
155+
aggregations: [{ function: 'count', alias: 'n', filter }],
156+
});
157+
expect(refused, JSON.stringify(filter)).toBe(true);
158+
}
159+
expect(bridge.calls).toHaveLength(0);
160+
});
161+
162+
it('CONTROL — an undeclared TOP-LEVEL key is still refused, naming the declared spelling', async () => {
163+
const { refused, text } = await aggregate(runtime, bridge, {
164+
objectName: 'showcase_project',
165+
metrics: [{ function: 'count', alias: 'n' }],
166+
});
167+
expect(refused).toBe(true);
168+
expect(text).toContain('metrics');
169+
expect(text).toContain('aggregations');
170+
expect(bridge.calls).toHaveLength(0);
171+
});
172+
173+
it('`tools/list` advertises the entry as closed, with `filter` declared', async () => {
174+
const json = await rpc(runtime, bridge, 'tools/list');
175+
const tool = (json.result?.tools ?? []).find((t: any) => t.name === 'aggregate_records');
176+
expect(tool).toBeDefined();
177+
const entry = tool.inputSchema?.properties?.aggregations?.items;
178+
expect(entry?.additionalProperties).toBe(false);
179+
expect(Object.keys(entry?.properties ?? {}).sort()).toEqual(['alias', 'field', 'filter', 'function']);
180+
expect(entry?.required).toEqual(expect.arrayContaining(['function', 'alias']));
181+
});
182+
});

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 59 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@
3939
import { z } from 'zod';
4040
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4141
import type { EngineAggregateOptions } from '@objectstack/spec/data';
42+
// [#28550] The engine's aggregation entry. Each `aggregate_records` entry is
43+
// built from ITS members, so this door and the REST query door (which parses
44+
// `FindDataRequestSchema`, whose `aggregations` are this node) judge one shape.
45+
import { AggregationNodeSchema } from '@objectstack/spec/data';
4246
// [#23529] The catalogue's spelling of `PERMISSION_DENIED`, the code whose
4347
// `details` `errorResultFromThrown` withholds. Imported, never hand-spelled.
4448
import { StandardErrorCode } from '@objectstack/spec/api';
@@ -689,6 +693,56 @@ function strictToolInput<T extends z.ZodRawShape>(
689693
.strict();
690694
}
691695

696+
/**
697+
* [#28550] One `aggregate_records` aggregation entry: closed, and carrying the
698+
* per-aggregation `filter`.
699+
*
700+
* The entry used to be a plain `z.object({ function, field, alias })`. Zod's
701+
* default for an object is `.strip`, and {@link strictToolInput} closes only the
702+
* tool's TOP-LEVEL keys, so an entry's `filter` was deleted before the handler
703+
* ran: `{ function: 'count', alias: 'n', filter: { status: 'active' } }` answered
704+
* the unconditional count, beside the REST query door answering the filtered
705+
* one for the same body. Any other unknown entry key vanished the same way.
706+
*
707+
* Both halves of the fix are the entry's shape, nothing else:
708+
*
709+
* - **`filter` is declared**, and it is the engine's own member,
710+
* `AggregationNodeSchema.shape.filter` (`FilterConditionSchema`), the slot the
711+
* REST door parses. The handler forwards `aggregations` to the bridge
712+
* unchanged, and every bridge hands them to `engine.aggregate`, which applies
713+
* the filter and runs it through the same refusal doors as `where` (shape,
714+
* unknown field, and the security middleware's field-read check). ⛔ No filter
715+
* is evaluated here: a second evaluator in this package would be a second
716+
* answer to the same question.
717+
* - **The entry is strict**, through {@link strictToolInput}, so an undeclared
718+
* entry key is refused by name, as an undeclared top-level key already is.
719+
* The aliases are semantic near-misses for `filter` and `alias`; they are
720+
* named in the refusal and never parsed.
721+
*
722+
* `function`, `field` and `alias` are the engine's members too. Each keeps the
723+
* description this tool advertised before; `.describe` copies the schema and
724+
* leaves its parse unchanged.
725+
*/
726+
function aggregationEntrySchema() {
727+
const node = AggregationNodeSchema.shape;
728+
return strictToolInput(
729+
{
730+
surface: 'this aggregate_records aggregation entry',
731+
aliases: { where: 'filter', filters: 'filter', conditions: 'filter', as: 'alias' },
732+
},
733+
{
734+
function: node.function.describe('Aggregation function'),
735+
field: node.field.describe('Field to aggregate (omit for count(*))'),
736+
alias: node.alias.describe('Result column name'),
737+
filter: node.filter.describe(
738+
'Optional per-aggregation filter, e.g. {"status":"active"}: only rows matching it feed THIS '
739+
+ 'aggregation, while the other aggregations in the call still read every row. Same operators '
740+
+ 'as where.',
741+
),
742+
},
743+
);
744+
}
745+
692746
/**
693747
* The spellings every object-scoped tool shares, split out because they are the
694748
* same guess wherever an object name is taken.
@@ -1179,17 +1233,12 @@ export function registerObjectTools(
11791233
{
11801234
objectName: z.string().describe('The object/table name'),
11811235
aggregations: z
1182-
.array(
1183-
z.object({
1184-
function: z
1185-
.enum(['count', 'sum', 'avg', 'min', 'max', 'count_distinct'])
1186-
.describe('Aggregation function'),
1187-
field: z.string().optional().describe('Field to aggregate (omit for count(*))'),
1188-
alias: z.string().describe('Result column name'),
1189-
}),
1190-
)
1236+
.array(aggregationEntrySchema())
11911237
.min(1)
1192-
.describe('Metrics to compute, e.g. [{"function":"sum","field":"amount","alias":"total"}]'),
1238+
.describe(
1239+
'Metrics to compute, e.g. [{"function":"sum","field":"amount","alias":"total"},'
1240+
+ '{"function":"count","alias":"open_count","filter":{"status":"open"}}]',
1241+
),
11931242
groupBy: z
11941243
.array(
11951244
z.union([

0 commit comments

Comments
 (0)