@usemcpkit/core 0.1.1 → 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 +95 -22
- package/build/mcpkit.core.js +699 -170
- 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;
|
|
@@ -126,6 +137,10 @@ var applyDomain = (manifest, domain) => {
|
|
|
126
137
|
return {
|
|
127
138
|
...manifest,
|
|
128
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,
|
|
129
144
|
auth: manifest.auth?.map((auth) => applyAuthDomain(auth, domain)),
|
|
130
145
|
tools: manifest.tools.map((tool) => applyToolEdition(tool, editionName))
|
|
131
146
|
};
|
|
@@ -138,7 +153,7 @@ var isDomainValue = (value) => typeof value === "string" && DOMAIN_VALUE_PATTERN
|
|
|
138
153
|
var isJsonObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
139
154
|
//#endregion
|
|
140
155
|
//#region src/json/is-string-record.ts
|
|
141
|
-
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");
|
|
142
157
|
//#endregion
|
|
143
158
|
//#region src/manifest/validation/guards/is-interactive-auth-type.ts
|
|
144
159
|
var isInteractiveAuthType = (type) => INTERACTIVE_AUTH_TYPES.some((interactiveType) => interactiveType === type);
|
|
@@ -168,10 +183,12 @@ var DEFAULT_UI_TEXTS = {
|
|
|
168
183
|
brand: "mcpkit",
|
|
169
184
|
pageTitle: "mcpkit · Connect",
|
|
170
185
|
title: "Connect {server}",
|
|
171
|
-
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.",
|
|
172
187
|
domainLabel: "Domain",
|
|
173
188
|
domainHint: "Host, optionally with a port and path, without https://",
|
|
174
189
|
domainPlaceholder: "api.example.com",
|
|
190
|
+
domainNewHost: "New host, saved with its own credentials.",
|
|
191
|
+
domainShowHosts: "Show saved hosts",
|
|
175
192
|
signInLabel: "Sign in with OAuth2",
|
|
176
193
|
tokenDivider: "or use an access token",
|
|
177
194
|
credentialLegend: "Credential",
|
|
@@ -186,7 +203,7 @@ var DEFAULT_UI_TEXTS = {
|
|
|
186
203
|
submit: "Save and continue",
|
|
187
204
|
requiredField: "{label} is required",
|
|
188
205
|
savedTitle: "{server} is connected",
|
|
189
|
-
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.",
|
|
190
207
|
signingInTitle: "Continue in the new tab",
|
|
191
208
|
signingInBody: "Approve access to {server} in the sign-in tab that just opened. You can close this one.",
|
|
192
209
|
cancelledTitle: "Cancelled",
|
|
@@ -318,6 +335,7 @@ var validateOAuthFields = (auth, location) => {
|
|
|
318
335
|
if (!isHttpsUrl(auth.authorizationUrl)) errors.push(`${location}.authorizationUrl must be an https:// URL`);
|
|
319
336
|
if (!isHttpsUrl(auth.tokenUrl)) errors.push(`${location}.tokenUrl must be an https:// URL`);
|
|
320
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"`);
|
|
321
339
|
return [...errors, ...validateSignInFields(auth, location)];
|
|
322
340
|
};
|
|
323
341
|
//#endregion
|
|
@@ -360,6 +378,7 @@ var validateDomainSpec = (manifest) => {
|
|
|
360
378
|
"hint",
|
|
361
379
|
"placeholder"
|
|
362
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");
|
|
363
382
|
return errors;
|
|
364
383
|
};
|
|
365
384
|
//#endregion
|
|
@@ -385,7 +404,20 @@ var validateServerFields = (manifest) => {
|
|
|
385
404
|
if (!SERVER_CATEGORY_PATTERN.test(String(manifest.category ?? ""))) errors.push(`category must match ${SERVER_CATEGORY_PATTERN}`);
|
|
386
405
|
if (typeof manifest.version !== "string") errors.push("version is required");
|
|
387
406
|
if (!isBaseUrl(manifest.baseUrl)) errors.push("baseUrl must be an https:// URL");
|
|
388
|
-
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");
|
|
389
421
|
return errors;
|
|
390
422
|
};
|
|
391
423
|
//#endregion
|
|
@@ -403,7 +435,7 @@ var isHttpMethod = (value) => HTTP_METHODS.some((method) => method === value);
|
|
|
403
435
|
//#region src/manifest/validation/tool/read-arg-names.ts
|
|
404
436
|
var readArgNames = (spec) => {
|
|
405
437
|
if (isStringList(spec)) return spec;
|
|
406
|
-
if (isStringRecord(spec)) return Object.values(spec);
|
|
438
|
+
if (isStringRecord$1(spec)) return Object.values(spec);
|
|
407
439
|
};
|
|
408
440
|
//#endregion
|
|
409
441
|
//#region src/manifest/validation/tool/validate-arg-spec.ts
|
|
@@ -414,6 +446,43 @@ var validateArgSpec = (spec, declaredArgs, location) => {
|
|
|
414
446
|
return names.filter((name) => !declaredArgs.has(name)).map((name) => `${location} uses undeclared arg "${name}"`);
|
|
415
447
|
};
|
|
416
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
|
|
417
486
|
//#region src/manifest/validation/tool/validate-fixed-values.ts
|
|
418
487
|
var validateFixedValues = (values, location) => {
|
|
419
488
|
if (values === void 0) return [];
|
|
@@ -431,6 +500,12 @@ var validateRequestPath = (path, declaredArgs, location) => {
|
|
|
431
500
|
return [...path.matchAll(/\{(\w+)\}/g)].map((match) => match[1] ?? "").filter((name) => !declaredArgs.has(name)).map((name) => `${location}.request.path uses undeclared arg "${name}"`);
|
|
432
501
|
};
|
|
433
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
|
|
434
509
|
//#region src/manifest/validation/tool/validate-request.ts
|
|
435
510
|
var validateRequest = (request, declaredArgs, location) => {
|
|
436
511
|
if (!isJsonObject(request)) return [`${location}.request is required`];
|
|
@@ -439,7 +514,13 @@ var validateRequest = (request, declaredArgs, location) => {
|
|
|
439
514
|
...validateRequestPath(request.path, declaredArgs, location),
|
|
440
515
|
...validateArgSpec(request.query, declaredArgs, `${location}.request.query`),
|
|
441
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),
|
|
442
521
|
...validateFixedValues(request.fixedQuery, `${location}.request.fixedQuery`),
|
|
522
|
+
...validateCommaQuery(request.commaQuery, `${location}.request.commaQuery`),
|
|
523
|
+
...validateFixedHeaders(request.fixedHeaders, `${location}.request.fixedHeaders`),
|
|
443
524
|
...validateFixedValues(request.fixedBody, `${location}.request.fixedBody`)
|
|
444
525
|
];
|
|
445
526
|
};
|
|
@@ -491,6 +572,9 @@ var validateTools = (tools, editionNames) => {
|
|
|
491
572
|
return [...toolErrors, ...duplicateErrors];
|
|
492
573
|
};
|
|
493
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
|
|
494
578
|
//#region src/manifest/validation/ui/validate-ui-texts.ts
|
|
495
579
|
var KNOWN_TEXT_KEYS = UI_TEXT_KEYS;
|
|
496
580
|
var validateUiTexts = (texts, location) => {
|
|
@@ -515,13 +599,14 @@ var validateServerUi = (manifest) => {
|
|
|
515
599
|
var validateManifest = (manifest) => {
|
|
516
600
|
if (!isJsonObject(manifest)) return ["manifest must be a JSON object"];
|
|
517
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)];
|
|
518
603
|
return [
|
|
519
604
|
...validateServerFields(manifest),
|
|
520
605
|
...validateDomainSpec(manifest),
|
|
521
606
|
...validateEditions(manifest.editions),
|
|
522
607
|
...validateAuth(manifest.auth, manifest.domain !== void 0),
|
|
523
608
|
...validateServerUi(manifest),
|
|
524
|
-
...
|
|
609
|
+
...toolErrors
|
|
525
610
|
];
|
|
526
611
|
};
|
|
527
612
|
//#endregion
|
|
@@ -541,12 +626,78 @@ var toNameMapping = (spec) => {
|
|
|
541
626
|
/** Replaces `{name}` with its value; a placeholder without a value stays as it is. */
|
|
542
627
|
var fillTemplate = (template, values) => template.replace(UI_PLACEHOLDER_PATTERN, (placeholder, name) => values[name] ?? placeholder);
|
|
543
628
|
//#endregion
|
|
544
|
-
//#region src/auth/
|
|
545
|
-
|
|
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
|
+
};
|
|
546
665
|
//#endregion
|
|
547
|
-
//#region src/
|
|
548
|
-
|
|
549
|
-
|
|
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);
|
|
550
701
|
//#endregion
|
|
551
702
|
//#region src/auth/secrets/write-json-file.ts
|
|
552
703
|
/** Writes through a temp file and rename so a crash never leaves a half-written file. */
|
|
@@ -559,32 +710,195 @@ var writeJsonFile = async (file, value) => {
|
|
|
559
710
|
await writeFile(tempFile, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
|
|
560
711
|
await rename(tempFile, file);
|
|
561
712
|
};
|
|
713
|
+
/** Data without a `version` is the first version. */
|
|
714
|
+
var readVersion = (data) => isJsonObject(data) && data.version !== void 0 ? data.version : 1;
|
|
562
715
|
//#endregion
|
|
563
|
-
//#region src/
|
|
564
|
-
|
|
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
|
+
};
|
|
565
732
|
//#endregion
|
|
566
|
-
//#region src/auth/
|
|
567
|
-
|
|
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
|
+
};
|
|
568
747
|
//#endregion
|
|
569
|
-
//#region src/auth/
|
|
570
|
-
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
|
+
};
|
|
571
764
|
//#endregion
|
|
572
|
-
//#region src/
|
|
573
|
-
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
|
+
};
|
|
574
774
|
//#endregion
|
|
575
|
-
//#region src/
|
|
576
|
-
|
|
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
|
+
};
|
|
577
801
|
//#endregion
|
|
578
|
-
//#region src/auth/
|
|
579
|
-
|
|
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;
|
|
580
841
|
try {
|
|
581
|
-
|
|
842
|
+
migrated = migrateData(JSON.parse(text), CONFIG_MIGRATIONS);
|
|
582
843
|
} catch (error) {
|
|
583
|
-
|
|
584
|
-
throw error;
|
|
844
|
+
throw new AuthError(`${file} ${error instanceof Error ? error.message : "is not a valid mcpkit config file"}`);
|
|
585
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
|
+
};
|
|
586
871
|
};
|
|
587
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
|
|
588
902
|
//#region src/auth/token-store/read-tokens.ts
|
|
589
903
|
/** A missing file means no sessions; a malformed one fails instead of being overwritten. */
|
|
590
904
|
var readTokens = async (file) => {
|
|
@@ -595,9 +909,6 @@ var readTokens = async (file) => {
|
|
|
595
909
|
return data;
|
|
596
910
|
};
|
|
597
911
|
//#endregion
|
|
598
|
-
//#region src/home/resolve-home-dir.ts
|
|
599
|
-
var resolveHomeDir = (env = process.env) => env.MCPKIT_HOME ?? join(homedir(), ".mcpkit");
|
|
600
|
-
//#endregion
|
|
601
912
|
//#region src/auth/token-store/resolve-tokens-file.ts
|
|
602
913
|
var resolveTokensFile = (env) => join(resolveHomeDir(env), TOKENS_FILE_NAME);
|
|
603
914
|
//#endregion
|
|
@@ -614,6 +925,7 @@ var saveToken = async (env, serverName, token) => {
|
|
|
614
925
|
//#region src/auth/oauth/pkce/build-authorization-url.ts
|
|
615
926
|
var buildAuthorizationUrl = (auth, { redirectUri, challenge, state }) => {
|
|
616
927
|
const url = new URL(auth.authorizationUrl);
|
|
928
|
+
for (const [name, value] of Object.entries(auth.authorizationParams ?? {})) url.searchParams.set(name, value);
|
|
617
929
|
url.searchParams.set("response_type", "code");
|
|
618
930
|
url.searchParams.set("client_id", auth.clientId);
|
|
619
931
|
url.searchParams.set("redirect_uri", redirectUri);
|
|
@@ -671,18 +983,22 @@ var readJsonBody = async (response, serverName) => {
|
|
|
671
983
|
//#endregion
|
|
672
984
|
//#region src/auth/oauth/sign-in/request-token.ts
|
|
673
985
|
var requestToken = async (auth, grant, serverName, { env, fetchImpl }) => {
|
|
674
|
-
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
|
+
}
|
|
675
998
|
const response = await fetchImpl(auth.tokenUrl, {
|
|
676
999
|
method: "POST",
|
|
677
|
-
headers
|
|
678
|
-
|
|
679
|
-
"Content-Type": "application/x-www-form-urlencoded"
|
|
680
|
-
},
|
|
681
|
-
body: new URLSearchParams({
|
|
682
|
-
...grant,
|
|
683
|
-
client_id: auth.clientId,
|
|
684
|
-
...clientSecret
|
|
685
|
-
}),
|
|
1000
|
+
headers,
|
|
1001
|
+
body,
|
|
686
1002
|
signal: AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS)
|
|
687
1003
|
});
|
|
688
1004
|
return parseTokenResponse(await readJsonBody(response, serverName), response.status, serverName, Date.now());
|
|
@@ -815,38 +1131,75 @@ var resolveSignedInAuth = async (serverName, auth, context) => {
|
|
|
815
1131
|
return createResolvedAuth({ Authorization: `Bearer ${token.accessToken}` });
|
|
816
1132
|
};
|
|
817
1133
|
//#endregion
|
|
818
|
-
//#region src/auth/config/
|
|
819
|
-
|
|
820
|
-
var
|
|
821
|
-
|
|
822
|
-
//#region src/auth/config/read-config.ts
|
|
823
|
-
/** A missing file means no settings; a malformed one fails instead of being overwritten. */
|
|
824
|
-
var readConfig = async (file) => {
|
|
825
|
-
const text = await readTokensText(file);
|
|
826
|
-
if (text === void 0) return {};
|
|
827
|
-
const data = JSON.parse(text);
|
|
828
|
-
if (!isMcpkitConfig(data)) throw new AuthError(`${file} is not a valid mcpkit config file`);
|
|
829
|
-
return data;
|
|
830
|
-
};
|
|
831
|
-
//#endregion
|
|
832
|
-
//#region src/auth/config/resolve-config-file.ts
|
|
833
|
-
var resolveConfigFile = (env) => join(resolveHomeDir(env), CONFIG_FILE_NAME);
|
|
834
|
-
//#endregion
|
|
835
|
-
//#region src/auth/config/save-server-domain.ts
|
|
836
|
-
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);
|
|
837
1138
|
const file = resolveConfigFile(env);
|
|
838
1139
|
const config = await readConfig(file);
|
|
839
1140
|
await writeJsonFile(file, {
|
|
840
1141
|
...config,
|
|
841
1142
|
servers: {
|
|
842
1143
|
...config.servers,
|
|
843
|
-
[
|
|
844
|
-
...config.servers?.[
|
|
845
|
-
|
|
1144
|
+
[server.category]: {
|
|
1145
|
+
...config.servers?.[server.category],
|
|
1146
|
+
[server.name]: change(readServerConfig(config, server) ?? {})
|
|
846
1147
|
}
|
|
847
1148
|
}
|
|
848
1149
|
});
|
|
849
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
|
+
};
|
|
850
1203
|
};
|
|
851
1204
|
//#endregion
|
|
852
1205
|
//#region src/auth/credentials/resolve/save-credentials.ts
|
|
@@ -856,20 +1209,26 @@ var saveCredentials = async (owner, values, secretStore) => {
|
|
|
856
1209
|
};
|
|
857
1210
|
//#endregion
|
|
858
1211
|
//#region src/auth/credentials/resolve/save-form-answer.ts
|
|
859
|
-
/**
|
|
1212
|
+
/** Credentials go to the secret store under their host; the host is remembered for the project that asked for it. */
|
|
860
1213
|
var saveFormAnswer = async (manifest, values, domain, context) => {
|
|
861
|
-
await saveCredentials(
|
|
862
|
-
|
|
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);
|
|
863
1222
|
};
|
|
864
1223
|
//#endregion
|
|
865
1224
|
//#region src/auth/credentials/resolve/resolve-form-sign-in.ts
|
|
866
|
-
var resolveFormSignIn = async (manifest, response, context) => {
|
|
1225
|
+
var resolveFormSignIn = async (manifest, response, domain, context) => {
|
|
867
1226
|
const oauth = manifest.auth?.find(isInteractiveAuth);
|
|
868
1227
|
if (!oauth) throw new AuthError(`${manifest.name}: this server has no sign-in`);
|
|
869
1228
|
return {
|
|
870
1229
|
auth: await resolveSignedInAuth(manifest.name, oauth, context),
|
|
871
1230
|
manifest,
|
|
872
|
-
commit: () => saveFormAnswer(manifest, {},
|
|
1231
|
+
commit: () => saveFormAnswer(manifest, {}, domain, context)
|
|
873
1232
|
};
|
|
874
1233
|
};
|
|
875
1234
|
//#endregion
|
|
@@ -893,14 +1252,14 @@ var resolveStaticAuth = (auth, serverName, env) => {
|
|
|
893
1252
|
var trimValues = (values) => Object.fromEntries(Object.entries(values).map(([key, value]) => [key, value.trim()]));
|
|
894
1253
|
//#endregion
|
|
895
1254
|
//#region src/auth/credentials/resolve/resolve-form-token.ts
|
|
896
|
-
var resolveFormToken = (manifest, response, context) => {
|
|
1255
|
+
var resolveFormToken = (manifest, response, domain, context) => {
|
|
897
1256
|
const auth = manifest.auth?.[response.option];
|
|
898
1257
|
if (!auth || isInteractiveAuth(auth)) throw new AuthError(`${manifest.name}: auth[${response.option}] does not take credentials`);
|
|
899
1258
|
const values = trimValues(response.values);
|
|
900
1259
|
return {
|
|
901
1260
|
auth: resolveStaticAuth(auth, manifest.name, values),
|
|
902
1261
|
manifest,
|
|
903
|
-
commit: () => saveFormAnswer(manifest, values,
|
|
1262
|
+
commit: () => saveFormAnswer(manifest, values, domain, context)
|
|
904
1263
|
};
|
|
905
1264
|
};
|
|
906
1265
|
//#endregion
|
|
@@ -915,7 +1274,7 @@ var validateResponseDomain = (request, domain) => {
|
|
|
915
1274
|
var validateTokenResponse = (request, response) => {
|
|
916
1275
|
const option = request.options.find((candidate) => candidate.index === response.option);
|
|
917
1276
|
if (!option) return ["choose one of the offered credentials"];
|
|
918
|
-
const values = isStringRecord(response.values) ? response.values : {};
|
|
1277
|
+
const values = isStringRecord$1(response.values) ? response.values : {};
|
|
919
1278
|
return option.fields.filter((field) => !values[field.key]?.trim()).map((field) => fillTemplate(request.texts.requiredField, { label: field.label }));
|
|
920
1279
|
};
|
|
921
1280
|
//#endregion
|
|
@@ -943,14 +1302,15 @@ var buildUiTexts = (manifest) => {
|
|
|
943
1302
|
//#endregion
|
|
944
1303
|
//#region src/auth/credentials/request/build-domain-field.ts
|
|
945
1304
|
/** A domain set through its env var is not offered for editing. */
|
|
946
|
-
var buildDomainField = (manifest, domain, env, texts) => {
|
|
1305
|
+
var buildDomainField = (manifest, domain, knownHosts, env, texts) => {
|
|
947
1306
|
const spec = manifest.domain;
|
|
948
1307
|
if (!spec || spec.env && env[spec.env]) return;
|
|
949
1308
|
return {
|
|
950
1309
|
label: spec.label ?? texts.domainLabel,
|
|
951
1310
|
hint: spec.hint ?? texts.domainHint,
|
|
952
1311
|
placeholder: spec.placeholder ?? texts.domainPlaceholder,
|
|
953
|
-
value: domain ?? ""
|
|
1312
|
+
value: domain ?? "",
|
|
1313
|
+
knownHosts
|
|
954
1314
|
};
|
|
955
1315
|
};
|
|
956
1316
|
//#endregion
|
|
@@ -1002,10 +1362,10 @@ var toCredentialOptions = (auth, index, serverName, texts) => {
|
|
|
1002
1362
|
};
|
|
1003
1363
|
//#endregion
|
|
1004
1364
|
//#region src/auth/credentials/request/build-credential-request.ts
|
|
1005
|
-
var buildCredentialRequest = (manifest, domain, env) => {
|
|
1365
|
+
var buildCredentialRequest = (manifest, domain, knownHosts, env) => {
|
|
1006
1366
|
const auth = manifest.auth ?? [];
|
|
1007
1367
|
const texts = buildUiTexts(manifest);
|
|
1008
|
-
const domainField = buildDomainField(manifest, domain, env, texts);
|
|
1368
|
+
const domainField = buildDomainField(manifest, domain, knownHosts, env, texts);
|
|
1009
1369
|
return {
|
|
1010
1370
|
serverName: manifest.name,
|
|
1011
1371
|
texts,
|
|
@@ -1021,14 +1381,18 @@ var buildCredentialRequest = (manifest, domain, env) => {
|
|
|
1021
1381
|
var pendingCredentialRequests = /* @__PURE__ */ new Map();
|
|
1022
1382
|
//#endregion
|
|
1023
1383
|
//#region src/auth/credentials/request/request-credentials-once.ts
|
|
1024
|
-
|
|
1025
|
-
|
|
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);
|
|
1026
1387
|
if (pending) return pending;
|
|
1027
|
-
const
|
|
1028
|
-
|
|
1388
|
+
const exchange = createRequest().then(async (request) => ({
|
|
1389
|
+
request,
|
|
1390
|
+
response: await requestCredentials(request)
|
|
1391
|
+
})).finally(() => {
|
|
1392
|
+
pendingCredentialRequests.delete(serverName);
|
|
1029
1393
|
});
|
|
1030
|
-
pendingCredentialRequests.set(
|
|
1031
|
-
return
|
|
1394
|
+
pendingCredentialRequests.set(serverName, exchange);
|
|
1395
|
+
return exchange;
|
|
1032
1396
|
};
|
|
1033
1397
|
//#endregion
|
|
1034
1398
|
//#region src/auth/credentials/request/resolve-credential-form.ts
|
|
@@ -1036,29 +1400,62 @@ var requestCredentialsOnce = (request, requestCredentials) => {
|
|
|
1036
1400
|
var resolveCredentialForm = async (manifest, domain, context) => {
|
|
1037
1401
|
const { requestCredentials } = context;
|
|
1038
1402
|
if (!requestCredentials) throw new AuthError(`${manifest.name}: asking for credentials needs a form, which this caller does not provide`);
|
|
1039
|
-
const request =
|
|
1040
|
-
|
|
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);
|
|
1041
1406
|
const errors = validateCredentialResponse(request, response);
|
|
1042
1407
|
if (errors.length > 0) throw new AuthError(`${manifest.name}: invalid credentials form answer: ${errors.join("; ")}`);
|
|
1043
|
-
const
|
|
1044
|
-
|
|
1045
|
-
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);
|
|
1046
1412
|
};
|
|
1047
1413
|
//#endregion
|
|
1048
|
-
//#region src/auth/
|
|
1049
|
-
var
|
|
1050
|
-
|
|
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;
|
|
1051
1423
|
};
|
|
1052
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
|
|
1053
1430
|
//#region src/auth/credentials/resolve/resolve-domain.ts
|
|
1054
|
-
/**
|
|
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
|
+
*/
|
|
1055
1436
|
var resolveDomain = async (manifest, context) => {
|
|
1056
1437
|
const { domain } = manifest;
|
|
1057
1438
|
if (!domain) return;
|
|
1058
|
-
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;
|
|
1059
1443
|
if (value !== void 0 && !isDomainValue(value)) throw new AuthError(`${manifest.name}: domain "${value}" must look like host[:port][/path]`);
|
|
1060
1444
|
return value;
|
|
1061
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
|
+
};
|
|
1062
1459
|
//#endregion
|
|
1063
1460
|
//#region src/auth/credentials/response/is-valid-credential-response.ts
|
|
1064
1461
|
var isValidCredentialResponse = (request, response) => validateCredentialResponse(request, response).length === 0;
|
|
@@ -1073,7 +1470,11 @@ var readFallbackValues = async (auth, owner, context) => {
|
|
|
1073
1470
|
};
|
|
1074
1471
|
//#endregion
|
|
1075
1472
|
//#region src/auth/resolve/resolve-fallback-auth.ts
|
|
1076
|
-
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));
|
|
1077
1478
|
//#endregion
|
|
1078
1479
|
//#region src/auth/oauth/refresh/is-token-expired.ts
|
|
1079
1480
|
var isTokenExpired = (token, now) => token.expiresAt !== void 0 && token.expiresAt - 6e4 <= now;
|
|
@@ -1138,66 +1539,31 @@ var resolveStoredAuth = async (serverName, auth, context) => {
|
|
|
1138
1539
|
return createResolvedAuth({ Authorization: `Bearer ${await readFreshAccessToken(serverName, issuer, stored, context)}` });
|
|
1139
1540
|
};
|
|
1140
1541
|
//#endregion
|
|
1141
|
-
//#region src/auth/secret-file/create-exclusive-runner.ts
|
|
1142
|
-
/** Runs tasks one at a time, so read-modify-write cycles on one file never lose each other's changes. */
|
|
1143
|
-
var createExclusiveRunner = () => {
|
|
1144
|
-
let pending = Promise.resolve();
|
|
1145
|
-
return (task) => {
|
|
1146
|
-
const run = pending.then(task);
|
|
1147
|
-
pending = run.catch(() => void 0);
|
|
1148
|
-
return run;
|
|
1149
|
-
};
|
|
1150
|
-
};
|
|
1151
|
-
//#endregion
|
|
1152
|
-
//#region src/auth/secret-file/is-stored-secrets.ts
|
|
1153
|
-
var isServerSecrets = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
1154
|
-
var isStoredSecrets = (value) => isJsonObject(value) && Object.values(value).every(isServerSecrets);
|
|
1155
|
-
//#endregion
|
|
1156
|
-
//#region src/auth/secret-file/read-stored-secrets.ts
|
|
1157
|
-
/** A missing file means nothing is saved; a malformed one fails instead of being overwritten. */
|
|
1158
|
-
var readStoredSecrets = async (file) => {
|
|
1159
|
-
const text = await readTokensText(file);
|
|
1160
|
-
if (text === void 0) return {};
|
|
1161
|
-
const data = JSON.parse(text);
|
|
1162
|
-
if (!isStoredSecrets(data)) throw new AuthError(`${file} is not a valid mcpkit secrets file`);
|
|
1163
|
-
return data;
|
|
1164
|
-
};
|
|
1165
|
-
//#endregion
|
|
1166
|
-
//#region src/auth/secret-file/resolve-secrets-file.ts
|
|
1167
|
-
var resolveSecretsFile = (env) => join(resolveHomeDir(env), SECRETS_FILE_NAME);
|
|
1168
|
-
//#endregion
|
|
1169
1542
|
//#region src/auth/secret-file/create-file-secret-store.ts
|
|
1170
|
-
|
|
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. */
|
|
1171
1545
|
var createFileSecretStore = (env = process.env) => {
|
|
1172
|
-
const file = resolveSecretsFile(env);
|
|
1173
|
-
const runExclusive = createExclusiveRunner();
|
|
1174
1546
|
return {
|
|
1175
|
-
get: async (owner, key) => (await
|
|
1176
|
-
set: (owner, key, value) =>
|
|
1177
|
-
const
|
|
1178
|
-
|
|
1179
|
-
...
|
|
1180
|
-
|
|
1181
|
-
...
|
|
1182
|
-
[
|
|
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
|
+
}
|
|
1183
1561
|
}
|
|
1184
|
-
};
|
|
1185
|
-
|
|
1186
|
-
})
|
|
1562
|
+
}));
|
|
1563
|
+
}
|
|
1187
1564
|
};
|
|
1188
1565
|
};
|
|
1189
1566
|
//#endregion
|
|
1190
|
-
//#region src/auth/ui/const.ts
|
|
1191
|
-
var WEB_HOST_API_PREFIX = "api.";
|
|
1192
|
-
//#endregion
|
|
1193
|
-
//#region src/auth/ui/to-web-host.ts
|
|
1194
|
-
/** `api.github.com` → `github.com`, `api.acme.ghe.com` → `acme.ghe.com`, `ghe.example.com/api/v3` → `ghe.example.com`. */
|
|
1195
|
-
var toWebHost = (domain) => {
|
|
1196
|
-
const [host = domain, ...path] = domain.split("/");
|
|
1197
|
-
if (path.length === 0 && host.startsWith("api.")) return host.slice(WEB_HOST_API_PREFIX.length);
|
|
1198
|
-
return host;
|
|
1199
|
-
};
|
|
1200
|
-
//#endregion
|
|
1201
1567
|
//#region src/auth/ui/resolve-cli-command.ts
|
|
1202
1568
|
var resolveCliCommand = (action, domain) => {
|
|
1203
1569
|
const args = action.args.map((arg) => {
|
|
@@ -1224,6 +1590,10 @@ var resolveLinkUrl = (url, domain) => {
|
|
|
1224
1590
|
});
|
|
1225
1591
|
};
|
|
1226
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
|
|
1227
1597
|
//#region src/mapping/read-property.ts
|
|
1228
1598
|
var readProperty = (source, key) => isJsonObject(source) ? source[key] : void 0;
|
|
1229
1599
|
//#endregion
|
|
@@ -1287,13 +1657,6 @@ var setJsonPath = (target, segments, value) => {
|
|
|
1287
1657
|
/** `{ 'fields.summary': 'x' }` → `{ fields: { summary: 'x' } }`. */
|
|
1288
1658
|
var expandJsonPaths = (values) => Object.entries(values).reduce((body, [path, value]) => setJsonPath(body, path.split("."), value), {});
|
|
1289
1659
|
//#endregion
|
|
1290
|
-
//#region src/execution/request/build-request-url.ts
|
|
1291
|
-
var buildRequestUrl = (baseUrl, path, params) => {
|
|
1292
|
-
const url = new URL(baseUrl.replace(/\/$/, "") + path);
|
|
1293
|
-
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, String(value));
|
|
1294
|
-
return url.toString();
|
|
1295
|
-
};
|
|
1296
|
-
//#endregion
|
|
1297
1660
|
//#region src/execution/request/collect-args.ts
|
|
1298
1661
|
var collectArgs = (spec, args) => {
|
|
1299
1662
|
if (!spec) return {};
|
|
@@ -1301,6 +1664,78 @@ var collectArgs = (spec, args) => {
|
|
|
1301
1664
|
return Object.fromEntries(entries);
|
|
1302
1665
|
};
|
|
1303
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
|
|
1304
1739
|
//#region src/execution/tool-error.ts
|
|
1305
1740
|
var ToolError = class extends Error {};
|
|
1306
1741
|
//#endregion
|
|
@@ -1312,29 +1747,25 @@ var fillPath = (template, args) => template.replace(/\{(\w+)\}/g, (_placeholder,
|
|
|
1312
1747
|
});
|
|
1313
1748
|
//#endregion
|
|
1314
1749
|
//#region src/execution/request/build-request.ts
|
|
1315
|
-
/** Expects args already passed through prepareToolArgs. */
|
|
1750
|
+
/** Expects args already passed through prepareToolArgs and loadFileArgs. */
|
|
1316
1751
|
var buildRequest = (manifest, tool, args, auth) => {
|
|
1317
|
-
const { method, path, query,
|
|
1318
|
-
const
|
|
1319
|
-
...fixedBody,
|
|
1320
|
-
...collectArgs(body, args)
|
|
1321
|
-
};
|
|
1322
|
-
const hasBody = method !== "GET" && Object.keys(payload).length > 0;
|
|
1323
|
-
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);
|
|
1324
1754
|
const params = {
|
|
1325
1755
|
...fixedQuery,
|
|
1326
1756
|
...collectArgs(query, args),
|
|
1327
1757
|
...auth.query
|
|
1328
1758
|
};
|
|
1329
1759
|
return {
|
|
1330
|
-
url: buildRequestUrl(manifest.baseUrl, fillPath(path, args), params),
|
|
1760
|
+
url: buildRequestUrl(manifest.baseUrl, fillPath(path, args), params, commaQuery),
|
|
1331
1761
|
method,
|
|
1332
1762
|
headers: {
|
|
1333
1763
|
...manifest.headers,
|
|
1764
|
+
...fixedHeaders,
|
|
1334
1765
|
...auth.headers,
|
|
1335
|
-
...
|
|
1766
|
+
...content?.headers
|
|
1336
1767
|
},
|
|
1337
|
-
...
|
|
1768
|
+
...content ? { body: content.body } : {}
|
|
1338
1769
|
};
|
|
1339
1770
|
};
|
|
1340
1771
|
//#endregion
|
|
@@ -1464,12 +1895,12 @@ var createStoredCandidate = (manifest, context) => {
|
|
|
1464
1895
|
};
|
|
1465
1896
|
//#endregion
|
|
1466
1897
|
//#region src/execution/auth-fallback/candidates/to-fallback-candidate.ts
|
|
1467
|
-
var toFallbackCandidate = (auth, index, manifest, context) => {
|
|
1898
|
+
var toFallbackCandidate = (auth, index, manifest, domain, context) => {
|
|
1468
1899
|
return {
|
|
1469
1900
|
label: `auth[${index}] ${describeAuthSpec(auth)}`,
|
|
1470
1901
|
kind: "provided",
|
|
1471
1902
|
resolve: async () => ({
|
|
1472
|
-
auth: await resolveFallbackAuth(auth, manifest, context),
|
|
1903
|
+
auth: await resolveFallbackAuth(auth, manifest, domain, context),
|
|
1473
1904
|
manifest
|
|
1474
1905
|
})
|
|
1475
1906
|
};
|
|
@@ -1477,11 +1908,11 @@ var toFallbackCandidate = (auth, index, manifest, context) => {
|
|
|
1477
1908
|
//#endregion
|
|
1478
1909
|
//#region src/execution/auth-fallback/candidates/list-provided-candidates.ts
|
|
1479
1910
|
/** Auth that needs nothing from the user: the `tokens.json` token and fallbacks whose credentials are set or saved. */
|
|
1480
|
-
var listProvidedCandidates = (manifest, context) => {
|
|
1911
|
+
var listProvidedCandidates = (manifest, domain, context) => {
|
|
1481
1912
|
const auth = manifest.auth ?? [];
|
|
1482
1913
|
if (auth.length === 0) return [createNoAuthCandidate(manifest)];
|
|
1483
1914
|
const stored = auth.some(isInteractiveAuth) ? [createStoredCandidate(manifest, context)] : [];
|
|
1484
|
-
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)]);
|
|
1485
1916
|
return [...stored, ...fallbacks];
|
|
1486
1917
|
};
|
|
1487
1918
|
//#endregion
|
|
@@ -1492,7 +1923,7 @@ var listProvidedCandidates = (manifest, context) => {
|
|
|
1492
1923
|
*/
|
|
1493
1924
|
var buildAuthCandidates = (manifest, domain, context) => {
|
|
1494
1925
|
const target = manifest.domain && domain === void 0 ? void 0 : applyDomain(manifest, domain);
|
|
1495
|
-
return [...target ? listProvidedCandidates(target, context) : [], ...listInteractiveCandidates(manifest, target, domain, context)];
|
|
1926
|
+
return [...target ? listProvidedCandidates(target, domain, context) : [], ...listInteractiveCandidates(manifest, target, domain, context)];
|
|
1496
1927
|
};
|
|
1497
1928
|
//#endregion
|
|
1498
1929
|
//#region src/execution/auth-fallback/candidates/preferred-auth-labels.ts
|
|
@@ -1529,6 +1960,31 @@ var sendWithAuthFallback = async (manifest, tool, args, context) => {
|
|
|
1529
1960
|
throw new AuthError(`${manifest.name}: no auth option worked\n ${failures.join("\n ")}`);
|
|
1530
1961
|
};
|
|
1531
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
|
|
1532
1988
|
//#region src/execution/request/apply-input-defaults.ts
|
|
1533
1989
|
var applyInputDefaults = (input, args) => {
|
|
1534
1990
|
const defaults = Object.entries(input.properties ?? {}).filter(([, schema]) => schema.default !== void 0).map(([name, schema]) => [name, schema.default]);
|
|
@@ -1551,19 +2007,92 @@ var prepareToolArgs = (tool, rawArgs = {}) => {
|
|
|
1551
2007
|
return args;
|
|
1552
2008
|
};
|
|
1553
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
|
|
1554
2027
|
//#region src/execution/execute-tool.ts
|
|
1555
2028
|
var executeTool = async (manifest, tool, rawArgs, { fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS, env = process.env, ...hooks } = {}) => {
|
|
1556
|
-
const
|
|
2029
|
+
const args = await loadFileArgs(tool, prepareToolArgs(tool, rawArgs));
|
|
2030
|
+
const { response, tool: sentTool } = await sendWithAuthFallback(manifest, tool, args, {
|
|
1557
2031
|
env,
|
|
1558
2032
|
fetchImpl,
|
|
1559
2033
|
timeoutMs,
|
|
1560
2034
|
...hooks
|
|
1561
2035
|
});
|
|
2036
|
+
const { saveToArg } = sentTool.request;
|
|
2037
|
+
if (saveToArg !== void 0 && response.ok) return saveResponseFile(response, args[saveToArg]);
|
|
1562
2038
|
const body = await readResponseBody(response);
|
|
1563
2039
|
if (!response.ok) throw new ToolError(`${manifest.name} API ${response.status}: ${readApiErrorMessage(body)}`.trim());
|
|
1564
2040
|
return mapResponse(body, sentTool.response);
|
|
1565
2041
|
};
|
|
1566
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
|
|
1567
2096
|
//#region src/sdk/define-server.ts
|
|
1568
2097
|
var defineServer = (manifest) => manifest;
|
|
1569
2098
|
//#endregion
|
|
@@ -1667,4 +2196,4 @@ var compareVersions = (left, right) => {
|
|
|
1667
2196
|
return 0;
|
|
1668
2197
|
};
|
|
1669
2198
|
//#endregion
|
|
1670
|
-
export { AuthError, CREDENTIALS_FORM_API, CREDENTIALS_FORM_SESSION_HEADER, CREDENTIALS_REQUEST_ELEMENT_ID, DEFAULT_UI_TEXTS, SERVER_NAME_PATTERN, TOOL_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 };
|