Skip to content

Commit c3c6fa1

Browse files
committed
fix(mcp): read every sent field name by its head on every channel
A dotted name in fields, orderBy, groupBy or an aggregation's field was taken whole, so a name reaching a related field through a served head was named as not recorded. Each sent name is now read by its first segment at the one place the members are decided. Adds a pin for the dotted case and a stdio twin over the shared ADR-0106 case table: the answer names only what the caller can see. Softens the picker's jsdoc to its stated scope. Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude <noreply@anthropic.com>
1 parent ee70211 commit c3c6fa1

4 files changed

Lines changed: 195 additions & 15 deletions

File tree

‎.changeset/35138-mcp-not-recorded.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Metadata-protocol: none
1212

1313
When `query_records`, `aggregate_records` or `get_record` is refused and the call named an object, or a field, that the caller's own schema does not show (the object as `describe_object` serves it to them), the refusal now carries two members beside it, on the HTTP and the stdio server alike:
1414

15-
- `notRecorded`: what is not recorded, as the caller sent it: `{ "object": "<name>" }`, or `{ "object": "<name>", "fields": ["<name>", …] }` for the field names the call sent that the schema does not show, in the order sent.
15+
- `notRecorded`: what is not recorded, as the caller sent it: `{ "object": "<name>" }`, or `{ "object": "<name>", "fields": ["<name>", …] }` for the field names the call sent that the schema does not show, in the order sent. Every sent name is read by its head on every channel (`where`, `fields`, `orderBy`, `groupBy`, an aggregation's `field` and `filter`), so `owner.name` is judged by `owner`, and a dotted name whose head the schema shows is never named.
1616
- `ifNotRecorded`: one sentence, in the caller's language (English, Simplified and Traditional Chinese, Japanese), telling the model to say the data is not recorded, never to report 0 or an empty result for it, and not to answer with another object or field in its place.
1717

1818
The answer names only what the caller can see: both members are built from the names the caller sent and from the caller's served schema, and nothing else. The refusal itself (`isError`, its `code`, `message` and `status`) is unchanged, byte for byte. A read that answers, a refusal about a field the caller's schema shows, a server fault, and a refusal whose schema read cannot be made carry no member. `id`, `created_at` and `updated_at`, which every object answers, are never named.

‎packages/core/src/sentence-locale.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s
44

55
/**
66
* [ADR-0149 M1] The language a platform-composed sentence in a tool's result
7-
* is written in: ONE picker for every executor that hands a caller a finished
8-
* sentence (the dataset tools' `nextStep` and `sourceLine` in
9-
* `@objectstack/service-analytics`, the MCP record tools' `ifNotRecorded` in
10-
* `@objectstack/mcp`), so two members of one answer never disagree on the
11-
* language for the same caller.
7+
* is written in: one picker shared by the dataset tools (`nextStep` and
8+
* `sourceLine` in `@objectstack/service-analytics`) and the MCP record tools
9+
* (`ifNotRecorded` in `@objectstack/mcp`), so those producers never disagree
10+
* on the language for the same caller.
1211
*
1312
* `locales` is the caller's ladder in order, as a door hands it
1413
* ({@link userTextLocalesOf}: the request's locale, then the workspace

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

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1288,10 +1288,19 @@ const ALWAYS_ADDRESSABLE_COLUMNS: ReadonlySet<string> = new Set([
12881288
const WHERE_LOGICAL_OPERATORS: ReadonlySet<string> = new Set(['$and', '$or', '$nor', '$not']);
12891289

12901290
/**
1291-
* The field names a `where` the caller sent addresses on its own object, in
1292-
* order: each condition key's first path segment (a dotted key names a
1293-
* relation's field through its head), through the logical operators. Other
1294-
* `$` keys are operators, never names.
1291+
* The name a sent field name addresses on the object itself: its first path
1292+
* segment. A dotted name (`owner.name`) reaches a relation's field through its
1293+
* head, and the head is what the object's schema lists; the rest is the
1294+
* related object's business. Every channel's names are read this way.
1295+
*/
1296+
function sentFieldHead(name: string): string {
1297+
return name.split('.')[0];
1298+
}
1299+
1300+
/**
1301+
* The field names a `where` the caller sent addresses, in order: each
1302+
* condition key, through the logical operators. Other `$` keys are operators,
1303+
* never names.
12951304
*/
12961305
function whereFieldNames(where: unknown, into: string[]): string[] {
12971306
if (Array.isArray(where)) {
@@ -1304,7 +1313,7 @@ function whereFieldNames(where: unknown, into: string[]): string[] {
13041313
if (WHERE_LOGICAL_OPERATORS.has(key)) whereFieldNames(value, into);
13051314
continue;
13061315
}
1307-
into.push(key.split('.')[0]);
1316+
into.push(key);
13081317
}
13091318
return into;
13101319
}
@@ -1344,7 +1353,8 @@ function aggregateRecordsSentFields(args: {
13441353
* `describe_object` answer). ⛔ So an object or a field the caller's schema
13451354
* does not show is answered exactly as one that does not exist, whatever the
13461355
* refusal beside it says, and nothing the schema shows is ever named or
1347-
* counted. A schema read that throws, or one with no field list, establishes
1356+
* counted. Each sent name is read by its head ({@link sentFieldHead}) on
1357+
* every channel, so a dotted name whose head the schema shows is never named. A schema read that throws, or one with no field list, establishes
13481358
* nothing: no member.
13491359
*/
13501360
async function notRecordedMembersOf(
@@ -1369,7 +1379,8 @@ async function notRecordedMembersOf(
13691379
const name = (f as { name?: unknown } | null)?.name;
13701380
if (typeof name === 'string') shown.add(name);
13711381
}
1372-
const absent = [...new Set(sentFields)].filter((name) => !shown.has(name));
1382+
const heads = sentFields.map(sentFieldHead).filter((head) => head !== '');
1383+
const absent = [...new Set(heads)].filter((name) => !shown.has(name));
13731384
if (absent.length === 0) return undefined;
13741385
notRecorded = { object: objectName, fields: absent };
13751386
}

‎packages/mcp/src/mcp-not-recorded.test.ts‎

Lines changed: 172 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,25 @@
1717
* the HTTP bridge's schema and locale answers are pinned in
1818
* `packages/runtime/src/domains/mcp-not-recorded.test.ts`).
1919
*
20-
* The stdio bridge's locale member is pinned at the bottom.
20+
* The stdio door is pinned over the shared ADR-0106 case table, on the real
21+
* stdio bridge and the real tools, and its locale member at the bottom.
2122
*/
2223

2324
import { describe, expect, it } from 'vitest';
25+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
26+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
27+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
2428
import type { ExecutionContext } from '@objectstack/spec/kernel';
2529
import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts';
30+
import { OBJECT_SCHEMA_MASK_DISABLE_ENV } from '@objectstack/metadata-core';
31+
import {
32+
FLS_CONTRACT_OBJECT,
33+
OBJECT_SCHEMA_MASK_CASES,
34+
securityDoubleFor,
35+
type ObjectSchemaMaskCase,
36+
} from '@objectstack/metadata-core/testing';
2637
import { MCPServerRuntime } from './mcp-server-runtime.js';
27-
import type { McpDataBridge } from './mcp-http-tools.js';
38+
import { registerObjectTools, type McpDataBridge } from './mcp-http-tools.js';
2839
import { createStdioDataBridge } from './stdio-data-bridge.js';
2940

3041
const OBJECT = 'crm_deal';
@@ -148,6 +159,30 @@ describe('[#35138] record reads: a field the caller\'s schema does not show', ()
148159
expect(answer.isError).toBe(true);
149160
expect(answer.payload.notRecorded).toEqual({ object: OBJECT, fields: ['region', 'invoice_total', 'channel'] });
150161
});
162+
163+
it('a dotted name is read by its head on every channel: a head the schema shows is never named', async () => {
164+
// `organization_id` is served; `organization_id.name` reaches the related
165+
// object's field through it. Whatever the door refuses, the call named
166+
// nothing the schema does not show.
167+
const query = await callTool(bridge(), 'query_records', {
168+
objectName: OBJECT,
169+
where: { 'organization_id.name': 'x' },
170+
fields: ['organization_id.name'],
171+
orderBy: [{ field: 'organization_id.name', order: 'asc' }],
172+
});
173+
expect(query.isError).toBe(true);
174+
expect(Object.keys(query.payload)).toEqual(['error']);
175+
const aggregate = await callTool(bridge(), 'aggregate_records', {
176+
objectName: OBJECT,
177+
groupBy: ['organization_id.name', { field: 'organization_id.region' }],
178+
aggregations: [{ function: 'sum', field: 'organization_id.amount', alias: 't', filter: { 'organization_id.kind': 'a' } }],
179+
});
180+
expect(aggregate.isError).toBe(true);
181+
expect(Object.keys(aggregate.payload)).toEqual(['error']);
182+
// A dotted name whose head the schema does not show names that head.
183+
const unknownHead = await callTool(bridge(), 'query_records', { objectName: OBJECT, fields: ['invoice_lines.qty'] });
184+
expect(unknownHead.payload.notRecorded).toEqual({ object: OBJECT, fields: ['invoice_lines'] });
185+
});
151186
});
152187

