Skip to content

Commit 0771cdd

Browse files
feat(mcp): get_current_user tells an MCP client's model who is signed in (#38513)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_ Fixes #38363 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 通过 MCP 连接的 AI 助手现在能查到"当前登录的是谁":本人、所在组织、主业务单元及其上级单元;之前它只能反问用户。 - 属于知识专题:让 MCP 通道像问答页面一样知道提问人是谁,答"我们单位的制度"这类问题时不再反问。 - 只读取登录者本人有权看的信息,看不到的上级单元直接省略、不点名;出错时最多是助手拿不到单元信息,可直接撤回。 - 无。目前普通成员看不到自己的单元信息,助手只会说"单元不可读";你已定下让每位内部成员默认能读本组织的业务单元,那张卡做完后助手就能直接答出单元(本改动没有放宽任何权限)。 ## What changes - **A new read-only MCP tool, `get_current_user`** (`packages/mcp/src/mcp-http-tools.ts`). No argument, so it can answer about nobody else. It registers where the bridge carries the new optional `McpDataBridge.currentUser` member and the grant is the read family's (an API key, a session, or an OAuth token with `data:read`). It answers `user` (id, name), `organization` (the vetted active organization: id, name), `businessUnits` (the primary unit, then each parent up to the root: id, name, kind) and `businessUnitNote` (why the chain stops, or that no primary unit is recorded), so an absent unit never reads as "no unit". - **One resolver, `resolveCallerIdentity`** (`packages/runtime/src/domains/mcp.ts`), which the HTTP bridge's `currentUser` member calls, and which the declared retrieval-ranking card (Blocked-by this one) can call as is. It takes the caller's `ExecutionContext` and a reader that runs as that caller. Every read is a by-id `findData` through `callData` with the request's own context: permissions, row-level security and field masking apply, and nothing reads with a system context. The parent walk is here because `IBusinessUnitGraphService` walks descendants only. It is cycle-safe and capped at `CALLER_UNIT_CHAIN_MAX_DEPTH` (32) reads; no contract member was added. A link field masked off a row the caller can read (`primary_business_unit_id` on the user, `parent_business_unit_id` on a unit) is "not readable" and ends the chain with its note. A link that is present but empty means no unit or the top of the tree. A `401`/`403`/`404` read is "not readable" and the fact is left out. Any other failure, such as a driver fault, fails the call with its coded envelope, so it never reads as a permission limit. - **One fixed sentence in the open server's `initialize` text**, sent only where the tool registers (`ASKER_TOOL_LINE`, `packages/mcp/src/mcp-server-runtime.ts`). It names the tool and says when to call it. It carries no caller fact and reads nothing, so it is byte-identical for every caller. A host's own text (`instructions` / `dataOnlyInstructions`) and an operator-configured text are left whole, as before. - The stdio transport does not list the tool: its bridge has no `currentUser` member, and `packages/mcp/src/plugin.ts` is not touched. - `@objectstack/mcp` exports the answer's types, `McpCurrentUser` and `McpBusinessUnitFact`, from its index beside `McpDataBridge`, so an outside bridge implementer can name what `currentUser` returns. - **The tools/list weight pin measures the new tool** (`packages/mcp/src/tools-list-weight-34689.test.ts`). Its stub bridge gains `currentUser` and its sanity list names `get_current_user`. `TOOLS_LIST_BYTE_CEILING` goes from 38,000 to 39,000, and its header no longer promises room for one more tool. Table below. ## Deviation from the 7248187244 scope note The adoption note (comment 7248187244) asked for an asker paragraph in the `initialize` instructions with a read-only tool beside it as the fallback. This PR ships **the tool alone plus one fixed pointer sentence** in the open server's `initialize` text. The sentence carries no caller fact and is the same bytes for every caller. Reasons, measured on d89d3e2: 1. `handleHttpRequest` builds a fresh server for **every** POST, and `instructions` is evaluated in that constructor for every method: `initialize`, `tools/list` and every `tools/call`. A per-user paragraph would read the caller's identity (3+N reads) on every MCP request, unless `initialize` got a method-specific path. The tool reads only when the model calls it. 2. Where a host injects its own text (`hostInstructions`: the authoring injection's `instructions` / `dataOnlyInstructions`) or the operator sets `instructions`, that text replaces the open text whole, and nothing is appended to it. A paragraph would be missing on exactly those hosts. The tool is served on all of them. 3. A client that drops or truncates `initialize` instructions gets nothing from a paragraph. A tool in `tools/list` reaches every client. The transport is stateless, so there was no server-side cache to leak across in either shape. What the tool route achieves for a model's answers is measured by #38503's arm 2 ("the model told who asks"). The probe below is written to be re-run there as is. What the tool costs in `tools/list`: one row. On the real `/mcp` route a session user goes from 21 to 22 tools (probe below). On the weight pin's API-key surface it goes from 17 to 18 tools and from **37,931 to 38,569 bytes**: | | tools | total bytes | descriptions | input schemas | |:--|--:|--:|--:|--:| | before (stub without `currentUser`) | 17 | 37,931 | 13,160 | 21,637 | | after (stub with `currentUser`) | 18 | 38,569 | 13,502 | 21,751 | | `get_current_user` row | | 456 | 342 | 114 | Before this change the old ceiling of 38,000 left 69 bytes of headroom. The new ceiling of 39,000 leaves 431 bytes, which is not enough for another tool. <details><summary>Per-tool rows after (measured at 38fbe35, mcp closure rebuilt)</summary> ``` tools/list: 18 tools, 38569 bytes (descriptions 13502, input schemas 21751) | tool | description | input schema | both | | query_dataset | 826 | 4591 | 5417 | | aggregate_records | 1061 | 3943 | 5004 | | validate_expression | 633 | 3671 | 4304 | | list_datasets | 2567 | 490 | 3057 | | query_records | 1119 | 1853 | 2972 | | run_action | 1352 | 884 | 2236 | | delete_record | 783 | 894 | 1677 | | get_record | 431 | 1228 | 1659 | | delete_records | 763 | 888 | 1651 | | create_upload_link | 794 | 827 | 1621 | | resume_run | 716 | 488 | 1204 | | describe_object | 927 | 223 | 1150 | | read_file | 444 | 621 | 1065 | | list_actions | 483 | 114 | 597 | | update_record | 42 | 460 | 502 | | get_current_user | 342 | 114 | 456 | | create_record | 73 | 348 | 421 | | list_objects | 146 | 114 | 260 | ``` The before run, from the parent commit's version of the file, prints the same rows without `get_current_user`. </details> ## Tests - `packages/mcp/src/mcp-asker-38363.test.ts` (JSON-RPC through `handleHttpRequest`): - the tool registers, read-only and with no argument, for a key or session and for a `data:read` token. It does not register for `data:write` / `actions:execute` / `metadata:write` grants, or on a bridge without the member. - Two callers get their own facts, unchanged. - An argument is refused before the member runs. - A member throw answers the coded envelope. - The `initialize` sentence appears exactly where the tool registers. It carries no caller fact, it is identical for two callers, and the member is not called. - Host and configured texts stay whole. - `packages/runtime/src/domains/mcp-asker-38363.test.ts`: - `resolveCallerIdentity`: two users get their own chains up to the root, and it reads only their own rows. - A hidden parent is absent and not named, and the chain ends below it with a note. A hidden primary unit leaves no unit. - A parent link masked off a readable unit ends the chain with the "next unit up is not readable" note, and the next unit is never read. The control is a present, empty link: that is the top, with no note. Ablated: with the fix hunk reverted on disk, this case fails (1 failed, 14 passed); with it restored, 15 passed. - A `403` throw leaves the fact out. A `500` throw or a status-less throw fails the answer. - A deployment with no business units answers the user and organization. - A masked primary-unit field and an empty one answer differently. - No active organization gives no organization key. - A loop stops, and the depth cap holds. No user means no read. - Through `buildMcpBridge`, every read is a by-id `findData` carrying the caller's own `ExecutionContext` (never `isSystem`), and a refused read leaves the fact out. <details><summary>Local runs, review rework (final head 2d2b2bf: origin/main merged in 206d1f0, then the fix commit)</summary> ``` pnpm --filter '@objectstack/runtime^...' --filter '@objectstack/mcp^...' build BUILD_OK (under the lock) pnpm --filter @objectstack/mcp typecheck exit 0 pnpm --filter @objectstack/runtime typecheck exit 0 runtime src/domains/mcp-asker-38363.test.ts 15 passed (15) mcp src/mcp-asker-38363.test.ts 8 passed (8) lock VERDICT command-exit 0 ``` Derived gate list at 2d2b2bf (`dispatch-gates --commands`, the same 69 commands): 68 exited 0. `check:dual-build-cjs-loads` exited 3 with PREREQUISITE NOT MET, because the fresh worktree had built only the closure. After a full `turbo run build` (123 tasks, VERDICT command-exit 0) it exits 0 ("126 published require entry point(s) across 74 package(s) load"). `--ran` gives "69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN". </details> <details><summary>Local runs, patch round (final head 38fbe35: origin/main merged in 165fe83, then the weight-pin commit)</summary> ``` pnpm --filter '@objectstack/mcp^...' build BUILD_OK (under the lock) pnpm --filter @objectstack/mcp typecheck exit 0 pnpm --filter @objectstack/mcp test Test Files 89 passed (89) · Tests 1665 passed (1665) src/tools-list-weight-34689.test.ts 1 passed · 18 tools, 38569 bytes (ceiling 39,000) parent commit's version of the same file 1 passed · 17 tools, 37931 bytes (ceiling 38,000) ``` Derived gate list at 38fbe35 (`dispatch-gates --commands`, the same 69 commands as the first round): 68 exited 0. `check:dual-build-cjs-loads` exited 3 with PREREQUISITE NOT MET, because this fresh worktree had built only the mcp closure. After a full `turbo run build` (123 tasks, VERDICT command-exit 0) it reads "126 published require entry point(s) across 74 package(s) load" and exits 0. `--ran` gives "69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN". The runtime suite was not re-run in this round. The merge brought in main's runtime test changes; none of them is this PR's code. </details> <details><summary>Local runs, first round (head 0cea24a)</summary> ``` pnpm --filter '@objectstack/runtime^...' --filter '@objectstack/mcp^...' build VERDICT command-exit 0 pnpm --filter @objectstack/mcp typecheck exit 0 (re-run at 0cea24a) pnpm --filter @objectstack/runtime typecheck exit 0 (re-run at 0cea24a) pnpm --filter @objectstack/mcp test Test Files 89 passed (89) · Tests 1661 passed (1661) at b5881fa pnpm --filter @objectstack/runtime test Test Files 657 passed (657) · Tests 12507 passed | 25 skipped (12532) at b5881fa both asker files at 0cea24a runtime 14 passed (14) · mcp 8 passed (8) ``` The commits after b5881fa change only the changeset and add a module-top `import '@objectstack/metadata'` to the runtime asker test, which `check:test-source-alias` asked for. Derived gate list (`node scripts/pm/dispatch-gates.mjs --commands`, 69 commands) run at 0cea24a: all 69 exited 0. `--ran` gives "69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN". The first pass at b5881fa had four reds: - `check:test-source-alias` was a real red on the new runtime test, fixed in 0cea24a. - `check:query-options-erasure` read the uncommitted probe file mid-removal. - `check:dts-closure` and `check:dual-build-cjs-loads` hit PREREQUISITE NOT MET on packages outside the build closure. The re-run at the final head is the reading of record. </details> ## Acceptance notes - **Plain members read no business unit by default.** On the showcase, a member with no permission set granting `sys_business_unit` read gets `user` and `organization` plus the note "Your primary business unit is not readable with your permissions." That is the fixed rule (only what the caller may read), and this PR widens no permission. Today a plain member gets that note unless an app grants `sys_business_unit` read. #38515 is ruled D: `member_default` gains one read-only line on business units, with no row policy, added by a separate build card. Once that build lands, every internal member gets their own chain with no app grant. This PR's code does not change for it, because the tool already reads the chain as the caller may, and this PR adds no permission line. - **`enable.aiReadable` is not consulted.** The record tools need that opt-in before they read a `sys_*` object. `get_current_user` instead reads a fixed projection of the caller's own facts: their `sys_user` row (`id`, `name`, `primary_business_unit_id`, all readable to a plain member), their active `sys_organization` (`id`, `name`), and the units on their own chain (`id`, `name`, `kind`, `parent_business_unit_id`). These are read under the caller's permissions, RLS and field masking. This is the same set of facts the ask route's asker block gets from the platform. It opens no general read of those objects. - **tools/list weight pin.** The pin's stub bridge now carries `currentUser`, so its surface matches the runtime bridge's. The ceiling moved from 38,000 to 39,000 beside the table above, as the test's header asks of a PR that adds weight. - The `initialize` answer's two construction sites named on the card: the long-lived server's site (`mcp-server-runtime.ts` ~2205, used by stdio) is unchanged, because stdio does not register the tool. - The filter-placeholder idea on the card thread (`{current_business_unit_ids}` and the like) is new filter vocabulary and a separate decision. It is not built here. ## Verification Live probe through the real `/api/v1/mcp` route. The showcase was booted `multiTenant: 'posture-only'` with `MCPServerPlugin` (a scratch dogfood file, not committed). Organization A ("Acme Group") has units `Acme Group HQ` (company) → `Field Operations` (division) → `West Coast` (office), and `Acme Group HQ` → `HQ Finance` (department). A unit `Seconded Desk` in A has its parent in organization B, behind the organization wall. Ada is primary in West Coast, Lin in HQ Finance, Max in Seconded Desk. All three are members of A, signed in by session. <details><summary>Before (base d89d3e2, mcp and runtime rebuilt from base) vs after</summary> - `tools/list`: 21 tools before, 22 after; the only added name is `get_current_user`. - `initialize`: identical text for Ada and Lin, both before and after. The only line added after is the fixed "Who is asking: call get_current_user …" sentence. No id or name of either caller appears in it. - `tools/call get_current_user`, before: `isError: true`, "MCP error -32602: Tool get_current_user not found". - After, no set grants `sys_business_unit` read: - every user gets `{ user: { id, name }, organization: { id, name: "Acme Group" }, businessUnitNote: "Your primary business unit is not readable with your permissions." }`, with no error. - After, each holds a set granting `sys_business_unit` read: - Ada: `businessUnits` = West Coast (office), Field Operations (division), Acme Group HQ (company). - Lin: `businessUnits` = HQ Finance (department), Acme Group HQ (company). - Max: `businessUnits` = Seconded Desk only, `businessUnitNote`: "The chain ends here: the next unit up is not readable with your permissions." The organization-B parent's id and name appear nowhere in the answer. </details> **Re-running the probe (for the next card's arm 2).** Nothing extra is committed. Save the script below as `packages/qa/dogfood/test/zz-probe-38363.dogfood.test.ts`, build `@objectstack/mcp` and `@objectstack/runtime` (and their closure), then run: ``` PROBE_OUT=/tmp/probe.json pnpm --filter @objectstack/dogfood exec vitest run --project isolated test/zz-probe-38363.dogfood.test.ts ``` Delete the file afterwards. For the "before" arm, write base `packages/mcp/src` and `packages/runtime/src` into the tree (`git restore --source=BASE_SHA -- packages/mcp/src packages/runtime/src`), rebuild those two, re-run the probe, then restore HEAD and rebuild. - Fixture: the showcase app (`bootShowcase`, `multiTenant: 'posture-only'`, `extraPlugins: [new MCPServerPlugin()]`). - Users: `p38363-ada`, `p38363-lin` and `p38363-max`, all members of organization "Acme Group" and signed in by session. - Units: those listed above. The BU-read grant is the showcase's `showcase_field_ops_delegate` permission set. - What the probe reads per user: `initialize` instructions, `tools/list` names, and `tools/call get_current_user`. It runs once before the grant and once after. - **No model was in the loop, so no question was asked.** The probe measures the text a model is handed, not a model's answer. "The model's answer changes with the asker" is NOT MEASURED here, per question or otherwise. What is measured is that the model-visible text differs between Ada, Lin and Max only by their own facts: the `get_current_user` answer differs, and `initialize` is byte-identical. <details><summary>Probe script (no angle brackets, so it survives the body sanitizer)</summary> ```ts // Probe for get_current_user through the real /api/v1/mcp route (not committed). // Save as packages/qa/dogfood/test/zz-probe-38363.dogfood.test.ts, build mcp + runtime, then: // PROBE_OUT=/tmp/probe.json pnpm --filter @objectstack/dogfood exec vitest run --project isolated test/zz-probe-38363.dogfood.test.ts // Readings land in PROBE_OUT as JSON; delete the file afterwards. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { writeFileSync } from 'node:fs'; import { type VerifyStack } from '@objectstack/verify'; import { MCPServerPlugin } from '@objectstack/mcp'; import { bootShowcase } from './showcase-boot.js'; const SYS = { isSystem: true } as const; const OUT = process.env.PROBE_OUT ?? '/tmp/probe-38363.json'; const idOf = (b: any): string => String(b?.id ?? b?.record?.id ?? b?.data?.id ?? ''); describe('probe 38363', () => { let stack: VerifyStack; let ql: any; const tok: any = {}; const readings: any = {}; const mcp = async (token: string, method: string, params?: unknown) => { const res = await stack.api('/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${token}` }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, ...(params !== undefined ? { params } : {}) }), }); return { status: res.status, body: (await res.json()) as any }; }; const userId = async (email: string) => String((await ql.findOne('sys_user', { where: { email }, context: SYS }))?.id ?? ''); const inOrg = (o: string) => ({ context: { ...SYS, tenantId: o } }); const organization = async (token: string, name: string, slug: string) => { const created = await stack.apiAs(token, 'POST', '/auth/organization/create', { name, slug }); expect(created.status, await created.clone().text()).toBe(200); const id = String(((await created.json()) as any).id); await stack.apiAs(token, 'POST', '/auth/organization/set-active', { organizationId: id }); return id; }; beforeAll(async () => { stack = await bootShowcase({ multiTenant: 'posture-only', extraPlugins: [new MCPServerPlugin()] }); ql = await stack.kernel.getServiceAsync('objectql'); const ownerA = await stack.signUp('p38363-owner-a@verify.test'); const orgA = await organization(ownerA, 'Acme Group', 'p38363-acme'); const ownerB = await stack.signUp('p38363-owner-b@verify.test'); const orgB = await organization(ownerB, 'Other Holding', 'p38363-other'); readings.orgs = { orgA, orgB }; const unit = async (o: string, name: string, code: string, kind: string, parent?: string) => idOf(await ql.insert('sys_business_unit', { name, code, kind, organization_id: o, ...(parent ? { parent_business_unit_id: parent } : {}) }, inOrg(o))); const group = await unit(orgA, 'Acme Group HQ', 'P-GRP', 'company'); const ops = await unit(orgA, 'Field Operations', 'P-OPS', 'division', group); const west = await unit(orgA, 'West Coast', 'P-WEST', 'office', ops); const fin = await unit(orgA, 'HQ Finance', 'P-FIN', 'department', group); const holding = await unit(orgB, 'Other Holding Parent', 'P-HOLD', 'company'); let seconded = ''; try { seconded = await unit(orgA, 'Seconded Desk', 'P-SEC', 'department', holding); } catch (e: any) { readings.secondedInsertError = String(e?.message ?? e); } readings.units = { group, ops, west, fin, holding, seconded }; const people: any[] = [['ada', 'p38363-ada@verify.test', west], ['lin', 'p38363-lin@verify.test', fin]]; if (seconded) people.push(['max', 'p38363-max@verify.test', seconded]); for (const [k, email, bu] of people) { tok[k] = await stack.signUp(email); const uid = await userId(email); await ql.insert('sys_member', { user_id: uid, organization_id: orgA, role: 'member' }, inOrg(orgA)); const act = await stack.apiAs(tok[k], 'POST', '/auth/organization/set-active', { organizationId: orgA }); expect(act.status).toBe(200); await ql.insert('sys_business_unit_member', { user_id: uid, business_unit_id: bu, is_primary: true, organization_id: orgA }, inOrg(orgA)); readings[`${k}_uid`] = uid; readings[`${k}_primary_at_rest`] = (await ql.findOne('sys_user', { where: { id: uid }, fields: ['primary_business_unit_id'], context: SYS }))?.primary_business_unit_id; } readings.grant = async () => { for (const [k] of people) { await ql.insert('sys_user_permission_set', { user_id: readings[`${k}_uid`], permission_set: 'showcase_field_ops_delegate', organization_id: orgA }, inOrg(orgA)); } }; }, 180_000); afterAll(async () => { const { grant, ...rest } = readings; writeFileSync(OUT, JSON.stringify(rest, null, 2)); await stack?.stop(); }); it('reads', async () => { for (const k of Object.keys(tok)) { const init = await mcp(tok[k], 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'probe', version: '0' } }); readings[`${k}_initialize`] = { status: init.status, instructions: init.body?.result?.instructions }; const list = await mcp(tok[k], 'tools/list'); const names = (list.body?.result?.tools ?? []).map((t: any) => t.name); readings[`${k}_tools`] = { count: names.length, hasGetCurrentUser: names.includes('get_current_user'), names }; } const callAll = async (phase: string) => { for (const k of Object.keys(tok)) { const r = await mcp(tok[k], 'tools/call', { name: 'get_current_user', arguments: {} }); const text = r.body?.result?.content?.[0]?.text; let parsed: unknown = text; try { parsed = JSON.parse(text); } catch { /* keep text */ } readings[`${phase}_${k}`] = { status: r.status, isError: r.body?.result?.isError ?? false, rpcError: r.body?.error, answer: parsed }; } }; await callAll('no_grant'); await readings.grant(); await callAll('with_bu_read'); }, 180_000); }); ``` </details> **Read first (by risk):** 1. `packages/runtime/src/domains/mcp.ts`: `resolveCallerIdentity`, `readOrUndefined` (which throws count as a refusal) and the `currentUser` member (the reader runs as `ec`). 2. `packages/mcp/src/mcp-http-tools.ts`: `currentUserToolServed`, the one gate shared by registration and the `initialize` sentence. 3. `packages/mcp/src/mcp-server-runtime.ts`: `ASKER_TOOL_LINE`, the fixed text. **Two-minute check:** `pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-asker-38363.test.ts`. Expect 8 tests passing, including "carries no caller fact and reads none: the same text for every caller". --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 688fddb commit 0771cdd

