diff --git a/.changeset/34787-stdio-list-datasets-locale.md b/.changeset/34787-stdio-list-datasets-locale.md new file mode 100644 index 00000000000..d0583bb5933 --- /dev/null +++ b/.changeset/34787-stdio-list-datasets-locale.md @@ -0,0 +1,14 @@ +--- +'@objectstack/mcp': patch +--- + +fix(mcp): stdio `list_datasets` localizes the dataset catalogue for the workspace default locale + +Clause-②: no +Metadata-protocol: none + +Over the stdio transport, `list_datasets` and `query_dataset` read the saved datasets untranslated. A workspace whose default locale is `zh-CN` therefore saw English member labels over stdio, and a term that equals a zh-CN bundle label (for example 总金额) matched nothing. The same workspace over HTTP, with no `Accept-Language`, showed the zh-CN labels and matched the term as `label`. + +The stdio bridge now localizes the dataset list with the same translator the HTTP door uses (`translateMetaList` from `@objectstack/rest`), for the i18n service's default locale. That is what the HTTP door answers when a call carries no locale, and it is the only locale a stdio session speaks (ADR-0149 D2). A host with no i18n service, or one whose i18n service cannot be resolved, keeps today's untranslated list. Matching is unchanged: a term still matches the label in the locale the catalogue is served in. + +`@objectstack/mcp` now depends on `@objectstack/rest`. diff --git a/packages/mcp/package.json b/packages/mcp/package.json index a96376d5d62..fd3773181f6 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -32,6 +32,7 @@ "@objectstack/formula": "workspace:*", "@objectstack/lint": "workspace:*", "@objectstack/metadata-core": "workspace:*", + "@objectstack/rest": "workspace:*", "@objectstack/spec": "workspace:*", "@objectstack/types": "workspace:*", "unpdf": "1.9.1", @@ -39,6 +40,7 @@ }, "devDependencies": { "@objectstack/objectql": "workspace:*", + "@objectstack/service-analytics": "workspace:*", "@types/node": "^26.6.5", "typescript": "^6.0.3", "vitest": "^4.1.11" diff --git a/packages/mcp/src/plugin.ts b/packages/mcp/src/plugin.ts index 9dcbc2b3e2c..e6a90877bd4 100644 --- a/packages/mcp/src/plugin.ts +++ b/packages/mcp/src/plugin.ts @@ -816,6 +816,10 @@ export class MCPServerPlugin implements Plugin { // registered during `init()`, so an absence now is final (ADR-0116), // and the tools must be registered before the transport attaches. datasetTools: datasetToolsService(ctx), + // [ADR-0149 D2] The i18n service the saved datasets are localized + // with, resolved at each use as the protocol is; a host that + // registers none serves them untranslated. + i18n: () => optionalService('i18n'), }); } else { // Functional degradation, said once and naming the remedy: two of the diff --git a/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts new file mode 100644 index 00000000000..3bfabc02d91 --- /dev/null +++ b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts @@ -0,0 +1,143 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0149 D2] The stdio bridge localizes its saved datasets for the + * workspace default locale, the way the HTTP door localizes them for a call + * with no `Accept-Language`. + * + * D2's `list_datasets` source is "localized at the metadata boundary for the + * caller's locale the way the REST door localizes a saved dataset", with no + * transport exception. The stdio transport carries no request, so its locale + * is the i18n service's default — the one locale this face speaks. + * + * The executor here is a stand-in that lists what the bridge loaded and + * matches the terms with the platform's own `matchDatasetTerms`, so a hit on a + * bundle label reads `matchedOn: 'label'` exactly when the bridge handed the + * translated label over. + * + * Pinned: + * - a zh-CN default: the catalogue carries the zh-CN bundle labels, and a + * bundle-only term (总金额 / 阶段) hits as `label`; + * - an `en` default: today's answer — the authored labels, and no hit for the + * zh-CN bundle term; + * - an i18n service the host cannot resolve (its resolver throws), or none: + * the untranslated list, never an error. + */ + +import { describe, it, expect } from 'vitest'; +import type { ListDatasetsOutput } from '@objectstack/spec/ai'; +import { matchDatasetTerms, type MatchableMember } from '@objectstack/service-analytics'; +import { createStdioDataBridge, type StdioDataBridgeDeps, type StdioDatasetToolsService } from './stdio-data-bridge.js'; + +const PRINCIPAL = { userId: 'u_key', tenantId: 'org_1' }; + +const METRICS = { + name: 'opp_metrics', + label: 'Opportunity Metrics', + object: 'crm_opportunity', + dimensions: [{ name: 'stage', label: 'Stage', field: 'stage', type: 'string' }], + measures: [{ name: 'total_amount', label: 'Total Amount', aggregate: 'sum', field: 'amount' }], +}; + +const ZH_CN = { + datasets: { + opp_metrics: { + label: '商机指标', + dimensions: { stage: { label: '阶段' } }, + measures: { total_amount: { label: '总金额' } }, + }, + }, +}; + +/** An i18n service double: the zh-CN bundle above, and the default the test 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, + }; +} + +type Member = MatchableMember & { label?: unknown }; +type LoadedDataset = { name: string; label?: string; object: string; dimensions: Member[]; measures: Member[] }; + +/** The stand-in executor: lists the loaded datasets and matches terms with the platform matcher. */ +const service: StdioDatasetToolsService = { + datasetTools: ({ loadDatasets }) => ({ + definitions: [], + async listDatasets(input, context) { + const terms = (input as { terms?: string[] }).terms; + const loaded = (await loadDatasets(context)) as LoadedDataset[]; + return { + datasets: loaded.map((d) => ({ + name: d.name, + label: d.label, + object: d.object, + dimensions: d.dimensions.map((m) => ({ name: m.name, label: m.label, type: 'string' })), + measures: d.measures.map((m) => ({ name: m.name, label: m.label, aggregate: 'sum' })), + ...(terms ? { matches: matchDatasetTerms(terms, { dimensions: d.dimensions, measures: d.measures }) } : {}), + })), + } as unknown as ListDatasetsOutput; + }, + async queryDataset() { + throw new Error('not used'); + }, + }), +}; + +function bridgeWith(i18n: StdioDataBridgeDeps['i18n']) { + return createStdioDataBridge({ + engine: {} as any, + metadataService: { list: async () => [] } as any, + protocol: () => ({ getMetaItems: async () => ({ items: [METRICS] }) }) as any, + resolvePrincipal: async () => PRINCIPAL as any, + datasetTools: service, + ...(i18n ? { i18n } : {}), + }); +} + +const TERMS = ['总金额', '阶段', 'Total Amount']; + +describe('[ADR-0149 D2] stdio list_datasets is localized for the workspace default locale', () => { + it('a zh-CN default serves the zh-CN bundle labels, and a bundle-only term hits as `label`', async () => { + const answer = await bridgeWith(() => i18nService('zh-CN')).listDatasets!({ terms: TERMS }); + const [ds] = answer.datasets; + expect(ds.label).toBe('商机指标'); + expect(ds.dimensions.map((m) => m.label)).toEqual(['阶段']); + expect(ds.measures.map((m) => m.label)).toEqual(['总金额']); + expect(ds.matches).toEqual([ + { term: '总金额', member: 'measures.total_amount', matchedOn: 'label' }, + { term: '阶段', member: 'dimensions.stage', matchedOn: 'label' }, + { term: 'Total Amount', member: 'measures.total_amount', matchedOn: 'name' }, + ]); + }); + + it('an `en` default keeps the authored labels, and the zh-CN bundle term does not hit', async () => { + const answer = await bridgeWith(() => i18nService('en')).listDatasets!({ terms: TERMS }); + const [ds] = answer.datasets; + expect(ds.label).toBe('Opportunity Metrics'); + expect(ds.dimensions.map((m) => m.label)).toEqual(['Stage']); + expect(ds.measures.map((m) => m.label)).toEqual(['Total Amount']); + expect(ds.matches).toEqual([ + { term: 'Total Amount', member: 'measures.total_amount', matchedOn: 'name' }, + ]); + }); + + it('an i18n service whose resolution throws leaves the list untranslated, not an error', async () => { + const answer = await bridgeWith(() => { + throw new Error('i18n service not registered'); + }).listDatasets!({ terms: TERMS }); + const [ds] = answer.datasets; + expect(ds.label).toBe('Opportunity Metrics'); + expect(ds.measures.map((m) => m.label)).toEqual(['Total Amount']); + expect(ds.matches).toEqual([ + { term: 'Total Amount', member: 'measures.total_amount', matchedOn: 'name' }, + ]); + }); + + it('a host with no i18n service leaves the list untranslated', async () => { + const answer = await bridgeWith(undefined).listDatasets!({}); + expect(answer.datasets[0].measures.map((m) => m.label)).toEqual(['Total Amount']); + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 02d2b2a3bfd..5dad161888a 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -161,6 +161,10 @@ import { type DiagnosedObjectListing, } from './metadata-completeness.js'; import { staleSummaryRefusalOrThrow, withEarnedAnswer, type SummaryRecomputeRefusal } from '@objectstack/types'; +// [ADR-0149 D2] The `/meta` list translation and its locale parse, the pair +// the HTTP door's `loadDatasets` runs — imported, never restated, so both +// transports localize a saved dataset with one function. +import { metaRequestLocale, translateMetaList } from '@objectstack/rest'; // [ADR-0106] Metadata-plane field-level security: the posture, its relation to // the fetched document and the projection every object-schema exit runs — the // REST `/meta` doors and the runtime dispatcher's included. Imported, never @@ -257,6 +261,12 @@ export interface StdioDataBridgeDeps { * dataset tool registers. */ 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. + */ + i18n?: () => unknown; } /** @@ -1406,17 +1416,42 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // analytics service's executor over. The saved datasets come from the // protocol's merged listing (the read the REST door resolves `datasetName` // from), or the metadata service on a host with none; a throwing read is - // left to throw, and the executor answers it as a degraded read. The stdio - // bridge has no delegation probe (an API key is not delegated), so none is - // passed, as `query_records` here carries none. + // left to throw, and the executor answers it as a degraded read. The list is + // localized with the HTTP door's `/meta` list translation: this transport + // carries no request, so the locale is the i18n service's default (what + // `metaRequestLocale` answers with no header), the workspace default the + // stdio principal speaks. An i18n service this host cannot resolve leaves the + // list untranslated, as there. The stdio bridge has no delegation probe (an + // API key is not delegated), so none is passed, as `query_records` here + // carries none. if (deps.datasetTools) { const service = deps.datasetTools; const loadDatasets = async (): Promise => { - const merged = protocol?.(); - if (merged && typeof merged.getMetaItems === 'function') { - return metaItemsArray(await merged.getMetaItems({ type: 'dataset' })); + const protocolService = protocol?.(); + let merged: StdioProtocolObjectReads | undefined; + let items: readonly unknown[]; + if (protocolService && typeof protocolService.getMetaItems === 'function') { + merged = protocolService; + items = metaItemsArray(await protocolService.getMetaItems({ type: 'dataset' })); + } else { + items = (await metadataService.list('dataset')) ?? []; } - return (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, + ); + return Array.isArray(translated) ? translated : items; }; const executor = (maxQueryLimit?: number) => service.datasetTools({ loadDatasets, ...(maxQueryLimit !== undefined ? { maxQueryLimit } : {}) }); diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts index c2b90be2860..9f54b45945a 100644 --- a/packages/mcp/vitest.config.ts +++ b/packages/mcp/vitest.config.ts @@ -64,11 +64,21 @@ export default defineConfig({ // name from `SEARCH_COMPANION_FIELD`: VALUE imports, judged against the // source in the checkout, not a build of it. Only the test loads the // engine; the tool reads the name from `@objectstack/spec/data`. + // + // The `@objectstack/rest` entry is for the stdio bridge's dataset loader + // (ADR-0149 D2), which localizes the saved datasets with the REST + // package's `translateMetaList`: a VALUE import every stdio-bridge suite + // reaches, judged against the translator in the checkout, not a build of it. + // The `@objectstack/service-analytics` entry is for that loader's suite, + // whose stand-in executor matches terms with the platform's own + // `matchDatasetTerms`, judged against the matcher in the checkout. alias: [ { find: /^@objectstack\/metadata-core$/, replacement: path.resolve(__dirname, '../metadata-core/src/index.ts') }, { find: /^@objectstack\/metadata-core\/testing$/, replacement: path.resolve(__dirname, '../metadata-core/src/testing.ts') }, { find: /^@objectstack\/lint$/, replacement: path.resolve(__dirname, '../lint/src/index.ts') }, { find: /^@objectstack\/objectql\/core$/, replacement: path.resolve(__dirname, '../objectql/src/core.ts') }, + { find: /^@objectstack\/rest$/, replacement: path.resolve(__dirname, '../rest/src/index.ts') }, + { find: /^@objectstack\/service-analytics$/, replacement: path.resolve(__dirname, '../services/service-analytics/src/index.ts') }, ], }, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e9810d8a0f9..4c70df748de 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1433,6 +1433,9 @@ importers: '@objectstack/metadata-core': specifier: workspace:* version: link:../metadata-core + '@objectstack/rest': + specifier: workspace:* + version: link:../rest '@objectstack/spec': specifier: workspace:* version: link:../spec @@ -1449,6 +1452,9 @@ importers: '@objectstack/objectql': specifier: workspace:* version: link:../objectql + '@objectstack/service-analytics': + specifier: workspace:* + version: link:../services/service-analytics '@types/node': specifier: ^26.6.5 version: 26.6.5