@ultimat3/mcp 31.49.0 → 31.51.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.
package/src/tenant.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  // A tenant the person is not in answers exactly as a hidden tool; a lookup that throws never does.
8
8
  // The token's scopes and MCP role carry unchanged; the actor is `resolve`'s alone, so it may narrow.
9
9
  // Only `tools/call` comes through here: every other method runs as the person, in no tenant.
10
+ // Which calls may name no tenant at all is `tenant-discover.ts`.
10
11
 
11
12
  import type { Actor } from '@ultimat3/core';
12
13
  import { isJsonObject, logger, renderCauseValue, renderThrowable } from '@ultimat3/core';
@@ -18,6 +19,8 @@ import {
18
19
  import { McpToolDuplicateError } from './errors';
19
20
  import type { AnyMcpTool, McpCaller, ToolListEntry } from './registry';
20
21
  import { jsonResult, withoutKey } from './registry';
22
+ import type { TenantSurface } from './tenant-discover';
23
+ import { assertTenantDoors, LIST_TENANTS, tenantLister } from './tenant-discover';
21
24
  import type { JsonSchema } from './wire';
22
25
  import { NO_ARGS } from './wire';
23
26
 
@@ -42,22 +45,47 @@ export interface McpTenant {
42
45
  readonly person: Actor;
43
46
  readonly value: string;
44
47
  }): Promise<Actor | null> | Actor | null;
45
- /** The tenants this person may name, served by `list_tenants` — what `X_MCP_TENANT_REQUIRED` points at. */
48
+ /**
49
+ * The tenants this person may name, served by `list_tenants` (or the `discover` tool) — what
50
+ * `X_MCP_TENANT_REQUIRED` points at.
51
+ */
46
52
  list(input: {
47
53
  readonly person: Actor;
48
54
  }): Promise<readonly McpTenantEntry[]> | readonly McpTenantEntry[];
55
+ /**
56
+ * The tool that lists the tenants IN PLACE of `list_tenants`, which is then not registered, so
57
+ * the tool list keeps its size: `'list_resources'` (on a surface that is `'meta'` or
58
+ * `'meta-split'` for every caller) or an ungrouped tool of `tools:` with no `visibleTo`. A call
59
+ * of it naming no tenant answers `list` as the person, behind the tool's own scope and whatever
60
+ * else it sends; a call naming one runs the tool itself, in that tenant. Refused at boot
61
+ * otherwise (`X_MCP_TENANT_INVALID`).
62
+ */
63
+ readonly discover?: string;
64
+ /**
65
+ * Ungrouped tools of `tools:` a call may reach with no tenant: they then run as the PERSON —
66
+ * no `orgId`, `caller.tenant` absent — and as the tenant actor when the call names one. A
67
+ * server's own manual (`docs`), an identity tool. Refused at boot for a name that is not such a
68
+ * tool (`X_MCP_TENANT_INVALID`).
69
+ */
70
+ readonly optional?: readonly string[];
49
71
  }
50
72
 
51
- /** The one tool a `tenant` server answers without a tenant: how a caller learns its tenants. */
52
- export const LIST_TENANTS = 'list_tenants';
73
+ export { LIST_TENANTS } from './tenant-discover';
53
74
 
54
75
  const ARG_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
55
76
 
56
77
  /** A value longer than this names no tenant anyone issues; refused without asking `resolve`. */
57
78
  const MAX_TENANT_VALUE = 256;
58
79
 
