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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/37311-search-knowledge-scope-granularity-groupby.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/service-knowledge': patch
---

feat(service-knowledge): `search_knowledge` takes `scope`, `granularity` and `groupBy`

Clause-②: yes
Metadata-protocol: none

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.

- `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.
- A hit also carries `headingPath` where its passage has headings. The hit stays a whitelist: no `chunkId`, `docHash` or `metadata`.
- 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.
- 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.
23 changes: 23 additions & 0 deletions content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,29 @@ const hits = await knowledge.search('notice period', {

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).

## The `search_knowledge` tool

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.

| Argument | What it does |
|:--|:--|
| `query` | What to look for, in plain words. Required. |
| `sourceIds` | Only these sources, by the ids every answer lists in `sources`. Omit to search them all. |
| `topK` | At most this many hits, 1 to 20, default 5. Counts records or groups in the two modes below. |
| `granularity` | `"chunk"` (the default): one hit per passage. `"record"`: one hit per record, its best passage. |
| `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`. |
| `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. |

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.

The tool is stricter than the service in a few places, so that a mistake is reported instead of being answered as "nothing matched":

- An empty `scope`, an entry with no ids, and an empty `sourceIds` are refused, not answered with no hits.
- An object name, record id or field name over 255 characters, or one holding a NUL character, is refused.
- 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.

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.

## What you get for free

- **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).
Expand Down
1 change: 1 addition & 0 deletions packages/mcp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"@objectstack/metadata-protocol": "workspace:*",
"@objectstack/objectql": "workspace:*",
"@objectstack/service-analytics": "workspace:*",
"@objectstack/service-knowledge": "workspace:*",
"@objectstack/service-record-context": "workspace:*",
"@types/node": "^26.6.5",
"typescript": "^6.0.3",
Expand Down
185 changes: 185 additions & 0 deletions packages/mcp/src/mcp-knowledge-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,24 @@
* in `prompts/list` where the tool is served and withheld, with a debug line
* naming the tool, where it is not; and the stdio bridge runs each call as the
* principal it resolves for that call.
*
* And over the knowledge service's REAL definition and executor (ADR-0161 K9,
* rules 1, 2 and 4): `tools/list` over HTTP and over stdio answer the same
* `search_knowledge` definition, byte for byte, carrying `scope`,
* `granularity` and `groupBy` (the definition converts to the SDK's input
* schema whole: a definition that did not would register no tool at all); and
* a call over either door answers one hit per record, one per group with its
* value, and only the scoped records' hits.
*/

import { describe, it, expect, vi } from 'vitest';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
import { MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE } from '@objectstack/spec/ai';
import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai';
import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts';
import { KnowledgeService, getKnowledgeToolDefinitions, recordToDocument } from '@objectstack/service-knowledge';
import { MCPServerRuntime } from './mcp-server-runtime.js';
import { SEARCH_KNOWLEDGE_TOOL_NAME, type McpDataBridge } from './mcp-http-tools.js';
import type { McpSkillBridge } from './skill-prompts.js';
Expand Down Expand Up @@ -235,3 +249,174 @@ describe('[ADR-0149 D2] search_knowledge on the stdio bridge', () => {
expect(searchKnowledge).toHaveBeenCalledWith({ query: 'refund' }, principal);
});
});

