@jini-ai/mcp 0.6.19 → 0.6.23

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,13 @@
1
+ ## 0.6.23
2
+
3
+ - Security hardening.
4
+
1
5
  # @jini-ai/mcp
2
6
 
7
+ ## 0.6.22
8
+
9
+ - 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.
10
+
3
11
  ## 0.6.19
4
12
 
5
13
  - Redact config/token parsing and federation bootstrap exception diagnostics.
@@ -1,4 +1,6 @@
1
1
  import { loadOptionalPeer } from '@jini-ai/core/optional-peer';
2
+ import { redactSecrets } from '@jini-ai/core';
3
+ import { scrubFederatedResponseValue } from "./result-secrets.js";
2
4
  import { parseSseRecord } from "@jini-ai/core/primitives";
3
5
  import { buildInitializeParams, CLIENT_PROTOCOL_VERSION, drainToolsList, McpAuthFailedError, McpProtocolError, parseCallToolResult, parseInitializeResult, } from "./mcp-protocol.js";
4
6
  /**
@@ -54,6 +56,14 @@ const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
54
56
  const SESSION_ID_PATTERN = /^[\x21-\x7e]{1,512}$/;
55
57
  /** MCP requires a client to accept both response modes on every request, and the server picks. */
56
58
  const ACCEPT_BOTH = "application/json, text/event-stream";
59
+ /** Configured headers carry connection credentials; retain both the full value and auth payload.
60
+ * @complexity O(h) time/space in configured header bytes; no credential lookup or I/O.
61
+ */
62
+ function headerSecrets({ headers }, _options = {}) {
63
+ return Object.entries(headers).flatMap(([name, value]) => name.toLowerCase() === "authorization"
64
+ ? [value, value.replace(/^\S+\s+/, "")]
65
+ : [value]);
66
+ }
57
67
  /** Wires `controller` to also abort when `callerSignal` does — including firing immediately if
58
68
  * `callerSignal` is already aborted by the time this runs. Returns the listener so the caller can
59
69
  * remove it again once the request settles. Split out of
@@ -110,7 +120,7 @@ class McpHttpSession {
110
120
  return drainToolsList({ requestPage: ({ params }) => this.request("tools/list", params) });
111
121
  }
112
122
  /**
113
- * @complexity O(1) beyond the remote's own round-trip.
123
+ * @complexity O(s*b) beyond the remote round-trip for s credentials and b bounded result bytes.
114
124
  */
115
125
  async callTool(request, options = {}) {
116
126
  return parseCallToolResult({ result: await this.request("tools/call", { name: request.name, arguments: request.arguments }, options.signal) });
@@ -175,20 +185,21 @@ class McpHttpSession {
175
185
  "mcp-protocol-version": this.serverProtocolVersion || CLIENT_PROTOCOL_VERSION,
176
186
  };
177
187
  }
178
- /** POSTs one JSON-RPC frame and returns the raw response, applying the timeout and recording any
179
- * session id the server issues. */
188
+ /** POSTs one JSON-RPC frame and keeps its credentials with the raw response, applying the timeout
189
+ * and recording any session id the server issues. */
180
190
  async send(body, signal) {
181
191
  if (this.closed)
182
192
  throw new McpProtocolError({ message: "mcp-federation: session is closed" });
183
193
  const headers = this.baseHeaders();
184
194
  if (this.sessionId !== null)
185
195
  headers["mcp-session-id"] = this.sessionId;
186
- const response = await this.postWithTimeout(body, headers, signal);
196
+ const authenticated = await this.postWithTimeout(body, headers, signal);
197
+ const { response } = authenticated;
187
198
  // A known auth failure must reach assertOkStatus even if the remote supplied a bad session id.
188
199
  if (response.status === 401)
189
- return response;
200
+ return authenticated;
190
201
  this.adoptSessionId(response);
191
- return response;
202
+ return authenticated;
192
203
  }
