Skip to content

Commit 3284b2f

Browse files
committed
test(dogfood): MCP aggregate_records and REST give one answer to a per-aggregation filter, and both refuse it on an unreadable field
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5kNo4JeL2JoFcPq4SH
1 parent 1dd7cc1 commit 3284b2f

2 files changed

Lines changed: 219 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/mcp': patch
3+
---
4+
5+
fix(mcp)!: an `aggregate_records` aggregation entry carries its `filter` to the engine and refuses an undeclared key by name (#28550)
6+
7+
Clause-②: yes (narrowing) — the aggregation entry now accepts `filter` (a widening of the tool's input), and refuses any other undeclared entry key, which it stripped and ignored before (a narrowing).
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No schema key of the metadata protocol is added, removed or re-shaped, and no export or type changes: the MCP tool's input closes an entry it already documented, and the key it now accepts is the engine's own `AggregationNodeSchema.filter`. An undeclared key used to be dropped without effect, so there is nothing for a migration to rewrite; the refusal names the key and, for `where` / `filters` / `conditions` / `as`, the spelling to send. -->
11+
12+
**BREAKING** accept-set narrowing at the MCP `aggregate_records` tool (`@objectstack/mcp`), on both the HTTP and the stdio transport.
13+
14+
- **Before.** Each aggregation entry was a non-strict `{ function, field, alias }`. A per-aggregation `filter` was stripped before the engine was asked, so `{"function":"count","alias":"n","filter":{"status":"active"}}` beside an unfiltered count answered the total twice, while the REST query door answered the filtered count for the same body. Any other unknown entry key was dropped the same way, with no error.
15+
- **Now.** The entry is built from the engine's `AggregationNodeSchema` members (`function`, `field`, `alias`, `filter`) and is closed. The `filter` is forwarded unchanged to `engine.aggregate`, the path REST uses, so both doors give one answer, including the security middleware's 403 `PERMISSION_DENIED` for a filter on a field the caller cannot read. An undeclared entry key (the retired `distinct` included) is refused by name before anything runs, as an undeclared top-level key already was.
16+
- **Unchanged.** Entries without a filter answer as before; the REST query door is untouched.
17+
- **Who sees it.** An MCP client that sent an extra key inside an aggregation entry: the call was answered with that key ignored, and it is now refused naming the key.
18+
19+
**The remedy.** Drop the key, or for a per-aggregation condition send it as the entry's `filter`.
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// #28550 — MCP `aggregate_records` and the REST query door give ONE answer to a
4+
// per-aggregation `filter`, through the real showcase + security + MCP stack.
5+
//
6+
// THE DEFECT, measured by QA on the stock showcase: the MCP tool's aggregation
7+
// entry was a non-strict zod object, so an entry's `filter` was stripped before
8+
// the call reached the engine. The same body answered
9+
//
10+
// MCP `rows: [{ n: 5, all: 5 }]` (the filter dropped)
11+
// REST `records: [{ n: 2, all: 5 }]` (the filter applied)
12+
//
13+
// and a per-aggregation filter on a field the caller cannot read answered the
14+
// unfiltered count through MCP, where REST refused it 403 PERMISSION_DENIED.
15+
//
16+
// WHAT IS PINNED. Both answers are read here, from the same principal, on the
17+
// same rows, and compared — never a hand-computed constant on one side only:
18+
//
19+
// 1. the filtered and unfiltered counts agree between MCP and REST, and are
20+
// DIFFERENT from each other (non-vacuous: a dropped filter would make them
21+
// equal, which is exactly how the defect looked);
22+
// 2. both equal the count the engine reads in system context;
23+
// 3. a member whose permission set marks `budget` `readable: false` gets the
24+
// security middleware's own refusal on BOTH doors (403 PERMISSION_DENIED),
25+
// not an unfiltered count — the refusal comes from the engine path, since
26+
// `packages/mcp` evaluates no filter;
27+
// 4. an undeclared entry key is refused by MCP, naming the key.
28+
//
29+
// CONTROLS. The same member's UNFILTERED count is served by both doors and
30+
// agrees, so the refusal in (3) is the predicate's and not the member's read of
31+
// the object.
32+
//
33+
// Why a private boot rather than the worker-shared showcase: this file saves a
34+
// permission set and loads the MCP plugin, which the shared harness excludes.
35+
36+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
37+
import { type VerifyStack } from '@objectstack/verify';
38+
import { MCPServerPlugin } from '@objectstack/mcp';
39+
import { bootShowcase } from './showcase-boot.js';
40+
import { showcaseAppDefaultSecurity } from './showcase-security.js';
41+
import { catalogPermissionSet } from './catalog-permission-set.js';
42+
43+
const SYS = { isSystem: true } as const;
44+
const OBJECT = 'showcase_project';
45+
const SCRATCH_SET = 'showcase_scratch_mcp_aggregate_budget_deny';
46+
const MEMBER = 'mcp-aggregate-filter@verify.test';
47+
48+
/** The reported body: a filtered count beside an unfiltered one. */
49+
const FILTERED_PAIR = [
50+
{ function: 'count', alias: 'n', filter: { status: 'active' } },
51+
{ function: 'count', alias: 'all' },
52+
];
53+
54+
function mcpBody(method: string, params?: unknown, id = 1) {
55+
return { jsonrpc: '2.0', id, method, ...(params !== undefined ? { params } : {}) };
56+
}
57+
58+
describe('showcase: MCP aggregate_records honours a per-aggregation filter as REST does (#28550)', () => {
59+
let stack: VerifyStack;
60+
let ql: any;
61+
let adminTok: string;
62+
let memberTok: string;
63+
64+
/** POST /api/v1/mcp tools/call; returns `{ isError, payload }` with the text content parsed. */
65+
async function mcpAggregate(token: string, args: Record<string, unknown>) {
66+
const res = await stack.api('/mcp', {
67+
method: 'POST',
68+
headers: {
69+
'Content-Type': 'application/json',
70+
Accept: 'application/json, text/event-stream',
71+
Authorization: `Bearer ${token}`,
72+
},
73+
body: JSON.stringify(mcpBody('tools/call', { name: 'aggregate_records', arguments: args })),
74+
});
75+
expect(res.status, `MCP transport: ${await res.clone().text()}`).toBe(200);
76+
const rpc: any = await res.json();
77+
expect(rpc.error, `JSON-RPC error: ${JSON.stringify(rpc.error)}`).toBeUndefined();
78+
const text: string = rpc.result?.content?.[0]?.text ?? '';
79+
let payload: any;
80+
try {
81+
payload = JSON.parse(text);
82+
} catch {
83+
payload = text;
84+
}
85+
return { isError: rpc.result?.isError === true, payload, text };
86+
}
87+
88+
/** POST /api/v1/data/:object/query with the same aggregation body. */
89+
async function restAggregate(token: string, body: Record<string, unknown>) {
90+
const res = await stack.apiAs(token, 'POST', `/data/${OBJECT}/query`, body);
91+
return { status: res.status, body: (await res.json()) as any };
92+
}
93+
94+
async function systemCount(where: Record<string, unknown>): Promise<number> {
95+
return Number(await ql.count(OBJECT, { where, context: SYS }));
96+
}
97+
98+
beforeAll(async () => {
99+
stack = await bootShowcase({
100+
extraPlugins: [new MCPServerPlugin()],
101+
security: showcaseAppDefaultSecurity(),
102+
});
103+
adminTok = await stack.signIn();
104+
memberTok = await stack.signUp(MEMBER);
105+
ql = await stack.kernel.getServiceAsync('objectql');
106+
107+
// A scratch set that denies READ on `budget` only: the app's everyone
108+
// baseline already grants read on `showcase_project`, so the set adds
109+
// nothing but the field deny. Object-qualified key (a bare `budget` key
110+
// enforces nothing).
111+
const authored = await stack.apiAs(adminTok, 'PUT', `/meta/permission/${SCRATCH_SET}`, {
112+
name: SCRATCH_SET,
113+
label: 'Scratch: FLS read deny on showcase_project.budget (#28550)',
114+
objects: {},
115+
fields: { [`${OBJECT}.budget`]: { readable: false, editable: false } },
116+
});
117+
expect(authored.status, 'scratch set authored through the metadata door').toBeLessThan(300);
118+
const ps = await catalogPermissionSet(ql, SCRATCH_SET);
119+
expect(ps, 'scratch permission set served by the catalog').toBeTruthy();
120+
const memberId = (await ql.findOne('sys_user', { where: { email: MEMBER }, context: SYS }))?.id;
121+
expect(memberId, 'member provisioned').toBeTruthy();
122+
await ql.insert('sys_user_permission_set', { user_id: memberId, permission_set: ps.name }, { context: SYS });
123+
}, 180_000);
124+
125+
afterAll(async () => {
126+
await stack?.stop?.();
127+
});
128+
129+
it('the reported body: MCP and REST give one answer, and the filter narrows it', async () => {
130+
const active = await systemCount({ status: 'active' });
131+
const total = await systemCount({});
132+
// Non-vacuous fixture: the seed must hold rows the filter excludes.
133+
expect(active, 'seeded active projects').toBeGreaterThan(0);
134+
expect(active, 'seeded projects that are not active').toBeLessThan(total);
135+
136+
const mcp = await mcpAggregate(adminTok, { objectName: OBJECT, aggregations: FILTERED_PAIR });
137+
expect(mcp.isError, mcp.text).toBe(false);
138+
const rest = await restAggregate(adminTok, { aggregations: FILTERED_PAIR });
139+
expect(rest.status, JSON.stringify(rest.body)).toBe(200);
140+
141+
const mcpRow = mcp.payload.rows?.[0];
142+
const restRow = (rest.body.records ?? rest.body.data)?.[0];
143+
expect({ n: Number(mcpRow?.n), all: Number(mcpRow?.all) }).toEqual({ n: active, all: total });
144+
expect({ n: Number(restRow?.n), all: Number(restRow?.all) }).toEqual({ n: active, all: total });
145+
});
146+
147+
it('grouped: each group\'s filtered count agrees between MCP and REST', async () => {
148+
const body = {
149+
groupBy: ['health'],
150+
aggregations: [
151+
{ function: 'count', alias: 'active_n', filter: { status: 'active' } },
152+
{ function: 'count', alias: 'all' },
153+
],
154+
};
155+
const mcp = await mcpAggregate(adminTok, { objectName: OBJECT, ...body });
156+
expect(mcp.isError, mcp.text).toBe(false);
157+
const rest = await restAggregate(adminTok, body);
158+
expect(rest.status, JSON.stringify(rest.body)).toBe(200);
159+
const norm = (rows: any[]) =>
160+
[...rows]
161+
.map((r) => ({ health: r.health ?? null, active_n: Number(r.active_n), all: Number(r.all) }))
162+
.sort((a, b) => String(a.health).localeCompare(String(b.health)));
163+
expect(norm(mcp.payload.rows ?? [])).toEqual(norm(rest.body.records ?? rest.body.data ?? []));
164+
});
165+
166+
it('an undeclared entry key is refused by MCP, naming the key', async () => {
167+
const mcp = await mcpAggregate(adminTok, {
168+
objectName: OBJECT,
169+
aggregations: [{ function: 'count', alias: 'n', bogusKey: 1 }],
170+
});
171+
expect(mcp.isError).toBe(true);
172+
expect(mcp.text).toContain('bogusKey');
173+
});
174+
175+
it('a filter on a field the caller cannot read is refused 403 PERMISSION_DENIED on BOTH doors', async () => {
176+
const aggregations = [
177+
{ function: 'count', alias: 'big', filter: { budget: { $gt: 0 } } },
178+
{ function: 'count', alias: 'all' },
179+
];
180+
const rest = await restAggregate(memberTok, { aggregations });
181+
expect(rest.status, JSON.stringify(rest.body)).toBe(403);
182+
expect(rest.body?.error?.code ?? rest.body?.code).toBe('PERMISSION_DENIED');
183+
184+
const mcp = await mcpAggregate(memberTok, { objectName: OBJECT, aggregations });
185+
expect(mcp.isError, `MCP served an answer: ${mcp.text}`).toBe(true);
186+
expect(mcp.payload?.error?.code).toBe('PERMISSION_DENIED');
187+
expect(mcp.payload?.error?.status).toBe(403);
188+
});
189+
190+
it('CONTROL — the same member\'s unfiltered count is served by both doors and agrees', async () => {
191+
const aggregations = [{ function: 'count', alias: 'all' }];
192+
const mcp = await mcpAggregate(memberTok, { objectName: OBJECT, aggregations });
193+
expect(mcp.isError, mcp.text).toBe(false);
194+
const rest = await restAggregate(memberTok, { aggregations });
195+
expect(rest.status, JSON.stringify(rest.body)).toBe(200);
196+
const restAll = Number((rest.body.records ?? rest.body.data)?.[0]?.all);
197+
expect(Number(mcp.payload.rows?.[0]?.all)).toBe(restAll);
198+
expect(restAll).toBeGreaterThan(0);
199+
});
200+
});

0 commit comments

Comments
 (0)