@jini-ai/mcp 0.7.2 → 0.7.3-next.2

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 (146) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/agent-install/antigravity/install.d.ts +15 -0
  3. package/dist/agent-install/antigravity/install.js +15 -0
  4. package/dist/agent-install/claude/install.d.ts +4 -0
  5. package/dist/agent-install/claude/install.js +11 -0
  6. package/dist/agent-install/cline/install.d.ts +4 -0
  7. package/dist/agent-install/cline/install.js +7 -0
  8. package/dist/agent-install/codex/install.d.ts +4 -0
  9. package/dist/agent-install/codex/install.js +10 -0
  10. package/dist/agent-install/cursor/install.d.ts +4 -0
  11. package/dist/agent-install/cursor/install.js +4 -0
  12. package/dist/agent-install/hermes/install.d.ts +4 -0
  13. package/dist/agent-install/hermes/install.js +26 -0
  14. package/dist/agent-install/index.d.ts +1 -1
  15. package/dist/agent-install/install.d.ts +1 -11
  16. package/dist/agent-install/install.js +29 -167
  17. package/dist/agent-install/kimi/install.d.ts +4 -0
  18. package/dist/agent-install/kimi/install.js +10 -0
  19. package/dist/agent-install/openclaw/install.d.ts +4 -0
  20. package/dist/agent-install/openclaw/install.js +4 -0
  21. package/dist/agent-install/opencode/install.d.ts +4 -0
  22. package/dist/agent-install/opencode/install.js +7 -0
  23. package/dist/agent-install/owned-json-install.d.ts +7 -0
  24. package/dist/agent-install/owned-json-install.js +4 -4
  25. package/dist/agent-install/pi/install.d.ts +4 -0
  26. package/dist/agent-install/pi/install.js +13 -0
  27. package/dist/agent-install/planner-shared.d.ts +40 -0
  28. package/dist/agent-install/planner-shared.js +52 -0
  29. package/dist/agent-install/trae/install.d.ts +4 -0
  30. package/dist/agent-install/trae/install.js +7 -0
  31. package/dist/agent-install/vibe/install.d.ts +4 -0
  32. package/dist/agent-install/vibe/install.js +30 -0
  33. package/dist/bin/serve.js +5 -3
  34. package/dist/client/client.js +11 -7
  35. package/dist/core/claude/config.d.ts +21 -0
  36. package/dist/core/claude/config.js +29 -0
  37. package/dist/core/config-shared.d.ts +27 -0
  38. package/dist/core/config-shared.js +64 -0
  39. package/dist/core/config.d.ts +60 -81
  40. package/dist/core/config.js +33 -192
  41. package/dist/core/opencode/config.d.ts +39 -0
  42. package/dist/core/opencode/config.js +74 -0
  43. package/dist/core/tokens.d.ts +38 -25
  44. package/dist/core/tokens.js +23 -54
  45. package/dist/federation/adapter.http.d.ts +8 -5
  46. package/dist/federation/adapter.http.js +12 -8
  47. package/dist/federation/admissions.d.ts +36 -0
  48. package/dist/federation/admissions.js +34 -0
  49. package/dist/federation/approvals/call-confirmation.js +2 -2
  50. package/dist/federation/approvals/remembered-approval.d.ts +11 -2
  51. package/dist/federation/approvals/remembered-approval.js +11 -8
  52. package/dist/federation/approvals/revocation-reason.d.ts +3 -1
  53. package/dist/federation/approvals/revocation-reason.js +1 -1
  54. package/dist/federation/approvals/revocation.js +3 -3
  55. package/dist/federation/approvals/scope-option.d.ts +3 -1
  56. package/dist/federation/approvals/scope-option.js +1 -1
  57. package/dist/federation/bootstrap.d.ts +1 -1
  58. package/dist/federation/bootstrap.js +4 -5
  59. package/dist/federation/config.d.ts +1 -1
  60. package/dist/federation/hosted/access.d.ts +53 -1
  61. package/dist/federation/hosted/access.js +94 -0
  62. package/dist/federation/hosted/connection-gate.js +1 -1
  63. package/dist/federation/hosted/index.d.ts +11 -3
  64. package/dist/federation/hosted/index.js +9 -3
  65. package/dist/federation/hosted/pinned-capability.d.ts +91 -0
  66. package/dist/federation/hosted/pinned-capability.js +73 -0
  67. package/dist/federation/hosted/probe.d.ts +67 -0
  68. package/dist/federation/hosted/probe.js +99 -0
  69. package/dist/federation/hosted/revocation.d.ts +5 -2
  70. package/dist/federation/hosted/revocation.js +1 -1
  71. package/dist/federation/hosted/store-config.d.ts +43 -0
  72. package/dist/federation/hosted/store-config.js +209 -0
  73. package/dist/federation/hosted/store-credentials.d.ts +74 -0
  74. package/dist/federation/hosted/store-credentials.js +228 -0
  75. package/dist/federation/hosted/store-input.d.ts +55 -0
  76. package/dist/federation/hosted/store-input.js +232 -0
  77. package/dist/federation/hosted/store-oauth-fields.d.ts +26 -0
  78. package/dist/federation/hosted/store-oauth-fields.js +246 -0
  79. package/dist/federation/hosted/store-view.d.ts +49 -0
  80. package/dist/federation/hosted/store-view.js +112 -0
  81. package/dist/federation/hosted/store.d.ts +13 -180
  82. package/dist/federation/hosted/store.js +33 -1252
  83. package/dist/federation/hosted/store.memory.d.ts +26 -1
  84. package/dist/federation/hosted/store.memory.js +71 -22
  85. package/dist/federation/hosted/store.save.d.ts +39 -0
  86. package/dist/federation/hosted/store.save.js +63 -0
  87. package/dist/federation/hosted/vault.d.ts +79 -1
  88. package/dist/federation/hosted/vault.js +107 -0
  89. package/dist/federation/hosted/vocabulary.d.ts +1 -1
  90. package/dist/federation/hosted/vocabulary.js +1 -1
  91. package/dist/federation/index.d.ts +1 -0
  92. package/dist/federation/index.js +1 -0
  93. package/dist/federation/mcp-protocol.d.ts +1 -1
  94. package/dist/federation/mcp-protocol.js +1 -1
  95. package/dist/federation/ports.d.ts +2 -2
  96. package/dist/federation/refusal-notice.d.ts +1 -1
  97. package/dist/federation/refusal-notice.js +1 -1
  98. package/dist/federation/registrations.d.ts +6 -6
  99. package/dist/federation/registrations.js +1 -1
  100. package/dist/federation/reload.js +37 -36
  101. package/dist/federation/stdio/adapter.stdio.js +27 -20
  102. package/dist/federation/stdio/default-connect.d.ts +2 -5
  103. package/dist/federation/stdio/default-connect.js +2 -1
  104. package/dist/federation/stdio/index.d.ts +1 -0
  105. package/dist/federation/stdio/index.js +1 -0
  106. package/dist/federation/stdio/smoke.d.ts +62 -0
  107. package/dist/federation/stdio/smoke.js +156 -0
  108. package/dist/federation/trust.d.ts +2 -2
  109. package/dist/federation/trust.js +4 -4
  110. package/dist/index.d.ts +3 -4
  111. package/dist/index.js +1 -1
  112. package/dist/server/adapters/sdk-server.d.ts +88 -0
  113. package/dist/server/adapters/sdk-server.js +27 -0
  114. package/dist/server/{sdk-transport.d.ts → adapters/sdk-transport.d.ts} +3 -3
  115. package/dist/server/{sdk-transport.js → adapters/sdk-transport.js} +2 -2
  116. package/dist/server/adapters/sdk-wire.d.ts +16 -0
  117. package/dist/server/adapters/sdk-wire.js +16 -0
  118. package/dist/server/call-progress.d.ts +48 -0
  119. package/dist/server/call-progress.js +60 -0
  120. package/dist/server/http-tool-server.adapter.js +209 -196
  121. package/dist/server/index.d.ts +1 -0
  122. package/dist/server/loopback-fetch.d.ts +5 -0
  123. package/dist/server/loopback-fetch.js +48 -0
  124. package/dist/server/resource-protocol.d.ts +1 -1
  125. package/dist/server/run-tool-host.js +3 -1
  126. package/dist/server/stdio-hosting.d.ts +8 -12
  127. package/dist/server/stdio-hosting.js +135 -126
  128. package/dist/server/tool-arguments.d.ts +9 -1
  129. package/dist/server/tool-arguments.js +18 -4
  130. package/dist/server/tool-protocol.d.ts +15 -3
  131. package/dist/server/tool-protocol.js +18 -21
  132. package/dist/server/tool-result-pages.js +37 -28
  133. package/dist/server/tool-server.d.ts +8 -46
  134. package/dist/server/tool-server.js +138 -128
  135. package/dist/server/tools/component-catalog-tools.d.ts +2 -2
  136. package/dist/server/tools/component-catalog-tools.js +2 -2
  137. package/dist/server/tools/delegated-tool.js +74 -57
  138. package/dist/server/tools/run-tools.d.ts +5 -5
  139. package/dist/server/tools/run-tools.js +5 -5
  140. package/dist/server/tools/tool-catalog-tools.d.ts +2 -2
  141. package/dist/server/tools/tool-catalog-tools.js +35 -12
  142. package/package.json +8 -9
  143. package/dist/core/oauth.d.ts +0 -274
  144. package/dist/core/oauth.js +0 -667
  145. package/dist/core/secure-write.d.ts +0 -17
  146. package/dist/core/secure-write.js +0 -72