193
204
  /**
194
205
  * Applies the per-request ceiling.
@@ -203,24 +214,32 @@ class McpHttpSession {
203
214
  const onCallerAbort = forwardAbort(controller, callerSignal);
204
215
  const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
205
216
  let response;
217
+ let secrets = headerSecrets({ headers: this.spec.headers });
206
218
  try {
207
- response = await this.exchange.send({ url: this.spec.url, method: "POST", headers: await this.authenticatedHeaders(headers, controller.signal) }, { body, signal: controller.signal });
219
+ const authenticated = await this.authenticatedHeaders(headers, controller.signal);
220
+ // Keep proof with its response, never in a growing session history: parallel calls may
221
+ // rotate tokens and complete out of order. Only configured credentials and the actual
222
+ // Authorization header are secrets; protocol headers must remain readable.
223
+ const authorization = Object.fromEntries(Object.entries(authenticated).filter(([name]) => name.toLowerCase() === "authorization"));
224
+ secrets = [...secrets, ...headerSecrets({ headers: authorization })];
225
+ response = await this.exchange.send({ url: this.spec.url, method: "POST", headers: authenticated }, { body, signal: controller.signal });
208
226
  if (response.status === 401)
209
227
  await this.notifyAuthenticationChallenge({ response, signal: controller.signal });
210
228
  }
211
229
  catch (error) {
212
- throw buildPostFailureError({
230
+ const failure = buildPostFailureError({
213
231
  error,
214
232
  timedOut: controller.signal.aborted,
215
233
  callerAborted: callerSignal?.aborted === true,
216
234
  requestTimeoutMs: this.requestTimeoutMs,
217
235
  });
236
+ throw new McpProtocolError({ message: redactSecrets({ input: failure.message }, { exactSecrets: secrets, policy: "exact-only" }) });
218
237
  }
219
238
  finally {
220
239
  clearTimeout(timer);
221
240
  callerSignal?.removeEventListener("abort", onCallerAbort);
222
241
  }
223
- return response;
242
+ return { response, secrets };
224
243
  }
225
244
  /** Observes a 401 within the POST's remaining budget, without superseding its typed auth error.
226
245
  * @complexity O(1) beyond the injected hook's work, bounded by the request signal.
@@ -280,13 +299,14 @@ class McpHttpSession {
280
299
  async request(method, params, signal) {
281
300
  const id = this.nextId;
282
301
  this.nextId += 1;
283
- const response = await this.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }), signal);
302
+ const { response, secrets } = await this.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }), signal);
284
303
  assertOkStatus(method, response, this.messages);
285
304
  const frame = extractJsonRpcFrame({ method, response, id });
286
305
  if (frame.error) {
287
- throw new McpProtocolError({ message: `mcp-federation: remote returned JSON-RPC error ${frame.error.code ?? "?"}: ${frame.error.message ?? "(no message)"}` });
306
+ throw new McpProtocolError({ message: redactSecrets({ input: `mcp-federation: remote returned JSON-RPC error ${frame.error.code ?? "?"}: ${frame.error.message ?? "(no message)"}` }, { exactSecrets: secrets, policy: "exact-only" }) });
288
307
  }
289
- return frame.result;
308
+ // Negotiation and discovery fields are protocol data; only successful tool results are scrubbed.
309
+ return method === "tools/call" ? scrubFederatedResponseValue({ value: frame.result, secrets }) : frame.result;
290
310
  }
291
311
  }
292
312
  /**
@@ -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
  }
@@ -0,0 +1,11 @@
1
+ /** Scrub decoded JSON strings, including object keys, before successful tool-call results leave the transport.
2
+ * Parsing each string before redaction preserves JSON syntax for short or escaped credentials.
3
+ * @param required - Parsed tool-result JSON and only this connection's known credentials.
4
+ * @returns The JSON value with exact credential occurrences masked; no input mutation or I/O.
5
+ * @complexity O(s*b) time for s secrets and b response bytes; O(b) space. Callers enforce transport caps.
6
+ */
7
+ export declare function scrubFederatedResponseValue({ value, secrets }: {
8
+ value: unknown;
9
+ secrets: readonly string[];
10
+ }, _options?: Record<string, never>): unknown;
11
+ //# sourceMappingURL=result-secrets.d.ts.map
@@ -0,0 +1,14 @@
1
+ import { redactSecrets } from "@jini-ai/core";
2
+ /** Scrub decoded JSON strings, including object keys, before successful tool-call results leave the transport.
3
+ * Parsing each string before redaction preserves JSON syntax for short or escaped credentials.
4
+ * @param required - Parsed tool-result JSON and only this connection's known credentials.
5
+ * @returns The JSON value with exact credential occurrences masked; no input mutation or I/O.
6
+ * @complexity O(s*b) time for s secrets and b response bytes; O(b) space. Callers enforce transport caps.
7
+ */
8
+ export function scrubFederatedResponseValue({ value, secrets }, _options = {}) {
9
+ if (value === undefined || secrets.length === 0)
10
+ return value;
11
+ const serialized = JSON.stringify(value);
12
+ return JSON.parse(serialized.replace(/"(?:[^"\\]|\\.)*"/g, literal => JSON.stringify(redactSecrets({ input: JSON.parse(literal) }, { exactSecrets: secrets, policy: "exact-only" }))));
13
+ }
14
+ //# sourceMappingURL=result-secrets.js.map
@@ -73,6 +73,7 @@ export declare function describeChildExit({ code, signal, stderrTail, secretValu
73
73
  * @param deps.channel - The transport seam. `spawnMcpStdioChannel` in production, a scripted
74
74
  * double in tests.
75
75
  * @param deps.requestTimeoutMs - Per-request ceiling, applied to the handshake too.
76
+ * @param deps.secretValues - This connection's own credentials; omitted by callers with no secrets.
76
77
  * @throws {Error} If `initialize` fails, times out, or the channel dies during it.
77
78
  * @complexity O(1) beyond the remote's round-trip.
78
79
  */
@@ -81,7 +82,8 @@ export declare function connectMcpStdioSession(deps: {
81
82
  requestTimeoutMs: number;
82
83
  clientInfo: McpClientInfo;
83
84
  messages: FederationMessages;
84
- }): Promise<McpSessionPort>;
85
+ secretValues?: readonly string[];
86
+ }, _options?: Record<string, never>): Promise<McpSessionPort>;
85
87
  /**
86
88
  * The production {@link McpStdioChannel}: a child process, its stdin, and newline-framed stdout.
87
89
  *
@@ -1,3 +1,5 @@
1
+ import { redactSecrets as redactExactSecrets } from "@jini-ai/core";
2
+ import { scrubFederatedResponseValue } from "../result-secrets.js";
1
3
  import { spawn } from "node:child_process";
2
4
  import os from "node:os";
3
5
  import path from "node:path";
@@ -160,6 +162,7 @@ class McpStdioSession {
160
162
  pending = new Map();
161
163
  clientInfo;
162
164
  messages;
165
+ secretValues;
163
166
  nextId = 1;
164
167
  closedReason = null;
165
168
  /** The protocol version the SERVER said it would speak, for diagnostics. */
