@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
@@ -1,7 +1,3 @@
1
- import { ExternalMcpValidationError } from "./validation-error.js";
2
- import { externalMcpAdmissionRevision, readExternalMcpToolGrants, validateExternalMcpToolNames, parseExternalMcpJsonArray } from "./access.js";
3
- import { ToolInputError } from "@jini-ai/core";
4
- import { resolveExternalMcpOAuthStatus } from "./auth.js";
5
1
  /**
6
2
  * @file The operator-editable roster of external MCP servers — what the host's connection settings write,
7
3
  * and what the agent daemon reads at boot to decide which third-party servers to federate.
@@ -40,49 +36,17 @@ import { resolveExternalMcpOAuthStatus } from "./auth.js";
40
36
  * server may also require OAuth — the host obtains the token and hands it to the child process in its
41
37
  * environment. Both combinations are real, so neither field can be derived from the other.
42
38
  */
43
- import { SUPPORTED_EXTERNAL_MCP_TRANSPORTS, EXTERNAL_MCP_OAUTH_GRANTS } from "./vocabulary.js";
39
+ import { ExternalMcpValidationError } from "./validation-error.js";
40
+ import { assertExternalMcpPlainInput, commitExternalMcpSave } from "./store.save.js";
41
+ import { assertWriteAllowlistSubset, parseAllowedToolNames, parseWriteAllowedToolNames, resolveWriteGrantAttribution, validateExternalMcpToolNames } from "./access.js";
42
+ import { ToolInputError } from "@jini-ai/core";
44
43
  import { nowIso } from "@jini-ai/core/primitives";
45
- import { FEDERATED_CONNECTION_DEFAULTS } from "../config.js";
46
- import { assertValidConnectionId } from "../trust.js";
47
- import { EXTERNAL_MCP_AUTH_MODES, externalMcpRecordHasStaticAccessToken, resolveExternalMcpAuthMode } from "./auth.js";
48
- /** `EXTERNAL_MCP_AUTH_MODES`/`ExternalMcpAuthMode` (how a server's credentials are obtained) and
49
- * their two readers live in the shared `auth.ts` leaf, so every
50
- * consumer reads the same mode vocabulary. */
51
- import { ExternalMcpSecretStoreUnconfiguredError } from "./unconfigured-error.js";
52
- /** One stored row. `sealedEnv` is null when the server needs no credentials, which is normal. */
53
- /** Compatibility DTO version for normalized vault envelopes; historical formats live in recovery. */
54
- export const EXTERNAL_MCP_VAULT_VERSION = 1;
55
- import { openExternalMcpVaultPayload, sealExternalMcpVaultPayload } from "./vault.js";
44
+ import { EXTERNAL_MCP_AUTH_MODES, resolveExternalMcpAuthMode } from "./auth.js";
45
+ import { assertSupportedExternalMcpTransport, assertValidExternalMcpServerId, parseArgs, resolveTransportTarget } from "./store-input.js";
46
+ import { resolveOAuthFields } from "./store-oauth-fields.js";
47
+ import { resolveExternalMcpSealedEnv, resolveSavedCredentialColumns } from "./store-credentials.js";
48
+ import { toView } from "./store-view.js";
56
49
  const MAX_SERVERS_PER_WORKSPACE = 32;
