Skip to content

Commit 6932cb8

Browse files
feat(analytics): list_datasets answers nextStep and query_dataset answers sourceLine, in the caller's language (#35043)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBLW6dHPW6sSheA32XPKZzPV)_ Part of #34919 Was stacked on #34982. #34982 merged to `main` as `92a5cac8d2`. `main` was merged into this branch twice, both merges pure (an empty `--remerge-diff`): `367e324eeb` at `f2105a6ba3`, then `eb7b09d4d2` at `2a3b6bc75d`. A third pure merge brings in `b85dff0f43` at `861f110f58`. The diff against `main` is now only this PR's own 9 files: `packages/services/service-analytics/**`, `packages/mcp/src/**` and one changeset. 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 ## 维护者速读 - **改了什么**:调用方传了 `terms` 时,`list_datasets` 返回 `nextStep`。它包含三样:判断(一个指标 / 多个指标 / 只有候选 / 没有指标)、涉及的词、一句按调用方语言写好的话。`query_dataset` 返回 `sourceLine`,即把 `provenance` 写成一行可直接引用的来源。多种情况同时出现时,按「多个指标 > 一个指标 > 只有候选 > 没有指标」报告。报告「一个指标」或「只有候选」时,这句话还会点名被搁下的词:「一个指标」下有候选的词连同它的候选一起列出,并要求先问用户;两种情况下查不到的词都给出带标注的退路,只是分组维度的词按分组点名。工具说明和 MCP `initialize` 规则也同步写上「按 `nextStep` 走、引用 `sourceLine`」以及这个顺序。 - **为什么改**:#34894 裁定 A。这个判断原来只在托管包装层里替一个客户端算,挪进框架执行器后,所有调用这个工具的客户端读到的是同一个下一步。模型拿到写好的句子会照抄,自己拼常常拼不对。 - **风险与回滚**:只填规范已声明的两个可选键(形状已随 #34982 合入)。`matches`、`candidates`、`provenance` 和 REST 返回一字不改。句子只用本次返回里调用方看得到的成员拼成。回滚就是 revert 本 PR。 - **先看**:`packages/services/service-analytics/src/dataset-next-step.ts`,看 `leftOutSentences` 以及 `composeDatasetNextStep` 里调用它的 `one_measure` 和 `candidates_only` 两个分支:被搁下的词在这里补上,这是本轮改动、风险最高的一段;`packages/services/service-analytics/src/dataset-tools.ts`,看 `listDatasets` 末尾和 `queryDataset` 返回处的两次调用;`packages/mcp/src/mcp-server-runtime.ts` 的 `DATASET_SELECTION_RULE`。 - **两分钟验证**:`pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/dataset-tools.test.ts`,预期 1 个文件 71 个测试全绿。 - **需要你做的**:无,席位落地。本 PR 用 `Part of`,卡片由后续的 o3-E PR 关闭。 ## What changes - **The decision and the sentence** (`packages/services/service-analytics/src/dataset-next-step.ts`, new). `composeDatasetNextStep` reads the answer `list_datasets` is about to serve and nothing else. Each term sent is read once: a repeated term is one term, and a member it equals counts once. The term's case is: - one measure equal to it ⇒ `one_measure`; - more than one ⇒ `several_measures`; - none, with entries in `candidates` ⇒ `candidates_only`; - otherwise ⇒ `no_measure`, which includes a term equal only to a dimension. A term equal to one measure and to a dimension in another dataset is `one_measure`, because a dimension is not counted (as the `decision` describe says). - **Precedence among mixed cases.** #34982's TSDoc leaves this to this card, and it is fixed here. The reported case is the first of `several_measures`, `one_measure`, `candidates_only`, `no_measure`. The order is `DATASET_NEXT_STEP_PRECEDENCE`, exported from `@objectstack/service-analytics`. `terms` names every term sent that is in the reported case, in the order sent. The reasons for this order: - an ambiguous measure word must be asked about before anything is computed; - an exact equality decides the measure and outranks a possible reading; - a possible reading is worth a question before falling back. So a dimension-matched term never outranks a measure-matched one: `["商机金额", "销售阶段"]` reads `one_measure` with `terms: ["商机金额"]` (N1). The order is stated in three places: the TSDoc on the fill, `LIST_DATASETS_DESCRIPTION` (built from the constant), and the MCP `initialize` rule (pinned to the constant). - **A `one_measure` or `candidates_only` note still names the words it leaves out** (seat ruling B on the L1-c N1 note, extended to `candidates_only` by the seat's L2 S3). The order is unchanged, and `decision` and `terms` still name only the reported case. One helper, `leftOutSentences`, writes the tail for both cases, in all four languages: - under `one_measure`, a word with candidates, together with those candidates (each by its label and its dataset's label), and "ask the user which one is meant before using it; do not pick one"; - under either case, an unknown word, with its labelled fallback to `query_records` / `aggregate_records` ("no governed metric was used for them"); - under either case, a word that equals only a dimension, as that grouping. So `["营收", "churn"]` gives 营收's measure query and asks about churn's candidates in one sentence, and `["库存周转", "金额"]` asks about 金额's candidates and names 库存周转 with its fallback. `several_measures` asks before anything is computed, so its note carries no such tail. `LIST_DATASETS_DESCRIPTION` says that the note, with one_measure, also names the words left out and their candidates, and with candidates_only names the unknown and grouping-only words left out. The `initialize` rule's "follow its note" covers it without new text. - **Two smaller note fixes (the seat's L2 nits N1 and N2).** Two words that equal the same measure (`["商机数", "商机数量"]`, both `opp_count`) are counted as one metric, so the note says "using that measure" instead of "each is its own metric". A `no_measure` note that holds an unknown word and a grouping word now gives both instructions: the fallback for the unknown word and "ask which number is meant" for the grouping word. - **`note` names the members (N2).** - `one_measure`: the measure's label, its dataset's label, and the `datasetName` / measure names to query. - `several_measures` and `candidates_only`: each offered member by its label and its dataset's label, then "ask the user, do not pick, compute nothing yet". - `no_measure`: an unknown word sends the reader to `query_records` / `aggregate_records` with the 非指标口径 label. A word that is only a grouping names the grouping and asks which number is meant. - **A partial answer (N4): `nextStep` is kept, and the note says so.** With `partial: true` the answer still carries `nextStep`, computed from what it lists. That covers a degraded read, a read that failed, and an admission that could not be judged. `note` ends with one sentence: the catalogue was incomplete, a measure missing from it may exist, and the `warning` is to be repeated. - **`sourceLine`.** `composeDatasetSourceLine` writes the answer's `provenance` as one line: each measure's label and the dataset's label, then each dimension's label. `provenance` and the REST door's answer are unchanged. - **Only the admitted answer (N5).** Both sentences are composed from the served answer's entries, `candidates` and `provenance`. A member over a field the caller cannot read, an `internal` member and an unqueryable dataset therefore never appear. - **Language.** The request's locale, then the workspace default, then English: `userTextLocalesOf` (`@objectstack/core`) over the caller's `ExecutionContext`. Each code is read through the platform locale table (`platformLocaleTagOf`). Sentences exist in `en`, `zh-Hans`, `zh-Hant` and `ja`; another language takes the next rung. See the Acceptance notes for the `?locale=` request. - **Tool texts.** `LIST_DATASETS_DESCRIPTION` says to follow `nextStep`'s note and names the precedence. The `query_dataset` description says `sourceLine` is the source already written, to cite as given. `DATASET_SELECTION_RULE` (MCP `initialize`) says the same, in one rule with the existing rows. Its docblock's stale sentence about the skill's loose-form rows is replaced (#34659 gap 1). - **The MCP door** passes both members through unchanged on HTTP and stdio. No code change was needed there, and two pins prove it with the real executor. - **A pin from `main` updated.** #35029 (now on `main`) pins stdio `list_datasets` when the i18n reads throw, comparing the whole answer, and it sends `terms`. With terms sent, that degraded answer now also carries `nextStep`: `no_measure` for every word, with the incomplete-catalogue sentence. The pin in `packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts` now expects it. The runtime twin of that pin sends no terms and is unchanged. ## Why Ruling #34894 = A (record 6953671481): the framework's executor returns `nextStep` (a closed decision, the candidates, a sentence) and `sourceLine`. The spec declares the shapes (#34982, now on `main`), and the sentence's text is the executor's (ADR-0149 M1 stands). Seat L2 6962300533 sent N1, N2, N4 and N5 to this card, and L1-c 6964761658 added ruling B on its note N1. Each has a pin below. ## Tests - **`examples/app-crm` pins** (`dataset-tools.test.ts`). The fixture mirrors `crm_opportunity_metrics` member for member, beside a second dataset over app-crm's line items. The second dataset is needed because the D1 rule forbids one word answering to two members of one dataset. - `商机数` ⇒ `one_measure`. - `deal value` ⇒ `several_measures`, naming `Total Amount (dataset: Opportunity Metrics)` and `Line Amount (dataset: Line Item Metrics)`. - `金额` ⇒ `candidates_only`, naming all three offered members. - `库存周转` ⇒ `no_measure`. - `销售阶段` ⇒ `no_measure`, naming the grouping. - A caller who cannot read `amount` sees none of the three withheld members in any `nextStep` or `sourceLine`, and is refused `total_amount` with 403. - **Ruling B pins.** Both are checked in `en`, `zh-CN`, `zh-TW` and `ja-JP`. - `["商机数", "金额"]` ⇒ `one_measure`, `terms: ["商机数"]`. The note carries the query names, the word 金额, each of its three candidates, and the second dataset's label. This is the `["营收", "churn"]` shape. - `["商机数", "库存周转", "销售阶段"]` ⇒ `one_measure`. The note keeps 库存周转's fallback (`query_records`) and names the grouping. As a control, `["商机数"]` alone sends nobody to the object tools. - **Seat L2 round pins.** - S2: the ruling-B ask-first sentence is pinned in all four languages, after the candidates it is about. As a control, `["商机数"]` alone carries no such sentence. - S3: `["库存周转", "金额", "销售阶段"]` ⇒ `candidates_only`, `terms: ["金额"]`, in all four languages. The note names the three candidates, 库存周转 with its fallback (`query_records`), and the grouping `Stage`. `["库存周转", "金额"]` carries the English unknown-word sentence and the "for them" fallback. As a control, `["金额"]` alone sends nobody to the object tools. - N1: `["商机数", "商机数量"]` reads as one metric. As a control, `["商机数", "商机金额"]` still reads "Each is its own metric". - N2: `["库存周转", "销售阶段"]` carries both the fallback and "ask the user which number they mean". - **Precedence (every pair), six of six.** `several_measures` over `one_measure` (`["商机数", "deal value"]`), over `candidates_only` (`["金额", "deal value"]`) and over `no_measure` (`["deal value", "库存周转"]`, added this round). `one_measure` over `candidates_only` (`["金额", "商机数"]`) and over `no_measure` (`["商机金额", "销售阶段"]`, both orders). `candidates_only` over `no_measure` (`["库存周转", "金额"]`). - **Other executor pins.** N3, a repeated term, the three partial paths, the locale ladder, and the description and `initialize` texts. - **MCP.** `list_datasets` / `query_dataset` run over the real executor through `MCPServerRuntime` and through `createStdioDataBridge`. Both answer the same `nextStep` and `sourceLine`, and the HTTP answer equals the executor's. ## Acceptance notes - **Carried by a later o3-E PR (seat ruling): the ask-data skill line ("follow `nextStep`; cite `sourceLine`") and the #34869 daily MCP ask round read before and after.** That PR closes the card, so this one says `Part of #34919`. - **`?locale=` (the seat's item): not fixed here; the fix is outside this PR's file surface.** I read both doors at `origin/main` `367e324eeb`. This is a reading of the code, not a run over the door. - The sentence follows the caller's `ExecutionContext`. On the HTTP MCP door that is `Accept-Language` (`packages/runtime/src/security/resolve-execution-context.ts`, `requestLocale: preferredLocaleFromHeader(...)`), then the workspace setting. - The catalogue labels on that door are translated in `packages/runtime/src/domains/mcp.ts` `metaTranslationSources`. It calls `metaRequestLocale({ headers: context.request?.headers }, i18n)` and passes no `query`. So on the MCP door the labels read `Accept-Language`, then the i18n service's default. They never read `?locale=`, although that function's docblock says they do. - Result: a request that names its locale with `?locale=` alone gets neither labels nor sentence in that locale. Without `Accept-Language`, the labels take the i18n default and the sentence takes the workspace setting, and those two can differ. With `Accept-Language` the two agree. - Making the sentence follow the labels' locale needs two changes. First, the HTTP door in `packages/runtime` must pass `query` to `metaRequestLocale` and hand the executor the locale it translated with. Second, the executor needs a seam to receive that locale (for example a `DatasetToolsDeps` member). The executor in `service-analytics` sees only the context and the already-translated list; it never sees the request. - The first change is outside the claim's surface (`packages/services/service-analytics/**`, `packages/mcp/src/**`), so it is not made here. Adding the second without the first would be a seam nothing on HTTP feeds. - The stdio door has the same split: labels at the i18n default (`metaRequestLocale(undefined, i18n)`), and the sentence at the workspace setting. The open #34995 branch reworks stdio's served-locale helpers and leaves this as it is. - Reported to the seat to be carried as one runtime-door change for both readings. - **`overlap-check` before each push of this round.** `node scripts/pm/overlap-check.mjs` at `861f110f58`: `VERDICT clean exit 0`, clean against `main` (`b85dff0f43`) and against #35060, which shares two `packages/mcp/src` files. #35059 shares no file with this PR. The #34766 PR-b branch (`claude/issue-34766-mcp-draft-door-write`) has no PR and shares no file; `git merge-tree` with it merges cleanly. ## Verification Every reading below is at head `861f110f58`, which carries the merge of `main` `b85dff0f43` (pure: `git show --remerge-diff` prints nothing). <details><summary>Package tests and typechecks</summary> - Build: `pnpm --filter '@objectstack/service-analytics...' --filter '@objectstack/mcp...' build` under the verify lock: `VERDICT command-exit 0`. - `pnpm --filter @objectstack/service-analytics exec vitest run`: Test Files 218 passed (218), Tests 5584 passed, 335 skipped (5919). - `pnpm --filter @objectstack/mcp exec vitest run`: Test Files 71 passed (71), Tests 1264 passed (1264). - `pnpm --filter @objectstack/service-analytics typecheck` and `pnpm --filter @objectstack/mcp typecheck` (including `check:test-typecheck`): pass. - Lock verdict for the run: `VERDICT command-exit 0`. </details> <details><summary>Ablations this round (scripts/ablation-replace.mjs, at 377b2e4)</summary> - S2: the line `if (offered.length > 0) sentences.push(copy.leftCandidateTail);` deleted alone. The anchor went 1 ⇒ 0 and the blob `f428470252f2` ⇒ `7a9829f9a251`. `dataset-tools.test.ts`: 1 failed / 70 passed, the ruling-B candidate pin, with the note ending right after the candidates. Restore: blob equals the HEAD blob `f428470252f2`, and `git diff HEAD` is empty. - S3: in the `candidates_only` branch, the `leftOutSentences` call removed. The first attempt replaced the two lines with a substring of themselves, so the tool refused it before any test ran (a no-op, not a reading). The rerun used a marker line: anchor 1 ⇒ 0, marker 0 ⇒ 1, blob `f428470252f2` ⇒ `ca89f326e9b8`. `dataset-tools.test.ts`: 1 failed / 70 passed, the S3 pin. Restore: blob equals HEAD, and `git diff HEAD` is empty. - The ruling-B ablation at `a95eb068e0` and the earlier ones at `cfdea828f9` are in previous revisions of this body. </details> <details><summary>Targeted gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands` (no paths) derived 69 families from the tree at `861f110f58`. Its change set is this PR's 9 files, against merge base `b85dff0f4`. - 68 exit 0. `pnpm check:dual-build-cjs-loads` exit 3: PREREQUISITE NOT MET, because it reads every package's `dist/` and needs a whole-repo `pnpm build`. NOT MEASURED locally; CI runs it after Build Core. - `dispatch-gates --ran` (exit-coded record): "69 derived, 68 run, 1 NOT-MEASURED, 0 UNRUN". - `node scripts/check-changeset-no-major.mjs --base origin/main --event` (this body as the payload): "LEVEL AXIS: this PR declares clause-② `yes (widening)` and metadata-protocol `none`, and it introduces no changeset entry graded `minor` or above". So the changes are at `patch`. - `node scripts/pm/check-governed-merges.mjs --branch claude/issue-34919-dataset-next-step-executor`: "0 of 9 path(s) hit the register … NOT governed". - Families CI runs (the artifact-roster families, the wide families, the type-check lanes, the dogfood shards) are read from this PR's check-runs, not re-run here. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; the repo-wide `pnpm lint` is CI's. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. (Stacked on #34982 until it merged; `main` is merged in now.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched by this PR.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfR33NbV51QQU6R6bm --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2487242 commit 6932cb8

