From 2f540bc3dc48a2cf6be8609dea399c16b8227315 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:22:51 +0000 Subject: [PATCH 01/25] feat(mcp): open draft door registry with the three read tools Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- packages/runtime/src/domains/mcp-authoring.ts | 421 ++++++++++++++++++ packages/runtime/src/domains/mcp.ts | 9 + 2 files changed, 430 insertions(+) create mode 100644 packages/runtime/src/domains/mcp-authoring.ts diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts new file mode 100644 index 00000000000..6b3fa91e621 --- /dev/null +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -0,0 +1,421 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The open MCP draft door: the authoring registry this runtime injects into + * `handleHttpRequest` as `authoring` (design `docs/design/mcp-local-first-door.md`, + * Design A; rulings D2 A, D3 A and E3 of the local-first door's epic). + * + * This first half carries the registry, its admission and the three read + * tools. The draft save and discard tools, and the publish verdict a save + * answers with, join it later; until then nothing here writes. + * + * ## Who is admitted (seat ruling D1 A) + * + * The effective right is an intersection, and both halves are read here, once + * per request (the HTTP door is stateless, so every `tools/call` is a request + * of its own and is judged afresh): + * + * 1. The TOKEN consents: its grant names `metadata:write`. The MCP runtime's + * own gate (`grantsAuthoringTools` in `@objectstack/mcp`) stays the + * authority on this half; it is read here only so an API key, a session + * or a data-only token costs no grant read. An API key or a session + * carries no grant at all and is never injected anything. + * 2. The HUMAN holds the authoring capability. An OAuth agent's envelope + * carries no system permission unless its token also holds + * `actions:execute` (`assemble-execution-context.ts`, ADR-0090 D10), so + * the capability cannot be read off the request. The user the token was + * issued to (`ExecutionContext.userId`) is resolved through the same + * grant resolution a request uses (`resolveUserAuthzGrants`), in the + * organization the token's consent bound (`tenantId`), and judged by the + * one predicate every `/meta` write door asks, `metaWriteCapabilityVerdict` + * (ADR-0066 D1, ADR-0131 D6). An AI service account resolves to no system + * permission and is refused there. + * + * Fail closed: no `userId`, or a grant resolution that throws, admits nothing. + * + * ## What a refused user sees (the listing rule of the federation pair) + * + * Listing and calling read ONE verdict, taken before the server is built: the + * registry lists its tools only when the verdict admitted the user, and every + * call reads the same verdict again before it touches the protocol. So a + * token with `metadata:write` whose user lacks `manage_metadata` is listed no + * authoring tool, the shape the MCP door gives every tool its caller cannot + * pass, and a call that reaches the registry anyway is refused + * `403 PERMISSION_DENIED`. + * + * ## What the reads serve + * + * The metadata protocol's public reads (`getMetaItems`, `getMetaItem`, + * `listDrafts`), unmasked. That is the `/meta` doors' own answer for this + * caller: a holder of `manage_metadata` is exempt from object-schema masking + * (ADR-0106 D4, `isObjectSchemaMaskExempt`), and the same predicate admits the + * pending-drafts read (`mayReadPendingDrafts`). + * + * The walled refusal (`walledCatalogWriteVerdict`, ADR-0131 D3/D12) gates + * metadata WRITES and no `/meta` read; it joins this door with the save tool. + * + * ## The names (seat ruling D3 A) + * + * The design table's `list_metadata` is already a hosted platform tool + * (`PLATFORM_TOOLS_BY_PACKAGE` in `@objectstack/spec/system`), so the two item + * reads are `list_metadata_items` and `get_metadata_item`. None of the three + * names is an MCP native tool: the SDK refuses a duplicate registration by + * throwing, and the request would fail with it. + * + * ## A host with a build door of its own + * + * There is no host hook for this injection to defer to: a host that serves its + * own build door passes its own `authoring` at its own `handleHttpRequest` + * call, and the option is one object, so the two registries are never merged + * and their names never meet. + */ + +import { resolveUserAuthzGrants } from '@objectstack/core'; +import { metaWriteCapabilityVerdict } from '@objectstack/metadata-core'; +import { refuseUnknownMetaListType } from '@objectstack/rest'; +import { MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; +import type { ErrorCode, ListDraftsResponse, MetadataProtocol } from '@objectstack/spec/api'; +import type { AIToolDefinition } from '@objectstack/spec/contracts'; +import type { HttpProtocolContext } from '../http-dispatcher.js'; +import type { DomainHandlerDeps } from '../domain-handler-registry.js'; + +/** The read tools' names, in the order the registry lists them. */ +export const OPEN_AUTHORING_READ_TOOL_NAMES = ['list_metadata_items', 'get_metadata_item', 'list_drafts'] as const; + +const PERMISSION_DENIED: ErrorCode = 'PERMISSION_DENIED'; +const INVALID_REQUEST: ErrorCode = 'INVALID_REQUEST'; +const RESOURCE_NOT_FOUND: ErrorCode = 'RESOURCE_NOT_FOUND'; +const SERVICE_UNAVAILABLE: ErrorCode = 'SERVICE_UNAVAILABLE'; +const INTERNAL_ERROR: ErrorCode = 'INTERNAL_ERROR'; + +/** The lifecycle selector the item reads take. */ +const STATES = ['active', 'draft'] as const; +type ReadState = (typeof STATES)[number]; + +const TYPE_PARAMETER = { + type: 'string', + minLength: 1, + description: 'The metadata type, singular: `object`, `view`, `flow`, `dashboard`, `app`, and so on.', +} as const; + +const STATE_PARAMETER = { + type: 'string', + enum: [...STATES], +} as const; + +/** + * The three read tools, in the `AIToolDefinition` shape every authoring + * registry hands the MCP runtime: a JSON Schema `parameters` the runtime + * converts into the tool's input schema, so an argument outside it is refused + * before the registry is called. + */ +const READ_TOOLS: readonly AIToolDefinition[] = Object.freeze([ + { + name: 'list_metadata_items', + description: + 'List the items of one metadata type in this environment. A pending draft is listed in place of ' + + 'its published version and marked `draft: true`. Pass `state: "active"` for the published items ' + + 'only, or `state: "draft"` for the pending drafts only. Each entry is a summary (name, label, ' + + 'package); read one item\'s full definition with `get_metadata_item`.', + parameters: { + type: 'object', + properties: { + type: TYPE_PARAMETER, + state: { + ...STATE_PARAMETER, + description: 'Omit to list drafts in place of their published versions; `active` lists the published items only; `draft` lists the pending drafts only.', + }, + }, + required: ['type'], + additionalProperties: false, + }, + }, + { + name: 'get_metadata_item', + description: + 'Read one metadata item\'s full definition. Without `state`, a pending draft is read in place of ' + + 'the published version and the answer says `draft: true`. `state: "draft"` reads the pending ' + + 'draft only and is refused when there is none; `state: "active"` reads the published version.', + parameters: { + type: 'object', + properties: { + type: TYPE_PARAMETER, + name: { type: 'string', minLength: 1, description: 'The item\'s machine name.' }, + state: { + ...STATE_PARAMETER, + description: 'Omit to read a pending draft where one exists and the published version otherwise; `draft` or `active` reads that version only.', + }, + }, + required: ['type', 'name'], + additionalProperties: false, + }, + }, + { + name: 'list_drafts', + description: + 'List the pending metadata drafts in this environment: what was saved as a draft and is not ' + + 'published yet. A person reviews and publishes drafts in Studio. Pass `package` to list one ' + + 'package\'s drafts.', + parameters: { + type: 'object', + properties: { + package: { type: 'string', minLength: 1, description: 'The id of the package whose drafts to list.' }, + }, + additionalProperties: false, + }, + }, +]); + +/** The protocol reads this door makes, named structurally (a host may fill the slot partially). */ +export type OpenAuthoringProtocol = Partial> & { + listDrafts?(request: { packageId?: string; type?: string }): Promise; +}; + +/** + * The per-call context the MCP runtime stamps on every authoring call + * (`McpAuthoringToolContext` in `@objectstack/mcp`), named structurally as + * this package names every MCP shape: it takes no dependency on that package. + */ +export interface OpenAuthoringCallContext { + door: 'mcp'; + principal: { userId: string }; + environmentId?: string; +} + +/** One tool call, as the MCP runtime hands it to an authoring registry. */ +export interface OpenAuthoringToolCall { + toolCallId: string; + toolName: string; + input: unknown; +} + +/** One tool result, as the MCP runtime reads it back (`formatToolOutput` reads `output.value`). */ +export interface OpenAuthoringToolResult { + type: 'tool-result'; + toolCallId: string; + toolName: string; + output: { type: 'text'; value: string }; + isError?: boolean; +} + +/** The registry half of `McpAuthoringInjection`. */ +export interface OpenAuthoringRegistry { + getAll(): AIToolDefinition[]; + execute(toolCall: OpenAuthoringToolCall, context: OpenAuthoringCallContext): Promise; +} + +/** What `handleHttpRequest` receives as `authoring` (`McpAuthoringInjection`). */ +export interface OpenAuthoringInjection { + registry: OpenAuthoringRegistry; + principal: { userId: string; organizationId?: string; clientId?: string; scopes: readonly string[] }; + environmentId?: string; +} + +/** + * The open authoring injection for this request, or `undefined` when none is + * owed: a grant without `metadata:write` (an API key and a session carry no + * grant), or an envelope with no `userId`. A token whose user is not admitted + * still gets the injection, with a registry that lists nothing and refuses + * every call: one verdict, read by both. + */ +export async function resolveOpenAuthoringInjection( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + grantedScopes: readonly string[] | undefined, +): Promise { + if (!Array.isArray(grantedScopes) || !grantedScopes.includes(MCP_OAUTH_SCOPE_METADATA_WRITE)) return undefined; + const ec: any = context.executionContext; + const userId = typeof ec?.userId === 'string' && ec.userId.length > 0 ? (ec.userId as string) : undefined; + // Fail closed: a token principal with no user has no human whose grant to read. + if (!userId) return undefined; + const organizationId = typeof ec?.tenantId === 'string' && ec.tenantId.length > 0 ? (ec.tenantId as string) : undefined; + const clientId = typeof ec?.performedBy?.clientId === 'string' ? (ec.performedBy.clientId as string) : undefined; + + const admitted = await humanHoldsAuthoringCapability(deps, context, userId, organizationId); + return { + registry: createOpenAuthoringRegistry({ + admitted, + userId, + getProtocol: async () => (await deps.resolveService(context, 'protocol', context.environmentId)) as OpenAuthoringProtocol | undefined, + logger: deps.logger, + }), + principal: { + userId, + ...(organizationId ? { organizationId } : {}), + ...(clientId ? { clientId } : {}), + scopes: [...grantedScopes], + }, + ...(context.environmentId !== undefined ? { environmentId: context.environmentId } : {}), + }; +} + +/** + * Does the human the token was issued to hold `manage_metadata` in the + * organization the token's consent bound? `false` when the grant resolution + * cannot be read (no data engine, or a read that throws): a capability nobody + * could read is not held. + */ +async function humanHoldsAuthoringCapability( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + userId: string, + organizationId: string | undefined, +): Promise { + try { + const ql = (await deps.getObjectQL(context, context.environmentId)) + ?? (await deps.resolveService(context, 'objectql', context.environmentId)); + if (!ql) throw new Error('no data engine to resolve the user\'s grants from'); + const grants = await resolveUserAuthzGrants(ql, userId, organizationId ? { tenantId: organizationId } : {}); + // The human's own grant, never the request envelope's: `isSystem` is not + // passed, and an agent envelope's system permissions are not read. + return metaWriteCapabilityVerdict({ systemPermissions: grants.systemPermissions, operation: 'save' }).allowed; + } catch (error) { + // A functional degradation (the authoring tools are not listed, and + // nothing claims to have persisted), so `warn`. + (deps.logger ?? console).warn?.( + '[MCP] The authoring tools are not served on this request: the user\'s metadata permission could not be read.', + { error: error instanceof Error ? error.message : String(error) }, + ); + return false; + } +} + +/** + * The registry over one admission verdict. Exported for its pins; the door + * builds it through {@link resolveOpenAuthoringInjection}. + */ +export function createOpenAuthoringRegistry(opts: { + admitted: boolean; + userId: string; + getProtocol: () => Promise; + logger?: { warn?: (...args: unknown[]) => void }; +}): OpenAuthoringRegistry { + const { admitted, userId, getProtocol } = opts; + return { + getAll: () => (admitted ? [...READ_TOOLS] : []), + async execute(toolCall, context) { + const answer = (body: unknown): OpenAuthoringToolResult => ({ + type: 'tool-result', + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + output: { type: 'text', value: JSON.stringify(body, null, 2) }, + }); + const refuse = (code: ErrorCode, message: string, status: number): OpenAuthoringToolResult => ({ + ...answer({ error: { code, message, status } }), + isError: true, + }); + + // The same verdict the listing read, and the same user it was taken for. + if (!admitted || context?.principal?.userId !== userId) { + return refuse( + PERMISSION_DENIED, + 'The authoring tools need the `metadata:write` scope on your connection and the `manage_metadata` capability on your own account.', + 403, + ); + } + + const input = (toolCall.input && typeof toolCall.input === 'object' ? toolCall.input : {}) as Record; + const state = input.state; + if (state !== undefined && !STATES.includes(state as ReadState)) { + return refuse(INVALID_REQUEST, '`state` is `active` or `draft`.', 400); + } + + const protocol = await getProtocol(); + try { + switch (toolCall.toolName) { + case 'list_metadata_items': { + if (typeof protocol?.getMetaItems !== 'function') return unavailable(); + const type = requiredString(input.type); + if (!type) return refuse(INVALID_REQUEST, 'Name the metadata type as `type`.', 400); + // A type the platform does not declare and this deployment holds + // nothing under is refused, as the `/meta` list refuses it, rather + // than answered an empty list. + await refuseUnknownMetaListType(protocol, type); + const listed = await protocol.getMetaItems({ + type, + ...(state === 'active' ? {} : { previewDrafts: true }), + }); + const items = (Array.isArray(listed?.items) ? listed.items : []) + .map(summaryOf) + .filter((item) => state !== 'draft' || item.draft); + return answer({ type: listed?.type ?? type, count: items.length, items }); + } + case 'get_metadata_item': { + if (typeof protocol?.getMetaItem !== 'function') return unavailable(); + const type = requiredString(input.type); + const name = requiredString(input.name); + if (!type || !name) return refuse(INVALID_REQUEST, 'Name the item as `type` and `name`.', 400); + const read = await protocol.getMetaItem({ + type, + name, + ...(state === 'draft' ? { state: 'draft' as const } : state === 'active' ? {} : { previewDrafts: true }), + }); + const item = read?.item; + if (item === undefined || item === null) { + return refuse(RESOURCE_NOT_FOUND, `No '${type}' item named '${name}' in this environment.`, 404); + } + const draft = state === 'draft' || (item as { _draft?: unknown })._draft === true; + return answer({ + type: read.type ?? type, + name: read.name ?? name, + draft, + ...(read.version !== undefined ? { version: read.version } : {}), + item, + }); + } + case 'list_drafts': { + if (typeof protocol?.listDrafts !== 'function') return unavailable(); + const pkg = input.package === undefined ? undefined : requiredString(input.package); + if (input.package !== undefined && !pkg) return refuse(INVALID_REQUEST, '`package` is a package id.', 400); + // ADR-0131 D6: no organization, as the `/meta` drafts list; every + // draft is saved environment-wide. + const listed = await protocol.listDrafts(pkg ? { packageId: pkg } : {}); + const drafts = Array.isArray(listed?.drafts) ? listed.drafts : []; + return answer({ count: drafts.length, drafts }); + } + default: + return refuse(INVALID_REQUEST, `'${toolCall.toolName}' is not one of this registry's tools.`, 400); + } + } catch (error) { + return refusalFromThrown(error); + } + + function unavailable(): OpenAuthoringToolResult { + return refuse(SERVICE_UNAVAILABLE, 'This environment serves no metadata protocol to read from.', 503); + } + + /** + * A coded throw (the protocol's own refusals: an unknown type, a draft + * that does not exist, a package-scoped refusal) keeps its code, status + * and sentence. Anything else is a fault, answered without its text. + */ + function refusalFromThrown(error: unknown): OpenAuthoringToolResult { + const code = (error as { code?: unknown } | null)?.code; + const status = (error as { status?: unknown } | null)?.status; + if (typeof code === 'string' && code.length > 0 && typeof status === 'number' && status < 500) { + return refuse(code as ErrorCode, error instanceof Error ? error.message : String(error), status); + } + (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName} failed`, { + error: error instanceof Error ? error.message : String(error), + }); + return refuse(INTERNAL_ERROR, 'Reading the metadata failed.', 500); + } + }, + }; +} + +function requiredString(value: unknown): string | undefined { + return typeof value === 'string' && value.trim().length > 0 ? value : undefined; +} + +/** One listed item as a summary: what a client needs to pick the item to read. */ +function summaryOf(raw: unknown): { name: string | null; label: unknown; packageId: string | null; draft: boolean } { + const item = (raw && typeof raw === 'object' ? raw : {}) as Record; + const pkg = item._packageId ?? item.packageId; + return { + name: typeof item.name === 'string' ? item.name : null, + label: item.label ?? null, + packageId: typeof pkg === 'string' ? pkg : null, + draft: item._draft === true, + }; +} diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index b4a8eb66b4e..fba506411a7 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -43,6 +43,8 @@ import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatch import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js'; import type { ActionDispatchAnswer, ActionResumeRequest, PlaceRequestInEnvironment } from '../action-dispatch.js'; import { readDispatchedBody } from '../deferred-request-body.js'; +// [#34766] The open MCP draft door: its registry, behind `metadata:write` and the user's own `manage_metadata`. +import { resolveOpenAuthoringInjection } from './mcp-authoring.js'; // [#28715] The engine's own reading of "this field declares options" (its // `label()` map is built from it), never a second spelling here. import { declaresOptions } from '@objectstack/formula'; @@ -243,6 +245,12 @@ export async function handleMcpRequest(deps: DomainHandlerDeps, body: any, conte // service serves its dataset executor. const datasetTools = await resolveMcpDatasetToolsService(deps, context); const bridge = buildMcpBridge(deps, context, { recordFiles, datasetTools }); + // [#34766] The open draft door (design `docs/design/mcp-local-first-door.md`, + // Design A): resolved per request, so the user's own `manage_metadata` is + // read for every call. `undefined` for a grant without `metadata:write` + // (an API key or a session carries none) and for an envelope with no user; + // a user without the capability gets a registry that lists nothing. + const authoring = await resolveOpenAuthoringInjection(deps, context, grantedScopes); let webRes: Response; try { webRes = await mcp.handleHttpRequest(webRequest, { @@ -251,6 +259,7 @@ export async function handleMcpRequest(deps: DomainHandlerDeps, body: any, conte // undefined = not scope-limited (API key / session); an array // narrows the registered tool families inside the MCP runtime. ...(grantedScopes ? { toolOptions: { grantedScopes } } : {}), + ...(authoring ? { authoring } : {}), // [#31605] Who this request was admitted as: the resolved // ExecutionContext and the environment it was dispatched for. A // host-installed tool-call interceptor reads every call's From 2e6afd688fc5c1d3c6ab8456775789abb0507ac1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:25:41 +0000 Subject: [PATCH 02/25] test(mcp): pin the open draft door's admission cells and read tools; design note and changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .changeset/34766-mcp-open-draft-door-read.md | 18 + docs/design/mcp-local-first-door.md | 2 + .../mcp/src/skill-md-surface-guard.test.ts | 26 ++ .../runtime/src/domains/mcp-authoring.test.ts | 358 ++++++++++++++++++ 4 files changed, 404 insertions(+) create mode 100644 .changeset/34766-mcp-open-draft-door-read.md create mode 100644 packages/runtime/src/domains/mcp-authoring.test.ts diff --git a/.changeset/34766-mcp-open-draft-door-read.md b/.changeset/34766-mcp-open-draft-door-read.md new file mode 100644 index 00000000000..34cd95f80f1 --- /dev/null +++ b/.changeset/34766-mcp-open-draft-door-read.md @@ -0,0 +1,18 @@ +--- +'@objectstack/runtime': patch +--- + +feat(runtime): the open MCP server lists metadata and pending drafts for an OAuth client with `metadata:write` whose user holds `manage_metadata` + +Clause-②: no +Metadata-protocol: none + +An AI client connected over MCP with an OAuth token that carries `metadata:write` now gets three read tools on a self-hosted runtime, the first half of the open draft door (design `docs/design/mcp-local-first-door.md`, Design A): + +- `list_metadata_items({ type, state? })` lists one metadata type's items as summaries (name, label, package). A pending draft is listed in place of its published version and marked `draft: true`; `state: "active"` lists the published items only, `state: "draft"` the pending drafts only. A type the platform does not declare is refused with `400 INVALID_REQUEST`, as the `/meta` list refuses it. +- `get_metadata_item({ type, name, state? })` reads one item's full definition: the pending draft where one exists, unless `state` selects the draft or the published version. An item that does not exist answers `404 RESOURCE_NOT_FOUND`. +- `list_drafts({ package? })` lists the pending drafts, optionally for one package. + +The tools are served only where both halves hold: the token consents (`metadata:write`) and the user the token was issued to holds `manage_metadata` in the organization the token bound. The user's capability is read from their own grants on each request, because an OAuth agent's envelope carries no system permission without `actions:execute`. A token whose user lacks the capability is listed none of the three tools, and a call that reaches them anyway is refused `403 PERMISSION_DENIED`. A token without `metadata:write`, an API key and a session see none of them, as before. When the user's grants cannot be read, the tools are not served on that request and the runtime logs one warning. + +The read tools are named `list_metadata_items` and `get_metadata_item`, not `list_metadata` and `get_metadata`, because `list_metadata` is a hosted platform tool. Nothing here writes: saving and discarding drafts, and the publish verdict a save answers with, come in a later change. diff --git a/docs/design/mcp-local-first-door.md b/docs/design/mcp-local-first-door.md index 640f5fedd67..0b016ac1787 100644 --- a/docs/design/mcp-local-first-door.md +++ b/docs/design/mcp-local-first-door.md @@ -79,6 +79,8 @@ Tools, registered by a new open registry behind `metadata:write`, each checking | `delete_metadata_draft({ type, name })` | Discards a pending draft | | | `list_drafts({ package? })` | Pending drafts with their verdicts | The review queue, as the client sees it | +> **Note (2026-11-17):** the two read tools are named `list_metadata_items` and `get_metadata_item`, because `list_metadata` is a cloud platform tool (`packages/spec/src/system/constants/platform-tool-names.ts:97`) and the open registry must not collide with it (seat ruling D3 on #34766, 2026-11-17). + - No publish tool, no `force`: a draft executes nothing, and the destructive-change confirmation stays at the human publish. - `initialize` instructions and discovery state `Authoring contract: @objectstack/spec ` and the install line for `@objectstack/skills@`. - The open runtime serves `GET /api/v1/discovery/restriction-profile` (mount what the CLI already reads). diff --git a/packages/mcp/src/skill-md-surface-guard.test.ts b/packages/mcp/src/skill-md-surface-guard.test.ts index 1ab73b52e28..5de822fc7db 100644 --- a/packages/mcp/src/skill-md-surface-guard.test.ts +++ b/packages/mcp/src/skill-md-surface-guard.test.ts @@ -207,3 +207,29 @@ describe('SKILL.md ↔ native tool surface drift guard', () => { expect(taughtButUnregistered, `the Build section teaches a tool this grant does not register: ${taughtButUnregistered.join(', ')}`).toEqual([]); }); }); + +/** + * [#34766] The open draft door's read tools, named as the runtime registry + * names them (`OPEN_AUTHORING_READ_TOOL_NAMES` in + * `@objectstack/runtime`, `src/domains/mcp-authoring.ts`; this package cannot + * import it). The SDK refuses a second registration under a name already on + * the server by throwing, so a collision with any native tool would fail + * every `metadata:write` request the open runtime serves. + */ +const OPEN_DRAFT_DOOR_READ_TOOLS = ['list_metadata_items', 'get_metadata_item', 'list_drafts']; + +describe('[#34766] the open draft door\'s read tools collide with no native tool', () => { + it('registers beside the full native surface under every scope', async () => { + const native = await listRegisteredToolNames({ grantedScopes: EVERY_SCOPE }); + for (const name of OPEN_DRAFT_DOOR_READ_TOOLS) expect(native, name).not.toContain(name); + + const registry: McpAuthoringToolRegistry = { + getAll: () => OPEN_DRAFT_DOOR_READ_TOOLS.map((name) => ({ name, description: name, parameters: { type: 'object', properties: {} } })), + async execute(toolCall): Promise { + return { type: 'tool-result', toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, output: { type: 'text', value: '' } } as ToolExecutionResult; + }, + }; + const withDoor = await listRegisteredToolNames({ grantedScopes: EVERY_SCOPE, registry }); + expect(withDoor.sort()).toEqual([...native, ...OPEN_DRAFT_DOOR_READ_TOOLS].sort()); + }); +}); diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts new file mode 100644 index 00000000000..7cdee481ecc --- /dev/null +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -0,0 +1,358 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34766] The open MCP draft door's admission and its three read tools. + * + * The effective right is the intersection of the token's consent + * (`metadata:write`) and the HUMAN's own `manage_metadata` (seat ruling D1 A). + * The four cells of that intersection are pinned through the real `/mcp` + * domain (`handleMcpRequest`), with the OAuth envelopes resolved by the real + * identity door (`resolveExecutionContext`), never written by hand: what an + * agent's envelope carries is that door's derivation, and it carries no system + * permission under a `metadata:write`-only grant. The MCP service is a double + * that records what `handleHttpRequest` is handed; the MCP package's own pins + * (`mcp-server-runtime.authoring-scope.test.ts`) hold that an injected + * registry's `getAll()` is exactly what `tools/list` serves under + * `metadata:write`, and nothing under any other grant. + * + * Fail closed: an envelope with no user is injected nothing, and a grant + * resolution that throws admits nothing. + */ + +import { describe, it, expect } from 'vitest'; +import { PLATFORM_PROVIDED_TOOL_NAMES, PLATFORM_TOOL_FAMILY_PREFIXES } from '@objectstack/spec/system'; +import { handleMcpRequest } from './mcp.js'; +import { + OPEN_AUTHORING_READ_TOOL_NAMES, + createOpenAuthoringRegistry, + resolveOpenAuthoringInjection, + type OpenAuthoringInjection, + type OpenAuthoringProtocol, +} from './mcp-authoring.js'; +import { resolveExecutionContext } from '../security/resolve-execution-context.js'; +import { bindCatalogFromTables } from '../security/security-catalog.testkit.js'; + +// --------------------------------------------------------------------------- +// Fixtures +// --------------------------------------------------------------------------- + +/** A data engine whose user `u1` holds one permission set carrying `systemPermissions`. */ +function userQl(systemPermissions: string[]) { + const reads: string[] = []; + const tables: Record = { + sys_member: [{ user_id: 'u1', organization_id: 'orgA', role: 'owner' }], + sys_organization: [{ id: 'org_default', slug: 'default' }], + sys_user_permission_set: [{ id: 'ups1', user_id: 'u1', permission_set_id: 'ps_admin', permission_set: 'admin_full_access', organization_id: 'org_default' }], + sys_permission_set: [{ id: 'ps_admin', name: 'admin_full_access', system_permissions: JSON.stringify(systemPermissions), object_permissions: '{}' }], + sys_position: [], sys_position_permission_set: [], sys_user_position: [], + }; + const ql = bindCatalogFromTables({ + async find(object: string, opts: any) { + reads.push(object); + const rows = (tables[object] ?? []).filter((row) => + Object.entries(opts?.where ?? {}).every(([k, v]) => + v !== null && typeof v === 'object' + ? (Array.isArray((v as any).$in) ? (v as any).$in.includes(row[k]) : true) + : (v ?? null) === (row[k] ?? null), + ), + ); + return typeof opts?.limit === 'number' ? rows.slice(0, opts.limit) : rows; + }, + }, tables); + return { ql, reads }; +} + +/** The envelope the real `/mcp` identity door resolves for an OAuth token with these scopes. */ +async function oauthEnvelope(scopes: string[], systemPermissions: string[]) { + return resolveExecutionContext({ + acceptOAuthAccessToken: true, + getService: async (name: string) => + name === 'auth' ? { verifyMcpAccessToken: async () => ({ userId: 'u1', scopes, clientId: 'c1' }) } : undefined, + getQl: async () => userQl(systemPermissions).ql, + request: { headers: { authorization: 'Bearer a.b.c' } }, + } as never); +} + +const ADMIN = ['manage_metadata', 'manage_users']; +const NOT_AN_AUTHOR = ['manage_users']; + +function fakeProtocol() { + const calls: unknown[] = []; + const protocol: OpenAuthoringProtocol = { + async getMetaItems(request: any) { + calls.push(['getMetaItems', request]); + return { + type: request.type, + items: [ + { name: 'lead_intake', label: 'Lead intake', _packageId: 'com.acme.crm', _draft: true, nodes: [] }, + { name: 'close_won', label: 'Close won', nodes: [] }, + ], + }; + }, + async getMetaItem(request: any) { + calls.push(['getMetaItem', request]); + if (request.name === 'missing') return { type: request.type, name: request.name, item: undefined }; + return { type: request.type, name: request.name, version: 'v7', item: { name: request.name, label: 'Lead intake', _draft: true } }; + }, + async listDrafts(request: any) { + calls.push(['listDrafts', request]); + return { drafts: [{ type: 'flow', name: 'lead_intake', label: 'Lead intake', packageId: 'com.acme.crm', updatedAt: null }] } as any; + }, + }; + return { protocol, calls }; +} + +interface Served { + status: number; + authoring: OpenAuthoringInjection | undefined; + /** Whether `handleHttpRequest` was handed an `authoring` member at all. */ + carried: boolean; + grantReads: string[]; + protocolCalls: unknown[]; + warnings: unknown[][]; +} + +/** + * One `/mcp` request through the real domain. `qlThrows` makes the grant + * resolution's data-engine lookup throw. + */ +async function serve(executionContext: unknown, opts: { systemPermissions?: string[]; qlThrows?: boolean } = {}): Promise { + const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN); + const { protocol, calls } = fakeProtocol(); + const warnings: unknown[][] = []; + let handed: any; + const mcp = { + async handleHttpRequest(_request: Request, handedOpts: any) { + handed = handedOpts; + return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }); + }, + }; + const deps = { + resolveService: async (_ctx: unknown, name: string) => (name === 'mcp' ? mcp : name === 'protocol' ? protocol : undefined), + resolveServiceOrLoud: async () => undefined, + getObjectQL: async () => { + if (opts.qlThrows) throw new Error('engine lookup failed'); + return ql; + }, + error: (message: string, status: number) => ({ status, body: { success: false, error: { message } } }), + errorFromThrown: (e: any, status: number) => ({ status, body: { success: false, error: { message: String(e?.message ?? e) } } }), + logger: { warn: (...args: unknown[]) => { warnings.push(args); }, debug: () => {}, info: () => {}, error: () => {} }, + }; + const context = { + environmentId: 'env_1', + executionContext, + request: { method: 'POST', url: '/api/v1/mcp', headers: { 'content-type': 'application/json' } }, + }; + const body = { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }; + const result: any = await handleMcpRequest(deps as never, body, context as never); + // The grant reads the door itself made (the envelope above was resolved elsewhere). + return { + status: result.response.status, + authoring: handed?.authoring, + carried: handed !== undefined && 'authoring' in handed, + grantReads: reads, + protocolCalls: calls, + warnings, + }; +} + +const CONTEXT = { door: 'mcp' as const, principal: { userId: 'u1' }, environmentId: 'env_1' }; + +async function call(authoring: OpenAuthoringInjection, toolName: string, input: unknown, context: any = CONTEXT) { + const result = await authoring.registry.execute({ toolCallId: `t-${toolName}`, toolName, input }, context); + return { isError: result.isError === true, body: JSON.parse(result.output.value) }; +} + +// --------------------------------------------------------------------------- +// The four cells +// --------------------------------------------------------------------------- + +describe('the open draft door is served only where the token consents AND the user holds manage_metadata', () => { + it('a token without metadata:write is handed no authoring registry, and the user\'s grant is never read', async () => { + const ec = await oauthEnvelope(['data:read', 'data:write'], ADMIN); + expect(ec.oauthScopes).toEqual(['data:read', 'data:write']); + const served = await serve(ec); + expect(served.status).toBe(200); + expect(served.carried).toBe(false); + expect(served.grantReads).toEqual([]); + }); + + it('a metadata:write token whose user lacks manage_metadata lists no tool, and a call is refused 403 before any read', async () => { + const ec = await oauthEnvelope(['metadata:write'], NOT_AN_AUTHOR); + const served = await serve(ec, { systemPermissions: NOT_AN_AUTHOR }); + expect(served.status).toBe(200); + expect(served.authoring).toBeDefined(); + // The MCP runtime registers exactly `getAll()`: nothing, so `tools/list` omits the family. + expect(served.authoring!.registry.getAll()).toEqual([]); + const refused = await call(served.authoring!, 'list_metadata_items', { type: 'flow' }); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls).toEqual([]); + }); + + it('a metadata:write token whose user holds manage_metadata lists the three read tools, and a read is served', async () => { + const ec = await oauthEnvelope(['metadata:write'], ADMIN); + // The envelope itself carries no capability: the door read the human's grant. + expect(ec.systemPermissions).toEqual([]); + const served = await serve(ec); + expect(served.grantReads.length).toBeGreaterThan(0); + const authoring = served.authoring!; + expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES]); + expect(authoring.principal).toMatchObject({ userId: 'u1', clientId: 'c1', scopes: ['metadata:write'] }); + expect(authoring.environmentId).toBe('env_1'); + + const listed = await call(authoring, 'list_metadata_items', { type: 'flow' }); + expect(listed.isError).toBe(false); + expect(listed.body).toEqual({ + type: 'flow', + count: 2, + items: [ + { name: 'lead_intake', label: 'Lead intake', packageId: 'com.acme.crm', draft: true }, + { name: 'close_won', label: 'Close won', packageId: null, draft: false }, + ], + }); + expect(served.protocolCalls).toEqual([['getMetaItems', { type: 'flow', previewDrafts: true }]]); + }); + + it('an API key is handed no authoring registry', async () => { + // An API key's envelope carries no grant (`oauthScopes` undefined); the + // capability on it changes nothing, since the family needs the token's consent. + const served = await serve({ userId: 'u1', principalKind: 'human', systemPermissions: ADMIN }); + expect(served.status).toBe(200); + expect(served.carried).toBe(false); + expect(served.grantReads).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// Fail closed +// --------------------------------------------------------------------------- + +describe('the open draft door fails closed', () => { + it('an envelope with no user is injected nothing, and no grant is read', async () => { + let lookedUp = false; + const deps = { + resolveService: async () => undefined, + getObjectQL: async () => { lookedUp = true; return userQl(ADMIN).ql; }, + }; + const injection = await resolveOpenAuthoringInjection( + deps as never, + { environmentId: 'env_1', executionContext: { oauthScopes: ['metadata:write'], systemPermissions: ADMIN } } as never, + ['metadata:write'], + ); + expect(injection).toBeUndefined(); + expect(lookedUp).toBe(false); + }); + + it('a grant resolution that throws admits nothing: no tool is listed, a call is refused, and the request is still served', async () => { + const ec = await oauthEnvelope(['metadata:write'], ADMIN); + const served = await serve(ec, { qlThrows: true }); + expect(served.status).toBe(200); + expect(served.authoring!.registry.getAll()).toEqual([]); + const refused = await call(served.authoring!, 'get_metadata_item', { type: 'flow', name: 'lead_intake' }); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls).toEqual([]); + expect(served.warnings.length).toBe(1); + }); + + it('a call stamped with another user than the one admitted is refused', async () => { + const { protocol, calls } = fakeProtocol(); + const registry = createOpenAuthoringRegistry({ admitted: true, userId: 'u1', getProtocol: async () => protocol }); + const result = await registry.execute( + { toolCallId: 't', toolName: 'list_drafts', input: {} }, + { door: 'mcp', principal: { userId: 'u2' } }, + ); + expect(result.isError).toBe(true); + expect(JSON.parse(result.output.value).error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(calls).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// The read tools +// --------------------------------------------------------------------------- + +describe('the read tools answer from the metadata protocol\'s public reads', () => { + const admitted = () => { + const { protocol, calls } = fakeProtocol(); + const authoring: OpenAuthoringInjection = { + registry: createOpenAuthoringRegistry({ admitted: true, userId: 'u1', getProtocol: async () => protocol }), + principal: { userId: 'u1', scopes: ['metadata:write'] }, + }; + return { authoring, calls }; + }; + + it('list_metadata_items with state active reads the published items only; with state draft keeps the drafts only', async () => { + const { authoring, calls } = admitted(); + await call(authoring, 'list_metadata_items', { type: 'flow', state: 'active' }); + const drafts = await call(authoring, 'list_metadata_items', { type: 'flow', state: 'draft' }); + expect(calls).toEqual([ + ['getMetaItems', { type: 'flow' }], + ['getMetaItems', { type: 'flow', previewDrafts: true }], + ]); + expect(drafts.body.items.map((i: any) => i.name)).toEqual(['lead_intake']); + }); + + it('list_metadata_items refuses a type the platform does not declare, as the /meta list does', async () => { + const { authoring } = admitted(); + const refused = await call(authoring, 'list_metadata_items', { type: 'no_such_type' }); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'INVALID_REQUEST', status: 400 }); + }); + + it('get_metadata_item reads a draft in place of the published version by default, and the draft only on state draft', async () => { + const { authoring, calls } = admitted(); + const read = await call(authoring, 'get_metadata_item', { type: 'flow', name: 'lead_intake' }); + expect(read.body).toEqual({ + type: 'flow', name: 'lead_intake', draft: true, version: 'v7', + item: { name: 'lead_intake', label: 'Lead intake', _draft: true }, + }); + await call(authoring, 'get_metadata_item', { type: 'flow', name: 'lead_intake', state: 'draft' }); + await call(authoring, 'get_metadata_item', { type: 'flow', name: 'lead_intake', state: 'active' }); + expect(calls).toEqual([ + ['getMetaItem', { type: 'flow', name: 'lead_intake', previewDrafts: true }], + ['getMetaItem', { type: 'flow', name: 'lead_intake', state: 'draft' }], + ['getMetaItem', { type: 'flow', name: 'lead_intake' }], + ]); + }); + + it('get_metadata_item answers 404 for an item the protocol does not have', async () => { + const { authoring } = admitted(); + const missing = await call(authoring, 'get_metadata_item', { type: 'flow', name: 'missing' }); + expect(missing.body.error).toMatchObject({ code: 'RESOURCE_NOT_FOUND', status: 404 }); + }); + + it('list_drafts passes the package through as the protocol\'s packageId', async () => { + const { authoring, calls } = admitted(); + const listed = await call(authoring, 'list_drafts', { package: 'com.acme.crm' }); + await call(authoring, 'list_drafts', {}); + expect(listed.body.count).toBe(1); + expect(calls).toEqual([['listDrafts', { packageId: 'com.acme.crm' }], ['listDrafts', {}]]); + }); + + it('a coded protocol refusal keeps its code; an uncoded throw is a fault answered without its text', async () => { + const coded = Object.assign(new Error('No pending draft for flow lead_intake.'), { code: 'RESOURCE_NOT_FOUND', status: 404 }); + const registry = (thrown: unknown) => createOpenAuthoringRegistry({ + admitted: true, + userId: 'u1', + getProtocol: async () => ({ getMetaItem: async () => { throw thrown; } }), + logger: { warn: () => {} }, + }); + const run = async (thrown: unknown) => JSON.parse((await registry(thrown).execute( + { toolCallId: 't', toolName: 'get_metadata_item', input: { type: 'flow', name: 'lead_intake', state: 'draft' } }, + CONTEXT, + )).output.value).error; + expect(await run(coded)).toEqual({ code: 'RESOURCE_NOT_FOUND', status: 404, message: 'No pending draft for flow lead_intake.' }); + expect(await run(new Error('connection reset by peer'))).toEqual({ code: 'INTERNAL_ERROR', status: 500, message: 'Reading the metadata failed.' }); + }); +}); + +describe('the read tools\' names', () => { + it('collide with no hosted platform tool (seat ruling D3: not list_metadata)', () => { + for (const name of OPEN_AUTHORING_READ_TOOL_NAMES) { + expect(PLATFORM_PROVIDED_TOOL_NAMES.has(name), name).toBe(false); + expect(PLATFORM_TOOL_FAMILY_PREFIXES.some((prefix) => name.startsWith(prefix)), name).toBe(false); + } + expect(PLATFORM_PROVIDED_TOOL_NAMES.has('list_metadata')).toBe(true); + }); +}); From f86960e5a81ea364dca5848f9f64d3f3765139e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:28:45 +0000 Subject: [PATCH 03/25] test(runtime): the unknown-type pin's protocol double serves its live type set Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- packages/runtime/src/domains/mcp-authoring.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 7cdee481ecc..85225dcfe4a 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -79,6 +79,11 @@ const NOT_AN_AUTHOR = ['manage_users']; function fakeProtocol() { const calls: unknown[] = []; const protocol: OpenAuthoringProtocol = { + // The live type set the unknown-type refusal reads: without it the refusal + // cannot disprove a type and lets it through. + async getMetaTypes() { + return { types: ['object', 'flow', 'view'] } as any; + }, async getMetaItems(request: any) { calls.push(['getMetaItems', request]); return { From a40a48ebbf92d5fc00feea111adf88d1fe13b123 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:59:26 +0000 Subject: [PATCH 04/25] fix(runtime): the draft door's own argument refusals answer the standard VALIDATION_ERROR Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- packages/runtime/src/domains/mcp-authoring.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 6b3fa91e621..fc57c4b4ba9 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -83,7 +83,8 @@ import type { DomainHandlerDeps } from '../domain-handler-registry.js'; export const OPEN_AUTHORING_READ_TOOL_NAMES = ['list_metadata_items', 'get_metadata_item', 'list_drafts'] as const; const PERMISSION_DENIED: ErrorCode = 'PERMISSION_DENIED'; -const INVALID_REQUEST: ErrorCode = 'INVALID_REQUEST'; +/** A malformed argument this door judges itself; a protocol refusal keeps its own code. */ +const VALIDATION_ERROR: ErrorCode = 'VALIDATION_ERROR'; const RESOURCE_NOT_FOUND: ErrorCode = 'RESOURCE_NOT_FOUND'; const SERVICE_UNAVAILABLE: ErrorCode = 'SERVICE_UNAVAILABLE'; const INTERNAL_ERROR: ErrorCode = 'INTERNAL_ERROR'; @@ -317,7 +318,7 @@ export function createOpenAuthoringRegistry(opts: { const input = (toolCall.input && typeof toolCall.input === 'object' ? toolCall.input : {}) as Record; const state = input.state; if (state !== undefined && !STATES.includes(state as ReadState)) { - return refuse(INVALID_REQUEST, '`state` is `active` or `draft`.', 400); + return refuse(VALIDATION_ERROR, '`state` is `active` or `draft`.', 400); } const protocol = await getProtocol(); @@ -326,7 +327,7 @@ export function createOpenAuthoringRegistry(opts: { case 'list_metadata_items': { if (typeof protocol?.getMetaItems !== 'function') return unavailable(); const type = requiredString(input.type); - if (!type) return refuse(INVALID_REQUEST, 'Name the metadata type as `type`.', 400); + if (!type) return refuse(VALIDATION_ERROR, 'Name the metadata type as `type`.', 400); // A type the platform does not declare and this deployment holds // nothing under is refused, as the `/meta` list refuses it, rather // than answered an empty list. @@ -344,7 +345,7 @@ export function createOpenAuthoringRegistry(opts: { if (typeof protocol?.getMetaItem !== 'function') return unavailable(); const type = requiredString(input.type); const name = requiredString(input.name); - if (!type || !name) return refuse(INVALID_REQUEST, 'Name the item as `type` and `name`.', 400); + if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the item as `type` and `name`.', 400); const read = await protocol.getMetaItem({ type, name, @@ -366,7 +367,7 @@ export function createOpenAuthoringRegistry(opts: { case 'list_drafts': { if (typeof protocol?.listDrafts !== 'function') return unavailable(); const pkg = input.package === undefined ? undefined : requiredString(input.package); - if (input.package !== undefined && !pkg) return refuse(INVALID_REQUEST, '`package` is a package id.', 400); + if (input.package !== undefined && !pkg) return refuse(VALIDATION_ERROR, '`package` is a package id.', 400); // ADR-0131 D6: no organization, as the `/meta` drafts list; every // draft is saved environment-wide. const listed = await protocol.listDrafts(pkg ? { packageId: pkg } : {}); @@ -374,7 +375,7 @@ export function createOpenAuthoringRegistry(opts: { return answer({ count: drafts.length, drafts }); } default: - return refuse(INVALID_REQUEST, `'${toolCall.toolName}' is not one of this registry's tools.`, 400); + return refuse(VALIDATION_ERROR, `'${toolCall.toolName}' is not one of this registry's tools.`, 400); } } catch (error) { return refusalFromThrown(error); From eaa8716693860c489eddedfe662193fcaa5fbdac Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:02:46 +0000 Subject: [PATCH 05/25] test(runtime): the draft door's pins pay the metadata package's load during collection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- packages/runtime/src/domains/mcp-authoring.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 85225dcfe4a..91c15714cb3 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -20,6 +20,9 @@ */ import { describe, it, expect } from 'vitest'; +// The `/mcp` domain reaches the dispatcher, which loads this package lazily; +// paid here, during collection, never inside a clocked case. +import '@objectstack/metadata'; import { PLATFORM_PROVIDED_TOOL_NAMES, PLATFORM_TOOL_FAMILY_PREFIXES } from '@objectstack/spec/system'; import { handleMcpRequest } from './mcp.js'; import { From 504662ea13e6d593c2ffca26ca97091c59da0972 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:39:54 +0000 Subject: [PATCH 06/25] chore(scripts): declare the open draft door's registry module among the dispatcher domains The route-envelope census enumerates every module in packages/runtime/src/domains; mcp-authoring.ts builds MCP tool results and no REST body, so it declares handBuilt 0. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- scripts/check-route-envelope.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index e90677fd739..833040cdcb8 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -1104,6 +1104,7 @@ const DISPATCHER_DOMAINS = { handBuilt: 2, note: 'the translations 200, which must carry `ETag` and `Cache-Control: private, no-cache` (`deps.success` takes none) and whose body is `deps.success`\'s envelope spread; and the body-less 304 a matching `If-None-Match` is answered, carrying the same two headers', }, + 'mcp-authoring.ts': { handBuilt: 0 }, // The "new similar" target rule both clone doors share (ADR-0146 D3/D6): // its one answer, `newSimilarTargetRefusalAnswer`, goes through `deps.error`. 'new-similar-target.ts': { handBuilt: 0 }, From 2ef0ca896e2eaebd9efec8e1eea0d738eb8e7b5a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:38:55 +0000 Subject: [PATCH 07/25] fix(runtime): the open draft door's reads run the /meta read gates with the human as the caller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit get_metadata_item and list_metadata_items now judge every item through the gates @objectstack/rest exports (createMetaItemReadGate under the stored-version door policy, createMetaListReadGate), with a caller built from the human's own grants. A dashboard, list view or app whose requiredPermissions the human lacks, and a book or doc outside their audience, are refused or left out as every /meta door does; a gate that cannot evaluate refuses. The draft-state list keeps the overlaid read because the list gate judges item bodies, which draft rows do not carry. The changeset declares Clause-② yes (widening). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .changeset/34766-mcp-open-draft-door-read.md | 4 +- .../runtime/src/domains/mcp-authoring.test.ts | 120 ++++++++++++- packages/runtime/src/domains/mcp-authoring.ts | 162 +++++++++++++++--- 3 files changed, 259 insertions(+), 27 deletions(-) diff --git a/.changeset/34766-mcp-open-draft-door-read.md b/.changeset/34766-mcp-open-draft-door-read.md index 34cd95f80f1..d68d21946cf 100644 --- a/.changeset/34766-mcp-open-draft-door-read.md +++ b/.changeset/34766-mcp-open-draft-door-read.md @@ -4,7 +4,7 @@ feat(runtime): the open MCP server lists metadata and pending drafts for an OAuth client with `metadata:write` whose user holds `manage_metadata` -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none An AI client connected over MCP with an OAuth token that carries `metadata:write` now gets three read tools on a self-hosted runtime, the first half of the open draft door (design `docs/design/mcp-local-first-door.md`, Design A): @@ -15,4 +15,6 @@ An AI client connected over MCP with an OAuth token that carries `metadata:write The tools are served only where both halves hold: the token consents (`metadata:write`) and the user the token was issued to holds `manage_metadata` in the organization the token bound. The user's capability is read from their own grants on each request, because an OAuth agent's envelope carries no system permission without `actions:execute`. A token whose user lacks the capability is listed none of the three tools, and a call that reaches them anyway is refused `403 PERMISSION_DENIED`. A token without `metadata:write`, an API key and a session see none of them, as before. When the user's grants cannot be read, the tools are not served on that request and the runtime logs one warning. +The reads withhold what every `/meta` door withholds from that user, judged by the same read gates with the user as the caller: a dashboard, a list view or an app whose `requiredPermissions` the user does not hold, and a book or doc outside their audience, are refused `403 PERMISSION_DENIED` by `get_metadata_item` and left out of `list_metadata_items`. Holding `manage_metadata` does not lift these refusals. A gate that cannot evaluate refuses the read. + The read tools are named `list_metadata_items` and `get_metadata_item`, not `list_metadata` and `get_metadata`, because `list_metadata` is a hosted platform tool. Nothing here writes: saving and discarding drafts, and the publish verdict a save answers with, come in a later change. diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 91c15714cb3..8b997e96c40 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -31,6 +31,7 @@ import { resolveOpenAuthoringInjection, type OpenAuthoringInjection, type OpenAuthoringProtocol, + type OpenAuthoringReadGateSources, } from './mcp-authoring.js'; import { resolveExecutionContext } from '../security/resolve-execution-context.js'; import { bindCatalogFromTables } from '../security/security-catalog.testkit.js'; @@ -79,16 +80,22 @@ async function oauthEnvelope(scopes: string[], systemPermissions: string[]) { const ADMIN = ['manage_metadata', 'manage_users']; const NOT_AN_AUTHOR = ['manage_users']; -function fakeProtocol() { +/** + * `store` serves the gated types' items by type (a list read, and a by-name + * read of one of them); every other type answers the flow fixtures. + */ +function fakeProtocol(store: Record = {}, opts: { listThrows?: string } = {}) { const calls: unknown[] = []; const protocol: OpenAuthoringProtocol = { // The live type set the unknown-type refusal reads: without it the refusal // cannot disprove a type and lets it through. async getMetaTypes() { - return { types: ['object', 'flow', 'view'] } as any; + return { types: ['object', 'flow', 'view', 'dashboard', 'book', 'doc'] } as any; }, async getMetaItems(request: any) { calls.push(['getMetaItems', request]); + if (opts.listThrows === request.type) throw new Error(`the ${request.type} list read failed`); + if (store[request.type]) return { type: request.type, items: store[request.type] }; return { type: request.type, items: [ @@ -99,6 +106,10 @@ function fakeProtocol() { }, async getMetaItem(request: any) { calls.push(['getMetaItem', request]); + if (store[request.type]) { + const item = store[request.type].find((it) => it.name === request.name); + return { type: request.type, name: request.name, item }; + } if (request.name === 'missing') return { type: request.type, name: request.name, item: undefined }; return { type: request.type, name: request.name, version: 'v7', item: { name: request.name, label: 'Lead intake', _draft: true } }; }, @@ -124,9 +135,15 @@ interface Served { * One `/mcp` request through the real domain. `qlThrows` makes the grant * resolution's data-engine lookup throw. */ -async function serve(executionContext: unknown, opts: { systemPermissions?: string[]; qlThrows?: boolean } = {}): Promise { +async function serve( + executionContext: unknown, + opts: { systemPermissions?: string[]; qlThrows?: boolean; store?: Record; listThrows?: string } = {}, +): Promise { const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN); - const { protocol, calls } = fakeProtocol(); + const { protocol, calls } = fakeProtocol(opts.store, { listThrows: opts.listThrows }); + // The holdings the docs audience reads: the permission sets on the caller the + // gate is handed, so a set the human does not hold is not held. + const security = { resolvePermissionSetNames: async (ctx: any) => (Array.isArray(ctx?.permissions) ? ctx.permissions : []) }; const warnings: unknown[][] = []; let handed: any; const mcp = { @@ -136,7 +153,7 @@ async function serve(executionContext: unknown, opts: { systemPermissions?: stri }, }; const deps = { - resolveService: async (_ctx: unknown, name: string) => (name === 'mcp' ? mcp : name === 'protocol' ? protocol : undefined), + resolveService: async (_ctx: unknown, name: string) => (name === 'mcp' ? mcp : name === 'protocol' ? protocol : name === 'security' ? security : undefined), resolveServiceOrLoud: async () => undefined, getObjectQL: async () => { if (opts.qlThrows) throw new Error('engine lookup failed'); @@ -166,6 +183,19 @@ async function serve(executionContext: unknown, opts: { systemPermissions?: stri const CONTEXT = { door: 'mcp' as const, principal: { userId: 'u1' }, environmentId: 'env_1' }; +/** + * The read gates' ports for a registry built by hand: an author caller, no + * security service, the protocol's own list read. The door builds its own from + * the human's grants (pinned below, through the real domain). + */ +const AUTHOR_READ_GATE: OpenAuthoringReadGateSources = (protocol) => ({ + resolveCaller: async () => ({ userId: 'u1', systemPermissions: ADMIN, mayWriteItem: true }), + resolveSecurityService: async () => undefined, + listMetaItems: (type) => protocol.getMetaItems?.({ type }), + serviceProbe: () => null, + navPruneLogged: new Set(), +}); + async function call(authoring: OpenAuthoringInjection, toolName: string, input: unknown, context: any = CONTEXT) { const result = await authoring.registry.execute({ toolCallId: `t-${toolName}`, toolName, input }, context); return { isError: result.isError === true, body: JSON.parse(result.output.value) }; @@ -284,7 +314,7 @@ describe('the read tools answer from the metadata protocol\'s public reads', () const admitted = () => { const { protocol, calls } = fakeProtocol(); const authoring: OpenAuthoringInjection = { - registry: createOpenAuthoringRegistry({ admitted: true, userId: 'u1', getProtocol: async () => protocol }), + registry: createOpenAuthoringRegistry({ admitted: true, userId: 'u1', getProtocol: async () => protocol, readGate: AUTHOR_READ_GATE }), principal: { userId: 'u1', scopes: ['metadata:write'] }, }; return { authoring, calls }; @@ -344,6 +374,7 @@ describe('the read tools answer from the metadata protocol\'s public reads', () admitted: true, userId: 'u1', getProtocol: async () => ({ getMetaItem: async () => { throw thrown; } }), + readGate: AUTHOR_READ_GATE, logger: { warn: () => {} }, }); const run = async (thrown: unknown) => JSON.parse((await registry(thrown).execute( @@ -355,6 +386,83 @@ describe('the read tools answer from the metadata protocol\'s public reads', () }); }); +// --------------------------------------------------------------------------- +// The /meta read gates, with the human as the caller +// --------------------------------------------------------------------------- + +describe('the read tools withhold what every /meta door withholds from this human (not whole-for-author)', () => { + // The human holds `manage_metadata` and `manage_users` through the set + // `admin_full_access`, and not `crm_admin` nor `finance.access`. + const STORE = { + dashboard: [ + { name: 'finance_board', label: 'Finance', requiredPermissions: ['finance.access'], widgets: [] }, + // Held by the human and by no envelope: served only if the gate read the human. + { name: 'people_board', label: 'People', requiredPermissions: ['manage_users'], widgets: [] }, + ], + book: [ + { name: 'admin_guide', label: 'Admin Guide', audience: { permissionSet: 'crm_admin' }, groups: [{ key: 'admin', label: 'Admin', include: 'crm_admin_*' }] }, + { name: 'help_center', label: 'Help Centre', audience: 'org', groups: [{ key: 'start', label: 'Start', include: 'crm_intro' }] }, + ], + doc: [ + { name: 'crm_intro', label: 'Getting started', content: 'Welcome aboard.' }, + { name: 'crm_admin_runbook', label: 'Admin runbook', content: 'Rotate the signing keys.' }, + ], + }; + const author = async (opts: { listThrows?: string } = {}) => { + const ec = await oauthEnvelope(['metadata:write'], ADMIN); + expect(ec.systemPermissions).toEqual([]); + const served = await serve(ec, { store: STORE, ...opts }); + return served.authoring!; + }; + + it('a dashboard whose requiredPermissions the human lacks is refused 403 and not listed; one they hold is served', async () => { + const authoring = await author(); + const refused = await call(authoring, 'get_metadata_item', { type: 'dashboard', name: 'finance_board' }); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(JSON.stringify(refused.body)).not.toContain('finance.access'); + + const allowed = await call(authoring, 'get_metadata_item', { type: 'dashboard', name: 'people_board' }); + expect(allowed.isError).toBe(false); + expect(allowed.body.item).toMatchObject({ name: 'people_board' }); + + const listed = await call(authoring, 'list_metadata_items', { type: 'dashboard' }); + expect(listed.body.items.map((i: any) => i.name)).toEqual(['people_board']); + }); + + it('a doc outside the human\'s audience is refused 403 and not listed; an org doc is served', async () => { + const authoring = await author(); + const refused = await call(authoring, 'get_metadata_item', { type: 'doc', name: 'crm_admin_runbook' }); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(JSON.stringify(refused.body)).not.toContain('Rotate the signing keys.'); + + const allowed = await call(authoring, 'get_metadata_item', { type: 'doc', name: 'crm_intro' }); + expect(allowed.isError).toBe(false); + expect(allowed.body.item).toMatchObject({ name: 'crm_intro', content: 'Welcome aboard.' }); + + const listed = await call(authoring, 'list_metadata_items', { type: 'doc' }); + expect(listed.body.items.map((i: any) => i.name)).toEqual(['crm_intro']); + }); + + it('a gate that cannot evaluate refuses: a books read that throws serves no doc', async () => { + const authoring = await author({ listThrows: 'book' }); + const refused = await call(authoring, 'get_metadata_item', { type: 'doc', name: 'crm_intro' }); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + expect(JSON.stringify(refused.body)).not.toContain('Welcome aboard.'); + }); + + it('a registry handed no read gate reads nothing', async () => { + const { protocol, calls } = fakeProtocol(); + const registry = createOpenAuthoringRegistry({ admitted: true, userId: 'u1', getProtocol: async () => protocol }); + const result = await registry.execute({ toolCallId: 't', toolName: 'get_metadata_item', input: { type: 'flow', name: 'lead_intake' } }, CONTEXT); + expect(result.isError).toBe(true); + expect(JSON.parse(result.output.value).error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(calls).toEqual([]); + }); +}); + describe('the read tools\' names', () => { it('collide with no hosted platform tool (seat ruling D3: not list_metadata)', () => { for (const name of OPEN_AUTHORING_READ_TOOL_NAMES) { diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index fc57c4b4ba9..ddb16de3ac4 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -46,10 +46,34 @@ * ## What the reads serve * * The metadata protocol's public reads (`getMetaItems`, `getMetaItem`, - * `listDrafts`), unmasked. That is the `/meta` doors' own answer for this - * caller: a holder of `manage_metadata` is exempt from object-schema masking - * (ADR-0106 D4, `isObjectSchemaMaskExempt`), and the same predicate admits the - * pending-drafts read (`mayReadPendingDrafts`). + * `listDrafts`), judged by the `/meta` doors' own per-caller read gates, with + * the HUMAN as the caller. The door is not whole-for-author: + * + * - The object-schema mask does not apply: a holder of `manage_metadata` is + * exempt from it on every `/meta` door (ADR-0106 D4, + * `isObjectSchemaMaskExempt`), and the same predicate admits the + * pending-drafts read (`mayReadPendingDrafts`). + * - The read gates do apply, as `@objectstack/rest` exports them + * (`createMetaItemReadGate`, `createMetaListReadGate`). They refuse on the + * caller's own `systemPermissions` and docs audience with no + * `manage_metadata` exemption: a dashboard, a list view or an app whose + * `requiredPermissions` the human does not hold, and a book or doc outside + * their ADR-0046 audience, are refused here as every `/meta` door refuses + * them to that human ("either way, author or not", ruling 5856774816). + * The caller the gates read is built from the grants the admission + * resolved (`resolveUserAuthzGrants`), never from the agent's envelope, + * whose system permissions and permission sets are the token's ceiling. + * - The item read runs `STORED_VERSION_DOOR_POLICY`, the policy of the + * `/meta` doors that serve a stored version for authoring (the plain read's + * `?state=draft` branch among them): only the per-caller gates, and the + * author exemption for a container's entries, since this caller may save + * the item. A whole refusal stays a refusal. + * - A gate that cannot evaluate (a books or doc read that throws, a security + * service that cannot resolve holdings) refuses: the read answers that + * fault, never the item (ADR-0049). + * - `list_drafts` runs no item gate, as `/meta/_drafts` runs none for this + * same caller: a draft row carries the item's identity and its own `label`, + * no body for a gate to judge. * * The walled refusal (`walledCatalogWriteVerdict`, ADR-0131 D3/D12) gates * metadata WRITES and no `/meta` read; it joins this door with the save tool. @@ -72,7 +96,14 @@ import { resolveUserAuthzGrants } from '@objectstack/core'; import { metaWriteCapabilityVerdict } from '@objectstack/metadata-core'; -import { refuseUnknownMetaListType } from '@objectstack/rest'; +import { + createMetaItemReadGate, + createMetaListReadGate, + refuseUnknownMetaListType, + STORED_VERSION_DOOR_POLICY, + type MetaItemReadGateSources, + type MetaReadGateCaller, +} from '@objectstack/rest'; import { MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; import type { ErrorCode, ListDraftsResponse, MetadataProtocol } from '@objectstack/spec/api'; import type { AIToolDefinition } from '@objectstack/spec/contracts'; @@ -172,6 +203,13 @@ export type OpenAuthoringProtocol = Partial; }; +/** + * The `/meta` read gates' ports for one protocol, with the admitted human as + * the caller. Built by {@link resolveOpenAuthoringInjection}; a registry + * handed none refuses every read (fail closed). + */ +export type OpenAuthoringReadGateSources = (protocol: OpenAuthoringProtocol) => MetaItemReadGateSources; + /** * The per-call context the MCP runtime stamps on every authoring call * (`McpAuthoringToolContext` in `@objectstack/mcp`), named structurally as @@ -232,12 +270,13 @@ export async function resolveOpenAuthoringInjection( const organizationId = typeof ec?.tenantId === 'string' && ec.tenantId.length > 0 ? (ec.tenantId as string) : undefined; const clientId = typeof ec?.performedBy?.clientId === 'string' ? (ec.performedBy.clientId as string) : undefined; - const admitted = await humanHoldsAuthoringCapability(deps, context, userId, organizationId); + const reader = await resolveHumanReader(deps, context, userId, organizationId); return { registry: createOpenAuthoringRegistry({ - admitted, + admitted: reader !== undefined, userId, getProtocol: async () => (await deps.resolveService(context, 'protocol', context.environmentId)) as OpenAuthoringProtocol | undefined, + ...(reader ? { readGate: openReadGateSources(deps, context, reader) } : {}), logger: deps.logger, }), principal: { @@ -251,17 +290,24 @@ export async function resolveOpenAuthoringInjection( } /** - * Does the human the token was issued to hold `manage_metadata` in the - * organization the token's consent bound? `false` when the grant resolution - * cannot be read (no data engine, or a read that throws): a capability nobody - * could read is not held. + * The human the token was issued to, as the `/meta` read gates read a caller, + * when they hold `manage_metadata` in the organization the token's consent + * bound; `undefined` when they do not, or when the grant resolution cannot be + * read (no data engine, or a read that throws): a capability nobody could read + * is not held. + * + * The caller is the human's own grants, never the agent envelope's: its + * `systemPermissions` and permission sets are what the gates' audience and + * `requiredPermissions` arms read. `mayWriteItem` is this door's save answer, + * the one `metaWriteCapabilityVerdict` just gave, as the `/meta` save door + * gives it. */ -async function humanHoldsAuthoringCapability( +async function resolveHumanReader( deps: DomainHandlerDeps, context: HttpProtocolContext, userId: string, organizationId: string | undefined, -): Promise { +): Promise { try { const ql = (await deps.getObjectQL(context, context.environmentId)) ?? (await deps.resolveService(context, 'objectql', context.environmentId)); @@ -269,7 +315,18 @@ async function humanHoldsAuthoringCapability( const grants = await resolveUserAuthzGrants(ql, userId, organizationId ? { tenantId: organizationId } : {}); // The human's own grant, never the request envelope's: `isSystem` is not // passed, and an agent envelope's system permissions are not read. - return metaWriteCapabilityVerdict({ systemPermissions: grants.systemPermissions, operation: 'save' }).allowed; + if (!metaWriteCapabilityVerdict({ systemPermissions: grants.systemPermissions, operation: 'save' }).allowed) return undefined; + return { + userId, + ...(organizationId ? { tenantId: organizationId } : {}), + positions: grants.positions, + permissions: grants.permissions, + ...(grants.permissionSetAddresses ? { permissionSetAddresses: grants.permissionSetAddresses } : {}), + systemPermissions: grants.systemPermissions, + principalKind: grants.principalKind ?? 'human', + isSystem: false, + mayWriteItem: true, + }; } catch (error) { // A functional degradation (the authoring tools are not listed, and // nothing claims to have persisted), so `warn`. @@ -277,10 +334,51 @@ async function humanHoldsAuthoringCapability( '[MCP] The authoring tools are not served on this request: the user\'s metadata permission could not be read.', { error: error instanceof Error ? error.message : String(error) }, ); - return false; + return undefined; } } +/** Where the app gate's nav-servability prune log records what it has already said, for this door. */ +const NAV_PRUNE_LOGGED = new Set(); + +/** + * The read gates' ports for this request, the I/O the runtime `/meta` domain + * hands the same gates, with `caller` in place of the request's envelope. Only + * I/O: every verdict is the gate's. + */ +function openReadGateSources( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + caller: MetaReadGateCaller, +): OpenAuthoringReadGateSources { + return (protocol) => ({ + resolveCaller: async () => caller, + resolveSecurityService: () => deps.resolveService(context, 'security'), + // `undefined` when the protocol has no list read: an unreadable input, + // which the gates refuse on, never an empty one. + listMetaItems: (type) => (typeof protocol.getMetaItems === 'function' ? protocol.getMetaItems({ type }) : undefined), + serviceProbe: () => async (name: string) => { + try { + return (await deps.resolveService(context, name)) != null; + } catch { + return false; + } + }, + navPruneLogged: NAV_PRUNE_LOGGED, + resolveMessageTranslator: async () => { + let i18n: { t?: unknown } | null | undefined; + try { + i18n = await deps.resolveService(context, 'i18n'); + } catch { + return undefined; + } + if (!i18n || typeof i18n.t !== 'function') return undefined; + const t = i18n.t as (key: string, locale: string, params?: Record) => string; + return (key, locale, params) => t.call(i18n, key, locale, params); + }, + }); +} + /** * The registry over one admission verdict. Exported for its pins; the door * builds it through {@link resolveOpenAuthoringInjection}. @@ -289,9 +387,11 @@ export function createOpenAuthoringRegistry(opts: { admitted: boolean; userId: string; getProtocol: () => Promise; + /** The `/meta` read gates' ports; without them every read is refused. */ + readGate?: OpenAuthoringReadGateSources; logger?: { warn?: (...args: unknown[]) => void }; }): OpenAuthoringRegistry { - const { admitted, userId, getProtocol } = opts; + const { admitted, userId, getProtocol, readGate } = opts; return { getAll: () => (admitted ? [...READ_TOOLS] : []), async execute(toolCall, context) { @@ -322,6 +422,11 @@ export function createOpenAuthoringRegistry(opts: { } const protocol = await getProtocol(); + // Fail closed: a registry with no read gate cannot judge what this + // caller may read, so it reads nothing. + if (typeof readGate !== 'function') { + return refuse(PERMISSION_DENIED, 'The authoring tools cannot judge what your account may read on this request.', 403); + } try { switch (toolCall.toolName) { case 'list_metadata_items': { @@ -332,11 +437,19 @@ export function createOpenAuthoringRegistry(opts: { // nothing under is refused, as the `/meta` list refuses it, rather // than answered an empty list. await refuseUnknownMetaListType(protocol, type); + // `state: "draft"` reads the draft-overlaid list and keeps its + // drafts, rather than `listDrafts({ type })`: the list gate + // below judges each item's BODY (its `requiredPermissions`, + // a doc's audience), and a draft row carries none. const listed = await protocol.getMetaItems({ type, ...(state === 'active' ? {} : { previewDrafts: true }), }); - const items = (Array.isArray(listed?.items) ? listed.items : []) + // What the `/meta` list withholds from this human is not listed. + const kept = await createMetaListReadGate(readGate(protocol), type)( + Array.isArray(listed?.items) ? listed.items : [], + ); + const items = kept .map(summaryOf) .filter((item) => state !== 'draft' || item.draft); return answer({ type: listed?.type ?? type, count: items.length, items }); @@ -351,10 +464,19 @@ export function createOpenAuthoringRegistry(opts: { name, ...(state === 'draft' ? { state: 'draft' as const } : state === 'active' ? {} : { previewDrafts: true }), }); - const item = read?.item; - if (item === undefined || item === null) { - return refuse(RESOURCE_NOT_FOUND, `No '${type}' item named '${name}' in this environment.`, 404); + const notFound = () => refuse(RESOURCE_NOT_FOUND, `No '${type}' item named '${name}' in this environment.`, 404); + const stored = read?.item; + if (stored === undefined || stored === null) return notFound(); + // The `/meta` item gate, as the doors that serve a stored version + // for authoring run it. `absent` is the not-found answer itself + // (an unpublished app stays unobservable, ADR-0045 §3). + const verdict = await createMetaItemReadGate(readGate(protocol), type, name, [stored], STORED_VERSION_DOOR_POLICY)(stored); + if (verdict.kind === 'refuse') { + const { refusal } = verdict; + if (refusal.reason === 'absent') return notFound(); + return refuse(refusal.code, refusal.message, refusal.status); } + const item = verdict.document; const draft = state === 'draft' || (item as { _draft?: unknown })._draft === true; return answer({ type: read.type ?? type, From 861c63e3dee99280eced6428ff7c47a085633587 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:02:14 +0000 Subject: [PATCH 08/25] feat(metadata-protocol): make the draft publish judgement public, reading the stored draft when no body is handed Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../src/protocol-authoring-gate.ts | 35 ++++++- .../protocol.draft-publish-verdict.test.ts | 92 +++++++++++++++++++ packages/metadata-protocol/src/protocol.ts | 6 +- 3 files changed, 127 insertions(+), 6 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index c05bab828be..621486cfaf3 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -51,6 +51,7 @@ import { permissionSetOwnerBindingRefusal, runtimeHookWithoutBodyRefusal } from import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js'; import { datasourceCredentialsRefSaveRefusal } from './protocol-datasource-credentials-ref.js'; import { storedFlowVerdictBody } from './protocol-flow-save-replay.js'; +import { noPendingDraftError } from './protocol-authoring-refusals.js'; import { evaluateRuntimeAuthoringGate } from './runtime-authoring-gate.js'; import type { PackagedRuleCopyRefusal, RuntimeAuthoringIssue, RuntimeAuthoringVerdict, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; @@ -742,11 +743,29 @@ export async function draftPublishVerdict( * publish checks before Publish is pressed. One run of the same rules; * `userTextLocales` picks the language of the advisories' user sentences and * nothing else. + * + * [#34766] The class method is PUBLIC: it is the publish verdict a door that + * cannot publish answers with (the open MCP draft door's save and its draft + * list), so its caller can tell its author what a publish would refuse before + * a person presses Publish. Each issue keeps every member the publish 422 + * carries (`rule`, `path`, `where`, `message`, `hint`, `severity`); the draft + * read's `_diagnostics` folds them and drops the `hint`, the next step. + * + * Such a door holds no stored row, so `body` may be omitted: the judgement + * then reads the stored draft itself, at the address `packageId` (`null` = the + * package-unbound draft) and `member` name, exactly as the draft read hands + * the row it serves (the bytes as stored, never a served or redacted copy), + * and an address that holds no draft is refused `404 NO_DRAFT`, the strict + * draft read's own refusal ({@link noPendingDraftError}). Never a second + * judgement: the same rules, on the same body, as the draft read's verdict. */ export async function draftPublishJudgement( this: DraftVerdictHost, draft: { - type: string; name: string; body: unknown; packageId: string | null; + /** [#34766] Omitted ⇒ the stored draft at (`type`, `name`, `packageId`, `member`) is read and judged. */ + type: string; name: string; body?: unknown; packageId: string | null; + /** [#34766] The bundle member whose stored draft to read when `body` is omitted; omitted, the canonical member. */ + member?: string; /** * [#34818] The locales the advisories' user sentences are composed in * (`GetMetaItemRequestSchema.userTextLocales`, stated by the draft read @@ -756,6 +775,16 @@ export async function draftPublishJudgement( }, ): Promise { const singular = PLURAL_TO_SINGULAR[draft.type] ?? draft.type; + // [#34766] No body handed: the stored draft at the address, as stored. + let body = draft.body; + if (body === undefined) { + const stored = await this.getOverlayRepo().get( + { type: singular, name: draft.name }, + { state: 'draft', packageId: draft.packageId, ...(draft.member !== undefined ? { member: draft.member } : {}) }, + ); + if (!stored) throw noPendingDraftError(draft.type, draft.name); + body = stored.body; + } // The closure "Publish all" judges this draft against: its package's other // drafts, collected by the batch door's own collector from the batch door's // own listing. A package-unbound draft has no batch; its publish is the @@ -776,11 +805,11 @@ export async function draftPublishJudgement( state: 'active', // [#29557] The body the promotion judges: a flow draft in its // D2-converted spelling, every other draft as stored. - body: storedFlowVerdictBody(singular, draft.body), + body: storedFlowVerdictBody(singular, body), packageId: draft.packageId, ...(pending !== undefined ? { pending } : {}), ...(channel - ? { restoredCredentialPaths: () => channel.heldPaths({ name: draft.name, state: 'draft', item: draft.body }) } + ? { restoredCredentialPaths: () => channel.heldPaths({ name: draft.name, state: 'draft', item: body }) } : {}), ...(draft.userTextLocales !== undefined ? { userTextLocales: draft.userTextLocales } : {}), }); diff --git a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts index 6bc0e28e377..6de786b556b 100644 --- a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts +++ b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts @@ -1383,3 +1383,95 @@ describe('[#34818] a flow draft read carries the advisories its publish would re expect(warnings.filter((w) => w.path === 'nodes.1')).toEqual([]); }); }); + +/** + * [#34766] The draft verdict is PUBLIC: a door that cannot publish (the open + * MCP draft door) answers its draft save and its draft list with it, so its + * caller learns what a publish would refuse before a person presses Publish. + * + * Such a door holds no stored row, so the method reads the stored draft itself + * when no `body` is handed. Pinned: that read judges the bytes as stored, at + * the package named, and answers the per-item publish's own 422 issues WHOLE, + * the `hint` (the next step) included, which the draft read's `_diagnostics` + * drops; an address with no draft is refused as the strict draft read refuses + * it. One judgement: the answer equals the body-handed call's. + */ +describe('[#34766] the public draft publish verdict judges the stored draft', () => { + let warn: ReturnType; + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + delete process.env.OS_ALLOW_UNLINTED_METADATA_WRITES; + }); + afterEach(() => { + warn.mockRestore(); + }); + + /** A record-triggered flow whose start node names no trigger: saved as a draft, refused at publish. */ + const unroutable = { + name: 'deal_followup', + label: 'Deal Follow-up', + type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'deal' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }; + + it('with no body, answers the publish 422 issues of the stored draft whole, hint included', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + expect(await stageDraft(protocol, 'flow', unroutable)).toMatchObject({ success: true, state: 'draft' }); + + const judgement = await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', packageId: PKG }); + + const finding = judgement.refusals.find((issue) => issue.rule === 'flow-trigger-unroutable'); + expect(finding, JSON.stringify(judgement.refusals)).toBeDefined(); + expect(finding!.path).toBe('flows[0].nodes[0].config.triggerType'); + expect(finding!.severity).toBe('error'); + expect(typeof finding!.hint === 'string' && finding!.hint.length > 0).toBe(true); + + // The publish refuses on exactly these issues, every member included. + const refusal: any = await protocol + .publishMetaItem({ type: 'flow', name: 'deal_followup', packageId: PKG } as any) + .then(() => null, (e: unknown) => e); + expect({ code: refusal?.code, status: refusal?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect(judgement.refusals).toEqual(refusal.issues); + }); + + it('judges the stored bytes as the body-handed call judges them: one judgement', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageDraft(protocol, 'flow', unroutable); + const stored = JSON.parse([...rows.values()].find((r) => r.name === 'deal_followup' && r.state === 'draft')!.metadata); + + expect(await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', packageId: PKG })) + .toEqual(await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', body: stored, packageId: PKG })); + }); + + it('an address that holds no draft is refused 404 NO_DRAFT, as the strict draft read refuses it', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageDraft(protocol, 'flow', unroutable); + + const refusalOf = (draft: { name: string; packageId: string | null }) => protocol + .draftPublishJudgement({ type: 'flow', ...draft }) + .then(() => null, (e: any) => ({ code: e?.code, status: e?.status })); + // Another name, and the package-unbound address of a draft staged into a package. + expect(await refusalOf({ name: 'no_such_flow', packageId: PKG })).toEqual({ code: 'NO_DRAFT', status: 404 }); + expect(await refusalOf({ name: 'deal_followup', packageId: null })).toEqual({ code: 'NO_DRAFT', status: 404 }); + const read: any = await protocol.getMetaItem({ type: 'flow', name: 'no_such_flow', state: 'draft', packageId: PKG } as any) + .then(() => null, (e: any) => ({ code: e?.code, status: e?.status })); + expect(read).toEqual({ code: 'NO_DRAFT', status: 404 }); + }); + + it('a draft the publish passes answers no refusal', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const routed = structuredClone(unroutable); + (routed.nodes[0]!.config as Record).triggerType = 'record-after-create'; + await stageDraft(protocol, 'flow', routed); + + expect((await protocol.draftPublishJudgement({ type: 'flow', name: 'deal_followup', packageId: PKG })).refusals).toEqual([]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index ebfaff50fe1..8bf18e67503 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1912,9 +1912,9 @@ export class ObjectStackProtocolImplementation implements return draftPublishVerdict.call(this.draftVerdictHost(), draft); } - /** [#34818] The same judgement with the gate's advisories beside its refusal (see `draftPublishJudgement`). */ - private draftPublishJudgement(draft: { - type: string; name: string; body: unknown; packageId: string | null; + /** [#34818, #34766] PUBLIC: this judgement with the gate's advisories; no `body` ⇒ the stored draft (see `draftPublishJudgement`). */ + draftPublishJudgement(draft: { + type: string; name: string; body?: unknown; packageId: string | null; member?: string; userTextLocales?: readonly (string | undefined)[]; }): Promise { return draftPublishJudgement.call(this.draftVerdictHost(), draft); From 87be08530827b97a28dc25d1ef9f3d8549aa11b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:07:28 +0000 Subject: [PATCH 09/25] fix(metadata-protocol): the stored-draft read names its environment row reference as the publish door does Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- packages/metadata-protocol/src/protocol-authoring-gate.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 621486cfaf3..28a4c0887e3 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -52,6 +52,7 @@ import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-fiel import { datasourceCredentialsRefSaveRefusal } from './protocol-datasource-credentials-ref.js'; import { storedFlowVerdictBody } from './protocol-flow-save-replay.js'; import { noPendingDraftError } from './protocol-authoring-refusals.js'; +import { memberOption } from './protocol-bundle-members.js'; import { evaluateRuntimeAuthoringGate } from './runtime-authoring-gate.js'; import type { PackagedRuleCopyRefusal, RuntimeAuthoringIssue, RuntimeAuthoringVerdict, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; @@ -778,9 +779,10 @@ export async function draftPublishJudgement( // [#34766] No body handed: the stored draft at the address, as stored. let body = draft.body; if (body === undefined) { - const stored = await this.getOverlayRepo().get( - { type: singular, name: draft.name }, - { state: 'draft', packageId: draft.packageId, ...(draft.member !== undefined ? { member: draft.member } : {}) }, + const repo = this.getOverlayRepo(); + const stored = await repo.get( + { type: singular, name: draft.name, org: 'env' } as Parameters[0], + { state: 'draft', packageId: draft.packageId, ...memberOption(draft.member) }, ); if (!stored) throw noPendingDraftError(draft.type, draft.name); body = stored.body; From 09f52492d760d8d81c6ae728c1f2fe05d24fe57c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:15:38 +0000 Subject: [PATCH 10/25] chore(changeset): declare the public draft publish verdict Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .changeset/34766-mcp-draft-door-write.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .changeset/34766-mcp-draft-door-write.md diff --git a/.changeset/34766-mcp-draft-door-write.md b/.changeset/34766-mcp-draft-door-write.md new file mode 100644 index 00000000000..95f154fb539 --- /dev/null +++ b/.changeset/34766-mcp-draft-door-write.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +feat(metadata-protocol): the draft publish verdict is a public protocol method, and it reads the stored draft itself + +Clause-②: yes (widening) +Metadata-protocol: none + +`ObjectStackProtocolImplementation.draftPublishJudgement` is now public. It answers what publishing a stored draft would say, without publishing it: `refusals`, the issues the publish would refuse the draft on, and `advisories`, the findings a publish that passes still returns. Each issue keeps every member the publish's `422 INVALID_METADATA` carries: `rule`, `path`, `where`, `message`, `hint` (the next step) and `severity`. The draft read's `_diagnostics` folds the same verdict but drops the `hint`. + +A caller that holds no stored row may omit `body`: the method then reads the stored draft at `type`, `name` and `packageId` (`null` for the draft bound to no package), and `member` for a bundled type, and judges the bytes as stored. An address that holds no draft is refused `404 NO_DRAFT`, as the strict draft read refuses it. It runs the same judgement the draft read and the publish gate run; nothing about either changes. From 9350be63901df18e25e41c274189a6398c89aa41 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:31:18 +0000 Subject: [PATCH 11/25] feat(runtime): the open draft door saves and discards drafts, and answers each save and draft with its publish verdict Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- packages/runtime/src/domains/mcp-authoring.ts | 373 +++++++++++++++++- 1 file changed, 353 insertions(+), 20 deletions(-) diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index ddb16de3ac4..8771daef3ab 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -5,9 +5,10 @@ * `handleHttpRequest` as `authoring` (design `docs/design/mcp-local-first-door.md`, * Design A; rulings D2 A, D3 A and E3 of the local-first door's epic). * - * This first half carries the registry, its admission and the three read - * tools. The draft save and discard tools, and the publish verdict a save - * answers with, join it later; until then nothing here writes. + * Five tools: three reads (`list_metadata_items`, `get_metadata_item`, + * `list_drafts`) and two draft writes (`save_metadata_draft`, + * `delete_metadata_draft`). No tool publishes and none takes a `force` (D2 A): + * a person reviews and publishes the drafts in Studio. * * ## Who is admitted (seat ruling D1 A) * @@ -75,14 +76,35 @@ * same caller: a draft row carries the item's identity and its own `label`, * no body for a gate to judge. * - * The walled refusal (`walledCatalogWriteVerdict`, ADR-0131 D3/D12) gates - * metadata WRITES and no `/meta` read; it joins this door with the save tool. + * ## What the writes do (E3: the save answers with the publish verdict) + * + * - `save_metadata_draft` saves through `saveMetaItem` with `mode: 'draft'`, + * `surface: 'mcp'` and the token's OAuth client as `client`, attributed to + * the human (`actor`). A draft save runs the type's schema parse and no + * authoring rule, so the reply carries what a publish would answer: the + * protocol's public `draftPublishJudgement` on the stored draft, every + * finding whole (rule id, path, message, hint, severity), and the Studio + * routes a person reviews it on. `package` is required (seat ruling D4): + * Studio's Changes review is per package, and a save naming none is + * refused with the writable packages named. A judgement that fails after + * the save landed is said beside the saved identity, never as a refused + * save. + * - `delete_metadata_draft` discards a pending draft through `deleteMetaItem` + * with `state: 'draft'`, never an active item. + * - Both ask the walled refusal (`walledCatalogWriteVerdict`, ADR-0131 + * D3/D12) before anything is written, as every `/meta` write door does, on + * the posture this transport reads (`readEffectiveTenancyPosture`). + * - `list_drafts` stays ungated as a list (as `/meta/_drafts`), and each + * entry now carries its publish verdict. The verdict is read off the + * draft's body, so it is told only where the `/meta` item gate admits the + * strict draft read for this human; elsewhere the entry says it was + * withheld and why. * * ## The names (seat ruling D3 A) * * The design table's `list_metadata` is already a hosted platform tool * (`PLATFORM_TOOLS_BY_PACKAGE` in `@objectstack/spec/system`), so the two item - * reads are `list_metadata_items` and `get_metadata_item`. None of the three + * reads are `list_metadata_items` and `get_metadata_item`. None of the five * names is an MCP native tool: the SDK refuses a duplicate registration by * throwing, and the request would fail with it. * @@ -94,8 +116,8 @@ * and their names never meet. */ -import { resolveUserAuthzGrants } from '@objectstack/core'; -import { metaWriteCapabilityVerdict } from '@objectstack/metadata-core'; +import { resolveUserAuthzGrants, userTextLocalesOf } from '@objectstack/core'; +import { metaWriteCapabilityVerdict, walledCatalogWriteVerdict } from '@objectstack/metadata-core'; import { createMetaItemReadGate, createMetaListReadGate, @@ -105,14 +127,18 @@ import { type MetaReadGateCaller, } from '@objectstack/rest'; import { MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; -import type { ErrorCode, ListDraftsResponse, MetadataProtocol } from '@objectstack/spec/api'; +import type { ErrorCode, ListDraftsResponse, MetadataProtocol, RuntimeAuthoringIssue } from '@objectstack/spec/api'; import type { AIToolDefinition } from '@objectstack/spec/contracts'; import type { HttpProtocolContext } from '../http-dispatcher.js'; import type { DomainHandlerDeps } from '../domain-handler-registry.js'; +import { readEffectiveTenancyPosture } from './activation-gate.js'; /** The read tools' names, in the order the registry lists them. */ export const OPEN_AUTHORING_READ_TOOL_NAMES = ['list_metadata_items', 'get_metadata_item', 'list_drafts'] as const; +/** The draft write tools' names, listed after the reads. */ +export const OPEN_AUTHORING_WRITE_TOOL_NAMES = ['save_metadata_draft', 'delete_metadata_draft'] as const; + const PERMISSION_DENIED: ErrorCode = 'PERMISSION_DENIED'; /** A malformed argument this door judges itself; a protocol refusal keeps its own code. */ const VALIDATION_ERROR: ErrorCode = 'VALIDATION_ERROR'; @@ -186,8 +212,9 @@ const READ_TOOLS: readonly AIToolDefinition[] = Object.freeze([ name: 'list_drafts', description: 'List the pending metadata drafts in this environment: what was saved as a draft and is not ' - + 'published yet. A person reviews and publishes drafts in Studio. Pass `package` to list one ' - + 'package\'s drafts.', + + 'published yet. A person reviews and publishes drafts in Studio. Each draft carries its publish ' + + 'verdict: `verdict.refusals` lists what a publish would refuse it on (rule id, path, hint), empty ' + + 'when it would publish. Pass `package` to list one package\'s drafts.', parameters: { type: 'object', properties: { @@ -198,11 +225,91 @@ const READ_TOOLS: readonly AIToolDefinition[] = Object.freeze([ }, ]); -/** The protocol reads this door makes, named structurally (a host may fill the slot partially). */ -export type OpenAuthoringProtocol = Partial> & { +/** + * The two draft write tools. `package` is required (seat ruling D4) and is + * judged by the registry rather than by the input schema's `required`, so a + * save naming none is answered with the packages it may name instead of the + * schema validator's bare refusal. + */ +const WRITE_TOOLS: readonly AIToolDefinition[] = Object.freeze([ + { + name: 'save_metadata_draft', + description: + 'Save one metadata item as a DRAFT in a package. Nothing is published: a person reviews and ' + + 'publishes drafts in Studio, and this server has no publish tool. The reply answers what a publish ' + + 'would say about the saved draft: `verdict.refusals` lists every rule the publish would refuse it ' + + 'on, each with its rule id, the path in the item and a `hint` (the next step); fix the item and ' + + 'save again until it is empty. `verdict.advisories` are findings a publish still returns. `review` ' + + 'names the Studio routes where the draft is reviewed. Saving again replaces the pending draft.', + parameters: { + type: 'object', + properties: { + type: TYPE_PARAMETER, + name: { type: 'string', minLength: 1, description: 'The item\'s machine name.' }, + item: { type: 'object', description: 'The item\'s full definition, as `get_metadata_item` reads it.' }, + package: { + type: 'string', + minLength: 1, + description: 'Required: the id of the package the draft is saved into. Studio reviews drafts per package; a save without one is refused with the writable packages named.', + }, + ifMatch: { + type: 'string', + minLength: 1, + description: 'Optional: the `version` a read or a save answered. The save is refused if the draft changed since.', + }, + }, + required: ['type', 'name', 'item'], + additionalProperties: false, + }, + }, + { + name: 'delete_metadata_draft', + description: + 'Discard one pending metadata draft. The published version, if any, is not touched. Pass ' + + '`package` to discard that package\'s draft of the item.', + parameters: { + type: 'object', + properties: { + type: TYPE_PARAMETER, + name: { type: 'string', minLength: 1, description: 'The item\'s machine name.' }, + package: { type: 'string', minLength: 1, description: 'The id of the package whose draft to discard.' }, + }, + required: ['type', 'name'], + additionalProperties: false, + }, + }, +]); + +/** The publish judgement of a stored draft (`ObjectStackProtocolImplementation#draftPublishJudgement`). */ +export interface OpenAuthoringDraftJudgement { + refusals: RuntimeAuthoringIssue[]; + advisories: RuntimeAuthoringIssue[]; +} + +/** The protocol calls this door makes, named structurally (a host may fill the slot partially). */ +export type OpenAuthoringProtocol = Partial> & { listDrafts?(request: { packageId?: string; type?: string }): Promise; + /** The metadata protocol's public draft verdict; with no `body`, it judges the stored draft at the address. */ + draftPublishJudgement?(draft: { + type: string; name: string; packageId: string | null; member?: string; + userTextLocales?: readonly (string | undefined)[]; + }): Promise; }; +/** + * What the write tools need beyond the protocol, built per request by + * {@link resolveOpenAuthoringInjection}; a registry handed none refuses every + * write (fail closed). + */ +export interface OpenAuthoringWriter { + /** The OAuth client the token was issued to, stated on the save as its `client`. */ + clientId?: string; + /** The languages the verdict's user sentences are composed in (`userTextLocalesOf`). */ + userTextLocales: string[]; + /** The walled refusal for a write of `type` (`walledCatalogWriteVerdict`). */ + writeVerdict(type: string): Promise<{ allowed: true } | { allowed: false; code: ErrorCode; message: string; status: number }>; +} + /** * The `/meta` read gates' ports for one protocol, with the admitted human as * the caller. Built by {@link resolveOpenAuthoringInjection}; a registry @@ -276,7 +383,7 @@ export async function resolveOpenAuthoringInjection( admitted: reader !== undefined, userId, getProtocol: async () => (await deps.resolveService(context, 'protocol', context.environmentId)) as OpenAuthoringProtocol | undefined, - ...(reader ? { readGate: openReadGateSources(deps, context, reader) } : {}), + ...(reader ? { readGate: openReadGateSources(deps, context, reader), writer: openWriter(deps, context, clientId) } : {}), logger: deps.logger, }), principal: { @@ -338,6 +445,36 @@ async function resolveHumanReader( } } +/** + * The write tools' per-request inputs. The walled refusal is the one every + * `/meta` write door asks (`walledCatalogWriteVerdict`), on the posture this + * transport reads; a posture that cannot be read refuses the write `503`, + * never a permit. The caller's posture rung is the request envelope's, as the + * `/meta` doors and the MCP `import_object` tool read it. + */ +function openWriter(deps: DomainHandlerDeps, context: HttpProtocolContext, clientId: string | undefined): OpenAuthoringWriter { + const ec: any = context.executionContext; + return { + ...(clientId ? { clientId } : {}), + userTextLocales: userTextLocalesOf(ec), + async writeVerdict(type) { + let tenancyPosture: Awaited>; + try { + tenancyPosture = await readEffectiveTenancyPosture(deps, context); + } catch { + return { + allowed: false, + code: SERVICE_UNAVAILABLE, + message: 'This environment\'s tenancy posture could not be read, so no metadata is written. Nothing was saved or discarded; try again.', + status: 503, + }; + } + const walled = walledCatalogWriteVerdict({ type, tenancyPosture, isSystem: ec?.isSystem === true, callerPosture: ec?.posture }); + return walled.allowed ? { allowed: true } : { allowed: false, code: PERMISSION_DENIED, message: walled.message, status: 403 }; + }, + }; +} + /** Where the app gate's nav-servability prune log records what it has already said, for this door. */ const NAV_PRUNE_LOGGED = new Set(); @@ -389,11 +526,13 @@ export function createOpenAuthoringRegistry(opts: { getProtocol: () => Promise; /** The `/meta` read gates' ports; without them every read is refused. */ readGate?: OpenAuthoringReadGateSources; + /** The write tools' inputs; without them every write is refused. */ + writer?: OpenAuthoringWriter; logger?: { warn?: (...args: unknown[]) => void }; }): OpenAuthoringRegistry { - const { admitted, userId, getProtocol, readGate } = opts; + const { admitted, userId, getProtocol, readGate, writer } = opts; return { - getAll: () => (admitted ? [...READ_TOOLS] : []), + getAll: () => (admitted ? [...READ_TOOLS, ...WRITE_TOOLS] : []), async execute(toolCall, context) { const answer = (body: unknown): OpenAuthoringToolResult => ({ type: 'tool-result', @@ -427,6 +566,9 @@ export function createOpenAuthoringRegistry(opts: { if (typeof readGate !== 'function') { return refuse(PERMISSION_DENIED, 'The authoring tools cannot judge what your account may read on this request.', 403); } + /** The `/meta` item gate, as the doors that serve a stored version for authoring run it. */ + const itemGate = (type: string, name: string, stored: unknown) => + createMetaItemReadGate(readGate(protocol ?? {}), type, name, [stored], STORED_VERSION_DOOR_POLICY)(stored); try { switch (toolCall.toolName) { case 'list_metadata_items': { @@ -470,7 +612,7 @@ export function createOpenAuthoringRegistry(opts: { // The `/meta` item gate, as the doors that serve a stored version // for authoring run it. `absent` is the not-found answer itself // (an unpublished app stays unobservable, ADR-0045 §3). - const verdict = await createMetaItemReadGate(readGate(protocol), type, name, [stored], STORED_VERSION_DOOR_POLICY)(stored); + const verdict = await itemGate(type, name, stored); if (verdict.kind === 'refuse') { const { refusal } = verdict; if (refusal.reason === 'absent') return notFound(); @@ -492,9 +634,87 @@ export function createOpenAuthoringRegistry(opts: { if (input.package !== undefined && !pkg) return refuse(VALIDATION_ERROR, '`package` is a package id.', 400); // ADR-0131 D6: no organization, as the `/meta` drafts list; every // draft is saved environment-wide. + if (typeof protocol.draftPublishJudgement !== 'function' || typeof protocol.getMetaItem !== 'function') { + return unavailable(); + } const listed = await protocol.listDrafts(pkg ? { packageId: pkg } : {}); const drafts = Array.isArray(listed?.drafts) ? listed.drafts : []; - return answer({ count: drafts.length, drafts }); + // The list itself runs no item gate, as `/meta/_drafts` runs + // none: a row is the item's identity and its own label. Each + // verdict is read off the draft's BODY, so it is told only where + // the item gate admits the strict draft read for this human. + const judged = []; + for (const draft of drafts) judged.push({ ...draft, ...(await gatedDraftVerdict(protocol, draft)) }); + return answer({ count: judged.length, drafts: judged }); + } + case 'save_metadata_draft': { + if (typeof protocol?.saveMetaItem !== 'function' || typeof protocol.draftPublishJudgement !== 'function') { + return unavailable(); + } + if (!writer) return refuse(PERMISSION_DENIED, 'The authoring tools cannot write on this request.', 403); + const type = requiredString(input.type); + const name = requiredString(input.name); + if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the item as `type` and `name`.', 400); + const item = input.item; + if (!item || typeof item !== 'object' || Array.isArray(item)) { + return refuse(VALIDATION_ERROR, 'Send the item\'s full definition as `item`, an object.', 400); + } + const pkg = requiredString(input.package); + // Seat ruling D4: Studio's Changes review is per package. + if (!pkg) return refuse(VALIDATION_ERROR, await packageRequiredMessage(protocol), 400); + const ifMatch = input.ifMatch === undefined ? undefined : requiredString(input.ifMatch); + if (input.ifMatch !== undefined && !ifMatch) { + return refuse(VALIDATION_ERROR, '`ifMatch` is the `version` a read or a save answered.', 400); + } + const walled = await writer.writeVerdict(type); + if (!walled.allowed) return refuse(walled.code, walled.message, walled.status); + // Built field by field: `item` is data, never a channel, so no + // `force`, `mode` or `writeFace` rides in through it. + const saved = await protocol.saveMetaItem({ + type, + name, + item, + packageId: pkg, + mode: 'draft', + surface: 'mcp', + ...(writer.clientId ? { client: { id: writer.clientId } } : {}), + // The face of a door with no `force` and a structured issues channel. + writeFace: 'meta-dispatch', + ...(ifMatch ? { parentVersion: ifMatch } : {}), + actor: userId, + userTextLocales: writer.userTextLocales, + }); + const identity = { + type, + name, + package: pkg, + state: (saved as { state?: unknown } | undefined)?.state ?? 'draft', + ...((saved as { version?: unknown } | undefined)?.version !== undefined ? { version: (saved as { version?: unknown }).version } : {}), + }; + const review = reviewRoutes(pkg, type, name); + let judgement: OpenAuthoringDraftJudgement; + try { + judgement = await protocol.draftPublishJudgement({ type, name, packageId: pkg, userTextLocales: writer.userTextLocales }); + } catch (error) { + // The draft is saved; only its verdict is missing, and the + // reply says so rather than reading as a refused save. + return answer({ saved: identity, verdict: null, verdictError: verdictErrorOf(error), review }); + } + return answer({ saved: identity, verdict: verdictOf(judgement), review }); + } + case 'delete_metadata_draft': { + if (typeof protocol?.deleteMetaItem !== 'function') return unavailable(); + if (!writer) return refuse(PERMISSION_DENIED, 'The authoring tools cannot write on this request.', 403); + const type = requiredString(input.type); + const name = requiredString(input.name); + if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the draft as `type` and `name`.', 400); + const pkg = input.package === undefined ? undefined : requiredString(input.package); + if (input.package !== undefined && !pkg) return refuse(VALIDATION_ERROR, '`package` is a package id.', 400); + const walled = await writer.writeVerdict(type); + if (!walled.allowed) return refuse(walled.code, walled.message, walled.status); + // `state: 'draft'`: the pending draft only, never an active item. + await protocol.deleteMetaItem({ type, name, state: 'draft', ...(pkg ? { packageId: pkg } : {}), actor: userId }); + return answer({ discarded: { type, name, package: pkg ?? null } }); } default: return refuse(VALIDATION_ERROR, `'${toolCall.toolName}' is not one of this registry's tools.`, 400); @@ -504,7 +724,61 @@ export function createOpenAuthoringRegistry(opts: { } function unavailable(): OpenAuthoringToolResult { - return refuse(SERVICE_UNAVAILABLE, 'This environment serves no metadata protocol to read from.', 503); + return refuse(SERVICE_UNAVAILABLE, 'This environment serves no metadata protocol this tool can use.', 503); + } + + /** One draft's verdict, told where the item gate admits this human's strict draft read. */ + async function gatedDraftVerdict( + p: OpenAuthoringProtocol, + draft: { type: string; name: string; packageId?: string | null; member?: string }, + ): Promise<{ verdict: ReturnType | null; verdictWithheld?: unknown; verdictError?: unknown }> { + try { + // A package-unbound draft is read without a package: the strict + // draft read's own address resolution then names it. + const read = await p.getMetaItem!({ + type: draft.type, + name: draft.name, + state: 'draft', + ...(draft.packageId ? { packageId: draft.packageId } : {}), + ...(draft.member !== undefined ? { member: draft.member } : {}), + } as Parameters>[0]); + if (read?.item === undefined || read.item === null) { + return { verdict: null, verdictWithheld: { code: RESOURCE_NOT_FOUND, message: `No '${draft.type}' draft named '${draft.name}' is readable here.`, status: 404 } }; + } + const gate = await itemGate(draft.type, draft.name, read.item); + if (gate.kind === 'refuse') { + const { refusal } = gate; + return { + verdict: null, + verdictWithheld: refusal.reason === 'absent' + ? { code: RESOURCE_NOT_FOUND, message: `No '${draft.type}' draft named '${draft.name}' is readable here.`, status: 404 } + : { code: refusal.code, message: refusal.message, status: refusal.status }, + }; + } + const judgement = await p.draftPublishJudgement!({ + type: draft.type, + name: draft.name, + packageId: draft.packageId ?? null, + ...(draft.member !== undefined ? { member: draft.member } : {}), + ...(writer ? { userTextLocales: writer.userTextLocales } : {}), + }); + return { verdict: verdictOf(judgement) }; + } catch (error) { + return { verdict: null, verdictError: verdictErrorOf(error) }; + } + } + + /** A verdict that could not be reached: a coded refusal keeps its code; a fault is named without its text. */ + function verdictErrorOf(error: unknown): { code: string; message: string; status: number } { + const code = (error as { code?: unknown } | null)?.code; + const status = (error as { status?: unknown } | null)?.status; + if (typeof code === 'string' && code.length > 0 && typeof status === 'number' && status < 500) { + return { code, message: error instanceof Error ? error.message : String(error), status }; + } + (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName}: the publish verdict could not be read`, { + error: error instanceof Error ? error.message : String(error), + }); + return { code: INTERNAL_ERROR, message: 'The publish verdict could not be read.', status: 500 }; } /** @@ -521,12 +795,71 @@ export function createOpenAuthoringRegistry(opts: { (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName} failed`, { error: error instanceof Error ? error.message : String(error), }); - return refuse(INTERNAL_ERROR, 'Reading the metadata failed.', 500); + return refuse( + INTERNAL_ERROR, + toolCall.toolName === 'save_metadata_draft' ? 'Saving the draft failed.' + : toolCall.toolName === 'delete_metadata_draft' ? 'Discarding the draft failed.' + : 'Reading the metadata failed.', + 500, + ); } }, }; } +/** A judgement as the replies carry it: `publishable` is "no refusal". */ +function verdictOf(judgement: OpenAuthoringDraftJudgement): { + publishable: boolean; + refusals: RuntimeAuthoringIssue[]; + advisories: RuntimeAuthoringIssue[]; +} { + const refusals = Array.isArray(judgement?.refusals) ? judgement.refusals : []; + const advisories = Array.isArray(judgement?.advisories) ? judgement.advisories : []; + return { publishable: refusals.length === 0, refusals, advisories }; +} + +/** + * Where a person reviews the draft, as Console routes: the package's Changes + * drawer (`?changes=review` on its Interfaces pillar, `studioChangesLink.ts`) + * and the item's draft review on Studio's metadata area (`?review=1`). + */ +function reviewRoutes(packageId: string, type: string, name: string): { changes: string; item: string; note: string } { + const pkg = encodeURIComponent(packageId); + return { + changes: `/studio/${pkg}/interfaces?changes=review`, + item: `/studio/${pkg}/metadata/${encodeURIComponent(type)}/${encodeURIComponent(name)}?review=1`, + note: 'Console routes. A person reviews and publishes the draft there; this server cannot publish.', + }; +} + +/** How many writable package ids the missing-package refusal names. */ +const NAMED_PACKAGES_CAP = 20; + +/** + * The refusal of a save naming no package (seat ruling D4), naming the + * packages it may name: the protocol's own writability verdict on each + * installed package (`getMetaItems({ type: 'package' })`'s `writable`). + */ +async function packageRequiredMessage(protocol: OpenAuthoringProtocol): Promise { + const head = 'Name the package to save the draft into as `package`: Studio reviews and publishes drafts per package. Nothing was saved.'; + let writable: string[] | undefined; + try { + const listed = typeof protocol.getMetaItems === 'function' ? await protocol.getMetaItems({ type: 'package' }) : undefined; + if (listed && Array.isArray(listed.items)) { + writable = listed.items + .filter((p: any) => p?.writable === true) + .map((p: any) => p?.manifest?.id ?? p?.id) + .filter((id: unknown): id is string => typeof id === 'string' && id.length > 0); + } + } catch { + writable = undefined; + } + if (writable === undefined) return `${head} The packages could not be listed on this request; list them with list_metadata_items, type "package".`; + if (writable.length === 0) return `${head} No package in this environment is writable: create one in Studio first.`; + const named = writable.slice(0, NAMED_PACKAGES_CAP).join(', '); + return `${head} Writable packages here: ${named}${writable.length > NAMED_PACKAGES_CAP ? `, and ${writable.length - NAMED_PACKAGES_CAP} more` : ''}.`; +} + function requiredString(value: unknown): string | undefined { return typeof value === 'string' && value.trim().length > 0 ? value : undefined; } From aa96eb004101b8d111a6e8fe96bb0af773a4c7d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:35:10 +0000 Subject: [PATCH 12/25] test(runtime,mcp): pin the draft writes, the verdicts and the app-crm done-when; the open server says authoring lands as drafts Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../initialize-selection-rule-34686.test.ts | 27 ++ packages/mcp/src/mcp-server-runtime.ts | 40 ++- .../mcp/src/skill-md-surface-guard.test.ts | 15 +- .../runtime/src/domains/mcp-authoring.test.ts | 274 +++++++++++++++++- 4 files changed, 335 insertions(+), 21 deletions(-) diff --git a/packages/mcp/src/initialize-selection-rule-34686.test.ts b/packages/mcp/src/initialize-selection-rule-34686.test.ts index cf33e7df170..f9952c4cda1 100644 --- a/packages/mcp/src/initialize-selection-rule-34686.test.ts +++ b/packages/mcp/src/initialize-selection-rule-34686.test.ts @@ -192,3 +192,30 @@ describe('[#34686] initialize instructions — host and configured texts are lef expect(await instructionsOf(runtime, makeBridge())).toBe(CONFIGURED); }); }); + +describe('[#34766] initialize instructions — the drafts line follows the authoring tools', () => { + const DRAFTS = 'They save drafts only'; + const ONE_TOOL = { getAll: () => [{ name: 'save_metadata_draft', description: 'Save a draft.' }], execute: async () => ({}) as never }; + + it('a metadata:write request whose host registry lists a tool is told authoring lands as drafts a person publishes', async () => { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const text = await instructionsOf(runtime, makeBridge(), { + grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_METADATA_WRITE], + authoring: { registry: ONE_TOOL as never }, + }); + expect(text).toContain(DRAFTS); + // The rest of the open text is still there. + expect(carriesRule(text)).toBe(true); + expect(text).toContain('@objectstack/skills'); + }); + + it('no drafts line where no authoring tool registers: an empty registry, a grant without metadata:write, no injection', async () => { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const cases: Opts[] = [ + { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], authoring: {} }, + { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ], authoring: { registry: ONE_TOOL as never } }, + {}, + ]; + for (const o of cases) expect(await instructionsOf(runtime, makeBridge(), o), JSON.stringify(o)).not.toContain(DRAFTS); + }); +}); diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index c11a91bff90..80f5ad65c30 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1826,6 +1826,29 @@ const DATASET_SELECTION_RULE = + 'and no candidates: fall back to query_records / aggregate_records and say the answer is not from a governed ' + 'metric.'; +/** + * [#34766] What a request that registers host-injected authoring tools is told + * about them, in one sentence true of every such registry: authoring lands as + * drafts that a person reviews and publishes (the authoring section of the + * served skill says the same, `skill-md.ts`). What each tool answers — the + * open draft door's save answers with the publish verdict — is the tool's own + * description. Sent only where the authoring family registers tools + * ({@link authoringToolsServed}). + */ +const AUTHORING_DRAFTS_LINE = + 'This connection also lists authoring tools, which change the app\'s metadata. They save drafts only: nothing ' + + 'they write is published until a person reviews and publishes it in Studio. Read each tool\'s reply before ' + + 'the next step; a refused authoring call means you may not author that here.'; + +/** + * [#34766] Does this request register host-injected authoring tools? The gate + * `registerAuthoringTools` reads (`grantsAuthoringTools`) and a registry that + * lists at least one tool for this caller. + */ +function authoringToolsServed(authoring: McpAuthoringInjection | undefined, grantedScopes: readonly string[] | undefined): boolean { + return authoring !== undefined && grantsAuthoringTools(grantedScopes) && authoring.registry.getAll().length > 0; +} + /** * [#34686] The published skills package an open server points a client to * (#34659 ruling D5 = A), at the version to install: this package's own @@ -1846,13 +1869,19 @@ function skillsInstallLine(version: string | undefined): string | undefined { /** * [#34686] The open server's own `initialize` text for one HTTP request: the * default sentence, the selection rule when this request's grant registers - * both dataset tools, and the skills install line. Read only when neither the + * both dataset tools, [#34766] the drafts line when it registers authoring + * tools, and the skills install line. Read only when neither the * host (`hostInstructions`) nor the runtime's configured `instructions` * answers: both are whole texts their author owns, and the configured one is * the same string for every grant, so nothing is appended to either. */ -function openServerInstructions(datasetRule: boolean): string { - return [DEFAULT_HTTP_INSTRUCTIONS, datasetRule ? DATASET_SELECTION_RULE : undefined, skillsInstallLine(PACKAGE_VERSION)] +function openServerInstructions(datasetRule: boolean, authoringServed = false): string { + return [ + DEFAULT_HTTP_INSTRUCTIONS, + datasetRule ? DATASET_SELECTION_RULE : undefined, + authoringServed ? AUTHORING_DRAFTS_LINE : undefined, + skillsInstallLine(PACKAGE_VERSION), + ] .filter((part): part is string => part !== undefined) .join('\n\n'); } @@ -2802,7 +2831,10 @@ export class MCPServerRuntime { instructions: hostInstructions(opts.authoring, opts.toolOptions?.grantedScopes) ?? this.config.instructions ?? - openServerInstructions(datasetToolsServed(opts.bridge, opts.toolOptions)), + openServerInstructions( + datasetToolsServed(opts.bridge, opts.toolOptions), + authoringToolsServed(opts.authoring, opts.toolOptions?.grantedScopes), + ), }, ); diff --git a/packages/mcp/src/skill-md-surface-guard.test.ts b/packages/mcp/src/skill-md-surface-guard.test.ts index 5de822fc7db..d0333b9acc3 100644 --- a/packages/mcp/src/skill-md-surface-guard.test.ts +++ b/packages/mcp/src/skill-md-surface-guard.test.ts @@ -209,27 +209,28 @@ describe('SKILL.md ↔ native tool surface drift guard', () => { }); /** - * [#34766] The open draft door's read tools, named as the runtime registry - * names them (`OPEN_AUTHORING_READ_TOOL_NAMES` in + * [#34766] The open draft door's five tools, named as the runtime registry + * names them (`OPEN_AUTHORING_READ_TOOL_NAMES` and + * `OPEN_AUTHORING_WRITE_TOOL_NAMES` in * `@objectstack/runtime`, `src/domains/mcp-authoring.ts`; this package cannot * import it). The SDK refuses a second registration under a name already on * the server by throwing, so a collision with any native tool would fail * every `metadata:write` request the open runtime serves. */ -const OPEN_DRAFT_DOOR_READ_TOOLS = ['list_metadata_items', 'get_metadata_item', 'list_drafts']; +const OPEN_DRAFT_DOOR_TOOLS = ['list_metadata_items', 'get_metadata_item', 'list_drafts', 'save_metadata_draft', 'delete_metadata_draft']; -describe('[#34766] the open draft door\'s read tools collide with no native tool', () => { +describe('[#34766] the open draft door\'s tools collide with no native tool', () => { it('registers beside the full native surface under every scope', async () => { const native = await listRegisteredToolNames({ grantedScopes: EVERY_SCOPE }); - for (const name of OPEN_DRAFT_DOOR_READ_TOOLS) expect(native, name).not.toContain(name); + for (const name of OPEN_DRAFT_DOOR_TOOLS) expect(native, name).not.toContain(name); const registry: McpAuthoringToolRegistry = { - getAll: () => OPEN_DRAFT_DOOR_READ_TOOLS.map((name) => ({ name, description: name, parameters: { type: 'object', properties: {} } })), + getAll: () => OPEN_DRAFT_DOOR_TOOLS.map((name) => ({ name, description: name, parameters: { type: 'object', properties: {} } })), async execute(toolCall): Promise { return { type: 'tool-result', toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, output: { type: 'text', value: '' } } as ToolExecutionResult; }, }; const withDoor = await listRegisteredToolNames({ grantedScopes: EVERY_SCOPE, registry }); - expect(withDoor.sort()).toEqual([...native, ...OPEN_DRAFT_DOOR_READ_TOOLS].sort()); + expect(withDoor.sort()).toEqual([...native, ...OPEN_DRAFT_DOOR_TOOLS].sort()); }); }); diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 8b997e96c40..7092dc5a896 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -1,7 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#34766] The open MCP draft door's admission and its three read tools. + * [#34766] The open MCP draft door's admission, its three read tools, its two + * draft writes, and the publish verdict a save and each listed draft answer with. * * The effective right is the intersection of the token's consent * (`metadata:write`) and the HUMAN's own `manage_metadata` (seat ruling D1 A). @@ -19,7 +20,19 @@ * resolution that throws admits nothing. */ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { + SysMetadataObject, + SysMetadataHistoryObject, + SysMetadataAuditObject, + SysMetadataCommitObject, +} from '@objectstack/metadata-core'; // The `/mcp` domain reaches the dispatcher, which loads this package lazily; // paid here, during collection, never inside a clocked case. import '@objectstack/metadata'; @@ -27,6 +40,7 @@ import { PLATFORM_PROVIDED_TOOL_NAMES, PLATFORM_TOOL_FAMILY_PREFIXES } from '@ob import { handleMcpRequest } from './mcp.js'; import { OPEN_AUTHORING_READ_TOOL_NAMES, + OPEN_AUTHORING_WRITE_TOOL_NAMES, createOpenAuthoringRegistry, resolveOpenAuthoringInjection, type OpenAuthoringInjection, @@ -78,6 +92,16 @@ async function oauthEnvelope(scopes: string[], systemPermissions: string[]) { } const ADMIN = ['manage_metadata', 'manage_users']; + +/** One publish finding, every member the publish 422 carries. */ +const UNROUTABLE_ISSUE = { + rule: 'flow-trigger-unroutable', + path: 'flows[0].nodes[0].config.triggerType', + where: 'flow "lead_intake" › start node', + message: 'declares type: \'record_change\' but its start node has no triggerType at all', + hint: 'Set triggerType to record-{before,after}-{create,update,delete,write}', + severity: 'error' as const, +}; const NOT_AN_AUTHOR = ['manage_users']; /** @@ -117,6 +141,18 @@ function fakeProtocol(store: Record = {}, opts: { listThrows?: st calls.push(['listDrafts', request]); return { drafts: [{ type: 'flow', name: 'lead_intake', label: 'Lead intake', packageId: 'com.acme.crm', updatedAt: null }] } as any; }, + async saveMetaItem(request: any) { + calls.push(['saveMetaItem', request]); + return { success: true, version: 'v8', seq: 1, state: 'draft' } as any; + }, + async deleteMetaItem(request: any) { + calls.push(['deleteMetaItem', request]); + return { success: true } as any; + }, + async draftPublishJudgement(draft: any) { + calls.push(['draftPublishJudgement', draft]); + return { refusals: [UNROUTABLE_ISSUE], advisories: [] }; + }, }; return { protocol, calls }; } @@ -137,10 +173,18 @@ interface Served { */ async function serve( executionContext: unknown, - opts: { systemPermissions?: string[]; qlThrows?: boolean; store?: Record; listThrows?: string } = {}, + opts: { + systemPermissions?: string[]; qlThrows?: boolean; store?: Record; listThrows?: string; + /** A protocol to serve in place of the recording double (the real one, for the end-to-end pin). */ + protocol?: OpenAuthoringProtocol; + /** The `tenancy` service the walled refusal reads its posture from. */ + tenancy?: { posture: string }; + } = {}, ): Promise { const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN); - const { protocol, calls } = fakeProtocol(opts.store, { listThrows: opts.listThrows }); + const fake = fakeProtocol(opts.store, { listThrows: opts.listThrows }); + const protocol = opts.protocol ?? fake.protocol; + const calls = fake.calls; // The holdings the docs audience reads: the permission sets on the caller the // gate is handed, so a set the human does not hold is not held. const security = { resolvePermissionSetNames: async (ctx: any) => (Array.isArray(ctx?.permissions) ? ctx.permissions : []) }; @@ -154,7 +198,7 @@ async function serve( }; const deps = { resolveService: async (_ctx: unknown, name: string) => (name === 'mcp' ? mcp : name === 'protocol' ? protocol : name === 'security' ? security : undefined), - resolveServiceOrLoud: async () => undefined, + resolveServiceOrLoud: async (_ctx: unknown, name: string) => (name === 'tenancy' ? opts.tenancy : undefined), getObjectQL: async () => { if (opts.qlThrows) throw new Error('engine lookup failed'); return ql; @@ -228,14 +272,14 @@ describe('the open draft door is served only where the token consents AND the us expect(served.protocolCalls).toEqual([]); }); - it('a metadata:write token whose user holds manage_metadata lists the three read tools, and a read is served', async () => { + it('a metadata:write token whose user holds manage_metadata lists the five tools, and a read is served', async () => { const ec = await oauthEnvelope(['metadata:write'], ADMIN); // The envelope itself carries no capability: the door read the human's grant. expect(ec.systemPermissions).toEqual([]); const served = await serve(ec); expect(served.grantReads.length).toBeGreaterThan(0); const authoring = served.authoring!; - expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES]); + expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]); expect(authoring.principal).toMatchObject({ userId: 'u1', clientId: 'c1', scopes: ['metadata:write'] }); expect(authoring.environmentId).toBe('env_1'); @@ -365,7 +409,7 @@ describe('the read tools answer from the metadata protocol\'s public reads', () const listed = await call(authoring, 'list_drafts', { package: 'com.acme.crm' }); await call(authoring, 'list_drafts', {}); expect(listed.body.count).toBe(1); - expect(calls).toEqual([['listDrafts', { packageId: 'com.acme.crm' }], ['listDrafts', {}]]); + expect(calls.filter((c: any) => c[0] === 'listDrafts')).toEqual([['listDrafts', { packageId: 'com.acme.crm' }], ['listDrafts', {}]]); }); it('a coded protocol refusal keeps its code; an uncoded throw is a fault answered without its text', async () => { @@ -463,12 +507,222 @@ describe('the read tools withhold what every /meta door withholds from this huma }); }); -describe('the read tools\' names', () => { +describe('the tools\' names', () => { it('collide with no hosted platform tool (seat ruling D3: not list_metadata)', () => { - for (const name of OPEN_AUTHORING_READ_TOOL_NAMES) { + for (const name of [...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]) { expect(PLATFORM_PROVIDED_TOOL_NAMES.has(name), name).toBe(false); expect(PLATFORM_TOOL_FAMILY_PREFIXES.some((prefix) => name.startsWith(prefix)), name).toBe(false); } expect(PLATFORM_PROVIDED_TOOL_NAMES.has('list_metadata')).toBe(true); }); }); + +// --------------------------------------------------------------------------- +// The draft writes, and the publish verdict each answers with +// --------------------------------------------------------------------------- + +const FLOW_DRAFT = { name: 'lead_intake', label: 'Lead intake', type: 'record_change', nodes: [], edges: [] }; + +/** An admitted author's injection through the real domain, over `protocol` (the recording double by default). */ +async function authorThroughDomain(opts: Parameters[1] = {}) { + const ec = await oauthEnvelope(['metadata:write'], ADMIN); + const served = await serve(ec, opts); + return { authoring: served.authoring!, served }; +} + +describe('save_metadata_draft saves a draft and answers with its publish verdict', () => { + it('saves through saveMetaItem as an mcp draft by the token\'s client, and the reply carries the verdict whole and the Studio routes', async () => { + const { authoring, served } = await authorThroughDomain(); + const saved = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm', ifMatch: 'v7' }); + + expect(saved.isError).toBe(false); + const save = served.protocolCalls.find((c: any) => c[0] === 'saveMetaItem') as any[]; + expect(save[1]).toEqual({ + type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, packageId: 'com.acme.crm', + mode: 'draft', surface: 'mcp', client: { id: 'c1' }, writeFace: 'meta-dispatch', + parentVersion: 'v7', actor: 'u1', userTextLocales: [], + }); + // The verdict is the protocol's judgement of the STORED draft at the saved address. + expect(served.protocolCalls.find((c: any) => c[0] === 'draftPublishJudgement')).toEqual( + ['draftPublishJudgement', { type: 'flow', name: 'lead_intake', packageId: 'com.acme.crm', userTextLocales: [] }], + ); + expect(saved.body).toEqual({ + saved: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm', state: 'draft', version: 'v8' }, + verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE], advisories: [] }, + review: { + changes: '/studio/com.acme.crm/interfaces?changes=review', + item: '/studio/com.acme.crm/metadata/flow/lead_intake?review=1', + note: expect.any(String), + }, + }); + }); + + it('a save naming no package is refused 400 naming the writable packages, and nothing is written (seat ruling D4)', async () => { + const store = { + package: [ + { manifest: { id: 'com.acme.crm' }, writable: true }, + { manifest: { id: 'com.objectstack.platform' }, writable: false }, + ], + }; + const { authoring, served } = await authorThroughDomain({ store }); + const refused = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT }); + + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(refused.body.error.message).toContain('com.acme.crm'); + expect(refused.body.error.message).not.toContain('com.objectstack.platform'); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + + it('under a walled tenancy posture the save is refused 403 before anything is written', async () => { + const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' } }); + const refused = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + + it('a verdict that cannot be read after the save landed is said beside the saved draft, never as a refused save', async () => { + const { protocol, calls } = fakeProtocol(); + protocol.draftPublishJudgement = async () => { throw Object.assign(new Error('No pending draft exists for flow/lead_intake.'), { code: 'NO_DRAFT', status: 404 }); }; + const { authoring } = await authorThroughDomain({ protocol }); + const saved = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect(saved.isError).toBe(false); + expect(saved.body.saved).toMatchObject({ type: 'flow', name: 'lead_intake', package: 'com.acme.crm' }); + expect(saved.body.verdict).toBeNull(); + expect(saved.body.verdictError).toMatchObject({ code: 'NO_DRAFT', status: 404 }); + expect(calls.filter((c: any) => c[0] === 'saveMetaItem')).toHaveLength(1); + }); + + it('a registry handed no writer writes nothing', async () => { + const { protocol, calls } = fakeProtocol(); + const registry = createOpenAuthoringRegistry({ admitted: true, userId: 'u1', getProtocol: async () => protocol, readGate: AUTHOR_READ_GATE }); + for (const [toolName, input] of [ + ['save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }], + ['delete_metadata_draft', { type: 'flow', name: 'lead_intake' }], + ] as const) { + const result = await registry.execute({ toolCallId: 't', toolName, input }, CONTEXT); + expect(JSON.parse(result.output.value).error, toolName).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + } + expect(calls).toEqual([]); + }); +}); + +describe('delete_metadata_draft discards a pending draft only', () => { + it('deletes the draft state, at the package named, attributed to the human', async () => { + const { authoring, served } = await authorThroughDomain(); + const discarded = await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'lead_intake', package: 'com.acme.crm' }); + expect(discarded.body).toEqual({ discarded: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm' } }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'deleteMetaItem')).toEqual( + [['deleteMetaItem', { type: 'flow', name: 'lead_intake', state: 'draft', packageId: 'com.acme.crm', actor: 'u1' }]], + ); + }); + + it('under a walled tenancy posture the discard is refused 403 before anything is deleted', async () => { + const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' } }); + const refused = await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'lead_intake' }); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'deleteMetaItem')).toEqual([]); + }); +}); + +describe('list_drafts answers each draft with its publish verdict, told where the item gate admits the draft read', () => { + it('a draft the human may read carries its verdict; one the item gate refuses them is listed with the verdict withheld', async () => { + const store = { + dashboard: [{ name: 'finance_board', label: 'Finance', requiredPermissions: ['finance.access'], widgets: [] }], + }; + const { protocol } = fakeProtocol(store); + protocol.listDrafts = async () => ({ + drafts: [ + { type: 'flow', name: 'lead_intake', label: 'Lead intake', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, + { type: 'dashboard', name: 'finance_board', label: 'Finance', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, + ], + } as any); + const { authoring } = await authorThroughDomain({ protocol }); + const listed = await call(authoring, 'list_drafts', {}); + + expect(listed.body.count).toBe(2); + const [flow, dashboard] = listed.body.drafts; + // The list stays ungated, as /meta/_drafts: both drafts are listed. + expect(flow).toMatchObject({ type: 'flow', name: 'lead_intake', verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE] } }); + expect(dashboard).toMatchObject({ type: 'dashboard', name: 'finance_board', verdict: null, verdictWithheld: { code: 'PERMISSION_DENIED', status: 403 } }); + }); +}); + +// --------------------------------------------------------------------------- +// Done when: the app-crm shape, end to end, on the real metadata protocol +// --------------------------------------------------------------------------- + +/** + * The card's done-when on the `examples/app-crm` shape (its `com.example.crm` + * package and its `crm_opportunity` object, declared here: this package's + * tests read nothing outside it). The metadata protocol is the real one over a + * real SQL store, the envelope is the real identity door's for an OAuth token + * with `metadata:write` alone, and the door is the real `/mcp` domain: the + * reply's finding is the publish gate's own, not a fixture's. + */ +describe('done when: an OAuth author saves an app-crm flow draft with no routable trigger and gets that finding in the same reply', () => { + let cleanup: Array<() => void> = []; + afterEach(() => { + for (const c of cleanup.reverse()) c(); + cleanup = []; + }); + + async function realProtocol() { + const dir = mkdtempSync(join(tmpdir(), 'os-34766-')); + cleanup.push(() => rmSync(dir, { recursive: true, force: true })); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + const platform = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject] as any[]; + await driver.initObjects(platform); + const engine = new ObjectQL(); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of platform) engine.registry.registerObject(o, '@objectstack/platform-objects'); + engine.registry.registerObject({ + name: 'crm_opportunity', + label: 'Opportunity', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, amount: { type: 'currency', label: 'Amount' } }, + } as any, 'com.example.crm'); + cleanup.push(() => { void engine.destroy(); }); + return new ObjectStackProtocolImplementation(engine as any) as unknown as OpenAuthoringProtocol; + } + + /** A record-triggered flow on the opportunity whose start node names no trigger. */ + const unroutable = { + name: 'crm_opportunity_followup', + label: 'Opportunity follow-up', + type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'crm_opportunity' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }; + + it('the save answers flow-trigger-unroutable with its rule id, path and hint, and list_drafts lists the draft with the same verdict', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]); + + const saved = await call(authoring, 'save_metadata_draft', { + type: 'flow', name: 'crm_opportunity_followup', item: unroutable, package: 'com.example.crm', + }); + expect(saved.isError, JSON.stringify(saved.body)).toBe(false); + expect(saved.body.saved).toMatchObject({ type: 'flow', name: 'crm_opportunity_followup', package: 'com.example.crm', state: 'draft' }); + const finding = saved.body.verdict.refusals.find((issue: any) => issue.rule === 'flow-trigger-unroutable'); + expect(finding, JSON.stringify(saved.body.verdict)).toBeDefined(); + expect(finding.path).toBe('flows[0].nodes[0].config.triggerType'); + expect(typeof finding.hint === 'string' && finding.hint.length > 0).toBe(true); + expect(saved.body.verdict.publishable).toBe(false); + expect(saved.body.review.changes).toBe('/studio/com.example.crm/interfaces?changes=review'); + + // The Studio Changes source: the package's pending drafts. + const listed = await call(authoring, 'list_drafts', { package: 'com.example.crm' }); + expect(listed.body.drafts.map((d: any) => [d.type, d.name, d.packageId])).toEqual([['flow', 'crm_opportunity_followup', 'com.example.crm']]); + expect(listed.body.drafts[0].verdict).toEqual(saved.body.verdict); + + // Discarded, it leaves the list; there was no active item to touch. + expect((await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'crm_opportunity_followup', package: 'com.example.crm' })).isError).toBe(false); + expect((await call(authoring, 'list_drafts', { package: 'com.example.crm' })).body.drafts).toEqual([]); + }); +}); From 1298f20c7a0a984d23ff1c5baf4ef343a4175f54 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:47:18 +0000 Subject: [PATCH 13/25] fix(runtime): the draft writes and the listed verdicts fold the type to its canonical singular before any verdict, gate or write Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../runtime/src/domains/mcp-authoring.test.ts | 12 ++++++++++++ packages/runtime/src/domains/mcp-authoring.ts | 18 +++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 7092dc5a896..0b8c2d63e94 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -557,6 +557,18 @@ describe('save_metadata_draft saves a draft and answers with its publish verdict }); }); + it('a plural type spelling is folded once: the save, the verdict, the discard and the review route name the canonical singular', async () => { + const { authoring, served } = await authorThroughDomain(); + const saved = await call(authoring, 'save_metadata_draft', { type: 'flows', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + await call(authoring, 'delete_metadata_draft', { type: 'flows', name: 'lead_intake', package: 'com.acme.crm' }); + const typesSent = served.protocolCalls + .filter((c: any) => ['saveMetaItem', 'draftPublishJudgement', 'deleteMetaItem'].includes(c[0])) + .map((c: any) => [c[0], c[1].type]); + expect(typesSent).toEqual([['saveMetaItem', 'flow'], ['draftPublishJudgement', 'flow'], ['deleteMetaItem', 'flow']]); + expect(saved.body.saved.type).toBe('flow'); + expect(saved.body.review.item).toBe('/studio/com.acme.crm/metadata/flow/lead_intake?review=1'); + }); + it('a save naming no package is refused 400 naming the writable packages, and nothing is written (seat ruling D4)', async () => { const store = { package: [ diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 8771daef3ab..1d82592170a 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -127,6 +127,7 @@ import { type MetaReadGateCaller, } from '@objectstack/rest'; import { MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; +import { canonicalMetaUrlType } from '@objectstack/spec/shared'; import type { ErrorCode, ListDraftsResponse, MetadataProtocol, RuntimeAuthoringIssue } from '@objectstack/spec/api'; import type { AIToolDefinition } from '@objectstack/spec/contracts'; import type { HttpProtocolContext } from '../http-dispatcher.js'; @@ -652,7 +653,10 @@ export function createOpenAuthoringRegistry(opts: { return unavailable(); } if (!writer) return refuse(PERMISSION_DENIED, 'The authoring tools cannot write on this request.', 403); - const type = requiredString(input.type); + // Folded once to the canonical singular, as the protocol folds a + // plural spelling, so the walled verdict, the save, the verdict and + // the review route all name the type the protocol writes. + const type = canonicalTypeOf(input.type); const name = requiredString(input.name); if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the item as `type` and `name`.', 400); const item = input.item; @@ -705,7 +709,7 @@ export function createOpenAuthoringRegistry(opts: { case 'delete_metadata_draft': { if (typeof protocol?.deleteMetaItem !== 'function') return unavailable(); if (!writer) return refuse(PERMISSION_DENIED, 'The authoring tools cannot write on this request.', 403); - const type = requiredString(input.type); + const type = canonicalTypeOf(input.type); const name = requiredString(input.name); if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the draft as `type` and `name`.', 400); const pkg = input.package === undefined ? undefined : requiredString(input.package); @@ -730,8 +734,10 @@ export function createOpenAuthoringRegistry(opts: { /** One draft's verdict, told where the item gate admits this human's strict draft read. */ async function gatedDraftVerdict( p: OpenAuthoringProtocol, - draft: { type: string; name: string; packageId?: string | null; member?: string }, + listed: { type: string; name: string; packageId?: string | null; member?: string }, ): Promise<{ verdict: ReturnType | null; verdictWithheld?: unknown; verdictError?: unknown }> { + // The gate and the judgement read the canonical singular. + const draft = { ...listed, type: canonicalMetaUrlType(listed.type) }; try { // A package-unbound draft is read without a package: the strict // draft read's own address resolution then names it. @@ -860,6 +866,12 @@ async function packageRequiredMessage(protocol: OpenAuthoringProtocol): Promise< return `${head} Writable packages here: ${named}${writable.length > NAMED_PACKAGES_CAP ? `, and ${writable.length - NAMED_PACKAGES_CAP} more` : ''}.`; } +/** A `type` argument folded to its canonical singular (`dashboards` → `dashboard`), or `undefined` when absent. */ +function canonicalTypeOf(value: unknown): string | undefined { + const type = requiredString(value); + return type === undefined ? undefined : canonicalMetaUrlType(type); +} + function requiredString(value: unknown): string | undefined { return typeof value === 'string' && value.trim().length > 0 ? value : undefined; } From 16c0ab930899f70d2d7f923ce85c46bd2b06fbbb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:58:08 +0000 Subject: [PATCH 14/25] test(runtime,mcp): the real envelope's locales and posture in the write pins; the default-text pins read the drafts line Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- ...mcp-server-runtime.authoring-scope.test.ts | 17 ++++-- .../runtime/src/domains/mcp-authoring.test.ts | 52 +++++++++++++------ 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts b/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts index 703c07261eb..9daca410c1f 100644 --- a/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts +++ b/packages/mcp/src/mcp-server-runtime.authoring-scope.test.ts @@ -57,6 +57,15 @@ import type { ToolRegistry, } from './types.js'; +/** [#34766] The paragraph the open server's default text adds where authoring tools register. */ +const AUTHORING_DRAFTS_PARAGRAPH_START = 'This connection also lists authoring tools'; + +/** The text with that one paragraph taken out (the paragraphs are joined by a blank line). */ +function withoutDraftsParagraph(text: unknown): unknown { + if (typeof text !== 'string') return text; + return text.split('\n\n').filter((part) => !part.startsWith(AUTHORING_DRAFTS_PARAGRAPH_START)).join('\n\n'); +} + // --------------------------------------------------------------------------- // Fixtures // --------------------------------------------------------------------------- @@ -686,10 +695,12 @@ describe('[#31022] per-request instructions on the authoring injection — answe ).toBe(defaultText); }); - it('a metadata:write request whose injection carries no instructions gets the default', async () => { + it('a metadata:write request whose injection carries no instructions gets the default, plus the drafts line its tools earn', async () => { const defaultText = await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }); const subject = await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], registry }); - expect(subject).toBe(defaultText); + // [#34766] The one paragraph a request that registers authoring tools adds. + expect(subject).toContain(AUTHORING_DRAFTS_PARAGRAPH_START); + expect(withoutDraftsParagraph(subject)).toBe(defaultText); }); it('a runtime configured with instructions keeps them for every request the injection does not reach', async () => { @@ -810,7 +821,7 @@ describe('[#32766] data-only instructions on the authoring injection — the com await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ], registry, dataOnlyInstructions: ' \n ' }), ).toBe(defaultText); expect( - await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], registry, instructions: '' }), + withoutDraftsParagraph(await instructionsAtInitialize(runtime, { grantedScopes: [MCP_OAUTH_SCOPE_METADATA_WRITE], registry, instructions: '' })), ).toBe(defaultText); }); diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 0b8c2d63e94..1b66e54a16b 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -523,9 +523,15 @@ describe('the tools\' names', () => { const FLOW_DRAFT = { name: 'lead_intake', label: 'Lead intake', type: 'record_change', nodes: [], edges: [] }; -/** An admitted author's injection through the real domain, over `protocol` (the recording double by default). */ -async function authorThroughDomain(opts: Parameters[1] = {}) { - const ec = await oauthEnvelope(['metadata:write'], ADMIN); +/** + * An admitted author's injection through the real domain, over `protocol` (the + * recording double by default). The fixture's user holds `admin_full_access`, + * which a single-posture resolution anchors as the platform operator; `posture` + * replaces that rung, as a walled deployment's resolution would not grant it. + */ +async function authorThroughDomain(opts: Parameters[1] & { posture?: string } = {}) { + const resolved = await oauthEnvelope(['metadata:write'], ADMIN); + const ec = opts.posture ? { ...resolved, posture: opts.posture } : resolved; const served = await serve(ec, opts); return { authoring: served.authoring!, served }; } @@ -540,11 +546,12 @@ describe('save_metadata_draft saves a draft and answers with its publish verdict expect(save[1]).toEqual({ type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, packageId: 'com.acme.crm', mode: 'draft', surface: 'mcp', client: { id: 'c1' }, writeFace: 'meta-dispatch', - parentVersion: 'v7', actor: 'u1', userTextLocales: [], + // The languages the real envelope states (`userTextLocalesOf`). + parentVersion: 'v7', actor: 'u1', userTextLocales: ['en-US', 'en-US'], }); // The verdict is the protocol's judgement of the STORED draft at the saved address. expect(served.protocolCalls.find((c: any) => c[0] === 'draftPublishJudgement')).toEqual( - ['draftPublishJudgement', { type: 'flow', name: 'lead_intake', packageId: 'com.acme.crm', userTextLocales: [] }], + ['draftPublishJudgement', { type: 'flow', name: 'lead_intake', packageId: 'com.acme.crm', userTextLocales: ['en-US', 'en-US'] }], ); expect(saved.body).toEqual({ saved: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm', state: 'draft', version: 'v8' }, @@ -587,7 +594,7 @@ describe('save_metadata_draft saves a draft and answers with its publish verdict }); it('under a walled tenancy posture the save is refused 403 before anything is written', async () => { - const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' } }); + const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' }, posture: 'TENANT_ADMIN' }); const refused = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); @@ -630,7 +637,7 @@ describe('delete_metadata_draft discards a pending draft only', () => { }); it('under a walled tenancy posture the discard is refused 403 before anything is deleted', async () => { - const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' } }); + const { authoring, served } = await authorThroughDomain({ tenancy: { posture: 'isolated' }, posture: 'TENANT_ADMIN' }); const refused = await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'lead_intake' }); expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); expect(served.protocolCalls.filter((c: any) => c[0] === 'deleteMetaItem')).toEqual([]); @@ -666,8 +673,10 @@ describe('list_drafts answers each draft with its publish verdict, told where th /** * The card's done-when on the `examples/app-crm` shape (its `com.example.crm` - * package and its `crm_opportunity` object, declared here: this package's - * tests read nothing outside it). The metadata protocol is the real one over a + * code package and its `crm_opportunity` object, declared here: this + * package's tests read nothing outside it). A booted code package is + * read-only, so the author saves into a Studio-created base beside it, + * `com.example.crm_studio`, the writable package the D4 refusal would name. The metadata protocol is the real one over a * real SQL store, the envelope is the real identity door's for an OAuth token * with `metadata:write` alone, and the door is the real `/mcp` domain: the * reply's finding is the publish gate's own, not a fixture's. @@ -695,10 +704,14 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl sharingModel: 'private', fields: { name: { type: 'text', label: 'Name' }, amount: { type: 'currency', label: 'Amount' } }, } as any, 'com.example.crm'); + engine.registry.installPackage({ id: 'com.example.crm', name: 'CRM', version: '1.0.0', type: 'app', scope: 'project' } as any, 'code' as never); + engine.registry.installPackage({ id: STUDIO_BASE, name: 'CRM Studio', version: '1.0.0', type: 'app' } as any, 'authored'); cleanup.push(() => { void engine.destroy(); }); return new ObjectStackProtocolImplementation(engine as any) as unknown as OpenAuthoringProtocol; } + const STUDIO_BASE = 'com.example.crm_studio'; + /** A record-triggered flow on the opportunity whose start node names no trigger. */ const unroutable = { name: 'crm_opportunity_followup', @@ -716,25 +729,32 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl const { authoring } = await authorThroughDomain({ protocol }); expect(authoring.registry.getAll().map((t) => t.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]); + // Seat ruling D4: a save naming no package is refused, naming the packages the + // protocol's own writability verdict admits (the base among them). + const unnamed = await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'crm_opportunity_followup', item: unroutable }); + expect(unnamed.body.error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(unnamed.body.error.message).toContain(STUDIO_BASE); + expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]); + const saved = await call(authoring, 'save_metadata_draft', { - type: 'flow', name: 'crm_opportunity_followup', item: unroutable, package: 'com.example.crm', + type: 'flow', name: 'crm_opportunity_followup', item: unroutable, package: STUDIO_BASE, }); expect(saved.isError, JSON.stringify(saved.body)).toBe(false); - expect(saved.body.saved).toMatchObject({ type: 'flow', name: 'crm_opportunity_followup', package: 'com.example.crm', state: 'draft' }); + expect(saved.body.saved).toMatchObject({ type: 'flow', name: 'crm_opportunity_followup', package: STUDIO_BASE, state: 'draft' }); const finding = saved.body.verdict.refusals.find((issue: any) => issue.rule === 'flow-trigger-unroutable'); expect(finding, JSON.stringify(saved.body.verdict)).toBeDefined(); expect(finding.path).toBe('flows[0].nodes[0].config.triggerType'); expect(typeof finding.hint === 'string' && finding.hint.length > 0).toBe(true); expect(saved.body.verdict.publishable).toBe(false); - expect(saved.body.review.changes).toBe('/studio/com.example.crm/interfaces?changes=review'); + expect(saved.body.review.changes).toBe(`/studio/${STUDIO_BASE}/interfaces?changes=review`); // The Studio Changes source: the package's pending drafts. - const listed = await call(authoring, 'list_drafts', { package: 'com.example.crm' }); - expect(listed.body.drafts.map((d: any) => [d.type, d.name, d.packageId])).toEqual([['flow', 'crm_opportunity_followup', 'com.example.crm']]); + const listed = await call(authoring, 'list_drafts', { package: STUDIO_BASE }); + expect(listed.body.drafts.map((d: any) => [d.type, d.name, d.packageId])).toEqual([['flow', 'crm_opportunity_followup', STUDIO_BASE]]); expect(listed.body.drafts[0].verdict).toEqual(saved.body.verdict); // Discarded, it leaves the list; there was no active item to touch. - expect((await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'crm_opportunity_followup', package: 'com.example.crm' })).isError).toBe(false); - expect((await call(authoring, 'list_drafts', { package: 'com.example.crm' })).body.drafts).toEqual([]); + expect((await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'crm_opportunity_followup', package: STUDIO_BASE })).isError).toBe(false); + expect((await call(authoring, 'list_drafts', { package: STUDIO_BASE })).body.drafts).toEqual([]); }); }); From 91c7ac4ed771b1aced35e9f262f09aca0134c6e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 03:02:34 +0000 Subject: [PATCH 15/25] chore(changeset): the open MCP server's draft writes, the listed verdicts and the drafts line Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../34766-mcp-draft-door-write-tools.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .changeset/34766-mcp-draft-door-write-tools.md diff --git a/.changeset/34766-mcp-draft-door-write-tools.md b/.changeset/34766-mcp-draft-door-write-tools.md new file mode 100644 index 00000000000..61c3b03fc4d --- /dev/null +++ b/.changeset/34766-mcp-draft-door-write-tools.md @@ -0,0 +1,20 @@ +--- +'@objectstack/runtime': patch +'@objectstack/mcp': patch +--- + +feat(runtime,mcp): the open MCP server saves and discards metadata drafts, and every save answers with what publishing the draft would say + +Clause-②: yes (widening) +Metadata-protocol: none + +The open draft door on a self-hosted runtime gains its write half. It is served to the same OAuth clients as the read tools: the token carries `metadata:write` and its user holds `manage_metadata`. + +- `save_metadata_draft({ type, name, item, package, ifMatch? })` saves `item` as a pending draft in `package`, recorded as an MCP save by the token's OAuth client. The reply carries `saved` (type, name, package, state, version), `verdict` and `review`. `verdict` is what publishing the stored draft would say: `publishable`, `refusals` (the issues a publish would refuse the draft on) and `advisories`, each with `rule`, `path`, `message`, `hint` and `severity`. `review` holds the Console routes where a person reviews and publishes the draft in Studio. `ifMatch` is the version the save expects to replace; a stale one is refused as the `/meta` draft save refuses it. +- A save that names no `package` is refused `400 VALIDATION_ERROR`, and nothing is saved. The refusal names the writable packages in that environment. +- `delete_metadata_draft({ type, name, package? })` discards a pending draft. The published version, if any, is left as it is. +- `list_drafts` now gives each draft its `verdict`. A draft the user may not read (for example a dashboard whose `requiredPermissions` they lack) is listed with `verdict: null` and the reason it was withheld. + +A plural type spelling (`dashboards`) is folded to its singular before any gate, verdict or write, as the `/meta` doors fold it. A tenant whose catalog is walled refuses both writes `403 PERMISSION_DENIED`, as the `/meta` write path does; a platform admin is admitted. Nothing on this server publishes: there is no publish tool and no `force`. + +When the authoring tools are listed, the open server's default `initialize` instructions add one paragraph saying that they save drafts only and that a person publishes in Studio. The paragraph is absent when the tools are not served, and a host's own instructions replace the default text as before. From bb39cca8810c3038501ff5a0acdf6825d3871a27 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 03:48:01 +0000 Subject: [PATCH 16/25] fix(runtime): the draft door folds the type once at its boundary, so every spelling meets the /meta read gates The protocol's reads fold `type` (`dashboards` reads the dashboard), and the /meta read gates judge the singular type only, leaving the fold to their caller. The door handed the raw argument to both, so a plural or alias spelling was read by the protocol and judged by no gate. It now folds once with `canonicalMetaUrlType`, the protocol's own fold, and hands the folded type to the protocol read, the unknown-type refusal and both gates. A name the fold answers no string for (an inherited member such as `constructor`) goes on unfolded and is refused as an undeclared type. The pins' protocol double folds as the real one does; `dashboards` and `docs` are refused on the item read and left out of the list. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 --- .../runtime/src/domains/mcp-authoring.test.ts | 61 +++++++++++++++++-- packages/runtime/src/domains/mcp-authoring.ts | 29 ++++++++- 2 files changed, 83 insertions(+), 7 deletions(-) diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 8b997e96c40..a55a57ee6e0 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -23,6 +23,7 @@ import { describe, it, expect } from 'vitest'; // The `/mcp` domain reaches the dispatcher, which loads this package lazily; // paid here, during collection, never inside a clocked case. import '@objectstack/metadata'; +import { canonicalMetaUrlType } from '@objectstack/spec/shared'; import { PLATFORM_PROVIDED_TOOL_NAMES, PLATFORM_TOOL_FAMILY_PREFIXES } from '@objectstack/spec/system'; import { handleMcpRequest } from './mcp.js'; import { @@ -82,7 +83,11 @@ const NOT_AN_AUTHOR = ['manage_users']; /** * `store` serves the gated types' items by type (a list read, and a by-name - * read of one of them); every other type answers the flow fixtures. + * read of one of them); every other type answers the flow fixtures. Both reads + * FOLD the requested type first, as the real protocol's reads do + * (`canonicalizeMetaRequestType`, over `canonicalMetaUrlType`), so a plural + * reads the gated type here as it does there; `calls` records the request as + * the door handed it, unfolded. */ function fakeProtocol(store: Record = {}, opts: { listThrows?: string } = {}) { const calls: unknown[] = []; @@ -92,8 +97,9 @@ function fakeProtocol(store: Record = {}, opts: { listThrows?: st async getMetaTypes() { return { types: ['object', 'flow', 'view', 'dashboard', 'book', 'doc'] } as any; }, - async getMetaItems(request: any) { - calls.push(['getMetaItems', request]); + async getMetaItems(handed: any) { + calls.push(['getMetaItems', handed]); + const request = { ...handed, type: canonicalMetaUrlType(handed.type) }; if (opts.listThrows === request.type) throw new Error(`the ${request.type} list read failed`); if (store[request.type]) return { type: request.type, items: store[request.type] }; return { @@ -104,8 +110,9 @@ function fakeProtocol(store: Record = {}, opts: { listThrows?: st ], }; }, - async getMetaItem(request: any) { - calls.push(['getMetaItem', request]); + async getMetaItem(handed: any) { + calls.push(['getMetaItem', handed]); + const request = { ...handed, type: canonicalMetaUrlType(handed.type) }; if (store[request.type]) { const item = store[request.type].find((it) => it.name === request.name); return { type: request.type, name: request.name, item }; @@ -338,6 +345,16 @@ describe('the read tools answer from the metadata protocol\'s public reads', () expect(refused.body.error).toMatchObject({ code: 'INVALID_REQUEST', status: 400 }); }); + it('list_metadata_items refuses an inherited member\'s name as an undeclared type, folded or not', async () => { + const { authoring, calls } = admitted(); + for (const type of ['constructor', 'toString']) { + const refused = await call(authoring, 'list_metadata_items', { type }); + expect(refused.isError, type).toBe(true); + expect(refused.body.error, type).toMatchObject({ code: 'INVALID_REQUEST', status: 400 }); + } + expect(calls).toEqual([]); + }); + it('get_metadata_item reads a draft in place of the published version by default, and the draft only on state draft', async () => { const { authoring, calls } = admitted(); const read = await call(authoring, 'get_metadata_item', { type: 'flow', name: 'lead_intake' }); @@ -445,6 +462,40 @@ describe('the read tools withhold what every /meta door withholds from this huma expect(listed.body.items.map((i: any) => i.name)).toEqual(['crm_intro']); }); + it('a plural spelling is folded at the door: `dashboards` and `docs` are refused on the item read and left out of the list', async () => { + const authoring = await author(); + for (const [type, name, secret] of [ + ['dashboards', 'finance_board', 'finance.access'], + ['docs', 'crm_admin_runbook', 'Rotate the signing keys.'], + ] as const) { + const refused = await call(authoring, 'get_metadata_item', { type, name }); + expect(refused.isError, type).toBe(true); + expect(refused.body.error, type).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(JSON.stringify(refused.body), type).not.toContain(secret); + } + // Served under the plural too, so the refusals above are the gates' verdicts, not a miss. + const allowed = await call(authoring, 'get_metadata_item', { type: 'dashboards', name: 'people_board' }); + expect(allowed.body).toMatchObject({ type: 'dashboard', item: { name: 'people_board' } }); + + const dashboards = await call(authoring, 'list_metadata_items', { type: 'dashboards' }); + expect(dashboards.body).toMatchObject({ type: 'dashboard', items: [{ name: 'people_board' }] }); + expect(dashboards.body.count).toBe(1); + const docs = await call(authoring, 'list_metadata_items', { type: 'docs' }); + expect(docs.body.items.map((i: any) => i.name)).toEqual(['crm_intro']); + }); + + it('the door hands the protocol the folded type, the one the gates judged', async () => { + const ec = await oauthEnvelope(['metadata:write'], ADMIN); + const served = await serve(ec, { store: STORE }); + await call(served.authoring!, 'list_metadata_items', { type: 'docs', state: 'active' }); + await call(served.authoring!, 'get_metadata_item', { type: 'dashboards', name: 'people_board', state: 'active' }); + expect(served.protocolCalls).toEqual(expect.arrayContaining([ + ['getMetaItems', { type: 'doc' }], + ['getMetaItem', { type: 'dashboard', name: 'people_board' }], + ])); + expect(served.protocolCalls.some((c: any) => c[1]?.type === 'docs' || c[1]?.type === 'dashboards')).toBe(false); + }); + it('a gate that cannot evaluate refuses: a books read that throws serves no doc', async () => { const authoring = await author({ listThrows: 'book' }); const refused = await call(authoring, 'get_metadata_item', { type: 'doc', name: 'crm_intro' }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index ddb16de3ac4..3042b94e8bd 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -60,6 +60,13 @@ * `requiredPermissions` the human does not hold, and a book or doc outside * their ADR-0046 audience, are refused here as every `/meta` door refuses * them to that human ("either way, author or not", ruling 5856774816). + * Whatever spelling of `type` the agent sends: the door folds it once, at + * its boundary, with the fold the protocol's reads apply + * (`canonicalMetaUrlType`), and hands the one folded type to the protocol + * read, to the unknown-type refusal and to both gates. The gates judge the + * SINGULAR type only and leave the fold to their caller, as every `/meta` + * caller of them folds first; an unfolded `dashboards` or `docs` would be + * read as the dashboard or doc by the protocol and judged by no gate. * The caller the gates read is built from the grants the admission * resolved (`resolveUserAuthzGrants`), never from the agent's envelope, * whose system permissions and permission sets are the token's ceiling. @@ -105,6 +112,7 @@ import { type MetaReadGateCaller, } from '@objectstack/rest'; import { MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; +import { canonicalMetaUrlType } from '@objectstack/spec/shared'; import type { ErrorCode, ListDraftsResponse, MetadataProtocol } from '@objectstack/spec/api'; import type { AIToolDefinition } from '@objectstack/spec/contracts'; import type { HttpProtocolContext } from '../http-dispatcher.js'; @@ -431,7 +439,7 @@ export function createOpenAuthoringRegistry(opts: { switch (toolCall.toolName) { case 'list_metadata_items': { if (typeof protocol?.getMetaItems !== 'function') return unavailable(); - const type = requiredString(input.type); + const type = canonicalTypeOf(input.type); if (!type) return refuse(VALIDATION_ERROR, 'Name the metadata type as `type`.', 400); // A type the platform does not declare and this deployment holds // nothing under is refused, as the `/meta` list refuses it, rather @@ -456,7 +464,7 @@ export function createOpenAuthoringRegistry(opts: { } case 'get_metadata_item': { if (typeof protocol?.getMetaItem !== 'function') return unavailable(); - const type = requiredString(input.type); + const type = canonicalTypeOf(input.type); const name = requiredString(input.name); if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the item as `type` and `name`.', 400); const read = await protocol.getMetaItem({ @@ -527,6 +535,23 @@ export function createOpenAuthoringRegistry(opts: { }; } +/** + * A `type` argument folded to its canonical singular (`dashboards` → `dashboard`), + * or `undefined` when absent: the door's one fold, applied once at its + * boundary, so the protocol read, the unknown-type refusal and both read gates + * see the same type. It is the fold the protocol's reads apply themselves. + */ +function canonicalTypeOf(value: unknown): string | undefined { + const type = requiredString(value); + if (type === undefined) return undefined; + const folded: unknown = canonicalMetaUrlType(type); + // The fold reads a plain object, so an inherited member's name + // (`constructor`, `toString`) answers no string. Such a spelling names no + // type: it goes on unfolded, and the unknown-type refusal judges it as it + // judges any other undeclared spelling. + return typeof folded === 'string' ? folded : type; +} + function requiredString(value: unknown): string | undefined { return typeof value === 'string' && value.trim().length > 0 ? value : undefined; } From b7838f512fa2cfaeb8a866d0fcce5bbb1e83618d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 03:52:19 +0000 Subject: [PATCH 17/25] test(runtime): pin that an inherited member's name reaches the protocol as the string sent The fold answers a function for `constructor` or `toString`; the door keeps the agent's string then, the spelling every /meta door hands the protocol. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 --- packages/runtime/src/domains/mcp-authoring.test.ts | 14 +++++++------- packages/runtime/src/domains/mcp-authoring.ts | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index a55a57ee6e0..15a473dcb1c 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -345,14 +345,14 @@ describe('the read tools answer from the metadata protocol\'s public reads', () expect(refused.body.error).toMatchObject({ code: 'INVALID_REQUEST', status: 400 }); }); - it('list_metadata_items refuses an inherited member\'s name as an undeclared type, folded or not', async () => { + it('an inherited member\'s name, which the fold answers no string for, reaches the protocol as the string sent', async () => { const { authoring, calls } = admitted(); - for (const type of ['constructor', 'toString']) { - const refused = await call(authoring, 'list_metadata_items', { type }); - expect(refused.isError, type).toBe(true); - expect(refused.body.error, type).toMatchObject({ code: 'INVALID_REQUEST', status: 400 }); - } - expect(calls).toEqual([]); + await call(authoring, 'list_metadata_items', { type: 'constructor', state: 'active' }); + await call(authoring, 'get_metadata_item', { type: 'toString', name: 'lead_intake', state: 'active' }); + expect(calls).toEqual([ + ['getMetaItems', { type: 'constructor' }], + ['getMetaItem', { type: 'toString', name: 'lead_intake' }], + ]); }); it('get_metadata_item reads a draft in place of the published version by default, and the draft only on state draft', async () => { diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 3042b94e8bd..a121757d632 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -546,9 +546,9 @@ function canonicalTypeOf(value: unknown): string | undefined { if (type === undefined) return undefined; const folded: unknown = canonicalMetaUrlType(type); // The fold reads a plain object, so an inherited member's name - // (`constructor`, `toString`) answers no string. Such a spelling names no - // type: it goes on unfolded, and the unknown-type refusal judges it as it - // judges any other undeclared spelling. + // (`constructor`, `toString`) answers a function, not a type. The door's + // type stays the string the agent sent then: the spelling the protocol and + // the unknown-type refusal are handed for it on every `/meta` door. return typeof folded === 'string' ? folded : type; } From b39f0f8ea5f6ce559df4fd4863cceda26a79196c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 04:42:59 +0000 Subject: [PATCH 18/25] chore(scripts): declare the draft door's tool-call refusal as how its save catch delivers the failure The tool switch's outer catch in packages/runtime/src/domains/mcp-authoring.ts guards saveMetaItem and returns refusalFromThrown on its only path: an isError tool result carrying the ADR-0112 envelope built from the caught error. The failure is handed to the agent that asked, so the gate's remedy is a FAILURE_PROPAGATION_SITES declaration scoped to that one function, not a log. Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- scripts/check-durability-degradation-log-level.mjs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/scripts/check-durability-degradation-log-level.mjs b/scripts/check-durability-degradation-log-level.mjs index 0b211c77411..da91f59ffa7 100644 --- a/scripts/check-durability-degradation-log-level.mjs +++ b/scripts/check-durability-degradation-log-level.mjs @@ -636,6 +636,20 @@ const FAILURE_PROPAGATION_SITES = new Map([ + "(#22985); `schema-migration-plugins.test.ts` pins the refusal note and the failed count.", }, ], + [ + 'packages/runtime/src/domains/mcp-authoring.ts::execute', + { + callees: [['refusalFromThrown', 'return']], + why: + "`refusalFromThrown()` is the open draft door's tool-call refusal: it builds the MCP tool result " + + 'with `isError: true` and an ADR-0112 `{ code, message, status }` envelope FROM the caught error, ' + + 'keeping a coded 4xx refusal whole and answering any other throw `500 INTERNAL_ERROR`. The tool ' + + 'switch\'s outer catch returns it on its only path, so the agent that asked for the draft save is ' + + 'told, in the same reply, that the draft did not land. Scoped to this one function because the ' + + 'name is a closure local to it (#34766); `mcp-authoring.test.ts` pins the coded refusal and the ' + + 'uncoded fault answered without its text.', + }, + ], ]); // ───────────────────────────────────────────────────────────────────────────── From ffb4f7b145f582e5194e20f06087ddc5c94ab58f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 04:52:12 +0000 Subject: [PATCH 19/25] test(runtime): pin that an inherited member's name as the write tools' type is refused and writes nothing Against the real protocol on a SqlDriver store: save_metadata_draft and delete_metadata_draft with type `constructor` or `toString` (which the door's fold keeps as sent) answer an error and leave no draft. Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../runtime/src/domains/mcp-authoring.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 5b990fe4a92..3758d45b52f 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -808,4 +808,19 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl expect((await call(authoring, 'delete_metadata_draft', { type: 'flow', name: 'crm_opportunity_followup', package: STUDIO_BASE })).isError).toBe(false); expect((await call(authoring, 'list_drafts', { package: STUDIO_BASE })).body.drafts).toEqual([]); }); + + it('an inherited member\'s name as `type`, which the fold keeps as sent, is refused and writes nothing', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + for (const type of ['constructor', 'toString']) { + // Refused, not written. The status is the protocol's answer for such a name, + // not pinned here: its own fold reads a plain object (Acceptance notes). + const saved = await call(authoring, 'save_metadata_draft', { type, name: 'crm_opportunity_followup', item: unroutable, package: STUDIO_BASE }); + expect(saved.isError, `${type}: ${JSON.stringify(saved.body)}`).toBe(true); + expect(saved.body.saved, type).toBeUndefined(); + const discarded = await call(authoring, 'delete_metadata_draft', { type, name: 'crm_opportunity_followup', package: STUDIO_BASE }); + expect(discarded.isError, `${type}: ${JSON.stringify(discarded.body)}`).toBe(true); + } + expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]); + }); }); From c1368f8042299c502711ccad72151099280ad64f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:27:39 +0000 Subject: [PATCH 20/25] fix(runtime): the draft door's reads run the /meta type-level read admission before any read get_metadata_item and list_metadata_items ask metaTypeReadRefusal of the folded type, with the human as the caller, before the protocol read and the item and list gates, on every state branch: a metadata type the caller may not read is refused as every /meta read refuses it. Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../runtime/src/domains/mcp-authoring.test.ts | 30 ++++++++++++++++++- packages/runtime/src/domains/mcp-authoring.ts | 23 ++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 15a473dcb1c..a72a1ccd772 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -95,7 +95,7 @@ function fakeProtocol(store: Record = {}, opts: { listThrows?: st // The live type set the unknown-type refusal reads: without it the refusal // cannot disprove a type and lets it through. async getMetaTypes() { - return { types: ['object', 'flow', 'view', 'dashboard', 'book', 'doc'] } as any; + return { types: ['object', 'flow', 'view', 'dashboard', 'book', 'doc', 'datasource'] } as any; }, async getMetaItems(handed: any) { calls.push(['getMetaItems', handed]); @@ -496,6 +496,34 @@ describe('the read tools withhold what every /meta door withholds from this huma expect(served.protocolCalls.some((c: any) => c[1]?.type === 'docs' || c[1]?.type === 'dashboards')).toBe(false); }); + it('a type the caller may not read is refused on item and list reads, on every state, before any protocol read', async () => { + const store = { ...STORE, datasource: [{ name: 'warehouse', label: 'Warehouse', driver: 'postgres' }] }; + const ec = await oauthEnvelope(['metadata:write'], ADMIN); + const served = await serve(ec, { store }); + const authoring = served.authoring!; + for (const state of [undefined, 'active', 'draft'] as const) { + for (const [toolName, input] of [ + ['get_metadata_item', { type: 'datasource', name: 'warehouse' }], + ['get_metadata_item', { type: 'datasources', name: 'warehouse' }], + ['get_metadata_item', { type: 'datasource', name: 'missing' }], + ['list_metadata_items', { type: 'datasource' }], + ] as const) { + const refused = await call(authoring, toolName, { ...input, ...(state ? { state } : {}) }); + const label = `${toolName} ${JSON.stringify(input)} ${state ?? '(default)'}`; + expect(refused.isError, label).toBe(true); + expect(refused.body.error, label).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(JSON.stringify(refused.body), label).not.toContain('postgres'); + } + } + expect(served.protocolCalls).toEqual([]); + + // The control: a human who holds the type's capability is served the same reads. + const holder = [...ADMIN, 'manage_platform_settings']; + const allowed = (await serve(await oauthEnvelope(['metadata:write'], holder), { store, systemPermissions: holder })).authoring!; + expect((await call(allowed, 'get_metadata_item', { type: 'datasource', name: 'warehouse' })).body.item).toMatchObject({ name: 'warehouse' }); + expect((await call(allowed, 'list_metadata_items', { type: 'datasources' })).body.items.map((i: any) => i.name)).toEqual(['warehouse']); + }); + it('a gate that cannot evaluate refuses: a books read that throws serves no doc', async () => { const authoring = await author({ listThrows: 'book' }); const refused = await call(authoring, 'get_metadata_item', { type: 'doc', name: 'crm_intro' }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index a121757d632..31253aca907 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -70,6 +70,12 @@ * The caller the gates read is built from the grants the admission * resolved (`resolveUserAuthzGrants`), never from the agent's envelope, * whose system permissions and permission sets are the token's ceiling. + * - Before either gate and before any protocol read, both reads ask the + * `/meta` type-level read admission (`metaTypeReadRefusal`, over + * `META_TYPE_READ_CAPABILITIES`) of the folded type, with the same human + * caller, on every `state`: a type whose own door requires a capability + * the human does not hold is refused here as every `/meta` read refuses + * it, `manage_metadata` or not. * - The item read runs `STORED_VERSION_DOOR_POLICY`, the policy of the * `/meta` doors that serve a stored version for authoring (the plain read's * `?state=draft` branch among them): only the per-caller gates, and the @@ -106,6 +112,7 @@ import { metaWriteCapabilityVerdict } from '@objectstack/metadata-core'; import { createMetaItemReadGate, createMetaListReadGate, + metaTypeReadRefusal, refuseUnknownMetaListType, STORED_VERSION_DOOR_POLICY, type MetaItemReadGateSources, @@ -441,6 +448,8 @@ export function createOpenAuthoringRegistry(opts: { if (typeof protocol?.getMetaItems !== 'function') return unavailable(); const type = canonicalTypeOf(input.type); if (!type) return refuse(VALIDATION_ERROR, 'Name the metadata type as `type`.', 400); + const typeRefused = await typeReadRefusal(type); + if (typeRefused) return typeRefused; // A type the platform does not declare and this deployment holds // nothing under is refused, as the `/meta` list refuses it, rather // than answered an empty list. @@ -467,6 +476,8 @@ export function createOpenAuthoringRegistry(opts: { const type = canonicalTypeOf(input.type); const name = requiredString(input.name); if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the item as `type` and `name`.', 400); + const typeRefused = await typeReadRefusal(type); + if (typeRefused) return typeRefused; const read = await protocol.getMetaItem({ type, name, @@ -511,6 +522,18 @@ export function createOpenAuthoringRegistry(opts: { return refusalFromThrown(error); } + /** + * The `/meta` type-level read admission (`metaTypeReadRefusal`), asked + * of the folded type with the human as the caller, before any read + * of the protocol, on every `state`: a type whose own door requires + * a capability the human lacks is refused here as every `/meta` read + * refuses it, whether or not the named item exists. + */ + async function typeReadRefusal(type: string): Promise { + const refusal = metaTypeReadRefusal('GET', type, await readGate!(protocol ?? {}).resolveCaller()); + return refusal ? refuse(refusal.code, refusal.message, refusal.status) : undefined; + } + function unavailable(): OpenAuthoringToolResult { return refuse(SERVICE_UNAVAILABLE, 'This environment serves no metadata protocol to read from.', 503); } From c50358b59c97a6bfd111f4c215a9c5ffe3167c57 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:28:45 +0000 Subject: [PATCH 21/25] chore(changeset): the draft door's reads ask the /meta type-level read admission Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .changeset/34766-mcp-open-draft-door-read.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34766-mcp-open-draft-door-read.md b/.changeset/34766-mcp-open-draft-door-read.md index d68d21946cf..1f9ae7dcb14 100644 --- a/.changeset/34766-mcp-open-draft-door-read.md +++ b/.changeset/34766-mcp-open-draft-door-read.md @@ -15,6 +15,6 @@ An AI client connected over MCP with an OAuth token that carries `metadata:write The tools are served only where both halves hold: the token consents (`metadata:write`) and the user the token was issued to holds `manage_metadata` in the organization the token bound. The user's capability is read from their own grants on each request, because an OAuth agent's envelope carries no system permission without `actions:execute`. A token whose user lacks the capability is listed none of the three tools, and a call that reaches them anyway is refused `403 PERMISSION_DENIED`. A token without `metadata:write`, an API key and a session see none of them, as before. When the user's grants cannot be read, the tools are not served on that request and the runtime logs one warning. -The reads withhold what every `/meta` door withholds from that user, judged by the same read gates with the user as the caller: a dashboard, a list view or an app whose `requiredPermissions` the user does not hold, and a book or doc outside their audience, are refused `403 PERMISSION_DENIED` by `get_metadata_item` and left out of `list_metadata_items`. Holding `manage_metadata` does not lift these refusals. A gate that cannot evaluate refuses the read. +The reads withhold what every `/meta` door withholds from that user, judged by the same read gates with the user as the caller: a dashboard, a list view or an app whose `requiredPermissions` the user does not hold, and a book or doc outside their audience, are refused `403 PERMISSION_DENIED` by `get_metadata_item` and left out of `list_metadata_items`. Before either gate, both reads ask the type-level read admission every `/meta` read asks: a metadata type the user may not read is refused `403 PERMISSION_DENIED` on both, whatever its spelling or `state`. Holding `manage_metadata` does not lift these refusals. A gate that cannot evaluate refuses the read. The read tools are named `list_metadata_items` and `get_metadata_item`, not `list_metadata` and `get_metadata`, because `list_metadata` is a hosted platform tool. Nothing here writes: saving and discarding drafts, and the publish verdict a save answers with, come in a later change. From 1294fe181cd13cfac528e5f191fc8f5405eee0cf Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:30:36 +0000 Subject: [PATCH 22/25] fix(runtime): the draft door's writes and verdicts ask the /meta type-level admissions save_metadata_draft and delete_metadata_draft ask metaTypeWriteRefusal (as PUT and DELETE) with the human as the caller before the walled refusal and before anything is written: a metadata type the caller may not write is refused as every /meta write refuses it. The authoring admission alone does not cover a type whose own write door requires more. The save's verdict and each listed draft's verdict are reads of the stored draft's body, so both are told only where metaTypeReadRefusal admits the human; elsewhere the reply says the verdict was withheld. Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../34766-mcp-draft-door-write-tools.md | 2 +- .../runtime/src/domains/mcp-authoring.test.ts | 41 +++++++++++++++-- packages/runtime/src/domains/mcp-authoring.ts | 45 +++++++++++++++++-- 3 files changed, 80 insertions(+), 8 deletions(-) diff --git a/.changeset/34766-mcp-draft-door-write-tools.md b/.changeset/34766-mcp-draft-door-write-tools.md index 61c3b03fc4d..e9c21d079cc 100644 --- a/.changeset/34766-mcp-draft-door-write-tools.md +++ b/.changeset/34766-mcp-draft-door-write-tools.md @@ -15,6 +15,6 @@ The open draft door on a self-hosted runtime gains its write half. It is served - `delete_metadata_draft({ type, name, package? })` discards a pending draft. The published version, if any, is left as it is. - `list_drafts` now gives each draft its `verdict`. A draft the user may not read (for example a dashboard whose `requiredPermissions` they lack) is listed with `verdict: null` and the reason it was withheld. -A plural type spelling (`dashboards`) is folded to its singular before any gate, verdict or write, as the `/meta` doors fold it. A tenant whose catalog is walled refuses both writes `403 PERMISSION_DENIED`, as the `/meta` write path does; a platform admin is admitted. Nothing on this server publishes: there is no publish tool and no `force`. +A plural type spelling (`dashboards`) is folded to its singular before any gate, verdict or write, as the `/meta` doors fold it. Both writes ask the type-level write admission every `/meta` write asks, so a metadata type the user may not write is refused `403 PERMISSION_DENIED` and nothing is written; a verdict, on a save or a listed draft, is withheld for a type the user may not read. A tenant whose catalog is walled refuses both writes `403 PERMISSION_DENIED`, as the `/meta` write path does; a platform admin is admitted. Nothing on this server publishes: there is no publish tool and no `force`. When the authoring tools are listed, the open server's default `initialize` instructions add one paragraph saying that they save drafts only and that a person publishes in Studio. The paragraph is absent when the tools are not served, and a host's own instructions replace the default text as before. diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 9680d019f9b..d6c31cfc500 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -655,6 +655,37 @@ describe('save_metadata_draft saves a draft and answers with its publish verdict expect(saved.body.review.item).toBe('/studio/com.acme.crm/metadata/flow/lead_intake?review=1'); }); + it('a type the caller may not write is refused on the save and the discard before anything is written', async () => { + const { authoring, served } = await authorThroughDomain(); + for (const type of ['datasource', 'datasources']) { + const saved = await call(authoring, 'save_metadata_draft', { type, name: 'warehouse', item: { name: 'warehouse' }, package: 'com.acme.crm' }); + expect(saved.body.error, type).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + const discarded = await call(authoring, 'delete_metadata_draft', { type, name: 'warehouse', package: 'com.acme.crm' }); + expect(discarded.body.error, type).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + } + expect(served.protocolCalls.filter((c: any) => ['saveMetaItem', 'deleteMetaItem', 'draftPublishJudgement'].includes(c[0]))).toEqual([]); + + // The control: a human who holds the type's capability writes it. + const holder = [...ADMIN, 'manage_platform_settings']; + const ec = await oauthEnvelope(['metadata:write'], holder); + const allowed = await serve(ec, { systemPermissions: holder }); + expect((await call(allowed.authoring!, 'save_metadata_draft', { type: 'datasource', name: 'warehouse', item: { name: 'warehouse' }, package: 'com.acme.crm' })).isError).toBe(false); + expect((await call(allowed.authoring!, 'delete_metadata_draft', { type: 'datasource', name: 'warehouse', package: 'com.acme.crm' })).isError).toBe(false); + expect(allowed.protocolCalls.filter((c: any) => ['saveMetaItem', 'deleteMetaItem'].includes(c[0])).map((c: any) => [c[0], c[1].type])).toEqual( + [['saveMetaItem', 'datasource'], ['deleteMetaItem', 'datasource']], + ); + }); + + it('a save of a type the caller may not read lands, and its verdict is withheld rather than read', async () => { + const { authoring, served } = await authorThroughDomain(); + const saved = await call(authoring, 'save_metadata_draft', { type: 'external_catalog', name: 'warehouse_catalog', item: { name: 'warehouse_catalog' }, package: 'com.acme.crm' }); + expect(saved.isError).toBe(false); + expect(saved.body.saved).toMatchObject({ type: 'external_catalog', name: 'warehouse_catalog' }); + expect(saved.body.verdict).toBeNull(); + expect(saved.body.verdictWithheld).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'draftPublishJudgement')).toEqual([]); + }); + it('a save naming no package is refused 400 naming the writable packages, and nothing is written (seat ruling D4)', async () => { const store = { package: [ @@ -728,18 +759,22 @@ describe('list_drafts answers each draft with its publish verdict, told where th const store = { dashboard: [{ name: 'finance_board', label: 'Finance', requiredPermissions: ['finance.access'], widgets: [] }], }; - const { protocol } = fakeProtocol(store); + const { protocol, calls } = fakeProtocol(store); protocol.listDrafts = async () => ({ drafts: [ { type: 'flow', name: 'lead_intake', label: 'Lead intake', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, { type: 'dashboard', name: 'finance_board', label: 'Finance', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, + { type: 'datasource', name: 'warehouse', label: 'Warehouse', packageId: 'com.acme.crm', updatedAt: null, updatedBy: null }, ], } as any); const { authoring } = await authorThroughDomain({ protocol }); const listed = await call(authoring, 'list_drafts', {}); - expect(listed.body.count).toBe(2); - const [flow, dashboard] = listed.body.drafts; + expect(listed.body.count).toBe(3); + const [flow, dashboard, typeRefused] = listed.body.drafts; + // A type the caller may not read: its body is not read and no verdict is told. + expect(typeRefused).toMatchObject({ type: 'datasource', name: 'warehouse', verdict: null, verdictWithheld: { code: 'PERMISSION_DENIED', status: 403 } }); + expect(calls.some((c: any) => c[1]?.type === 'datasource')).toBe(false); // The list stays ungated, as /meta/_drafts: both drafts are listed. expect(flow).toMatchObject({ type: 'flow', name: 'lead_intake', verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE] } }); expect(dashboard).toMatchObject({ type: 'dashboard', name: 'finance_board', verdict: null, verdictWithheld: { code: 'PERMISSION_DENIED', status: 403 } }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 80991df11f9..04e3fe15e4f 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -104,9 +104,16 @@ * save. * - `delete_metadata_draft` discards a pending draft through `deleteMetaItem` * with `state: 'draft'`, never an active item. - * - Both ask the walled refusal (`walledCatalogWriteVerdict`, ADR-0131 - * D3/D12) before anything is written, as every `/meta` write door does, on - * the posture this transport reads (`readEffectiveTenancyPosture`). + * - Both ask the `/meta` type-level write admission (`metaTypeWriteRefusal`, + * the save as `PUT`, the discard as `DELETE`) with the human as the caller, + * then the walled refusal (`walledCatalogWriteVerdict`, ADR-0131 D3/D12), + * before anything is written, as every `/meta` write door does, on the + * posture this transport reads (`readEffectiveTenancyPosture`). The + * authoring admission (D1) alone does not cover a type whose own write + * door requires more. + * - A verdict is a read of the stored draft's body, so the save's verdict + * and each listed draft's verdict are told only where the type-level read + * admission admits the human; elsewhere the reply says it was withheld. * - `list_drafts` stays ungated as a list (as `/meta/_drafts`), and each * entry now carries its publish verdict. The verdict is read off the * draft's body, so it is told only where the `/meta` item gate admits the @@ -135,6 +142,7 @@ import { createMetaItemReadGate, createMetaListReadGate, metaTypeReadRefusal, + metaTypeWriteRefusal, refuseUnknownMetaListType, STORED_VERSION_DOOR_POLICY, type MetaItemReadGateSources, @@ -688,6 +696,9 @@ export function createOpenAuthoringRegistry(opts: { if (input.ifMatch !== undefined && !ifMatch) { return refuse(VALIDATION_ERROR, '`ifMatch` is the `version` a read or a save answered.', 400); } + // The `/meta` type-level write admission, before anything is written. + const typeWriteRefused = await typeAdmission('PUT', type); + if (typeWriteRefused) return refuse(typeWriteRefused.code, typeWriteRefused.message, typeWriteRefused.status); const walled = await writer.writeVerdict(type); if (!walled.allowed) return refuse(walled.code, walled.message, walled.status); // Built field by field: `item` is data, never a channel, so no @@ -714,6 +725,12 @@ export function createOpenAuthoringRegistry(opts: { ...((saved as { version?: unknown } | undefined)?.version !== undefined ? { version: (saved as { version?: unknown }).version } : {}), }; const review = reviewRoutes(pkg, type, name); + // The verdict is a read of the stored draft: told only where the + // `/meta` type-level read admission admits this human. + const typeReadRefused = await typeAdmission('read', type); + if (typeReadRefused) { + return answer({ saved: identity, verdict: null, verdictWithheld: typeReadRefused, review }); + } let judgement: OpenAuthoringDraftJudgement; try { judgement = await protocol.draftPublishJudgement({ type, name, packageId: pkg, userTextLocales: writer.userTextLocales }); @@ -732,6 +749,8 @@ export function createOpenAuthoringRegistry(opts: { if (!type || !name) return refuse(VALIDATION_ERROR, 'Name the draft as `type` and `name`.', 400); const pkg = input.package === undefined ? undefined : requiredString(input.package); if (input.package !== undefined && !pkg) return refuse(VALIDATION_ERROR, '`package` is a package id.', 400); + const typeWriteRefused = await typeAdmission('DELETE', type); + if (typeWriteRefused) return refuse(typeWriteRefused.code, typeWriteRefused.message, typeWriteRefused.status); const walled = await writer.writeVerdict(type); if (!walled.allowed) return refuse(walled.code, walled.message, walled.status); // `state: 'draft'`: the pending draft only, never an active item. @@ -753,10 +772,25 @@ export function createOpenAuthoringRegistry(opts: { * refuses it, whether or not the named item exists. */ async function typeReadRefusal(type: string): Promise { - const refusal = metaTypeReadRefusal('GET', type, await readGate!(protocol ?? {}).resolveCaller()); + const refusal = await typeAdmission('read', type); return refusal ? refuse(refusal.code, refusal.message, refusal.status) : undefined; } + /** + * The `/meta` type-level admissions, read or write, with the human as + * the caller: `metaTypeReadRefusal` for a read of a typed item (a draft's + * body, the verdict read off it), `metaTypeWriteRefusal` for a draft save + * (`PUT`) or discard (`DELETE`), as the `/meta` entry asks them of the + * same verbs. `undefined` admits. + */ + async function typeAdmission( + kind: 'read' | 'PUT' | 'DELETE', + type: string, + ): Promise<{ code: ErrorCode; message: string; status: number } | undefined> { + const caller = await readGate!(protocol ?? {}).resolveCaller(); + return kind === 'read' ? metaTypeReadRefusal('GET', type, caller) : metaTypeWriteRefusal(kind, type, caller); + } + function unavailable(): OpenAuthoringToolResult { return refuse(SERVICE_UNAVAILABLE, 'This environment serves no metadata protocol this tool can use.', 503); } @@ -770,6 +804,9 @@ export function createOpenAuthoringRegistry(opts: { // the door's one helper; a row with no type keeps the row's own. const draft = { ...listed, type: canonicalTypeOf(listed.type) ?? listed.type }; try { + // A type this human may not read: neither its body nor a verdict read off it. + const typeRefused = await typeAdmission('read', draft.type); + if (typeRefused) return { verdict: null, verdictWithheld: typeRefused }; // A package-unbound draft is read without a package: the strict // draft read's own address resolution then names it. const read = await p.getMetaItem!({ From a94722fca26aff1da2190da61d866ca167e5e9b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 06:12:19 +0000 Subject: [PATCH 23/25] docs(permissions): name the draft door's walled write verdict on the system-context page The open MCP server's draft save and discard ask walledCatalogWriteVerdict with the envelope's isSystem in openWriter; row 55b now lists that door and names the symbol, and the generated site register carries its read. Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index d221ce0be0b..5da5efe131d 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -210,7 +210,7 @@ One of the largest consumers of the flag; | 54 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `refusePackageRequest` | | 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `requireManageMetadata`, `requireReadCapability` | | 56 | Activation write / authoring refusals do not fire | runtime | Get: activation artifacts writable and authorable without the activation-authoring capability | `refuseUngrantedActivationWrite`, `refuseUngrantedActivationAuthoring` | -| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService` | +| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | | 57 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes, and the elevated self-triggered start, the AI-service-account elevated start and the start-record check at every door that starts a flow by name all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) through any door that starts a flow by name — the trigger route, an action of `type: 'flow'` (REST `/actions` and the MCP `run_action` bridge) and a declared endpoint of `type: 'flow'` — which every other caller, the guest principal included, is refused `403 PERMISSION_DENIED` (the maintainer's rulings, letters B and A) — and starting, through the same doors, a flow whose `requiredPermissions` the caller does not hold (ruling record 6377848497, letter A) — and starting, through the same doors, a flow declared `runAs: 'system'` as an AI service account (an agent acting for itself, with no `onBehalfOf`) where the action's `ai.exposed: true` opt-in is not in hand, which that account is refused `403 PERMISSION_DENIED` (ADR-0151 Non-goals, ruling record 6812617393, letter C; a trigger route and a declared endpoint carry no opt-in, so there it is always refused, and the refusal names the action door that admits it). And starting, through the same doors, a flow on a record key the caller's own scope does not deliver, which every other caller is refused with the action door's `404 RECORD_NOT_FOUND` before the run exists (and `400 VALIDATION_FAILED` for a key that is not one id, or for an elevated start that names no object). The three doors ask one check, so this is one bypass for all of them, and it is the in-process caller's, such as a job: inbound HTTP never carries the flag | `mayReadRunState`, `refuseUngrantedFlowWrite`, `isRunStarterOrRunStateReader`, `refuseUngrantedRunLifecycleWrite`, `flowStartRefusal`, `refuseUnreadableFlowStartRecords` | | 57b | Connector credential door's capability and posture gates pass | runtime | Get: listing, setting and clearing the environment's stored connector credentials (`/automation/connectors/credential-refs`) without `manage_metadata`, and under the `group` / `isolated` postures, where the door refuses every other caller `403 PERMISSION_DENIED` naming the posture, the platform operator included, because the store is environment-level. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more about the value: no answer of this door carries it | `refuseUngrantedConnectorCredentialAccess`, `refuseWalledConnectorCredentialAccess` | | 57c | Connector connection door's capability gate passes | runtime | Get: reading, beginning, completing (the OAuth callback) and revoking an organization's connection of an `oauth2` `authorization_code` connector instance (`/automation/connectors/:name/connection`, `/automation/connectors/oauth/callback`, ADR-0143 D5) without `manage_metadata`. No posture refuses it: a connection belongs to its organization. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more: no answer of this door carries a token, and the callback's `state` is still bound to the user and organization that began the connect | `refuseUngrantedConnectorConnectionAccess` | @@ -675,6 +675,7 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/domains/automation.ts#refuseWalledConnectorCredentialAccess` | 1 | 57b | | `packages/runtime/src/domains/automation.ts#refuseWalledFlowDefinitionWrite` | 1 | 55b | | `packages/runtime/src/domains/i18n.ts#handleI18nRequest` | 1 | 52 | +| `packages/runtime/src/domains/mcp-authoring.ts#openWriter` | 1 | 55b | | `packages/runtime/src/domains/mcp.ts#federationService` | 1 | 55b | | `packages/runtime/src/domains/mcp.ts#handleMcpRequest` | 1 | 53 | | `packages/runtime/src/domains/mcp.ts#membershipReachRefusal` | 1 | 62b | From 7cbb4252a9ad8b12f874f4c6e11fcf61d466f6b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 07:30:44 +0000 Subject: [PATCH 24/25] fix(runtime,metadata-protocol): record the draft door's save among the registry-question producers, and relay a refusal's structured findings The runtime repo tier's producer census (metadata-registry-question-producers) went red: the open MCP draft door's save_metadata_draft is a request-carrying saveMetaItem call no ledger row recorded. REGISTRY_QUESTION_PRODUCERS now records it, by face: face meta-dispatch, always mode draft, so the body-only question. The face set's note says meta-dispatch is stated at a second door. The meta-dispatch face trims a spec-validation refusal's message to a headline because the face declares a structured issues channel. The door's coded refusal now relays the thrown issues beside the message, so the finding that names the key reaches the agent. Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../metadata-protocol/src/registry-question.ts | 6 +++++- packages/runtime/src/domains/mcp-authoring.test.ts | 14 ++++++++++++++ packages/runtime/src/domains/mcp-authoring.ts | 11 ++++++++--- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/metadata-protocol/src/registry-question.ts b/packages/metadata-protocol/src/registry-question.ts index c750414bb22..14dccb38283 100644 --- a/packages/metadata-protocol/src/registry-question.ts +++ b/packages/metadata-protocol/src/registry-question.ts @@ -62,7 +62,10 @@ export type RegistryQuestion = 'against-registry' | 'body-only'; * dispatcher (`meta-dispatch`), and a datasource table's import * (`external-import`: each import saves ONE object and relays the save's * refusal to its caller, #32369 — not a batch). Each is stated at exactly one - * call site. + * call site, except `meta-dispatch`, which the open MCP draft door + * (`packages/runtime/src/domains/mcp-authoring.ts`) also states for its + * structured `issues[]` channel; that door saves drafts only, so it asks the + * body-only question ({@link saveRegistryQuestion}). */ export const AGAINST_REGISTRY_SAVE_FACES: ReadonlySet = new Set(['meta-envelope', 'meta-dispatch', 'external-import']); @@ -104,6 +107,7 @@ export interface RegistryQuestionProducer { export const REGISTRY_QUESTION_PRODUCERS: readonly RegistryQuestionProducer[] = [ { file: 'packages/rest/src/meta-item-write-routes.ts', callee: 'saveMetaItem', calls: 1, question: 'by-face', why: '`PUT /meta/:type/:name`, face `meta-envelope`: against the registry when published.' }, { file: 'packages/runtime/src/domains/meta.ts', callee: 'saveMetaItem', calls: 1, question: 'by-face', why: 'the runtime `/meta` dispatcher, face `meta-dispatch`: against the registry when published.' }, + { file: 'packages/runtime/src/domains/mcp-authoring.ts', callee: 'saveMetaItem', calls: 1, question: 'by-face', why: 'the open MCP draft door\'s `save_metadata_draft`, face `meta-dispatch` and always `mode: \'draft\'` (it has no publish tool): body-only; a person publishes in Studio, through a door that asks its own question.' }, { file: 'packages/runtime/src/domains/automation.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a flow clone writes a flow, never an object.' }, { file: 'packages/runtime/src/domains/packages.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a package publish/unpublish flips each of its apps\' visibility: writes an app, never an object.' }, { file: 'packages/runtime/src/domains/permission-set-clone.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a permission-set clone writes a permission set, never an object.' }, diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index d6c31cfc500..39cd135bb2e 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -872,6 +872,20 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl expect((await call(authoring, 'list_drafts', { package: STUDIO_BASE })).body.drafts).toEqual([]); }); + it('a save the schema refuses answers its structured findings beside the headline, and writes nothing', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + const refused = await call(authoring, 'save_metadata_draft', { + type: 'flow', name: 'crm_opportunity_followup', item: { ...unroutable, bogus_key: 1 }, package: STUDIO_BASE, + }); + expect(refused.isError).toBe(true); + expect(refused.body.error).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + // The message is the face's headline; the finding that names the key is in `issues`. + expect(refused.body.error.message).not.toContain('bogus_key'); + expect(JSON.stringify(refused.body.error.issues)).toContain('bogus_key'); + expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]); + }); + it('an inherited member\'s name as `type`, which the fold keeps as sent, is refused and writes nothing', async () => { const protocol = await realProtocol(); const { authoring } = await authorThroughDomain({ protocol }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 04e3fe15e4f..647fb95516d 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -563,8 +563,8 @@ export function createOpenAuthoringRegistry(opts: { toolName: toolCall.toolName, output: { type: 'text', value: JSON.stringify(body, null, 2) }, }); - const refuse = (code: ErrorCode, message: string, status: number): OpenAuthoringToolResult => ({ - ...answer({ error: { code, message, status } }), + const refuse = (code: ErrorCode, message: string, status: number, issues?: unknown[]): OpenAuthoringToolResult => ({ + ...answer({ error: { code, message, status, ...(issues ? { issues } : {}) } }), isError: true, }); @@ -864,7 +864,12 @@ export function createOpenAuthoringRegistry(opts: { const code = (error as { code?: unknown } | null)?.code; const status = (error as { status?: unknown } | null)?.status; if (typeof code === 'string' && code.length > 0 && typeof status === 'number' && status < 500) { - return refuse(code as ErrorCode, error instanceof Error ? error.message : String(error), status); + // The structured findings travel beside the message: the save + // states the `meta-dispatch` face, whose spec-validation refusal + // trims its message to a headline because the face carries + // `issues[]` (`specValidationFindings`), so they are relayed here. + const issues = (error as { issues?: unknown } | null)?.issues; + return refuse(code as ErrorCode, error instanceof Error ? error.message : String(error), status, Array.isArray(issues) ? issues : undefined); } (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName} failed`, { error: error instanceof Error ? error.message : String(error), From 50b2d84512dc152c4dc384385f475ba46915475c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 12:12:58 +0000 Subject: [PATCH 25/25] fix(runtime,metadata-protocol): the draft list collects each package's publish closure once per pass A draft's publish closure is a function of its package alone, so a caller judging several drafts in one answer hands the judgement one map for the pass and each package's closure is collected on its first draft. Without the map the judgement collects per call, as before. The per-draft strict read stays: the item gate judges the served body, and the judgement reads the row as stored, which the served read is not, and answers each finding whole. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 --- .changeset/34766-mcp-draft-door-write.md | 2 ++ .../src/protocol-authoring-gate.ts | 16 +++++++++- .../protocol.draft-publish-verdict.test.ts | 20 ++++++++++++ packages/metadata-protocol/src/protocol.ts | 1 + .../runtime/src/domains/mcp-authoring.test.ts | 32 ++++++++++++++++++- packages/runtime/src/domains/mcp-authoring.ts | 20 +++++++++--- 6 files changed, 85 insertions(+), 6 deletions(-) diff --git a/.changeset/34766-mcp-draft-door-write.md b/.changeset/34766-mcp-draft-door-write.md index 95f154fb539..6c8b6b023f3 100644 --- a/.changeset/34766-mcp-draft-door-write.md +++ b/.changeset/34766-mcp-draft-door-write.md @@ -10,3 +10,5 @@ Metadata-protocol: none `ObjectStackProtocolImplementation.draftPublishJudgement` is now public. It answers what publishing a stored draft would say, without publishing it: `refusals`, the issues the publish would refuse the draft on, and `advisories`, the findings a publish that passes still returns. Each issue keeps every member the publish's `422 INVALID_METADATA` carries: `rule`, `path`, `where`, `message`, `hint` (the next step) and `severity`. The draft read's `_diagnostics` folds the same verdict but drops the `hint`. A caller that holds no stored row may omit `body`: the method then reads the stored draft at `type`, `name` and `packageId` (`null` for the draft bound to no package), and `member` for a bundled type, and judges the bytes as stored. An address that holds no draft is refused `404 NO_DRAFT`, as the strict draft read refuses it. It runs the same judgement the draft read and the publish gate run; nothing about either changes. + +A caller that judges several drafts in one pass may hand one `packageClosures` map (an empty `Map`) to every call of the pass. The package's other drafts, which a package publish judges each draft against, are then collected once per package instead of once per call. The answers are the same; without the map, each call collects them as before. diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 4d39d226487..638ced616c4 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -777,6 +777,14 @@ export async function draftPublishJudgement( * doors). Absent ⇒ `en`. Selects a language, never a verdict. */ userTextLocales?: readonly (string | undefined)[]; + /** + * [#34766] One map per pass, for a caller that judges several drafts in + * one answer (the open MCP door's draft list): a package's closure is + * collected on its first draft and reused for the rest, since it is a + * function of the package alone, never of the draft judged. Absent ⇒ + * collected on this call, as before. + */ + packageClosures?: Map>; }, ): Promise { const singular = PLURAL_TO_SINGULAR[draft.type] ?? draft.type; @@ -799,7 +807,13 @@ export async function draftPublishJudgement( if (draft.packageId) { const repo = this.getOverlayRepo(); if (typeof repo.listDrafts === 'function') { - pending = await this.collectBatchPendingDeclarations(await repo.listDrafts({ packageId: draft.packageId })); + const packageId = draft.packageId; + let closure = draft.packageClosures?.get(packageId); + if (!closure) { + closure = repo.listDrafts({ packageId }).then((drafts) => this.collectBatchPendingDeclarations(drafts)); + draft.packageClosures?.set(packageId, closure); + } + pending = await closure; } } // The promotion's restored-credential read: the stored draft holds no diff --git a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts index 6de786b556b..be522f9254e 100644 --- a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts +++ b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts @@ -1465,6 +1465,26 @@ describe('[#34766] the public draft publish verdict judges the stored draft', () expect(read).toEqual({ code: 'NO_DRAFT', status: 404 }); }); + it('one closure map for a pass collects each package\'s closure once and changes no answer; without it, each call collects', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const names = ['deal_followup', 'deal_followup_b', 'deal_followup_c']; + for (const name of names) await stageDraft(protocol, 'flow', { ...unroutable, name }); + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + + const alone = []; + for (const name of names) alone.push(await protocol.draftPublishJudgement({ type: 'flow', name, packageId: PKG })); + expect(collect).toHaveBeenCalledTimes(3); + + collect.mockClear(); + const packageClosures = new Map(); + const pass = []; + for (const name of names) pass.push(await protocol.draftPublishJudgement({ type: 'flow', name, packageId: PKG, packageClosures })); + expect(collect).toHaveBeenCalledTimes(1); + expect(pass).toEqual(alone); + expect(alone.every((j) => j.refusals.some((issue) => issue.rule === 'flow-trigger-unroutable'))).toBe(true); + }); + it('a draft the publish passes answers no refusal', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 1503b733741..8b709139b40 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1916,6 +1916,7 @@ export class ObjectStackProtocolImplementation implements draftPublishJudgement(draft: { type: string; name: string; body?: unknown; packageId: string | null; member?: string; userTextLocales?: readonly (string | undefined)[]; + packageClosures?: Map>; }): Promise { return draftPublishJudgement.call(this.draftVerdictHost(), draft); } diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 39cd135bb2e..6fe0dd3bf42 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -20,7 +20,7 @@ * resolution that throws admits nothing. */ -import { describe, it, expect, afterEach } from 'vitest'; +import { describe, it, expect, afterEach, vi } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -872,6 +872,36 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl expect((await call(authoring, 'list_drafts', { package: STUDIO_BASE })).body.drafts).toEqual([]); }); + it('list_drafts collects a package\'s publish closure once for all its drafts, and each verdict equals the draft judged alone', async () => { + const protocol = await realProtocol(); + const { authoring } = await authorThroughDomain({ protocol }); + const routed = structuredClone(unroutable); + (routed.nodes[0]!.config as Record).triggerType = 'record-after-create'; + const names = ['crm_opportunity_followup', 'crm_opportunity_followup_b', 'crm_opportunity_followup_c']; + for (const [i, name] of names.entries()) { + const item = { ...(i === 1 ? routed : unroutable), name }; + expect((await call(authoring, 'save_metadata_draft', { type: 'flow', name, item, package: STUDIO_BASE })).isError).toBe(false); + } + + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + const listed = await call(authoring, 'list_drafts', { package: STUDIO_BASE }); + expect(listed.body.count).toBe(3); + // Each strict draft read collects for the verdict it folds into its own + // `_diagnostics`; the door's judgements share one collection per package. + expect(collect).toHaveBeenCalledTimes(names.length + 1); + + // Each draft judged alone, one closure collection per call: the same verdict. + collect.mockClear(); + for (const entry of listed.body.drafts) { + const alone = await protocol.draftPublishJudgement!({ type: 'flow', name: entry.name, packageId: STUDIO_BASE }); + expect(entry.verdict, entry.name).toEqual({ publishable: alone.refusals.length === 0, refusals: alone.refusals, advisories: alone.advisories }); + } + expect(collect).toHaveBeenCalledTimes(3); + const unroutableOf = (d: any) => d.verdict.refusals.some((issue: any) => issue.rule === 'flow-trigger-unroutable'); + expect(listed.body.drafts.map((d: any) => [d.name, unroutableOf(d)]).sort()) + .toEqual([[names[0], true], [names[1], false], [names[2], true]]); + }); + it('a save the schema refuses answers its structured findings beside the headline, and writes nothing', async () => { const protocol = await realProtocol(); const { authoring } = await authorThroughDomain({ protocol }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 647fb95516d..4797fb94e88 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -85,9 +85,9 @@ * - A gate that cannot evaluate (a books or doc read that throws, a security * service that cannot resolve holdings) refuses: the read answers that * fault, never the item (ADR-0049). - * - `list_drafts` runs no item gate, as `/meta/_drafts` runs none for this - * same caller: a draft row carries the item's identity and its own `label`, - * no body for a gate to judge. + * - `list_drafts` runs no item gate on its rows, as `/meta/_drafts` runs none + * for this same caller: a draft row carries the item's identity and its own + * `label`, no body for a gate to judge (each row's verdict is gated, below). * * ## What the writes do (E3: the save answers with the publish verdict) * @@ -316,6 +316,8 @@ export type OpenAuthoringProtocol = Partial>; }): Promise; }; @@ -670,8 +672,16 @@ export function createOpenAuthoringRegistry(opts: { // none: a row is the item's identity and its own label. Each // verdict is read off the draft's BODY, so it is told only where // the item gate admits the strict draft read for this human. + // Cost per draft: that strict read, which the item gate needs + // (it judges the served body, and the read folds its own verdict + // into `_diagnostics` as every `/meta` draft read does), and the + // judgement, which reads the row as stored (the bytes the publish + // judges; the served copy is not) and answers each finding whole. + // The closure a draft is judged against is its package's alone, + // so one map collects it once per package for the judgements. + const packageClosures = new Map>(); const judged = []; - for (const draft of drafts) judged.push({ ...draft, ...(await gatedDraftVerdict(protocol, draft)) }); + for (const draft of drafts) judged.push({ ...draft, ...(await gatedDraftVerdict(protocol, draft, packageClosures)) }); return answer({ count: judged.length, drafts: judged }); } case 'save_metadata_draft': { @@ -799,6 +809,7 @@ export function createOpenAuthoringRegistry(opts: { async function gatedDraftVerdict( p: OpenAuthoringProtocol, listed: { type: string; name: string; packageId?: string | null; member?: string }, + packageClosures: Map>, ): Promise<{ verdict: ReturnType | null; verdictWithheld?: unknown; verdictError?: unknown }> { // The gate and the judgement read the canonical singular, folded by // the door's one helper; a row with no type keeps the row's own. @@ -835,6 +846,7 @@ export function createOpenAuthoringRegistry(opts: { packageId: draft.packageId ?? null, ...(draft.member !== undefined ? { member: draft.member } : {}), ...(writer ? { userTextLocales: writer.userTextLocales } : {}), + packageClosures, }); return { verdict: verdictOf(judgement) }; } catch (error) {