@ultimat3/mcp 30.9.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,12 @@
1
1
  // OAuth 2.0 Protected Resource Metadata (RFC 9728) for the MCP endpoint — the framework half of
2
- // the MCP authorization spec (2025-06-18, unchanged in 2025-11-25): a 401 names where the metadata
3
- // lives (`WWW-Authenticate: Bearer resource_metadata="…"`), and the metadata names the
4
- // authorization server(s) a client goes to for a token. The server itself is `@ultimat3/auth`'s
2
+ // the MCP authorization spec's discovery, which the revisions this transport serves (`wire.ts`)
3
+ // do not define alike. The revisions served are 2026-07-28 (`MCP_MODERN_VERSIONS`) and 2025-11-25 /
4
+ // 2025-06-18 / 2025-03-26 (`MCP_LEGACY_VERSIONS`). All but 2025-03-26 require RFC 9728: a 401 names
5
+ // where the metadata lives (`WWW-Authenticate: Bearer resource_metadata="…"`), the metadata names
6
+ // the authorization server(s) a client goes to for a token. 2025-11-25 made that header optional
7
+ // with a `.well-known` fallback (SEP-985); 2025-06-18 required it. 2025-03-26 defines no
8
+ // protected-resource metadata at all — its discovery is RFC 8414 authorization-server metadata at
9
+ // the origin — so it reads none of this. The server itself is `@ultimat3/auth`'s
5
10
  // `authorizationServer`, bound to one endpoint by `mcpAuthorizationServer` (`oauth-server.ts`).
6
11
 
7
12
  import { McpOAuthInvalidError } from './errors-transport';