57
- const MAX_ENV_VARS = 64;
58
- const MAX_ARGS = 64;
59
- /** POSIX-ish environment variable name. Deliberately stricter than what a shell tolerates: a name
60
- * outside this set is far more likely a mis-pasted line than an intentional variable. */
61
- const ENV_NAME_PATTERN = /^[A-Za-z_]\w*$/;
62
- /** Generous — a provider asking for more distinct scopes than this is misconfigured, not ambitious. */
63
- const MAX_OAUTH_SCOPES = 64;
64
- /** Bounds the single-line OAuth identity fields (client id, secret). A real one is far shorter; the
65
- * cap exists so a pasted file cannot become a database row. */
66
- const MAX_OAUTH_FIELD_LENGTH = 1024;
67
- /** Matches the OAuth provider identifier rule. Restated rather than imported for the reason this
68
- * file's header gives: the row shape must not depend on the flow module. */
69
- const OAUTH_PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
70
- /** Parses a stored JSON object column, tolerating a null/absent/corrupt value as `{}` — the same
71
- * posture {@link parseJsonArray} takes, and for the same reason: one unreadable column must not
72
- * make a whole row unreadable. */
73
- function parseJsonObject(raw) {
74
- if (!raw)
75
- return {};
76
- try {
77
- const parsed = JSON.parse(raw);
78
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
79
- return {};
80
- return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
81
- }
82
- catch {
83
- return {};
84
- }
85
- }
86
50
  /** Validate exact approved access, then conditionally replace only the access columns.
87
51
  * @throws ExternalMcpValidationError for invalid names/subsets; ToolInputError if the source changed.
88
52
  * @complexity O(a+w) in at most 64 tool names per list, one conditional repository operation.
@@ -97,645 +61,6 @@ export async function applyExternalMcpAccess({ repo, clock, workspaceId, serverI
97
61
  if (!applied)
98
62
  throw new ToolInputError({ message: `The '${serverId}' connection or its access changed while awaiting approval. Nothing was changed by this approval. Request its access change again to review the current proposal.` });
99
63
  }
100
- /**
101
- * Parses an operator's `KEY=VALUE`-per-line environment block into a map.
102
- *
103
- * Blank lines and `#` comments are skipped so an operator can annotate the block. Everything else
104
- * must parse: a line without `=` is rejected rather than ignored, because silently dropping what
105
- * looks like a credential is how a server ends up launching without the token the operator believes
106
- * they supplied. Only the FIRST `=` splits, so values may contain `=` (base64 padding, connection
107
- * strings).
108
- *
109
- * @param text - Raw textarea content.
110
- * @returns The parsed variables, in first-seen order.
111
- * @throws {ExternalMcpValidationError} On a malformed line, an invalid name, a duplicate, or more
112
- * than {@link MAX_ENV_VARS} variables.
113
- * @complexity O(n) in the number of lines.
114
- * @overallScore 100
115
- */
116
- /** One line of {@link parseEnvBlock}'s input, parsed and name-validated but not yet checked against
117
- * the running `env` map (dedup/cap are the loop's own job, since they need cross-line state). Split
118
- * out purely to keep `parseEnvBlock`'s cognitive complexity under the shop ceiling — `null` means
119
- * "skip this line" (blank or `#` comment), matching the original inline `continue`. */
120
- function parseEnvLine(rawLine, index) {
121
- const line = rawLine;
122
- if (line.trim() === "" || line.trimStart().startsWith("#"))
123
- return null;
124
- const separator = line.indexOf("=");
125
- // Validation reaches the model through the human form; never echo the credential block.
126
- if (separator <= 0) {
127
- throw new ExternalMcpValidationError(`line ${index + 1} of the environment block is not \`NAME=VALUE\` — correct it in the connection form`, "env");
128
- }
129
- const name = line.slice(0, separator).trim();
130
- if (!ENV_NAME_PATTERN.test(name)) {
131
- throw new ExternalMcpValidationError(`line ${index + 1} of the environment block has an invalid variable name (letters, digits and underscore, not starting with a digit)`, "env");
132
- }
133
- return { name, value: line.slice(separator + 1).trim() };
134
- }
135
- /** @agent-note `ports` are the host-bound credential rules (length cap, messages, secret-in-plain-field check). */
136
- export function parseEnvBlock(text, ports) {
137
- // JSON is the lossless representation for multiline values; NAME=VALUE remains compatible.
138
- if (text.trimStart().startsWith('{')) {
139
- return parseJsonEnvBlock({ text, ports });
140
- }
141
- const env = {};
142
- const lines = text.split(/\r?\n/);
143
- for (const [index, rawLine] of lines.entries()) {
144
- const parsed = parseEnvLine(rawLine, index);
145
- if (!parsed)
146
- continue;
147
- // Rejected rather than last-write-wins: two lines setting the same variable means the operator
148
- // believes both are in effect, and picking one silently is the failure mode this guards.
149
- if (Object.hasOwn(env, parsed.name)) {
150
- throw new ExternalMcpValidationError(`environment variable '${parsed.name}' is set more than once`, "env");
151
- }
152
- if (Object.keys(env).length >= MAX_ENV_VARS) {
153
- throw new ExternalMcpValidationError(`at most ${MAX_ENV_VARS} environment variables are supported`, "env");
154
- }
155
- if (parsed.value.length > ports.credential.limit)
156
- throw new ExternalMcpValidationError("The token exceeds the 8192-character limit. Copy only the token.", "env");
157
- assertExternalMcpPlainField({ value: parsed.name, field: "env" }, ports);
158
- env[parsed.name] = parsed.value;
159
- }
160
- return env;
161
- }
162
- function assertJsonEnvEntry({ name, value, ports }, _options = {}) {
163
- if (!ENV_NAME_PATTERN.test(name) || typeof value !== 'string' || value.includes('\0'))
164
- throw new ExternalMcpValidationError(ports.credential.messages.env, 'env');
165
- assertExternalMcpPlainField({ value: name, field: 'env' }, ports);
166
- if (value.length > ports.credential.limit)
167
- throw new ExternalMcpValidationError('The token exceeds the 8192-character limit. Copy only the token.', 'env');
168
- }
169
- function parseJsonEnvBlock({ text, ports }, _options = {}) {
170
- let parsed;
171
- try {
172
- parsed = JSON.parse(text);
173
- }
174
- catch {
175
- throw new ExternalMcpValidationError(ports.credential.messages.env, 'env');
176
- }
177
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
178
- throw new ExternalMcpValidationError(ports.credential.messages.env, 'env');
179
- const entries = Object.entries(parsed);
180
- if (entries.length > MAX_ENV_VARS)
181
- throw new ExternalMcpValidationError(`at most ${MAX_ENV_VARS} environment variables are supported`, 'env');
182
- for (const [name, value] of entries)
183
- assertJsonEnvEntry({ name, value, ports });
184
- return Object.fromEntries(entries);
185
- }
186
- /**
187
- * Splits an operator's space-separated argv string.
188
- *
189
- * One quoting rule, and only one: a token that STARTS with `"` runs to the next `"`, which must end
190
- * the token (whitespace or end of string after it), and both quotes are dropped. That is what lets a
191
- * path with a space in it — `"C:\\Users\\John Smith\\..."`, the desktop shell's win32
192
- * registration — arrive as one argument. There are no escapes (a backslash is always literal, since
193
- * Windows paths are full of them), and a `"` anywhere else in a token stays literal exactly as it did
194
- * before this rule existed, so `--name="x"` still reaches the child unchanged. This is NOT shell
195
- * quoting: the command is spawned WITHOUT a shell (`adapter.stdio.ts` uses `spawn` with an argv
196
- * array), and nothing else a shell would do happens here.
197
- *
198
- * @throws {ExternalMcpValidationError} On an unterminated quoted token, a closing quote followed by
199
- * more characters, or more than `MAX_ARGS` arguments.
200
- * @complexity O(n) in the string length.
201
- */
202
- export function parseArgs(raw) {
203
- const args = [];
204
- let index = 0;
205
- while (index < raw.length) {
206
- if (/\s/.test(raw[index])) {
207
- index += 1;
208
- continue;
209
- }
210
- const token = raw[index] === '"' ? readQuotedArg(raw, index) : readBareArg(raw, index);
211
- args.push(token.value);
212
- index = token.end;
213
- }
214
- if (args.length > MAX_ARGS) {
215
- throw new ExternalMcpValidationError(`at most ${MAX_ARGS} arguments are supported`, "args");
216
- }
217
- return args;
218
- }
219
- /** {@link parseArgs}'s unquoted token: everything up to the next whitespace, quotes included. */
220
- function readBareArg(raw, start) {
221
- const match = /\s/.exec(raw.slice(start));
222
- const end = match === null ? raw.length : start + match.index;
223
- return { value: raw.slice(start, end), end };
224
- }
225
- /** {@link parseArgs}'s quoted token, `start` pointing at its opening `"`.
226
- * @throws {ExternalMcpValidationError} When the quote never closes, or does not end the token. */
227
- function readQuotedArg(raw, start) {
228
- const close = raw.indexOf('"', start + 1);
229
- if (close === -1) {
230
- throw new ExternalMcpValidationError("an argument opens a double quote that never closes", "args");
231
- }
232
- const end = close + 1;
233
- if (end < raw.length && !/\s/.test(raw[end])) {
234
- throw new ExternalMcpValidationError("a closing double quote must be followed by a space or the end of the arguments", "args");
235
- }
236
- return { value: raw.slice(start + 1, close), end };
237
- }
238
- /**
239
- * Splits an operator's comma-separated list of remote tool names, shared by {@link
240
- * parseAllowedToolNames} and {@link parseWriteAllowedToolNames} — the two lists use the identical
241
- * charset, cap and dedup rule, and differ only in which field a rejection names.
242
- *
243
- * An empty result is a legitimate, meaningful value on either list — it yields a server that
244
- * contributes (or write-authorizes) zero tools — so it is returned rather than rejected. That is the
245
- * safe direction and matches `trust.ts` R2's default-deny posture.
246
- *
247
- * @throws {ExternalMcpValidationError} On a name the trust tier would refuse anyway, so the operator
248
- * learns at save time instead of discovering an unexplained absence after a restart.
249
- * @complexity O(n) in the number of names.
250
- */
251
- function parseToolNameList(raw, field) {
252
- const names = raw
253
- .split(",")
254
- .map((part) => part.trim())
255
- .filter((part) => part.length > 0);
256
- return validateExternalMcpToolNames({ names, field });
257
- }
258
- /**
259
- * Splits an operator's comma-separated allowlist of remote tool names.
260
- *
261
- * @throws {ExternalMcpValidationError} See {@link parseToolNameList}. `field` is `"allowedToolNames"`.
262
- * @complexity O(n) in the number of names.
263
- * @overallScore 100
264
- */
265
- export function parseAllowedToolNames(raw) {
266
- return parseToolNameList(raw, "allowedToolNames");
267
- }
268
- /**
269
- * Splits an operator's comma-separated list of remote tool names separately authorized to write —
270
- * `trust.ts` R3's override, checked only after {@link parseAllowedToolNames}'s allowlist passes (see
271
- * {@link assertWriteAllowlistSubset}).
272
- *
273
- * @throws {ExternalMcpValidationError} See {@link parseToolNameList}. `field` is
274
- * `"writeAllowedToolNames"`.
275
- * @complexity O(n) in the number of names.
276
- * @overallScore 100
277
- */
278
- export function parseWriteAllowedToolNames(raw) {
279
- return parseToolNameList(raw, "writeAllowedToolNames");
280
- }
281
- /**
282
- * A tool may be write-authorized only if it is ALSO allowlisted. Enforced at save time so an
283
- * operator learns of the mistake immediately rather than the entry sitting inert (or, worse, being
284
- * misread as intentional) until a boot-time report surfaces it.
285
- *
286
- * @throws {ExternalMcpValidationError} Naming the first write-authorized tool absent from the
287
- * allowlist, with `field === "writeAllowedToolNames"`.
288
- * @complexity O(n) in the number of write-authorized names.
289
- */
290
- function assertWriteAllowlistSubset(writeAllowedToolNames, allowedToolNames) {
291
- const allowed = new Set(allowedToolNames);
292
- for (const name of writeAllowedToolNames) {
293
- if (!allowed.has(name)) {
294
- 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");
295
- }
296
- }
297
- }
298
- /** Whether two tool-name lists name the same SET of tools, ignoring order — the write list is a set
299
- * of operator decisions, not an ordered sequence, so a save that re-sends the same names in a
300
- * different order must not read as a change. Used only to decide whether {@link
301
- * resolveWriteGrantAttribution} owes a new attribution.
302
- * @complexity O(n) in the longer list. */
303
- function toolNameSetsEqual(a, b) {
304
- if (a.length !== b.length)
305
- return false;
306
- const setB = new Set(b);
307
- return a.every((name) => setB.has(name));
308
- }
309
- /**
310
- * Whether this row holds an access TOKEN — answered from PLAINTEXT columns alone, never by unsealing.
311
- *
312
- * Token clearing preserves the client secret sharing the sealed blob (setOAuthStatus). A
313
- * disconnected row can therefore have a non-null blob containing a secret but no access token;
314
- * blob presence alone cannot answer this question.
315
- *
316
- * Not repaired by unsealing, deliberately. This is read by a plain list route that must answer
317
- * without a keyring round trip, and must keep answering TRUTHFULLY for a row whose blob will not
318
- * open at all: a rotated site key, or a legacy `aad_version 0` ciphertext. A decrypt here would turn
319
- * either into a failed settings tab, and would put a keyring dependency on a read path that has
320
- * never had one.
321
- *
322
- * The blob check leads because it is the NECESSARY condition — no blob, no token, whatever the
323
- * plaintext says. Each of the two disjuncts after it is independently SUFFICIENT, which is what
324
- * makes a false positive unreachable:
325
- *
326
- * - `connected` is written by exactly one place, `persistTokens`, and that same upsert writes the
327
- * tokens. Every path that clears a token moves the row off `connected` in the same write.
328
- * - `oauthExpiresAt` is written beside the tokens by that same `persistTokens`, and nulled by every
329
- * clear (`setOAuthStatus`'s `clearToken` branch) and by every save that invalidates the token
330
- * ({@link carryOAuthRuntimeState}), so a non-null expiry cannot outlive the token it describes.
331
- *
332
- * @returns `true` only when a token is stored. The single state it can UNDER-report is a token
333
- * issued with no `expires_in` — RFC 6749 §5.1 makes it optional and the OAuth token endpoint stores `null` rather than fabricating one — on a row that has since moved off `connected`
334
- * without its token being cleared: a re-connect left `pending`, or a terminal device-poll failure.
335
- * Under-reporting is the safe direction, and closing it exactly needs a plaintext token-presence
336
- * column, which is a schema change rather than a read fix.
337
- * @complexity O(1) — three field reads, no I/O.
338
- */
339
- export function externalMcpRecordHasStoredToken(record) {
340
- if (record.sealedOAuth === null)
341
- return false;
342
- return resolveExternalMcpOAuthStatus(record) === "connected" || record.oauthExpiresAt !== null;
343
- }
344
- async function externalMcpEnvHints({ record, sealer, ports }, _options = {}) {
345
- const envTokenHints = {};
346
- if (!sealer || !record.sealedEnv)
347
- return envTokenHints;
348
- const opened = await openExternalMcpEnv(record, { ...ports, sealer });
349
- if (!opened.ok)
350
- return envTokenHints;
351
- for (const [name, value] of Object.entries(opened.env)) {
352
- if (typeof value === 'string')
353
- envTokenHints[name] = ports.credential.hint({ token: value });
354
- }
355
- return envTokenHints;
356
- }
357
- async function externalMcpAccessTokenHint({ record, sealer, ports }, _options = {}) {
358
- let accessTokenHint = null;
359
- if (sealer && record.sealedOAuth) {
360
- try {
361
- const payload = await openExternalMcpOAuthPayload({ ...ports, sealer }, record);
362
- const token = payload.staticAccessToken ?? payload.tokens?.accessToken;
363
- if (token)
364
- accessTokenHint = ports.credential.hint({ token });
365
- }
366
- catch { /* A rotated site key must not prevent listing non-secret metadata. */ }
367
- }
368
- return accessTokenHint;
369
- }
370
- async function toView(record, ports, sealer) {
371
- const envTokenHints = await externalMcpEnvHints({ record, sealer, ports });
372
- const accessTokenHint = await externalMcpAccessTokenHint({ record, sealer, ports });
373
- return {
374
- serverId: record.serverId,
375
- label: record.label ?? record.serverId,
376
- provisionedByPluginId: record.provisionedByPluginId,
377
- transport: record.transport,
378
- authMode: resolveExternalMcpAuthMode(record),
379
- enabled: record.enabled,
380
- command: record.command ?? "",
381
- url: record.url,
382
- args: parseExternalMcpJsonArray({ raw: record.args }),
383
- allowedToolNames: parseExternalMcpJsonArray({ raw: record.allowedToolNames }),
384
- writeAllowedToolNames: parseExternalMcpJsonArray({ raw: record.writeAllowedToolNames }),
385
- writeGrantsUpdatedByPrincipalId: record.writeGrantsUpdatedByPrincipalId,
386
- writeGrantsUpdatedAt: record.writeGrantsUpdatedAt,
387
- envNames: parseExternalMcpJsonArray({ raw: record.envNames }),
388
- hasAccessToken: externalMcpRecordHasStaticAccessToken(record),
389
- accessTokenHint,
390
- ...(Object.keys(envTokenHints).length ? { envTokenHints } : {}),
391
- accessTokenEnvName: resolveExternalMcpAuthMode(record) === "static_env" ? record.oauthTokenEnvName : null,
392
- oauth: {
393
- providerId: record.oauthProviderId,
394
- grant: record.oauthGrant,
395
- clientId: record.oauthClientId,
396
- scopes: parseExternalMcpJsonArray({ raw: record.oauthScopesJson }),
397
- status: resolveExternalMcpOAuthStatus(record),
398
- expiresAt: record.oauthExpiresAt,
399
- tokenEnvName: record.oauthTokenEnvName,
400
- hasStoredToken: externalMcpRecordHasStoredToken(record),
401
- },
402
- };
403
- }
404
- /**
405
- * Lists the workspace's servers for the admin tab. The tab has no use for env
406
- * values and must not be a route that decrypts them. Token hints alone are now derived by
407
- * server-side unsealing, per the owner decision; no secret value is returned.
408
- *
409
- * @complexity O(n) in the stored server count.
410
- * @overallScore 100
411
- */
412
- export async function listExternalMcpServerViews(deps, workspaceId) {
413
- const records = await deps.repo.listByWorkspaceId(workspaceId);
414
- return Promise.all(records.map(record => toView(record, deps, deps.sealer)));
415
- }
416
- /**
417
- * Reads and decrypts every ENABLED server, for the daemon's boot-time federation pass.
418
- *
419
- * A row whose sealed env cannot be opened is SKIPPED rather than thrown on, and the reason is
420
- * returned in `failures`. This mirrors `bootstrap.ts`'s fail-open posture for the same reason: a
421
- * rotated site key or a corrupt row must not stop the daemon booting, and one unusable server must
422
- * not take out a second working one. Disabled rows never reach the sealer at all.
423
- *
424
- * @returns The usable configs plus a per-server accounting of what could not be read.
425
- * @complexity O(n) in the enabled server count, one unseal each.
426
- * @overallScore 100
427
- */
428
- /** Opens `record`'s sealed env block, or returns `{}` when there is none to open. Split out of
429
- * {@link resolveExternalMcpConfig} purely to keep that function's complexity under the shop
430
- * ceiling — a decrypt failure is reported through the same ok/reason shape the caller already
431
- * threads through, not thrown, since one unreadable server must not abort the whole read. */
432
- async function openExternalMcpEnv(record, deps) {
433
- if (record.sealedEnv === null)
434
- return { ok: true, env: {} };
435
- try {
436
- const env = await openExternalMcpVaultPayload({ sealer: deps.sealer, sealed: record.sealedEnv, identity: record, kind: "mcp-env", ports: deps });
437
- return { ok: true, env };
438
- }
439
- catch {
440
- // These reasons reach admissions and chat tools. Parser/sealer errors can contain secret plaintext.
441
- return { ok: false, reason: `stored credentials could not be decrypted — check the site credential store and re-enter them in ${deps.settingsLink}` };
442
- }
443
- }
444
- /**
445
- * A `needs_reauth`/`disconnected`/`pending` row is reported rather than connected.
446
- *
447
- * Reported, not silently skipped: an operator whose token expired needs to see WHY the server's
448
- * tools vanished, and the reason string is the only thing carrying that at boot. The admin tab's
449
- * `needs_reauth` badge is the out-of-band half of the same signal.
450
- */
451
- function oauthStatusFailure(record, settingsLink) {
452
- const status = resolveExternalMcpOAuthStatus(record);
453
- if (status === "connected")
454
- return null;
455
- if (status === "needs_reauth") {
456
- return `its authorization expired or was revoked — reconnect it in ${settingsLink}`;
457
- }
458
- return `it has not been authorized yet (status '${status}') — connect it in ${settingsLink}`;
459
- }
460
- /**
461
- * Obtains one record's OAuth access token, or explains why it cannot be.
462
- *
463
- * Returns the raw token rather than a placement, because WHERE it goes is the transport's business:
464
- * a child-process variable for `stdio`, an `Authorization` header for a hosted endpoint. Splitting
465
- * "can we get a token" from "where does it go" is what stops the second question's answer from
466
- * being duplicated per transport.
467
- *
468
- * @complexity O(1) plus at most one token refresh round trip.
469
- */
470
- async function resolveExternalMcpAccessToken(record, oauth, { settingsLink, reauthRequiredCode }) {
471
- try {
472
- const shared = await oauth?.resolveSharedAccessToken?.({ serverId: record.serverId });
473
- if (shared !== undefined)
474
- return { ok: true, token: shared, shared: true };
475
- }
476
- catch {
477
- return { ok: false, reason: `This shared connection is no longer granted to this site. Choose it again or sign in from ${settingsLink}.` };
478
- }
479
- const statusFailure = oauthStatusFailure(record, settingsLink);
480
- if (statusFailure !== null)
481
- return { ok: false, reason: statusFailure };
482
- if (!oauth) {
483
- return { ok: false, reason: "this process was not wired with an OAuth token resolver, so its access token cannot be obtained" };
484
- }
485
- return resolveOwnedAccessToken(record, oauth, { settingsLink, reauthRequiredCode });
486
- }
487
- /** {@link resolveExternalMcpAccessToken}'s last step, split out unchanged to keep each function under the complexity limit. */
488
- async function resolveOwnedAccessToken(record, oauth, { settingsLink, reauthRequiredCode }) {
489
- try {
490
- return { ok: true, token: await oauth.resolveAccessToken({ serverId: record.serverId }) };
491
- }
492
- catch (err) {
493
- // Preserve reauthorization as a typed outcome, without echoing raw provider error messages.
494
- const needsReauth = err instanceof Error && "code" in err && err.code === reauthRequiredCode;
495
- return { ok: false, reason: needsReauth
496
- ? `its authorization expired or was revoked — reconnect it in ${settingsLink}`
497
- : `its OAuth access token could not be obtained: OAuth token resolution failed — reconnect this server in ${settingsLink}` };
498
- }
499
- }
500
- /** A failure entry for one record, in the shape {@link readEnabledExternalMcpConfigs} collects. */
501
- function externalMcpFailure(record, reason) {
502
- return { ok: false, failure: { serverId: record.serverId, reason } };
503
- }
504
- /**
505
- * Builds a `stdio` row's target: its pasted environment, plus the access token under the operator's
506
- * chosen variable name when the row is OAuth-authenticated.
507
- *
508
- * The two credential sources compose rather than exclude: a server can need a pasted `BASE_URL` AND
509
- * an OAuth bearer token. The OAuth-derived variable is applied LAST so it cannot be shadowed by a
510
- * stale hand-typed copy of the same name in the pasted block.
511
- */
512
- async function resolveStdioTarget(record, env, authMode, oauth, staticAccessToken, ports) {
513
- if (!record.command)
514
- return externalMcpFailure(record, "no command is configured to launch it");
515
- const withStaticToken = withStaticAccessToken(record, env, authMode, staticAccessToken);
516
- if (withStaticToken === null) {
517
- return externalMcpFailure(record, "no environment variable name is configured to receive its access token");
518
- }
519
- let resolvedEnv = withStaticToken;
520
- if (authMode === "oauth") {
521
- if (!record.oauthTokenEnvName) {
522
- return externalMcpFailure(record, "no environment variable name is configured to receive its OAuth access token");
523
- }
524
- const token = await resolveExternalMcpAccessToken(record, oauth, ports);
525
- if (!token.ok)
526
- return externalMcpFailure(record, token.reason);
527
- resolvedEnv = { ...resolvedEnv, [record.oauthTokenEnvName]: token.token };
528
- }
529
- return { ok: true, target: { kind: "stdio", command: record.command, args: parseExternalMcpJsonArray({ raw: record.args }), env: resolvedEnv } };
530
- }
531
- /**
532
- * Builds a hosted row's target: its endpoint, plus the bearer header when the row is
533
- * OAuth-authenticated.
534
- *
535
- * A hosted row's pasted `env` block is deliberately NOT turned into headers. An operator typing
536
- * `FOO=bar` means an environment variable, and silently promoting it to a request header would send
537
- * a value they scoped to a local process to a third party over the network. A hosted server's static
538
- * credential is the dedicated `static_env` access token instead: typed for THIS endpoint, and sent as
539
- * `Authorization: Bearer`.
540
- */
541
- async function resolveHttpTarget(record, authMode, oauth, staticAccessToken, ports) {
542
- if (!record.url)
543
- return externalMcpFailure(record, "no URL is configured to reach it");
544
- const headers = {};
545
- let shared = false;
546
- if (authMode === "static_env" && staticAccessToken !== null)
547
- headers.authorization = `Bearer ${staticAccessToken}`;
548
- if (authMode === "oauth") {
549
- const token = await resolveExternalMcpAccessToken(record, oauth, ports);
550
- if (!token.ok)
551
- return externalMcpFailure(record, token.reason);
552
- headers.authorization = `Bearer ${token.token}`;
553
- shared = token.shared === true;
554
- }
555
- if (headers.authorization !== undefined) {
556
- const failure = hostedTokenFailure({ authorization: headers.authorization, credential: ports.credential });
557
- if (failure !== null)
558
- return externalMcpFailure(record, failure);
559
- }
560
- return { ok: true, target: { kind: "streamable_http", url: record.url, headers,
561
- ...(shared ? { bearerToken: async () => {
562
- const token = await oauth.resolveSharedAccessToken({ serverId: record.serverId });
563
- if (token === undefined)
564
- throw new Error(`This shared connection was removed from this site. Choose a saved connection again in ${ports.settingsLink}.`);
565
- return token;
566
- } } : {}),
567
- } };
568
- }
569
- function hostedTokenFailure({ authorization, credential }, _options = {}) {
570
- try {
571
- credential.assert({ value: authorization.slice('Bearer '.length), hosted: true });
572
- }
573
- catch (err) {
574
- return err instanceof credential.InputError ? err.message : credential.messages.ascii;
575
- }
576
- return null;
577
- }
578
- /**
579
- * `env` with a `static_env` row's access token applied under its variable name — LAST, as the OAuth
580
- * token is in {@link resolveStdioTarget}, so a stale pasted copy of the same variable cannot shadow it.
581
- *
582
- * @returns `env` unchanged when the row holds no static token; `null` when it holds one but names no
583
- * variable to put it in (the save path refuses that, so reaching it means another writer).
584
- * @complexity O(n) in the env variable count.
585
- */
586
- function withStaticAccessToken(record, env, authMode, staticAccessToken) {
587
- if (authMode !== "static_env" || staticAccessToken === null)
588
- return env;
589
- if (!record.oauthTokenEnvName)
590
- return null;
591
- return { ...env, [record.oauthTokenEnvName]: staticAccessToken };
592
- }
593
- /**
594
- * Opens a `static_env` row's sealed access token, or resolves `null` when it holds none — without
595
- * touching the sealer for any other row. A blob that will not open is a per-row failure, the same
596
- * posture {@link openExternalMcpEnv} takes for the env block.
597
- *
598
- * @complexity O(1) — at most one unseal.
599
- */
600
- async function openExternalMcpStaticAccessToken(record, deps) {
601
- if (!externalMcpRecordHasStaticAccessToken(record))
602
- return { ok: true, token: null };
603
- try {
604
- const payload = await openExternalMcpOAuthPayload(deps, record);
605
- return { ok: true, token: payload.staticAccessToken ?? null };
606
- }
607
- catch {
608
- // Never put decrypted payloads or cryptographic exception text into an operator/model response.
609
- return { ok: false, reason: `its stored access token could not be decrypted — re-enter it in ${deps.settingsLink}` };
610
- }
611
- }
612
- /** Resolves one ENABLED record into either a usable config or a failure entry, for
613
- * {@link readEnabledExternalMcpConfigs}'s loop. */
614
- async function resolveExternalMcpConfig(record, deps, oauth) {
615
- const transport = record.transport;
616
- if (!SUPPORTED_EXTERNAL_MCP_TRANSPORTS.includes(transport)) {
617
- return externalMcpFailure(record, `unsupported transport '${record.transport}'`);
618
- }
619
- const opened = await openExternalMcpEnv(record, deps);
620
- if (!opened.ok)
621
- return externalMcpFailure(record, opened.reason);
622
- const authMode = resolveExternalMcpAuthMode(record);
623
- const staticToken = await openExternalMcpStaticAccessToken(record, deps);
624
- if (!staticToken.ok)
625
- return externalMcpFailure(record, staticToken.reason);
626
- const resolved = transport === "stdio"
627
- ? await resolveStdioTarget(record, opened.env, authMode, oauth, staticToken.token, deps)
628
- : await resolveHttpTarget(record, authMode, oauth, staticToken.token, deps);
629
- if (!resolved.ok)
630
- return resolved;
631
- const grants = readExternalMcpToolGrants(record);
632
- return {
633
- ok: true,
634
- config: {
635
- serverId: record.serverId,
636
- ...(record.provisionedByPluginId ? { provisionedByPluginId: record.provisionedByPluginId } : {}),
637
- label: record.label ?? record.serverId,
638
- transport,
639
- authMode,
640
- enabled: true,
641
- allowedToolNames: grants.allowedToolNames,
642
- writeAllowedToolNames: grants.writeAllowedToolNames,
643
- target: resolved.target,
644
- admissionRevision: externalMcpAdmissionRevision(record),
645
- },
646
- };
647
- }
648
- export async function readEnabledExternalMcpConfigs(deps, workspaceId) {
649
- const records = await deps.repo.listByWorkspaceId(workspaceId);
650
- const configs = [];
651
- const failures = [];
652
- for (const record of records) {
653
- if (!record.enabled)
654
- continue;
655
- const resolved = await resolveExternalMcpConfig(record, deps, deps.oauth);
656
- if (resolved.ok)
657
- configs.push(resolved.config);
658
- else
659
- failures.push(resolved.failure);
660
- }
661
- return { configs, failures };
662
- }
663
- /**
664
- * Maps stored configs onto the shape `../bootstrap.ts` consumes.
665
- *
666
- * Timeouts and caps come from core's shared `FEDERATED_CONNECTION_DEFAULTS` rather than being
667
- * stored per server: they are policy about how much a third party may cost this process, which is
668
- * the host's call and not an operator preference. `allowedToolNames` is the one field that IS the
669
- * operator's, and it is passed through untouched for `trust.ts` to enforce.
670
- *
671
- * @param readOnlyRemoteNamesByServer - Reviewed manifest lists matched by the roster source;
672
- * never inferred from remote annotations or the tool admission allowlist.
673
- * @complexity O(n) time and output space in the config count.
674
- */
675
- export function toResolvedFederatedConnections(configs, readOnlyRemoteNamesByServer = new Map()) {
676
- return configs.map((config) => ({
677
- ...(config.target.kind === "streamable_http" && config.target.bearerToken ? { bearerToken: config.target.bearerToken } : {}),
678
- config: {
679
- connectionId: config.serverId,
680
- ...(config.provisionedByPluginId ? { provisionedByPluginId: config.provisionedByPluginId } : {}),
681
- label: config.label,
682
- allowedToolNames: config.allowedToolNames,
683
- writeAllowedToolNames: config.writeAllowedToolNames,
684
- ...(readOnlyRemoteNamesByServer.has(config.serverId) ? { readOnlyRemoteNames: readOnlyRemoteNamesByServer.get(config.serverId) } : {}),
685
- connectTimeoutMs: FEDERATED_CONNECTION_DEFAULTS.connectTimeoutMs,
686
- callTimeoutMs: FEDERATED_CONNECTION_DEFAULTS.callTimeoutMs,
687
- maxResultBytes: FEDERATED_CONNECTION_DEFAULTS.maxResultBytes,
688
- maxTools: FEDERATED_CONNECTION_DEFAULTS.maxTools,
689
- origin: { kind: "roster", admissionRevision: config.admissionRevision },
690
- },
691
- launch: toFederatedLaunchSpec(config.target),
692
- }));
693
- }
694
- /** Maps a resolved target onto the federation layer's launch spec. The two shapes are deliberately
695
- * separate — this one is the store's, that one is federation's — so neither domain has to widen
696
- * when the other gains a field. */
697
- function toFederatedLaunchSpec(target) {
698
- if (target.kind === "streamable_http")
699
- return { url: target.url, headers: target.headers };
700
- return {
701
- command: target.command,
702
- args: target.args,
703
- // The child's environment REPLACES the daemon's rather than extending it, matching the
704
- // Supabase preset. `PATH`/`HOME`/`TMPDIR` are added by the launcher, not here; anything else
705
- // a server needs is an explicit, written-down grant in its own env block.
706
- env: target.env,
707
- };
708
- }
709
- /**
710
- * Validates and persists one server, sealing its env block.
711
- *
712
- * `env: undefined` preserves whatever is already stored, which is what lets the tab patch `enabled`
713
- * or `label` without the operator re-typing credentials the UI never sent them. `env: ""` is the
714
- * distinct, explicit "clear the credentials" instruction — the same unset-vs-empty distinction
715
- * `../config.ts` draws for allowlists, and for the same reason.
716
- *
717
- * @throws {ExternalMcpValidationError} On any invalid operator input.
718
- * @throws {ExternalMcpSecretStoreUnconfiguredError} When no site key is available to seal under.
719
- * @complexity O(n) in the size of the env block.
720
- * @overallScore 100
721
- */
722
- /** Validates `serverId` via the trust tier's own assertion, remapped onto this store's own error
723
- * type. Split out purely to keep {@link saveExternalMcpServer}'s complexity under the shop
724
- * ceiling — reuses `trust.ts`'s rule rather than restating it, since this id becomes part of every
725
- * federated tool id and two copies of that rule could drift. */
726
- function assertValidExternalMcpServerId(serverId) {
727
- try {
728
- assertValidConnectionId({ connectionId: serverId });
729
- }
730
- catch (err) {
731
- throw new ExternalMcpValidationError(err instanceof Error ? err.message : String(err), "id");
732
- }
733
- }
734
- function assertSupportedExternalMcpTransport(transport) {
735
- if (!SUPPORTED_EXTERNAL_MCP_TRANSPORTS.includes(transport)) {
736
- throw new ExternalMcpValidationError(`transport '${transport}' is not supported — only ${SUPPORTED_EXTERNAL_MCP_TRANSPORTS.join(", ")} is implemented`, "transport");
737
- }
738
- }
739
64
  /** Resolves the auth mode for one save: explicit input wins, then the existing row's mode, then
740
65
  * `static_env` for a brand-new row.
741
66
  * @throws {ExternalMcpValidationError} On a mode outside {@link EXTERNAL_MCP_AUTH_MODES}. */
