Skip to content

Commit 1e47288

Browse files
committed
test(mcp,runtime,metadata-protocol,dogfood): pin the MCP data paths to the data door's internal-field refusal
Claude-Session: https://claude.ai/code/session_017xRBcVy4VXmkQjn2MGeaWk Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1cf0d93 commit 1e47288

5 files changed

Lines changed: 669 additions & 0 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/runtime': patch
4+
'@objectstack/metadata-protocol': patch
5+
---
6+
7+
fix(mcp,runtime)!: the MCP data tools refuse to filter, sort, group or aggregate on a field declared `internal: true`, with the data door's own 400 INVALID_FIELD, on the stdio transport and on the HTTP bridge's aggregate_records
8+
9+
Clause-②: no (narrowing) — the MCP stdio transport's `query_records` and `aggregate_records`, and the HTTP MCP bridge's `aggregate_records`, refuse a query that evaluates a field declared `internal: true`, which they served before. Nothing is widened.
10+
Metadata-protocol: none
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no metadata an author writes changes meaning: a query position the REST data door already refuses is now refused by the MCP data tools too, with the door's own refusal. The fix for a caller is to query another field, which the refusal says; there is nothing for a migration to rewrite and no tombstone. -->
13+
14+
**BREAKING** accept-set narrowing at the MCP data tools (`@objectstack/mcp`, `@objectstack/runtime`), on the gate the data door already applies (`@objectstack/metadata-protocol`).
15+
16+
- **Before.** A field declared `internal: true` was omitted from every row on every door, and the REST data door (and the HTTP bridge's `query_records`, which reaches it) refused to evaluate one: `400 INVALID_FIELD`. Three MCP mouths hand a caller's query to the engine without reaching that door, and evaluated it: the stdio transport's `query_records` answered a `where` on such a field (`$eq`, `$startsWith`, any operator) and an `orderBy` by it; the stdio transport's `aggregate_records` and the HTTP bridge's `aggregate_records` answered a `where` or an aggregation's own `filter` on it. A group key or an aggregation operand on it was refused by the engine there, in the engine's words.
17+
- **Now.** Each of the three asks the data door's gate (`assertNoInternalFieldEvaluated`, now public on the protocol service) before the engine, for every principal, administrators included, and answers what the door answers for the same query: `400 INVALID_FIELD`, naming the object, the field and the position, in the door's sentence. On MCP the tool result carries that `code`, `status` and message. No row is read.
18+
- **Unchanged.** A query over ordinary fields is served as before; the flagged field is still omitted from every row; a field the caller may not read is still the security middleware's `403 PERMISSION_DENIED`. The engine's privileged lookups that match on such a field (key, token and share-link verification) do not pass through these doors and are untouched. A host that registers no protocol service has no data door for these tools to agree with and serves them as before.
19+
- **Who sees it.** An MCP client that filters, sorts, groups or aggregates on a field its object declares `internal: true`. The built-in objects that declare one are platform `sys_*` objects, which the MCP data tools refuse by default (`allowSystemObjects`); where a host serves them, the same refusal now applies.
20+
21+
**The remedy.** Filter, sort, group and aggregate on another field. A field that must be queryable is not one to declare `internal: true`.
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The stdio data bridge asks the data door's internal-field gate — the
5+
* `protocol` service's `assertNoInternalFieldEvaluated` — before its engine
6+
* reads anything, on `query` (the call's `where` and `orderBy`) and on
7+
* `aggregate` (`where`, `groupBy`, `aggregations`), and a refusal it throws
8+
* reaches the caller as thrown: the tool renders its `code`, `status` and
9+
* sentence, and the engine is never asked.
10+
*
11+
* The gate itself is the protocol's and is pinned there
12+
* (`@objectstack/metadata-protocol`, the public-face cases beside the data
13+
* door's position enumeration), and the whole path on a real stack in
14+
* `@objectstack/dogfood`. This file pins the bridge's half: that it asks, with
15+
* what, before what — and that a host whose protocol has no such face (or that
16+
* registers no protocol) is served exactly as before. Refusals are asserted on
17+
* the envelope, never on a bare throw.
18+
*/
19+
20+
import { describe, it, expect, vi } from 'vitest';
21+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
22+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
23+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
24+
import type { ExecutionContext } from '@objectstack/spec/kernel';
25+
import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts';
26+
import { createStdioDataBridge, type StdioProtocolObjectReads } from './stdio-data-bridge.js';
27+
import { registerObjectTools } from './mcp-http-tools.js';
28+
29+
const OBJECT = 'ifx_vault';
30+
const FLAGGED = 'pin';
31+
const DEF = { name: OBJECT, fields: { name: { type: 'text' }, [FLAGGED]: { type: 'text' } } };
32+
33+
/** The door's refusal as the protocol throws it (fields only; the sentence is the protocol's to pin). */
34+
function doorRefusal(param: string) {
35+
return Object.assign(new Error(`Cannot evaluate '${OBJECT}' by '${FLAGGED}' (${param}): the query was not run.`), {
36+
code: 'INVALID_FIELD', status: 400, httpStatus: 400, object: OBJECT, field: FLAGGED, fields: [FLAGGED], param,
37+
});
38+
}
39+
40+
/** A stand-in for the protocol's gate: refuses any query whose JSON names the flagged field. */
41+
function gate() {
42+
return vi.fn((_object: string, query: Record<string, unknown>) => {
43+
if (JSON.stringify(query).includes(`"${FLAGGED}"`)) throw doorRefusal('filter');
44+
});
45+
}
46+
47+
function makeBridge(protocol?: StdioProtocolObjectReads) {
48+
const engine = {
49+
find: vi.fn(async () => [{ id: 'r1', name: 'alpha' }]),
50+
aggregate: vi.fn(async () => [{ n: 1 }]),
51+
};
52+
const metadataService = { getObject: vi.fn(async (name: string) => (name === OBJECT ? DEF : undefined)) };
53+
const bridge = createStdioDataBridge({
54+
engine: engine as unknown as IDataEngine,
55+
metadataService: metadataService as unknown as IMetadataService,
56+
...(protocol ? { protocol: () => protocol } : {}),
57+
resolvePrincipal: async () => ({ userId: 'u1', isSystem: false }) as unknown as ExecutionContext,
58+
});
59+
return { bridge, engine };
60+
}
61+
62+
const refusalOf = async (run: () => Promise<unknown>) => {
63+
const err: any = await run().then(() => undefined, (e: unknown) => e);
64+
expect(err, 'the call resolved: the gate\'s refusal did not reach the caller').toBeDefined();
65+
return { code: err.code, status: err.status, field: err.field, object: err.object };
66+
};
67+
const REFUSED = { code: 'INVALID_FIELD', status: 400, field: FLAGGED, object: OBJECT };
68+
69+
describe('the stdio bridge asks the protocol\'s internal-field gate before the engine', () => {
70+
it('query: the gate is asked with the call\'s where and orderBy, and its refusal stops the read', async () => {
71+
const assertNoInternalFieldEvaluated = gate();
72+
const { bridge, engine } = makeBridge({ assertNoInternalFieldEvaluated });
73+
const where = { [FLAGGED]: { $startsWith: 'x' } };
74+
const orderBy = [{ field: 'name', order: 'asc' as const }];
75+
expect(await refusalOf(() => bridge.query(OBJECT, { where, orderBy, limit: 5 }))).toEqual(REFUSED);
76+
expect(assertNoInternalFieldEvaluated).toHaveBeenCalledWith(OBJECT, { where, orderBy });
77+
expect(engine.find).not.toHaveBeenCalled();
78+
79+
const sorted = [{ field: FLAGGED, order: 'desc' as const }];
80+
expect(await refusalOf(() => bridge.query(OBJECT, { orderBy: sorted }))).toEqual(REFUSED);
81+
expect(engine.find).not.toHaveBeenCalled();
82+
});
83+
84+
it('aggregate: the gate is asked with where, groupBy and aggregations, and its refusal stops the aggregate', async () => {
85+
const assertNoInternalFieldEvaluated = gate();
86+
const { bridge, engine } = makeBridge({ assertNoInternalFieldEvaluated });
87+
const bodies = [
88+
{ where: { [FLAGGED]: 'x' }, aggregations: [{ function: 'count' as const, alias: 'n' }] },
89+
{ groupBy: [FLAGGED], aggregations: [{ function: 'count' as const, alias: 'n' }] },
90+
{ aggregations: [{ function: 'max' as const, field: FLAGGED, alias: 'm' }] },
91+
{ aggregations: [{ function: 'count' as const, alias: 'n', filter: { [FLAGGED]: 'x' } }] },
92+
];
93+
for (const body of bodies) {
94+
expect(await refusalOf(() => bridge.aggregate!(OBJECT, body))).toEqual(REFUSED);
95+
expect(assertNoInternalFieldEvaluated).toHaveBeenLastCalledWith(OBJECT, {
96+
where: (body as { where?: unknown }).where,
97+
groupBy: (body as { groupBy?: unknown }).groupBy,
98+
aggregations: body.aggregations,
99+
});
100+
}
101+
expect(engine.aggregate).not.toHaveBeenCalled();
102+
});
103+
104+
it('CONTROL — a query the gate passes reaches the engine unchanged, on both verbs', async () => {
105+
const assertNoInternalFieldEvaluated = gate();
106+
const { bridge, engine } = makeBridge({ assertNoInternalFieldEvaluated });
107+
const where = { name: 'alpha' };
108+
await bridge.query(OBJECT, { where, orderBy: [{ field: 'name', order: 'asc' }] });
109+
expect(engine.find).toHaveBeenCalledTimes(1);
110+
expect((engine.find.mock.calls[0] as unknown[])[1]).toMatchObject({ where, orderBy: [{ field: 'name', order: 'asc' }] });
111+
await bridge.aggregate!(OBJECT, { where, groupBy: ['name'], aggregations: [{ function: 'count', alias: 'n' }] });
112+
expect(engine.aggregate).toHaveBeenCalledTimes(1);
113+
expect(assertNoInternalFieldEvaluated).toHaveBeenCalledTimes(2);
114+
});
115+
116+
it('CONTROL — no protocol, or one without the face: served as before (no door to agree with)', async () => {
117+
for (const protocol of [undefined, {} as StdioProtocolObjectReads]) {
118+
const { bridge, engine } = makeBridge(protocol);
119+
await bridge.query(OBJECT, { where: { [FLAGGED]: 'x' } });
120+
await bridge.aggregate!(OBJECT, { where: { [FLAGGED]: 'x' }, aggregations: [{ function: 'count', alias: 'n' }] });
121+
expect(engine.find).toHaveBeenCalledTimes(1);
122+
expect(engine.aggregate).toHaveBeenCalledTimes(1);
123+
}
124+
});
125+
126+
it('query_records and aggregate_records render the gate\'s refusal as its envelope', async () => {
127+
const { bridge, engine } = makeBridge({ assertNoInternalFieldEvaluated: gate() });
128+
const server = new McpServer({ name: 'pin', version: '0' });
129+
registerObjectTools(server, bridge);
130+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
131+
await server.connect(serverSide);
132+
const client = new Client({ name: 'pin', version: '0' });
133+
await client.connect(clientSide);
134+
try {
135+
for (const [name, args] of [
136+
['query_records', { objectName: OBJECT, where: { [FLAGGED]: 'x' } }],
137+
['aggregate_records', { objectName: OBJECT, groupBy: [FLAGGED], aggregations: [{ function: 'count', alias: 'n' }] }],
138+
] as const) {
139+
const res = (await client.callTool({ name, arguments: args })) as { isError?: boolean; content: Array<{ text: string }> };
140+
expect(res.isError, name).toBe(true);
141+
const { error } = JSON.parse(res.content[0]!.text) as { error: { code: unknown; status: unknown; message: string } };
142+
expect({ code: error.code, status: error.status }).toEqual({ code: 'INVALID_FIELD', status: 400 });
143+
expect(error.message).toBe(doorRefusal('filter').message);
144+
}
145+
expect(engine.find).not.toHaveBeenCalled();
146+
expect(engine.aggregate).not.toHaveBeenCalled();
147+
} finally {
148+
await client.close();
149+
}
150+
});
151+
});

‎packages/metadata-protocol/src/protocol.data-door-internal-field-positions.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,3 +251,53 @@ describe('[#22646] CONTROL — ordinary fields through a relation and at depth a
251251
}
252252
}
253253
});
254+
255+
/**
256+
* The PUBLIC face the MCP data mouths ask (`assertNoInternalFieldEvaluated`):
257+
* the MCP stdio transport's `query_records` / `aggregate_records` and the HTTP
258+
* bridge's `aggregate_records` hand a caller's query to the engine without
259+
* passing through `findData`, so each asks this method of the `protocol`
260+
* service first. It must be the door's own verdict, not a second one: for each
261+
* canonical query those mouths can send, the face throws exactly what
262+
* `findData` throws for the same query (code, status, object, field, param,
263+
* message), and an ordinary-field query passes it without a throw.
264+
*/
265+
describe('the public internal-field face answers exactly what findData answers', () => {
266+
const shapes: Array<[string, Record<string, unknown>]> = [
267+
['filter ($eq)', { where: { [F]: { $eq: 'h1' } } }],
268+
['filter ($startsWith)', { where: { [F]: { $startsWith: 'h' } } }],
269+
['sort (orderBy node)', { orderBy: [{ field: F, order: 'asc' }] }],
270+
['aggregate where', { where: { [F]: 'h1' }, aggregations: [{ function: 'count', alias: 'n' }] }],
271+
['group key', { groupBy: [F], aggregations: [{ function: 'count', alias: 'n' }] }],
272+
['aggregation operand', { aggregations: [{ function: 'max', field: F, alias: 'm' }] }],
273+
["aggregation's own filter", { aggregations: [{ function: 'count', alias: 'n', filter: { [F]: 'h1' } }] }],
274+
['relation condition onto the target', { where: { vault_id: { [F]: 'h1' } } }],
275+
];
276+
const envelope = (e: any) => ({ code: e?.code, status: e?.status, object: e?.object, field: e?.field, param: e?.param, message: e?.message });
277+
278+
for (const [label, query] of shapes) {
279+
it(`${label}: the face throws the door's refusal, field for field`, async () => {
280+
const object = label.startsWith('relation') ? 'pv_holder' : 'pv_vault';
281+
const { p, find, aggregate } = makeProtocol();
282+
const door = await refusal(() => p.findData({ object, query: { ...query } }));
283+
let thrown: unknown;
284+
try { p.assertNoInternalFieldEvaluated(object, { ...query }); } catch (e) { thrown = e; }
285+
expect(thrown, 'the face let a position the door refuses through').toBeDefined();
286+
expect(envelope(thrown)).toEqual(envelope(door));
287+
expect(envelope(thrown)).toMatchObject({ code: 'INVALID_FIELD', status: 400 });
288+
expect(find).not.toHaveBeenCalled();
289+
expect(aggregate).not.toHaveBeenCalled();
290+
});
291+
}
292+
293+
it('CONTROL — ordinary fields in every position pass the face without a throw', () => {
294+
const { p } = makeProtocol();
295+
expect(() => p.assertNoInternalFieldEvaluated('pv_vault', {
296+
where: { name: { $startsWith: 'a' } },
297+
orderBy: [{ field: 'name', order: 'asc' }],
298+
groupBy: ['name'],
299+
aggregations: [{ function: 'max', field: 'rank', alias: 'm', filter: { name: 'alpha' } }],
300+
})).not.toThrow();
301+
expect(() => p.assertNoInternalFieldEvaluated('pv_holder', { where: { vault_id: { name: 'alpha' } } })).not.toThrow();
302+
});
303+
});

0 commit comments

Comments
 (0)