From ca2cd22a93c19717e6d9663f8823a0051b2cdf92 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 06:19:12 +0000 Subject: [PATCH 1/4] test(runtime): reach the real record-context executor and the MCP stdio plugin from runtime tests Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzi13yZRqVcp2mGonWK --- packages/runtime/package.json | 2 ++ pnpm-lock.yaml | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/packages/runtime/package.json b/packages/runtime/package.json index b1c4777148f..9f290703dc8 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -74,6 +74,7 @@ }, "devDependencies": { "@libsql/client": "^0.18.0", + "@objectstack/mcp": "workspace:*", "@objectstack/platform-objects": "workspace:*", "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/plugin-sharing": "workspace:*", @@ -82,6 +83,7 @@ "@objectstack/service-job": "workspace:*", "@objectstack/service-messaging": "workspace:*", "@objectstack/service-package": "workspace:*", + "@objectstack/service-record-context": "workspace:*", "@objectstack/service-settings": "workspace:*", "@objectstack/service-storage": "workspace:*", "typescript": "^6.0.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f0b97384e12..df1eac6c9b1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2777,6 +2777,9 @@ importers: '@libsql/client': specifier: ^0.18.0 version: 0.18.0 + '@objectstack/mcp': + specifier: workspace:* + version: link:../mcp '@objectstack/platform-objects': specifier: workspace:* version: link:../platform-objects @@ -2798,6 +2801,9 @@ importers: '@objectstack/service-package': specifier: workspace:* version: link:../services/service-package + '@objectstack/service-record-context': + specifier: workspace:* + version: link:../services/service-record-context '@objectstack/service-settings': specifier: workspace:* version: link:../services/service-settings From 0fa37da2d57841930ec0e986896a977d1fa38492 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 06:28:45 +0000 Subject: [PATCH 2/4] test(runtime): WIP record-context HTTP/stdio rig bring-up (blocked, not a deliverable) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzi13yZRqVcp2mGonWK --- .../domains/mcp-record-context-37175.test.ts | 254 ++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 packages/runtime/src/domains/mcp-record-context-37175.test.ts diff --git a/packages/runtime/src/domains/mcp-record-context-37175.test.ts b/packages/runtime/src/domains/mcp-record-context-37175.test.ts new file mode 100644 index 00000000000..0b8298e05ec --- /dev/null +++ b/packages/runtime/src/domains/mcp-record-context-37175.test.ts @@ -0,0 +1,254 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * WIP PROBE, not a deliverable: the bring-up of the record-context HTTP/stdio + * parity rig, kept on this branch so the work resumes from it. + * + * What it measured at ad604c10: every pack the protocol's merged listing + * serves carries the `_diagnostics` decoration (`decorateMetadataItem`), and + * the executor's strict `AiContextSchema` parse (`parsedContextPacks`) drops + * the row, so both doors answer "no context pack" for a valid pack. With + * `RC_STRIP=1` the rig strips the decoration (a CONTROL only) and the HTTP door + * reads the pack. The stdio half still answers RECORD_NOT_FOUND for the same + * row: its key-resolved caller is not yet the HTTP caller. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { SysMetadataAuditObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { MCPServerPlugin, MCPServerRuntime } from '@objectstack/mcp'; +import { RecordContextServicePlugin } from '@objectstack/service-record-context'; +import { HttpDispatcher } from '../http-dispatcher.js'; +import '@objectstack/metadata'; + +const PKG = 'com.objectstack.qa.record-context-37175'; +const OFF_PKG = 'com.objectstack.qa.record-context-37175-off'; +const all = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + +describe('probe', () => { + let engine: ObjectQL; + const services: Record = {}; + const stdioServices = new Map(); + let rpc: (method: string, params?: unknown) => Promise; + const contexts: any[] = []; + + beforeAll(async () => { + engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const storeObjects = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject] as any[]; + await driver.initObjects(storeObjects); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of storeObjects) engine.registry.registerObject(o, '@objectstack/platform-objects'); + engine.registerApp({ + id: PKG, name: 'record context rig', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [ + { + name: 'rc_policy', label: 'Policy', nameField: 'title', sharingModel: 'public_read_write', + fields: { + title: { name: 'title', type: 'text', label: 'Title' }, + status: { name: 'status', type: 'select', label: 'Status', options: [{ value: 'active', label: 'Active' }] }, + secret_note: { name: 'secret_note', type: 'text', label: 'Secret note' }, + vault: { name: 'vault', type: 'lookup', reference: 'rc_vault', label: 'Vault' }, + content: { name: 'content', type: 'markdown', label: 'Content' }, + }, + }, + { + name: 'rc_revision', label: 'Revision', nameField: 'version', sharingModel: 'private', + fields: { + version: { name: 'version', type: 'text', label: 'Version' }, + policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, + }, + }, + { + name: 'rc_vault', label: 'Vault', enable: { apiEnabled: false }, sharingModel: 'public_read_write', + fields: { label: { name: 'label', type: 'text', label: 'Label' } }, + }, + { + name: 'rc_closed', label: 'Closed', enable: { apiEnabled: false }, sharingModel: 'public_read_write', + fields: { + version: { name: 'version', type: 'text', label: 'Version' }, + policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, + }, + }, + { + name: 'rc_hidden', label: 'Hidden', sharingModel: 'public_read_write', + fields: { + version: { name: 'version', type: 'text', label: 'Version' }, + policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, + }, + }, + { + name: 'sys_rc_note', label: 'Note', sharingModel: 'public_read_write', + fields: { + body: { name: 'body', type: 'text', label: 'Body' }, + policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, + }, + }, + ], + aiContexts: [ + { + name: 'rc_main', label: 'Policy document', object: 'rc_policy', + fields: ['title', 'status', 'secret_note', 'vault'], + related: [{ object: 'rc_revision', fields: ['version'] }], + body: { field: 'content' }, + }, + ], + } as never); + engine.registerApp({ + id: OFF_PKG, name: 'record context rig (off)', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [{ + name: 'rc_off', label: 'Off', sharingModel: 'public_read_write', + fields: { + version: { name: 'version', type: 'text', label: 'Version' }, + policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, + }, + }], + } as never); + await engine.syncSchemas(); + await engine.insert('rc_vault', { id: 'v1', label: 'Vault 1', organization_id: 'org_1' }, { context: { isSystem: true } } as never); + await engine.insert('rc_policy', { id: 'p1', title: 'Fire cover', status: 'active', secret_note: 'hush', vault: 'v1', content: '# Scope\nCovers fire.\n# Exclusions\nFlood.', organization_id: 'org_1' }, { context: { isSystem: true } } as never); + await engine.insert('rc_revision', { id: 'r1', version: 'v1', policy: 'p1', owner_id: 'usr_member', organization_id: 'org_1' }, { context: { isSystem: true } } as never); + await engine.insert('rc_revision', { id: 'r2', version: 'v2', policy: 'p1', owner_id: 'usr_other', organization_id: 'org_1' }, { context: { isSystem: true } } as never); + + const sets = [ + PermissionSetSchema.parse({ + name: 'rc_member', label: 'Member', isDefault: true, + objects: { '*': all, rc_hidden: { allowRead: false, allowCreate: false, allowEdit: false, allowDelete: false } }, + fields: { 'rc_policy.secret_note': { readable: false, editable: false } }, + }), + ]; + const pluginServices: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? sets.find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, + list: async (type: string) => (type === 'permission' ? sets : []), + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn((name: string, service: unknown) => { pluginServices[name] = service; }), + getService: (name: string) => { + if (!(name in pluginServices)) throw new Error(`service not registered: ${name}`); + return pluginServices[name]; + }, + }; + const security = new SecurityPlugin({ fallbackPermissionSet: 'rc_member' }); + await security.init(ctx as never); + await security.start(ctx as never); + await new RecordContextServicePlugin().init(ctx as never); + + const realProtocol = new ObjectStackProtocolImplementation(engine as any); + services.realProtocol = realProtocol; + services.protocol = process.env.RC_STRIP ? new Proxy(realProtocol as any, { + get(t, prop, r) { + if (prop === 'getMetaItems') { + return async (req: any) => { + const out: any = await t.getMetaItems(req); + if (req?.type !== 'ai_context') return out; + return { ...out, items: out.items.map(({ _diagnostics, ...rest }: any) => rest) }; + }; + } + const v = Reflect.get(t, prop, r); + return typeof v === 'function' ? v.bind(t) : v; + }, + }) : realProtocol; + services.security = pluginServices.security; + services.objectql = engine; + services['record-context'] = pluginServices['record-context']; + services.metadata = pluginServices.metadata; + + // stdio + process.env.OS_MCP_STDIO_API_KEY = 'osk_rc37175_probe_key_0000000000000000'; + const ql = new Proxy(engine as any, { + get(target, prop, receiver) { + if (prop === 'update') { + return async (object: string, data: unknown, options?: unknown) => + object === 'sys_api_key' ? {} : target.update(object, data, options); + } + if (prop === 'find') { + return async (object: string, query?: unknown, options?: unknown) => { + if (object === 'sys_api_key') return [{ id: 'k1', user_id: 'usr_member', revoked: false }]; + if (object === 'sys_user') return (query as any)?.where?.id === 'usr_member' ? [{ id: 'usr_member' }] : []; + if (object.startsWith('sys_') && object !== 'sys_metadata' && !target.registry.getObject(object)) return []; + contexts.push({ object, query, options }); + return target.find(object, query, options); + }; + } + const value = Reflect.get(target, prop, receiver); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + for (const [k, v] of Object.entries({ metadata: services.metadata, protocol: services.protocol, objectql: ql, security: services.security, 'record-context': services['record-context'] })) stdioServices.set(k, v); + const sctx: any = { + registerService: vi.fn((name: string, service: unknown) => stdioServices.set(name, service)), + getService: vi.fn((name: string) => { + if (!stdioServices.has(name)) throw new Error(`Service "${name}" not found`); + return stdioServices.get(name); + }), + replaceService: vi.fn(), + getServices: vi.fn(() => stdioServices), + hook: vi.fn(), + trigger: vi.fn(async () => {}), + logger: { info: vi.fn(), warn: vi.fn((...a: any[]) => console.log('WARN', ...a)), error: vi.fn((...a: any[]) => console.log('ERR', ...a)), debug: vi.fn() }, + getKernel: vi.fn(() => ({})), + }; + const plugin = new MCPServerPlugin({ autoStart: true }); + await plugin.init(sctx); + const runtime = stdioServices.get('mcp') as MCPServerRuntime; + vi.spyOn(runtime, 'start').mockResolvedValue(undefined); + await plugin.start(sctx); + const waiting = new Map void>(); + let nextId = 1; + const transport: any = { + onmessage: undefined, onclose: undefined, onerror: undefined, + async start() {}, async close() { transport.onclose?.(); }, + async send(message: any) { + const resolve = typeof message?.id === 'number' ? waiting.get(message.id) : undefined; + if (resolve) { waiting.delete(message.id); resolve(message); } + }, + }; + rpc = (method: string, params?: unknown) => new Promise((resolve) => { + const id = nextId++; + waiting.set(id, resolve); + transport.onmessage?.({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) }); + }); + await runtime.server.connect(transport as never); + await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'probe', version: '0' } }); + transport.onmessage?.({ jsonrpc: '2.0', method: 'notifications/initialized' }); + }, 60_000); + + afterAll(async () => { + vi.restoreAllMocks(); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + it('probes', async () => { + console.log('PACKS', JSON.stringify(await services.protocol.getMetaItems({ type: 'ai_context' })).slice(0, 400)); + const s = await rpc('tools/call', { name: 'get_record_context', arguments: { objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' } }); + console.log('STDIO', JSON.stringify(s).slice(0, 3000)); + const ec = contexts.find((c) => c.object === 'rc_policy'); + console.log('CTX', String(JSON.stringify(ec?.options ?? ec?.query ?? contexts.map((c) => c.object))).slice(0, 1500)); + const mcp: any = { + handleHttpRequest: (req: Request, opts: any) => new MCPServerRuntime({ name: 'objectstack', version: '0.0.0' }).handleHttpRequest(req, opts), + }; + const allSvc: Record = { ...services, mcp }; + const get = (n: string) => allSvc[n] ?? null; + const kernel = { getService: get, getServiceAsync: async (n: string) => get(n), context: { getService: get } } as any; + const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_record_context', arguments: { objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' } } }; + const res = await dispatcher.handleMcp(body, { + request: new Request('http://localhost/api/v1/mcp', { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify(body) }), + response: {}, environmentId: undefined, + executionContext: { userId: 'usr_member', positions: [], permissions: [], systemPermissions: [] }, + } as any); + console.log('HTTP', res.response?.status, JSON.stringify(res.response?.body).slice(0, 3000)); + expect(true).toBe(true); + }); +}); From fa9d84f77bf3ed1e19f5bc0a02b181ecb74ce181 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:19:16 +0000 Subject: [PATCH 3/4] test(runtime): get_record_context parity rig over one real kernel, /mcp and stdio answer one caller with the same bytes Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .../domains/mcp-record-context-37175.test.ts | 254 ------------- .../mcp-record-context-tools-bridge.test.ts | 338 +++++++++++++++++- 2 files changed, 336 insertions(+), 256 deletions(-) delete mode 100644 packages/runtime/src/domains/mcp-record-context-37175.test.ts diff --git a/packages/runtime/src/domains/mcp-record-context-37175.test.ts b/packages/runtime/src/domains/mcp-record-context-37175.test.ts deleted file mode 100644 index 0b8298e05ec..00000000000 --- a/packages/runtime/src/domains/mcp-record-context-37175.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * WIP PROBE, not a deliverable: the bring-up of the record-context HTTP/stdio - * parity rig, kept on this branch so the work resumes from it. - * - * What it measured at ad604c10: every pack the protocol's merged listing - * serves carries the `_diagnostics` decoration (`decorateMetadataItem`), and - * the executor's strict `AiContextSchema` parse (`parsedContextPacks`) drops - * the row, so both doors answer "no context pack" for a valid pack. With - * `RC_STRIP=1` the rig strips the decoration (a CONTROL only) and the HTTP door - * reads the pack. The stdio half still answers RECORD_NOT_FOUND for the same - * row: its key-resolved caller is not yet the HTTP caller. - */ - -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; -import { SysMetadataAuditObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; -import { PermissionSetSchema } from '@objectstack/spec/security'; -import { ObjectQL } from '@objectstack/objectql'; -import { SqlDriver } from '@objectstack/driver-sql'; -import { SecurityPlugin } from '@objectstack/plugin-security'; -import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; -import { MCPServerPlugin, MCPServerRuntime } from '@objectstack/mcp'; -import { RecordContextServicePlugin } from '@objectstack/service-record-context'; -import { HttpDispatcher } from '../http-dispatcher.js'; -import '@objectstack/metadata'; - -const PKG = 'com.objectstack.qa.record-context-37175'; -const OFF_PKG = 'com.objectstack.qa.record-context-37175-off'; -const all = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; - -describe('probe', () => { - let engine: ObjectQL; - const services: Record = {}; - const stdioServices = new Map(); - let rpc: (method: string, params?: unknown) => Promise; - const contexts: any[] = []; - - beforeAll(async () => { - engine = new ObjectQL(); - const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); - const storeObjects = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject] as any[]; - await driver.initObjects(storeObjects); - engine.registerDriver(driver as any, true); - await engine.init(); - for (const o of storeObjects) engine.registry.registerObject(o, '@objectstack/platform-objects'); - engine.registerApp({ - id: PKG, name: 'record context rig', version: '1.0.0', type: 'plugin', scope: 'system', - objects: [ - { - name: 'rc_policy', label: 'Policy', nameField: 'title', sharingModel: 'public_read_write', - fields: { - title: { name: 'title', type: 'text', label: 'Title' }, - status: { name: 'status', type: 'select', label: 'Status', options: [{ value: 'active', label: 'Active' }] }, - secret_note: { name: 'secret_note', type: 'text', label: 'Secret note' }, - vault: { name: 'vault', type: 'lookup', reference: 'rc_vault', label: 'Vault' }, - content: { name: 'content', type: 'markdown', label: 'Content' }, - }, - }, - { - name: 'rc_revision', label: 'Revision', nameField: 'version', sharingModel: 'private', - fields: { - version: { name: 'version', type: 'text', label: 'Version' }, - policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, - }, - }, - { - name: 'rc_vault', label: 'Vault', enable: { apiEnabled: false }, sharingModel: 'public_read_write', - fields: { label: { name: 'label', type: 'text', label: 'Label' } }, - }, - { - name: 'rc_closed', label: 'Closed', enable: { apiEnabled: false }, sharingModel: 'public_read_write', - fields: { - version: { name: 'version', type: 'text', label: 'Version' }, - policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, - }, - }, - { - name: 'rc_hidden', label: 'Hidden', sharingModel: 'public_read_write', - fields: { - version: { name: 'version', type: 'text', label: 'Version' }, - policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, - }, - }, - { - name: 'sys_rc_note', label: 'Note', sharingModel: 'public_read_write', - fields: { - body: { name: 'body', type: 'text', label: 'Body' }, - policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, - }, - }, - ], - aiContexts: [ - { - name: 'rc_main', label: 'Policy document', object: 'rc_policy', - fields: ['title', 'status', 'secret_note', 'vault'], - related: [{ object: 'rc_revision', fields: ['version'] }], - body: { field: 'content' }, - }, - ], - } as never); - engine.registerApp({ - id: OFF_PKG, name: 'record context rig (off)', version: '1.0.0', type: 'plugin', scope: 'system', - objects: [{ - name: 'rc_off', label: 'Off', sharingModel: 'public_read_write', - fields: { - version: { name: 'version', type: 'text', label: 'Version' }, - policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, - }, - }], - } as never); - await engine.syncSchemas(); - await engine.insert('rc_vault', { id: 'v1', label: 'Vault 1', organization_id: 'org_1' }, { context: { isSystem: true } } as never); - await engine.insert('rc_policy', { id: 'p1', title: 'Fire cover', status: 'active', secret_note: 'hush', vault: 'v1', content: '# Scope\nCovers fire.\n# Exclusions\nFlood.', organization_id: 'org_1' }, { context: { isSystem: true } } as never); - await engine.insert('rc_revision', { id: 'r1', version: 'v1', policy: 'p1', owner_id: 'usr_member', organization_id: 'org_1' }, { context: { isSystem: true } } as never); - await engine.insert('rc_revision', { id: 'r2', version: 'v2', policy: 'p1', owner_id: 'usr_other', organization_id: 'org_1' }, { context: { isSystem: true } } as never); - - const sets = [ - PermissionSetSchema.parse({ - name: 'rc_member', label: 'Member', isDefault: true, - objects: { '*': all, rc_hidden: { allowRead: false, allowCreate: false, allowEdit: false, allowDelete: false } }, - fields: { 'rc_policy.secret_note': { readable: false, editable: false } }, - }), - ]; - const pluginServices: Record = { - manifest: { register: vi.fn() }, - objectql: engine, - metadata: { - get: async (type: string, name: string) => - (type === 'permission' ? sets.find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, - list: async (type: string) => (type === 'permission' ? sets : []), - }, - }; - const ctx = { - logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, - registerService: vi.fn((name: string, service: unknown) => { pluginServices[name] = service; }), - getService: (name: string) => { - if (!(name in pluginServices)) throw new Error(`service not registered: ${name}`); - return pluginServices[name]; - }, - }; - const security = new SecurityPlugin({ fallbackPermissionSet: 'rc_member' }); - await security.init(ctx as never); - await security.start(ctx as never); - await new RecordContextServicePlugin().init(ctx as never); - - const realProtocol = new ObjectStackProtocolImplementation(engine as any); - services.realProtocol = realProtocol; - services.protocol = process.env.RC_STRIP ? new Proxy(realProtocol as any, { - get(t, prop, r) { - if (prop === 'getMetaItems') { - return async (req: any) => { - const out: any = await t.getMetaItems(req); - if (req?.type !== 'ai_context') return out; - return { ...out, items: out.items.map(({ _diagnostics, ...rest }: any) => rest) }; - }; - } - const v = Reflect.get(t, prop, r); - return typeof v === 'function' ? v.bind(t) : v; - }, - }) : realProtocol; - services.security = pluginServices.security; - services.objectql = engine; - services['record-context'] = pluginServices['record-context']; - services.metadata = pluginServices.metadata; - - // stdio - process.env.OS_MCP_STDIO_API_KEY = 'osk_rc37175_probe_key_0000000000000000'; - const ql = new Proxy(engine as any, { - get(target, prop, receiver) { - if (prop === 'update') { - return async (object: string, data: unknown, options?: unknown) => - object === 'sys_api_key' ? {} : target.update(object, data, options); - } - if (prop === 'find') { - return async (object: string, query?: unknown, options?: unknown) => { - if (object === 'sys_api_key') return [{ id: 'k1', user_id: 'usr_member', revoked: false }]; - if (object === 'sys_user') return (query as any)?.where?.id === 'usr_member' ? [{ id: 'usr_member' }] : []; - if (object.startsWith('sys_') && object !== 'sys_metadata' && !target.registry.getObject(object)) return []; - contexts.push({ object, query, options }); - return target.find(object, query, options); - }; - } - const value = Reflect.get(target, prop, receiver); - return typeof value === 'function' ? value.bind(target) : value; - }, - }); - for (const [k, v] of Object.entries({ metadata: services.metadata, protocol: services.protocol, objectql: ql, security: services.security, 'record-context': services['record-context'] })) stdioServices.set(k, v); - const sctx: any = { - registerService: vi.fn((name: string, service: unknown) => stdioServices.set(name, service)), - getService: vi.fn((name: string) => { - if (!stdioServices.has(name)) throw new Error(`Service "${name}" not found`); - return stdioServices.get(name); - }), - replaceService: vi.fn(), - getServices: vi.fn(() => stdioServices), - hook: vi.fn(), - trigger: vi.fn(async () => {}), - logger: { info: vi.fn(), warn: vi.fn((...a: any[]) => console.log('WARN', ...a)), error: vi.fn((...a: any[]) => console.log('ERR', ...a)), debug: vi.fn() }, - getKernel: vi.fn(() => ({})), - }; - const plugin = new MCPServerPlugin({ autoStart: true }); - await plugin.init(sctx); - const runtime = stdioServices.get('mcp') as MCPServerRuntime; - vi.spyOn(runtime, 'start').mockResolvedValue(undefined); - await plugin.start(sctx); - const waiting = new Map void>(); - let nextId = 1; - const transport: any = { - onmessage: undefined, onclose: undefined, onerror: undefined, - async start() {}, async close() { transport.onclose?.(); }, - async send(message: any) { - const resolve = typeof message?.id === 'number' ? waiting.get(message.id) : undefined; - if (resolve) { waiting.delete(message.id); resolve(message); } - }, - }; - rpc = (method: string, params?: unknown) => new Promise((resolve) => { - const id = nextId++; - waiting.set(id, resolve); - transport.onmessage?.({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) }); - }); - await runtime.server.connect(transport as never); - await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'probe', version: '0' } }); - transport.onmessage?.({ jsonrpc: '2.0', method: 'notifications/initialized' }); - }, 60_000); - - afterAll(async () => { - vi.restoreAllMocks(); - try { await engine?.destroy(); } catch { /* noop */ } - }); - - it('probes', async () => { - console.log('PACKS', JSON.stringify(await services.protocol.getMetaItems({ type: 'ai_context' })).slice(0, 400)); - const s = await rpc('tools/call', { name: 'get_record_context', arguments: { objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' } }); - console.log('STDIO', JSON.stringify(s).slice(0, 3000)); - const ec = contexts.find((c) => c.object === 'rc_policy'); - console.log('CTX', String(JSON.stringify(ec?.options ?? ec?.query ?? contexts.map((c) => c.object))).slice(0, 1500)); - const mcp: any = { - handleHttpRequest: (req: Request, opts: any) => new MCPServerRuntime({ name: 'objectstack', version: '0.0.0' }).handleHttpRequest(req, opts), - }; - const allSvc: Record = { ...services, mcp }; - const get = (n: string) => allSvc[n] ?? null; - const kernel = { getService: get, getServiceAsync: async (n: string) => get(n), context: { getService: get } } as any; - const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); - const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_record_context', arguments: { objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' } } }; - const res = await dispatcher.handleMcp(body, { - request: new Request('http://localhost/api/v1/mcp', { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify(body) }), - response: {}, environmentId: undefined, - executionContext: { userId: 'usr_member', positions: [], permissions: [], systemPermissions: [] }, - } as any); - console.log('HTTP', res.response?.status, JSON.stringify(res.response?.body).slice(0, 3000)); - expect(true).toBe(true); - }); -}); diff --git a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts index 0e0cfa2cb4d..af400d545ac 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -31,8 +31,10 @@ import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { SecurityPlugin } from '@objectstack/plugin-security'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; -import { MCPServerRuntime } from '@objectstack/mcp'; -import { createRecordContextTools } from '@objectstack/service-record-context'; +import { assembleExecutionContext, resolveAuthzContext } from '@objectstack/core'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { MCPServerPlugin, MCPServerRuntime } from '@objectstack/mcp'; +import { createRecordContextTools, RecordContextServicePlugin } from '@objectstack/service-record-context'; import { HttpDispatcher } from './http-dispatcher.js'; import { buildMcpBridge, @@ -328,3 +330,335 @@ describe('[ADR-0160 D4] the /mcp route answers through a package pack the real p expect(bare.payload.error.message).toContain('rcdp-rcd_brief'); }); }); + +/** + * [ADR-0149 D7 · ADR-0160 D3/D4] The two MCP doors over ONE real kernel, for + * ONE caller: the `/mcp` route (`HttpDispatcher.handleMcp` into the real + * `MCPServerRuntime`, this package's HTTP data bridge) and the long-lived + * stdio session of the real `MCPServerPlugin` (`createStdioDataBridge`), + * both answering through the real `record-context` service + * (`RecordContextServicePlugin`) over a real `ObjectQL` on `SqlDriver`, the + * real `SecurityPlugin` and the real protocol. Nothing of the metadata plane, + * the data plane or the executor is a double. + * + * The caller is one identity: the stdio session resolves its + * `OS_MCP_STDIO_API_KEY` through `resolveAuthzContext` and + * `assembleExecutionContext`, and the `/mcp` request is handed the context + * those same two calls assemble for the same key. Every case below asks both + * doors the same call and requires the same bytes back, refusals included. + * + * Where `main` differs from ADR-0160 as amended 2026-11-25 (a related child + * THIS caller is not served is left out and stated, not refused), the case + * pins what the executor does today and says so in its title. + */ +describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: the /mcp door and the stdio door answer one caller with the same bytes', () => { + const PKG = 'com.objectstack.qa.record-context-parity'; + const OFF_PKG = 'com.objectstack.qa.record-context-parity-off'; + const KEY = 'osk_rc_parity_key_000000000000000000000000'; + const READ_ALL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + const READ_NONE = { allowRead: false, allowCreate: false, allowEdit: false, allowDelete: false }; + let engine: ObjectQL; + let protocol: ObjectStackProtocolImplementation; + let dispatcher: HttpDispatcher; + let caller: ExecutionContext; + let rpc: (method: string, params?: unknown) => Promise; + /** The execution context the stdio door handed the engine, per object read. */ + const stdioReads: Array<{ object: string; context: any }> = []; + + beforeAll(async () => { + vi.stubEnv('OS_MCP_STDIO_API_KEY', KEY); + engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const store = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject] as any[]; + await driver.initObjects(store); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of store) engine.registry.registerObject(o, '@objectstack/platform-objects'); + const child = (name: string, label: string, extra: Record = {}) => ({ + name, label, nameField: 'version', sharingModel: 'public_read_write', ...extra, + fields: { + version: { name: 'version', type: 'text', label: 'Version' }, + policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, + }, + }); + engine.registerApp({ + id: PKG, name: 'record context parity', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [ + { + name: 'rc_policy', label: 'Policy', nameField: 'title', sharingModel: 'public_read_write', + fields: { + title: { name: 'title', type: 'text', label: 'Title' }, + status: { name: 'status', type: 'select', label: 'Status', options: [{ value: 'active', label: 'Active' }] }, + secret_note: { name: 'secret_note', type: 'text', label: 'Secret note' }, + vault: { name: 'vault', type: 'lookup', reference: 'rc_vault', label: 'Vault' }, + content: { name: 'content', type: 'markdown', label: 'Content' }, + }, + }, + child('rc_revision', 'Revision'), + child('rc_closed', 'Closed', { enable: { apiEnabled: false } }), + child('rc_hidden', 'Hidden'), + { + name: 'rc_vault', label: 'Vault', sharingModel: 'public_read_write', enable: { apiEnabled: false }, + fields: { label: { name: 'label', type: 'text', label: 'Label' } }, + }, + ], + aiContexts: [ + { + name: 'rc_main', label: 'Policy document', object: 'rc_policy', + fields: ['title', 'status', 'secret_note', 'vault'], + related: [{ object: 'rc_revision', fields: ['version'] }], + body: { field: 'content' }, + }, + { name: 'rc_unserved_child', label: 'Unserved child', object: 'rc_policy', fields: ['title'], related: [{ object: 'rc_hidden', fields: ['version'] }] }, + { name: 'rc_exposure_child', label: 'Exposure child', object: 'rc_policy', fields: ['title'], related: [{ object: 'rc_closed', fields: ['version'] }] }, + { name: 'rc_disabled_child', label: 'Disabled child', object: 'rc_policy', fields: ['title'], related: [{ object: 'rc_off', fields: ['version'] }] }, + ], + } as never); + engine.registerApp({ + id: OFF_PKG, name: 'record context parity (off)', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [child('rc_off', 'Off')], + } as never); + await engine.syncSchemas(); + const sys = { context: { isSystem: true } } as never; + await engine.insert('rc_vault', { id: 'v1', label: 'Vault 1', organization_id: 'org_1' }, sys); + await engine.insert('rc_policy', { + id: 'p1', title: 'Fire cover', status: 'active', secret_note: 'hush', vault: 'v1', + content: '# Scope\nCovers fire.\n# Exclusions\nFlood.', organization_id: 'org_1', + }, sys); + await engine.insert('rc_revision', { id: 'r1', version: 'v1', policy: 'p1', owner_id: 'usr_member', organization_id: 'org_1' }, sys); + await engine.insert('rc_revision', { id: 'r2', version: 'v2', policy: 'p1', owner_id: 'usr_other', organization_id: 'org_1' }, sys); + await engine.insert('rc_hidden', { id: 'h1', version: 'h', policy: 'p1', organization_id: 'org_1' }, sys); + engine.registry.disablePackage(OFF_PKG); + + const sets = [PermissionSetSchema.parse({ + name: 'rc_member', label: 'Member', isDefault: true, + objects: { '*': READ_ALL, rc_hidden: READ_NONE }, + fields: { 'rc_policy.secret_note': { readable: false, editable: false } }, + rowLevelSecurity: [{ name: 'rc_own_revisions', object: 'rc_revision', operation: 'select', using: 'owner_id == current_user.id' }], + })]; + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? sets.find((s) => s.name === name) : engine.getSchema(name)) ?? null, + list: async (type: string) => (type === 'permission' ? sets : []), + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn((name: string, service: unknown) => { services[name] = service; }), + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const security = new SecurityPlugin({ fallbackPermissionSet: 'rc_member' }); + await security.init(ctx as never); + await security.start(ctx as never); + await new RecordContextServicePlugin().init(ctx as never); + protocol = new ObjectStackProtocolImplementation(engine as any); + + // The key's two auth tables are not part of this kernel: the engine + // answers them for the one key, and every other read is the engine's. + const keyedQl = new Proxy(engine as any, { + get(target, prop, receiver) { + if (prop === 'update') { + return async (object: string, data: unknown, options?: unknown) => + object === 'sys_api_key' ? {} : target.update(object, data, options); + } + if (prop === 'find') { + return async (object: string, query?: any, options?: any) => { + if (object === 'sys_api_key') { + return [{ id: 'k1', user_id: 'usr_member', revoked: false, active_organization_id: 'org_1' }]; + } + if (object === 'sys_user') return query?.where?.id === 'usr_member' ? [{ id: 'usr_member' }] : []; + if (object === 'sys_member') return [{ id: 'm1', user_id: 'usr_member', organization_id: 'org_1', role: 'member' }]; + if (object.startsWith('sys_') && !target.registry.getObject(object)) return []; + stdioReads.push({ object, context: query?.context ?? options?.context }); + return target.find(object, query, options); + }; + } + const value = Reflect.get(target, prop, receiver); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + caller = assembleExecutionContext({ + authz: await resolveAuthzContext({ ql: keyedQl, headers: { 'x-api-key': KEY }, tenancyPosture: undefined, client: { transport: 'stdio' } } as never), + oauth: undefined, localization: undefined, requestLocale: undefined, accessToken: undefined, + } as never) as ExecutionContext; + + // The stdio door: the real plugin's long-lived session, over an in-process transport. + const stdioServices = new Map(Object.entries({ + metadata: services.metadata, protocol, objectql: keyedQl, security: services.security, + 'record-context': services['record-context'], + })); + const sctx: any = { + registerService: vi.fn((name: string, service: unknown) => stdioServices.set(name, service)), + getService: vi.fn((name: string) => { + if (!stdioServices.has(name)) throw new Error(`Service "${name}" not found`); + return stdioServices.get(name); + }), + replaceService: vi.fn(), + getServices: vi.fn(() => stdioServices), + hook: vi.fn(), + trigger: vi.fn(async () => {}), + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(() => ({})), + }; + const plugin = new MCPServerPlugin({ autoStart: true }); + await plugin.init(sctx); + const stdioRuntime = stdioServices.get('mcp') as MCPServerRuntime; + vi.spyOn(stdioRuntime, 'start').mockResolvedValue(undefined); + await plugin.start(sctx); + const waiting = new Map void>(); + let nextId = 1; + const transport: any = { + async start() {}, + async close() { transport.onclose?.(); }, + async send(message: any) { + const resolve = typeof message?.id === 'number' ? waiting.get(message.id) : undefined; + if (resolve) { waiting.delete(message.id); resolve(message); } + }, + }; + rpc = (method, params) => new Promise((resolve) => { + const id = nextId++; + waiting.set(id, resolve); + transport.onmessage?.({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) }); + }); + await stdioRuntime.server.connect(transport as never); + await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'parity', version: '0' } }); + transport.onmessage?.({ jsonrpc: '2.0', method: 'notifications/initialized' }); + + // The /mcp door: the dispatcher over the same kernel's services and a fresh MCP runtime per request. + const httpRuntime = new MCPServerRuntime({ name: 'objectstack', version: '0.0.0' }); + const served: Record = { + ...services, + protocol, + mcp: { handleHttpRequest: (req: Request, o: any) => httpRuntime.handleHttpRequest(req, o) }, + }; + const get = (n: string) => served[n] ?? null; + dispatcher = new HttpDispatcher({ getService: get, getServiceAsync: async (n: string) => get(n), context: { getService: get } } as any, undefined, { enforceProjectMembership: false }); + }, 60_000); + + afterAll(async () => { + vi.unstubAllEnvs(); + try { await engine?.destroy(); } catch { /* best effort */ } + }); + + interface DoorAnswer { isError: boolean; text: string } + + const overHttp = async (args: Record): Promise => { + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_record_context', arguments: args } }; + const res = await dispatcher.handleMcp(body, { + request: new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }), + response: {}, + environmentId: undefined, + executionContext: caller, + } as any); + expect(res.response?.status).toBe(200); + const result = (res.response?.body as any)?.result; + return { isError: result?.isError === true, text: result?.content?.[0]?.text }; + }; + const overStdio = async (args: Record): Promise => { + const frame = await rpc('tools/call', { name: 'get_record_context', arguments: args }); + return { isError: frame?.result?.isError === true, text: frame?.result?.content?.[0]?.text }; + }; + /** Both doors, one call: the same bytes, or the case fails here. */ + const both = async (args: Record) => { + const http = await overHttp(args); + const stdio = await overStdio(args); + expect(typeof http.text).toBe('string'); + expect(stdio).toEqual(http); + return { isError: http.isError, text: http.text, payload: JSON.parse(http.text) }; + }; + + it('precondition: the stdio session reads as the caller the /mcp request carries', async () => { + expect(caller).toMatchObject({ userId: 'usr_member', tenantId: 'org_1' }); + stdioReads.length = 0; + await overStdio({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + const root = stdioReads.find((r) => r.object === 'rc_policy'); + expect(root?.context).toMatchObject({ + userId: caller.userId, tenantId: caller.tenantId, permissions: caller.permissions, positions: caller.positions, + }); + }); + + it('a record through its package pack: a hidden field stated, an unopenable lookup not shown, an unreadable related row absent', async () => { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(answer.isError).toBe(false); + const { data, notes } = answer.payload; + expect(data.pack).toEqual({ name: 'rc_main', label: 'Policy document' }); + expect(data.record).toEqual({ object: 'rc_policy', id: 'p1', displayName: 'Fire cover' }); + // The hidden field (FLS) is not carried and not named; the notes state it. + expect(data.fields.map((f: { name: string }) => f.name)).toEqual(['title', 'status', 'vault']); + expect(answer.text).not.toContain('secret_note'); + expect(answer.text).not.toContain('hush'); + expect(notes.map((n: { kind: string }) => n.kind)).toEqual(['not_visible']); + // [card amendment 4] The door decides an expansion target's API exposure: + // `rc_vault` is `apiEnabled: false`, so its row is never expanded or named. + expect(data.fields.find((f: { name: string }) => f.name === 'vault')).toEqual({ name: 'vault', label: 'Vault', notVisible: true }); + expect(answer.text).not.toContain('Vault 1'); + // The related list is read as the caller: the row its row rule refuses is absent. + expect(data.related).toHaveLength(1); + expect(data.related[0]).toMatchObject({ object: 'rc_revision', field: 'policy' }); + expect(data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['r1']); + expect(data.body).toEqual({ field: 'content', label: 'Content', text: '# Scope\nCovers fire.\n# Exclusions\nFlood.' }); + }); + + it('the root the caller may not read is refused before any pack is looked up', async () => { + const answer = await both({ objectName: 'rc_hidden', recordId: 'h1', context: 'rc_main' }); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: expect.any(String), status: expect.any(Number) }); + expect(answer.text).not.toContain('rc_main'); + }); + + it('[today; ADR-0160 as amended says left out and stated] a related child this caller is not served refuses the call, unnamed', async () => { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_unserved_child' }); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(answer.text).not.toContain('rc_hidden'); + }); + + it('a related child its API exposure refuses refuses the call, named (the caller\'s schema shows it)', async () => { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_exposure_child' }); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(answer.payload.error.message).toContain("'rc_closed'"); + }); + + it('a related child whose package is disabled (OBJECT_PACKAGE_DISABLED) refuses the call, unnamed', async () => { + await expect(protocol.getMetaItemForExecution({ type: 'object', name: 'rc_off' } as never)).rejects.toMatchObject({ code: 'OBJECT_PACKAGE_DISABLED' }); + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_disabled_child' }); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(answer.text).not.toContain('rc_off'); + }); + + it('an anchor the body does not resolve is one coded answer', async () => { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main', anchor: 'nowhere' }); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: 'RESOURCE_NOT_FOUND', status: 404 }); + }); + + it('a pack served from the metadata registry (saved at run time, not shipped by the stack) is read', async () => { + await protocol.saveMetaItem({ + type: 'ai_context', name: 'rc_registry', + item: { name: 'rc_registry', label: 'Registry brief', object: 'rc_policy', fields: ['title', 'status'] }, + } as never); + const listed: any = await protocol.getMetaItems({ type: 'ai_context' }); + const row = listed.items.find((p: { name?: string }) => p.name === 'rc_registry'); + expect(row).toBeDefined(); + expect(row?._packageId).toBeUndefined(); + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_registry' }); + expect(answer.isError).toBe(false); + expect(answer.payload.data.pack).toEqual({ name: 'rc_registry', label: 'Registry brief' }); + expect(answer.payload.data.fields.map((f: { name: string; value: unknown }) => [f.name, f.value])).toEqual([ + ['title', 'Fire cover'], + ['status', 'active'], + ]); + }); +}); From 9c9d8a634936381709d276fa430cacb9fc174921 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:22:05 +0000 Subject: [PATCH 4/4] test(runtime): pin the root refusal against get_record's answer on both doors Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .../mcp-record-context-tools-bridge.test.ts | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts index af400d545ac..bf084dd46b9 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -19,6 +19,12 @@ * the protocol's served listing decorates with the read path's `_diagnostics`, * is the pack `get_record_context` answers through on the `/mcp` route — the * door hands the executor the authored pack, not the serving envelope. + * + * And the two doors over one real kernel for one caller (the last `describe`): + * the `/mcp` route and the real `MCPServerPlugin` stdio session, through the + * real `record-context` service, answer every case with the same bytes — + * refusals included — and a pack saved at run time to the metadata registry + * is read as a shipped one is. */ import { afterAll, beforeAll, describe, it, expect, vi } from 'vitest'; @@ -459,8 +465,10 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: await new RecordContextServicePlugin().init(ctx as never); protocol = new ObjectStackProtocolImplementation(engine as any); - // The key's two auth tables are not part of this kernel: the engine - // answers them for the one key, and every other read is the engine's. + // The key's auth tables (`sys_api_key`, `sys_user`, `sys_member`) are + // not part of this kernel: these answers stand in for them, for the one + // key (owner `usr_member`, active in `org_1`); every other read is the + // engine's, and the stdio door's are recorded with their context. const keyedQl = new Proxy(engine as any, { get(target, prop, receiver) { if (prop === 'update') { @@ -548,8 +556,8 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: interface DoorAnswer { isError: boolean; text: string } - const overHttp = async (args: Record): Promise => { - const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_record_context', arguments: args } }; + const overHttp = async (args: Record, tool = 'get_record_context'): Promise => { + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }; const res = await dispatcher.handleMcp(body, { request: new Request('http://localhost/api/v1/mcp', { method: 'POST', @@ -564,14 +572,14 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: const result = (res.response?.body as any)?.result; return { isError: result?.isError === true, text: result?.content?.[0]?.text }; }; - const overStdio = async (args: Record): Promise => { - const frame = await rpc('tools/call', { name: 'get_record_context', arguments: args }); + const overStdio = async (args: Record, tool = 'get_record_context'): Promise => { + const frame = await rpc('tools/call', { name: tool, arguments: args }); return { isError: frame?.result?.isError === true, text: frame?.result?.content?.[0]?.text }; }; /** Both doors, one call: the same bytes, or the case fails here. */ - const both = async (args: Record) => { - const http = await overHttp(args); - const stdio = await overStdio(args); + const both = async (args: Record, tool = 'get_record_context') => { + const http = await overHttp(args, tool); + const stdio = await overStdio(args, tool); expect(typeof http.text).toBe('string'); expect(stdio).toEqual(http); return { isError: http.isError, text: http.text, payload: JSON.parse(http.text) }; @@ -609,11 +617,14 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(data.body).toEqual({ field: 'content', label: 'Content', text: '# Scope\nCovers fire.\n# Exclusions\nFlood.' }); }); - it('the root the caller may not read is refused before any pack is looked up', async () => { + it('a root the caller may not read is refused before any pack is looked up, as get_record refuses it', async () => { const answer = await both({ objectName: 'rc_hidden', recordId: 'h1', context: 'rc_main' }); expect(answer.isError).toBe(true); - expect(answer.payload.error).toMatchObject({ code: expect.any(String), status: expect.any(Number) }); + expect(answer.payload.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); expect(answer.text).not.toContain('rc_main'); + const record = await both({ objectName: 'rc_hidden', recordId: 'h1' }, 'get_record'); + expect(record.isError).toBe(true); + expect(answer.payload.error).toEqual(record.payload.error); }); it('[today; ADR-0160 as amended says left out and stated] a related child this caller is not served refuses the call, unnamed', async () => {