@@ -747,38 +72,6 @@ function resolveSavedAuthMode(input, existing) {
747
72
  }
748
73
  return input.authMode;
749
74
  }
750
- /**
751
- * Splits an operator's comma- or space-separated OAuth scope list.
752
- *
753
- * An empty result is legitimate — several providers infer scope from the client registration — so it
754
- * is returned rather than rejected, the same call {@link parseAllowedToolNames} makes.
755
- *
756
- * @throws {ExternalMcpValidationError} Past {@link MAX_OAUTH_SCOPES}.
757
- * @complexity O(n) in the number of scopes.
758
- */
759
- export function parseOAuthScopes(raw) {
760
- const scopes = raw.split(/[\s,]+/).filter((part) => part.length > 0);
761
- if (scopes.length > MAX_OAUTH_SCOPES) {
762
- throw new ExternalMcpValidationError(`at most ${MAX_OAUTH_SCOPES} OAuth scopes are supported`, "oauth.scopes");
763
- }
764
- return [...new Set(scopes)];
765
- }
766
- /** The endpoints an operator typed for a connection that defines its own provider. Empty strings are
767
- * dropped so `{}` — "this connection names a registered provider instead" — stays representable. */
768
- function buildOAuthEndpoints(oauth) {
769
- const entries = [
770
- ["authorizationEndpoint", oauth.authorizationEndpoint],
771
- ["tokenEndpoint", oauth.tokenEndpoint],
772
- ["deviceAuthorizationEndpoint", oauth.deviceAuthorizationEndpoint],
773
- ];
774
- const endpoints = {};
775
- for (const [key, value] of entries) {
776
- const trimmed = value?.trim();
777
- if (trimmed)
778
- endpoints[key] = trimmed;
779
- }
780
- return endpoints;
781
- }
782
75
  /**
783
76
  * The identity a stored token was issued under.
784
77
  *
@@ -799,207 +92,6 @@ function oauthBindingFingerprint(record) {
799
92
  record.oauthScopesJson,
800
93
  ]);
801
94
  }
802
- /**
803
- * Validates and resolves the OAuth columns for one save.
804
- *
805
- * @throws {ExternalMcpValidationError} On any invalid operator input, with `field` naming the
806
- * offending form control (`oauth.clientId`, `oauth.grant`, ...).
807
- * @complexity O(n) in the number of scopes.
808
- */
809
- /** The OAuth columns of a row that is NOT OAuth-authenticated: all cleared.
810
- *
811
- * Cleared rather than preserved, deliberately: a row switched to `static_env` that still carried a
812
- * provider and a client id would silently re-adopt them if it were ever switched back, along with a
813
- * token issued under configuration nobody has looked at since. */
814
- const NO_OAUTH_FIELDS = {
815
- oauthProviderId: null,
816
- oauthGrant: null,
817
- oauthClientId: null,
818
- oauthEndpointsJson: null,
819
- oauthScopesJson: null,
820
- oauthTokenEnvName: null,
821
- clientSecret: "",
822
- };
823
- /**
824
- * The first non-empty trimmed candidate, or `""`.
825
- *
826
- * Every OAuth identity field follows the same precedence — what the operator just submitted, then
827
- * what the row already holds, then nothing — and writing that as a `??` chain at each field is both
828
- * repetitive and, measurably, most of these functions' branch count. One helper makes the precedence
829
- * a single named rule instead of five copies of it.
830
- *
831
- * @complexity O(n) in the number of candidates, each trimmed once.
832
- */
833
- function firstTrimmed(...candidates) {
834
- for (const candidate of candidates) {
835
- const trimmed = candidate?.trim();
836
- if (trimmed)
837
- return trimmed;
838
- }
839
- return "";
840
- }
841
- /**
842
- * Validates a sign-in method, or admits its absence on a row that can discover it for itself.
843
- *
844
- * The same exception {@link assertOAuthClientId} documents, extended to the grant: a REMOTE row can
845
- * run RFC 8414 discovery against its own URL at connect time and read the authorization server's own
846
- * `grant_types_supported` (`discovery.ts`) instead of an operator having to guess between "Browser
847
- * sign-in" and "Device code" before they know what the server even offers. See
848
- * the sign-in service's `selfConfigureConnection`, which resolves and persists a concrete grant
849
- * the first time such a row connects. A stdio row has no URL to discover from, so for those the
850
- * requirement stands unchanged.
851
- *
852
- * @returns The validated grant, or `null` when the row will resolve one at connect.
853
- * @throws {ExternalMcpValidationError} On an empty grant the row cannot leave to discovery, or one
854
- * outside {@link EXTERNAL_MCP_OAUTH_GRANTS}.
855
- * @complexity O(1).
856
- */
857
- function assertOAuthGrant(grant, selfConfigurable) {
858
- if (grant === "") {
859
- if (selfConfigurable)
860
- return null;
861
- throw new ExternalMcpValidationError("an OAuth connection needs a sign-in method", "oauth.grant");
862
- }
863
- if (!EXTERNAL_MCP_OAUTH_GRANTS.includes(grant)) {
864
- throw new ExternalMcpValidationError(`OAuth grant '${grant}' is not supported — expected one of ${EXTERNAL_MCP_OAUTH_GRANTS.join(", ")}`, "oauth.grant");
865
- }
866
- return grant;
867
- }
868
- /**
869
- * Validates a client id, or admits its absence on a row that can obtain one for itself.
870
- *
871
- * `selfConfigurable` is what makes an empty client id legitimate rather than a validation failure.
872
- * A growing share of hosted authorization servers publish an RFC 7591 `registration_endpoint` and no
873
- * developer console at all, so for those there is no human path to a client id — demanding one here
874
- * would make the connection unreachable by any amount of operator effort. A row that carries a REMOTE
875
- * URL can run discovery against it at connect time and mint one; a stdio row has nothing to discover
876
- * from, so for those the requirement stands unchanged.
877
- *
878
- * @returns The validated client id, or `null` when the row will mint one at connect.
879
- * @throws {ExternalMcpValidationError} On an empty client id the row cannot obtain, or an oversized one.
880
- * @complexity O(1).
881
- */
882
- function assertOAuthClientId(clientId, selfConfigurable) {
883
- if (clientId === "") {
884
- if (selfConfigurable)
885
- return null;
886
- throw new ExternalMcpValidationError("an OAuth connection needs a client id", "oauth.clientId");
887
- }
888
- if (clientId.length > MAX_OAUTH_FIELD_LENGTH) {
889
- throw new ExternalMcpValidationError(`the OAuth client id may be at most ${MAX_OAUTH_FIELD_LENGTH} characters`, "oauth.clientId");
890
- }
891
- return clientId;
892
- }
893
- /**
894
- * Resolves the provider half of an OAuth connection: a registered provider id, its own endpoints, or
895
- * both.
896
- *
897
- * Endpoints are re-derived whenever the operator actually TYPED into either identity field, so
898
- * clearing a provider id and typing endpoints (or the reverse) cannot leave half of the old pairing
899
- * behind. "Actually typed" is judged by content, not key presence: the admin form sends both fields
900
- * on every save (it cannot round-trip a connection's own endpoints), so treating mere presence as a
901
- * touch made an untouched save look like an identity change on every edit. The host's form must preserve that distinction.
902
- *
903
- * The dynamic-registration members (`clientAuth`, `dynamicClientId`, `registeredRedirectUri`) are
904
- * exempted from re-derivation regardless of branch: they are server-owned, written only by dynamic
905
- * client registration by the sign-in service, and no operator input can express them, so even a
906
- * save that legitimately edits the other endpoints must not drop them.
907
- *
908
- * @throws {ExternalMcpValidationError} When neither a provider id nor a token endpoint is present,
909
- * or the provider id is malformed.
910
- * @complexity O(1).
911
- */
912
- function resolveOAuthEndpoints(oauth, existing) {
913
- const stored = parseJsonObject(existing?.oauthEndpointsJson ?? null);
914
- const touchedIdentity = (oauth.providerId ?? "").trim() !== "" || (oauth.tokenEndpoint ?? "").trim() !== "";
915
- if (!touchedIdentity)
916
- return stored;
917
- const rebuilt = buildOAuthEndpoints(oauth);
918
- for (const key of DYNAMIC_REGISTRATION_ENDPOINT_KEYS) {
919
- if (stored[key] !== undefined)
920
- rebuilt[key] = stored[key];
921
- }
922
- return rebuilt;
923
- }
924
- /** The endpoints-blob members only dynamic client registration writes. */
925
- const DYNAMIC_REGISTRATION_ENDPOINT_KEYS = ["clientAuth", "dynamicClientId", "registeredRedirectUri"];
926
- /**
927
- * @param selfConfigurable - Whether this row can discover its own endpoints — see
928
- * {@link assertOAuthClientId} for the same argument applied to the client id.
929
- * @throws {ExternalMcpValidationError} When neither identity is present on a row that cannot
930
- * discover one, or the id is malformed.
931
- */
932
- function assertOAuthProviderIdentity(providerId, endpoints, selfConfigurable) {
933
- if (providerId === "" && endpoints.tokenEndpoint === undefined && !selfConfigurable) {
934
- throw new ExternalMcpValidationError("an OAuth connection needs either a registered provider id or its own token endpoint", "oauth.providerId");
935
- }
936
- if (providerId !== "" && !OAUTH_PROVIDER_ID_PATTERN.test(providerId)) {
937
- throw new ExternalMcpValidationError(`'${providerId}' is not a valid provider id (lowercase letters, digits and hyphens)`, "oauth.providerId");
938
- }
939
- }
940
- function resolveOAuthProviderIdentity(oauth, existing, selfConfigurable) {
941
- const providerId = firstTrimmed(oauth.providerId, existing?.oauthProviderId);
942
- const endpoints = resolveOAuthEndpoints(oauth, existing);
943
- assertOAuthProviderIdentity(providerId, endpoints, selfConfigurable);
944
- return {
945
- oauthProviderId: providerId === "" ? null : providerId,
946
- oauthEndpointsJson: Object.keys(endpoints).length === 0 ? null : JSON.stringify(endpoints),
947
- };
948
- }
949
- /**
950
- * Resolves which child-process environment variable receives the access token.
951
- *
952
- * `null` for every non-`stdio` transport: only `stdio` hands credentials to a child process, so only
953
- * `stdio` needs a name for one.
954
- *
955
- * @throws {ExternalMcpValidationError} When a stdio+OAuth row names none, or names an invalid one.
956
- * @complexity O(n) in the name length.
957
- */
958
- function resolveOAuthTokenEnvName(transport, oauth, existing) {
959
- if (transport !== "stdio")
960
- return null;
961
- const tokenEnvName = firstTrimmed(oauth.tokenEnvName, existing?.oauthTokenEnvName);
962
- if (tokenEnvName === "") {
963
- throw new ExternalMcpValidationError("a stdio server authenticated with OAuth needs the name of the environment variable that receives its access token", "oauth.tokenEnvName");
964
- }
965
- if (!ENV_NAME_PATTERN.test(tokenEnvName)) {
966
- throw new ExternalMcpValidationError(`'${tokenEnvName}' is not a valid environment variable name (letters, digits and underscore, not starting with a digit)`, "oauth.tokenEnvName");
967
- }
968
- return tokenEnvName;
969
- }
970
- /** Scopes for one save. Absent input KEEPS the stored list (the three-state rule `env` sets); an
971
- * empty string clears it, since {@link parseOAuthScopes} of `""` is `[]`. */
972
- function resolveSavedOAuthScopes(oauth, existing) {
973
- if (oauth.scopes === undefined)
974
- return parseExternalMcpJsonArray({ raw: existing?.oauthScopesJson ?? null });
975
- return parseOAuthScopes(oauth.scopes);
976
- }
977
- function resolveOAuthFields(authMode, transport, input, existing, credential) {
978
- if (authMode !== "oauth")
979
- return NO_OAUTH_FIELDS;
980
- const oauth = input.oauth ?? {};
981
- // Only a remote row has a URL for the sign-in service to run RFC 9728 / RFC 8414 discovery
982
- // against, so only a remote row may leave its provider identity, grant and client id to be filled
983
- // in at connect time.
984
- const selfConfigurable = transport !== "stdio";
985
- return {
986
- ...resolveOAuthProviderIdentity(oauth, existing, selfConfigurable),
987
- oauthGrant: assertOAuthGrant(firstTrimmed(oauth.grant, existing?.oauthGrant), selfConfigurable),
988
- oauthClientId: assertOAuthClientId(firstTrimmed(oauth.clientId, existing?.oauthClientId), selfConfigurable),
989
- oauthScopesJson: JSON.stringify(resolveSavedOAuthScopes(oauth, existing)),
990
- oauthTokenEnvName: resolveOAuthTokenEnvName(transport, oauth, existing),
991
- clientSecret: oauth.clientSecret === '' || oauth.clientSecret === undefined ? undefined : normalizeOAuthClientSecret({ value: oauth.clientSecret, credential }),
992
- };
993
- }
994
- /** Trims and validates `rawCommand`, returning the trimmed value. Split out purely to keep
995
- * {@link saveExternalMcpServer}'s complexity under the shop ceiling. */
996
- function assertNonEmptyExternalMcpCommand(rawCommand) {
997
- const command = rawCommand.trim();
998
- if (command === "") {
999
- throw new ExternalMcpValidationError("a stdio server needs a command to launch", "command");
1000
- }
1001
- return command;
1002
- }
1003
95
  /** Enforces {@link MAX_SERVERS_PER_WORKSPACE} for a NEW server only — an existing row is always an
1004
96
  * update, never a new slot, so it is exempt. Split out purely to keep
1005
97
  * {@link saveExternalMcpServer}'s complexity under the shop ceiling. */
