@jini-ai/mcp 0.7.3-next.1 → 0.7.3-next.3

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 (77) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +15 -0
  3. package/dist/agent-install/owned-json-install.d.ts +1 -1
  4. package/dist/client/client.js +1 -1
  5. package/dist/client/css-url-refs.d.ts +3 -1
  6. package/dist/client/css-url-refs.js +1 -1
  7. package/dist/external/access-review.d.ts +46 -0
  8. package/dist/external/access-review.js +175 -0
  9. package/dist/external/agent-tools.d.ts +72 -0
  10. package/dist/external/agent-tools.js +218 -0
  11. package/dist/external/built-in-connections.d.ts +17 -0
  12. package/dist/external/built-in-connections.js +15 -0
  13. package/dist/external/external-mcp-host-copy.d.ts +14 -0
  14. package/dist/external/external-mcp-host-copy.js +8 -0
  15. package/dist/external/operations-tools.d.ts +69 -0
  16. package/dist/external/operations-tools.js +96 -0
  17. package/dist/external/save-form.d.ts +105 -0
  18. package/dist/external/save-form.js +260 -0
  19. package/dist/external/save-input.d.ts +41 -0
  20. package/dist/external/save-input.js +149 -0
  21. package/dist/external/tool-registrations.d.ts +130 -0
  22. package/dist/external/tool-registrations.js +299 -0
  23. package/dist/federation/bootstrap.d.ts +18 -0
  24. package/dist/federation/bootstrap.js +2 -2
  25. package/dist/federation/external-mcp-admissions.d.ts +19 -0
  26. package/dist/federation/external-mcp-admissions.js +30 -0
  27. package/dist/federation/external-mcp-probe.d.ts +86 -0
  28. package/dist/federation/external-mcp-probe.js +75 -0
  29. package/dist/federation/hosted/external-mcp-repo.d.ts +108 -0
  30. package/dist/federation/hosted/external-mcp-repo.js +210 -0
  31. package/dist/federation/hosted/external-mcp-repo.writes.d.ts +75 -0
  32. package/dist/federation/hosted/external-mcp-repo.writes.js +131 -0
  33. package/dist/federation/hosted/store-credentials.d.ts +6 -1
  34. package/dist/federation/hosted/store-credentials.js +2 -2
  35. package/dist/federation/hosted/store-input.d.ts +11 -3
  36. package/dist/federation/hosted/store-input.js +5 -5
  37. package/dist/federation/hosted/store-oauth-fields.d.ts +10 -2
  38. package/dist/federation/hosted/store-oauth-fields.js +7 -7
  39. package/dist/federation/hosted/store-view.d.ts +6 -1
  40. package/dist/federation/hosted/store-view.js +2 -2
  41. package/dist/federation/hosted/store.js +7 -7
  42. package/dist/federation/hosted/store.memory.d.ts +2 -0
  43. package/dist/federation/hosted/store.memory.js +6 -2
  44. package/dist/federation/index.d.ts +2 -0
  45. package/dist/federation/index.js +2 -0
  46. package/dist/federation/registrations.js +73 -56
  47. package/dist/federation/roster-change.d.ts +63 -0
  48. package/dist/federation/roster-change.js +68 -0
  49. package/dist/federation/runtime.d.ts +140 -0
  50. package/dist/federation/runtime.js +118 -0
  51. package/dist/react/external-mcp/ExternalMcpAdmissionsBanner.d.ts +42 -0
  52. package/dist/react/external-mcp/ExternalMcpAdmissionsBanner.js +80 -0
  53. package/dist/react/external-mcp/ExternalMcpPanelSections.d.ts +50 -0
  54. package/dist/react/external-mcp/ExternalMcpPanelSections.js +35 -0
  55. package/dist/react/external-mcp/ExternalMcpSettingsPanel.d.ts +446 -0
  56. package/dist/react/external-mcp/ExternalMcpSettingsPanel.hooks.d.ts +135 -0
  57. package/dist/react/external-mcp/ExternalMcpSettingsPanel.hooks.js +122 -0
  58. package/dist/react/external-mcp/ExternalMcpSettingsPanel.js +63 -0
  59. package/dist/react/external-mcp/ExternalMcpSourceRow.d.ts +40 -0
  60. package/dist/react/external-mcp/ExternalMcpSourceRow.js +100 -0
  61. package/dist/react/external-mcp/hooks/external-mcp-form.rules.d.ts +58 -0
  62. package/dist/react/external-mcp/hooks/external-mcp-form.rules.js +209 -0
  63. package/dist/react/external-mcp/hooks/external-mcp-source-actions.d.ts +115 -0
  64. package/dist/react/external-mcp/hooks/external-mcp-source-actions.js +152 -0
  65. package/dist/react/external-mcp/hooks/use-external-mcp-admissions.hooks.d.ts +166 -0
  66. package/dist/react/external-mcp/hooks/use-external-mcp-admissions.hooks.js +209 -0
  67. package/dist/react/external-mcp/hooks/use-external-mcp.hooks.d.ts +132 -0
  68. package/dist/react/external-mcp/hooks/use-external-mcp.hooks.js +37 -0
  69. package/dist/server/tool-arguments.d.ts +5 -1
  70. package/dist/server/tool-arguments.js +13 -9
  71. package/dist/server/tool-protocol.js +7 -5
  72. package/dist/server/tools/tool-catalog-tools.js +6 -3
  73. package/dist/tools/ask-choice/custom-answer.d.ts +77 -0
  74. package/dist/tools/ask-choice/custom-answer.js +113 -0
  75. package/dist/tools/ask-choice/index.d.ts +2 -0
  76. package/dist/tools/ask-choice/index.js +1 -0
  77. package/package.json +122 -7
