|
14 | 14 | * in `prompts/list` where the tool is served and withheld, with a debug line |
15 | 15 | * naming the tool, where it is not; and the stdio bridge runs each call as the |
16 | 16 | * 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. |
17 | 25 | */ |
18 | 26 |
|
19 | 27 | 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'; |
20 | 31 | 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'; |
21 | 35 | import { MCPServerRuntime } from './mcp-server-runtime.js'; |
22 | 36 | import { SEARCH_KNOWLEDGE_TOOL_NAME, type McpDataBridge } from './mcp-http-tools.js'; |
23 | 37 | import type { McpSkillBridge } from './skill-prompts.js'; |
@@ -235,3 +249,174 @@ describe('[ADR-0149 D2] search_knowledge on the stdio bridge', () => { |
235 | 249 | expect(searchKnowledge).toHaveBeenCalledWith({ query: 'refund' }, principal); |
236 | 250 | }); |
237 | 251 | }); |
| 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 | +}); |
0 commit comments