@jini-ai/mcp 0.6.19 → 0.6.22

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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @jini-ai/mcp
2
2
 
3
+ ## 0.6.22
4
+
5
+ - Owner grant changes reuse the connection's original tool snapshot (`federation/frozen-grants`). Delegated tool input envelopes are decoded only where the tool's schema calls for it.
6
+
3
7
  ## 0.6.19
4
8
 
5
9
  - Redact config/token parsing and federation bootstrap exception diagnostics.
@@ -3,7 +3,7 @@ import type { ToolRegistry } from "@jini-ai/core";
3
3
  import type { ResolvedFederatedConnection } from "./config.js";
4
4
  import type { McpSessionPort } from "./ports.js";
5
5
  import { type FederatedMcpPresetRegistry } from "./presets.js";
6
- import { type FederationDeps } from "./registrations.js";
6
+ import { type FederationDeps, type buildFederatedMcpRegistrations } from "./registrations.js";
7
7
  import type { FederatedAdmissionReport } from "./trust.js";
8
8
  export interface AttachFederatedToolsResult {
9
9
  /** Ids actually registered. Empty when federation is off or every attempt failed. */
@@ -74,6 +74,8 @@ export interface AttachFederatedToolsResult {
74
74
  * @complexity O(c · t) in connections and their advertised tools.
75
75
  */
76
76
  export interface AttachFederatedMcpToolsParams {
77
+ /** Host approval adapter, replayed against frozen definitions when the owner's grants change. */
78
+ readonly buildRegistrations?: typeof buildFederatedMcpRegistrations;
77
79
  readonly presetRegistry?: FederatedMcpPresetRegistry;
78
80
  registry: ToolRegistry;
79
81
  deps: FederationDeps;
@@ -3,6 +3,7 @@ import { redactSecrets } from '@jini-ai/core';
3
3
  import { createConsoleLogger } from "@jini-ai/core/primitives";
4
4
  import { defaultFederatedMcpPresetRegistry } from "./presets.js";
5
5
  import { federateSession } from "./registrations.js";
6
+ import { registerFrozenFederationConnection } from './frozen-grants.js';
6
7
  /**
7
8
  * @file The composition root for outbound MCP federation: the one function
8
9
  * `agent-daemon-server.ts` calls, and the only place in this subtree that performs I/O it was not
@@ -75,7 +76,7 @@ export async function attachFederatedMcpTools(requiredArgs, optionalArgs = {}) {
75
76
  const reports = [];
76
77
  const connectFailures = [];
77
78
  for (const { connection, isPreset } of connections) {
78
- const attached = await attachOneFederatedConnection({ connection, registry: params.registry, deps: params.deps, connect, logger });
79
+ const attached = await attachOneFederatedConnection({ connection, registry: params.registry, deps: params.deps, connect, logger, ...(params.buildRegistrations ? { buildRegistrations: params.buildRegistrations } : {}) });
79
80
  registeredToolIds.push(...attached.registeredToolIds);
80
81
  if (attached.session)
81
82
  sessions.push(attached.session);
@@ -99,6 +100,16 @@ function registerFederatedTools(registry, registrations) {
99
100
  }
100
101
  return registeredToolIds;
101
102
  }
103
+ /** R5 freezes definitions, not owner grants. A nonempty roster source uses the core's existing
104
+ * scope so owner changes can hide/restore it and admit other originally listed tools. Empty
105
+ * grants still close below; their first grant retains the existing fresh-admission path.
106
+ * @complexity O(t) in the source's original tool listing; no I/O.
107
+ */
108
+ function registerConnectedFederatedTools({ registry, session, config, deps, registrations, frozenTools, buildRegistrations }) {
109
+ if (config.origin?.kind !== 'roster' || config.allowedToolNames.length === 0 || !frozenTools)
110
+ return registerFederatedTools(registry, registrations);
111
+ return registerFrozenFederationConnection({ registry, session, config, deps, tools: frozenTools, registrations }, buildRegistrations ? { buildRegistrations } : {});
112
+ }
102
113
  /** Logs one connection's full admission accounting. Refusals are reported, never silent —
103
114
  * `buildDomainRegistrations`'s own "silence is never the outcome" discipline. An operator
104
115
  * debugging a missing tool needs the reason, and an operator reading logs after an incident needs
@@ -140,8 +151,8 @@ async function attachOneFederatedConnection(params) {
140
151
  // Snapshotted here, immediately before the admission check, so the collision assertion sees
141
152
  // every native tool AND every tool an earlier connection in this same loop already claimed.
142
153
  const nativeToolIds = new Set(registry.list({}).map((descriptor) => descriptor.id));
143
- const { registrations, report } = await federateSession({ session, config: connection.config, deps, nativeToolIds });
144
- const registeredToolIds = registerFederatedTools(registry, registrations);
154
+ const { registrations, report, frozenTools } = await federateSession({ session, config: connection.config, deps, nativeToolIds, ...(params.buildRegistrations ? { buildRegistrations: params.buildRegistrations } : {}) });
155
+ const registeredToolIds = registerConnectedFederatedTools({ registry, session, config: connection.config, deps, registrations, frozenTools, buildRegistrations: params.buildRegistrations });
145
156
  logger.info({ message: `mcp-federation: '${connectionId}' registered ${registrations.length} federated tool(s): ${registrations.map((r) => r.descriptor.id).join(", ") || "(none)"}` });
146
157
  logFederatedAdmissionReport(connectionId, report, logger);
147
158
  // An empty grant has no callable handler retaining this session. Release its child/socket
@@ -0,0 +1,37 @@
1
+ /** Owner grant changes reuse the connection's original untrusted tool snapshot (R5). */
2
+ import { type ToolRegistry, type ToolRegistration } from '@jini-ai/core';
3
+ import type { ResolvedFederatedConnection } from './config.js';
4
+ import type { McpSessionPort, RemoteToolDescriptor, FederatedMcpConnectionConfig } from './ports.js';
5
+ import type { FederatedAdmissionReport } from './trust.js';
6
+ import { buildFederatedMcpRegistrations, type FederationDeps } from './registrations.js';
7
+ /** Register one roster source in the existing core revocation scope and retain its first listing.
8
+ * @returns Registered tool ids; remote snapshots stay private to this registry's lifetime.
9
+ * @throws Core scope/collision errors before publishing a partial replacement.
10
+ * @complexity O(t) snapshot and registration work for t originally listed tools; no I/O.
11
+ */
12
+ export declare function registerFrozenFederationConnection({ registry, session, config, tools, deps, registrations }: {
13
+ registry: ToolRegistry;
14
+ session: McpSessionPort;
15
+ config: FederatedMcpConnectionConfig;
16
+ tools: readonly RemoteToolDescriptor[];
17
+ deps: FederationDeps;
18
+ registrations: readonly ToolRegistration[];
19
+ }, { buildRegistrations }?: {
20
+ buildRegistrations?: typeof buildFederatedMcpRegistrations;
21
+ }): string[];
22
+ /** Apply current owner grants to already connected roster sources without tools/list or connect.
23
+ * Missing sources are hidden; changed identities remain hidden until a new connection is admitted.
24
+ * @returns Updated reports in the existing admission shape; frozen definitions never widen.
25
+ * @throws Collision errors from the core's atomic registration-scope replacement.
26
+ * @complexity O(c + r*(n+t)) for c sources, r changed grants, n registered tools, t frozen tools;
27
+ * no database, filesystem, polling or remote I/O.
28
+ */
29
+ export declare function refreshFrozenFederationGrants({ registry, connections }: {
30
+ registry: ToolRegistry;
31
+ connections: readonly ResolvedFederatedConnection[];
32
+ }, _options?: {}): {
33
+ connectionId: string;
34
+ report: FederatedAdmissionReport;
35
+ isPreset: boolean;
36
+ }[];
37
+ //# sourceMappingURL=frozen-grants.d.ts.map
@@ -0,0 +1,67 @@
1
+ /** Owner grant changes reuse the connection's original untrusted tool snapshot (R5). */
2
+ import { createToolRegistrationScope } from '@jini-ai/core';
3
+ import { buildFederatedMcpRegistrations } from './registrations.js';
4
+ const connectionsByRegistry = new WeakMap();
5
+ /** Compare only owner grants; remote definitions, endpoint identity and read trust remain frozen. */
6
+ function grantsKey({ config }, _options = {}) {
7
+ return JSON.stringify([config.allowedToolNames, config.writeAllowedToolNames]);
8
+ }
9
+ /** Register one roster source in the existing core revocation scope and retain its first listing.
10
+ * @returns Registered tool ids; remote snapshots stay private to this registry's lifetime.
11
+ * @throws Core scope/collision errors before publishing a partial replacement.
12
+ * @complexity O(t) snapshot and registration work for t originally listed tools; no I/O.
13
+ */
14
+ export function registerFrozenFederationConnection({ registry, session, config, tools, deps, registrations }, { buildRegistrations = buildFederatedMcpRegistrations } = {}) {
15
+ const scope = createToolRegistrationScope({ registry });
16
+ scope.replace({ registrations });
17
+ const connections = connectionsByRegistry.get(registry) ?? new Map();
18
+ connectionsByRegistry.set(registry, connections);
19
+ const ids = registrations.map(registration => registration.descriptor.id);
20
+ connections.set(config.connectionId, { scope, session, deps, buildRegistrations, config: structuredClone(config), tools: structuredClone(tools), ids: new Set(ids), grantsKey: grantsKey({ config }), visible: true });
21
+ return ids;
22
+ }
23
+ /** Hide a removed/off/changed source, revoking already-held handler closures too. O(t) removals. */
24
+ function hideConnection({ frozen }, _options = {}) {
25
+ if (!frozen.visible)
26
+ return;
27
+ frozen.scope.replace({ registrations: [] });
28
+ frozen.visible = false;
29
+ }
30
+ /** Restore or re-grant only the original endpoint, with original schemas and classifications.
31
+ * @complexity O(n+t) registry collision checking and rebuilding for t frozen tools; no I/O.
32
+ */
33
+ function refreshConnection({ registry, frozen, current }, _options = {}) {
34
+ if (!current || JSON.stringify(current.config.origin) !== JSON.stringify(frozen.config.origin)) {
35
+ hideConnection({ frozen });
36
+ return null;
37
+ }
38
+ const key = grantsKey({ config: current.config });
39
+ if (frozen.visible && key === frozen.grantsKey)
40
+ return null;
41
+ const config = { ...frozen.config, allowedToolNames: current.config.allowedToolNames, writeAllowedToolNames: current.config.writeAllowedToolNames };
42
+ const nativeToolIds = new Set(registry.list({}).map(tool => tool.id).filter(id => !frozen.ids.has(id)));
43
+ const { registrations, report } = frozen.buildRegistrations({ config, tools: frozen.tools, session: frozen.session, deps: frozen.deps, nativeToolIds });
44
+ frozen.scope.replace({ registrations });
45
+ frozen.ids = new Set(registrations.map(registration => registration.descriptor.id));
46
+ frozen.grantsKey = key;
47
+ frozen.visible = true;
48
+ return report;
49
+ }
50
+ /** Apply current owner grants to already connected roster sources without tools/list or connect.
51
+ * Missing sources are hidden; changed identities remain hidden until a new connection is admitted.
52
+ * @returns Updated reports in the existing admission shape; frozen definitions never widen.
53
+ * @throws Collision errors from the core's atomic registration-scope replacement.
54
+ * @complexity O(c + r*(n+t)) for c sources, r changed grants, n registered tools, t frozen tools;
55
+ * no database, filesystem, polling or remote I/O.
56
+ */
57
+ export function refreshFrozenFederationGrants({ registry, connections }, _options = {}) {
58
+ const currentById = new Map(connections.map(connection => [connection.config.connectionId, connection]));
59
+ const reports = [];
60
+ for (const [connectionId, frozen] of connectionsByRegistry.get(registry) ?? []) {
61
+ const report = refreshConnection({ registry, frozen, current: currentById.get(connectionId) });
62
+ if (report)
63
+ reports.push({ connectionId, report, isPreset: false });
64
+ }
65
+ return reports;
66
+ }
67
+ //# sourceMappingURL=frozen-grants.js.map
@@ -1,7 +1,7 @@
1
1
  import type { FederationMessages } from "./messages.js";
2
2
  import { type ToolExecutionContext, type ToolExecutionOptions, type ToolRegistration } from "@jini-ai/core";
3
3
  import { McpAuthFailedError } from "./mcp-protocol.js";
4
- import type { FederatedCallConfirmationOutcome, FederatedCallConfirmationRequest, FederatedCallTarget, FederatedGateVerdict, FederatedMcpConnectionConfig, McpSessionPort } from "./ports.js";
4
+ import type { FederatedCallConfirmationOutcome, FederatedCallConfirmationRequest, FederatedCallTarget, FederatedGateVerdict, FederatedMcpConnectionConfig, McpSessionPort, RemoteToolDescriptor } from "./ports.js";
5
5
  import { admitRemoteTools, type AdmittedFederatedTool, type FederatedCallConfirmation, type FederatedAdmissionReport } from "./trust.js";
6
6
  /**
7
7
  * @file Turns one connected external MCP server into `ToolRegistration`s — the federated
@@ -145,6 +145,8 @@ export interface FederationDeps {
145
145
  }
146
146
  export interface FederatedRegistrationResult {
147
147
  readonly registrations: ToolRegistration[];
148
+ /** First tools/list snapshot, retained privately by boot for owner grant changes; never re-listed. */
149
+ readonly frozenTools?: readonly RemoteToolDescriptor[];
148
150
  /** The full accounting of what was admitted and refused, for the caller to log. */
149
151
  readonly report: FederatedAdmissionReport;
150
152
  }
@@ -182,5 +184,6 @@ export declare function federateSession(params: {
182
184
  config: FederatedMcpConnectionConfig;
183
185
  deps: FederationDeps;
184
186
  nativeToolIds: ReadonlySet<string>;
187
+ buildRegistrations?: typeof buildFederatedMcpRegistrations;
185
188
  }): Promise<FederatedRegistrationResult>;
186
189
  //# sourceMappingURL=registrations.d.ts.map
@@ -101,7 +101,7 @@ export function buildFederatedMcpRegistrations(params) {
101
101
  */
102
102
  export async function federateSession(params) {
103
103
  const tools = await params.session.listTools();
104
- return buildFederatedMcpRegistrations({ ...params, tools });
104
+ return { ...(params.buildRegistrations ?? buildFederatedMcpRegistrations)({ ...params, tools }), frozenTools: structuredClone(tools) };
105
105
  }
106
106
  /**
107
107
  * Liveness, revocation and authorization for one call — run before anything is sent, and again
@@ -12,16 +12,17 @@ import type { FederationDeps } from "./registrations.js";
12
12
  *
13
13
  * ## What this does NOT do, on purpose
14
14
  *
15
- * `trust.ts` R5 freezes an ALREADY-ADMITTED connection's tool set at connect, forever, for this
15
+ * `trust.ts` R5 freezes an ALREADY-ADMITTED connection's remote definitions at connect, forever, for this
16
16
  * process's lifetime — the rug-pull protection that file's own header explains. This module never
17
- * re-lists, re-classifies, or re-admits a connectionId with admitted tools that has gone through
17
+ * re-lists or replaces the remote definitions of a connectionId with admitted tools that has gone through
18
18
  * {@link attachFederatedMcpTools} once, whether that pass ran at boot or at an earlier reload
19
19
  * ({@link selectUnadmittedConnections} is the whole enforcement mechanism: a connectionId already in
20
20
  * `admittedConnectionIds` is filtered out before `attach` is ever called on it again). It only ever
21
21
  * widens the set of connections that have been admitted AT ALL — new rows, never revised ones — which
22
22
  * is the same guarantee a fresh boot already gives, just applied to a connection that did not exist
23
23
  * yet when this process started. `ToolRegistry` (`@jini-ai/core`) is deliberately append-only with no
24
- * unregister, so this module still has no way to revise or drop an admitted tool even if it wanted to.
24
+ * unregister. The existing core registration scope now withdraws/restores a roster source and
25
+ * replays owner grant changes against its original definitions, without a new handshake or listing.
25
26
  * A roster row admitted with an empty allowlist and no tools can wait for its first operator grant.
26
27
  * Retrying that row replaces no tool or classification; after its first nonempty admission it freezes
27
28
  * just like every other connection. An unchanged empty grant never triggers another handshake.
@@ -31,8 +32,9 @@ import type { FederationDeps } from "./registrations.js";
31
32
  * `FederationDeps.assertConnectionUsable`) re-reads the connection's row on every call, independent of
32
33
  * this reload path. Turning a connection off, deleting it, disconnecting its OAuth, or narrowing its
33
34
  * allowlist or write list all take effect on the very NEXT call, with no restart and no reload
34
- * required. Widening the allowlist, or changing the server's address, command, args or sign-in method,
35
- * still needs a real restart: the new tools are never registered, and the old ones refuse as
35
+ * required. Widening the allowlist can now admit another originally listed tool through the same
36
+ * frozen snapshot. Changing the server's address, command, args or sign-in method still needs a
37
+ * real restart: definitions from a changed source are never registered, and the old ones refuse as
36
38
  * `"changed"` (the row's admission revision no longer matches what the tool was admitted under) until
37
39
  * the process restarts and re-admits the connection fresh.
38
40
  *
@@ -59,7 +61,7 @@ export declare function selectUnadmittedConnections({ allConnections, admittedCo
59
61
  admittedConnectionIds: ReadonlySet<string>;
60
62
  }): readonly ResolvedFederatedConnection[];
61
63
  export interface FederationReloadResult {
62
- /** Ids newly admitted by THIS reload pass — empty when nothing in the roster was unadmitted. */
64
+ /** Ids newly admitted or whose owner grants were refreshed by THIS reload pass. */
63
65
  readonly newlyAdmittedConnectionIds: readonly string[];
64
66
  /** This pass's own admission reports only, in `attachFederatedMcpTools`'s own shape — the caller
65
67
  * (`agent-daemon-server.ts`) merges these into the running, boot-plus-every-reload accounting
@@ -1,4 +1,5 @@
1
1
  import { attachFederatedMcpTools } from "./bootstrap.js";
2
+ import { refreshFrozenFederationGrants } from './frozen-grants.js';
2
3
  /**
3
4
  * @file Hot re-admission of federated MCP connections — the piece that lets an owner who finishes an
4
5
  * external MCP sign-in (or an operator who saves a ready, non-OAuth connection) see its tools without
@@ -9,16 +10,17 @@ import { attachFederatedMcpTools } from "./bootstrap.js";
9
10
  *
10
11
  * ## What this does NOT do, on purpose
11
12
  *
12
- * `trust.ts` R5 freezes an ALREADY-ADMITTED connection's tool set at connect, forever, for this
13
+ * `trust.ts` R5 freezes an ALREADY-ADMITTED connection's remote definitions at connect, forever, for this
13
14
  * process's lifetime — the rug-pull protection that file's own header explains. This module never
14
- * re-lists, re-classifies, or re-admits a connectionId with admitted tools that has gone through
15
+ * re-lists or replaces the remote definitions of a connectionId with admitted tools that has gone through
15
16
  * {@link attachFederatedMcpTools} once, whether that pass ran at boot or at an earlier reload
16
17
  * ({@link selectUnadmittedConnections} is the whole enforcement mechanism: a connectionId already in
17
18
  * `admittedConnectionIds` is filtered out before `attach` is ever called on it again). It only ever
18
19
  * widens the set of connections that have been admitted AT ALL — new rows, never revised ones — which
19
20
  * is the same guarantee a fresh boot already gives, just applied to a connection that did not exist
20
21
  * yet when this process started. `ToolRegistry` (`@jini-ai/core`) is deliberately append-only with no
21
- * unregister, so this module still has no way to revise or drop an admitted tool even if it wanted to.
22
+ * unregister. The existing core registration scope now withdraws/restores a roster source and
23
+ * replays owner grant changes against its original definitions, without a new handshake or listing.
22
24
  * A roster row admitted with an empty allowlist and no tools can wait for its first operator grant.
23
25
  * Retrying that row replaces no tool or classification; after its first nonempty admission it freezes
24
26
  * just like every other connection. An unchanged empty grant never triggers another handshake.
@@ -28,8 +30,9 @@ import { attachFederatedMcpTools } from "./bootstrap.js";
28
30
  * `FederationDeps.assertConnectionUsable`) re-reads the connection's row on every call, independent of
29
31
  * this reload path. Turning a connection off, deleting it, disconnecting its OAuth, or narrowing its
30
32
  * allowlist or write list all take effect on the very NEXT call, with no restart and no reload
31
- * required. Widening the allowlist, or changing the server's address, command, args or sign-in method,
32
- * still needs a real restart: the new tools are never registered, and the old ones refuse as
33
+ * required. Widening the allowlist can now admit another originally listed tool through the same
34
+ * frozen snapshot. Changing the server's address, command, args or sign-in method still needs a
35
+ * real restart: definitions from a changed source are never registered, and the old ones refuse as
33
36
  * `"changed"` (the row's admission revision no longer matches what the tool was admitted under) until
34
37
  * the process restarts and re-admits the connection fresh.
35
38
  *
@@ -68,6 +71,7 @@ export function createFederationReloadCoordinator({ coordDeps, initiallyAdmitted
68
71
  let queuedNext = null;
69
72
  async function runOnePass() {
70
73
  const allConnections = await coordDeps.resolveConnections();
74
+ const refreshed = refreshFrozenFederationGrants({ registry: coordDeps.registry, connections: allConnections });
71
75
  const eligibleIds = new Set(admitted);
72
76
  for (const connection of allConnections) {
73
77
  if (awaitingGrants.has(connection.config.connectionId) && connection.config.allowedToolNames.length > 0)
@@ -75,7 +79,7 @@ export function createFederationReloadCoordinator({ coordDeps, initiallyAdmitted
75
79
  }
76
80
  const unadmitted = selectUnadmittedConnections({ allConnections, admittedConnectionIds: eligibleIds });
77
81
  if (unadmitted.length === 0)
78
- return { newlyAdmittedConnectionIds: [], reports: [], connectFailures: [] };
82
+ return { newlyAdmittedConnectionIds: refreshed.map(entry => entry.connectionId), reports: refreshed, connectFailures: [] };
79
83
  // Empty, not omitted: omission resolves presets from the environment again, even though the
80
84
  // boot pass already admitted them. Reload concerns only the operator-editable roster;
81
85
  // environment presets cannot change without a real restart.
@@ -85,8 +89,8 @@ export function createFederationReloadCoordinator({ coordDeps, initiallyAdmitted
85
89
  rememberAdmission({ entry, connection: attemptedConnections.get(entry.connectionId) });
86
90
  }
87
91
  return {
88
- newlyAdmittedConnectionIds: attached.reports.map((entry) => entry.connectionId),
89
- reports: attached.reports,
92
+ newlyAdmittedConnectionIds: [...refreshed, ...attached.reports].map((entry) => entry.connectionId),
93
+ reports: [...refreshed, ...attached.reports],
90
94
  connectFailures: attached.connectFailures,
91
95
  };
92
96
  }
@@ -34,14 +34,9 @@ export declare function resolveMcpToolName({ name }: {
34
34
  }): string;
35
35
  /** True for a plain JSON object (not `null`, not an array). */
36
36
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
37
- /**
38
- * Copies caller arguments into their canonical wrapper shape before schema validation, reading a
39
- * canonical integer string as the integer a top-level `integer` property declares.
40
- * @param requiredArgs - Tool contract and untrusted arguments; neither is mutated.
41
- * @param _options - Reserved normalization options.
42
- * @returns Canonical arguments; nested tool input is copied only when fields are folded.
43
- * @throws Error naming an ambiguous alias, duplicate input key, or invalid wrapper field.
44
- * @complexity O(k + a + i) time and space for k argument keys, a aliases, and i input keys.
37
+ /** Normalize the transport envelope, then existing aliases, integer fields and gateway input.
38
+ * @returns A detached argument object; malformed or ambiguous input throws a repair instruction.
39
+ * @complexity O(k + a + i + n) for argument/alias/input keys and encoded JSON characters.
45
40
  */
46
41
  export declare function normalizeToolArguments({ tool, rawArgs }: {
47
42
  tool: McpToolArgumentContract;
@@ -1,3 +1,4 @@
1
+ import { decodeToolInputObject, unwrapToolInputEnvelope } from '@jini-ai/core';
1
2
  /** Resolve this host's CLI decoration, preserving exact registered names and other servers.
2
3
  * @param required - Model-visible name, possibly prefixed by the Jini MCP client.
3
4
  * @param options - Exact-name lookup when a local tool index is available.
@@ -80,18 +81,30 @@ function assertNoMisplacedInputKey({ args, schema }) {
80
81
  throw new Error(`move \`input.${misplaced}\` to top-level \`${misplaced}\``);
81
82
  }
82
83
  /**
83
- * Copies caller arguments into their canonical wrapper shape before schema validation, reading a
84
- * canonical integer string as the integer a top-level `integer` property declares.
85
- * @param requiredArgs - Tool contract and untrusted arguments; neither is mutated.
86
- * @param _options - Reserved normalization options.
87
- * @returns Canonical arguments; nested tool input is copied only when fields are folded.
88
- * @throws Error naming an ambiguous alias, duplicate input key, or invalid wrapper field.
89
- * @complexity O(k + a + i) time and space for k argument keys, a aliases, and i input keys.
84
+ * Copy the tool's transport arguments, decoding only schema-directed delegated envelopes.
85
+ * @returns Detached arguments; declared tool-owned `input` fields retain their meaning.
86
+ * @throws ToolInputError for JSON strings that do not encode objects.
87
+ * @complexity O(k + n) time/space for k keys and n JSON characters; no I/O.
88
+ */
89
+ function argumentSource({ tool, rawArgs }) {
90
+ const source = tool.argumentNormalization?.schemaInput
91
+ ? unwrapToolInputEnvelope({ input: rawArgs, schema: tool.inputSchema }) : rawArgs;
92
+ const args = { ...source };
93
+ // The gateway owns an object-valued `input`; clients sometimes JSON-encode that field.
94
+ // Decode before folding/validation so every delegated tool receives the same object contract.
95
+ if (tool.argumentNormalization?.foldIntoInput && Object.hasOwn(args, 'input')) {
96
+ args.input = decodeToolInputObject({ input: args.input });
97
+ }
98
+ return args;
99
+ }
100
+ /** Normalize the transport envelope, then existing aliases, integer fields and gateway input.
101
+ * @returns A detached argument object; malformed or ambiguous input throws a repair instruction.
102
+ * @complexity O(k + a + i + n) for argument/alias/input keys and encoded JSON characters.
90
103
  */
91
104
  export function normalizeToolArguments({ tool, rawArgs }, _options = {}) {
92
105
  if (!isRecord(rawArgs))
93
106
  throw new Error('replace `arguments` with a JSON object');
94
- const args = { ...rawArgs };
107
+ const args = argumentSource({ tool, rawArgs });
95
108
  const properties = tool.inputSchema.properties ?? {};
96
109
  applyAliases({ args, aliases: tool.argumentNormalization?.aliases ?? {} });
97
110
  coerceIntegerStrings({ args, properties });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/mcp",
3
- "version": "0.6.19",
3
+ "version": "0.6.22",
4
4
  "description": "Model Context Protocol adapters: server config schema and IO, an MCP client, and agent-side MCP server installation.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -85,16 +85,16 @@
85
85
  "dependencies": {
86
86
  "@cfworker/json-schema": "^4.1.1",
87
87
  "@modelcontextprotocol/sdk": "^1.29.0",
88
- "@jini-ai/core": "^0.6.19",
89
- "@jini-ai/platform": "^0.6.19",
90
- "@jini-ai/protocol": "^0.6.19"
88
+ "@jini-ai/protocol": "^0.6.19",
89
+ "@jini-ai/platform": "^0.6.22",
90
+ "@jini-ai/core": "^0.6.22"
91
91
  },
92
92
  "devDependencies": {
93
93
  "@cfworker/json-schema": "^4.1.1",
94
94
  "@modelcontextprotocol/sdk": "^1.29.0",
95
- "@jini-ai/daemon": "^0.6.19",
96
- "@jini-ai/platform": "^0.6.19",
97
- "@jini-ai/core": "^0.6.19"
95
+ "@jini-ai/core": "^0.6.22",
96
+ "@jini-ai/daemon": "^0.6.22",
97
+ "@jini-ai/platform": "^0.6.22"
98
98
  },
99
99
  "scripts": {
100
100
  "build": "tsc -p tsconfig.json && chmod +x dist/bin/serve.js",