From 2f540bc3dc48a2cf6be8609dea399c16b8227315 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:22:51 +0000 Subject: [PATCH 01/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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 bb39cca8810c3038501ff5a0acdf6825d3871a27 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 03:48:01 +0000 Subject: [PATCH 08/11] 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 09/11] 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 c1368f8042299c502711ccad72151099280ad64f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:27:39 +0000 Subject: [PATCH 10/11] 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 11/11] 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.