Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .changeset/35145-mcp-latest-per.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@objectstack/mcp': patch
'@objectstack/objectql': patch
'@objectstack/driver-sql': patch
'@objectstack/driver-turso': patch
'@objectstack/metadata-protocol': patch
'@objectstack/runtime': patch
---

feat(mcp): "each X with its latest Y" in one `query_records` call — `latestPer`

Clause-②: yes (widening): a new read form on the published MCP tool surface. Judged from the card content; the build confirms it
Metadata-protocol: none

`query_records` takes `latestPer: { by, orderBy }`: one row per group, the group's first row in the given order. `by` names 1 to 3 fields, `orderBy` 1 to 3 keys (`asc` / `desc`); a tie goes to the record id in the direction of the last key, and an empty order value ranks last. "Each account with its latest deal" is `{ objectName: 'crm_opportunity', latestPer: { by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] } }`.

- The row is chosen among the rows the caller may read and the `where` admits: a group whose newest row is hidden from the caller answers its newest readable row, never the hidden one and never nothing. The organization wall holds inside the choice. Field masking still applies to the returned rows.
- A partition or order field the caller may not read is refused as it is in `orderBy`; a computed, JSON or multi-value field, or a dotted path, is refused as a partition or order field.
- `limit` counts groups, capped at the tool's `maxLimit` like any list. The answer is `{ object, records, hasMore }` and never a `total`; when more groups exist than came back it carries `truncated: true`.
- Served by the SQL driver (Postgres, MySQL, SQLite) and by `driver-sqlite-wasm` and the Turso driver on a local or embedded-replica database: the driver compiles a `ROW_NUMBER()` window over the read's own scoped selection. Every other driver (in-memory, Turso's remote connection, MongoDB), an object with an `afterFind` hook and an object with object-scoped read middleware refuse with `INVALID_QUERY` / 400 before anything is read. The Turso driver's remote face refuses the directive itself too.
- New exports: `LATEST_PER`, `LATEST_PER_MAX_KEYS` and the `LatestPerRequest` / `LatestPerOrder` / `LatestPerOutcome` types from `@objectstack/objectql`; `LATEST_PER_DIRECTIVE`, `latestPerDirectiveOf` and the `LatestPerDirective` / `LatestPerDirectiveOrder` types from `@objectstack/driver-sql`; `McpLatestPer` from `@objectstack/mcp`. The request rides an in-process read option, never a wire or query key; `@objectstack/spec` is unchanged.

Without `latestPer`, `query_records` and every read are unchanged.
33 changes: 33 additions & 0 deletions content/docs/ai/connect-mcp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,39 @@ service is installed:
| `list_datasets` | List the governed datasets (business metrics) you may query: their measures and dimensions with business labels, descriptions and synonyms, and which of the question's words each one matches exactly |
| `query_dataset` | Compute a governed metric by the names `list_datasets` gives; the answer carries its provenance (the dataset and measures used) |

### Each X with its latest Y: `latestPer`

"Each account with its latest deal" is one `query_records` call. `latestPer`
names the groups and the order that picks each group's row:

```json
{
"objectName": "crm_opportunity",
"where": { "stage": { "$ne": "closed_won" } },
"latestPer": { "by": ["account"], "orderBy": [{ "field": "close_date", "order": "desc" }] }
}
```

- `by` takes 1 to 3 fields; `orderBy` takes 1 to 3 keys, each `asc` or `desc`.
The answer is one row per group: the group's first row in that order. A tie
goes to the record id, in the direction of the last key; an empty order value
ranks last.
- The row is chosen among the rows the caller may read and the `where` admits:
a group whose newest row is hidden from the caller answers its newest row the
caller can read. Your own `orderBy`, `fields` and `offset` apply to the
answered rows.
- `limit` counts groups (capped at 50, like any list). The answer is
`{ object, records, hasMore }` with no `total`; when more groups exist than
came back it also carries `truncated: true`.
- A partition or order field the caller may not read is refused, as it is in
`orderBy`. A computed, JSON or multi-value field, or a dotted path, is refused
as a partition or order field.
- The SQL drivers serve it (Postgres, MySQL, SQLite, and Turso on a local or
embedded-replica database). Elsewhere (the in-memory driver, Turso's remote
connection, MongoDB) the call is refused with `INVALID_QUERY` before anything
is read, as it is for an object with an `afterFind` hook or object-scoped read
middleware.

### Governed metrics and the `initialize` instructions