@@ -1011,90 +103,6 @@ async function assertUnderExternalMcpServerCap(deps, workspaceId, existing) {
1011
103
  throw new ExternalMcpValidationError(`this workspace already has the maximum of ${MAX_SERVERS_PER_WORKSPACE} external MCP servers`, "id");
1012
104
  }
1013
105
  }
1014
- /** Resolves the sealed env block and its plaintext variable-name index for one save. `rawEnv ===
1015
- * undefined` preserves whatever `existing` already has (see {@link saveExternalMcpServer}'s doc for
1016
- * why); an empty parsed block clears the seal to `null` rather than sealing `{}`. Split out purely
1017
- * to keep {@link saveExternalMcpServer}'s complexity under the shop ceiling.
1018
- * @throws {ExternalMcpValidationError} On a malformed env block (via {@link parseEnvBlock}).
1019
- * @throws {ExternalMcpSecretStoreUnconfiguredError} When no site key is available to seal under. */
1020
- /** {@link resolveExternalMcpSealedEnv}'s `rawEnv === undefined` branch — carries the existing sealed
1021
- * env block through untouched. Split out purely to keep that function's complexity under the shop
1022
- * ceiling.
1023
- *
1024
- * Carried through untouched, so its lineage must be carried too — bumping the version here would
1025
- * claim an AAD binding the stored ciphertext does not have, and brick the row. */
1026
- function carryForwardExternalMcpSealedEnv(existing) {
1027
- return {
1028
- sealedEnv: existing?.sealedEnv ?? null,
1029
- envNames: parseExternalMcpJsonArray({ raw: existing?.envNames ?? null }),
1030
- aadVersion: existing?.aadVersion ?? EXTERNAL_MCP_VAULT_VERSION,
1031
- };
1032
- }
1033
- /** {@link resolveExternalMcpSealedEnv}'s fresh-seal branch — parses and seals a NEW env block. Split
1034
- * out purely to keep that function's complexity under the shop ceiling.
1035
- * @throws {ExternalMcpValidationError} On a malformed env block (via {@link parseEnvBlock}).
1036
- * @throws {ExternalMcpSecretStoreUnconfiguredError} When no site key is available to seal under. */
1037
- async function sealFreshExternalMcpEnv(deps, identity, rawEnv) {
1038
- const env = parseEnvBlock(rawEnv, deps);
1039
- const envNames = Object.keys(env);
1040
- if (envNames.length === 0)
1041
- return { sealedEnv: null, envNames, aadVersion: EXTERNAL_MCP_VAULT_VERSION };
1042
- try {
1043
- const sealedEnv = await sealExternalMcpVaultPayload({ deps, identity, kind: "mcp-env", payload: env });
1044
- return { sealedEnv, envNames, aadVersion: EXTERNAL_MCP_VAULT_VERSION };
1045
- }
1046
- catch {
1047
- throw new ExternalMcpSecretStoreUnconfiguredError(deps.credential.messages.storage);
1048
- }
1049
- }
1050
- async function resolveExternalMcpSealedEnv(deps, identity, rawEnv, existing) {
1051
- // Owner policy: an exact blank update keeps credentials; whitespace cannot clear them.
1052
- if (rawEnv !== undefined && rawEnv !== '' && rawEnv.trim() === '')
1053
- throw new ExternalMcpValidationError(deps.credential.messages.blank, 'env');
1054
- return rawEnv === undefined || rawEnv === ''
1055
- ? carryForwardExternalMcpSealedEnv(existing)
1056
- : sealFreshExternalMcpEnv(deps, identity, rawEnv);
1057
- }
1058
- /** Hosts for which plaintext `http` is tolerated — a local development server, and nothing else. */
1059
- const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
1060
- /**
1061
- * Validates a remote MCP server URL.
1062
- *
1063
- * Same rule the OAuth endpoints follow (`oauth/endpoint-safety.ts`): https, or http only for
1064
- * loopback. A remote MCP endpoint carries the bearer token this whole subsystem exists to obtain, so
1065
- * a plaintext one to anywhere but a developer's own machine is a credential on the wire.
1066
- *
1067
- * @returns The normalized absolute URL.
1068
- * @throws {ExternalMcpValidationError} On an empty, unparseable, or plaintext-non-loopback URL.
1069
- * @complexity O(n) in the URL length.
1070
- */
1071
- function assertSafeRemoteMcpUrl(rawUrl, transport, ports) {
1072
- const url = rawUrl.trim();
1073
- if (url === "") {
1074
- throw new ExternalMcpValidationError(`a ${transport} server needs a URL`, "url");
1075
- }
1076
- let parsed;
1077
- try {
1078
- parsed = new URL(url);
1079
- }
1080
- catch {
1081
- throw new ExternalMcpValidationError(ports.credential.messages.url, "url");
1082
- }
1083
- assertExternalMcpPlainField({ value: url, field: "url" }, ports);
1084
- const loopback = LOOPBACK_HOSTNAMES.has(parsed.hostname.toLowerCase());
1085
- if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) {
1086
- throw new ExternalMcpValidationError("a remote MCP server URL must use https (http is permitted only for loopback)", "url");
1087
- }
1088
- return parsed.toString();
1089
- }
1090
- /** A `stdio` row needs a command; a remote row needs a URL. Split out to keep
1091
- * {@link saveExternalMcpServer}'s complexity under the shop ceiling.
1092
- * @throws {ExternalMcpValidationError} When the transport's own required field is missing or unsafe. */
1093
- function resolveTransportTarget(transport, input, ports) {
1094
- if (transport === "stdio")
1095
- return { command: assertNonEmptyExternalMcpCommand(input.command), url: null };
1096
- return { command: null, url: assertSafeRemoteMcpUrl(input.url ?? "", transport, ports) };
1097
- }
1098
106
  /**
1099
107
  * The OAuth runtime columns a save carries forward.
1100
108
  *
@@ -1120,246 +128,18 @@ function carryOAuthRuntimeState(authMode, resolved, existing) {
1120
128
  };
1121
129
  }
1122
130
  /**
1123
- * What the OAuth sealed blob holds.
1124
- *
1125
- * ONE blob rather than a column per secret, for exactly the reason the env block is one blob: every
1126
- * read path wants the whole thing at once, and per-secret sealing would buy nothing and cost N
1127
- * keyring round trips. The consequence is a READ-MODIFY-WRITE rule that every writer must honour —
1128
- * unseal, change one member, reseal — because a writer that seals `{ tokens }` alone silently
1129
- * deletes the operator's client secret.
1130
- *
1131
- * Structurally compatible with the OAuth client's `OAuthTokenSet`, but declared here rather than
1132
- * imported: this is the STORED shape, and it must be able to stay still while the flow module's
1133
- * in-memory type moves.
1134
- */
1135
- /**
1136
- * Schema version of the *plaintext* inside the sealed OAuth blob.
1137
- *
1138
- * Distinct from `oauth_aad_version`, which versions how the blob is BOUND to its row and says
1139
- * nothing about what is inside it. Without this, a field could be added but never renamed, changed,
1140
- * or removed — there would be nothing to branch on at open time, and the only way out would be a
1141
- * migration over live credentials. Stamped at seal; a blob without it predates versioning and is
1142
- * upgraded on read.
1143
- */
1144
- export const EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION = 1;
1145
- /**
1146
- * The branching read for a sealed OAuth payload. A missing version is v0 (pre-versioning) and is
1147
- * upgraded in place; a newer version is refused rather than misread, because silently
1148
- * reinterpreting an unknown shape here means handing back a wrong or partial live credential.
1149
- *
1150
- * `schemaVersion` is stripped from the result: it is a wire concern, and a caller that saw it could
1151
- * persist it back into a payload it does not own.
1152
- *
1153
- * The vault's open already refuses a non-object payload, so `parsed` is always an object here.
1154
- *
1155
- * @throws When the payload was written by a newer build than this one understands.
1156
- * @complexity O(1).
1157
- */
1158
- export function hydrateExternalMcpOAuthPayload(parsed) {
1159
- const { schemaVersion, ...rest } = parsed;
1160
- const stored = typeof schemaVersion === "number" ? schemaVersion : 0;
1161
- if (stored > EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION) {
1162
- throw new Error(`external MCP OAuth payload was written at schema version ${stored}, newer than this build understands (${EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION}) — upgrade rather than risk misreading a live credential`);
1163
- }
1164
- // v0 -> v1 added only the discriminator, so the upgrade is a stamp; a later version adds its own
1165
- // branch here rather than a backfill over live credentials.
1166
- return rest;
1167
- }
1168
- /**
1169
- * Opens a row's sealed OAuth blob.
1170
- *
1171
- * @returns `{}` when the row holds none, which is the normal state before a connection is authorized.
1172
- * @throws {ExternalMcpSecretStoreUnconfiguredError} When the blob exists but cannot be opened — a
1173
- * rotated site key or a corrupt row. Distinct from "no blob" on purpose: the caller must not treat a
1174
- * decryption failure as "not connected yet" and start a fresh authorization over a token that is
1175
- * still live at the provider.
1176
- * @complexity O(1) — one unseal.
1177
- */
1178
- /** @agent-note `deps` is the per-call sealer plus the host-bound ports; exactly one `sealer.open` per call. */
1179
- export async function openExternalMcpOAuthPayload(deps, record) {
1180
- if (record.sealedOAuth === null)
1181
- return {};
1182
- let parsed;
1183
- try {
1184
- parsed = await openExternalMcpVaultPayload({ sealer: deps.sealer, sealed: record.sealedOAuth, identity: record, kind: "mcp-auth", ports: deps });
1185
- }
1186
- catch {
1187
- throw new ExternalMcpSecretStoreUnconfiguredError("Stored OAuth credentials could not be decrypted.");
1188
- }
1189
- // Deliberately OUTSIDE the catch above: a version mismatch is not a decryption failure, and must
1190
- // not be swallowed by a caller that treats that error as "not connected yet".
1191
- return hydrateExternalMcpOAuthPayload(parsed);
1192
- }
1193
- /** @agent-note `deps` is the per-call sealer/keyring plus the host-bound ports; exactly one seal, the envelope is staged for the host repository's transaction. */
1194
- export async function sealExternalMcpOAuthPayload(deps, identity, payload) {
1195
- const hasSecret = (payload.clientSecret !== undefined && payload.clientSecret !== "") || payload.tokens !== undefined || Boolean(payload.staticAccessToken);
1196
- if (!hasSecret)
1197
- return { sealedOAuth: null, oauthAadVersion: EXTERNAL_MCP_VAULT_VERSION };
1198
- try {
1199
- const sealedOAuth = await sealExternalMcpVaultPayload({ deps, identity, kind: "mcp-auth",
1200
- // The discriminator remains authenticated inside the payload, never plain metadata.
1201
- payload: JSON.parse(JSON.stringify({ ...payload, schemaVersion: EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION })),
1202
- });
1203
- return { sealedOAuth, oauthAadVersion: EXTERNAL_MCP_VAULT_VERSION };
1204
- }
1205
- catch {
1206
- throw new ExternalMcpSecretStoreUnconfiguredError(deps.credential.messages.storage);
1207
- }
1208
- }
1209
- /**
1210
- * Applies one save's client-secret instruction to the stored blob, preserving the token.
1211
- *
1212
- * `carryToken` is `null` when the save invalidated the stored token (see
1213
- * {@link carryOAuthRuntimeState}); passing the record means "keep whatever token it holds".
1214
- *
1215
- * @throws {ExternalMcpSecretStoreUnconfiguredError} When the blob cannot be opened or resealed.
1216
- * @complexity O(1) — at most one unseal plus one seal.
1217
- */
1218
- async function resolveSealedOAuthBlob(deps, identity, clientSecret, carryToken) {
1219
- // Nothing to preserve and nothing to write: skip the keyring entirely rather than seal an empty
1220
- // object, which is what keeps a `none`/`static_env` row's OAuth blob genuinely absent.
1221
- if (carryToken === null && (clientSecret === undefined || clientSecret === "")) {
1222
- return { sealedOAuth: null, oauthAadVersion: EXTERNAL_MCP_VAULT_VERSION };
1223
- }
1224
- const existingPayload = carryToken === null ? {} : await openExternalMcpOAuthPayload(deps, carryToken);
1225
- let nextClientSecret = clientSecret;
1226
- if (clientSecret === undefined)
1227
- nextClientSecret = existingPayload.clientSecret;
1228
- if (clientSecret === "")
1229
- nextClientSecret = undefined;
1230
- const next = {
1231
- ...(nextClientSecret === undefined ? {} : { clientSecret: nextClientSecret }),
1232
- ...(existingPayload.tokens === undefined ? {} : { tokens: existingPayload.tokens }),
1233
- };
1234
- return sealExternalMcpOAuthPayload(deps, identity, next);
1235
- }
1236
- /**
1237
- * Resolves the two write-grant attribution columns for one save.
1238
- *
1239
- * Written ONLY when {@link writeAllowedToolNames}'s contents actually change — compared as a set
1240
- * against whatever the row already has — so a save that merely renames a connection or flips
1241
- * `enabled` does not stamp a new "authorized by / on" over an untouched grant. `input.principalId`
1242
- * is read only on the changed branch, which is what lets it stay a required TYPE without becoming a
1243
- * runtime hazard: a caller written before this field existed can only reach `undefined` here if it
1244
- * also never sets a non-empty {@link SaveExternalMcpServerInput.writeAllowedToolNames}, in which case
1245
- * the list never changes and this branch never runs.
1246
- *
1247
- * @complexity O(n) in the length of the longer list (via {@link toolNameSetsEqual}).
1248
- */
1249
- function resolveWriteGrantAttribution(input, writeAllowedToolNames, existing, nowIso) {
1250
- const previousWriteAllowedToolNames = parseExternalMcpJsonArray({ raw: existing?.writeAllowedToolNames ?? null });
1251
- if (toolNameSetsEqual(previousWriteAllowedToolNames, writeAllowedToolNames)) {
1252
- return {
1253
- writeGrantsUpdatedByPrincipalId: existing?.writeGrantsUpdatedByPrincipalId ?? null,
1254
- writeGrantsUpdatedAt: existing?.writeGrantsUpdatedAt ?? null,
1255
- };
1256
- }
1257
- return { writeGrantsUpdatedByPrincipalId: input.principalId, writeGrantsUpdatedAt: nowIso };
1258
- }
1259
- /** Host error adapter for the shared token policy. The store alone normalizes the value. */
1260
- function normalizeOAuthClientSecret({ value, credential }) {
1261
- try {
1262
- return credential.normalize({ value, field: 'oauth.clientSecret' });
1263
- }
1264
- catch (err) {
1265
- if (err instanceof credential.InputError)
1266
- throw new ExternalMcpValidationError(err.message, err.field);
1267
- throw err;
1268
- }
1269
- }
1270
- /** @agent-note `credential` is the host-bound token policy; its input errors become the canonical validation error with the same message and field. */
1271
- export function normalizeExternalMcpAccessToken({ value, transport, credential }, _optional = {}) {
1272
- try {
1273
- return credential.normalize({ value, field: 'accessToken', hosted: transport !== 'stdio' });
1274
- }
1275
- catch (err) {
1276
- if (err instanceof credential.InputError)
1277
- throw new ExternalMcpValidationError(err.message, err.field);
1278
- throw err;
1279
- }
1280
- }
1281
- /**
1282
- * The sealed blob for a `static_env` row's access token, under the `env` field's three-state rule.
131
+ * Validates and persists one server, sealing its env block.
1283
132
  *
1284
- * Stored in the row's existing sealed OAuth columns (and AAD lineage) rather than a new column: it is
1285
- * the same kind of thing — a sealed connection credential beside the env block — and while a row is
1286
- * `static_env` that blob holds nothing else. A carried token keeps its ciphertext AND its
1287
- * `oauthAadVersion` together, for the reason {@link SealedExternalMcpOAuth} gives.
133
+ * `env: undefined` preserves whatever is already stored, which is what lets the tab patch `enabled`
134
+ * or `label` without the operator re-typing credentials the UI never sent them. `env: ""` is the
135
+ * distinct, explicit "clear the credentials" instruction — the same unset-vs-empty distinction
136
+ * `../config.ts` draws for allowlists, and for the same reason.
1288
137
  *
1289
- * @throws {ExternalMcpValidationError} Via {@link assertValidStaticAccessToken}.
138
+ * @throws {ExternalMcpValidationError} On any invalid operator input.
1290
139
  * @throws {ExternalMcpSecretStoreUnconfiguredError} When no site key is available to seal under.
1291
- * @complexity O(n) in the token length; at most one seal.
1292
- */
1293
- async function resolveSealedStaticAccessToken(deps, identity, rawToken, existing, transport) {
1294
- const none = { sealedOAuth: null, oauthAadVersion: EXTERNAL_MCP_VAULT_VERSION };
1295
- if (rawToken === undefined || rawToken === "") {
1296
- return existing !== null && externalMcpRecordHasStaticAccessToken(existing)
1297
- ? { sealedOAuth: existing.sealedOAuth, oauthAadVersion: existing.oauthAadVersion }
1298
- : none;
1299
- }
1300
- const token = normalizeExternalMcpAccessToken({ value: rawToken, transport, credential: deps.credential });
1301
- return sealExternalMcpOAuthPayload(deps, identity, { staticAccessToken: token });
1302
- }
1303
- /**
1304
- * Which child env variable receives a `stdio` + `static_env` row's access token. `null` for a hosted
1305
- * row (its token travels in a header) and for a stdio row that neither holds a token nor names one.
1306
- *
1307
- * @throws {ExternalMcpValidationError} When a stdio row holds a token but names no variable, or an
1308
- * invalid one.
1309
- * @complexity O(n) in the name length.
1310
- */
1311
- function resolveStaticAccessTokenEnvName(transport, input, existing, holdsToken) {
1312
- if (transport !== "stdio")
1313
- return null;
1314
- const name = firstTrimmed(input.accessTokenEnvName, existing?.oauthTokenEnvName);
1315
- if (name === "") {
1316
- if (!holdsToken)
1317
- return null;
1318
- throw new ExternalMcpValidationError("a local command given an access token needs the name of the environment variable that receives it", "accessTokenEnvName");
1319
- }
1320
- if (!ENV_NAME_PATTERN.test(name)) {
1321
- throw new ExternalMcpValidationError(`'${name}' is not a valid environment variable name (letters, digits and underscore, not starting with a digit)`, "accessTokenEnvName");
1322
- }
1323
- return name;
1324
- }
1325
- /**
1326
- * The sealed-credential columns for one save, by auth mode: a `static_env` row's access token and its
1327
- * variable name, or an `oauth`/`none` row's client secret and carried token set (nothing, for `none`).
1328
- * Split out to keep {@link saveExternalMcpServer} under the shop's complexity ceiling.
1329
- *
1330
- * @complexity O(1) beyond at most one unseal and one seal.
140
+ * @complexity O(n) in the size of the env block.
141
+ * @overallScore 100
1331
142
  */
