@jini-ai/mcp 0.6.23 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/agent-install/index.d.ts +1 -0
  3. package/dist/agent-install/index.js +1 -0
  4. package/dist/agent-install/install.d.ts +2 -1
  5. package/dist/agent-install/install.js +28 -6
  6. package/dist/agent-install/owned-json-install.d.ts +12 -0
  7. package/dist/agent-install/owned-json-install.js +48 -0
  8. package/dist/federation/adapter.http.d.ts +3 -6
  9. package/dist/federation/bootstrap.js +15 -2
  10. package/dist/federation/config.d.ts +3 -0
  11. package/dist/federation/frozen-grants.d.ts +11 -1
  12. package/dist/federation/frozen-grants.js +14 -0
  13. package/dist/federation/hosted/access.d.ts +92 -0
  14. package/dist/federation/hosted/access.js +116 -0
  15. package/dist/federation/hosted/auth.d.ts +69 -0
  16. package/dist/federation/hosted/auth.js +70 -0
  17. package/dist/federation/hosted/connection-gate.d.ts +83 -0
  18. package/dist/federation/hosted/connection-gate.js +107 -0
  19. package/dist/federation/hosted/index.d.ts +14 -0
  20. package/dist/federation/hosted/index.js +13 -0
  21. package/dist/federation/hosted/projections.d.ts +15 -0
  22. package/dist/federation/hosted/projections.js +15 -0
  23. package/dist/federation/hosted/revocation.d.ts +70 -0
  24. package/dist/federation/hosted/revocation.js +78 -0
  25. package/dist/federation/hosted/store-ports.d.ts +95 -0
  26. package/dist/federation/hosted/store-ports.js +2 -0
  27. package/dist/federation/hosted/store.d.ts +211 -0
  28. package/dist/federation/hosted/store.js +1441 -0
  29. package/dist/federation/hosted/store.memory.d.ts +41 -0
  30. package/dist/federation/hosted/store.memory.js +149 -0
  31. package/dist/federation/hosted/unconfigured-error.d.ts +7 -0
  32. package/dist/federation/hosted/unconfigured-error.js +10 -0
  33. package/dist/federation/hosted/validation-error.d.ts +8 -0
  34. package/dist/federation/hosted/validation-error.js +12 -0
  35. package/dist/federation/hosted/vault.d.ts +68 -0
  36. package/dist/federation/hosted/vault.js +106 -0
  37. package/dist/federation/hosted/vocabulary.d.ts +17 -0
  38. package/dist/federation/hosted/vocabulary.js +17 -0
  39. package/dist/federation/index.d.ts +1 -0
  40. package/dist/federation/index.js +1 -0
  41. package/dist/federation/ports.d.ts +4 -0
  42. package/dist/federation/registrations.js +1 -0
  43. package/dist/federation/stdio/default-connect.js +1 -1
  44. package/dist/index.d.ts +2 -2
  45. package/dist/index.js +2 -2
  46. package/dist/server/{http-tool-server.d.ts → http-tool-server.adapter.d.ts} +1 -1
  47. package/dist/server/{http-tool-server.js → http-tool-server.adapter.js} +1 -1
  48. package/dist/server/index.d.ts +1 -1
  49. package/dist/server/index.js +1 -1
  50. package/dist/server/tool-result-pages.d.ts +1 -1
  51. package/package.json +14 -8
package/CHANGELOG.md CHANGED
@@ -1,3 +1,25 @@
1
+ ## 0.7.0
2
+
3
+ ### Minor Changes
4
+
5
+ - 27063ef: Add the node entry `@jini-ai/mcp/federation/hosted` with hosted MCP vocabulary constants, auth/status readers, admission revision/snapshot/tool-grant helpers, the canonical validation and unconfigured error classes, and `hostedMcpProjections`. `McpBearerTokenSupplier` is now re-exported from core under the same name.
6
+ - 0203256: Hosted MCP store, in-memory repository, vault envelope module and revocation decision now live in `@jini-ai/mcp/federation/hosted`. Hosts bind vault, error, metadata-parser, credential-policy and settings-link ports once (`HostedMcpStorePorts`); saved formats, AAD and seal counts are unchanged.
7
+ - 50f6e4c: Add `createHostedMcpConnectionGate` (+ `HostedMcpConnectionGatePorts`, `ExternalMcpConnectionGateDeps`) to `@jini-ai/mcp/federation/hosted`: the per-call liveness and revocation gate for hosted MCP connections, with reauth/revoked errors, recovery copy and operator log injected as ports.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [8fe045b]
12
+ - Updated dependencies [c393010]
13
+ - Updated dependencies [41ff2ff]
14
+ - Updated dependencies [a266ba8]
15
+ - Updated dependencies [27063ef]
16
+ - Updated dependencies [6ab1d81]
17
+ - Updated dependencies [699b478]
18
+ - Updated dependencies [39cf677]
19
+ - @jini-ai/core@0.7.0
20
+ - @jini-ai/platform@0.7.0
21
+ - @jini-ai/protocol@0.7.0
22
+
1
23
  ## 0.6.23
2
24
 
3
25
  - Security hardening.
@@ -7,4 +7,5 @@
7
7
  */
