Skip to content

Commit 8856afc

Browse files
feat(mcp): a refused record read says what is not recorded, in the caller's language (#35198)
<!-- 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 notRecorded) Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:MCP 的 `query_records` / `aggregate_records` / `get_record` 被拒绝时,若调用点名的对象或字段在调用者自己的 schema 里不存在,拒绝旁边多出 `notRecorded`(点名的是哪个对象/字段,原样取自调用者的输入)和 `ifNotRecorded`(按调用者语言的一句话:告诉用户"这项数据没有记录",不要报 0);新增 `@objectstack/core` 的共享句子语言选择器,数据集工具改用它,行为不变。 - 为什么改:托管侧实测模型拿到裸的 not-found 会绕着答(报 0 或拿别的字段凑),开源 MCP 门的客户端和每日问数轮次拿不到这条信号;本 PR 把它搬进框架。 - 风险与回滚:原有拒绝(`isError`、`code`、`message`、`status`)字节不变,只在拒绝旁追加两个成员;两个成员只由"调用者发送的名字"和"调用者被服务的 schema"构成,不点名调用者看不到的任何东西。回滚即 revert 本 PR。 - 先看:`packages/mcp/src/mcp-http-tools.ts` 的 `notRecordedMembersOf` / `recordReadErrorResult`(决定何时出现成员、成员由什么构成);`packages/core/src/sentence-locale.ts`(共享选择器);`packages/services/service-analytics/src/dataset-next-step.ts`(改用共享选择器)。 - 两分钟验证:`pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-not-recorded.test.ts`,预期 14 个用例全绿,其中 CONTROL 用例断言"看不到的字段/对象"与"不存在的字段/对象"成员文本逐字节相同。 - 需要你做的:无,席位落地。 ## What changes - **`notRecorded` / `ifNotRecorded` on a refused record read.** `query_records`, `aggregate_records` and `get_record` keep their coded refusal byte for byte and, where the call named an object or a field that the caller's served schema (`describeObject`, the `describe_object` answer) does not show, render `{ error, notRecorded, ifNotRecorded }`: - `notRecorded`: `{ object }` when the schema shows no such object; `{ object, fields }` with the field names the call sent that the schema does not show, in the order sent (read from `where` through `$and` / `$or` / `$nor` / `$not`, a dotted key by its head, `fields`, `orderBy`, `groupBy`, each aggregation's `field` and `filter`); - `ifNotRecorded`: one sentence in the caller's language (en, zh-Hans, zh-Hant, ja), written in the executor (ADR-0149 M1: no wording in the spec). - **The rule.** The answer names only what the caller can see: both members are built from the names the caller sent and the caller's served schema, nothing else, with one wording for every case; nothing the schema shows is named or counted. A read that answers, a refusal about a field the schema shows, a server fault, and a refusal whose schema read throws carry no member. `id`, `created_at`, `updated_at` (answered on every object, `PLATFORM_PROVISIONED_COLUMNS`) are never named. - **One sentence-locale picker** in `@objectstack/core`: `pickSentenceLocale(locales, written)` and `platformLocaleNamedBy(code)`, moved from `service-analytics`' `dataset-next-step.ts`. `datasetToolSentenceLocale` now wraps it; its pins are unchanged and green. - **A locale member on both bridges:** optional `McpDataBridge.userTextLocales()`. HTTP: `userTextLocalesOf(ec)`, the ladder the dataset tools read on that door. stdio: the principal's ladder (what the dataset tools read there), then the i18n service's default. Absent or throwing: `en`. - Type stays local to `packages/mcp` (`NotRecordedMembers`); nothing enters `packages/spec`. ## Tests - `packages/mcp/src/mcp-not-recorded.test.ts` (14): unknown object on all three tools; unknown field on `query_records` and `aggregate_records`; CONTROL: a field (and an object) the caller cannot see answers members byte-identical to one that does not exist, whatever refusal stands beside them; a readable existing field, `id` / `created_at` / `updated_at`, a successful read, a server fault and a failing schema read carry no member; zh / zh-Hant / ja / fallback / no-member / throwing locale; the stdio bridge's `userTextLocales`. - `packages/runtime/src/domains/mcp-not-recorded.test.ts` (5): over the real security layer (`SecurityPlugin`, `ObjectQL`, `SqlDriver`, protocol), the HTTP bridge's served schema shows neither a field the caller is denied nor an unknown field, `describeObject` answers `null` for an object the caller cannot read as for an unknown name, a read naming either is refused 4xx, CONTROL the staff reads both, and `userTextLocales` answers `userTextLocalesOf(ec)`. - `packages/core/src/sentence-locale.test.ts` (2): whole-code and prefix lookup, next rung, `en` floor. - Existing pins adjusted: the tripwire's face roster and the stdio member roster gain `userTextLocales`; the HTTP twin in `stdio-data-bridge.not-found.test.ts` now serves `task` (as the stdio side does), so the PARITY pin still compares like with like. <details><summary>Package runs (head e4c3aa0, then the merge of origin/main at ee70211)</summary> - `@objectstack/mcp` typecheck (incl. `check:test-typecheck`) exit 0; `vitest run`: 72 files / 1285 tests passed at e4c3aa0, 73 files / 1306 tests passed at ee70211. - `@objectstack/core` + `@objectstack/service-analytics` `vitest run`: 161 files / 3734 tests and 218 files / 5592 passed, 335 skipped; typecheck exit 0 for both. - `@objectstack/runtime` typecheck exit 0; `vitest run`: 627 files / 12969 passed, 25 skipped (e4c3aa0 tree before the member move; `src/domains/mcp*` re-run at ee70211: 9 files / 289 passed). </details> <details><summary>Ablations (each through scripts/ablation-replace.mjs: anchor hit once, blob changed, restored to the HEAD blob with an empty git diff HEAD)</summary> | Mutation | Pin | Result | |:--|:--|:--| | members never computed | object + field + CONTROL + locale | 9 failed | | sent field names never compared | field pins + CONTROL | 3 failed / 14 | | members made to depend on the refusal's code | CONTROL | 2 failed / 14 | | served fields not read | readable-field pin | 3 failed / 14 | | always-answered columns dropped | readable-field pin | 3 failed / 14 | | sentence always en | zh pin | 1 failed / 14 | | dataset picker narrowed to en | service-analytics nextStep / sourceLine locale pins | 8 failed | | core picker without prefix lookup | core pin | 1 failed / 2 (the first run stayed green: every code in the test was named whole by the table; prefix-only codes added, then red) | | HTTP bridge locale member empty | runtime locale pin | 1 failed / 5 | | stdio i18n-default rung dropped | stdio pin | 1 failed / 14 | </details> ## Acceptance notes - The members are decided by the names sent and the caller's served schema alone, never by the refusal beside them; a server fault (5xx) carries none. - `ifNotRecorded` is not described in the three tool descriptions; the sentence states its own instruction. The card's ask cards (`#35113`) are outside this PR's file surface. - `aggregate_records` reads the served object a second way for option order and currency (`servedFieldsOf`, landed in this card's PR 2, through `servedObjectDefinitionOf`); this PR reads `describeObject`, which tells an unserved object (`null`) from one it cannot read and leaves the search companion out, which that helper does not. - `pnpm check:dual-build-cjs-loads` locally: PREREQUISITE NOT MET (needs a full workspace build); CI runs it. ## Verification <details><summary>Derived gate families (dispatch-gates --commands, head e4c3aa0)</summary> 76 derived, 75 exit 0, 1 NOT MEASURED (`pnpm check:dual-build-cjs-loads`, exit 3, no full build). `dispatch-gates --ran`: 76 accounted, 75 run, 1 NOT-MEASURED. After merging origin/main (ee70211) re-run: `check:type-check-coverage`, `check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check:nul-bytes`, `check:doc-authoring`, `check:issue-citations`, `check:test-source-alias`, `check:cross-package-test-inputs`, `check:published-files` all exit 0; `check:type-check-debt` hit the local 300 s timeout (exit 124, NOT MEASURED there; exit 0 at e4c3aa0). `overlap-check.mjs` before each push. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0739dee commit 8856afc

