Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
fe96c22
feat(spec): the dataset tools' output declares nextStep on list_datas…
claude Nov 17, 2026
d10ea09
chore(spec): regenerate the artefacts for nextStep and sourceLine
claude Nov 17, 2026
d304f1b
docs(spec): one nextStep reports one case, and the ADR-0149 M1 note n…
claude Nov 17, 2026
dd86154
feat(analytics): list_datasets answers nextStep and query_dataset ans…
claude Nov 17, 2026
284c04b
feat(analytics): the tool texts say follow nextStep and cite sourceLi…
claude Nov 17, 2026
cfdea82
test(analytics): a word equal to a measure and a dimension reads one_…
claude Nov 17, 2026
f10de61
merge origin/main (4443014630) into the dataset next-step branch
claude Nov 17, 2026
d80b2d8
chore(spec): regenerate the reference index after merging main
claude Nov 17, 2026
dd32488
Merge #34982's head d80b2d888d into claude/issue-34919-dataset-next-s…
claude Nov 17, 2026
f2105a6
Merge origin/main (367e324eeb) into claude/issue-34919-dataset-next-s…
claude Nov 18, 2026
4dd94e3
feat(analytics): a one_measure note names the words it leaves out, wi…
claude Nov 18, 2026
50f5944
test(analytics): the left-out unknown word keeps its fallback in all …
claude Nov 18, 2026
2a3b6bc
Merge origin/main (eb7b09d4d2) into claude/issue-34919-dataset-next-s…
claude Nov 18, 2026
a95eb06
test(mcp): the degraded stdio list_datasets read with terms carries n…
claude Nov 18, 2026
377b2e4
feat(analytics): candidates_only notes name the words they leave out;…
claude Nov 18, 2026
861f110
Merge origin/main b85dff0f43 into claude/issue-34919-dataset-next-ste…
claude Nov 18, 2026
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
21 changes: 21 additions & 0 deletions .changeset/34919-dataset-next-step-executor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/service-analytics': patch
'@objectstack/mcp': patch
---

feat(analytics): `list_datasets` answers `nextStep` and `query_dataset` answers `sourceLine`, written by the platform in the caller's language

Clause-②: yes (widening: the dataset tools' answers now carry `nextStep` and `sourceLine`, `@objectstack/service-analytics` exports `DATASET_NEXT_STEP_PRECEDENCE`, and the `list_datasets` / `query_dataset` descriptions and the MCP `initialize` rule gain the follow-`nextStep`, cite-`sourceLine` instructions)
Metadata-protocol: none

The dataset tools now fill the two members the spec declares (`DatasetNextStepSchema`, `QueryDatasetOutputSchema.sourceLine`, `@objectstack/spec/ai`). Until now the decision "one match answers, several ask, near ones are offered, none falls back" and the citation line were left for each AI client to work out from `matches`, `candidates` and `provenance`; a model handed a finished sentence copies it, and one that builds it from parts often does not.

- **`nextStep` on `list_datasets`, whenever `terms` were sent.** `decision` is the case of the ADR-0149 D3 rule the words are in, counted in measures: one measure equals the word ⇒ `one_measure`; more than one, in one dataset or several ⇒ `several_measures`; no match but `candidates` ⇒ `candidates_only`; otherwise `no_measure`, which includes a word that equals only a dimension. `terms` names every word sent (once each, in order) that is in the reported case. `note` is that case as a finished sentence: the measure and the names to query for `one_measure`; each member by its label and its dataset's label for `several_measures` and `candidates_only`, with "ask the user, do not pick"; the object query tools for an unknown word, and "ask which number" for a word that is only a grouping (both, when a `no_measure` answer holds one of each).
- **Words a `one_measure` or `candidates_only` answer leaves out are still named.** A `one_measure` `note` gives the measure word's query and then names each other word: one with candidates together with those candidates (label and dataset label) and "ask before using it"; an unknown one with its labelled fallback to the object query tools; a grouping word as that grouping. A `candidates_only` `note` asks about the candidates and names each unknown word with its labelled fallback and each grouping-only word the same way. Two words that equal the same measure are told it is one metric.
- **Precedence among mixed cases.** One answer reports one case, the first of `several_measures`, `one_measure`, `candidates_only`, `no_measure`. A word that matches only a dimension never outranks a measure match: `["营收", "销售阶段"]` reports `one_measure` for `营收`. The order is exported as `DATASET_NEXT_STEP_PRECEDENCE` from `@objectstack/service-analytics`, and the tool description and the MCP `initialize` rule name it.
- **A partial answer says so.** With `partial: true` the answer still carries `nextStep`, computed from what it lists, and `note` ends by saying the catalogue was incomplete, that a measure missing from it may exist, and to repeat the `warning`.
- **`sourceLine` on `query_dataset`.** The answer's `provenance` as one line to cite: each measure's label and the dataset's label, then each dimension's label (`指标:营收(数据集:销售分析);维度:阶段`). `provenance` is unchanged and stays the structured source. The REST dataset door's answer is not changed.
- **Only what the caller may see.** Both sentences are composed from the answer being served: a member over a field the caller cannot read, an `internal` member and a dataset the caller may not query never appear in either.
- **Language.** The request's locale, else the workspace default, else English, the ladder every platform-composed sentence follows (`userTextLocalesOf`, read from the caller's execution context). Sentences are written in English, Simplified Chinese, Traditional Chinese and Japanese; another language takes the next rung. The HTTP and stdio MCP doors hand the executor the same execution context, so a caller reads the same sentence on either when both doors carry the same locale (the stdio door has no request locale, so there the workspace default or English decides).

