diff --git a/.changeset/mcp-aggregate-lookup-group-labels.md b/.changeset/mcp-aggregate-lookup-group-labels.md new file mode 100644 index 00000000000..b38fb948ceb --- /dev/null +++ b/.changeset/mcp-aggregate-lookup-group-labels.md @@ -0,0 +1,17 @@ +--- +'@objectstack/mcp': patch +--- + +feat(mcp): `aggregate_records` names the record of a lookup group beside its id, read as the caller + +Clause-②: yes (widening) +Metadata-protocol: none + +When the MCP `aggregate_records` tool groups by a `lookup` or `master_detail` field, each group now carries a new member `__label` beside the key: the name of the referenced record, from the referenced object's name field (`nameField`, as ADR-0079 resolves it). `` 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. + +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. + +- 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. +- 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. + +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. diff --git a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts index 163e9aea838..2a89369a29f 100644 --- a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts +++ b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts @@ -33,12 +33,19 @@ * `distinct` as a schema nothing satisfies (`not: {}`), with the removal text. */ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { AggregationNodeSchema } from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { registerObjectTools } from './mcp-http-tools.js'; import type { McpDataBridge } from './mcp-http-tools.js'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; interface RecordingBridge extends McpDataBridge { calls: any[]; @@ -359,3 +366,205 @@ describe('aggregate_records — select groups in declared option order, a fixed expect(bridge.schemaReads).toBe(0); }); }); + +/** + * [#35138] A group keyed by a lookup (or master-detail) field names its + * record beside the id, in `__label`: the referenced record's name field + * (ADR-0079), read AS THE CALLER in one batched `query` of the referenced + * object, through the same bridge as the aggregate. + * + * The rule pinned: a label is present only for a key whose record the + * caller's read returns with a non-blank name; every other key answers the + * same (no label), and nothing else in the answer changes. A referenced + * object, name field or lookup field the caller is not served, a referenced + * object this tool does not read, and a read that throws all leave the answer + * exactly as it was before. + * + * Both doors serve the tool from one handler: the HTTP door over a recording + * bridge below, and the stdio door over its own bridge and a stand-in engine + * at the foot of this block. + */ +describe('aggregate_records — a lookup group names its record beside the id, read as the caller (#35138)', () => { + const DEAL = { + name: 'deal', + fields: { + account: { type: 'lookup', reference: 'account' }, + parent: { type: 'master_detail', reference: 'account' }, + partner: { type: 'lookup', reference: 'sys_partner' }, + stage: { type: 'select', options: [{ value: 'won' }, { value: 'lost' }] }, + ref_code: { type: 'text' }, + amount: { type: 'number' }, + }, + }; + const ACCOUNT = { name: 'account', nameField: 'title', fields: { title: { type: 'text' }, code: { type: 'text' } } }; + /** Every account record that exists, and the ones the caller's read returns. */ + const STORE: Record = { a1: 'Acme', a2: 'Globex', a3: ' ', a4: 'Initech' }; + + interface LookupBridge extends RecordingBridge { + reads: Array<[string, any]>; + } + + function lookupBridge( + rows: unknown[], + opts: { readable?: (id: string) => boolean; store?: Record; defs?: Record } = {}, + ): LookupBridge { + const bridge = makeBridge() as LookupBridge; + const readable = opts.readable ?? (() => true); + const store = opts.store ?? STORE; + const defs: Record = opts.defs ?? { deal: DEAL, account: ACCOUNT }; + bridge.reads = []; + bridge.aggregate = async (object: string, o: any) => { + bridge.calls.push([object, o]); + return rows; + }; + bridge.servedObjectDefinitionOf = async (name: string) => (defs[name] ?? null) as Record | null; + bridge.query = async (object: string, o: any) => { + bridge.reads.push([object, o]); + const ids: string[] = o?.where?.id?.$in ?? []; + const records = ids + .filter((id) => Object.prototype.hasOwnProperty.call(store, id) && readable(id)) + .map((id) => ({ id, title: store[id] })); + return { object, records, total: records.length }; + }; + return bridge; + } + + async function answer(bridge: RecordingBridge, args: Record) { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const { refused, text } = await aggregate(runtime, bridge, { objectName: 'deal', ...args }); + expect(refused, text).toBe(false); + return JSON.parse(text) as { rows: Array>; totalGroups: number; truncated?: true }; + } + + const COUNT = [{ function: 'count', alias: 'n' }]; + + it('a lookup and a master-detail group carry `__label`: the referenced record\'s name field, beside the key', async () => { + const bridge = lookupBridge([{ account: 'a1', n: 3 }, { account: 'a2', n: 1 }]); + const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account'] }); + expect(out.rows).toEqual([{ account: 'a1', account__label: 'Acme', n: 3 }, { account: 'a2', account__label: 'Globex', n: 1 }]); + expect(Object.keys(out.rows[0]!)).toEqual(['account', 'account__label', 'n']); + + const aliased = await answer(lookupBridge([{ p: 'a2', n: 2 }]), { aggregations: COUNT, groupBy: [{ field: 'parent', alias: 'p' }] }); + expect(aliased.rows).toEqual([{ p: 'a2', p__label: 'Globex', n: 2 }]); + }); + + it('CONTROL — a second key that is not a lookup carries no label, even where its value is a record id', async () => { + const bridge = lookupBridge([{ account: 'a1', ref_code: 'a2', n: 2 }, { account: 'a2', ref_code: 'a1', n: 1 }]); + const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account', 'ref_code'] }); + expect(out.rows).toEqual([ + { account: 'a1', account__label: 'Acme', ref_code: 'a2', n: 2 }, + { account: 'a2', account__label: 'Globex', ref_code: 'a1', n: 1 }, + ]); + for (const row of out.rows) expect(row).not.toHaveProperty('ref_code__label'); + }); + + it('CONTROL — a record the caller\'s read does not return and a deleted record answer the same, with no label', async () => { + const rows = [{ account: 'a1', n: 1 }, { account: 'a4', n: 2 }]; + const args = { aggregations: COUNT, groupBy: ['account'] }; + // a4 exists, and the caller's read does not return it. + const unreadable = await answer(lookupBridge(rows, { readable: (id) => id !== 'a4' }), args); + // a4 no longer exists. + const { a4: _deleted, ...rest } = STORE; + const deleted = await answer(lookupBridge(rows, { store: rest }), args); + expect(unreadable).toEqual(deleted); + expect(JSON.stringify(unreadable)).toBe(JSON.stringify(deleted)); + expect(unreadable.rows[1]).toEqual({ account: 'a4', n: 2 }); + expect(unreadable.rows[0]).toEqual({ account: 'a1', account__label: 'Acme', n: 1 }); + }); + + it('CONTROL — a record whose name is blank, and a null key, carry no label', async () => { + const out = await answer(lookupBridge([{ account: 'a3', n: 1 }, { account: null, n: 4 }]), { aggregations: COUNT, groupBy: ['account'] }); + expect(out.rows).toEqual([{ account: 'a3', n: 1 }, { account: null, n: 4 }]); + }); + + 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 () => { + const rows = [{ account: 'a1', n: 1 }, { partner: 'p1', n: 2 }]; + const args = { aggregations: COUNT, groupBy: ['account'] }; + const { account: _lookup, ...dealWithout } = DEAL.fields; + const cases: Array> = [ + { deal: DEAL }, + { deal: DEAL, account: { ...ACCOUNT, fields: { code: { type: 'text' } } } }, + { deal: { ...DEAL, fields: dealWithout }, account: ACCOUNT }, + ]; + for (const defs of cases) { + const bridge = lookupBridge(rows, { defs }); + const out = await answer(bridge, args); + expect(out).toEqual({ rows, totalGroups: 2 }); + expect(bridge.reads).toEqual([]); + } + // A referenced `sys_*` object this tool does not read is never read for a name. + const system = lookupBridge(rows, { defs: { deal: DEAL, sys_partner: ACCOUNT } }); + const out = await answer(system, { aggregations: COUNT, groupBy: ['partner'] }); + expect(out).toEqual({ rows, totalGroups: 2 }); + expect(system.reads).toEqual([]); + }); + + it('CONTROL — a name read that throws, or answers no records list, answers as before', async () => { + const rows = [{ account: 'a1', n: 1 }]; + const throwing = lookupBridge(rows); + throwing.query = async () => { throw new Error('read refused'); }; + const shapeless = lookupBridge(rows); + shapeless.query = async () => [{ id: 'a1', title: 'Acme' }]; + for (const bridge of [throwing, shapeless]) { + const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account'] }); + expect(out).toEqual({ rows, totalGroups: 1 }); + } + }); + + it('the names are one batched read of the referenced object, for the groups served, as the caller', async () => { + const rows = Array.from({ length: 60 }, (_, i) => ({ account: `x${i}`, parent: i % 2 === 0 ? 'a1' : 'a2', n: i })); + const bridge = lookupBridge(rows, { store: { ...STORE, x0: 'First', x49: 'Last served', x50: 'Past the cap' } }); + const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account', 'parent'] }); + expect(bridge.reads).toHaveLength(1); + const [object, read] = bridge.reads[0]!; + expect(object).toBe('account'); + expect(read.fields).toEqual(['id', 'title']); + expect(read.limit).toBe(52); + expect([...read.where.id.$in].sort()).toEqual([...rows.slice(0, 50).map((r) => r.account), 'a1', 'a2'].sort()); + expect(out.rows).toHaveLength(50); + expect(out.rows[0]).toEqual({ account: 'x0', account__label: 'First', parent: 'a1', parent__label: 'Acme', n: 0 }); + expect(out.rows[49]).toMatchObject({ account__label: 'Last served', parent__label: 'Globex' }); + expect(out.rows[1]).toEqual({ account: 'x1', parent: 'a2', parent__label: 'Globex', n: 1 }); + }); + + it('the stdio door: the name is read through the stdio bridge under the caller\'s own context', async () => { + const principal = { userId: 'u1', isSystem: false } as unknown as ExecutionContext; + const engine = { + aggregate: vi.fn(async () => [{ account: 'a1', n: 2 }, { account: 'a4', n: 1 }]), + // The caller's read returns a1 only. + find: vi.fn(async (_object: string, query: any) => + ((query?.where?.id?.$in ?? []) as string[]).filter((id) => id === 'a1').map((id) => ({ id, title: STORE[id] }))), + }; + const defs: Record = { deal: DEAL, account: ACCOUNT }; + const metadataService = { getObject: vi.fn(async (name: string) => defs[name]) }; + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: metadataService as unknown as IMetadataService, + resolvePrincipal: async () => principal, + }); + const server = new McpServer({ name: 'pin', version: '0' }); + registerObjectTools(server, bridge); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await server.connect(serverSide); + const client = new Client({ name: 'pin', version: '0' }); + await client.connect(clientSide); + try { + const res = (await client.callTool({ + name: 'aggregate_records', + arguments: { objectName: 'deal', aggregations: COUNT, groupBy: ['account'] }, + })) as { isError?: boolean; content: Array<{ text: string }> }; + expect(res.isError, res.content[0]?.text).not.toBe(true); + expect(JSON.parse(res.content[0]!.text)).toEqual({ + rows: [{ account: 'a1', account__label: 'Acme', n: 2 }, { account: 'a4', n: 1 }], + totalGroups: 2, + }); + expect(engine.find).toHaveBeenCalledTimes(1); + const [object, query, opts] = engine.find.mock.calls[0] as unknown as [string, any, unknown]; + expect(object).toBe('account'); + expect(query).toMatchObject({ where: { id: { $in: ['a1', 'a4'] } }, fields: ['id', 'title'], limit: 2 }); + expect(opts).toEqual({ context: principal }); + } finally { + await client.close(); + } + }); +}); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 5908040c1e0..a3381bff979 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -43,12 +43,15 @@ import { z } from 'zod'; import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import type { EngineAggregateOptions } from '@objectstack/spec/data'; +import type { DisplayNameObjectMeta, EngineAggregateOptions } from '@objectstack/spec/data'; // [#28550, #28609] The engine's aggregation entry. Each `aggregate_records` // entry IS this node, so this door and the REST query door (which parses // `FindDataRequestSchema`, whose `aggregations` are this node) judge one shape // with one refusal. import { AggregationNodeSchema, SEARCH_COMPANION_FIELD } from '@objectstack/spec/data'; +// [#35138] ADR-0079's one reading of an object's name field +// (`nameField ?? displayNameField ?? derived`), which names a lookup group. +import { resolveDisplayField } from '@objectstack/spec/data'; // [#23529] The catalogue's spelling of `PERMISSION_DENIED`, the code whose // `details` `errorResultFromThrown` withholds. Imported, never hand-spelled. import { StandardErrorCode, type ErrorCode } from '@objectstack/spec/api'; @@ -717,18 +720,34 @@ function errorResult(message: string) { async function servedFieldsOf( bridge: McpDataBridge, objectName: string, +): Promise | undefined> { + return fieldMapOf(await servedDefinitionOf(bridge, objectName)); +} + +/** + * The object `objectName` as this caller is served it, or `undefined` when the + * bridge cannot say (no member, no object, or a throw). + */ +async function servedDefinitionOf( + bridge: McpDataBridge, + objectName: string, ): Promise | undefined> { if (typeof bridge.servedObjectDefinitionOf !== 'function') return undefined; try { - const fields = (await bridge.servedObjectDefinitionOf(objectName))?.fields; - return fields !== null && typeof fields === 'object' && !Array.isArray(fields) - ? (fields as Record) - : undefined; + return (await bridge.servedObjectDefinitionOf(objectName)) ?? undefined; } catch { return undefined; } } +/** A served definition's name-keyed field map, or `undefined` when it carries none. */ +function fieldMapOf(def: Record | undefined): Record | undefined { + const fields = def?.fields; + return fields !== null && typeof fields === 'object' && !Array.isArray(fields) + ? (fields as Record) + : undefined; +} + /** The served field `name`, or `undefined` when the caller's view has no such field. */ function servedFieldOf(fields: Record, name: unknown): Record | undefined { if (typeof name !== 'string' || !Object.prototype.hasOwnProperty.call(fields, name)) return undefined; @@ -805,6 +824,127 @@ function inDeclaredOptionOrder( }); } +/** + * [#35138] The field types whose group value is the id of a record of another + * object, the field's `reference`. + */ +const LOOKUP_GROUP_TYPES: ReadonlySet = new Set(['lookup', 'master_detail']); + +/** [#35138] The member beside a lookup group key that names its record: `__label`. */ +const LOOKUP_LABEL_SUFFIX = '__label'; + +/** + * [#35138] `aggregate_records`' groups with each lookup key's record named + * beside it, in `__label`, where `` is the group column (the key's + * alias when it has one). + * + * A group key is a lookup key when the caller's served schema shows it as a + * `lookup` or `master_detail` field with a `reference`. The name is the + * referenced record's value of the referenced object's name field (ADR-0079, + * {@link resolveDisplayField}), read AS THE CALLER: one `bridge.query` per + * referenced object, for the ids of the groups served, through the same + * bridge and context as the aggregate. Nothing is read with other rights, so + * the caller's object, field and record permissions apply as to any read the + * caller makes. + * + * A label is set 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, so the answer says nothing about why a key has none. + * No label at all is added, and the rows come back as they are, when the + * referenced object is not one this tool reads (`admitsRead`), when the + * caller is not served it or its name field, or when the read fails. + * ⛔ This read never fails the aggregate it annotates. + */ +async function withLookupGroupLabels( + bridge: McpDataBridge, + rows: unknown[], + groupBy: NonNullable | undefined, + fields: Record, + admitsRead: (objectName: string) => Promise, +): Promise { + const keysByTarget = new Map(); + for (const entry of groupBy ?? []) { + const item = typeof entry === 'string' ? { field: entry } : (entry as { field?: unknown; alias?: unknown; dateGranularity?: unknown }); + if (item.dateGranularity !== undefined) continue; + const def = servedFieldOf(fields, item.field); + if (!def || typeof def.type !== 'string' || !LOOKUP_GROUP_TYPES.has(def.type)) continue; + if (typeof def.reference !== 'string' || def.reference === '') continue; + const column = typeof item.alias === 'string' ? item.alias : (item.field as string); + keysByTarget.set(def.reference, [...(keysByTarget.get(def.reference) ?? []), column]); + } + if (keysByTarget.size === 0) return rows; + + const namesByColumn = new Map>(); + for (const [target, columns] of keysByTarget) { + const ids = new Set(); + for (const row of rows) { + if (row === null || typeof row !== 'object') continue; + for (const column of columns) { + const id = (row as Record)[column]; + if (typeof id === 'string' && id !== '') ids.add(id); + } + } + if (ids.size === 0) continue; + const names = await recordNamesAsCaller(bridge, target, [...ids], admitsRead); + if (!names || names.size === 0) continue; + for (const column of columns) namesByColumn.set(column, names); + } + if (namesByColumn.size === 0) return rows; + + return rows.map((row) => { + if (row === null || typeof row !== 'object' || Array.isArray(row)) return row; + const source = row as Record; + const labelled: Record = {}; + for (const [member, value] of Object.entries(source)) { + labelled[member] = value; + const names = namesByColumn.get(member); + const name = names && typeof value === 'string' ? names.get(value) : undefined; + const labelMember = `${member}${LOOKUP_LABEL_SUFFIX}`; + // A column the aggregate itself answers under that name is never overwritten. + if (name !== undefined && !Object.prototype.hasOwnProperty.call(source, labelMember)) labelled[labelMember] = name; + } + return labelled; + }); +} + +/** + * [#35138] The name of each of `ids` in `target` that the caller's own read + * returns with a non-blank name, by id. `undefined` when no name can be read + * at all: the object is not one this tool reads, the caller is not served it + * or its name field, or the read fails. + */ +async function recordNamesAsCaller( + bridge: McpDataBridge, + target: string, + ids: string[], + admitsRead: (objectName: string) => Promise, +): Promise | undefined> { + try { + if (!(await admitsRead(target))) return undefined; + const def = await servedDefinitionOf(bridge, target); + const targetFields = fieldMapOf(def); + if (!def || !targetFields) return undefined; + const nameField = resolveDisplayField(def as DisplayNameObjectMeta); + if (!nameField || !servedFieldOf(targetFields, nameField)) return undefined; + const answer = await bridge.query(target, { where: { id: { $in: ids } }, fields: ['id', nameField], limit: ids.length }); + const records = (answer as { records?: unknown } | null | undefined)?.records; + if (!Array.isArray(records)) return undefined; + const asked = new Set(ids); + const names = new Map(); + for (const record of records) { + if (record === null || typeof record !== 'object') continue; + const id = idOfRow(record as Record); + const name = (record as Record)[nameField]; + if (id === undefined || !asked.has(id)) continue; + if (typeof name === 'string' && name.trim() !== '') names.set(id, name); + else if (typeof name === 'number' && Number.isFinite(name)) names.set(id, String(name)); + } + return names; + } catch { + return undefined; + } +} + /** * [#35138] The aggregate functions whose value is an amount in the field's * currency: the ones that read the amount (ADR-0144 Open item 10, the set @@ -3213,6 +3353,10 @@ export function registerObjectTools( 'Groups of a select field come back in the order the field declares its options. ' + 'An amount column over a field with one fixed currency is named in currencies, alias to ISO 4217 code; ' + 'an amount whose records each carry their own currency is answered only grouped by its currency code field. ' + + // [#35138] The name of a lookup group's record, read as the caller. + 'A group keyed by a lookup or master-detail field carries __label beside the record id: the name of that record, ' + + '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. ' + 'Use this instead of paging query_records when a question needs totals or breakdowns. ' + 'Runs under the caller\'s permissions, row-level security and field-level security.', inputSchema: strictToolInput( @@ -3299,8 +3443,14 @@ export function registerObjectTools( // Group count is unbounded (a high-cardinality groupBy can return // thousands of rows) — cap the tool output like query_records does. const truncated = groups.length > maxLimit; + const served = truncated ? groups.slice(0, maxLimit) : groups; + // [#35138] Each lookup key's record named beside it, read as the + // caller, for the groups served only. + const labelled = fields + ? await withLookupGroupLabels(bridge, served, groupBy, fields, async (name) => (await readGuard(name)) === undefined) + : served; return textResult({ - rows: truncated ? groups.slice(0, maxLimit) : groups, + rows: labelled, totalGroups: rows.length, ...(truncated ? { truncated: true } : {}), ...(Object.keys(currencies).length > 0 ? { currencies } : {}),