8 files changed

Lines changed: 807 additions & 11 deletions

File tree

‎.changeset/38363-mcp-asker.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
feat(mcp): `get_current_user` tells an MCP client's model who is signed in
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
The `/mcp` route lists a new read-only tool, `get_current_user`, for an API key, a session and an OAuth token that grants `data:read`. It answers the caller's own facts: their user id and name, their active organization, and their primary business unit (`sys_user.primary_business_unit_id`) followed by each parent unit up to the top of the tree, each with its `name` and `kind`. Every read runs as the caller through the data API's permissions, row-level security and field masking, so a unit the caller may not read is left out (never named) and `businessUnitNote` says where the chain stops, or that no primary unit is recorded; a read that fails for any other reason fails the call with its coded error rather than reading as a permission limit. It takes no argument and answers nothing about any other user. A deployment with no business units answers the user and organization.
12+
13+
Where the tool registers and neither the host nor the operator writes the `initialize` text, that text gains one sentence pointing the model to the tool; the sentence is the same for every caller. `@objectstack/mcp` exports the answer's types, `McpCurrentUser` and `McpBusinessUnitFact`, for a host that implements `McpDataBridge.currentUser`. The stdio transport does not list the tool. The identity is resolved by one runtime function that any later door needing the asker's identity can reuse.