@@ -0,0 +1,131 @@
1
+ import { externalMcpVaultRecord, persistExternalMcpVaultEnvelope } from "./index.js";
2
+ import { deleteExternalMcpVaultEnvelope } from "./index.js";
3
+ class WriteMissed extends Error {
4
+ }
5
+ export function toRow({ record, pointers }, _optional = {}) {
6
+ return {
7
+ workspace_id: record.workspaceId,
8
+ server_id: record.serverId,
9
+ label: record.label,
10
+ provisioned_by_plugin_id: record.provisionedByPluginId,
11
+ transport: record.transport,
12
+ auth_mode: record.authMode,
13
+ enabled: record.enabled,
14
+ command: record.command,
15
+ url: record.url,
16
+ args: record.args,
17
+ allowed_tool_names: record.allowedToolNames,
18
+ write_allowed_tool_names: record.writeAllowedToolNames,
19
+ write_grants_updated_by_principal_id: record.writeGrantsUpdatedByPrincipalId,
20
+ write_grants_updated_at: record.writeGrantsUpdatedAt,
21
+ env_names: record.envNames,
22
+ ...pointers,
23
+ oauth_provider_id: record.oauthProviderId,
24
+ oauth_grant: record.oauthGrant,
25
+ oauth_client_id: record.oauthClientId,
26
+ oauth_endpoints_json: record.oauthEndpointsJson,
27
+ oauth_scopes_json: record.oauthScopesJson,
28
+ oauth_status: record.oauthStatus,
29
+ oauth_expires_at: record.oauthExpiresAt,
30
+ oauth_token_env_name: record.oauthTokenEnvName,
31
+ oauth_refresh_lease_until: record.oauthRefreshLeaseUntil,
32
+ created_at: record.createdAt,
33
+ updated_at: record.updatedAt,
34
+ version: record.version,
35
+ };
36
+ }
37
+ /** The vault id an envelope the writer read points at, or `null` for no envelope. */
38
+ function pointerOf({ sealed, key, kind, vaultErrors }) {
39
+ return sealed ? externalMcpVaultRecord({ sealed, identity: key, kind, vaultErrors }).id : null;
40
+ }
41
+ async function readPointers({ kernel, key, tables }) {
42
+ return kernel.run(db => db.withTables().selectFrom(tables.servers).select(["env_secret_id", "oauth_secret_id", "version", "created_at"])
43
+ .where("workspace_id", "=", key.workspaceId).where("server_id", "=", key.serverId).executeTakeFirst());
44
+ }
45
+ /** Runs `body` in a locked transaction; `false` when it threw {@link WriteMissed} (rolled back). */
46
+ async function lockedWrite({ kernel, workspaceId, body }) {
47
+ try {
48
+ return await kernel.transaction(async () => {
49
+ await kernel.lockKey(`secrets_vault:${workspaceId}`);
50
+ return body();
51
+ });
52
+ }
53
+ catch (error) {
54
+ if (error instanceof WriteMissed)
55
+ return false;
56
+ throw error;
57
+ }
58
+ }
59
+ async function stagePointers({ vaultRepo, record, vaultErrors }) {
60
+ return {
61
+ env_secret_id: await persistExternalMcpVaultEnvelope({ repo: vaultRepo, vaultErrors, sealed: record.sealedEnv, identity: record, kind: "mcp-env" }),
62
+ oauth_secret_id: await persistExternalMcpVaultEnvelope({ repo: vaultRepo, vaultErrors, sealed: record.sealedOAuth, identity: record, kind: "mcp-auth" }),
63
+ };
64
+ }
65
+ /** Creates the row at version 1; `false` and nothing written when the key is taken. */
66
+ export async function insertRow({ kernel, vaultRepo, tables, vaultErrors, record }, _optional = {}) {
67
+ return lockedWrite({ kernel, workspaceId: record.workspaceId, body: async () => {
68
+ if (await readPointers({ kernel, tables, key: record }))
69
+ return false;
70
+ const row = toRow({ record: { ...record, version: 1 }, pointers: await stagePointers({ vaultRepo, record, vaultErrors }) });
71
+ await kernel.run(db => db.withTables().insertInto(tables.servers).values(row).execute());
72
+ return true;
73
+ } });
74
+ }
75
+ /** The edit write: version and both credential pointers compared in the `WHERE`, version + 1 set. */
76
+ export async function updateRowIfVersion({ kernel, vaultRepo, tables, vaultErrors, record, expectedVersion, expectedCreatedAt, replaces }, _optional = {}) {
77
+ const replacedEnv = pointerOf({ sealed: replaces.sealedEnv, key: record, kind: "mcp-env", vaultErrors });
78
+ const replacedAuth = pointerOf({ sealed: replaces.sealedOAuth, key: record, kind: "mcp-auth", vaultErrors });
79
+ return lockedWrite({ kernel, workspaceId: record.workspaceId, body: async () => {
80
+ const previous = await readPointers({ kernel, tables, key: record });
81
+ if (!previous || Number(previous.version) !== expectedVersion || previous.env_secret_id !== replacedEnv || previous.oauth_secret_id !== replacedAuth)
82
+ return false;
83
+ if (expectedCreatedAt !== undefined && previous.created_at !== expectedCreatedAt)
84
+ return false;
85
+ const pointers = await stagePointers({ vaultRepo, record, vaultErrors });
86
+ const { workspace_id: _workspace, server_id: _server, ...columns } = toRow({ record: { ...record, version: expectedVersion + 1 }, pointers });
87
+ const result = await kernel.run(db => {
88
+ let update = db.withTables().updateTable(tables.servers).set(columns)
89
+ .where("workspace_id", "=", record.workspaceId).where("server_id", "=", record.serverId).where("version", "=", expectedVersion)
90
+ .where("env_secret_id", replacedEnv === null ? "is" : "=", replacedEnv).where("oauth_secret_id", replacedAuth === null ? "is" : "=", replacedAuth);
91
+ if (expectedCreatedAt !== undefined)
92
+ update = update.where("created_at", "=", expectedCreatedAt);
93
+ return update.executeTakeFirst();
94
+ });
95
+ if (Number(result.numUpdatedRows) !== 1)
96
+ throw new WriteMissed();
97
+ // The update unlinked the old pointers; RESTRICT foreign keys are satisfied.
98
+ if (previous.env_secret_id !== pointers.env_secret_id)
99
+ await deleteExternalMcpVaultEnvelope({ repo: vaultRepo, workspaceId: record.workspaceId, id: previous.env_secret_id });
100
+ if (previous.oauth_secret_id !== pointers.oauth_secret_id)
101
+ await deleteExternalMcpVaultEnvelope({ repo: vaultRepo, workspaceId: record.workspaceId, id: previous.oauth_secret_id });
102
+ return true;
103
+ } });
104
+ }
105
+ /** The runtime write: OAuth pointer, status, expiry, lease only, while the credential is the one read. */
106
+ export async function updateRuntime({ kernel, vaultRepo, tables, vaultErrors, key, expectedSealedOAuth, expectedConfig, patch }, _optional = {}) {
107
+ const expectedAuth = pointerOf({ sealed: expectedSealedOAuth, key, kind: "mcp-auth", vaultErrors });
108
+ return lockedWrite({ kernel, workspaceId: key.workspaceId, body: async () => {
109
+ const previous = await readPointers({ kernel, tables, key });
110
+ if (!previous || previous.oauth_secret_id !== expectedAuth)
111
+ return false;
112
+ if (expectedConfig !== undefined && (Number(previous.version) !== expectedConfig.version || previous.created_at !== expectedConfig.createdAt))
113
+ return false;
114
+ const oauth_secret_id = await persistExternalMcpVaultEnvelope({ repo: vaultRepo, vaultErrors, sealed: patch.sealedOAuth, identity: key, kind: "mcp-auth" });
115
+ const result = await kernel.run(db => {
116
+ let update = db.withTables().updateTable(tables.servers)
117
+ .set({ oauth_secret_id, oauth_status: patch.oauthStatus, oauth_expires_at: patch.oauthExpiresAt, oauth_refresh_lease_until: patch.oauthRefreshLeaseUntil, updated_at: patch.updatedAt })
118
+ .where("workspace_id", "=", key.workspaceId).where("server_id", "=", key.serverId)
119
+ .where("oauth_secret_id", expectedAuth === null ? "is" : "=", expectedAuth);
120
+ if (expectedConfig !== undefined)
121
+ update = update.where("version", "=", expectedConfig.version).where("created_at", "=", expectedConfig.createdAt);
122
+ return update.executeTakeFirst();
123
+ });
124
+ if (Number(result.numUpdatedRows) !== 1)
125
+ throw new WriteMissed();
126
+ if (previous.oauth_secret_id !== oauth_secret_id)
127
+ await deleteExternalMcpVaultEnvelope({ repo: vaultRepo, workspaceId: key.workspaceId, id: previous.oauth_secret_id });
128
+ return true;
129
+ } });
130
+ }
131
+ //# sourceMappingURL=external-mcp-repo.writes.js.map
@@ -39,7 +39,12 @@ export declare function openExternalMcpStaticAccessToken(record: ExternalMcpServ
39
39
  readonly ok: false;
40
40
  readonly reason: string;
41
41
  }>;
