From 26b1d2eeab248ce1c2dce8f88d26ed8adb0ee234 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:13:40 +0000 Subject: [PATCH 1/2] feat(mcp): aggregate_records orders select groups by declared options and names a fixed amount's currency (wip) Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .../mcp-http-tools.aggregation-entry.test.ts | 154 ++++++++++++++++ packages/mcp/src/mcp-http-tools.ts | 164 +++++++++++++++++- 2 files changed, 315 insertions(+), 3 deletions(-) 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 14a216767aa..163e9aea838 100644 --- a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts +++ b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts @@ -205,3 +205,157 @@ describe('aggregate_records — the aggregation entry (#28550)', () => { expect(entry?.required).toEqual(expect.arrayContaining(['function', 'alias'])); }); }); + +/** + * [#35138] Two facts `aggregate_records` reads off the object as the caller + * is served it (`servedObjectDefinitionOf`): groups keyed by a select field + * come back in the option order the field declares, sorted before the cap so + * the cap keeps the first declared groups; and an amount column over a + * `fixed`-currency field names its currency in `currencies`, by alias. + * + * CONTROLS. A group key that is not a select field keeps the driver's order; a + * field the served schema does not show is neither ordered nor named; a + * `count`, a non-currency measure, a `record`-mode and a `dynamic`-mode amount + * carry no currency; a bridge without the member answers as before. + */ +describe('aggregate_records — select groups in declared option order, a fixed amount names its currency (#35138)', () => { + const STAGES = ['prospect', 'qualified', 'won', 'lost']; + const served = { + name: 'deal', + fields: { + stage: { type: 'select', options: STAGES.map((value) => ({ value, label: value.toUpperCase() })) }, + priority: { type: 'radio', options: [{ value: 'high' }, { value: 'low' }] }, + region: { type: 'text' }, + amount: { type: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' } }, + local_amount: { type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } }, + tenant_amount: { type: 'currency', currencyConfig: { currencyMode: 'dynamic' } }, + seats: { type: 'number' }, + currency_code: { type: 'text' }, + many: { type: 'select', options: Array.from({ length: 60 }, (_, i) => ({ value: `o${String(i).padStart(2, '0')}` })) }, + }, + }; + + function servedBridge(rows: unknown[], def: Record | null = served): RecordingBridge & { schemaReads: number } { + const bridge = makeBridge() as RecordingBridge & { schemaReads: number }; + bridge.schemaReads = 0; + bridge.aggregate = async (object: string, opts: any) => { + bridge.calls.push([object, opts]); + return rows; + }; + bridge.servedObjectDefinitionOf = async () => { + bridge.schemaReads++; + return def; + }; + 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; currencies?: Record }; + } + + it('groups of a select field come back in the declared option order, a value no option declares last', async () => { + const bridge = servedBridge([ + { stage: 'lost', n: 1 }, { stage: null, n: 9 }, { stage: 'won', n: 2 }, { stage: 'prospect', n: 3 }, { stage: 'qualified', n: 4 }, + ]); + const out = await answer(bridge, { aggregations: [{ function: 'count', alias: 'n' }], groupBy: ['stage'] }); + expect(out.rows.map((r) => r.stage)).toEqual(['prospect', 'qualified', 'won', 'lost', null]); + expect(out.totalGroups).toBe(5); + }); + + it('the order is read by the group key\'s alias, and a second select key orders within the first', async () => { + const bridge = servedBridge([ + { s: 'won', priority: 'low', n: 1 }, { s: 'prospect', priority: 'low', n: 2 }, + { s: 'won', priority: 'high', n: 3 }, { s: 'prospect', priority: 'high', n: 4 }, + ]); + const out = await answer(bridge, { + aggregations: [{ function: 'count', alias: 'n' }], + groupBy: [{ field: 'stage', alias: 's' }, 'priority'], + }); + expect(out.rows.map((r) => r.n)).toEqual([4, 2, 3, 1]); + }); + + it('the order is taken before the cap, so the cap keeps the first declared groups', async () => { + const rows = Array.from({ length: 60 }, (_, i) => ({ many: `o${String(59 - i).padStart(2, '0')}`, n: i })); + const out = await answer(servedBridge(rows), { aggregations: [{ function: 'count', alias: 'n' }], groupBy: ['many'] }); + expect(out.rows).toHaveLength(50); + expect(out.rows[0]!.many).toBe('o00'); + expect(out.rows[49]!.many).toBe('o49'); + expect(out.truncated).toBe(true); + expect(out.totalGroups).toBe(60); + }); + + it('CONTROL — a group key that is not a select field keeps the driver\'s order, and so do the keys after it', async () => { + const driverOrder = [ + { region: 'west', stage: 'won', n: 1 }, { region: 'east', stage: 'prospect', n: 2 }, { region: 'east', stage: 'won', n: 3 }, + ]; + const out = await answer(servedBridge(driverOrder), { + aggregations: [{ function: 'count', alias: 'n' }], + groupBy: ['region', 'stage'], + }); + expect(out.rows.map((r) => r.n)).toEqual([1, 2, 3]); + }); + + it('CONTROL — a select field the served schema does not show is not ordered by its options', async () => { + const { stage: _withheld, ...rest } = served.fields; + const bridge = servedBridge([{ stage: 'lost', n: 1 }, { stage: 'prospect', n: 2 }], { name: 'deal', fields: rest }); + const out = await answer(bridge, { aggregations: [{ function: 'count', alias: 'n' }], groupBy: ['stage'] }); + expect(out.rows.map((r) => r.stage)).toEqual(['lost', 'prospect']); + }); + + it('an amount over a fixed-currency field names its currency, by the column alias', async () => { + const bridge = servedBridge([{ stage: 'won', total: 1200, mean: 600 }]); + const out = await answer(bridge, { + aggregations: [ + { function: 'sum', field: 'amount', alias: 'total' }, + { function: 'avg', field: 'amount', alias: 'mean' }, + ], + groupBy: ['stage'], + }); + expect(out.currencies).toEqual({ total: 'USD', mean: 'USD' }); + }); + + it('CONTROL — a count, a non-currency measure, a record-mode and a dynamic-mode amount carry no currency', async () => { + const bridge = servedBridge([{ currency_code: 'EUR', n: 2, k: 2, seats_sum: 5, local: 30, tenant: 40 }]); + const out = await answer(bridge, { + aggregations: [ + { function: 'count', alias: 'n' }, + { function: 'count_distinct', field: 'amount', alias: 'k' }, + { function: 'sum', field: 'seats', alias: 'seats_sum' }, + { function: 'sum', field: 'local_amount', alias: 'local' }, + { function: 'sum', field: 'tenant_amount', alias: 'tenant' }, + ], + groupBy: ['currency_code'], + }); + expect(out).not.toHaveProperty('currencies'); + }); + + it('CONTROL — a fixed-currency field the served schema does not show names no currency', async () => { + const { amount: _withheld, ...rest } = served.fields; + const bridge = servedBridge([{ total: 1 }], { name: 'deal', fields: rest }); + const out = await answer(bridge, { aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }] }); + expect(out).not.toHaveProperty('currencies'); + }); + + it('CONTROL — a bridge without the served definition, or one that throws, answers as before', async () => { + const driverOrder = [{ stage: 'lost', total: 1 }, { stage: 'won', total: 2 }]; + const args = { aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }], groupBy: ['stage'] }; + const bare = servedBridge(driverOrder); + delete bare.servedObjectDefinitionOf; + const throwing = servedBridge(driverOrder); + throwing.servedObjectDefinitionOf = async () => { throw new Error('metadata outage'); }; + for (const bridge of [bare, throwing]) { + const out = await answer(bridge, args); + expect(out).toEqual({ rows: driverOrder, totalGroups: 2 }); + } + }); + + it('a call with no group key and no amount column does not read the served schema', async () => { + const bridge = servedBridge([{ n: 3 }]); + const out = await answer(bridge, { aggregations: [{ function: 'count', alias: 'n' }] }); + expect(out).toEqual({ rows: [{ n: 3 }], totalGroups: 1 }); + expect(bridge.schemaReads).toBe(0); + }); +}); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 9a18605c784..0ed787fe694 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -212,7 +212,9 @@ export interface McpDataBridge { * that judge what a field declares (`required`, `defaultValue`, a * `reference`'s target, an external binding) read the definition, which * `describeObject`'s projection does not carry. Never rendered to the - * caller: only the gate's findings are. + * caller: only the gate's findings are. [#35138] `aggregate_records` reads + * two facts off it the same way, a group key's declared option order and + * an amount's fixed currency, and renders those alone. * * OPTIONAL, like {@link optionFieldsOf}: a bridge that omits it gets the * shared validator's verdict alone, exactly as before. @@ -701,6 +703,147 @@ function errorResult(message: string) { return { content: [{ type: 'text' as const, text: message }], isError: true as const }; } +/** + * [#35138] The fields of `objectName` as this caller is served them + * ({@link McpDataBridge.servedObjectDefinitionOf}): the map + * `aggregate_records` reads a group key's declared options and an amount's + * fixed currency from. A field the caller's view removed is not in it, so + * nothing read from it names a field the caller cannot see. + * + * `undefined` when the bridge cannot say — no member, no object, or a throw — + * and the tool then renders exactly what it rendered before. ⛔ This read + * never fails the aggregate it annotates. + */ +async function servedFieldsOf( + 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; + } catch { + return 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; + const def = fields[name]; + return def !== null && typeof def === 'object' ? (def as Record) : undefined; +} + +/** + * [#35138] The field types whose group value is ONE declared option, so the + * groups have the order the author declared the options in. A `multiselect` + * groups by a combination of options, which has no declared order. + */ +const OPTION_ORDERED_GROUP_TYPES: ReadonlySet = new Set(['select', 'radio']); + +/** + * Each declared option value of `def` with its position, or `undefined` when + * the served field is not a single-option field declaring options. + */ +function declaredOptionRank(def: Record | undefined): Map | undefined { + if (!def || typeof def.type !== 'string' || !OPTION_ORDERED_GROUP_TYPES.has(def.type)) return undefined; + if (!Array.isArray(def.options)) return undefined; + const rank = new Map(); + for (const option of def.options) { + if (option === null || typeof option !== 'object' || !('value' in option)) continue; + const value = (option as { value: unknown }).value; + if (!rank.has(value)) rank.set(value, rank.size); + } + return rank.size > 0 ? rank : undefined; +} + +/** + * [#35138] `aggregate_records`' groups in the option order the caller's + * served schema declares, for a call that states no order of its own. + * + * The group keys are read in `groupBy` order while each one is a + * single-option field ({@link OPTION_ORDERED_GROUP_TYPES}) the served schema + * declares options for; the first key that is not one ends the reading, so + * the groups under it keep the order the driver answered. A value no option + * declares (a null, a value stored before an option was removed) sorts after + * every declared one. The sort is stable: groups the declared order does not + * tell apart keep the driver's order. With no such leading key, `rows` comes + * back as it is. + * + * Run over every group, BEFORE the tool's cap, so the groups the cap keeps + * are the first in the declared order. Reordering a list the driver already + * answered whole runs no second query. + */ +function inDeclaredOptionOrder( + rows: unknown[], + groupBy: NonNullable | undefined, + fields: Record, +): unknown[] { + const keys: Array<{ column: string; rank: Map }> = []; + for (const entry of groupBy ?? []) { + const item = typeof entry === 'string' ? { field: entry } : (entry as { field?: unknown; alias?: unknown; dateGranularity?: unknown }); + // A bucketed key is a period, not a declared option. + if (item.dateGranularity !== undefined) break; + const rank = declaredOptionRank(servedFieldOf(fields, item.field)); + if (!rank) break; + const column = typeof item.alias === 'string' ? item.alias : (item.field as string); + keys.push({ column, rank }); + } + if (keys.length === 0) return rows; + const position = (row: unknown, key: { column: string; rank: Map }): number => { + const value = row !== null && typeof row === 'object' ? (row as Record)[key.column] : undefined; + return key.rank.get(value) ?? key.rank.size; + }; + return [...rows].sort((a, b) => { + for (const key of keys) { + const by = position(a, key) - position(b, key); + if (by !== 0) return by; + } + return 0; + }); +} + +/** + * [#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 + * `@objectstack/objectql`'s `record-currency-aggregate-door.ts` judges). + * `count` reads no amount and `count_distinct` counts values, so neither + * answers a currency. + */ +const AMOUNT_AGGREGATE_FUNCTIONS: ReadonlySet = new Set(['sum', 'avg', 'min', 'max']); + +/** + * [#35138] The currency of each amount column whose field has ONE currency, + * by the column's alias: a served field whose `currencyConfig` is + * `currencyMode: 'fixed'` answers its `defaultCurrency`. Empty when no + * column has one. + * + * The other two modes answer nothing here. A `record`-mode amount is + * answered by the engine only grouped by its own currency code field + * (`record-currency-aggregate-door.ts`, ADR-0144 D6), so each group's code is + * already in its row. A `dynamic`-mode amount has no currency of its own: it + * displays in the tenant default currency, which the served schema does not + * carry. + */ +function fixedAmountCurrencies( + aggregations: NonNullable, + fields: Record, +): Record { + const currencies: Record = {}; + for (const aggregation of aggregations) { + if (!AMOUNT_AGGREGATE_FUNCTIONS.has(aggregation.function)) continue; + const config = servedFieldOf(fields, aggregation.field)?.currencyConfig; + if (config === null || typeof config !== 'object') continue; + const { currencyMode, defaultCurrency } = config as { currencyMode?: unknown; defaultCurrency?: unknown }; + if (currencyMode === 'fixed' && typeof defaultCurrency === 'string' && defaultCurrency !== '') { + currencies[aggregation.alias] = defaultCurrency; + } + } + return currencies; +} + /** * A tool error that PRESERVES an ADR-0112 envelope when the thrown value * carries one. @@ -3005,6 +3148,10 @@ export function registerObjectTools( description: 'Aggregate records with GROUP BY: count/sum/avg/min/max/count_distinct over an object, ' + 'optionally grouped by fields (dates can be bucketed by day/week/month/quarter/year). ' + + // [#35138] The two facts the answer carries from the served schema. + '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. ' + '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( @@ -3078,13 +3225,24 @@ export function registerObjectTools( aggregations, timezone, })) ?? []; + // [#35138] Read off the object as the caller is served it: the + // declared option order of a select group key, and the one + // currency of a fixed-currency amount. Only when the call has a + // group key or an amount column to read it for. + const fields = (groupBy?.length ?? 0) > 0 + || aggregations.some((a) => AMOUNT_AGGREGATE_FUNCTIONS.has(a.function) && typeof a.field === 'string') + ? await servedFieldsOf(bridge, objectName) + : undefined; + const groups = fields ? inDeclaredOptionOrder(rows, groupBy, fields) : rows; + const currencies = fields ? fixedAmountCurrencies(aggregations, fields) : {}; // Group count is unbounded (a high-cardinality groupBy can return // thousands of rows) — cap the tool output like query_records does. - const truncated = rows.length > maxLimit; + const truncated = groups.length > maxLimit; return textResult({ - rows: truncated ? rows.slice(0, maxLimit) : rows, + rows: truncated ? groups.slice(0, maxLimit) : groups, totalGroups: rows.length, ...(truncated ? { truncated: true } : {}), + ...(Object.keys(currencies).length > 0 ? { currencies } : {}), }); } catch (err) { return dataDoorErrorResult(err, 'aggregate_records', objectName); From 4582c20e076360cfe76027bb27a266063e2a61da Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:23:21 +0000 Subject: [PATCH 2/2] chore(changeset): aggregate_records option order and fixed currency Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .../35138-aggregate-option-order-currency.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .changeset/35138-aggregate-option-order-currency.md diff --git a/.changeset/35138-aggregate-option-order-currency.md b/.changeset/35138-aggregate-option-order-currency.md new file mode 100644 index 00000000000..6153d72199d --- /dev/null +++ b/.changeset/35138-aggregate-option-order-currency.md @@ -0,0 +1,15 @@ +--- +'@objectstack/mcp': patch +--- + +feat(mcp): `aggregate_records` returns select groups in their declared option order and names the currency of a fixed-currency amount + +Clause-②: yes (widening) +Metadata-protocol: none + +Two facts the MCP `aggregate_records` tool now reads from the object as the caller is served it, on both the HTTP and the stdio door: + +- Groups keyed by a `select` or `radio` field come back in the order the field declares its options, instead of the order the driver returned them in. A value no option declares, such as a null, sorts last. When the call groups by several keys, the order is applied to the leading select keys. From the first key that is not a select field onward, the driver's order stays. The groups are sorted before the tool's row cap, so the groups the cap keeps are the first ones in declared order. +- An amount column (`sum`, `avg`, `min` or `max`) over a field whose `currencyConfig` is `currencyMode: 'fixed'` is named in a new result member `currencies`, which maps the column's alias to its ISO 4217 code, e.g. `"currencies": { "total": "USD" }`. The member is present only when at least one column has a currency. `count`, `count_distinct`, non-currency fields and `dynamic`-mode amounts carry none. A `record`-mode amount is still answered only when it is grouped by its currency code field, so each group's code is already in its row. + +A field the caller's served schema does not show is never ordered by its options or named. A host whose bridge cannot serve the definition answers exactly as before. Existing members (`rows`, `totalGroups`, `truncated`) are unchanged.