describe('[ADR-0161 K9] search_knowledge over the real definition — every transport serves it unchanged', () => {
type Row = Record<string, unknown> & { id: string };
const CLAUSES: Row[] = [
{ id: 'c1', body: 'annual leave', policy: 'P_leave' },
{ id: 'c2', body: 'sick leave', policy: 'P_leave' },
{ id: 'c3', body: 'travel', policy: 'P_travel' },
];
const SOURCE: KnowledgeSource = {
id: 'clauses',
label: 'Clauses',
adapter: 'memory',
source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: ['policy'] } as ObjectKnowledgeSource,
};

function indexHit(row: Row, n: number, score: number): KnowledgeHit {
const doc = recordToDocument(SOURCE, SOURCE.source as ObjectKnowledgeSource, row);
return {
chunkId: `${doc.id}#${n}`, documentId: doc.id, sourceId: SOURCE.id, sourceRecordId: row.id,
score, snippet: `${row.body as string} (${n})`, metadata: doc.metadata, docHash: doc.docHash,
};
}

/** A stdio bridge over a real knowledge service: one clause source, an adapter ranking the index's hits, an engine over CLAUSES. */
function realBridge(): McpDataBridge {
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)];
const adapter = {
id: 'memory',
upsert: async () => undefined,
delete: async () => undefined,
search: async (_q: string, opts: { topK: number }) => corpus.slice(0, opts.topK),
} as unknown as IKnowledgeAdapter;
const matches = (row: Row, where: Record<string, unknown> = {}): boolean =>
Object.entries(where).every(([k, v]) => {
if (k === '$and') return (v as Record<string, unknown>[]).every((w) => matches(row, w));
if (v !== null && typeof v === 'object') return (v as { $in: string[] }).$in.includes(row[k] as string);
return row[k] === v;
});
const engine = {
find: async (_object: string, q: { where?: Record<string, unknown>; fields?: string[]; limit?: number }) => {
const rows = CLAUSES.filter((r) => matches(r, q.where));
const page = typeof q.limit === 'number' ? rows.slice(0, q.limit) : rows;
return page.map((r) => (q.fields ? Object.fromEntries(q.fields.filter((f) => f in r).map((f) => [f, r[f]])) : { ...r }));
},
} as unknown as IDataEngine;
const service = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined, debug: () => undefined } });
service.registerAdapter('memory', adapter);
service.registerSource(SOURCE);
return createStdioDataBridge({
engine: {} as never,
metadataService: { list: async () => [], getObject: async () => undefined } as never,
resolvePrincipal: async () => ({ userId: 'u_key_owner', isSystem: false }) as never,
knowledgeTools: service,
});
}

async function overStdio<T>(bridge: McpDataBridge, use: (client: Client) => Promise<T>): Promise<T> {
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
runtime.bridgeDataTools(bridge);
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
await runtime.server.connect(serverSide);
const client = new Client({ name: 't', version: '1.0.0' });
await client.connect(clientSide);
try {
return await use(client);
} finally {
await client.close();
}
}

/**
* One JSON-RPC request over stdio, answered as the wire carries it: read off
* the transport, not through the SDK client, whose result parse re-orders
* an input schema's keys and would make a byte comparison read the client.
*/
async function rawOverStdio(bridge: McpDataBridge, message: JSONRPCMessage & { id: number }) {
const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' });
runtime.bridgeDataTools(bridge);
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
await runtime.server.connect(serverSide);
const reply = new Promise<any>((resolve) => {
clientSide.onmessage = (m) => {
if ((m as { id?: number }).id === message.id) resolve(m);
};
});
await clientSide.start();
await clientSide.send(message);
try {
return await reply;
} finally {
await clientSide.close();
}
}

async function callBoth(args: Record<string, unknown>) {
const http = (await callTool(realBridge(), args)).result!;
const stdio = (await overStdio(realBridge(), (c) => c.callTool({ name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args }))) as {
content: Array<{ text: string }>;
isError?: boolean;
};
expect(http.isError).toBeFalsy();
expect(stdio.isError).toBeFalsy();
expect(stdio.content[0].text).toBe(http.content[0].text);
return JSON.parse(http.content[0].text) as { hits: Array<{ record?: { id: string }; groupValue?: unknown }> };
}

