Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/37944-in-process-authoring-entry.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |

Expand Down Expand Up @@ -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 |
Expand Down
22 changes: 22 additions & 0 deletions packages/runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions packages/runtime/src/action-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1318,6 +1318,21 @@ export async function dispatchActionRequest(
/** One dispatcher per kernel: its deps are the REST door's. */
const hostDispatchers = new WeakMap<object, HttpDispatcher>();

/**
* 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
Expand Down
165 changes: 165 additions & 0 deletions packages/runtime/src/domains/mcp-authoring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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';

Expand Down Expand Up @@ -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<string, unknown> = {
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<any> }, 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([]);
});
});
Loading
Loading