Skip to content

Commit 8a3315a

Browse files
feat(service-knowledge): search_knowledge takes scope, granularity and groupBy (#37393)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8HJYax4fkqGNdUaezCWuEvn)_ Fixes #37311 Clause-②: yes Metadata-protocol: none ## 维护者速读 - 外部 AI(MCP)和应用内对话用的知识检索工具多了三个参数:只在指定的几条记录里搜(比如一份制度),按记录返回而不是按片段,按某个字段分组返回(「哪几份制度」);每条结果还带上所在章节标题和分组的值。 - 属于知识检索平台化专题(阶段三第 12 行),让制度问询可以先找「哪几份制度」,再在其中一份里细查。 - 出错只会让这三个新参数被拒或答空,已有的检索调用照旧;回答里从不透露被权限或范围过滤掉的条数,也不暴露隐藏的知识源;可直接撤回。 - 无。 ## What changes ADR-0161 K9, rule 2: the one `search_knowledge` definition (`packages/services/service-knowledge/src/knowledge-tools.ts`) gains `scope`, `granularity` and `groupBy`, the options `IKnowledgeService.search` already reads (#37103 for the last two, #37308 for the first). No transport adds or edits an argument: the MCP HTTP door and stdio register the definition as handed over, and the hosted agent registers the same one through objectstack-ai/cloud#4933. **The definition.** `SEARCH_KNOWLEDGE_PARAMETERS` declares: - `scope`: `minItems: 1`, `maxItems: 10` entries of `{ object, ids }` (`additionalProperties: false`), `ids` `minItems: 1`, `maxItems: 500`; every name and id `minLength: 1`, `maxLength: 255`. - `granularity`: `enum: ['chunk', 'record']`. - `groupBy`: `minLength: 1`, `maxLength: 255`. The description tells the model when to use each one, and names the two new hit members, `groupValue` (the stored value: a string, a number or a list) and `headingPath`. Under `groupBy`, an object source that does not list the field answers nothing, and a `file` / `http` source answers one hit per document with no `groupValue`. `topK`'s text now says it counts records or groups in those modes. New exports: `SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES` (10) and `SEARCH_KNOWLEDGE_MAX_SCOPE_IDS` (500), read from the service's own `SEARCH_SCOPE_MAX_ENTRIES` / `SEARCH_SCOPE_MAX_IDS`, and `SEARCH_KNOWLEDGE_MAX_NAME_LENGTH` (255), with the types `SearchKnowledgeScopeEntry` and `SearchKnowledgeGranularity`. **The door (`parseInput`).** The executor refuses each malformed value `VALIDATION_ERROR` (400) before the service is asked, and the message names the argument. Over MCP, a shape the schema states (an empty or over-long `scope`, a string over 255 characters, an unknown `granularity` or key) is refused first by the SDK's input validation: `-32602`, naming the argument, with no ADR-0112 code. The coded refusal answers what the schema cannot state (a NUL, `groupBy` with `"chunk"`), and everything the in-product agent sends. Carried from the #37308 reviews: - An id, object name or field name holding a NUL character is refused. So is one over 255 characters. The bound is the length the platform stores a record id and an object name in (`sys_recycle_bin.record_id` / `object_name`, `maxLength: 255`). - A refusal that repeats a caller's string quotes it with `JSON.stringify`, so a control character reads as its escape, and cuts it to 64 characters. It lists at most five strings, then "and N more". At the executor, this also covers the two refusals that existed before this PR: an unknown key, and an unknown `sourceIds` entry. Over MCP, the SDK's refusal of an unknown key repeats it as sent; that path predates this PR and the seat files it separately. - `groupBy` with `granularity: 'chunk'` is refused at the door, naming `groupBy`. The service refuses it too. **The executor.** It hands `scope`, `granularity` and `groupBy` to `searchWithRefusals` as its options of the same names. `aiExposed` stays enforced here (K9 rule 3). The service is asked only about exposed sources, so a `scope` entry or `groupBy` field that only a withheld source would answer gets exactly the answer one no source answers: no hits. **The answer.** `hitOf` stays a whitelist and gains two members: - `headingPath`, where the passage has one. - `groupValue`: under `groupBy`, `metadata[groupBy]`, and only for an object source that lists that field in `metadataFields`. Source admission holds every listed field queryable by the caller. `chunkId`, `docHash` and `metadata` never reach the answer. Nothing in the answer counts hits that the permission re-check or the scope removed (K9 rule 6). **Docs.** `content/docs/ai/knowledge-rag.mdx` gains a section on the `search_knowledge` tool: the six arguments, the hit's members, where the tool is stricter than the service, and the withheld-source rule. **Surface widened** (claim amended by the seat at 2026-11-26 01:15Z, for this test only). `packages/mcp` now dev-depends on `@objectstack/service-knowledge`, with one source alias in `packages/mcp/vitest.config.ts` and its importer line in `pnpm-lock.yaml`. This is the same arrangement `service-record-context` already has. The transport test needs the REAL definition: `registerKnowledgeTools` silently registers nothing when `z.fromJSONSchema` cannot convert a definition (`mcp-http-tools.ts`, `registerKnowledgeTools`), and the nested `scope` schema is the shape that could trip that conversion. It converts whole: no change to the definition's shape was needed. ## Tests - `service-knowledge` `knowledge-tools.test.ts` (56 cases, 22 of them new refusals) checks the following against the real `KnowledgeService`: - the declared bounds; - the description naming each argument and member; - every malformed shape refused, naming its argument, with no raw NUL and no over-long string in the message; - message quoting and cutting, and a short string holding a quote, a newline and a NUL repeated only as its JSON escape; - the three options reaching `searchWithRefusals` unchanged; - record mode answering one hit per record, `groupBy` one per group with its `groupValue`, and `scope` only the named records; - `groupBy` over a `file` source whose hit carries `metadata[groupBy]`: one hit per document, no `groupValue` (the guard in `hitOf`); - the hit whitelist, read as a whole object (`headingPath` and `groupValue` present; `docHash`, `chunkId` and `metadata` absent); - a whole answer, read with `toEqual`, carrying no count when the re-check and the scope both removed hits; - the withheld-source answers: a `scope` and a `groupBy` that only a withheld source would answer, compared with an absent object and an absent field. The answers are identical, the withheld adapter is never asked, and the adapters asked are the same. - `mcp` `mcp-knowledge-tools.test.ts` (18 cases, 6 of them new) runs the real definition and executor behind a stdio bridge, over HTTP and over stdio: - `tools/list` returns byte-identical `search_knowledge` definitions with the three arguments. Stdio is read raw off the transport, because the SDK client's result parse re-orders an input schema's keys. The listed input schema, less `$schema`, equals the definition's `parameters` by `toEqual`, so any transport-side schema edit is red. - `granularity: 'record'`, `groupBy` and `scope` each answer the same text on both doors, with the expected hits. - A scope past its bound is refused by the SDK's schema check before the bridge is called: `isError`, `-32602`, naming `scope`, the same text on both doors. - A NUL in a scope id reaches the executor and answers its coded `VALIDATION_ERROR` naming `scope`, the same text on both doors. <details><summary>Local runs at 44e00dc, 1ebae53 and 4a2b34e</summary> - At `44e00dcf` (the L1 round): `knowledge-tools.test.ts` 56/56; `mcp-knowledge-tools.test.ts` 18/18; both packages' `typecheck` green; `eslint --no-inline-config` on the three touched source/test files clean; `check-nul-bytes` OK. Ablations through `scripts/ablation-replace.mjs`, each restored blob == HEAD: the `groupValue` guard removed, 1 red (S2); `JSON.stringify` replaced by plain quotes in `quoted`, 1 red (S3); `registerKnowledgeTools` rewriting `groupBy`'s schema before conversion, 2 red over MCP (S4). - At `1ebae539`: `knowledge-tools.test.ts` 54/54; `mcp-knowledge-tools.test.ts` 17/17; `pnpm --filter @objectstack/service-knowledge --filter @objectstack/mcp typecheck` green. `1ebae539` only bounds the two new engine doubles by the caller's `limit` (CI's `check:objectql-double-limit` caught the MCP one as limit-blind at `4a2b34e8`; it is green locally now). - At `4a2b34e8`: `pnpm --filter @objectstack/service-knowledge test`: 13 files, 414/414; `pnpm --filter @objectstack/mcp exec vitest run`: 85 files, 1520/1520. - `node scripts/check-nul-bytes.mjs`: OK. - Ablations at `4a2b34e8`, run in a scratch worktree through `scripts/ablation-replace.mjs` (dependencies' `dist/` linked in), one change each. Every one was restored with blob == HEAD and an empty `git diff HEAD`. - `scope` not handed to the service: 4 red in `knowledge-tools.test.ts`; 1 red over MCP (scope on both doors). - `granularity` not handed over: 1 red over MCP. `groupBy` not handed over: 1 red over MCP. - `docHash` added to `hitOf`: 2 red (the whitelist, the whole answer). - `groupValue` never set: 2 red. - The NUL check removed: 3 red (object, id, `groupBy`). - The `aiExposed` filter removed: 9 red. - The 64-character cut removed: 1 red. </details> ## Acceptance notes 1. **The door is stricter than the service, deliberately.** An empty `scope` and an entry with no ids are refused at the tool, where `IKnowledgeService.search` answers them with no hits. This matches the tool's own rule for an empty `sourceIds`: a call that names nothing would answer no passage, which the description tells the model to report as "nothing matched". The service keeps its row-11 behaviour for its own callers. The reviewer should confirm this reading of "bounded as row 11 bounds it" (card item 1). 2. **`groupValue` is the stored value, unparsed.** It is a string for a text or lookup field and can be a number, a boolean or a list (a `multiple` lookup). It is typed `unknown` and the description does not promise a type. A `file` / `http` hit under `groupBy` carries none, because it stands for its document. 3. **`sourceIds` items gain no length bound.** Only the refusal message cuts them. The carried rule names the scope's ids, and adding `maxLength` to `sourceIds` would change an existing argument's schema. 4. The doc section is new. The page had no tool section before, only the in-product callout. 5. L1 round 1 (PR comment 7180869252): M1 and S2 to S5 are done as listed above; nits 6, 7 and 9 are done; nit 8 (format characters, UTF-16 against code points) is not taken, since both directions are the stricter or harmless one. ## Verification Read first, by risk: 1. `knowledge-tools.ts`, `parseScope` / `isName`, and the executor's `searchOpts`. 2. `knowledge-tools.ts`, `hitOf`: the whitelist and the `groupValue` guard. 3. `mcp-knowledge-tools.test.ts`, the last `describe` (the real definition on both doors). Two-minute check: `pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-knowledge-tools.test.ts` → 18 passed, including "tools/list over HTTP and over stdio answer byte-identical definitions, carrying scope, granularity and groupBy". Gates. The local derived set: `dispatch-gates --commands`, 114 commands, reconciled with `--ran`. 111 exited 0. 3 exited 3, PREREQUISITE NOT MET, and are NOT MEASURED locally; CI runs them: - `check-plugin-teardown-shape --self-test`: the clone is shallow. - `check:skill-examples` (spec): the client `dist/` is not built. - `check:dual-build-cjs-loads`: a package has no `dist/`. Commands 1 to 60 ran on the `4a2b34e8` tree, and 61 to 114 on `1ebae539`. The only change between the two is the test doubles. CI at `1ebae539`: 64 success, 11 expected skips, 0 failed, `mergeable_state` clean (the seat's reading). CI at `44e00dcf`: to be read at hand-back. The local derived set above was not re-run for `44e00dcf`: its delta is one description sentence, two constants now read from the service, test cases and prose. The docs drift check names 20 hand-written pages. I re-read the six that name `search_knowledge`, and none of them is falsified. `connect-mcp.mdx`'s tool row does not mention the three new arguments, but it is still true as written. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbXPpBL56eaDCJ6MFm4 --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbXPpBL56eaDCJ6MFm4)_ <!-- signed: repo:cloud#1 · os-warren · session_01JQwxbXPpBL56eaDCJ6MFm4 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 40570d6 commit 8a3315a

8 files changed

Lines changed: 778 additions & 17 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
feat(service-knowledge): `search_knowledge` takes `scope`, `granularity` and `groupBy`
6+
7+
Clause-②: yes
8+
Metadata-protocol: none
9+
10+
ADR-0161 K9, rule 2 (#37311): the one `search_knowledge` definition gains the three arguments its knowledge service already reads, so an MCP client (HTTP and stdio) and the in-product agent are offered them alike. No transport adds or edits an argument.
11+
12+
- `granularity: "record"` answers one hit per record, its best passage; `groupBy` answers one hit per value of a field the source lists in `metadataFields`, the value carried as the hit's `groupValue` (as the index stores it); an object source that does not list the field answers nothing for that search, and a `file` / `http` source answers one hit per document with no `groupValue`; `scope` searches only inside the named records, or the records linking to the named parents. Each is handed to `IKnowledgeService.search` as its option of the same name.
13+
- A hit also carries `headingPath` where its passage has headings. The hit stays a whitelist: no `chunkId`, `docHash` or `metadata`.
14+
- The executor refuses each malformed argument `VALIDATION_ERROR` (400) naming it; over MCP, a shape the definition's schema states is refused first by the SDK's input validation (`-32602`). The tool is stricter than the service: an empty `scope` or an entry with no ids is refused (as an empty `sourceIds` is), and an object name, record id or field name over 255 characters or holding a NUL character is refused. A refusal quotes a caller's string and cuts it to 64 characters, and lists at most five.
15+
- The executor searches only `aiExposed` sources, so a `scope` entry or `groupBy` field only a withheld source would answer gets the same empty answer as one no source answers. The answer carries no count of hits the permission re-check or the scope removed.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,29 @@ const hits = await knowledge.search('notice period', {
113113

114114
An adapter that reads the scope filters before it ranks, so the `topK` hits all come from inside the scope. Whatever the adapter does, the service drops any hit outside the scope, so an adapter that ignores it may answer fewer than `topK`. A source the scope does not reach is not searched, and `scope: []` answers nothing, never everything. A scope narrows what is searched; each hit is still re-checked against the caller, so it never shows a record the caller could not read. Bounds, the parent-link rules and what an adapter must do are in [the protocol's record scope](/docs/protocol/knowledge#record-scope).
115115

116+
## The `search_knowledge` tool
117+
118+
An AI client searches through one tool, `search_knowledge`, defined once by the knowledge service. The MCP door (HTTP and stdio) and the in-product agent serve that one definition unchanged, so every client is offered the same arguments and gets the same answer. It searches only sources whose `aiExposed` is not `false`, and reads as the person asking.
119+
120+
| Argument | What it does |
121+
|:--|:--|
122+
| `query` | What to look for, in plain words. Required. |
123+
| `sourceIds` | Only these sources, by the ids every answer lists in `sources`. Omit to search them all. |
124+
| `topK` | At most this many hits, 1 to 20, default 5. Counts records or groups in the two modes below. |
125+
| `granularity` | `"chunk"` (the default): one hit per passage. `"record"`: one hit per record, its best passage. |
126+
| `groupBy` | One hit per value of a field the source lists in `metadataFields`, such as `policy`: "which policies", not "which clauses". Implies `"record"`; refused with `"chunk"`. A source of indexed records that does not list the field answers nothing for that call; a file or web source still answers, one hit per document, with no `groupValue`. |
127+
| `scope` | Only inside these records: a list of `{ object, ids }`, as `KnowledgeSearchOptions.scope` reads it above. At most 10 entries of at most 500 ids. |
128+
129+
Each hit carries `sourceId`, `documentId`, `title`, `snippet`, `score`, and for an indexed record `record: { object, id }`, which the record tools read. It also carries `headingPath`, the headings its passage sits under, where the document has headings, and under `groupBy` the group's value as `groupValue`: the value as the index stores it (a string, a number, or a list for a multi-value lookup), absent on a hit of a file or web source. The answer also lists the searchable `sources`, and in `refused` any source that could not be searched.
130+
131+
The tool is stricter than the service in a few places, so that a mistake is reported instead of being answered as "nothing matched":
132+
133+
- An empty `scope`, an entry with no ids, and an empty `sourceIds` are refused, not answered with no hits.
134+
- An object name, record id or field name over 255 characters, or one holding a NUL character, is refused.
135+
- Each malformed argument is refused `VALIDATION_ERROR` (400), naming the argument. Over MCP, a shape the tool's schema states (an empty or over-long `scope`, a string over 255 characters, an unknown `granularity` or key) is refused first by the MCP input-validation check, as error `-32602` naming the argument, without that code. The coded refusal answers what the schema cannot state, such as a NUL character or `groupBy` with `"chunk"`, and every malformed argument the in-product agent sends.
136+
137+
The answer never says how many hits the permission re-check or the scope removed. A `scope` entry or `groupBy` field that only a withheld source would answer gets the same empty answer as one that no source answers, so the answer never shows that a withheld source exists.
138+
116139
## What you get for free
117140

118141
- **Permission-aware retrieval.** Every hit with a `sourceRecordId` is re-checked against the caller's `ExecutionContext` via `IDataEngine` — the same RLS that gates plain ObjectQL queries. A salesperson asking "find proposals about ACME" only sees the proposals they could already read directly. Before a source is searched, the caller's field-level read rules and the object's API exposure are asked too: a source serving a field the caller may not query is not searched for them (see [the protocol's source admission](/docs/protocol/knowledge#source-admission-exposure-and-field-level-rules)). File / HTTP hits pass through (ACL is the adapter's problem).

‎packages/mcp/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
"@objectstack/metadata-protocol": "workspace:*",
4444
"@objectstack/objectql": "workspace:*",
4545
"@objectstack/service-analytics": "workspace:*",
46+
"@objectstack/service-knowledge": "workspace:*",
4647
"@objectstack/service-record-context": "workspace:*",
4748
"@types/node": "^26.6.5",
4849
"typescript": "^6.0.3",

‎packages/mcp/src/mcp-knowledge-tools.test.ts‎

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,24 @@
1414
* in `prompts/list` where the tool is served and withheld, with a debug line
1515
* naming the tool, where it is not; and the stdio bridge runs each call as the
1616
* principal it resolves for that call.
17+
*
18+
* And over the knowledge service's REAL definition and executor (ADR-0161 K9,
19+
* rules 1, 2 and 4): `tools/list` over HTTP and over stdio answer the same
20+
* `search_knowledge` definition, byte for byte, carrying `scope`,
21+
* `granularity` and `groupBy` (the definition converts to the SDK's input
22+
* schema whole: a definition that did not would register no tool at all); and
23+
* a call over either door answers one hit per record, one per group with its
24+
* value, and only the scoped records' hits.
1725
*/
1826

1927
import { describe, it, expect, vi } from 'vitest';
28+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
29+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
30+
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
2031
import { MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE } from '@objectstack/spec/ai';
32+
import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai';
33+
import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts';
34+
import { KnowledgeService, getKnowledgeToolDefinitions, recordToDocument } from '@objectstack/service-knowledge';
2135
import { MCPServerRuntime } from './mcp-server-runtime.js';
2236
import { SEARCH_KNOWLEDGE_TOOL_NAME, type McpDataBridge } from './mcp-http-tools.js';
2337
import type { McpSkillBridge } from './skill-prompts.js';
@@ -235,3 +249,174 @@ describe('[ADR-0149 D2] search_knowledge on the stdio bridge', () => {
235249
expect(searchKnowledge).toHaveBeenCalledWith({ query: 'refund' }, principal);
236250
});
237251
});
252+
253+
describe('[ADR-0161 K9] search_knowledge over the real definition — every transport serves it unchanged', () => {
254+
type Row = Record<string, unknown> & { id: string };
255+
const CLAUSES: Row[] = [
256+
{ id: 'c1', body: 'annual leave', policy: 'P_leave' },
257+
{ id: 'c2', body: 'sick leave', policy: 'P_leave' },
258+
{ id: 'c3', body: 'travel', policy: 'P_travel' },
259+
];
260+
const SOURCE: KnowledgeSource = {
261+
id: 'clauses',
262+
label: 'Clauses',
263+
adapter: 'memory',
264+
source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: ['policy'] } as ObjectKnowledgeSource,
265+
};
266+
267+
function indexHit(row: Row, n: number, score: number): KnowledgeHit {
268+
const doc = recordToDocument(SOURCE, SOURCE.source as ObjectKnowledgeSource, row);
269+
return {
270+
chunkId: `${doc.id}#${n}`, documentId: doc.id, sourceId: SOURCE.id, sourceRecordId: row.id,
271+
score, snippet: `${row.body as string} (${n})`, metadata: doc.metadata, docHash: doc.docHash,
272+
};
273+
}
274+
275+
/** A stdio bridge over a real knowledge service: one clause source, an adapter ranking the index's hits, an engine over CLAUSES. */
276+
function realBridge(): McpDataBridge {
277+
const corpus = [indexHit(CLAUSES[0], 0, 0.9), indexHit(CLAUSES[0], 1, 0.8), indexHit(CLAUSES[1], 0, 0.7), indexHit(CLAUSES[2], 0, 0.6)];
278+
const adapter = {
279+
id: 'memory',
280+
upsert: async () => undefined,
281+
delete: async () => undefined,
282+
search: async (_q: string, opts: { topK: number }) => corpus.slice(0, opts.topK),
283+
} as unknown as IKnowledgeAdapter;
284+
const matches = (row: Row, where: Record<string, unknown> = {}): boolean =>
285+
Object.entries(where).every(([k, v]) => {
286+
if (k === '$and') return (v as Record<string, unknown>[]).every((w) => matches(row, w));
287+
if (v !== null && typeof v === 'object') return (v as { $in: string[] }).$in.includes(row[k] as string);
288+
return row[k] === v;
289+
});
290+
const engine = {
291+
find: async (_object: string, q: { where?: Record<string, unknown>; fields?: string[]; limit?: number }) => {
292+
const rows = CLAUSES.filter((r) => matches(r, q.where));
293+
const page = typeof q.limit === 'number' ? rows.slice(0, q.limit) : rows;
294+
return page.map((r) => (q.fields ? Object.fromEntries(q.fields.filter((f) => f in r).map((f) => [f, r[f]])) : { ...r }));
295+
},
296+
} as unknown as IDataEngine;
297+
const service = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined, debug: () => undefined } });
298+
service.registerAdapter('memory', adapter);
299+
service.registerSource(SOURCE);
300+
return createStdioDataBridge({
301+
engine: {} as never,
302+
metadataService: { list: async () => [], getObject: async () => undefined } as never,
303+
resolvePrincipal: async () => ({ userId: 'u_key_owner', isSystem: false }) as never,
304+
knowledgeTools: service,
305+
});
306+
}
307+
308+
async function overStdio<T>(bridge: McpDataBridge, use: (client: Client) => Promise<T>): Promise<T> {
309+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
310+
runtime.bridgeDataTools(bridge);
311+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
312+
await runtime.server.connect(serverSide);
313+
const client = new Client({ name: 't', version: '1.0.0' });
314+
await client.connect(clientSide);
315+
try {
316+
return await use(client);
317+
} finally {
318+
await client.close();
319+
}
320+
}
321+
322+
/**
323+
* One JSON-RPC request over stdio, answered as the wire carries it: read off
324+
* the transport, not through the SDK client, whose result parse re-orders
325+
* an input schema's keys and would make a byte comparison read the client.
326+
*/
327+
async function rawOverStdio(bridge: McpDataBridge, message: JSONRPCMessage & { id: number }) {
328+
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
329+
runtime.bridgeDataTools(bridge);
330+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
331+
await runtime.server.connect(serverSide);
332+
const reply = new Promise<any>((resolve) => {
333+
clientSide.onmessage = (m) => {
334+
if ((m as { id?: number }).id === message.id) resolve(m);
335+
};
336+
});
337+
await clientSide.start();
338+
await clientSide.send(message);
339+
try {
340+
return await reply;
341+
} finally {
342+
await clientSide.close();
343+
}
344+
}
345+
346+
async function callBoth(args: Record<string, unknown>) {
347+
const http = (await callTool(realBridge(), args)).result!;
348+
const stdio = (await overStdio(realBridge(), (c) => c.callTool({ name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args }))) as {
349+
content: Array<{ text: string }>;
350+
isError?: boolean;
351+
};
352+
expect(http.isError).toBeFalsy();
353+
expect(stdio.isError).toBeFalsy();
354+
expect(stdio.content[0].text).toBe(http.content[0].text);
355+
return JSON.parse(http.content[0].text) as { hits: Array<{ record?: { id: string }; groupValue?: unknown }> };
356+
}
357+
358+
it('tools/list over HTTP and over stdio answer byte-identical definitions, carrying scope, granularity and groupBy', async () => {
359+
const http = knowledgeTool(await listTools(realBridge()));
360+
const stdio = knowledgeTool((await rawOverStdio(realBridge(), { jsonrpc: '2.0', id: 1, method: 'tools/list' })).result.tools);
361+
expect(http).toBeDefined();
362+
expect(JSON.stringify(stdio)).toBe(JSON.stringify(http));
363+
const [definition] = getKnowledgeToolDefinitions();
364+
expect(http!.description).toBe(definition.description);
365+
// The listed schema IS the definition's: no transport-side edit of a bound, a description or a key.
366+
const { $schema: _dialect, ...listed } = http!.inputSchema;
367+
expect(listed).toEqual(definition.parameters);
368+
expect(Object.keys(http!.inputSchema.properties).sort()).toEqual(['granularity', 'groupBy', 'query', 'scope', 'sourceIds', 'topK']);
369+
// The nested scope schema reaches the client whole, bounds included.
370+
expect(http!.inputSchema.properties.scope).toMatchObject({
371+
type: 'array', minItems: 1, maxItems: 10,
372+
items: { type: 'object', required: ['object', 'ids'], additionalProperties: false, properties: { ids: { maxItems: 500 } } },
373+
});
374+
expect(http!.inputSchema.properties.granularity.enum).toEqual(['chunk', 'record']);
375+
});
376+
377+
it("granularity 'record' answers one hit per record over both doors", async () => {
378+
const answer = await callBoth({ query: 'leave', granularity: 'record' });
379+
expect(answer.hits.map((h) => h.record?.id)).toEqual(['c1', 'c2', 'c3']);
380+
});
381+
382+
it('groupBy answers one hit per group, with its value, over both doors', async () => {
383+
const answer = await callBoth({ query: 'leave', groupBy: 'policy' });
384+
expect(answer.hits.map((h) => [h.record?.id, h.groupValue])).toEqual([['c1', 'P_leave'], ['c3', 'P_travel']]);
385+
});
386+
387+
it('scope answers only the named records over both doors', async () => {
388+
const answer = await callBoth({ query: 'leave', scope: [{ object: 'clause', ids: ['c3'] }] });
389+
expect(answer.hits.map((h) => h.record?.id)).toEqual(['c3']);
390+
});
391+
392+
it('a scope past its bound is refused by the schema check before the bridge is asked, with the same answer on both doors', async () => {
393+
const args = { query: 'q', scope: Array.from({ length: 11 }, () => ({ object: 'clause', ids: ['c1'] })) };
394+
const bridge = realBridge();
395+
const search = vi.spyOn(bridge, 'searchKnowledge');
396+
const http = (await callTool(bridge, args)).result!;
397+
const stdio = (await rawOverStdio(realBridge(), {
398+
jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args },
399+
})).result as { content: Array<{ text: string }>; isError?: boolean };
400+
expect(search).not.toHaveBeenCalled();
401+
// The SDK's input-validation refusal (-32602), naming the argument: a schema-stated shape never reaches the
402+
// executor over MCP, so it carries no ADR-0112 code. The coded VALIDATION_ERROR is the executor's own.
403+
expect(http.isError).toBe(true);
404+
expect(http.content[0].text).toContain('-32602');
405+
expect(http.content[0].text).toContain('scope');
406+
expect(stdio.isError).toBe(true);
407+
expect(stdio.content[0].text).toBe(http.content[0].text);
408+
});
409+
410+
it('a shape the schema cannot state (a NUL in an id) reaches the executor and answers its coded VALIDATION_ERROR on both doors', async () => {
411+
const args = { query: 'q', scope: [{ object: 'clause', ids: ['c1\u0000x'] }] };
412+
const http = (await callTool(realBridge(), args)).result!;
413+
const stdio = (await rawOverStdio(realBridge(), {
414+
jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args },
415+
})).result as { content: Array<{ text: string }>; isError?: boolean };
416+
expect(http.isError).toBe(true);
417+
expect(JSON.parse(http.content[0].text).error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
418+
expect(http.content[0].text).toContain('`scope`');
419+
expect(stdio.isError).toBe(true);
420+
expect(stdio.content[0].text).toBe(http.content[0].text);
421+
});
422+
});

‎packages/mcp/vitest.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ export default defineConfig({
8787
{ find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../drivers/driver-sql/src/index.ts') },
8888
// [ADR-0160] The record-context executor, so `get_record_context`'s transport parity runs the real one.
8989
{ find: /^@objectstack\/service-record-context$/, replacement: path.resolve(__dirname, '../services/service-record-context/src/index.ts') },
90+
// [ADR-0161 K9] The knowledge tool's one definition and executor, so `search_knowledge`'s transport parity runs the real ones.
91+
{ find: /^@objectstack\/service-knowledge$/, replacement: path.resolve(__dirname, '../services/service-knowledge/src/index.ts') },
9092
],
9193
},
9294
});

0 commit comments

Comments
 (0)