8
8
  export * from './install.js';
9
9
  export { CHROME_DEVTOOLS_MCP_PRESET } from './chrome-devtools.js';
10
+ export { installOwnedJsonAgent } from './owned-json-install.js';
10
11
  //# sourceMappingURL=index.d.ts.map
@@ -7,4 +7,5 @@
7
7
  */
8
8
  export * from './install.js';
9
9
  export { CHROME_DEVTOOLS_MCP_PRESET } from './chrome-devtools.js';
10
+ export { installOwnedJsonAgent } from './owned-json-install.js';
10
11
  //# sourceMappingURL=index.js.map
@@ -102,7 +102,8 @@ export declare function planAgentInstall({ slug, spec, ctx }: {
102
102
  }): InstallPlan;
103
103
  /**
104
104
  * Merge one server entry into existing config text without disturbing the
105
- * rest. Missing intermediate objects are created. Returns pretty JSON with
105
+ * rest. Missing intermediate objects are created; an entry under the same name that launches this
106
+ * package's bridge (an earlier install) is replaced; any other named entry and non-object paths are refused. Returns pretty JSON with
106
107
  * a trailing newline. Throws if existing text is non-empty but unparseable
107
108
  * (caller decides whether to bail or back up), or if `plan.keyPath` /
108
109
  * `plan.serverKey` contains a dangerous object-path segment (CR-007).
@@ -32,6 +32,7 @@
32
32
  // The planning functions are pure (no fs / spawn) so they unit-test
33
33
  // against fixed launch specs + a fake home dir; the executor performs the IO.
34
34
  import path from 'node:path';
35
+ import { isDeepStrictEqual } from 'node:util';
35
36
  /**
36
37
  * Exhaustive tuple of all agent slugs recognized by `mcp install`.
37
38
  * Used as the source of truth for the `AgentSlug` union type and the `isAgentSlug` guard.
@@ -235,7 +236,8 @@ function assertSafeJsonInstallPlan(plan) {
235
236
  }
236
237
  /**
237
238
  * Merge one server entry into existing config text without disturbing the
238
- * rest. Missing intermediate objects are created. Returns pretty JSON with
239
+ * rest. Missing intermediate objects are created; an entry under the same name that launches this
240
+ * package's bridge (an earlier install) is replaced; any other named entry and non-object paths are refused. Returns pretty JSON with
239
241
  * a trailing newline. Throws if existing text is non-empty but unparseable
240
242
  * (caller decides whether to bail or back up), or if `plan.keyPath` /
241
243
  * `plan.serverKey` contains a dangerous object-path segment (CR-007).
@@ -246,14 +248,34 @@ export function applyJsonInstall({ existingText, plan }) {
246
248
  let cursor = root;
247
249
  for (const key of plan.keyPath) {
248
250
  const next = cursor[key];
249
- if (next == null || typeof next !== 'object' || Array.isArray(next)) {
250
- cursor[key] = {};
251
+ if (next !== undefined && (next === null || typeof next !== 'object' || Array.isArray(next))) {
252
+ throw new Error('Existing MCP config path is not an object');
251
253
  }
254
+ if (next === undefined)
255
+ cursor[key] = {};
252
256
  cursor = cursor[key];
253
257
  }
258
+ if (Object.hasOwn(cursor, plan.serverKey) && !isDeepStrictEqual(cursor[plan.serverKey], plan.entry)
259
+ && !launchesJiniBridge({ entry: cursor[plan.serverKey] })) {
260
+ throw new Error(`${plan.configPath} already has an MCP server named "${plan.serverKey}" that this app did not add, so it was left as it is. `
261
+ + `Rename or remove that "${plan.serverKey}" entry, then try again, or choose another agent.`);
262
+ }
254
263
  cursor[plan.serverKey] = plan.entry;
255
264
  return `${JSON.stringify(root, null, 2)}\n`;
256
265
  }
266
+ /** The bridge script every install of this package launches: `<pkg>/dist/bin/serve.js`, published as
267
+ * `@jini-ai/mcp` (or the earlier `@jini/mcp`) or linked from a `jini/packages/mcp` checkout. */
268
+ const JINI_BRIDGE_SCRIPT = /(?:^|\/)(?:@jini(?:-ai)?|jini\/packages)\/mcp\/dist\/bin\/serve\.js$/i;
269
+ /** True when an existing entry launches this package's own bridge, i.e. an earlier install wrote it
270
+ * (another install path, Node binary, env or enabled flag). Covers both the `command`+`args` and the
271
+ * folded OpenCode `command: [bin, ...args]` shapes. O(launch strings). */
272
+ function launchesJiniBridge({ entry }) {
273
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
274
+ return false;
275
+ const { command, args } = entry;
276
+ const launch = [...(Array.isArray(command) ? command : [command]), ...(Array.isArray(args) ? args : [])];
277
+ return launch.some(part => typeof part === 'string' && JINI_BRIDGE_SCRIPT.test(part.replaceAll('\\', '/')));
278
+ }
257
279
  /**
258
280
  * Remove the server entry. Returns the new text, or null when the file did
259
281
  * not exist / had nothing to remove (caller treats null as a no-op). Throws
@@ -285,9 +307,9 @@ function parseJsonObject(text, where) {
285
307
  try {
286
308
  parsed = JSON.parse(text);
287
309
  }
288
- catch (err) {
289
- // JSON.parse only ever throws a SyntaxError, so `err` is always an Error.
290
- throw new Error(`existing config at ${where} is not valid JSON: ${err.message}`);
310
+ catch {
311
+ // JSON.parse only throws SyntaxError; its message may quote private configuration bytes.
312
+ throw new Error(`existing config at ${where} is not valid JSON`);
291
313
  }
292
314
  if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) {
293
315
  throw new Error(`existing config at ${where} is not a JSON object`);
@@ -0,0 +1,12 @@
1
+ import { type McpLaunchSpec, type PlanContext } from './install.js';
2
+ /** Install one owned static connector after explicit consent, preserving foreign data and a first backup.
3
+ * The host must call this only for a CLI without a temporary config path. No token is accepted or minted.
4
+ * @complexity O(config bytes) time and space; one locked read and, when changed, backup plus atomic write.
5
+ */
6
+ export declare function installOwnedJsonAgent(required: {
7
+ agentId: string;
8
+ spec: McpLaunchSpec;
9
+ ctx: PlanContext;
10
+ allowed: boolean;
11
+ }, _optional?: Record<string, never>): Promise<void>;
12
+ //# sourceMappingURL=owned-json-install.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { backupOriginalOnce, withFileLock, writeFileAtomicAsync } from '@jini-ai/platform/fs';
4
+ import { applyJsonInstall, isAgentSlug, planAgentInstall } from './install.js';
5
+ /** Missing is the only condition permitting creation; reject symlinks even for an unchanged entry. */
6
+ async function readConfig({ path }) {
7
+ try {
8
+ if ((await fs.lstat(path)).isSymbolicLink())
9
+ throw new Error('MCP config is a symlink; choose another agent.');
10
+ return await fs.readFile(path, 'utf8');
11
+ }
12
+ catch (error) {
13
+ if (error.code !== 'ENOENT')
14
+ throw error;
15
+ return null;
16
+ }
17
+ }
18
+ /** Persistent connectors contain no run credentials. Only the static Electron switch is permitted. */
19
+ function assertCredentialFree({ spec }) {
20
+ if (Object.entries(spec.env).some(([key, value]) => key !== 'ELECTRON_RUN_AS_NODE' || value !== '1')) {
21
+ throw new Error('MCP connector contains run environment values and cannot be saved.');
22
+ }
23
+ }
24
+ /** Install one owned static connector after explicit consent, preserving foreign data and a first backup.
25
+ * The host must call this only for a CLI without a temporary config path. No token is accepted or minted.
26
+ * @complexity O(config bytes) time and space; one locked read and, when changed, backup plus atomic write.
27
+ */
28
+ export async function installOwnedJsonAgent(required, _optional = {}) {
29
+ if (required.allowed !== true)
30
+ throw new Error('Allow this agent to change its settings outside the host before installing its connector.');
31
+ assertCredentialFree(required);
32
+ const slug = { value: required.agentId };
33
+ if (!isAgentSlug(slug))
34
+ throw new Error('Unknown MCP agent installation');
35
+ const plan = planAgentInstall({ slug: slug.value, spec: required.spec, ctx: required.ctx });
36
+ if (plan.kind !== 'json')
37
+ throw new Error('MCP installation does not use a JSON registry');
38
+ await withFileLock({ lockPath: `${plan.configPath}.jini-lock`, run: async () => {
39
+ const existingText = await readConfig({ path: plan.configPath });
40
+ const content = applyJsonInstall({ existingText, plan });
41
+ if (existingText !== null && isDeepStrictEqual(JSON.parse(existingText), JSON.parse(content)))
42
+ return;
43
+ if (existingText !== null)
44
+ await backupOriginalOnce({ filePath: plan.configPath });
45
+ await writeFileAtomicAsync({ filePath: plan.configPath, content }, { refuseSymlink: true });
46
+ } }, { createParent: true, timeoutMs: 5000 });
47
+ }
48
+ //# sourceMappingURL=owned-json-install.js.map
@@ -1,3 +1,4 @@
1
+ import type { McpBearerTokenSupplier } from "@jini-ai/core/contracts/hosted-mcp";
1
2
  import type { FederationMessages } from "./messages.js";
