Skip to content

Commit 66919b6

Browse files
fix(runtime,mcp): list_actions marks an organization action the caller's membership role does not reach (#33194)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoSLDKWQ8v7cxY9uDGijfncD)_ Fixes #32163 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:普通成员的 AI 通过 MCP `list_actions` 看到的 15 个组织类身份动作(邀请成员、移除成员、改组织、管团队等)仍然列出,但每行带上 `unavailable` 标记,写明需要哪种组织角色(如"需要组织 owner、admin 或 delegated admin")。owner、admin(邀请类还有 delegated admin)看到的列表不变。 - 为什么改:这些动作成员一执行就被组织端点 403 拒绝,AI 却以为能用,白白规划、浪费轮次。按裁决 E「列出并标记,不隐藏」处理。 - 风险与回滚:只多一个标记;谁能执行完全不变(两个执行门都不读这个标记,实测 main 与本分支执行结果逐一相同)。删 SSO 提供方、删 OAuth 应用、建组织这 3 个按记录所有者或部署形态判定的动作不标记。回滚即还原本 PR。 - 先看:`packages/runtime/src/domains/mcp.ts` 的 `membershipReachRefusal` 与 `listActions` 里 `refusal` 那一行的顺序;`packages/runtime/src/platform-admin-action-gate.test.ts` 末尾新 describe。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/platform-admin-action-gate.test.ts`,预期 16 passed。 - 需要你做的:无,席位落地。 ## What changes - **The mark.** `listActions` (`packages/runtime/src/domains/mcp.ts`) asks a new module function, `membershipReachRefusal(action, objectName, ec)`, after the two existing refusals: `confirmation ?? apiForwardCredentialRefusal(...) ?? membershipReachRefusal(...)`. That is the order `run_action` meets them: the confirmation gate in the admission sequence, the forward's credential table before the target is called, and the organization endpoint last. - **Where the reach comes from.** The function reads the action's declared `target`. When it is an organization endpoint under the auth base path (`/api/v1/auth/organization/...`), the grades that reach it are the union of the grades of every `MEMBERSHIP_REACH` row naming that endpoint (`@objectstack/spec/identity`, the table plugin-auth's `membership-reach-table.test.ts` pins equal to the vendor doors). `/organization/update-member-role` is two rows, so its reach is their union. No local list, and no new stored key: the reach is derived from what survives on the served action (its `target`), so ruling A's key is not needed. - **Whose grades.** The caller's `positions` in the organization the listing reads, by the names `mapMembershipRole` projects the grades to (`org_owner`, `org_admin`, `delegated_admin`). That is the reading the actions' `requiresMembershipReach` sugar is lowered to. Only an envelope that carries its own positions is judged: the system context, a delegated agent (its envelope carries the agent ceiling, `positions: []`, not the person's grades) and an envelope with no `positions` array are left unmarked. - **The mark's shape.** `unavailable: { code: 'PERMISSION_DENIED', reason }`. The code is the one `run_action` answered for a member on every set-A/B action measured on a booted showcase (below). The reason names the action, the roles that reach it and the endpoint, and says who can run it: "Action 'invite_user' on 'sys_member' needs an organization owner, admin or delegated admin: its endpoint (/organization/invite-member) refuses every other membership role, and your role in this organization is none of those. Ask a person who holds one of those roles to run it." - **Nothing hidden, no run change.** Every action stays listed. Neither run door reads the mark: `run_action` and `POST /actions` forward the call to the endpoint exactly as before, and the endpoint stays the authority (a call naming another organization is judged there). - **System-context page.** Row 62b on `content/docs/permissions/system-context.mdx` owns the mark's system-context skip (an elevation read the census counts), and the generated site register names `mcp.ts#membershipReachRefusal`. - **Published page.** `content/docs/ai/actions-as-tools.mdx`: the `list_actions` row names the three codes a listed action can carry (`UNAUTHENTICATED`, `ACTION_CONFIRMATION_REQUIRED`, and `PERMISSION_DENIED` for the membership grade), and the intro and "What gets exposed" sentences no longer say every listed action can be run. - **Wording.** `McpActionSummary.unavailable`'s JSDoc and the `list_actions` tool description (`packages/mcp/src/mcp-http-tools.ts`) name the membership-role case and its code, and the description no longer promises that every returned action can be run ("that the caller's permissions allow are returned"; "cannot be run by you as you are connected (your credential, or your role in this organization)"). The served skill (`packages/mcp/src/skill-md.ts`) no longer says "only those … you are permitted to run" and says what `unavailable` means. Its Console mirror (`ui/apps/console/src/pages/developer/objectstack-skill.ts`) carries the same bytes, as its two drift pins require. **Not marked (sets C and D, listed and refused at their door as today):** `sys_sso_provider.delete_sso_provider` and `sys_oauth_application.delete_oauth_application` (judged on record ownership), and `sys_organization.create_organization` (judged on the deployment's tenancy posture; measured on the showcase: `403 ORGANIZATION_CREATION_DISABLED`). No reach row names their endpoints, so the function answers `undefined` for them. ## Tests New top-level `describe('[ruling E] list_actions marks an organization action the caller's membership role does not reach')` in `packages/runtime/src/platform-admin-action-gate.test.ts`, the identity-action harness: the REAL identity declarations (`@objectstack/platform-objects/identity`) through the production `McpActionBridge`, with the forward target faked as the endpoints answer a refused role. 1. Premise: every pinned action is AI-exposed, `api`-typed, and declares no capability gate. 2. A plain member (`positions: ['org_member', 'everyone']`) is listed every set-A and set-B action, each marked `PERMISSION_DENIED`, the reason naming "owner or admin" (set A) or "owner, admin or delegated admin" and `/organization/invite-member` (set B). 3. Owner and admin get no mark on any of the 15; delegated_admin gets none on set B and keeps it on set A. 4. CONTROL: the set-C and set-D actions are listed unmarked, for the member and the admin. 5. CONTROL: a delegated agent and the system context are left unmarked. 6. CONTROL: `run_action` unchanged. For each of the 15, the member's call is forwarded (the fake endpoint is called once, so no door refused first) and refused with the endpoint's `PERMISSION_DENIED` / 403 and its sentence; the admin's call is forwarded once and served. Green at `main` too. Red at `main` (test file at this branch, `packages/runtime/src/domains/mcp.ts` restored from `28a2f0f5`): 2 failed / 14 passed (cases 2 and 3: no mark). Green here: 16 / 16. <details><summary>Ablations (each through <code>scripts/ablation-replace.mjs</code>, anchor 1 → 0, restored to the HEAD blob, <code>git diff HEAD</code> empty after each; the suite imports <code>./http-dispatcher.js</code> from <code>src</code>, so no <code>dist/</code> sits between mutation and run)</summary> | Mutation | Red | | --- | --- | | A: the caller's grades never reach (`if (false) return undefined;`) | case 3 | | B: the mark not asked in `listActions` (`?? undefined`) | cases 2 and 3 | | C: a delegated agent and the system context judged too | case 5 | | D: reach from every row, not the rows naming the endpoint | cases 2, 3 and 4 | | E: hide instead of mark (`if (!served \|\| membershipReachRefusal(...)) continue;`) | cases 2, 3 (and the run control at the first test revision) | </details> <details><summary>Live measurement on a booted showcase (temporary dogfood file, not committed; MCP over the session bearer of a signed-up plain member and of the administrator)</summary> At `origin/main` `28a2f0f5`: the member is listed 34 `sys_*` actions, all 18 of sets A–D among them, none marked; the administrator 44. As the member, `run_action` answers `403 PERMISSION_DENIED` with the endpoint's own sentence on 14 of the 15 set-A/B actions ("You are not allowed to invite users to this organization", "… to delete this member", "… to update this organization", "… to create teams in this organization", …). `cancel_invitation` answered `400 VALIDATION_ERROR` "Member not found": the only invitation row the fixture holds belongs to another organization, so the endpoint stops before its role check. Set C/D: `create_organization` `403 ORGANIZATION_CREATION_DISABLED`; the two deletes `404` (no such provider or client in the fixture). At this branch (`d4df05f4`, after the rebuild): the member is listed the same 34, the 15 set-A/B rows marked `PERMISSION_DENIED` and nothing else; the administrator the same 44, none marked. Every member `run_action` answer is identical to `main`'s, code, status and sentence. Records: `measure-main-28a2f0f5.json` and `measure-head-d4df05f4.json` in the seat's `out/32163/`. </details> ## Acceptance notes - **Surface.** Ruling grep (`ruling|Ruling-ref|maintainer|⛔`) over the edited files: `mcp.ts` 17 hits, `mcp-http-tools.ts` 39, `skill-md.ts` 1, none in or governing `listActions`, the `unavailable` JSDoc or the `list_actions` description and skill lines; the one adjacent is the `run_action` listed-check ("maintainer's ruling on the card: no bypass"), which this change does not touch. - **What the mark reads is the courtesy reading, not the door's.** It reads `positions`, as the lowered `visible` predicate does. Two edges where it can differ from the endpoint, both in the safe direction for running (the mark never stops a run): a position granted directly through `sys_user_position` under a grade name (no mark, the endpoint still refuses, as today); a `sys_member` row outside its ADR-0091 validity window (no position, so marked, while the vendor may still admit). With no active organization, every membership's grades count, so a caller who is an admin anywhere is not marked. - **The code.** `PERMISSION_DENIED` is a constant beside the function, typed as the registered vocabulary. It is what `run_action` answered for a member on the showcase; the reason is this listing's own sentence, not the endpoint's (each endpoint words its refusal differently, and the table does not carry them). - **REST `/actions` listing** is not changed: the ruling scopes the mark to MCP `list_actions`. ## Verification <details><summary>Package suites, typecheck, lint (at `056f314d`; later commits are docs-only)</summary> After the last merge of `main` (`056f314d`), on a fresh install and a full build (declarations included) of the `@objectstack/runtime...`, `@objectstack/mcp...` and `@objectstack/service-storage...` closures: | Run | Result | | --- | --- | | `pnpm --filter @objectstack/runtime exec vitest run` | 601 files, 11956 passed, 19 skipped | | `pnpm --filter @objectstack/mcp exec vitest run` | 64 files, 1145 passed | | `pnpm --dir ui exec vitest run apps/console/src/pages/developer/objectstack-skill.test.ts` | 13 passed | | `pnpm --filter @objectstack/runtime --filter @objectstack/mcp typecheck` | exit 0 | | `pnpm lint` | exit 0 | `3de7508e` (system-context row) and `f91b2a1d` (actions-as-tools page) add only docs on top of `056f314d`; the package suites were not rerun for them. </details> <details><summary>Derived gates (dispatch-gates --commands; reconciled with --ran)</summary> `dispatch-gates --ran` at `f91b2a1d`: **100 derived, 100 run, 0 NOT MEASURED, 0 unrun.** Record: `gates-ran-f91b2a1d.list` in the seat's `out/32163/`. The docs-family gates (31, `check:role-word` and `check:system-context-census` among them) were rerun at `f91b2a1d`; the rest were run at `3de7508e`, which differs from it by one docs page. - `node scripts/check-plugin-teardown-shape.mjs --self-test` first exited 3: its positive control is pinned to commit `621a4876`, which the shallow clone did not hold. After `git fetch --depth=1 origin 621a487…` it passes (48 cases). - `pnpm check:system-context-census` was red at the first gate run: the mark's system-context skip is an elevation read no row owned. Fixed in `3de7508e` with row 62b on `content/docs/permissions/system-context.mdx` and the regenerated register; green after. - `pnpm check:role-word` was red on the first wording of that row ("membership role"); the row now says "membership grade". Green after. - The docs edit added 31 docs-family gates to the derivation; all were run at the new tree. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibvdpdhupF2wQf2NUU8)_ <!-- signed: domain:server#7 · os-tesla · session_01L9qibvdpdhupF2wQf2NUU8 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 30e364e commit 66919b6