1332
- async function resolveSavedCredentialColumns(deps, identity, context) {
1333
- const { authMode, transport, input, oauthFields, keepToken, existing } = context;
1334
- if (authMode !== "static_env") {
1335
- const sealed = await resolveSealedOAuthBlob(deps, identity, oauthFields.clientSecret, keepToken ? existing : null);
1336
- return { ...sealed, oauthTokenEnvName: oauthFields.oauthTokenEnvName };
1337
- }
1338
- const sealed = await resolveSealedStaticAccessToken(deps, identity, input.accessToken, existing, transport);
1339
- if (transport !== "stdio" && sealed.sealedOAuth === null) {
1340
- throw new ExternalMcpValidationError("Enter a token. Spaces alone are not a token.", "accessToken");
1341
- }
1342
- return { ...sealed, oauthTokenEnvName: resolveStaticAccessTokenEnvName(transport, input, existing, sealed.sealedOAuth !== null) };
1343
- }
1344
- function assertExternalMcpPlainField(required, ports) {
1345
- try {
1346
- ports.assertFreeField(required);
1347
- }
1348
- catch (err) {
1349
- if (err instanceof ports.credential.InputError)
1350
- throw new ExternalMcpValidationError(err.message, err.field);
1351
- throw err;
1352
- }
1353
- }
1354
- function assertExternalMcpPlainInput({ input, ports }, _options = {}) {
1355
- for (const field of ["serverId", "label", "command", "args", "url", "transport", "authMode", "accessTokenEnvName"]) {
1356
- assertExternalMcpPlainField({ value: input[field] ?? "", field }, ports);
1357
- }
1358
- for (const [field, value] of Object.entries(input.oauth ?? {})) {
1359
- if (field !== 'clientSecret' && typeof value === 'string')
1360
- assertExternalMcpPlainField({ value, field: `oauth.${field}` }, ports);
1361
- }
1362
- }
1363
143
  /** @agent-note `deps.repo` is the host repository whose transaction commits the staged envelopes with the row pointers; seal order, id timing and the carried-envelope rule are unchanged. */