@@ -172,6 +175,7 @@ class McpStdioSession {
172
175
  this.clientInfo = deps.clientInfo;
173
176
  this.messages = deps.messages;
174
177
  this.requestTimeoutMs = deps.requestTimeoutMs;
178
+ this.secretValues = [...(deps.secretValues ?? [])];
175
179
  this.channel.onMessage({ listener: ({ message: line }) => this.handleMessage(line) });
176
180
  this.channel.onClose({ listener: ({ reason }) => this.handleClose(reason) });
177
181
  }
@@ -182,10 +186,11 @@ class McpStdioSession {
182
186
  return drainToolsList({ requestPage: ({ params }) => this.request("tools/list", params) });
183
187
  }
184
188
  /**
185
- * @complexity O(1) beyond the remote's own round-trip.
189
+ * @complexity O(s*b) beyond the remote round-trip for s credentials and b bounded result bytes.
186
190
  */
187
191
  async callTool(request, options = {}) {
188
- return parseCallToolResult({ result: await this.request("tools/call", { name: request.name, arguments: request.arguments }, options.signal) });
192
+ const result = await this.request("tools/call", { name: request.name, arguments: request.arguments }, options.signal);
193
+ return parseCallToolResult({ result: scrubFederatedResponseValue({ value: result, secrets: this.secretValues }) });
189
194
  }