9 files changed

Lines changed: 1024 additions & 20 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
'@objectstack/mcp': patch
4+
---
5+
6+
feat(analytics): `list_datasets` answers `nextStep` and `query_dataset` answers `sourceLine`, written by the platform in the caller's language
7+
8+
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)
9+
Metadata-protocol: none
10+
11+
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.
12+
13+
- **`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).
14+
- **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.
15+
- **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.
16+
- **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`.
17+
- **`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.
18+
- **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.
19+
- **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).
20+
21+
`@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.

‎packages/mcp/src/initialize-selection-rule-34686.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
MCP_OAUTH_SCOPE_METADATA_WRITE,
2727
QUERY_DATASET_TOOL_NAME,
2828
} from '@objectstack/spec/ai';
29+
import { DATASET_NEXT_STEP_PRECEDENCE } from '@objectstack/service-analytics';
2930
import { MCPServerRuntime } from './mcp-server-runtime.js';
3031
import type { McpDataBridge } from './mcp-http-tools.js';
3132
import type { McpAuthoringInjection } from './types.js';
@@ -202,3 +203,19 @@ describe('[#34686] initialize instructions — host and configured texts are lef
202203
expect(await instructionsOf(runtime, makeBridge())).toBe(CONFIGURED);
203204
});
204205
});
206+
207+
/**
208+
* [#34919] The rule tells the client to follow `list_datasets`' `nextStep`
209+
* and cite `query_dataset`'s `sourceLine`, and names the precedence among
210+
* mixed cases in the order the service-analytics executor applies it (its
211+
* exported constant, so a reorder there reds here).
212+
*/
213+
describe('[#34919] initialize instructions — follow nextStep, cite sourceLine', () => {
214+
it('names both members and the executor\'s precedence, in its order', async () => {
215+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
216+
const text = await instructionsOf(runtime, makeBridge());
217+
expect(text).toContain('nextStep');
218+
expect(text).toContain('sourceLine');
219+
expect(text).toContain(DATASET_NEXT_STEP_PRECEDENCE.join(', '));
220+
});
221+
});

