diff --git a/.changeset/37243-record-context-authored-packs.md b/.changeset/37243-record-context-authored-packs.md new file mode 100644 index 00000000000..5953a0f49e3 --- /dev/null +++ b/.changeset/37243-record-context-authored-packs.md @@ -0,0 +1,16 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +'@objectstack/service-record-context': patch +--- + +fix(mcp,runtime): `get_record_context` reads a package's context packs on both MCP doors + +Clause-②: no +Metadata-protocol: none + +A deployment serving context packs (`aiContexts`) answered every `get_record_context` call with `RESOURCE_NOT_FOUND` ("No context pack named … reads object …"), on the HTTP `/mcp` route and on stdio alike. Both doors read the packs from the protocol's served `ai_context` listing, which carries the read path's `_diagnostics` on every item; the record-context executor parses each pack with the closed `AiContextSchema`, so it dropped every one as an unrecognized key. + +Both doors now hand the executor the authored packs: the listing passes through `stripReadDecorations` (`@objectstack/spec/kernel`), which removes exactly the read decorations (`METADATA_READ_DECORATIONS`) and keeps the ADR-0010 protection envelope (`_packageId`, `_provenance`, `_lock`, …) the schema declares. The executor's parse is unchanged. Nothing to do on upgrade. + +For anyone implementing a `RecordContextDoor`: `listContextPacks` hands over the authored packs with the read decorations removed (`stripReadDecorations`), or the executor drops them. diff --git a/packages/mcp/package.json b/packages/mcp/package.json index f153b9cf7cc..ea43c9f8537 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -39,6 +39,8 @@ "zod": "^4.6.6" }, "devDependencies": { + "@objectstack/driver-sql": "workspace:*", + "@objectstack/metadata-protocol": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/service-analytics": "workspace:*", "@objectstack/service-record-context": "workspace:*", diff --git a/packages/mcp/src/mcp-record-context-tools.test.ts b/packages/mcp/src/mcp-record-context-tools.test.ts index 01fef07b6c6..65257814879 100644 --- a/packages/mcp/src/mcp-record-context-tools.test.ts +++ b/packages/mcp/src/mcp-record-context-tools.test.ts @@ -16,6 +16,10 @@ * (order of judgement, naming bound, field and row level, the body) are * pinned with the service, in `service-record-context`'s tests; the HTTP * bridge's door wiring in `packages/runtime/src/mcp-record-context-tools-bridge.test.ts`. + * + * And over the real protocol (no protocol double): a package pack the + * protocol's served listing decorates with `_diagnostics` is the pack the + * stdio door answers through — the door hands the executor the authored pack. */ import { describe, expect, it, vi } from 'vitest'; @@ -24,6 +28,10 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { GET_RECORD_CONTEXT_TOOL_NAME, MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE } from '@objectstack/spec/ai'; import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; import { createRecordContextTools } from '@objectstack/service-record-context'; +import { ObjectQL } from '@objectstack/objectql/core'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysMetadataObject } from '@objectstack/metadata-core'; import { MCPServerRuntime } from './mcp-server-runtime.js'; import type { McpDataBridge } from './mcp-http-tools.js'; import { createStdioDataBridge } from './stdio-data-bridge.js'; @@ -294,3 +302,46 @@ describe('[ADR-0160 D4] get_record_context — the gates the record tools put be expect(http.payload.error.message).toContain("'closed_revision'"); }); }); + +describe('[ADR-0160 D4] get_record_context — a package pack the real protocol serves', () => { + it('the served listing carries the read decoration, and both doors answer through the pack', async () => { + const engineOfRecord = new ObjectQL(); + const store = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); + await store.initObjects([SysMetadataObject] as never); + engineOfRecord.registerDriver(store as never, true); + await engineOfRecord.init(); + engineOfRecord.registry.registerObject(SysMetadataObject as never, '@objectstack/platform-objects'); + engineOfRecord.registerApp({ + id: 'com.objectstack.qa.record-context-stdio', + name: 'record context stdio', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [OBJECTS.policy, OBJECTS.policy_revision], + aiContexts: [PACK], + } as never); + const protocol = new ObjectStackProtocolImplementation(engineOfRecord as never); + try { + // Precondition: the protocol serves the pack decorated, as `/meta/ai_context` does. + // Were it served bare, this case could not tell a door that strips from one that does not. + const listed = (await protocol.getMetaItems({ type: 'ai_context' })) as { items: Array> }; + const served = listed.items.find((p) => p.name === PACK.name); + expect(served?._packageId).toBe('com.objectstack.qa.record-context-stdio'); + expect(served).toHaveProperty('_diagnostics'); + + // No pack on the metadata service: the only listing is the protocol's. + const bridge = stdioBridge([], true, protocol as unknown as Record); + const { http, stdio } = await callBoth(bridge, GET_RECORD_CONTEXT_TOOL_NAME, { + objectName: 'policy', + recordId: 'p1', + context: PACK.name, + }); + expect(http.isError, JSON.stringify(http.payload)).toBe(false); + expect(stdio).toEqual(http); + expect(http.payload.data.pack.name).toBe(PACK.name); + expect(http.payload.data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['r1', 'r2']); + } finally { + await engineOfRecord.destroy(); + } + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 4f5b3da3bbf..6bd64f50715 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -131,6 +131,9 @@ import { redactStoredMetadataRow, STORED_METADATA_BODY_COLUMN, STORED_METADATA_TYPE_COLUMN, + // [ADR-0160 D4] The read path's own decorations, removed from the + // context-pack listing before the record-context executor parses it. + stripReadDecorations, } from '@objectstack/spec/kernel'; import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; import { resolveObjectSortability } from '@objectstack/spec/api'; @@ -1878,12 +1881,17 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge ((await localizedView.getObject(name)) as Record | undefined) ?? null, publishedObjectDefinitionOf: async (name: string) => ((await readObjectDeclaration(reads, name)) as Record | undefined) ?? null, + // The authored packs, not the serving envelope: the protocol's served + // listing stamps every item with `_diagnostics`, which the executor's + // closed `AiContextSchema` refuses, dropping every pack. The read + // decorations go (`stripReadDecorations`); the protection envelope the + // schema declares stays. listContextPacks: async () => { const protocolService = protocol?.(); if (protocolService && typeof protocolService.getMetaItems === 'function') { - return metaItemsArray(await protocolService.getMetaItems({ type: 'ai_context' })); + return metaItemsArray(await protocolService.getMetaItems({ type: 'ai_context' })).map(stripReadDecorations); } - return (await metadataService.list('ai_context')) ?? []; + return ((await metadataService.list('ai_context')) ?? []).map(stripReadDecorations); }, get: (object: string, id: string) => self.get(object, id), query: (object: string, o: Parameters[1]) => self.query(object, o), diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts index b02430ed386..ff949e7c934 100644 --- a/packages/mcp/vitest.config.ts +++ b/packages/mcp/vitest.config.ts @@ -79,6 +79,12 @@ export default defineConfig({ { find: /^@objectstack\/objectql\/core$/, replacement: path.resolve(__dirname, '../objectql/src/core.ts') }, { find: /^@objectstack\/rest$/, replacement: path.resolve(__dirname, '../rest/src/index.ts') }, { find: /^@objectstack\/service-analytics$/, replacement: path.resolve(__dirname, '../services/service-analytics/src/index.ts') }, + // [ADR-0160 D4] The protocol, so `get_record_context`'s pack + // listing is read off the real `ObjectStackProtocolImplementation` in the + // checkout, decorations included, never a build of it. + { find: /^@objectstack\/metadata-protocol$/, replacement: path.resolve(__dirname, '../metadata-protocol/src/index.ts') }, + // …over a real store: an in-memory SQLite `SqlDriver` backs the `sys_metadata` read the protocol's listing makes. + { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../drivers/driver-sql/src/index.ts') }, // [ADR-0160] The record-context executor, so `get_record_context`'s transport parity runs the real one. { find: /^@objectstack\/service-record-context$/, replacement: path.resolve(__dirname, '../services/service-record-context/src/index.ts') }, ], 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/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 98f20ba0ecc..6c1db76058a 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -14,6 +14,9 @@ import type { ErrorCode, MetadataProtocol } from '@objectstack/spec/api'; import type { ISecurityService } from '@objectstack/spec/contracts'; // [#32442] The ONE reading of `enable.aiReadable` (ruling A, #32865). import { isAiReadExposed } from '@objectstack/spec/data'; +// [ADR-0160 D4] The read path's own decorations, removed from the context-pack +// listing before the record-context executor parses it (`listContextPacks`). +import { stripReadDecorations } from '@objectstack/spec/kernel'; import { BUILTIN_MEMBERSHIP_ROLES, MEMBERSHIP_REACH, @@ -1688,12 +1691,19 @@ export function buildMcpBridge( return (localized ?? def) as Record; }, publishedObjectDefinitionOf: async (name) => ((await readServedObject(name)) ?? null) as Record | null, + // The authored packs, not the serving envelope: the merged listing + // is the one `/meta/ai_context` serves, so every item carries the + // read path's `_diagnostics`, which the executor's closed + // `AiContextSchema` refuses as an unrecognized key — every pack + // would be dropped. `stripReadDecorations` removes exactly the + // read decorations (`METADATA_READ_DECORATIONS`) and keeps the + // ADR-0010 protection envelope the schema declares. listContextPacks: async () => { const merged = await actionExec.readMergedItems(await getProtocol(), 'ai_context'); - if (merged !== undefined) return merged; + if (merged !== undefined) return merged.map(stripReadDecorations); const meta: any = await getMeta(); const listed = typeof meta?.list === 'function' ? await meta.list('ai_context') : []; - return Array.isArray(listed) ? listed : []; + return Array.isArray(listed) ? listed.map(stripReadDecorations) : []; }, })); } 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 a2a7335b785..25d1546ac58 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -14,12 +14,25 @@ * family, so a token without `data:read` is carried neither member and never * has the service resolved. The executor itself is pinned with the service; * the tool on both transports in `packages/mcp/src/mcp-record-context-tools.test.ts`. + * + * And, over the real protocol (no protocol double): a valid package pack, which + * 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. */ -import { describe, it, expect, vi } from 'vitest'; +import { afterAll, beforeAll, describe, it, expect, vi } from 'vitest'; // Paid during collection, not inside a clocked case: the dispatcher reaches // `standalone-stack.ts`, whose function body `import()`s it (`scripts/check-test-source-alias.mjs`). import '@objectstack/metadata'; +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 { MCPServerRuntime } from '@objectstack/mcp'; +import { createRecordContextTools } from '@objectstack/service-record-context'; import { HttpDispatcher } from './http-dispatcher.js'; import { buildMcpBridge, @@ -164,3 +177,113 @@ describe('[ADR-0160 D4] the /mcp route carries get_record_context only where the expect(resolved).not.toContain('record-context'); }); }); + +/** + * The `/mcp` route over the REAL protocol: a real `ObjectQL` over a real + * `SqlDriver`, the security layer, `ObjectStackProtocolImplementation` over + * that engine, the real executor and the real MCP runtime. Nothing here is a + * double of the metadata plane, so the pack reaches the executor exactly as + * the protocol serves it. + */ +describe('[ADR-0160 D4] the /mcp route answers through a package pack the real protocol serves', () => { + const PKG_ID = 'com.objectstack.qa.record-context-door'; + let engine: ObjectQL; + let protocol: ObjectStackProtocolImplementation; + let kernel: any; + + beforeAll(async () => { + 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'); + engine.registerApp({ + id: PKG_ID, name: 'record context door', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [{ + name: 'rcd_policy', label: 'Policy', nameField: 'title', sharingModel: 'public_read_write', + fields: { + title: { name: 'title', type: 'text', label: 'Title' }, + status: { name: 'status', type: 'text', label: 'Status' }, + }, + }], + aiContexts: [{ name: 'rcd_policy_document', label: 'Policy document', object: 'rcd_policy', fields: ['title', 'status'] }], + } as never); + await engine.syncSchemas(); + await engine.insert('rcd_policy', { id: 'p1', title: 'Fire cover', status: 'active', organization_id: 'org_1' }, { context: { isSystem: true } } as never); + + const all = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + const sets = [PermissionSetSchema.parse({ name: 'rcd_member', label: 'Member', isDefault: true, objects: { '*': all } })]; + 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: 'rcd_member' }); + await security.init(ctx as never); + await security.start(ctx as never); + + protocol = new ObjectStackProtocolImplementation(engine as any); + const tools = createRecordContextTools(); + const runtime = new MCPServerRuntime({ name: 'objectstack', version: '0.0.0' }); + const served: Record = { + ...services, + protocol, + 'record-context': { recordContextTools: () => tools }, + mcp: { handleHttpRequest: (req: Request, o: any) => runtime.handleHttpRequest(req, o) }, + }; + const get = (n: string) => served[n] ?? null; + kernel = { getService: get, getServiceAsync: async (n: string) => get(n), context: { getService: get } }; + }, 60_000); + + afterAll(async () => { + try { await engine?.destroy(); } catch { /* best effort */ } + }); + + it('the served listing carries the read decoration, and the call is answered through the pack', async () => { + // Precondition: the protocol serves the pack decorated, as `/meta/ai_context` does. + // Were it served bare, this case could not tell a door that strips from one that does not. + const listed: any = await protocol.getMetaItems({ type: 'ai_context' }); + const served = listed.items.find((p: { name?: string }) => p.name === 'rcd_policy_document'); + expect(served?._packageId).toBe(PKG_ID); + expect(served).toHaveProperty('_diagnostics'); + + 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: 'rcd_policy', recordId: 'p1', context: 'rcd_policy_document' } }, + }; + 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', tenantId: 'org_1', positions: [], permissions: [], systemPermissions: [] }, + } as any); + expect(res.response?.status).toBe(200); + const result = (res.response?.body as any)?.result; + expect(result?.isError, JSON.stringify(result)).not.toBe(true); + const answer = JSON.parse(result.content[0].text); + expect(answer.data.pack.name).toBe('rcd_policy_document'); + expect(answer.data.fields.map((f: { name: string; value: unknown }) => [f.name, f.value])).toEqual([ + ['title', 'Fire cover'], + ['status', 'active'], + ]); + }); +}); diff --git a/packages/runtime/vitest.config.ts b/packages/runtime/vitest.config.ts index 299c08508a1..069428c48ca 100644 --- a/packages/runtime/vitest.config.ts +++ b/packages/runtime/vitest.config.ts @@ -241,6 +241,16 @@ export default defineConfig({ find: '@objectstack/service-package', replacement: path.resolve(__dirname, '../services/service-package/src/index.ts'), }, + // Dev-only: mcp-record-context-tools-bridge.test.ts drives the `/mcp` + // route over the REAL MCP runtime and the REAL record-context executor + // (ADR-0160 D4), so the pack the door hands over is judged by the + // executor in the checkout, never a built copy of it. Anchored: each + // pin imports only the root entry. + { find: /^@objectstack\/mcp$/, replacement: path.resolve(__dirname, '../mcp/src/index.ts') }, + { + find: /^@objectstack\/service-record-context$/, + replacement: path.resolve(__dirname, '../services/service-record-context/src/index.ts'), + }, ], }, test: { diff --git a/packages/services/service-record-context/src/door.ts b/packages/services/service-record-context/src/door.ts index f206fabd39c..bab154b6538 100644 --- a/packages/services/service-record-context/src/door.ts +++ b/packages/services/service-record-context/src/door.ts @@ -37,7 +37,13 @@ export interface RecordContextDoor { * by `os validate`, and silent here). */ publishedObjectDefinitionOf(objectName: string): Promise | null>; - /** The published context packs (`ai_context` items). */ + /** + * The published context packs (`ai_context` items), each the authored pack, + * not the serving envelope: the door removes the read path's decorations + * (`stripReadDecorations`, `@objectstack/spec/kernel`) before handing the + * listing over, because the executor parses every row with the closed + * `AiContextSchema` and a decorated row is no pack. + */ listContextPacks(): Promise; /** The record, read as the caller; `null` (or a throw) when the caller cannot read it. */ get(objectName: string, id: string): Promise; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f0b97384e12..7535b8c12b3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1454,6 +1454,12 @@ importers: specifier: ^4.6.6 version: 4.6.7 devDependencies: + '@objectstack/driver-sql': + specifier: workspace:* + version: link:../drivers/driver-sql + '@objectstack/metadata-protocol': + specifier: workspace:* + version: link:../metadata-protocol '@objectstack/objectql': specifier: workspace:* version: link:../objectql @@ -2777,6 +2783,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 +2807,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