59
- /** Boot: the arg is a plain name no tool's input declares, and `list_tenants` is not taken. */
60
- export function assertTenant(tenant: McpTenant, tools: readonly AnyMcpTool[]): void {
80
+ /**
81
+ * Boot: the arg is a plain name no tool's input declares, `list_tenants` is not taken while the
82
+ * server registers it, and `discover` / `optional` name tools every caller reaches.
83
+ */
84
+ export function assertTenant(
85
+ tenant: McpTenant,
86
+ tools: readonly AnyMcpTool[],
87
+ meta: TenantSurface = {},
88
+ ): void {
61
89
  const arg: unknown = tenant.arg;
62
90
  if (typeof arg !== 'string' || !ARG_NAME.test(arg)) {
63
91
  throw new McpTenantInvalidError({
@@ -65,9 +93,12 @@ export function assertTenant(tenant: McpTenant, tools: readonly AnyMcpTool[]): v
65
93
  });
66
94
  }
67
95
  for (const tool of tools) {
68
- if (tool.name === LIST_TENANTS) throw new McpToolDuplicateError({ name: LIST_TENANTS });
96
+ if (tenant.discover === undefined && tool.name === LIST_TENANTS) {
97
+ throw new McpToolDuplicateError({ name: LIST_TENANTS });
98
+ }
69
99
  assertArgFree(arg, tool);
70
100
  }
101
+ assertTenantDoors(tenant, tools, meta);
71
102
  }
72
103
 
73
104
  /** The arg is stripped from every call, so a tool declaring it would never receive it. */
@@ -79,8 +110,13 @@ export function assertArgFree(arg: string, tool: AnyMcpTool): void {
79
110
  }
80
111
  }
81
112
 
82
- /** `list_tenants`: the person's own tenants, nothing else — no scope, no tenant. */
113
+ /**
114
+ * The person's own tenants, nothing else — no scope, no tenant. Registered as `list_tenants`, or
115
+ * run in place of the `discover` tool when a call of it names no tenant: that answer also says
116
+ * how to name one, since the tool's own description is about something else.
117
+ */
83
118
  export function listTenantsTool(tenant: McpTenant): AnyMcpTool {
119
+ const discover = tenant.discover;
84
120
  return {
85
121
  name: LIST_TENANTS,
86
122
  title: 'List tenants',
@@ -95,35 +131,69 @@ export function listTenantsTool(tenant: McpTenant): AnyMcpTool {
95
131
  value: entry.value,
96
132
  ...(entry.name === undefined ? {} : { name: entry.name }),
97
133
  })),
134
+ ...(discover === undefined
135
+ ? {}
136
+ : { next: `${discover}({ "${tenant.arg}": "<one of the values>" })` }),
98
137
  });
99
138
  },
100
139
  };
101
140
  }
102
141
 
103
- /** `tools/list` with the tenant arg published on every tool but `list_tenants` — never in a tool's own schema. */
142
+ /**
143
+ * `tools/list` with the tenant arg published — never in a tool's own schema — and required only
144
+ * where a call without it is refused: not on `list_tenants` (which takes none), the `discover`
145
+ * tool or an `optional` one.
146
+ */
104
147
  export function withTenantArg(
105
148
  entries: readonly ToolListEntry[],
106
- arg: string,
149
+ tenant: McpTenant,
107
150
  ): readonly ToolListEntry[] {
108
- return entries.map((entry) =>
109
- entry.name === LIST_TENANTS
110
- ? entry
111
- : { ...entry, inputSchema: published(entry.inputSchema, arg) },
112
- );
151
+ const lister = tenantLister(tenant);
152
+ const from = `The tenant this call acts in: a value from ${lister}.`;
153
+ return entries.map((entry) => {
154
+ if (entry.name === lister) {
155
+ return tenant.discover === undefined
156
+ ? entry
157
+ : {
158
+ ...entry,
159
+ inputSchema: published(
160
+ entry.inputSchema,
161
+ tenant.arg,
162
+ 'The tenant this call acts in. Omit it to list the tenants this caller may act in.',
163
+ false,
164
+ ),
165
+ };
166
+ }
167
+ return tenant.optional?.includes(entry.name) === true
168
+ ? {
169
+ ...entry,
170
+ inputSchema: published(
171
+ entry.inputSchema,
172
+ tenant.arg,
173
+ `${from} Optional here: without it the call acts in no tenant.`,
174
+ false,
175
+ ),
176
+ }
177
+ : { ...entry, inputSchema: published(entry.inputSchema, tenant.arg, from, true) };
178
+ });
113
179
  }
