Skip to content

Commit 284c04b

Browse files
committed
feat(analytics): the tool texts say follow nextStep and cite sourceLine, naming the precedence
LIST_DATASETS_DESCRIPTION names the order from the exported DATASET_NEXT_STEP_PRECEDENCE; the MCP initialize rule says the same and is pinned to the constant. The DATASET_SELECTION_RULE docblock drops its stale sentence about the skill's loose-form rows. Both doors are pinned to pass the executor's answer through unchanged, one sentence on HTTP and stdio. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm
1 parent dd86154 commit 284c04b

8 files changed

Lines changed: 172 additions & 10 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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-②: no
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.
14+
- **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.
15+
- **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`.
16+
- **`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.
17+
- **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.
18+
- **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 context, so one caller reads one sentence on either.
19+
20+
`@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
@@ -25,6 +25,7 @@ import {
2525
MCP_OAUTH_SCOPE_METADATA_WRITE,
2626
QUERY_DATASET_TOOL_NAME,
2727
} from '@objectstack/spec/ai';
28+
import { DATASET_NEXT_STEP_PRECEDENCE } from '@objectstack/service-analytics';
2829
import { MCPServerRuntime } from './mcp-server-runtime.js';
2930
import type { McpDataBridge } from './mcp-http-tools.js';
3031
import type { McpAuthoringInjection } from './types.js';
@@ -192,3 +193,19 @@ describe('[#34686] initialize instructions — host and configured texts are lef
192193
expect(await instructionsOf(runtime, makeBridge())).toBe(CONFIGURED);
193194
});
194195
});
196+
197+
/**
198+
* [#34919] The rule tells the client to follow `list_datasets`' `nextStep`
199+
* and cite `query_dataset`'s `sourceLine`, and names the precedence among
200+
* mixed cases in the order the service-analytics executor applies it (its
201+
* exported constant, so a reorder there reds here).
202+
*/
203+
describe('[#34919] initialize instructions — follow nextStep, cite sourceLine', () => {
204+
it('names both members and the executor\'s precedence, in its order', async () => {
205+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
206+
const text = await instructionsOf(runtime, makeBridge());
207+
expect(text).toContain('nextStep');
208+
expect(text).toContain('sourceLine');
209+
expect(text).toContain(DATASET_NEXT_STEP_PRECEDENCE.join(', '));
210+
});
211+
});

‎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/services/service-analytics/src/__tests__/dataset-tools.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel';
3030
import { AnalyticsServicePlugin } from '../plugin.js';
3131
import { AnalyticsService } from '../analytics-service.js';
3232
import { createDatasetTools, getDatasetToolDefinitions } from '../dataset-tools.js';
33-
import { composeDatasetSourceLine, datasetToolSentenceLocale } from '../dataset-next-step.js';
33+
import { DATASET_NEXT_STEP_PRECEDENCE, composeDatasetSourceLine, datasetToolSentenceLocale } from '../dataset-next-step.js';
3434

3535
const ME = { userId: 'u_me', tenantId: 'org_a', locale: 'zh-CN' } as ExecutionContext;
3636
const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext;
@@ -178,6 +178,14 @@ describe('the two AIToolDefinitions', () => {
178178
expect(defs[0].description).toContain('非指标口径');
179179
expect(defs[1].description).toContain('provenance');
180180
});
181+
182+
it('[#34919] says follow nextStep and cite sourceLine, and names the precedence the executor applies', () => {
183+
const [list, query] = getDatasetToolDefinitions();
184+
expect(list.description).toContain('nextStep');
185+
expect(list.description).toContain(DATASET_NEXT_STEP_PRECEDENCE.join(', '));
186+
expect(query.description).toContain('sourceLine');
187+
expect(DATASET_NEXT_STEP_PRECEDENCE).toEqual(['several_measures', 'one_measure', 'candidates_only', 'no_measure']);
188+
});
181189
});
182190

183191
describe('[ADR-0149 D4 caveat] the tools require the plugin-wired service', () => {

‎packages/services/service-analytics/src/dataset-next-step.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,18 @@ export function datasetToolSentenceLocale(locales: readonly (string | undefined)
228228
return 'en';
229229
}
230230

231-
/** The decisions in reporting order: the first a term is in is the case `nextStep` reports. */
232-
const DECISION_PRECEDENCE: readonly DatasetNextStepDecision[] = ['several_measures', 'one_measure', 'candidates_only', 'no_measure'];
231+
/**
232+
* The decisions in reporting order: the first a term is in is the case
233+
* `nextStep` reports (the precedence above). `list_datasets`' description names
234+
* this order from this constant, and the MCP `initialize` rule is pinned to it,
235+
* so the order a client is told is the order the executor applies.
236+
*/
237+
export const DATASET_NEXT_STEP_PRECEDENCE: readonly DatasetNextStepDecision[] = Object.freeze([
238+
'several_measures',
239+
'one_measure',
240+
'candidates_only',
241+
'no_measure',
242+
]);
233243

234244
interface TermReading {
235245
readonly term: string;
@@ -316,7 +326,7 @@ export function composeDatasetNextStep(source: DatasetNextStepSource): DatasetNe
316326
const unique = [...new Set(source.terms)];
317327
if (unique.length === 0) return undefined;
318328
const readings = unique.map((term) => readTerm(term, source.datasets, source.candidates));
319-
const decision = DECISION_PRECEDENCE.find((d) => readings.some((r) => r.decision === d))!;
329+
const decision = DATASET_NEXT_STEP_PRECEDENCE.find((d) => readings.some((r) => r.decision === d))!;
320330
const reported = readings.filter((r) => r.decision === decision);
321331
const copy = COPY[datasetToolSentenceLocale(source.locales)];
322332
const members = (ms: readonly NamedMember[]) => copy.list(ms.map(copy.member));

‎packages/services/service-analytics/src/dataset-tools.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import {
3434
usableDeclaredMembers,
3535
} from './dataset-declared-members.js';
3636
import { findDatasetTermCandidates, matchDatasetTerms, type CandidateDataset } from './dataset-term-matcher.js';
37-
import { composeDatasetNextStep, composeDatasetSourceLine } from './dataset-next-step.js';
37+
import { DATASET_NEXT_STEP_PRECEDENCE, composeDatasetNextStep, composeDatasetSourceLine } from './dataset-next-step.js';
3838

3939
/**
4040
* The dataset AI tools — `list_datasets` and `query_dataset` — defined once,
@@ -113,7 +113,9 @@ const LIST_DATASETS_DESCRIPTION =
113113
+ 'dataset\'s `object`, add one line naming that dataset and its measures. A dimension match alone picks a '
114114
+ 'grouping, not a number: a measure must still match. `membersWithheld` means some members exist that this '
115115
+ 'caller may not see. When `terms` were sent the answer carries `nextStep`: the case of this rule your words are '
116-
+ 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`.';
116+
+ 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`. When '
117+
+ `the words are in different cases it reports the first of ${DATASET_NEXT_STEP_PRECEDENCE.join(', ')}, so a word `
118+
+ 'matching only a dimension never outranks a measure match.';
117119

118120
const QUERY_DATASET_DESCRIPTION =
119121
'Run a selection (measures, optional dimensions, filter, time window, order, limit) against one saved business '

‎packages/services/service-analytics/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ export type {
5555
} from './dataset-tools.js';
5656
export { matchDatasetTerms } from './dataset-term-matcher.js';
5757
export type { MatchableMember } from './dataset-term-matcher.js';
58+
// [#34919] The order list_datasets reports mixed cases by (`nextStep`), for the texts that name it.
59+
export { DATASET_NEXT_STEP_PRECEDENCE } from './dataset-next-step.js';
5860

5961
// Strategies
6062
export { NativeSQLStrategy } from './strategies/native-sql-strategy.js';

0 commit comments

Comments
 (0)