Skip to content

Commit c513d62

Browse files
feat(mcp): initialize instructions carry the governed-metric selection rule and the skills install line (#34790)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBLW6dHPW6sSheA32XPKZzPV)_ Part of #34686. This PR is the instructions half. The `/mcp/skill` single-source half (the served data-loop text rendered from the published ask-data skill, plus its pin test) waits for #34685 and lands as a separate PR. Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:开放 MCP 服务器(HTTP)的 `initialize` 指令在默认文案后追加两段:凭据能用 `list_datasets` 和 `query_dataset` 时,加一段"先找治理指标"的选择规则;所有凭据都加一行技能包安装提示,版本取自服务器自身包版本。 - **为什么改**:客户端只在选中某个工具之后才读它的描述,所以写在数据集工具描述里的选指标规则,只跑过 `claude mcp add` 的客户端根本看不到。#34659 裁决 D5 = A:初始化指令带上这条短规则,并指向本地技能包。 - **风险与回滚**:只改默认文案,宿主注入的指令和 `instructions` 配置项原样不动,stdio 不变。回滚就是 revert 本 PR。指令从 98 字节增至 812 字节(有数据集工具)或 357 字节(无 `data:read`)。 - **先看**:`packages/mcp/src/mcp-server-runtime.ts`(`DATASET_SELECTION_RULE` / `openServerInstructions` 以及 `handleHttpRequest` 里的 instructions 那几行)、`packages/mcp/src/mcp-http-tools.ts`(`datasetToolDescriptions`,与工具注册共用的那道门)、`packages/mcp/src/initialize-selection-rule-34686.test.ts`。 - **两分钟验证**:`pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/initialize-selection-rule-34686.test.ts`,预期 7 个测试全绿。 - **需要你做的**:无,席位落地。 ## What changes - **`initialize` instructions over HTTP** (`packages/mcp/src/mcp-server-runtime.ts`). When neither the host's per-request text nor the runtime's configured `instructions` answers, `result.instructions` is now the existing default sentence followed by: - **the selection rule**, only when this request registers both `list_datasets` and `query_dataset`. It says: look for a governed metric first by calling `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 is answered with `query_dataset`. Several matches mean asking the user, without picking. No match falls back to `query_records` / `aggregate_records` and says the answer is not from a governed metric. This is the same meaning as ADR-0149 D3 and as `DATASET_TOOL_LINES` (`packages/mcp/src/skill-md.ts`), which this PR does not change. - **the skills install line**, for every grant: `Published skills: @objectstack/skills VERSION`, then the `pnpm add -D @objectstack/skills@VERSION` command and a pointer to the package README for syncing. VERSION is `PACKAGE_VERSION` (`packages/mcp/src/package-version.ts`), which is how the package already reads its own version. `@objectstack/skills` and `@objectstack/mcp` are in one `fixed` group in `.changeset/config.json`, so they always share a version. It is deliberately not `config.version`, because that is the operator's `serverInfo.version` override (the plugin's `version` option). No line is sent when the manifest cannot be read, because an unversioned install takes the registry's `latest`, which can be another major's catalog. The ask-data skill is named only by its package; the skill itself does not exist on main yet (#34685). - **One gate for the dataset pair** (`packages/mcp/src/mcp-http-tools.ts`). The new `datasetToolDescriptions(bridge, options)` holds the condition `registerDatasetTools` used to hold inline: the bridge carries all three dataset members (`hasDatasetTools`), the grant is unscoped or includes `data:read`, and the bridge defines a description for the tool. `registerDatasetTools` now registers from it, and `datasetToolsServed` (both tools present) decides whether the rule is sent. The runtime's bridge carries the pair only where the analytics service serves `datasetTools` (`packages/runtime/src/domains/mcp.ts`, `resolveMcpDatasetToolsService` and `buildMcpBridge`). No change was needed on the producer side. - **Precedence (measured choice).** Host-injected instructions (`hostInstructions`: the hosted door's `instructions` / `dataOnlyInstructions`) are untouched. The configured `instructions` option is also served exactly as written, with nothing appended, for three reasons. It is one string for every grant, so appending a grant-dependent rule would make it a different text per grant. The existing pins `mcp-server-runtime.authoring-scope.test.ts` "a runtime configured with instructions keeps them for every request the injection does not reach" and "…without it the configured text stays" state that contract. And no producer in this repository sets it: `MCPServerPlugin` is constructed without `instructions` everywhere in `packages/` and `examples/`, so `examples/app-crm` reads the default path, as the live reading below shows. - **Stdio unchanged, on purpose.** The long-lived server's instructions are fixed when the `McpServer` is constructed. The SDK copies them in its constructor and has no public setter. `bridgeDataTools`, which decides whether the dataset pair exists, runs later in `start()`. So the stdio server cannot say at construction whether it serves the dataset tools. - **Docs.** `packages/mcp/README.md` gains the two dataset tools in the tool list and their registration condition, `data:read` coverage of the pair, and a section on the `initialize` instructions: precedence, the two parts, and stdio. `content/docs/ai/connect-mcp.mdx` gains the two tools in the tool table and a "Governed metrics and the `initialize` instructions" section, and the verify transcript now names the dataset pair. - **Changeset.** `.changeset/34686-initialize-selection-rule.md`: `@objectstack/mcp` patch, `Clause-②: no`, `Metadata-protocol: none`. Instructions size, in bytes (UTF-8), for `result.instructions`: | Grant | Before (`f02f4f63`) | After | |:--|--:|--:| | (i) admin API key, dataset tools registered | 98 | 812 | | (ii) OAuth token without `data:read` (`data:write` only) | 98 | 357 | Both "after" numbers were measured live (below) and in-process over a fake bridge at `ae5008be`; the two readings agree. Out of scope: `list_datasets` matching and candidates. Separate cards carry them (#34761 spec, #34763 server). The instructions text does not mention a candidates list, because that field does not exist yet. The authoring (draft) tools are a later milestone of #34659. ## Why The open server told a connecting client one sentence. Then it listed 17 tools (about 40 KB). The rule for choosing between a governed metric and an object query lived only inside the dataset tools' descriptions, and a client reads those only after it has already chosen a tool. #34659 ruling 6940528935, D5 = A: the open server points to the local skills package, and the `initialize` instructions carry the short selection rule. ## Tests New file `packages/mcp/src/initialize-selection-rule-34686.test.ts`, 7 tests: - the rule is present where both dataset tools register: an API key or session, and a `data:read` token, each beside its `tools/list` control; - a grant without `data:read` (`data:write`, `metadata:write`) gets neither dataset tool name, and `tools/list` lists neither tool; - a bridge missing any one of the three dataset members gets no rule; - a bridge that registers only `list_datasets` (no description for `query_dataset`) gets no rule, because the rule names both; - the install line carries this package's own version (read from `../package.json`), for every grant, and never the operator's `version` (a runtime built with `0.0.1-operator`); - the host's `instructions` and `dataOnlyInstructions`, and the configured `instructions`, are answered byte-for-byte as given. <details><summary>Test runs at ae5008b</summary> - `pnpm --filter @objectstack/mcp typecheck`: `tsc --noEmit` exits 0, then `check:test-typecheck: OK — @objectstack/mcp's test layer compiles under packages/mcp/tsconfig.test.json; 6 file(s) / 53 error(s) / 8 pinned signature(s) held` (debt unchanged; the package `tsconfig.json` excludes `*.test.ts`, which is why the test layer is checked through `tsconfig.test.json`). - `pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2` (whole package, under the shared verify lock): `Test Files 67 passed (67)`, `Tests 1233 passed (1233)`, lock `VERDICT command-exit 0`. - Targeted run at `b31f2955` (new file, `mcp-dataset-tools.test.ts`, `mcp-server-runtime.authoring-scope.test.ts`): `Test Files 3 passed (3)`, `Tests 60 passed (60)`. </details> <details><summary>Ablations (one-shot, through scripts/ablation-replace.mjs, restored and verified against HEAD)</summary> The tests import `./mcp-server-runtime.js` from source, so no `dist/` is involved. 1. The data:read gate in `datasetToolDescriptions`: `if (scopes && !scopes.includes(MCP_OAUTH_SCOPE_DATA_READ)) return descriptions;` was replaced by the same line with `&& false` appended. Result: `anchor 1 -> 0`, `blob 8d01389 -> c783220d5998`, then `× a grant without data:read gets neither dataset sentence (and lists neither tool)`, `Tests 1 failed | 6 passed (7)`. Restore: `blob == HEAD (8d01389) and git diff HEAD is empty`. 2. The instructions gate itself: `openServerInstructions(datasetToolsServed(opts.bridge, opts.toolOptions))` was replaced by `openServerInstructions(true || datasetToolsServed(…))`. Result: `anchor 1 -> 0`, then the no-`data:read`, the no-dataset-pair and the list-only tests went red on the instructions assertion (`expected false to be true`), `Tests 3 failed | 4 passed (7)`. Restore: `blob == HEAD (9590d8a) and git diff HEAD is empty`. </details> ## Acceptance notes - The configured-`instructions` path and stdio do not carry the rule or the install line. The reasons are under What changes. If a deployment that sets `instructions` should also get the rule, that is a contract change to the option and a decision for its own card; it is not made here. - When the dataset rule is sent, it names `aggregate_records` as a fallback, as `DATASET_TOOL_LINES` does. `aggregate_records` registers only where the bridge implements `aggregate`. On `examples/app-crm` it is listed. ## Verification Live, `examples/app-crm` (`pnpm dev:crm -- --fresh -p 38643`, built from `ae5008be`), a fresh HTTP `initialize` per credential. Both credentials were minted on that throwaway instance and discarded with it. <details><summary>(i) Admin API key (POST /api/v1/keys as the seeded platform admin): 812 bytes, 17 tools listed including list_datasets and query_dataset</summary> ```text ObjectStack MCP Server. The tools this connection lists depend on what its credential was granted. 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. Published skills: @objectstack/skills 18.5.0. To give a coding agent the ObjectStack procedures, install that version in the project (pnpm add -D @objectstack/skills@18.5.0) and follow the package README to sync the skills into the agent's skills directory. ``` `serverInfo`: `{"name":"objectstack","version":"18.5.0"}`. `tools/list`: list_objects, describe_object, validate_expression, query_records, aggregate_records, get_record, create_record, update_record, delete_record, delete_records, read_file, create_upload_link, list_actions, run_action, resume_run, list_datasets, query_dataset. </details> <details><summary>(ii) OAuth access token granted data:write only (dynamic client registration, PKCE authorization code, consent as the admin): 357 bytes, 4 tools listed, no dataset tool</summary> ```text ObjectStack MCP Server. The tools this connection lists depend on what its credential was granted. Published skills: @objectstack/skills 18.5.0. To give a coding agent the ObjectStack procedures, install that version in the project (pnpm add -D @objectstack/skills@18.5.0) and follow the package README to sync the skills into the agent's skills directory. ``` Token `scope`: `data:write`. `tools/list`: create_record, update_record, delete_record, create_upload_link. </details> <details><summary>Local gates at ae5008b</summary> - `node scripts/pm/dispatch-gates.mjs --commands` derived 98 families from this diff. All 98 were run, and `--ran` answers `98 derived famil(ies) accounted for — 98 run, 0 NOT-MEASURED`. - 95 exited 0 on the first pass. Three exited 3 (PREREQUISITE NOT MET, so nothing was measured) and were re-run after fixing the prerequisite; all three then exited 0: - `pnpm check:dual-build-cjs-loads` needed a full build: `124 published require entry point(s) across 72 package(s) load`. - `pnpm --filter @objectstack/spec run check:skill-examples` also needed a full build: `347 prose examples type-check across 3 surface(s)`. - `node scripts/check-plugin-teardown-shape.mjs --self-test` needed its pinned fixture commit, fetched at depth 1: `48 cases pass`. - `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0`. - CI check-runs: not yet concluded when this PR was opened. CI convergence is the seat's. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` is not touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` is CI's. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request (the PR2 half is a separate branch, as claimed). - [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. - [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 (the maintainer quick-read is in Chinese by the seat's convention). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. Files: `.changeset/34686-initialize-selection-rule.md`, `content/docs/ai/connect-mcp.mdx`, `packages/mcp/README.md`, `packages/mcp/src/initialize-selection-rule-34686.test.ts`, `packages/mcp/src/mcp-http-tools.ts`, `packages/mcp/src/mcp-server-runtime.ts`. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfR33NbV51QQU6R6bm --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3bbda33 commit c513d62

6 files changed

Lines changed: 375 additions & 16 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/mcp': patch
3+
---
4+
5+
feat(mcp): the HTTP `initialize` instructions carry the governed-metric selection rule and the skills install line
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A client connected to the open MCP server over HTTP was told one sentence at `initialize`. The rule for choosing between a governed metric and an object query lived only in the dataset tools' own descriptions, which a client reads after it has already chosen a tool, and nothing named the skills package to install.
11+
12+
When neither the host's per-request text nor the plugin's `instructions` option answers, `result.instructions` now carries, after that sentence:
13+
14+
- **The selection rule**, only where the request registers both `list_datasets` and `query_dataset` (a bridge with the dataset members and a grant that admits `data:read`; an API key or session counts): look for a governed metric first with `list_datasets` and the question's business words; a word matches only an equal name, label or synonym; one measure match answers through `query_dataset`; several matches are a question for the user; no match falls back to `query_records` / `aggregate_records` and says the answer is not from a governed metric. A grant without `data:read` gets no dataset sentence.
15+
- **The skills install line**: `Published skills: @objectstack/skills <version>` with its `pnpm add -D` command, at this package's own version (released together with `@objectstack/skills`), not the `version` option.
16+
17+
Host-injected instructions and the `instructions` option are served exactly as before, with nothing appended. The stdio server's instructions are unchanged.

‎content/docs/ai/connect-mcp.mdx‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,8 +261,9 @@ decision.
261261

262262
## What the agent gets
263263

264-
Thirteen tools, generated from your metadata, and two more for files where the
265-
storage service is installed:
264+
Thirteen tools, generated from your metadata, two more for files where the
265+
storage service is installed, and two for governed metrics where the analytics
266+
service is installed:
266267

267268
| Tool | What it does |
268269
|:---|:---|
@@ -276,6 +277,31 @@ storage service is installed:
276277
| `resume_run` | Finish a flow action that paused on a screen, by submitting the screen's values |
277278
| `read_file` | Read a file a record carries: its text (text files, PDF, Word `.docx`) or the image itself, with its size, the byte cap and a short-lived download link |
278279
| `create_upload_link` | Hand the user a single-use link that uploads a file onto a record's file field or its attachments (up to 10 files, sent together, for a multi-file field) |
280+
| `list_datasets` | List the governed datasets (business metrics) you may query: their measures and dimensions with business labels, descriptions and synonyms, and which of the question's words each one matches exactly |
281+
| `query_dataset` | Compute a governed metric by the names `list_datasets` gives; the answer carries its provenance (the dataset and measures used) |
282+
283+
### Governed metrics and the `initialize` instructions
284+
285+
`list_datasets` and `query_dataset` are registered with the `data:read` scope,
286+
and only where the analytics service is installed. Over HTTP, the server's
287+
`initialize` answer (`result.instructions`) tells the client how to choose
288+
between a governed metric and an object query, because a client reads a tool's
289+
description only after it has chosen that tool. Where both dataset tools are
290+
registered for the connection, the instructions say: look for a governed metric
291+
first by calling `list_datasets` with the question's business words; a word
292+
matches only when it equals a name, label or synonym; one measure match is
293+
answered with `query_dataset`; several matches are a question for the user; no
294+
match falls back to `query_records` / `aggregate_records`, saying the answer is
295+
not from a governed metric. A token without `data:read` gets neither tool and no
296+
such sentence.
297+
298+
The instructions also name the published skills package and the version to
299+
install, which is the server's own version
300+
(`Published skills: @objectstack/skills <version>`, with
301+
`pnpm add -D @objectstack/skills@<version>`); see
302+
[Skills](/docs/ai/skills) for syncing it into your agent. A deployment that sets
303+
the MCP plugin's `instructions` option serves that text as written instead, and
304+
the local stdio server's instructions carry neither part.
279305

280306
### Files: `read_file` and `create_upload_link`
281307

@@ -690,7 +716,8 @@ call '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":
690716
# → {"result":{"serverInfo":{"name":"objectstack",...},"capabilities":{"tools":{...},"prompts":{}}},...}
691717

692718
call '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | grep -o '"name":"[a-z_]*"'
693-
# → the thirteen tools, list_objects … resume_run (fifteen with read_file and create_upload_link where storage is installed)
719+
# → the thirteen tools, list_objects … resume_run (plus read_file and create_upload_link where storage is installed,
720+
# and list_datasets and query_dataset where the analytics service is installed)
694721

695722
call '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"query_records","arguments":{"objectName":"crm_opportunity","limit":3}}}'
696723
# → {"result":{"content":[{"type":"text","text":"{ \"object\": \"crm_opportunity\", \"records\": [ ... ], \"total\": 23, \"hasMore\": true }"}]}}

‎packages/mcp/README.md‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,28 @@ interface MCPServerPluginOptions {
6767
}
6868
```
6969

70+
### The `initialize` instructions
71+
72+
Over HTTP, `initialize` answers `result.instructions` with the first of: the
73+
host's per-request text (`instructions` / `dataOnlyInstructions` on the
74+
authoring injection), the `instructions` option, or the open server's own text.
75+
The host's text and the option are served exactly as written. The open
76+
server's own text is one sentence saying the tool list follows the credential's
77+
grant, then two parts:
78+
79+
- **The selection rule**, only where this request registers both
80+
`list_datasets` and `query_dataset`: look for a governed metric first with
81+
`list_datasets` and the question's business words; one measure match answers
82+
through `query_dataset`; several matches are a question for the user; no
83+
match falls back to the object tools and says the answer is not from a
84+
governed metric. A grant without `data:read` gets no such sentence.
85+
- **The skills install line**: `Published skills: @objectstack/skills <version>`
86+
and its `pnpm add -D` command, at this package's own version (the two are
87+
released together), never the `version` option.
88+
89+
The stdio server's instructions are fixed when it is constructed, before its
90+
tools are bridged, and carry neither part.
91+
7092
Tools and resources are **not** opted into per-option — the plugin bridges the
7193
AI tool registry, metadata service and data engine automatically when it
7294
starts. The HTTP surface needs no start at all: it is served per-request at
@@ -124,14 +146,21 @@ apply):
124146
'list_actions' // Invokable business actions the caller may run
125147
'run_action' // Invoke an action by name or listed face with { recordId, params }
126148
'resume_run' // Continue a run paused on a screen with { runId, values }
149+
150+
// Governed metrics (ADR-0149)
151+
'list_datasets' // Governed datasets: measures and dimensions, with labels, synonyms and exact matches
152+
'query_dataset' // Compute a governed metric; the answer carries its provenance
127153
```
128154

129155
`aggregate_records` is registered only when the bridge implements `aggregate`,
130-
and `resume_run` only when it implements `resumeRun`; a bridge without those
131-
seams serves the rest and advertises nothing it cannot do.
156+
`resume_run` only when it implements `resumeRun`, and `list_datasets` /
157+
`query_dataset` only when it implements all three of `listDatasets`,
158+
`queryDataset` and `datasetToolDefinitions` (the runtime's bridge does where the
159+
analytics service serves its dataset executor); a bridge without those seams
160+
serves the rest and advertises nothing it cannot do.
132161

133162
OAuth scopes narrow the families at consent time: `data:read` covers
134-
list/describe/query/aggregate/get, `data:write` covers create/update/delete, and
163+
list/describe/query/aggregate/get and the dataset pair, `data:write` covers create/update/delete, and
135164
`actions:execute` covers `list_actions` / `run_action` / `resume_run`. `delete_records` needs both
136165
`data:read` and `data:write`: its preview reads the selection's ids and count. A tool outside the grant
137166
is **not registered at all**, so the SDK rejects it as an unknown tool — the
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#34686] The open server's HTTP `initialize` instructions carry the
5+
* metric-first selection rule (ADR-0149 D3) and the published skills install
6+
* line (#34659 ruling D5 = A).
7+
*
8+
* - The rule rides only where this request registers BOTH dataset tools: the
9+
* same gate `registerDatasetTools` reads (`datasetToolDescriptions`), so a
10+
* grant without `data:read`, a bridge without the dataset members, and a
11+
* bridge that defines no description for one of the pair get no rule — each
12+
* pinned beside its `tools/list` control.
13+
* - The install line names `@objectstack/skills` at this package's own
14+
* version (one `fixed` changeset group), for every grant.
15+
* - Host-injected text and the runtime's configured text are whole answers
16+
* their author owns: nothing is appended to either.
17+
*/
18+
19+
import { createRequire } from 'node:module';
20+
import { describe, it, expect, beforeEach } from 'vitest';
21+
import {
22+
LIST_DATASETS_TOOL_NAME,
23+
MCP_OAUTH_SCOPE_DATA_READ,
24+
MCP_OAUTH_SCOPE_DATA_WRITE,
25+
MCP_OAUTH_SCOPE_METADATA_WRITE,
26+
QUERY_DATASET_TOOL_NAME,
27+
} from '@objectstack/spec/ai';
28+
import { MCPServerRuntime } from './mcp-server-runtime.js';
29+
import type { McpDataBridge } from './mcp-http-tools.js';
30+
import type { McpAuthoringInjection } from './types.js';
31+
32+
const OWN_VERSION = (createRequire(import.meta.url)('../package.json') as { version: string }).version;
33+
34+
const DEFINITIONS = [
35+
{ name: LIST_DATASETS_TOOL_NAME, description: 'list the governed datasets' },
36+
{ name: QUERY_DATASET_TOOL_NAME, description: 'compute a governed metric' },
37+
];
38+
39+
type DatasetMember = 'listDatasets' | 'queryDataset' | 'datasetToolDefinitions';
40+
41+
function makeBridge(
42+
without: readonly DatasetMember[] = [],
43+
definitions: ReadonlyArray<{ name: string; description: string }> = DEFINITIONS,
44+
): McpDataBridge {
45+
const bridge: McpDataBridge = {
46+
async listObjects() { return []; },
47+
async describeObject() { return null; },
48+
async query() { return { records: [] }; },
49+
async get() { return null; },
50+
async create() { return {}; },
51+
async update() { return {}; },
52+
async remove() { return {}; },
53+
async listDatasets() { return { datasets: [] }; },
54+
async queryDataset() { return { rows: [], fields: [], rowCount: 0, truncated: false } as never; },
55+
datasetToolDefinitions() { return definitions; },
56+
};
57+
for (const member of without) delete bridge[member];
58+
return bridge;
59+
}
60+
61+
interface Opts {
62+
grantedScopes?: string[];
63+
authoring?: Partial<McpAuthoringInjection>;
64+
}
65+
66+
async function rpc(runtime: MCPServerRuntime, bridge: McpDataBridge, body: unknown, o: Opts = {}) {
67+
const res = await runtime.handleHttpRequest(
68+
new Request('http://localhost/api/v1/mcp', {
69+
method: 'POST',
70+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
71+
body: JSON.stringify(body),
72+
}),
73+
{
74+
bridge,
75+
parsedBody: body,
76+
...(o.grantedScopes ? { toolOptions: { grantedScopes: o.grantedScopes } } : {}),
77+
...(o.authoring
78+
? {
79+
authoring: {
80+
registry: { getAll: () => [], execute: async () => ({}) as never },
81+
principal: { userId: 'usr_1', scopes: o.grantedScopes ?? [] },
82+
...o.authoring,
83+
} as McpAuthoringInjection,
84+
}
85+
: {}),
86+
},
87+
);
88+
expect(res.status).toBe(200);
89+
return (await res.json()) as any;
90+
}
91+
92+
async function instructionsOf(runtime: MCPServerRuntime, bridge: McpDataBridge, o: Opts = {}): Promise<string> {
93+
const json = await rpc(runtime, bridge, {
94+
jsonrpc: '2.0',
95+
id: 1,
96+
method: 'initialize',
97+
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'pin', version: '0' } },
98+
}, o);
99+
expect(json.error).toBeUndefined();
100+
expect(typeof json.result.instructions).toBe('string');
101+
return json.result.instructions;
102+
}
103+
104+
async function datasetToolsListed(runtime: MCPServerRuntime, bridge: McpDataBridge, o: Opts = {}): Promise<string[]> {
105+
const json = await rpc(runtime, bridge, { jsonrpc: '2.0', id: 2, method: 'tools/list' }, o);
106+
return ((json.result?.tools ?? []) as Array<{ name: string }>)
107+
.map((t) => t.name)
108+
.filter((n) => n === LIST_DATASETS_TOOL_NAME || n === QUERY_DATASET_TOOL_NAME)
109+
.sort();
110+
}
111+
112+
/** The rule names both dataset tools; neither name appears anywhere else in the open server's text. */
113+
const carriesRule = (text: string) => text.includes(LIST_DATASETS_TOOL_NAME) && text.includes(QUERY_DATASET_TOOL_NAME);
114+
const namesNoDatasetTool = (text: string) => !text.includes(LIST_DATASETS_TOOL_NAME) && !text.includes(QUERY_DATASET_TOOL_NAME);
115+
116+
describe('[#34686] initialize instructions — the selection rule follows the dataset tools', () => {
117+
let runtime: MCPServerRuntime;
118+
beforeEach(() => {
119+
runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
120+
});
121+
122+
it('carries the rule where both dataset tools register: an API key / session and a data:read token', async () => {
123+
for (const o of [{}, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }] as Opts[]) {
124+
expect(await datasetToolsListed(runtime, makeBridge(), o)).toEqual([LIST_DATASETS_TOOL_NAME, QUERY_DATASET_TOOL_NAME].sort());
125+
expect(carriesRule(await instructionsOf(runtime, makeBridge(), o))).toBe(true);
126+
}
127+
});
128+
129+
it('a grant without data:read gets neither dataset sentence (and lists neither tool)', async () => {
130+
for (const grantedScopes of [[MCP_OAUTH_SCOPE_DATA_WRITE], [MCP_OAUTH_SCOPE_METADATA_WRITE]]) {
131+
expect(await datasetToolsListed(runtime, makeBridge(), { grantedScopes })).toEqual([]);
132+
expect(namesNoDatasetTool(await instructionsOf(runtime, makeBridge(), { grantedScopes }))).toBe(true);
133+
}
134+
});
135+
136+
it('a bridge without the dataset pair gets no rule, whatever the grant', async () => {
137+
for (const without of [['listDatasets'], ['queryDataset'], ['datasetToolDefinitions']] as DatasetMember[][]) {
138+
expect(await datasetToolsListed(runtime, makeBridge(without))).toEqual([]);
139+
expect(namesNoDatasetTool(await instructionsOf(runtime, makeBridge(without)))).toBe(true);
140+
}
141+
});
142+
143+
it('a bridge that registers only one of the pair gets no rule: the rule names both', async () => {
144+
const listOnly = makeBridge([], DEFINITIONS.filter((d) => d.name === LIST_DATASETS_TOOL_NAME));
145+
expect(await datasetToolsListed(runtime, listOnly)).toEqual([LIST_DATASETS_TOOL_NAME]);
146+
expect(namesNoDatasetTool(await instructionsOf(runtime, listOnly))).toBe(true);
147+
});
148+
});
149+
150+
describe('[#34686] initialize instructions — the skills install line', () => {
151+
let runtime: MCPServerRuntime;
152+
beforeEach(() => {
153+
// The operator's serverInfo.version is not the skills version: a distinct value proves which one is read.
154+
runtime = new MCPServerRuntime({ name: 't', version: '0.0.1-operator' });
155+
});
156+
157+
it('names @objectstack/skills at this package\'s own version, for every grant', async () => {
158+
expect(OWN_VERSION).toMatch(/^\d+\.\d+\.\d+/);
159+
for (const o of [{}, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] }] as Opts[]) {
160+
const text = await instructionsOf(runtime, makeBridge(), o);
161+
expect(text).toContain(`Published skills: @objectstack/skills ${OWN_VERSION}`);
162+
expect(text).toContain(`@objectstack/skills@${OWN_VERSION}`);
163+
expect(text).not.toContain('0.0.1-operator');
164+
}
165+
});
166+
});
167+
168+
describe('[#34686] initialize instructions — host and configured texts are left whole', () => {
169+
const HOST = 'Host text for a connection that can build.';
170+
const DATA_ONLY = 'Host text for a connection that cannot build.';
171+
const CONFIGURED = 'Configured server-wide instructions.';
172+
173+
it('the host\'s per-request texts answer exactly as injected, with no rule or install line appended', async () => {
174+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
175+
expect(
176+
await instructionsOf(runtime, makeBridge(), {
177+
grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_METADATA_WRITE],
178+
authoring: { instructions: HOST },
179+
}),
180+
).toBe(HOST);
181+
expect(
182+
await instructionsOf(runtime, makeBridge(), {
183+
grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ],
184+
authoring: { dataOnlyInstructions: DATA_ONLY },
185+
}),
186+
).toBe(DATA_ONLY);
187+
});
188+
189+
it('a runtime configured with instructions answers them exactly, dataset tools served or not', async () => {
190+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0', instructions: CONFIGURED });
191+
expect(await datasetToolsListed(runtime, makeBridge())).toHaveLength(2);
192+
expect(await instructionsOf(runtime, makeBridge())).toBe(CONFIGURED);
193+
});
194+
});

0 commit comments

Comments
 (0)