190
195
  async close(_required) {
191
196
  this.handleClose(this.messages.closedByHost);
@@ -283,7 +288,9 @@ class McpStdioSession {
283
288
  this.pending.delete(message.id);
284
289
  clearTimeout(entry.timer);
285
290
  if (message.error) {
286
- entry.reject(new McpProtocolError({ message: `mcp-federation: remote returned JSON-RPC error ${message.error.code ?? "?"}: ${message.error.message ?? "(no message)"}` }));
291
+ entry.reject(new McpProtocolError({ message: redactExactSecrets({
292
+ input: `mcp-federation: remote returned JSON-RPC error ${message.error.code ?? "?"}: ${message.error.message ?? "(no message)"}`,
293
+ }, { exactSecrets: this.secretValues, policy: "exact-only" }) }));
287
294
  return;
288
295
  }
289
296
  entry.resolve(message.result);
@@ -306,10 +313,11 @@ class McpStdioSession {
306
313
  * @param deps.channel - The transport seam. `spawnMcpStdioChannel` in production, a scripted
307
314
  * double in tests.
308
315
  * @param deps.requestTimeoutMs - Per-request ceiling, applied to the handshake too.
316
+ * @param deps.secretValues - This connection's own credentials; omitted by callers with no secrets.
309
317
  * @throws {Error} If `initialize` fails, times out, or the channel dies during it.
310
318
  * @complexity O(1) beyond the remote's round-trip.
311
319
  */
312
- export async function connectMcpStdioSession(deps) {
320
+ export async function connectMcpStdioSession(deps, _options = {}) {
313
321
  const session = new McpStdioSession(deps);
314
322
  try {
315
323
  await session.initialize();
@@ -70,7 +70,8 @@ async function connectMcpStdioSessionWithSpawnTimeout(connection, launch, resolv
70
70
  channel = spawnChannel({ resolved });
71
71
  if (Date.now() >= deadline)
72
72
  throw timeoutError();
73
- return connectMcpStdioSession({ channel, requestTimeoutMs: connection.config.callTimeoutMs, clientInfo, messages });
73
+ // Only this connection's credentials, never inherited paths or launch settings, are secrets.
74
+ return connectMcpStdioSession({ channel, requestTimeoutMs: connection.config.callTimeoutMs, clientInfo, messages, secretValues: Object.values(resolved.env) });
74
75
  }),
75
76
  // Not `unref()`ed, for the same reason as `adapter.stdio.ts`'s per-request timer: an unref'd
76
77
  // timer would let the loop drain and abandon this race unsettled instead of rejecting. The
@@ -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.23",
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/core": "^0.6.23",
89
+ "@jini-ai/protocol": "^0.6.19",
90
+ "@jini-ai/platform": "^0.6.23"
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/daemon": "^0.6.23",
96
+ "@jini-ai/core": "^0.6.23",
97
+ "@jini-ai/platform": "^0.6.23"
98
98
  },
99
99
  "scripts": {
100
100
  "build": "tsc -p tsconfig.json && chmod +x dist/bin/serve.js",