@jini-ai/mcp 0.6.17 → 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.
Files changed (35) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/bin/serve.js +12 -81
  3. package/dist/core/config.js +3 -1
  4. package/dist/core/tokens.js +3 -1
  5. package/dist/federation/bootstrap.d.ts +6 -5
  6. package/dist/federation/bootstrap.js +25 -6
  7. package/dist/federation/frozen-grants.d.ts +37 -0
  8. package/dist/federation/frozen-grants.js +67 -0
  9. package/dist/federation/registrations.d.ts +4 -1
  10. package/dist/federation/registrations.js +1 -1
  11. package/dist/federation/reload.d.ts +13 -6
  12. package/dist/federation/reload.js +35 -12
  13. package/dist/index.d.ts +5 -2
  14. package/dist/index.js +3 -1
  15. package/dist/server/daemon-client.d.ts +2 -2
  16. package/dist/server/daemon-client.js +4 -1
  17. package/dist/server/http-tool-server.d.ts +44 -0
  18. package/dist/server/http-tool-server.js +272 -0
  19. package/dist/server/index.d.ts +2 -0
  20. package/dist/server/index.js +2 -0
  21. package/dist/server/run-tool-host.d.ts +28 -0
  22. package/dist/server/run-tool-host.js +103 -0
  23. package/dist/server/sdk-transport.d.ts +7 -1
  24. package/dist/server/tool-arguments.d.ts +29 -10
  25. package/dist/server/tool-arguments.js +66 -15
  26. package/dist/server/tool-protocol.js +39 -9
  27. package/dist/server/tool-result-pages.d.ts +21 -0
  28. package/dist/server/tool-result-pages.js +74 -0
  29. package/dist/server/tool-server.d.ts +11 -5
  30. package/dist/server/tool-server.js +78 -53
  31. package/dist/server/tools/delegated-tool.d.ts +7 -6
  32. package/dist/server/tools/delegated-tool.js +8 -3
  33. package/dist/server/tools/wait.d.ts +5 -0
  34. package/dist/server/tools/wait.js +17 -0
  35. package/package.json +7 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
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
+
7
+ ## 0.6.19
8
+
9
+ - Redact config/token parsing and federation bootstrap exception diagnostics.
10
+ - A top-level `integer` argument sent as a canonical integer string (`search_tools {max_results: "8"}`) is read as that integer instead of refused, so the agent does not lose a turn retrying.
11
+
3
12
  ## 0.6.17
4
13
 
5
14
  ### Patch Changes
package/dist/bin/serve.js CHANGED
@@ -38,15 +38,9 @@
38
38
  */
39
39
  import { existsSync, realpathSync } from 'node:fs';
40
40
  import { fileURLToPath } from 'node:url';
41
- import { createCheckMessagesTool, messageRelayInstructions } from '../server/message-relay.js';
42
41
  import { isLoopbackHostname } from '@jini-ai/platform/net';
43
42
  import { createMcpToolServer as createMcpToolServerDefault } from '../server/tool-server.js';
44
- import { RUN_TOOLS } from '../server/tools/run-tools.js';
45
- import { describeToolTool, TOOL_CATALOG_TOOLS } from '../server/tools/tool-catalog-tools.js';
46
- import { COMPONENT_CATALOG_TOOLS } from '../server/tools/component-catalog-tools.js';
47
- import { createExecuteDelegatedToolTool, createExecuteReadonlyDelegatedToolTool } from '../server/tools/delegated-tool.js';
48
- import { KERNEL_RESOURCES } from '../server/resources/active-resource.js';
49
- import { createSiteGuideResource } from '../server/resources/site-guide-resource.js';
43
+ import { assembleRunToolHost } from '../server/run-tool-host.js';
50
44
  /** The one run this process is scoped to for its entire lifetime. Set by the spawning daemon, never by the MCP client. */
51
45
  export const RUN_ID_ENV_VAR = 'JINI_RUN_ID';
