diff --git a/.changeset/34995-mcp-object-resources-caller-locale.md b/.changeset/34995-mcp-object-resources-caller-locale.md new file mode 100644 index 00000000000..c49ec65a6da --- /dev/null +++ b/.changeset/34995-mcp-object-resources-caller-locale.md @@ -0,0 +1,15 @@ +--- +'@objectstack/mcp': patch +--- + +fix(mcp): the `objectstack://objects` resources serve labels in the locale the object tools speak + +Clause-②: no +Metadata-protocol: none + +Over the stdio transport, the `objectstack://objects` and `objectstack://objects/{name}` resources now answer an object's label, description, field labels, field descriptions and option labels in the workspace's default locale, as `list_objects` and `describe_object` have since the object tools were localized. Before, the resources served the authored text, so a resource read and a tool call for the same object could name it in two languages. + +- The resources read the same localized view the two tools read, through the same translation the HTTP door's `/meta` answers use. A resource read and a tool call for one object answer the same labels. +- A field the caller cannot read stays absent from the resources, its translated text with it. +- With no default locale, or a key the bundle does not carry, the authored text is served, as before. Names never change. +- The Streamable HTTP door registers no resources, so nothing changes there. diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index c11a91bff90..ab04b0c1160 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -2161,7 +2161,10 @@ export class MCPServerRuntime { * * [#25245] The two object resources read the view this runtime's host gave * (`setRuntimeObjectView`, package-internal), at each read; without one they - * read `metadataService`, as before. + * read `metadataService`, as before. [#34995] Labels are served as that view + * serves them: the stdio host's view is localized as the object tools are + * (`servedLocaleObjectView`, `stdio-data-bridge.ts`), so the two builders + * below translate nothing themselves. */ bridgeResources( metadataService: IMetadataService, diff --git a/packages/mcp/src/plugin.ts b/packages/mcp/src/plugin.ts index e6a90877bd4..9169554f984 100644 --- a/packages/mcp/src/plugin.ts +++ b/packages/mcp/src/plugin.ts @@ -44,6 +44,7 @@ import { GATED_ACTIONS, serveStoredMetadataHashes, serveStoredMetadataRow, + servedLocaleObjectView, stdioObjectView, type StdioObjectReads, type StdioDatasetToolsService, @@ -901,12 +902,19 @@ export class MCPServerPlugin implements Plugin { // object-schema mask (`callerObjectView`), the view the tools read, so // a resource never names a field the tools withhold. With no principal // (this process starts no stdio transport) the view is the bare one. + // [#34995] …in the locale the object tools speak: the served view, + // localized through the wrapper the stdio bridge's `list_objects` / + // `describe_object` read (`servedLocaleObjectView`), with the same i18n + // service, so a resource and a tool answer one object with one label. const objectView = stdioObjectView({ metadataService, protocol: protocolReads }); setRuntimeObjectView( this.runtime, - schemaPrincipal - ? callerObjectView(objectView, { resolvePrincipal: schemaPrincipal, security: securityReads, schemaReadDelegates }) - : objectView, + servedLocaleObjectView( + schemaPrincipal + ? callerObjectView(objectView, { resolvePrincipal: schemaPrincipal, security: securityReads, schemaReadDelegates }) + : objectView, + { i18n: () => optionalService('i18n'), protocol: protocolReads }, + ), ); this.runtime.bridgeResources(metadataService, getRecord); // Awaited: the prompt bridge reads `skill` metadata to project each 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 index 0da68cefae3..9ba18b96123 100644 --- a/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts +++ b/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts @@ -27,6 +27,8 @@ 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'; +import { MCPServerPlugin } from './plugin.js'; +import type { MCPServerRuntime } from './mcp-server-runtime.js'; const OBJ = 'deal'; const PLAIN = 'plain'; @@ -202,3 +204,136 @@ describe('[#34872] stdio list_objects and describe_object serve labels and descr } }); }); + +describe('[#34995] the stdio object resources serve labels in the locale the object tools speak', () => { + const originalEnv = { ...process.env }; + beforeEach(() => { + process.env = { ...originalEnv }; + delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + process.env.OS_MCP_STDIO_API_KEY = 'osk_object_locale_resource_pin'; + }); + afterEach(() => { + process.env = { ...originalEnv }; + vi.restoreAllMocks(); + }); + + /** + * `MCPServerPlugin` over a host registering `i18n` (none when omitted) and a + * security service answering `readable`, and a client on its long-lived + * server: the composition that hands the tools and the resources their views. + */ + async function boot(opts: { readable: readonly string[]; i18n?: unknown }) { + const defs = () => [deal(), plain()]; + const metadata = { + listObjects: vi.fn(async () => defs()), + getObject: vi.fn(async (name: string) => defs().find((d) => d.name === name) ?? null), + get: vi.fn(async () => null), + list: vi.fn(async () => []), + exists: vi.fn(async () => false), + getRegisteredTypes: vi.fn(async () => ['object']), + register: vi.fn(), + unregister: vi.fn(), + }; + const objectql = { + // The stdio principal resolves from this key row and its owner. + find: vi.fn(async (object: string, query?: any) => { + if (object === 'sys_api_key') return [{ id: 'k1', user_id: 'usr_stdio', revoked: false }]; + if (object === 'sys_user') return query?.where?.id === 'usr_stdio' ? [{ id: 'usr_stdio' }] : []; + return []; + }), + getSchema: vi.fn(() => undefined), + }; + const answer = async () => [...opts.readable]; + const security = { getReadableFields: vi.fn(answer), getMetadataReadableFields: vi.fn(answer) }; + const registry = new Map([['metadata', metadata], ['objectql', objectql], ['security', security]]); + if (opts.i18n) registry.set('i18n', opts.i18n); + const ctx: any = { + registerService: vi.fn((name: string, service: unknown) => registry.set(name, service)), + getService: vi.fn((name: string) => { + if (!registry.has(name)) throw new Error(`Service "${name}" not found`); + return registry.get(name); + }), + replaceService: vi.fn(), + getServices: vi.fn(() => registry), + hook: vi.fn(), + trigger: vi.fn(async () => {}), + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(() => ({})), + }; + const plugin = new MCPServerPlugin({ autoStart: true }); + await plugin.init(ctx); + const runtime = registry.get('mcp') as MCPServerRuntime; + // `start()` would claim this process's real stdin/stdout. + vi.spyOn(runtime, 'start').mockResolvedValue(undefined); + await plugin.start(ctx); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await runtime.server.connect(serverSide); + const client = new Client({ name: 'pin', version: '0' }); + await client.connect(clientSide); + const tool = async (name: string, args: Record) => { + const res = (await client.callTool({ name, arguments: args })) as { isError?: boolean; content: Array<{ text: string }> }; + return { isError: res.isError === true, text: res.content[0]!.text, json: JSON.parse(res.content[0]!.text) }; + }; + const resource = async (uri: string) => { + const res = await client.readResource({ uri }); + const text = (res.contents[0] as { text: string }).text; + return { text, json: JSON.parse(text) }; + }; + return { tool, resource, close: () => client.close() }; + } + + /** Each listed object's name and label. */ + const labelsOf = (listed: any) => Object.fromEntries(listed.objects.map((o: any) => [o.name, o.label])); + + it('under a zh-CN default: each resource serves the bundle\'s labels, exactly as describe_object and list_objects do', async () => { + const k = await boot({ readable: MEMBER_READS, i18n: i18nService('zh-CN') }); + try { + const schema = await k.resource(`objectstack://objects/${OBJ}`); + expect(schema.json).toMatchObject({ name: OBJ, label: '交易', description: '一笔销售交易,从首次接触到签单。' }); + expect(field(schema.json, 'subject')).toMatchObject({ name: 'subject', label: '主题' }); + expect(field(schema.json, 'amount')).toMatchObject({ name: 'amount', label: '金额', description: '金额,不含税。' }); + expect(field(schema.json, 'stage').options).toEqual([{ value: 'won', label: '赢单' }, { value: 'lost', label: 'Lost' }]); + const listing = await k.resource('objectstack://objects'); + expect(labelsOf(listing.json)).toEqual({ [OBJ]: '交易', [PLAIN]: 'Plain' }); + + // The card's done-when: a resource read and a tool call for the same object answer the same labels. + const described = await k.tool('describe_object', { objectName: OBJ }); + expect(described.isError).toBe(false); + expect(schema.json).toEqual(described.json); + expect(labelsOf(listing.json)).toEqual(labelsOf((await k.tool('list_objects', {})).json)); + } finally { + await k.close(); + } + }); + + it('a field the principal cannot read stays absent from the translated resources, its translated text with it', async () => { + const k = await boot({ readable: MEMBER_READS, i18n: i18nService('zh-CN') }); + try { + const schema = await k.resource(`objectstack://objects/${OBJ}`); + expect(schema.json.label).toBe('交易'); + expect(field(schema.json, DENIED)).toBeUndefined(); + for (const leaked of [DENIED, '毛利', '返利后的内部毛利。', 'Margin', DENIED_TEXT]) expect(schema.text).not.toContain(leaked); + const listing = await k.resource('objectstack://objects'); + expect(listing.json.objects.find((o: any) => o.name === OBJ)?.fieldCount).toBe(4); + } finally { + await k.close(); + } + }); + + it('an `en` default with no entry, or no i18n service on the host: the authored labels on the resources and the tools alike', async () => { + for (const i18n of [i18nService('en'), undefined]) { + const k = await boot({ readable: MEMBER_READS, ...(i18n ? { i18n } : {}) }); + try { + const schema = await k.resource(`objectstack://objects/${OBJ}`); + expect(schema.json).toMatchObject({ name: OBJ, label: 'Deal', description: OBJECT_TEXT }); + expect(field(schema.json, 'amount')).toMatchObject({ label: 'Amount', description: AMOUNT_TEXT }); + expect(schema.json).toEqual((await k.tool('describe_object', { objectName: OBJ })).json); + const listing = await k.resource('objectstack://objects'); + expect(labelsOf(listing.json)).toEqual({ [OBJ]: 'Deal', [PLAIN]: 'Plain' }); + expect(labelsOf(listing.json)).toEqual(labelsOf((await k.tool('list_objects', {})).json)); + } finally { + await k.close(); + } + } + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index f4f5d631df3..70f78a7a4cd 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -644,6 +644,85 @@ export function callerObjectView(view: McpObjectView, deps: CallerObjectViewDeps return served; } +/** What {@link servedLocaleObjectView} localizes with: the host's `i18n` service and `protocol`. */ +export interface ServedLocaleSources { + /** The `i18n` service, resolved at each use ({@link StdioDataBridgeDeps.i18n}); a resolver that throws is none. */ + i18n?: () => unknown; + /** The `protocol` service: an object's packaged base and a declared override's pair translations. */ + protocol?: () => StdioProtocolObjectReads | undefined; +} + +/** + * [ADR-0149 D2 · #34872] What the HTTP door's `/meta` translation reads, on a + * transport that carries no request: the i18n service (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. + */ +function defaultLocaleSources(i18n: (() => unknown) | undefined, resolveProtocol: () => Promise) { + return { + resolveI18nService: async () => { + try { + return i18n?.(); + } catch { + return undefined; + } + }, + resolveProtocol, + requestLocale: (service?: unknown) => metaRequestLocale(undefined, service), + }; +} + +/** + * [#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. + */ +async function inServedLocale(sources: ServedLocaleSources, served: readonly ObjectDef[]): Promise { + if (served.length === 0) return [...served]; + const translated = await translateMetaList( + defaultLocaleSources(sources.i18n, async () => sources.protocol?.()), + 'object', + [...served], + ); + return Array.isArray(translated) ? (translated as ObjectDef[]) : [...served]; +} + +/** + * [#34872 · #34995] `view` in the locale this transport speaks + * ({@link inServedLocale}): what the object tools (`list_objects`, + * `describe_object`) and the `objectstack://objects` resources read, so a + * resource and a tool describe one object with one set of labels. Wrap the + * view the principal is served ({@link callerObjectView}): the served object + * is what is translated, never the declaration, so a masked field stays absent + * (ADR-0106 D3/D5). The declaration that object was projected from is handed + * on untranslated ({@link readObjectWithDeclaration}): only `readonly` is read + * off it. + */ +export function servedLocaleObjectView(view: McpObjectView, sources: ServedLocaleSources): McpObjectView { + const readWithDeclaration = async (name: string) => { + const { served, declared } = await readObjectWithDeclaration(view, name); + if (!served) return { served, declared }; + const [def] = await inServedLocale(sources, [served as ObjectDef]); + return { served: def, declared }; + }; + const localized: McpObjectView = { + async listObjects() { + return inServedLocale(sources, ((await view.listObjects()) ?? []) as ObjectDef[]); + }, + async getObject(name) { + return (await readWithDeclaration(name)).served; + }, + }; + setDeclaredObjectRead(localized, readWithDeclaration); + return localized; +} + /** * The ADR-0049 object exposure gate, applied before a data verb dispatches * (#8083). Throws {@link McpExposureError} when the object's own declaration @@ -1172,41 +1251,11 @@ 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]; - }; + // [#34872 · #34995] …and in the locale this transport speaks + // ({@link servedLocaleObjectView}): the view the object tools describe + // from, through the wrapper `plugin.ts` puts on the view the + // `objectstack://objects` resources read, so the two answer alike. + const localizedView = servedLocaleObjectView(servedView, { i18n: deps.i18n, protocol }); const bridge: McpDataBridge = { async listObjects(): Promise { @@ -1214,8 +1263,8 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // [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. - // [#34872] …in the locale this transport speaks ({@link inServedLocale}). - return (await inServedLocale((await servedView.listObjects()) as ObjectDef[])).map((o) => ({ + // [#34872] …in the locale this transport speaks ({@link servedLocaleObjectView}). + return ((await localizedView.listObjects()) as ObjectDef[]).map((o) => ({ name: o.name, label: o.label ?? o.name, ...authoredDescription(o), @@ -1257,17 +1306,16 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // twin judges it ({@link readObjectWithDeclaration}): only that boolean // is read off the declaration. async describeObject(name: string): Promise { - const { served, declared } = await readObjectWithDeclaration(servedView, name); - if (!served) return null; - // [#34872] …in the locale this transport speaks ({@link inServedLocale}); + // [#34872] …in the locale this transport speaks ({@link servedLocaleObjectView}); // `declared` is read for the `readonly` verdict alone. - const [def] = await inServedLocale([served as ObjectDef]); + const { served: def, declared } = await readObjectWithDeclaration(localizedView, name); + if (!def) return null; // 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 // leave that tool with zero fields in scope. // [#32435] …each field and rule carrying what a write needs. - return describeServedObject(def, declared as ServedObjectDef); + return describeServedObject(def as ServedObjectDef, declared as ServedObjectDef); }, // [#28715] From the object `describeObject` reads: the protocol's served @@ -1480,7 +1528,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge } else { items = (await metadataService.list('dataset')) ?? []; } - const translated = await translateMetaList(defaultLocaleSources(async () => merged), 'dataset', items); + const translated = await translateMetaList(defaultLocaleSources(deps.i18n, async () => merged), 'dataset', items); return Array.isArray(translated) ? translated : items; }; const executor = (maxQueryLimit?: number) =>