Skip to content

Commit 084156d

Browse files
feat(mcp): aggregate_records names a lookup group's record beside its id, read as the caller (#35202)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8AJJJRiYjshMUNgyMZSqBsr)_ Refs #35138 (item lookup group name) Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:MCP 的 `aggregate_records` 按 lookup / master_detail 字段分组时,每个分组在键旁多出 `KEY__label`,值为被引用记录的名称(被引用对象的名称字段,按 ADR-0079 解析);工具描述要求模型用 `__label` 称呼该分组、永不写出 id,没有 `__label` 时说明该记录无法命名。HTTP 与 stdio 两个入口共用同一处理函数。 - 为什么改:#35138 W0 决定表「lookup 分组名称」一行:托管问数工具发现分组只给 id 时模型会把 id 当答案念出来;这一项从托管层挪进框架,开源 MCP 客户端也能拿到,拼写与托管 `aggregate_data` 相同。 - 风险与回滚:名称以调用方身份、经同一个 bridge 读取(一次批量读),不以任何其他权限读;读不到的记录与已删除的记录同样没有标签,答案里没有任何东西区分二者;对象、名称字段或 lookup 字段对调用方不可见、目标是工具不读的系统对象、或读取失败时,结果与之前完全一致。已有成员 `rows`/`totalGroups`/`truncated`/`currencies` 不变。回滚即 revert 本 PR。 - 先看:① `packages/mcp/src/mcp-http-tools.ts` 的 `recordNamesAsCaller`(读取走 `bridge.query`、可见性检查与失败即无标签);② 同文件 `withLookupGroupLabels`(只对截断后实际返回的分组读名称,非 lookup 键不加标签);③ `aggregate_records` 处理函数里传入的 `readGuard` 谓词。 - 两分钟验证:`pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-http-tools.aggregation-entry.test.ts`,预期 27 个测试全绿,其中 8 个是本 PR 新增的 lookup 名称用例。 - 需要你做的:无,席位落地。 ## What changes `aggregate_records` (`packages/mcp/src/mcp-http-tools.ts`, one handler serving both the HTTP and the stdio door) now names the record behind each lookup group key: - A group key is a lookup key when the caller's served schema (`servedObjectDefinitionOf`, the member #35186 reads) shows it as a `lookup` or `master_detail` field with a `reference`. A date-bucketed key is never one. - Beside each such key the group carries `KEY__label`, where KEY is the group column (the key's alias when the call gives one). Its value is the referenced record's value of the referenced object's name field, resolved with `resolveDisplayField` from `@objectstack/spec/data` (ADR-0079: `nameField`, then `displayNameField`, then the derived title field) over the referenced object as the caller is served it. - The names are read as the caller: one `bridge.query` per referenced object, `where: { id: { $in: ids } }`, `fields: ['id', NAME_FIELD]`, `limit: ids.length`, for the groups the tool serves (after the row cap), through the same bridge and context as the aggregate. Two lookup keys on the same referenced object share that one read. This is the read shape `delete_records` already uses for an id list. - A label is present only for a key whose record that read returns with a non-blank name. Every other key carries no label and nothing else in the answer changes. - No label is added, and the result is exactly as before, when: the lookup field is not served to the caller; the referenced object or its name field is not served to the caller; the referenced object is one this tool does not read (the same `readGuard` the read tools apply, so a `sys_` object without the AI read opt-in is never read for a name); or the read throws or answers no records list. A name read never fails the aggregate. - A column the aggregate already answers under the label's name is never overwritten. - The tool description gains: a lookup group carries `KEY__label` beside the id, read with the caller's own permissions; name such a group by its `__label`, never by the id; where a group has no `__label`, its record cannot be named, so say that rather than quoting the id. The type stays local to `packages/mcp`; the `aggregate_records` result has no schema in `packages/spec`, and no guidance text enters the spec (ADR-0149 M1). No existing member is renamed or removed. ## Tests <details><summary>New pins: top-level describe in packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts (the shared aggregate_records harness)</summary> - a lookup and a master-detail group carry `KEY__label`: the referenced record's name field (`nameField: 'title'`), placed right after the key; an aliased key is labelled by its alias - CONTROL: a second key that is not a lookup carries no label, even where its value is a record id - CONTROL: a record the caller's read does not return and a deleted record answer the same, with no label (the two answers compared whole and as JSON text) - CONTROL: a record whose name is blank, and a null key, carry no label - CONTROL: a referenced object, a name field or a lookup field the caller is not served, or a system object the tool does not read, answers exactly as before and makes no name read - CONTROL: a name read that throws, or answers no records list, answers exactly as before - the names are one batched read of the referenced object, for the groups served (60 groups, cap 50: one read, 52 ids, two keys on one object), as the caller - the stdio door: through `createStdioDataBridge` and a real MCP client, the name read reaches the engine as one `find` under the principal's own context, and only the record that read returns is labelled </details> <details><summary>Ablations (one or more per pin, through scripts/ablation-replace.mjs; each restored to the HEAD blob a3381bf)</summary> Each mutation landed (anchor 1 then 0, blob changed) and the file went red; every restore read `ok restored: blob == HEAD (a3381bf) and git diff HEAD is empty`. - A, the label never set: 5 failed (the label pin, both CONTROLs that also expect a label, the batched-read pin, the stdio pin). - B, names applied to any column: 1 failed (the non-lookup CONTROL). - C, a placeholder label for a key with no name: 3 failed (the unreadable/deleted CONTROL, the batched-read pin, the stdio pin). - D1, the name field's served check removed: 1 failed (the not-served CONTROL). - D2, the referenced object's read guard replaced by `true`: 1 failed (the not-served CONTROL, its system-object half). - D3, the lookup-type check replaced by a field-name match: 1 failed (the not-served CONTROL, its lookup-field half). - E, the read's catch rethrows: 1 failed (the throwing-read CONTROL). - F1, one read per id: 2 failed (the batched-read pin, the stdio pin). - F2, names read for every group before the cap: 2 failed (the batched-read pin, and #35186's cap pin). The unreadable/deleted CONTROL is red under C on its shape half. Its comparison half cannot be turned red by a mutation inside the handler, because the handler sees only what the caller's read returns. </details> ## Acceptance notes - **#35193 (#35144, area o1-C) shares this handler and is still open.** `overlap-check` reports conflicts with it in `mcp-http-tools.ts` and `mcp-http-tools.aggregation-entry.test.ts`, both adjacent insertions. Whichever PR merges `main` second keeps both behaviours: the cut path's result (`aggregateGroups`) gets its served rows labelled the same way, through `withLookupGroupLabels(bridge, ROWS, groupBy, FIELDS, READ_GUARD_PREDICATE)` over `servedFieldsOf(bridge, objectName)`; the default path keeps `groupCount` from #35193 and the labels from here. - **Aliased keys.** The label member is named after the group column, which is the alias when the call gives one (`{ field: 'parent', alias: 'p' }` gives `p__label`), so the label always sits beside the key it names. - **Name values.** A non-blank string is a name; a finite number (an explicit numeric name field) is served as its string. Anything else is no name. - **Stdio query cost.** The stdio bridge's `query` counts the match when a `limit` is passed, so the one name read there is a find plus a count of the same filter, both as the caller. The `limit` is kept because it is the read shape `delete_records` uses and it bounds the read on any host page size. ## Verification All readings below are at head `90e185aa5b`, the final commit. <details><summary>Local subset</summary> - `pnpm --filter @objectstack/mcp typecheck`, then `vitest run --maxWorkers=2` over the whole package, under the shared verify lock: `VERDICT command-exit 0`; `Test Files 72 passed (72)`, `Tests 1299 passed (1299)`; `check:test-typecheck: OK`. - `src/mcp-http-tools.aggregation-entry.test.ts`: `Tests 27 passed (27)`. - `dispatch-gates --commands`: 68 derived families, each exit code captured before any pipe. `--ran` reconciliation: `68 derived, 67 run, 1 NOT-MEASURED, 0 UNRUN`. - NOT MEASURED: `check:dual-build-cjs-loads`, exit 3, `PREREQUISITE NOT MET` (it reads every package's `dist`, and only the mcp closure was built). CI runs it. - `node scripts/check-nul-bytes.mjs`: OK. - `overlap-check.mjs`: `VERDICT overlap exit 1`, against origin/main `ba6556c617` (merges cleanly) and two open PR heads: #35179 merges cleanly; #35193 conflicts as described above. - `test:repo` not run locally: the diff touches no repo-project test and the derivation names none; CI's `Test Core` runs it. </details> The families CI runs (`Lint & Repo Gates`, `Test Core`, `Build Core`, the type-check lanes) are left to this PR's check-runs. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2d33205 commit 084156d

3 files changed

Lines changed: 383 additions & 7 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/mcp': patch
3+
---
4+
5+
feat(mcp): `aggregate_records` names the record of a lookup group beside its id, read as the caller
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
When the MCP `aggregate_records` tool groups by a `lookup` or `master_detail` field, each group now carries a new member `<key>__label` beside the key: the name of the referenced record, from the referenced object's name field (`nameField`, as ADR-0079 resolves it). `<key>` is the group column, which is the key's alias when the call gives one. The same spelling is used by the hosted ask tools, so one prompt reads both. This holds on both the HTTP and the stdio door.
11+
12+
The name is read as the caller, through the same bridge and context as the aggregate, in one batched read of the referenced object for the groups the tool serves. Nothing is read with other rights, so the caller's object, field and record permissions apply as they do for any read the caller makes.
13+
14+
- A label is present only for a key whose record the caller's read returns with a non-blank name. Any other key carries no label, and nothing else in the answer changes.
15+
- No label is added, and the answer is exactly as before, when the caller is not served the referenced object, its name field or the lookup field, when the referenced object is a system object the tool does not read, or when the read fails. A failed name read never fails the aggregate.
16+
17+
The tool description now tells a model to name such a group by its `__label`, never by the id, and to say the record cannot be named where no label is present. Existing members (`rows`, `totalGroups`, `truncated`, `currencies`) are unchanged.

‎packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts‎

Lines changed: 210 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,19 @@
3333
* `distinct` as a schema nothing satisfies (`not: {}`), with the removal text.
3434
*/
3535

36-
import { describe, it, expect, beforeEach } from 'vitest';
36+
import { describe, it, expect, beforeEach, vi } from 'vitest';
37+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
38+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
39+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
3740

3841
import { AggregationNodeSchema } from '@objectstack/spec/data';
42+
import type { ExecutionContext } from '@objectstack/spec/kernel';
43+
import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts';
3944

4045
import { MCPServerRuntime } from './mcp-server-runtime.js';
46+
import { registerObjectTools } from './mcp-http-tools.js';
4147
import type { McpDataBridge } from './mcp-http-tools.js';
48+
import { createStdioDataBridge } from './stdio-data-bridge.js';
4249

4350
interface RecordingBridge extends McpDataBridge {
4451
calls: any[];
@@ -359,3 +366,205 @@ describe('aggregate_records — select groups in declared option order, a fixed
359366
expect(bridge.schemaReads).toBe(0);
360367
});
361368
});
369+
370+
/**
371+
* [#35138] A group keyed by a lookup (or master-detail) field names its
372+
* record beside the id, in `<key>__label`: the referenced record's name field
373+
* (ADR-0079), read AS THE CALLER in one batched `query` of the referenced
374+
* object, through the same bridge as the aggregate.
375+
*
376+
* The rule pinned: a label is present only for a key whose record the
377+
* caller's read returns with a non-blank name; every other key answers the
378+
* same (no label), and nothing else in the answer changes. A referenced
379+
* object, name field or lookup field the caller is not served, a referenced
380+
* object this tool does not read, and a read that throws all leave the answer
381+
* exactly as it was before.
382+
*
383+
* Both doors serve the tool from one handler: the HTTP door over a recording
384+
* bridge below, and the stdio door over its own bridge and a stand-in engine
385+
* at the foot of this block.
386+
*/
387+
describe('aggregate_records — a lookup group names its record beside the id, read as the caller (#35138)', () => {
388+
const DEAL = {
389+
name: 'deal',
390+
fields: {
391+
account: { type: 'lookup', reference: 'account' },
392+
parent: { type: 'master_detail', reference: 'account' },
393+
partner: { type: 'lookup', reference: 'sys_partner' },
394+
stage: { type: 'select', options: [{ value: 'won' }, { value: 'lost' }] },
395+
ref_code: { type: 'text' },
396+
amount: { type: 'number' },
397+
},
398+
};
399+
const ACCOUNT = { name: 'account', nameField: 'title', fields: { title: { type: 'text' }, code: { type: 'text' } } };
400+
/** Every account record that exists, and the ones the caller's read returns. */
401+
const STORE: Record<string, string> = { a1: 'Acme', a2: 'Globex', a3: ' ', a4: 'Initech' };
402+
403+
interface LookupBridge extends RecordingBridge {
404+
reads: Array<[string, any]>;
405+
}
406+
407+
function lookupBridge(
408+
rows: unknown[],
409+
opts: { readable?: (id: string) => boolean; store?: Record<string, string>; defs?: Record<string, unknown> } = {},
410+
): LookupBridge {
411+
const bridge = makeBridge() as LookupBridge;
412+
const readable = opts.readable ?? (() => true);
413+
const store = opts.store ?? STORE;
414+
const defs: Record<string, unknown> = opts.defs ?? { deal: DEAL, account: ACCOUNT };
415+
bridge.reads = [];
416+
bridge.aggregate = async (object: string, o: any) => {
417+
bridge.calls.push([object, o]);
418+
return rows;
419+
};
420+
bridge.servedObjectDefinitionOf = async (name: string) => (defs[name] ?? null) as Record<string, unknown> | null;
421+
bridge.query = async (object: string, o: any) => {
422+
bridge.reads.push([object, o]);
423+
const ids: string[] = o?.where?.id?.$in ?? [];
424+
const records = ids
425+
.filter((id) => Object.prototype.hasOwnProperty.call(store, id) && readable(id))
426+
.map((id) => ({ id, title: store[id] }));
427+
return { object, records, total: records.length };
428+
};
429+
return bridge;
430+
}
431+
432+
async function answer(bridge: RecordingBridge, args: Record<string, unknown>) {
433+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
434+
const { refused, text } = await aggregate(runtime, bridge, { objectName: 'deal', ...args });
435+
expect(refused, text).toBe(false);
436+
return JSON.parse(text) as { rows: Array<Record<string, unknown>>; totalGroups: number; truncated?: true };
437+
}
438+
439+
const COUNT = [{ function: 'count', alias: 'n' }];
440+
441+
it('a lookup and a master-detail group carry `<key>__label`: the referenced record\'s name field, beside the key', async () => {
442+
const bridge = lookupBridge([{ account: 'a1', n: 3 }, { account: 'a2', n: 1 }]);
443+
const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account'] });
444+
expect(out.rows).toEqual([{ account: 'a1', account__label: 'Acme', n: 3 }, { account: 'a2', account__label: 'Globex', n: 1 }]);
445+
expect(Object.keys(out.rows[0]!)).toEqual(['account', 'account__label', 'n']);
446+
447+
const aliased = await answer(lookupBridge([{ p: 'a2', n: 2 }]), { aggregations: COUNT, groupBy: [{ field: 'parent', alias: 'p' }] });
448+
expect(aliased.rows).toEqual([{ p: 'a2', p__label: 'Globex', n: 2 }]);
449+
});
450+
451+
it('CONTROL — a second key that is not a lookup carries no label, even where its value is a record id', async () => {
452+
const bridge = lookupBridge([{ account: 'a1', ref_code: 'a2', n: 2 }, { account: 'a2', ref_code: 'a1', n: 1 }]);
453+
const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account', 'ref_code'] });
454+
expect(out.rows).toEqual([
455+
{ account: 'a1', account__label: 'Acme', ref_code: 'a2', n: 2 },
456+
{ account: 'a2', account__label: 'Globex', ref_code: 'a1', n: 1 },
457+
]);
458+
for (const row of out.rows) expect(row).not.toHaveProperty('ref_code__label');
459+
});
460+
461+
it('CONTROL — a record the caller\'s read does not return and a deleted record answer the same, with no label', async () => {
462+
const rows = [{ account: 'a1', n: 1 }, { account: 'a4', n: 2 }];
463+
const args = { aggregations: COUNT, groupBy: ['account'] };
464+
// a4 exists, and the caller's read does not return it.
465+
const unreadable = await answer(lookupBridge(rows, { readable: (id) => id !== 'a4' }), args);
466+
// a4 no longer exists.
467+
const { a4: _deleted, ...rest } = STORE;
468+
const deleted = await answer(lookupBridge(rows, { store: rest }), args);
469+
expect(unreadable).toEqual(deleted);
470+
expect(JSON.stringify(unreadable)).toBe(JSON.stringify(deleted));
471+
expect(unreadable.rows[1]).toEqual({ account: 'a4', n: 2 });
472+
expect(unreadable.rows[0]).toEqual({ account: 'a1', account__label: 'Acme', n: 1 });
473+
});
474+
475+
it('CONTROL — a record whose name is blank, and a null key, carry no label', async () => {
476+
const out = await answer(lookupBridge([{ account: 'a3', n: 1 }, { account: null, n: 4 }]), { aggregations: COUNT, groupBy: ['account'] });
477+
expect(out.rows).toEqual([{ account: 'a3', n: 1 }, { account: null, n: 4 }]);
478+
});
479+
480+
it('CONTROL — a referenced object, a name field or a lookup field the caller is not served, or a system object, answers as before', async () => {
481+
const rows = [{ account: 'a1', n: 1 }, { partner: 'p1', n: 2 }];
482+
const args = { aggregations: COUNT, groupBy: ['account'] };
483+
const { account: _lookup, ...dealWithout } = DEAL.fields;
484+
const cases: Array<Record<string, unknown>> = [
485+
{ deal: DEAL },
486+
{ deal: DEAL, account: { ...ACCOUNT, fields: { code: { type: 'text' } } } },
487+
{ deal: { ...DEAL, fields: dealWithout }, account: ACCOUNT },
488+
];
489+
for (const defs of cases) {
490+
const bridge = lookupBridge(rows, { defs });
491+
const out = await answer(bridge, args);
492+
expect(out).toEqual({ rows, totalGroups: 2 });
493+
expect(bridge.reads).toEqual([]);
494+
}
495+
// A referenced `sys_*` object this tool does not read is never read for a name.
496+
const system = lookupBridge(rows, { defs: { deal: DEAL, sys_partner: ACCOUNT } });
497+
const out = await answer(system, { aggregations: COUNT, groupBy: ['partner'] });
498+
expect(out).toEqual({ rows, totalGroups: 2 });
499+
expect(system.reads).toEqual([]);
500+
});
501+
502+
it('CONTROL — a name read that throws, or answers no records list, answers as before', async () => {
503+
const rows = [{ account: 'a1', n: 1 }];
504+
const throwing = lookupBridge(rows);
505+
throwing.query = async () => { throw new Error('read refused'); };
506+
const shapeless = lookupBridge(rows);
507+
shapeless.query = async () => [{ id: 'a1', title: 'Acme' }];
508+
for (const bridge of [throwing, shapeless]) {
509+
const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account'] });
510+
expect(out).toEqual({ rows, totalGroups: 1 });
511+
}
512+
});
513+
514+
it('the names are one batched read of the referenced object, for the groups served, as the caller', async () => {
515+
const rows = Array.from({ length: 60 }, (_, i) => ({ account: `x${i}`, parent: i % 2 === 0 ? 'a1' : 'a2', n: i }));
516+
const bridge = lookupBridge(rows, { store: { ...STORE, x0: 'First', x49: 'Last served', x50: 'Past the cap' } });
517+
const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account', 'parent'] });
518+
expect(bridge.reads).toHaveLength(1);
519+
const [object, read] = bridge.reads[0]!;
520+
expect(object).toBe('account');
521+
expect(read.fields).toEqual(['id', 'title']);
522+
expect(read.limit).toBe(52);
523+
expect([...read.where.id.$in].sort()).toEqual([...rows.slice(0, 50).map((r) => r.account), 'a1', 'a2'].sort());
524+
expect(out.rows).toHaveLength(50);
525+
expect(out.rows[0]).toEqual({ account: 'x0', account__label: 'First', parent: 'a1', parent__label: 'Acme', n: 0 });
526+
expect(out.rows[49]).toMatchObject({ account__label: 'Last served', parent__label: 'Globex' });
527+
expect(out.rows[1]).toEqual({ account: 'x1', parent: 'a2', parent__label: 'Globex', n: 1 });
528+
});
529+
530+
it('the stdio door: the name is read through the stdio bridge under the caller\'s own context', async () => {
531+
const principal = { userId: 'u1', isSystem: false } as unknown as ExecutionContext;
532+
const engine = {
533+
aggregate: vi.fn(async () => [{ account: 'a1', n: 2 }, { account: 'a4', n: 1 }]),
534+
// The caller's read returns a1 only.
535+
find: vi.fn(async (_object: string, query: any) =>
536+
((query?.where?.id?.$in ?? []) as string[]).filter((id) => id === 'a1').map((id) => ({ id, title: STORE[id] }))),
537+
};
538+
const defs: Record<string, unknown> = { deal: DEAL, account: ACCOUNT };
539+
const metadataService = { getObject: vi.fn(async (name: string) => defs[name]) };
540+
const bridge = createStdioDataBridge({
541+
engine: engine as unknown as IDataEngine,
542+
metadataService: metadataService as unknown as IMetadataService,
543+
resolvePrincipal: async () => principal,
544+
});
545+
const server = new McpServer({ name: 'pin', version: '0' });
546+
registerObjectTools(server, bridge);
547+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
548+
await server.connect(serverSide);
549+
const client = new Client({ name: 'pin', version: '0' });
550+
await client.connect(clientSide);
551+
try {
552+
const res = (await client.callTool({
553+
name: 'aggregate_records',
554+
arguments: { objectName: 'deal', aggregations: COUNT, groupBy: ['account'] },
555+
})) as { isError?: boolean; content: Array<{ text: string }> };
556+
expect(res.isError, res.content[0]?.text).not.toBe(true);
557+
expect(JSON.parse(res.content[0]!.text)).toEqual({
558+
rows: [{ account: 'a1', account__label: 'Acme', n: 2 }, { account: 'a4', n: 1 }],
559+
totalGroups: 2,
560+
});
561+
expect(engine.find).toHaveBeenCalledTimes(1);
562+
const [object, query, opts] = engine.find.mock.calls[0] as unknown as [string, any, unknown];
563+
expect(object).toBe('account');
564+
expect(query).toMatchObject({ where: { id: { $in: ['a1', 'a4'] } }, fields: ['id', 'title'], limit: 2 });
565+
expect(opts).toEqual({ context: principal });
566+
} finally {
567+
await client.close();
568+
}
569+
});
570+
});

0 commit comments

Comments
 (0)