42
- export declare function resolveExternalMcpSealedEnv(deps: SealDeps, identity: ExternalMcpIdentity, rawEnv: string | undefined, existing: ExternalMcpServerRecord | null): Promise<{
42
+ export declare function resolveExternalMcpSealedEnv({ deps, identity, rawEnv, existing }: {
43
+ deps: SealDeps;
44
+ identity: ExternalMcpIdentity;
45
+ rawEnv: string | undefined;
46
+ existing: ExternalMcpServerRecord | null;
47
+ }, _optional?: Record<string, never>): Promise<{
43
48
  readonly sealedEnv: SealedSecret | null;
44
49
  readonly envNames: string[];
45
50
  readonly aadVersion: number;
@@ -116,7 +116,7 @@ async function sealFreshExternalMcpEnv(deps, identity, rawEnv) {
116
116
  throw new ExternalMcpSecretStoreUnconfiguredError(deps.credential.messages.storage);
117
117
  }
118
118
  }
119
- export async function resolveExternalMcpSealedEnv(deps, identity, rawEnv, existing) {
119
+ export async function resolveExternalMcpSealedEnv({ deps, identity, rawEnv, existing }, _optional = {}) {
120
120
  // Owner policy: an exact blank update keeps credentials; whitespace cannot clear them.
121
121
  if (rawEnv !== undefined && rawEnv !== '' && rawEnv.trim() === '')
122
122
  throw new ExternalMcpValidationError(deps.credential.messages.blank, 'env');
@@ -195,7 +195,7 @@ async function resolveSealedStaticAccessToken(deps, identity, rawToken, existing
195
195
  function resolveStaticAccessTokenEnvName(transport, input, existing, holdsToken) {
196
196
  if (transport !== "stdio")
197
197
  return null;
198
- const name = firstTrimmed(input.accessTokenEnvName, existing?.oauthTokenEnvName);
198
+ const name = firstTrimmed({ candidates: [input.accessTokenEnvName, existing?.oauthTokenEnvName] });
199
199
  if (name === "") {
200
200
  if (!holdsToken)
201
201
  return null;
@@ -31,8 +31,12 @@ export declare function parseArgs({ raw }: {
31
31
  * type. Split out purely to keep {@link saveExternalMcpServer}'s complexity under the shop
32
32
  * ceiling — reuses `trust.ts`'s rule rather than restating it, since this id becomes part of every
33
33
  * federated tool id and two copies of that rule could drift. */
34
- export declare function assertValidExternalMcpServerId(serverId: string): void;
35
- export declare function assertSupportedExternalMcpTransport(transport: string): void;
34
+ export declare function assertValidExternalMcpServerId({ serverId }: {
35
+ serverId: string;
36
+ }, _optional?: Record<string, never>): void;
37
+ export declare function assertSupportedExternalMcpTransport({ transport }: {
38
+ transport: string;
39
+ }, _optional?: Record<string, never>): void;
36
40
  /**
37
41
  * Splits an operator's comma- or space-separated OAuth scope list.
38
42
  *
@@ -48,7 +52,11 @@ export declare function parseOAuthScopes({ raw }: {
48
52
  /** A `stdio` row needs a command; a remote row needs a URL. Split out to keep
49
53
  * {@link saveExternalMcpServer}'s complexity under the shop ceiling.
50
54
  * @throws {ExternalMcpValidationError} When the transport's own required field is missing or unsafe. */
51
- export declare function resolveTransportTarget(transport: ExternalMcpTransport, input: SaveExternalMcpServerInput, ports: CredentialPorts): {
55
+ export declare function resolveTransportTarget({ transport, input, ports }: {
56
+ transport: ExternalMcpTransport;
57
+ input: SaveExternalMcpServerInput;
58
+ ports: CredentialPorts;
59
+ }, _optional?: Record<string, never>): {
52
60
  readonly command: string | null;
53
61
  readonly url: string | null;
54
62
  };
@@ -65,7 +65,7 @@ export function parseEnvBlock({ text, ports }, _optional = {}) {
65
65
  throw new ExternalMcpValidationError(`at most ${MAX_ENV_VARS} environment variables are supported`, "env");
66
66
  }
67
67
  if (parsed.value.length > ports.credential.limit)
68
- throw new ExternalMcpValidationError("The token exceeds the 8192-character limit. Copy only the token.", "env");
68
+ throw new ExternalMcpValidationError(`The token exceeds the ${ports.credential.limit}-character limit. Copy only the token.`, "env");
69
69
  assertExternalMcpPlainField({ value: parsed.name, field: "env" }, ports);
70
70
  env[parsed.name] = parsed.value;
71
71
  }
@@ -76,7 +76,7 @@ function assertJsonEnvEntry({ name, value, ports }, _options = {}) {
76
76
  throw new ExternalMcpValidationError(ports.credential.messages.env, 'env');
77
77
  assertExternalMcpPlainField({ value: name, field: 'env' }, ports);
78
78
  if (value.length > ports.credential.limit)
79
- throw new ExternalMcpValidationError('The token exceeds the 8192-character limit. Copy only the token.', 'env');
79
+ throw new ExternalMcpValidationError(`The token exceeds the ${ports.credential.limit}-character limit. Copy only the token.`, 'env');
80
80
  }
81
81
  function parseJsonEnvBlock({ text, ports }, _options = {}) {
82
82
  let parsed;
@@ -151,7 +151,7 @@ function readQuotedArg(raw, start) {
151
151
  * type. Split out purely to keep {@link saveExternalMcpServer}'s complexity under the shop
152
152
  * ceiling — reuses `trust.ts`'s rule rather than restating it, since this id becomes part of every
153
153
  * federated tool id and two copies of that rule could drift. */
154
- export function assertValidExternalMcpServerId(serverId) {
154
+ export function assertValidExternalMcpServerId({ serverId }, _optional = {}) {
155
155
  try {
156
156
  assertValidConnectionId({ connectionId: serverId });
157
157
  }
@@ -159,7 +159,7 @@ export function assertValidExternalMcpServerId(serverId) {
159
159
  throw new ExternalMcpValidationError(err instanceof Error ? err.message : String(err), "id");
160
160
  }
161
161
  }
162
- export function assertSupportedExternalMcpTransport(transport) {
162
+ export function assertSupportedExternalMcpTransport({ transport }, _optional = {}) {
163
163
  if (!SUPPORTED_EXTERNAL_MCP_TRANSPORTS.includes(transport)) {
164
164
  throw new ExternalMcpValidationError(`transport '${transport}' is not supported — only ${SUPPORTED_EXTERNAL_MCP_TRANSPORTS.join(", ")} is implemented`, "transport");
165
165
  }
@@ -224,7 +224,7 @@ function assertSafeRemoteMcpUrl(rawUrl, transport, ports) {
224
224
  /** A `stdio` row needs a command; a remote row needs a URL. Split out to keep
225
225
  * {@link saveExternalMcpServer}'s complexity under the shop ceiling.
226
226
  * @throws {ExternalMcpValidationError} When the transport's own required field is missing or unsafe. */
227
- export function resolveTransportTarget(transport, input, ports) {
227
+ export function resolveTransportTarget({ transport, input, ports }, _optional = {}) {
228
228
  if (transport === "stdio")
229
229
  return { command: assertNonEmptyExternalMcpCommand(input.command), url: null };
230
230
  return { command: null, url: assertSafeRemoteMcpUrl(input.url ?? "", transport, ports) };
@@ -21,6 +21,14 @@ export interface ResolvedOAuthFields {
21
21
  *
22
22
  * @complexity O(n) in the number of candidates, each trimmed once.
23
23
  */
24
- export declare function firstTrimmed(...candidates: readonly (string | null | undefined)[]): string;
25
- export declare function resolveOAuthFields(authMode: ExternalMcpAuthMode, transport: ExternalMcpTransport, input: SaveExternalMcpServerInput, existing: ExternalMcpServerRecord | null, credential: HostedMcpStorePorts["credential"]): ResolvedOAuthFields;
24
+ export declare function firstTrimmed({ candidates }: {
25
+ candidates: readonly (string | null | undefined)[];
26
+ }, _optional?: Record<string, never>): string;
27
+ export declare function resolveOAuthFields({ authMode, transport, input, existing, credential }: {
28
+ authMode: ExternalMcpAuthMode;
29
+ transport: ExternalMcpTransport;
30
+ input: SaveExternalMcpServerInput;
31
+ existing: ExternalMcpServerRecord | null;
32
+ credential: HostedMcpStorePorts["credential"];
33
+ }, _optional?: Record<string, never>): ResolvedOAuthFields;
26
34
  //# sourceMappingURL=store-oauth-fields.d.ts.map
@@ -71,7 +71,7 @@ const NO_OAUTH_FIELDS = {
71
71
  *
72
72
  * @complexity O(n) in the number of candidates, each trimmed once.
73
73
  */
74
- export function firstTrimmed(...candidates) {
74
+ export function firstTrimmed({ candidates }, _optional = {}) {
75
75
  for (const candidate of candidates) {
76
76
  const trimmed = candidate?.trim();
77
77
  if (trimmed)
@@ -102,7 +102,7 @@ function assertOAuthGrant(grant, selfConfigurable) {
102
102
  throw new ExternalMcpValidationError("an OAuth connection needs a sign-in method", "oauth.grant");
103
103
  }
104
104
  if (!EXTERNAL_MCP_OAUTH_GRANTS.includes(grant)) {
105
- throw new ExternalMcpValidationError(`OAuth grant '${grant}' is not supported — expected one of ${EXTERNAL_MCP_OAUTH_GRANTS.join(", ")}`, "oauth.grant");
105
+ throw new ExternalMcpValidationError(`OAuth grant is not supported — expected one of ${EXTERNAL_MCP_OAUTH_GRANTS.join(", ")}`, "oauth.grant");
106
106
  }
107
107
  return grant;
108
108
  }
@@ -179,7 +179,7 @@ function assertOAuthProviderIdentity(providerId, endpoints, selfConfigurable) {
179
179
  }
180
180
  }
181
181
  function resolveOAuthProviderIdentity(oauth, existing, selfConfigurable) {
182
- const providerId = firstTrimmed(oauth.providerId, existing?.oauthProviderId);
182
+ const providerId = firstTrimmed({ candidates: [oauth.providerId, existing?.oauthProviderId] });
183
183
  const endpoints = resolveOAuthEndpoints(oauth, existing);
184
184
  assertOAuthProviderIdentity(providerId, endpoints, selfConfigurable);
185
185
  return {
@@ -199,7 +199,7 @@ function resolveOAuthProviderIdentity(oauth, existing, selfConfigurable) {
199
199
  function resolveOAuthTokenEnvName(transport, oauth, existing) {
200
200
  if (transport !== "stdio")
201
201
  return null;
202
- const tokenEnvName = firstTrimmed(oauth.tokenEnvName, existing?.oauthTokenEnvName);
202
+ const tokenEnvName = firstTrimmed({ candidates: [oauth.tokenEnvName, existing?.oauthTokenEnvName] });
203
203
  if (tokenEnvName === "") {
204
204
  throw new ExternalMcpValidationError("a stdio server authenticated with OAuth needs the name of the environment variable that receives its access token", "oauth.tokenEnvName");
205
205
  }
@@ -215,7 +215,7 @@ function resolveSavedOAuthScopes(oauth, existing) {
215
215
  return parseExternalMcpJsonArray({ raw: existing?.oauthScopesJson ?? null });
216
216
  return parseOAuthScopes({ raw: oauth.scopes });
217
217
  }
218
- export function resolveOAuthFields(authMode, transport, input, existing, credential) {
218
+ export function resolveOAuthFields({ authMode, transport, input, existing, credential }, _optional = {}) {
219
219
  if (authMode !== "oauth")
220
220
  return NO_OAUTH_FIELDS;
221
221
  const oauth = input.oauth ?? {};
@@ -225,8 +225,8 @@ export function resolveOAuthFields(authMode, transport, input, existing, credent
225
225
  const selfConfigurable = transport !== "stdio";
226
226
  return {
227
227
  ...resolveOAuthProviderIdentity(oauth, existing, selfConfigurable),
228
- oauthGrant: assertOAuthGrant(firstTrimmed(oauth.grant, existing?.oauthGrant), selfConfigurable),
229
- oauthClientId: assertOAuthClientId(firstTrimmed(oauth.clientId, existing?.oauthClientId), selfConfigurable),
228
+ oauthGrant: assertOAuthGrant(firstTrimmed({ candidates: [oauth.grant, existing?.oauthGrant] }), selfConfigurable),
229
+ oauthClientId: assertOAuthClientId(firstTrimmed({ candidates: [oauth.clientId, existing?.oauthClientId] }), selfConfigurable),
230
230
  oauthScopesJson: JSON.stringify(resolveSavedOAuthScopes(oauth, existing)),
231
231
  oauthTokenEnvName: resolveOAuthTokenEnvName(transport, oauth, existing),
232
232
  clientSecret: oauth.clientSecret === '' || oauth.clientSecret === undefined ? undefined : normalizeOAuthClientSecret({ value: oauth.clientSecret, credential }),
@@ -33,7 +33,12 @@ import type { HostedMcpStorePorts, HostedMcpTokenHint } from "./store-ports.js";
33
33
  * @complexity O(1) — three field reads, no I/O.
34
34
  */
35
35
  export declare function externalMcpRecordHasStoredToken(record: Pick<ExternalMcpServerRecord, "sealedOAuth" | "oauthStatus" | "oauthExpiresAt">): boolean;
36
- export declare function toView(record: ExternalMcpServerRecord, ports: HostedMcpStorePorts, sealer?: SecretSealerPort): Promise<ExternalMcpServerView<HostedMcpTokenHint>>;
36
+ export declare function toView({ record, ports }: {
37
+ record: ExternalMcpServerRecord;
38
+ ports: HostedMcpStorePorts;
39
+ }, { sealer }?: {
40
+ sealer?: SecretSealerPort | undefined;
41
+ }): Promise<ExternalMcpServerView<HostedMcpTokenHint>>;
37
42
  /**
38
43
  * Lists the workspace's servers for the admin tab. The tab has no use for env
39
44
  * values and must not be a route that decrypts them. Token hints alone are now derived by
@@ -62,7 +62,7 @@ async function externalMcpAccessTokenHint({ record, sealer, ports }, _options =
62
62
  }
63
63
  return accessTokenHint;
64
64
  }
65
- export async function toView(record, ports, sealer) {
65
+ export async function toView({ record, ports }, { sealer } = {}) {
66
66
  const envTokenHints = await externalMcpEnvHints({ record, sealer, ports });
67
67
  const accessTokenHint = await externalMcpAccessTokenHint({ record, sealer, ports });
68
68
  return {
@@ -107,6 +107,6 @@ export async function toView(record, ports, sealer) {
107
107
  */
108
108
  export async function listExternalMcpServerViews({ deps, workspaceId }, _optional = {}) {
109
109
  const records = await deps.repo.listByWorkspaceId(workspaceId);
110
- return Promise.all(records.map(record => toView(record, deps, deps.sealer)));
110
+ return Promise.all(records.map(record => toView({ record, ports: deps }, { sealer: deps.sealer })));
111
111
  }
112
112
  //# sourceMappingURL=store-view.js.map
@@ -68,7 +68,7 @@ function resolveSavedAuthMode(input, existing) {
68
68
  if (input.authMode === undefined)
69
69
  return existing ? resolveExternalMcpAuthMode(existing) : "static_env";
70
70
  if (!EXTERNAL_MCP_AUTH_MODES.includes(input.authMode)) {
71
- throw new ExternalMcpValidationError(`auth mode '${input.authMode}' is not supported — expected one of ${EXTERNAL_MCP_AUTH_MODES.join(", ")}`, "authMode");
71
+ throw new ExternalMcpValidationError(`auth mode is not supported — expected one of ${EXTERNAL_MCP_AUTH_MODES.join(", ")}`, "authMode");
72
72
  }
73
73
  return input.authMode;
74
74
  }
@@ -144,10 +144,10 @@ function carryOAuthRuntimeState(authMode, resolved, existing) {
144
144
  export async function saveExternalMcpServer(deps, input) {
145
145
  assertExternalMcpPlainInput({ input, ports: deps });
146
146
  const serverId = input.serverId.trim().toLowerCase();
147
- assertValidExternalMcpServerId(serverId);
148
- assertSupportedExternalMcpTransport(input.transport);
147
+ assertValidExternalMcpServerId({ serverId });
148
+ assertSupportedExternalMcpTransport({ transport: input.transport });
149
149
  const transport = input.transport;
150
- const { command, url } = resolveTransportTarget(transport, input, deps);
150
+ const { command, url } = resolveTransportTarget({ transport, input, ports: deps });
151
151
  const args = parseArgs({ raw: input.args });
152
152
  const allowedToolNames = parseAllowedToolNames({ raw: input.allowedToolNames });
153
153
  // `?? ""` is a defensive fallback, not the documented contract (the type requires the field): a
@@ -159,7 +159,7 @@ export async function saveExternalMcpServer(deps, input) {
159
159
  const parsed = { serverId, transport, command, url, args, allowedToolNames, writeAllowedToolNames };
160
160
  const key = { workspaceId: input.workspaceId, serverId };
161
161
  const record = await commitExternalMcpSave({ repo: deps.repo, key, expectedVersion: input.expectedVersion, build: existing => buildSavedRecord(deps, input, parsed, existing) });
162
- return toView(record, deps, deps.sealer);
162
+ return toView({ record, ports: deps }, { sealer: deps.sealer });
163
163
  }
164
164
  /** Builds the row a save will write from the stored row it read (`null` for a create); re-run on the
165
165
  * fresh row when a runtime write moved a credential between that read and the write (M4). */
@@ -167,10 +167,10 @@ async function buildSavedRecord(deps, input, parsed, existing) {
167
167
  const { serverId, transport, command, url, args, allowedToolNames, writeAllowedToolNames } = parsed;
168
168
  await assertUnderExternalMcpServerCap(deps, input.workspaceId, existing);
169
169
  const authMode = resolveSavedAuthMode(input, existing);
170
- const oauthFields = resolveOAuthFields(authMode, transport, input, existing, deps.credential);
170
+ const oauthFields = resolveOAuthFields({ authMode, transport, input, existing, credential: deps.credential });
171
171
  const runtime = carryOAuthRuntimeState(authMode, oauthFields, existing);
172
172
  const aadIdentity = { workspaceId: input.workspaceId, serverId };
173
- const { sealedEnv, envNames, aadVersion } = await resolveExternalMcpSealedEnv(deps, aadIdentity, input.env, existing);
173
+ const { sealedEnv, envNames, aadVersion } = await resolveExternalMcpSealedEnv({ deps, identity: aadIdentity, rawEnv: input.env, existing });
174
174
  const { sealedOAuth, oauthAadVersion, oauthTokenEnvName } = await resolveSavedCredentialColumns({ deps, identity: aadIdentity, context: { authMode, transport, input, oauthFields, keepToken: runtime.keepToken, existing } });
175
175
  const now = nowIso({ clock: deps.clock });
176
176
  const writeGrantAttribution = resolveWriteGrantAttribution({ input, writeAllowedToolNames, existing, nowIso: now });
@@ -30,6 +30,7 @@ export declare class InMemoryExternalMcpServerRepo implements ExternalMcpServerR
30
30
  updateIfVersion(required: {
31
31
  readonly record: ExternalMcpServerRecord;
32
32
  readonly expectedVersion: number;
33
+ readonly expectedCreatedAt?: string;
33
34
  readonly replaces: ExternalMcpReplacedSecrets;
34
35
  }): Promise<boolean>;
35
36
  /** The runtime write: only the sealed-OAuth pointer and its status/expiry/lease columns change,
@@ -38,6 +39,7 @@ export declare class InMemoryExternalMcpServerRepo implements ExternalMcpServerR
38
39
  updateOAuthRuntime(required: {
39
40
  readonly key: ExternalMcpServerKey;
40
41
  readonly expectedSealedOAuth: SealedSecret | null;
42
+ readonly expectedConfig?: Pick<ExternalMcpServerRecord, "createdAt" | "version">;
41
43
  readonly patch: ExternalMcpOAuthRuntimePatch;
42
44
  }): Promise<boolean>;
43
45
  private pointerId;
@@ -87,10 +87,12 @@ export class InMemoryExternalMcpServerRepo {
87
87
  * @complexity O(1) row lookup plus the bounded two-envelope commit. */
88
88
  async updateIfVersion(required) {
89
89
  return this.write(async () => {
90
- const { record, expectedVersion, replaces } = required;
90
+ const { record, expectedVersion, expectedCreatedAt, replaces } = required;
91
91
  const current = this.rows.get(keyOf(record.workspaceId, record.serverId));
92
92
  if (!current || current.version !== expectedVersion)
93
93
  return false;
94
+ if (expectedCreatedAt !== undefined && current.createdAt !== expectedCreatedAt)
95
+ return false;
94
96
  const sameEnv = this.pointerId({ sealed: replaces.sealedEnv, identity: current, kind: "mcp-env" }) === this.pointerId({ sealed: current.sealedEnv, identity: current, kind: "mcp-env" });
95
97
  const sameAuth = this.pointerId({ sealed: replaces.sealedOAuth, identity: current, kind: "mcp-auth" }) === this.pointerId({ sealed: current.sealedOAuth, identity: current, kind: "mcp-auth" });
96
98
  if (!sameEnv || !sameAuth)
@@ -104,10 +106,12 @@ export class InMemoryExternalMcpServerRepo {
104
106
  * @complexity O(1) row lookup plus the bounded two-envelope commit. */
105
107
  async updateOAuthRuntime(required) {
106
108
  return this.write(async () => {
107
- const { key, expectedSealedOAuth, patch } = required;
109
+ const { key, expectedSealedOAuth, expectedConfig, patch } = required;
108
110
  const current = this.rows.get(keyOf(key.workspaceId, key.serverId));
109
111
  if (!current)
110
112
  return false;
113
+ if (expectedConfig !== undefined && (current.version !== expectedConfig.version || current.createdAt !== expectedConfig.createdAt))
114
+ return false;
111
115
  const expectedId = this.pointerId({ sealed: expectedSealedOAuth, identity: current, kind: "mcp-auth" });
112
116
  if (expectedId !== this.pointerId({ sealed: current.sealedOAuth, identity: current, kind: "mcp-auth" }))
113
117
  return false;
@@ -8,6 +8,8 @@ export * from "./refusal-notice.js";
8
8
  export * from "./registrations.js";
9
9
  export * from "./bootstrap.js";
10
10
  export * from "./reload.js";
11
+ export * from "./runtime.js";
12
+ export * from "./roster-change.js";
11
13
  export * from "./admissions.js";
12
14
  export * from "./tool-approvals.js";
13
15
  export * from "./approvals/index.js";
@@ -8,6 +8,8 @@ export * from "./refusal-notice.js";
8
8
  export * from "./registrations.js";
9
9
  export * from "./bootstrap.js";
10
10
  export * from "./reload.js";
11
+ export * from "./runtime.js";
12
+ export * from "./roster-change.js";
11
13
  export * from "./admissions.js";
12
14
  export * from "./tool-approvals.js";
13
15
  export * from "./approvals/index.js";
@@ -2,6 +2,77 @@ import { ToolInputError } from "@jini-ai/core";
2
2
  import { McpAuthFailedError } from "./mcp-protocol.js";
3
3
  import { admitRemoteTools, isOperatorDeclaredReadOnly, assertNoNativeCollision, extractFederatedImageBlocks, FEDERATED_ENTITY_TYPE, FEDERATED_TOOL_PERMISSION, wrapUntrustedResult, writeShapedInputNames, federatedCallConfirmationForAction, federatedToolId, federatedToolRequiresWriteGrant, refusalForAdmittedToolUnderCurrentGrants, strongestFederatedConfirmation, } from "./trust.js";
4
4
  import { revocationReasonForToolRefusal } from "./approvals/revocation-reason.js";
5
+ /**
6
+ * Shapes one remote call's result for the model: image blocks are hoisted onto the daemon's typed
7
+ * media channel and everything else is wrapped as untrusted data.
8
+ */
9
+ function federatedResultForModel({ result, config, tool }) {
10
+ // R7's media carve-out (trust.ts): image blocks are pulled out of `result.content` BEFORE the
11
+ // untrusted-data envelope is built, so they reach the model through the daemon's typed
12
+ // `media` channel (`extractResultMedia`) intact — see `extractFederatedImageBlocks`'s own doc
13
+ // for why stringifying them into the byte-capped text boundary instead would corrupt them.
14
+ const { images, remainder } = extractFederatedImageBlocks({
15
+ content: result.content,
16
+ maxResultBytes: config.maxResultBytes,
17
+ });
18
+ // R7. Every federated result reaches the model inside an untrusted-data boundary, including
19
+ // the remote's own `isError` claim — which is reported as data rather than acted on, because
20
+ // a remote lying about its own success is not a case this side can adjudicate.
21
+ return {
22
+ federated: { connectionId: config.connectionId, tool: tool.remoteName, remoteReportedError: result.isError === true },
23
+ untrusted: wrapUntrustedResult({
24
+ connectionLabel: config.label,
25
+ remoteName: tool.remoteName,
26
+ result: { content: remainder, structuredContent: result.structuredContent },
27
+ maxResultBytes: config.maxResultBytes,
28
+ }),
29
+ // The ONLY field `@jini-ai/daemon`'s `extractResultMedia` reads to hoist inline media onto
30
+ // the `tool_result` wire event — see `demo-image-tool.ts` for the identical shape proven
31
+ // end to end through the chat pane. Omitted (not an empty array) when there is nothing to
32
+ // hoist, so a text-only result's return shape is byte-identical to before this existed.
33
+ ...(images.length > 0 ? { content: images } : {}),
34
+ };
35
+ }
36
+ /**
37
+ * The one `ToolHandler` for an admitted federated tool: gate, ask, forward `tools/call`, and wrap
38
+ * the result. This handler is the tool's single authorization evaluator.
39
+ */
40
+ function federatedToolHandler({ session, config, deps, tool, call }) {
41
+ return async (ctx, options = {}) => {
42
+ await assertCallAllowed({ ctx, deps, config, call });
43
+ // Fixed ONCE, before any card is drawn: the frozen copy the human sees is the same object that
44
+ // is sent, so nothing that happens to `ctx.input` while the card waits can change what runs.
45
+ const args = frozenArguments(ctx.input);
46
+ const declined = await askBeforeCall({ ctx: { ...ctx, ...options }, deps, config, tool, args, call });
47
+ if (declined)
48
+ return declined;
49
+ let result;
50
+ try {
51
+ result = await session.callTool({ name: tool.remoteName, arguments: args }, { signal: ctx.signal });
52
+ }
53
+ catch (error) {
54
+ // A token valid at boot can die mid-session; nothing here re-probes it proactively (no
55
+ // periodic refresh exists), so this is where that discovery actually happens. Handed to
56
+ // `onAuthFailed` so the SAME durable state and terminal, non-retryable error this file's
57
+ // `assertConnectionUsable` doc already promises apply here too — not just to a connection
58
+ // already known dead at the call's start.
59
+ if (error instanceof McpAuthFailedError && deps.onAuthFailed)
60
+ await deps.onAuthFailed({ connectionId: config.connectionId, error: error });
61
+ throw error;
62
+ }
63
+ return federatedResultForModel({ result, config, tool });
64
+ };
65
+ }
66
+ /** The published descriptor: provenance metadata, the remote's untrusted schema, and the operator's read-only marker. */
67
+ function federatedToolDescriptor({ tool, config }) {
68
+ return {
69
+ id: tool.toolId,
70
+ metadata: { mcpSource: { id: config.connectionId, host: config.sourceHost ?? "unknown", ...(config.provisionedByPluginId ? { pluginId: config.provisionedByPluginId } : {}) } },
71
+ description: tool.description,
72
+ inputSchema: tool.inputSchema,
73
+ ...(isOperatorDeclaredReadOnly({ remoteName: tool.remoteName, annotations: tool.declaredAnnotations, readList: config.readOnlyRemoteNames }) ? { readOnly: true } : {}),
74
+ };
75
+ }
5
76
  /**
6
77
  * Builds the `ToolRegistration`s for one federated connection from its already-listed tool surface.
7
78
  *
@@ -26,67 +97,13 @@ export function buildFederatedMcpRegistrations(params) {
26
97
  origin: config.origin,
27
98
  requiresWriteGrant: federatedToolRequiresWriteGrant({ remoteName: tool.remoteName, annotations: tool.declaredAnnotations }, { readList: config.readOnlyRemoteNames }),
28
99
  };
29
- const handler = async (ctx, options = {}) => {
30
- await assertCallAllowed({ ctx, deps, config, call });
31
- // Fixed ONCE, before any card is drawn: the frozen copy the human sees is the same object that
32
- // is sent, so nothing that happens to `ctx.input` while the card waits can change what runs.
33
- const args = frozenArguments(ctx.input);
34
- const declined = await askBeforeCall({ ctx: { ...ctx, ...options }, deps, config, tool, args, call });
35
- if (declined)
36
- return declined;
37
- let result;
38
- try {
39
- result = await session.callTool({ name: tool.remoteName, arguments: args }, { signal: ctx.signal });
40
- }
41
- catch (error) {
42
- // A token valid at boot can die mid-session; nothing here re-probes it proactively (no
43
- // periodic refresh exists), so this is where that discovery actually happens. Handed to
44
- // `onAuthFailed` so the SAME durable state and terminal, non-retryable error this file's
45
- // `assertConnectionUsable` doc already promises apply here too — not just to a connection
46
- // already known dead at the call's start.
47
- if (error instanceof McpAuthFailedError && deps.onAuthFailed)
48
- await deps.onAuthFailed({ connectionId: config.connectionId, error: error });
49
- throw error;
50
- }
51
- // R7's media carve-out (trust.ts): image blocks are pulled out of `result.content` BEFORE the
52
- // untrusted-data envelope is built, so they reach the model through the daemon's typed
53
- // `media` channel (`extractResultMedia`) intact — see `extractFederatedImageBlocks`'s own doc
54
- // for why stringifying them into the byte-capped text boundary instead would corrupt them.
55
- const { images, remainder } = extractFederatedImageBlocks({
56
- content: result.content,
57
- maxResultBytes: config.maxResultBytes,
58
- });
59
- // R7. Every federated result reaches the model inside an untrusted-data boundary, including
60
- // the remote's own `isError` claim — which is reported as data rather than acted on, because
61
- // a remote lying about its own success is not a case this side can adjudicate.
62
- return {
63
- federated: { connectionId: config.connectionId, tool: tool.remoteName, remoteReportedError: result.isError === true },
64
- untrusted: wrapUntrustedResult({
65
- connectionLabel: config.label,
66
- remoteName: tool.remoteName,
67
- result: { content: remainder, structuredContent: result.structuredContent },
68
- maxResultBytes: config.maxResultBytes,
69
- }),
70
- // The ONLY field `@jini-ai/daemon`'s `extractResultMedia` reads to hoist inline media onto
71
- // the `tool_result` wire event — see `demo-image-tool.ts` for the identical shape proven
72
- // end to end through the chat pane. Omitted (not an empty array) when there is nothing to
73
- // hoist, so a text-only result's return shape is byte-identical to before this existed.
74
- ...(images.length > 0 ? { content: images } : {}),
75
- };
76
- };
77
100
  return {
78
- descriptor: {
79
- id: tool.toolId,
80
- metadata: { mcpSource: { id: config.connectionId, host: config.sourceHost ?? "unknown", ...(config.provisionedByPluginId ? { pluginId: config.provisionedByPluginId } : {}) } },
81
- description: tool.description,
82
- inputSchema: tool.inputSchema,
83
- ...(isOperatorDeclaredReadOnly({ remoteName: tool.remoteName, annotations: tool.declaredAnnotations, readList: config.readOnlyRemoteNames }) ? { readOnly: true } : {}),
84
- },
101
+ descriptor: federatedToolDescriptor({ tool, config }),
85
102
  // Pass-through, matching `buildDomainRegistrations`'s identical choice and for the identical
86
103
  // §2 reason: the handler above IS this tool's one gate, and a `ToolPolicy` check would. See docs/decisions/DR-003-trusted-federation-composition.md.
87
104
  // be a second evaluator of the same rule.
88
105
  policy: { authorize: () => "allow" },
89
- handler,
106
+ handler: federatedToolHandler({ session, config, deps, tool, call }),
90
107
  };
91
108
  });
92
109
  return { registrations, report };