Skip to content
Merged
16 changes: 16 additions & 0 deletions .changeset/37243-record-context-authored-packs.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions packages/mcp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
51 changes: 51 additions & 0 deletions packages/mcp/src/mcp-record-context-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand Down Expand Up @@ -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<Record<string, unknown>> };
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<string, unknown>);
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();
}
});
});
12 changes: 10 additions & 2 deletions packages/mcp/src/stdio-data-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -1878,12 +1881,17 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge
((await localizedView.getObject(name)) as Record<string, unknown> | undefined) ?? null,
publishedObjectDefinitionOf: async (name: string) =>
((await readObjectDeclaration(reads, name)) as Record<string, unknown> | 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<McpDataBridge['query']>[1]) => self.query(object, o),
Expand Down
6 changes: 6 additions & 0 deletions packages/mcp/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') },
],
Expand Down
2 changes: 2 additions & 0 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand All @@ -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",
Expand Down
14 changes: 12 additions & 2 deletions packages/runtime/src/domains/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1688,12 +1691,19 @@ export function buildMcpBridge(
return (localized ?? def) as Record<string, unknown>;
},
publishedObjectDefinitionOf: async (name) => ((await readServedObject(name)) ?? null) as Record<string, unknown> | 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) : [];
},
}));
}
Expand Down
125 changes: 124 additions & 1 deletion packages/runtime/src/mcp-record-context-tools-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, any> = {
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<string, any> = {
...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'],
]);
});
});
10 changes: 10 additions & 0 deletions packages/runtime/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
Loading
Loading