‎packages/mcp/src/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ export type {
6767
McpActionUnavailable,
6868
RegisterActionToolsOptions,
6969
McpFederationBridge,
70+
// [#38363] What `McpDataBridge.currentUser` answers, for an outside bridge implementer.
71+
McpCurrentUser,
72+
McpBusinessUnitFact,
7073
} from './mcp-http-tools.js';
7174
// [#33712] Step 1 of the amended confirmation contract: the person asked in their client.
7275
export {
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#38363] `get_current_user`: an MCP client's model can learn who is signed
5+
* in — the caller's user, active organization and primary business unit with
6+
* its parents — through the real registration path (`handleHttpRequest`, a
7+
* JSON-RPC round-trip), never a list of names.
8+
*
9+
* Pinned here: the tool registers exactly where the bridge resolves its
10+
* caller (`currentUser`) and the grant is the read family's; it takes no
11+
* argument; a call answers the bridge's facts unchanged, and a member throw
12+
* answers the ADR-0112 envelope; the open server's `initialize` text points to
13+
* the tool exactly where it registers, with the same sentence for every caller
14+
* (no caller fact in it), and a host's own text is left whole.
15+
*
16+
* The resolver behind the member is pinned in
17+
* `packages/runtime/src/domains/mcp-asker-38363.test.ts`.
18+
*/
19+
20+
import { describe, it, expect, vi, beforeEach } from 'vitest';
21+
import {
22+
MCP_OAUTH_SCOPE_ACTIONS,
23+
MCP_OAUTH_SCOPE_DATA_READ,
24+
MCP_OAUTH_SCOPE_DATA_WRITE,
25+
MCP_OAUTH_SCOPE_METADATA_WRITE,
26+
} from '@objectstack/spec/ai';
27+
import { MCPServerRuntime } from './mcp-server-runtime.js';
28+
import { GET_CURRENT_USER_TOOL_NAME, type McpCurrentUser, type McpDataBridge } from './mcp-http-tools.js';
29+
import type { McpAuthoringInjection } from './types.js';
30+
31+
const ADA: McpCurrentUser = {
32+
user: { id: 'u_ada', name: 'Ada' },
33+
organization: { id: 'org_1', name: 'Acme Group' },
34+
businessUnits: [
35+
{ id: 'bu_west', name: 'West Coast', kind: 'office' },
36+
{ id: 'bu_group', name: 'Acme Group', kind: 'company' },
37+
],
38+
};
39+
40+
function makeBridge(currentUser?: () => Promise<McpCurrentUser>): McpDataBridge {
41+
return {
42+
async listObjects() { return []; },
43+
async describeObject() { return null; },
44+
async query() { return { records: [] }; },
45+
async get() { return null; },
46+
async create() { return {}; },
47+
async update() { return {}; },
48+
async remove() { return {}; },
49+
...(currentUser ? { currentUser } : {}),
50+
};
51+
}
52+
53+
interface Opts { grantedScopes?: string[]; authoring?: Partial<McpAuthoringInjection> }
54+
55+
async function rpc(runtime: MCPServerRuntime, bridge: McpDataBridge, body: unknown, o: Opts = {}) {
56+
const res = await runtime.handleHttpRequest(
57+
new Request('http://localhost/api/v1/mcp', {
58+
method: 'POST',
59+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
60+
body: JSON.stringify(body),
61+
}),
62+
{
63+
bridge,
64+
parsedBody: body,
65+
...(o.grantedScopes ? { toolOptions: { grantedScopes: o.grantedScopes } } : {}),
66+
...(o.authoring
67+
? {
68+
authoring: {
69+
registry: { getAll: () => [], execute: async () => ({}) as never },
70+
principal: { userId: 'u_ada', scopes: o.grantedScopes ?? [] },
71+
...o.authoring,
72+
} as McpAuthoringInjection,
73+
}
74+
: {}),
75+
},
76+
);
77+
expect(res.status).toBe(200);
78+
return (await res.json()) as any;
79+
}
80+
81+
async function listedTool(runtime: MCPServerRuntime, bridge: McpDataBridge, o: Opts = {}) {
82+
const json = await rpc(runtime, bridge, { jsonrpc: '2.0', id: 1, method: 'tools/list' }, o);
83+
return ((json.result?.tools ?? []) as any[]).find((t) => t.name === GET_CURRENT_USER_TOOL_NAME);
84+
}
85+
86+
async function instructionsOf(runtime: MCPServerRuntime, bridge: McpDataBridge, o: Opts = {}): Promise<string> {
87+
const json = await rpc(runtime, bridge, {
88+
jsonrpc: '2.0',
89+
id: 2,
90+
method: 'initialize',
91+
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'pin', version: '0' } },
92+
}, o);
93+
expect(json.error).toBeUndefined();
94+
return json.result.instructions;
95+
}
96+
97+
async function call(runtime: MCPServerRuntime, bridge: McpDataBridge, args: Record<string, unknown> = {}) {
98+
const json = await rpc(runtime, bridge, {
99+
jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: GET_CURRENT_USER_TOOL_NAME, arguments: args },
100+
});
101+
return json.result as { content: Array<{ type: string; text: string }>; isError?: boolean };
102+
}
103+
104+
describe('[#38363] get_current_user — registration', () => {
105+
let runtime: MCPServerRuntime;
106+
beforeEach(() => { runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); });
107+
108+
it('registers, read-only and with no argument, where the bridge resolves its caller: a key or session, a data:read token', async () => {
109+
for (const o of [{}, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }] as Opts[]) {
110+
const tool = await listedTool(runtime, makeBridge(async () => ADA), o);
111+
expect(tool).toBeDefined();
112+
expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false });
113+
expect(Object.keys(tool.inputSchema.properties ?? {})).toEqual([]);
114+
expect(tool.description).toContain('businessUnits');
115+
}
116+
});
117+
118+
it('is not registered for a grant without data:read, nor on a bridge without the member', async () => {
119+
for (const grantedScopes of [[MCP_OAUTH_SCOPE_DATA_WRITE], [MCP_OAUTH_SCOPE_ACTIONS], [MCP_OAUTH_SCOPE_METADATA_WRITE]]) {
120+
expect(await listedTool(runtime, makeBridge(async () => ADA), { grantedScopes })).toBeUndefined();
121+
}
122+
expect(await listedTool(runtime, makeBridge())).toBeUndefined();
123+
});
124+
});
125+
126+
describe('[#38363] get_current_user — the answer', () => {
127+
let runtime: MCPServerRuntime;
128+
beforeEach(() => { runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); });
129+
130+
it('answers the bridge\'s facts for this caller, unchanged; two callers get their own', async () => {
131+
const lin: McpCurrentUser = {
132+
user: { id: 'u_lin', name: 'Lin' },
133+
organization: { id: 'org_1', name: 'Acme Group' },
134+
businessUnits: [{ id: 'bu_fin', name: 'HQ Finance', kind: 'department' }, { id: 'bu_group', name: 'Acme Group', kind: 'company' }],
135+
};
136+
const adaMember = vi.fn(async () => ADA);
137+
const adaRes = await call(runtime, makeBridge(adaMember));
138+
const linRes = await call(runtime, makeBridge(async () => lin));
139+
expect(adaMember).toHaveBeenCalledTimes(1);
140+
expect(adaRes.isError).toBeFalsy();
141+
expect(JSON.parse(adaRes.content[0].text)).toEqual(ADA);
142+
expect(JSON.parse(linRes.content[0].text)).toEqual(lin);
143+
});
144+
145+
it('refuses an argument rather than answer about someone else', async () => {
146+
const member = vi.fn(async () => ADA);
147+
const res = await call(runtime, makeBridge(member), { userId: 'u_lin' });
148+
expect(res.isError).toBe(true);
149+
expect(member).not.toHaveBeenCalled();
150+
});
151+
152+
it('a member throw answers the coded envelope', async () => {
153+
const res = await call(runtime, makeBridge(async () => {
154+
throw Object.assign(new Error('Service unavailable'), { code: 'SERVICE_UNAVAILABLE', status: 503 });
155+
}));
156+
expect(res.isError).toBe(true);
157+
const envelope = JSON.parse(res.content[0].text);
158+
expect(envelope.error ?? envelope).toMatchObject({ code: 'SERVICE_UNAVAILABLE' });
159+
});
160+
});
161+
162+
describe('[#38363] initialize — the pointer to get_current_user', () => {
163+
let runtime: MCPServerRuntime;
164+
beforeEach(() => { runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); });
165+
166+
it('the open server names the tool exactly where it registers', async () => {
167+
const served = await instructionsOf(runtime, makeBridge(async () => ADA));
168+
expect(served.split(GET_CURRENT_USER_TOOL_NAME)).toHaveLength(2);
169+
expect(await instructionsOf(runtime, makeBridge())).not.toContain(GET_CURRENT_USER_TOOL_NAME);
170+
expect(
171+
await instructionsOf(runtime, makeBridge(async () => ADA), { grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] }),
172+
).not.toContain(GET_CURRENT_USER_TOOL_NAME);
173+
});
174+
175+
it('carries no caller fact and reads none: the same text for every caller', async () => {
176+
const member = vi.fn(async () => ADA);
177+
const text = await instructionsOf(runtime, makeBridge(member));
178+
expect(member).not.toHaveBeenCalled();
179+
for (const fact of ['u_ada', 'Ada', 'Acme', 'West Coast', 'org_1']) expect(text).not.toContain(fact);
180+
expect(await instructionsOf(runtime, makeBridge(async () => ({ user: { id: 'u_lin', name: 'Lin' } })))).toBe(text);
181+
});
182+
183+
it('a host\'s own initialize text and a configured one are left whole', async () => {
184+
const hostText = 'Host text, owned by the host.';
185+
expect(await instructionsOf(runtime, makeBridge(async () => ADA), {
186+
grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ],
187+
authoring: { dataOnlyInstructions: hostText },
188+
})).toBe(hostText);
189+
const configured = new MCPServerRuntime({ name: 't', version: '1.0.0', instructions: 'Configured.' });
190+
expect(await instructionsOf(configured, makeBridge(async () => ADA))).toBe('Configured.');
191+
});
192+
});

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

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,50 @@ export interface McpDataBridge {
498498
* `packages/mcp` holds no second copy. OPTIONAL — see {@link getRecordContext}.
499499
*/
500500
recordContextToolDefinitions?(): ReadonlyArray<Pick<AIToolDefinition, 'name' | 'description'>>;
501+
/**
502+
* [#38363] `get_current_user`: who is signed in on this connection, as the
503+
* caller may read it about themselves ({@link McpCurrentUser}). Every read
504+
* behind it runs AS the principal, under the same permissions, row-level
505+
* security and field masking every other member runs under: a record the
506+
* caller may not read is left out, never named. It answers nothing about
507+
* any other user and writes nothing.
508+
*
509+
* OPTIONAL: a bridge that cannot resolve its principal's identity (the
510+
* stdio API-key host) omits it, and the tool does not register.
511+
*/
512+
currentUser?(): Promise<McpCurrentUser>;
513+
}
514+
515+
/**
516+
* [#38363] One business unit in {@link McpCurrentUser.businessUnits}: the
517+
* fields of its `sys_business_unit` row the caller read.
518+
*/
519+
export interface McpBusinessUnitFact {
520+
id: string;
521+
name?: string;
522+
/** The unit's `kind` (company, division, department, …), where it carries one. */
523+
kind?: string;
524+
}
525+
526+
/**
527+
* [#38363] What `get_current_user` answers: the caller's own facts, each read
528+
* with the caller's own permissions. A key is absent when its fact is not
529+
* recorded or not readable; `businessUnitNote` says which, so an absent unit
530+
* never reads as "no unit".
531+
*/
532+
export interface McpCurrentUser {
533+
/** The signed-in user: their id, and their display name where readable. Absent for a connection with no user. */
534+
user?: { id: string; name?: string };
535+
/** The active organization: its id, and its name where readable. Absent when the session has none. */
536+
organization?: { id: string; name?: string };
537+
/**
538+
* The primary business unit first, then each parent unit up to the top of
539+
* the tree, as far as the caller may read them. Absent when no unit is
540+
* readable or recorded.
541+
*/
542+
businessUnits?: McpBusinessUnitFact[];
543+
/** Why the business units end where they do, when they are not the whole chain up to the top. */
544+
businessUnitNote?: string;
501545
}
502546