it('tools/list over HTTP and over stdio answer byte-identical definitions, carrying scope, granularity and groupBy', async () => {
const http = knowledgeTool(await listTools(realBridge()));
const stdio = knowledgeTool((await rawOverStdio(realBridge(), { jsonrpc: '2.0', id: 1, method: 'tools/list' })).result.tools);
expect(http).toBeDefined();
expect(JSON.stringify(stdio)).toBe(JSON.stringify(http));
const [definition] = getKnowledgeToolDefinitions();
expect(http!.description).toBe(definition.description);
// The listed schema IS the definition's: no transport-side edit of a bound, a description or a key.
const { $schema: _dialect, ...listed } = http!.inputSchema;
expect(listed).toEqual(definition.parameters);
expect(Object.keys(http!.inputSchema.properties).sort()).toEqual(['granularity', 'groupBy', 'query', 'scope', 'sourceIds', 'topK']);
// The nested scope schema reaches the client whole, bounds included.
expect(http!.inputSchema.properties.scope).toMatchObject({
type: 'array', minItems: 1, maxItems: 10,
items: { type: 'object', required: ['object', 'ids'], additionalProperties: false, properties: { ids: { maxItems: 500 } } },
});
expect(http!.inputSchema.properties.granularity.enum).toEqual(['chunk', 'record']);
});

it("granularity 'record' answers one hit per record over both doors", async () => {
const answer = await callBoth({ query: 'leave', granularity: 'record' });
expect(answer.hits.map((h) => h.record?.id)).toEqual(['c1', 'c2', 'c3']);
});

it('groupBy answers one hit per group, with its value, over both doors', async () => {
const answer = await callBoth({ query: 'leave', groupBy: 'policy' });
expect(answer.hits.map((h) => [h.record?.id, h.groupValue])).toEqual([['c1', 'P_leave'], ['c3', 'P_travel']]);
});

it('scope answers only the named records over both doors', async () => {
const answer = await callBoth({ query: 'leave', scope: [{ object: 'clause', ids: ['c3'] }] });
expect(answer.hits.map((h) => h.record?.id)).toEqual(['c3']);
});

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 () => {
const args = { query: 'q', scope: Array.from({ length: 11 }, () => ({ object: 'clause', ids: ['c1'] })) };
const bridge = realBridge();
const search = vi.spyOn(bridge, 'searchKnowledge');
const http = (await callTool(bridge, args)).result!;
const stdio = (await rawOverStdio(realBridge(), {
jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args },
})).result as { content: Array<{ text: string }>; isError?: boolean };
expect(search).not.toHaveBeenCalled();
// The SDK's input-validation refusal (-32602), naming the argument: a schema-stated shape never reaches the
// executor over MCP, so it carries no ADR-0112 code. The coded VALIDATION_ERROR is the executor's own.
expect(http.isError).toBe(true);
expect(http.content[0].text).toContain('-32602');
expect(http.content[0].text).toContain('scope');
expect(stdio.isError).toBe(true);
expect(stdio.content[0].text).toBe(http.content[0].text);
});

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 () => {
const args = { query: 'q', scope: [{ object: 'clause', ids: ['c1\u0000x'] }] };
const http = (await callTool(realBridge(), args)).result!;
const stdio = (await rawOverStdio(realBridge(), {
jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args },
})).result as { content: Array<{ text: string }>; isError?: boolean };
expect(http.isError).toBe(true);
expect(JSON.parse(http.content[0].text).error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
expect(http.content[0].text).toContain('`scope`');
expect(stdio.isError).toBe(true);
expect(stdio.content[0].text).toBe(http.content[0].text);
});
});
2 changes: 2 additions & 0 deletions packages/mcp/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ export default defineConfig({
{ find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../drivers/driver-sql/src/index.ts') },
// [ADR-0160] The record-context executor, so `get_record_context`'s transport parity runs the real one.
{ find: /^@objectstack\/service-record-context$/, replacement: path.resolve(__dirname, '../services/service-record-context/src/index.ts') },
// [ADR-0161 K9] The knowledge tool's one definition and executor, so `search_knowledge`'s transport parity runs the real ones.
{ find: /^@objectstack\/service-knowledge$/, replacement: path.resolve(__dirname, '../services/service-knowledge/src/index.ts') },
],
},
});
Loading
Loading