`list_datasets` and `query_dataset` are registered with the `data:read` scope,
Expand Down
4 changes: 4 additions & 0 deletions packages/drivers/driver-sql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ export {
UnsupportedDialectEmissionError,
renderDialectEmissionRefusal,
} from './dialect-emission-refusal.js';
// [latest per group] The window directive `find` compiles, so a subclass that
// answers `find` on another transport (Turso's remote face) can tell it rode in.
export { LATEST_PER_DIRECTIVE, latestPerDirectiveOf } from './sql-driver-latest-per.js';
export type { LatestPerDirective, LatestPerDirectiveOrder } from './sql-driver-latest-per.js';
// [ADR-0131 D9] The autonumber counter's refusal of an organization-less row on
// a tenant table — exported for the same reason: a caller recognises it by `code`.
export {
Expand Down
13 changes: 12 additions & 1 deletion packages/drivers/driver-sql/src/sql-driver-crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
import type { SqlDriver } from './sql-driver.js';
import { oracleUuidReadForm } from './sql-driver-oracle-dialect.js';
import { StandardErrorCode } from '@objectstack/spec/api';
import { latestPerDirectiveOf, latestPerIdSubquery } from './sql-driver-latest-per.js';

/**
* [`DriverOptions.lockRows`] Lock the rows a `find()` returns until its
Expand Down Expand Up @@ -154,7 +155,7 @@ export class CrudFacet {
* cited that as agreement, which it was not; objectstack#4419.) The
* obligation the contract states is on `find`, and this keeps it there.
*/
static async findRows(this: Pick<CrudHost, 'applyFilters' | 'applyTenantScope' | 'backendStatementFault' | 'formatOutput' | 'getBuilder' | 'isMssql' | 'isOracle' | 'mapSortField' | 'orderKeysFor' | 'primeMssqlGuidColumns' | 'primeMssqlPagingKey' | 'primeOracleRawUuidColumns' | 'remoteColumn' | 'unresolvableFilterColumnRefusal'>, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise<any[]> {
static async findRows(this: Pick<CrudHost, 'applyFilters' | 'applyTenantScope' | 'backendStatementFault' | 'formatOutput' | 'getBuilder' | 'isMssql' | 'isOracle' | 'knex' | 'mapSortField' | 'orderKeysFor' | 'primeMssqlGuidColumns' | 'primeMssqlPagingKey' | 'primeOracleRawUuidColumns' | 'remoteColumn' | 'unresolvableFilterColumnRefusal'>, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise<any[]> {
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
Expand All @@ -169,6 +170,10 @@ export class CrudFacet {
// whether the statement HAS a sort to drop, instead of asking whether the
// caller supplied one — since #4363 those are different questions.
const orderKeys = this.orderKeysFor(object, query, { singleRowLookup });
// [latest per group] One row per group, when the engine handed the window
// directive (`sql-driver-latest-per.ts`): one more predicate on the same
// statement, so every clause below holds for it unchanged.
const latestPer = latestPerDirectiveOf(query);

// Build everything EXCEPT the SELECT list, so the unknown-column retry
// below can rebuild without re-deriving where/order/pagination.
Expand All @@ -181,6 +186,12 @@ export class CrudFacet {
if (query.where) {
this.applyFilters(b, query.where, options);
}
if (latestPer !== undefined) {
b.whereIn(
this.remoteColumn(object, 'id', 'id'),
latestPerIdSubquery.call(this, object, query.where, latestPer, options),
);
}

// ORDER BY
if (withOrderBy) {
Expand Down
144 changes: 144 additions & 0 deletions packages/drivers/driver-sql/src/sql-driver-latest-per.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [latest per group] `find()` compiles the window directive the engine hands
* it (objectql `latest-per.ts`) into its own statement: one more predicate,
* `id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY …
* ORDER BY …, id) rn FROM t WHERE <tenant wall> AND <where>) w WHERE rn = 1)`.
*
* Pinned here: one row per group, the order's first row, ties broken by id in
* the last key's direction, a NULL order value ranked last; the window chosen
* among the rows the read's `where` admits (a group whose newest row the
* `where` hides answers its newest admitted row) and inside the tenant wall
* (another tenant's newer row never wins a group); the read's own ORDER BY,
* limit, offset and projection applied to the groups; no helper column on the
* rows; and a malformed directive refused before anything compiles.
*
* Every live cell runs where the suite provisions it (`OS_TEST_POSTGRES_URL`,
* `OS_TEST_MYSQL_URL`); SQLite always runs.
*/

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import type { DriverQuery } from '@objectstack/spec/contracts';
import { SqlDriver } from './sql-driver.js';
import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js';
import { LATEST_PER_DIRECTIVE, type LatestPerDirective } from './sql-driver-latest-per.js';

const TABLE = 'os_latest_per_deal';

/**
* Deals by account and owner. Account `a1`: d3 is newest; `a2`: d5 and d6 tie
* on the date (d6 wins on id, descending); `a3`: d8 has no date and ranks last
* whatever the direction; `ab` is another tenant's account, and `a1` carries
* one more deal, newer than all, in another tenant (xb).
*/
const DEALS = [
{ id: 'd1', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-01-10', amount: 10, organization_id: 'org_a' },
{ id: 'd2', account: 'a1', owner: 'u2', stage: 'lost', close_date: '2026-02-10', amount: 20, organization_id: 'org_a' },
{ id: 'd3', account: 'a1', owner: 'u1', stage: 'hidden', close_date: '2026-03-10', amount: 30, organization_id: 'org_a' },
{ id: 'd4', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-01-05', amount: 40, organization_id: 'org_a' },
{ id: 'd5', account: 'a2', owner: 'u1', stage: 'won', close_date: '2026-04-01', amount: 50, organization_id: 'org_a' },
{ id: 'd6', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-04-01', amount: 60, organization_id: 'org_a' },
{ id: 'd7', account: 'a3', owner: 'u1', stage: 'won', close_date: '2026-01-01', amount: 70, organization_id: 'org_a' },
{ id: 'd8', account: 'a3', owner: 'u1', stage: 'won', close_date: null, amount: 80, organization_id: 'org_a' },
{ id: 'xb', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-12-31', amount: 90, organization_id: 'org_b' },
{ id: 'yb', account: 'ab', owner: 'u9', stage: 'won', close_date: '2026-06-01', amount: 99, organization_id: 'org_b' },
];

const latestBy = (by: string[], orderBy: LatestPerDirective['orderBy']): LatestPerDirective => ({ by, orderBy });
const NEWEST_PER_ACCOUNT = latestBy(['account'], [{ field: 'close_date', order: 'desc' }]);

const query = (directive: unknown, over: Partial<DriverQuery> = {}): DriverQuery => ({
orderBy: [{ field: 'account', order: 'asc' }],
...over,
[LATEST_PER_DIRECTIVE]: directive,
} as unknown as DriverQuery);

const ids = (rows: Array<Record<string, unknown>>) => rows.map((r) => String(r.id));

function declareCell(cell: DialectCell): void {
describe(`[latest per group] driver-sql — find answers one row per group (${cell.label})`, () => {
let driver: SqlDriver;
const OLD_POSTURE = process.env.OS_TENANCY_POSTURE;

beforeAll(async () => {
process.env.OS_TENANCY_POSTURE = 'isolated';
driver = new SqlDriver(cell.config());
await driver.execute(`drop table if exists ${TABLE}`).catch(() => {});
await driver.initObjects([
{
name: TABLE,
fields: {
account: { type: 'text' }, owner: { type: 'text' }, stage: { type: 'text' },
close_date: { type: 'date' }, amount: { type: 'number' }, organization_id: { type: 'text' },
},
},
] as never);
for (const row of DEALS) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true });
});

afterAll(async () => {
await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {});
await driver?.disconnect?.();
if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE;
else process.env.OS_TENANCY_POSTURE = OLD_POSTURE;
});

it('one row per group: the newest; a tie goes to the larger id; a NULL date ranks last', async () => {
const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' });
expect(ids(rows)).toEqual(['d3', 'd6', 'd7']);
});

it('ascending: the earliest per group, a tie to the smaller id, NULL still last', async () => {
const rows = await driver.find(TABLE, query(latestBy(['account'], [{ field: 'close_date', order: 'asc' }])), { tenantId: 'org_a' });
expect(ids(rows)).toEqual(['d1', 'd4', 'd7']);
});

it('a group whose newest row the where hides answers its newest ADMITTED row, never nothing', async () => {
const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, { where: { stage: { $ne: 'hidden' } } }), { tenantId: 'org_a' });
expect(ids(rows)).toEqual(['d2', 'd6', 'd7']);
});

it('inside the tenant wall: another tenant\'s newer row never wins, its groups never appear', async () => {
const a = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' });
expect(ids(a)).not.toContain('xb');
expect(ids(a)).not.toContain('yb');
const b = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_b' });
expect(ids(b)).toEqual(['xb', 'yb']);
});

it('several partition fields: one row per (account, owner)', async () => {
const rows = await driver.find(TABLE, query(latestBy(['account', 'owner'], [{ field: 'close_date', order: 'desc' }]), {
orderBy: [{ field: 'id', order: 'asc' }],
}), { tenantId: 'org_a' });
expect(ids(rows)).toEqual(['d2', 'd3', 'd5', 'd6', 'd7']);
});

it('the read\'s own ORDER BY, limit, offset and projection apply to the groups; no helper column', async () => {
const page = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, {
orderBy: [{ field: 'amount', order: 'desc' }],
limit: 2,
offset: 1,
fields: ['id', 'amount'],
}), { tenantId: 'org_a' });
// Groups by amount desc: d7 (70), d6 (60), d3 (30) → offset 1, limit 2.
expect(ids(page)).toEqual(['d6', 'd3']);
for (const row of page) expect(Object.keys(row).sort()).toEqual(['amount', 'id']);
const full = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' });
for (const row of full) expect(Object.keys(row).some((k) => k.startsWith('__os_latest_per'))).toBe(false);
});

it('control: the same read without the directive answers every row', async () => {
const rows = await driver.find(TABLE, { orderBy: [{ field: 'id', order: 'asc' }] } as DriverQuery, { tenantId: 'org_a' });
expect(ids(rows)).toEqual(['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8']);
});

it('a malformed directive is refused before anything compiles', async () => {
const err = await driver.find(TABLE, query({ by: [], orderBy: [] }), { tenantId: 'org_a' })
.then(() => null, (e: Error) => e);
expect(err?.message).toMatch(/latest-per directive is malformed/);
});
});
}

for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'find latest per group', declareCell);
Loading
Loading