8 files changed

Lines changed: 312 additions & 23 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/mcp': patch
4+
'@object-ui/console': patch
5+
---
6+
7+
fix(runtime): MCP `list_actions` marks an organization action the caller's membership role does not reach `unavailable`
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
A plain organization member's agent was listed identity actions such as inviting a user, removing a member, editing the organization or managing its teams, and `run_action` then answered `403 PERMISSION_DENIED` from the organization endpoint each time. The actions stay listed, and for a caller whose membership role in the organization does not reach the endpoint the row now carries `unavailable: { code: 'PERMISSION_DENIED', reason }`, where the reason names the roles that do reach it (for example "needs an organization owner, admin or delegated admin"). The reach is read from the action's `target` against the `MEMBERSHIP_REACH` table in `@objectstack/spec/identity`. Owners, admins and (for invitations) delegated admins see the rows unmarked. Nothing is hidden and neither run door reads the mark, so who can run each action is unchanged. Actions judged on record ownership or on the deployment's tenancy posture (deleting an SSO provider or an OAuth application, creating an organization) are not marked. The `list_actions` tool description, the `McpActionSummary.unavailable` documentation and the served skill (with its Console mirror) now say a listed action can carry `unavailable` for the caller's role, not only for its credential.

‎content/docs/ai/actions-as-tools.mdx‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ client, or a local model) connects over the Model Context Protocol, and the
1515
server exposes three business-action tools — `list_actions`, `run_action` and
1616
`resume_run` — bound to the caller's principal. The agent invokes actions the same way the
1717
Console toolbar does — but only actions the author explicitly exposed to AI, and
18-
only ones the caller is permitted to run. No cloud service and no ObjectOS
18+
only ones the caller's permissions allow; one the caller still cannot run as it
19+
is connected is listed with `unavailable` (see below). No cloud service and no ObjectOS
1920
runtime are required.
2021