52
46
  /** Checked (only) when resolving the daemon HTTP base URL — see `resolveDaemonUrl`'s own docs; matches the CLI entry point's identically-named constant. */
@@ -79,16 +73,6 @@ export const DELEGATED_TOOL_TIMEOUT_ENV_VAR = 'JINI_DELEGATED_TOOL_TIMEOUT_MS';
79
73
  /** JSON array of host-selected visible registry IDs; never sourced from diagnostic IDs. */
80
74
  export const STARTUP_TOOL_IDS_ENV_VAR = 'JINI_STARTUP_TOOL_IDS';
81
75
  const SERVER_NAME = 'jini-mcp';
82
- const SERVER_VERSION = '0.0.0';
83
- const INSTRUCTIONS = 'Tools proxying this host\'s Jini daemon over loopback HTTP, scoped to the run that spawned this MCP server process. ' +
84
- 'Use execute_delegated_tool to invoke a Jini-registered tool (never an agent-vendor-specific tool name) against that run — ' +
85
- 'Registered operation calls use the daemon\'s deny-by-default ToolExecutor gate; ' +
86
- 'MCP-local names use their existing validated handlers. ' +
87
- 'Concrete operation tools accept their own arguments directly. describe_tool publishes a concrete definition; ' +
88
- 'refresh tools/list when supported, or use the delegated gateways as the compatibility fallback. ' +
89
- 'When the host provides site_guide, consult jini://site-guide or call site_guide with operation overview ' +
90
- 'through execute_readonly_delegated_tool; follow with explain for the relevant topic ids. ' +
91
- 'If the host does not provide site_guide, report that availability gap.';
92
76
  // Keep the bin's environment-only assembly here; a general CLI resolver would introduce a
93
77
  // runtime dependency on another shell. No discovery/default URL is selected for a run child.