@@ -113,4 +113,98 @@ export function validateExternalMcpToolNames({ names, field }, _options = {}) {
113
113
  }
114
114
  return [...new Set(names)];
115
115
  }
116
+ /**
117
+ * Splits an operator's comma-separated list of remote tool names, shared by {@link
118
+ * parseAllowedToolNames} and {@link parseWriteAllowedToolNames} — the two lists use the identical
119
+ * charset, cap and dedup rule, and differ only in which field a rejection names.
120
+ *
121
+ * An empty result is a legitimate, meaningful value on either list — it yields a server that
122
+ * contributes (or write-authorizes) zero tools — so it is returned rather than rejected. That is the
123
+ * safe direction and matches `trust.ts` R2's default-deny posture.
124
+ *
125
+ * @throws {ExternalMcpValidationError} On a name the trust tier would refuse anyway, so the operator
126
+ * learns at save time instead of discovering an unexplained absence after a restart.
127
+ * @complexity O(n) in the number of names.
128
+ */
129
+ function parseToolNameList(raw, field) {
130
+ const names = raw
131
+ .split(",")
132
+ .map((part) => part.trim())
133
+ .filter((part) => part.length > 0);
134
+ return validateExternalMcpToolNames({ names, field });
135
+ }
136
+ /**
137
+ * Splits an operator's comma-separated allowlist of remote tool names.
138
+ *
139
+ * @throws {ExternalMcpValidationError} See {@link parseToolNameList}. `field` is `"allowedToolNames"`.
140
+ * @complexity O(n) in the number of names.
141
+ * @overallScore 100
142
+ */
143
+ export function parseAllowedToolNames({ raw }, _optional = {}) {
144
+ return parseToolNameList(raw, "allowedToolNames");
145
+ }
146
+ /**
147
+ * Splits an operator's comma-separated list of remote tool names separately authorized to write —
148
+ * `trust.ts` R3's override, checked only after {@link parseAllowedToolNames}'s allowlist passes (see
149
+ * {@link assertWriteAllowlistSubset}).
150
+ *
151
+ * @throws {ExternalMcpValidationError} See {@link parseToolNameList}. `field` is
152
+ * `"writeAllowedToolNames"`.
153
+ * @complexity O(n) in the number of names.
154
+ * @overallScore 100
155
+ */
156
+ export function parseWriteAllowedToolNames({ raw }, _optional = {}) {
157
+ return parseToolNameList(raw, "writeAllowedToolNames");
158
+ }
159
+ /**
160
+ * A tool may be write-authorized only if it is ALSO allowlisted. Enforced at save time so an
161
+ * operator learns of the mistake immediately rather than the entry sitting inert (or, worse, being
162
+ * misread as intentional) until a boot-time report surfaces it.
163
+ *
164
+ * @throws {ExternalMcpValidationError} Naming the first write-authorized tool absent from the
165
+ * allowlist, with `field === "writeAllowedToolNames"`.
166
+ * @complexity O(n) in the number of write-authorized names.
167
+ */
168
+ export function assertWriteAllowlistSubset(writeAllowedToolNames, allowedToolNames) {
169
+ const allowed = new Set(allowedToolNames);
170
+ for (const name of writeAllowedToolNames) {
171
+ if (!allowed.has(name)) {
172
+ throw new ExternalMcpValidationError(`'${name}' is authorized to write but is not in the allowlist — a tool must be allowlisted before it can be write-authorized`, "writeAllowedToolNames");
173
+ }
174
+ }
175
+ }
176
+ /** Whether two tool-name lists name the same SET of tools, ignoring order — the write list is a set
177
+ * of operator decisions, not an ordered sequence, so a save that re-sends the same names in a
178
+ * different order must not read as a change. Used only to decide whether {@link
179
+ * resolveWriteGrantAttribution} owes a new attribution.
180
+ * @complexity O(n) in the longer list. */
181
+ function toolNameSetsEqual(a, b) {
182
+ if (a.length !== b.length)
183
+ return false;
184
+ const setB = new Set(b);
185
+ return a.every((name) => setB.has(name));
186
+ }
187
+ /**
188
+ * Resolves the two write-grant attribution columns for one save.
189
+ *
190
+ * Written ONLY when {@link writeAllowedToolNames}'s contents actually change — compared as a set
191
+ * against whatever the row already has — so a save that merely renames a connection or flips
192
+ * `enabled` does not stamp a new "authorized by / on" over an untouched grant. `input.principalId`
193
+ * is read only on the changed branch, which is what lets it stay a required TYPE without becoming a
194
+ * runtime hazard: a caller written before this field existed can only reach `undefined` here if it
195
+ * also never sets a non-empty {@link SaveExternalMcpServerInput.writeAllowedToolNames}, in which case
196
+ * the list never changes and this branch never runs.
197
+ *
198
+ * @complexity O(n) in the length of the longer list (via {@link toolNameSetsEqual}).
199
+ */
200
+ export function resolveWriteGrantAttribution({ input, writeAllowedToolNames, existing, nowIso }, _optional = {}) {
201
+ const previousWriteAllowedToolNames = parseExternalMcpJsonArray({ raw: existing?.writeAllowedToolNames ?? null });
202
+ if (toolNameSetsEqual(previousWriteAllowedToolNames, writeAllowedToolNames)) {
203
+ return {
204
+ writeGrantsUpdatedByPrincipalId: existing?.writeGrantsUpdatedByPrincipalId ?? null,
205
+ writeGrantsUpdatedAt: existing?.writeGrantsUpdatedAt ?? null,
206
+ };
207
+ }
208
+ return { writeGrantsUpdatedByPrincipalId: input.principalId, writeGrantsUpdatedAt: nowIso };
209
+ }
116
210
  //# sourceMappingURL=access.js.map