2122
<Callout type="warn">
@@ -49,7 +50,7 @@ bound to the caller's principal (the API key acts as the user):
4950

5051
| Tool | What it does |
5152
|:---|:---|
52-
| `list_actions` | Enumerates the business actions that are **AI-exposed** (`ai.exposed: true`) **and** the caller is permitted to run — name, target object, description, whether it needs a `recordId`, whether it is destructive, its declared params, and `aiExposed: true` (the author's opt-in, attested by the bridge). An `api` action that `run_action` would refuse for the caller's credential (see the `api` row below) is still listed, with `unavailable: { code, reason }`: `code` is `UNAUTHENTICATED`, the code `run_action` answers with, and `reason` is the same sentence, so an agent can tell its user why it cannot run the action. |
53+
| `list_actions` | Enumerates the business actions that are **AI-exposed** (`ai.exposed: true`) **and** the caller's permissions allow — name, target object, description, whether it needs a `recordId`, whether it is destructive, its declared params, and `aiExposed: true` (the author's opt-in, attested by the bridge). An action that `run_action` would refuse for this caller is still listed, with `unavailable: { code, reason }`. `code` is the code `run_action` answers with: `UNAUTHENTICATED` for an `api` action whose endpoint does not accept the caller's credential (see the `api` row below); `ACTION_CONFIRMATION_REQUIRED` for an action declaring `ai.requiresConfirmation: true` listed for an AI service account; `PERMISSION_DENIED` for an `api` action whose target is an organization endpoint (inviting or removing a member, editing the organization or its teams) that the caller's membership grade in this organization (owner, admin, delegated admin) does not reach. `reason` says why and what would let the action run, so an agent can tell its user why it cannot run it. Nothing is hidden for these reasons, and the mark changes no run: the endpoint still judges the call. |
5354
| `run_action` | Invokes an action by name with `{ recordId, params }`. Invocation is gated (author opt-in + capabilities); the action body then runs the app's registered logic as trusted code. |
5455
| `resume_run` | Continues a flow run that `run_action` answered with `status: "paused"` and a `screen`, by submitting that screen's field values as `{ runId, values }`. Only the user who started the run can resume it, behind the same gates as `run_action`. See [Completing a paused screen flow](#completing-a-paused-screen-flow). |
5556

