diff --git a/.changeset/35442-mcp-app-docs-tools.md b/.changeset/35442-mcp-app-docs-tools.md index 175951bedf0..953887f6f35 100644 --- a/.changeset/35442-mcp-app-docs-tools.md +++ b/.changeset/35442-mcp-app-docs-tools.md @@ -13,7 +13,7 @@ An AI client connected over MCP (a user's own Claude, Cursor, …) can now answe - **`search_package_docs({ terms, package? })`** finds the pages whose title, a heading or text contains one of the terms (case aside, in the page's base text or a translation). Pages that contain more of the terms come first, then pages where the terms sit higher (the sum of title 3, heading 2, text 1), then by title; at most 10, each with an excerpt, its manual and, where the page has one, its console address (`/_console/apps//docs//`) to cite. The heading parse is line-based and linear. - **`read_package_doc({ name, package?, locale? })`** reads one page: its title, manual, Markdown content and, where the page has one, its console address (cut at 60,000 characters, and the answer says so). -- **Who sees what.** Both tools read the `doc` items through the `/meta/doc` docs-audience gate (ADR-0046 §6.7) with the request's execution context as the caller: a page the caller may not read is neither found nor read, and answers as not found. On an OAuth grant that caller is the agent, so the docs audience is judged on the token's grant (its scope-derived permission sets), not on the person's own permission sets: a manual whose audience is a permission set the person holds stays hidden on that connection. Both tool descriptions say so. Both are read tools: they register for an API key, a session, or a token granted `data:read`. The runtime's HTTP bridge carries them where the protocol serves the `/meta` list read; the stdio bridge does not. +- **Who sees what.** Both tools read the `doc` items through the `/meta/doc` docs-audience gate (ADR-0046 §6.7) with the request's execution context as the caller: a page the caller may not read is neither found nor read, and answers as not found. On an OAuth grant the request is an agent acting for the person who consented, and a permission-set audience is read against that person's own permission sets (ADR-0090 D10), never the token's scope-derived sets. Both are read tools: they register for an API key, a session, or a token granted `data:read`. The runtime's HTTP bridge carries them where the protocol serves the `/meta` list read; the stdio bridge does not. - **The answer order.** Where both tools register, the HTTP `initialize` instructions say: read the manuals first; answer a concept from the manual, and label a general explanation as one when no page covers it; for a process or rule, also read its real definition, which wins where the two differ; end with each page's title and url. The rule names a definition reader only where the connection lists one (`describe_metadata`, else `get_metadata_item`, both under `metadata:write`); without one it says to answer from the manual and state that the configured process was not checked. A host's own instructions and a configured `instructions` option are served unchanged. The two names are the ones the cloud AI runtime already registers, so `MCP_DOOR_TOOL_NAMES` (`@objectstack/spec/system`) now lists them too; `PLATFORM_PROVIDED_TOOL_NAMES` is unchanged. No metadata key, value or default changes. diff --git a/.changeset/35584-delegated-docs-audience.md b/.changeset/35584-delegated-docs-audience.md new file mode 100644 index 00000000000..b76601b854d --- /dev/null +++ b/.changeset/35584-delegated-docs-audience.md @@ -0,0 +1,20 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +--- + +Clause-②: yes — widening: on a delegated agent token whose scope reaches the docs tools, a permission-set-gated package doc is now found and read when the delegating person holds that set (ADR-0090 D10, ceiling ∩ delegator); nothing served today is refused, a non-holder and a token without docs-tool access still see nothing. Seat runs a contract read before ready; security#2 checks the head read-only before merge. +Metadata-protocol: none + +fix(runtime): on an OAuth MCP connection, `search_package_docs` and `read_package_doc` judge a manual's permission-set audience by the delegating person's own permission sets + +An OAuth token makes the request an agent acting on behalf of the person who consented (ADR-0090 D10). The two app-docs tools used to judge a manual whose audience is `{ permissionSet }` against the token's scope-derived permission sets, so a person who holds that set could not find or read the manual from their own AI client, while the Console showed it to them. + +Now, on such a connection: + +- The token's scope still decides whether the docs tools are reached at all (`data:read`). A token without it is served neither tool, whatever the person holds. +- The audience reads the person's own permission sets, resolved by the same grant resolution a request uses, in the organization the request runs in: the one the token's consent bound, while the person's membership there is current. A person with no user row holds no set here. A person whose membership there has ended is read with no active organization, as their own session is, so no grant stored in an organization applies. +- The token's own permission sets are never added to the person's: a manual whose audience is one of the token's scope sets stays closed unless the person holds it. +- Manuals with the default audience answer as before. API keys, signed-in sessions and AI service accounts keep their own permission sets. + +Both tool descriptions now say so: on an OAuth connection, the person's own permission sets decide, never more. diff --git a/packages/mcp/README.md b/packages/mcp/README.md index ed561626ebd..dccd438f225 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -180,8 +180,9 @@ analytics service serves its dataset executor), and `search_package_docs` / `readPackageDoc` (the runtime's HTTP bridge does where the protocol serves the `/meta` list read; it reads every page through the `/meta/doc` docs-audience gate as the caller, so a page the caller may not read is neither found nor -read; on an OAuth grant the caller is the agent, judged on the token's grant -rather than the person's own permission sets; the stdio bridge carries neither); a bridge without those seams +read; on an OAuth connection whose grant reaches the docs tools, a +permission-set audience is read against the delegating person's own permission +sets, never wider; the stdio bridge carries neither); a bridge without those seams serves the rest and advertises nothing it cannot do. OAuth scopes narrow the families at consent time: `data:read` covers diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 3bd9c6e7d97..f953c9e2c0e 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -427,7 +427,7 @@ export interface McpDataBridge { * `input.terms`, ranked and capped at `opts.maxResults`. Runs AS the * principal: the host reads the docs through the ADR-0046 §6.7 docs-audience * gate, so a page the caller may not read is never searched. On an OAuth - * grant the principal is the agent envelope, judged on the token's grant. + * grant the audience is the delegating person's own permission sets. * * OPTIONAL: a host that cannot read docs for the caller omits both doc * members ({@link searchPackageDocs}, {@link readPackageDoc}) and neither @@ -3315,10 +3315,10 @@ export function packageDocToolsServed( * - **No second gate.** Neither tool judges what the caller may read: the * host's members read the `doc` items through the `/meta/doc` docs-audience * gate (ADR-0046 §6.7) as the principal, so a page the caller may not read - * is neither found nor read, and reads as not found. On an OAuth grant the - * principal is the agent envelope, so the docs audience is judged on the - * token's grant, not the person's own permission sets; both descriptions - * say so. + * is neither found nor read, and reads as not found. On an OAuth grant that + * reaches these tools (the gate above), the docs audience is the delegating + * person's own permission sets, never wider (ADR-0090 D10); both + * descriptions say so. * - **The search is a substring match**, stated in the description: no * server-side doc search exists, so the honest search is a term found in a * page's title, a heading or its text (case aside). Pages that contain more @@ -3348,7 +3348,7 @@ export function registerPackageDocTools( + 'aside. Pages that contain more of the terms come first, then pages where the terms sit higher (title, ' + `then heading, then text), then by title; at most ${PACKAGE_DOC_SEARCH_MAX_RESULTS}, each with an excerpt ` + 'and, where the page has one, the url to cite. Only pages this connection may read are searched; on an ' - + 'OAuth connection that is judged on the connection\'s grant, not on the person\'s own permission sets. ' + + 'OAuth connection, those the person\'s own permission sets open, never more. ' + `Read a page with ${READ_PACKAGE_DOC_TOOL_NAME}.`, inputSchema: strictToolInput( { @@ -3382,7 +3382,7 @@ export function registerPackageDocTools( 'Read one page of an installed app\'s manual by its name (the name search_package_docs answers): its ' + 'title, its manual, its Markdown content and, where the page has one, its url to cite. Send package when ' + 'two apps ship a page of that name. A page this connection may not read answers as not found; on an OAuth ' - + 'connection that is judged on the connection\'s grant, not on the person\'s own permission sets.', + + 'connection, the person\'s own permission sets decide, never more.', inputSchema: strictToolInput( { surface: `this ${READ_PACKAGE_DOC_TOOL_NAME} call`, diff --git a/packages/runtime/src/domains/mcp-package-docs.test.ts b/packages/runtime/src/domains/mcp-package-docs.test.ts index 9e437a7956c..0234295966a 100644 --- a/packages/runtime/src/domains/mcp-package-docs.test.ts +++ b/packages/runtime/src/domains/mcp-package-docs.test.ts @@ -12,16 +12,23 @@ * - One visibility rule, the `/meta/doc` docs-audience gate (ADR-0046 §6.7): * a page only a `{ permissionSet }` manual claims is neither found nor read * by a caller without that set, and is both for a holder — the control that - * it is a match at all. On an OAuth grant the caller is the agent envelope, - * whose sets are the token's grant, so the page stays hidden there even when - * the delegating person holds the set. + * it is a match at all. + * - On an OAuth grant (ADR-0090 D10) the holdings are the delegating person's + * own, read by grant resolution in the token's organization: a holder finds + * and reads the page, a non-holder does not, a person who does not exist or + * holds no membership there holds no set, a set only the token's ceiling + * carries opens nothing, and a token whose scope does not reach the docs + * tools is carried no docs member at all. * - The address follows the Console's home-manual pick: the manual that claims * the page, else the package's implicit manual (ADR-0046 §6.4). * - The door's twin for the tool layer is `packages/mcp/src/mcp-package-doc-tools-35442.test.ts`. */ import { describe, expect, it } from 'vitest'; +import { MCP_AGENT_PERMISSION_SET_READ } from '@objectstack/spec/ai'; import { HttpDispatcher } from '../http-dispatcher.js'; +import { resolveExecutionContext } from '../security/resolve-execution-context.js'; +import { bindCatalogFromTables } from '../security/security-catalog.testkit.js'; // Paid at collection, not inside a case's clock: the dispatcher's reach loads it lazily. import '@objectstack/metadata'; @@ -83,11 +90,56 @@ const DOCS = [ ]; /** - * A kernel over a protocol serving `items`, a security service granting - * `crm_admin` to the person `admin`, and an `mcp` service that hands back the - * bridge. The security fake keeps the real resolver's agent arm (ADR-0090 - * D10): an agent principal's sets are its own `permissions`, the token's - * scope-derived ceiling, never its delegator's. + * The grant rows behind the OAuth pins: `admin` holds `crm_admin` in `orgA`; + * `u1` is a member of `orgA` holding it only in `orgB`; `ghost` has grant and + * membership rows and no `sys_user` row. + */ +function grantQl() { + const tables: Record = { + sys_user: [{ id: 'admin' }, { id: 'u1' }], + sys_organization: [{ id: 'orgA' }, { id: 'orgB' }], + sys_member: ['admin', 'u1', 'ghost'].map((user_id) => ({ user_id, organization_id: 'orgA', role: 'member' })), + sys_user_permission_set: [ + { id: 'g1', user_id: 'admin', permission_set_id: 'ps_crm_admin', permission_set: 'crm_admin', organization_id: 'orgA' }, + { id: 'g2', user_id: 'ghost', permission_set_id: 'ps_crm_admin', permission_set: 'crm_admin', organization_id: 'orgA' }, + { id: 'g3', user_id: 'u1', permission_set_id: 'ps_crm_admin', permission_set: 'crm_admin', organization_id: 'orgB' }, + ], + sys_permission_set: [{ id: 'ps_crm_admin', name: 'crm_admin', object_permissions: '{}' }], + sys_position: [], sys_position_permission_set: [], sys_user_position: [], + }; + const match = (opts: any) => (row: any) => 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 bindCatalogFromTables({ + async find(object: string, opts: any) { + const rows = (tables[object] ?? []).filter(match(opts)); + return typeof opts?.limit === 'number' ? rows.slice(0, opts.limit) : rows; + }, + async findOne(object: string, opts: any) { + return (tables[object] ?? []).find(match(opts)) ?? null; + }, + }, tables); +} + +/** The envelope the real `/mcp` identity door resolves for an OAuth token `person` consented to in `orgA`. */ +async function oauthEnvelope(person: string, scopes: string[], ql = grantQl()) { + return resolveExecutionContext({ + acceptOAuthAccessToken: true, + getService: async (name: string) => name === 'auth' + ? { verifyMcpAccessToken: async () => ({ userId: person, scopes, clientId: 'c1', organizationId: 'orgA' }) } + : undefined, + getQl: async () => ql, + request: { headers: { authorization: 'Bearer a.b.c' } }, + } as never) as Promise>; +} + +/** + * A kernel over a protocol serving `items`, a security service, a data engine + * (`grantQl`) and an `mcp` service that hands back the bridge. The security + * fake answers the set names a context carries (`permissions`), as the real + * resolver requests them with the baseline left out: an agent envelope's are + * the token's scope-derived ceiling, a person's are their own. */ function kernelOver(items: { doc: any[]; book: any[] } | null) { const mcp: any = { @@ -100,18 +152,17 @@ function kernelOver(items: { doc: any[]; book: any[] } | null) { const protocol = items ? { getMetaItems: async ({ type }: { type: string }) => ({ type, items: (items as any)[type] ?? [] }) } : {}; - const security = { - resolvePermissionSetNames: async (ctx: any) => { - if (ctx?.principalKind === 'agent') return [...(ctx.permissions ?? [])]; - return ctx?.userId === 'admin' ? ['crm_admin'] : []; - }, - }; - const all: Record = { protocol, security, mcp }; + const security = { resolvePermissionSetNames: async (ctx: any) => [...(ctx?.permissions ?? [])] }; + const all: Record = { protocol, security, mcp, objectql: grantQl() }; const get = (n: string) => all[n] ?? null; return { getService: get, getServiceAsync: async (n: string) => get(n), context: { getService: get } } as any; } -async function bridgeFor(caller: string | Record, items: { doc: any[]; book: any[] } | null = { doc: DOCS, book: BOOKS }) { +/** A signed-in session's envelope carries the person's own sets: `admin` holds `crm_admin`. */ +const session = (userId: string) => ({ userId, isSystem: false, permissions: userId === 'admin' ? ['crm_admin'] : [] }); + +/** The options the `/mcp` route hands the MCP runtime for this caller. */ +async function servedFor(caller: string | Record, items: { doc: any[]; book: any[] } | null = { doc: DOCS, book: BOOKS }) { const kernel = kernelOver(items); const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); const res = await dispatcher.handleMcp({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { @@ -122,10 +173,14 @@ async function bridgeFor(caller: string | Record, items: { doc: }), response: {}, environmentId: undefined, - executionContext: typeof caller === 'string' ? { userId: caller, isSystem: false } : caller, + executionContext: typeof caller === 'string' ? session(caller) : caller, } as any); expect(res.response?.status, 'precondition: the MCP route must have been served').toBe(200); - return kernel.getService('mcp').lastOpts.bridge; + return kernel.getService('mcp').lastOpts; +} + +async function bridgeFor(caller: string | Record, items?: { doc: any[]; book: any[] } | null) { + return (await servedFor(caller, items)).bridge; } const MAX = { maxResults: 10 }; @@ -180,25 +235,66 @@ describe('[#35442] one visibility rule: the /meta/doc docs-audience gate', () => const page = await bridge.readPackageDoc({ name: 'crm_commission_rules' }); expect(page.url).toBe(`/_console/apps/${CRM}/docs/admin/crm_commission_rules`); }); +}); - it('on an OAuth grant the caller is the agent: the page is neither found nor read though the delegator holds the set', async () => { - // The agent envelope `assembleExecutionContext` builds for an OAuth token: - // the person stays `userId` and `onBehalfOf`, and `permissions` are the - // token's scope-derived ceiling. - const bridge = await bridgeFor({ - userId: 'admin', - isSystem: false, - principalKind: 'agent', - onBehalfOf: { userId: 'admin', principalKind: 'human' }, - positions: [], - permissions: ['mcp_agent_read'], - }); - const names = (await bridge.searchPackageDocs({ terms: ['回款'] }, MAX)).results.map((r: any) => r.name); - expect(names).toEqual(['crm_order_payment']); - await expect(bridge.readPackageDoc({ name: 'crm_commission_rules' })).rejects.toMatchObject({ - code: 'RESOURCE_NOT_FOUND', - status: 404, - }); +/** The page names a search for 回款 finds, and whether the restricted page reads. */ +async function reach(bridge: any): Promise<{ found: string[]; reads: boolean }> { + const found = (await bridge.searchPackageDocs({ terms: ['回款'] }, MAX)).results.map((r: any) => r.name).sort(); + const reads = await bridge.readPackageDoc({ name: 'crm_commission_rules' }).then( + () => true, + (e: any) => { + expect(e).toMatchObject({ code: 'RESOURCE_NOT_FOUND', status: 404 }); + return false; + }, + ); + return { found, reads }; +} + +const OPEN = { found: ['crm_commission_rules', 'crm_order_payment'], reads: true }; +const CLOSED = { found: ['crm_order_payment'], reads: false }; + +describe('[#35584] on an OAuth grant the audience reads the delegating person\'s own holdings (ADR-0090 D10)', () => { + it('precondition: the envelope is the agent acting for the person, its sets the token\'s ceiling', async () => { + const ec = await oauthEnvelope('admin', ['data:read']); + expect(ec).toMatchObject({ principalKind: 'agent', onBehalfOf: { userId: 'admin' }, tenantId: 'orgA', permissions: [MCP_AGENT_PERMISSION_SET_READ] }); + }); + + // Edited in place: before ADR-0090 D10 was applied here the agent envelope's + // ceiling was the caller, and this holder answered CLOSED. + it('the holder of the set finds and reads the page, addressed through the manual that claims it', async () => { + const bridge = await bridgeFor(await oauthEnvelope('admin', ['data:read'])); + expect(await reach(bridge)).toEqual(OPEN); + expect((await bridge.readPackageDoc({ name: 'crm_commission_rules' })).url).toBe(`/_console/apps/${CRM}/docs/admin/crm_commission_rules`); + }); + + it('control: a person who does not hold the set in the token\'s organization neither finds nor reads it', async () => { + expect(await reach(await bridgeFor(await oauthEnvelope('u1', ['data:read'])))).toEqual(CLOSED); + }); + + it('a token whose scope does not reach the docs tools is carried no docs member, whatever the person holds', async () => { + const opts = await servedFor(await oauthEnvelope('admin', ['metadata:write', 'actions:execute'])); + expect(opts.toolOptions).toEqual({ grantedScopes: ['metadata:write', 'actions:execute'] }); + expect(opts.bridge.searchPackageDocs).toBeUndefined(); + expect(opts.bridge.readPackageDoc).toBeUndefined(); + }); + + it('fails closed: a person with no user row, or with no membership in the request\'s organization, holds no set', async () => { + const held = await oauthEnvelope('admin', ['data:read']); + const ghost = { ...held, userId: 'ghost', onBehalfOf: { userId: 'ghost', principalKind: 'human' } }; + expect(await reach(await bridgeFor(ghost))).toEqual(CLOSED); + // `u1` holds the set in orgB only, and is a member of orgA only. + const outside = { ...(await oauthEnvelope('u1', ['data:read'])), tenantId: 'orgB' }; + expect(await reach(await bridgeFor(outside))).toEqual(CLOSED); + }); + + it('no union: a manual whose audience is a set only the token\'s ceiling carries stays closed', async () => { + const books = [...BOOKS.slice(0, 1), { ...BOOKS[1], audience: { permissionSet: MCP_AGENT_PERMISSION_SET_READ } }]; + expect(await reach(await bridgeFor(await oauthEnvelope('admin', ['data:read']), { doc: DOCS, book: books }))).toEqual(CLOSED); + }); + + it('an AI service account keeps its own sets', async () => { + const account = { userId: 'svc_bot', isSystem: false, principalKind: 'agent', positions: [], permissions: ['crm_admin'] }; + expect(await reach(await bridgeFor(account))).toEqual(OPEN); }); }); diff --git a/packages/runtime/src/domains/mcp-package-docs.ts b/packages/runtime/src/domains/mcp-package-docs.ts index e2b025e9c2f..2334108e4b7 100644 --- a/packages/runtime/src/domains/mcp-package-docs.ts +++ b/packages/runtime/src/domains/mcp-package-docs.ts @@ -17,14 +17,18 @@ * A page the caller may not read is neither found nor read, and reads as not * found. * - * The caller is the request's execution context as the door received it. On - * an OAuth grant that is the agent envelope (ADR-0090 D10): the security - * service resolves its permission sets from the token's grant, the - * scope-derived ceiling, and not from the person's own sets, so a manual whose - * audience is a permission set the person holds stays hidden on that - * connection unless the grant carries the set. That fails closed, and it is - * stricter than the `/meta` doors a signed-in person reads through the - * Console, which judge the person's own sets. + * The caller is the request's execution context as the door received it. Its + * permission-set holdings, which a `{ permissionSet }` audience reads, are its + * own, with one exception ({@link packageDocsReadGate}): on a delegated agent + * envelope (an OAuth grant: `principalKind: 'agent'` acting `onBehalfOf` a + * person) they are the delegating person's own sets, resolved by grant + * resolution in the organization the request runs in (ADR-0090 D10: the + * token's ceiling decides whether the docs tools are reached at all, and the + * person's holdings decide which manuals open). Never the envelope's + * scope-derived ceiling sets, and never a union with them. A person who does + * not exist, who holds no membership in that organization, or whose grants + * cannot be read holds no set here: permission-set audiences stay closed. An + * AI service account (an agent acting for nobody) keeps its own sets. * * ## The search * @@ -66,6 +70,7 @@ import { type ResolverDoc, } from '@objectstack/spec/system'; import type { ErrorCode } from '@objectstack/spec/api'; +import { resolveUserAuthzGrants, vetOrganizationClaim } from '@objectstack/core'; /** The protocol read these members take: the merged `/meta` list read. */ export interface PackageDocsProtocol { @@ -398,15 +403,38 @@ export function createPackageDocMembers(getSources: () => Promise Promise, + resolveEngine: () => Promise = async () => undefined, ): MetaItemReadGateSources { + type Security = Awaited>; + const security = async () => (await resolveService('security')) as Security; + const personId = delegatingPersonOf(caller); + let holdings: Promise | undefined; return { resolveCaller: async () => caller, - resolveSecurityService: async () => (await resolveService('security')) as Awaited>, + resolveSecurityService: personId === undefined + ? security + : async () => { + const svc = await security(); + const names = svc?.resolvePermissionSetNames?.bind(svc); + if (!names) return undefined; + // A throw here (no such person, no membership, an unreadable + // grant) is read by the gate as unresolved holdings: closed. + return { + resolvePermissionSetNames: async () => + names(await (holdings ??= delegatorHoldingsCaller(resolveEngine, personId, caller?.tenantId))), + }; + }, listMetaItems: (type) => protocol.getMetaItems({ type }), // Only the `app` and `dashboard` arms probe services or log nav prunes; // the `doc` and `book` arms these members read do neither. @@ -414,3 +442,50 @@ export function packageDocsReadGate( navPruneLogged: new Set(), }; } + +/** + * The person a delegated agent envelope acts for (ADR-0090 D10): its + * `onBehalfOf.userId` when the caller is an agent principal, else `undefined`. + * An AI service account is an agent acting for nobody, so it keeps its own sets. + */ +export function delegatingPersonOf(caller: MetaReadGateCaller | undefined): string | undefined { + if (caller?.principalKind !== 'agent') return undefined; + const id = (caller.onBehalfOf as { userId?: unknown } | undefined)?.userId; + return typeof id === 'string' && id.length > 0 ? id : undefined; +} + +/** + * The delegating person as the audience reads a caller: their own grants + * (`resolveUserAuthzGrants`, as the open draft door's reader resolves them, + * with no capability asked of them) in the organization the request runs in. + * Fails closed as the security plugin's delegator resolution does: it throws + * when no `sys_user` row has the id (the resolver synthesises a baseline for + * any id), and when the person holds no current membership in that + * organization (`vetOrganizationClaim`, the one membership rule). + */ +async function delegatorHoldingsCaller( + resolveEngine: () => Promise, + userId: string, + organization: unknown, +): Promise { + const ql = (await resolveEngine()) as { findOne(object: string, query: unknown): Promise } | undefined; + if (!ql) throw new Error('no data engine to resolve the delegating person\'s grants from'); + const tenantId = typeof organization === 'string' && organization.length > 0 ? organization : undefined; + if (!(await ql.findOne('sys_user', { where: { id: userId }, context: { isSystem: true } }))) { + throw new Error('the delegating person does not exist'); + } + const grants = await resolveUserAuthzGrants(ql as never, userId, tenantId ? { tenantId } : {}); + if (tenantId && vetOrganizationClaim(tenantId, grants.accessible_org_ids) === undefined) { + throw new Error('the delegating person holds no membership in the request\'s organization'); + } + return { + userId, + ...(tenantId ? { tenantId } : {}), + positions: grants.positions, + permissions: grants.permissions, + ...(grants.permissionSetAddresses ? { permissionSetAddresses: grants.permissionSetAddresses } : {}), + systemPermissions: grants.systemPermissions, + principalKind: grants.principalKind ?? 'human', + isSystem: false, + }; +} diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index d3c559f7c15..f101e59653a 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -9,7 +9,7 @@ */ import { isMcpServerEnabled } from '@objectstack/types'; -import { MCP_OAUTH_SCOPES, deriveAiFaceName } from '@objectstack/spec/ai'; +import { MCP_OAUTH_SCOPES, MCP_OAUTH_SCOPE_DATA_READ, deriveAiFaceName } from '@objectstack/spec/ai'; import type { ErrorCode, MetadataProtocol } from '@objectstack/spec/api'; import type { ISecurityService } from '@objectstack/spec/contracts'; // [#32442] The ONE reading of `enable.aiReadable` (ruling A, #32865). @@ -251,8 +251,14 @@ export async function handleMcpRequest(deps: DomainHandlerDeps, body: any, conte // service serves its dataset executor. const datasetTools = await resolveMcpDatasetToolsService(deps, context); // [#35442] The docs seam: the bridge carries `search_package_docs` / - // `read_package_doc` exactly where the protocol serves the `/meta` list read. - const packageDocs = await resolveMcpPackageDocsProtocol(deps, context); + // `read_package_doc` exactly where the protocol serves the `/meta` list read + // and [ADR-0090 D10] the grant reaches the docs tools. The MCP runtime's + // `packageDocToolsServed` (`data:read`, or no grant at all) stays the + // authority on listing them; it is read here too so a token that cannot + // reach them never has the delegating person's holdings read for them. + const packageDocs = !grantedScopes || grantedScopes.includes(MCP_OAUTH_SCOPE_DATA_READ) + ? await resolveMcpPackageDocsProtocol(deps, context) + : undefined; const bridge = buildMcpBridge(deps, context, { recordFiles, datasetTools, packageDocs }); // [#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 @@ -1605,7 +1611,9 @@ export function buildMcpBridge( // [#35442] The docs seam (`search_package_docs` / `read_package_doc`), // carried only where the protocol serves the `/meta` list read. Every // page is read through the `/meta/doc` docs-audience gate AS this - // request's caller (`mcp-package-docs.ts`), in this request's locale. + // request's caller (`mcp-package-docs.ts`), in this request's locale; + // [ADR-0090 D10] on a delegated agent envelope with the delegating + // person's own holdings, read through this request's data engine. ...(seams.packageDocs ? createPackageDocMembers(async () => ({ protocol: seams.packageDocs!, @@ -1613,6 +1621,8 @@ export function buildMcpBridge( seams.packageDocs!, ec as Record | undefined, (name) => deps.resolveService(context, name), + async () => (await deps.getObjectQL(context, envId)) + ?? (await deps.resolveService(context, 'objectql', envId)), ), locale: metaRequestLocale(mcpRequestHttp(context)), }))