13 files changed

Lines changed: 1015 additions & 45 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/runtime': patch
4+
'@objectstack/core': patch
5+
'@objectstack/service-analytics': patch
6+
---
7+
8+
feat(mcp): a refused record read says the data is not recorded, in the caller's language
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: none
12+
13+
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:
14+
15+
- `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.
16+
- `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.
17+
18+
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.
19+
20+
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`.

‎packages/core/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,10 @@ export * from './stack-organization-record-page.js';
5959
// in packages that cannot import each other (`@objectstack/service-automation`
6060
// and `@objectstack/runtime`'s seed load), and both already depend on this one.
6161
export * from './organization-locale.js';
62+
// The language a sentence in a tool's result is written in — one picker for
63+
// the dataset tools (`@objectstack/service-analytics`) and the MCP record
64+
// tools (`@objectstack/mcp`), which cannot import each other.
65+
export * from './sentence-locale.js';
6266
export * from './lite-kernel.js';
6367
export * from './types.js';
6468
export * from './logger.js';
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, expect, it } from 'vitest';
4+
import { pickSentenceLocale } from './sentence-locale.js';
5+
6+
describe('[#35138] pickSentenceLocale — the language of a sentence in a tool result', () => {
7+
const WRITTEN = ['en', 'zh-Hans', 'zh-Hant', 'ja'] as const;
8+
9+
it('reads each code whole, then one subtag shorter, and takes the first language the producer writes', () => {
10+
expect(pickSentenceLocale(['zh-CN'], WRITTEN)).toBe('zh-Hans');
11+
expect(pickSentenceLocale(['zh-TW'], WRITTEN)).toBe('zh-Hant');
12+
expect(pickSentenceLocale(['zh-Hant-HK'], WRITTEN)).toBe('zh-Hant');
13+
expect(pickSentenceLocale(['fr-FR', 'ja-JP'], WRITTEN)).toBe('ja');
14+
// Not in the table whole: named by a shorter prefix.
15+
expect(pickSentenceLocale(['ja-JP-u-ca-japanese'], WRITTEN)).toBe('ja');
16+
expect(pickSentenceLocale(['zh-Hans-SG-x-a'], WRITTEN)).toBe('zh-Hans');
17+
});
18+
19+
it('a language the producer does not write takes the next rung, and `en` is the floor', () => {
20+
expect(pickSentenceLocale(['zh-CN'], ['en', 'ja'] as const)).toBe('en');
21+
expect(pickSentenceLocale(['fr-FR', undefined, ''], WRITTEN)).toBe('en');
22+
expect(pickSentenceLocale([], WRITTEN)).toBe('en');
23+
});
24+
});
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/system';
4+
5+
/**
6+
* [ADR-0149 M1] The language a platform-composed sentence in a tool's result
7+
* is written in: one picker shared by the dataset tools (`nextStep` and
8+
* `sourceLine` in `@objectstack/service-analytics`) and the MCP record tools
9+
* (`ifNotRecorded` in `@objectstack/mcp`), so those producers never disagree
10+
* on the language for the same caller.
11+
*
12+
* `locales` is the caller's ladder in order, as a door hands it
13+
* ({@link userTextLocalesOf}: the request's locale, then the workspace
14+
* default); `written` is the languages the producer has sentences for. The
15+
* first code that names one of them decides, else `en`, the floor every
16+
* producer writes. A code is read through the platform locale table
17+
* (`platformLocaleTagOf`), whole and then one subtag shorter at a time
18+
* ({@link platformLocaleNamedBy}), so a language the producer does not write
19+
* takes the next rung rather than a guess.
20+
*/
21+
export function pickSentenceLocale<T extends PlatformLocaleTag>(
22+
locales: readonly (string | undefined)[],
23+
written: readonly T[],
24+
): T | 'en' {
25+
for (const code of locales) {
26+
const tag = platformLocaleNamedBy(code);
27+
if (tag !== undefined && (written as readonly PlatformLocaleTag[]).includes(tag)) return tag as T;
28+
}
29+
return 'en';
30+
}
31+
32+
/**
33+
* The platform locale a code names, or `undefined`: the whole code through
34+
* `platformLocaleTagOf`, then each shorter prefix one subtag at a time (RFC
35+
* 4647 lookup: `zh-CN` → `zh-Hans`, `en-GB` → `en`, `zh-Hant-TW` → `zh-Hant`).
36+
* The first prefix the table names decides, so a Traditional Chinese code is
37+
* never handed the Simplified sentence.
38+
*/
39+
export function platformLocaleNamedBy(code: string | undefined): PlatformLocaleTag | undefined {
40+
if (typeof code !== 'string' || code.length === 0) return undefined;
41+
const subtags = code.split('-');
42+
for (let n = subtags.length; n > 0; n -= 1) {
43+
const tag = platformLocaleTagOf(subtags.slice(0, n).join('-'));
44+
if (tag !== undefined) return tag;
45+
}
46+
return undefined;
47+
}

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 217 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,8 @@ import { resolveDisplayField } from '@objectstack/spec/data';
5757
import { StandardErrorCode, type ErrorCode } from '@objectstack/spec/api';
5858
// The repo's ONE not-found envelope, which the HTTP bridge's `get` throws:
5959
// `get_record` refuses a null read with it, so both doors answer one 404.
60-
import { recordNotFoundError } from '@objectstack/core';
60+
import { pickSentenceLocale, recordNotFoundError } from '@objectstack/core';
61+
import { SystemFieldName } from '@objectstack/spec/system';
6162
// [#23701] The one key every door that translates the engine's unique-violation
6263
// envelope asks (the registered code AND the class name, never message text),
6364
// and the one classification whose arm states the wire code for it.
@@ -293,6 +294,19 @@ export interface McpDataBridge {
293294
timezone?: string;
294295
},
295296
): Promise<unknown[]>;
297+
/**
298+
* [#35138] The caller's locale ladder for a sentence the tools compose into
299+
* a result (`ifNotRecorded`): the codes in order, the shared picker
300+
* (`pickSentenceLocale`, `@objectstack/core`) choosing the first language
301+
* the sentence is written in, `en` below all. The HTTP bridge answers
302+
* `userTextLocalesOf` over the request's `ExecutionContext`, the ladder the
303+
* dataset tools' `nextStep` reads on that door; the stdio bridge answers the
304+
* principal's ladder, then the i18n service's default.
305+
*
306+
* OPTIONAL: a bridge that omits it, or whose answer throws, is written to in
307+
* `en`.
308+
*/
309+
userTextLocales?(): Promise<readonly string[]>;
296310
/**
297311
* [ADR-0149 D2] `list_datasets`: the governed datasets this caller may
298312
* query, each with its dimensions and measures, their business vocabulary,
@@ -1385,9 +1399,14 @@ function refusalAsTheDoorServesIt(envelope: ThrownRefusalEnvelope, door: DataDoo
13851399
* code-less sentences, which the door's message heuristics would misread, so
13861400
* it keeps {@link errorResultWithCode}.
13871401
*/
1388-
function dataDoorErrorResult(err: unknown, tool: DataDoorTool | typeof DELETE_RECORDS_TOOL, objectName: string) {
1402+
function dataDoorErrorResult(
1403+
err: unknown,
1404+
tool: DataDoorTool | typeof DELETE_RECORDS_TOOL,
1405+
objectName: string,
1406+
beside?: NotRecordedMembers,
1407+
) {
13891408
const envelope = dataDoorRefusalEnvelope(err, objectName);
1390-
if (envelope) return codedErrorResult({ ...envelope });
1409+
if (envelope) return codedErrorResult({ ...envelope }, beside);
13911410
const door = dataDoorAnswerOf(err, objectName);
13921411
if (isServerFault(door.status)) {
13931412
logServerFault({
@@ -1397,7 +1416,181 @@ function dataDoorErrorResult(err: unknown, tool: DataDoorTool | typeof DELETE_RE
13971416
request: { method: 'tools/call', path: `${tool} ${objectName}` },
13981417
});
13991418
}
1400-
return codedErrorResult(door);
1419+
return codedErrorResult(door, isServerFault(door.status) ? undefined : beside);
1420+
}
1421+
1422+
/**
1423+
* [#35138] What a record read's refusal says about data the caller's app does
1424+
* not record: `notRecorded` names it, as the caller sent it, and
1425+
* `ifNotRecorded` tells the model, in the caller's language, to say so rather
1426+
* than answer around a bare not-found. Rendered beside the coded refusal
1427+
* (`{ error, notRecorded, ifNotRecorded }`), whose `error` is unchanged.
1428+
*
1429+
* - `{ object }`: the caller's schema shows no object by the name they sent;
1430+
* - `{ object, fields }`: it shows the object, and not these names the call
1431+
* sent (in the order first sent).
1432+
*/
1433+
export interface NotRecordedMembers {
1434+
notRecorded: { object: string; fields?: string[] };
1435+
ifNotRecorded: string;
1436+
}
1437+
1438+
/** The languages {@link NOT_RECORDED_SENTENCE} is written in; `en` is the floor. */
1439+
const NOT_RECORDED_LOCALES = ['en', 'zh-Hans', 'zh-Hant', 'ja'] as const;
1440+
1441+
/**
1442+
* [#35138, ADR-0149 M1] The `ifNotRecorded` sentence, one per language, in
1443+
* the executor: the spec fixes no wording. ⛔ One sentence for every case the
1444+
* member is served on, naming nothing: what is not recorded is the
1445+
* `notRecorded` member's, built from the caller's own words.
1446+
*/
1447+
const NOT_RECORDED_SENTENCE: Readonly<Record<(typeof NOT_RECORDED_LOCALES)[number], string>> = {
1448+
en:
1449+
'What notRecorded names is not recorded here, so nothing was read: tell the user this data is not recorded, '
1450+
+ 'never report 0 or an empty result for it, and do not answer with another object or field in its place.',
1451+
'zh-Hans': 'notRecorded 所列的内容在这里没有记录,因此没有读取任何数据:请告诉用户这项数据没有记录,不要为它报告 0 或空结果,也不要用其他对象或字段代替回答。',
1452+
'zh-Hant': 'notRecorded 所列的內容在這裡沒有記錄,因此沒有讀取任何資料:請告訴使用者這項資料沒有記錄,不要為它回報 0 或空結果,也不要用其他物件或欄位代替回答。',
1453+
ja: 'notRecorded に挙げたものはここに記録されていないため、何も読み取っていません:このデータは記録されていないとユーザーに伝え、0 や空の結果を報告せず、別のオブジェクトやフィールドで代わりに答えないでください。',
1454+
};
1455+
1456+
/**
1457+
* The columns every object answers whatever its schema lists: the primary key
1458+
* and the two audit timestamps the engine's read and write doors admit on any
1459+
* object (`PLATFORM_PROVISIONED_COLUMNS`, `@objectstack/objectql`). A schema
1460+
* need not list them, so their absence there never makes them not recorded.
1461+
*/
1462+
const ALWAYS_ADDRESSABLE_COLUMNS: ReadonlySet<string> = new Set([
1463+
SystemFieldName.ID,
1464+
SystemFieldName.CREATED_AT,
1465+
SystemFieldName.UPDATED_AT,
1466+
]);
1467+
1468+
/** The logical operators whose operands are themselves conditions on the object's fields. */
1469+
const WHERE_LOGICAL_OPERATORS: ReadonlySet<string> = new Set(['$and', '$or', '$nor', '$not']);
1470+
1471+
/**
1472+
* The name a sent field name addresses on the object itself: its first path
1473+
* segment. A dotted name (`owner.name`) reaches a relation's field through its
1474+
* head, and the head is what the object's schema lists; the rest is the
1475+
* related object's business. Every channel's names are read this way.
1476+
*/
1477+
function sentFieldHead(name: string): string {
1478+
return name.split('.')[0];
1479+
}
1480+
1481+
/**
1482+
* The field names a `where` the caller sent addresses, in order: each
1483+
* condition key, through the logical operators. Other `$` keys are operators,
1484+
* never names.
1485+
*/
1486+
function whereFieldNames(where: unknown, into: string[]): string[] {
1487+
if (Array.isArray(where)) {
1488+
for (const branch of where) whereFieldNames(branch, into);
1489+
return into;
1490+
}
1491+
if (!where || typeof where !== 'object') return into;
1492+
for (const [key, value] of Object.entries(where as Record<string, unknown>)) {
1493+
if (key.startsWith('$')) {
1494+
if (WHERE_LOGICAL_OPERATORS.has(key)) whereFieldNames(value, into);
1495+
continue;
1496+
}
1497+
into.push(key);
1498+
}
1499+
return into;
1500+
}
1501+
1502+
/** The field names a `query_records` call sent: `where`, `fields`, `orderBy`. */
1503+
function queryRecordsSentFields(args: {
1504+
where?: Record<string, unknown>;
1505+
fields?: string[];
1506+
orderBy?: Array<{ field: string }>;
1507+
}): string[] {
1508+
return [
1509+
...whereFieldNames(args.where, []),
1510+
...(args.fields ?? []),
1511+
...(args.orderBy ?? []).map((o) => o.field),
1512+
];
1513+
}
1514+
1515+
/** The field names an `aggregate_records` call sent: `where`, `groupBy`, each aggregation's `field` and `filter`. */
1516+
function aggregateRecordsSentFields(args: {
1517+
where?: Record<string, unknown>;
1518+
groupBy?: Array<string | { field: string }>;
1519+
aggregations: Array<{ field?: string; filter?: unknown }>;
1520+
}): string[] {
1521+
const names = whereFieldNames(args.where, []);
1522+
for (const g of args.groupBy ?? []) names.push(typeof g === 'string' ? g : g.field);
1523+
for (const a of args.aggregations) {
1524+
if (typeof a.field === 'string' && a.field !== '') names.push(a.field);
1525+
whereFieldNames(a.filter, names);
1526+
}
1527+
return names;
1528+
}
1529+
1530+
/**
1531+
* [#35138] {@link NotRecordedMembers} for a refused record read, or
1532+
* `undefined`. Decided from two things only: the names the caller sent, and
1533+
* the object as the caller's own schema shows it (`describeObject`, the
1534+
* `describe_object` answer). ⛔ So an object or a field the caller's schema
1535+
* does not show is answered exactly as one that does not exist, whatever the
1536+
* refusal beside it says, and nothing the schema shows is ever named or
1537+
* counted. Each sent name is read by its head ({@link sentFieldHead}) on
1538+
* 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
1539+
* nothing: no member.
1540+
*/
1541+
async function notRecordedMembersOf(
1542+
bridge: McpDataBridge,
1543+
objectName: string,
1544+
sentFields: readonly string[],
1545+
): Promise<NotRecordedMembers | undefined> {
1546+
let served: unknown;
1547+
try {
1548+
served = await bridge.describeObject(objectName);
1549+
} catch {
1550+
return undefined;
1551+
}
1552+
let notRecorded: NotRecordedMembers['notRecorded'];
1553+
if (served == null) {
1554+
notRecorded = { object: objectName };
1555+
} else {
1556+
const fields = (served as { fields?: unknown }).fields;
1557+
if (!Array.isArray(fields)) return undefined;
1558+
const shown = new Set<string>(ALWAYS_ADDRESSABLE_COLUMNS);
1559+
for (const f of fields) {
1560+
const name = (f as { name?: unknown } | null)?.name;
1561+
if (typeof name === 'string') shown.add(name);
1562+
}
1563+
const heads = sentFields.map(sentFieldHead).filter((head) => head !== '');
1564+
const absent = [...new Set(heads)].filter((name) => !shown.has(name));
1565+
if (absent.length === 0) return undefined;
1566+
notRecorded = { object: objectName, fields: absent };
1567+
}
1568+
let locales: readonly string[] = [];
1569+
try {
1570+
locales = (await bridge.userTextLocales?.()) ?? [];
1571+
} catch {
1572+
locales = [];
1573+
}
1574+
return { notRecorded, ifNotRecorded: NOT_RECORDED_SENTENCE[pickSentenceLocale(locales, NOT_RECORDED_LOCALES)] };
1575+
}
1576+
1577+
/**
1578+
* [#35138] A record read tool's answer to a throw ({@link dataDoorErrorResult},
1579+
* unchanged), with {@link NotRecordedMembers} beside the refusal where the
1580+
* caller's schema does not show what the call named. A server fault is not a
1581+
* refusal and carries none.
1582+
*/
1583+
async function recordReadErrorResult(
1584+
bridge: McpDataBridge,
1585+
err: unknown,
1586+
tool: 'query_records' | 'aggregate_records' | 'get_record',
1587+
objectName: string,
1588+
sentFields: readonly string[],
1589+
) {
1590+
const refusal = dataDoorRefusalEnvelope(err, objectName) !== undefined
1591+
|| !isServerFault(dataDoorAnswerOf(err, objectName).status);
1592+
const beside = refusal ? await notRecordedMembersOf(bridge, objectName, sentFields) : undefined;
1593+
return dataDoorErrorResult(err, tool, objectName, beside);
14011594
}
14021595

14031596
/**
@@ -1477,16 +1670,19 @@ function landedWriteResultOrError(
14771670
* (`tool-call-interceptor.ts`), so a host's deny reaches the client in the
14781671
* envelope the tools' own refusals use; not on the package entry.
14791672
*/
1480-
export function codedErrorResult(error: {
1481-
code?: string;
1482-
message: string;
1483-
status?: number;
1484-
declaredCode?: string;
1485-
userMessage?: string;
1486-
details?: unknown;
1487-
}) {
1673+
export function codedErrorResult(
1674+
error: {
1675+
code?: string;
1676+
message: string;
1677+
status?: number;
1678+
declaredCode?: string;
1679+
userMessage?: string;
1680+
details?: unknown;
1681+
},
1682+
beside?: NotRecordedMembers,
1683+
) {
14881684
return {
1489-
content: [{ type: 'text' as const, text: jsonText({ error }) }],
1685+
content: [{ type: 'text' as const, text: jsonText(beside ? { error, ...beside } : { error }) }],
14901686
isError: true as const,
14911687
};
14921688
}
@@ -3403,7 +3599,8 @@ export function registerObjectTools(
34033599
if (!diagnosed?.narrowed || !diagnosed.statement) return textResult(result);
34043600
return textResult(withDelegationNotice(result, diagnosed.statement));
34053601
} catch (err) {
3406-
return dataDoorErrorResult(err, 'query_records', objectName);
3602+
// [#35138] …with what the call named that the caller's schema does not show.
3603+
return recordReadErrorResult(bridge, err, 'query_records', objectName, queryRecordsSentFields({ where, fields, orderBy }));
34073604
}
34083605
},
34093606
);
@@ -3523,7 +3720,10 @@ export function registerObjectTools(
35233720
...(Object.keys(currencies).length > 0 ? { currencies } : {}),
35243721
});
35253722
} catch (err) {
3526-
return dataDoorErrorResult(err, 'aggregate_records', objectName);
3723+
// [#35138] …with what the call named that the caller's schema does not show.
3724+
return recordReadErrorResult(
3725+
bridge, err, 'aggregate_records', objectName, aggregateRecordsSentFields({ where, groupBy, aggregations }),
3726+
);
35273727
}
35283728
},
35293729
);
@@ -3557,7 +3757,8 @@ export function registerObjectTools(
35573757
if (record == null) throw recordNotFoundError(objectName, recordId);
35583758
return textResult(record);
35593759
} catch (err) {
3560-
return dataDoorErrorResult(err, 'get_record', objectName);
3760+
// [#35138] …and an object the caller's schema does not show is said to be not recorded.
3761+
return recordReadErrorResult(bridge, err, 'get_record', objectName, []);
35613762
}
35623763
},
35633764
);

0 commit comments

Comments
 (0)