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

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 -9
  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
@@ -0,0 +1,232 @@
1
+ import { ExternalMcpValidationError } from "./validation-error.js";
2
+ import { assertExternalMcpPlainField } from "./store.save.js";
3
+ import { SUPPORTED_EXTERNAL_MCP_TRANSPORTS } from "./vocabulary.js";
4
+ import { assertValidConnectionId } from "../trust.js";
5
+ const MAX_ENV_VARS = 64;
6
+ const MAX_ARGS = 64;
7
+ /** POSIX-ish environment variable name. Deliberately stricter than what a shell tolerates: a name
8
+ * outside this set is far more likely a mis-pasted line than an intentional variable. */
9
+ export const ENV_NAME_PATTERN = /^[A-Za-z_]\w*$/;
10
+ /** Generous — a provider asking for more distinct scopes than this is misconfigured, not ambitious. */
11
+ const MAX_OAUTH_SCOPES = 64;
12
+ /**
13
+ * Parses an operator's `KEY=VALUE`-per-line environment block into a map.
14
+ *
15
+ * Blank lines and `#` comments are skipped so an operator can annotate the block. Everything else
16
+ * must parse: a line without `=` is rejected rather than ignored, because silently dropping what
17
+ * looks like a credential is how a server ends up launching without the token the operator believes
18
+ * they supplied. Only the FIRST `=` splits, so values may contain `=` (base64 padding, connection
19
+ * strings).
20
+ *
21
+ * @param text - Raw textarea content.
22
+ * @returns The parsed variables, in first-seen order.
23
+ * @throws {ExternalMcpValidationError} On a malformed line, an invalid name, a duplicate, or more
24
+ * than {@link MAX_ENV_VARS} variables.
25
+ * @complexity O(n) in the number of lines.
26
+ * @overallScore 100
27
+ */
28
+ /** One line of {@link parseEnvBlock}'s input, parsed and name-validated but not yet checked against
29
+ * the running `env` map (dedup/cap are the loop's own job, since they need cross-line state). Split
30
+ * out purely to keep `parseEnvBlock`'s cognitive complexity under the shop ceiling — `null` means
31
+ * "skip this line" (blank or `#` comment), matching the original inline `continue`. */
32
+ function parseEnvLine(rawLine, index) {
33
+ const line = rawLine;
34
+ if (line.trim() === "" || line.trimStart().startsWith("#"))
35
+ return null;
36
+ const separator = line.indexOf("=");
37
+ // Validation reaches the model through the human form; never echo the credential block.
38
+ if (separator <= 0) {
39
+ throw new ExternalMcpValidationError(`line ${index + 1} of the environment block is not \`NAME=VALUE\` — correct it in the connection form`, "env");
40
+ }
41
+ const name = line.slice(0, separator).trim();
42
+ if (!ENV_NAME_PATTERN.test(name)) {
43
+ 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");
44
+ }
45
+ return { name, value: line.slice(separator + 1).trim() };
46
+ }
47
+ /** @agent-note `ports` are the host-bound credential rules (length cap, messages, secret-in-plain-field check). */
48
+ export function parseEnvBlock({ text, ports }, _optional = {}) {
49
+ // JSON is the lossless representation for multiline values; NAME=VALUE remains compatible.
50
+ if (text.trimStart().startsWith('{')) {
51
+ return parseJsonEnvBlock({ text, ports });
52
+ }
53
+ const env = {};
54
+ const lines = text.split(/\r?\n/);
55
+ for (const [index, rawLine] of lines.entries()) {
56
+ const parsed = parseEnvLine(rawLine, index);
57
+ if (!parsed)
58
+ continue;
59
+ // Rejected rather than last-write-wins: two lines setting the same variable means the operator
60
+ // believes both are in effect, and picking one silently is the failure mode this guards.
61
+ if (Object.hasOwn(env, parsed.name)) {
62
+ throw new ExternalMcpValidationError(`environment variable '${parsed.name}' is set more than once`, "env");
63
+ }
64
+ if (Object.keys(env).length >= MAX_ENV_VARS) {
65
+ throw new ExternalMcpValidationError(`at most ${MAX_ENV_VARS} environment variables are supported`, "env");
66
+ }
67
+ if (parsed.value.length > ports.credential.limit)
68
+ throw new ExternalMcpValidationError("The token exceeds the 8192-character limit. Copy only the token.", "env");
69
+ assertExternalMcpPlainField({ value: parsed.name, field: "env" }, ports);
70
+ env[parsed.name] = parsed.value;
71
+ }
72
+ return env;
73
+ }
74
+ function assertJsonEnvEntry({ name, value, ports }, _options = {}) {
75
+ if (!ENV_NAME_PATTERN.test(name) || typeof value !== 'string' || value.includes('\0'))
76
+ throw new ExternalMcpValidationError(ports.credential.messages.env, 'env');
77
+ assertExternalMcpPlainField({ value: name, field: 'env' }, ports);
78
+ if (value.length > ports.credential.limit)
79
+ throw new ExternalMcpValidationError('The token exceeds the 8192-character limit. Copy only the token.', 'env');
80
+ }
81
+ function parseJsonEnvBlock({ text, ports }, _options = {}) {
82
+ let parsed;
83
+ try {
84
+ parsed = JSON.parse(text);
85
+ }
86
+ catch {
87
+ throw new ExternalMcpValidationError(ports.credential.messages.env, 'env');
88
+ }
89
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
90
+ throw new ExternalMcpValidationError(ports.credential.messages.env, 'env');
91
+ const entries = Object.entries(parsed);
92
+ if (entries.length > MAX_ENV_VARS)
93
+ throw new ExternalMcpValidationError(`at most ${MAX_ENV_VARS} environment variables are supported`, 'env');
94
+ for (const [name, value] of entries)
95
+ assertJsonEnvEntry({ name, value, ports });
96
+ return Object.fromEntries(entries);
97
+ }
98
+ /**
99
+ * Splits an operator's space-separated argv string.
100
+ *
101
+ * One quoting rule, and only one: a token that STARTS with `"` runs to the next `"`, which must end
102
+ * the token (whitespace or end of string after it), and both quotes are dropped. That is what lets a
103
+ * path with a space in it — `"C:\\Users\\John Smith\\..."`, the desktop shell's win32
104
+ * registration — arrive as one argument. There are no escapes (a backslash is always literal, since
105
+ * Windows paths are full of them), and a `"` anywhere else in a token stays literal exactly as it did
106
+ * before this rule existed, so `--name="x"` still reaches the child unchanged. This is NOT shell
107
+ * quoting: the command is spawned WITHOUT a shell (`adapter.stdio.ts` uses `spawn` with an argv
108
+ * array), and nothing else a shell would do happens here.
109
+ *
110
+ * @throws {ExternalMcpValidationError} On an unterminated quoted token, a closing quote followed by
111
+ * more characters, or more than `MAX_ARGS` arguments.
112
+ * @complexity O(n) in the string length.
113
+ */
114
+ export function parseArgs({ raw }, _optional = {}) {
115
+ const args = [];
116
+ let index = 0;
117
+ while (index < raw.length) {
118
+ if (/\s/.test(raw[index])) {
119
+ index += 1;
120
+ continue;
121
+ }
122
+ const token = raw[index] === '"' ? readQuotedArg(raw, index) : readBareArg(raw, index);
123
+ args.push(token.value);
124
+ index = token.end;
125
+ }
126
+ if (args.length > MAX_ARGS) {
127
+ throw new ExternalMcpValidationError(`at most ${MAX_ARGS} arguments are supported`, "args");
128
+ }
129
+ return args;
130
+ }
131
+ /** {@link parseArgs}'s unquoted token: everything up to the next whitespace, quotes included. */
132
+ function readBareArg(raw, start) {
133
+ const match = /\s/.exec(raw.slice(start));
134
+ const end = match === null ? raw.length : start + match.index;
135
+ return { value: raw.slice(start, end), end };
136
+ }
137
+ /** {@link parseArgs}'s quoted token, `start` pointing at its opening `"`.
138
+ * @throws {ExternalMcpValidationError} When the quote never closes, or does not end the token. */
139
+ function readQuotedArg(raw, start) {
140
+ const close = raw.indexOf('"', start + 1);
141
+ if (close === -1) {
142
+ throw new ExternalMcpValidationError("an argument opens a double quote that never closes", "args");
143
+ }
144
+ const end = close + 1;
145
+ if (end < raw.length && !/\s/.test(raw[end])) {
146
+ throw new ExternalMcpValidationError("a closing double quote must be followed by a space or the end of the arguments", "args");
147
+ }
148
+ return { value: raw.slice(start + 1, close), end };
149
+ }
150
+ /** Validates `serverId` via the trust tier's own assertion, remapped onto this store's own error
151
+ * type. Split out purely to keep {@link saveExternalMcpServer}'s complexity under the shop
152
+ * ceiling — reuses `trust.ts`'s rule rather than restating it, since this id becomes part of every
153
+ * federated tool id and two copies of that rule could drift. */
154
+ export function assertValidExternalMcpServerId(serverId) {
155
+ try {
156
+ assertValidConnectionId({ connectionId: serverId });
157
+ }
158
+ catch (err) {
159
+ throw new ExternalMcpValidationError(err instanceof Error ? err.message : String(err), "id");
160
+ }
161
+ }
162
+ export function assertSupportedExternalMcpTransport(transport) {
163
+ if (!SUPPORTED_EXTERNAL_MCP_TRANSPORTS.includes(transport)) {
164
+ throw new ExternalMcpValidationError(`transport '${transport}' is not supported — only ${SUPPORTED_EXTERNAL_MCP_TRANSPORTS.join(", ")} is implemented`, "transport");
165
+ }
166
+ }
167
+ /**
168
+ * Splits an operator's comma- or space-separated OAuth scope list.
169
+ *
170
+ * An empty result is legitimate — several providers infer scope from the client registration — so it
171
+ * is returned rather than rejected, the same call {@link parseAllowedToolNames} makes.
172
+ *
173
+ * @throws {ExternalMcpValidationError} Past {@link MAX_OAUTH_SCOPES}.
174
+ * @complexity O(n) in the number of scopes.
175
+ */
176
+ export function parseOAuthScopes({ raw }, _optional = {}) {
177
+ const scopes = raw.split(/[\s,]+/).filter((part) => part.length > 0);
178
+ if (scopes.length > MAX_OAUTH_SCOPES) {
179
+ throw new ExternalMcpValidationError(`at most ${MAX_OAUTH_SCOPES} OAuth scopes are supported`, "oauth.scopes");
180
+ }
181
+ return [...new Set(scopes)];
182
+ }
183
+ /** Trims and validates `rawCommand`, returning the trimmed value. Split out purely to keep
184
+ * {@link saveExternalMcpServer}'s complexity under the shop ceiling. */
185
+ function assertNonEmptyExternalMcpCommand(rawCommand) {
186
+ const command = rawCommand.trim();
187
+ if (command === "") {
188
+ throw new ExternalMcpValidationError("a stdio server needs a command to launch", "command");
189
+ }
190
+ return command;
191
+ }
192
+ /** Hosts for which plaintext `http` is tolerated — a local development server, and nothing else. */
193
+ const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
194
+ /**
195
+ * Validates a remote MCP server URL.
196
+ *
197
+ * Same rule the OAuth endpoints follow (`oauth/endpoint-safety.ts`): https, or http only for
198
+ * loopback. A remote MCP endpoint carries the bearer token this whole subsystem exists to obtain, so
199
+ * a plaintext one to anywhere but a developer's own machine is a credential on the wire.
200
+ *
201
+ * @returns The normalized absolute URL.
202
+ * @throws {ExternalMcpValidationError} On an empty, unparseable, or plaintext-non-loopback URL.
203
+ * @complexity O(n) in the URL length.
204
+ */
205
+ function assertSafeRemoteMcpUrl(rawUrl, transport, ports) {
206
+ const url = rawUrl.trim();
207
+ if (url === "") {
208
+ throw new ExternalMcpValidationError(`a ${transport} server needs a URL`, "url");
209
+ }
210
+ let parsed;
211
+ try {
212
+ parsed = new URL(url);
213
+ }
214
+ catch {
215
+ throw new ExternalMcpValidationError(ports.credential.messages.url, "url");
216
+ }
217
+ assertExternalMcpPlainField({ value: url, field: "url" }, ports);
218
+ const loopback = LOOPBACK_HOSTNAMES.has(parsed.hostname.toLowerCase());
219
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) {
220
+ throw new ExternalMcpValidationError("a remote MCP server URL must use https (http is permitted only for loopback)", "url");
221
+ }
222
+ return parsed.toString();
223
+ }
224
+ /** A `stdio` row needs a command; a remote row needs a URL. Split out to keep
225
+ * {@link saveExternalMcpServer}'s complexity under the shop ceiling.
226
+ * @throws {ExternalMcpValidationError} When the transport's own required field is missing or unsafe. */
227
+ export function resolveTransportTarget(transport, input, ports) {
228
+ if (transport === "stdio")
229
+ return { command: assertNonEmptyExternalMcpCommand(input.command), url: null };
230
+ return { command: null, url: assertSafeRemoteMcpUrl(input.url ?? "", transport, ports) };
231
+ }
232
+ //# sourceMappingURL=store-input.js.map
@@ -0,0 +1,26 @@
1
+ import type { ExternalMcpAuthMode, ExternalMcpServerRecord, ExternalMcpTransport, SaveExternalMcpServerInput } from "@jini-ai/core/contracts/hosted-mcp";
2
+ import type { HostedMcpStorePorts } from "./store-ports.js";
3
+ /** The OAuth columns produced by one save, plus the operator's client-secret instruction. */
4
+ export interface ResolvedOAuthFields {
5
+ readonly oauthProviderId: string | null;
6
+ readonly oauthGrant: string | null;
7
+ readonly oauthClientId: string | null;
8
+ readonly oauthEndpointsJson: string | null;
9
+ readonly oauthScopesJson: string | null;
10
+ readonly oauthTokenEnvName: string | null;
11
+ /** Three-state, as `env` is: `undefined` keeps, a string replaces, `""` clears. */
12
+ readonly clientSecret: string | undefined;
13
+ }
14
+ /**
15
+ * The first non-empty trimmed candidate, or `""`.
16
+ *
17
+ * Every OAuth identity field follows the same precedence — what the operator just submitted, then
18
+ * what the row already holds, then nothing — and writing that as a `??` chain at each field is both
19
+ * repetitive and, measurably, most of these functions' branch count. One helper makes the precedence
20
+ * a single named rule instead of five copies of it.
21
+ *
22
+ * @complexity O(n) in the number of candidates, each trimmed once.
23
+ */
24
+ export declare function firstTrimmed(...candidates: readonly (string | null | undefined)[]): string;
25
+ export declare function resolveOAuthFields(authMode: ExternalMcpAuthMode, transport: ExternalMcpTransport, input: SaveExternalMcpServerInput, existing: ExternalMcpServerRecord | null, credential: HostedMcpStorePorts["credential"]): ResolvedOAuthFields;
26
+ //# sourceMappingURL=store-oauth-fields.d.ts.map
@@ -0,0 +1,246 @@
1
+ import { ExternalMcpValidationError } from "./validation-error.js";
2
+ import { EXTERNAL_MCP_OAUTH_GRANTS } from "./vocabulary.js";
3
+ import { parseExternalMcpJsonArray } from "./access.js";
4
+ import { ENV_NAME_PATTERN, parseOAuthScopes } from "./store-input.js";
5
+ /** Bounds the single-line OAuth identity fields (client id, secret). A real one is far shorter; the
6
+ * cap exists so a pasted file cannot become a database row. */
7
+ const MAX_OAUTH_FIELD_LENGTH = 1024;
8
+ /** Matches the OAuth provider identifier rule. Restated rather than imported for the reason this
9
+ * file's header gives: the row shape must not depend on the flow module. */
10
+ const OAUTH_PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
11
+ /** Parses a stored JSON object column, tolerating a null/absent/corrupt value as `{}` — the same
12
+ * posture {@link parseJsonArray} takes, and for the same reason: one unreadable column must not
13
+ * make a whole row unreadable. */
14
+ function parseJsonObject(raw) {
15
+ if (!raw)
16
+ return {};
17
+ try {
18
+ const parsed = JSON.parse(raw);
19
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
20
+ return {};
21
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
22
+ }
23
+ catch {
24
+ return {};
25
+ }
26
+ }
27
+ /** The endpoints an operator typed for a connection that defines its own provider. Empty strings are
28
+ * dropped so `{}` — "this connection names a registered provider instead" — stays representable. */
29
+ function buildOAuthEndpoints(oauth) {
30
+ const entries = [
31
+ ["authorizationEndpoint", oauth.authorizationEndpoint],
32
+ ["tokenEndpoint", oauth.tokenEndpoint],
33
+ ["deviceAuthorizationEndpoint", oauth.deviceAuthorizationEndpoint],
34
+ ];
35
+ const endpoints = {};
36
+ for (const [key, value] of entries) {
37
+ const trimmed = value?.trim();
38
+ if (trimmed)
39
+ endpoints[key] = trimmed;
40
+ }
41
+ return endpoints;
42
+ }
43
+ /**
44
+ * Validates and resolves the OAuth columns for one save.
45
+ *
46
+ * @throws {ExternalMcpValidationError} On any invalid operator input, with `field` naming the
47
+ * offending form control (`oauth.clientId`, `oauth.grant`, ...).
48
+ * @complexity O(n) in the number of scopes.
49
+ */
50
+ /** The OAuth columns of a row that is NOT OAuth-authenticated: all cleared.
51
+ *
52
+ * Cleared rather than preserved, deliberately: a row switched to `static_env` that still carried a
53
+ * provider and a client id would silently re-adopt them if it were ever switched back, along with a
54
+ * token issued under configuration nobody has looked at since. */
55
+ const NO_OAUTH_FIELDS = {
56
+ oauthProviderId: null,
57
+ oauthGrant: null,
58
+ oauthClientId: null,
59
+ oauthEndpointsJson: null,
60
+ oauthScopesJson: null,
61
+ oauthTokenEnvName: null,
62
+ clientSecret: "",
63
+ };
64
+ /**
65
+ * The first non-empty trimmed candidate, or `""`.
66
+ *
67
+ * Every OAuth identity field follows the same precedence — what the operator just submitted, then
68
+ * what the row already holds, then nothing — and writing that as a `??` chain at each field is both
69
+ * repetitive and, measurably, most of these functions' branch count. One helper makes the precedence
70
+ * a single named rule instead of five copies of it.
71
+ *
72
+ * @complexity O(n) in the number of candidates, each trimmed once.
73
+ */
74
+ export function firstTrimmed(...candidates) {
75
+ for (const candidate of candidates) {
76
+ const trimmed = candidate?.trim();
77
+ if (trimmed)
78
+ return trimmed;
79
+ }
80
+ return "";
81
+ }
82
+ /**
83
+ * Validates a sign-in method, or admits its absence on a row that can discover it for itself.
84
+ *
85
+ * The same exception {@link assertOAuthClientId} documents, extended to the grant: a REMOTE row can
86
+ * run RFC 8414 discovery against its own URL at connect time and read the authorization server's own
87
+ * `grant_types_supported` (`discovery.ts`) instead of an operator having to guess between "Browser
88
+ * sign-in" and "Device code" before they know what the server even offers. See
89
+ * the sign-in service's `selfConfigureConnection`, which resolves and persists a concrete grant
90
+ * the first time such a row connects. A stdio row has no URL to discover from, so for those the
91
+ * requirement stands unchanged.
92
+ *
93
+ * @returns The validated grant, or `null` when the row will resolve one at connect.
94
+ * @throws {ExternalMcpValidationError} On an empty grant the row cannot leave to discovery, or one
95
+ * outside {@link EXTERNAL_MCP_OAUTH_GRANTS}.
96
+ * @complexity O(1).
97
+ */
98
+ function assertOAuthGrant(grant, selfConfigurable) {
99
+ if (grant === "") {
100
+ if (selfConfigurable)
101
+ return null;
102
+ throw new ExternalMcpValidationError("an OAuth connection needs a sign-in method", "oauth.grant");
103
+ }
104
+ if (!EXTERNAL_MCP_OAUTH_GRANTS.includes(grant)) {
105
+ throw new ExternalMcpValidationError(`OAuth grant '${grant}' is not supported — expected one of ${EXTERNAL_MCP_OAUTH_GRANTS.join(", ")}`, "oauth.grant");
106
+ }
107
+ return grant;
108
+ }
109
+ /**
110
+ * Validates a client id, or admits its absence on a row that can obtain one for itself.
111
+ *
112
+ * `selfConfigurable` is what makes an empty client id legitimate rather than a validation failure.
113
+ * A growing share of hosted authorization servers publish an RFC 7591 `registration_endpoint` and no
114
+ * developer console at all, so for those there is no human path to a client id — demanding one here
115
+ * would make the connection unreachable by any amount of operator effort. A row that carries a REMOTE
116
+ * URL can run discovery against it at connect time and mint one; a stdio row has nothing to discover
117
+ * from, so for those the requirement stands unchanged.
118
+ *
119
+ * @returns The validated client id, or `null` when the row will mint one at connect.
120
+ * @throws {ExternalMcpValidationError} On an empty client id the row cannot obtain, or an oversized one.
121
+ * @complexity O(1).
122
+ */
123
+ function assertOAuthClientId(clientId, selfConfigurable) {
124
+ if (clientId === "") {
125
+ if (selfConfigurable)
126
+ return null;
127
+ throw new ExternalMcpValidationError("an OAuth connection needs a client id", "oauth.clientId");
128
+ }
129
+ if (clientId.length > MAX_OAUTH_FIELD_LENGTH) {
130
+ throw new ExternalMcpValidationError(`the OAuth client id may be at most ${MAX_OAUTH_FIELD_LENGTH} characters`, "oauth.clientId");
131
+ }
132
+ return clientId;
133
+ }
134
+ /**
135
+ * Resolves the provider half of an OAuth connection: a registered provider id, its own endpoints, or
136
+ * both.
137
+ *
138
+ * Endpoints are re-derived whenever the operator actually TYPED into either identity field, so
139
+ * clearing a provider id and typing endpoints (or the reverse) cannot leave half of the old pairing
140
+ * behind. "Actually typed" is judged by content, not key presence: the admin form sends both fields
141
+ * on every save (it cannot round-trip a connection's own endpoints), so treating mere presence as a
142
+ * touch made an untouched save look like an identity change on every edit. The host's form must preserve that distinction.
143
+ *
144
+ * The dynamic-registration members (`clientAuth`, `dynamicClientId`, `registeredRedirectUri`) are
145
+ * exempted from re-derivation regardless of branch: they are server-owned, written only by dynamic
146
+ * client registration by the sign-in service, and no operator input can express them, so even a
147
+ * save that legitimately edits the other endpoints must not drop them.
148
+ *
149
+ * @throws {ExternalMcpValidationError} When neither a provider id nor a token endpoint is present,
150
+ * or the provider id is malformed.
151
+ * @complexity O(1).
152
+ */
153
+ function resolveOAuthEndpoints(oauth, existing) {
154
+ const stored = parseJsonObject(existing?.oauthEndpointsJson ?? null);
155
+ const touchedIdentity = (oauth.providerId ?? "").trim() !== "" || (oauth.tokenEndpoint ?? "").trim() !== "";
156
+ if (!touchedIdentity)
157
+ return stored;
158
+ const rebuilt = buildOAuthEndpoints(oauth);
159
+ for (const key of DYNAMIC_REGISTRATION_ENDPOINT_KEYS) {
160
+ if (stored[key] !== undefined)
161
+ rebuilt[key] = stored[key];
162
+ }
163
+ return rebuilt;
164
+ }
165
+ /** The endpoints-blob members only dynamic client registration writes. */
166
+ const DYNAMIC_REGISTRATION_ENDPOINT_KEYS = ["clientAuth", "dynamicClientId", "registeredRedirectUri"];
167
+ /**
168
+ * @param selfConfigurable - Whether this row can discover its own endpoints — see
169
+ * {@link assertOAuthClientId} for the same argument applied to the client id.
170
+ * @throws {ExternalMcpValidationError} When neither identity is present on a row that cannot
171
+ * discover one, or the id is malformed.
172
+ */
173
+ function assertOAuthProviderIdentity(providerId, endpoints, selfConfigurable) {
174
+ if (providerId === "" && endpoints.tokenEndpoint === undefined && !selfConfigurable) {
175
+ throw new ExternalMcpValidationError("an OAuth connection needs either a registered provider id or its own token endpoint", "oauth.providerId");
176
+ }
177
+ if (providerId !== "" && !OAUTH_PROVIDER_ID_PATTERN.test(providerId)) {
178
+ throw new ExternalMcpValidationError(`'${providerId}' is not a valid provider id (lowercase letters, digits and hyphens)`, "oauth.providerId");
179
+ }
180
+ }
181
+ function resolveOAuthProviderIdentity(oauth, existing, selfConfigurable) {
182
+ const providerId = firstTrimmed(oauth.providerId, existing?.oauthProviderId);
183
+ const endpoints = resolveOAuthEndpoints(oauth, existing);
184
+ assertOAuthProviderIdentity(providerId, endpoints, selfConfigurable);
185
+ return {
186
+ oauthProviderId: providerId === "" ? null : providerId,
187
+ oauthEndpointsJson: Object.keys(endpoints).length === 0 ? null : JSON.stringify(endpoints),
188
+ };
189
+ }
190
+ /**
191
+ * Resolves which child-process environment variable receives the access token.
192
+ *
193
+ * `null` for every non-`stdio` transport: only `stdio` hands credentials to a child process, so only
194
+ * `stdio` needs a name for one.
195
+ *
196
+ * @throws {ExternalMcpValidationError} When a stdio+OAuth row names none, or names an invalid one.
197
+ * @complexity O(n) in the name length.
198
+ */
199
+ function resolveOAuthTokenEnvName(transport, oauth, existing) {
200
+ if (transport !== "stdio")
201
+ return null;
202
+ const tokenEnvName = firstTrimmed(oauth.tokenEnvName, existing?.oauthTokenEnvName);
203
+ if (tokenEnvName === "") {
204
+ throw new ExternalMcpValidationError("a stdio server authenticated with OAuth needs the name of the environment variable that receives its access token", "oauth.tokenEnvName");
205
+ }
206
+ if (!ENV_NAME_PATTERN.test(tokenEnvName)) {
207
+ throw new ExternalMcpValidationError(`'${tokenEnvName}' is not a valid environment variable name (letters, digits and underscore, not starting with a digit)`, "oauth.tokenEnvName");
208
+ }
209
+ return tokenEnvName;
210
+ }
211
+ /** Scopes for one save. Absent input KEEPS the stored list (the three-state rule `env` sets); an
212
+ * empty string clears it, since {@link parseOAuthScopes} of `""` is `[]`. */
213
+ function resolveSavedOAuthScopes(oauth, existing) {
214
+ if (oauth.scopes === undefined)
215
+ return parseExternalMcpJsonArray({ raw: existing?.oauthScopesJson ?? null });
216
+ return parseOAuthScopes({ raw: oauth.scopes });
217
+ }
218
+ export function resolveOAuthFields(authMode, transport, input, existing, credential) {
219
+ if (authMode !== "oauth")
220
+ return NO_OAUTH_FIELDS;
221
+ const oauth = input.oauth ?? {};
222
+ // Only a remote row has a URL for the sign-in service to run RFC 9728 / RFC 8414 discovery
223
+ // against, so only a remote row may leave its provider identity, grant and client id to be filled
224
+ // in at connect time.
225
+ const selfConfigurable = transport !== "stdio";
226
+ return {
227
+ ...resolveOAuthProviderIdentity(oauth, existing, selfConfigurable),
228
+ oauthGrant: assertOAuthGrant(firstTrimmed(oauth.grant, existing?.oauthGrant), selfConfigurable),
229
+ oauthClientId: assertOAuthClientId(firstTrimmed(oauth.clientId, existing?.oauthClientId), selfConfigurable),
230
+ oauthScopesJson: JSON.stringify(resolveSavedOAuthScopes(oauth, existing)),
231
+ oauthTokenEnvName: resolveOAuthTokenEnvName(transport, oauth, existing),
232
+ clientSecret: oauth.clientSecret === '' || oauth.clientSecret === undefined ? undefined : normalizeOAuthClientSecret({ value: oauth.clientSecret, credential }),
233
+ };
234
+ }
235
+ /** Host error adapter for the shared token policy. The store alone normalizes the value. */
236
+ function normalizeOAuthClientSecret({ value, credential }) {
237
+ try {
238
+ return credential.normalize({ value, field: 'oauth.clientSecret' });
239
+ }
240
+ catch (err) {
241
+ if (err instanceof credential.InputError)
242
+ throw new ExternalMcpValidationError(err.message, err.field);
243
+ throw err;
244
+ }
245
+ }
246
+ //# sourceMappingURL=store-oauth-fields.js.map
@@ -0,0 +1,49 @@
1
+ import type { ExternalMcpServerRecord, ExternalMcpServerView, ExternalMcpStoreDeps } from "@jini-ai/core/contracts/hosted-mcp";
2
+ import type { UUID } from "@jini-ai/core/primitives";
3
+ import type { SecretSealerPort } from "@jini-ai/core/contracts/vault";
4
+ import type { HostedMcpStorePorts, HostedMcpTokenHint } from "./store-ports.js";
5
+ /**
6
+ * Whether this row holds an access TOKEN — answered from PLAINTEXT columns alone, never by unsealing.
7
+ *
8
+ * Token clearing preserves the client secret sharing the sealed blob (setOAuthStatus). A
9
+ * disconnected row can therefore have a non-null blob containing a secret but no access token;
10
+ * blob presence alone cannot answer this question.
11
+ *
12
+ * Not repaired by unsealing, deliberately. This is read by a plain list route that must answer
13
+ * without a keyring round trip, and must keep answering TRUTHFULLY for a row whose blob will not
14
+ * open at all: a rotated site key, or a legacy `aad_version 0` ciphertext. A decrypt here would turn
15
+ * either into a failed settings tab, and would put a keyring dependency on a read path that has
16
+ * never had one.
17
+ *
18
+ * The blob check leads because it is the NECESSARY condition — no blob, no token, whatever the
19
+ * plaintext says. Each of the two disjuncts after it is independently SUFFICIENT, which is what
20
+ * makes a false positive unreachable:
21
+ *
22
+ * - `connected` is written by exactly one place, `persistTokens`, and that same upsert writes the
23
+ * tokens. Every path that clears a token moves the row off `connected` in the same write.
24
+ * - `oauthExpiresAt` is written beside the tokens by that same `persistTokens`, and nulled by every
25
+ * clear (`setOAuthStatus`'s `clearToken` branch) and by every save that invalidates the token
26
+ * ({@link carryOAuthRuntimeState}), so a non-null expiry cannot outlive the token it describes.
27
+ *
28
+ * @returns `true` only when a token is stored. The single state it can UNDER-report is a token
29
+ * 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`
30
+ * without its token being cleared: a re-connect left `pending`, or a terminal device-poll failure.
31
+ * Under-reporting is the safe direction, and closing it exactly needs a plaintext token-presence
32
+ * column, which is a schema change rather than a read fix.
33
+ * @complexity O(1) — three field reads, no I/O.
34
+ */
35
+ export declare function externalMcpRecordHasStoredToken(record: Pick<ExternalMcpServerRecord, "sealedOAuth" | "oauthStatus" | "oauthExpiresAt">): boolean;
36
+ export declare function toView(record: ExternalMcpServerRecord, ports: HostedMcpStorePorts, sealer?: SecretSealerPort): Promise<ExternalMcpServerView<HostedMcpTokenHint>>;
37
+ /**
38
+ * Lists the workspace's servers for the admin tab. The tab has no use for env
39
+ * values and must not be a route that decrypts them. Token hints alone are now derived by
40
+ * server-side unsealing, per the owner decision; no secret value is returned.
41
+ *
42
+ * @complexity O(n) in the stored server count.
43
+ * @overallScore 100
44
+ */
45
+ export declare function listExternalMcpServerViews({ deps, workspaceId }: {
46
+ deps: Pick<ExternalMcpStoreDeps, "repo"> & Partial<Pick<ExternalMcpStoreDeps, "sealer">> & HostedMcpStorePorts;
47
+ workspaceId: UUID;
48
+ }, _optional?: Record<string, never>): Promise<ExternalMcpServerView<HostedMcpTokenHint>[]>;
49
+ //# sourceMappingURL=store-view.d.ts.map
@@ -0,0 +1,112 @@
1
+ import { externalMcpRecordHasStaticAccessToken, resolveExternalMcpAuthMode, resolveExternalMcpOAuthStatus } from "./auth.js";
2
+ import { parseExternalMcpJsonArray } from "./access.js";
3
+ import { openExternalMcpEnv, openExternalMcpOAuthPayload } from "./vault.js";
4
+ /**
5
+ * Whether this row holds an access TOKEN — answered from PLAINTEXT columns alone, never by unsealing.
6
+ *
7
+ * Token clearing preserves the client secret sharing the sealed blob (setOAuthStatus). A
8
+ * disconnected row can therefore have a non-null blob containing a secret but no access token;
9
+ * blob presence alone cannot answer this question.
10
+ *
11
+ * Not repaired by unsealing, deliberately. This is read by a plain list route that must answer
12
+ * without a keyring round trip, and must keep answering TRUTHFULLY for a row whose blob will not
13
+ * open at all: a rotated site key, or a legacy `aad_version 0` ciphertext. A decrypt here would turn
14
+ * either into a failed settings tab, and would put a keyring dependency on a read path that has
15
+ * never had one.
16
+ *
17
+ * The blob check leads because it is the NECESSARY condition — no blob, no token, whatever the
18
+ * plaintext says. Each of the two disjuncts after it is independently SUFFICIENT, which is what
19
+ * makes a false positive unreachable:
20
+ *
21
+ * - `connected` is written by exactly one place, `persistTokens`, and that same upsert writes the
22
+ * tokens. Every path that clears a token moves the row off `connected` in the same write.
23
+ * - `oauthExpiresAt` is written beside the tokens by that same `persistTokens`, and nulled by every
24
+ * clear (`setOAuthStatus`'s `clearToken` branch) and by every save that invalidates the token
25
+ * ({@link carryOAuthRuntimeState}), so a non-null expiry cannot outlive the token it describes.
26
+ *
27
+ * @returns `true` only when a token is stored. The single state it can UNDER-report is a token
28
+ * 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`
29
+ * without its token being cleared: a re-connect left `pending`, or a terminal device-poll failure.
30
+ * Under-reporting is the safe direction, and closing it exactly needs a plaintext token-presence
31
+ * column, which is a schema change rather than a read fix.
32
+ * @complexity O(1) — three field reads, no I/O.
33
+ */
34
+ export function externalMcpRecordHasStoredToken(record) {
35
+ if (record.sealedOAuth === null)
36
+ return false;
37
+ return resolveExternalMcpOAuthStatus(record) === "connected" || record.oauthExpiresAt !== null;
38
+ }
39
+ async function externalMcpEnvHints({ record, sealer, ports }, _options = {}) {
40
+ const envTokenHints = {};
41
+ if (!sealer || !record.sealedEnv)
42
+ return envTokenHints;
43
+ const opened = await openExternalMcpEnv(record, { ...ports, sealer });
44
+ if (!opened.ok)
45
+ return envTokenHints;
46
+ for (const [name, value] of Object.entries(opened.env)) {
47
+ if (typeof value === 'string')
48
+ envTokenHints[name] = ports.credential.hint({ token: value });
49
+ }
50
+ return envTokenHints;
51
+ }
52
+ async function externalMcpAccessTokenHint({ record, sealer, ports }, _options = {}) {
53
+ let accessTokenHint = null;
54
+ if (sealer && record.sealedOAuth) {
55
+ try {
56
+ const payload = await openExternalMcpOAuthPayload({ ...ports, sealer }, record);
57
+ const token = payload.staticAccessToken ?? payload.tokens?.accessToken;
58
+ if (token)
59
+ accessTokenHint = ports.credential.hint({ token });
60
+ }
61
+ catch { /* A rotated site key must not prevent listing non-secret metadata. */ }
62
+ }
63
+ return accessTokenHint;
64
+ }
65
+ export async function toView(record, ports, sealer) {
66
+ const envTokenHints = await externalMcpEnvHints({ record, sealer, ports });
67
+ const accessTokenHint = await externalMcpAccessTokenHint({ record, sealer, ports });
68
+ return {
69
+ serverId: record.serverId,
70
+ label: record.label ?? record.serverId,
71
+ provisionedByPluginId: record.provisionedByPluginId,
72
+ transport: record.transport,
73
+ authMode: resolveExternalMcpAuthMode(record),
74
+ enabled: record.enabled,
75
+ command: record.command ?? "",
76
+ url: record.url,
77
+ args: parseExternalMcpJsonArray({ raw: record.args }),
78
+ allowedToolNames: parseExternalMcpJsonArray({ raw: record.allowedToolNames }),
79
+ writeAllowedToolNames: parseExternalMcpJsonArray({ raw: record.writeAllowedToolNames }),
80
+ writeGrantsUpdatedByPrincipalId: record.writeGrantsUpdatedByPrincipalId,
81
+ writeGrantsUpdatedAt: record.writeGrantsUpdatedAt,
82
+ envNames: parseExternalMcpJsonArray({ raw: record.envNames }),
83
+ hasAccessToken: externalMcpRecordHasStaticAccessToken(record),
84
+ accessTokenHint,
85
+ ...(Object.keys(envTokenHints).length ? { envTokenHints } : {}),
86
+ accessTokenEnvName: resolveExternalMcpAuthMode(record) === "static_env" ? record.oauthTokenEnvName : null,
87
+ oauth: {
88
+ providerId: record.oauthProviderId,
89
+ grant: record.oauthGrant,
90
+ clientId: record.oauthClientId,
91
+ scopes: parseExternalMcpJsonArray({ raw: record.oauthScopesJson }),
92
+ status: resolveExternalMcpOAuthStatus(record),
93
+ expiresAt: record.oauthExpiresAt,
94
+ tokenEnvName: record.oauthTokenEnvName,
95
+ hasStoredToken: externalMcpRecordHasStoredToken(record),
96
+ },
97
+ version: record.version,
98
+ };
99
+ }
100
+ /**
101
+ * Lists the workspace's servers for the admin tab. The tab has no use for env
102
+ * values and must not be a route that decrypts them. Token hints alone are now derived by
103
+ * server-side unsealing, per the owner decision; no secret value is returned.
104
+ *
105
+ * @complexity O(n) in the stored server count.
106
+ * @overallScore 100
107
+ */
108
+ export async function listExternalMcpServerViews({ deps, workspaceId }, _optional = {}) {
109
+ const records = await deps.repo.listByWorkspaceId(workspaceId);
110
+ return Promise.all(records.map(record => toView(record, deps, deps.sealer)));
111
+ }
112
+ //# sourceMappingURL=store-view.js.map