2
3
  import type { TextReadOptions } from "@jini-ai/platform/fetch-with-timeout";
3
4
  import type { McpHttpExchange, McpHttpLaunchSpec, McpSessionPort, McpClientInfo } from "./ports.js";
@@ -8,12 +9,8 @@ import type { McpHttpExchange, McpHttpLaunchSpec, McpSessionPort, McpClientInfo
8
9
  * always one whose handshake completed — mirroring `adapter.stdio.ts`, and for the same reason:
9
10
  * there is no half-initialized state a caller could accidentally use.
10
11
  */
11
- /** Supplies a current token per exchange. Undefined preserves configured headers. */
12
- export type McpBearerTokenSupplier = (request: {
13
- readonly url: string;
14
- }, options?: {
15
- readonly signal?: AbortSignal | undefined;
16
- }) => string | undefined | Promise<string | undefined>;
12
+ /** @agent-note Canonical type lives in `@jini-ai/core/contracts/hosted-mcp`; re-exported here so existing federation imports keep the same name. */
13
+ export type { McpBearerTokenSupplier } from "@jini-ai/core/contracts/hosted-mcp";
17
14
  /** Notifies the host of a 401, including its authentication challenge. No OAuth flow or retry here. */
18
15
  export type McpAuthenticationChallengeHook = (request: {
19
16
  readonly url: string;
@@ -137,6 +137,18 @@ function logFederatedAdmissionReport(connectionId, report, logger) {
137
137
  logger.warn({ message: `mcp-federation: '${connectionId}' write-authorizes '${drift}' but it is not in the allowlist — it will never be admitted until it is added to both` });
138
138
  }
139
139
  }
140
+ /** One public address label from the resolved transport; never exposes userinfo, path, headers or commands.
141
+ * @complexity O(u) for URL length, with no I/O. @overallScore 100 */
142
+ function publicConnectionHost({ connection }) {
143
+ if (!("url" in connection.launch))
144
+ return "local command";
145
+ try {
146
+ return new URL(connection.launch.url).hostname;
147
+ }
148
+ catch {
149
+ return "unknown";
150
+ }
151
+ }
140
152
  /** One iteration of {@link attachFederatedMcpTools}'s original inline loop body — connect, list,
141
153
  * admit, register, log — extracted purely to keep that function's complexity under the shop
142
154
  * ceiling. Fail-open per connection: any failure (connect, list, or admission) is logged and
@@ -145,14 +157,15 @@ function logFederatedAdmissionReport(connectionId, report, logger) {
145
157
  async function attachOneFederatedConnection(params) {
146
158
  const { connection, registry, deps, connect, logger } = params;
147
159
  const { connectionId } = connection.config;
160
+ const config = { ...connection.config, sourceHost: publicConnectionHost({ connection }) };
148
161
  let session;
149
162
  try {
150
163
  session = await connect({ connection });
151
164
  // Snapshotted here, immediately before the admission check, so the collision assertion sees
152
165
  // every native tool AND every tool an earlier connection in this same loop already claimed.
153
166
  const nativeToolIds = new Set(registry.list({}).map((descriptor) => descriptor.id));
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 });
167
+ const { registrations, report, frozenTools } = await federateSession({ session, config, deps, nativeToolIds, ...(params.buildRegistrations ? { buildRegistrations: params.buildRegistrations } : {}) });
168
+ const registeredToolIds = registerConnectedFederatedTools({ registry, session, config, deps, registrations, frozenTools, buildRegistrations: params.buildRegistrations });
156
169
  logger.info({ message: `mcp-federation: '${connectionId}' registered ${registrations.length} federated tool(s): ${registrations.map((r) => r.descriptor.id).join(", ") || "(none)"}` });
157
170
  logFederatedAdmissionReport(connectionId, report, logger);
158
171
  // An empty grant has no callable handler retaining this session. Release its child/socket
@@ -1,3 +1,4 @@
1
+ import type { McpBearerTokenSupplier } from "@jini-ai/core/contracts/hosted-mcp";
1
2
  import type { FederatedMcpConnectionConfig, McpLaunchSpec } from "./ports.js";
2
3
  /**
3
4
  * @file GENERIC configuration-resolution scaffolding for federated MCP connections — the parts every
@@ -34,6 +35,8 @@ import type { FederatedMcpConnectionConfig, McpLaunchSpec } from "./ports.js";
34
35
  export interface ResolvedFederatedConnection {
35
36
  readonly config: FederatedMcpConnectionConfig;
36
37
  readonly launch: McpLaunchSpec;
38
+ /** Live, connection-bound HTTP credential resolver; omitted connections keep their configured headers. */
39
+ readonly bearerToken?: McpBearerTokenSupplier;
37
40
  }
38
41
  /**
39
42
  * Shared ceilings, so two presets do not disagree about what a reasonable bound is.
@@ -1,9 +1,19 @@
1
1
  /** Owner grant changes reuse the connection's original untrusted tool snapshot (R5). */
2
2
  import { type ToolRegistry, type ToolRegistration } from '@jini-ai/core';
3
3
  import type { ResolvedFederatedConnection } from './config.js';
4
- import type { McpSessionPort, RemoteToolDescriptor, FederatedMcpConnectionConfig } from './ports.js';
4
+ import type { McpSessionPort, RemoteToolDescriptor, FederatedMcpConnectionConfig, FederatedConnectionOrigin } from './ports.js';
5
5
  import type { FederatedAdmissionReport } from './trust.js';
6
6
  import { buildFederatedMcpRegistrations, type FederationDeps } from './registrations.js';
7
+ /** Read only the original connection listing for the exact admitted source identity.
8
+ * Unavailable or replaced sources return null; querying never connects or lists remote tools.
9
+ * @returns Detached advertised names, including tools not yet granted by the owner.
10
+ * @complexity O(t) time/space for t names in the existing bounded listing; no I/O.
11
+ */
12
+ export declare function readFrozenFederationToolNames({ registry, connectionId, origin }: {
13
+ registry: ToolRegistry;
14
+ connectionId: string;
15
+ origin: FederatedConnectionOrigin;
16
+ }, _options?: {}): readonly string[] | null;
7
17
  /** Register one roster source in the existing core revocation scope and retain its first listing.
8
18
  * @returns Registered tool ids; remote snapshots stay private to this registry's lifetime.
9
19
  * @throws Core scope/collision errors before publishing a partial replacement.
@@ -2,6 +2,20 @@
2
2
  import { createToolRegistrationScope } from '@jini-ai/core';
3
3
  import { buildFederatedMcpRegistrations } from './registrations.js';
4
4
  const connectionsByRegistry = new WeakMap();
5
+ /** Read only the original connection listing for the exact admitted source identity.
6
+ * Unavailable or replaced sources return null; querying never connects or lists remote tools.
7
+ * @returns Detached advertised names, including tools not yet granted by the owner.
8
+ * @complexity O(t) time/space for t names in the existing bounded listing; no I/O.
9
+ */
10
+ export function readFrozenFederationToolNames({ registry, connectionId, origin }, _options = {}) {
11
+ const frozen = connectionsByRegistry.get(registry)?.get(connectionId);
12
+ const admittedOrigin = frozen?.config.origin;
13
+ if (!frozen || !admittedOrigin || admittedOrigin.kind !== origin.kind)
14
+ return null;
15
+ if (origin.kind === 'roster' && admittedOrigin.kind === 'roster' && origin.admissionRevision !== admittedOrigin.admissionRevision)
16
+ return null;
17
+ return frozen.tools.map(tool => tool.name);
18
+ }
5
19
  /** Compare only owner grants; remote definitions, endpoint identity and read trust remain frozen. */
6
20
  function grantsKey({ config }, _options = {}) {
7
21
  return JSON.stringify([config.allowedToolNames, config.writeAllowedToolNames]);
@@ -0,0 +1,92 @@
1
+ import type { ISODateTime } from "@jini-ai/core/primitives";
2
+ import type { ExternalMcpAccessSnapshot } from "@jini-ai/core/contracts/hosted-mcp";
3
+ /** Only source identity is hashed; credentials are represented by their existing ciphertext. */
4
+ interface ExternalMcpAdmissionSource {
5
+ readonly createdAt: ISODateTime;
6
+ readonly transport: string;
7
+ readonly url: string | null;
8
+ readonly command: string | null;
9
+ readonly args: string | null;
10
+ readonly authMode: string;
11
+ readonly sealedEnv: {
12
+ readonly ciphertext: string;
13
+ } | null;
14
+ readonly sealedOAuth: {
15
+ readonly ciphertext: string;
16
+ } | null;
17
+ }
18
+ type ExternalMcpAccessRecord = ExternalMcpAdmissionSource & Omit<ExternalMcpAccessSnapshot, "admissionRevision">;
19
+ /** Decode stored list columns; strict grant readers refuse malformed state. O(n) JSON bytes. */
20
+ /** @agent-note Pure decode of a saved JSON list column. Strict mode throws `ToolInputError` (model-facing, neutral wording); non-strict fails closed to `[]`. */
21
+ export declare function parseExternalMcpJsonArray({ raw }: {
22
+ raw: string | null;
23
+ }, { strict }?: {
24
+ strict?: boolean | undefined;
25
+ }): string[];
26
+ /**
27
+ * A connection's "admitted under this" fingerprint — what `revocation.ts`'s per-call
28
+ * gate compares a roster connection's row against to catch a delete-then-recreate, a
29
+ * url/command/args/transport/authMode edit, or a rotated/cleared static credential, none of
30
+ * which re-admit an already-running connection (the registry is append-only;
31
+ * `../reload.ts` never re-admits an admitted id).
32
+ *
33
+ * `sealedEnv`'s CIPHERTEXT is included: a `static_env`/`stdio` credential is
34
+ * resealed only when an operator actually submits a new `env` block — an ordinary toggle/rename
35
+ * leaves `env` undefined and carries the existing seal through byte-for-byte (see
36
+ * `resolveExternalMcpSealedEnv`'s `rawEnv === undefined` branch), so the ciphertext is stable across
37
+ * cosmetic saves and only moves when the credential itself is rotated or cleared. On `static_env`
38
+ * rows, `sealedOAuth` holds the dedicated static access token and follows the same preservation rule,
39
+ * so its ciphertext is included too. On OAuth rows it is excluded: re-sealing on token refresh must
40
+ * not refuse an otherwise valid connection.
41
+ *
42
+ * Otherwise deliberately narrow: `label`, `enabled`, both grant lists, OAuth status/expiry/tokens,
43
+ * and `updatedAt` are excluded, because none of them identify WHERE or via WHAT credentials a call
44
+ * reaches the remote, and including any of them would flip the revision on a toggle or a token
45
+ * refresh that must not refuse an already-admitted tool. `createdAt` is included so a delete +
46
+ * re-create under the same id (same url/command, different row) still changes the revision.
47
+ *
48
+ * Hashed rather than kept as plain text, because a hosted row's `url` can itself carry a bearer
49
+ * token as a query parameter — this value is compared, logged, and passed to a model-facing gate, so
50
+ * it must never be a place a credential could leak through.
51
+ *
52
+ * @complexity O(1).
53
+ * @overallScore 100
54
+ */
55
+ /** @agent-note Saved/compared format: sha256 hex over the exact JSON array below. Never reorder, add or drop inputs; existing approvals and per-call gates compare these bytes. */
56
+ export declare function externalMcpAdmissionRevision(record: ExternalMcpAdmissionSource): string;
57
+ /** Capture the source identity, exact previous grants and their decision, excluding token-refresh metadata.
58
+ * @agent-note Canonical saved representation: JSON-serializable with this stable key order. Approval
59
+ * revalidation compares JSON.stringify output byte-for-byte; a second host's projection must too.
60
+ * @returns A detached approval snapshot containing no credential bytes.
61
+ * @complexity O(a+w) in the bounded grant lists; no I/O.
62
+ */
63
+ /** @agent-note Pure, no I/O. One of the six `hostedMcpProjections`; the repository's compare-and-set compares its output field-for-field. */
64
+ export declare function externalMcpAccessSnapshot({ record }: {
65
+ record: ExternalMcpAccessRecord;
66
+ }, _options?: {}): ExternalMcpAccessSnapshot;
67
+ /** Parses a row's two grant lists the same way {@link resolveExternalMcpConfig} does — shared so
68
+ * admission and `revocation.ts`'s per-call re-check can never silently disagree about
69
+ * what a malformed list means (both fail closed to `[]`).
70
+ * @agent-note With `{ strict: true }` (grant planning) an unreadable list throws; it never reads as
71
+ * an empty or fresh grant.
72
+ * @complexity O(n) in the size of the two JSON blobs. */
73
+ /** @agent-note Pure. Admission and the per-call gate must both use this function so a malformed list means the same thing to both. */
74
+ export declare function readExternalMcpToolGrants(record: Pick<ExternalMcpAccessSnapshot, "allowedToolNames" | "writeAllowedToolNames">, options?: {
75
+ strict?: boolean;
76
+ }): {
77
+ allowedToolNames: string[];
78
+ writeAllowedToolNames: string[];
79
+ };
80
+ /** Validate already-decoded names using the save path's charset, cap and dedup rule.
81
+ * @agent-note What this throws, the paired `classifyError` must call 'validation'; its message is the
82
+ * model-facing repair reason, so it must stay public-safe (consumers still pass it through core redaction).
83
+ * @throws ExternalMcpValidationError for a refused name or more than 64 tools.
84
+ * @complexity O(names), no I/O.
85
+ */
86
+ /** @agent-note Pure. Throws only the canonical `ExternalMcpValidationError`, which plugin `classifyError` and sign-in refusal recognize. */
87
+ export declare function validateExternalMcpToolNames({ names, field }: {
88
+ names: readonly string[];
89
+ field: string;
90
+ }, _options?: {}): string[];
91
+ export {};
92
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1,116 @@
1
+ /** Shared external-MCP access vocabulary and pure row projections. Persistence remains in the
2
+ * external-MCP service and is supplied to plugin consumers through their MCP port. */
3
+ import { createHash } from "node:crypto";
4
+ import { ToolInputError } from "@jini-ai/core";
5
+ import { ExternalMcpValidationError } from "./validation-error.js";
6
+ const MAX_ALLOWED_TOOLS = 64;
7
+ /** Matches `trust.ts`'s own `REMOTE_TOOL_NAME_PATTERN`. Restated rather than imported because that
8
+ * constant is private to the trust tier; the host's store conformance tests asserts the two
9
+ * agree by round-tripping a name through `admitRemoteTools`. */
10
+ const REMOTE_TOOL_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$/;
11
+ /** Decode stored list columns; strict grant readers refuse malformed state. O(n) JSON bytes. */
12
+ /** @agent-note Pure decode of a saved JSON list column. Strict mode throws `ToolInputError` (model-facing, neutral wording); non-strict fails closed to `[]`. */
13
+ export function parseExternalMcpJsonArray({ raw }, { strict = false } = {}) {
14
+ if (raw === null)
15
+ return [];
16
+ try {
17
+ const parsed = JSON.parse(raw);
18
+ if (strict && (!Array.isArray(parsed) || !parsed.every(v => typeof v === "string")))
19
+ throw new Error("malformed");
20
+ return Array.isArray(parsed) ? parsed.filter((v) => typeof v === "string") : [];
21
+ }
22
+ catch {
23
+ if (strict)
24
+ throw new ToolInputError({ message: "The plugin connection has an unreadable tool list. Save its tool list again before enabling it." });
25
+ return [];
26
+ }
27
+ }
28
+ /**
29
+ * A connection's "admitted under this" fingerprint — what `revocation.ts`'s per-call
30
+ * gate compares a roster connection's row against to catch a delete-then-recreate, a
31
+ * url/command/args/transport/authMode edit, or a rotated/cleared static credential, none of
32
+ * which re-admit an already-running connection (the registry is append-only;
33
+ * `../reload.ts` never re-admits an admitted id).
34
+ *
35
+ * `sealedEnv`'s CIPHERTEXT is included: a `static_env`/`stdio` credential is
36
+ * resealed only when an operator actually submits a new `env` block — an ordinary toggle/rename
37
+ * leaves `env` undefined and carries the existing seal through byte-for-byte (see
38
+ * `resolveExternalMcpSealedEnv`'s `rawEnv === undefined` branch), so the ciphertext is stable across
39
+ * cosmetic saves and only moves when the credential itself is rotated or cleared. On `static_env`
40
+ * rows, `sealedOAuth` holds the dedicated static access token and follows the same preservation rule,
41
+ * so its ciphertext is included too. On OAuth rows it is excluded: re-sealing on token refresh must
42
+ * not refuse an otherwise valid connection.
43
+ *
44
+ * Otherwise deliberately narrow: `label`, `enabled`, both grant lists, OAuth status/expiry/tokens,
45
+ * and `updatedAt` are excluded, because none of them identify WHERE or via WHAT credentials a call
46
+ * reaches the remote, and including any of them would flip the revision on a toggle or a token
47
+ * refresh that must not refuse an already-admitted tool. `createdAt` is included so a delete +
48
+ * re-create under the same id (same url/command, different row) still changes the revision.
49
+ *
50
+ * Hashed rather than kept as plain text, because a hosted row's `url` can itself carry a bearer
51
+ * token as a query parameter — this value is compared, logged, and passed to a model-facing gate, so
52
+ * it must never be a place a credential could leak through.
53
+ *
54
+ * @complexity O(1).
55
+ * @overallScore 100
56
+ */
57
+ /** @agent-note Saved/compared format: sha256 hex over the exact JSON array below. Never reorder, add or drop inputs; existing approvals and per-call gates compare these bytes. */
58
+ export function externalMcpAdmissionRevision(record) {
59
+ return createHash("sha256")
60
+ .update(JSON.stringify([
61
+ record.createdAt,
62
+ record.transport,
63
+ record.url,
64
+ record.command,
65
+ record.args,
66
+ record.authMode,
67
+ record.sealedEnv?.ciphertext ?? null,
68
+ record.authMode === "static_env" ? (record.sealedOAuth?.ciphertext ?? null) : null,
69
+ ]))
70
+ .digest("hex");
71
+ }
72
+ /** Capture the source identity, exact previous grants and their decision, excluding token-refresh metadata.
73
+ * @agent-note Canonical saved representation: JSON-serializable with this stable key order. Approval
74
+ * revalidation compares JSON.stringify output byte-for-byte; a second host's projection must too.
75
+ * @returns A detached approval snapshot containing no credential bytes.
76
+ * @complexity O(a+w) in the bounded grant lists; no I/O.
77
+ */
78
+ /** @agent-note Pure, no I/O. One of the six `hostedMcpProjections`; the repository's compare-and-set compares its output field-for-field. */
79
+ export function externalMcpAccessSnapshot({ record }, _options = {}) {
80
+ return { admissionRevision: externalMcpAdmissionRevision(record), enabled: record.enabled,
81
+ allowedToolNames: record.allowedToolNames, writeAllowedToolNames: record.writeAllowedToolNames,
82
+ writeGrantsUpdatedByPrincipalId: record.writeGrantsUpdatedByPrincipalId, writeGrantsUpdatedAt: record.writeGrantsUpdatedAt,
83
+ provisionedByPluginId: record.provisionedByPluginId };
84
+ }
85
+ /** Parses a row's two grant lists the same way {@link resolveExternalMcpConfig} does — shared so
86
+ * admission and `revocation.ts`'s per-call re-check can never silently disagree about
87
+ * what a malformed list means (both fail closed to `[]`).
88
+ * @agent-note With `{ strict: true }` (grant planning) an unreadable list throws; it never reads as
89
+ * an empty or fresh grant.
90
+ * @complexity O(n) in the size of the two JSON blobs. */
91
+ /** @agent-note Pure. Admission and the per-call gate must both use this function so a malformed list means the same thing to both. */
92
+ export function readExternalMcpToolGrants(record, options = {}) {
93
+ return {
94
+ allowedToolNames: parseExternalMcpJsonArray({ raw: record.allowedToolNames }, { strict: options.strict }),
95
+ writeAllowedToolNames: parseExternalMcpJsonArray({ raw: record.writeAllowedToolNames }, { strict: options.strict }),
96
+ };
97
+ }
98
+ /** Validate already-decoded names using the save path's charset, cap and dedup rule.
99
+ * @agent-note What this throws, the paired `classifyError` must call 'validation'; its message is the
100
+ * model-facing repair reason, so it must stay public-safe (consumers still pass it through core redaction).
101
+ * @throws ExternalMcpValidationError for a refused name or more than 64 tools.
102
+ * @complexity O(names), no I/O.
103
+ */
104
+ /** @agent-note Pure. Throws only the canonical `ExternalMcpValidationError`, which plugin `classifyError` and sign-in refusal recognize. */
105
+ export function validateExternalMcpToolNames({ names, field }, _options = {}) {
106
+ if (names.length > MAX_ALLOWED_TOOLS) {
107
+ throw new ExternalMcpValidationError(`at most ${MAX_ALLOWED_TOOLS} tools are supported`, field);
108
+ }
109
+ for (const name of names) {
110
+ if (!REMOTE_TOOL_NAME_PATTERN.test(name)) {
111
+ throw new ExternalMcpValidationError(`'${name}' is not a valid MCP tool name, so the trust tier would refuse it on connect`, field);
112
+ }
113
+ }
114
+ return [...new Set(names)];
115
+ }
116
+ //# sourceMappingURL=access.js.map
@@ -0,0 +1,69 @@
1
+ import type { SealedSecret } from "@jini-ai/core/contracts/vault";
2
+ import type { ExternalMcpAuthMode, ExternalMcpOAuthStatus } from "@jini-ai/core/contracts/hosted-mcp";
3
+ /**
4
+ * @file The hosted-MCP auth-mode readers. The store and its consumers import this shared leaf
5
+ * directly, preserving a single vocabulary owner without importing the sign-in or host tool layer.
6
+ *
7
+ * Parameters are declared STRUCTURALLY (the two fields each reader touches) rather than as
8
+ * `Pick<ExternalMcpServerRecord, ...>`: the record type lives in the store, which imports THIS file,
9
+ * so naming it here would close an import cycle. `ExternalMcpServerRecord` satisfies both shapes.
10
+ */
11
+ /**
12
+ * How a server's credentials are obtained — independent of `ExternalMcpTransport`.
13
+ *
14
+ * - `none` — no credentials at all. Common for local developer tooling.
15
+ * - `static_env` — the operator pasted a `KEY=VALUE` block. What this store has always done, and
16
+ * the default for every row that predates this field.
17
+ * - `oauth` — the host holds a token it obtained itself and must keep alive. See
18
+ * the separately wired sign-in service.
19
+ */
20
+ /** @agent-note Saved `authMode` literals; equals core `ExternalMcpAuthMode` both ways (pinned by test). */
21
+ export declare const EXTERNAL_MCP_AUTH_MODES: readonly ["none", "static_env", "oauth"];
22
+ /**
23
+ * Reads a row's auth mode, defaulting a row written before the column existed.
24
+ *
25
+ * `static_env` is the correct default rather than `none`: every pre-existing row was written by a
26
+ * form whose only credential mechanism was the env block, and a row with an empty block behaves
27
+ * identically under either mode. Defaulting to `none` would silently relabel rows that DO carry a
28
+ * sealed block as credential-free.
29
+ *
30
+ * @complexity O(1).
31
+ */
32
+ /** @agent-note Pure, no I/O; the `static_env` default is the saved-format compatibility rule for rows older than the column. Hosts bind this exact function. */
33
+ export declare function resolveExternalMcpAuthMode(record: {
34
+ authMode: string;
35
+ }): ExternalMcpAuthMode;
36
+ /**
37
+ * Whether a row holds a `static_env` access token — answered from plaintext columns, never by unsealing.
38
+ *
39
+ * Truthful because a `static_env` row's sealed OAuth blob only ever holds that token: leaving `oauth`
40
+ * clears the client secret and token set (`store.ts`'s `resolveSealedOAuthBlob`),
41
+ * and entering `oauth` never carries this token forward (`openExternalMcpOAuthPayload`'s callers
42
+ * rebuild the payload from `clientSecret`/`tokens` alone).
43
+ *
44
+ * @complexity O(1).
45
+ */
46
+ /** @agent-note Pure, plain-text columns only; never unseals. One of the six `hostedMcpProjections`. */
47
+ export declare function externalMcpRecordHasStaticAccessToken(record: {
48
+ authMode: string;
49
+ sealedOAuth: SealedSecret | null;
50
+ }): boolean;
51
+ /**
52
+ * The runtime lifecycle of an OAuth-backed connection.
53
+ *
54
+ * `needs_reauth` is the state that earns its place here. It is deliberately NOT the boot-time "skip
55
+ * this row and report why" path {@link readEnabledExternalMcpConfigs} already uses for a sealed blob
56
+ * that will not decrypt: that is a STORAGE failure, nothing the operator types can fix it, and it is
57
+ * discovered while the daemon starts. `needs_reauth` is an expected RUNTIME lifecycle state — a
58
+ * token expired or was revoked while everything was working — it is exactly operator-actionable, and
59
+ * it must be visible in the admin tab rather than buried in a boot log nobody is reading at the time.
60
+ */
61
+ /** @agent-note Saved `oauthStatus` literals; equals core `ExternalMcpOAuthStatus` both ways. */
62
+ export declare const EXTERNAL_MCP_OAUTH_STATUSES: readonly ["disconnected", "pending", "connected", "needs_reauth"];
63
+ /** A row's OAuth status, defaulting an absent or unrecognized value to `disconnected` — the safe
64
+ * direction, since it is the state in which no token is used and the operator is prompted. */
65
+ /** @agent-note Pure, no I/O; unknown defaults to `disconnected`. One of the six `hostedMcpProjections`. */
66
+ export declare function resolveExternalMcpOAuthStatus(record: {
67
+ oauthStatus: string | null;
68
+ }): ExternalMcpOAuthStatus;
69
+ //# sourceMappingURL=auth.d.ts.map