Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/34872-mcp-object-tools-locale.md
Original file line number Diff line number Diff line change
@@ -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.
204 changes: 204 additions & 0 deletions packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = { '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<string, unknown>): 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();
}
}
});
});
68 changes: 47 additions & 21 deletions packages/mcp/src/stdio-data-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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<unknown>) => ({
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<ObjectDef[]> => {
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<McpObjectSummary[]> {
// [#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),
Expand Down Expand Up @@ -1220,8 +1258,10 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge
// is read off the declaration.
async describeObject(name: string): Promise<unknown | null> {
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
Expand Down Expand Up @@ -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) =>
Expand Down
Loading
Loading