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
20 changes: 20 additions & 0 deletions .changeset/35138-mcp-not-recorded.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/mcp': patch
'@objectstack/runtime': patch
'@objectstack/core': patch
'@objectstack/service-analytics': patch
---

feat(mcp): a refused record read says the data is not recorded, in the caller's language

Clause-②: yes (widening)
Metadata-protocol: none

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:

- `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.
- `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.

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.

The language is chosen by one shared picker, `pickSentenceLocale` (with `platformLocaleNamedBy`), now exported from `@objectstack/core`: the first of the caller's locales (the request's, then the workspace default) that names a language the sentence is written in, else `en`. The dataset tools' `nextStep` and `sourceLine` (`@objectstack/service-analytics`) use the same picker, with unchanged behaviour. `McpDataBridge` gains an optional `userTextLocales()` member: the HTTP bridge answers the request's ladder, the stdio bridge the principal's ladder and then the i18n service's default. A bridge without it is answered in `en`.
4 changes: 4 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ export * from './stack-organization-record-page.js';
// in packages that cannot import each other (`@objectstack/service-automation`
// and `@objectstack/runtime`'s seed load), and both already depend on this one.
export * from './organization-locale.js';
// The language a sentence in a tool's result is written in — one picker for
// the dataset tools (`@objectstack/service-analytics`) and the MCP record
// tools (`@objectstack/mcp`), which cannot import each other.
export * from './sentence-locale.js';
export * from './lite-kernel.js';
export * from './types.js';
export * from './logger.js';
Expand Down
24 changes: 24 additions & 0 deletions packages/core/src/sentence-locale.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, expect, it } from 'vitest';
import { pickSentenceLocale } from './sentence-locale.js';

describe('[#35138] pickSentenceLocale — the language of a sentence in a tool result', () => {
const WRITTEN = ['en', 'zh-Hans', 'zh-Hant', 'ja'] as const;

it('reads each code whole, then one subtag shorter, and takes the first language the producer writes', () => {
expect(pickSentenceLocale(['zh-CN'], WRITTEN)).toBe('zh-Hans');
expect(pickSentenceLocale(['zh-TW'], WRITTEN)).toBe('zh-Hant');
expect(pickSentenceLocale(['zh-Hant-HK'], WRITTEN)).toBe('zh-Hant');
expect(pickSentenceLocale(['fr-FR', 'ja-JP'], WRITTEN)).toBe('ja');
// Not in the table whole: named by a shorter prefix.
expect(pickSentenceLocale(['ja-JP-u-ca-japanese'], WRITTEN)).toBe('ja');
expect(pickSentenceLocale(['zh-Hans-SG-x-a'], WRITTEN)).toBe('zh-Hans');
});

it('a language the producer does not write takes the next rung, and `en` is the floor', () => {
expect(pickSentenceLocale(['zh-CN'], ['en', 'ja'] as const)).toBe('en');
expect(pickSentenceLocale(['fr-FR', undefined, ''], WRITTEN)).toBe('en');
expect(pickSentenceLocale([], WRITTEN)).toBe('en');
});
});
47 changes: 47 additions & 0 deletions packages/core/src/sentence-locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/system';

/**
* [ADR-0149 M1] The language a platform-composed sentence in a tool's result
* is written in: one picker shared by the dataset tools (`nextStep` and
* `sourceLine` in `@objectstack/service-analytics`) and the MCP record tools
* (`ifNotRecorded` in `@objectstack/mcp`), so those producers never disagree
* on the language for the same caller.
*
* `locales` is the caller's ladder in order, as a door hands it
* ({@link userTextLocalesOf}: the request's locale, then the workspace
* default); `written` is the languages the producer has sentences for. The
* first code that names one of them decides, else `en`, the floor every
* producer writes. A code is read through the platform locale table
* (`platformLocaleTagOf`), whole and then one subtag shorter at a time
* ({@link platformLocaleNamedBy}), so a language the producer does not write
* takes the next rung rather than a guess.
*/
export function pickSentenceLocale<T extends PlatformLocaleTag>(
locales: readonly (string | undefined)[],
written: readonly T[],
): T | 'en' {
for (const code of locales) {
const tag = platformLocaleNamedBy(code);
if (tag !== undefined && (written as readonly PlatformLocaleTag[]).includes(tag)) return tag as T;
}
return 'en';
}