@@ -128,8 +133,10 @@ export function assertScopeTokens(scopes: readonly string[]): void {
128
133
  /**
129
134
  * The challenge a 401 carries. `error="invalid_token"` only when a token WAS sent (RFC 6750
130
135
  * §3.1: a request with no credential gets no error code). `scope` names what the resource
131
- * supports (RFC 6750 §3, MCP authorization 2025-06-18 / 2025-11-25 "scope selection"), so a
132
- * client can ask for it without first fetching the metadata; omitted when there is none.
136
+ * supports (RFC 6750 §3), so a client can ask for it without first fetching the metadata;
137
+ * omitted when there is none. Scope selection on the challenge is the MCP authorization spec's
138
+ * from 2025-11-25 (SEP-835), and modern 2026-07-28 keeps it; the 2025-06-18 and 2025-03-26
139
+ * revisions carry no scope guidance there.
133
140
  */
134
141
  export function bearerChallenge(
135
142
  metadataUrl: string | undefined,
@@ -94,11 +94,11 @@ export function primitiveFromQuery(target: AnyQuery): ProjectablePrimitive {
94
94
  ? {}
95
95
  : { outputJsonSchema: output, ...(single ? {} : { outputWrap: 'rows' }) }),
96
96
  mutates: false,
97
- // `sourceFor`'s opening gate, on the surface it runs on ('server'), asked before `invalid-args`.
97
+ // `sourceFor`'s opening gate, on the surface `run` passes it ('mcp'), asked before `invalid-args`.
98
98
  admit: (actor: Actor) =>
99
99
  asCallerContext(actor, () => {
100
100
  const ctx = useContext();
101
- guardQueryBeforeInput(target.policy, { actor: actorOf(ctx), ctx, query: name }, 'server');
101
+ guardQueryBeforeInput(target.policy, { actor: actorOf(ctx), ctx, query: name }, 'mcp');
102
102
  }),
103
103
  run: ({ input, actor }) =>
104
104
  asCallerContext(actor, async () => {
package/src/registry.ts CHANGED
@@ -41,7 +41,9 @@ export interface McpCaller {
41
41
  readonly role?: McpRole;
42
42
  /**
43
43
  * The tenant THIS call acts in, on a `defineAppMcp({ tenant })` server — set by `tenant.ts` for
44
- * one call, with `actor` the tenant's. Absent for the connection's own caller. Audited.
44
+ * one call, with `actor` the tenant's. Absent for the connection's own caller. Audited. The
45
+ * caller's tenant VALUE (`'acme'`), never the arg NAME it was sent under (`'project'`): the name
46
+ * belongs to the server, and `ToolRegistry` is where it lives.
45
47
  */
46
48
  readonly tenant?: string;
47
49
  }
@@ -251,6 +253,15 @@ export type ToolResolution =
251
253
 
252
254
  export class ToolRegistry {
253
255
  readonly #tools = new Map<string, AnyMcpTool>();
256
+ /**
257
+ * The argument a `defineAppMcp({ tenant })` server reserves on every call — `tenant.arg`, the
258
+ * NAME, given at construction because no caller carries it. Absent: this registry strips nothing.
259
+ */
260
+ readonly #tenantArg: string | undefined;
261
+
262
+ constructor(tenantArg?: string) {
263
+ this.#tenantArg = tenantArg;
264
+ }
254
265
 
255
266
  register(tool: AnyMcpTool): this {
256
267
  if (this.#tools.has(tool.name)) {
@@ -268,7 +279,9 @@ export class ToolRegistry {
268
279
  return this;
269
280
  }
270
281
 
271
- /** Raw lookup with NO gate applied — the resolver owns the gates. */
282
+ /**
283
+ * Raw lookup with NO gate applied — the resolver owns the gates.
284
+ */
272
285
  get(name: string): AnyMcpTool | undefined {
273
286
  return this.#tools.get(name);
274
287
  }
@@ -299,16 +312,37 @@ export class ToolRegistry {
299
312
  * Validating before the gates would leak a schema to a caller that may not see the tool;
300
313
  * running the policy before the scope gate would decide a refusal from attacker-supplied
301
314
  * input. Absent and hidden collapse into ONE branch so the two cannot drift apart.
315
+ *
316
+ * Tenancy is decided BEFORE this gate: the server asks `tenantStep` for the call's tenant, which
317
+ * strips `tenant.arg` and rebuilds the caller, so nothing here ever models it. A call on a
318
+ * tenant-scoped server that names no tenant is refused there (`McpTenantRequiredError`), ahead
319
+ * of any tool-specific answer. Built with the reserved name — `new ToolRegistry(tenant.arg)` —
320
+ * this method strips it too, so a direct caller of `resolve` (the meta surface, an embedder, a
321
+ * test) cannot smuggle it through. Built with none, nothing is reserved and nothing stripped.
322
+ *
323
+ * The key is the NAME this registry was constructed with, never `caller.tenant`: that field is
324
+ * the VALUE the call chose, so keying the strip on it stripped nothing a real tenant server sends
325
+ * (`project` arrived, `acme` was stripped) and deleted a legitimate argument whenever one
326
+ * happened to be named after the renter.
302
327
  */
303
328
  resolve(name: string, rawArgs: unknown, caller: McpCaller): ToolResolution {
304
- const tool = this.#tools.get(name);
305
- if (tool === undefined || !visibleToCaller(tool, caller)) {
329
+ const arg = this.#tenantArg;
330
+ const isRecord = typeof rawArgs === 'object' && rawArgs !== null && !Array.isArray(rawArgs);
331
+ // A non-record stays as it is rather than becoming `{}`: validation refuses it as a whole, and
332
+ // an empty object here would answer a malformed call as an argument-less one.
333
+ const args =
334
+ arg === undefined || !isRecord
335
+ ? rawArgs
336
+ : withoutKey(rawArgs as Readonly<Record<string, unknown>>, arg);
337
+ const found = this.#tools.get(name);
338
+ const tool = found === undefined || !visibleToCaller(found, caller) ? undefined : found;
339
+ if (tool === undefined) {
306
340
  return { kind: 'not-found', name };
307
341
  }
308
342
  if (tool.scope !== undefined && !caller.scopes.has(tool.scope)) {
309
343
  return { kind: 'scope-denied', name, scope: tool.scope };
310
344
  }
311
- const validation = validateArgs(tool.inputSchema, rawArgs ?? {});
345
+ const validation = validateArgs(tool.inputSchema, args ?? {});
312
346
  if (!validation.ok) return { kind: 'invalid-args', name, issues: validation.issues, tool };
313
347
  return { kind: 'ok', tool, args: validation.value };
314
348
  }
@@ -324,6 +358,29 @@ export class ToolRegistry {
324
358
  }
325
359
  }
326
360
 
361
+ /**
362
+ * A copy of `args` without `key` — the ONE tenant-arg strip, shared by `tenantStep` (the server
363
+ * path) and `ToolRegistry.resolve` (a direct caller). Each remaining key lands through
364
+ * `defineProperty`, so `__proto__` and `constructor` are copied as data and never set the
365
+ * prototype of the object the schema then validates.
366
+ */
367
+ export function withoutKey(
368
+ args: Readonly<Record<string, unknown>>,
369
+ key: string,
370
+ ): Record<string, unknown> {
371
+ const out: Record<string, unknown> = {};
372
+ for (const [name, value] of Object.entries(args)) {
373
+ if (name === key) continue;
374
+ Object.defineProperty(out, name, {
375
+ value,
376
+ enumerable: true,
377
+ writable: true,
378
+ configurable: true,
379
+ });
380
+ }
381
+ return out;
382
+ }
383
+
327
384
  /** Convenience constructor for a one-block text result. */
328
385
  export function textResult(text: string, isError = false): McpToolResult {
329
386
  const content: readonly ContentBlock[] = [{ type: 'text', text }];
@@ -3,7 +3,8 @@
3
3
  // person sets. `x mcp lock <name>` writes it; `mcpTools()` reads it; any difference from the live
4
4
  // server is `X_MCP_REMOTE_TOOL_CHANGED`. Deterministic bytes, so a diff is the review.
5
5
 
6
- import { isJsonObject } from '@ultimat3/core';
6
+ import { stableStringify } from '@ultimat3/action';
7
+ import { canonicalJson, isJsonObject } from '@ultimat3/core';
7
8
  import type { RemoteTool } from './remote-client';
8
9
  import { McpRemoteToolChangedError } from './remote-errors';
9
10
 
@@ -65,7 +66,8 @@ export function lockChanges(
65
66
  if (current === undefined) changes.push(`"${name}" is gone from the server`);
66
67
  else if (current.description !== entry.description)
67
68
  changes.push(`"${name}" changed its description`);
68
- else if (canonical(current.inputSchema) !== canonical(entry.inputSchema)) {
69
+ // Core's HASH form: an equality question, never written down.
70
+ else if (canonicalJson(current.inputSchema) !== canonicalJson(entry.inputSchema)) {
69
71
  changes.push(`"${name}" changed its input schema`);
70
72
  }
71
73
  }
@@ -85,7 +87,8 @@ export function assertLocked(
85
87
 
86
88
  /**
87
89
  * The lock with `server` rewritten from `live`, keeping every other server and each tool's
88
- * reviewed `readOnly`. Serialised with sorted keys: the same tools are the same bytes.
90
+ * reviewed `readOnly`. `@ultimat3/action`'s DOCUMENT form (`stableStringify`): sorted keys at
91
+ * every depth and valid JSON, so the same tools are the same bytes and the file re-reads.
89
92
  */
90
93
  export function writeToolsLock(
91
94
  previous: unknown,
@@ -116,24 +119,9 @@ export function writeToolsLock(
116
119
  });
117
120
  }
118
121
  servers.set(server, serialisable({ url, tools }));
119
- return `${canonical({ version: 1, servers: Object.fromEntries(servers) }, 2)}\n`;
122
+ return `${stableStringify({ version: 1, servers: Object.fromEntries(servers) }, 2)}\n`;
120
123
  }
121
124
 
122
125
  function serialisable(entry: LockedServer): unknown {
123
126
  return { url: entry.url, tools: Object.fromEntries(entry.tools) };
124
127
  }
125
-
126
- /** JSON with every object's keys sorted, at any depth. */
127
- export function canonical(value: unknown, indent?: number): string {
128
- return JSON.stringify(sortKeys(value), null, indent);
129
- }
130
-
131
- function sortKeys(value: unknown): unknown {
132
- if (Array.isArray(value)) return value.map(sortKeys);
133
- if (!isJsonObject(value)) return value;
134
- return Object.fromEntries(
135
- Object.keys(value)
136
- .sort()
137
- .map((key) => [key, sortKeys(value[key])]),
138
- );
139
- }
@@ -7,7 +7,8 @@
7
7
 
8
8
  import type { Action } from '@ultimat3/action';
9
9
  import { action } from '@ultimat3/action';
10
- import { finiteCount } from '@ultimat3/core';
10
+ import type { Clock } from '@ultimat3/core';
11
+ import { finiteCount, systemClock, throwIfAborted } from '@ultimat3/core';
11
12
  import type { OutboundFetch } from '@ultimat3/core/outbound';
12
13
  import type { KnownPermission } from '@ultimat3/policy';
13
14
  import { can } from '@ultimat3/policy';
@@ -40,8 +41,24 @@ export interface McpToolsDef {
40
41
  /** The longest answer handed to a model; the middle of a longer one is cut. Default 20,000. */
41
42
  readonly maxResultChars?: number;
42
43
  readonly fetch?: OutboundFetch;
44
+ /**
45
+ * Whether this app's OWN MCP surface (`include: 'exposed'`) and its in-app `agent()`s are offered
46
+ * these tools. Default `false`: an app that exposes them republishes a third party's tools on its
47
+ * own `/mcp` — a proxy, under the app's name and token. Opt in per remote server.
48
+ */
49
+ readonly expose?: boolean;
50
+ /**
51
+ * How long one verdict against the live server stands, in milliseconds. A remote that changes and
52
+ * announces nothing is held to the lock again once this has passed. Default 3,600,000 (an hour).
53
+ */
54
+ readonly reverifyMs?: number;
55
+ /** Where the re-verify window reads time. Default core's `systemClock`. */
56
+ readonly clock?: Clock;
43
57
  }
44
58
 
59
+ /** One hour: a remote that changes silently is caught within it, not at the next restart. */
60
+ const DEFAULT_REVERIFY_MS = 3_600_000;
61
+
45
62
  /** What a remote tool answers: its text, delimited as untrusted, and whether it reported an error. */
46
63
  export const RemoteToolOutput = t.object({ untrusted: t.string, isError: t.boolean });
47
64
 
@@ -72,6 +89,13 @@ export function declaredMcpServers(): ReadonlyMap<string, DeclaredMcpServer> {
72
89
 
73
90
  export function mcpTools(def: McpToolsDef): McpTools {
74
91
  const maxChars = finiteCount('mcpTools', 'maxResultChars', def.maxResultChars ?? 20_000, 1);
92
+ const reverifyMs = finiteCount(
93
+ 'mcpTools',
94
+ 'reverifyMs',
95
+ def.reverifyMs ?? DEFAULT_REVERIFY_MS,
96
+ 1,
97
+ );
98
+ const clock = def.clock ?? systemClock;
75
99
  const locked = readToolsLock(def.lock).get(def.name);
76
100
  const client = mcpClient({
77
101
  name: def.name,
@@ -90,10 +114,17 @@ export function mcpTools(def: McpToolsDef): McpTools {
90
114
  DECLARED.set(def.name, { name: def.name, url: def.url, allow: [...def.allow], client });
91
115
  // At declaration: an allowed tool the lock does not hold was never reviewed.
92
116
  assertLocked(def.name, locked, def.url, def.allow);
93
- // Checked against the live server once per process, before the first call goes out.
117
+ // Checked against the live server before the first call goes out, again on every announced change
118
+ // (`onToolsChanged`), and again once a verdict is `reverifyMs` old.
94
119
  let verified: Promise<readonly RemoteTool[]> | undefined;
120
+ let verifiedAt = 0;
95
121
  const check = (options: { readonly signal?: AbortSignal } = {}) => {
96
- verified ??= client.listTools(options).then((live) => {
122
+ if (verified !== undefined && clock.monotonic() - verifiedAt >= reverifyMs)
123
+ verified = undefined;
124
+ if (verified === undefined) verifiedAt = clock.monotonic();
125
+ // SHARED, so it carries no caller's signal: one caller leaving must not reject every caller
126
+ // that joined it. Bounded by the client's own `deadlineMs`; each caller races its own signal.
127
+ verified ??= client.listTools().then((live) => {
97
128
  assertLocked(def.name, locked, def.url, def.allow, live);
98
129
  return live;
99
130
  });
@@ -101,7 +132,7 @@ export function mcpTools(def: McpToolsDef): McpTools {
101
132
  verified.catch(() => {
102
133
  verified = undefined;
103
134
  });
104
- return verified;
135
+ return options.signal === undefined ? verified : raced(verified, options.signal);
105
136
  };
106
137
  const tools = new Map<string, RemoteToolAction>();
107
138
  for (const tool of def.allow) {
@@ -113,7 +144,9 @@ export function mcpTools(def: McpToolsDef): McpTools {
113
144
  output: RemoteToolOutput,
114
145
  policy: can(def.policy),
115
146
  mcp: {
116
- expose: true,
147
+ expose: def.expose === true,
148
+ // This app's own agents may use what it declared, published or not.
149
+ agents: true,
117
150
  // The LOCKED description, never the live one: what the model reads is what was reviewed.
118
151
  description: `[remote ${def.name}] ${entry.description}`,
119
152
  annotations: {
@@ -123,7 +156,11 @@ export function mcpTools(def: McpToolsDef): McpTools {
123
156
  },
124
157
  },
125
158
  async handle({ input, ctx }) {
126
- await check({ signal: ctx.signal });
159
+ await check({ signal: ctx.signal }).catch((error: unknown) => {
160
+ // The caller left: core's `X_ABORTED`, never the signal's raw reason.
161
+ throwIfAborted(ctx);
162
+ throw error;
163
+ });
127
164
  const args = typeof input === 'object' && input !== null ? input : {};
128
165
  const answer = await client.callTool(tool, args as Record<string, unknown>, {
129
166
  signal: ctx.signal,
@@ -141,12 +178,19 @@ export function actionNameFor(server: string, tool: string): string {
141
178
  return `${server}_${tool}`.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 64);
142
179
  }
143
180
 
181
+ /** Invisible format characters (zero-width space, word joiner, bidi marks): they split a tag. */
182
+ const FORMAT_CHARS = /\p{Cf}/gu;
183
+ /** `<`, and the two brackets a model reads as one: full-width `<` and small `﹤`. */
184
+ const OPENERS = /[<\uFF1C\uFE64]/g;
185
+
144
186
  /**
145
- * The remote's words inside a fence a model is told not to obey. A closing tag inside the text is
146
- * broken, so the remote cannot end the fence early and speak as the app.
187
+ * The remote's words inside a fence a model is told not to obey. Every bracket in the text is
188
+ * escaped (`&lt;`) after the format characters are stripped — no tag-shaped pattern to match, so
189
+ * no spelling of `</untrusted>` (case, whitespace, a zero-width space, a full-width `<`) can end
190
+ * the fence early and speak as the app, or open a forged one naming another source.
147
191
  */
148
192
  export function delimit(source: string, text: string, max: number): string {
149
- const body = truncate(text, max).replaceAll('</untrusted', '<\\/untrusted');
193
+ const body = truncate(text, max).replace(FORMAT_CHARS, '').replace(OPENERS, '&lt;');
150
194
  return `<untrusted source="${source}">\n${body}\n</untrusted>`;
151
195
  }
152
196
 
@@ -155,3 +199,22 @@ function truncate(text: string, max: number): string {
155
199
  const keep = Math.max(1, Math.floor((max - 40) / 2));
156
200
  return `${text.slice(0, keep)}\n…[${String(text.length - keep * 2)} characters cut]…\n${text.slice(-keep)}`;
157
201
  }
202
+
203
+ /** `shared`, or the caller's own abort — whichever settles first; the shared promise runs on. */
204
+ function raced<T>(shared: Promise<T>, signal: AbortSignal): Promise<T> {
205
+ if (signal.aborted) return Promise.reject(signal.reason);
206
+ return new Promise<T>((resolve, reject) => {
207
+ const leave = () => reject(signal.reason);
208
+ signal.addEventListener('abort', leave, { once: true });
209
+ shared.then(
210
+ (value) => {
211
+ signal.removeEventListener('abort', leave);
212
+ resolve(value);
213
+ },
214
+ (error: unknown) => {
215
+ signal.removeEventListener('abort', leave);
216
+ reject(error);
217
+ },
218
+ );
219
+ });
220
+ }
@@ -2,6 +2,7 @@
2
2
  // one audited, and every provider call inside a `try`. Split from `server.ts` for the size ceiling;
3
3
  // the server passes what it owns, so this stays a function and never a second dispatcher.
4
4
 
5
+ import { asCallerContext } from '@ultimat3/action';
5
6
  import type { ErrorAudience } from '@ultimat3/core';
6
7
  import { fixFor } from '@ultimat3/core';
7
8
  import type { McpAuditor } from './audit-hook';
@@ -93,8 +94,12 @@ export async function resourcesRead(
93
94
  // `toolsCall` uses above, for the same reason.
94
95
  try {
95
96
  // The resource the resolver admitted, read AS that caller: a per-caller source's resource is
96
- // in no fixed map, and a body may vary by who asked.
97
- const contents = await readResource(resolved.resource, caller);
97
+ // in no fixed map, and a body may vary by who asked. `ctx.actor` too, as a tool's `handle`
98
+ // gets it: a reader asking `useContext()` saw the HTTP request's actor (a cookie session's
99
+ // user), not the token's.
100
+ const contents = await asCallerContext(caller.actor, () =>
101
+ readResource(resolved.resource, caller),
102
+ );
98
103
  on.audit.resourceRead({ uri, outcome: 'ok', caller });
99
104
  return resultResponse(id, { contents: [contents] });
100
105
  } catch (error) {
@@ -4,7 +4,11 @@
4
4
 
5
5
  import { InputInvalidError } from '@ultimat3/action';
6
6
  import type { ErrorAudience } from '@ultimat3/core';
7
+ import { renderCauseValue } from '@ultimat3/core';
7
8
  import { formatIssues } from '@ultimat3/schema';
9
+ import type { McpCatalogDetail } from './meta-catalog-render';
10
+ import { McpSurfaceInvalidError } from './meta-errors';
11
+ import type { McpSurfaceOption } from './meta-surface';
8
12
  import type { McpCaller, McpToolResult } from './registry';
9
13
  import type { ArgIssue } from './validate-args';
10
14
 
@@ -15,6 +19,8 @@ export type McpInstructions = string | ((caller: McpCaller) => string | undefine
15
19
  export interface McpServerVoice {
16
20
  readonly instructions?: McpInstructions | undefined;
17
21
  readonly errorAudience: ErrorAudience;
22
+ /** How much of each action `list_resources` says — `McpServerInput.catalogDetail`. */
23
+ readonly catalogDetail?: McpCatalogDetail | undefined;
18
24
  }
19
25
 
20
26
  /** The instructions THIS caller is handed, or `undefined`. Fail-closed to none, never a throw. */
@@ -67,3 +73,26 @@ export function invalidArgsError(name: string, issues: readonly ArgIssue[]): Inp
67
73
  'tool',
68
74
  );
69
75
  }
76
+
77
+ /**
78
+ * `catalogDetail`, screened at boot: one of the two values, and only on a server some caller reads
79
+ * `list_resources` from — on a flat-only one it would shape a catalog nobody is served.
80
+ */
81
+ export function screenCatalogDetail(
82
+ detail: McpCatalogDetail | undefined,
83
+ surface: McpSurfaceOption | undefined,
84
+ ): McpCatalogDetail {
85
+ if (detail === undefined || detail === 'full') return 'full';
86
+ if (detail !== 'compact') {
87
+ throw new McpSurfaceInvalidError({
88
+ cause: `catalogDetail is ${renderCauseValue(detail)}; it is 'full' or 'compact'`,
89
+ });
90
+ }
91
+ if (surface === undefined || surface === 'flat') {
92
+ throw new McpSurfaceInvalidError({
93
+ cause:
94
+ "catalogDetail: 'compact' shapes list_resources, and surface is 'flat' for every caller, so no caller would ever read it",
95
+ });
96
+ }
97
+ return detail;
98
+ }
package/src/server.ts CHANGED
@@ -10,6 +10,7 @@ import type { McpAuditHook, McpAuditor } from './audit-hook';
10
10
  import { LOG_ONLY_AUDITOR, mcpAuditor } from './audit-hook';
11
11
  import { McpProtocolError, McpScopeDeniedError, TOOL_UNKNOWN_FIX } from './errors';
12
12
  import { metaCall } from './meta-call';
13
+ import type { McpCatalogDetail } from './meta-catalog-render';
13
14
  import { META_UNKNOWN_FIX } from './meta-errors';
14
15
  import type { McpResourceGroups, McpSurfaceOption, MetaResource } from './meta-surface';
15
16
  import { MetaSurface } from './meta-surface';
@@ -39,7 +40,7 @@ import type { CatalogRefused, CatalogView, McpCatalogSource, PerCall } from './s
39
40
  import { catalogRefusal, viewOf } from './server-catalog';
40
41
  import { resourcesRead } from './server-resources';
41
42
  import type { McpInstructions, McpServerVoice } from './server-voice';
42
- import { instructionsFor, invalidArgsResult } from './server-voice';
43
+ import { instructionsFor, invalidArgsResult, screenCatalogDetail } from './server-voice';
43
44
  import type { McpTenant } from './tenant';
44
45
  import { assertTenant, LIST_TENANTS, listTenantsTool, tenantStep, withTenantArg } from './tenant';
45
46
  import { admitted, thrownResponse } from './tool-thrown';
@@ -70,6 +71,11 @@ export interface McpServerInput {
70
71
  readonly surface?: McpSurfaceOption | undefined;
71
72
  /** The meta catalog's resources. Required with a surface that can be `'meta'`. */
72
73
  readonly groups?: McpResourceGroups | undefined;
74
+ /**
75
+ * How much of each action `list_resources` says: `'full'` (the default) or `'compact'` — names
76
+ * and tags, the rest in `describe_resource`. Needs a surface that can be `'meta'`.
77
+ */
78
+ readonly catalogDetail?: McpCatalogDetail | undefined;
73
79
  /**
74
80
  * `initialize`'s `instructions`: how to use this server, for a client that injects it into the
75
81
  * model's context (Claude Code does; many clients do not — never load-bear on it). A function
@@ -110,13 +116,18 @@ export function mcpServer(input: McpServerInput = {}): McpServer {
110
116
  groups: input.groups,
111
117
  tools: all,
112
118
  });
119
+ const catalogDetail = screenCatalogDetail(input.catalogDetail, input.surface);
113
120
  return new McpServer(
114
121
  tools,
115
122
  resources,
116
123
  input.prompts ?? [],
117
124
  input.serverInfo ?? defaultServerInfo(),
118
125
  meta,
119
- { instructions: input.instructions, errorAudience: input.errorAudience ?? 'developer' },
126
+ {
127
+ instructions: input.instructions,
128
+ errorAudience: input.errorAudience ?? 'developer',
129
+ catalogDetail,
130
+ },
120
131
  input.onAudit === undefined && input.clock === undefined
121
132
  ? LOG_ONLY_AUDITOR
122
133
  : mcpAuditor({ onAudit: input.onAudit, clock: input.clock }),
@@ -349,6 +360,7 @@ export class McpServer {
349
360
  {
350
361
  tools: view.tools,
351
362
  audit: this.audit,
363
+ catalogDetail: this.voice.catalogDetail ?? 'full',
352
364
  dispatch: (at, tool, resolved, who) => this.dispatch(at, tool, resolved, who),
353
365
  notFound: (at, tool, who, fix) => this.notFound(at, tool, who, fix),
354
366
  refuse: (at, tool, error, who) =>
package/src/tenant.ts CHANGED
@@ -5,6 +5,8 @@
5
5
  // the app's `resolve`, and the actor it answers IS the caller from there on — visibility, scope,
6
6
  // args, admit, confirmation, policy, `ctx.actor.orgId` — so the tenancy guards see one org per call.
7
7
  // A tenant the person is not in answers exactly as a hidden tool; a lookup that throws never does.
8
+ // The token's scopes and MCP role carry unchanged; the actor is `resolve`'s alone, so it may narrow.
9
+ // Only `tools/call` comes through here: every other method runs as the person, in no tenant.
8
10
 
9
11
  import type { Actor } from '@ultimat3/core';
10
12
  import { logger, renderCauseValue, renderThrowable } from '@ultimat3/core';
@@ -15,7 +17,7 @@ import {
15
17
  } from './catalog-errors';
16
18
  import { McpToolDuplicateError } from './errors';
17
19
  import type { AnyMcpTool, McpCaller, ToolListEntry } from './registry';
18
- import { jsonResult } from './registry';
20
+ import { jsonResult, withoutKey } from './registry';
19
21
  import type { JsonSchema } from './wire';
20
22
  import { NO_ARGS } from './wire';
21
23
 
@@ -33,7 +35,8 @@ export interface McpTenant {
33
35
  /**
34
36
  * The actor this person acts as in tenant `value`, or `null` when they are not a member — `null`
35
37
  * answers as a hidden tool. Must answer a `kind: 'agent'` actor; a throw is
36
- * `X_MCP_TENANT_UNRESOLVED`, never read as "not a member".
38
+ * `X_MCP_TENANT_UNRESOLVED`, never read as "not a member". The answer REPLACES the person's actor
39
+ * — no role of theirs is merged in — so this is where a tenant's authority is narrowed.
37
40
  */
38
41
  resolve(input: {
39
42
  readonly person: Actor;
@@ -151,13 +154,17 @@ export async function tenantStep(
151
154
  return unresolved(`tenant.resolve threw: ${renderThrowable(thrown)}`, thrown);
152
155
  }
153
156
  if (actor === null) return { kind: 'not-member' };
154
- if ((actor as { kind?: unknown }).kind !== 'agent') {
155
- return unresolved('tenant.resolve answered an actor that is not kind "agent"');
157
+ // `undefined` (a `Map.get` miss) is neither the member `null` nor an actor: reading `.kind` off
158
+ // it threw a TypeError out of the step.
159
+ if (typeof actor !== 'object' || (actor as { kind?: unknown }).kind !== 'agent') {
160
+ return unresolved(
161
+ 'tenant.resolve answered something that is not an actor of kind "agent", nor null',
162
+ );
156
163
  }
157
164
  return {
158
165
  kind: 'ok',
159
166
  caller: { ...caller, actor, tenant: value },
160
- args: without(args, tenant.arg),
167
+ args: withoutKey(args, tenant.arg),
161
168
  };
162
169
  }
163
170
 
@@ -170,20 +177,5 @@ function unresolved(cause: string, thrown?: unknown): TenantStep {
170
177
  return { kind: 'refused', error };
171
178
  }
172
179
 
173
- /** A copy without `key`, every other key landed through `defineProperty` (`__proto__` included). */
174
- function without(args: Readonly<Record<string, unknown>>, key: string): Record<string, unknown> {
175
- const out: Record<string, unknown> = {};
176
- for (const [name, value] of Object.entries(args)) {
177
- if (name === key) continue;
178
- Object.defineProperty(out, name, {
179
- value,
180
- enumerable: true,
181
- writable: true,
182
- configurable: true,
183
- });
184
- }
185
- return out;
186
- }
187
-
188
180
  const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
189
181
  typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -80,6 +80,7 @@ export type McpRateLimits = Readonly<Record<McpVerbClass, number>> & {
80
80
 
81
81
  /** What a token resolves to. `null` = unauthenticated, answered 401 with no catalog. */
82
82
  export interface ResolvedToken {
83
+ /** The actor half. Per-call tenancy is NOT here: a `tenant` option on the server refines the actor per call, server-side. */
83
84
  readonly actor: Actor;
84
85
  readonly scopes: ReadonlySet<string>;
85
86
  readonly role?: McpRole;