‎packages/mcp/src/mcp-dataset-tools.test.ts‎

Lines changed: 99 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
* the bridge as sent, with the tool's page cap beside them; an undeclared key is
1212
* refused before the bridge is asked, in the spec's words; a refusal the bridge
1313
* throws comes back as the coded tool error; `list_datasets.candidates` comes
14-
* back exactly as the executor answered it (#34763).
14+
* back exactly as the executor answered it (#34763); `list_datasets.nextStep`
15+
* and `query_dataset.sourceLine` reach the client as the executor wrote them,
16+
* one sentence for one caller on HTTP and on stdio (#34919).
1517
*/
1618

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

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

@@ -443,3 +446,98 @@ describe('[#34763] list_datasets candidates pass through MCP unchanged', () => {
443446
expect('candidates' in answer).toBe(false);
444447
});
445448
});
449+
450+
/**
451+
* [#34919, ADR-0149 M1 note] `list_datasets.nextStep` and
452+
* `query_dataset.sourceLine` are written by the service-analytics executor
453+
* (`dataset-next-step.ts`, pinned there); the MCP door holds no copy of either
454+
* sentence. Here the REAL executor, over a service `AnalyticsServicePlugin`
455+
* wires, answers one caller through the HTTP tool layer and through the stdio
456+
* bridge: both doors serve the executor's answer unchanged, so the caller reads
457+
* the same decision and the same sentence, in its locale, on either transport.
458+
*/
459+
describe('[#34919] nextStep and sourceLine reach the client unchanged, one sentence on HTTP and stdio', () => {
460+
const PRINCIPAL = { userId: 'u_key', tenantId: 'org_1', locale: 'zh-CN' };
461+
const OBJECTS: Record<string, { fields: Record<string, { type: string }> }> = {
462+
crm_opportunity: { fields: { id: { type: 'text' }, stage: { type: 'text' }, amount: { type: 'number' } } },
463+
};
464+
const METRICS = {
465+
name: 'crm_opportunity_metrics',
466+
label: 'Opportunity Metrics',
467+
object: 'crm_opportunity',
468+
dimensions: [{ name: 'stage', label: 'Stage', field: 'stage', type: 'string', synonyms: ['销售阶段'] }],
469+
measures: [
470+
{ name: 'opp_count', label: 'Opportunities', aggregate: 'count', synonyms: ['商机数'] },
471+
{ name: 'total_amount', label: 'Total Amount', aggregate: 'sum', field: 'amount', synonyms: ['商机金额'] },
472+
],
473+
};
474+
475+
async function wiredService(): Promise<AnalyticsService> {
476+
const registered: Record<string, unknown> = {};
477+
const engine = {
478+
execute: async () => ({ rows: [{ stage: 'won', opp_count: 3 }] }),
479+
hasObjectMiddleware: () => false,
480+
getObject: (name: string) => OBJECTS[name],
481+
resolveEffectiveDatasource: () => undefined,
482+
};
483+
const allFields = async (object: string) => Object.keys(OBJECTS[object]?.fields ?? {});
484+
const security = { getReadFilter: async () => undefined, canReadObject: () => true, getReadableFields: allFields, getQueryableFields: allFields };
485+
const ctx = {
486+
getService: (name: string) => (name === 'security' ? security : name === 'data' ? engine : registered[name]),
487+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
488+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
489+
logger: { info() {}, warn() {}, error() {}, debug() {} },
490+
};
491+
await new AnalyticsServicePlugin({ queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }) })
492+
.init(ctx as never);
493+
return registered.analytics as AnalyticsService;
494+
}
495+
496+
/** The HTTP door's bridge members over the executor, as the runtime binds them to the request's principal. */
497+
function httpBridge(service: AnalyticsService): McpDataBridge {
498+
const executor = () => service.datasetTools({ loadDatasets: async () => [METRICS] });
499+
const bridge = makeBridge();
500+
bridge.listDatasets = (input) => executor().listDatasets(input, PRINCIPAL as never);
501+
bridge.queryDataset = (input) => executor().queryDataset(input, PRINCIPAL as never);
502+
bridge.datasetToolDefinitions = () => executor().definitions;
503+
return bridge;
504+
}
505+
506+
function stdioBridge(service: AnalyticsService) {
507+
return createStdioDataBridge({
508+
engine: {} as any,
509+
metadataService: { list: async () => [] } as any,
510+
protocol: () => ({ getMetaItems: async () => ({ items: [METRICS] }) }) as any,
511+
resolvePrincipal: async () => PRINCIPAL as any,
512+
datasetTools: service as unknown as StdioDatasetToolsService,
513+
});
514+
}
515+
516+
it('list_datasets: the same nextStep on both doors, the executor\'s answer unchanged', async () => {
517+
const service = await wiredService();
518+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
519+
const input = { terms: ['商机金额', '销售阶段'] };
520+
const direct = await service.datasetTools({ loadDatasets: async () => [METRICS] }).listDatasets(input, PRINCIPAL as never);
521+
const json = await callTool(runtime, httpBridge(service), LIST_DATASETS_TOOL_NAME, input);
522+
expect(json.result?.isError).toBeFalsy();
523+
const viaHttp = JSON.parse(json.result!.content[0].text) as ListDatasetsOutput;
524+
const viaStdio = await stdioBridge(service).listDatasets!(input);
525+
expect(viaHttp).toEqual(direct);
526+
expect(direct.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机金额'] });
527+
expect(viaStdio.nextStep).toEqual(viaHttp.nextStep);
528+
expect(ListDatasetsOutputSchema.safeParse(viaHttp).success).toBe(true);
529+
});
530+
531+
it('query_dataset: the same sourceLine on both doors, the executor\'s answer unchanged', async () => {
532+
const service = await wiredService();
533+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
534+
const input = { datasetName: 'crm_opportunity_metrics', selection: { measures: ['opp_count'], dimensions: ['stage'] } };
535+
const json = await callTool(runtime, httpBridge(service), QUERY_DATASET_TOOL_NAME, input);
536+
expect(json.result?.isError).toBeFalsy();
537+
const viaHttp = JSON.parse(json.result!.content[0].text) as QueryDatasetOutput;
538+
const viaStdio = await stdioBridge(service).queryDataset!(input, { maxRows: 50 });
539+
expect(viaHttp.sourceLine).toEqual(expect.any(String));
540+
for (const label of ['Opportunities', 'Opportunity Metrics', 'Stage']) expect(viaHttp.sourceLine).toContain(label);
541+
expect(viaStdio.sourceLine).toBe(viaHttp.sourceLine);
542+
});
543+
});

