diff --git a/.changeset/34872-mcp-object-tools-locale.md b/.changeset/34872-mcp-object-tools-locale.md new file mode 100644 index 00000000000..43b572b4440 --- /dev/null +++ b/.changeset/34872-mcp-object-tools-locale.md @@ -0,0 +1,18 @@ +--- +'@objectstack/runtime': patch +'@objectstack/mcp': patch +--- + +feat(mcp): `list_objects` and `describe_object` serve labels and descriptions in the caller's locale + +Clause-②: no +Metadata-protocol: none + +The two MCP object tools now serve the object's label and description, and each field's label, description and option labels, in the caller's locale, the way the REST `/meta` object door serves them. Before, both tools served the authored text in every locale. A client asking in Chinese about an app with a Chinese translation bundle was shown the English labels. + +- **HTTP:** the locale is the request's `Accept-Language` (then `?locale=`, then the i18n service's default), read and translated by the `/meta` door's own routine. The dataset tools already used the same routine. +- **stdio:** the transport carries no request, so the locale is the i18n service's default. The stdio `list_datasets` already uses that locale. + +Translation runs on the object as the caller is served it, after the field mask, so a field the caller cannot read stays absent and so does its translated text. Names and option values never change. Where the bundle has no entry for a key, or no i18n service is registered, the tools serve the authored text. Without `Accept-Language`, the HTTP tools now serve the i18n default locale's bundle entries, as the REST door does. An app whose `en` bundle relabels a field (app-crm's `amount` is "Deal Value") shows that label there. + +The answer's shape is unchanged. Validation rule messages are translated by the same routine where the bundle carries them. diff --git a/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts b/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts new file mode 100644 index 00000000000..0da68cefae3 --- /dev/null +++ b/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts @@ -0,0 +1,204 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34872] The stdio transport's `list_objects` and `describe_object` answer + * the object's and each field's label, option labels and descriptions in the + * locale this transport speaks: it carries no request, so that is the i18n + * service's default (what `metaRequestLocale` answers with no header), the + * reading the stdio `list_datasets` localizes with. The translation is the + * `/meta` object door's own (`translateMetaList`), applied to the object as + * the principal is served it (ADR-0106 D3/D5): a masked field stays absent, + * its translated text with it. An `en` default with no entry, or no i18n + * service the host can resolve, serves the authored text. Names never change. + * + * Driven through the real tools (`registerObjectTools`) over the stdio bridge, + * with a security service built by the shared ADR-0106 double + * (`securityDoubleFor`). The HTTP twin is + * `packages/runtime/src/domains/mcp-object-locale-34872.test.ts`. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } 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 { securityDoubleFor } from '@objectstack/metadata-core/testing'; +import { OBJECT_SCHEMA_MASK_DISABLE_ENV } from '@objectstack/metadata-core'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; +import { registerObjectTools } from './mcp-http-tools.js'; + +const OBJ = 'deal'; +const PLAIN = 'plain'; +const DENIED = 'secret_margin'; +const OBJECT_TEXT = 'A sales deal, from first call to signed order.'; +const AMOUNT_TEXT = 'Amount, tax excluded.'; +const DENIED_TEXT = 'Internal margin after rebates.'; + +const deal = () => ({ + name: OBJ, + label: 'Deal', + description: OBJECT_TEXT, + fields: { + id: { name: 'id', type: 'text', label: 'ID' }, + subject: { name: 'subject', type: 'text', label: 'Subject' }, + amount: { name: 'amount', type: 'currency', label: 'Amount', description: AMOUNT_TEXT }, + stage: { + name: 'stage', type: 'select', label: 'Stage', + options: [{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }], + }, + [DENIED]: { name: DENIED, type: 'currency', label: 'Margin', description: DENIED_TEXT }, + }, +}); +const plain = () => ({ name: PLAIN, label: 'Plain', fields: { id: { name: 'id', type: 'text' }, title: { name: 'title', type: 'text', label: 'Title' } } }); + +/** The zh-CN bundle: the deal, its fields (`help` is the bundle key a field's description is served from) and one option. */ +const ZH_CN = { + objects: { + [OBJ]: { + label: '交易', + description: '一笔销售交易,从首次接触到签单。', + fields: { + subject: { label: '主题' }, + amount: { label: '金额', help: '金额,不含税。' }, + stage: { label: '阶段', options: { won: '赢单' } }, + [DENIED]: { label: '毛利', help: '返利后的内部毛利。' }, + }, + }, + }, +}; + +/** An i18n service double: the zh-CN bundle above, an empty `en` one, and the default the case names. */ +function i18nService(defaultLocale: string) { + const bundles: Record = { 'zh-CN': ZH_CN, en: {} }; + return { + getLocales: () => Object.keys(bundles), + getTranslations: (locale: string) => bundles[locale], + getDefaultLocale: () => defaultLocale, + }; +} + +/** + * The real tools over the stdio bridge, the principal reading `readable` + * (every field when omitted), localized by `i18n` (no i18n dependency when omitted). + */ +async function connect(opts: { readable?: readonly string[]; i18n?: () => unknown } = {}) { + const { readable, i18n } = opts; + const security = readable + ? securityDoubleFor({ + id: 'restricted-caller/34872', + why: 'a principal denied one field', + context: { userId: 'u_member', systemPermissions: [] }, + readable: [...readable], + expect: { kind: 'unmasked' }, + } as never) + : undefined; + const defs = () => [deal(), plain()]; + const bridge = createStdioDataBridge({ + engine: {} as unknown as IDataEngine, + metadataService: { + listObjects: vi.fn(async () => defs()), + getObject: vi.fn(async (name: string) => defs().find((d) => d.name === name)), + } as unknown as IMetadataService, + resolvePrincipal: async () => ({ userId: 'u_member', systemPermissions: [] }) as unknown as ExecutionContext, + ...(security ? { security: () => security } : {}), + ...(i18n ? { i18n } : {}), + }); + 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): Promise<{ text: string; json: any; isError: boolean }> => { + const res = (await client.callTool({ name, arguments: args })) as { isError?: boolean; content: Array<{ text: string }> }; + const text = res.content[0]!.text; + return { text, json: JSON.parse(text), isError: res.isError === true }; + }; + return { call, close: () => client.close() }; +} + +const prevMask = process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; +beforeEach(() => { delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; }); +afterEach(() => { + if (prevMask === undefined) delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + else process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = prevMask; +}); + +/** Every field but the denied one (the double answers one readable set for every object). */ +const MEMBER_READS = ['id', 'subject', 'amount', 'stage', 'title'] as const; + +const field = (described: any, name: string) => described.fields.find((f: any) => f.name === name); + +describe('[#34872] stdio list_objects and describe_object serve labels and descriptions in the default locale', () => { + it('describe_object under a zh-CN default: the object\'s and each field\'s label, description and option label are the bundle\'s; names never change', async () => { + const session = await connect({ i18n: () => i18nService('zh-CN') }); + try { + const described = await session.call('describe_object', { objectName: OBJ }); + expect(described.isError).toBe(false); + expect(described.json).toMatchObject({ name: OBJ, label: '交易', description: '一笔销售交易,从首次接触到签单。' }); + expect(field(described.json, 'subject')).toMatchObject({ name: 'subject', label: '主题' }); + expect(field(described.json, 'amount')).toMatchObject({ name: 'amount', label: '金额', description: '金额,不含税。' }); + expect(field(described.json, 'stage')).toMatchObject({ + name: 'stage', + label: '阶段', + options: [{ value: 'won', label: '赢单' }, { value: 'lost', label: 'Lost' }], + }); + } finally { + await session.close(); + } + }); + + it('list_objects under a zh-CN default: each object\'s label and description are the bundle\'s; an object the bundle does not carry keeps its own', async () => { + const session = await connect({ readable: MEMBER_READS, i18n: () => i18nService('zh-CN') }); + try { + const listed = (await session.call('list_objects', {})).json; + const found = (name: string) => listed.objects.find((o: any) => o.name === name); + expect(found(OBJ)).toEqual({ name: OBJ, label: '交易', description: '一笔销售交易,从首次接触到签单。', fieldCount: 4 }); + expect(found(PLAIN)).toEqual({ name: PLAIN, label: 'Plain', fieldCount: 2 }); + } finally { + await session.close(); + } + }); + + it('a field the principal cannot read stays absent under translation, its translated label and description with it', async () => { + const session = await connect({ readable: MEMBER_READS, i18n: () => i18nService('zh-CN') }); + try { + const described = await session.call('describe_object', { objectName: OBJ }); + expect(described.json.label).toBe('交易'); + expect(field(described.json, DENIED)).toBeUndefined(); + for (const leaked of ['毛利', '返利后的内部毛利。', 'Margin', DENIED_TEXT]) expect(described.text).not.toContain(leaked); + } finally { + await session.close(); + } + }); + + it('an `en` default with no entry: the authored labels, descriptions and option labels', async () => { + const session = await connect({ i18n: () => i18nService('en') }); + try { + const described = (await session.call('describe_object', { objectName: OBJ })).json; + expect(described).toMatchObject({ name: OBJ, label: 'Deal', description: OBJECT_TEXT }); + expect(field(described, 'amount')).toMatchObject({ label: 'Amount', description: AMOUNT_TEXT }); + expect(field(described, 'stage').options).toEqual([{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }]); + const listed = (await session.call('list_objects', {})).json; + expect(listed.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + } finally { + await session.close(); + } + }); + + it('an i18n service the host cannot resolve (its resolver throws), or none: the authored text, never an error', async () => { + for (const i18n of [() => { throw new Error('i18n not registered'); }, undefined]) { + const session = await connect({ ...(i18n ? { i18n } : {}) }); + try { + const described = await session.call('describe_object', { objectName: OBJ }); + expect(described.isError).toBe(false); + expect(described.json).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + const listed = (await session.call('list_objects', {})).json; + expect(listed.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + } finally { + await session.close(); + } + } + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 1d5da459f02..f4f5d631df3 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -263,9 +263,10 @@ export interface StdioDataBridgeDeps { */ datasetTools?: StdioDatasetToolsService; /** - * [ADR-0149 D2] The `i18n` service the saved datasets are localized with, - * resolved at each use. `undefined`, or a resolver that throws, means none: - * the datasets are then served untranslated, as on the HTTP door. + * [ADR-0149 D2 · #34872] The `i18n` service the saved datasets and the + * object tools' labels and descriptions are localized with, resolved at each + * use. `undefined`, or a resolver that throws, means none: they are then + * served untranslated, as on the HTTP door. */ i18n?: () => unknown; } @@ -1171,13 +1172,50 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // the view discovery answers from. The gates below read `objectView` whole. const servedView = callerObjectView(objectView, { resolvePrincipal, security, schemaReadDelegates }); + /** + * [ADR-0149 D2 · #34872] What the HTTP door's `/meta` translation reads, on + * a transport that carries no request: the i18n service ({@link + * StdioDataBridgeDeps.i18n}; a resolver that throws is none) and, for the + * locale, `metaRequestLocale` with no request — the i18n service's default, + * the workspace default the stdio principal speaks. `resolveProtocol` + * answers the protocol the read was served from (an object's packaged base, + * a declared override's pair translations), or none. + */ + const defaultLocaleSources = (resolveProtocol: () => Promise) => ({ + resolveI18nService: async () => { + try { + return deps.i18n?.(); + } catch { + return undefined; + } + }, + resolveProtocol, + requestLocale: (i18n?: unknown) => metaRequestLocale(undefined, i18n), + }); + + /** + * [#34872] Served objects in the locale this transport speaks: the HTTP + * door's `/meta` object translation (`translateMetaList`), ⛔ never a second + * routine, over the objects AS THE PRINCIPAL IS SERVED THEM ({@link + * callerObjectView}): the translator rewrites the text of the fields it is + * given and adds none, so a masked field stays absent, its translated text + * with it (ADR-0106 D3/D5). No locale, or a key the bundle does not carry, + * leaves the authored text; names never change. + */ + const inServedLocale = async (served: readonly ObjectDef[]): Promise => { + if (served.length === 0) return [...served]; + const translated = await translateMetaList(defaultLocaleSources(async () => protocol?.()), 'object', [...served]); + return Array.isArray(translated) ? (translated as ObjectDef[]) : [...served]; + }; + const bridge: McpDataBridge = { async listObjects(): Promise { // [#25138] The protocol's merged listing ({@link readMergedObjects}), // [ADR-0106] as the principal is served it, so `fieldCount` counts the // fields that exist for them ({@link callerObjectView}). // [#34721] …and the object's authored `description`, as the HTTP twin serves it. - return ((await servedView.listObjects()) as ObjectDef[]).map((o) => ({ + // [#34872] …in the locale this transport speaks ({@link inServedLocale}). + return (await inServedLocale((await servedView.listObjects()) as ObjectDef[])).map((o) => ({ name: o.name, label: o.label ?? o.name, ...authoredDescription(o), @@ -1220,8 +1258,10 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // is read off the declaration. async describeObject(name: string): Promise { const { served, declared } = await readObjectWithDeclaration(servedView, name); - const def = served as ObjectDef | undefined; - if (!def) return null; + if (!served) return null; + // [#34872] …in the locale this transport speaks ({@link inServedLocale}); + // `declared` is read for the `readonly` verdict alone. + const [def] = await inServedLocale([served as ObjectDef]); // The field list is an ARRAY here, not the stored map: `validate_expression` // reads `Array.isArray(def.fields)` off this very value, and the HTTP // bridge projects the same shape. A map would type-check and silently @@ -1440,21 +1480,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge } else { items = (await metadataService.list('dataset')) ?? []; } - const translated = await translateMetaList( - { - resolveI18nService: async () => { - try { - return deps.i18n?.(); - } catch { - return undefined; - } - }, - resolveProtocol: async () => merged, - requestLocale: (i18n?: unknown) => metaRequestLocale(undefined, i18n), - }, - 'dataset', - items, - ); + const translated = await translateMetaList(defaultLocaleSources(async () => merged), 'dataset', items); return Array.isArray(translated) ? translated : items; }; const executor = (maxQueryLimit?: number) => diff --git a/packages/runtime/src/domains/mcp-object-locale-34872.test.ts b/packages/runtime/src/domains/mcp-object-locale-34872.test.ts new file mode 100644 index 00000000000..34fd1acfcbb --- /dev/null +++ b/packages/runtime/src/domains/mcp-object-locale-34872.test.ts @@ -0,0 +1,256 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34872] The HTTP MCP bridge's `list_objects` and `describe_object` answers + * carry the object's and each field's label, option labels and descriptions + * in the CALLER'S locale — this request's `Accept-Language`, read by + * `metaRequestLocale` and translated by `translateMetaList`, the `/meta` + * object door's own routine — over the object AS THE CALLER IS SERVED IT + * (ADR-0106 D3/D5): translation never brings back a masked field or its text. + * Without a locale, or for a key the bundle does not carry, the authored text. + * Names never change. + * + * Driven 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, with an i18n service double + * that carries a zh-CN bundle. The stdio twin is + * `packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts`. + */ + +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`, under `acceptLanguage` when given, and hand back the bridge it built. */ +async function bridgeFor(kernel: any, executionContext: Record, acceptLanguage?: string) { + const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); + const headers: Record = { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }; + if (acceptLanguage !== undefined) headers['accept-language'] = acceptLanguage; + const res = await dispatcher.handleMcp({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { + request: new Request('http://localhost/api/v1/mcp', { method: 'POST', headers, 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; +} + +const OBJ = 'mcp_loc_deal'; +const PLAIN = 'mcp_loc_plain'; +const DENIED = 'secret_margin'; +const OBJECT_TEXT = 'A sales deal, from first call to signed order.'; +const AMOUNT_TEXT = 'Amount, tax excluded.'; +const DENIED_TEXT = 'Internal margin after rebates.'; + +/** The zh-CN bundle: the deal, its fields (`help` is the bundle key a field's description is served from) and one option. */ +const ZH_CN = { + objects: { + [OBJ]: { + label: '交易', + description: '一笔销售交易,从首次接触到签单。', + fields: { + subject: { label: '主题' }, + amount: { label: '金额', help: '金额,不含税。' }, + stage: { label: '阶段', options: { won: '赢单' } }, + [DENIED]: { label: '毛利', help: '返利后的内部毛利。' }, + }, + }, + }, +}; + +/** An i18n service double: the zh-CN bundle above, an empty `en` one, and `en` as the default. */ +const i18nService = { + getLocales: () => ['en', 'zh-CN'], + getTranslations: (locale: string) => (locale === 'zh-CN' ? ZH_CN : locale === 'en' ? {} : undefined), + getDefaultLocale: () => 'en', +}; + +const PERSONAS = { + /** Denied one field. */ + member: { userId: 'usr_member', positions: [] as string[], permissions: ['mcp_loc_member'], systemPermissions: [] as string[] }, + /** Denied nothing: the control. */ + staff: { userId: 'usr_staff', positions: [] as string[], permissions: ['mcp_loc_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('[#34872] HTTP MCP list_objects and describe_object serve labels and descriptions in the caller\'s locale', () => { + 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-object-locale', + name: 'MCP object locale', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + { + name: OBJ, + label: 'Deal', + description: OBJECT_TEXT, + sharingModel: 'public_read_write', + fields: { + subject: { name: 'subject', type: 'text', label: 'Subject' }, + amount: { name: 'amount', type: 'currency', label: 'Amount', description: AMOUNT_TEXT }, + stage: { + name: 'stage', type: 'select', label: 'Stage', + options: [{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }], + }, + [DENIED]: { name: DENIED, type: 'currency', label: 'Margin', description: DENIED_TEXT }, + }, + }, + { + name: PLAIN, + label: 'Plain', + 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_loc_member', label: 'Member', objects: { '*': all }, + fields: { [`${OBJ}.${DENIED}`]: { readable: false, editable: false } }, + }), + PermissionSetSchema.parse({ name: 'mcp_loc_staff', label: 'Staff', objects: { '*': 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]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'mcp_loc_staff' }); + 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, + i18n: i18nService, + }; + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + }, 60_000); + + afterAll(async () => { + vi.restoreAllMocks(); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + const bridgeAs = (persona: Record, acceptLanguage?: string, extra: Record = {}) => + bridgeFor(kernelOver({ ...services, ...extra }), persona, acceptLanguage); + const field = (described: any, name: string) => described.fields.find((f: any) => f.name === name); + + it('describe_object under zh-CN: the object\'s and each field\'s label, description and option label are the bundle\'s; names never change', async () => { + const described = await (await bridgeAs(PERSONAS.staff, 'zh-CN,zh;q=0.9,en;q=0.8')).describeObject(OBJ); + expect(described).toMatchObject({ name: OBJ, label: '交易', description: '一笔销售交易,从首次接触到签单。' }); + expect(field(described, 'subject')).toMatchObject({ name: 'subject', label: '主题' }); + expect(field(described, 'amount')).toMatchObject({ name: 'amount', label: '金额', description: '金额,不含税。' }); + expect(field(described, 'stage')).toMatchObject({ + name: 'stage', + label: '阶段', + // The stored value a write sends is unchanged; only what a person reads is translated. + options: [{ value: 'won', label: '赢单' }, { value: 'lost', label: 'Lost' }], + }); + }); + + it('list_objects under zh-CN: each object\'s label and description are the bundle\'s, and the field count is the served one', async () => { + const listed: any[] = await (await bridgeAs(PERSONAS.member, 'zh-CN')).listObjects(); + expect(listed.find((o) => o.name === OBJ)).toEqual({ + name: OBJ, label: '交易', description: '一笔销售交易,从首次接触到签单。', fieldCount: expect.any(Number), + }); + // An object the bundle does not carry keeps its authored label. + expect(listed.find((o) => o.name === PLAIN)).toMatchObject({ name: PLAIN, label: 'Plain' }); + }); + + it('a field the member cannot read stays absent under translation, its translated label and description with it', async () => { + const bridge = await bridgeAs(PERSONAS.member, 'zh-CN'); + const described = await bridge.describeObject(OBJ); + expect(described.label).toBe('交易'); + expect(field(described, DENIED)).toBeUndefined(); + const text = JSON.stringify(described); + for (const leaked of ['毛利', '返利后的内部毛利。', 'Margin', DENIED_TEXT]) expect(text).not.toContain(leaked); + // …and the listing counts the fields the member is served: one fewer than the unrestricted control. + const memberCount = (await bridge.listObjects()).find((o: any) => o.name === OBJ).fieldCount; + const staffCount = (await (await bridgeAs(PERSONAS.staff, 'zh-CN')).listObjects()).find((o: any) => o.name === OBJ).fieldCount; + expect(memberCount).toBe(staffCount - 1); + }); + + it('without a locale preference (the default `en` carries no entry): the authored labels and descriptions', async () => { + const bridge = await bridgeAs(PERSONAS.staff); + const described = await bridge.describeObject(OBJ); + expect(described).toMatchObject({ name: OBJ, label: 'Deal', description: OBJECT_TEXT }); + expect(field(described, 'amount')).toMatchObject({ label: 'Amount', description: AMOUNT_TEXT }); + expect(field(described, 'stage').options).toEqual([{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }]); + expect((await bridge.listObjects()).find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + }); + + it('a locale the bundle does not carry, or no i18n service at all: the authored text', async () => { + const described = await (await bridgeAs(PERSONAS.staff, 'fr-FR')).describeObject(OBJ); + expect(described).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + const noI18n = await (await bridgeAs(PERSONAS.staff, 'zh-CN', { i18n: null })).describeObject(OBJ); + expect(noI18n).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + expect(field(noI18n, 'subject')).toMatchObject({ label: 'Subject' }); + }); +}); diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index d8b6b274b5d..b4a8eb66b4e 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -29,6 +29,7 @@ import { metaRequestLocale, translateMetaList, type FederationCallKind, + type MetaListTranslationSources, } from '@objectstack/rest'; // [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. @@ -1020,6 +1021,24 @@ export function buildMcpBridge( return { obj: projected.object ?? obj }; }; + /** + * [#34872] Served objects in THIS caller's locale: the `/meta` object + * door's translation (`translateMetaList`, the routine `GET /meta/object` + * and the dataset tools below run) for this request's locale + * ({@link metaTranslationSources}), ⛔ never a second translation routine. + * Handed the objects AS THIS CALLER IS SERVED THEM ({@link servedToCaller}): + * the translator rewrites the text of the fields it is given and adds + * none, so a field the mask removed stays absent, its translated label and + * description with it (ADR-0106 D3/D5). Computed per request (ADR-0156). + * No locale, or a key the bundle does not carry, leaves the authored text; + * names never change. + */ + const inCallerLocale = async (served: readonly any[]): Promise => { + if (served.length === 0) return [...served]; + const translated = await translateMetaList(metaTranslationSources(deps, context, getProtocol), 'object', [...served]); + return Array.isArray(translated) ? translated : [...served]; + }; + /** {@link readServedObject}, as this caller is served it ({@link servedToCaller}). */ const readObjectForCaller = async (name: string): Promise => { const def: any = await readServedObject(name); @@ -1028,7 +1047,7 @@ export function buildMcpBridge( const listObjectSummaries = async (): Promise => { const objs = await readServedObjects(); - const out: any[] = []; + const served: any[] = []; // [ADR-0106 D5(2)] Every listed object as this caller is served it, // so `fieldCount` counts the fields that exist for them. One object // that cannot be projected refuses the listing, as the `/meta` @@ -1036,7 +1055,11 @@ export function buildMcpBridge( for (const listed of objs) { const o = await servedToCaller(listed); // [ruling record 6787890900] An object the caller may not read is left out. - if (o === undefined) continue; + if (o !== undefined) served.push(o); + } + const out: any[] = []; + // [#34872] …in the caller's locale, the page translated in one call. + for (const o of await inCallerLocale(served)) { out.push({ name: o.name, label: o.label ?? o.name, @@ -1121,8 +1144,11 @@ export function buildMcpBridge( const declared: any = await readServedObject(name); const def: any = declared ? await servedToCaller(declared) : declared; if (!def) return null; + // [#34872] …in the caller's locale. `declared` is read for the + // `readonly` verdict alone, which no translation touches. + const [localized] = await inCallerLocale([def]); // [#32435] …each field and rule carrying what a write needs. - return describeServedObject(def, declared); + return describeServedObject(localized, declared); }, // [#28715] The fields `validate_expression` judges a `label()` call // against, from the object `describeObject` reads: the served object, @@ -1515,6 +1541,34 @@ export async function resolveMcpDatasetToolsService( return service && typeof service.datasetTools === 'function' ? (service as McpDatasetToolsService) : undefined; } +/** + * [ADR-0149 D2 · #34872] What the `/meta` translation reads for THIS request: + * the request's i18n service (a lookup that throws is none, and the text is + * then served untranslated), its protocol (an object's packaged base and a + * declared override's pair translations) and its locale — the + * `Accept-Language` / `?locale=` reading every `/meta` answer takes + * (`metaRequestLocale`), the i18n service's default last. One reading for the + * dataset tools and the object tools, so the two answer one caller in one + * locale. + */ +function metaTranslationSources( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + getProtocol: () => Promise, +): MetaListTranslationSources { + return { + resolveI18nService: async () => { + try { + return await deps.resolveService(context, 'i18n', context.environmentId); + } catch { + return undefined; + } + }, + resolveProtocol: getProtocol, + requestLocale: (i18n?: unknown) => metaRequestLocale({ headers: context.request?.headers }, i18n), + }; +} + /** * [ADR-0149 D2] The bridge's three dataset members over the analytics * service's executor, bound to THIS request's principal. @@ -1543,17 +1597,7 @@ function datasetToolMembers( const protocol = await getProtocol(); const items = (await actionExec.readMergedItems(protocol, 'dataset')) ?? []; const translated = await translateMetaList( - { - resolveI18nService: async () => { - try { - return await deps.resolveService(context, 'i18n', envId); - } catch { - return undefined; - } - }, - resolveProtocol: async () => protocol as any, - requestLocale: (i18n?: unknown) => metaRequestLocale({ headers: context.request?.headers }, i18n), - }, + metaTranslationSources(deps, context, async () => protocol), 'dataset', items, );