@usemcpkit/core 0.1.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +191 -0
- package/build/mcpkit.core.d.ts +98 -22
- package/build/mcpkit.core.js +702 -171
- package/package.json +2 -2
package/build/mcpkit.core.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
1
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { createHash, randomBytes } from "node:crypto";
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
6
7
|
//#region src/auth/auth-error.ts
|
|
7
8
|
var AuthError = class extends Error {};
|
|
8
9
|
//#endregion
|
|
@@ -24,6 +25,16 @@ var CREDENTIALS_REQUEST_ELEMENT_ID = "mcpkit-request";
|
|
|
24
25
|
var CREDENTIALS_FORM_SESSION_HEADER = "X-Mcpkit-Session";
|
|
25
26
|
var CONFIG_FILE_NAME = "config.json";
|
|
26
27
|
var SECRETS_FILE_NAME = "secrets.json";
|
|
28
|
+
/** The host key of a server that has no domain, so its credentials still live under `hosts`. */
|
|
29
|
+
var DEFAULT_HOST_KEY = "default";
|
|
30
|
+
var GIT_COMMAND_TIMEOUT_MS = 3e3;
|
|
31
|
+
/** The category of the servers that existed before the config grouped them by category. */
|
|
32
|
+
var LEGACY_SERVER_CATEGORIES = {
|
|
33
|
+
confluence: "atlassian",
|
|
34
|
+
jira: "atlassian",
|
|
35
|
+
github: "git",
|
|
36
|
+
gitlab: "git"
|
|
37
|
+
};
|
|
27
38
|
//#endregion
|
|
28
39
|
//#region src/manifest/auth/describe-auth-type.ts
|
|
29
40
|
var describeAuthType = (auth) => auth.type === "oauth" ? "oauth pkce" : auth.type;
|
|
@@ -59,6 +70,8 @@ var isInteractiveAuth = (auth) => auth.type === "oauth";
|
|
|
59
70
|
//#endregion
|
|
60
71
|
//#region src/manifest/const.ts
|
|
61
72
|
var SERVER_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
73
|
+
/** `resource:action`, for example `pull_request:list`; the action part is optional. */
|
|
74
|
+
var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]*(:[a-z][a-z0-9_]*)*$/;
|
|
62
75
|
var SERVER_CATEGORY_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
63
76
|
var HTTP_METHODS = [
|
|
64
77
|
"GET",
|
|
@@ -124,6 +137,10 @@ var applyDomain = (manifest, domain) => {
|
|
|
124
137
|
return {
|
|
125
138
|
...manifest,
|
|
126
139
|
baseUrl: fillDomain(manifest.baseUrl, domain),
|
|
140
|
+
upstream: manifest.upstream?.type === "http" ? {
|
|
141
|
+
...manifest.upstream,
|
|
142
|
+
url: fillDomain(manifest.upstream.url, domain)
|
|
143
|
+
} : manifest.upstream,
|
|
127
144
|
auth: manifest.auth?.map((auth) => applyAuthDomain(auth, domain)),
|
|
128
145
|
tools: manifest.tools.map((tool) => applyToolEdition(tool, editionName))
|
|
129
146
|
};
|
|
@@ -136,7 +153,7 @@ var isDomainValue = (value) => typeof value === "string" && DOMAIN_VALUE_PATTERN
|
|
|
136
153
|
var isJsonObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
137
154
|
//#endregion
|
|
138
155
|
//#region src/json/is-string-record.ts
|
|
139
|
-
var isStringRecord = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
156
|
+
var isStringRecord$1 = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
140
157
|
//#endregion
|
|
141
158
|
//#region src/manifest/validation/guards/is-interactive-auth-type.ts
|
|
142
159
|
var isInteractiveAuthType = (type) => INTERACTIVE_AUTH_TYPES.some((interactiveType) => interactiveType === type);
|
|
@@ -166,10 +183,12 @@ var DEFAULT_UI_TEXTS = {
|
|
|
166
183
|
brand: "mcpkit",
|
|
167
184
|
pageTitle: "mcpkit · Connect",
|
|
168
185
|
title: "Connect {server}",
|
|
169
|
-
intro: "A tool call needs access to {server}. What you enter is saved in ~/.mcpkit/
|
|
186
|
+
intro: "A tool call needs access to {server}. What you enter is saved in ~/.mcpkit/config.json and used for later calls.",
|
|
170
187
|
domainLabel: "Domain",
|
|
171
188
|
domainHint: "Host, optionally with a port and path, without https://",
|
|
172
189
|
domainPlaceholder: "api.example.com",
|
|
190
|
+
domainNewHost: "New host, saved with its own credentials.",
|
|
191
|
+
domainShowHosts: "Show saved hosts",
|
|
173
192
|
signInLabel: "Sign in with OAuth2",
|
|
174
193
|
tokenDivider: "or use an access token",
|
|
175
194
|
credentialLegend: "Credential",
|
|
@@ -184,7 +203,7 @@ var DEFAULT_UI_TEXTS = {
|
|
|
184
203
|
submit: "Save and continue",
|
|
185
204
|
requiredField: "{label} is required",
|
|
186
205
|
savedTitle: "{server} is connected",
|
|
187
|
-
savedBody: "The credentials are saved in ~/.mcpkit/
|
|
206
|
+
savedBody: "The credentials are saved in ~/.mcpkit/config.json. This tab closes by itself in a few seconds; you can also close it and go back to your MCP client.",
|
|
188
207
|
signingInTitle: "Continue in the new tab",
|
|
189
208
|
signingInBody: "Approve access to {server} in the sign-in tab that just opened. You can close this one.",
|
|
190
209
|
cancelledTitle: "Cancelled",
|
|
@@ -316,6 +335,7 @@ var validateOAuthFields = (auth, location) => {
|
|
|
316
335
|
if (!isHttpsUrl(auth.authorizationUrl)) errors.push(`${location}.authorizationUrl must be an https:// URL`);
|
|
317
336
|
if (!isHttpsUrl(auth.tokenUrl)) errors.push(`${location}.tokenUrl must be an https:// URL`);
|
|
318
337
|
if (auth.clientSecretEnv !== void 0 && typeof auth.clientSecretEnv !== "string") errors.push(`${location}.clientSecretEnv must be a string`);
|
|
338
|
+
if (auth.clientAuthentication !== void 0 && auth.clientAuthentication !== "body" && auth.clientAuthentication !== "basic") errors.push(`${location}.clientAuthentication must be "body" or "basic"`);
|
|
319
339
|
return [...errors, ...validateSignInFields(auth, location)];
|
|
320
340
|
};
|
|
321
341
|
//#endregion
|
|
@@ -358,6 +378,7 @@ var validateDomainSpec = (manifest) => {
|
|
|
358
378
|
"hint",
|
|
359
379
|
"placeholder"
|
|
360
380
|
]) if (domain[key] !== void 0 && typeof domain[key] !== "string") errors.push(`domain.${key} must be a string`);
|
|
381
|
+
if (domain.matchGitRemote !== void 0 && typeof domain.matchGitRemote !== "boolean") errors.push("domain.matchGitRemote must be a boolean");
|
|
361
382
|
return errors;
|
|
362
383
|
};
|
|
363
384
|
//#endregion
|
|
@@ -383,7 +404,20 @@ var validateServerFields = (manifest) => {
|
|
|
383
404
|
if (!SERVER_CATEGORY_PATTERN.test(String(manifest.category ?? ""))) errors.push(`category must match ${SERVER_CATEGORY_PATTERN}`);
|
|
384
405
|
if (typeof manifest.version !== "string") errors.push("version is required");
|
|
385
406
|
if (!isBaseUrl(manifest.baseUrl)) errors.push("baseUrl must be an https:// URL");
|
|
386
|
-
if (manifest.headers !== void 0 && !isStringRecord(manifest.headers)) errors.push("headers must be an object of strings");
|
|
407
|
+
if (manifest.headers !== void 0 && !isStringRecord$1(manifest.headers)) errors.push("headers must be an object of strings");
|
|
408
|
+
return errors;
|
|
409
|
+
};
|
|
410
|
+
//#endregion
|
|
411
|
+
//#region src/manifest/validation/server/validate-upstream.ts
|
|
412
|
+
var PROGRAM_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
413
|
+
var validateUpstream = (upstream) => {
|
|
414
|
+
if (!isJsonObject(upstream)) return ["upstream must be an object"];
|
|
415
|
+
if (upstream.type === "http") return isHttpsUrl(upstream.url) ? [] : ["upstream.url must be an https:// URL"];
|
|
416
|
+
if (upstream.type !== "stdio") return ["upstream.type must be \"http\" or \"stdio\""];
|
|
417
|
+
const errors = [];
|
|
418
|
+
if (typeof upstream.command !== "string" || !PROGRAM_NAME_PATTERN.test(upstream.command)) errors.push("upstream.command must be a program name on PATH, not a path");
|
|
419
|
+
if (upstream.args !== void 0 && !isStringList(upstream.args)) errors.push("upstream.args must be a list of strings");
|
|
420
|
+
if (upstream.forwardEnv !== void 0 && !isStringList(upstream.forwardEnv)) errors.push("upstream.forwardEnv must be a list of strings");
|
|
387
421
|
return errors;
|
|
388
422
|
};
|
|
389
423
|
//#endregion
|
|
@@ -401,7 +435,7 @@ var isHttpMethod = (value) => HTTP_METHODS.some((method) => method === value);
|
|
|
401
435
|
//#region src/manifest/validation/tool/read-arg-names.ts
|
|
402
436
|
var readArgNames = (spec) => {
|
|
403
437
|
if (isStringList(spec)) return spec;
|
|
404
|
-
if (isStringRecord(spec)) return Object.values(spec);
|
|
438
|
+
if (isStringRecord$1(spec)) return Object.values(spec);
|
|
405
439
|
};
|
|
406
440
|
//#endregion
|
|
407
441
|
//#region src/manifest/validation/tool/validate-arg-spec.ts
|
|
@@ -412,6 +446,43 @@ var validateArgSpec = (spec, declaredArgs, location) => {
|
|
|
412
446
|
return names.filter((name) => !declaredArgs.has(name)).map((name) => `${location} uses undeclared arg "${name}"`);
|
|
413
447
|
};
|
|
414
448
|
//#endregion
|
|
449
|
+
//#region src/manifest/validation/tool/validate-body-arg.ts
|
|
450
|
+
var validateBodyArg = (request, declaredArgs, location) => {
|
|
451
|
+
const { bodyArg, body, fixedBody } = request;
|
|
452
|
+
if (bodyArg === void 0) return [];
|
|
453
|
+
if (typeof bodyArg !== "string" || !declaredArgs.has(bodyArg)) return [`${location}.request.bodyArg must name a declared arg`];
|
|
454
|
+
return body !== void 0 || fixedBody !== void 0 ? [`${location}.request.bodyArg cannot be combined with body or fixedBody`] : [];
|
|
455
|
+
};
|
|
456
|
+
//#endregion
|
|
457
|
+
//#region src/manifest/validation/tool/validate-comma-query.ts
|
|
458
|
+
var validateCommaQuery = (keys, location) => {
|
|
459
|
+
if (keys === void 0) return [];
|
|
460
|
+
return Array.isArray(keys) && keys.every((key) => typeof key === "string") ? [] : [`${location} must be an array of strings`];
|
|
461
|
+
};
|
|
462
|
+
//#endregion
|
|
463
|
+
//#region src/manifest/validation/tool/validate-content-type.ts
|
|
464
|
+
var validateContentType = (request, location) => {
|
|
465
|
+
const { contentType, bodyArg } = request;
|
|
466
|
+
if (contentType === void 0) return [];
|
|
467
|
+
if (typeof contentType !== "string" || contentType.trim() === "") return [`${location}.request.contentType must be a non-empty string`];
|
|
468
|
+
if (contentType.startsWith("text/") && bodyArg === void 0) return [`${location}.request.contentType ${contentType} requires bodyArg`];
|
|
469
|
+
return contentType === "multipart/form-data" && bodyArg !== void 0 ? [`${location}.request.contentType ${contentType} cannot be combined with bodyArg`] : [];
|
|
470
|
+
};
|
|
471
|
+
//#endregion
|
|
472
|
+
//#region src/manifest/validation/tool/validate-file-args.ts
|
|
473
|
+
var validateFileArgs = (fileArgs, declaredArgs, location) => {
|
|
474
|
+
if (fileArgs === void 0) return [];
|
|
475
|
+
if (!Array.isArray(fileArgs)) return [`${location} must be an array of argument names`];
|
|
476
|
+
return fileArgs.filter((name) => typeof name !== "string" || !declaredArgs.has(name)).map((name) => `${location} names an undeclared arg: ${String(name)}`);
|
|
477
|
+
};
|
|
478
|
+
//#endregion
|
|
479
|
+
//#region src/manifest/validation/tool/validate-fixed-headers.ts
|
|
480
|
+
var validateFixedHeaders = (headers, location) => {
|
|
481
|
+
if (headers === void 0) return [];
|
|
482
|
+
if (!isJsonObject(headers)) return [`${location} must be an object`];
|
|
483
|
+
return Object.entries(headers).filter(([, value]) => typeof value !== "string").map(([name]) => `${location}.${name} must be a string`);
|
|
484
|
+
};
|
|
485
|
+
//#endregion
|
|
415
486
|
//#region src/manifest/validation/tool/validate-fixed-values.ts
|
|
416
487
|
var validateFixedValues = (values, location) => {
|
|
417
488
|
if (values === void 0) return [];
|
|
@@ -429,6 +500,12 @@ var validateRequestPath = (path, declaredArgs, location) => {
|
|
|
429
500
|
return [...path.matchAll(/\{(\w+)\}/g)].map((match) => match[1] ?? "").filter((name) => !declaredArgs.has(name)).map((name) => `${location}.request.path uses undeclared arg "${name}"`);
|
|
430
501
|
};
|
|
431
502
|
//#endregion
|
|
503
|
+
//#region src/manifest/validation/tool/validate-save-to-arg.ts
|
|
504
|
+
var validateSaveToArg = (saveToArg, declaredArgs, location) => {
|
|
505
|
+
if (saveToArg === void 0) return [];
|
|
506
|
+
return typeof saveToArg === "string" && declaredArgs.has(saveToArg) ? [] : [`${location}.request.saveToArg must name a declared arg`];
|
|
507
|
+
};
|
|
508
|
+
//#endregion
|
|
432
509
|
//#region src/manifest/validation/tool/validate-request.ts
|
|
433
510
|
var validateRequest = (request, declaredArgs, location) => {
|
|
434
511
|
if (!isJsonObject(request)) return [`${location}.request is required`];
|
|
@@ -437,7 +514,13 @@ var validateRequest = (request, declaredArgs, location) => {
|
|
|
437
514
|
...validateRequestPath(request.path, declaredArgs, location),
|
|
438
515
|
...validateArgSpec(request.query, declaredArgs, `${location}.request.query`),
|
|
439
516
|
...validateArgSpec(request.body, declaredArgs, `${location}.request.body`),
|
|
517
|
+
...validateSaveToArg(request.saveToArg, declaredArgs, location),
|
|
518
|
+
...validateFileArgs(request.fileArgs, declaredArgs, `${location}.request.fileArgs`),
|
|
519
|
+
...validateContentType(request, location),
|
|
520
|
+
...validateBodyArg(request, declaredArgs, location),
|
|
440
521
|
...validateFixedValues(request.fixedQuery, `${location}.request.fixedQuery`),
|
|
522
|
+
...validateCommaQuery(request.commaQuery, `${location}.request.commaQuery`),
|
|
523
|
+
...validateFixedHeaders(request.fixedHeaders, `${location}.request.fixedHeaders`),
|
|
441
524
|
...validateFixedValues(request.fixedBody, `${location}.request.fixedBody`)
|
|
442
525
|
];
|
|
443
526
|
};
|
|
@@ -459,7 +542,7 @@ var validateToolEditions = (tool, declaredArgs, editionNames, location) => {
|
|
|
459
542
|
//#region src/manifest/validation/tool/validate-tool-fields.ts
|
|
460
543
|
var validateToolFields = (tool, location) => {
|
|
461
544
|
const errors = [];
|
|
462
|
-
if (!
|
|
545
|
+
if (!TOOL_NAME_PATTERN.test(String(tool.name ?? ""))) errors.push(`${location}.name must match ${TOOL_NAME_PATTERN}`);
|
|
463
546
|
if (typeof tool.description !== "string") errors.push(`${location}.description is required`);
|
|
464
547
|
if (tool.response !== void 0 && !isJsonObject(tool.response)) errors.push(`${location}.response must be an object`);
|
|
465
548
|
return errors;
|
|
@@ -489,6 +572,9 @@ var validateTools = (tools, editionNames) => {
|
|
|
489
572
|
return [...toolErrors, ...duplicateErrors];
|
|
490
573
|
};
|
|
491
574
|
//#endregion
|
|
575
|
+
//#region src/manifest/validation/tool/validate-upstream-tools.ts
|
|
576
|
+
var validateUpstreamTools = (tools) => Array.isArray(tools) && tools.length === 0 ? [] : ["tools must be empty when the manifest has an upstream"];
|
|
577
|
+
//#endregion
|
|
492
578
|
//#region src/manifest/validation/ui/validate-ui-texts.ts
|
|
493
579
|
var KNOWN_TEXT_KEYS = UI_TEXT_KEYS;
|
|
494
580
|
var validateUiTexts = (texts, location) => {
|
|
@@ -513,13 +599,14 @@ var validateServerUi = (manifest) => {
|
|
|
513
599
|
var validateManifest = (manifest) => {
|
|
514
600
|
if (!isJsonObject(manifest)) return ["manifest must be a JSON object"];
|
|
515
601
|
const editionNames = new Set(isJsonObject(manifest.editions) ? Object.keys(manifest.editions) : []);
|
|
602
|
+
const toolErrors = manifest.upstream === void 0 ? validateTools(manifest.tools, editionNames) : [...validateUpstream(manifest.upstream), ...validateUpstreamTools(manifest.tools)];
|
|
516
603
|
return [
|
|
517
604
|
...validateServerFields(manifest),
|
|
518
605
|
...validateDomainSpec(manifest),
|
|
519
606
|
...validateEditions(manifest.editions),
|
|
520
607
|
...validateAuth(manifest.auth, manifest.domain !== void 0),
|
|
521
608
|
...validateServerUi(manifest),
|
|
522
|
-
...
|
|
609
|
+
...toolErrors
|
|
523
610
|
];
|
|
524
611
|
};
|
|
525
612
|
//#endregion
|
|
@@ -539,12 +626,78 @@ var toNameMapping = (spec) => {
|
|
|
539
626
|
/** Replaces `{name}` with its value; a placeholder without a value stays as it is. */
|
|
540
627
|
var fillTemplate = (template, values) => template.replace(UI_PLACEHOLDER_PATTERN, (placeholder, name) => values[name] ?? placeholder);
|
|
541
628
|
//#endregion
|
|
542
|
-
//#region src/auth/
|
|
543
|
-
|
|
629
|
+
//#region src/auth/config/list-known-hosts.ts
|
|
630
|
+
/** The hosts a server has been used with: those with saved settings. */
|
|
631
|
+
var listKnownHosts = (server) => Object.keys(server?.hosts ?? {});
|
|
632
|
+
//#endregion
|
|
633
|
+
//#region src/auth/secret-file/merge-legacy-secrets.ts
|
|
634
|
+
/** Adds the credentials of the old secrets file under the host the server uses; a value already in the config wins. */
|
|
635
|
+
var mergeLegacySecrets = (config, legacy) => {
|
|
636
|
+
const servers = { ...config.servers };
|
|
637
|
+
for (const [name, secrets] of Object.entries(legacy)) {
|
|
638
|
+
const category = LEGACY_SERVER_CATEGORIES[name] ?? "other";
|
|
639
|
+
const server = servers[category]?.[name] ?? {};
|
|
640
|
+
const known = listKnownHosts(server);
|
|
641
|
+
const [onlyHost] = known;
|
|
642
|
+
const host = known.length === 1 && onlyHost !== void 0 ? onlyHost : DEFAULT_HOST_KEY;
|
|
643
|
+
servers[category] = {
|
|
644
|
+
...servers[category],
|
|
645
|
+
[name]: {
|
|
646
|
+
...server,
|
|
647
|
+
hosts: {
|
|
648
|
+
...server.hosts,
|
|
649
|
+
[host]: {
|
|
650
|
+
...server.hosts?.[host],
|
|
651
|
+
secrets: {
|
|
652
|
+
...secrets,
|
|
653
|
+
...server.hosts?.[host]?.secrets
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
return {
|
|
661
|
+
...config,
|
|
662
|
+
servers
|
|
663
|
+
};
|
|
664
|
+
};
|
|
544
665
|
//#endregion
|
|
545
|
-
//#region src/
|
|
546
|
-
|
|
547
|
-
|
|
666
|
+
//#region src/errors/describe-error.ts
|
|
667
|
+
var describeError = (error) => error instanceof Error ? error.message : String(error);
|
|
668
|
+
//#endregion
|
|
669
|
+
//#region src/errors/is-missing-file-error.ts
|
|
670
|
+
var isMissingFileError = (error) => error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
671
|
+
//#endregion
|
|
672
|
+
//#region src/auth/token-store/read-tokens-text.ts
|
|
673
|
+
var readTokensText = async (file) => {
|
|
674
|
+
try {
|
|
675
|
+
return await readFile(file, "utf8");
|
|
676
|
+
} catch (error) {
|
|
677
|
+
if (isMissingFileError(error)) return;
|
|
678
|
+
throw error;
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
//#endregion
|
|
682
|
+
//#region src/auth/secret-file/is-stored-secrets.ts
|
|
683
|
+
var isServerSecrets = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
684
|
+
var isStoredSecrets = (value) => isJsonObject(value) && Object.values(value).every(isServerSecrets);
|
|
685
|
+
//#endregion
|
|
686
|
+
//#region src/auth/secret-file/read-stored-secrets.ts
|
|
687
|
+
/** A missing file means nothing is saved; a malformed one fails instead of being overwritten. */
|
|
688
|
+
var readStoredSecrets = async (file) => {
|
|
689
|
+
const text = await readTokensText(file);
|
|
690
|
+
if (text === void 0) return {};
|
|
691
|
+
const data = JSON.parse(text);
|
|
692
|
+
if (!isStoredSecrets(data)) throw new AuthError(`${file} is not a valid mcpkit secrets file`);
|
|
693
|
+
return data;
|
|
694
|
+
};
|
|
695
|
+
//#endregion
|
|
696
|
+
//#region src/home/resolve-home-dir.ts
|
|
697
|
+
var resolveHomeDir = (env = process.env) => env.MCPKIT_HOME ?? join(homedir(), ".mcpkit");
|
|
698
|
+
//#endregion
|
|
699
|
+
//#region src/auth/secret-file/resolve-secrets-file.ts
|
|
700
|
+
var resolveSecretsFile = (env) => join(resolveHomeDir(env), SECRETS_FILE_NAME);
|
|
548
701
|
//#endregion
|
|
549
702
|
//#region src/auth/secrets/write-json-file.ts
|
|
550
703
|
/** Writes through a temp file and rename so a crash never leaves a half-written file. */
|
|
@@ -557,32 +710,195 @@ var writeJsonFile = async (file, value) => {
|
|
|
557
710
|
await writeFile(tempFile, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
|
|
558
711
|
await rename(tempFile, file);
|
|
559
712
|
};
|
|
713
|
+
/** Data without a `version` is the first version. */
|
|
714
|
+
var readVersion = (data) => isJsonObject(data) && data.version !== void 0 ? data.version : 1;
|
|
560
715
|
//#endregion
|
|
561
|
-
//#region src/
|
|
562
|
-
|
|
716
|
+
//#region src/migrations/migrate-data.ts
|
|
717
|
+
/**
|
|
718
|
+
* Runs the migrations from the data's version up to the latest, which is `migrations.length + 1`, and stamps it.
|
|
719
|
+
* Adding a version means appending one migration to the list; nothing else changes. Data from a newer version throws
|
|
720
|
+
* instead of being rewritten.
|
|
721
|
+
*/
|
|
722
|
+
var migrateData = (data, migrations) => {
|
|
723
|
+
const latest = 1 + migrations.length;
|
|
724
|
+
const version = readVersion(data);
|
|
725
|
+
if (!isJsonObject(data) || typeof version !== "number" || !Number.isInteger(version) || version < 1) throw new Error("is not valid versioned data");
|
|
726
|
+
if (version > latest) throw new Error(`is version ${version}; this mcpkit reads up to version ${latest}, update mcpkit`);
|
|
727
|
+
return {
|
|
728
|
+
...migrations.slice(version - 1).reduce((current, migrate) => migrate(current), data),
|
|
729
|
+
version: latest
|
|
730
|
+
};
|
|
731
|
+
};
|
|
563
732
|
//#endregion
|
|
564
|
-
//#region src/auth/
|
|
565
|
-
|
|
733
|
+
//#region src/auth/config/migrations/drop-last-used-domain.ts
|
|
734
|
+
/** 2 → 3: the last used `domain` is dropped, the hosts it was kept in already list it. */
|
|
735
|
+
var dropLastUsedDomain = (server) => {
|
|
736
|
+
const { domain, ...rest } = server;
|
|
737
|
+
if (typeof domain !== "string") return rest;
|
|
738
|
+
const hosts = isJsonObject(rest.hosts) ? rest.hosts : {};
|
|
739
|
+
return {
|
|
740
|
+
...rest,
|
|
741
|
+
hosts: {
|
|
742
|
+
[domain]: {},
|
|
743
|
+
...hosts
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
};
|
|
566
747
|
//#endregion
|
|
567
|
-
//#region src/auth/
|
|
568
|
-
var
|
|
748
|
+
//#region src/auth/config/migrations/group-servers.ts
|
|
749
|
+
var groupServers = (toGroup) => (data) => {
|
|
750
|
+
if (!isJsonObject(data.servers)) return { ...data };
|
|
751
|
+
const grouped = {};
|
|
752
|
+
for (const [name, server] of Object.entries(data.servers)) {
|
|
753
|
+
const group = toGroup(name);
|
|
754
|
+
grouped[group] = {
|
|
755
|
+
...grouped[group],
|
|
756
|
+
[name]: server
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
return {
|
|
760
|
+
...data,
|
|
761
|
+
servers: grouped
|
|
762
|
+
};
|
|
763
|
+
};
|
|
569
764
|
//#endregion
|
|
570
|
-
//#region src/
|
|
571
|
-
var
|
|
765
|
+
//#region src/auth/config/migrations/migrate-servers.ts
|
|
766
|
+
var migrateServers = (migrateServer) => (data) => {
|
|
767
|
+
if (!isJsonObject(data.servers)) return { ...data };
|
|
768
|
+
const servers = Object.entries(data.servers).map(([name, server]) => [name, isJsonObject(server) ? migrateServer(server) : server]);
|
|
769
|
+
return {
|
|
770
|
+
...data,
|
|
771
|
+
servers: Object.fromEntries(servers)
|
|
772
|
+
};
|
|
773
|
+
};
|
|
572
774
|
//#endregion
|
|
573
|
-
//#region src/
|
|
574
|
-
|
|
775
|
+
//#region src/auth/config/migrations/move-secrets-under-host.ts
|
|
776
|
+
/** 1 → 2: a server's `secrets` move under the host of its domain, and the domain itself becomes a known host. */
|
|
777
|
+
var moveSecretsUnderHost = (server) => {
|
|
778
|
+
const { secrets, ...rest } = server;
|
|
779
|
+
const domain = typeof rest.domain === "string" ? rest.domain : void 0;
|
|
780
|
+
const hosts = {
|
|
781
|
+
...domain === void 0 ? {} : { [domain]: {} },
|
|
782
|
+
...isJsonObject(rest.hosts) ? rest.hosts : {}
|
|
783
|
+
};
|
|
784
|
+
const host = domain ?? "default";
|
|
785
|
+
if (isJsonObject(secrets)) {
|
|
786
|
+
const current = isJsonObject(hosts[host]) ? hosts[host] : {};
|
|
787
|
+
const currentSecrets = isJsonObject(current.secrets) ? current.secrets : {};
|
|
788
|
+
hosts[host] = {
|
|
789
|
+
...current,
|
|
790
|
+
secrets: {
|
|
791
|
+
...secrets,
|
|
792
|
+
...currentSecrets
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
return Object.keys(hosts).length === 0 ? rest : {
|
|
797
|
+
...rest,
|
|
798
|
+
hosts
|
|
799
|
+
};
|
|
800
|
+
};
|
|
575
801
|
//#endregion
|
|
576
|
-
//#region src/auth/
|
|
577
|
-
|
|
802
|
+
//#region src/auth/config/migrations/to-legacy-category.ts
|
|
803
|
+
/** 3 → 4: `servers.<name>` becomes `servers.<category>.<name>`. */
|
|
804
|
+
var toLegacyCategory = (name) => LEGACY_SERVER_CATEGORIES[name] ?? "other";
|
|
805
|
+
//#endregion
|
|
806
|
+
//#region src/auth/config/config-migrations.ts
|
|
807
|
+
/** One entry per version bump, in order; the version of the config file is the list length plus one. */
|
|
808
|
+
var CONFIG_MIGRATIONS = [
|
|
809
|
+
migrateServers(moveSecretsUnderHost),
|
|
810
|
+
migrateServers(dropLastUsedDomain),
|
|
811
|
+
groupServers(toLegacyCategory)
|
|
812
|
+
];
|
|
813
|
+
var CONFIG_VERSION = CONFIG_MIGRATIONS.length + 1;
|
|
814
|
+
//#endregion
|
|
815
|
+
//#region src/auth/config/resolve-config-file.ts
|
|
816
|
+
var resolveConfigFile = (env) => join(resolveHomeDir(env), CONFIG_FILE_NAME);
|
|
817
|
+
//#endregion
|
|
818
|
+
//#region src/auth/config/needs-migration.ts
|
|
819
|
+
/** True when the config file is an older version or the old `secrets.json` is still there. */
|
|
820
|
+
var needsMigration = async (env) => {
|
|
821
|
+
if (await readTokensText(resolveSecretsFile(env)) !== void 0) return true;
|
|
822
|
+
const text = await readTokensText(resolveConfigFile(env));
|
|
823
|
+
return text !== void 0 && readVersion(JSON.parse(text)) !== CONFIG_VERSION;
|
|
824
|
+
};
|
|
825
|
+
//#endregion
|
|
826
|
+
//#region src/auth/config/is-mcpkit-config.ts
|
|
827
|
+
var isStringRecord = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
828
|
+
var isHostConfig = (value) => isJsonObject(value) && (value.secrets === void 0 || isStringRecord(value.secrets));
|
|
829
|
+
var isServerConfig = (value) => isJsonObject(value) && (value.hosts === void 0 || isJsonObject(value.hosts) && Object.values(value.hosts).every(isHostConfig)) && (value.projects === void 0 || isStringRecord(value.projects));
|
|
830
|
+
var isMcpkitConfig = (value) => isJsonObject(value) && value.version === CONFIG_VERSION && (value.servers === void 0 || isJsonObject(value.servers) && Object.values(value.servers).every((group) => isJsonObject(group) && Object.values(group).every(isServerConfig)));
|
|
831
|
+
//#endregion
|
|
832
|
+
//#region src/auth/config/read-config.ts
|
|
833
|
+
/**
|
|
834
|
+
* A missing file means no settings; an older version is migrated in memory (writing happens on the next save);
|
|
835
|
+
* a malformed file or one from a newer mcpkit fails instead of being overwritten.
|
|
836
|
+
*/
|
|
837
|
+
var readConfig = async (file) => {
|
|
838
|
+
const text = await readTokensText(file);
|
|
839
|
+
if (text === void 0) return { version: CONFIG_VERSION };
|
|
840
|
+
let migrated;
|
|
578
841
|
try {
|
|
579
|
-
|
|
842
|
+
migrated = migrateData(JSON.parse(text), CONFIG_MIGRATIONS);
|
|
580
843
|
} catch (error) {
|
|
581
|
-
|
|
582
|
-
throw error;
|
|
844
|
+
throw new AuthError(`${file} ${error instanceof Error ? error.message : "is not a valid mcpkit config file"}`);
|
|
583
845
|
}
|
|
846
|
+
if (!isMcpkitConfig(migrated)) throw new AuthError(`${file} is not a valid mcpkit config file`);
|
|
847
|
+
return migrated;
|
|
848
|
+
};
|
|
849
|
+
//#endregion
|
|
850
|
+
//#region src/auth/config/migrate-config.ts
|
|
851
|
+
/** Writes the config in the current version and folds in the old `secrets.json`, then removes it. Call it under the config lock. */
|
|
852
|
+
var migrateConfig = async (env) => {
|
|
853
|
+
if (!await needsMigration(env)) return;
|
|
854
|
+
const configFile = resolveConfigFile(env);
|
|
855
|
+
const legacyFile = resolveSecretsFile(env);
|
|
856
|
+
const config = await readConfig(configFile);
|
|
857
|
+
const legacy = await readTokensText(legacyFile) === void 0 ? void 0 : await readStoredSecrets(legacyFile);
|
|
858
|
+
await writeJsonFile(configFile, legacy ? mergeLegacySecrets(config, legacy) : config);
|
|
859
|
+
if (legacy) await rm(legacyFile);
|
|
860
|
+
};
|
|
861
|
+
//#endregion
|
|
862
|
+
//#region src/auth/secret-file/create-exclusive-runner.ts
|
|
863
|
+
/** Runs tasks one at a time, so read-modify-write cycles on one file never lose each other's changes. */
|
|
864
|
+
var createExclusiveRunner = () => {
|
|
865
|
+
let pending = Promise.resolve();
|
|
866
|
+
return (task) => {
|
|
867
|
+
const run = pending.then(task);
|
|
868
|
+
pending = run.catch(() => void 0);
|
|
869
|
+
return run;
|
|
870
|
+
};
|
|
584
871
|
};
|
|
585
872
|
//#endregion
|
|
873
|
+
//#region src/auth/config/run-config-exclusive.ts
|
|
874
|
+
var runConfigExclusive = createExclusiveRunner();
|
|
875
|
+
//#endregion
|
|
876
|
+
//#region src/auth/config/load-config.ts
|
|
877
|
+
/** Reads the config, first migrating an older file or an old `secrets.json` to the current version. */
|
|
878
|
+
var loadConfig = async (env) => {
|
|
879
|
+
if (await needsMigration(env)) await runConfigExclusive(() => migrateConfig(env));
|
|
880
|
+
return readConfig(resolveConfigFile(env));
|
|
881
|
+
};
|
|
882
|
+
//#endregion
|
|
883
|
+
//#region src/auth/config/read-server-config.ts
|
|
884
|
+
var readServerConfig = (config, server) => config.servers?.[server.category]?.[server.name];
|
|
885
|
+
//#endregion
|
|
886
|
+
//#region src/auth/secrets/to-auth-key.ts
|
|
887
|
+
var toAuthKey = (auth) => `oauth ${auth.tokenUrl}`;
|
|
888
|
+
//#endregion
|
|
889
|
+
//#region src/auth/oauth/sign-in/pending-sign-ins.ts
|
|
890
|
+
/** Concurrent tool calls for one server and auth entry share a single browser sign-in. */
|
|
891
|
+
var pendingSignIns = /* @__PURE__ */ new Map();
|
|
892
|
+
//#endregion
|
|
893
|
+
//#region src/auth/token-store/is-optional-of-type.ts
|
|
894
|
+
var isOptionalOfType = (value, type) => value === void 0 || typeof value === type;
|
|
895
|
+
//#endregion
|
|
896
|
+
//#region src/auth/token-store/is-stored-token.ts
|
|
897
|
+
var isStoredToken = (value) => isJsonObject(value) && typeof value.accessToken === "string" && typeof value.tokenType === "string" && isOptionalOfType(value.refreshToken, "string") && isOptionalOfType(value.expiresAt, "number") && isOptionalOfType(value.scope, "string") && isOptionalOfType(value.authKey, "string");
|
|
898
|
+
//#endregion
|
|
899
|
+
//#region src/auth/token-store/is-stored-tokens.ts
|
|
900
|
+
var isStoredTokens = (value) => isJsonObject(value) && Object.values(value).every(isStoredToken);
|
|
901
|
+
//#endregion
|
|
586
902
|
//#region src/auth/token-store/read-tokens.ts
|
|
587
903
|
/** A missing file means no sessions; a malformed one fails instead of being overwritten. */
|
|
588
904
|
var readTokens = async (file) => {
|
|
@@ -593,9 +909,6 @@ var readTokens = async (file) => {
|
|
|
593
909
|
return data;
|
|
594
910
|
};
|
|
595
911
|
//#endregion
|
|
596
|
-
//#region src/home/resolve-home-dir.ts
|
|
597
|
-
var resolveHomeDir = (env = process.env) => env.MCPKIT_HOME ?? join(homedir(), ".mcpkit");
|
|
598
|
-
//#endregion
|
|
599
912
|
//#region src/auth/token-store/resolve-tokens-file.ts
|
|
600
913
|
var resolveTokensFile = (env) => join(resolveHomeDir(env), TOKENS_FILE_NAME);
|
|
601
914
|
//#endregion
|
|
@@ -612,6 +925,7 @@ var saveToken = async (env, serverName, token) => {
|
|
|
612
925
|
//#region src/auth/oauth/pkce/build-authorization-url.ts
|
|
613
926
|
var buildAuthorizationUrl = (auth, { redirectUri, challenge, state }) => {
|
|
614
927
|
const url = new URL(auth.authorizationUrl);
|
|
928
|
+
for (const [name, value] of Object.entries(auth.authorizationParams ?? {})) url.searchParams.set(name, value);
|
|
615
929
|
url.searchParams.set("response_type", "code");
|
|
616
930
|
url.searchParams.set("client_id", auth.clientId);
|
|
617
931
|
url.searchParams.set("redirect_uri", redirectUri);
|
|
@@ -669,18 +983,22 @@ var readJsonBody = async (response, serverName) => {
|
|
|
669
983
|
//#endregion
|
|
670
984
|
//#region src/auth/oauth/sign-in/request-token.ts
|
|
671
985
|
var requestToken = async (auth, grant, serverName, { env, fetchImpl }) => {
|
|
672
|
-
const
|
|
986
|
+
const secret = auth.clientSecretEnv ? readSecret(env, auth.clientSecretEnv, serverName) : void 0;
|
|
987
|
+
const headers = {
|
|
988
|
+
Accept: "application/json",
|
|
989
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
990
|
+
...auth.tokenHeaders
|
|
991
|
+
};
|
|
992
|
+
const body = new URLSearchParams(grant);
|
|
993
|
+
if (auth.clientAuthentication === "basic") headers.Authorization = `Basic ${Buffer.from(`${auth.clientId}:${secret ?? ""}`).toString("base64")}`;
|
|
994
|
+
else {
|
|
995
|
+
body.set("client_id", auth.clientId);
|
|
996
|
+
if (secret !== void 0) body.set("client_secret", secret);
|
|
997
|
+
}
|
|
673
998
|
const response = await fetchImpl(auth.tokenUrl, {
|
|
674
999
|
method: "POST",
|
|
675
|
-
headers
|
|
676
|
-
|
|
677
|
-
"Content-Type": "application/x-www-form-urlencoded"
|
|
678
|
-
},
|
|
679
|
-
body: new URLSearchParams({
|
|
680
|
-
...grant,
|
|
681
|
-
client_id: auth.clientId,
|
|
682
|
-
...clientSecret
|
|
683
|
-
}),
|
|
1000
|
+
headers,
|
|
1001
|
+
body,
|
|
684
1002
|
signal: AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS)
|
|
685
1003
|
});
|
|
686
1004
|
return parseTokenResponse(await readJsonBody(response, serverName), response.status, serverName, Date.now());
|
|
@@ -813,38 +1131,75 @@ var resolveSignedInAuth = async (serverName, auth, context) => {
|
|
|
813
1131
|
return createResolvedAuth({ Authorization: `Bearer ${token.accessToken}` });
|
|
814
1132
|
};
|
|
815
1133
|
//#endregion
|
|
816
|
-
//#region src/auth/config/
|
|
817
|
-
|
|
818
|
-
var
|
|
819
|
-
|
|
820
|
-
//#region src/auth/config/read-config.ts
|
|
821
|
-
/** A missing file means no settings; a malformed one fails instead of being overwritten. */
|
|
822
|
-
var readConfig = async (file) => {
|
|
823
|
-
const text = await readTokensText(file);
|
|
824
|
-
if (text === void 0) return {};
|
|
825
|
-
const data = JSON.parse(text);
|
|
826
|
-
if (!isMcpkitConfig(data)) throw new AuthError(`${file} is not a valid mcpkit config file`);
|
|
827
|
-
return data;
|
|
828
|
-
};
|
|
829
|
-
//#endregion
|
|
830
|
-
//#region src/auth/config/resolve-config-file.ts
|
|
831
|
-
var resolveConfigFile = (env) => join(resolveHomeDir(env), CONFIG_FILE_NAME);
|
|
832
|
-
//#endregion
|
|
833
|
-
//#region src/auth/config/save-server-domain.ts
|
|
834
|
-
var saveServerDomain = async (env, serverName, domain) => {
|
|
1134
|
+
//#region src/auth/config/update-server-config.ts
|
|
1135
|
+
/** Read-modify-write of one server's entry, serialized so concurrent saves never lose each other's changes. */
|
|
1136
|
+
var updateServerConfig = (env, server, change) => runConfigExclusive(async () => {
|
|
1137
|
+
await migrateConfig(env);
|
|
835
1138
|
const file = resolveConfigFile(env);
|
|
836
1139
|
const config = await readConfig(file);
|
|
837
1140
|
await writeJsonFile(file, {
|
|
838
1141
|
...config,
|
|
839
1142
|
servers: {
|
|
840
1143
|
...config.servers,
|
|
841
|
-
[
|
|
842
|
-
...config.servers?.[
|
|
843
|
-
|
|
1144
|
+
[server.category]: {
|
|
1145
|
+
...config.servers?.[server.category],
|
|
1146
|
+
[server.name]: change(readServerConfig(config, server) ?? {})
|
|
844
1147
|
}
|
|
845
1148
|
}
|
|
846
1149
|
});
|
|
847
1150
|
return file;
|
|
1151
|
+
});
|
|
1152
|
+
//#endregion
|
|
1153
|
+
//#region src/auth/config/save-server-domain.ts
|
|
1154
|
+
/** Makes the host a known host and, with a project, binds the project to it. */
|
|
1155
|
+
var saveServerDomain = (env, server, domain, projectKey) => updateServerConfig(env, server, (current) => ({
|
|
1156
|
+
...current,
|
|
1157
|
+
hosts: {
|
|
1158
|
+
...current.hosts,
|
|
1159
|
+
[domain]: { ...current.hosts?.[domain] }
|
|
1160
|
+
},
|
|
1161
|
+
...projectKey === void 0 ? {} : { projects: {
|
|
1162
|
+
...current.projects,
|
|
1163
|
+
[projectKey]: domain
|
|
1164
|
+
} }
|
|
1165
|
+
}));
|
|
1166
|
+
//#endregion
|
|
1167
|
+
//#region src/auth/project/parse-remote-host.ts
|
|
1168
|
+
var SCP_LIKE_REMOTE = /^(?:[^@/]+@)?([^:/]+):(?!\/\/)/;
|
|
1169
|
+
/** The host of a git remote URL (https, ssh or scp-like `git@host:path`), lowercase and without a port. */
|
|
1170
|
+
var parseRemoteHost = (remote) => {
|
|
1171
|
+
if (remote.includes("://")) try {
|
|
1172
|
+
return new URL(remote).hostname.toLowerCase() || void 0;
|
|
1173
|
+
} catch {
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
return SCP_LIKE_REMOTE.exec(remote)?.[1]?.toLowerCase();
|
|
1177
|
+
};
|
|
1178
|
+
//#endregion
|
|
1179
|
+
//#region src/auth/project/read-git-output.ts
|
|
1180
|
+
/** Trimmed stdout of a git command in `cwd`; undefined when git is missing, `cwd` is not a repository or there is no such setting. */
|
|
1181
|
+
var readGitOutput = (cwd, args) => new Promise((resolve) => {
|
|
1182
|
+
execFile("git", [...args], {
|
|
1183
|
+
cwd,
|
|
1184
|
+
timeout: GIT_COMMAND_TIMEOUT_MS
|
|
1185
|
+
}, (error, stdout) => {
|
|
1186
|
+
resolve(error ? void 0 : stdout.trim() || void 0);
|
|
1187
|
+
});
|
|
1188
|
+
});
|
|
1189
|
+
//#endregion
|
|
1190
|
+
//#region src/auth/project/resolve-project.ts
|
|
1191
|
+
/** The project a call belongs to: its git root (else the directory itself) and the host of its `origin` remote. */
|
|
1192
|
+
var resolveProject = async (directory) => {
|
|
1193
|
+
const root = await readGitOutput(directory, ["rev-parse", "--show-toplevel"]);
|
|
1194
|
+
const remote = root === void 0 ? void 0 : await readGitOutput(root, [
|
|
1195
|
+
"remote",
|
|
1196
|
+
"get-url",
|
|
1197
|
+
"origin"
|
|
1198
|
+
]);
|
|
1199
|
+
return {
|
|
1200
|
+
key: root ?? directory,
|
|
1201
|
+
remoteHost: remote && parseRemoteHost(remote)
|
|
1202
|
+
};
|
|
848
1203
|
};
|
|
849
1204
|
//#endregion
|
|
850
1205
|
//#region src/auth/credentials/resolve/save-credentials.ts
|
|
@@ -854,20 +1209,26 @@ var saveCredentials = async (owner, values, secretStore) => {
|
|
|
854
1209
|
};
|
|
855
1210
|
//#endregion
|
|
856
1211
|
//#region src/auth/credentials/resolve/save-form-answer.ts
|
|
857
|
-
/**
|
|
1212
|
+
/** Credentials go to the secret store under their host; the host is remembered for the project that asked for it. */
|
|
858
1213
|
var saveFormAnswer = async (manifest, values, domain, context) => {
|
|
859
|
-
await saveCredentials(
|
|
860
|
-
|
|
1214
|
+
await saveCredentials({
|
|
1215
|
+
name: manifest.name,
|
|
1216
|
+
category: manifest.category,
|
|
1217
|
+
domain
|
|
1218
|
+
}, values, context.secretStore);
|
|
1219
|
+
if (domain === void 0) return;
|
|
1220
|
+
const project = context.projectDir === void 0 ? void 0 : await resolveProject(context.projectDir);
|
|
1221
|
+
await saveServerDomain(context.env, manifest, domain, project?.key);
|
|
861
1222
|
};
|
|
862
1223
|
//#endregion
|
|
863
1224
|
//#region src/auth/credentials/resolve/resolve-form-sign-in.ts
|
|
864
|
-
var resolveFormSignIn = async (manifest, response, context) => {
|
|
1225
|
+
var resolveFormSignIn = async (manifest, response, domain, context) => {
|
|
865
1226
|
const oauth = manifest.auth?.find(isInteractiveAuth);
|
|
866
1227
|
if (!oauth) throw new AuthError(`${manifest.name}: this server has no sign-in`);
|
|
867
1228
|
return {
|
|
868
1229
|
auth: await resolveSignedInAuth(manifest.name, oauth, context),
|
|
869
1230
|
manifest,
|
|
870
|
-
commit: () => saveFormAnswer(manifest, {},
|
|
1231
|
+
commit: () => saveFormAnswer(manifest, {}, domain, context)
|
|
871
1232
|
};
|
|
872
1233
|
};
|
|
873
1234
|
//#endregion
|
|
@@ -891,14 +1252,14 @@ var resolveStaticAuth = (auth, serverName, env) => {
|
|
|
891
1252
|
var trimValues = (values) => Object.fromEntries(Object.entries(values).map(([key, value]) => [key, value.trim()]));
|
|
892
1253
|
//#endregion
|
|
893
1254
|
//#region src/auth/credentials/resolve/resolve-form-token.ts
|
|
894
|
-
var resolveFormToken = (manifest, response, context) => {
|
|
1255
|
+
var resolveFormToken = (manifest, response, domain, context) => {
|
|
895
1256
|
const auth = manifest.auth?.[response.option];
|
|
896
1257
|
if (!auth || isInteractiveAuth(auth)) throw new AuthError(`${manifest.name}: auth[${response.option}] does not take credentials`);
|
|
897
1258
|
const values = trimValues(response.values);
|
|
898
1259
|
return {
|
|
899
1260
|
auth: resolveStaticAuth(auth, manifest.name, values),
|
|
900
1261
|
manifest,
|
|
901
|
-
commit: () => saveFormAnswer(manifest, values,
|
|
1262
|
+
commit: () => saveFormAnswer(manifest, values, domain, context)
|
|
902
1263
|
};
|
|
903
1264
|
};
|
|
904
1265
|
//#endregion
|
|
@@ -913,7 +1274,7 @@ var validateResponseDomain = (request, domain) => {
|
|
|
913
1274
|
var validateTokenResponse = (request, response) => {
|
|
914
1275
|
const option = request.options.find((candidate) => candidate.index === response.option);
|
|
915
1276
|
if (!option) return ["choose one of the offered credentials"];
|
|
916
|
-
const values = isStringRecord(response.values) ? response.values : {};
|
|
1277
|
+
const values = isStringRecord$1(response.values) ? response.values : {};
|
|
917
1278
|
return option.fields.filter((field) => !values[field.key]?.trim()).map((field) => fillTemplate(request.texts.requiredField, { label: field.label }));
|
|
918
1279
|
};
|
|
919
1280
|
//#endregion
|
|
@@ -941,14 +1302,15 @@ var buildUiTexts = (manifest) => {
|
|
|
941
1302
|
//#endregion
|
|
942
1303
|
//#region src/auth/credentials/request/build-domain-field.ts
|
|
943
1304
|
/** A domain set through its env var is not offered for editing. */
|
|
944
|
-
var buildDomainField = (manifest, domain, env, texts) => {
|
|
1305
|
+
var buildDomainField = (manifest, domain, knownHosts, env, texts) => {
|
|
945
1306
|
const spec = manifest.domain;
|
|
946
1307
|
if (!spec || spec.env && env[spec.env]) return;
|
|
947
1308
|
return {
|
|
948
1309
|
label: spec.label ?? texts.domainLabel,
|
|
949
1310
|
hint: spec.hint ?? texts.domainHint,
|
|
950
1311
|
placeholder: spec.placeholder ?? texts.domainPlaceholder,
|
|
951
|
-
value: domain ?? ""
|
|
1312
|
+
value: domain ?? "",
|
|
1313
|
+
knownHosts
|
|
952
1314
|
};
|
|
953
1315
|
};
|
|
954
1316
|
//#endregion
|
|
@@ -1000,10 +1362,10 @@ var toCredentialOptions = (auth, index, serverName, texts) => {
|
|
|
1000
1362
|
};
|
|
1001
1363
|
//#endregion
|
|
1002
1364
|
//#region src/auth/credentials/request/build-credential-request.ts
|
|
1003
|
-
var buildCredentialRequest = (manifest, domain, env) => {
|
|
1365
|
+
var buildCredentialRequest = (manifest, domain, knownHosts, env) => {
|
|
1004
1366
|
const auth = manifest.auth ?? [];
|
|
1005
1367
|
const texts = buildUiTexts(manifest);
|
|
1006
|
-
const domainField = buildDomainField(manifest, domain, env, texts);
|
|
1368
|
+
const domainField = buildDomainField(manifest, domain, knownHosts, env, texts);
|
|
1007
1369
|
return {
|
|
1008
1370
|
serverName: manifest.name,
|
|
1009
1371
|
texts,
|
|
@@ -1019,14 +1381,18 @@ var buildCredentialRequest = (manifest, domain, env) => {
|
|
|
1019
1381
|
var pendingCredentialRequests = /* @__PURE__ */ new Map();
|
|
1020
1382
|
//#endregion
|
|
1021
1383
|
//#region src/auth/credentials/request/request-credentials-once.ts
|
|
1022
|
-
|
|
1023
|
-
|
|
1384
|
+
/** One form per server at a time; the request is built only by the call that opens it. */
|
|
1385
|
+
var requestCredentialsOnce = (serverName, createRequest, requestCredentials) => {
|
|
1386
|
+
const pending = pendingCredentialRequests.get(serverName);
|
|
1024
1387
|
if (pending) return pending;
|
|
1025
|
-
const
|
|
1026
|
-
|
|
1388
|
+
const exchange = createRequest().then(async (request) => ({
|
|
1389
|
+
request,
|
|
1390
|
+
response: await requestCredentials(request)
|
|
1391
|
+
})).finally(() => {
|
|
1392
|
+
pendingCredentialRequests.delete(serverName);
|
|
1027
1393
|
});
|
|
1028
|
-
pendingCredentialRequests.set(
|
|
1029
|
-
return
|
|
1394
|
+
pendingCredentialRequests.set(serverName, exchange);
|
|
1395
|
+
return exchange;
|
|
1030
1396
|
};
|
|
1031
1397
|
//#endregion
|
|
1032
1398
|
//#region src/auth/credentials/request/resolve-credential-form.ts
|
|
@@ -1034,29 +1400,62 @@ var requestCredentialsOnce = (request, requestCredentials) => {
|
|
|
1034
1400
|
var resolveCredentialForm = async (manifest, domain, context) => {
|
|
1035
1401
|
const { requestCredentials } = context;
|
|
1036
1402
|
if (!requestCredentials) throw new AuthError(`${manifest.name}: asking for credentials needs a form, which this caller does not provide`);
|
|
1037
|
-
const request =
|
|
1038
|
-
|
|
1403
|
+
const { request, response } = await requestCredentialsOnce(manifest.name, async () => {
|
|
1404
|
+
return buildCredentialRequest(manifest, domain, listKnownHosts(readServerConfig(await loadConfig(context.env), manifest)), context.env);
|
|
1405
|
+
}, requestCredentials);
|
|
1039
1406
|
const errors = validateCredentialResponse(request, response);
|
|
1040
1407
|
if (errors.length > 0) throw new AuthError(`${manifest.name}: invalid credentials form answer: ${errors.join("; ")}`);
|
|
1041
|
-
const
|
|
1042
|
-
|
|
1043
|
-
return
|
|
1408
|
+
const chosen = response.domain ?? domain;
|
|
1409
|
+
const target = applyDomain(manifest, chosen);
|
|
1410
|
+
if (response.method === "sign-in") return resolveFormSignIn(target, response, chosen, context);
|
|
1411
|
+
return resolveFormToken(target, response, chosen, context);
|
|
1044
1412
|
};
|
|
1045
1413
|
//#endregion
|
|
1046
|
-
//#region src/auth/
|
|
1047
|
-
var
|
|
1048
|
-
|
|
1414
|
+
//#region src/auth/ui/const.ts
|
|
1415
|
+
var WEB_HOST_API_PREFIX = "api.";
|
|
1416
|
+
//#endregion
|
|
1417
|
+
//#region src/auth/ui/to-web-host.ts
|
|
1418
|
+
/** `api.github.com` → `github.com`, `api.acme.ghe.com` → `acme.ghe.com`, `ghe.example.com/api/v3` → `ghe.example.com`. */
|
|
1419
|
+
var toWebHost = (domain) => {
|
|
1420
|
+
const [host = domain, ...path] = domain.split("/");
|
|
1421
|
+
if (path.length === 0 && host.startsWith("api.")) return host.slice(WEB_HOST_API_PREFIX.length);
|
|
1422
|
+
return host;
|
|
1049
1423
|
};
|
|
1050
1424
|
//#endregion
|
|
1425
|
+
//#region src/auth/project/pick-remote-host.ts
|
|
1426
|
+
var toHostname = (domain) => (domain.split("/")[0] ?? domain).split(":")[0]?.toLowerCase();
|
|
1427
|
+
/** The known host a git remote host points at: `github.com` picks `api.github.com`, a self-managed host picks itself. */
|
|
1428
|
+
var pickRemoteHost = (knownHosts, remoteHost) => knownHosts.find((host) => toHostname(host) === remoteHost || toHostname(toWebHost(host)) === remoteHost);
|
|
1429
|
+
//#endregion
|
|
1051
1430
|
//#region src/auth/credentials/resolve/resolve-domain.ts
|
|
1052
|
-
/**
|
|
1431
|
+
/**
|
|
1432
|
+
* The host of a call, in this order: its env var; the host this project was bound to; the known host the project's
|
|
1433
|
+
* git remote points at (when the manifest asks for it); the only host in use, or the manifest default. With several
|
|
1434
|
+
* hosts and no way to tell, it is undefined so the form asks.
|
|
1435
|
+
*/
|
|
1053
1436
|
var resolveDomain = async (manifest, context) => {
|
|
1054
1437
|
const { domain } = manifest;
|
|
1055
1438
|
if (!domain) return;
|
|
1056
|
-
const
|
|
1439
|
+
const fromEnv = domain.env ? context.env[domain.env] : void 0;
|
|
1440
|
+
const saved = fromEnv ? void 0 : await resolveSavedDomain(manifest, context);
|
|
1441
|
+
if (saved === null) return;
|
|
1442
|
+
const value = fromEnv || saved || domain.default;
|
|
1057
1443
|
if (value !== void 0 && !isDomainValue(value)) throw new AuthError(`${manifest.name}: domain "${value}" must look like host[:port][/path]`);
|
|
1058
1444
|
return value;
|
|
1059
1445
|
};
|
|
1446
|
+
/** Null when several hosts are known and nothing says which one this project uses; undefined when none is known. */
|
|
1447
|
+
var resolveSavedDomain = async (manifest, context) => {
|
|
1448
|
+
const server = readServerConfig(await loadConfig(context.env), manifest);
|
|
1449
|
+
const knownHosts = listKnownHosts(server);
|
|
1450
|
+
if (knownHosts.length === 0) return;
|
|
1451
|
+
if (context.projectDir === void 0) return knownHosts.length === 1 ? knownHosts[0] : null;
|
|
1452
|
+
const project = await resolveProject(context.projectDir);
|
|
1453
|
+
const bound = server?.projects?.[project.key];
|
|
1454
|
+
if (bound) return bound;
|
|
1455
|
+
const remote = manifest.domain?.matchGitRemote && project.remoteHost ? pickRemoteHost(knownHosts, project.remoteHost) : void 0;
|
|
1456
|
+
if (remote) return remote;
|
|
1457
|
+
return knownHosts.length === 1 ? knownHosts[0] : null;
|
|
1458
|
+
};
|
|
1060
1459
|
//#endregion
|
|
1061
1460
|
//#region src/auth/credentials/response/is-valid-credential-response.ts
|
|
1062
1461
|
var isValidCredentialResponse = (request, response) => validateCredentialResponse(request, response).length === 0;
|
|
@@ -1071,7 +1470,11 @@ var readFallbackValues = async (auth, owner, context) => {
|
|
|
1071
1470
|
};
|
|
1072
1471
|
//#endregion
|
|
1073
1472
|
//#region src/auth/resolve/resolve-fallback-auth.ts
|
|
1074
|
-
var resolveFallbackAuth = async (auth, manifest, context) => resolveStaticAuth(auth, manifest.name, await readFallbackValues(auth,
|
|
1473
|
+
var resolveFallbackAuth = async (auth, manifest, domain, context) => resolveStaticAuth(auth, manifest.name, await readFallbackValues(auth, {
|
|
1474
|
+
name: manifest.name,
|
|
1475
|
+
category: manifest.category,
|
|
1476
|
+
domain
|
|
1477
|
+
}, context));
|
|
1075
1478
|
//#endregion
|
|
1076
1479
|
//#region src/auth/oauth/refresh/is-token-expired.ts
|
|
1077
1480
|
var isTokenExpired = (token, now) => token.expiresAt !== void 0 && token.expiresAt - 6e4 <= now;
|
|
@@ -1136,66 +1539,31 @@ var resolveStoredAuth = async (serverName, auth, context) => {
|
|
|
1136
1539
|
return createResolvedAuth({ Authorization: `Bearer ${await readFreshAccessToken(serverName, issuer, stored, context)}` });
|
|
1137
1540
|
};
|
|
1138
1541
|
//#endregion
|
|
1139
|
-
//#region src/auth/secret-file/create-exclusive-runner.ts
|
|
1140
|
-
/** Runs tasks one at a time, so read-modify-write cycles on one file never lose each other's changes. */
|
|
1141
|
-
var createExclusiveRunner = () => {
|
|
1142
|
-
let pending = Promise.resolve();
|
|
1143
|
-
return (task) => {
|
|
1144
|
-
const run = pending.then(task);
|
|
1145
|
-
pending = run.catch(() => void 0);
|
|
1146
|
-
return run;
|
|
1147
|
-
};
|
|
1148
|
-
};
|
|
1149
|
-
//#endregion
|
|
1150
|
-
//#region src/auth/secret-file/is-stored-secrets.ts
|
|
1151
|
-
var isServerSecrets = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
1152
|
-
var isStoredSecrets = (value) => isJsonObject(value) && Object.values(value).every(isServerSecrets);
|
|
1153
|
-
//#endregion
|
|
1154
|
-
//#region src/auth/secret-file/read-stored-secrets.ts
|
|
1155
|
-
/** A missing file means nothing is saved; a malformed one fails instead of being overwritten. */
|
|
1156
|
-
var readStoredSecrets = async (file) => {
|
|
1157
|
-
const text = await readTokensText(file);
|
|
1158
|
-
if (text === void 0) return {};
|
|
1159
|
-
const data = JSON.parse(text);
|
|
1160
|
-
if (!isStoredSecrets(data)) throw new AuthError(`${file} is not a valid mcpkit secrets file`);
|
|
1161
|
-
return data;
|
|
1162
|
-
};
|
|
1163
|
-
//#endregion
|
|
1164
|
-
//#region src/auth/secret-file/resolve-secrets-file.ts
|
|
1165
|
-
var resolveSecretsFile = (env) => join(resolveHomeDir(env), SECRETS_FILE_NAME);
|
|
1166
|
-
//#endregion
|
|
1167
1542
|
//#region src/auth/secret-file/create-file-secret-store.ts
|
|
1168
|
-
|
|
1543
|
+
var toHostKey = (owner) => owner.domain ?? "default";
|
|
1544
|
+
/** Plain text in the 0600 config file under the mcpkit home, by server and host, read on every call so all running servers see each other's saves. */
|
|
1169
1545
|
var createFileSecretStore = (env = process.env) => {
|
|
1170
|
-
const file = resolveSecretsFile(env);
|
|
1171
|
-
const runExclusive = createExclusiveRunner();
|
|
1172
1546
|
return {
|
|
1173
|
-
get: async (owner, key) => (await
|
|
1174
|
-
set: (owner, key, value) =>
|
|
1175
|
-
const
|
|
1176
|
-
|
|
1177
|
-
...
|
|
1178
|
-
|
|
1179
|
-
...
|
|
1180
|
-
[
|
|
1547
|
+
get: async (owner, key) => readServerConfig(await loadConfig(env), owner)?.hosts?.[toHostKey(owner)]?.secrets?.[key],
|
|
1548
|
+
set: async (owner, key, value) => {
|
|
1549
|
+
const host = toHostKey(owner);
|
|
1550
|
+
await updateServerConfig(env, owner, (current) => ({
|
|
1551
|
+
...current,
|
|
1552
|
+
hosts: {
|
|
1553
|
+
...current.hosts,
|
|
1554
|
+
[host]: {
|
|
1555
|
+
...current.hosts?.[host],
|
|
1556
|
+
secrets: {
|
|
1557
|
+
...current.hosts?.[host]?.secrets,
|
|
1558
|
+
[key]: value
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1181
1561
|
}
|
|
1182
|
-
};
|
|
1183
|
-
|
|
1184
|
-
})
|
|
1562
|
+
}));
|
|
1563
|
+
}
|
|
1185
1564
|
};
|
|
1186
1565
|
};
|
|
1187
1566
|
//#endregion
|
|
1188
|
-
//#region src/auth/ui/const.ts
|
|
1189
|
-
var WEB_HOST_API_PREFIX = "api.";
|
|
1190
|
-
//#endregion
|
|
1191
|
-
//#region src/auth/ui/to-web-host.ts
|
|
1192
|
-
/** `api.github.com` → `github.com`, `api.acme.ghe.com` → `acme.ghe.com`, `ghe.example.com/api/v3` → `ghe.example.com`. */
|
|
1193
|
-
var toWebHost = (domain) => {
|
|
1194
|
-
const [host = domain, ...path] = domain.split("/");
|
|
1195
|
-
if (path.length === 0 && host.startsWith("api.")) return host.slice(WEB_HOST_API_PREFIX.length);
|
|
1196
|
-
return host;
|
|
1197
|
-
};
|
|
1198
|
-
//#endregion
|
|
1199
1567
|
//#region src/auth/ui/resolve-cli-command.ts
|
|
1200
1568
|
var resolveCliCommand = (action, domain) => {
|
|
1201
1569
|
const args = action.args.map((arg) => {
|
|
@@ -1222,6 +1590,10 @@ var resolveLinkUrl = (url, domain) => {
|
|
|
1222
1590
|
});
|
|
1223
1591
|
};
|
|
1224
1592
|
//#endregion
|
|
1593
|
+
//#region src/auth/unauthorized-error.ts
|
|
1594
|
+
/** An upstream answered 401: the auth option that produced the credentials is rejected and the next one is tried. */
|
|
1595
|
+
var UnauthorizedError = class extends Error {};
|
|
1596
|
+
//#endregion
|
|
1225
1597
|
//#region src/mapping/read-property.ts
|
|
1226
1598
|
var readProperty = (source, key) => isJsonObject(source) ? source[key] : void 0;
|
|
1227
1599
|
//#endregion
|
|
@@ -1285,13 +1657,6 @@ var setJsonPath = (target, segments, value) => {
|
|
|
1285
1657
|
/** `{ 'fields.summary': 'x' }` → `{ fields: { summary: 'x' } }`. */
|
|
1286
1658
|
var expandJsonPaths = (values) => Object.entries(values).reduce((body, [path, value]) => setJsonPath(body, path.split("."), value), {});
|
|
1287
1659
|
//#endregion
|
|
1288
|
-
//#region src/execution/request/build-request-url.ts
|
|
1289
|
-
var buildRequestUrl = (baseUrl, path, params) => {
|
|
1290
|
-
const url = new URL(baseUrl.replace(/\/$/, "") + path);
|
|
1291
|
-
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, String(value));
|
|
1292
|
-
return url.toString();
|
|
1293
|
-
};
|
|
1294
|
-
//#endregion
|
|
1295
1660
|
//#region src/execution/request/collect-args.ts
|
|
1296
1661
|
var collectArgs = (spec, args) => {
|
|
1297
1662
|
if (!spec) return {};
|
|
@@ -1299,6 +1664,78 @@ var collectArgs = (spec, args) => {
|
|
|
1299
1664
|
return Object.fromEntries(entries);
|
|
1300
1665
|
};
|
|
1301
1666
|
//#endregion
|
|
1667
|
+
//#region src/execution/request/build-body-payload.ts
|
|
1668
|
+
var buildBodyPayload = ({ body, bodyArg, fixedBody }, args) => {
|
|
1669
|
+
if (bodyArg !== void 0) return args[bodyArg];
|
|
1670
|
+
const values = {
|
|
1671
|
+
...fixedBody,
|
|
1672
|
+
...collectArgs(body, args)
|
|
1673
|
+
};
|
|
1674
|
+
return Object.keys(values).length > 0 ? expandJsonPaths(values) : void 0;
|
|
1675
|
+
};
|
|
1676
|
+
//#endregion
|
|
1677
|
+
//#region src/execution/request/is-uploaded-file.ts
|
|
1678
|
+
var isUploadedFile = (value) => typeof value === "object" && value !== null && "name" in value && "data" in value && value.data instanceof Uint8Array;
|
|
1679
|
+
//#endregion
|
|
1680
|
+
//#region src/execution/request/build-form-data.ts
|
|
1681
|
+
var toFieldValue = (value) => typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
1682
|
+
var buildFormData = ({ body, fixedBody }, args) => {
|
|
1683
|
+
const form = new FormData();
|
|
1684
|
+
for (const [key, value] of Object.entries({
|
|
1685
|
+
...fixedBody,
|
|
1686
|
+
...collectArgs(body, args)
|
|
1687
|
+
})) {
|
|
1688
|
+
const files = [value].flat().filter(isUploadedFile);
|
|
1689
|
+
if (files.length > 0) {
|
|
1690
|
+
for (const file of files) form.append(key, new Blob([file.data]), file.name);
|
|
1691
|
+
continue;
|
|
1692
|
+
}
|
|
1693
|
+
form.append(key, toFieldValue(value));
|
|
1694
|
+
}
|
|
1695
|
+
return form;
|
|
1696
|
+
};
|
|
1697
|
+
//#endregion
|
|
1698
|
+
//#region src/execution/request/const.ts
|
|
1699
|
+
var JSON_CONTENT_TYPE = "application/json";
|
|
1700
|
+
var NO_HEADERS = {};
|
|
1701
|
+
//#endregion
|
|
1702
|
+
//#region src/execution/request/serialize-body.ts
|
|
1703
|
+
var serializeBody = (payload, contentType) => contentType.startsWith("text/") ? String(payload) : JSON.stringify(payload);
|
|
1704
|
+
//#endregion
|
|
1705
|
+
//#region src/execution/request/build-request-body.ts
|
|
1706
|
+
var buildRequestBody = (spec, args, contentType) => {
|
|
1707
|
+
if (contentType === "multipart/form-data") {
|
|
1708
|
+
const form = buildFormData(spec, args);
|
|
1709
|
+
return [...form.keys()].length > 0 ? {
|
|
1710
|
+
body: form,
|
|
1711
|
+
headers: NO_HEADERS
|
|
1712
|
+
} : void 0;
|
|
1713
|
+
}
|
|
1714
|
+
const payload = buildBodyPayload(spec, args);
|
|
1715
|
+
if (payload === void 0) return;
|
|
1716
|
+
if (isUploadedFile(payload)) return {
|
|
1717
|
+
body: new Blob([payload.data]),
|
|
1718
|
+
headers: { "Content-Type": contentType }
|
|
1719
|
+
};
|
|
1720
|
+
return {
|
|
1721
|
+
body: serializeBody(payload, contentType),
|
|
1722
|
+
headers: { "Content-Type": contentType }
|
|
1723
|
+
};
|
|
1724
|
+
};
|
|
1725
|
+
//#endregion
|
|
1726
|
+
//#region src/execution/request/build-request-url.ts
|
|
1727
|
+
var buildRequestUrl = (baseUrl, path, params, commaKeys = []) => {
|
|
1728
|
+
const url = new URL(baseUrl.replace(/\/$/, "") + path);
|
|
1729
|
+
for (const [key, value] of Object.entries(params)) {
|
|
1730
|
+
if (!Array.isArray(value) || commaKeys.includes(key)) {
|
|
1731
|
+
url.searchParams.set(key, String(value));
|
|
1732
|
+
continue;
|
|
1733
|
+
}
|
|
1734
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
1735
|
+
}
|
|
1736
|
+
return url.toString();
|
|
1737
|
+
};
|
|
1738
|
+
//#endregion
|
|
1302
1739
|
//#region src/execution/tool-error.ts
|
|
1303
1740
|
var ToolError = class extends Error {};
|
|
1304
1741
|
//#endregion
|
|
@@ -1310,29 +1747,25 @@ var fillPath = (template, args) => template.replace(/\{(\w+)\}/g, (_placeholder,
|
|
|
1310
1747
|
});
|
|
1311
1748
|
//#endregion
|
|
1312
1749
|
//#region src/execution/request/build-request.ts
|
|
1313
|
-
/** Expects args already passed through prepareToolArgs. */
|
|
1750
|
+
/** Expects args already passed through prepareToolArgs and loadFileArgs. */
|
|
1314
1751
|
var buildRequest = (manifest, tool, args, auth) => {
|
|
1315
|
-
const { method, path, query,
|
|
1316
|
-
const
|
|
1317
|
-
...fixedBody,
|
|
1318
|
-
...collectArgs(body, args)
|
|
1319
|
-
};
|
|
1320
|
-
const hasBody = method !== "GET" && Object.keys(payload).length > 0;
|
|
1321
|
-
const contentHeaders = hasBody ? { "Content-Type": "application/json" } : {};
|
|
1752
|
+
const { method, path, query, fixedQuery, fixedHeaders, commaQuery, contentType = JSON_CONTENT_TYPE } = tool.request;
|
|
1753
|
+
const content = method === "GET" ? void 0 : buildRequestBody(tool.request, args, contentType);
|
|
1322
1754
|
const params = {
|
|
1323
1755
|
...fixedQuery,
|
|
1324
1756
|
...collectArgs(query, args),
|
|
1325
1757
|
...auth.query
|
|
1326
1758
|
};
|
|
1327
1759
|
return {
|
|
1328
|
-
url: buildRequestUrl(manifest.baseUrl, fillPath(path, args), params),
|
|
1760
|
+
url: buildRequestUrl(manifest.baseUrl, fillPath(path, args), params, commaQuery),
|
|
1329
1761
|
method,
|
|
1330
1762
|
headers: {
|
|
1331
1763
|
...manifest.headers,
|
|
1764
|
+
...fixedHeaders,
|
|
1332
1765
|
...auth.headers,
|
|
1333
|
-
...
|
|
1766
|
+
...content?.headers
|
|
1334
1767
|
},
|
|
1335
|
-
...
|
|
1768
|
+
...content ? { body: content.body } : {}
|
|
1336
1769
|
};
|
|
1337
1770
|
};
|
|
1338
1771
|
//#endregion
|
|
@@ -1462,12 +1895,12 @@ var createStoredCandidate = (manifest, context) => {
|
|
|
1462
1895
|
};
|
|
1463
1896
|
//#endregion
|
|
1464
1897
|
//#region src/execution/auth-fallback/candidates/to-fallback-candidate.ts
|
|
1465
|
-
var toFallbackCandidate = (auth, index, manifest, context) => {
|
|
1898
|
+
var toFallbackCandidate = (auth, index, manifest, domain, context) => {
|
|
1466
1899
|
return {
|
|
1467
1900
|
label: `auth[${index}] ${describeAuthSpec(auth)}`,
|
|
1468
1901
|
kind: "provided",
|
|
1469
1902
|
resolve: async () => ({
|
|
1470
|
-
auth: await resolveFallbackAuth(auth, manifest, context),
|
|
1903
|
+
auth: await resolveFallbackAuth(auth, manifest, domain, context),
|
|
1471
1904
|
manifest
|
|
1472
1905
|
})
|
|
1473
1906
|
};
|
|
@@ -1475,11 +1908,11 @@ var toFallbackCandidate = (auth, index, manifest, context) => {
|
|
|
1475
1908
|
//#endregion
|
|
1476
1909
|
//#region src/execution/auth-fallback/candidates/list-provided-candidates.ts
|
|
1477
1910
|
/** Auth that needs nothing from the user: the `tokens.json` token and fallbacks whose credentials are set or saved. */
|
|
1478
|
-
var listProvidedCandidates = (manifest, context) => {
|
|
1911
|
+
var listProvidedCandidates = (manifest, domain, context) => {
|
|
1479
1912
|
const auth = manifest.auth ?? [];
|
|
1480
1913
|
if (auth.length === 0) return [createNoAuthCandidate(manifest)];
|
|
1481
1914
|
const stored = auth.some(isInteractiveAuth) ? [createStoredCandidate(manifest, context)] : [];
|
|
1482
|
-
const fallbacks = auth.flatMap((entry, index) => isInteractiveAuth(entry) ? [] : [toFallbackCandidate(entry, index, manifest, context)]);
|
|
1915
|
+
const fallbacks = auth.flatMap((entry, index) => isInteractiveAuth(entry) ? [] : [toFallbackCandidate(entry, index, manifest, domain, context)]);
|
|
1483
1916
|
return [...stored, ...fallbacks];
|
|
1484
1917
|
};
|
|
1485
1918
|
//#endregion
|
|
@@ -1490,7 +1923,7 @@ var listProvidedCandidates = (manifest, context) => {
|
|
|
1490
1923
|
*/
|
|
1491
1924
|
var buildAuthCandidates = (manifest, domain, context) => {
|
|
1492
1925
|
const target = manifest.domain && domain === void 0 ? void 0 : applyDomain(manifest, domain);
|
|
1493
|
-
return [...target ? listProvidedCandidates(target, context) : [], ...listInteractiveCandidates(manifest, target, domain, context)];
|
|
1926
|
+
return [...target ? listProvidedCandidates(target, domain, context) : [], ...listInteractiveCandidates(manifest, target, domain, context)];
|
|
1494
1927
|
};
|
|
1495
1928
|
//#endregion
|
|
1496
1929
|
//#region src/execution/auth-fallback/candidates/preferred-auth-labels.ts
|
|
@@ -1527,6 +1960,31 @@ var sendWithAuthFallback = async (manifest, tool, args, context) => {
|
|
|
1527
1960
|
throw new AuthError(`${manifest.name}: no auth option worked\n ${failures.join("\n ")}`);
|
|
1528
1961
|
};
|
|
1529
1962
|
//#endregion
|
|
1963
|
+
//#region src/execution/request/read-uploaded-files.ts
|
|
1964
|
+
var readUploadedFile = async (argName, path) => {
|
|
1965
|
+
if (typeof path !== "string") throw new ToolError(`Argument "${argName}" must be the path of a local file`);
|
|
1966
|
+
try {
|
|
1967
|
+
return {
|
|
1968
|
+
name: basename(path),
|
|
1969
|
+
data: new Uint8Array(await readFile(path))
|
|
1970
|
+
};
|
|
1971
|
+
} catch (error) {
|
|
1972
|
+
throw new ToolError(`Cannot read the file for "${argName}": ${error instanceof Error ? error.message : String(error)}`);
|
|
1973
|
+
}
|
|
1974
|
+
};
|
|
1975
|
+
var readUploadedFiles = (argName, value) => Array.isArray(value) ? Promise.all(value.map((path) => readUploadedFile(argName, path))) : readUploadedFile(argName, value);
|
|
1976
|
+
//#endregion
|
|
1977
|
+
//#region src/execution/request/load-file-args.ts
|
|
1978
|
+
/** An argument may hold one path or an array of paths. */
|
|
1979
|
+
var loadFileArgs = async ({ request }, args) => {
|
|
1980
|
+
const present = (request.fileArgs ?? []).filter((argName) => args[argName] !== void 0);
|
|
1981
|
+
const files = await Promise.all(present.map(async (argName) => [argName, await readUploadedFiles(argName, args[argName])]));
|
|
1982
|
+
return {
|
|
1983
|
+
...args,
|
|
1984
|
+
...Object.fromEntries(files)
|
|
1985
|
+
};
|
|
1986
|
+
};
|
|
1987
|
+
//#endregion
|
|
1530
1988
|
//#region src/execution/request/apply-input-defaults.ts
|
|
1531
1989
|
var applyInputDefaults = (input, args) => {
|
|
1532
1990
|
const defaults = Object.entries(input.properties ?? {}).filter(([, schema]) => schema.default !== void 0).map(([name, schema]) => [name, schema.default]);
|
|
@@ -1549,19 +2007,92 @@ var prepareToolArgs = (tool, rawArgs = {}) => {
|
|
|
1549
2007
|
return args;
|
|
1550
2008
|
};
|
|
1551
2009
|
//#endregion
|
|
2010
|
+
//#region src/execution/response/save-response-file.ts
|
|
2011
|
+
var saveResponseFile = async (response, path) => {
|
|
2012
|
+
if (typeof path !== "string" || path === "") throw new ToolError("The save path must be a non-empty string");
|
|
2013
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
2014
|
+
try {
|
|
2015
|
+
await mkdir(dirname(path), { recursive: true });
|
|
2016
|
+
await writeFile(path, bytes);
|
|
2017
|
+
} catch (error) {
|
|
2018
|
+
throw new ToolError(`Cannot save the response to ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2019
|
+
}
|
|
2020
|
+
return {
|
|
2021
|
+
savedTo: path,
|
|
2022
|
+
bytes: bytes.byteLength,
|
|
2023
|
+
contentType: response.headers.get("content-type")
|
|
2024
|
+
};
|
|
2025
|
+
};
|
|
2026
|
+
//#endregion
|
|
1552
2027
|
//#region src/execution/execute-tool.ts
|
|
1553
2028
|
var executeTool = async (manifest, tool, rawArgs, { fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS, env = process.env, ...hooks } = {}) => {
|
|
1554
|
-
const
|
|
2029
|
+
const args = await loadFileArgs(tool, prepareToolArgs(tool, rawArgs));
|
|
2030
|
+
const { response, tool: sentTool } = await sendWithAuthFallback(manifest, tool, args, {
|
|
1555
2031
|
env,
|
|
1556
2032
|
fetchImpl,
|
|
1557
2033
|
timeoutMs,
|
|
1558
2034
|
...hooks
|
|
1559
2035
|
});
|
|
2036
|
+
const { saveToArg } = sentTool.request;
|
|
2037
|
+
if (saveToArg !== void 0 && response.ok) return saveResponseFile(response, args[saveToArg]);
|
|
1560
2038
|
const body = await readResponseBody(response);
|
|
1561
2039
|
if (!response.ok) throw new ToolError(`${manifest.name} API ${response.status}: ${readApiErrorMessage(body)}`.trim());
|
|
1562
2040
|
return mapResponse(body, sentTool.response);
|
|
1563
2041
|
};
|
|
1564
2042
|
//#endregion
|
|
2043
|
+
//#region src/execution/upstream/read-forwarded-env.ts
|
|
2044
|
+
/** Each forwarded credential from its env var, else from the secret store. */
|
|
2045
|
+
var readForwardedEnv = async (manifest, { forwardEnv = [] }, domain, context) => {
|
|
2046
|
+
const owner = {
|
|
2047
|
+
name: manifest.name,
|
|
2048
|
+
category: manifest.category,
|
|
2049
|
+
domain
|
|
2050
|
+
};
|
|
2051
|
+
const entries = await Promise.all(forwardEnv.map(async (name) => [name, context.env[name] || await context.secretStore?.get(owner, name)]));
|
|
2052
|
+
const missing = entries.filter(([, value]) => !value).map(([name]) => name);
|
|
2053
|
+
if (missing.length > 0) throw new AuthError(`${manifest.name}: missing credential, set ${missing.join(", ")} in the client's env for mcpkit`);
|
|
2054
|
+
return Object.fromEntries(entries.map(([name, value]) => [name, value ?? ""]));
|
|
2055
|
+
};
|
|
2056
|
+
//#endregion
|
|
2057
|
+
//#region src/execution/upstream/with-upstream-access.ts
|
|
2058
|
+
/**
|
|
2059
|
+
* Runs `run` with the access of an `upstream` manifest. A stdio upstream gets its forwarded credentials; an HTTP one
|
|
2060
|
+
* tries the manifest's auth options in order like an API call does, moving on when `run` throws UnauthorizedError.
|
|
2061
|
+
*/
|
|
2062
|
+
var withUpstreamAccess = async (manifest, run, { fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS, env = process.env, ...hooks } = {}) => {
|
|
2063
|
+
const context = {
|
|
2064
|
+
env,
|
|
2065
|
+
fetchImpl,
|
|
2066
|
+
timeoutMs,
|
|
2067
|
+
...hooks
|
|
2068
|
+
};
|
|
2069
|
+
const domain = await resolveDomain(manifest, context);
|
|
2070
|
+
const upstream = applyDomain(manifest, domain).upstream;
|
|
2071
|
+
if (!upstream) throw new AuthError(`${manifest.name} has no upstream`);
|
|
2072
|
+
if (upstream.type === "stdio") return run({
|
|
2073
|
+
upstream,
|
|
2074
|
+
headers: {},
|
|
2075
|
+
env: await readForwardedEnv(manifest, upstream, domain, context)
|
|
2076
|
+
});
|
|
2077
|
+
const failures = [];
|
|
2078
|
+
for (const candidate of orderAuthCandidates(manifest.name, buildAuthCandidates(manifest, domain, context))) try {
|
|
2079
|
+
const resolution = await candidate.resolve();
|
|
2080
|
+
const result = await run({
|
|
2081
|
+
upstream,
|
|
2082
|
+
headers: resolution.auth.headers,
|
|
2083
|
+
env: {}
|
|
2084
|
+
});
|
|
2085
|
+
await resolution.commit?.();
|
|
2086
|
+
if (candidate.kind === "provided") preferredAuthLabels.set(manifest.name, candidate.label);
|
|
2087
|
+
return result;
|
|
2088
|
+
} catch (error) {
|
|
2089
|
+
if (!(error instanceof AuthError || error instanceof UnauthorizedError)) throw error;
|
|
2090
|
+
failures.push(`${candidate.label}: ${describeError(error)}`);
|
|
2091
|
+
}
|
|
2092
|
+
preferredAuthLabels.delete(manifest.name);
|
|
2093
|
+
throw new AuthError(`${manifest.name}: no auth option worked\n ${failures.join("\n ")}`);
|
|
2094
|
+
};
|
|
2095
|
+
//#endregion
|
|
1565
2096
|
//#region src/sdk/define-server.ts
|
|
1566
2097
|
var defineServer = (manifest) => manifest;
|
|
1567
2098
|
//#endregion
|
|
@@ -1665,4 +2196,4 @@ var compareVersions = (left, right) => {
|
|
|
1665
2196
|
return 0;
|
|
1666
2197
|
};
|
|
1667
2198
|
//#endregion
|
|
1668
|
-
export { AuthError, CREDENTIALS_FORM_API, CREDENTIALS_FORM_SESSION_HEADER, CREDENTIALS_REQUEST_ELEMENT_ID, DEFAULT_UI_TEXTS, SERVER_NAME_PATTERN, ToolError, applyDomain, array, boolean, buildRequest, compareVersions, createFileSecretStore, defineServer, defineTool, defineUI, describeAuth, describeAuthSpec, describeError, executeTool, fillTemplate, getPath, input, isDomainValue, isInteractiveAuth, isJsonObject, isMissingFileError, isValidCredentialResponse, isValidManifest, listAuthEnvNames, mapResponse, number, oneOf, optional, prepareToolArgs, resolveCliCommand, resolveHomeDir, resolveLinkUrl, resolveStaticAuth, signIn, string, toNameMapping, validateCredentialResponse, validateManifest };
|
|
2199
|
+
export { AuthError, CREDENTIALS_FORM_API, CREDENTIALS_FORM_SESSION_HEADER, CREDENTIALS_REQUEST_ELEMENT_ID, DEFAULT_UI_TEXTS, SERVER_NAME_PATTERN, TOOL_NAME_PATTERN, ToolError, UnauthorizedError, applyDomain, array, boolean, buildRequest, compareVersions, createFileSecretStore, defineServer, defineTool, defineUI, describeAuth, describeAuthSpec, describeError, executeTool, fillTemplate, getPath, input, isDomainValue, isInteractiveAuth, isJsonObject, isMissingFileError, isValidCredentialResponse, isValidManifest, listAuthEnvNames, mapResponse, number, oneOf, optional, prepareToolArgs, resolveCliCommand, resolveHomeDir, resolveLinkUrl, resolveStaticAuth, signIn, string, toNameMapping, validateCredentialResponse, validateManifest, withUpstreamAccess };
|