Skip to content

Commit 34a30e8

Browse files
feat(mcp): serve list_datasets and query_dataset over MCP under data:read (#31773)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9DiJcGW3TmZrvWPuvNopKmm)_ Fixes #31590 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:MCP 新增 `list_datasets` / `query_dataset` 两个只读工具(`data:read` 范围),HTTP 与 stdio 两条桥都接到 service-analytics 的数据集执行器;生成的 SKILL.md 教客户端「先查数据集、精确命中才用指标、多义先问、无命中退回对象查询并注明非指标口径」。 - 为什么改:ADR-0149 D2/D3 —— 外部 AI 客户端与产品内问数用同一套数据集工具、同一口径,答案带出处。 - 风险与回滚:纯新增;没有 analytics 服务(或服务不带 `datasetTools`)的部署工具列表与现在完全一样;不带 `data:read` 的令牌看不到这两个工具。回滚即 revert 本 PR。依赖 #31589 合入后才真正有服务端可调。 - 先看:`packages/mcp/src/mcp-http-tools.ts` 的 `registerDatasetTools`(注册条件与范围门)、`packages/runtime/src/domains/mcp.ts` 的 `datasetToolMembers`(数据集读取、本地化、按调用者身份执行)、`packages/mcp/src/skill-md.ts` 的选择规则文案。 - 两分钟验证:`pnpm --filter @objectstack/mcp exec vitest run src/mcp-dataset-tools.test.ts`,预期 20 个用例全绿。 - 需要你做的:无,席位落地(在 #31589 之后)。 ## What changes - **Bridge members (`packages/mcp/src/mcp-http-tools.ts`).** `McpDataBridge` gains three optional members: `listDatasets(input)`, `queryDataset(input, { maxRows })` and `datasetToolDefinitions()`. The third carries the service-analytics definitions, so this package holds no copy of the tool descriptions (seat ruling 1, the third member accepted by the seat). - **`registerDatasetTools`, called from `wireBridgeTools`.** Registers `list_datasets` / `query_dataset` only when the bridge carries all three members AND the grant admits `data:read` (`grantedScopes` undefined keeps them, as every read tool). Name from the spec constants, description from the bridge's definitions (a tool the definitions do not describe is not registered), input schema = the spec declaration `ListDatasetsInputSchema` / `QueryDatasetInputSchema` taken whole (the precedent: `aggregate_records` takes `AggregationNodeSchema` whole), so an undeclared key is refused before dispatch with the spec's prescription. `query_dataset` hands the tool's page cap (`maxQueryLimit`, default 50, the `query_records` cap) to the bridge. Refusals render through `errorResultWithCode`, the coded envelope the other data tools use. Annotations: read-only, not destructive, closed world. - **HTTP bridge (`packages/runtime/src/domains/mcp.ts`).** `handleMcpRequest` resolves the `analytics` service per request; the bridge carries the three members only when it has `datasetTools` (seat ruling C: `AnalyticsService.datasetTools(deps)` from #31589). The executor is bound to: the saved datasets from the protocol's merged `getMetaItems({ type: 'dataset' })` (the read the REST door resolves `datasetName` from), localized with `translateMetaList` for the request's locale; the request's security service as the narrowing probe; and the tool's page cap. Every call runs as the request's `ExecutionContext`. A throwing dataset read reaches the executor as a throw (its degraded-read answer), never as an empty catalogue. The `/mcp/skill` route renders the dataset section exactly where the bridge would carry the pair. - **stdio bridge (`packages/mcp/src/stdio-data-bridge.ts`, `plugin.ts`).** `createStdioDataBridge` takes an optional `datasetTools` service; the plugin resolves it in `start()` (all services are registered by then, and the tools must be registered before the transport attaches). Datasets come from the protocol's merged read, or the metadata service's `list('dataset')` on a host with none; calls run as the stdio principal, re-resolved per call. - **SKILL.md (`packages/mcp/src/skill-md.ts`).** New `datasetTools` render option (the `fileTools` pattern): the two tool entries and the D3 selection rule render only when the host's bridge carries the pair and the grant admits `data:read`. - Changeset: patch for `@objectstack/mcp` and `@objectstack/runtime`. - Not touched: the existing tool shapes (`run_action` / `list_actions` / `agent_prompt`), E8's by-name readers, `packages/spec/**`, `packages/services/service-analytics/**`, `ui/**`. ## Tests - New `packages/mcp/src/mcp-dataset-tools.test.ts` (20 cases): registration with all three members; descriptions verbatim from the definitions; input schemas closed; each partial-member case (each one of the three missing, and all three) registers neither tool and leaves the rest of the surface unchanged; a definition missing → that tool absent; `data:read` admits both; a `data:write`-only grant registers neither and a call gets the same unknown-tool refusal as `query_records`, with the bridge never asked; argument pass-through and page cap (default and host `maxQueryLimit`); undeclared key refused before the bridge naming `datasetName`; coded refusal envelope; SKILL.md rendering by bridge and grant; the stdio bridge's members (absent without the executor, run as the stdio principal with the cap, merged read and metadata-service fallback). - New `packages/runtime/src/mcp-dataset-tools-bridge.test.ts` (6 cases): the seam is served only by an `analytics` service carrying `datasetTools` (absent service and method-absent cases pinned, as the seat asked); no seam → no members; definitions handed over unchanged; both calls run as the request's principal; page cap and narrowing probe bound; a throwing dataset read stays a throw. - **Forced test edit:** `packages/mcp/src/skill-md-surface-guard.test.ts` — the full-surface bridge gains the three dataset members and the two renders pass `datasetTools: true`, so the drift guard covers the new tools. ## Acceptance notes - **Lands after #31589.** This branch compiles and passes without it (the service face is declared structurally, as `McpRecordFileService` is), but no deployment serves `datasetTools` until #31589 merges; then merge main here. The MCP row of #31589's four-face parity test is #31589's to fill once both are on main. - **stdio datasets are not localized.** The stdio transport has no request locale (an API-key principal), so labels come as authored; the HTTP bridge localizes as the REST door does. - **The stdio bridge passes no narrowing probe**, matching `query_records` on stdio (an API key is not delegated). ## Verification Head `5078be21` (merge of `origin/main` `f65c36fc` into the card commits; that main commit touches `plugin-webhooks` only), measured in a card container. - `@objectstack/mcp` test: Test Files 62 passed (62), Tests 979 passed (979). - `@objectstack/runtime` test: Test Files 564 passed (564), Tests 9065 passed, 19 skipped (9084). - `@objectstack/mcp` and `@objectstack/runtime` typecheck (`tsc --noEmit` + `check:test-typecheck`): exit 0 on `37710911` (later commits: the changeset and the merge, which brought no file of either package). The runtime reading needed `driver-turso` built first: an untouched kernel test imports it. - Lint: `eslint --no-inline-config packages/mcp packages/runtime` exit 0. - Derived gates: 68 derived, 67 run with exit 0, 1 NOT MEASURED (`check:dual-build-cjs-loads`, exit 3: it needs every workspace package built; left to CI). `check-plugin-teardown-shape --self-test` first exited 3 on the shallow clone and is exit 0 after fetching its pinned fixture commit. `dispatch-gates --ran`: 0 UNRUN. <details><summary>Red on main: 12 of 17 registration/call pins fail on the origin/main source</summary> `mcp-http-tools.ts` and `skill-md.ts` restored from `origin/main` `0105a687`, the new test file kept: `Tests 12 failed | 5 passed (17)`. The five that pass are the "no dataset tool" cases, which hold on main by construction. (The three stdio cases were added after this leg.) </details> <details><summary>Ablations: four legs, each red, each restored (scripts/ablation-replace.mjs)</summary> The tests import source directly (no dist leg). Each leg: anchor x1 to x0, marker x0 to x1, run red, restore proved by blob == HEAD and an empty `git diff HEAD`. - A1 drop the `data:read` gate in `registerDatasetTools`: red `a grant without data:read registers neither…` (1 failed, 16 passed). - A2 require only `listDatasets` in `hasDatasetTools`: red `a bridge without ["queryDataset"]…` and `…["datasetToolDefinitions"]…` (2 failed). - A3 serve the HTTP seam from any `analytics` service, method or not: red `the seam is served by an analytics service carrying datasetTools, and not without one` (1 failed, 5 passed). - A4 attach the stdio members without the executor: red `a bridge built without the analytics executor carries no dataset member` (1 failed, 19 passed). A1's first attempt used a replacement already present in the file; the tool refused it before running anything (replacement count did not rise) and it was re-run with a marker. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a, not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQuUSo11ZX1avrvbez)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 41106b5 commit 34a30e8

9 files changed

Lines changed: 861 additions & 7 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
feat(mcp): serve `list_datasets` and `query_dataset` over MCP under `data:read`
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
An MCP client can now answer business questions through the governed dataset layer (ADR-0149 D2). `McpDataBridge` gains three optional members, `listDatasets`, `queryDataset` and `datasetToolDefinitions`, and `wireBridgeTools` registers the two tools only when a bridge carries all three and the caller's grant admits `data:read` (an API key or a session keeps them, as every read tool). Both bridges carry the members where the `analytics` service serves its dataset executor (`datasetTools`) and none of them otherwise, so a deployment without the analytics service lists exactly the tools it listed before.
12+
13+
The tools run the service-analytics executor as the caller, with no gate added or skipped: each tool's description is the executor's own definition, its input is the spec declaration (`ListDatasetsInputSchema` / `QueryDatasetInputSchema`), `query_dataset` is held to the same page cap as `query_records`, and a refusal answers in the coded envelope the other data tools use. The generated `SKILL.md` names both tools where they register and teaches the selection rule: an exact word match on a member's name, label or synonym is the only hit, one hit answers through `query_dataset`, several hits are a question for the user, and no hit falls back to the object tools with the answer marked as not a governed metric.
Lines changed: 340 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,340 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0149 D2] `list_datasets` and `query_dataset` on MCP.
5+
*
6+
* Pinned here over a fake bridge (the catalogue, the matcher, the executor and
7+
* the four-face parity live with the service-analytics executor): the pair
8+
* registers only on a bridge that carries all three dataset members, and only
9+
* for a grant that admits `data:read`; each tool's description is the one the
10+
* bridge's definitions carry, never a copy in this package; the arguments reach
11+
* the bridge as sent, with the tool's page cap beside them; an undeclared key is
12+
* refused before the bridge is asked, in the spec's words; a refusal the bridge
13+
* throws comes back as the coded tool error.
14+
*/
15+
16+
import { describe, it, expect, beforeEach, vi } from 'vitest';
17+
import {
18+
LIST_DATASETS_TOOL_NAME,
19+
MCP_OAUTH_SCOPE_DATA_READ,
20+
MCP_OAUTH_SCOPE_DATA_WRITE,
21+
QUERY_DATASET_TOOL_NAME,
22+
type ListDatasetsOutput,
23+
type QueryDatasetOutput,
24+
} from '@objectstack/spec/ai';
25+
import { MCPServerRuntime } from './mcp-server-runtime.js';
26+
import { hasDatasetTools, type McpDataBridge } from './mcp-http-tools.js';
27+
import { createStdioDataBridge, type StdioDatasetToolsService } from './stdio-data-bridge.js';
28+
import { renderSkillMarkdown } from './skill-md.js';
29+
30+
const DATASET_TOOLS = [LIST_DATASETS_TOOL_NAME, QUERY_DATASET_TOOL_NAME].sort();
31+
32+
/** Stand-ins for the service-analytics definitions: distinctive, so a copy anywhere else cannot match by accident. */
33+
const DEFINITIONS = [
34+
{ name: LIST_DATASETS_TOOL_NAME, description: 'DEFINED-BY-EXECUTOR list: one hit wins; several, ask; none, fall back.' },
35+
{ name: QUERY_DATASET_TOOL_NAME, description: 'DEFINED-BY-EXECUTOR query: cite the provenance block.' },
36+
];
37+
38+
const CATALOGUE: ListDatasetsOutput = {
39+
datasets: [
40+
{
41+
name: 'sales_analysis',
42+
label: 'Sales analysis',
43+
object: 'crm_opportunity',
44+
dimensions: [{ name: 'stage', label: 'Stage', type: 'string' }],
45+
measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum', synonyms: ['营收'] }],
46+
matches: [{ term: '营收', member: 'measures.revenue', matchedOn: 'synonym' }],
47+
},
48+
],
49+
};
50+
51+
const ANSWER: QueryDatasetOutput = {
52+
rows: [{ stage: 'won', revenue: 42 }],
53+
fields: [
54+
{ name: 'stage', label: 'Stage', type: 'string' },
55+
{ name: 'revenue', label: 'Revenue', type: 'number' },
56+
],
57+
provenance: {
58+
kind: 'dataset',
59+
dataset: { name: 'sales_analysis', label: 'Sales analysis' },
60+
measures: [{ name: 'revenue', label: 'Revenue' }],
61+
dimensions: [{ name: 'stage', label: 'Stage' }],
62+
},
63+
rowCount: 1,
64+
truncated: false,
65+
} as QueryDatasetOutput;
66+
67+
type Call = [string, ...unknown[]];
68+
type DatasetMember = 'listDatasets' | 'queryDataset' | 'datasetToolDefinitions';
69+
70+
function makeBridge(
71+
without: readonly DatasetMember[] = [],
72+
definitions: ReadonlyArray<{ name: string; description: string }> = DEFINITIONS,
73+
): McpDataBridge & { calls: Call[] } {
74+
const calls: Call[] = [];
75+
const bridge: McpDataBridge & { calls: Call[] } = {
76+
calls,
77+
async listObjects() { return []; },
78+
async describeObject() { return null; },
79+
async query() { return { records: [] }; },
80+
async get() { return null; },
81+
async create() { return {}; },
82+
async update() { return {}; },
83+
async remove() { return {}; },
84+
async listDatasets(input) {
85+
calls.push(['listDatasets', input]);
86+
return CATALOGUE;
87+
},
88+
async queryDataset(input, opts) {
89+
calls.push(['queryDataset', input, opts]);
90+
if (input.datasetName === 'hidden_dataset') {
91+
throw Object.assign(new Error('Dataset "hidden_dataset" not found'), { code: 'NOT_FOUND', status: 404 });
92+
}
93+
return ANSWER;
94+
},
95+
datasetToolDefinitions() {
96+
calls.push(['datasetToolDefinitions']);
97+
return definitions;
98+
},
99+
};
100+
for (const member of without) delete bridge[member];
101+
return bridge;
102+
}
103+
104+
async function rpc(
105+
runtime: MCPServerRuntime,
106+
bridge: unknown,
107+
body: unknown,
108+
toolOptions?: { grantedScopes?: string[]; maxQueryLimit?: number },
109+
) {
110+
const req = new Request('http://localhost/api/v1/mcp', {
111+
method: 'POST',
112+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
113+
body: JSON.stringify(body),
114+
});
115+
const res = await runtime.handleHttpRequest(req, {
116+
bridge: bridge as McpDataBridge,
117+
parsedBody: body,
118+
...(toolOptions ? { toolOptions } : {}),
119+
});
120+
return (await res.json()) as any;
121+
}
122+
123+
async function listTools(runtime: MCPServerRuntime, bridge: unknown, grantedScopes?: string[]) {
124+
const json = await rpc(runtime, bridge, { jsonrpc: '2.0', id: 1, method: 'tools/list' }, grantedScopes ? { grantedScopes } : undefined);
125+
return (json.result?.tools ?? []) as Array<{ name: string; description?: string; inputSchema?: any; annotations?: any }>;
126+
}
127+
128+
const namesOf = (tools: Array<{ name: string }>) => tools.map((t) => t.name);
129+
const datasetToolsIn = (tools: Array<{ name: string }>) => namesOf(tools).filter((n) => DATASET_TOOLS.includes(n)).sort();
130+
131+
async function callTool(
132+
runtime: MCPServerRuntime,
133+
bridge: unknown,
134+
name: string,
135+
args: Record<string, unknown>,
136+
toolOptions?: { grantedScopes?: string[]; maxQueryLimit?: number },
137+
) {
138+
const json = await rpc(runtime, bridge, { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name, arguments: args } }, toolOptions);
139+
return json as { result?: { content: Array<{ type: 'text'; text: string }>; isError?: boolean }; error?: { code: number; message: string } };
140+
}
141+
142+
describe('[ADR-0149 D2] dataset tools on MCP — registration', () => {
143+
let runtime: MCPServerRuntime;
144+
beforeEach(() => {
145+
runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
146+
});
147+
148+
it('a bridge carrying all three members registers both tools, read-only, for an unscoped caller', async () => {
149+
const tools = await listTools(runtime, makeBridge());
150+
expect(datasetToolsIn(tools)).toEqual(DATASET_TOOLS);
151+
for (const name of DATASET_TOOLS) {
152+
const tool = tools.find((t) => t.name === name)!;
153+
expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false });
154+
}
155+
});
156+
157+
it('each description is the one the bridge definitions carry, verbatim', async () => {
158+
const tools = await listTools(runtime, makeBridge());
159+
for (const def of DEFINITIONS) {
160+
expect(tools.find((t) => t.name === def.name)?.description).toBe(def.description);
161+
}
162+
});
163+
164+
it('the input schemas are the spec declarations, closed against undeclared keys', async () => {
165+
const tools = await listTools(runtime, makeBridge());
166+
const list = tools.find((t) => t.name === LIST_DATASETS_TOOL_NAME)!;
167+
const query = tools.find((t) => t.name === QUERY_DATASET_TOOL_NAME)!;
168+
expect(Object.keys(list.inputSchema.properties)).toEqual(['terms']);
169+
expect(list.inputSchema.additionalProperties).toBe(false);
170+
expect(Object.keys(query.inputSchema.properties).sort()).toEqual(['datasetName', 'selection']);
171+
expect(query.inputSchema.required).toEqual(expect.arrayContaining(['datasetName', 'selection']));
172+
expect(query.inputSchema.additionalProperties).toBe(false);
173+
});
174+
175+
it.each([
176+
[['listDatasets']],
177+
[['queryDataset']],
178+
[['datasetToolDefinitions']],
179+
[['listDatasets', 'queryDataset', 'datasetToolDefinitions']],
180+
] as Array<[DatasetMember[]]>)('a bridge without %j registers no dataset tool, and the rest of the surface is unchanged', async (without) => {
181+
const full = namesOf(await listTools(runtime, makeBridge()));
182+
const partial = namesOf(await listTools(new MCPServerRuntime({ name: 't', version: '1.0.0' }), makeBridge(without)));
183+
expect(datasetToolsIn(partial.map((name) => ({ name })))).toEqual([]);
184+
expect(partial.sort()).toEqual(full.filter((n) => !DATASET_TOOLS.includes(n)).sort());
185+
});
186+
187+
it('a tool the definitions do not describe is not registered', async () => {
188+
const tools = await listTools(runtime, makeBridge([], [DEFINITIONS[1]]));
189+
expect(datasetToolsIn(tools)).toEqual([QUERY_DATASET_TOOL_NAME]);
190+
});
191+
192+
it('data:read admits both tools', async () => {
193+
const tools = await listTools(runtime, makeBridge(), [MCP_OAUTH_SCOPE_DATA_READ]);
194+
expect(datasetToolsIn(tools)).toEqual(DATASET_TOOLS);
195+
});
196+
197+
it('a grant without data:read registers neither, and a call gets the unknown-tool refusal without reaching the bridge', async () => {
198+
const bridge = makeBridge();
199+
const tools = await listTools(runtime, bridge, [MCP_OAUTH_SCOPE_DATA_WRITE]);
200+
expect(datasetToolsIn(tools)).toEqual([]);
201+
// The same answer a read tool outside the grant gets (`query_records`).
202+
for (const name of [QUERY_DATASET_TOOL_NAME, 'query_records']) {
203+
const json = await callTool(
204+
new MCPServerRuntime({ name: 't', version: '1.0.0' }),
205+
bridge,
206+
name,
207+
name === 'query_records' ? { objectName: 'crm_opportunity' } : { datasetName: 'sales_analysis', selection: { measures: ['revenue'] } },
208+
{ grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] },
209+
);
210+
const refused = Boolean(json.error) || json.result?.isError === true;
211+
expect(refused, name).toBe(true);
212+
const text = json.error?.message ?? json.result?.content[0]?.text ?? '';
213+
expect(text, name).toMatch(new RegExp(`Tool ${name} not found`));
214+
}
215+
expect(bridge.calls.filter((c) => c[0] === 'listDatasets' || c[0] === 'queryDataset')).toEqual([]);
216+
});
217+
});
218+
219+
describe('[ADR-0149 D2] dataset tools on MCP — calls', () => {
220+
let runtime: MCPServerRuntime;
221+
beforeEach(() => {
222+
runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
223+
});
224+
225+
it('list_datasets hands the terms to the bridge and answers its catalogue', async () => {
226+
const bridge = makeBridge();
227+
const json = await callTool(runtime, bridge, LIST_DATASETS_TOOL_NAME, { terms: ['营收'] });
228+
expect(json.result?.isError).toBeFalsy();
229+
expect(JSON.parse(json.result!.content[0].text)).toEqual(CATALOGUE);
230+
expect(bridge.calls.filter((c) => c[0] === 'listDatasets')).toEqual([['listDatasets', { terms: ['营收'] }]]);
231+
});
232+
233+
it('query_dataset hands the input to the bridge with the default page cap, and answers rows plus provenance', async () => {
234+
const bridge = makeBridge();
235+
const input = { datasetName: 'sales_analysis', selection: { measures: ['revenue'], dimensions: ['stage'] } };
236+
const json = await callTool(runtime, bridge, QUERY_DATASET_TOOL_NAME, input);
237+
expect(json.result?.isError).toBeFalsy();
238+
expect(JSON.parse(json.result!.content[0].text)).toEqual(ANSWER);
239+
const [call] = bridge.calls.filter((c) => c[0] === 'queryDataset');
240+
expect(call[1]).toMatchObject(input);
241+
expect(call[2]).toEqual({ maxRows: 50 });
242+
});
243+
244+
it('query_dataset carries the host page cap (maxQueryLimit), the one query_records uses', async () => {
245+
const bridge = makeBridge();
246+
await callTool(runtime, bridge, QUERY_DATASET_TOOL_NAME, { datasetName: 'sales_analysis', selection: { measures: ['revenue'] } }, { maxQueryLimit: 7 });
247+
expect(bridge.calls.find((c) => c[0] === 'queryDataset')?.[2]).toEqual({ maxRows: 7 });
248+
});
249+
250+
it('an undeclared key is refused before the bridge is asked, naming the key to send', async () => {
251+
const bridge = makeBridge();
252+
const json = await callTool(runtime, bridge, QUERY_DATASET_TOOL_NAME, {
253+
dataset: 'sales_analysis',
254+
selection: { measures: ['revenue'] },
255+
});
256+
const text = json.error?.message ?? json.result?.content[0]?.text ?? '';
257+
expect(Boolean(json.error) || json.result?.isError === true).toBe(true);
258+
expect(text).toContain('datasetName');
259+
expect(bridge.calls.filter((c) => c[0] === 'queryDataset')).toEqual([]);
260+
});
261+
262+
it('a refusal the bridge throws comes back as the coded tool error', async () => {
263+
const bridge = makeBridge();
264+
const json = await callTool(runtime, bridge, QUERY_DATASET_TOOL_NAME, {
265+
datasetName: 'hidden_dataset',
266+
selection: { measures: ['revenue'] },
267+
});
268+
expect(json.result?.isError).toBe(true);
269+
const envelope = JSON.parse(json.result!.content[0].text);
270+
expect(envelope.error).toMatchObject({ code: 'NOT_FOUND', status: 404 });
271+
});
272+
});
273+
274+
describe('[ADR-0149 D3] the SKILL.md teaches the selection rule where the pair registers', () => {
275+
it('renders both tools and the rule for a host whose bridge carries them', () => {
276+
const md = renderSkillMarkdown({ datasetTools: true });
277+
for (const name of DATASET_TOOLS) expect(md).toContain(`**${name}(`);
278+
expect(md).toContain('Choosing between a metric and an object query');
279+
});
280+
281+
it('renders them for a data:read grant, and not without one or without the pair', () => {
282+
expect(renderSkillMarkdown({ datasetTools: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] })).toContain('list_datasets');
283+
expect(renderSkillMarkdown({ datasetTools: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] })).not.toContain('list_datasets');
284+
expect(renderSkillMarkdown({})).not.toContain('list_datasets');
285+
});
286+
});
287+
288+
describe('[ADR-0149 D2] the stdio bridge\'s dataset members', () => {
289+
const PRINCIPAL = { userId: 'u_key', tenantId: 'org_1' };
290+
const SAVED = [{ name: 'sales_analysis', object: 'crm_opportunity' }];
291+
292+
function stdioHarness(protocolItems: unknown[] | undefined) {
293+
const bound: any[] = [];
294+
const executor = {
295+
definitions: DEFINITIONS,
296+
listDatasets: vi.fn(async () => CATALOGUE),
297+
queryDataset: vi.fn(async () => ANSWER),
298+
};
299+
const service: StdioDatasetToolsService = { datasetTools: vi.fn((d) => { bound.push(d); return executor; }) };
300+
const metadataService = { list: vi.fn(async () => SAVED) } as any;
301+
const protocol = protocolItems === undefined
302+
? undefined
303+
: () => ({ getMetaItems: vi.fn(async () => ({ items: protocolItems })) });
304+
const deps = {
305+
engine: {} as any,
306+
metadataService,
307+
...(protocol ? { protocol } : {}),
308+
resolvePrincipal: async () => PRINCIPAL as any,
309+
};
310+
return { deps, service, executor, bound, metadataService };
311+
}
312+
313+
it('a bridge built without the analytics executor carries no dataset member', () => {
314+
const { deps } = stdioHarness([]);
315+
const bridge = createStdioDataBridge(deps);
316+
expect(hasDatasetTools(bridge)).toBe(false);
317+
expect(bridge.listDatasets).toBeUndefined();
318+
});
319+
320+
it('runs both tools as the stdio principal, with the page cap, over the merged dataset read', async () => {
321+
const { deps, service, executor, bound } = stdioHarness(SAVED);
322+
const bridge = createStdioDataBridge({ ...deps, datasetTools: service });
323+
expect(hasDatasetTools(bridge)).toBe(true);
324+
expect(bridge.datasetToolDefinitions!()).toBe(DEFINITIONS);
325+
await bridge.listDatasets!({ terms: ['营收'] });
326+
expect(executor.listDatasets).toHaveBeenCalledWith({ terms: ['营收'] }, PRINCIPAL);
327+
const input = { datasetName: 'sales_analysis', selection: { measures: ['revenue'] } };
328+
await bridge.queryDataset!(input, { maxRows: 9 });
329+
expect(executor.queryDataset).toHaveBeenCalledWith(input, PRINCIPAL);
330+
expect(bound.at(-1).maxQueryLimit).toBe(9);
331+
expect(await bound[0].loadDatasets(PRINCIPAL)).toEqual(SAVED);
332+
});
333+
334+
it('reads the metadata service on a host with no merged read', async () => {
335+
const { deps, service, bound, metadataService } = stdioHarness(undefined);
336+
createStdioDataBridge({ ...deps, datasetTools: service }).datasetToolDefinitions!();
337+
expect(await bound[0].loadDatasets(PRINCIPAL)).toEqual(SAVED);
338+
expect(metadataService.list).toHaveBeenCalledWith('dataset');
339+
});
340+
});

0 commit comments

Comments
 (0)