diff --git a/.changeset/37944-in-process-authoring-entry.md b/.changeset/37944-in-process-authoring-entry.md new file mode 100644 index 00000000000..1c41e09a8e1 --- /dev/null +++ b/.changeset/37944-in-process-authoring-entry.md @@ -0,0 +1,17 @@ +--- +'@objectstack/runtime': patch +--- + +feat(runtime): an in-process entry to the light authoring door, for a host's own AI assistant + +Clause-②: no +Metadata-protocol: none + +`createInProcessAuthoringRegistry(kernel, { executionContext, environmentId })` returns the five tools the MCP draft door serves (`list_metadata_items`, `get_metadata_item`, `list_drafts`, `save_metadata_draft`, `delete_metadata_draft`) for an AI assistant that runs in the server process and acts as the signed-in person, such as a host's in-app ask turn. It is built by the MCP door's own assembly, over a request placed the way `dispatchAction` places a host's action call, so the tool definitions, the read gates, the writer and the publish verdicts are the MCP door's, with no second copy. + +- **Admission** is the person's own `manage_metadata`, read from their grants exactly as the MCP door reads the human half. There is no OAuth scope to hold: the host's authenticated session takes its place. A person without the capability is listed no tool and every call is refused `403 PERMISSION_DENIED`, the MCP door's shape. An envelope with no user, a system envelope, or a grant read that fails admits nothing. +- **Saves state `surface: 'copilot'`** (an AI assistant's tool writing on a person's behalf), never `mcp`, and no OAuth `client`, so Studio's draft marks and per-key provenance tell an in-app save from an MCP one. +- **No publish tool**: drafts stay for a person to review and publish in Studio. +- **The MCP door is unchanged**: same tools, same admission, same `surface: 'mcp'` saves with the token's client. + +The host keeps the same jobs `dispatchAction` leaves it: authenticating the person, the authentication-policy gate and the environment-membership gate. A `kernel-resolver` that refuses to place the request rejects the call. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index bd92159c370..47686def9fe 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -222,6 +222,7 @@ One of the largest consumers of the flag; | 60 | **Automation flow data nodes re-add the `owner_id` stamp** (the one place row 2's gap is compensated inline) | service-automation | Get: a flow-authored INSERT under system elevation still lands owned, when the run resolved a user. Fill-only — flow-authored values win | `stampSystemInsertOwner`, called from `packages/services/service-automation/src/builtin/crud-nodes.ts#registerCrudNodes` | | 61 | Inbox caller refusal names `isSystem` as what was carried | service-messaging | Get: nothing — the refusal still fires. The flag only shapes the diagnostic, because privilege is not an authorization subject | `resolveInboxRecipient` | | 61b | **The principal-session mint refuses a system context** | plugin-auth | Get: nothing — `mintPrincipalSession` answers `PERMISSION_DENIED` / `403` before anything is minted. A principal session acts as the requesting user and never as the system, so a render or any other in-process act that needs a session must carry the user's own context | `refuseUpFront` | +| 61c | **The in-process authoring entry admits a system context nothing** | runtime | Get: nothing — `createInProcessAuthoringRegistry` lists no tool and refuses every call `403 PERMISSION_DENIED`, before any grant is read or the request is placed. The entry acts as a signed-in person, and a system context is no person; carried into the draft writer, its flag would also pass the walled environment-metadata refusal | `inProcessAuthoringRegistryRequest` | | 62 | **`organization_id` is not auto-stamped on INSERT** — the organization-axis twin of the `owner_id` gap above | organizations | Get: an elevated write may name another organization deliberately, which is what the per-organization seed replay, the orphan-row claim, imports and migrations all rely on. Lose: the fill-only stamp, so an elevated insert that names no organization lands `organization_id = NULL` and the wall hides it. ⛔ Neither path rewrites a supplied `organization_id`: the non-elevated path fills only an absent one, and a supplied value meets the Layer 0 write wall, which refuses a forged one `403 PERMISSION_DENIED` exactly as it refuses an update re-pointing a row. Elevation skips the stamp and the wall alike, which is why it is the seam the legitimate cross-organization writers use | `packages/plugins/organizations/src/organizations-plugin.ts#start` | | 62b | **MCP `list_actions` asks no membership-grade mark of a system caller** — an organization action whose endpoint (`/organization/...`) the caller's membership grade does not reach is listed without `unavailable` | runtime | Get: nothing a run would not give. The mark is a courtesy reading of the caller's own `positions` (ruling record 6812625052, letter E: list and mark, do not hide), and a system context carries no person's grades, so it is left unmarked, as a delegated agent's envelope is. Every other caller whose positions name none of the grades the `MEMBERSHIP_REACH` rows for that endpoint list sees the row marked `PERMISSION_DENIED`. Lose: nothing — neither run door reads the mark, and the organization endpoint still judges the call | `membershipReachRefusal` | @@ -702,6 +703,7 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/domains/permission-set-clone.ts#handlePermissionSetCloneWrite` | 2 | 50 | | `packages/runtime/src/domains/security.ts#handleSecurityRequest` | 1 | 52 | | `packages/runtime/src/flow-start-admission.ts#flowStartRefusal` | 1 | 57 | +| `packages/runtime/src/in-process-authoring.ts#inProcessAuthoringRegistryRequest` | 1 | 61c | | `packages/runtime/src/sandbox/body-doors.ts#callerScopeOf` | 1 | 65b | | `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 | | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 | diff --git a/packages/runtime/README.md b/packages/runtime/README.md index 4303b547332..94b960644bb 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -261,6 +261,28 @@ interface PluginContext { } ``` +### In-process authoring tools + +A host's own AI assistant that runs in the server process (an in-app ask turn) +calls the MCP draft door's five tools as the signed-in person, with no OAuth +grant, through `createInProcessAuthoringRegistry`. The tools, read gates and +publish verdicts are the MCP door's own; admission is the person's own +`manage_metadata`; saves are recorded as `surface: 'copilot'`; no tool +publishes, so a person reviews and publishes the drafts in Studio. + +```typescript +import { createInProcessAuthoringRegistry } from '@objectstack/runtime'; + +// Once per turn, as the person your door authenticated. +const authoring = await createInProcessAuthoringRegistry(kernel, { executionContext, environmentId }); +const tools = authoring.getAll(); // [] when the person lacks manage_metadata +const result = await authoring.execute({ toolCallId, toolName: 'list_drafts', input: {} }); +``` + +`kernel` and the placement are `dispatchAction`'s; as there, authenticating +the person, the authentication-policy gate and environment membership stay the +host's job. + ## Examples Complete, CI-exercised examples live in the repo's [`examples/`](../../examples) diff --git a/packages/runtime/src/action-dispatch.ts b/packages/runtime/src/action-dispatch.ts index 26dd2b2f3f5..652314725ff 100644 --- a/packages/runtime/src/action-dispatch.ts +++ b/packages/runtime/src/action-dispatch.ts @@ -1318,6 +1318,21 @@ export async function dispatchActionRequest( /** One dispatcher per kernel: its deps are the REST door's. */ const hostDispatchers = new WeakMap(); +/** + * The one dispatcher a host's in-process doors run on for `kernel`, from the + * map {@link dispatchAction} and {@link dispatchActionResume} fill: the + * in-process authoring entry (`./in-process-authoring.ts`) runs on the + * same dispatcher, and so on the same placement, as a host's action call. + */ +export function hostDispatcherFor(kernel: ObjectKernel): HttpDispatcher { + let dispatcher = hostDispatchers.get(kernel); + if (!dispatcher) { + dispatcher = new HttpDispatcher(kernel); + hostDispatchers.set(kernel, dispatcher); + } + return dispatcher; +} + /** * Run one business action from a host's own door — the REST `/actions` * door's admission and dispatch, as a function. A host that runs actions diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index fff4879911f..add1ea37bb0 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -18,6 +18,11 @@ * * Fail closed: an envelope with no user is injected nothing, and a grant * resolution that throws admits nothing. + * + * [#37944] The last group pins the in-process entry + * (`createInProcessAuthoringRegistry`) against this door: the same five tool + * definitions, the same refusal shape for a person without `manage_metadata`, + * the same writer, and saves stamped `copilot` where this door stamps `mcp`. */ import { describe, it, expect, afterEach, vi } from 'vitest'; @@ -53,6 +58,7 @@ import { type OpenAuthoringProtocol, type OpenAuthoringReadGateSources, } from './mcp-authoring.js'; +import { createInProcessAuthoringRegistry } from '../in-process-authoring.js'; import { resolveExecutionContext } from '../security/resolve-execution-context.js'; import { bindCatalogFromTables } from '../security/security-catalog.testkit.js'; @@ -1404,3 +1410,162 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]); }); }); + +// --------------------------------------------------------------------------- +// [#37944] The in-process entry: the same five tools, as the signed-in person +// --------------------------------------------------------------------------- + +/** + * One host kernel serving the door's services, as `dispatchAction`'s pins + * build one: the recording protocol, the human's grant engine, the security + * service, and `tenancy` / `kernel-resolver` when given. `scopes` records the + * environment each scoped lookup was asked under. + */ +function inProcessHost(opts: { + systemPermissions?: string[]; protocol?: OpenAuthoringProtocol; tenancy?: { posture: string }; + qlThrows?: boolean; resolveKernel?: (ctx: any) => unknown; +} = {}) { + const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN); + const fake = fakeProtocol(); + const protocol = opts.protocol ?? fake.protocol; + const security = { resolvePermissionSetNames: async (ctx: any) => (Array.isArray(ctx?.permissions) ? ctx.permissions : []) }; + const warnings: unknown[][] = []; + const services: Record = { + protocol, + security, + ...(opts.tenancy ? { tenancy: opts.tenancy } : {}), + ...(opts.resolveKernel ? { 'kernel-resolver': { resolveKernel: opts.resolveKernel } } : {}), + logger: { warn: (...args: unknown[]) => { warnings.push(args); }, debug: () => {}, info: () => {}, error: () => {} }, + }; + const resolve = (name: string): any => { + if (name === 'objectql') { + if (opts.qlThrows) throw new Error('engine lookup failed'); + return ql; + } + return services[name] ?? null; + }; + const scopes: string[] = []; + const kernel: any = { + getService: resolve, + getServiceAsync: async (name: string, scopeId?: string) => { + if (scopeId !== undefined) scopes.push(scopeId); + return resolve(name); + }, + context: { getService: resolve }, + }; + return { kernel, grantReads: reads, protocolCalls: fake.calls, scopes, warnings }; +} + +/** A signed-in person's session envelope, as a host's session door resolves it: no OAuth grant. */ +const SESSION_EC = { userId: 'u1', isSystem: false, roles: [], permissions: [], systemPermissions: [] } as any; + +async function inProcessCall(authoring: { execute: (call: any) => Promise }, toolName: string, input: unknown) { + const result = await authoring.execute({ toolCallId: `t-${toolName}`, toolName, input }); + return { isError: result.isError === true, body: JSON.parse(result.output.value) }; +} + +describe('[#37944] createInProcessAuthoringRegistry serves the MCP door\'s five tools in process, as the signed-in person', () => { + it('is the runtime package\'s public entry', async () => { + const runtime = await import('../index.js'); + expect(runtime.createInProcessAuthoringRegistry).toBe(createInProcessAuthoringRegistry); + }); + + it('a person holding manage_metadata is listed the same five tool definitions the MCP door lists, with no OAuth grant', async () => { + const host = inProcessHost(); + const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC }); + expect(authoring.admitted).toBe(true); + // The admission read the person's own grants: the session envelope carries no capability. + expect(host.grantReads.length).toBeGreaterThan(0); + + const { authoring: mcpDoor } = await authorThroughDomain(); + expect(authoring.getAll()).toEqual(mcpDoor.registry.getAll()); + expect(authoring.getAll().map((tool) => tool.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]); + // No publish tool rides in. + expect(authoring.getAll().map((tool) => tool.name).some((name) => /publish/.test(name))).toBe(false); + + const listed = await inProcessCall(authoring, 'list_metadata_items', { type: 'flow' }); + expect(listed.isError).toBe(false); + expect(listed.body.items.map((item: any) => item.name)).toEqual(['lead_intake', 'close_won']); + }); + + it('a person without manage_metadata is listed no tool and a call is refused 403, the MCP door\'s refusal shape, before any read', async () => { + const host = inProcessHost({ systemPermissions: NOT_AN_AUTHOR }); + const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC }); + expect(authoring.admitted).toBe(false); + expect(authoring.getAll()).toEqual([]); + + const mcpEc = await oauthEnvelope(['metadata:write'], NOT_AN_AUTHOR); + const mcpRefusal = await call((await serve(mcpEc, { systemPermissions: NOT_AN_AUTHOR })).authoring!, 'save_metadata_draft', {}); + for (const tool of [...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]) { + const refused = await inProcessCall(authoring, tool, { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect(refused.isError, tool).toBe(true); + expect(refused.body.error, tool).toMatchObject({ code: mcpRefusal.body.error.code, status: mcpRefusal.body.error.status }); + expect(refused.body.error, tool).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + // No OAuth half to name: the sentence names only the capability. + expect(refused.body.error.message, tool).not.toContain('metadata:write'); + } + expect(host.protocolCalls).toEqual([]); + }); + + it('a draft save stamps surface copilot, not mcp, with no client, as the person, and answers the publish verdict', async () => { + const host = inProcessHost(); + const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC }); + const saved = await inProcessCall(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm', ifMatch: 'v7' }); + + expect(saved.isError).toBe(false); + const save = host.protocolCalls.find((c: any) => c[0] === 'saveMetaItem') as any[]; + expect(save[1]).toMatchObject({ + type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, packageId: 'com.acme.crm', + mode: 'draft', surface: 'copilot', writeFace: 'meta-dispatch', parentVersion: 'v7', actor: 'u1', + }); + expect(save[1]).not.toHaveProperty('client'); + expect(saved.body).toMatchObject({ + saved: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm', state: 'draft', version: 'v8' }, + verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE], advisories: [] }, + review: { changes: '/studio/com.acme.crm/data?changes=review', item: '/studio/com.acme.crm/metadata/flow/lead_intake?review=1' }, + }); + + // The MCP door's save, unchanged: `mcp` and the token's client. + const { authoring: mcpDoor, served } = await authorThroughDomain(); + await call(mcpDoor, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect((served.protocolCalls.find((c: any) => c[0] === 'saveMetaItem') as any[])[1]).toMatchObject({ surface: 'mcp', client: { id: 'c1' } }); + }); + + it('the writer is the MCP door\'s: under a walled tenancy posture the save is refused 403 before anything is written', async () => { + const host = inProcessHost({ tenancy: { posture: 'isolated' } }); + const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: { ...SESSION_EC, posture: 'TENANT_ADMIN' } }); + const refused = await inProcessCall(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(host.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + + it('fails closed: no person, a system envelope, or a grant read that throws admits nothing', async () => { + for (const executionContext of [{ isSystem: false } as any, { ...SESSION_EC, isSystem: true }]) { + const host = inProcessHost(); + const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext }); + expect(authoring.admitted).toBe(false); + expect(authoring.getAll()).toEqual([]); + expect((await inProcessCall(authoring, 'list_drafts', {})).body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + // No grant is read for it. + expect(host.grantReads).toEqual([]); + expect(host.protocolCalls).toEqual([]); + } + const throwing = inProcessHost({ qlThrows: true }); + const authoring = await createInProcessAuthoringRegistry(throwing.kernel, { executionContext: SESSION_EC }); + expect(authoring.admitted).toBe(false); + expect(authoring.getAll()).toEqual([]); + }); + + it('is placed as dispatchAction places a host call: the named environment scopes the lookups, and a resolver that refuses rejects', async () => { + const host = inProcessHost(); + const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC, environmentId: 'env_named' }); + await inProcessCall(authoring, 'list_drafts', {}); + expect(host.scopes.length).toBeGreaterThan(0); + expect(new Set(host.scopes)).toEqual(new Set(['env_named'])); + + const refusing = inProcessHost({ resolveKernel: async () => { throw Object.assign(new Error('not a member of env_named'), { status: 403 }); } }); + await expect(createInProcessAuthoringRegistry(refusing.kernel, { executionContext: SESSION_EC, environmentId: 'env_named' })) + .rejects.toThrow('not a member of env_named'); + expect(refusing.grantReads).toEqual([]); + }); +}); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 00c58d72bda..5fcfc5885f5 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -145,6 +145,16 @@ * 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. + * + * ## The in-process entry + * + * [#37944] A host's own AI assistant that runs in the server process (an + * in-app ask turn) calls the same five tools through + * `createInProcessAuthoringRegistry` (`../in-process-authoring.ts`, exported by + * the package). It is built by this module's {@link buildOpenAuthoringRegistry} + * over a request the dispatcher placed, so the read gates, the writer and the + * verdicts are these; there is no token, so its admission is the human half + * alone, and its saves state `surface: 'copilot'`. */ import { createRequire } from 'node:module'; @@ -168,7 +178,7 @@ import { import { MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai'; import { SEMVER_2_0_0_VERSION_PATTERN } from '@objectstack/spec/kernel'; import { canonicalMetaUrlType } from '@objectstack/spec/shared'; -import type { ErrorCode, ListDraftsResponse, MetadataProtocol, RuntimeAuthoringIssue } from '@objectstack/spec/api'; +import type { ErrorCode, ListDraftsResponse, MetadataAuthoringSurface, MetadataProtocol, RuntimeAuthoringIssue } from '@objectstack/spec/api'; import type { AIToolDefinition } from '@objectstack/spec/contracts'; import type { HttpProtocolContext } from '../http-dispatcher.js'; import type { DomainHandlerDeps } from '../domain-handler-registry.js'; @@ -444,9 +454,12 @@ export type OpenAuthoringReadGateSources = (protocol: OpenAuthoringProtocol) => * 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. + * `in_process` is the context `createInProcessAuthoringRegistry` stamps on its + * own calls (`../in-process-authoring.ts`); the registry reads only + * `principal.userId`. */ export interface OpenAuthoringCallContext { - door: 'mcp'; + door: 'mcp' | 'in_process'; principal: { userId: string }; environmentId?: string; } @@ -500,10 +513,55 @@ 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 reader = await resolveHumanReader(deps, context, userId, organizationId); + const { registry } = await buildOpenAuthoringRegistry(deps, context, { userId, organizationId, clientId, surface: 'mcp' }); + return { + registry, + principal: { + userId, + ...(organizationId ? { organizationId } : {}), + ...(clientId ? { clientId } : {}), + scopes: [...grantedScopes], + }, + ...(context.environmentId !== undefined ? { environmentId: context.environmentId } : {}), + }; +} + +/** + * The authoring surface a registry's draft saves state + * (`MetadataAuthoringSurfaceSchema`): `mcp` for the MCP door, `copilot` for + * the in-process entry, the published value for an AI assistant's tool + * writing on a person's behalf, which only an in-process caller may state. + */ +export type OpenAuthoringSurface = Extract; + +/** + * The one assembly both entries call, over a request already placed in its + * environment: the human admitted by {@link resolveHumanReader}, then the + * registry over that verdict, with the read gates and the writer built for + * that human. The MCP door ({@link resolveOpenAuthoringInjection}) passes its + * `/mcp` request and `surface: 'mcp'`; the in-process entry + * (`../in-process-authoring.ts`) passes the request the dispatcher's own + * placement step placed for it and `surface: 'copilot'`. So both read the same + * services, the same way, and one implementation answers both. + */ +export async function buildOpenAuthoringRegistry( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + principal: { + userId: string; + organizationId: string | undefined; + /** The OAuth client an MCP token was issued to; an in-process caller has none. */ + clientId: string | undefined; + surface: OpenAuthoringSurface; + }, +): Promise<{ registry: OpenAuthoringRegistry; admitted: boolean }> { + const { userId, organizationId, clientId, surface } = principal; + const reader = await resolveHumanReader(deps, context, userId, organizationId, surface); + const admitted = reader !== undefined; return { + admitted, registry: createOpenAuthoringRegistry({ - admitted: reader !== undefined, + admitted, userId, getProtocol: async () => (await deps.resolveService(context, 'protocol', context.environmentId)) as OpenAuthoringProtocol | undefined, getAutomation: async () => { @@ -515,19 +573,14 @@ export async function resolveOpenAuthoringInjection( }, ...(reader ? { readGate: openReadGateSources(deps, context, reader), writer: openWriter(deps, context, clientId, reader) } : {}), logger: deps.logger, + surface, }), - principal: { - userId, - ...(organizationId ? { organizationId } : {}), - ...(clientId ? { clientId } : {}), - scopes: [...grantedScopes], - }, - ...(context.environmentId !== undefined ? { environmentId: context.environmentId } : {}), }; } /** - * The human the token was issued to, as the `/meta` read gates read a caller, + * The human the token was issued to (in process: the signed-in person), 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 @@ -544,6 +597,7 @@ async function resolveHumanReader( context: HttpProtocolContext, userId: string, organizationId: string | undefined, + surface: OpenAuthoringSurface, ): Promise { try { const ql = (await deps.getObjectQL(context, context.environmentId)) @@ -568,7 +622,9 @@ async function resolveHumanReader( // 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.', + surface === 'mcp' + ? '[MCP] The authoring tools are not served on this request: the user\'s metadata permission could not be read.' + : '[authoring] The in-process authoring tools are not served: the user\'s metadata permission could not be read.', { error: error instanceof Error ? error.message : String(error) }, ); return undefined; @@ -692,8 +748,16 @@ export function createOpenAuthoringRegistry(opts: { /** The write tools' inputs; without them every write is refused. */ writer?: OpenAuthoringWriter; logger?: { warn?: (...args: unknown[]) => void }; + /** + * The surface every draft save states: `mcp` (the default, the MCP door) + * or `copilot` (the in-process entry). It also picks the sentence a caller + * the verdict did not admit is refused with, and the warnings' prefix. + */ + surface?: OpenAuthoringSurface; }): OpenAuthoringRegistry { const { admitted, userId, getProtocol, getAutomation, readGate, writer } = opts; + const surface: OpenAuthoringSurface = opts.surface ?? 'mcp'; + const logPrefix = surface === 'mcp' ? '[MCP]' : '[authoring]'; return { getAll: () => (admitted ? [...READ_TOOLS, ...WRITE_TOOLS] : []), async execute(toolCall, context) { @@ -712,7 +776,9 @@ export function createOpenAuthoringRegistry(opts: { 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.', + surface === 'mcp' + ? 'The authoring tools need the `metadata:write` scope on your connection and the `manage_metadata` capability on your own account.' + : 'The authoring tools need the `manage_metadata` capability on your own account.', 403, ); } @@ -885,7 +951,7 @@ export function createOpenAuthoringRegistry(opts: { item, packageId: pkg, mode: 'draft', - surface: 'mcp', + surface, ...(writer.clientId ? { client: { id: writer.clientId } } : {}), // The face of a door with no `force` and a structured issues channel. writeFace: 'meta-dispatch', @@ -1027,7 +1093,7 @@ export function createOpenAuthoringRegistry(opts: { if (typeof code === 'string' && code.length > 0 && typeof status === 'number' && status < 500) { return { code, message: error instanceof Error ? error.message : String(error), status }; } - (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName}: the publish verdict could not be read`, { + (opts.logger ?? console).warn?.(`${logPrefix} ${toolCall.toolName}: the publish verdict could not be read`, { error: error instanceof Error ? error.message : String(error), }); return { code: INTERNAL_ERROR, message: 'The publish verdict could not be read.', status: 500 }; @@ -1049,7 +1115,7 @@ export function createOpenAuthoringRegistry(opts: { const issues = (error as { issues?: unknown } | null)?.issues; return refuse(code as ErrorCode, error instanceof Error ? error.message : String(error), status, Array.isArray(issues) ? issues : undefined); } - (opts.logger ?? console).warn?.(`[MCP] ${toolCall.toolName} failed`, { + (opts.logger ?? console).warn?.(`${logPrefix} ${toolCall.toolName} failed`, { error: error instanceof Error ? error.message : String(error), }); return refuse( diff --git a/packages/runtime/src/http-dispatcher.ts b/packages/runtime/src/http-dispatcher.ts index cf8e67dc21b..3672eca887c 100644 --- a/packages/runtime/src/http-dispatcher.ts +++ b/packages/runtime/src/http-dispatcher.ts @@ -65,6 +65,7 @@ import { createAiDomain, handleAIRequest } from './domains/ai.js'; import { createActionsDomain, handleActionsRequest } from './domains/actions.js'; import { dispatchActionRequest, type ActionDispatchAnswer, type ActionDispatchRequest, type ActionResumeRequest } from './action-dispatch.js'; import { createMcpDomains, handleMcpRequest, handleMcpSkillRequest, buildMcpBridge, resumeActionRunRequest } from './domains/mcp.js'; +import { inProcessAuthoringRegistryRequest, type InProcessAuthoringRegistry, type InProcessAuthoringRequest } from './in-process-authoring.js'; import { createMetaDomain, handleMetadataRequest } from './domains/meta.js'; import { createDataDomain, handleDataRequest } from './domains/data.js'; @@ -2958,6 +2959,16 @@ export class HttpDispatcher { return resumeActionRunRequest(this.domainDeps, request, (context, hints) => this.placeHostActionRequest(context, hints)); } + /** + * [#37944] A host's in-process authoring entry over this dispatcher's deps — + * the MCP draft door's five tools as the signed-in person + * (`./in-process-authoring.ts#createInProcessAuthoringRegistry`, + * the published entry), placed as {@link dispatchHostAction} places its call. + */ + async hostAuthoringRegistry(request: InProcessAuthoringRequest): Promise { + return inProcessAuthoringRegistryRequest(this.domainDeps, request, (context, hints) => this.placeHostActionRequest(context, hints)); + } + /** * The host action door's resolver hints, written from the call's values * rather than parsed from a path: `routePath` is the REST route of the diff --git a/packages/runtime/src/in-process-authoring.ts b/packages/runtime/src/in-process-authoring.ts new file mode 100644 index 00000000000..15218911c02 --- /dev/null +++ b/packages/runtime/src/in-process-authoring.ts @@ -0,0 +1,166 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The in-process entry to the light authoring door: the five tools the MCP + * draft door serves (`./domains/mcp-authoring.ts`), with the same contract, read + * gates and verdicts, for an AI assistant that runs in the server process and + * acts as the signed-in person (a host's in-app ask turn). It is built by the + * MCP door's own assembly (`buildOpenAuthoringRegistry`) over a request placed + * by the dispatcher's own placement step, as `dispatchAction` places a + * host's action call, so it reads the same services the same way; only the + * admission's first half and the saves' `surface` differ. + * + * ## Who is admitted + * + * The MCP door's admission is an intersection of the token's consent + * (`metadata:write`) and the human's own `manage_metadata`. Here there is no + * token: the person's signed-in session, which the host authenticated, takes + * the consent's place. What remains is the second half, decided exactly as the + * MCP door decides it (`resolveHumanReader`): the person's own grants, resolved + * in their session's organization (`tenantId`), judged by + * `metaWriteCapabilityVerdict`. A person without the capability is listed no + * tool, and a call is refused `403 PERMISSION_DENIED`, the MCP door's refusal + * shape. Fail closed: an envelope with no user, a system envelope (no person, + * and one the walled refusal would wave through), or a grant read that fails + * admits nothing. + * + * ## What a save states + * + * `surface: 'copilot'`, the published value for an AI assistant's tool + * writing on a person's behalf, which only an in-process caller may state + * (`MetadataAuthoringSurfaceSchema`; every HTTP door refuses it). So Studio's + * draft marks and per-key provenance tell an in-app save from an MCP one + * (`mcp`) and from the person's own edit (`studio`). No `client` is stated: + * there is no OAuth client. + * + * No tool publishes and none takes a `force`: a person reviews and publishes + * the drafts in Studio, as with the MCP door. + */ + +import type { ObjectKernel } from '@objectstack/core'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { AIToolDefinition } from '@objectstack/spec/contracts'; +import { hostDispatcherFor, type PlaceRequestInEnvironment } from './action-dispatch.js'; +import type { HttpProtocolContext } from './http-dispatcher.js'; +import type { DomainHandlerDeps } from './domain-handler-registry.js'; +import { + buildOpenAuthoringRegistry, + createOpenAuthoringRegistry, + type OpenAuthoringRegistry, + type OpenAuthoringToolCall, + type OpenAuthoringToolResult, +} from './domains/mcp-authoring.js'; + +/** What a host hands {@link createInProcessAuthoringRegistry} for one person's turn. */ +export interface InProcessAuthoringRequest { + /** + * The signed-in person, as the host authenticated them: `userId` is the + * person the tools act as, `tenantId` the organization their capability is + * read in, `posture` the rung the walled refusal reads, and the user-text + * locales the verdicts' sentences are composed in. It is used as given, + * as `dispatchAction` uses its envelope. Never a system envelope: + * one is admitted nothing. + */ + executionContext: ExecutionContext; + /** + * The environment the person is working in. On a host with a + * `kernel-resolver` it reaches the resolver as the scoped-URL hint and + * the resolver places the request; on a host without one it is the + * request's environment, or the default environment when omitted. As + * `dispatchAction`'s `environmentId`. + */ + environmentId?: string; +} + +/** The five tools, bound to one person for one turn. */ +export interface InProcessAuthoringRegistry { + /** Whether the person holds `manage_metadata`: the one verdict both methods read. */ + readonly admitted: boolean; + /** The five tools' definitions when admitted; none otherwise. */ + getAll(): AIToolDefinition[]; + /** + * One tool call, answered as the MCP door answers it: a `tool-result` + * whose `output.value` is the JSON reply, with `isError` on a refusal + * (`{ error: { code, message, status } }`). + */ + execute(toolCall: OpenAuthoringToolCall): Promise; +} + +/** + * The light authoring door's five tools (`list_metadata_items`, + * `get_metadata_item`, `list_drafts`, `save_metadata_draft`, + * `delete_metadata_draft`), in process, as the signed-in person. Build one per + * turn: the admission is read once, here, and both `getAll` and `execute` read + * that verdict. + * + * `kernel` is `dispatchAction`'s: the kernel the host's HTTP door is + * served from (on a multi-kernel host, the one that registers the + * `kernel-resolver` service). A resolver that refuses to place the request + * rejects this call with its error. + * + * What stays the host's job before it calls, as for `dispatchAction`: + * authenticating the person and resolving their envelope for the environment + * (`executionContext` is used as given), the ADR-0069 authentication-policy + * gate and the environment-membership gate. + * + * @example + * const authoring = await createInProcessAuthoringRegistry(kernel, { executionContext, environmentId }); + * tools.push(...authoring.getAll()); + * // later, for a call the model made: + * const result = await authoring.execute({ toolCallId, toolName, input }); + */ +export async function createInProcessAuthoringRegistry( + kernel: ObjectKernel, + request: InProcessAuthoringRequest, +): Promise { + return hostDispatcherFor(kernel).hostAuthoringRegistry(request); +} + +/** + * The entry's body over one dispatcher's deps. `place` is the dispatcher's own + * placement step (`placeHostActionRequest`), the one `dispatchAction`'s + * call is placed by. + */ +export async function inProcessAuthoringRegistryRequest( + deps: DomainHandlerDeps, + request: InProcessAuthoringRequest, + place: PlaceRequestInEnvironment, +): Promise { + const ec: any = request?.executionContext; + const userId = typeof ec?.userId === 'string' && ec.userId.length > 0 ? (ec.userId as string) : undefined; + // Fail closed: no person, or a system envelope, is admitted nothing, and + // no grant is read and nothing is placed for it. + if (!userId || ec?.isSystem === true) { + return bound(createOpenAuthoringRegistry({ admitted: false, userId: '', getProtocol: async () => undefined, surface: 'copilot' }), false, ''); + } + const organizationId = typeof ec?.tenantId === 'string' && ec.tenantId.length > 0 ? (ec.tenantId as string) : undefined; + + // PLACEMENT, as `dispatchActionRequest` places a host's action call: on a + // host with a `kernel-resolver` the environment is the RESOLVER's to + // write, and the named one reaches it as the scoped-URL hint. + const namedEnvironment = typeof request.environmentId === 'string' && request.environmentId !== '' ? request.environmentId : undefined; + const context: HttpProtocolContext = { request: { headers: {} }, executionContext: ec }; + await place(context, { routePath: '/meta', ...(namedEnvironment ? { environmentId: namedEnvironment } : {}) }); + if (namedEnvironment && !deps.isMultiTenantHost()) context.environmentId = namedEnvironment; + if (!context.environmentId) { + const def = deps.getDefaultEnvironmentId(); + if (def) context.environmentId = def; + } + + const { registry, admitted } = await buildOpenAuthoringRegistry(deps, context, { + userId, + organizationId, + clientId: undefined, + surface: 'copilot', + }); + return bound(registry, admitted, userId); +} + +/** The registry bound to the person it was built for: every call is stamped as theirs. */ +function bound(registry: OpenAuthoringRegistry, admitted: boolean, userId: string): InProcessAuthoringRegistry { + return { + admitted, + getAll: () => registry.getAll(), + execute: (toolCall) => registry.execute(toolCall, { door: 'in_process', principal: { userId } }), + }; +} diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 8e02c88c2a6..482c5f515b6 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -267,6 +267,14 @@ export type { ActionDispatchRequest, ActionDispatchAnswer, ActionDispatchPosture // `resume_run` gates. export { dispatchActionResume } from './action-dispatch.js'; export type { ActionResumeRequest } from './action-dispatch.js'; +// [#37944] The light authoring door's five tools (the MCP draft door's +// list/get/list-drafts reads and draft save/discard) for a host's in-process +// AI assistant, as the signed-in person: one implementation with the MCP +// door, admitted on the person's own `manage_metadata`, saves stamped +// `surface: 'copilot'`, no publish tool. +export { createInProcessAuthoringRegistry } from './in-process-authoring.js'; +export type { InProcessAuthoringRequest, InProcessAuthoringRegistry } from './in-process-authoring.js'; +export type { OpenAuthoringToolCall, OpenAuthoringToolResult } from './domains/mcp-authoring.js'; // ADR-0076 D11 step ③ — thin domain-handler registry seam; owning service // packages register normalized handlers via HttpDispatcher.registerDomainHandler. export { DomainHandlerRegistry } from './domain-handler-registry.js';