503547
/** [#35442] Where a manual page lives: its name, app, title, manual and the console address to cite. */
@@ -3382,6 +3426,9 @@ export function wireBridgeTools(
33823426
// [ADR-0149 D2] `search_knowledge`, only where the bridge carries both
33833427
// knowledge members and the grant admits `data:read`.
33843428
registered.push(...registerKnowledgeTools(server, bridge, options));
3429+
// [#38363] `get_current_user`, only where the bridge resolves its caller
3430+
// and the grant admits `data:read`.
3431+
registered.push(...registerCurrentUserTool(server, bridge, options));
33853432
return registered;
33863433
}
33873434

@@ -3783,6 +3830,67 @@ export function registerKnowledgeTools(
37833830
return [SEARCH_KNOWLEDGE_TOOL_NAME];
37843831
}
37853832

3833+
/** [#38363] The tool that says who is signed in on this connection. */
3834+
export const GET_CURRENT_USER_TOOL_NAME = 'get_current_user';
3835+
3836+
/**
3837+
* [#38363] Whether this bridge and grant register `get_current_user`: the
3838+
* bridge resolves its caller ({@link McpDataBridge.currentUser}) and the grant
3839+
* is the read family's (an undefined grant keeps it, a scope list without
3840+
* `data:read` does not). The one gate: {@link registerCurrentUserTool}
3841+
* registers from it, and `handleHttpRequest` reads it to decide whether the
3842+
* `initialize` instructions point to the tool.
3843+
*/
3844+
export function currentUserToolServed(
3845+
bridge: Partial<McpDataBridge> | undefined,
3846+
options: RegisterObjectToolsOptions = {},
3847+
): boolean {
3848+
if (!bridge || typeof bridge.currentUser !== 'function') return false;
3849+
const scopes = options.grantedScopes;
3850+
return !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ);
3851+
}
3852+
3853+
/**
3854+
* [#38363] Register `get_current_user` over {@link McpDataBridge.currentUser}.
3855+
*
3856+
* - **The caller's own facts, nothing else.** The member reads the caller's
3857+
* user row, active organization and primary business unit with its parents
3858+
* AS the caller; a unit the caller may not read is left out and the chain
3859+
* ends below it. It takes no argument, so it can answer about no one else.
3860+
* - **A tool, not an `initialize` paragraph.** It is served on every host
3861+
* whose bridge resolves the caller, including the ones whose host or
3862+
* operator writes the whole `initialize` text; it costs one row of
3863+
* `tools/list`, and no read runs until it is called.
3864+
*/
3865+
export function registerCurrentUserTool(
3866+
server: McpServer,
3867+
bridge: Partial<McpDataBridge>,
3868+
options: RegisterObjectToolsOptions = {},
3869+
): string[] {
3870+
if (!currentUserToolServed(bridge, options)) return [];
3871+
const resolve = bridge.currentUser!.bind(bridge);
3872+
server.registerTool(
3873+
GET_CURRENT_USER_TOOL_NAME,
3874+
{
3875+
description:
3876+
'Who is signed in here: your user id and name, active organization, and primary business unit then each '
3877+
+ 'parent up to the top (businessUnits). Read with your own permissions: a unit you may not read is left '
3878+
+ 'out, and businessUnitNote says why the chain stops. Call it instead of asking the user who they are or '
3879+
+ 'which company or unit they are in.',
3880+
inputSchema: strictToolInput({ surface: `this ${GET_CURRENT_USER_TOOL_NAME} call` }, {}),
3881+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
3882+
},
3883+
async () => {
3884+
try {
3885+
return textResult(await resolve());
3886+
} catch (err) {
3887+
return errorResultWithCode(err);
3888+
}
3889+
},
3890+
);
3891+
return [GET_CURRENT_USER_TOOL_NAME];
3892+
}
3893+
37863894
/**
37873895
* [#27745] Register the federation pair, `list_remote_tables` and
37883896
* `import_object`, over {@link McpFederationBridge}.

0 commit comments

Comments
 (0)