@@ -38,7 +38,7 @@ export function createHostedMcpConnectionGate(deps) {
38
38
  const record = await readConnectionRowOrRefuse(deps, connectionId);
39
39
  await assertProvisioningPluginEnabled({ deps, record });
40
40
  const isPreset = call.origin?.kind === "preset";
41
- const refusal = isPreset ? null : rosterRefusalFor(record, call);
41
+ const refusal = isPreset ? null : rosterRefusalFor({ record, call });
42
42
  if (refusal !== null) {
43
43
  offerPluginAccessCard({ deps, record, refusal });
44
44
  throw deps.revoked({ serverId: connectionId, label: record?.label ?? null, remoteName: call.remoteName, reason: refusal });
@@ -1,14 +1,22 @@
1
1
  /** @agent-note Node entry: values for hosted MCP connections. Types come from `@jini-ai/core/contracts/hosted-mcp`; the host wires these values into its store, plugin and sign-in seams. No other Jini package is imported. */
2
2
  export * from "./vocabulary.js";
3
3
  export * from "./auth.js";
4
- export * from "./access.js";
4
+ export { parseExternalMcpJsonArray, externalMcpAdmissionRevision, externalMcpAccessSnapshot, readExternalMcpToolGrants, validateExternalMcpToolNames, parseAllowedToolNames, parseWriteAllowedToolNames } from "./access.js";
5
5
  export { ExternalMcpValidationError } from "./validation-error.js";
6
6
  export { ExternalMcpSecretStoreUnconfiguredError } from "./unconfigured-error.js";
7
7
  export { hostedMcpProjections } from "./projections.js";
8
8
  export type * from "./store-ports.js";
9
- export * from "./vault.js";
10
- export * from "./store.js";
9
+ export { externalMcpVaultEnvelope, externalMcpVaultRecord, sealExternalMcpVaultPayload, openExternalMcpVaultPayload, persistExternalMcpVaultEnvelope, deleteExternalMcpVaultEnvelope, EXTERNAL_MCP_VAULT_VERSION, EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION, hydrateExternalMcpOAuthPayload, openExternalMcpOAuthPayload, sealExternalMcpOAuthPayload } from "./vault.js";
10
+ export type { Identity, Kind } from "./vault.js";
11
+ export { applyExternalMcpAccess, saveExternalMcpServer, deleteExternalMcpServer } from "./store.js";
12
+ export type { HostedMcpStoreDeps } from "./store.js";
13
+ export { parseEnvBlock, parseArgs, parseOAuthScopes } from "./store-input.js";
14
+ export { normalizeExternalMcpAccessToken } from "./store-credentials.js";
15
+ export { externalMcpRecordHasStoredToken, listExternalMcpServerViews } from "./store-view.js";
16
+ export { readEnabledExternalMcpConfigs, toResolvedFederatedConnections } from "./store-config.js";
11
17
  export { InMemoryExternalMcpServerRepo } from "./store.memory.js";
12
18
  export * from "./revocation.js";
13
19
  export * from "./connection-gate.js";
20
+ export * from "./probe.js";
21
+ export * from "./pinned-capability.js";
14
22
  //# sourceMappingURL=index.d.ts.map
@@ -1,13 +1,19 @@
1
1
  /** @agent-note Node entry: values for hosted MCP connections. Types come from `@jini-ai/core/contracts/hosted-mcp`; the host wires these values into its store, plugin and sign-in seams. No other Jini package is imported. */
2
2
  export * from "./vocabulary.js";
3
3
  export * from "./auth.js";
4
- export * from "./access.js";
4
+ export { parseExternalMcpJsonArray, externalMcpAdmissionRevision, externalMcpAccessSnapshot, readExternalMcpToolGrants, validateExternalMcpToolNames, parseAllowedToolNames, parseWriteAllowedToolNames } from "./access.js";
5
5
  export { ExternalMcpValidationError } from "./validation-error.js";
6
6
  export { ExternalMcpSecretStoreUnconfiguredError } from "./unconfigured-error.js";
7
7
  export { hostedMcpProjections } from "./projections.js";
8
- export * from "./vault.js";
9
- export * from "./store.js";
8
+ export { externalMcpVaultEnvelope, externalMcpVaultRecord, sealExternalMcpVaultPayload, openExternalMcpVaultPayload, persistExternalMcpVaultEnvelope, deleteExternalMcpVaultEnvelope, EXTERNAL_MCP_VAULT_VERSION, EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION, hydrateExternalMcpOAuthPayload, openExternalMcpOAuthPayload, sealExternalMcpOAuthPayload } from "./vault.js";
9
+ export { applyExternalMcpAccess, saveExternalMcpServer, deleteExternalMcpServer } from "./store.js";
10
+ export { parseEnvBlock, parseArgs, parseOAuthScopes } from "./store-input.js";
11
+ export { normalizeExternalMcpAccessToken } from "./store-credentials.js";
12
+ export { externalMcpRecordHasStoredToken, listExternalMcpServerViews } from "./store-view.js";
13
+ export { readEnabledExternalMcpConfigs, toResolvedFederatedConnections } from "./store-config.js";
10
14
  export { InMemoryExternalMcpServerRepo } from "./store.memory.js";
11
15
  export * from "./revocation.js";
12
16
  export * from "./connection-gate.js";
17
+ export * from "./probe.js";
18
+ export * from "./pinned-capability.js";
13
19
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @file Immutable pinning and changing-capability delivery for a hosted MCP endpoint that one host
3
+ * process owns and hands to the processes it spawns.
4
+ *
5
+ * Why this exists: the spawning process holds a loopback `{ url, token }` capability plus a private
6
+ * handoff token. A child must be able to read the capability once, then lose the environment copy
7
+ * (so nothing it spawns inherits it), and a different process must never be able to replace a
8
+ * capability that is already pinned. The token is reachable ONLY through the bearer supplier, which
9
+ * answers only for the exact pinned endpoint; no accessor hands out the pinned object or the token.
10
+ * When the listener binds late or rebinds, the new capability is delivered to the child with the
11
+ * handoff token as bearer; delivery is cancellable and never replays tool calls.
12
+ *
13
+ * The endpoint policy (which URL spellings count as a capability) and the environment variable
14
+ * NAMES are the host's: they arrive as `isCapability` and `names`. The handoff token format is fixed
15
+ * here: 64 lowercase hex characters (32 random bytes); any other value is dropped, not accepted.
16
+ */
17
+ import type { McpBearerTokenSupplier } from "@jini-ai/core/contracts/hosted-mcp";
18
+ export interface PinnedCapability {
19
+ readonly url: string;
20
+ readonly token: string;
21
+ }
22
+ /** Environment variable names the spawn contract uses. They are scrubbed from `env` on capture. */
23
+ export interface PinnedCapabilityNames {
24
+ readonly url: string;
25
+ readonly token: string;
26
+ readonly handoff: string;
27
+ }
28
+ export interface PinnedCapabilityRuntime {
29
+ readonly handoffToken: string | undefined;
30
+ /** True once this process was handed a capability or the authority to receive one. */
31
+ readonly owned: boolean;
32
+ /** The names this runtime deleted from the `env` object it was given, so a host can assert on them. */
33
+ readonly scrubbed: readonly string[];
34
+ /** Answers only for the exact pinned endpoint; anything else gets no token. */
35
+ readonly bearerToken: McpBearerTokenSupplier;
36
+ /** The pinned endpoint URL, or `null` while none is pinned. Never the token and never the pin itself. */
37
+ endpointUrl(required: Record<string, never>, optional?: Record<string, never>): string | null;
38
+ accept(required: PinnedCapability, optional?: Record<string, never>): boolean;
39
+ }
40
+ export interface PinnedCapabilityRequired {
41
+ /** Mutated: the three named keys are deleted from THIS object. Pass the live environment object the
42
+ * process's children inherit; if you pass a copy, nothing a child inherits is scrubbed and the host
43
+ * must delete the same names from the live environment itself. */
44
+ readonly env: Record<string, string | undefined>;
45
+ readonly names: PinnedCapabilityNames;
46
+ /** Host endpoint policy: exact spelling and token shape of an acceptable capability. It is shown a
47
+ * detached copy holding only `url` and `token`, and exactly that copy is what gets pinned. */
48
+ readonly isCapability: (value: unknown) => value is PinnedCapability;
49
+ }
50
+ /** Capture and scrub the spawn contract before any child can inherit it. An initial bind failure
51
+ * leaves only the handoff authority; its authenticated later delivery can fill the endpoint once.
52
+ * A different process can never replace a pinned endpoint, and nothing the runtime returns can move
53
+ * the pin. No I/O or persistence.
54
+ * @example const runtime = createPinnedCapabilityRuntime({ env: process.env, names, isCapability });
55
+ * @complexity O(1) time/state.
56
+ */
57
+ export declare function createPinnedCapabilityRuntime({ env, names, isCapability }: PinnedCapabilityRequired, _optional?: Record<string, never>): PinnedCapabilityRuntime;
58
+ /** The slice of a hosted tool-server runtime that capability delivery needs. */
59
+ export interface CapabilitySubscribable {
60
+ subscribe(required: {
61
+ listener: (capability: PinnedCapability) => void | Promise<void>;
62
+ }, optional?: Record<string, never>): () => void;
63
+ }
64
+ export interface CapabilityDeliveryRequired {
65
+ /** Where each capability is POSTed (already validated by the host's endpoint policy). */
66
+ readonly endpoint: URL;
67
+ readonly handoffToken: string;
68
+ /** Resolves to the hosted runtime, or `undefined` when the listener never became available. */
69
+ readonly host: Promise<CapabilitySubscribable | undefined>;
70
+ readonly fetch: typeof fetch;
71
+ /** Called when the host promise rejects or subscribing throws, with that error as thrown. It is never
72
+ * a delivery failure (those reject to the subscribed runtime), so it carries no token and no request
73
+ * body; the host still words and redacts the warning it shows. */
74
+ readonly onUnavailable: (required: {
75
+ error: unknown;
76
+ }, optional?: Record<string, never>) => void;
77
+ }
78
+ export interface CapabilityDeliveryOptions {
79
+ readonly timeoutMs?: number;
80
+ }
81
+ /** Deliver every capability the host publishes to one child until `disconnect`. Retries belong to the
82
+ * subscribed runtime, which also repairs the listener; a failed POST rejects so it retries. The POST
83
+ * never follows a redirect (the handoff bearer goes to the one configured endpoint only) and is aborted
84
+ * by `disconnect` and by the timeout. A refused delivery names the HTTP status and nothing else.
85
+ * @example const { disconnect } = startCapabilityDelivery({ endpoint, handoffToken, host, fetch, onUnavailable });
86
+ * @complexity O(1) state; one POST per published capability.
87
+ */
88
+ export declare function startCapabilityDelivery({ endpoint, handoffToken, host, fetch: fetchImpl, onUnavailable }: CapabilityDeliveryRequired, { timeoutMs }?: CapabilityDeliveryOptions): {
89
+ disconnect(required: Record<string, never>, optional?: Record<string, never>): void;
90
+ };
91
+ //# sourceMappingURL=pinned-capability.d.ts.map
@@ -0,0 +1,73 @@
1
+ const HANDOFF_PATTERN = /^[a-f0-9]{64}$/;
2
+ /** A detached, frozen `{ url, token }` read once from `value`: extra properties are never held, and a
3
+ * later change to the caller's object (or a property that answers differently on a second read) cannot
4
+ * reach the pin. Non-objects pass through for the host predicate to refuse. */
5
+ function detached({ value }, _optional = {}) {
6
+ if (typeof value !== "object" || value === null)
7
+ return value;
8
+ const { url, token } = value;
9
+ return Object.freeze({ url, token });
10
+ }
11
+ /** Deletes the three contract keys from `env`, valid or not, and reports which ones were present. */
12
+ function scrub({ env, names }, _optional = {}) {
13
+ const present = [names.url, names.token, names.handoff].filter(key => key in env);
14
+ for (const key of present)
15
+ delete env[key];
16
+ return Object.freeze(present);
17
+ }
18
+ /** Capture and scrub the spawn contract before any child can inherit it. An initial bind failure
19
+ * leaves only the handoff authority; its authenticated later delivery can fill the endpoint once.
20
+ * A different process can never replace a pinned endpoint, and nothing the runtime returns can move
21
+ * the pin. No I/O or persistence.
22
+ * @example const runtime = createPinnedCapabilityRuntime({ env: process.env, names, isCapability });
23
+ * @complexity O(1) time/state.
24
+ */
25
+ export function createPinnedCapabilityRuntime({ env, names, isCapability }, _optional = {}) {
26
+ const candidate = detached({ value: { url: env[names.url], token: env[names.token] } });
27
+ let capability = isCapability(candidate) ? candidate : undefined;
28
+ const suppliedHandoff = env[names.handoff];
29
+ const handoffToken = suppliedHandoff && HANDOFF_PATTERN.test(suppliedHandoff) ? suppliedHandoff : undefined;
30
+ const scrubbed = scrub({ env, names });
31
+ return {
32
+ handoffToken,
33
+ owned: capability !== undefined || handoffToken !== undefined,
34
+ scrubbed,
35
+ bearerToken: ({ url }) => (capability && url === capability.url ? capability.token : undefined),
36
+ endpointUrl: (_required, _optional = {}) => capability?.url ?? null,
37
+ accept(input, _optional = {}) {
38
+ const delivered = detached({ value: input });
39
+ if (!isCapability(delivered))
40
+ return false;
41
+ if (capability && (capability.url !== delivered.url || capability.token !== delivered.token))
42
+ return false;
43
+ capability ??= delivered;
44
+ return true;
45
+ },
46
+ };
47
+ }
48
+ /** Deliver every capability the host publishes to one child until `disconnect`. Retries belong to the
49
+ * subscribed runtime, which also repairs the listener; a failed POST rejects so it retries. The POST
50
+ * never follows a redirect (the handoff bearer goes to the one configured endpoint only) and is aborted
51
+ * by `disconnect` and by the timeout. A refused delivery names the HTTP status and nothing else.
52
+ * @example const { disconnect } = startCapabilityDelivery({ endpoint, handoffToken, host, fetch, onUnavailable });
53
+ * @complexity O(1) state; one POST per published capability.
54
+ */
55
+ export function startCapabilityDelivery({ endpoint, handoffToken, host, fetch: fetchImpl, onUnavailable }, { timeoutMs = 5000 } = {}) {
56
+ const abort = new AbortController();
57
+ let unsubscribe;
58
+ void host.then(runtime => {
59
+ if (abort.signal.aborted)
60
+ return;
61
+ unsubscribe = runtime?.subscribe({ listener: async (capability) => {
62
+ const response = await fetchImpl(endpoint, { method: "POST", redirect: "error",
63
+ headers: { authorization: `Bearer ${handoffToken}`, "content-type": "application/json" },
64
+ body: JSON.stringify(capability), signal: AbortSignal.any([abort.signal, AbortSignal.timeout(timeoutMs)]),
65
+ });
66
+ await response.body?.cancel();
67
+ if (!response.ok)
68
+ throw new Error(`Capability handoff unavailable: the receiving process answered HTTP ${response.status}`);
69
+ } });
70
+ }).catch((error) => { onUnavailable({ error }); });
71
+ return { disconnect(_required, _optional = {}) { abort.abort(); unsubscribe?.(); } };
72
+ }
73
+ //# sourceMappingURL=pinned-capability.js.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @file Probe one saved hosted MCP server: resolve its credentials through the host's bound store read,
3
+ * connect once, list and describe its tools, close. Never spawns a local command and never invokes a
4
+ * remote tool. OAuth resolution inside the store read can refresh and persist a grant, so a probe is
5
+ * not read-only. Failures are typed kinds; the host owns statuses, response bodies, copy and links.
6
+ */
7
+ import type { ExternalMcpConfigFailure, ExternalMcpServerConfig, ExternalMcpServerRepoPort } from "@jini-ai/core/contracts/hosted-mcp";
8
+ import type { UUID } from "@jini-ai/core/primitives";
9
+ import type { McpHttpLaunchSpec, McpSessionPort } from "../ports.js";
10
+ import { describeRemoteToolSurface } from "../trust.js";
11
+ /** Injectable session factory — the seam a test scripts instead of opening a real socket, so the
12
+ * protocol code under test is the real thing, not a second hand-rolled fake of it. */
13
+ export type ExternalMcpProbeSessionFactory = (required: {
14
+ spec: McpHttpLaunchSpec;
15
+ requestTimeoutMs: number;
16
+ }, optional?: Record<string, never>) => Promise<McpSessionPort>;
17
+ /** @agent-note Host-wired. `readEnabledConfigs` is the host's already-bound hosted-store read (its vault,
18
+ * credential policy and settings link applied), so credential resolution is never re-implemented here. */
19
+ export interface ExternalMcpProbePorts {
20
+ readonly repo: Pick<ExternalMcpServerRepoPort, "findByServerId">;
21
+ readonly readEnabledConfigs: (required: {
22
+ workspaceId: UUID;
23
+ }) => Promise<{
24
+ readonly configs: readonly ExternalMcpServerConfig[];
25
+ readonly failures: readonly ExternalMcpConfigFailure[];
26
+ }>;
27
+ /** One handshake bounded by the connection's own `connectTimeoutMs` (the session is closed right after one `listTools`). */
28
+ readonly connect: ExternalMcpProbeSessionFactory;
29
+ }
30
+ /** Why a probe did not list tools. `stage` separates the record-level refusal from the defensive launch-shape check. */
31
+ export type ExternalMcpProbeFailure = {
32
+ readonly kind: "unknown_server";
33
+ } | {
34
+ readonly kind: "local_command";
35
+ readonly stage: "record" | "launch";
36
+ } | {
37
+ readonly kind: "disabled";
38
+ } | {
39
+ readonly kind: "reauth_required";
40
+ readonly stage: "stored";
41
+ readonly label: string | null;
42
+ } | {
43
+ readonly kind: "reauth_required";
44
+ readonly stage: "resolve";
45
+ readonly reason: string;
46
+ } | {
47
+ readonly kind: "unresolved";
48
+ readonly reason?: string;
49
+ } | {
50
+ readonly kind: "auth" | "timeout" | "unreachable";
51
+ };
52
+ export type ExternalMcpProbeResult = {
53
+ readonly ok: true;
54
+ readonly tools: ReturnType<typeof describeRemoteToolSurface>;
55
+ } | {
56
+ readonly ok: false;
57
+ readonly failure: ExternalMcpProbeFailure;
58
+ };
59
+ /** Resolves credentials, probes once, then closes. OAuth resolution can refresh and persist a grant, so
60
+ * this operation is not read-only.
61
+ * @complexity O(n + t) time and space for saved servers and advertised tools, plus bounded I/O. */
62
+ export declare function probeExternalMcpServer({ ports, workspaceId, serverId }: {
63
+ readonly ports: ExternalMcpProbePorts;
64
+ readonly workspaceId: UUID;
65
+ readonly serverId: string;
66
+ }, _optional?: Record<string, never>): Promise<ExternalMcpProbeResult>;
67
+ //# sourceMappingURL=probe.d.ts.map
@@ -0,0 +1,99 @@
1
+ import { McpAuthFailedError, McpProtocolError } from "../mcp-protocol.js";
2
+ import { describeRemoteToolSurface } from "../trust.js";
3
+ import { resolveExternalMcpAuthMode, resolveExternalMcpOAuthStatus } from "./auth.js";
4
+ import { toResolvedFederatedConnections } from "./store-config.js";
5
+ /** Refuses a local-command row, a disabled row, and a row already parked `needs_reauth`, all from the
6
+ * record alone — before any credential is ever resolved.
7
+ * @returns The refusal, or `null` to continue resolving.
8
+ * @complexity O(1). */
9
+ function refuseBeforeResolving({ record }, _optional = {}) {
10
+ if (record.transport === "stdio")
11
+ return { kind: "local_command", stage: "record" };
12
+ if (!record.enabled)
13
+ return { kind: "disabled" };
14
+ if (resolveExternalMcpAuthMode(record) === "oauth" && resolveExternalMcpOAuthStatus(record) === "needs_reauth") {
15
+ return { kind: "reauth_required", stage: "stored", label: record.label };
16
+ }
17
+ return null;
18
+ }
19
+ /** Turns one store-read MISS into a typed failure. A row whose stored status was `"connected"` but whose
20
+ * live token refresh failed with an invalid grant during this exact call carries the typed
21
+ * `reauth_required` category; branching on the type (never the prose) keeps that distinction stable.
22
+ * @complexity O(1). */
23
+ function resolutionFailure({ failure }, _optional = {}) {
24
+ if (failure?.category === "reauth_required")
25
+ return { kind: "reauth_required", stage: "resolve", reason: failure.reason };
26
+ return failure === undefined ? { kind: "unresolved" } : { kind: "unresolved", reason: failure.reason };
27
+ }
28
+ /** Resolves one `serverId` into a probeable target through the same store read a real connect uses,
29
+ * never a second, parallel reading of the row.
30
+ * @complexity O(n) in the workspace's configured server count (bounded by the store's per-workspace cap). */
31
+ async function resolveProbeTarget({ ports, workspaceId, serverId }, _optional = {}) {
32
+ const record = await ports.repo.findByServerId({ workspaceId, serverId });
33
+ if (!record)
34
+ return { ok: false, failure: { kind: "unknown_server" } };
35
+ const earlyRefusal = refuseBeforeResolving({ record });
36
+ if (earlyRefusal)
37
+ return { ok: false, failure: earlyRefusal };
38
+ const { configs, failures } = await ports.readEnabledConfigs({ workspaceId });
39
+ const config = configs.find((candidate) => candidate.serverId === serverId);
40
+ if (!config)
41
+ return { ok: false, failure: resolutionFailure({ failure: failures.find((candidate) => candidate.serverId === serverId) }) };
42
+ const [resolved] = toResolvedFederatedConnections({ configs: [config] });
43
+ // Defensive, not reachable given the transport check above (`config.transport` mirrors
44
+ // `record.transport` — both come from the same row): a probe must never launch a child process,
45
+ // and a launch-spec SHAPE check right before connecting is the cheapest second guarantee of that,
46
+ // independent of whatever produced `resolved`.
47
+ if (!resolved || !("url" in resolved.launch))
48
+ return { ok: false, failure: { kind: "local_command", stage: "launch" } };
49
+ return { ok: true, target: { federationConfig: resolved.config, launch: resolved.launch } };
50
+ }
51
+ /** Recognizes the probe's supported opaque HTTP and typed MCP authentication failures. */
52
+ function isProbeAuthFailure({ error }, _options = {}) {
53
+ const status = error && typeof error === 'object' ? error.status ?? error.statusCode : undefined;
54
+ if (status === 401 || status === 403 || error instanceof McpAuthFailedError)
55
+ return true;
56
+ return error instanceof McpProtocolError && /with HTTP (401|403)$/.test(error.message);
57
+ }
58
+ /** Only real Error instances and recognized protocol messages count as timeouts. */
59
+ function isProbeTimeoutFailure({ error }, _options = {}) {
60
+ if (!(error instanceof Error))
61
+ return false;
62
+ if (error.name === 'AbortError' || error.name === 'TimeoutError')
63
+ return true;
64
+ return error instanceof McpProtocolError && /request (?:timed out|was aborted)/.test(error.message);
65
+ }
66
+ /** Connects once, lists, describes, and closes — the `finally` is the whole safety story for the
67
+ * outbound session, kept separate to stay under the complexity ceiling.
68
+ * @complexity O(t) in the remote's advertised tool count, plus one round trip. */
69
+ async function runProbe({ connect, target }, _optional = {}) {
70
+ let session;
71
+ try {
72
+ session = await connect({ spec: target.launch, requestTimeoutMs: target.federationConfig.connectTimeoutMs });
73
+ const tools = await session.listTools();
74
+ return { ok: true, tools: describeRemoteToolSurface({ tools, config: target.federationConfig }) };
75
+ }
76
+ catch (err) {
77
+ // Report the failed connection without logging upstream errors that may contain credentials.
78
+ // Upstream bodies/errors may contain credentials; only the closed category crosses this boundary.
79
+ const auth = isProbeAuthFailure({ error: err });
80
+ const timeout = isProbeTimeoutFailure({ error: err });
81
+ const fallbackKind = timeout ? 'timeout' : 'unreachable';
82
+ return { ok: false, kind: auth ? 'auth' : fallbackKind };
83
+ }
84
+ finally {
85
+ // The probe result is already decided; closing its optional session is best effort.
86
+ await session?.close({}).catch(() => undefined);
87
+ }
88
+ }
89
+ /** Resolves credentials, probes once, then closes. OAuth resolution can refresh and persist a grant, so
90
+ * this operation is not read-only.
91
+ * @complexity O(n + t) time and space for saved servers and advertised tools, plus bounded I/O. */
92
+ export async function probeExternalMcpServer({ ports, workspaceId, serverId }, _optional = {}) {
93
+ const resolution = await resolveProbeTarget({ ports, workspaceId, serverId });
94
+ if (!resolution.ok)
95
+ return resolution;
96
+ const outcome = await runProbe({ connect: ports.connect, target: resolution.target });
97
+ return outcome.ok ? outcome : { ok: false, failure: { kind: outcome.kind } };
98
+ }
99
+ //# sourceMappingURL=probe.js.map
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * `ExternalMcpConnectionRevokedError` extends `ToolInputError` rather than being reported through a
17
17
  * `ToolPolicy` deny — the same D1 argument `registrations.ts`'s own gate doc and
18
- * `federated-refusal-diagnosis.ts` both make: every consumer maps a policy `denied` to a fixed
18
+ * `packages/daemon/src/tool-recovery/federated-refusal.ts` both make: every consumer maps a policy `denied` to a fixed
19
19
  * "denied by policy"-shaped string, which sends an operator who DOES have the permission looking in
20
20
  * the wrong place. A handler-side `ToolInputError` reaches the model as `errorKind: 'validation'`
21
21
  * with this file's own text instead.
@@ -66,5 +66,8 @@ export declare class ExternalMcpConnectionRevokedError extends ToolInputError {
66
66
  * @complexity O(1).
67
67
  */
68
68
  /** @agent-note Pure: the caller passes the row it already read (the store's repository, once per call) and the admitted call identity; no I/O and no state. */
69
- export declare function rosterRefusalFor(record: ExternalMcpServerRecord | null, call: FederatedCallTarget): ExternalMcpRevocationReason | null;
69
+ export declare function rosterRefusalFor({ record, call }: {
70
+ record: ExternalMcpServerRecord | null;
71
+ call: FederatedCallTarget;
72
+ }, _optional?: Record<string, never>): ExternalMcpRevocationReason | null;
70
73
  //# sourceMappingURL=revocation.d.ts.map
@@ -62,7 +62,7 @@ function grantRefusalFor(record, call) {
62
62
  * @complexity O(1).
63
63
  */
64
64
  /** @agent-note Pure: the caller passes the row it already read (the store's repository, once per call) and the admitted call identity; no I/O and no state. */
65
- export function rosterRefusalFor(record, call) {
65
+ export function rosterRefusalFor({ record, call }, _optional = {}) {
66
66
  if (call.origin === undefined || call.origin.kind === "preset")
67
67
  return "unverifiable";
68
68
  if (record === null)
@@ -0,0 +1,43 @@
1
+ import type { ResolvedFederatedConnection } from "../config.js";
2
+ import type { ExternalMcpConfigFailure, ExternalMcpOAuthTokenResolverPort, ExternalMcpServerConfig, ExternalMcpStoreDeps } from "@jini-ai/core/contracts/hosted-mcp";
3
+ import type { UUID } from "@jini-ai/core/primitives";
4
+ import type { HostedMcpStorePorts } from "./store-ports.js";
5
+ /**
6
+ * Reads and decrypts every ENABLED server, for the daemon's boot-time federation pass.
7
+ *
8
+ * A row whose sealed env cannot be opened is SKIPPED rather than thrown on, and the reason is
9
+ * returned in `failures`. This mirrors `bootstrap.ts`'s fail-open posture for the same reason: a
10
+ * rotated site key or a corrupt row must not stop the daemon booting, and one unusable server must
11
+ * not take out a second working one. Disabled rows never reach the sealer at all.
12
+ *
13
+ * @returns The usable configs plus a per-server accounting of what could not be read.
14
+ * @complexity O(n) in the enabled server count, one unseal each.
15
+ * @overallScore 100
16
+ */
17
+ export declare function readEnabledExternalMcpConfigs({ deps, workspaceId }: {
18
+ deps: Pick<ExternalMcpStoreDeps, "repo" | "sealer"> & {
19
+ oauth?: ExternalMcpOAuthTokenResolverPort;
20
+ } & HostedMcpStorePorts;
21
+ workspaceId: UUID;
22
+ }, _optional?: Record<string, never>): Promise<{
23
+ configs: ExternalMcpServerConfig[];
24
+ failures: ExternalMcpConfigFailure[];
25
+ }>;
26
+ /**
27
+ * Maps stored configs onto the shape `../bootstrap.ts` consumes.
28
+ *
29
+ * Timeouts and caps come from core's shared `FEDERATED_CONNECTION_DEFAULTS` rather than being
30
+ * stored per server: they are policy about how much a third party may cost this process, which is
31
+ * the host's call and not an operator preference. `allowedToolNames` is the one field that IS the
32
+ * operator's, and it is passed through untouched for `trust.ts` to enforce.
33
+ *
34
+ * @param readOnlyRemoteNamesByServer - Reviewed manifest lists matched by the roster source;
35
+ * never inferred from remote annotations or the tool admission allowlist.
36
+ * @complexity O(n) time and output space in the config count.
37
+ */
38
+ export declare function toResolvedFederatedConnections({ configs }: {
39
+ configs: readonly ExternalMcpServerConfig[];
40
+ }, { readOnlyRemoteNamesByServer }?: {
41
+ readOnlyRemoteNamesByServer?: ReadonlyMap<string, ReadonlySet<string>>;
42
+ }): ResolvedFederatedConnection[];
43
+ //# sourceMappingURL=store-config.d.ts.map