@@ -101,7 +102,8 @@ data-layer backstop, is the boundary (#2849).
101102

102103
The bridge walks every registered object's `actions[]` and offers only actions
103104
that are **AI-exposed** (`ai.exposed: true`), have a headless dispatch path,
104-
**and** that the caller is permitted to run. An action on a system object
105+
**and** that the caller's permissions allow (one `run_action` would still refuse
106+
for this caller is listed with `unavailable`, as above). An action on a system object
105107
(`sys_*`) is offered only on its own `ai.exposed: true` — the object's name is
106108
not a second opt-in to clear, and no deployment switch opens one that is not
107109
flagged — and then runs behind every gate below, as on any other object (#27681).

‎content/docs/permissions/system-context.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ One of the largest consumers of the flag;
220220
| 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` |
221221
| 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` |
222222
| 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` |
223+
| 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` |
223224

224225
### 6. Reads that only carry the flag onward
225226

@@ -674,6 +675,7 @@ and CI refuses one that differs from what the tree produces.
674675
| `packages/runtime/src/domains/i18n.ts#handleI18nRequest` | 1 | 52 |
675676
| `packages/runtime/src/domains/mcp.ts#federationService` | 1 | 55b |
676677
| `packages/runtime/src/domains/mcp.ts#handleMcpRequest` | 1 | 53 |
678+
| `packages/runtime/src/domains/mcp.ts#membershipReachRefusal` | 1 | 62b |
677679
| `packages/runtime/src/domains/meta.ts#handleMetadataRequest` | 5 | 50, 52 |
678680
| `packages/runtime/src/domains/packages.ts#handlePackagesRequest` | 1 | 52 |
679681
| `packages/runtime/src/domains/packages.ts#refuseWalledCatalogPackageWrite` | 1 | 55b |

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -377,17 +377,21 @@ export interface McpActionSummary {
377377
/** Declared input parameters. */
378378
params?: McpActionParamSummary[];
379379
/**
380-
* Present when `run_action` would refuse this action for THIS caller's
381-
* credential before running it: an `api` action whose target endpoint does
382-
* not accept the credential the caller connected with (an OAuth access token
383-
* is honoured on the MCP endpoint only, so an endpoint outside it cannot read
384-
* it), or an action declaring `ai.requiresConfirmation: true` listed for an
385-
* AI service account, which never confirms an action for itself (ADR-0151 D3
386-
* rule 3). The action is still listed, so an agent can tell its user why it
380+
* Present when `run_action` would refuse this action for THIS caller: an
381+
* `api` action whose target endpoint does not accept the credential the
382+
* caller connected with (an OAuth access token is honoured on the MCP
383+
* endpoint only, so an endpoint outside it cannot read it); an action
384+
* declaring `ai.requiresConfirmation: true` listed for an AI service
385+
* account, which never confirms an action for itself (ADR-0151 D3 rule 3);
386+
* or an `api` action whose target is an organization endpoint the caller's
387+
* membership role in this organization does not reach (inviting, removing a
388+
* member, editing the organization or its teams), which that endpoint
389+
* refuses. The action is still listed, so an agent can tell its user why it
387390
* cannot run it; `code` is the error code `run_action` answers with
388-
* (`UNAUTHENTICATED` for the endpoint, `ACTION_CONFIRMATION_REQUIRED` for the
389-
* account), `reason` the sentence it carries, including what would let the
390-
* action run. Absent when the action can be run.
391+
* (`UNAUTHENTICATED` for the credential, `ACTION_CONFIRMATION_REQUIRED` for
392+
* the account, `PERMISSION_DENIED` for the membership role), `reason` the
393+
* sentence that says why, including what would let the action run. Absent
394+
* when the action can be run.
391395
*/
392396
unavailable?: McpActionUnavailable;
393397
}
@@ -3217,12 +3221,12 @@ export function registerActionTools(
32173221
'List the business actions you can invoke in this app (e.g. "complete task", "convert lead"). ' +
32183222
'Returns each action\'s name, the object it operates on, a description, whether it needs a record id, ' +
32193223
'whether it is destructive, and its input parameters. Only actions the app author has exposed to AI ' +
3220-
'and that the caller is permitted to run are returned. Use run_action to invoke one. One name can be ' +
3224+
'and that the caller\'s permissions allow are returned. Use run_action to invoke one. One name can be ' +
32213225
'listed on several rows, one per object it is bound to: each row carries its own face, and run_action ' +
32223226
'takes that face as actionName (or the row\'s name with its objectName and namespace). An action that ' +
3223-
'carries "unavailable" cannot be run with the credential you connected with: run_action would refuse ' +
3224-
'it with unavailable.code, and unavailable.reason says why and what would let it run, so tell the ' +
3225-
'user instead of calling it.',
3227+
'carries "unavailable" cannot be run by you as you are connected (your credential, or your role in ' +
3228+
'this organization): run_action would refuse it with unavailable.code, and unavailable.reason says ' +
3229+
'why and what would let it run, so tell the user instead of calling it.',
32263230
inputSchema: strictToolInput({ surface: 'this list_actions call' }, {}),
32273231
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
32283232
},

‎packages/mcp/src/skill-md.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -462,9 +462,12 @@ create/update payload.
462462
stops the call and names the record it stopped at. Over OAuth it needs both
463463
\`data:read\` and \`data:write\`.
464464
- **list_actions()** — list the business actions available to you (only those
465-
the app author exposed to AI and you are permitted to run), with each
465+
the app author exposed to AI and your permissions allow), with each
466466
action's declared parameters, whether it operates on a record, and whether
467-
it is flagged destructive.
467+
it is flagged destructive. An action that carries \`unavailable\` is listed
468+
but \`run_action\` would refuse it for you (your credential, or your role in
469+
this organization): \`unavailable.reason\` says why and what would let it
470+
run, so tell your human instead of calling it.
468471
- **run_action({ actionName, objectName?, recordId?, params?, confirm? })** —
469472
invoke a business action by name. Invocation is permission-gated, but the
470473
action body executes the app's registered logic as trusted code (it can

‎packages/runtime/src/domains/mcp.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@ import type { ErrorCode, MetadataProtocol } from '@objectstack/spec/api';
1414
import type { ISecurityService } from '@objectstack/spec/contracts';
1515
// [#32442] The ONE reading of `enable.aiReadable` (ruling A, #32865).
1616
import { isAiReadExposed } from '@objectstack/spec/data';
17+
import {
18+
BUILTIN_MEMBERSHIP_ROLES,
19+
MEMBERSHIP_REACH,
20+
mapMembershipRole,
21+
type BuiltinMembershipRole,
22+
type MembershipReachEntry,
23+
} from '@objectstack/spec/identity';
1724
import type { AIActionConfirmation, IExternalDatasourceService } from '@objectstack/spec/contracts';
1825
import {
1926
FEDERATION_READ_CAPABILITY,
@@ -55,6 +62,67 @@ import { actionRunFieldVisibilityRefusal, actionRunMasker, projectActionForCalle
5562
/** Typed as the registered vocabulary, so a misspelling fails to compile. */
5663
const FIELD_VISIBILITY_UNRESOLVED: ErrorCode = 'FIELD_VISIBILITY_UNRESOLVED';
5764

65+
/**
66+
* The code `run_action` answers when an organization endpoint refuses the
67+
* caller's membership role: the forward relays the endpoint's 403, served as
68+
* the standard code for that status (ADR-0112).
69+
*/
70+
const MEMBERSHIP_REACH_REFUSAL_CODE: ErrorCode = 'PERMISSION_DENIED';
71+
72+
/** An identity-route target on better-auth's organization plugin, captured relative to the auth base path. */
73+
const ORGANIZATION_ENDPOINT_TARGET = /^\/api\/v1\/auth(\/organization\/[^?#]+)/;
74+
75+
/**
76+
* [ruling record 6812625052, letter E: list and mark, do not hide] Why
77+
* `run_action` would be refused for a listed `api` action whose target is an
78+
* organization endpoint the caller's membership role does not reach, or
79+
* `undefined` when it would not, or when this listing cannot tell.
80+
*
81+
* The reach is read from the action's declared `target` against the spec's
82+
* reach table ({@link MEMBERSHIP_REACH}, pinned equal to the vendor doors in
83+
* plugin-auth), never from a local list: the grades that reach the endpoint
84+
* are those of every row naming it (`/organization/update-member-role` is two
85+
* rows, so its reach is their union). A target no row names is no grade's to
86+
* judge (`/organization/create` is judged on the deployment's tenancy posture,
87+
* an SSO provider or OAuth application on record ownership), so it is never
88+
* marked.
89+
*
90+
* The caller's grades are its `positions` in the organization this listing
91+
* reads, by the names {@link mapMembershipRole} projects them to: the reading
92+
* the action's `requiresMembershipReach` sugar is lowered to. Only a principal
93+
* whose envelope carries its own positions is judged: the system context, a
94+
* delegated agent (its envelope carries the agent ceiling, not the delegating
95+
* person's grades) and an envelope with no `positions` are left unmarked.
96+
*
97+
* This is a mark and nothing else. The run doors do not read it: the endpoint
98+
* stays the authority, and a call naming another organization is judged there.
99+
*/
100+
function membershipReachRefusal(action: any, objectName: string | undefined, ec: any): { code: string; message: string } | undefined {
101+
if (action?.type !== 'api' || typeof action?.target !== 'string') return undefined;
102+
const endpoint = ORGANIZATION_ENDPOINT_TARGET.exec(action.target)?.[1]?.replace(/\/+$/, '');
103+
if (!endpoint) return undefined;
104+
const reaching = new Set<BuiltinMembershipRole>();
105+
for (const row of Object.values(MEMBERSHIP_REACH) as MembershipReachEntry[]) {
106+
if (row.endpoint === endpoint) for (const grade of row.grades) reaching.add(grade);
107+
}
108+
if (reaching.size === 0) return undefined;
109+
if (!ec || ec.isSystem === true || ec.onBehalfOf || !Array.isArray(ec.positions)) return undefined;
110+
const grades = BUILTIN_MEMBERSHIP_ROLES.filter((grade) => reaching.has(grade));
111+
if (grades.some((grade) => ec.positions.includes(mapMembershipRole(grade)))) return undefined;
112+
113+
const names = grades.map((grade) => grade.replace(/_/g, ' '));
114+
const roles = names.length > 1 ? `${names.slice(0, -1).join(', ')} or ${names[names.length - 1]}` : names[0];
115+
const on = objectName ? ` on '${objectName}'` : '';
116+
const where = ec.tenantId ? 'in this organization' : 'in any organization you belong to';
117+
return {
118+
code: MEMBERSHIP_REACH_REFUSAL_CODE,
119+
message:
120+
`Action '${String(action?.name ?? '')}'${on} needs an organization ${roles}: its endpoint ` +
121+
`(${endpoint}) refuses every other membership role, and your role ${where} is none of those. ` +
122+
`Ask a person who holds one of those roles to run it.`,
123+
};
124+
}
125+
58126
/**
59127
* [ADR-0106 D6 tier 3] The refusal an MCP object-schema read answers when the
60128
* caller's field visibility could not be evaluated, or the projection would
@@ -1224,7 +1292,14 @@ export function buildMcpBridge(
12241292
const confirmation = actionExec.isAiServiceAccountCaller(ec)
12251293
? actionExec.actionConfirmationRefusal(deps, action, undefined, objectName, ec)
12261294
: undefined;
1227-
const refusal = confirmation ?? actionExec.apiForwardCredentialRefusal(context, action);
1295+
// [ruling record 6812625052, letter E] …and an organization
1296+
// endpoint the caller's membership role does not reach: the
1297+
// forward reaches it and it refuses 403. Asked last, because
1298+
// `run_action` meets it last: after the admission sequence and
1299+
// the forward's credential table. Listed, never hidden: the
1300+
// run doors do not read the mark ({@link membershipReachRefusal}).
1301+
const refusal = confirmation ?? actionExec.apiForwardCredentialRefusal(context, action)
1302+
?? membershipReachRefusal(action, actionExec.isObjectLessActionKey(objectName) ? undefined : objectName, ec);
12281303
// [ADR-0106 D1] Summarised against the object as this caller is
12291304
// served it, and not listed where `/meta` withholds it.
12301305
const served = await servedActionObject(action, objectName, obj, objectsByName);

0 commit comments

Comments
 (0)