`@objectstack/mcp`: the `initialize` selection rule now tells the client to follow `nextStep`'s note, names the precedence, and says to cite `sourceLine`. Both tools pass the two members through unchanged.
17 changes: 17 additions & 0 deletions packages/mcp/src/initialize-selection-rule-34686.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
MCP_OAUTH_SCOPE_METADATA_WRITE,
QUERY_DATASET_TOOL_NAME,
} from '@objectstack/spec/ai';
import { DATASET_NEXT_STEP_PRECEDENCE } from '@objectstack/service-analytics';
import { MCPServerRuntime } from './mcp-server-runtime.js';
import type { McpDataBridge } from './mcp-http-tools.js';
import type { McpAuthoringInjection } from './types.js';
Expand Down Expand Up @@ -192,3 +193,19 @@ describe('[#34686] initialize instructions — host and configured texts are lef
expect(await instructionsOf(runtime, makeBridge())).toBe(CONFIGURED);
});
});

/**
* [#34919] The rule tells the client to follow `list_datasets`' `nextStep`
* and cite `query_dataset`'s `sourceLine`, and names the precedence among
* mixed cases in the order the service-analytics executor applies it (its
* exported constant, so a reorder there reds here).
*/
describe('[#34919] initialize instructions — follow nextStep, cite sourceLine', () => {
it('names both members and the executor\'s precedence, in its order', async () => {
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
const text = await instructionsOf(runtime, makeBridge());
expect(text).toContain('nextStep');
expect(text).toContain('sourceLine');
expect(text).toContain(DATASET_NEXT_STEP_PRECEDENCE.join(', '));
});
});
100 changes: 99 additions & 1 deletion packages/mcp/src/mcp-dataset-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
* the bridge as sent, with the tool's page cap beside them; an undeclared key is
* refused before the bridge is asked, in the spec's words; a refusal the bridge
* throws comes back as the coded tool error; `list_datasets.candidates` comes
* back exactly as the executor answered it (#34763).
* back exactly as the executor answered it (#34763); `list_datasets.nextStep`
* and `query_dataset.sourceLine` reach the client as the executor wrote them,
* one sentence for one caller on HTTP and on stdio (#34919).
*/

import { describe, it, expect, beforeEach, vi } from 'vitest';
Expand All @@ -29,6 +31,7 @@ import { MCPServerRuntime } from './mcp-server-runtime.js';
import { hasDatasetTools, type McpDataBridge } from './mcp-http-tools.js';
import { createStdioDataBridge, type StdioDatasetToolsService } from './stdio-data-bridge.js';
import { ASK_SECTION_HEADING, renderSkillMarkdown } from './skill-md.js';
import { AnalyticsServicePlugin, type AnalyticsService } from '@objectstack/service-analytics';

const DATASET_TOOLS = [LIST_DATASETS_TOOL_NAME, QUERY_DATASET_TOOL_NAME].sort();

Expand Down Expand Up @@ -443,3 +446,98 @@ describe('[#34763] list_datasets candidates pass through MCP unchanged', () => {
expect('candidates' in answer).toBe(false);
});
});

/**
* [#34919, ADR-0149 M1 note] `list_datasets.nextStep` and
* `query_dataset.sourceLine` are written by the service-analytics executor
* (`dataset-next-step.ts`, pinned there); the MCP door holds no copy of either
* sentence. Here the REAL executor, over a service `AnalyticsServicePlugin`
* wires, answers one caller through the HTTP tool layer and through the stdio
* bridge: both doors serve the executor's answer unchanged, so the caller reads
* the same decision and the same sentence, in its locale, on either transport.
*/
describe('[#34919] nextStep and sourceLine reach the client unchanged, one sentence on HTTP and stdio', () => {
const PRINCIPAL = { userId: 'u_key', tenantId: 'org_1', locale: 'zh-CN' };
const OBJECTS: Record<string, { fields: Record<string, { type: string }> }> = {
crm_opportunity: { fields: { id: { type: 'text' }, stage: { type: 'text' }, amount: { type: 'number' } } },
};
const METRICS = {
name: 'crm_opportunity_metrics',
label: 'Opportunity Metrics',
object: 'crm_opportunity',
dimensions: [{ name: 'stage', label: 'Stage', field: 'stage', type: 'string', synonyms: ['销售阶段'] }],
measures: [
{ name: 'opp_count', label: 'Opportunities', aggregate: 'count', synonyms: ['商机数'] },
{ name: 'total_amount', label: 'Total Amount', aggregate: 'sum', field: 'amount', synonyms: ['商机金额'] },
],
};

async function wiredService(): Promise<AnalyticsService> {
const registered: Record<string, unknown> = {};
const engine = {
execute: async () => ({ rows: [{ stage: 'won', opp_count: 3 }] }),
hasObjectMiddleware: () => false,
getObject: (name: string) => OBJECTS[name],
resolveEffectiveDatasource: () => undefined,
};
const allFields = async (object: string) => Object.keys(OBJECTS[object]?.fields ?? {});
const security = { getReadFilter: async () => undefined, canReadObject: () => true, getReadableFields: allFields, getQueryableFields: allFields };
const ctx = {
getService: (name: string) => (name === 'security' ? security : name === 'data' ? engine : registered[name]),
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
logger: { info() {}, warn() {}, error() {}, debug() {} },
};
await new AnalyticsServicePlugin({ queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }) })
.init(ctx as never);
return registered.analytics as AnalyticsService;
}

/** The HTTP door's bridge members over the executor, as the runtime binds them to the request's principal. */
function httpBridge(service: AnalyticsService): McpDataBridge {
const executor = () => service.datasetTools({ loadDatasets: async () => [METRICS] });
const bridge = makeBridge();
bridge.listDatasets = (input) => executor().listDatasets(input, PRINCIPAL as never);
bridge.queryDataset = (input) => executor().queryDataset(input, PRINCIPAL as never);
bridge.datasetToolDefinitions = () => executor().definitions;
return bridge;
}

function stdioBridge(service: AnalyticsService) {
return createStdioDataBridge({
engine: {} as any,
metadataService: { list: async () => [] } as any,
protocol: () => ({ getMetaItems: async () => ({ items: [METRICS] }) }) as any,
resolvePrincipal: async () => PRINCIPAL as any,
datasetTools: service as unknown as StdioDatasetToolsService,
});
}

it('list_datasets: the same nextStep on both doors, the executor\'s answer unchanged', async () => {
const service = await wiredService();
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
const input = { terms: ['商机金额', '销售阶段'] };
const direct = await service.datasetTools({ loadDatasets: async () => [METRICS] }).listDatasets(input, PRINCIPAL as never);
const json = await callTool(runtime, httpBridge(service), LIST_DATASETS_TOOL_NAME, input);
expect(json.result?.isError).toBeFalsy();
const viaHttp = JSON.parse(json.result!.content[0].text) as ListDatasetsOutput;
const viaStdio = await stdioBridge(service).listDatasets!(input);
expect(viaHttp).toEqual(direct);
expect(direct.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机金额'] });
expect(viaStdio.nextStep).toEqual(viaHttp.nextStep);
expect(ListDatasetsOutputSchema.safeParse(viaHttp).success).toBe(true);
});

it('query_dataset: the same sourceLine on both doors, the executor\'s answer unchanged', async () => {
const service = await wiredService();
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
const input = { datasetName: 'crm_opportunity_metrics', selection: { measures: ['opp_count'], dimensions: ['stage'] } };
const json = await callTool(runtime, httpBridge(service), QUERY_DATASET_TOOL_NAME, input);
expect(json.result?.isError).toBeFalsy();
const viaHttp = JSON.parse(json.result!.content[0].text) as QueryDatasetOutput;
const viaStdio = await stdioBridge(service).queryDataset!(input, { maxRows: 50 });
expect(viaHttp.sourceLine).toEqual(expect.any(String));
for (const label of ['Opportunities', 'Opportunity Metrics', 'Stage']) expect(viaHttp.sourceLine).toContain(label);
expect(viaStdio.sourceLine).toBe(viaHttp.sourceLine);
});
});
11 changes: 8 additions & 3 deletions packages/mcp/src/mcp-server-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1812,8 +1812,11 @@ const DEFAULT_HTTP_INSTRUCTIONS =
* that the same question, listing each candidate's label, dataset label and
* description, never a pick and never a match, even for a single candidate;
* only a word with no match and no candidate falls back to the object tools,
* with the answer labelled. The skill's own loose-form rows predate
* `candidates` and are amended in its lane.
* with the answer labelled. [#34919] The answer itself then states the
* case (`list_datasets` `nextStep`, composed by the service-analytics
* executor, `dataset-next-step.ts`) and the source to cite
* (`query_dataset` `sourceLine`); the rule says to follow the one and cite
* the other, and names the precedence the executor reports mixed cases by.
* Sent only where both dataset tools register ({@link datasetToolsServed}).
*/
const DATASET_SELECTION_RULE =
Expand All @@ -1824,7 +1827,9 @@ const DATASET_SELECTION_RULE =
+ 'they mean; do not pick. A word with no match but with candidates in the answer: ask the same way, listing '
+ 'each candidate\'s label, dataset label and description; do not pick one or treat it as a match. No match '
+ 'and no candidates: fall back to query_records / aggregate_records and say the answer is not from a governed '
+ 'metric.';
+ 'metric. The list_datasets answer states which of these cases your words are in as nextStep: follow its note, '
+ 'which reports the first of several_measures, one_measure, candidates_only, no_measure when words differ. Cite '
+ 'query_dataset\'s sourceLine as the answer\'s source.';

/**
* [#34686] The published skills package an open server points a client to
Expand Down
10 changes: 9 additions & 1 deletion packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,15 @@ describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but i
it.each(CASES)('$read throwing: list_datasets lists nothing, says partial and names the i18n error', async ({ read, message }) => {
const bridge = await bridgeOverRealExecutor(() => i18nWhoseReadThrows(read, message));
const answer = await bridge.listDatasets!({ terms: TERMS });
expect(answer).toEqual({ datasets: [], partial: true, warning: expect.stringContaining(message) });
// [#34919] Terms were sent, so the degraded answer also carries `nextStep`:
// nothing listed reads `no_measure` for every word, and the note says the
// catalogue was incomplete and to repeat the warning.
expect(answer).toEqual({
datasets: [],
partial: true,
warning: expect.stringContaining(message),
nextStep: { decision: 'no_measure', terms: TERMS, note: expect.stringContaining('warning') },
});
expect(answer.warning).toMatch(/^The dataset catalogue could not be read: /);
});

Expand Down
Loading
Loading