/**
* The platform locale a code names, or `undefined`: the whole code through
* `platformLocaleTagOf`, then each shorter prefix one subtag at a time (RFC
* 4647 lookup: `zh-CN` → `zh-Hans`, `en-GB` → `en`, `zh-Hant-TW` → `zh-Hant`).
* The first prefix the table names decides, so a Traditional Chinese code is
* never handed the Simplified sentence.
*/
export function platformLocaleNamedBy(code: string | undefined): PlatformLocaleTag | undefined {
if (typeof code !== 'string' || code.length === 0) return undefined;
const subtags = code.split('-');
for (let n = subtags.length; n > 0; n -= 1) {
const tag = platformLocaleTagOf(subtags.slice(0, n).join('-'));
if (tag !== undefined) return tag;
}
return undefined;
}
233 changes: 217 additions & 16 deletions packages/mcp/src/mcp-http-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ import { AggregationNodeSchema, SEARCH_COMPANION_FIELD } from '@objectstack/spec
import { StandardErrorCode, type ErrorCode } from '@objectstack/spec/api';
// The repo's ONE not-found envelope, which the HTTP bridge's `get` throws:
// `get_record` refuses a null read with it, so both doors answer one 404.
import { recordNotFoundError } from '@objectstack/core';
import { pickSentenceLocale, recordNotFoundError } from '@objectstack/core';
import { SystemFieldName } from '@objectstack/spec/system';
// [#23701] The one key every door that translates the engine's unique-violation
// envelope asks (the registered code AND the class name, never message text),
// and the one classification whose arm states the wire code for it.
Expand Down Expand Up @@ -281,6 +282,19 @@ export interface McpDataBridge {
timezone?: string;
},
): Promise<unknown[]>;
/**
* [#35138] The caller's locale ladder for a sentence the tools compose into
* a result (`ifNotRecorded`): the codes in order, the shared picker
* (`pickSentenceLocale`, `@objectstack/core`) choosing the first language
* the sentence is written in, `en` below all. The HTTP bridge answers
* `userTextLocalesOf` over the request's `ExecutionContext`, the ladder the
* dataset tools' `nextStep` reads on that door; the stdio bridge answers the
* principal's ladder, then the i18n service's default.
*
* OPTIONAL: a bridge that omits it, or whose answer throws, is written to in
* `en`.
*/
userTextLocales?(): Promise<readonly string[]>;
/**
* [ADR-0149 D2] `list_datasets`: the governed datasets this caller may
* query, each with its dimensions and measures, their business vocabulary,
Expand Down Expand Up @@ -1204,9 +1218,14 @@ function refusalAsTheDoorServesIt(envelope: ThrownRefusalEnvelope, door: DataDoo
* code-less sentences, which the door's message heuristics would misread, so
* it keeps {@link errorResultWithCode}.
*/
function dataDoorErrorResult(err: unknown, tool: DataDoorTool | typeof DELETE_RECORDS_TOOL, objectName: string) {
function dataDoorErrorResult(
err: unknown,
tool: DataDoorTool | typeof DELETE_RECORDS_TOOL,
objectName: string,
beside?: NotRecordedMembers,
) {
const envelope = dataDoorRefusalEnvelope(err, objectName);
if (envelope) return codedErrorResult({ ...envelope });
if (envelope) return codedErrorResult({ ...envelope }, beside);
const door = dataDoorAnswerOf(err, objectName);
if (isServerFault(door.status)) {
logServerFault({
Expand All @@ -1216,7 +1235,181 @@ function dataDoorErrorResult(err: unknown, tool: DataDoorTool | typeof DELETE_RE
request: { method: 'tools/call', path: `${tool} ${objectName}` },
});
}
return codedErrorResult(door);
return codedErrorResult(door, isServerFault(door.status) ? undefined : beside);
}

/**
* [#35138] What a record read's refusal says about data the caller's app does
* not record: `notRecorded` names it, as the caller sent it, and
* `ifNotRecorded` tells the model, in the caller's language, to say so rather
* than answer around a bare not-found. Rendered beside the coded refusal
* (`{ error, notRecorded, ifNotRecorded }`), whose `error` is unchanged.
*
* - `{ object }`: the caller's schema shows no object by the name they sent;
* - `{ object, fields }`: it shows the object, and not these names the call
* sent (in the order first sent).
*/
export interface NotRecordedMembers {
notRecorded: { object: string; fields?: string[] };
ifNotRecorded: string;
}

/** The languages {@link NOT_RECORDED_SENTENCE} is written in; `en` is the floor. */
const NOT_RECORDED_LOCALES = ['en', 'zh-Hans', 'zh-Hant', 'ja'] as const;

/**
* [#35138, ADR-0149 M1] The `ifNotRecorded` sentence, one per language, in
* the executor: the spec fixes no wording. ⛔ One sentence for every case the
* member is served on, naming nothing: what is not recorded is the
* `notRecorded` member's, built from the caller's own words.
*/
const NOT_RECORDED_SENTENCE: Readonly<Record<(typeof NOT_RECORDED_LOCALES)[number], string>> = {
en:
'What notRecorded names is not recorded here, so nothing was read: tell the user this data is not recorded, '
+ 'never report 0 or an empty result for it, and do not answer with another object or field in its place.',
'zh-Hans': 'notRecorded 所列的内容在这里没有记录,因此没有读取任何数据:请告诉用户这项数据没有记录,不要为它报告 0 或空结果,也不要用其他对象或字段代替回答。',
'zh-Hant': 'notRecorded 所列的內容在這裡沒有記錄,因此沒有讀取任何資料:請告訴使用者這項資料沒有記錄,不要為它回報 0 或空結果,也不要用其他物件或欄位代替回答。',
ja: 'notRecorded に挙げたものはここに記録されていないため、何も読み取っていません:このデータは記録されていないとユーザーに伝え、0 や空の結果を報告せず、別のオブジェクトやフィールドで代わりに答えないでください。',
};

/**
* The columns every object answers whatever its schema lists: the primary key
* and the two audit timestamps the engine's read and write doors admit on any
* object (`PLATFORM_PROVISIONED_COLUMNS`, `@objectstack/objectql`). A schema
* need not list them, so their absence there never makes them not recorded.
*/
const ALWAYS_ADDRESSABLE_COLUMNS: ReadonlySet<string> = new Set([
SystemFieldName.ID,
SystemFieldName.CREATED_AT,
SystemFieldName.UPDATED_AT,
]);

/** The logical operators whose operands are themselves conditions on the object's fields. */
const WHERE_LOGICAL_OPERATORS: ReadonlySet<string> = new Set(['$and', '$or', '$nor', '$not']);

/**
* The name a sent field name addresses on the object itself: its first path
* segment. A dotted name (`owner.name`) reaches a relation's field through its
* head, and the head is what the object's schema lists; the rest is the
* related object's business. Every channel's names are read this way.
*/
function sentFieldHead(name: string): string {
return name.split('.')[0];
}

/**
* The field names a `where` the caller sent addresses, in order: each
* condition key, through the logical operators. Other `$` keys are operators,
* never names.
*/
function whereFieldNames(where: unknown, into: string[]): string[] {
if (Array.isArray(where)) {
for (const branch of where) whereFieldNames(branch, into);
return into;
}
if (!where || typeof where !== 'object') return into;
for (const [key, value] of Object.entries(where as Record<string, unknown>)) {
if (key.startsWith('$')) {
if (WHERE_LOGICAL_OPERATORS.has(key)) whereFieldNames(value, into);
continue;
}
into.push(key);
}
return into;
}

/** The field names a `query_records` call sent: `where`, `fields`, `orderBy`. */
function queryRecordsSentFields(args: {
where?: Record<string, unknown>;
fields?: string[];
orderBy?: Array<{ field: string }>;
}): string[] {
return [
...whereFieldNames(args.where, []),
...(args.fields ?? []),
...(args.orderBy ?? []).map((o) => o.field),
];
}

/** The field names an `aggregate_records` call sent: `where`, `groupBy`, each aggregation's `field` and `filter`. */
function aggregateRecordsSentFields(args: {
where?: Record<string, unknown>;
groupBy?: Array<string | { field: string }>;
aggregations: Array<{ field?: string; filter?: unknown }>;
}): string[] {
const names = whereFieldNames(args.where, []);
for (const g of args.groupBy ?? []) names.push(typeof g === 'string' ? g : g.field);
for (const a of args.aggregations) {
if (typeof a.field === 'string' && a.field !== '') names.push(a.field);
whereFieldNames(a.filter, names);
}
return names;
}

/**
* [#35138] {@link NotRecordedMembers} for a refused record read, or
* `undefined`. Decided from two things only: the names the caller sent, and
* the object as the caller's own schema shows it (`describeObject`, the
* `describe_object` answer). ⛔ So an object or a field the caller's schema
* does not show is answered exactly as one that does not exist, whatever the
* refusal beside it says, and nothing the schema shows is ever named or
* counted. Each sent name is read by its head ({@link sentFieldHead}) on
* 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
* nothing: no member.
*/
async function notRecordedMembersOf(
bridge: McpDataBridge,
objectName: string,
sentFields: readonly string[],
): Promise<NotRecordedMembers | undefined> {
let served: unknown;
try {
served = await bridge.describeObject(objectName);
} catch {
return undefined;
}
let notRecorded: NotRecordedMembers['notRecorded'];
if (served == null) {
notRecorded = { object: objectName };
} else {
const fields = (served as { fields?: unknown }).fields;
if (!Array.isArray(fields)) return undefined;
const shown = new Set<string>(ALWAYS_ADDRESSABLE_COLUMNS);
for (const f of fields) {
const name = (f as { name?: unknown } | null)?.name;
if (typeof name === 'string') shown.add(name);
}
const heads = sentFields.map(sentFieldHead).filter((head) => head !== '');
const absent = [...new Set(heads)].filter((name) => !shown.has(name));
if (absent.length === 0) return undefined;
notRecorded = { object: objectName, fields: absent };
}
let locales: readonly string[] = [];
try {
locales = (await bridge.userTextLocales?.()) ?? [];
} catch {
locales = [];
}
return { notRecorded, ifNotRecorded: NOT_RECORDED_SENTENCE[pickSentenceLocale(locales, NOT_RECORDED_LOCALES)] };
}

/**
* [#35138] A record read tool's answer to a throw ({@link dataDoorErrorResult},
* unchanged), with {@link NotRecordedMembers} beside the refusal where the
* caller's schema does not show what the call named. A server fault is not a
* refusal and carries none.
*/
async function recordReadErrorResult(
bridge: McpDataBridge,
err: unknown,
tool: 'query_records' | 'aggregate_records' | 'get_record',
objectName: string,
sentFields: readonly string[],
) {
const refusal = dataDoorRefusalEnvelope(err, objectName) !== undefined
|| !isServerFault(dataDoorAnswerOf(err, objectName).status);
const beside = refusal ? await notRecordedMembersOf(bridge, objectName, sentFields) : undefined;
return dataDoorErrorResult(err, tool, objectName, beside);
}

/**
Expand Down Expand Up @@ -1296,16 +1489,19 @@ function landedWriteResultOrError(
* (`tool-call-interceptor.ts`), so a host's deny reaches the client in the
* envelope the tools' own refusals use; not on the package entry.
*/
export function codedErrorResult(error: {
code?: string;
message: string;
status?: number;
declaredCode?: string;
userMessage?: string;
details?: unknown;
}) {
export function codedErrorResult(
error: {
code?: string;
message: string;
status?: number;
declaredCode?: string;
userMessage?: string;
details?: unknown;
},
beside?: NotRecordedMembers,
) {
return {
content: [{ type: 'text' as const, text: jsonText({ error }) }],
content: [{ type: 'text' as const, text: jsonText(beside ? { error, ...beside } : { error }) }],
isError: true as const,
};
}
Expand Down Expand Up @@ -3196,7 +3392,8 @@ export function registerObjectTools(
if (!diagnosed?.narrowed || !diagnosed.statement) return textResult(result);
return textResult(withDelegationNotice(result, diagnosed.statement));
} catch (err) {
return dataDoorErrorResult(err, 'query_records', objectName);
// [#35138] …with what the call named that the caller's schema does not show.
return recordReadErrorResult(bridge, err, 'query_records', objectName, queryRecordsSentFields({ where, fields, orderBy }));
}
},
);
Expand Down Expand Up @@ -3306,7 +3503,10 @@ export function registerObjectTools(
...(Object.keys(currencies).length > 0 ? { currencies } : {}),
});
} catch (err) {
return dataDoorErrorResult(err, 'aggregate_records', objectName);
// [#35138] …with what the call named that the caller's schema does not show.
return recordReadErrorResult(
bridge, err, 'aggregate_records', objectName, aggregateRecordsSentFields({ where, groupBy, aggregations }),
);
}
},
);
Expand Down Expand Up @@ -3340,7 +3540,8 @@ export function registerObjectTools(
if (record == null) throw recordNotFoundError(objectName, recordId);
return textResult(record);
} catch (err) {
return dataDoorErrorResult(err, 'get_record', objectName);
// [#35138] …and an object the caller's schema does not show is said to be not recorded.
return recordReadErrorResult(bridge, err, 'get_record', objectName, []);
}
},
);
Expand Down
Loading
Loading