From 41320146498353159161fac2b9d21947d28b71f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:55:21 +0000 Subject: [PATCH 1/4] feat(analytics): list_datasets fills candidates for a term that matched nothing The near-term finder beside matchDatasetTerms (containment either way after normalization, both sides at least two code points), over admitted members only, run only for terms with no hit in any listed entry; the list_datasets description and the MCP initialize selection rule learn the candidates row. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- content/docs/ai/connect-mcp.mdx | 12 +- packages/mcp/README.md | 10 +- packages/mcp/src/mcp-server-runtime.ts | 19 ++- .../src/dataset-term-matcher.ts | 109 +++++++++++++++++- .../service-analytics/src/dataset-tools.ts | 29 +++-- 5 files changed, 155 insertions(+), 24 deletions(-) diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 3294135de0d..65d130bfe83 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -289,10 +289,14 @@ between a governed metric and an object query, because a client reads a tool's description only after it has chosen that tool. Where both dataset tools are registered for the connection, the instructions say: look for a governed metric first by calling `list_datasets` with the question's business words; a word -matches only when it equals a name, label or synonym; one measure match is -answered with `query_dataset`; several matches are a question for the user; no -match falls back to `query_records` / `aggregate_records`, saying the answer is -not from a governed metric. A token without `data:read` gets neither tool and no +matches only when it equals a name, label or synonym; each word with exactly one +measure match is answered with `query_dataset`, and two such words are two +metrics computed both; several matches are a question for the user; a word with +no match but with `candidates` in the answer (members offered as possible +readings) is the same question, listing each candidate's label, dataset label +and description, and is never treated as a match; no match and no candidates +falls back to `query_records` / `aggregate_records`, saying the answer is not +from a governed metric. A token without `data:read` gets neither tool and no such sentence. The instructions also name the published skills package and the version to diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 15b357e4728..25aae1ade9d 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -78,10 +78,12 @@ grant, then two parts: - **The selection rule**, only where this request registers both `list_datasets` and `query_dataset`: look for a governed metric first with - `list_datasets` and the question's business words; one measure match answers - through `query_dataset`; several matches are a question for the user; no - match falls back to the object tools and says the answer is not from a - governed metric. A grant without `data:read` gets no such sentence. + `list_datasets` and the question's business words; each word with exactly + one measure match answers through `query_dataset`, and two such words are two + metrics computed both; several matches are a question for the user; a word + with `candidates` in the answer is the same question, never a match; no match + and no candidates falls back to the object tools and says the answer is not + from a governed metric. A grant without `data:read` gets no such sentence. - **The skills install line**: `Published skills: @objectstack/skills ` and its `pnpm add -D` command, at this package's own version (the two are released together), never the `version` option. diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index f7962db531b..dac849c9b8d 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1804,16 +1804,23 @@ const DEFAULT_HTTP_INSTRUCTIONS = * chosen that tool (#34659 ruling D5 = A); the full procedure stays in the * tools' own descriptions and in the served skill (`DATASET_TOOL_LINES` in * `skill-md.ts`), which say the same thing: an exact name, label or synonym is - * the only match, one measure match answers, several are a question for the - * user, none falls back to the object tools with the answer labelled. - * Sent only where both dataset tools register ({@link datasetToolsServed}). + * the only match, each word with one measure match answers (two such words + * are two metrics), several are a question for the user, a word with + * `candidates` is the same question and never a match (the ADR-0149 D3 + * amendment note), and none with no candidate falls back to the object tools + * with the answer labelled. The published skill's step 2 rows say it too + * (`skills/objectstack-ask/SKILL.md`). Sent only where both dataset tools + * register ({@link datasetToolsServed}). */ const DATASET_SELECTION_RULE = 'For a question about a business number, look for a governed metric first: call list_datasets with the ' + 'question\'s business words. A word matches only when it equals a measure\'s or dimension\'s name, label or ' - + 'synonym, never a similar word. One measure match: answer with query_dataset. Several matches: ask the user ' - + 'which one they mean; do not pick. No match: fall back to query_records / aggregate_records and say the answer ' - + 'is not from a governed metric.'; + + 'synonym, never a similar word. Each word that matches exactly one measure: answer with query_dataset; two ' + + 'such words are two metrics, so compute both. One word matching several measures: ask the user which one ' + + '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.'; /** * [#34686] The published skills package an open server points a client to diff --git a/packages/services/service-analytics/src/dataset-term-matcher.ts b/packages/services/service-analytics/src/dataset-term-matcher.ts index f4e92f4503b..85170dd79c0 100644 --- a/packages/services/service-analytics/src/dataset-term-matcher.ts +++ b/packages/services/service-analytics/src/dataset-term-matcher.ts @@ -1,6 +1,11 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import type { DatasetTermMatch, DatasetTermMatchedOn } from '@objectstack/spec/ai'; +import { + LIST_DATASETS_MAX_CANDIDATES_PER_TERM, + type DatasetTermCandidate, + type DatasetTermMatch, + type DatasetTermMatchedOn, +} from '@objectstack/spec/ai'; import { normalizeDatasetTerm } from '@objectstack/spec/ui'; /** @@ -19,6 +24,10 @@ import { normalizeDatasetTerm } from '@objectstack/spec/ui'; * query labelled 「非指标口径」, a dimension hit alone is no answer) are the * caller's: the tool descriptions state them, and `matches` is the input they * decide on. This function decides nothing beyond "which words are equal". + * + * {@link findDatasetTermCandidates} is the D3 amendment note's half (behind + * `list_datasets.candidates`): for a term with no hit anywhere, the members + * offered for a clarifying question. It never changes what a hit is. */ /** A member's match targets, as the dataset declares them. */ @@ -77,3 +86,101 @@ export function matchDatasetTerms( } return matches; } + +/** + * A listed dataset as {@link findDatasetTermCandidates} reads it: its name and + * the members the caller was ADMITTED to see, in the order its catalogue entry + * lists them. + */ +export interface CandidateDataset { + readonly name: string; + readonly dimensions: readonly MatchableMember[]; + readonly measures: readonly MatchableMember[]; +} + +/** + * The shortest word, in code points after normalization, that takes part in a + * near comparison, on either side. One code point (`a`, `营`) is contained in + * too many words to say anything about any of them. + */ +export const DATASET_TERM_NEAR_MIN_CODE_POINTS = 2; + +const codePoints = (s: string): number => [...s].length; + +/** Every match target a member carries: its name, each label locale, each string synonym. */ +function targetsOf(member: MatchableMember): string[] { + return [ + member.name, + ...labelTargets(member.label), + ...(member.synonyms ?? []).filter((s): s is string => typeof s === 'string'), + ]; +} + +/** + * Whether `member` is NEAR `normalizedTerm`: after the one normalization, one + * of its match targets contains the term, or the term contains the target, + * both at least {@link DATASET_TERM_NEAR_MIN_CODE_POINTS} code points long. + * `金额` is near `合同金额` and `合同金额` is near `金额`. No edit distance, stem or + * embedding: a containment test is a string comparison a unit test can pin + * (ADR-0149 D3), and every consumer gets the same answer. + */ +function isNear(normalizedTerm: string, member: MatchableMember): boolean { + for (const target of targetsOf(member)) { + const t = normalizeDatasetTerm(target); + if (codePoints(t) < DATASET_TERM_NEAR_MIN_CODE_POINTS) continue; + if (t.includes(normalizedTerm) || normalizedTerm.includes(t)) return true; + } + return false; +} + +/** + * [ADR-0149 D3, amendment note] The members `list_datasets` offers as possible + * readings of each term that matched nothing: `ListDatasetsOutputSchema`'s + * `candidates`, to its shape, order and cap. + * + * - Only over the members given, which are the members the caller was + * admitted to see in the datasets the caller may query: a withheld member, + * an `internal`-field member or an unadmitted dataset is never passed in, + * so it is never offered and every pointer names a member the same answer + * lists. + * - Only for a term with NO hit in any dataset given, judged by the same + * equality {@link matchDatasetTerms} reports as `matches`: a candidate is + * never a hit, and a term with a hit anywhere has no candidate. + * - Near is {@link isNear}: containment either way after normalization, both + * sides at least two code points. + * - Order is the listing order, never a ranking: terms as sent (a term sent + * twice is offered once), then datasets as given, then each dataset's + * measures before its dimensions (a dimension alone is no answer, D3 rule + * 5), each in the order given. At most + * `LIST_DATASETS_MAX_CANDIDATES_PER_TERM` per term, the first in that order; + * nothing marks the cut. + * + * An empty array when there is nothing to offer: the caller omits the key. + */ +export function findDatasetTermCandidates( + terms: readonly string[], + datasets: readonly CandidateDataset[], +): DatasetTermCandidate[] { + const candidates: DatasetTermCandidate[] = []; + const seen = new Set(); + for (const term of terms) { + if (seen.has(term)) continue; + seen.add(term); + const normalized = normalizeDatasetTerm(term); + if (codePoints(normalized) < DATASET_TERM_NEAR_MIN_CODE_POINTS) continue; + const hit = datasets.some((d) => + [...d.dimensions, ...d.measures].some((m) => matchedOn(normalized, m) !== undefined)); + if (hit) continue; + let offered = 0; + scan: for (const dataset of datasets) { + for (const [kind, list] of [['measures', dataset.measures], ['dimensions', dataset.dimensions]] as const) { + for (const member of list) { + if (!isNear(normalized, member)) continue; + candidates.push({ term, dataset: dataset.name, member: `${kind}.${member.name}` }); + if (++offered >= LIST_DATASETS_MAX_CANDIDATES_PER_TERM) break scan; + } + } + } + } + return candidates; +} diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index cc4635da312..7efcfee5b29 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -28,7 +28,7 @@ import { undeclaredSelectionMembers, usableDeclaredMembers, } from './dataset-declared-members.js'; -import { matchDatasetTerms } from './dataset-term-matcher.js'; +import { findDatasetTermCandidates, matchDatasetTerms, type CandidateDataset } from './dataset-term-matcher.js'; /** * The dataset AI tools — `list_datasets` and `query_dataset` — defined once, @@ -86,14 +86,17 @@ const LIST_DATASETS_DESCRIPTION = 'List the governed business datasets this caller may query: each dataset\'s dimensions (what an answer can be ' + 'grouped by) and measures (the numbers it can answer), with their business definitions and synonyms. Pass ' + '`terms` — the business words lifted from the question — and each dataset reports which of them equal a ' - + 'member\'s name, label or synonym (`matches`). Selection rule: one match on a measure wins, so answer through ' - + '`query_dataset` with that dataset and measure, and cite the answer\'s `provenance` as its source. Several ' - + 'matches (two datasets or two members answer to the word): ask the user which one is meant, listing each ' - + 'candidate\'s label, dataset label and description; never pick one. No match: fall back to the object query ' - + 'tools and say in the answer that no governed metric was used (非指标口径); when the object you fall back to ' - + 'is a listed dataset\'s `object`, add one line naming that dataset and its measures. A dimension match alone ' - + 'picks a grouping, not a number: a measure must still match. `membersWithheld` means some members exist that ' - + 'this caller may not see.'; + + 'member\'s name, label or synonym (`matches`). Selection rule: a word for a thing measured that matches exactly ' + + 'one measure wins, so answer through `query_dataset` with that dataset and measure, and cite the answer\'s ' + + '`provenance` as its source; two such words are two metrics, so compute both. One word matching several ' + + 'measures (in one dataset or two): ask the user which one is meant, listing each candidate\'s label, dataset ' + + 'label and description; never pick one. A word that matched nothing may have `candidates`, members offered as ' + + 'possible readings: ask the same way, listing each one\'s label, dataset label and description; never pick one, ' + + 'and never treat a candidate as a match. No match and no candidates: fall back to the object query tools and ' + + 'say in the answer that no governed metric was used (非指标口径); when the object you fall back to is a listed ' + + 'dataset\'s `object`, add one line naming that dataset and its measures. A dimension match alone picks a ' + + 'grouping, not a number: a measure must still match. `membersWithheld` means some members exist that this ' + + 'caller may not see.'; const QUERY_DATASET_DESCRIPTION = 'Run a selection (measures, optional dimensions, filter, time window, order, limit) against one saved business ' @@ -406,6 +409,9 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { const locale = context?.locale; const entries: DatasetToolCatalogEntry[] = []; + // The admitted members of each listed dataset, in its entry's order: the + // only members a candidate may name (ADR-0149 D3 amendment note). + const listed: CandidateDataset[] = []; let unresolved = false; for (const dataset of loaded.datasets) { const admission = await service.admitDatasetCatalogEntry(dataset, context); @@ -438,7 +444,11 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { }; if (terms !== undefined) entry.matches = matchDatasetTerms(terms, { dimensions, measures }); entries.push(entry); + listed.push({ name: dataset.name, dimensions, measures }); } + // Terms with no hit in any listed entry get the near members, or nothing: + // the key is absent rather than an empty list. + const candidates = terms !== undefined ? findDatasetTermCandidates(terms, listed) : []; const warnings: string[] = []; if (loaded.partial && loaded.warning) warnings.push(loaded.warning); @@ -448,6 +458,7 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { return { datasets: entries, ...(warnings.length > 0 ? { partial: true as const, warning: warnings.join(' ') } : {}), + ...(candidates.length > 0 ? { candidates } : {}), }; } From ddb99a1114f936907214d6ddfdd95d74da89fc8d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:56:25 +0000 Subject: [PATCH 2/4] fix(mcp): leave the selection rule's docblock to the in-flight skill single-source change Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- packages/mcp/src/mcp-server-runtime.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index dac849c9b8d..92d4acd7ebc 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1804,13 +1804,9 @@ const DEFAULT_HTTP_INSTRUCTIONS = * chosen that tool (#34659 ruling D5 = A); the full procedure stays in the * tools' own descriptions and in the served skill (`DATASET_TOOL_LINES` in * `skill-md.ts`), which say the same thing: an exact name, label or synonym is - * the only match, each word with one measure match answers (two such words - * are two metrics), several are a question for the user, a word with - * `candidates` is the same question and never a match (the ADR-0149 D3 - * amendment note), and none with no candidate falls back to the object tools - * with the answer labelled. The published skill's step 2 rows say it too - * (`skills/objectstack-ask/SKILL.md`). Sent only where both dataset tools - * register ({@link datasetToolsServed}). + * the only match, one measure match answers, several are a question for the + * user, none falls back to the object tools with the answer labelled. + * Sent only where both dataset tools register ({@link datasetToolsServed}). */ const DATASET_SELECTION_RULE = 'For a question about a business number, look for a governed metric first: call list_datasets with the ' From 2926ce238477e4883615483452548d9a09c8c4fd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:00:37 +0000 Subject: [PATCH 3/4] test(analytics): pin list_datasets candidates; checklist near-miss step; changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../34763-list-datasets-candidates-fill.md | 20 +++ docs/qa/platform-checklist/areas/ai.json | 23 +++- .../list-datasets-candidates-34763.test.ts | 114 ++++++++++++++++++ .../__tests__/dataset-term-matcher.test.ts | 103 +++++++++++++++- .../src/__tests__/dataset-tools.test.ts | 65 +++++++++- 5 files changed, 318 insertions(+), 7 deletions(-) create mode 100644 .changeset/34763-list-datasets-candidates-fill.md create mode 100644 packages/mcp/src/list-datasets-candidates-34763.test.ts diff --git a/.changeset/34763-list-datasets-candidates-fill.md b/.changeset/34763-list-datasets-candidates-fill.md new file mode 100644 index 00000000000..3e6955d14d9 --- /dev/null +++ b/.changeset/34763-list-datasets-candidates-fill.md @@ -0,0 +1,20 @@ +--- +'@objectstack/service-analytics': patch +'@objectstack/mcp': patch +--- + +feat(analytics): `list_datasets` offers `candidates` for a term that matched nothing, and the selection text says to ask about them + +Clause-②: no +Metadata-protocol: none + +A business word that equalled no member's name, label or synonym used to get nothing back, so an AI went straight to the object query tools even when a listed measure was obviously what the user meant (`invoice` beside the measure labelled `Invoices`). + +`list_datasets` now fills the `candidates` member the spec already declares: for each term with no match in any listed dataset, the members near it, as `{ term, dataset, member }` pointers to members listed in the same answer. + +- **Near** means that, after the same normalization the matcher uses, one of the member's names, labels (any locale) or synonyms contains the term, or the term contains it, with both at least two characters (code points) long. `金额` is near `合同金额` and the reverse. No edit distance, stems or embeddings. +- **Only what the caller may read.** Candidates come from the datasets and members the answer lists. A member over a field the caller cannot read, a member over an `internal` field, and a dataset the caller may not query are never offered. +- **Never beside a match.** A term with a match anywhere in the answer has no candidates. What counts as a match is unchanged. +- **Listing order, capped.** Terms in the order sent (a repeated term is offered once), then datasets in the order listed, then each dataset's measures before its dimensions. At most `LIST_DATASETS_MAX_CANDIDATES_PER_TERM` (5) per term, with no marker for the cut. When nothing is offered the key is absent, never an empty list. + +The `list_datasets` tool description and the `initialize` selection rule the HTTP MCP server sends now say: each word that matches exactly one measure is computed, and two such words are two metrics computed both; one word matching several measures is a question for the user; a word with `candidates` is the same question, listing each candidate's label, dataset label and description, and a candidate is never picked or treated as a match; no match and no candidates falls back to the object tools, saying the answer is not from a governed metric. diff --git a/docs/qa/platform-checklist/areas/ai.json b/docs/qa/platform-checklist/areas/ai.json index 35f1d6d7ef0..40e683469db 100644 --- a/docs/qa/platform-checklist/areas/ai.json +++ b/docs/qa/platform-checklist/areas/ai.json @@ -1137,7 +1137,7 @@ "title": "MCP serves the governed datasets: list_datasets lists each dataset this caller may query with its members and reports which terms match which member, and query_dataset answers rows with provenance, a row count and a truncation fact, never SQL", "since": "v18.4", "status": "active", - "revision": 2, + "revision": 3, "priority": "P1", "surface": "api", "personas": [ @@ -1157,13 +1157,14 @@ "call query_dataset { datasetName: 'showcase_invoice_metrics', selection: { measures: ['invoice_count'], dimensions: ['status'] } }", "the same with selection.limit: 1", "query_dataset { datasetName: 'qa_no_such_dataset', selection: { measures: ['invoice_count'] } }", - "query_dataset { dataset: 'showcase_invoice_metrics', selection: { measures: ['invoice_count'] } }; then { datasetName: 'showcase_invoice_metrics', measures: ['invoice_count'] }" + "query_dataset { dataset: 'showcase_invoice_metrics', selection: { measures: ['invoice_count'] } }; then { datasetName: 'showcase_invoice_metrics', measures: ['invoice_count'] }", + "a near miss: list_datasets { terms: ['invoice'] }; then list_datasets { terms: ['invoices'] }" ], "acceptance": [ { "clause": "a keyed session lists both tools, each described with the selection rule the model reads", "oracle": "network", - "verify": "tools/list names list_datasets and query_dataset; the list_datasets description says one match on a measure wins and several matches ask the user (packages/services/service-analytics/src/dataset-tools.ts#getDatasetToolDefinitions; packages/mcp/src/mcp-http-tools.ts#registerDatasetTools)", + "verify": "tools/list names list_datasets and query_dataset; the list_datasets description says one match on a measure wins, several matches ask the user, and a word with candidates asks the same way and is never a match (packages/services/service-analytics/src/dataset-tools.ts#getDatasetToolDefinitions; packages/mcp/src/mcp-http-tools.ts#registerDatasetTools)", "evidence": "the two tool entries" }, { @@ -1175,7 +1176,7 @@ { "clause": "terms are matched after normalization against name, label and synonym, and each match names its member", "oracle": "network", - "verify": "the invoice entry's matches hold { term: 'invoices', member: 'measures.invoice_count', matchedOn: 'label' } and { term: 'status', member: 'dimensions.status', matchedOn: 'name' }; qa_no_word matches nothing anywhere (packages/spec/src/ui/dataset.zod.ts#normalizeDatasetTerm; packages/spec/src/ai/dataset-tools.zod.ts#DatasetTermMatchSchema)", + "verify": "the invoice entry's matches hold { term: 'invoices', member: 'measures.invoice_count', matchedOn: 'label' } and { term: 'status', member: 'dimensions.status', matchedOn: 'name' }; qa_no_word matches nothing anywhere, and the answer carries no `candidates` key (packages/spec/src/ui/dataset.zod.ts#normalizeDatasetTerm; packages/spec/src/ai/dataset-tools.zod.ts#DatasetTermMatchSchema)", "evidence": "the matches arrays" }, { @@ -1207,6 +1208,12 @@ "oracle": "test", "verify": "run each file in automated.ref with its package's vitest and `--reporter=tree`, which prints one line per file (RUNNER.md's environment facts); each reports ≥1 test and 0 failed", "evidence": "the vitest summary line per file, with the subject sha" + }, + { + "clause": "a term that matches nothing is answered with candidates: members near it that this caller may read, offered for a question and never a match; a term that matches has none", + "oracle": "network", + "verify": "terms ['invoice']: no dataset's matches holds the term, and `candidates` holds { term: 'invoice', dataset: 'showcase_invoice_metrics', member: 'measures.invoice_count' }, each entry a pointer to a member the same answer lists, at most 5 per term. terms ['invoices']: the label match of step 2 and no `candidates` key (packages/spec/src/ai/dataset-tools.zod.ts#DatasetTermCandidateSchema; packages/services/service-analytics/src/dataset-term-matcher.ts#findDatasetTermCandidates)", + "evidence": "both answers' matches and candidates" } ], "negative": [ @@ -1219,7 +1226,7 @@ ], "automated": { "kind": "unit", - "ref": "packages/services/service-analytics/src/__tests__/dataset-tools.test.ts, packages/mcp/src/mcp-dataset-tools.test.ts, packages/runtime/src/mcp-dataset-tools-bridge.test.ts; no live spec opens a keyed MCP session against the datasets" + "ref": "packages/services/service-analytics/src/__tests__/dataset-tools.test.ts, packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts, packages/mcp/src/mcp-dataset-tools.test.ts, packages/mcp/src/list-datasets-candidates-34763.test.ts, packages/runtime/src/mcp-dataset-tools-bridge.test.ts; no live spec opens a keyed MCP session against the datasets" }, "source": [ "docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md D2 and D3", @@ -1242,6 +1249,12 @@ "date": "2026-11-15", "change": "acceptance[7].verify names `--reporter=tree`, the reporter that prints the one line per pin file this is scored on: in a runner's non-TTY shell vitest's default reporter prints the run's totals only (RUNNER.md's environment facts; QA run #33784's note 10, comment 6893243542). No clause or threshold changed. Card #33969", "ref": "#34068" + }, + { + "revision": 3, + "date": "2026-11-17", + "change": "a near-miss step and its clause: list_datasets answers a term that matched nothing with `candidates` (ADR-0149 D3 amendment note), and qa_no_word carries none; the description clause names the candidates row; automated.ref names the candidate pins. Card #34763", + "ref": "#34763" } ] }, diff --git a/packages/mcp/src/list-datasets-candidates-34763.test.ts b/packages/mcp/src/list-datasets-candidates-34763.test.ts new file mode 100644 index 00000000000..2d0a0bec199 --- /dev/null +++ b/packages/mcp/src/list-datasets-candidates-34763.test.ts @@ -0,0 +1,114 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34763, ADR-0149 D3 amendment note] `list_datasets.candidates` reaches an + * MCP client exactly as the executor answered it. + * + * The members offered for a term that matched nothing are chosen by the + * service-analytics executor (`findDatasetTermCandidates`, pinned there); the + * MCP tool layer holds no copy of that rule and must neither drop the key, + * reorder its entries nor add one. Pinned over a fake bridge whose answer is + * a spec-valid `ListDatasetsOutput` carrying `candidates`, and its control: an + * answer without the key comes back without it. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { + LIST_DATASETS_TOOL_NAME, + ListDatasetsOutputSchema, + QUERY_DATASET_TOOL_NAME, + type ListDatasetsOutput, +} from '@objectstack/spec/ai'; +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import type { McpDataBridge } from './mcp-http-tools.js'; + +const WITH_CANDIDATES: ListDatasetsOutput = { + datasets: [ + { + name: 'showcase_invoice_metrics', + label: 'Invoice Metrics', + object: 'showcase_invoice', + dimensions: [{ name: 'status', label: 'Status', type: 'string' }], + measures: [ + { name: 'invoice_count', label: 'Invoices', aggregate: 'count' }, + { name: 'paid_count', label: 'Paid Invoices', aggregate: 'count' }, + ], + matches: [], + }, + ], + candidates: [ + { term: 'invoice', dataset: 'showcase_invoice_metrics', member: 'measures.invoice_count' }, + { term: 'invoice', dataset: 'showcase_invoice_metrics', member: 'measures.paid_count' }, + ], +}; + +const WITHOUT_CANDIDATES: ListDatasetsOutput = { + datasets: [{ ...WITH_CANDIDATES.datasets[0], matches: [{ term: 'invoices', member: 'measures.invoice_count', matchedOn: 'label' }] }], +}; + +function bridgeAnswering(answer: ListDatasetsOutput): McpDataBridge & { inputs: unknown[] } { + const inputs: unknown[] = []; + return { + inputs, + async listObjects() { return []; }, + async describeObject() { return null; }, + async query() { return { records: [] }; }, + async get() { return null; }, + async create() { return {}; }, + async update() { return {}; }, + async remove() { return {}; }, + async listDatasets(input) { + inputs.push(input); + return answer; + }, + async queryDataset() { return { rows: [], fields: [], rowCount: 0, truncated: false } as never; }, + datasetToolDefinitions() { + return [ + { name: LIST_DATASETS_TOOL_NAME, description: 'list the governed datasets' }, + { name: QUERY_DATASET_TOOL_NAME, description: 'compute a governed metric' }, + ]; + }, + }; +} + +async function callListDatasets(runtime: MCPServerRuntime, bridge: McpDataBridge, args: Record) { + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: LIST_DATASETS_TOOL_NAME, arguments: args } }; + const res = await runtime.handleHttpRequest( + new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }), + { bridge, parsedBody: body }, + ); + expect(res.status).toBe(200); + const json = (await res.json()) as { result?: { content: Array<{ type: string; text: string }>; isError?: boolean } }; + expect(json.result?.isError).toBeFalsy(); + return JSON.parse(json.result!.content[0].text) as ListDatasetsOutput; +} + +describe('[#34763] list_datasets candidates over MCP', () => { + let runtime: MCPServerRuntime; + beforeEach(() => { + runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + }); + + it('the fixtures are answers the spec accepts', () => { + expect(ListDatasetsOutputSchema.safeParse(WITH_CANDIDATES).success).toBe(true); + expect(ListDatasetsOutputSchema.safeParse(WITHOUT_CANDIDATES).success).toBe(true); + }); + + it('passes the executor\'s candidates through unchanged: same entries, same order, nothing added', async () => { + const bridge = bridgeAnswering(WITH_CANDIDATES); + const answer = await callListDatasets(runtime, bridge, { terms: ['invoice'] }); + expect(answer).toEqual(WITH_CANDIDATES); + expect(answer.candidates).toEqual(WITH_CANDIDATES.candidates); + expect(bridge.inputs).toEqual([{ terms: ['invoice'] }]); + }); + + it('an answer without candidates comes back without the key', async () => { + const answer = await callListDatasets(runtime, bridgeAnswering(WITHOUT_CANDIDATES), { terms: ['invoices'] }); + expect(answer).toEqual(WITHOUT_CANDIDATES); + expect('candidates' in answer).toBe(false); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts b/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts index 3800c57ec96..deee6f764f1 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts @@ -7,8 +7,9 @@ */ import { describe, it, expect } from 'vitest'; +import { LIST_DATASETS_MAX_CANDIDATES_PER_TERM } from '@objectstack/spec/ai'; import { normalizeDatasetTerm } from '@objectstack/spec/ui'; -import { matchDatasetTerms } from '../dataset-term-matcher.js'; +import { findDatasetTermCandidates, matchDatasetTerms } from '../dataset-term-matcher.js'; const members = { dimensions: [ @@ -66,3 +67,103 @@ describe('matchDatasetTerms', () => { expect(matchDatasetTerms(['营收'], { dimensions: [], measures: [] })).toEqual([]); }); }); + +/** + * [#34763, ADR-0149 D3 amendment note] `list_datasets.candidates`: the + * members offered for a term with no hit anywhere. Near is containment either + * way after the same normalization, both sides at least two code points; the + * order is the listing order and the cap is the spec's. + */ +describe('findDatasetTermCandidates', () => { + const contracts = { + name: 'contracts', + dimensions: [{ name: 'contract_type', label: '合同类型' }], + measures: [{ name: 'contract_amount', label: { en: 'Contract amount', 'zh-CN': '合同金额' } }], + }; + const payments = { + name: 'payments', + dimensions: [], + measures: [{ name: 'paid', label: '金额', synonyms: ['回款'] }], + }; + + it('offers a member a target of which contains the term, and one the term contains', () => { + expect(findDatasetTermCandidates(['金额'], [contracts])).toEqual([ + { term: '金额', dataset: 'contracts', member: 'measures.contract_amount' }, + ]); + expect(findDatasetTermCandidates(['合同金额'], [payments])).toEqual([ + { term: '合同金额', dataset: 'payments', member: 'measures.paid' }, + ]); + // A name, a label in any locale and a synonym are all targets, after normalization. + expect(findDatasetTermCandidates(['CONTRACT-AMOUNTS', '回款额'], [contracts, payments])).toEqual([ + { term: 'CONTRACT-AMOUNTS', dataset: 'contracts', member: 'measures.contract_amount' }, + { term: '回款额', dataset: 'payments', member: 'measures.paid' }, + ]); + }); + + it('holds both sides to two code points', () => { + const tiny = { name: 'tiny', dimensions: [], measures: [{ name: 'xx', label: '额', synonyms: ['金'] }] }; + // A one-code-point term is in too many words to offer any of them. + expect(findDatasetTermCandidates(['额', '金'], [contracts, tiny])).toEqual([]); + // A one-code-point target is never offered, though the term contains it. + expect(findDatasetTermCandidates(['金额'], [tiny])).toEqual([]); + // Two code points on each side are enough. + expect(findDatasetTermCandidates(['xx总'], [tiny])).toEqual([ + { term: 'xx总', dataset: 'tiny', member: 'measures.xx' }, + ]); + }); + + it('offers nothing for a term with a hit in ANY dataset, and still offers for the other terms', () => { + // `金额` equals `payments.paid`'s label: a hit, so `contracts` offers nothing for it. + expect(findDatasetTermCandidates(['金额', '合同'], [contracts, payments])).toEqual([ + { term: '合同', dataset: 'contracts', member: 'measures.contract_amount' }, + { term: '合同', dataset: 'contracts', member: 'dimensions.contract_type' }, + ]); + expect(matchDatasetTerms(['金额'], payments)).toHaveLength(1); + }); + + it('lists terms as sent, datasets as given, a dataset\'s measures before its dimensions', () => { + const first = { + name: 'first', + // Declared first, listed after the measure. + dimensions: [{ name: 'region_amount_band', label: 'Amount band' }], + measures: [{ name: 'won_amount', label: 'Won amount' }], + }; + const second = { name: 'second', dimensions: [], measures: [{ name: 'lost_amount', label: 'Lost amount' }] }; + expect(findDatasetTermCandidates(['lost', 'amount'], [first, second])).toEqual([ + { term: 'lost', dataset: 'second', member: 'measures.lost_amount' }, + { term: 'amount', dataset: 'first', member: 'measures.won_amount' }, + { term: 'amount', dataset: 'first', member: 'dimensions.region_amount_band' }, + { term: 'amount', dataset: 'second', member: 'measures.lost_amount' }, + ]); + }); + + it(`offers at most ${LIST_DATASETS_MAX_CANDIDATES_PER_TERM} per term, the first in listing order, with no cut marker`, () => { + const many = (name: string, n: number) => ({ + name, + dimensions: [{ name: `${name}_amount_band`, label: 'Amount band' }], + measures: Array.from({ length: n }, (_, i) => ({ name: `${name}_amount_${i}`, label: `M${i}` })), + }); + const out = findDatasetTermCandidates(['amount', 'band'], [many('a', 4), many('b', 4)]); + expect(LIST_DATASETS_MAX_CANDIDATES_PER_TERM).toBe(5); + expect(out.filter((c) => c.term === 'amount')).toEqual([ + { term: 'amount', dataset: 'a', member: 'measures.a_amount_0' }, + { term: 'amount', dataset: 'a', member: 'measures.a_amount_1' }, + { term: 'amount', dataset: 'a', member: 'measures.a_amount_2' }, + { term: 'amount', dataset: 'a', member: 'measures.a_amount_3' }, + { term: 'amount', dataset: 'a', member: 'dimensions.a_amount_band' }, + ]); + // The cap is per term: the next term starts its own count. + expect(out.filter((c) => c.term === 'band').map((c) => c.member)).toEqual([ + 'dimensions.a_amount_band', + 'dimensions.b_amount_band', + ]); + // Every entry is the bare pointer: nothing says more were left out. + for (const c of out) expect(Object.keys(c).sort()).toEqual(['dataset', 'member', 'term']); + }); + + it('offers a term sent twice once, and nothing for a term that normalizes to nothing or with no datasets', () => { + expect(findDatasetTermCandidates(['合同', '合同'], [payments, contracts])).toHaveLength(2); + expect(findDatasetTermCandidates(['', ' ', '__'], [contracts])).toEqual([]); + expect(findDatasetTermCandidates(['合同'], [])).toEqual([]); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index 0b9311c0082..f0d76468397 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -21,7 +21,7 @@ */ import { describe, it, expect, vi } from 'vitest'; -import { getDatasetToolJsonSchemas } from '@objectstack/spec/ai'; +import { ListDatasetsOutputSchema, getDatasetToolJsonSchemas } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { AnalyticsServicePlugin } from '../plugin.js'; import { AnalyticsService } from '../analytics-service.js'; @@ -764,3 +764,66 @@ describe('[#32072] query_dataset resolves the dataset by package (ADR-0150 D3)', expect(spy).not.toHaveBeenCalled(); }); }); + +describe('[#34763] list_datasets candidates — only what this caller may read, never beside a match', () => { + /** Every candidate names a dataset the same answer lists and a member that entry lists. */ + function expectResolvable(out: Awaited['listDatasets']>>) { + for (const c of out.candidates ?? []) { + const entry = out.datasets.find((d) => d.name === c.dataset); + expect(entry, `${c.dataset} is listed`).toBeDefined(); + const [kind, name] = c.member.split('.') as ['measures' | 'dimensions', string]; + expect(entry![kind].map((m) => m.name), `${c.member} is listed in ${c.dataset}`).toContain(name); + } + expect(ListDatasetsOutputSchema.safeParse(out).success).toBe(true); + } + + const TERMS = ['rev', '营收', 'secret', 'rate', 'tot', 'marg']; + + it('offers the readable near member for a term that matched nothing, and nothing for a term that matched', async () => { + const { service } = await bootWired(); + const out = await service.datasetTools({ loadDatasets: loadSaved }).listDatasets({ terms: TERMS }, ME); + // `secret` (an internal-field member), `rate` and `marg` (members over the + // unreadable `margin`) and `tot` (a measure of locked_ds, which u_me may + // not query, and of closed_ds, which is not API-exposed) offer nothing. + expect(out.candidates).toEqual([{ term: 'rev', dataset: 'pipeline', member: 'measures.revenue' }]); + expect(out.datasets[0].matches).toEqual([{ term: '营收', member: 'measures.revenue', matchedOn: 'label' }]); + expectResolvable(out); + }); + + it('a caller who reads more is offered more, from the same rule; an unexposed dataset is offered to nobody', async () => { + const { service } = await bootWired(); + const out = await service.datasetTools({ loadDatasets: loadSaved }).listDatasets({ terms: TERMS }, ADMIN); + expect(out.candidates).toEqual([ + { term: 'rev', dataset: 'pipeline', member: 'measures.revenue' }, + { term: 'rate', dataset: 'pipeline', member: 'measures.margin_rate' }, + // `margin_total` folds to "margin total", which contains `tot`; datasets in listing order. + { term: 'tot', dataset: 'pipeline', member: 'measures.margin_total' }, + { term: 'tot', dataset: 'locked_ds', member: 'measures.total' }, + { term: 'marg', dataset: 'pipeline', member: 'measures.margin_total' }, + { term: 'marg', dataset: 'pipeline', member: 'measures.margin_rate' }, + ]); + expect(out.candidates!.some((c) => c.dataset === 'closed_ds' || c.member === 'measures.secret_sum')).toBe(false); + expectResolvable(out); + }); + + it('a term with a match anywhere in the answer has no candidate, though a member is near it', async () => { + const { service } = await bootWired(); + const tools = service.datasetTools({ loadDatasets: loadSaved }); + // `margin` equals margin_total's label; margin_rate ("Margin rate") contains it and is not offered. + const matched = await tools.listDatasets({ terms: ['margin'] }, ADMIN); + expect(matched.datasets[0].matches).toEqual([{ term: 'margin', member: 'measures.margin_total', matchedOn: 'label' }]); + expect('candidates' in matched).toBe(false); + // The control: the near form alone is offered both members. + const near = await tools.listDatasets({ terms: ['marg'] }, ADMIN); + expect(near.candidates?.map((c) => c.member)).toEqual(['measures.margin_total', 'measures.margin_rate']); + }); + + it('omits the key when nothing is offered: no terms, every term matched, or nothing readable is near', async () => { + const { service } = await bootWired(); + const tools = service.datasetTools({ loadDatasets: loadSaved }); + for (const input of [{}, { terms: ['营收', 'phase'] }, { terms: ['secret', 'rate', 'tot', 'qa_no_word'] }]) { + const out = await tools.listDatasets(input, ME); + expect('candidates' in out, JSON.stringify(input)).toBe(false); + } + }); +}); From 883af46685e88741f55ac36c67cad2c8159dcbd6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:26:42 +0000 Subject: [PATCH 4/4] test(mcp): fold the candidates pass-through pin into the dataset tools harness; the rule's docblock names candidates Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- docs/qa/platform-checklist/areas/ai.json | 2 +- .../list-datasets-candidates-34763.test.ts | 114 ------------------ packages/mcp/src/mcp-dataset-tools.test.ts | 76 +++++++++++- packages/mcp/src/mcp-server-runtime.ts | 12 +- 4 files changed, 85 insertions(+), 119 deletions(-) delete mode 100644 packages/mcp/src/list-datasets-candidates-34763.test.ts diff --git a/docs/qa/platform-checklist/areas/ai.json b/docs/qa/platform-checklist/areas/ai.json index 40e683469db..b298abb1537 100644 --- a/docs/qa/platform-checklist/areas/ai.json +++ b/docs/qa/platform-checklist/areas/ai.json @@ -1226,7 +1226,7 @@ ], "automated": { "kind": "unit", - "ref": "packages/services/service-analytics/src/__tests__/dataset-tools.test.ts, packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts, packages/mcp/src/mcp-dataset-tools.test.ts, packages/mcp/src/list-datasets-candidates-34763.test.ts, packages/runtime/src/mcp-dataset-tools-bridge.test.ts; no live spec opens a keyed MCP session against the datasets" + "ref": "packages/services/service-analytics/src/__tests__/dataset-tools.test.ts, packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts, packages/mcp/src/mcp-dataset-tools.test.ts, packages/runtime/src/mcp-dataset-tools-bridge.test.ts; no live spec opens a keyed MCP session against the datasets" }, "source": [ "docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md D2 and D3", diff --git a/packages/mcp/src/list-datasets-candidates-34763.test.ts b/packages/mcp/src/list-datasets-candidates-34763.test.ts deleted file mode 100644 index 2d0a0bec199..00000000000 --- a/packages/mcp/src/list-datasets-candidates-34763.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [#34763, ADR-0149 D3 amendment note] `list_datasets.candidates` reaches an - * MCP client exactly as the executor answered it. - * - * The members offered for a term that matched nothing are chosen by the - * service-analytics executor (`findDatasetTermCandidates`, pinned there); the - * MCP tool layer holds no copy of that rule and must neither drop the key, - * reorder its entries nor add one. Pinned over a fake bridge whose answer is - * a spec-valid `ListDatasetsOutput` carrying `candidates`, and its control: an - * answer without the key comes back without it. - */ - -import { describe, it, expect, beforeEach } from 'vitest'; -import { - LIST_DATASETS_TOOL_NAME, - ListDatasetsOutputSchema, - QUERY_DATASET_TOOL_NAME, - type ListDatasetsOutput, -} from '@objectstack/spec/ai'; -import { MCPServerRuntime } from './mcp-server-runtime.js'; -import type { McpDataBridge } from './mcp-http-tools.js'; - -const WITH_CANDIDATES: ListDatasetsOutput = { - datasets: [ - { - name: 'showcase_invoice_metrics', - label: 'Invoice Metrics', - object: 'showcase_invoice', - dimensions: [{ name: 'status', label: 'Status', type: 'string' }], - measures: [ - { name: 'invoice_count', label: 'Invoices', aggregate: 'count' }, - { name: 'paid_count', label: 'Paid Invoices', aggregate: 'count' }, - ], - matches: [], - }, - ], - candidates: [ - { term: 'invoice', dataset: 'showcase_invoice_metrics', member: 'measures.invoice_count' }, - { term: 'invoice', dataset: 'showcase_invoice_metrics', member: 'measures.paid_count' }, - ], -}; - -const WITHOUT_CANDIDATES: ListDatasetsOutput = { - datasets: [{ ...WITH_CANDIDATES.datasets[0], matches: [{ term: 'invoices', member: 'measures.invoice_count', matchedOn: 'label' }] }], -}; - -function bridgeAnswering(answer: ListDatasetsOutput): McpDataBridge & { inputs: unknown[] } { - const inputs: unknown[] = []; - return { - inputs, - async listObjects() { return []; }, - async describeObject() { return null; }, - async query() { return { records: [] }; }, - async get() { return null; }, - async create() { return {}; }, - async update() { return {}; }, - async remove() { return {}; }, - async listDatasets(input) { - inputs.push(input); - return answer; - }, - async queryDataset() { return { rows: [], fields: [], rowCount: 0, truncated: false } as never; }, - datasetToolDefinitions() { - return [ - { name: LIST_DATASETS_TOOL_NAME, description: 'list the governed datasets' }, - { name: QUERY_DATASET_TOOL_NAME, description: 'compute a governed metric' }, - ]; - }, - }; -} - -async function callListDatasets(runtime: MCPServerRuntime, bridge: McpDataBridge, args: Record) { - const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: LIST_DATASETS_TOOL_NAME, arguments: args } }; - const res = await runtime.handleHttpRequest( - new Request('http://localhost/api/v1/mcp', { - method: 'POST', - headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, - body: JSON.stringify(body), - }), - { bridge, parsedBody: body }, - ); - expect(res.status).toBe(200); - const json = (await res.json()) as { result?: { content: Array<{ type: string; text: string }>; isError?: boolean } }; - expect(json.result?.isError).toBeFalsy(); - return JSON.parse(json.result!.content[0].text) as ListDatasetsOutput; -} - -describe('[#34763] list_datasets candidates over MCP', () => { - let runtime: MCPServerRuntime; - beforeEach(() => { - runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); - }); - - it('the fixtures are answers the spec accepts', () => { - expect(ListDatasetsOutputSchema.safeParse(WITH_CANDIDATES).success).toBe(true); - expect(ListDatasetsOutputSchema.safeParse(WITHOUT_CANDIDATES).success).toBe(true); - }); - - it('passes the executor\'s candidates through unchanged: same entries, same order, nothing added', async () => { - const bridge = bridgeAnswering(WITH_CANDIDATES); - const answer = await callListDatasets(runtime, bridge, { terms: ['invoice'] }); - expect(answer).toEqual(WITH_CANDIDATES); - expect(answer.candidates).toEqual(WITH_CANDIDATES.candidates); - expect(bridge.inputs).toEqual([{ terms: ['invoice'] }]); - }); - - it('an answer without candidates comes back without the key', async () => { - const answer = await callListDatasets(runtime, bridgeAnswering(WITHOUT_CANDIDATES), { terms: ['invoices'] }); - expect(answer).toEqual(WITHOUT_CANDIDATES); - expect('candidates' in answer).toBe(false); - }); -}); diff --git a/packages/mcp/src/mcp-dataset-tools.test.ts b/packages/mcp/src/mcp-dataset-tools.test.ts index 83b1c21a62e..63a7fc8a77a 100644 --- a/packages/mcp/src/mcp-dataset-tools.test.ts +++ b/packages/mcp/src/mcp-dataset-tools.test.ts @@ -10,12 +10,14 @@ * bridge's definitions carry, never a copy in this package; the arguments reach * 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. + * throws comes back as the coded tool error; `list_datasets.candidates` comes + * back exactly as the executor answered it (#34763). */ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { LIST_DATASETS_TOOL_NAME, + ListDatasetsOutputSchema, MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE, QUERY_DATASET_TOOL_NAME, @@ -369,3 +371,75 @@ describe('[ADR-0149 D2] dataset tools on MCP — the spec refusal is kept whole' expect(bridge.calls.filter((c) => c[0] === 'listDatasets')).toEqual([]); }); }); + +/** + * [#34763, ADR-0149 D3 amendment note] `list_datasets.candidates` reaches an + * MCP client exactly as the executor answered it. The members offered for a + * term that matched nothing are chosen by the service-analytics executor + * (`findDatasetTermCandidates`, pinned there); the MCP tool layer holds no copy + * of that rule and must neither drop the key, reorder its entries nor add one. + */ +describe('[#34763] list_datasets candidates pass through MCP unchanged', () => { + const WITH_CANDIDATES: ListDatasetsOutput = { + datasets: [ + { + name: 'showcase_invoice_metrics', + label: 'Invoice Metrics', + object: 'showcase_invoice', + dimensions: [{ name: 'status', label: 'Status', type: 'string' }], + measures: [ + { name: 'invoice_count', label: 'Invoices', aggregate: 'count' }, + { name: 'paid_count', label: 'Paid Invoices', aggregate: 'count' }, + ], + matches: [], + }, + ], + candidates: [ + { term: 'invoice', dataset: 'showcase_invoice_metrics', member: 'measures.invoice_count' }, + { term: 'invoice', dataset: 'showcase_invoice_metrics', member: 'measures.paid_count' }, + ], + }; + const WITHOUT_CANDIDATES: ListDatasetsOutput = { + datasets: [{ + ...WITH_CANDIDATES.datasets[0], + matches: [{ term: 'invoices', member: 'measures.invoice_count', matchedOn: 'label' }], + }], + }; + + function bridgeAnswering(answer: ListDatasetsOutput) { + const bridge = makeBridge(); + bridge.listDatasets = async (input) => { + bridge.calls.push(['listDatasets', input]); + return answer; + }; + return bridge; + } + + let runtime: MCPServerRuntime; + beforeEach(() => { + runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + }); + + it('the fixtures are answers the spec accepts', () => { + expect(ListDatasetsOutputSchema.safeParse(WITH_CANDIDATES).success).toBe(true); + expect(ListDatasetsOutputSchema.safeParse(WITHOUT_CANDIDATES).success).toBe(true); + }); + + it('passes the executor\'s candidates through unchanged: same entries, same order, nothing added', async () => { + const bridge = bridgeAnswering(WITH_CANDIDATES); + const json = await callTool(runtime, bridge, LIST_DATASETS_TOOL_NAME, { terms: ['invoice'] }); + expect(json.result?.isError).toBeFalsy(); + const answer = JSON.parse(json.result!.content[0].text) as ListDatasetsOutput; + expect(answer).toEqual(WITH_CANDIDATES); + expect(answer.candidates).toEqual(WITH_CANDIDATES.candidates); + expect(bridge.calls.filter((c) => c[0] === 'listDatasets')).toEqual([['listDatasets', { terms: ['invoice'] }]]); + }); + + it('an answer without candidates comes back without the key', async () => { + const json = await callTool(runtime, bridgeAnswering(WITHOUT_CANDIDATES), LIST_DATASETS_TOOL_NAME, { terms: ['invoices'] }); + expect(json.result?.isError).toBeFalsy(); + const answer = JSON.parse(json.result!.content[0].text) as ListDatasetsOutput; + expect(answer).toEqual(WITHOUT_CANDIDATES); + expect('candidates' in answer).toBe(false); + }); +}); diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index f9fd8ac4095..c11a91bff90 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1805,9 +1805,15 @@ const DEFAULT_HTTP_INSTRUCTIONS = * tools' own descriptions and in the served skill's data loop * (`ASK_SKILL_DATA_LOOP`, generated from `skills/objectstack-ask/SKILL.md` and * rendered by `skill-md.ts`). All three hold an exact name, label or synonym as - * the only match, one measure match as the answer, and several matches on one - * word as a question for the user; the skill also asks before it falls back - * when a word with no match is a loose form of several listed measures. + * the only match, one measure match as the answer (two words with one measure + * match each are two metrics, both computed), and several matches on one word + * as a question for the user. [#34763] A word with no match may come back with + * `list_datasets` `candidates` (the ADR-0149 D3 amendment note): the rule makes + * 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. * Sent only where both dataset tools register ({@link datasetToolsServed}). */ const DATASET_SELECTION_RULE =