|
24 | 24 | * value, and only the scoped records' hits. |
25 | 25 | */ |
26 | 26 |
|
27 | | -import { describe, it, expect, vi } from 'vitest'; |
| 27 | +import { describe, it, expect, vi, afterEach } from 'vitest'; |
28 | 28 | import { Client } from '@modelcontextprotocol/sdk/client/index.js'; |
29 | 29 | import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; |
30 | | -import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; |
| 30 | +import { ToolListChangedNotificationSchema, type JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; |
31 | 31 | import { MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE } from '@objectstack/spec/ai'; |
32 | 32 | import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; |
33 | 33 | import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; |
34 | 34 | import { KnowledgeService, getKnowledgeToolDefinitions, recordToDocument } from '@objectstack/service-knowledge'; |
35 | 35 | import { MCPServerRuntime } from './mcp-server-runtime.js'; |
| 36 | +import { MCPServerPlugin } from './plugin.js'; |
36 | 37 | import { SEARCH_KNOWLEDGE_TOOL_NAME, type McpDataBridge } from './mcp-http-tools.js'; |
37 | 38 | import type { McpSkillBridge } from './skill-prompts.js'; |
38 | 39 | import { createStdioDataBridge, type StdioKnowledgeToolsService } from './stdio-data-bridge.js'; |
@@ -421,3 +422,163 @@ describe('[ADR-0161 K9] search_knowledge over the real definition — every tran |
421 | 422 | expect(stdio.content[0].text).toBe(http.content[0].text); |
422 | 423 | }); |
423 | 424 | }); |
| 425 | + |
| 426 | +/** |
| 427 | + * [ADR-0161 K8, the dated note on item 12] A knowledge service the runtime |
| 428 | + * composed is enabled by configuration, read at `kernel:bootstrapped`. Until |
| 429 | + * that reading, and while it says not enabled, the service hands out no |
| 430 | + * definition, so neither transport lists `search_knowledge`; enabled, both |
| 431 | + * do. The stdio transport registers its tools in the MCP plugin's `start()`, |
| 432 | + * before the reading, so it registers this one at `kernel:listening`, once |
| 433 | + * the reading said enabled — never listed and then withdrawn. A service a |
| 434 | + * host mounts serves its definition from the start, as before. |
| 435 | + */ |
| 436 | +describe('[ADR-0161 K8, note on item 12] search_knowledge follows the enabled reading on both transports', () => { |
| 437 | + const originalEnv = { ...process.env }; |
| 438 | + afterEach(() => { |
| 439 | + process.env = { ...originalEnv }; |
| 440 | + vi.restoreAllMocks(); |
| 441 | + }); |
| 442 | + |
| 443 | + const SOURCE: KnowledgeSource = { |
| 444 | + name: 'faq', |
| 445 | + label: 'FAQ', |
| 446 | + source: { kind: 'object', object: 'faq', content: ['body'] } as ObjectKnowledgeSource, |
| 447 | + }; |
| 448 | + |
| 449 | + function service(opts: { runtimeComposed: boolean }): KnowledgeService { |
| 450 | + const svc = new KnowledgeService({ |
| 451 | + logger: { warn: () => undefined, debug: () => undefined }, |
| 452 | + deploymentAdapter: 'memory', |
| 453 | + ...(opts.runtimeComposed ? { enabledByConfiguration: true } : {}), |
| 454 | + }); |
| 455 | + svc.registerAdapter('memory', { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] }); |
| 456 | + svc.registerSource(SOURCE); |
| 457 | + return svc; |
| 458 | + } |
| 459 | + |
| 460 | + const bridgeOver = (svc: KnowledgeService) => |
| 461 | + createStdioDataBridge({ |
| 462 | + engine: {} as never, |
| 463 | + metadataService: { list: async () => [], getObject: async () => undefined } as never, |
| 464 | + resolvePrincipal: async () => ({ userId: 'u_key_owner', isSystem: false }) as never, |
| 465 | + knowledgeTools: svc, |
| 466 | + }); |
| 467 | + |
| 468 | + it('over HTTP: absent until the reading, absent when held, listed when enabled', async () => { |
| 469 | + const held = service({ runtimeComposed: true }); |
| 470 | + expect(knowledgeTool(await listTools(bridgeOver(held)))).toBeUndefined(); |
| 471 | + held.settleEnablement({ embedder: 'no provider is saved' }); |
| 472 | + expect(knowledgeTool(await listTools(bridgeOver(held)))).toBeUndefined(); |
| 473 | + |
| 474 | + const enabled = service({ runtimeComposed: true }); |
| 475 | + enabled.settleEnablement(undefined); |
| 476 | + expect(knowledgeTool(await listTools(bridgeOver(enabled)))).toBeDefined(); |
| 477 | + |
| 478 | + // A service a host mounts: listed from the start. |
| 479 | + expect(knowledgeTool(await listTools(bridgeOver(service({ runtimeComposed: false }))))).toBeDefined(); |
| 480 | + }); |
| 481 | + |
| 482 | + /** The MCP plugin's stdio wiring over a context holding `knowledge`; the boot hooks are fired by hand. */ |
| 483 | + async function stdioPlugin(knowledge: KnowledgeService) { |
| 484 | + process.env.OS_MCP_STDIO_API_KEY = 'osk_stdio_pin'; |
| 485 | + delete process.env.OS_MCP_SERVER_TRANSPORT; |
| 486 | + delete process.env.OS_MCP_STDIO_ENABLED; |
| 487 | + const hooks = new Map<string, Array<() => Promise<void> | void>>(); |
| 488 | + const services = new Map<string, unknown>([ |
| 489 | + ['knowledge', knowledge], |
| 490 | + ['metadata', { |
| 491 | + listObjects: async () => [], getObject: async () => null, get: async () => null, list: async () => [], |
| 492 | + exists: async () => false, getRegisteredTypes: async () => ['object'], register: () => undefined, unregister: () => undefined, |
| 493 | + }], |
| 494 | + ['objectql', { |
| 495 | + find: async (object: string, query?: { where?: { id?: string } }) => { |
| 496 | + if (object === 'sys_api_key') return [{ id: 'k1', user_id: 'usr_stdio', revoked: false }]; |
| 497 | + if (object === 'sys_user') return query?.where?.id === 'usr_stdio' ? [{ id: 'usr_stdio' }] : []; |
| 498 | + return []; |
| 499 | + }, |
| 500 | + findOne: async () => null, |
| 501 | + count: async () => 0, |
| 502 | + aggregate: async () => [], |
| 503 | + }], |
| 504 | + ]); |
| 505 | + const ctx = { |
| 506 | + registerService: (name: string, svc: unknown) => services.set(name, svc), |
| 507 | + getService: (name: string) => { |
| 508 | + if (!services.has(name)) throw new Error(`Service "${name}" not found`); |
| 509 | + return services.get(name); |
| 510 | + }, |
| 511 | + replaceService: () => undefined, |
| 512 | + getServices: () => services, |
| 513 | + hook: (name: string, fn: () => Promise<void> | void) => hooks.set(name, [...(hooks.get(name) ?? []), fn]), |
| 514 | + trigger: async () => undefined, |
| 515 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, |
| 516 | + getKernel: () => ({}), |
| 517 | + }; |
| 518 | + const plugin = new MCPServerPlugin({ autoStart: true }); |
| 519 | + await plugin.init(ctx as never); |
| 520 | + const runtime = services.get('mcp') as MCPServerRuntime; |
| 521 | + // Only the transport attach is stubbed: it would claim this process's stdin/stdout. |
| 522 | + vi.spyOn(runtime, 'start').mockResolvedValue(undefined); |
| 523 | + await plugin.start(ctx as never); |
| 524 | + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); |
| 525 | + await runtime.server.connect(serverSide); |
| 526 | + const client = new Client({ name: 't', version: '1.0.0' }); |
| 527 | + let listChanged = 0; |
| 528 | + client.setNotificationHandler(ToolListChangedNotificationSchema, () => { |
| 529 | + listChanged += 1; |
| 530 | + }); |
| 531 | + await client.connect(clientSide); |
| 532 | + const fire = async (name: string) => { |
| 533 | + for (const fn of hooks.get(name) ?? []) await fn(); |
| 534 | + }; |
| 535 | + const names = async () => (await client.listTools()).tools.map((t) => t.name); |
| 536 | + return { client, fire, names, listChanged: () => listChanged, ctx }; |
| 537 | + } |
| 538 | + |
| 539 | + it('over stdio, held: never listed — not before the reading, not after it', async () => { |
| 540 | + const knowledge = service({ runtimeComposed: true }); |
| 541 | + const { client, fire, names, listChanged } = await stdioPlugin(knowledge); |
| 542 | + try { |
| 543 | + expect(await names()).toContain('query_records'); |
| 544 | + expect(await names()).not.toContain(SEARCH_KNOWLEDGE_TOOL_NAME); |
| 545 | + knowledge.settleEnablement({ embedder: 'no provider is saved' }); |
| 546 | + await fire('kernel:bootstrapped'); |
| 547 | + await fire('kernel:listening'); |
| 548 | + expect(await names()).not.toContain(SEARCH_KNOWLEDGE_TOOL_NAME); |
| 549 | + expect(listChanged()).toBe(0); |
| 550 | + } finally { |
| 551 | + await client.close(); |
| 552 | + } |
| 553 | + }); |
| 554 | + |
| 555 | + it('over stdio, enabled: registered at kernel:listening, and a connected client is told the list changed', async () => { |
| 556 | + const knowledge = service({ runtimeComposed: true }); |
| 557 | + const { client, fire, names, listChanged } = await stdioPlugin(knowledge); |
| 558 | + try { |
| 559 | + expect(await names()).not.toContain(SEARCH_KNOWLEDGE_TOOL_NAME); |
| 560 | + knowledge.settleEnablement(undefined); |
| 561 | + await fire('kernel:bootstrapped'); |
| 562 | + await fire('kernel:listening'); |
| 563 | + expect(await names()).toContain(SEARCH_KNOWLEDGE_TOOL_NAME); |
| 564 | + await vi.waitFor(() => expect(listChanged()).toBeGreaterThan(0)); |
| 565 | + // The one definition the service hands out, as HTTP lists it. |
| 566 | + const listed = (await client.listTools()).tools.find((t) => t.name === SEARCH_KNOWLEDGE_TOOL_NAME); |
| 567 | + expect(listed?.description).toBe(getKnowledgeToolDefinitions()[0]!.description); |
| 568 | + } finally { |
| 569 | + await client.close(); |
| 570 | + } |
| 571 | + }); |
| 572 | + |
| 573 | + it('over stdio, a service a host mounts: registered with the other tools in start(), as before', async () => { |
| 574 | + const { client, fire, names, listChanged } = await stdioPlugin(service({ runtimeComposed: false })); |
| 575 | + try { |
| 576 | + expect(await names()).toContain(SEARCH_KNOWLEDGE_TOOL_NAME); |
| 577 | + await fire('kernel:listening'); |
| 578 | + expect((await names()).filter((n) => n === SEARCH_KNOWLEDGE_TOOL_NAME)).toHaveLength(1); |
| 579 | + expect(listChanged()).toBe(0); |
| 580 | + } finally { |
| 581 | + await client.close(); |
| 582 | + } |
| 583 | + }); |
| 584 | +}); |
0 commit comments