@jini-ai/mcp 0.6.22 → 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,3 +1,7 @@
1
+ ## 0.6.23
2
+
3
+ - Security hardening.
4
+
1
5
  # @jini-ai/mcp
2
6
 
3
7
  ## 0.6.22
@@ -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
  /**
@@ -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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/mcp",
3
- "version": "0.6.22",
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.23",
88
89
  "@jini-ai/protocol": "^0.6.19",
89
- "@jini-ai/platform": "^0.6.22",
90
- "@jini-ai/core": "^0.6.22"
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/core": "^0.6.22",
96
- "@jini-ai/daemon": "^0.6.22",
97
- "@jini-ai/platform": "^0.6.22"
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",