Skip to content

Commit 2ac16d0

Browse files
committed
wip: runtime-composed knowledge enablement pins; stdio late registration
Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW Co-authored-by: Claude <noreply@anthropic.com>
1 parent 63ffb69 commit 2ac16d0

2 files changed

Lines changed: 270 additions & 2 deletions

File tree

‎packages/mcp/src/plugin.ts‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ import {
5959
type StdioProtocolObjectReads,
6060
type StoredHashDigest,
6161
} from './stdio-data-bridge.js';
62-
import type { McpDataBridge } from './mcp-http-tools.js';
62+
import { SEARCH_KNOWLEDGE_TOOL_NAME, knowledgeToolDefinition, registerKnowledgeTools, type McpDataBridge } from './mcp-http-tools.js';
6363
import { CONNECT_AGENT_UI_BUNDLE } from './connect-ui.js';
6464
import { configureReadFileExtraction } from './file-content.js';
6565

@@ -968,7 +968,8 @@ export class MCPServerPlugin implements Plugin {
968968
// record argument only where this server registers `get_record_context`,
969969
// which it reads from the tools registered by then.
970970
if (dataBridge) {
971-
this.runtime.bridgeDataTools(dataBridge);
971+
const bridged = this.runtime.bridgeDataTools(dataBridge);
972+
this.registerKnowledgeToolOnceSettled(ctx, dataBridge, bridged);
972973
}
973974

974975
if (metadataService) {
@@ -1038,6 +1039,45 @@ export class MCPServerPlugin implements Plugin {
10381039
await ctx.trigger('mcp:ready', this.runtime);
10391040
}
10401041

1042+
/**
1043+
* [ADR-0161 K8, the dated note on item 12] `search_knowledge` on the stdio
1044+
* transport, for a knowledge service the runtime composed. Such a service is
1045+
* enabled by configuration, read once at `kernel:bootstrapped`, and until
1046+
* then hands out no definition, so {@link MCPServerRuntime.bridgeDataTools},
1047+
* which runs in this `start()`, registered none. The tool registers here,
1048+
* at `kernel:listening` — after every `kernel:bootstrapped` handler, the
1049+
* reading's among them — only when the service now hands out its
1050+
* definition (enabled). Not enabled, it stays absent: an unknown state reads
1051+
* as absent, never listed and then withdrawn. The server already declares
1052+
* the `tools` capability (the object tools registered it before the
1053+
* transport attached), so the SDK takes a tool after the transport has
1054+
* attached and tells a connected client with `notifications/tools/list_changed`.
1055+
* The skill prompts read the served tools at each listing, so a skill that
1056+
* binds the tool is listed from then on.
1057+
*
1058+
* A service a host mounted hands out its definition from the start, so its
1059+
* tool registered with the others and nothing is done here.
1060+
*/
1061+
private registerKnowledgeToolOnceSettled(ctx: PluginContext, bridge: McpDataBridge, bridged: readonly string[]): void {
1062+
if (bridged.includes(SEARCH_KNOWLEDGE_TOOL_NAME)) return;
1063+
if (typeof bridge.searchKnowledge !== 'function' || typeof bridge.knowledgeToolDefinitions !== 'function') return;
1064+
ctx.hook('kernel:listening', async () => {
1065+
const runtime = this.runtime;
1066+
if (!runtime || !knowledgeToolDefinition(bridge)) return;
1067+
try {
1068+
const registered = registerKnowledgeTools(runtime.server, bridge, { logger: ctx.logger });
1069+
if (registered.length > 0) {
1070+
ctx.logger.info(`[MCP] stdio transport: ${registered.join(', ')} registered once the knowledge service was read as enabled`);
1071+
}
1072+
} catch (err) {
1073+
// A tool of that name the AI registry bridged keeps it (the SDK refuses a second registration).
1074+
ctx.logger.warn(
1075+
`[MCP] stdio transport: ${SEARCH_KNOWLEDGE_TOOL_NAME} was not registered (${err instanceof Error ? err.message : String(err)}).`,
1076+
);
1077+
}
1078+
});
1079+
}
1080+
10411081
async destroy(): Promise<void> {
10421082
if (this.runtime?.isStarted) {
10431083
await this.runtime.stop();

‎packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts‎

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -759,3 +759,231 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
759759
expect(requests).toHaveLength(0);
760760
});
761761
});
762+
763+
/**
764+
* [ADR-0161 K8, the dated note on item 12] A knowledge service the runtime
765+
* composed (`runtimeComposed`, set by `resolveCapabilityArgument`) is enabled
766+
* by configuration: at `kernel:bootstrapped` it serves only with an embedder
767+
* and the deployment's store, and otherwise holds every source — listed, never
768+
* built, synced or searched, no tool definition, no store called — said once,
769+
* in one line. A plugin a host mounts itself is untouched.
770+
*/
771+
describe('[ADR-0161 K8, note on item 12] a runtime-composed knowledge service is enabled by configuration', () => {
772+
afterEach(() => {
773+
vi.unstubAllGlobals();
774+
});
775+
776+
/** Every call the deployment's store is handed, by member. */
777+
type StoreCalls = string[];
778+
779+
/** The deployment's store (`id`), counting every call made to it. */
780+
class CountingStorePlugin implements Plugin {
781+
name = 'test.knowledge.counting-store';
782+
version = '1.0.0';
783+
type = 'standard' as const;
784+
dependencies = ['com.objectstack.service.knowledge'];
785+
constructor(private readonly id: string, private readonly calls: StoreCalls) {}
786+
async init(): Promise<void> {}
787+
async start(ctx: PluginContext): Promise<void> {
788+
const calls = this.calls;
789+
const embedder = () => ctx.getService<IEmbedder>(EMBEDDER_SERVICE);
790+
const adapter: IKnowledgeAdapter = {
791+
id: this.id,
792+
async upsert(docs) {
793+
calls.push('upsert');
794+
await embedder().embed(docs.map((d) => d.content));
795+
},
796+
async search(query) {
797+
calls.push('search');
798+
await embedder().embed([query]);
799+
return [];
800+
},
801+
async delete() {
802+
calls.push('delete');
803+
},
804+
async dropSource() {
805+
calls.push('dropSource');
806+
},
807+
};
808+
// Registered in start(), as a store plugin registers its adapter.
809+
ctx.getService<KnowledgeService>(KNOWLEDGE_SERVICE).registerAdapter(this.id, adapter);
810+
}
811+
}
812+
813+
async function bootComposed(opts: {
814+
runtimeComposed?: { declared: boolean };
815+
/** The deployment's store id the runtime marks. @default 'vec' */
816+
deploymentAdapter?: string;
817+
/** Whether the deployment's store registers its adapter. @default true */
818+
storeMounted?: boolean;
819+
saved?: Record<string, unknown>;
820+
host?: { embedder: IEmbedder; phase: 'init' | 'kernel:ready' };
821+
sources?: KnowledgeSource[];
822+
} = {}) {
823+
const lines: LoggedLine[] = [];
824+
const calls: StoreCalls = [];
825+
const store = opts.deploymentAdapter ?? 'vec';
826+
const kernel = new LiteKernel();
827+
kernel.use(new LogRecorder(lines));
828+
if (opts.host) kernel.use(new HostEmbedderPlugin(opts.host.embedder, opts.host.phase));
829+
kernel.use(new KnowledgeServicePlugin({
830+
enableEventSync: false,
831+
deploymentAdapter: store,
832+
...(opts.runtimeComposed ? { runtimeComposed: opts.runtimeComposed } : {}),
833+
// A shipped source names no adapter: it binds to the deployment's store.
834+
sources: opts.sources ?? [{ name: 'docs', label: 'Docs', source: { kind: 'object', object: 'doc', content: ['body'] } }],
835+
}));
836+
kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() }));
837+
if (opts.storeMounted !== false) kernel.use(new CountingStorePlugin(store, calls));
838+
if (opts.saved) kernel.use(new SavedAiSettings(opts.saved));
839+
await kernel.bootstrap();
840+
// The boot build runs in the background: let it settle before counting.
841+
await new Promise((resolve) => setTimeout(resolve, 20));
842+
const knowledge = kernel.getService<KnowledgeService>(KNOWLEDGE_SERVICE);
843+
/** The one line of the held state, if any. */
844+
const heldLines = () => lines.filter((l) => l.line.includes('the knowledge service is not enabled'));
845+
return { kernel, lines, calls, knowledge, heldLines };
846+
}
847+
848+
/** What the record sync's two triggers hand the service for one write and one delete. */
849+
async function writeAndDelete(knowledge: KnowledgeService): Promise<void> {
850+
await knowledge.handleRecordUpsert('doc', { id: 'd1', body: 'granite quarry' });
851+
await knowledge.handleRecordDelete('doc', 'd1');
852+
knowledge.enqueueRecordSync('doc', 'd1');
853+
await knowledge.reconcileSources();
854+
knowledge.requestReconcile('doc');
855+
}
856+
857+
const hostEmbedder = (): IEmbedder => ({ id: 'host-own', dimensions: 2, embed: async (t) => t.map(() => [0.6, 0.8]) });
858+
859+
it('a shipped source and no embedder: mounted, held, zero store calls across boot and a record write, one line at info', async () => {
860+
const requests = stubProvider();
861+
const { knowledge, calls, lines, heldLines } = await bootComposed({ runtimeComposed: { declared: false } });
862+
863+
// Mounted: the service and the deployment's store are both there.
864+
expect(knowledge.listAdapters()).toEqual(['vec']);
865+
expect(knowledge.describeSources().map((d) => d.id)).toEqual(['docs']);
866+
expect(knowledge.heldReading()).toEqual({ embedder: expect.stringContaining('ai.embedder_provider') });
867+
868+
await writeAndDelete(knowledge);
869+
expect(calls).toEqual([]);
870+
expect(requests).toHaveLength(0);
871+
872+
// Exactly one line says the state, at info, naming the remedy and the held source.
873+
expect(heldLines()).toHaveLength(1);
874+
expect(heldLines()[0]).toMatchObject({ level: 'info' });
875+
expect(heldLines()[0].line).toContain('save an embedder provider');
876+
expect(heldLines()[0].line).toContain('docs');
877+
// Folded into it: the embedder's own line and the unplaceable-source error, and no reconcile line.
878+
expect(lines.filter((l) => l.line.includes('no embedder is configured (') && !l.line.includes('not enabled'))).toEqual([]);
879+
expect(lines.filter((l) => l.level === 'error')).toEqual([]);
880+
expect(lines.filter((l) => l.line.includes('reconcile'))).toEqual([]);
881+
});
882+
883+
it('held: no tool definition, and a direct search is refused 503 naming the missing half, never answered empty', async () => {
884+
const { knowledge } = await bootComposed({ runtimeComposed: { declared: false } });
885+
expect(knowledge.knowledgeTools().definitions).toEqual([]);
886+
const refused = await knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM }).catch((e: unknown) => e);
887+
expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
888+
expect((refused as Error).message).toMatch(/^\[knowledge\] the knowledge service is not enabled on this deployment: no embedder is configured/);
889+
expect((refused as Error).message).toContain('save an embedder provider');
890+
expect((refused as Error).message).not.toContain('knowledge store');
891+
const report = await knowledge.searchWithRefusals('granite', { executionContext: SYSTEM }).catch((e: unknown) => e);
892+
expect(report).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
893+
// An operator's rebuild calls no store either.
894+
await expect(knowledge.rebuildSource('docs', { trigger: 'operator' })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
895+
});
896+
897+
it("requires: ['knowledge'] and no embedder: the one line is warn; the boot succeeds", async () => {
898+
const { knowledge, heldLines, calls } = await bootComposed({ runtimeComposed: { declared: true } });
899+
expect(knowledge.heldReading()).toBeDefined();
900+
expect(heldLines()).toHaveLength(1);
901+
expect(heldLines()[0]).toMatchObject({ level: 'warn' });
902+
expect(calls).toEqual([]);
903+
});
904+
905+
it('a provider saved without its key: the one line is warn and names the reason', async () => {
906+
const requests = stubProvider();
907+
const { knowledge, heldLines } = await bootComposed({ runtimeComposed: { declared: false }, saved: { embedder_provider: 'siliconflow' } });
908+
expect(knowledge.heldReading()?.embedder).toContain('requires an API key');
909+
expect(heldLines()).toHaveLength(1);
910+
expect(heldLines()[0]).toMatchObject({ level: 'warn' });
911+
expect(heldLines()[0].line).toContain('requires an API key');
912+
expect(requests).toHaveLength(0);
913+
});
914+
915+
it("the deployment's store not mounted, an embedder there: held, warn, naming the store and that the boot log says why", async () => {
916+
const { knowledge, heldLines } = await bootComposed({
917+
runtimeComposed: { declared: false },
918+
host: { embedder: hostEmbedder(), phase: 'init' },
919+
storeMounted: false,
920+
deploymentAdapter: 'turso',
921+
});
922+
expect(knowledge.heldReading()).toEqual({ store: 'turso' });
923+
expect(heldLines()).toHaveLength(1);
924+
expect(heldLines()[0]).toMatchObject({ level: 'warn' });
925+
expect(heldLines()[0].line).toContain("knowledge store 'turso' is not mounted");
926+
expect(heldLines()[0].line).not.toContain('save an embedder provider');
927+
const refused = await knowledge.search('x', { executionContext: SYSTEM }).catch((e: unknown) => e);
928+
expect((refused as Error).message).toContain("mount the deployment's knowledge store");
929+
});
930+
931+
it('both halves missing: the refusal names both', async () => {
932+
const { knowledge } = await bootComposed({ runtimeComposed: { declared: false }, storeMounted: false, deploymentAdapter: 'turso' });
933+
expect(knowledge.heldReading()).toEqual({ embedder: expect.any(String), store: 'turso' });
934+
const refused = (await knowledge.search('x', { executionContext: SYSTEM }).catch((e: unknown) => e)) as Error;
935+
expect(refused.message).toContain('save an embedder provider');
936+
expect(refused.message).toContain("mount the deployment's knowledge store");
937+
});
938+
939+
it('[point 2] a source on a store the application registered is held too: the state is the whole service\'s', async () => {
940+
const { knowledge, calls } = await bootComposed({
941+
runtimeComposed: { declared: false },
942+
// The application's own store, named by the source; the deployment's is another id, unmounted.
943+
deploymentAdapter: 'turso',
944+
storeMounted: false,
945+
sources: [{ name: 'docs', label: 'Docs', adapter: 'vec', source: { kind: 'object', object: 'doc', content: ['body'] } }],
946+
});
947+
// Not mounted by the runtime: register the application's store by hand, as app code does.
948+
const appCalls: string[] = [];
949+
knowledge.registerAdapter('vec', { id: 'vec', upsert: async () => { appCalls.push('upsert'); }, search: async () => { appCalls.push('search'); return []; }, delete: async () => { appCalls.push('delete'); } });
950+
await writeAndDelete(knowledge);
951+
expect(appCalls).toEqual([]);
952+
expect(calls).toEqual([]);
953+
expect(knowledge.knowledgeTools().definitions).toEqual([]);
954+
});
955+
956+
it('control — an embedder registered by a plugin: enabled, the tool is handed out and a record write reaches the store', async () => {
957+
const { knowledge, calls, heldLines, lines } = await bootComposed({
958+
runtimeComposed: { declared: true },
959+
host: { embedder: hostEmbedder(), phase: 'kernel:ready' },
960+
});
961+
expect(knowledge.heldReading()).toBeUndefined();
962+
expect(heldLines()).toEqual([]);
963+
expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']);
964+
expect(lines.filter((l) => l.line.includes('already registered') && l.line.includes('host-own'))).toHaveLength(1);
965+
await knowledge.handleRecordUpsert('doc', { id: 'd1', body: 'granite quarry' });
966+
expect(calls).toContain('upsert');
967+
});
968+
969+
it('control — an embedder built from the saved settings: enabled', async () => {
970+
stubProvider();
971+
const { knowledge, heldLines } = await bootComposed({
972+
runtimeComposed: { declared: false },
973+
saved: { embedder_provider: 'openai', embedder_api_key: API_KEY },
974+
});
975+
expect(knowledge.heldReading()).toBeUndefined();
976+
expect(heldLines()).toEqual([]);
977+
expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']);
978+
});
979+
980+
it('a plugin a host mounts itself, no embedder: as before — not held, the tool handed out, the stand-in refuses at the store', async () => {
981+
const { knowledge, heldLines, lines, calls } = await bootComposed({});
982+
expect(knowledge.heldReading()).toBeUndefined();
983+
expect(heldLines()).toEqual([]);
984+
expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']);
985+
expect(lines.some((l) => l.level === 'info' && l.line.includes('no embedder is configured ('))).toBe(true);
986+
await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]);
987+
expect(calls).toContain('search');
988+
});
989+
});

0 commit comments

Comments
 (0)