‎packages/mcp/src/mcp-server-runtime.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1812,8 +1812,11 @@ const DEFAULT_HTTP_INSTRUCTIONS =
18121812
* that the same question, listing each candidate's label, dataset label and
18131813
* description, never a pick and never a match, even for a single candidate;
18141814
* only a word with no match and no candidate falls back to the object tools,
1815-
* with the answer labelled. The skill's own loose-form rows predate
1816-
* `candidates` and are amended in its lane.
1815+
* with the answer labelled. [#34919] The answer itself then states the
1816+
* case (`list_datasets` `nextStep`, composed by the service-analytics
1817+
* executor, `dataset-next-step.ts`) and the source to cite
1818+
* (`query_dataset` `sourceLine`); the rule says to follow the one and cite
1819+
* the other, and names the precedence the executor reports mixed cases by.
18171820
* Sent only where both dataset tools register ({@link datasetToolsServed}).
18181821
*/
18191822
const DATASET_SELECTION_RULE =
@@ -1824,7 +1827,9 @@ const DATASET_SELECTION_RULE =
18241827
+ 'they mean; do not pick. A word with no match but with candidates in the answer: ask the same way, listing '
18251828
+ 'each candidate\'s label, dataset label and description; do not pick one or treat it as a match. No match '
18261829
+ 'and no candidates: fall back to query_records / aggregate_records and say the answer is not from a governed '
1827-
+ 'metric.';
1830+
+ 'metric. The list_datasets answer states which of these cases your words are in as nextStep: follow its note, '
1831+
+ 'which reports the first of several_measures, one_measure, candidates_only, no_measure when words differ. Cite '
1832+
+ 'query_dataset\'s sourceLine as the answer\'s source.';
18281833

18291834
/**
18301835
* [#34686] The published skills package an open server points a client to

‎packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,15 @@ describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but i
242242
it.each(CASES)('$read throwing: list_datasets lists nothing, says partial and names the i18n error', async ({ read, message }) => {
243243
const bridge = await bridgeOverRealExecutor(() => i18nWhoseReadThrows(read, message));
244244
const answer = await bridge.listDatasets!({ terms: TERMS });
245-
expect(answer).toEqual({ datasets: [], partial: true, warning: expect.stringContaining(message) });
245+
// [#34919] Terms were sent, so the degraded answer also carries `nextStep`:
246+
// nothing listed reads `no_measure` for every word, and the note says the
247+
// catalogue was incomplete and to repeat the warning.
248+
expect(answer).toEqual({
249+
datasets: [],
250+
partial: true,
251+
warning: expect.stringContaining(message),
252+
nextStep: { decision: 'no_measure', terms: TERMS, note: expect.stringContaining('warning') },
253+
});
246254
expect(answer.warning).toMatch(/^The dataset catalogue could not be read: /);
247255
});
248256

0 commit comments

Comments
 (0)