@ultimat3/mcp 31.48.0 → 31.50.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.
@@ -0,0 +1,167 @@
1
+ // `tenant.discover` and `tenant.optional`: the calls a `tenant` server answers with no tenant named.
2
+ //
3
+ // By default one tool does, `list_tenants`. `discover` names a tool the server already serves to
4
+ // take its place — called without `tenant.arg` it answers `tenant.list`, called with it it is the
5
+ // tool it always was — so the tool list keeps its size. `optional` names tools that run as the
6
+ // PERSON without the arg and as the tenant actor with it. Both are boot-checked: a name no caller
7
+ // could reach would leave `X_MCP_TENANT_REQUIRED` pointing at nothing.
8
+
9
+ import { isJsonObject, renderCauseValue } from '@ultimat3/core';
10
+ import { McpTenantInvalidError } from './catalog-errors';
11
+ import type { McpResourceGroups, McpSurfaceOption } from './meta-surface';
12
+ import { LIST_RESOURCES, META_TOOL_NAMES } from './meta-surface';
13
+ import type { AnyMcpTool, McpCaller, ToolResolution } from './registry';
14
+
15
+ /** The tool a `tenant` server registers to list tenants when `discover` names no other. */
16
+ export const LIST_TENANTS = 'list_tenants';
17
+
18
+ /** The half of `McpTenant` this file reads. */
19
+ export interface TenantDoors {
20
+ readonly arg: string;
21
+ readonly discover?: string | undefined;
22
+ readonly optional?: readonly string[] | undefined;
23
+ }
24
+
25
+ /** The meta declaration the discover and optional names are checked against. */
26
+ export interface TenantSurface {
27
+ readonly surface?: McpSurfaceOption | undefined;
28
+ readonly groups?: McpResourceGroups | undefined;
29
+ /** The dispatcher envelopes' own fields: the arg is stripped from those too. */
30
+ readonly split?: { readonly fields?: Readonly<Record<string, unknown>> | undefined } | undefined;
31
+ }
32
+
33
+ /**
34
+ * How one call meets the tenant step. `'tenants'`: answer the tenant list. `'person'`: run the
35
+ * tool as the person, in no tenant. `'step'`: the call names its tenant, or is refused.
36
+ */
37
+ export type TenantDoor = 'tenants' | 'person' | 'step';
38
+
39
+ /** The tool that lists this server's tenants: what `X_MCP_TENANT_REQUIRED` points at. */
40
+ export const tenantLister = (tenant: TenantDoors): string => tenant.discover ?? LIST_TENANTS;
41
+
42
+ /**
43
+ * Only an ABSENT arg opens a door. One that is present and unusable (`''`, `null`, a number) goes
44
+ * to the step and is refused there: a malformed tenant never quietly becomes "no tenant".
45
+ */
46
+ export function tenantDoor(tenant: TenantDoors, name: string, rawArgs: unknown): TenantDoor {
47
+ // `list_tenants` takes no tenant whatever it is sent, as it always did.
48
+ if (tenant.discover === undefined && name === LIST_TENANTS) return 'person';
49
+ const named =
50
+ isJsonObject(rawArgs) &&
51
+ Object.hasOwn(rawArgs, tenant.arg) &&
52
+ rawArgs[tenant.arg] !== undefined;
53
+ if (named) return 'step';
54
+ if (name === tenant.discover) return 'tenants';
55
+ return tenant.optional?.includes(name) === true ? 'person' : 'step';
56
+ }
57
+
58
+ const FIX =
59
+ "defineAppMcp({ tenant: { arg, resolve, list, discover: 'list_resources', optional: ['docs'] } }) — discover names list_resources (surface: 'meta' or 'meta-split', never a function) or an ungrouped tool of tools: with no visibleTo; optional names ungrouped tools of tools: — or drop the option the cause names";
60
+
61
+ function refuse(cause: string): never {
62
+ throw new McpTenantInvalidError({ cause, fix: FIX });
63
+ }
64
+
65
+ /** Boot: `discover` and `optional` each name a tool every caller reaches by that name. */
66
+ export function assertTenantDoors(
67
+ tenant: TenantDoors,
68
+ tools: readonly AnyMcpTool[],
69
+ meta: TenantSurface,
70
+ ): void {
71
+ if (Object.hasOwn(meta.split?.fields ?? {}, tenant.arg)) {
72
+ throw new McpTenantInvalidError({
73
+ cause: `split.fields declares "${tenant.arg}", which tenant.arg strips from every call`,
74
+ });
75
+ }
76
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
77
+ const grouped = new Set(Object.values(meta.groups ?? {}).flatMap((group) => group.tools));
78
+ const discover: unknown = tenant.discover;
79
+ if (discover !== undefined) assertDiscover(discover, byName, grouped, meta.surface);
80
+ const optional: unknown = tenant.optional;
81
+ if (optional === undefined) return;
82
+ if (!Array.isArray(optional)) {
83
+ refuse(
84
+ `tenant.optional is ${renderCauseValue(optional)}, and it has to be a list of tool names`,
85
+ );
86
+ }
87
+ const seen = new Set<unknown>();
88
+ for (const name of optional as readonly unknown[]) {
89
+ const shown = renderCauseValue(name);
90
+ if (seen.has(name)) refuse(`tenant.optional names ${shown} twice`);
91
+ seen.add(name);
92
+ if (name === discover) {
93
+ refuse(
94
+ `tenant.optional names ${shown}, which is tenant.discover: with no tenant it answers the tenant list`,
95
+ );
96
+ }
97
+ assertUngrouped('tenant.optional', name, byName, grouped);
98
+ }
99
+ }
100
+
101
+ function assertDiscover(
102
+ discover: unknown,
103
+ tools: ReadonlyMap<string, AnyMcpTool>,
104
+ grouped: ReadonlySet<string>,
105
+ surface: McpSurfaceOption | undefined,
106
+ ): void {
107
+ const shown = renderCauseValue(discover);
108
+ if (typeof discover === 'string' && META_TOOL_NAMES.includes(discover)) {
109
+ if (discover !== LIST_RESOURCES) {
110
+ refuse(
111
+ `tenant.discover names ${shown}, and the one meta tool that can list tenants is "${LIST_RESOURCES}"`,
112
+ );
113
+ }
114
+ // A function serves some callers 'flat', and they would have no tool to list their tenants.
115
+ if (surface !== 'meta' && surface !== 'meta-split') {
116
+ refuse(
117
+ `tenant.discover names ${shown}, and surface is not 'meta' or 'meta-split' for every caller, so some caller is never served that tool`,
118
+ );
119
+ }
120
+ return;
121
+ }
122
+ const tool = assertUngrouped('tenant.discover', discover, tools, grouped);
123
+ // The tenant list is answered in the tool's place: its scope is still asked, but a caller it is
124
+ // hidden from would be pointed at a tool it cannot see.
125
+ if (tool.visibleTo !== undefined) {
126
+ refuse(
127
+ `tenant.discover names ${shown}, which declares visibleTo: a caller it is hidden from could not list its tenants`,
128
+ );
129
+ }
130
+ }
131
+
132
+ /**
133
+ * A call of the discover tool that names no tenant, resolved: `lister` runs in its place, behind
134
+ * the scope the tool itself declares — the one gate of its own a boot check has not ruled out.
135
+ */
136
+ export function tenantsCall(
137
+ lister: AnyMcpTool,
138
+ discover: AnyMcpTool | undefined,
139
+ name: string,
140
+ caller: McpCaller,
141
+ ): ToolResolution {
142
+ const scope = discover?.scope;
143
+ return scope !== undefined && !caller.scopes.has(scope)
144
+ ? { kind: 'scope-denied', name, scope }
145
+ : { kind: 'ok', tool: lister, args: {} };
146
+ }
147
+
148
+ function assertUngrouped(
149
+ option: string,
150
+ name: unknown,
151
+ tools: ReadonlyMap<string, AnyMcpTool>,
152
+ grouped: ReadonlySet<string>,
153
+ ): AnyMcpTool {
154
+ const shown = renderCauseValue(name);
155
+ const tool = typeof name === 'string' ? tools.get(name) : undefined;
156
+ if (tool === undefined) {
157
+ return refuse(
158
+ `${option} names ${shown}, which is not a tool of this server's tools: (a per-caller catalog tool and a meta dispatcher cannot be named)`,
159
+ );
160
+ }
161
+ if (grouped.has(tool.name)) {
162
+ return refuse(
163
+ `${option} names ${shown}, which a group lists: a grouped tool is reached through a dispatcher, never by its name`,
164
+ );
165
+ }
166
+ return tool;
167
+ }
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: