diff --git a/.changeset/35138-mcp-not-recorded.md b/.changeset/35138-mcp-not-recorded.md new file mode 100644 index 00000000000..f7131488dc0 --- /dev/null +++ b/.changeset/35138-mcp-not-recorded.md @@ -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": "" }`, or `{ "object": "", "fields": ["", …] }` 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`. diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b3cc71bb6f6..11d9bbb4a05 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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'; diff --git a/packages/core/src/sentence-locale.test.ts b/packages/core/src/sentence-locale.test.ts new file mode 100644 index 00000000000..3147f37f84d --- /dev/null +++ b/packages/core/src/sentence-locale.test.ts @@ -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'); + }); +}); diff --git a/packages/core/src/sentence-locale.ts b/packages/core/src/sentence-locale.ts new file mode 100644 index 00000000000..6aa0c60b129 --- /dev/null +++ b/packages/core/src/sentence-locale.ts @@ -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( + 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; +} diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 5908040c1e0..f0eda4b454d 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -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. @@ -281,6 +282,19 @@ export interface McpDataBridge { timezone?: string; }, ): Promise; + /** + * [#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; /** * [ADR-0149 D2] `list_datasets`: the governed datasets this caller may * query, each with its dimensions and measures, their business vocabulary, @@ -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({ @@ -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> = { + 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 = 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 = 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)) { + 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; + 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; + groupBy?: Array; + 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 { + 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(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); } /** @@ -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, }; } @@ -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 })); } }, ); @@ -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 }), + ); } }, ); @@ -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, []); } }, ); diff --git a/packages/mcp/src/mcp-not-recorded.test.ts b/packages/mcp/src/mcp-not-recorded.test.ts new file mode 100644 index 00000000000..004b6d24cd1 --- /dev/null +++ b/packages/mcp/src/mcp-not-recorded.test.ts @@ -0,0 +1,432 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35138] A refused record read (`query_records`, `aggregate_records`, + * `get_record`) of an object, or a field, that the caller's schema does not + * show keeps its coded refusal and carries two members beside it: + * `notRecorded` (what the call named that is not recorded, as the caller sent + * it) and `ifNotRecorded` (one sentence, in the caller's locale, telling the + * model to say the data is not recorded rather than answer around a bare + * not-found). + * + * The rule: the members are built only from what the caller sent and what the + * caller's served schema (`describeObject`) shows, so an object or field the + * caller cannot see is answered exactly as one that does not exist for them, + * and nothing the schema shows is ever named. Each bridge below replays the + * refusal its door answers for the case (measured on the real security layer; + * the HTTP bridge's schema and locale answers are pinned in + * `packages/runtime/src/domains/mcp-not-recorded.test.ts`). + * + * The stdio door is pinned over the shared ADR-0106 case table, on the real + * stdio bridge and the real tools, and its locale member at the bottom. + */ + +import { describe, expect, it } 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 type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { OBJECT_SCHEMA_MASK_DISABLE_ENV } from '@objectstack/metadata-core'; +import { + FLS_CONTRACT_OBJECT, + OBJECT_SCHEMA_MASK_CASES, + securityDoubleFor, + type ObjectSchemaMaskCase, +} from '@objectstack/metadata-core/testing'; +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { registerObjectTools, type McpDataBridge } from './mcp-http-tools.js'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; + +const OBJECT = 'crm_deal'; +const SERVED_FIELDS = ['subject', 'amount', 'margin_formula', 'organization_id']; + +/** Does `name` occur in `text` as an identifier token? */ +const mentions = (text: string, name: string) => (text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? ([] as string[])).includes(name); + +/** A thrown coded refusal, as the doors throw one. */ +function refusal(code: string, status: number, message: string): Error { + return Object.assign(new Error(message), { code, status }); +} + +const OBJECT_NOT_FOUND = (name: string) => refusal('OBJECT_NOT_FOUND', 404, `Object '${name}' not found`); +const INVALID_FIELD = (name: string) => + refusal('INVALID_FIELD', 400, `Query parameter 'where' filters on '${name}', which is not a field on object '${OBJECT}'.`); +/** Refusals a door may answer beside the members: the members never depend on which. */ +const REFUSALS: ReadonlyArray<(name: string) => unknown> = [ + OBJECT_NOT_FOUND, + INVALID_FIELD, + () => refusal('PERMISSION_DENIED', 403, 'You do not have permission to perform this action.'), +]; + +interface BridgeCase { + /** Objects the caller's schema shows, each with its field names. */ + served: Record; + /** What every read throws, or `undefined` to answer. */ + throws?: (object: string) => unknown; + locales?: McpDataBridge['userTextLocales']; +} + +function makeBridge(c: BridgeCase): McpDataBridge { + const read = async (object: string, answer: unknown) => { + if (c.throws) throw c.throws(object); + return answer; + }; + const bridge: McpDataBridge = { + async listObjects() { return Object.keys(c.served).map((name) => ({ name })); }, + async describeObject(name: string) { + const fields = c.served[name]; + return fields ? { name, label: name, fields: fields.map((f) => ({ name: f, type: 'text' })) } : null; + }, + query: (object) => read(object, { object, records: [], total: 0 }), + get: (object, id) => read(object, { id }), + aggregate: (object) => read(object, []) as Promise, + async create(object, data) { return { object, data }; }, + async update(object, id) { return { object, id }; }, + async remove(object, id) { return { object, id, success: true }; }, + }; + if (c.locales) bridge.userTextLocales = c.locales; + return bridge; +} + +async function callTool(bridge: McpDataBridge, name: string, args: Record) { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }; + const req = new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }); + const res = await runtime.handleHttpRequest(req, { bridge, parsedBody: body }); + const json: any = await res.json(); + const text: string = json.result.content[0].text; + let payload: any; + try { + payload = JSON.parse(text); + } catch { + payload = undefined; + } + return { isError: json.result.isError === true, text, payload }; +} + +/** The members beside the refusal, as their own JSON text: what CONTROL compares byte for byte. */ +const membersText = (payload: any) => JSON.stringify({ notRecorded: payload.notRecorded, ifNotRecorded: payload.ifNotRecorded }); + +const EN = /^What notRecorded names is not recorded here, so nothing was read: tell the user this data is not recorded/; + +describe('[#35138] record reads: an object the caller\'s schema does not show', () => { + const bridge = () => makeBridge({ served: { [OBJECT]: SERVED_FIELDS }, throws: OBJECT_NOT_FOUND }); + + it.each([ + ['query_records', { objectName: 'crm_invoice' }], + ['aggregate_records', { objectName: 'crm_invoice', aggregations: [{ function: 'count', alias: 'n' }] }], + ['get_record', { objectName: 'crm_invoice', recordId: 'r1' }], + ])('%s keeps the coded refusal and names the object as not recorded, in one sentence', async (tool, args) => { + const answer = await callTool(bridge(), tool, args); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toEqual({ code: 'OBJECT_NOT_FOUND', message: "Object 'crm_invoice' not found", status: 404 }); + expect(answer.payload.notRecorded).toEqual({ object: 'crm_invoice' }); + expect(answer.payload.ifNotRecorded).toMatch(EN); + expect(Object.keys(answer.payload)).toEqual(['error', 'notRecorded', 'ifNotRecorded']); + for (const field of SERVED_FIELDS) expect(mentions(answer.text, field)).toBe(false); + }); +}); + +describe('[#35138] record reads: a field the caller\'s schema does not show', () => { + const bridge = () => makeBridge({ served: { [OBJECT]: SERVED_FIELDS }, throws: () => INVALID_FIELD('invoice_total') }); + + it('query_records names each field it sent that the schema does not show, in the order sent, and the coded refusal stands', async () => { + const answer = await callTool(bridge(), 'query_records', { + objectName: OBJECT, + where: { $or: [{ invoice_total: { $gt: 1 } }, { subject: 'x' }], 'invoice_lines.qty': 2 }, + fields: ['subject', 'invoice_total'], + orderBy: [{ field: 'paid_on', order: 'desc' }, { field: 'id', order: 'asc' }], + }); + expect(answer.isError).toBe(true); + expect(answer.payload.error.code).toBe('INVALID_FIELD'); + expect(answer.payload.error.status).toBe(400); + expect(answer.payload.notRecorded).toEqual({ object: OBJECT, fields: ['invoice_total', 'invoice_lines', 'paid_on'] }); + expect(answer.payload.ifNotRecorded).toMatch(EN); + }); + + it('aggregate_records reads groupBy, each aggregation\'s field and filter, and where', async () => { + const answer = await callTool(bridge(), 'aggregate_records', { + objectName: OBJECT, + groupBy: ['region', { field: 'created_at', dateGranularity: 'month' }], + aggregations: [{ function: 'sum', field: 'invoice_total', alias: 't', filter: { channel: 'web' } }], + where: { amount: { $gt: 0 } }, + }); + expect(answer.isError).toBe(true); + expect(answer.payload.notRecorded).toEqual({ object: OBJECT, fields: ['region', 'invoice_total', 'channel'] }); + }); + + it('a dotted name is read by its head on every channel: a head the schema shows is never named', async () => { + // `organization_id` is served; `organization_id.name` reaches the related + // object's field through it. Whatever the door refuses, the call named + // nothing the schema does not show. + const query = await callTool(bridge(), 'query_records', { + objectName: OBJECT, + where: { 'organization_id.name': 'x' }, + fields: ['organization_id.name'], + orderBy: [{ field: 'organization_id.name', order: 'asc' }], + }); + expect(query.isError).toBe(true); + expect(Object.keys(query.payload)).toEqual(['error']); + const aggregate = await callTool(bridge(), 'aggregate_records', { + objectName: OBJECT, + groupBy: ['organization_id.name', { field: 'organization_id.region' }], + aggregations: [{ function: 'sum', field: 'organization_id.amount', alias: 't', filter: { 'organization_id.kind': 'a' } }], + }); + expect(aggregate.isError).toBe(true); + expect(Object.keys(aggregate.payload)).toEqual(['error']); + // A dotted name whose head the schema does not show names that head. + const unknownHead = await callTool(bridge(), 'query_records', { objectName: OBJECT, fields: ['invoice_lines.qty'] }); + expect(unknownHead.payload.notRecorded).toEqual({ object: OBJECT, fields: ['invoice_lines'] }); + }); +}); + +describe('[#35138] the answer names only what the caller can see — CONTROL', () => { + it('a field the caller cannot see is answered with members byte-identical to a field that does not exist', async () => { + const args = { objectName: OBJECT, where: { margin_net: { $gt: 0 } } }; + // The same call, the same served schema: the object either declares no such + // field, or declares one the caller's schema does not show. Whatever + // refusal the door answers beside them, the members are one text. + const answers = []; + for (const throws of REFUSALS) { + answers.push(await callTool(makeBridge({ served: { [OBJECT]: SERVED_FIELDS }, throws: () => throws('margin_net') }), 'query_records', args)); + } + for (const answer of answers) { + expect(answer.isError).toBe(true); + expect(answer.payload.notRecorded).toEqual({ object: OBJECT, fields: ['margin_net'] }); + expect(membersText(answer.payload)).toBe(membersText(answers[0].payload)); + expect(Object.keys(answer.payload)).toEqual(['error', 'notRecorded', 'ifNotRecorded']); + for (const field of SERVED_FIELDS) expect(mentions(membersText(answer.payload), field)).toBe(false); + } + }); + + it('an object the caller cannot read is answered with members byte-identical to an object that does not exist', async () => { + const served = { [OBJECT]: SERVED_FIELDS }; + for (const tool of ['query_records', 'get_record'] as const) { + const args = tool === 'get_record' ? { objectName: 'crm_vault', recordId: 'r1' } : { objectName: 'crm_vault' }; + const answers = []; + for (const throws of REFUSALS) answers.push(await callTool(makeBridge({ served, throws }), tool, args)); + for (const answer of answers) { + expect(answer.payload.notRecorded).toEqual({ object: 'crm_vault' }); + expect(membersText(answer.payload)).toBe(membersText(answers[0].payload)); + } + } + }); + + it('a readable existing field is never named: a refusal about it carries no member', async () => { + const bridge = makeBridge({ + served: { [OBJECT]: SERVED_FIELDS }, + throws: () => refusal('INVALID_FIELD', 400, "sum over 'margin_formula' cannot run: a formula has no column."), + }); + const answer = await callTool(bridge, 'aggregate_records', { + objectName: OBJECT, + groupBy: ['subject'], + aggregations: [{ function: 'sum', field: 'margin_formula', alias: 't' }], + where: { id: 'r1', created_at: { $gt: '2026-01-01' }, updated_at: { $gt: '2026-01-01' } }, + }); + expect(answer.isError).toBe(true); + expect(Object.keys(answer.payload)).toEqual(['error']); + }); + + it('a read that answers carries no member, and a server fault carries none even for an unknown object', async () => { + const ok = await callTool(makeBridge({ served: { [OBJECT]: SERVED_FIELDS } }), 'query_records', { objectName: OBJECT, where: { subject: 'x' } }); + expect(ok.isError).toBe(false); + expect(ok.payload).toEqual({ object: OBJECT, records: [], total: 0 }); + const fault = await callTool( + makeBridge({ served: {}, throws: () => new Error('socket hang up (test)') }), + 'query_records', + { objectName: 'crm_invoice' }, + ); + expect(fault.isError).toBe(true); + expect(fault.payload.notRecorded).toBeUndefined(); + expect(fault.payload.ifNotRecorded).toBeUndefined(); + }); + + it('a schema read that throws establishes nothing: the refusal is served alone', async () => { + const bridge = makeBridge({ served: {}, throws: OBJECT_NOT_FOUND }); + bridge.describeObject = async () => { throw refusal('FIELD_VISIBILITY_UNRESOLVED', 503, 'x'); }; + const answer = await callTool(bridge, 'query_records', { objectName: 'crm_invoice' }); + expect(Object.keys(answer.payload)).toEqual(['error']); + }); +}); + +describe('[#35138] ifNotRecorded is written in the caller\'s locale', () => { + const sentenceFor = async (locales: McpDataBridge['userTextLocales']) => + (await callTool(makeBridge({ served: {}, throws: OBJECT_NOT_FOUND, locales }), 'query_records', { objectName: 'crm_invoice' })) + .payload.ifNotRecorded as string; + + it('a zh caller is answered the zh sentence; Traditional, Japanese and an unwritten language take their rung', async () => { + expect(await sentenceFor(async () => ['zh-CN'])).toMatch(/^notRecorded 所列的内容在这里没有记录/); + expect(await sentenceFor(async () => ['zh-TW'])).toMatch(/^notRecorded 所列的內容在這裡沒有記錄/); + expect(await sentenceFor(async () => ['fr-FR', 'ja-JP'])).toMatch(/^notRecorded に挙げたものはここに記録されていない/); + expect(await sentenceFor(async () => ['fr-FR'])).toMatch(EN); + }); + + it('a bridge with no locale member, or whose answer throws, is answered in en', async () => { + expect(await sentenceFor(undefined)).toMatch(EN); + expect(await sentenceFor(async () => { throw new Error('principal unavailable (test)'); })).toMatch(EN); + }); +}); + +describe('[#35138] stdio bridge: userTextLocales', () => { + const engine = { find: async () => [], findOne: async () => null } as unknown as IDataEngine; + const metadataService = { listObjects: async () => [], getObject: async () => undefined, list: async () => [] } as unknown as IMetadataService; + const bridgeWith = (principal: Partial, i18n?: () => unknown) => + createStdioDataBridge({ + engine, + metadataService, + resolvePrincipal: async () => ({ userId: 'u1', isSystem: false, ...principal }) as ExecutionContext, + ...(i18n ? { i18n } : {}), + }); + + it('answers the principal\'s ladder, then the i18n service\'s default', async () => { + const i18n = () => ({ getDefaultLocale: () => 'zh-CN' }); + expect(await bridgeWith({ locale: 'ja-JP', workspaceLocale: 'en-US' }, i18n).userTextLocales!()).toEqual(['ja-JP', 'en-US', 'zh-CN']); + expect(await bridgeWith({}, i18n).userTextLocales!()).toEqual(['zh-CN']); + }); + + it('an i18n service it cannot resolve, or whose default read throws, adds no rung', async () => { + expect(await bridgeWith({ locale: 'ja-JP' }).userTextLocales!()).toEqual(['ja-JP']); + expect(await bridgeWith({}, () => { throw new Error('no i18n (test)'); }).userTextLocales!()).toEqual([]); + expect(await bridgeWith({}, () => ({ getDefaultLocale: () => { throw new Error('boom (test)'); } })).userTextLocales!()).toEqual([]); + }); +}); + +/** + * The stdio door, over the shared ADR-0106 case table (`OBJECT_SCHEMA_MASK_CASES`, + * the cases every object-schema exit is judged by): the real stdio bridge, + * its own caller view of the object, and the real tools, with the engine + * refusing every read. A case's absent fields and an unreadable object are + * what that caller cannot see; each is answered with members byte-identical + * to a name that does not exist, the name aside. + */ +describe('[#35138] stdio door: the answer names only what the caller can see', () => { + const STDIO_OBJECT = FLS_CONTRACT_OBJECT.name; + const UNKNOWN_FIELD = 'no_such_field'; + const UNKNOWN_OBJECT = 'no_such_object'; + const declared = () => JSON.parse(JSON.stringify(FLS_CONTRACT_OBJECT)); + const refusing = () => refusal('PERMISSION_DENIED', 403, 'You do not have permission to perform this action.'); + + async function connect(testCase: ObjectSchemaMaskCase) { + const security = securityDoubleFor(testCase); + const engine = { + find: async () => { throw refusing(); }, + count: async () => { throw refusing(); }, + aggregate: async () => { throw refusing(); }, + } as unknown as IDataEngine; + const metadataService = { + listObjects: async () => [declared()], + getObject: async (name: string) => (name === STDIO_OBJECT ? declared() : undefined), + list: async () => [], + } as unknown as IMetadataService; + const bridge = createStdioDataBridge({ + engine, + metadataService, + resolvePrincipal: async () => ({ ...testCase.context }) as unknown as ExecutionContext, + ...(security ? { security: () => security } : {}), + }); + 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); + const call = async (name: string, args: Record) => { + const res = (await client.callTool({ name, arguments: args })) as { isError?: boolean; content: Array<{ text: string }> }; + const text = res.content[0]!.text; + let payload: any; + try { payload = JSON.parse(text); } catch { payload = undefined; } + return { isError: res.isError === true, text, payload }; + }; + return { call, close: () => client.close() }; + } + + /** Run `run` with masking on: none of these cases switches it off. */ + async function underMasking(run: () => Promise): Promise { + const previous = process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + try { + return await run(); + } finally { + if (previous !== undefined) process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = previous; + } + } + + const fieldCases = OBJECT_SCHEMA_MASK_CASES.filter((c) => c.expect.kind === 'fields' && !c.maskingDisabled); + const objectCases = OBJECT_SCHEMA_MASK_CASES.filter((c) => c.expect.kind === 'absent' && !c.maskingDisabled); + + it('the table carries cases of both kinds', () => { + expect(fieldCases.length).toBeGreaterThan(0); + expect(objectCases.length).toBeGreaterThan(0); + }); + + it.each(fieldCases.map((c) => [c.id, c] as const))( + '%s: a field the caller cannot see gets the members a field that does not exist gets', + async (_id, testCase) => { + const expected = testCase.expect as { present: readonly string[]; absent: readonly string[] }; + await underMasking(async () => { + const session = await connect(testCase); + try { + const ask = (field: string) => + session.call('query_records', { objectName: STDIO_OBJECT, where: { [field]: 'x' }, fields: [field] }); + const unknown = await ask(UNKNOWN_FIELD); + expect(unknown.isError).toBe(true); + expect(unknown.payload.notRecorded).toEqual({ object: STDIO_OBJECT, fields: [UNKNOWN_FIELD] }); + for (const field of expected.absent) { + const answer = await ask(field); + expect(answer.isError).toBe(true); + expect(Object.keys(answer.payload)).toEqual(Object.keys(unknown.payload)); + expect(membersText(answer.payload).split(field).join(UNKNOWN_FIELD)).toBe(membersText(unknown.payload)); + for (const other of expected.absent) { + if (other !== field) expect(mentions(answer.text, other)).toBe(false); + } + } + // CONTROL: a field the caller can see is never named, nor a dotted name through it. + for (const field of expected.present) { + const answer = await session.call('query_records', { + objectName: STDIO_OBJECT, + where: { [field]: 'x' }, + fields: [`${field}.label`], + }); + expect(answer.isError).toBe(true); + expect(Object.keys(answer.payload)).toEqual(['error']); + } + } finally { + await session.close(); + } + }); + }, + ); + + it.each(objectCases.map((c) => [c.id, c] as const))( + '%s: an object the caller cannot read gets the members an object that does not exist gets', + async (_id, testCase) => { + await underMasking(async () => { + const session = await connect(testCase); + try { + for (const [tool, extra] of [ + ['query_records', {}], + ['get_record', { recordId: 'r1' }], + ['aggregate_records', { aggregations: [{ function: 'count', alias: 'n' }] }], + ] as const) { + const unknown = await session.call(tool, { objectName: UNKNOWN_OBJECT, ...extra }); + const hidden = await session.call(tool, { objectName: STDIO_OBJECT, ...extra }); + expect(unknown.isError).toBe(true); + expect(hidden.isError).toBe(true); + expect(unknown.payload.notRecorded).toEqual({ object: UNKNOWN_OBJECT }); + expect(hidden.payload.notRecorded).toEqual({ object: STDIO_OBJECT }); + expect(Object.keys(hidden.payload)).toEqual(Object.keys(unknown.payload)); + expect(membersText(hidden.payload).split(STDIO_OBJECT).join(UNKNOWN_OBJECT)).toBe(membersText(unknown.payload)); + for (const field of Object.keys(FLS_CONTRACT_OBJECT.fields ?? {})) expect(mentions(hidden.text, field)).toBe(false); + } + } finally { + await session.close(); + } + }); + }, + ); +}); diff --git a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts index 602244ee9e8..954cc68b67c 100644 --- a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts +++ b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts @@ -164,6 +164,8 @@ const RECIPES: Record = { query: { invoke: (b) => b.query('vault', {}), writesRecords: false }, get: { invoke: (b) => b.get('vault', 'row-1'), writesRecords: false }, aggregate: { invoke: (b) => b.aggregate('vault', {}), writesRecords: false }, + // [#35138] The caller's locale codes: no engine read, no record. + userTextLocales: { invoke: (b) => b.userTextLocales(), writesRecords: false }, // ── write faces: an engine write result rides (or could ride) the response ── create: { invoke: (b) => b.create('vault', { name: CONTROL }), writesRecords: true }, diff --git a/packages/mcp/src/stdio-data-bridge.not-found.test.ts b/packages/mcp/src/stdio-data-bridge.not-found.test.ts index 203524a58a8..df119a69907 100644 --- a/packages/mcp/src/stdio-data-bridge.not-found.test.ts +++ b/packages/mcp/src/stdio-data-bridge.not-found.test.ts @@ -187,7 +187,8 @@ async function callOnLongLivedServer(bridge: McpDataBridge, name: string, args: async function getRecordOverHttp(objectName: string, recordId: string) { const bridge: McpDataBridge = { async listObjects() { return [{ name: 'task', label: 'Task', fieldCount: 0 }]; }, - async describeObject() { return null; }, + // [#35138] `task` is served, as the stdio side serves it: a miss on it is a missing record, not an unrecorded object. + async describeObject(name) { return name === 'task' ? { name: 'task', label: 'Task', fields: [] } : null; }, async query(object) { return { object, records: [], total: 0 }; }, async get(object, id) { throw recordNotFoundError(object, id); }, async create(object, data) { return { object, id: 'n1', record: data }; }, diff --git a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts index 985e31f0310..f0c7c1076d8 100644 --- a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts +++ b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts @@ -475,6 +475,7 @@ const BRIDGE_MEMBERS: Record = { create: 'refused by the exposure gate — the stored-body tables admit no write verb (family pin)', update: 'refused by the exposure gate — the stored-body tables admit no write verb (family pin)', remove: 'refused by the exposure gate — the stored-body tables admit no write verb (family pin)', + userTextLocales: 'no row body — the principal\'s locale codes and the i18n default', }; /** diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 847ac8aaef7..961edd5ff88 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -138,7 +138,7 @@ import { isAiReadExposed } from '@objectstack/spec/data'; // a direct `@objectstack/core` dependency (`plugin.ts` imports from it too), // and `@objectstack/core` is the lowest package that carries the factory, so // there is no reason to add a second import path to the same function. -import { recordNotFoundError } from '@objectstack/core'; +import { recordNotFoundError, userTextLocalesOf } from '@objectstack/core'; // Managing API keys is a signed-in-session act: the one rule every data door // asks beside its exposure gate (`RestServer.enforceApiAccess`, the runtime // dispatcher's `refuseUnexposedDataAction`), asked here by the write arms. @@ -1409,6 +1409,23 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge ); }, + // [#35138] The locale ladder for a sentence the record tools compose + // (`ifNotRecorded`): the principal's, the ladder the dataset tools' + // `nextStep` reads on this door (`userTextLocalesOf`), then the i18n + // service's default, the locale this transport's `/meta` translation + // speaks ({@link defaultLocaleSources}). An i18n service this host cannot + // resolve, or whose default read throws, adds no rung. + async userTextLocales(): Promise { + const ladder = userTextLocalesOf(await resolvePrincipal()); + let fallback: string | undefined; + try { + fallback = metaRequestLocale(undefined, deps.i18n?.()); + } catch { + fallback = undefined; + } + return fallback !== undefined ? [...ladder, fallback] : ladder; + }, + async create(object, data) { const context = await resolvePrincipal(); await enforceApiExposure(reads, object, GATED_ACTIONS.create, context); diff --git a/packages/runtime/src/domains/mcp-not-recorded.test.ts b/packages/runtime/src/domains/mcp-not-recorded.test.ts new file mode 100644 index 00000000000..3c97557a931 --- /dev/null +++ b/packages/runtime/src/domains/mcp-not-recorded.test.ts @@ -0,0 +1,232 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35138] What the MCP record tools build `notRecorded` / `ifNotRecorded` + * from, on the HTTP bridge: the caller's served schema (`describeObject`) and + * the caller's locale ladder (`userTextLocales`). The tool layer renders the + * members (`packages/mcp/src/mcp-not-recorded.test.ts`); here the bridge's + * two answers are pinned over the real security layer (`SecurityPlugin` on a + * real `ObjectQL` over a real `SqlDriver`, the protocol over that engine), + * through the bridge the real `/mcp` entry builds for the caller. + * + * The rule the tools hold: an object or field the caller cannot see is + * answered exactly as one that does not exist for them. So the served schema + * must not show it, and a read naming it must be refused, for both. + */ + +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + OBJECT_SCHEMA_MASK_DISABLE_ENV, + SysMetadataAuditObject, + SysMetadataHistoryObject, + SysMetadataObject, +} from '@objectstack/metadata-core'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid at collection, not inside a case's clock: the dispatcher's reach loads it lazily. +import '@objectstack/metadata'; + +/** A kernel over `services`, with an `mcp` service that hands back the bridge `handleMcp` built. */ +function kernelOver(services: Record) { + const mcp: any = { + lastOpts: undefined, + handleHttpRequest: async (_req: Request, o: any) => { + mcp.lastOpts = o; + return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }); + }, + }; + const all: Record = { ...services, mcp }; + const get = (n: string) => all[n] ?? null; + return { getService: get, getServiceAsync: async (n: string) => get(n), context: { getService: get } } as any; +} + +/** Drive the real `/mcp` entry for `executionContext` and hand back the bridge it built. */ +async function bridgeFor(kernel: any, executionContext: Record) { + const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); + const res = await dispatcher.handleMcp({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { + request: new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: '{}', + }), + response: {}, + environmentId: undefined, + executionContext: { ...executionContext }, + } as any); + expect(res.response?.status, 'precondition: the MCP route must have been served').toBe(200); + return kernel.getService('mcp').lastOpts.bridge; +} + +/** The rejection `run` raised, or `undefined` when it resolved. */ +const rejectionOf = async (run: () => Promise): Promise => run().then(() => undefined, (e: unknown) => e); + +const OBJ = 'mcp_nr_deal'; +const VAULT = 'mcp_nr_vault'; +const HIDDEN = 'secret_margin'; +const UNKNOWN_FIELD = 'invoice_total'; +const UNKNOWN_OBJECT = 'mcp_nr_invoice'; + +const PERSONAS = { + /** Reads {@link OBJ} without {@link HIDDEN}; no grant on {@link VAULT}. */ + member: { userId: 'usr_member', positions: [] as string[], permissions: ['mcp_nr_member'], systemPermissions: [] as string[] }, + /** Reads everything: the control. */ + staff: { userId: 'usr_staff', positions: [] as string[], permissions: ['mcp_nr_staff'], systemPermissions: [] as string[] }, +} as const; + +const prevMcp = process.env.OS_MCP_SERVER_ENABLED; +const prevMask = process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; +beforeEach(() => { + process.env.OS_MCP_SERVER_ENABLED = 'true'; + delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; +}); +afterEach(() => { + if (prevMcp === undefined) delete process.env.OS_MCP_SERVER_ENABLED; + else process.env.OS_MCP_SERVER_ENABLED = prevMcp; + if (prevMask === undefined) delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + else process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = prevMask; +}); + +describe('[#35138] HTTP MCP bridge — the served schema and locale the not-recorded members are built from', () => { + let engine: ObjectQL; + let services: Record; + + beforeAll(async () => { + engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const storeObjects = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject] as any[]; + await driver.initObjects(storeObjects); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of storeObjects) engine.registry.registerObject(o, '@objectstack/platform-objects'); + engine.registerApp({ + id: 'com.objectstack.qa.mcp-not-recorded', + name: 'MCP not recorded', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + { + name: OBJ, + label: 'Deal', + sharingModel: 'public_read_write', + fields: { + subject: { name: 'subject', type: 'text', label: 'Subject' }, + amount: { name: 'amount', type: 'currency', label: 'Amount' }, + [HIDDEN]: { name: HIDDEN, type: 'currency', label: 'Margin' }, + }, + }, + { + name: VAULT, + label: 'Vault', + sharingModel: 'public_read_write', + fields: { title: { name: 'title', type: 'text', label: 'Title' } }, + }, + ], + } as never); + await engine.syncSchemas(); + const all = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + const sets = [ + PermissionSetSchema.parse({ + name: 'mcp_nr_member', label: 'Member', objects: { [OBJ]: all }, + fields: { [`${OBJ}.${HIDDEN}`]: { readable: false, editable: false } }, + }), + PermissionSetSchema.parse({ name: 'mcp_nr_staff', label: 'Staff', objects: { [OBJ]: all, [VAULT]: all } }), + PermissionSetSchema.parse({ name: 'mcp_nr_base', label: 'Base', objects: { [OBJ]: all } }), + ]; + const pluginServices: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? sets.find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, + list: async () => sets, + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn((name: string, service: unknown) => { pluginServices[name] = service; }), + getService: (name: string) => { + if (!(name in pluginServices)) throw new Error(`service not registered: ${name}`); + return pluginServices[name]; + }, + }; + // The deployment's baseline set grants nothing on {@link VAULT}. + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'mcp_nr_base' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + services = { + protocol: new ObjectStackProtocolImplementation(engine as any), + security: pluginServices.security, + objectql: engine, + }; + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + }, 60_000); + + afterAll(async () => { + vi.restoreAllMocks(); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + /** The field names `describeObject` serves `persona` on {@link OBJ}. */ + async function servedNames(persona: Record): Promise { + const bridge = await bridgeFor(kernelOver(services), persona); + return ((await bridge.describeObject(OBJ)).fields as Array<{ name: string }>).map((f) => f.name); + } + + it('precondition: the staff is served the field the member is denied, and only the staff may read the vault', async () => { + expect(await servedNames(PERSONAS.staff)).toContain(HIDDEN); + expect(await services.security.canReadObject(VAULT, PERSONAS.member)).toBe(false); + expect(await services.security.canReadObject(VAULT, PERSONAS.staff)).toBe(true); + }); + + it('a field the member cannot see is absent from their schema as an unknown one is, and a read naming either is refused', async () => { + const names = await servedNames(PERSONAS.member); + expect(names).toEqual(expect.arrayContaining(['subject', 'amount'])); + const bridge = await bridgeFor(kernelOver(services), PERSONAS.member); + for (const name of [HIDDEN, UNKNOWN_FIELD]) { + expect(names).not.toContain(name); + for (const run of [ + () => bridge.query(OBJ, { where: { [name]: 1 } }), + () => bridge.aggregate(OBJ, { groupBy: [name], aggregations: [{ function: 'count', alias: 'n' }] }), + ]) { + const refused = await rejectionOf(run); + expect(refused, `a read naming ${name} must be refused`).toBeDefined(); + expect(typeof refused.code).toBe('string'); + expect(refused.status ?? refused.statusCode).toBeGreaterThanOrEqual(400); + expect(refused.status ?? refused.statusCode).toBeLessThan(500); + } + } + }); + + it('an object the member cannot read is no object in their schema, as an unknown name is, and a read of either is refused', async () => { + const bridge = await bridgeFor(kernelOver(services), PERSONAS.member); + for (const name of [VAULT, UNKNOWN_OBJECT]) { + expect(await bridge.describeObject(name)).toBeNull(); + const refused = await rejectionOf(() => bridge.query(name, {})); + expect(refused, `a read of ${name} must be refused`).toBeDefined(); + expect(refused.status ?? refused.statusCode).toBeGreaterThanOrEqual(400); + expect(refused.status ?? refused.statusCode).toBeLessThan(500); + } + }); + + it('CONTROL — the staff reads the field and the vault, and the member reads a field it is served', async () => { + const staff = await bridgeFor(kernelOver(services), PERSONAS.staff); + await expect(staff.query(OBJ, { where: { [HIDDEN]: 1 } })).resolves.toBeDefined(); + await expect(staff.query(VAULT, {})).resolves.toBeDefined(); + expect(await staff.describeObject(VAULT)).not.toBeNull(); + const member = await bridgeFor(kernelOver(services), PERSONAS.member); + await expect(member.query(OBJ, { where: { amount: 1 } })).resolves.toBeDefined(); + }); + + it('userTextLocales answers this request\'s ladder: its locale, then the workspace default; none for an unlocalized caller', async () => { + const localized = await bridgeFor(kernelOver(services), { ...PERSONAS.member, locale: 'zh-CN', workspaceLocale: 'ja-JP' }); + expect(await localized.userTextLocales()).toEqual(['zh-CN', 'ja-JP']); + const plain = await bridgeFor(kernelOver(services), PERSONAS.member); + expect(await plain.userTextLocales()).toEqual([]); + }); +}); diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index fba506411a7..0c9f3fa586c 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -34,7 +34,7 @@ import { // [ADR-0131 D3 · D12 items 7–8 · D11] The walled refusal every door that writes // the environment's metadata asks, read through this transport's one posture read. import { walledCatalogWriteVerdict } from '@objectstack/metadata-core'; -import { shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE } from '@objectstack/core'; +import { shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE, userTextLocalesOf } from '@objectstack/core'; import { readEffectiveTenancyPosture } from './activation-gate.js'; import { buildApiError } from '../error-envelope.js'; import * as actionExec from '../action-execution.js'; @@ -1243,6 +1243,10 @@ export function buildMcpBridge( ); return res?.rows ?? []; }, + // [#35138] The caller's locale ladder for a sentence the record tools + // compose (`ifNotRecorded`): this request's, as the dataset tools' + // `nextStep` reads it on this door (`userTextLocalesOf`). + userTextLocales: async (): Promise => userTextLocalesOf(ec), // ── Skill metadata → MCP prompts (#3905) ────────────────── // ADR-0063 §2 names skills the only third-party extension primitive, diff --git a/packages/services/service-analytics/src/dataset-next-step.ts b/packages/services/service-analytics/src/dataset-next-step.ts index bfd1844761e..432c7f9f236 100644 --- a/packages/services/service-analytics/src/dataset-next-step.ts +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -7,7 +7,8 @@ import type { DatasetTermCandidate, DatasetToolCatalogEntry, } from '@objectstack/spec/ai'; -import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/system'; +import { pickSentenceLocale } from '@objectstack/core'; +import type { PlatformLocaleTag } from '@objectstack/spec/system'; /** * [ADR-0149 M1, the amendment note under it; ruling #34894 = A] The two @@ -113,9 +114,9 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s * the ones the door already put on the caller's `ExecutionContext` (`locale`, * `workspaceLocale`), the context the executor resolves every label with, so * the HTTP door and the stdio door get the same sentence for the same caller. - * A code is read through the platform locale table (`platformLocaleTagOf`), - * whole and then one subtag shorter at a time; a language with no sentences - * here takes the next rung. + * A code is read through the platform locale table, whole and then one + * subtag shorter at a time, by the shared picker (`pickSentenceLocale`, + * `@objectstack/core`); a language with no sentences here takes the next rung. */ /** The languages this file writes, keyed by platform locale tag; `en` is the floor. */ @@ -251,34 +252,18 @@ const COPY: Readonly> = { }, }; -/** - * 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. - */ -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; -} +/** The languages {@link COPY} writes, in its key order. */ +const NEXT_STEP_LOCALES = Object.keys(COPY) as NextStepLocale[]; /** * The language a sentence is written in for an ordered list of candidate codes * (the request's locale, then the workspace default): the first that names a - * language this file writes, else `en`. + * language this file writes, else `en`. The shared picker + * (`pickSentenceLocale`, `@objectstack/core`), so every sentence in a tool's + * result reads the caller's locale the same way. */ export function datasetToolSentenceLocale(locales: readonly (string | undefined)[]): NextStepLocale { - for (const code of locales) { - const tag = platformLocaleNamedBy(code); - if (tag !== undefined && Object.prototype.hasOwnProperty.call(COPY, tag)) return tag as NextStepLocale; - } - return 'en'; + return pickSentenceLocale(locales, NEXT_STEP_LOCALES); } /**