114
180
 
115
- function published(schema: JsonSchema, arg: string): JsonSchema {
181
+ function published(
182
+ schema: JsonSchema,
183
+ arg: string,
184
+ description: string,
185
+ required: boolean,
186
+ ): JsonSchema {
116
187
  const properties: Record<string, JsonSchema> = { ...schema.properties };
117
188
  Object.defineProperty(properties, arg, {
118
- value: {
119
- type: 'string',
120
- description: `The tenant this call acts in: a value from ${LIST_TENANTS}.`,
121
- },
189
+ value: { type: 'string', description },
122
190
  enumerable: true,
123
191
  writable: true,
124
192
  configurable: true,
125
193
  });
126
- return { ...schema, properties, required: [...(schema.required ?? []), arg] };
194
+ return required
195
+ ? { ...schema, properties, required: [...(schema.required ?? []), arg] }
196
+ : { ...schema, properties };
127
197
  }
128
198
 
129
199
  /** One call's tenant step. `not-member` is answered exactly as a hidden tool. */
@@ -144,7 +214,10 @@ export async function tenantStep(
144
214
  const args = isJsonObject(rawArgs) ? rawArgs : {};
145
215
  const value = Object.hasOwn(args, tenant.arg) ? args[tenant.arg] : undefined;
146
216
  if (typeof value !== 'string' || value.length === 0) {
147
- return { kind: 'refused', error: new McpTenantRequiredError({ arg: tenant.arg }) };
217
+ return {
218
+ kind: 'refused',
219
+ error: new McpTenantRequiredError({ arg: tenant.arg, lister: tenantLister(tenant) }),
220
+ };
148
221
  }
149
222
  if (value.length > MAX_TENANT_VALUE) return { kind: 'not-member' };
150
223
  let actor: Actor | null;
@@ -0,0 +1,153 @@
1
+ // URL-mode elicitation on a JSON answer (MCP 2026-07-28, `client/elicitation`, `basic/patterns/
2
+ // mrtr`): how a tool says "the person must open this page", and what one `tools/call` answers for
3
+ // it. A modern request that declared `elicitation.url` gets an `InputRequiredResult`; every other
4
+ // caller gets the tool's `content`. Stateless: no `requestState` goes out, so none is trusted back.
5
+
6
+ import { asyncContext, isJsonObject, UltimateError } from '@ultimat3/core';
7
+ // why a side-effect import: the code this class raises is REGISTERED by `errors.ts`.
8
+ import './errors';
9
+ import { eraOf } from './protocol-era';
10
+ import type { McpToolResult, McpUrlElicitation } from './registry';
11
+ import type { JsonRpcRequest } from './wire';
12
+ import { META_CLIENT_CAPABILITIES, paramsOf } from './wire';
13
+
14
+ /** The one key of `inputRequests`, and the key a retry answers under in `inputResponses`. */
15
+ export const URL_ELICITATION_KEY = 'url_elicitation';
16
+
17
+ /** Why an ask is refused — a reason, never the value: the URL may be the secret it must not hold. */
18
+ type AskDefect = 'shape' | 'message' | 'url' | 'scheme' | 'credentials';
19
+
20
+ const DEFECT: Readonly<Record<AskDefect, string>> = {
21
+ shape: 'is not an object with a string url and a string message',
22
+ message: 'has an empty message, so the person would be shown a URL and no reason',
23
+ url: 'has a url that is not an absolute URL',
24
+ scheme: 'has a url that is neither https nor http on this machine',
25
+ credentials: 'has a url carrying a username or password',
26
+ };
27
+
28
+ export class McpElicitationUrlError extends UltimateError {
29
+ constructor(input: { defect: AskDefect }) {
30
+ super({
31
+ code: 'X_MCP_ELICITATION_URL_INVALID',
32
+ cause: `a tool asked for a URL prompt that ${DEFECT[input.defect]}`,
33
+ fix: "withUrlElicitation(output, { url: new URL('/connect', appOrigin).href, message: 'Open this page to finish connecting.' }) // in a hand-built McpTool, the same value as the result's urlElicitation field; an absolute https URL (http only on localhost, 127.0.0.1 or [::1]), no user:password@, a non-empty message",
34
+ callerFix:
35
+ 'this is a fault in the tool, not in the call: report it to the server operator, and do not retry — the same call is refused the same way',
36
+ meta: { defect: input.defect },
37
+ });
38
+ }
39
+ }
40
+
41
+ const LOOPBACK: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);
42
+
43
+ /**
44
+ * The ask, checked: the spec's server rules that can be read off the value. The URL must be valid;
45
+ * it should be https outside development; it must not carry credentials. What cannot be read off
46
+ * it stays the app's: nothing about the person in it, and the page it names verifies who opened it.
47
+ */
48
+ function checked(ask: unknown): McpUrlElicitation {
49
+ if (!isJsonObject(ask) || typeof ask['url'] !== 'string' || typeof ask['message'] !== 'string') {
50
+ throw new McpElicitationUrlError({ defect: 'shape' });
51
+ }
52
+ const { url, message } = ask;
53
+ if (message.trim() === '') throw new McpElicitationUrlError({ defect: 'message' });
54
+ if (!URL.canParse(url)) throw new McpElicitationUrlError({ defect: 'url' });
55
+ const parsed = new URL(url);
56
+ const local = parsed.protocol === 'http:' && LOOPBACK.has(parsed.hostname);
57
+ if (parsed.protocol !== 'https:' && !local)
58
+ throw new McpElicitationUrlError({ defect: 'scheme' });
59
+ if (parsed.username !== '' || parsed.password !== '') {
60
+ throw new McpElicitationUrlError({ defect: 'credentials' });
61
+ }
62
+ // The parsed spelling: `https:app.test/x` passes the parser by repair, and a client resolving
63
+ // the raw string as a link could land somewhere the check never saw.
64
+ return { url: parsed.href, message };
65
+ }
66
+
67
+ /** The ask of the tool call in flight, if its handler made one. */
68
+ interface CallAsk {
69
+ ask: McpUrlElicitation | undefined;
70
+ }
71
+
72
+ // Scoped to the invocation, never keyed on the returned value: an action's output is parsed into a
73
+ // copy before the projection sees it, and an object a handler returns on every call would carry
74
+ // one caller's ask into the next caller's answer.
75
+ const inFlight = asyncContext<CallAsk>('the URL elicitation of a tool call');
76
+
77
+ /**
78
+ * From a tool's or an action's handler: `return withUrlElicitation(output, { url, message })`.
79
+ * `output` is returned as it is and must still say, in its own fields, what the person has to do —
80
+ * it is the whole answer for every client that cannot show the prompt. The ask belongs to the MCP
81
+ * call running the handler; outside one (the HTTP route of the same action) it is checked and
82
+ * otherwise ignored. The client retries the call after the person answers, so the handler runs again.
83
+ */
84
+ export function withUrlElicitation<T extends object>(output: T, ask: McpUrlElicitation): T {
85
+ const valid = checked(ask);
86
+ const call = inFlight.get();
87
+ if (call !== undefined) call.ask = valid;
88
+ return output;
89
+ }
90
+
91
+ /** Run one tool call's handler; the ask it made, if any, comes back beside its value. */
92
+ export async function withCallAsk<T>(
93
+ fn: () => Promise<T>,
94
+ ): Promise<{ readonly value: T; readonly ask: McpUrlElicitation | undefined }> {
95
+ const call: CallAsk = { ask: undefined };
96
+ const value = await inFlight.run(call, fn);
97
+ return { value, ask: call.ask };
98
+ }
99
+
100
+ /** `elicitation.url` is an object on THIS request. `elicitation: {}` is form mode only. */
101
+ function declaresUrlMode(params: Record<string, unknown> | null): boolean {
102
+ const meta = params === null ? undefined : own(params, '_meta');
103
+ const capabilities = isJsonObject(meta) ? own(meta, META_CLIENT_CAPABILITIES) : undefined;
104
+ const elicitation = isJsonObject(capabilities) ? own(capabilities, 'elicitation') : undefined;
105
+ return isJsonObject(elicitation) && isJsonObject(own(elicitation, 'url'));
106
+ }
107
+
108
+ const ACTIONS: ReadonlySet<unknown> = new Set(['accept', 'decline', 'cancel']);
109
+
110
+ /**
111
+ * The retry already carries the person's answer. Asked once per call, whatever the answer: accept
112
+ * is consent to open the page, not proof the page was finished, and only the tool's own rerun
113
+ * knows which — so the rerun's `content` is the answer, and a decline is never asked again.
114
+ */
115
+ function answered(params: Record<string, unknown> | null): boolean {
116
+ const responses = params === null ? undefined : own(params, 'inputResponses');
117
+ const response = isJsonObject(responses) ? own(responses, URL_ELICITATION_KEY) : undefined;
118
+ return isJsonObject(response) && ACTIONS.has(own(response, 'action'));
119
+ }
120
+
121
+ /** An OWN member: the request is a caller's JSON, and a prototype is not something it sent. */
122
+ const own = (value: Record<string, unknown>, key: string): unknown =>
123
+ Object.hasOwn(value, key) ? value[key] : undefined;
124
+
125
+ /**
126
+ * What `tools/call` answers instead of the tool's result, or `undefined` for "the result itself".
127
+ * Throws `X_MCP_ELICITATION_URL_INVALID` for a bad ask whoever called: a fault that showed only
128
+ * to a capable client would ship unseen. A tool that failed is not asked about at all: its
129
+ * failure is the answer, and a malformed ask beside it must not replace it.
130
+ *
131
+ * Legacy revisions get the plain answer. 2025-11-25 defines `URLElicitationRequiredError`
132
+ * (`-32042`) for a JSON answer, but its capability is declared once, on `initialize`, and this
133
+ * server keeps no handshake — and a server MUST NOT send a mode the client did not declare.
134
+ */
135
+ export function inputRequiredFor(
136
+ request: JsonRpcRequest,
137
+ result: McpToolResult,
138
+ ): Record<string, unknown> | undefined {
139
+ // A tool that failed answers its failure: a prompt — or a refused prompt — would hide it.
140
+ if (result.urlElicitation === undefined || result.isError === true) return undefined;
141
+ const ask = checked(result.urlElicitation);
142
+ const params = paramsOf(request);
143
+ if (eraOf(request) !== 'modern' || !declaresUrlMode(params) || answered(params)) return undefined;
144
+ return {
145
+ resultType: 'input_required',
146
+ inputRequests: {
147
+ [URL_ELICITATION_KEY]: {
148
+ method: 'elicitation/create',
149
+ params: { mode: 'url', url: ask.url, message: ask.message },
150
+ },
151
+ },
152
+ };
153
+ }
package/src/wire.ts CHANGED
@@ -20,6 +20,8 @@ export const MCP_LEGACY_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26'] as
20
20
  /** The `_meta` keys a modern request and result carry. */
21
21
  export const META_PROTOCOL_VERSION = 'io.modelcontextprotocol/protocolVersion';
22
22
  export const META_SERVER_INFO = 'io.modelcontextprotocol/serverInfo';
23
+ /** Where a modern request declares what its client can do: there is no handshake to keep it. */
24
+ export const META_CLIENT_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities';
23
25
 
24
26
  /**
25
27
  * Identity advertised on `initialize` unless the host overrides it. A call and not a constant: