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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/34686-skill-single-source.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/mcp': patch
---

fix(mcp): the data loop on `GET /mcp/skill` is the published `objectstack-ask` skill's text

Clause-②: no
Metadata-protocol: none

The page an open server serves at `GET /mcp/skill` taught the governed-metric procedure in its own hand-written words, and those words had drifted from the published `objectstack-ask` skill. The page now carries the skill's own steps, generated from `skills/objectstack-ask/SKILL.md` into the package, under a new section **Answering a business question**. A test fails when the two differ.

What a connected client now reads on that page, where it reads differently from before:

- Each word for a thing measured is decided on its own: two words with one measure each are two metrics, computed both, not a question for the user. One word that matches several measures is still a question.
- A word with no match that is a loose form of several listed measures (a bare "revenue" beside Won Revenue, Annual Revenue and Planned Revenue) is a question too, with nothing computed yet. One near form selects nothing.
- `membersWithheld: true` is reported as members (measures or groupings) the user may not read, and the metric asked for may be among them.
- The fallback to object queries reads the object's fields first, uses `aggregate_records` rather than adding pages up, opens with a line saying the answer is not from a governed metric, and names a listed dataset on that object when there is one.
- The answer is written in the user's language, with labels rather than machine names, and states its filter and time window.

The two dataset tool entries in the page's tool list now give only each tool's signature and what its answer carries. The section renders where it did before and nowhere else: only when the host carries the dataset tools and the grant has `data:read` (or names no scopes). Pages for other hosts and grants are byte-identical to before.
93 changes: 93 additions & 0 deletions packages/mcp/src/ask-skill.generated.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

// GENERATED by scripts/gen-mcp-ask-skill.mjs from skills/objectstack-ask/SKILL.md.
// Do not edit this file: change the skill, then run `node scripts/gen-mcp-ask-skill.mjs`.

/**
* The ask-data skill's data loop: its body after the title, served under its
* own heading by `renderSkillMarkdown` (`skill-md.ts`) where the dataset tools
* register for the grant. One source: the published skill.
*/
export const ASK_SKILL_DATA_LOOP: string = [
'You are connected to a live environment through its MCP tools, and the user',
'asked for a figure or a list from its data. Work these steps in order for every',
'question. Never skip step 1: a governed metric (a dataset measure whose owner',
'wrote its business definition) outranks a number you work out yourself.',
'',
'## 1. Lift the business words and look for a governed metric',
'',
'- Lift the question\'s business words: the thing measured ("win rate", "营收",',
' "商机数") and what it is grouped or filtered by ("by stage", "按行业").',
'- Call `list_datasets({ terms })` with those words, as the user wrote them and',
' in the user\'s language. Do not translate or reword a term: a match on a word',
' you supplied is your reading, not the user\'s.',
'- Each dataset in the answer carries `matches`: one entry per hit, with the',
' `term`, the `member` it names (`measures.<name>` or `dimensions.<name>`) and',
' `matchedOn`. A word matches only when it equals a member\'s name, label or',
' synonym (case, spacing, `_` and `-` aside), never by similarity.',
'- No `list_datasets` among your tools: this environment serves you no governed',
' metrics. Go to step 4.',
'',
'## 2. Decide by the matches',
'',
'| What the answer shows | What you do |',
'|:--|:--|',
'| Each word for a thing measured matches exactly one measure | Compute: step 3. Two words with one measure each ("营收和赢单率") are two metrics, not a choice: compute both, with one `query_dataset` per dataset. |',
'| One word matches several measures, in one dataset or in two | Ask the user which one they mean. List each candidate\'s label, its dataset\'s label and its description. Do not pick one. |',
'| Only a dimension matches | That is a grouping ("by stage"), not a number. You still need a measure match; without one, ask which number is meant. |',
'| Nothing matches, and the word is a loose form of several listed measures | Ask the user which one they mean, listing the same three things. Do not pick one, and compute nothing yet. |',
'| Nothing matches, and the listed measures do not offer several readings of the word | Step 4, and say in the answer that no governed metric was used. One near form is not a match either: it selects nothing. |',
'| `membersWithheld: true` on a dataset | Say that it has members (measures or groupings) you may not read; the metric asked for may be among them. Do not say the metric does not exist. |',
'',
'The same answer lists every dataset you may query with all its measures,',
'matched or not (a call without `terms` returns that catalogue too), so the',
'loose-form check needs no second read. A loose form is a word a listed',
'measure\'s name, label or description contains, directly or in translation:',
'"revenue" against Won Revenue, Annual Revenue and Planned Revenue; "金额"',
'against several amounts.',
'',
'When you ask, the reply is the question alone: no figure, and no tool call',
'until the user answers. `partial: true` on the answer means the catalogue may',
'be incomplete; `warning` says why, and you repeat it when you fall back.',
'',
'## 3. Compute a governed metric',
'',
'- `query_dataset({ datasetName, selection })`. `selection.measures` and',
' `selection.dimensions` take the names `list_datasets` gave;',
' `selection.runtimeFilter` filters; `selection.dateGranularity` buckets a date',
' dimension for a trend; `selection.order` and `selection.limit` rank.',
'- Cite the source from the answer\'s `provenance` (the dataset\'s label and each',
' measure\'s label, as in 「指标:营收(数据集:销售分析)」), not from memory.',
'- Use the measure\'s `description` to say what the number includes and excludes.',
'- `truncated: true`: more rows existed than came back. Say the result is',
' partial. A `warning` on the answer narrows what you were allowed to read:',
' repeat it.',
'',
'## 4. Fallback: object queries',
'',
'- `list_objects`, then `describe_object({ objectName })` on the object you will',
' read. Read its fields before you filter: a field with `options` is filtered',
' by the option\'s `value`, never its label.',
'- Use `aggregate_records` for a count, sum, average or breakdown. Never page',
' through `query_records` to add numbers up yourself. `truncated: true` on its',
' answer means groups were cut off: say so.',
'- Open the answer with one line saying it is not from a governed metric',
' (非指标口径), and name the object and fields you computed it from.',
'- When that object is a listed dataset\'s `object`, add one line naming the',
' dataset and its measures, so the user can ask for the governed figure.',
'',
'## 5. When the data cannot answer',
'',
'- No metric, object or field records what the question needs: say the data you',
' can read does not record it, name what is missing (such as a shipment\'s',
' weight), and offer the computation if the user supplies it.',
'- Never fill the gap with an assumed value, and never draw a conclusion from',
' one.',
'',
'## 6. Writing the answer',
'',
'- Answer in the user\'s language.',
'- Show labels, not machine names or raw option values.',
'- Every figure comes from a tool answer in this conversation.',
'- State the filter and the time window you used, in words.',
].join('\n');
25 changes: 12 additions & 13 deletions packages/mcp/src/mcp-dataset-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { RETIRED_KEY_UPGRADE_GUIDE_SENTENCE } from '@objectstack/spec/shared';
import { MCPServerRuntime } from './mcp-server-runtime.js';
import { hasDatasetTools, type McpDataBridge } from './mcp-http-tools.js';
import { createStdioDataBridge, type StdioDatasetToolsService } from './stdio-data-bridge.js';
import { renderSkillMarkdown } from './skill-md.js';
import { ASK_SECTION_HEADING, renderSkillMarkdown } from './skill-md.js';

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

Expand Down Expand Up @@ -273,23 +273,22 @@ describe('[ADR-0149 D2] dataset tools on MCP — calls', () => {
});

describe('[ADR-0149 D3] the SKILL.md teaches the selection rule where the pair registers', () => {
it('renders both tools and the rule for a host whose bridge carries them', () => {
it('renders both tools and the ask-data data loop for a host whose bridge carries them', () => {
const md = renderSkillMarkdown({ datasetTools: true });
for (const name of DATASET_TOOLS) expect(md).toContain(`**${name}(`);
expect(md).toContain('Choosing between a metric and an object query');
expect(md).toContain(`\n${ASK_SECTION_HEADING}\n`);
});

it('renders the rule for a question the data cannot answer beside the selection rule', () => {
// [#34686] The data loop's words (the selection rule, the fallback, and a
// question the data cannot answer) are the published ask-data skill's, and
// skill-single-source-34686.test.ts pins the served section byte-equal to
// it. What stays here is where the section sits and when it is absent.
it('renders the data loop after the tool entries, and not without the pair', () => {
const md = renderSkillMarkdown({ datasetTools: true });
const rule = md.indexOf('**When the data cannot answer.**');
expect(rule).toBeGreaterThan(md.indexOf('Choosing between a metric and an object query'));
const text = md.slice(rule, md.indexOf('\n- ', rule) === -1 ? undefined : md.indexOf('\n- ', rule));
expect(text).toContain('say the data you can read does not record it');
expect(text).toContain('offer the computation');
expect(text).toContain('Never fill the gap with an assumed value');
expect(text).toContain('nor draw a conclusion from one');
expect(text).toContain('Any figure you add comes from a tool answer; cite it.');
expect(renderSkillMarkdown({})).not.toContain('When the data cannot answer');
const section = md.indexOf(`\n${ASK_SECTION_HEADING}\n`);
expect(section).toBeGreaterThan(md.indexOf('**query_dataset('));
expect(section).toBeLessThan(md.indexOf('\n## Conventions & gotchas'));
expect(renderSkillMarkdown({})).not.toContain(ASK_SECTION_HEADING);
});

it('renders them for a data:read grant, and not without one or without the pair', () => {
Expand Down
10 changes: 6 additions & 4 deletions packages/mcp/src/mcp-server-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1802,10 +1802,12 @@ const DEFAULT_HTTP_INSTRUCTIONS =
* (ADR-0149 D3), in the few lines `initialize` carries. It rides the
* instructions because a client reads a tool's description only after it has
* 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.
* 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.
* Sent only where both dataset tools register ({@link datasetToolsServed}).
*/
const DATASET_SELECTION_RULE =
Expand Down
85 changes: 46 additions & 39 deletions packages/mcp/src/skill-md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

import type { AIToolDefinition } from '@objectstack/spec/contracts';
import { MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE, MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai';
import { ASK_SKILL_DATA_LOOP } from './ask-skill.generated.js';
import {
DELETE_AMBIGUOUS_ASKS_FIRST,
DELETE_NAMED_RECORD_IS_APPROVAL,
Expand Down Expand Up @@ -125,7 +126,8 @@ export interface RenderSkillOptions {
/**
* [ADR-0149 D2] Whether the host's bridge carries the dataset pair
* (`list_datasets` / `query_dataset`, `registerDatasetTools`). The entries,
* and the D3 selection rule that teaches a client when to use them, render
* and the ask-data skill's data loop that teaches a client when to use them
* (#34686: generated from the published skill), render
* only when this is true AND {@link grantedScopes} admit `data:read`, so the
* skill names them exactly where `tools/list` lists them. Default false: the
* renderer cannot see the bridge, so the host says so.
Expand Down Expand Up @@ -253,50 +255,55 @@ const NEW_RECORD_UPLOAD_LINK_LINES = ` For a record you have not created yet (a
`;

/**
* [ADR-0149 D2/D3] The dataset pair's entries and the selection rule that
* tells a client when a governed metric answers instead of an object query.
* The rule is ADR-0149 D3's, in the client's terms: an exact word match
* (after normalization) is the only hit, one hit wins, several hits are a
* question for the user, no hit falls back to the object tools with the
* answer labelled as not a governed metric, and a dimension alone is not an
* answer. The last entry covers a question no tool can answer: name what the
* data lacks, never answer from an assumed value.
* [ADR-0149 D2] The dataset pair's entries in the tool list: each tool's
* signature and what its answer carries, in a sentence. When to call them and
* how to read their answers (ADR-0149 D3's selection rule, the fallback, and a
* question the data cannot answer) is {@link ASK_SECTION_HEADING}'s section,
* which the published skill writes.
*/
const DATASET_TOOL_LINES = `- **list_datasets({ terms? })** — the governed datasets (business metrics)
you may query: each dataset's measures and dimensions with their business
labels, descriptions and synonyms. Pass the business words of the question
as \`terms\`; the answer's \`matches\` says which member each word names
exactly. \`membersWithheld: true\` means some measures exist that you may not
read: say so rather than saying the metric does not exist.
- **query_dataset({ datasetName, selection })** — compute a governed metric:
\`selection\` takes \`measures\`, \`dimensions\` and a \`runtimeFilter\`, by
the names \`list_datasets\` gives. The answer carries \`provenance\` (the
dataset and measures used); cite the source from it, not from memory, and
use a measure's \`description\` to explain what the number includes.
- **Choosing between a metric and an object query.** Call \`list_datasets\`
with the question's business words first. A word matches only when it
equals a member's name, label or synonym (case, spacing, \`_\` and \`-\`
aside), never by similarity. One measure match: answer with
\`query_dataset\`. Several matches (two datasets or two members): ask the
user which one they mean, listing each candidate's label, dataset and
description; do not pick. No match: fall back to \`query_records\` /
\`aggregate_records\` and say the answer is not from a governed metric. A
dimension match alone (a grouping such as "by stage") is not an answer: you
still need a measure match, or ask.
- **When the data cannot answer.** No metric, object or field records what the
question needs: say the data you can read does not record it and name what
is missing (such as a shipment's weight), and offer the computation if the
user supplies it. Never fill the gap with an assumed value,
nor draw a conclusion from one ("under a typical term, none would…").
Any figure you add comes from a tool answer; cite it.
labels, descriptions and synonyms, and, for the \`terms\` you pass, the
\`matches\` each word made.
- **query_dataset({ datasetName, selection })** — compute a governed metric
by the names \`list_datasets\` gives; the answer carries \`provenance\`.
When to call these two, and how to read their answers: the section
**Answering a business question** below.
`;

/** The dataset pair's entries for a host whose bridge carries them, under the grant that registers them. */
function renderDatasetToolLines(options: RenderSkillOptions): string {
if (options.datasetTools !== true) return '';
/**
* [#34686] The heading the served page gives the ask-data skill's data loop.
* The text under it is {@link ASK_SKILL_DATA_LOOP}, generated from
* `skills/objectstack-ask/SKILL.md` (`scripts/gen-mcp-ask-skill.mjs`) and pinned
* equal to it by `skill-single-source-34686.test.ts`: the published skill is
* the one source, and nothing here restates it.
*/
export const ASK_SECTION_HEADING = '## Answering a business question';

/**
* Whether this render teaches the dataset pair: a host whose bridge carries
* them, under a grant that registers them.
*/
function datasetToolsTaught(options: RenderSkillOptions): boolean {
if (options.datasetTools !== true) return false;
// Mirrors the gate in `registerDatasetTools` (`!scopes || scopes.includes(data:read)`).
const scopes = options.grantedScopes;
return !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ) ? DATASET_TOOL_LINES : '';
return !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ);
}

/** The dataset pair's entries in the tool list, where {@link datasetToolsTaught}. */
function renderDatasetToolLines(options: RenderSkillOptions): string {
return datasetToolsTaught(options) ? DATASET_TOOL_LINES : '';
}

/**
* [#34686] The ask-data skill's data loop under its own heading, where
* {@link datasetToolsTaught}. It renders after every other block of the tool
* list and before the conventions, so a render that does not teach the pair is
* byte-identical to one from before this section existed.
*/
function renderAskSection(options: RenderSkillOptions): string {
return datasetToolsTaught(options) ? `\n${ASK_SECTION_HEADING}\n\n${ASK_SKILL_DATA_LOOP}\n` : '';
}

/** The file pair's entries for a host whose bridge carries them, each for the grant that registers it. */
Expand Down Expand Up @@ -522,7 +529,7 @@ create/update payload.
(the person's confirmation, in your client or in the app, for an action its
author declared \`requiresConfirmation\`, the refusal of a call that sends \`confirm\`,
and its refusal under an AI service account's own key whatever the call sends).
${renderFileToolLines(options)}${renderDatasetToolLines(options)}${options.federationTools === true && grantsAuthoringTools(options.grantedScopes) ? FEDERATION_TOOL_LINES : ''}${authoringTools ? renderAuthoringSection(authoringTools, describeObjectRegistered) : ''}${dataOnlyBlock}
${renderFileToolLines(options)}${renderDatasetToolLines(options)}${options.federationTools === true && grantsAuthoringTools(options.grantedScopes) ? FEDERATION_TOOL_LINES : ''}${authoringTools ? renderAuthoringSection(authoringTools, describeObjectRegistered) : ''}${dataOnlyBlock}${renderAskSection(options)}
## Conventions & gotchas

- **Permissions/RLS apply to every call.** Fewer rows than expected, or a
Expand Down
Loading
Loading