153188
describe('[#35138] the answer names only what the caller can see — CONTROL', () => {
@@ -260,3 +295,138 @@ describe('[#35138] stdio bridge: userTextLocales', () => {
260295
expect(await bridgeWith({}, () => ({ getDefaultLocale: () => { throw new Error('boom (test)'); } })).userTextLocales!()).toEqual([]);
261296
});
262297
});
298+
299+
/**
300+
* The stdio door, over the shared ADR-0106 case table (`OBJECT_SCHEMA_MASK_CASES`,
301+
* the cases every object-schema exit is judged by): the real stdio bridge,
302+
* its own caller view of the object, and the real tools, with the engine
303+
* refusing every read. A case's absent fields and an unreadable object are
304+
* what that caller cannot see; each is answered with members byte-identical
305+
* to a name that does not exist, the name aside.
306+
*/
307+
describe('[#35138] stdio door: the answer names only what the caller can see', () => {
308+
const STDIO_OBJECT = FLS_CONTRACT_OBJECT.name;
309+
const UNKNOWN_FIELD = 'no_such_field';
310+
const UNKNOWN_OBJECT = 'no_such_object';
311+
const declared = () => JSON.parse(JSON.stringify(FLS_CONTRACT_OBJECT));
312+
const refusing = () => refusal('PERMISSION_DENIED', 403, 'You do not have permission to perform this action.');
313+
314+
async function connect(testCase: ObjectSchemaMaskCase) {
315+
const security = securityDoubleFor(testCase);
316+
const engine = {
317+
find: async () => { throw refusing(); },
318+
findOne: async () => { throw refusing(); },
319+
count: async () => { throw refusing(); },
320+
aggregate: async () => { throw refusing(); },
321+
} as unknown as IDataEngine;
322+
const metadataService = {
323+
listObjects: async () => [declared()],
324+
getObject: async (name: string) => (name === STDIO_OBJECT ? declared() : undefined),
325+
list: async () => [],
326+
} as unknown as IMetadataService;
327+
const bridge = createStdioDataBridge({
328+
engine,
329+
metadataService,
330+
resolvePrincipal: async () => ({ ...testCase.context }) as unknown as ExecutionContext,
331+
...(security ? { security: () => security } : {}),
332+
});
333+
const server = new McpServer({ name: 'pin', version: '0' });
334+
registerObjectTools(server, bridge);
335+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
336+
await server.connect(serverSide);
337+
const client = new Client({ name: 'pin', version: '0' });
338+
await client.connect(clientSide);
339+
const call = async (name: string, args: Record<string, unknown>) => {
340+
const res = (await client.callTool({ name, arguments: args })) as { isError?: boolean; content: Array<{ text: string }> };
341+
const text = res.content[0]!.text;
342+
let payload: any;
343+
try { payload = JSON.parse(text); } catch { payload = undefined; }
344+
return { isError: res.isError === true, text, payload };
345+
};
346+
return { call, close: () => client.close() };
347+
}
348+
349+
async function under<T>(testCase: ObjectSchemaMaskCase, run: () => Promise<T>): Promise<T> {
350+
const previous = process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV];
351+
delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV];
352+
try {
353+
return await run();
354+
} finally {
355+
if (previous !== undefined) process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = previous;
356+
}
357+
}
358+
359+
const fieldCases = OBJECT_SCHEMA_MASK_CASES.filter((c) => c.expect.kind === 'fields' && !c.maskingDisabled);
360+
const objectCases = OBJECT_SCHEMA_MASK_CASES.filter((c) => c.expect.kind === 'absent' && !c.maskingDisabled);
361+
362+
it('the table carries cases of both kinds', () => {
363+
expect(fieldCases.length).toBeGreaterThan(0);
364+
expect(objectCases.length).toBeGreaterThan(0);
365+
});
366+
367+
it.each(fieldCases.map((c) => [c.id, c] as const))(
368+
'%s: a field the caller cannot see gets the members a field that does not exist gets',
369+
async (_id, testCase) => {
370+
const expected = testCase.expect as { present: readonly string[]; absent: readonly string[] };
371+
await under(testCase, async () => {
372+
const session = await connect(testCase);
373+
try {
374+
const ask = (field: string) =>
375+
session.call('query_records', { objectName: STDIO_OBJECT, where: { [field]: 'x' }, fields: [field] });
376+
const unknown = await ask(UNKNOWN_FIELD);
377+
expect(unknown.isError).toBe(true);
378+
expect(unknown.payload.notRecorded).toEqual({ object: STDIO_OBJECT, fields: [UNKNOWN_FIELD] });
379+
for (const field of expected.absent) {
380+
const answer = await ask(field);
381+
expect(answer.isError).toBe(true);
382+
expect(Object.keys(answer.payload)).toEqual(Object.keys(unknown.payload));
383+
expect(membersText(answer.payload).split(field).join(UNKNOWN_FIELD)).toBe(membersText(unknown.payload));
384+
for (const other of expected.absent) {
385+
if (other !== field) expect(mentions(answer.text, other)).toBe(false);
386+
}
387+
}
388+
// CONTROL: a field the caller can see is never named, nor a dotted name through it.
389+
for (const field of expected.present) {
390+
const answer = await session.call('query_records', {
391+
objectName: STDIO_OBJECT,
392+
where: { [field]: 'x' },
393+
fields: [`${field}.label`],
394+
});
395+
expect(answer.isError).toBe(true);
396+
expect(Object.keys(answer.payload)).toEqual(['error']);
397+
}
398+
} finally {
399+
await session.close();
400+
}
401+
});
402+
},
403+
);
404+
405+
it.each(objectCases.map((c) => [c.id, c] as const))(
406+
'%s: an object the caller cannot read gets the members an object that does not exist gets',
407+
async (_id, testCase) => {
408+
await under(testCase, async () => {
409+
const session = await connect(testCase);
410+
try {
411+
for (const [tool, extra] of [
412+
['query_records', {}],
413+
['get_record', { recordId: 'r1' }],
414+
['aggregate_records', { aggregations: [{ function: 'count', alias: 'n' }] }],
415+
] as const) {
416+
const unknown = await session.call(tool, { objectName: UNKNOWN_OBJECT, ...extra });
417+
const hidden = await session.call(tool, { objectName: STDIO_OBJECT, ...extra });
418+
expect(unknown.isError).toBe(true);
419+
expect(hidden.isError).toBe(true);
420+
expect(unknown.payload.notRecorded).toEqual({ object: UNKNOWN_OBJECT });
421+
expect(hidden.payload.notRecorded).toEqual({ object: STDIO_OBJECT });
422+
expect(Object.keys(hidden.payload)).toEqual(Object.keys(unknown.payload));
423+
expect(membersText(hidden.payload).split(STDIO_OBJECT).join(UNKNOWN_OBJECT)).toBe(membersText(unknown.payload));
424+
for (const field of Object.keys(FLS_CONTRACT_OBJECT.fields ?? {})) expect(mentions(hidden.text, field)).toBe(false);
425+
}
426+
} finally {
427+
await session.close();
428+
}
429+
});
430+
},
431+
);
432+
});

0 commit comments

Comments
 (0)