94
78
  async function resolveDaemonUrlDefault(_required, options) {
@@ -146,24 +130,20 @@ export async function serve(_requiredArgs, deps = {}) {
146
130
  };
147
131
  const delegatedGatewayOptions = buildDelegatedGatewayOptions({ env }, deps);
148
132
  const messageRelay = resolveMessageRelay({ env, runId, writeErr, exit });
149
- const requiredArgs = {
150
- name: SERVER_NAME,
151
- version: SERVER_VERSION,
152
- tools: [...buildTools({ runId, delegatedGatewayOptions }), ...(messageRelay ? [createCheckMessagesTool(messageRelay)] : [])],
153
- resolveBaseUrl,
154
- };
155
- const serverOptions = buildServerOptions({ env, runId, delegatedGatewayOptions }, deps);
156
- if (messageRelay)
157
- Object.assign(serverOptions, { messageRelay, instructions: `${INSTRUCTIONS} ${messageRelayInstructions(messageRelay)}` });
158
133
  try {
159
134
  const diagnosticToolIds = parseLaunchToolIds({ env, key: 'JINI_DIAGNOSTIC_TOOL_IDS' });
160
- if (diagnosticToolIds.length)
161
- Object.assign(serverOptions, { diagnosticToolIds });
162
- const initialTools = await resolveStartupTools({
163
- toolIds: parseLaunchToolIds({ env, key: STARTUP_TOOL_IDS_ENV_VAR }), resolveBaseUrl, serverOptions,
135
+ // Absent credential => no `authHeaders` at all => byte-identical request headers to before this
136
+ // env var existed. See DAEMON_TOKEN_ENV_VAR's doc for why an unset value is not a startup failure.
137
+ const assembled = await assembleRunToolHost({ runId, resolveBaseUrl }, {
138
+ ...delegatedGatewayOptions,
139
+ ...definedOnly({ credential: env[DAEMON_TOKEN_ENV_VAR], fetchImpl: deps.fetchImpl,
140
+ messageRelayNonce: messageRelay?.nonce }),
141
+ startupToolIds: parseLaunchToolIds({ env, key: STARTUP_TOOL_IDS_ENV_VAR }),
142
+ ...(diagnosticToolIds.length ? { diagnosticToolIds } : {}),
164
143
  });
165
- Object.assign(serverOptions, { delegatedTools: { runId, ...delegatedGatewayOptions, initialTools } });
166
- await createMcpToolServerFn(requiredArgs, serverOptions).run({});
144
+ await createMcpToolServerFn(assembled.required, { ...assembled.options,
145
+ ...definedOnly({ stdin: deps.stdin, stdout: deps.stdout }),
146
+ }).run({});
167
147
  }
168
148
  catch (err) {
169
149
  const message = err instanceof Error ? err.message : String(err);
@@ -211,33 +191,6 @@ function buildDelegatedGatewayOptions({ env }, deps) {
211
191
  delegatedToolTimeoutMs: rawTimeout === undefined ? undefined : Number(rawTimeout),
212
192
  });
213
193
  }
214
- function buildTools({ runId, delegatedGatewayOptions }) {
215
- return [
216
- ...RUN_TOOLS,
217
- ...TOOL_CATALOG_TOOLS,
218
- ...COMPONENT_CATALOG_TOOLS,
219
- createExecuteDelegatedToolTool({ runId }, delegatedGatewayOptions),
220
- // Hosted ALONGSIDE the unconstrained gateway, never instead of it. A client that gates on
221
- // `readOnlyHint: true` can now reach the read half of the catalog at all; every other client
222
- // sees both and picks by what its call actually does.
223
- createExecuteReadonlyDelegatedToolTool({ runId }, delegatedGatewayOptions),
224
- ];
225
- }
226
- function buildServerOptions({ env, runId, delegatedGatewayOptions }, deps) {
227
- // Absent credential => no `authHeaders` at all => byte-identical request headers to before this
228
- // env var existed. See DAEMON_TOKEN_ENV_VAR's doc for why an unset value is not a startup failure.
229
- const credential = env[DAEMON_TOKEN_ENV_VAR];
230
- return {
231
- resources: [...KERNEL_RESOURCES, createSiteGuideResource({ runId }, delegatedGatewayOptions)],
232
- instructions: INSTRUCTIONS,
233
- ...definedOnly({
234
- authHeaders: credential ? { Authorization: `Bearer ${credential}` } : undefined,
235
- fetchImpl: deps.fetchImpl,
236
- stdin: deps.stdin,
237
- stdout: deps.stdout,
238
- }),
239
- };
240
- }
241
194
  // Only the spawning host supplies registration metadata. Never learn exceptions from an
242
195
  // error body or model arguments: either would turn a secret into its own redaction exemption.
243
196
  function parseLaunchToolIds({ env, key }) {
@@ -247,28 +200,6 @@ function parseLaunchToolIds({ env, key }) {
247
200
  }
248
201
  return toolIds;
249
202
  }
250
- /**
251
- * Resolve each unique startup ID through the existing authenticated describe/publication owner.
252
- * The temporary descriptor list seeds M1's bounded exposure; it is not an execution catalog.
253
- * Failure aborts startup before any partially resolved list can reach the client.
254
- * @returns Authoritative descriptors; no daemon I/O when startup IDs are absent.
255
- * @throws The existing descriptor/daemon errors, reported by serve's stderr/exit boundary.
256
- * @complexity O(n + s) space/time plus n sequential bounded GETs for n unique IDs and s schema bytes.
257
- */
258
- async function resolveStartupTools({ toolIds, resolveBaseUrl, serverOptions }) {
259
- if (toolIds.length === 0)
260
- return [];
261
- const descriptors = [];
262
- const ctx = {
263
- baseUrl: await resolveBaseUrl(),
264
- fetchImpl: serverOptions.fetchImpl ?? fetch,
265
- ...definedOnly({ authHeaders: serverOptions.authHeaders, diagnosticToolIds: serverOptions.diagnosticToolIds }),
266
- publishTool: async ({ descriptor }) => { descriptors.push(descriptor); },
267
- };
268
- for (const id of new Set(toolIds))
269
- await describeToolTool.handler({ args: { id }, ctx });
270
- return descriptors;
271
- }
272
203
  // Only run for real when this module is the actual process entrypoint (`node dist/bin/serve.js`,
273
204
  // or the `jini-mcp` bin shim pnpm/npm links to it) — not merely imported, e.g. by this file's own
274
205
  // tests importing the named `serve` export above. Mirrors the CLI entry point's identical guard.
@@ -1,3 +1,5 @@
1
+ import { inspect } from 'node:util';
2
+ import { redactSecrets } from '@jini-ai/core';
1
3
  import { isLoopbackHostname } from '@jini-ai/platform/net';
2
4
  /**
3
5
  * @module @jini-ai/mcp/core/config
@@ -232,7 +234,7 @@ export async function readMcpConfig({ dataDir }, { filesystem = defaultFilesyste
232
234
  if (e.code === 'ENOENT')
233
235
  return { servers: [] };
234
236
  if (e.name === 'SyntaxError') {
235
- console.error('[mcp-config] Corrupted JSON, returning empty:', e.message);
237
+ console.error('[mcp-config] Corrupted JSON, returning empty:', redactSecrets({ input: inspect(e) }, { redactPii: false }));
236
238
  return { servers: [] };
237
239
  }
238
240
  throw err;
@@ -1,3 +1,5 @@
1
+ import { inspect } from 'node:util';
2
+ import { redactSecrets } from '@jini-ai/core';
1
3
  import { createSystemClock } from "@jini-ai/core/primitives";
2
4
  /**
3
5
  * @module @jini-ai/mcp/core/tokens
@@ -145,7 +147,7 @@ export async function readTokensFile({ dataDir }, options = {}) {
145
147
  filePath: `${tokensFile(dataDir)}.corrupt-${digest}`,
146
148
  contents: raw,
147
149
  });
148
- console.error('[mcp-tokens] Corrupted JSON, returning empty:', e.message);
150
+ console.error('[mcp-tokens] Corrupted JSON, returning empty:', redactSecrets({ input: inspect(e) }, { redactPii: false }));
149
151
  return { ...EMPTY, servers: { ...EMPTY.servers } };
150
152
  }
151
153
  throw err;
@@ -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. */
@@ -46,10 +46,9 @@ export interface AttachFederatedToolsResult {
46
46
  * connection was simply invisible everywhere an operator could look — `GET
47
47
  * /api/federation/admissions` showed no row for it and `configFailures` (a SEPARATE, boot-time
48
48
  * config-resolution channel — see `external-mcp-connection-source.ts`) has no way to know about a
49
- * failure that happens deeper, inside `connect()` itself. `reason` is `messageOf(error)` — the
50
- * same text `logger.warn` already prints for this exact failure, so this field discloses nothing
51
- * that was not already reaching this process's own stderr; it is never a raw env value or secret,
52
- * since nothing in this file's `connect`/`spawn` error paths ever formats one into a message.
49
+ * failure that happens deeper, inside `connect()` itself. The message is redacted before it
50
+ * reaches this caller-visible field: remote failures can echo tokens and credentialed URLs,
51
+ * and the log's separate redaction does not protect the returned value.
53
52
  */
54
53
  readonly connectFailures: readonly {
55
54
  readonly connectionId: string;
@@ -75,6 +74,8 @@ export interface AttachFederatedToolsResult {
75
74
  * @complexity O(c · t) in connections and their advertised tools.
76
75
  */
77
76
  export interface AttachFederatedMcpToolsParams {
77
+ /** Host approval adapter, replayed against frozen definitions when the owner's grants change. */
78
+ readonly buildRegistrations?: typeof buildFederatedMcpRegistrations;
78
79
  readonly presetRegistry?: FederatedMcpPresetRegistry;
79
80
  registry: ToolRegistry;
80
81
  deps: FederationDeps;
@@ -1,6 +1,9 @@
1
+ import { inspect } from 'node:util';
2
+ import { redactSecrets } from '@jini-ai/core';
1
3
  import { createConsoleLogger } from "@jini-ai/core/primitives";
2
4
  import { defaultFederatedMcpPresetRegistry } from "./presets.js";
3
5
  import { federateSession } from "./registrations.js";
6
+ import { registerFrozenFederationConnection } from './frozen-grants.js';
4
7
  /**
5
8
  * @file The composition root for outbound MCP federation: the one function
6
9
  * `agent-daemon-server.ts` calls, and the only place in this subtree that performs I/O it was not
@@ -73,7 +76,7 @@ export async function attachFederatedMcpTools(requiredArgs, optionalArgs = {}) {
73
76
  const reports = [];
74
77
  const connectFailures = [];
75
78
  for (const { connection, isPreset } of connections) {
76
- 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 } : {}) });
77
80
  registeredToolIds.push(...attached.registeredToolIds);
78
81
  if (attached.session)
79
82
  sessions.push(attached.session);
@@ -97,6 +100,16 @@ function registerFederatedTools(registry, registrations) {
97
100
  }
98
101
  return registeredToolIds;
99
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
+ }
100
113
  /** Logs one connection's full admission accounting. Refusals are reported, never silent —
101
114
  * `buildDomainRegistrations`'s own "silence is never the outcome" discipline. An operator
102
115
  * debugging a missing tool needs the reason, and an operator reading logs after an incident needs
@@ -138,17 +151,23 @@ async function attachOneFederatedConnection(params) {
138
151
  // Snapshotted here, immediately before the admission check, so the collision assertion sees
139
152
  // every native tool AND every tool an earlier connection in this same loop already claimed.
140
153
  const nativeToolIds = new Set(registry.list({}).map((descriptor) => descriptor.id));
141
- const { registrations, report } = await federateSession({ session, config: connection.config, deps, nativeToolIds });
142
- 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 });
143
156
  logger.info({ message: `mcp-federation: '${connectionId}' registered ${registrations.length} federated tool(s): ${registrations.map((r) => r.descriptor.id).join(", ") || "(none)"}` });
144
157
  logFederatedAdmissionReport(connectionId, report, logger);
158
+ // An empty grant has no callable handler retaining this session. Release its child/socket
159
+ // before a later operator grant re-admits the row with a new session.
160
+ if (connection.config.allowedToolNames.length === 0) {
161
+ await session.close({});
162
+ return { registeredToolIds, session: null, report };
163
+ }
145
164
  return { registeredToolIds, session, report };
146
165
  }
147
166
  catch (error) {
148
- logger.warn({ message: `mcp-federation: '${connectionId}' failed, continuing without its tools — ${messageOf(error)}` });
167
+ logger.warn({ message: `mcp-federation: '${connectionId}' failed, continuing without its tools — ${redactSecrets({ input: inspect(error) }, { redactPii: false })}` });
149
168
  // A session that connected but failed during listing/admission still owns a child process.
150
169
  await session?.close({}).catch(() => undefined);
151
- return { registeredToolIds: [], session: null, report: null, connectFailureReason: messageOf(error) };
170
+ return { registeredToolIds: [], session: null, report: null, connectFailureReason: redactSecrets({ input: messageOf(error) }, { redactPii: false }) };
152
171
  }
153
172
  }
154
173
  /**
@@ -171,7 +190,7 @@ export function resolveFederatedMcpPresets({ env, logger, registry }, _optional
171
190
  connections.push(connection);
172
191
  }
173
192
  catch (error) {
174
- logger.warn({ message: `mcp-federation: preset '${preset.presetId}' configuration is invalid, continuing without federated tools — ${messageOf(error)}` });
193
+ logger.warn({ message: `mcp-federation: preset '${preset.presetId}' configuration is invalid, continuing without federated tools — ${redactSecrets({ input: inspect(error) }, { redactPii: false })}` });
175
194
  }
176
195
  }
177
196
  return connections;
@@ -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,24 +12,29 @@ 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 that has already 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.
26
+ * A roster row admitted with an empty allowlist and no tools can wait for its first operator grant.
27
+ * Retrying that row replaces no tool or classification; after its first nonempty admission it freezes
28
+ * just like every other connection. An unchanged empty grant never triggers another handshake.
25
29
  *
26
30
  * That admission freeze no longer means an operator's edit is inert until restart, though —
27
31
  * `external-mcp-revocation.ts`'s per-call gate (`mcp-federation/registrations.ts`'s
28
32
  * `FederationDeps.assertConnectionUsable`) re-reads the connection's row on every call, independent of
29
33
  * this reload path. Turning a connection off, deleting it, disconnecting its OAuth, or narrowing its
30
34
  * 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
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
33
38
  * `"changed"` (the row's admission revision no longer matches what the tool was admitted under) until
34
39
  * the process restarts and re-admits the connection fresh.
35
40
  *
@@ -56,7 +61,7 @@ export declare function selectUnadmittedConnections({ allConnections, admittedCo
56
61
  admittedConnectionIds: ReadonlySet<string>;
57
62
  }): readonly ResolvedFederatedConnection[];
58
63
  export interface FederationReloadResult {
59
- /** 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. */
60
65
  readonly newlyAdmittedConnectionIds: readonly string[];
61
66
  /** This pass's own admission reports only, in `attachFederatedMcpTools`'s own shape — the caller
62
67
  * (`agent-daemon-server.ts`) merges these into the running, boot-plus-every-reload accounting
@@ -108,5 +113,7 @@ export interface FederationReloadCoordinator {
108
113
  export declare function createFederationReloadCoordinator({ coordDeps, initiallyAdmitted }: {
109
114
  coordDeps: FederationReloadCoordinatorDeps;
110
115
  initiallyAdmitted: Iterable<string>;
116
+ }, { initiallyAwaitingGrants }?: {
117
+ initiallyAwaitingGrants?: Iterable<string>;
111
118
  }): FederationReloadCoordinator;
112
119
  //# sourceMappingURL=reload.d.ts.map
@@ -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,24 +10,29 @@ 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 that has already 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.
24
+ * A roster row admitted with an empty allowlist and no tools can wait for its first operator grant.
25
+ * Retrying that row replaces no tool or classification; after its first nonempty admission it freezes
26
+ * just like every other connection. An unchanged empty grant never triggers another handshake.
22
27
  *
23
28
  * That admission freeze no longer means an operator's edit is inert until restart, though —
24
29
  * `external-mcp-revocation.ts`'s per-call gate (`mcp-federation/registrations.ts`'s
25
30
  * `FederationDeps.assertConnectionUsable`) re-reads the connection's row on every call, independent of
26
31
  * this reload path. Turning a connection off, deleting it, disconnecting its OAuth, or narrowing its
27
32
  * allowlist or write list all take effect on the very NEXT call, with no restart and no reload
28
- * required. Widening the allowlist, or changing the server's address, command, args or sign-in method,
29
- * 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
30
36
  * `"changed"` (the row's admission revision no longer matches what the tool was admitted under) until
31
37
  * the process restarts and re-admits the connection fresh.
32
38
  *
@@ -57,28 +63,45 @@ export function selectUnadmittedConnections({ allConnections, admittedConnection
57
63
  * @complexity `reload()` is O(c · t) in the unadmitted connection count and their advertised tools
58
64
  * (the underlying `attachFederatedMcpTools` cost); `admittedConnectionIds()` is O(1).
59
65
  */
60
- export function createFederationReloadCoordinator({ coordDeps, initiallyAdmitted }) {
66
+ export function createFederationReloadCoordinator({ coordDeps, initiallyAdmitted }, { initiallyAwaitingGrants = [] } = {}) {
61
67
  const admitted = new Set(initiallyAdmitted);
68
+ const awaitingGrants = new Set(initiallyAwaitingGrants);
62
69
  const attach = coordDeps.attach ?? attachFederatedMcpTools;
63
70
  let inFlight = null;
64
71
  let queuedNext = null;
65
72
  async function runOnePass() {
66
73
  const allConnections = await coordDeps.resolveConnections();
67
- const unadmitted = selectUnadmittedConnections({ allConnections: allConnections, admittedConnectionIds: admitted });
74
+ const refreshed = refreshFrozenFederationGrants({ registry: coordDeps.registry, connections: allConnections });
75
+ const eligibleIds = new Set(admitted);
76
+ for (const connection of allConnections) {
77
+ if (awaitingGrants.has(connection.config.connectionId) && connection.config.allowedToolNames.length > 0)
78
+ eligibleIds.delete(connection.config.connectionId);
79
+ }
80
+ const unadmitted = selectUnadmittedConnections({ allConnections, admittedConnectionIds: eligibleIds });
68
81
  if (unadmitted.length === 0)
69
- return { newlyAdmittedConnectionIds: [], reports: [], connectFailures: [] };
82
+ return { newlyAdmittedConnectionIds: refreshed.map(entry => entry.connectionId), reports: refreshed, connectFailures: [] };
70
83
  // Empty, not omitted: omission resolves presets from the environment again, even though the
71
84
  // boot pass already admitted them. Reload concerns only the operator-editable roster;
72
85
  // environment presets cannot change without a real restart.
73
86
  const attached = await attach({ registry: coordDeps.registry, deps: coordDeps.deps, connect: coordDeps.connect }, { connections: [], extraConnections: unadmitted, ...(coordDeps.logger ? { logger: coordDeps.logger } : {}) });
74
- for (const entry of attached.reports)
75
- admitted.add(entry.connectionId);
87
+ const attemptedConnections = new Map(unadmitted.map(connection => [connection.config.connectionId, connection]));
88
+ for (const entry of attached.reports) {
89
+ rememberAdmission({ entry, connection: attemptedConnections.get(entry.connectionId) });
90
+ }
76
91
  return {
77
- newlyAdmittedConnectionIds: attached.reports.map((entry) => entry.connectionId),
78
- reports: attached.reports,
92
+ newlyAdmittedConnectionIds: [...refreshed, ...attached.reports].map((entry) => entry.connectionId),
93
+ reports: [...refreshed, ...attached.reports],
79
94
  connectFailures: attached.connectFailures,
80
95
  };
81
96
  }
97
+ /** Only a successful empty-grant admission remains eligible for its first operator grant. O(1). */
98
+ function rememberAdmission({ entry, connection }, _options = {}) {
99
+ admitted.add(entry.connectionId);
100
+ if (connection?.config.allowedToolNames.length === 0 && entry.report.admitted.length === 0)
101
+ awaitingGrants.add(entry.connectionId);
102
+ else
103
+ awaitingGrants.delete(entry.connectionId);
104
+ }
82
105
  function reload(_required) {
83
106
  if (!inFlight) {
84
107
  inFlight = runOnePass().finally(() => {
package/dist/index.d.ts CHANGED
@@ -12,8 +12,8 @@ export type { StoredMcpToken, McpTokensFile } from './core/index.js';
12
12
  export { buildMcpInstallPayload } from './core/index.js';
13
13
  export type { BuildMcpInstallPayloadInputs, McpInstallPayload } from './core/index.js';
14
14
  export { createMcpIdleExitController, extractRelativeRefs, isTextualMime, } from './client/index.js';
15
- export { cancelRunTool, createMcpToolServer, daemonCallOptions, errorResult, getActiveContextTool, getDaemonJson, getRunTool, listAgentsTool, okResult, postDaemonJson, requireString, RUN_TOOLS, startRunTool, toolsToList, buildToolIndex, handleToolCall, DaemonResponseTooLargeError, } from './server/index.js';
16
- export type { DaemonRequestOptions, McpServerLike, McpToolContext, McpToolDef, McpToolServerHandle, McpToolServerOptions, McpTransportLike, } from './server/index.js';
15
+ export { cancelRunTool, createMcpToolServer, startMcpHttpToolServer, createMcpHttpToolServerRuntime, daemonCallOptions, errorResult, getActiveContextTool, getDaemonJson, getRunTool, listAgentsTool, okResult, postDaemonJson, requireString, RUN_TOOLS, startRunTool, toolsToList, buildToolIndex, handleToolCall, DaemonResponseTooLargeError, } from './server/index.js';
16
+ export type { DaemonRequestOptions, McpServerLike, McpToolContext, McpToolDef, McpToolServerHandle, McpHttpToolServerHandle, McpHttpToolServerRuntime, McpHttpToolServerOptions, McpToolServerOptions, McpTransportLike, } from './server/index.js';
17
17
  export { activeContextResource, createSiteGuideResource, buildResourceIndex, handleResourceRead, KERNEL_RESOURCES, resourcesToList, } from './server/index.js';
18
18
  export type { McpResourceDef, McpResourceReadResult } from './server/index.js';
19
19
  export { searchToolsTool, describeToolTool, TOOL_CATALOG_TOOLS } from './server/index.js';
@@ -29,4 +29,7 @@ export type { McpIdleTimerPort } from './client/client.js';
29
29
  export type { McpToolServerRequiredArgs } from './server/tool-server.js';
30
30
  export type { CreateExecuteDelegatedToolToolRequiredArgs } from './server/tools/delegated-tool.js';
31
31
  export { DaemonHttpError } from './server/daemon-client.js';
32
+ export { assembleRunToolHost } from './server/run-tool-host.js';
33
+ export type { RunToolHostInput, RunToolHostOptions, RunToolHost } from './server/run-tool-host.js';
34
+ export { MCP_HTTP_SESSION_MODE_SUPPORTED } from './server/http-tool-server.js';
32
35
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ export { buildMcpInstallPayload } from './core/index.js';
14
14
  // ── client: product-neutral stdio-server runtime primitives ─────────────────
15
15
  export { createMcpIdleExitController, extractRelativeRefs, isTextualMime, } from './client/index.js';
16
16
  // ── server: the generic MCP tool-hosting mechanism + kernel-run tool defs ───
17
- export { cancelRunTool, createMcpToolServer, daemonCallOptions, errorResult, getActiveContextTool, getDaemonJson, getRunTool, listAgentsTool, okResult, postDaemonJson, requireString, RUN_TOOLS, startRunTool, toolsToList, buildToolIndex, handleToolCall, DaemonResponseTooLargeError, } from './server/index.js';
17
+ export { cancelRunTool, createMcpToolServer, startMcpHttpToolServer, createMcpHttpToolServerRuntime, daemonCallOptions, errorResult, getActiveContextTool, getDaemonJson, getRunTool, listAgentsTool, okResult, postDaemonJson, requireString, RUN_TOOLS, startRunTool, toolsToList, buildToolIndex, handleToolCall, DaemonResponseTooLargeError, } from './server/index.js';
18
18
  // ── server: the generic MCP resource surface + kernel resource defs ────────
19
19
  export { activeContextResource, createSiteGuideResource, buildResourceIndex, handleResourceRead, KERNEL_RESOURCES, resourcesToList, } from './server/index.js';
20
20
  // ── server: the tool-catalog discovery defs (search_tools / describe_tool) ──
@@ -26,4 +26,6 @@ export { createExecuteDelegatedToolTool, createExecuteReadonlyDelegatedToolTool,
26
26
  // ── agent-install: register an MCP server into external agents ──────────────
27
27
  export { CHROME_DEVTOOLS_MCP_PRESET, AGENT_SLUGS, isAgentSlug, planAgentInstall, verifyJsonAgentInstall, applyJsonInstall, removeJsonInstall, } from './agent-install/index.js';
28
28
  export { DaemonHttpError } from './server/daemon-client.js';
29
+ export { assembleRunToolHost } from './server/run-tool-host.js';
30
+ export { MCP_HTTP_SESSION_MODE_SUPPORTED } from './server/http-tool-server.js';
29
31
  //# sourceMappingURL=index.js.map