1364
144
  export async function saveExternalMcpServer(deps, input) {
1365
145
  assertExternalMcpPlainInput({ input, ports: deps });
@@ -1368,31 +148,32 @@ export async function saveExternalMcpServer(deps, input) {
1368
148
  assertSupportedExternalMcpTransport(input.transport);
1369
149
  const transport = input.transport;
1370
150
  const { command, url } = resolveTransportTarget(transport, input, deps);
1371
- const args = parseArgs(input.args);
1372
- const allowedToolNames = parseAllowedToolNames(input.allowedToolNames);
151
+ const args = parseArgs({ raw: input.args });
152
+ const allowedToolNames = parseAllowedToolNames({ raw: input.allowedToolNames });
1373
153
  // `?? ""` is a defensive fallback, not the documented contract (the type requires the field): a
1374
154
  // caller that predates this field reaches `undefined` here, and must degrade to "no write grants"
1375
155
  // rather than throw on `undefined.split`. See `SaveExternalMcpServerInput.writeAllowedToolNames`'s
1376
156
  // doc.
1377
- const writeAllowedToolNames = parseWriteAllowedToolNames(input.writeAllowedToolNames ?? "");
157
+ const writeAllowedToolNames = parseWriteAllowedToolNames({ raw: input.writeAllowedToolNames ?? "" });
1378
158
  assertWriteAllowlistSubset(writeAllowedToolNames, allowedToolNames);
1379
- const existing = await deps.repo.findByServerId({ workspaceId: input.workspaceId, serverId });
159
+ const parsed = { serverId, transport, command, url, args, allowedToolNames, writeAllowedToolNames };
160
+ const key = { workspaceId: input.workspaceId, serverId };
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);
163
+ }
164
+ /** Builds the row a save will write from the stored row it read (`null` for a create); re-run on the
165
+ * fresh row when a runtime write moved a credential between that read and the write (M4). */
166
+ async function buildSavedRecord(deps, input, parsed, existing) {
167
+ const { serverId, transport, command, url, args, allowedToolNames, writeAllowedToolNames } = parsed;
1380
168
  await assertUnderExternalMcpServerCap(deps, input.workspaceId, existing);
1381
169
  const authMode = resolveSavedAuthMode(input, existing);
1382
170
  const oauthFields = resolveOAuthFields(authMode, transport, input, existing, deps.credential);
1383
171
  const runtime = carryOAuthRuntimeState(authMode, oauthFields, existing);
1384
172
  const aadIdentity = { workspaceId: input.workspaceId, serverId };
1385
173
  const { sealedEnv, envNames, aadVersion } = await resolveExternalMcpSealedEnv(deps, aadIdentity, input.env, existing);
1386
- const { sealedOAuth, oauthAadVersion, oauthTokenEnvName } = await resolveSavedCredentialColumns(deps, aadIdentity, {
1387
- authMode,
1388
- transport,
1389
- input,
1390
- oauthFields,
1391
- keepToken: runtime.keepToken,
1392
- existing,
1393
- });
174
+ const { sealedOAuth, oauthAadVersion, oauthTokenEnvName } = await resolveSavedCredentialColumns({ deps, identity: aadIdentity, context: { authMode, transport, input, oauthFields, keepToken: runtime.keepToken, existing } });
1394
175
  const now = nowIso({ clock: deps.clock });
1395
- const writeGrantAttribution = resolveWriteGrantAttribution(input, writeAllowedToolNames, existing, now);
176
+ const writeGrantAttribution = resolveWriteGrantAttribution({ input, writeAllowedToolNames, existing, nowIso: now });
1396
177
  const record = {
1397
178
  workspaceId: input.workspaceId,
1398
179
  serverId,
@@ -1424,9 +205,9 @@ export async function saveExternalMcpServer(deps, input) {
1424
205
  oauthAadVersion,
1425
206
  createdAt: existing?.createdAt ?? now,
1426
207
  updatedAt: now,
208
+ version: existing?.version ?? 1,
1427
209
  };
1428
- await deps.repo.upsert(record);
1429
- return toView(record, deps, deps.sealer);
210
+ return record;
1430
211
  }
1431
212
  /**
1432
213
  * Removes one server. Returns whether a row was actually deleted, so a route can answer 404 rather