@arabold/docs-mcp-server 2.4.0 → 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/{main-BoUugvTO.js → main-WZKPkgC6.js} +617 -96
- package/dist/main-WZKPkgC6.js.map +1 -0
- package/dist/{utils-CUTutkx-.js → utils-CJgh41os.js} +48 -3
- package/dist/utils-CJgh41os.js.map +1 -0
- package/package.json +1 -1
- package/dist/main-BoUugvTO.js.map +0 -1
- package/dist/utils-CUTutkx-.js.map +0 -1
|
@@ -9,7 +9,7 @@ import path from "node:path";
|
|
|
9
9
|
import { URL as URL$1 } from "node:url";
|
|
10
10
|
import envPaths from "env-paths";
|
|
11
11
|
import { l as logger, n as normalizeEnvValue, g as getLogLevelFromEnv, a as setLogLevel, L as LogLevel } from "./logger-CLtABTNb.js";
|
|
12
|
-
import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus, f as getProjectRoot, E as EmbeddingConfig, b as EventType, S as ServerEventName, s as shouldEnableTelemetry, r as resolveProtocol, p as parseAuthConfig, v as validateAuthConfig, w as warnHttpUsage, e as ensurePlaywrightBrowsersInstalled, g as getEventBus, h as handleEmbeddingModelChange, d as createAppServerConfig, j as parseHeaders, m as validatePort, l as validateHost, k as resolveStorePath, i as initTelemetry, a as EventBusService, c as TelemetryService } from "./utils-
|
|
12
|
+
import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus, f as getProjectRoot, E as EmbeddingConfig, b as EventType, S as ServerEventName, s as shouldEnableTelemetry, r as resolveProtocol, p as parseAuthConfig, v as validateAuthConfig, w as warnHttpUsage, e as ensurePlaywrightBrowsersInstalled, g as getEventBus, h as handleEmbeddingModelChange, d as createAppServerConfig, j as parseHeaders, m as validatePort, l as validateHost, k as resolveStorePath, i as initTelemetry, a as EventBusService, c as TelemetryService } from "./utils-CJgh41os.js";
|
|
13
13
|
import yargs from "yargs";
|
|
14
14
|
import { hideBin } from "yargs/helpers";
|
|
15
15
|
import yaml from "yaml";
|
|
@@ -356,6 +356,62 @@ function createEmbeddingModel(providerAndModel, runtime) {
|
|
|
356
356
|
throw new UnsupportedProviderError(provider);
|
|
357
357
|
}
|
|
358
358
|
}
|
|
359
|
+
function normalizePublicOrigin(origin) {
|
|
360
|
+
const trimmed = origin?.trim();
|
|
361
|
+
if (!trimmed) {
|
|
362
|
+
return void 0;
|
|
363
|
+
}
|
|
364
|
+
let parsed;
|
|
365
|
+
try {
|
|
366
|
+
parsed = new URL(trimmed);
|
|
367
|
+
} catch {
|
|
368
|
+
throw new Error(
|
|
369
|
+
"server.publicOrigin must be an absolute HTTP(S) origin without path, query, or fragment."
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
373
|
+
throw new Error("server.publicOrigin must use the http or https protocol.");
|
|
374
|
+
}
|
|
375
|
+
if (parsed.username || parsed.password) {
|
|
376
|
+
throw new Error("server.publicOrigin must not include credentials.");
|
|
377
|
+
}
|
|
378
|
+
if (parsed.pathname !== "/" || parsed.search || parsed.hash) {
|
|
379
|
+
throw new Error(
|
|
380
|
+
"server.publicOrigin must not include a path, query string, or fragment."
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
return parsed.origin;
|
|
384
|
+
}
|
|
385
|
+
function buildBindOrigin(host, port) {
|
|
386
|
+
const formattedHost = formatHostForUrl(host);
|
|
387
|
+
return new URL(`http://${formattedHost}:${port}`).origin;
|
|
388
|
+
}
|
|
389
|
+
function getCanonicalServerOrigin(config, port) {
|
|
390
|
+
return normalizePublicOrigin(config.server.publicOrigin) ?? buildBindOrigin(config.server.host, port);
|
|
391
|
+
}
|
|
392
|
+
function isWildcardBindHost(host) {
|
|
393
|
+
const normalized = stripIpv6Brackets(host.trim().toLowerCase());
|
|
394
|
+
return normalized === "0.0.0.0" || normalized === "::" || normalized === "::0" || normalized === "0:0:0:0:0:0:0:0" || normalized === "0000:0000:0000:0000:0000:0000:0000:0000";
|
|
395
|
+
}
|
|
396
|
+
function formatHostForUrl(host) {
|
|
397
|
+
const trimmed = host.trim();
|
|
398
|
+
const unbracketed = stripIpv6Brackets(trimmed);
|
|
399
|
+
if (unbracketed.includes(":")) {
|
|
400
|
+
return `[${unbracketed}]`;
|
|
401
|
+
}
|
|
402
|
+
return trimmed;
|
|
403
|
+
}
|
|
404
|
+
function stripIpv6Brackets(host) {
|
|
405
|
+
return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
|
406
|
+
}
|
|
407
|
+
const managedConfigVectorDimensionOmissionMarker = "docs-mcp-server-managed-vector-dimension-omitted";
|
|
408
|
+
const managedConfigHeader = [
|
|
409
|
+
`# ${managedConfigVectorDimensionOmissionMarker}`,
|
|
410
|
+
"# embeddings.vectorDimension is omitted when it comes from generated defaults.",
|
|
411
|
+
"# Add embeddings.vectorDimension explicitly to override native model dimensions.",
|
|
412
|
+
""
|
|
413
|
+
].join("\n");
|
|
414
|
+
const vectorDimensionPath = ["embeddings", "vectorDimension"];
|
|
359
415
|
const envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
|
|
360
416
|
if (Array.isArray(value)) {
|
|
361
417
|
return value;
|
|
@@ -371,6 +427,23 @@ const envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
|
|
|
371
427
|
const lower = val.toLowerCase().trim();
|
|
372
428
|
return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off" && lower !== "";
|
|
373
429
|
}).pipe(z.boolean());
|
|
430
|
+
const publicOriginSchema = z.preprocess((value) => {
|
|
431
|
+
if (typeof value !== "string") {
|
|
432
|
+
return value;
|
|
433
|
+
}
|
|
434
|
+
const trimmed = value.trim();
|
|
435
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
436
|
+
}, z.string().optional()).transform((value, ctx) => {
|
|
437
|
+
try {
|
|
438
|
+
return normalizePublicOrigin(value);
|
|
439
|
+
} catch (error) {
|
|
440
|
+
ctx.addIssue({
|
|
441
|
+
code: z.ZodIssueCode.custom,
|
|
442
|
+
message: error instanceof Error ? error.message : String(error)
|
|
443
|
+
});
|
|
444
|
+
return z.NEVER;
|
|
445
|
+
}
|
|
446
|
+
});
|
|
374
447
|
const DEFAULT_CONFIG = {
|
|
375
448
|
app: {
|
|
376
449
|
storePath: "",
|
|
@@ -381,6 +454,7 @@ const DEFAULT_CONFIG = {
|
|
|
381
454
|
server: {
|
|
382
455
|
protocol: "auto",
|
|
383
456
|
host: "127.0.0.1",
|
|
457
|
+
publicOrigin: void 0,
|
|
384
458
|
ports: {
|
|
385
459
|
default: 6280,
|
|
386
460
|
worker: 8080,
|
|
@@ -478,6 +552,7 @@ const AppConfigSchema = z.object({
|
|
|
478
552
|
server: z.object({
|
|
479
553
|
protocol: z.string().default(DEFAULT_CONFIG.server.protocol),
|
|
480
554
|
host: z.string().default(DEFAULT_CONFIG.server.host),
|
|
555
|
+
publicOrigin: publicOriginSchema.optional(),
|
|
481
556
|
ports: z.object({
|
|
482
557
|
default: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.default),
|
|
483
558
|
worker: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.worker),
|
|
@@ -485,7 +560,12 @@ const AppConfigSchema = z.object({
|
|
|
485
560
|
web: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.web)
|
|
486
561
|
}).default(DEFAULT_CONFIG.server.ports),
|
|
487
562
|
heartbeatMs: z.coerce.number().int().default(DEFAULT_CONFIG.server.heartbeatMs)
|
|
488
|
-
}).default(
|
|
563
|
+
}).default({
|
|
564
|
+
protocol: DEFAULT_CONFIG.server.protocol,
|
|
565
|
+
host: DEFAULT_CONFIG.server.host,
|
|
566
|
+
ports: DEFAULT_CONFIG.server.ports,
|
|
567
|
+
heartbeatMs: DEFAULT_CONFIG.server.heartbeatMs
|
|
568
|
+
}),
|
|
489
569
|
auth: z.object({
|
|
490
570
|
enabled: envBoolean.default(DEFAULT_CONFIG.auth.enabled),
|
|
491
571
|
issuerUrl: z.string().default(DEFAULT_CONFIG.auth.issuerUrl),
|
|
@@ -578,6 +658,7 @@ const AppConfigSchema = z.object({
|
|
|
578
658
|
maxChunkDistance: z.coerce.number().int().min(0).default(DEFAULT_CONFIG.assembly.maxChunkDistance)
|
|
579
659
|
}).default(DEFAULT_CONFIG.assembly)
|
|
580
660
|
});
|
|
661
|
+
const vectorDimensionExplicit = /* @__PURE__ */ Symbol("vectorDimensionExplicit");
|
|
581
662
|
const defaults = AppConfigSchema.parse({});
|
|
582
663
|
const configMappings = [
|
|
583
664
|
{ path: ["server", "protocol"], env: ["DOCS_MCP_PROTOCOL"], cli: "protocol" },
|
|
@@ -607,6 +688,11 @@ const configMappings = [
|
|
|
607
688
|
cli: "port"
|
|
608
689
|
},
|
|
609
690
|
{ path: ["server", "host"], env: ["DOCS_MCP_HOST", "HOST"], cli: "host" },
|
|
691
|
+
{
|
|
692
|
+
path: ["server", "publicOrigin"],
|
|
693
|
+
env: ["DOCS_MCP_SERVER_PUBLIC_ORIGIN"],
|
|
694
|
+
cli: "publicOrigin"
|
|
695
|
+
},
|
|
610
696
|
{
|
|
611
697
|
path: ["app", "embeddingModel"],
|
|
612
698
|
env: ["DOCS_MCP_EMBEDDING_MODEL"],
|
|
@@ -639,16 +725,34 @@ function loadConfig(cliArgs = {}, options = {}) {
|
|
|
639
725
|
}
|
|
640
726
|
logger.debug(`Using config file: ${configPath}`);
|
|
641
727
|
const fileConfig = loadConfigFile(configPath) || {};
|
|
728
|
+
const hasManagedVectorDimensionOmissionMarker = hasManagedConfigVectorDimensionOmissionMarker(configPath);
|
|
642
729
|
const baseConfig = deepMerge(defaults, fileConfig);
|
|
730
|
+
const envConfig = mapEnvToConfig();
|
|
731
|
+
const cliConfig = mapCliToConfig(cliArgs);
|
|
732
|
+
const vectorDimensionWasExplicit = wasVectorDimensionExplicit(
|
|
733
|
+
fileConfig,
|
|
734
|
+
envConfig,
|
|
735
|
+
cliConfig,
|
|
736
|
+
isReadOnlyConfig,
|
|
737
|
+
hasManagedVectorDimensionOmissionMarker
|
|
738
|
+
);
|
|
739
|
+
const fileVectorDimensionWasExplicit = wasVectorDimensionExplicit(
|
|
740
|
+
fileConfig,
|
|
741
|
+
{},
|
|
742
|
+
{},
|
|
743
|
+
isReadOnlyConfig,
|
|
744
|
+
hasManagedVectorDimensionOmissionMarker
|
|
745
|
+
);
|
|
643
746
|
if (!isReadOnlyConfig) {
|
|
644
747
|
try {
|
|
645
|
-
saveConfigFile(configPath, baseConfig
|
|
748
|
+
saveConfigFile(configPath, baseConfig, {
|
|
749
|
+
managedDefaultConfig: true,
|
|
750
|
+
omitVectorDimension: !fileVectorDimensionWasExplicit
|
|
751
|
+
});
|
|
646
752
|
} catch (error) {
|
|
647
753
|
logger.warn(`Failed to save config file to ${configPath}: ${error}`);
|
|
648
754
|
}
|
|
649
755
|
}
|
|
650
|
-
const envConfig = mapEnvToConfig();
|
|
651
|
-
const cliConfig = mapCliToConfig(cliArgs);
|
|
652
756
|
const mergedInput = deepMerge(
|
|
653
757
|
baseConfig,
|
|
654
758
|
deepMerge(envConfig, cliConfig)
|
|
@@ -658,7 +762,15 @@ function loadConfig(cliArgs = {}, options = {}) {
|
|
|
658
762
|
}
|
|
659
763
|
const parseResult = AppConfigSchema.safeParse(mergedInput);
|
|
660
764
|
if (parseResult.success) {
|
|
661
|
-
return
|
|
765
|
+
return markVectorDimensionSource(
|
|
766
|
+
parseResult.data,
|
|
767
|
+
vectorDimensionWasExplicit
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
if (hasParseIssueAtPath(parseResult.error, ["server", "publicOrigin"])) {
|
|
771
|
+
throw new Error(
|
|
772
|
+
`Invalid configuration for server.publicOrigin: ${parseResult.error.message}`
|
|
773
|
+
);
|
|
662
774
|
}
|
|
663
775
|
if (!isReadOnlyConfig && fs.existsSync(configPath)) {
|
|
664
776
|
const quarantinePath = `${configPath}.invalid-${Date.now()}`;
|
|
@@ -685,14 +797,40 @@ function loadConfig(cliArgs = {}, options = {}) {
|
|
|
685
797
|
setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
|
|
686
798
|
}
|
|
687
799
|
const fallback = AppConfigSchema.parse(fallbackInput);
|
|
800
|
+
const fallbackConfig = markVectorDimensionSource(
|
|
801
|
+
fallback,
|
|
802
|
+
wasVectorDimensionExplicit({}, envConfig, cliConfig, false, false)
|
|
803
|
+
);
|
|
688
804
|
if (!isReadOnlyConfig) {
|
|
689
805
|
try {
|
|
690
|
-
saveConfigFile(configPath,
|
|
806
|
+
saveConfigFile(configPath, fallbackConfig, {
|
|
807
|
+
managedDefaultConfig: true,
|
|
808
|
+
omitVectorDimension: true
|
|
809
|
+
});
|
|
691
810
|
} catch (error) {
|
|
692
811
|
logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
|
|
693
812
|
}
|
|
694
813
|
}
|
|
695
|
-
return
|
|
814
|
+
return fallbackConfig;
|
|
815
|
+
}
|
|
816
|
+
function hasManagedConfigVectorDimensionOmissionMarker(filePath) {
|
|
817
|
+
if (!fs.existsSync(filePath)) return false;
|
|
818
|
+
try {
|
|
819
|
+
return fs.readFileSync(filePath, "utf8").includes(managedConfigVectorDimensionOmissionMarker);
|
|
820
|
+
} catch {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
function isVectorDimensionExplicit(config) {
|
|
825
|
+
return config.embeddings[vectorDimensionExplicit] === true;
|
|
826
|
+
}
|
|
827
|
+
function markVectorDimensionSource(config, explicit) {
|
|
828
|
+
Object.defineProperty(config.embeddings, vectorDimensionExplicit, {
|
|
829
|
+
value: explicit,
|
|
830
|
+
enumerable: false,
|
|
831
|
+
configurable: true
|
|
832
|
+
});
|
|
833
|
+
return config;
|
|
696
834
|
}
|
|
697
835
|
function loadConfigFile(filePath) {
|
|
698
836
|
if (!fs.existsSync(filePath)) return null;
|
|
@@ -707,16 +845,45 @@ function loadConfigFile(filePath) {
|
|
|
707
845
|
return null;
|
|
708
846
|
}
|
|
709
847
|
}
|
|
710
|
-
function
|
|
848
|
+
function wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker) {
|
|
849
|
+
if (getAtPath(envConfig, vectorDimensionPath) !== void 0 || getAtPath(cliConfig, vectorDimensionPath) !== void 0) {
|
|
850
|
+
return true;
|
|
851
|
+
}
|
|
852
|
+
const fileValue = getAtPath(fileConfig, vectorDimensionPath);
|
|
853
|
+
if (fileValue === void 0) {
|
|
854
|
+
return false;
|
|
855
|
+
}
|
|
856
|
+
if (isReadOnlyConfig || fileValue !== DEFAULT_CONFIG.embeddings.vectorDimension || hasManagedVectorDimensionOmissionMarker) {
|
|
857
|
+
return true;
|
|
858
|
+
}
|
|
859
|
+
return !looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig);
|
|
860
|
+
}
|
|
861
|
+
function looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig) {
|
|
862
|
+
const embeddings = fileConfig.embeddings;
|
|
863
|
+
if (typeof embeddings !== "object" || embeddings === null || Array.isArray(embeddings)) {
|
|
864
|
+
return false;
|
|
865
|
+
}
|
|
866
|
+
return Object.keys(DEFAULT_CONFIG.embeddings).every(
|
|
867
|
+
(key) => Object.hasOwn(embeddings, key)
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
function saveConfigFile(filePath, config, options = {}) {
|
|
711
871
|
const dir = path.dirname(filePath);
|
|
712
872
|
if (!fs.existsSync(dir)) {
|
|
713
873
|
fs.mkdirSync(dir, { recursive: true });
|
|
714
874
|
}
|
|
875
|
+
const configToWrite = cloneConfigValue(config);
|
|
876
|
+
if (options.omitVectorDimension) {
|
|
877
|
+
unsetAtPath(configToWrite, vectorDimensionPath);
|
|
878
|
+
}
|
|
715
879
|
let content;
|
|
716
880
|
if (filePath.endsWith(".json")) {
|
|
717
|
-
content = JSON.stringify(
|
|
881
|
+
content = JSON.stringify(configToWrite, null, 2);
|
|
718
882
|
} else {
|
|
719
|
-
content = yaml.stringify(
|
|
883
|
+
content = yaml.stringify(configToWrite);
|
|
884
|
+
if (options.managedDefaultConfig) {
|
|
885
|
+
content = `${managedConfigHeader}${content}`;
|
|
886
|
+
}
|
|
720
887
|
}
|
|
721
888
|
logger.debug(`Updating config file at ${filePath}`);
|
|
722
889
|
fs.writeFileSync(filePath, content, "utf8");
|
|
@@ -792,6 +959,44 @@ function getAtPath(obj, pathArr) {
|
|
|
792
959
|
}
|
|
793
960
|
return current;
|
|
794
961
|
}
|
|
962
|
+
function unsetAtPath(obj, pathArr) {
|
|
963
|
+
let current = obj;
|
|
964
|
+
for (const key of pathArr.slice(0, -1)) {
|
|
965
|
+
if (typeof current !== "object" || current === null) {
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
current = current[key];
|
|
969
|
+
}
|
|
970
|
+
if (typeof current === "object" && current !== null) {
|
|
971
|
+
delete current[pathArr[pathArr.length - 1]];
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
function cloneConfigValue(value) {
|
|
975
|
+
if (Array.isArray(value)) {
|
|
976
|
+
return value.map((item) => cloneConfigValue(item));
|
|
977
|
+
}
|
|
978
|
+
if (typeof value === "object" && value !== null) {
|
|
979
|
+
const output = {};
|
|
980
|
+
for (const [key, child] of Object.entries(value)) {
|
|
981
|
+
output[key] = cloneConfigValue(child);
|
|
982
|
+
}
|
|
983
|
+
return output;
|
|
984
|
+
}
|
|
985
|
+
return value;
|
|
986
|
+
}
|
|
987
|
+
function hasPath(obj, pathArr) {
|
|
988
|
+
let current = obj;
|
|
989
|
+
for (const key of pathArr) {
|
|
990
|
+
if (typeof current !== "object" || current === null || !Object.hasOwn(current, key)) {
|
|
991
|
+
return false;
|
|
992
|
+
}
|
|
993
|
+
current = current[key];
|
|
994
|
+
}
|
|
995
|
+
return true;
|
|
996
|
+
}
|
|
997
|
+
function hasParseIssueAtPath(error, pathArr) {
|
|
998
|
+
return error.issues.some((issue) => issue.path.join(".") === pathArr.join("."));
|
|
999
|
+
}
|
|
795
1000
|
function deepMerge(target, source) {
|
|
796
1001
|
if (typeof target !== "object" || target === null) return source;
|
|
797
1002
|
if (typeof source !== "object" || source === null) return target;
|
|
@@ -812,7 +1017,7 @@ function deepMerge(target, source) {
|
|
|
812
1017
|
}
|
|
813
1018
|
function isValidConfigPath(path2) {
|
|
814
1019
|
const pathArr = path2.split(".");
|
|
815
|
-
return
|
|
1020
|
+
return hasPath(DEFAULT_CONFIG, pathArr);
|
|
816
1021
|
}
|
|
817
1022
|
function getConfigValue(config, path2) {
|
|
818
1023
|
const pathArr = path2.split(".");
|
|
@@ -1084,6 +1289,7 @@ class ProxyAuthManager {
|
|
|
1084
1289
|
proxyProvider = null;
|
|
1085
1290
|
discoveredEndpoints = null;
|
|
1086
1291
|
jwks = null;
|
|
1292
|
+
resourceOrigin = null;
|
|
1087
1293
|
/**
|
|
1088
1294
|
* Get the authentication configuration
|
|
1089
1295
|
*/
|
|
@@ -1143,6 +1349,7 @@ class ProxyAuthManager {
|
|
|
1143
1349
|
if (!this.proxyProvider) {
|
|
1144
1350
|
throw new Error("Proxy provider not initialized");
|
|
1145
1351
|
}
|
|
1352
|
+
this.resourceOrigin = baseUrl.origin;
|
|
1146
1353
|
server.get("/.well-known/oauth-authorization-server", async (_request, reply) => {
|
|
1147
1354
|
const metadata = {
|
|
1148
1355
|
issuer: baseUrl.origin,
|
|
@@ -1341,14 +1548,16 @@ class ProxyAuthManager {
|
|
|
1341
1548
|
* Get supported resource URLs for this MCP server instance.
|
|
1342
1549
|
* This enables self-discovering resource validation per MCP Authorization spec.
|
|
1343
1550
|
*/
|
|
1344
|
-
getSupportedResources(
|
|
1345
|
-
|
|
1551
|
+
getSupportedResources() {
|
|
1552
|
+
if (!this.resourceOrigin) {
|
|
1553
|
+
return [];
|
|
1554
|
+
}
|
|
1346
1555
|
return [
|
|
1347
|
-
`${
|
|
1556
|
+
`${this.resourceOrigin}/sse`,
|
|
1348
1557
|
// SSE transport
|
|
1349
|
-
`${
|
|
1558
|
+
`${this.resourceOrigin}/mcp`,
|
|
1350
1559
|
// Streaming HTTP transport
|
|
1351
|
-
|
|
1560
|
+
this.resourceOrigin
|
|
1352
1561
|
// Server root
|
|
1353
1562
|
];
|
|
1354
1563
|
}
|
|
@@ -1408,7 +1617,7 @@ class ProxyAuthManager {
|
|
|
1408
1617
|
throw new Error("Userinfo response missing subject");
|
|
1409
1618
|
}
|
|
1410
1619
|
if (request) {
|
|
1411
|
-
const supportedResources = this.getSupportedResources(
|
|
1620
|
+
const supportedResources = this.getSupportedResources();
|
|
1412
1621
|
logger.debug(`Supported resources: ${JSON.stringify(supportedResources)}`);
|
|
1413
1622
|
}
|
|
1414
1623
|
return {
|
|
@@ -5533,23 +5742,112 @@ class HtmlPlaywrightMiddleware {
|
|
|
5533
5742
|
}
|
|
5534
5743
|
return this.browser;
|
|
5535
5744
|
}
|
|
5745
|
+
getPageTimeoutMs() {
|
|
5746
|
+
return this.config.pageTimeoutMs ?? defaults.scraper.pageTimeoutMs;
|
|
5747
|
+
}
|
|
5748
|
+
getBrowserTimeoutMs() {
|
|
5749
|
+
return this.config.browserTimeoutMs ?? defaults.scraper.browserTimeoutMs;
|
|
5750
|
+
}
|
|
5751
|
+
async withTimeout(operation, timeoutMs, description) {
|
|
5752
|
+
let timeout;
|
|
5753
|
+
try {
|
|
5754
|
+
return await Promise.race([
|
|
5755
|
+
operation,
|
|
5756
|
+
new Promise((_resolve, reject) => {
|
|
5757
|
+
timeout = setTimeout(() => {
|
|
5758
|
+
reject(new Error(`${description} timed out after ${timeoutMs}ms`));
|
|
5759
|
+
}, timeoutMs);
|
|
5760
|
+
})
|
|
5761
|
+
]);
|
|
5762
|
+
} finally {
|
|
5763
|
+
if (timeout) {
|
|
5764
|
+
clearTimeout(timeout);
|
|
5765
|
+
}
|
|
5766
|
+
}
|
|
5767
|
+
}
|
|
5768
|
+
getBrowserProcess(browser) {
|
|
5769
|
+
if (!("process" in browser) || typeof browser.process !== "function") {
|
|
5770
|
+
return null;
|
|
5771
|
+
}
|
|
5772
|
+
return browser.process();
|
|
5773
|
+
}
|
|
5774
|
+
killBrowserProcess(browser, reason) {
|
|
5775
|
+
const browserProcess = this.getBrowserProcess(browser);
|
|
5776
|
+
if (!browserProcess || browserProcess.killed) {
|
|
5777
|
+
return;
|
|
5778
|
+
}
|
|
5779
|
+
const pid = browserProcess.pid ? ` pid=${browserProcess.pid}` : "";
|
|
5780
|
+
logger.warn(`⚠️ Force killing Playwright browser process${pid}: ${reason}`);
|
|
5781
|
+
try {
|
|
5782
|
+
if (!browserProcess.kill("SIGKILL")) {
|
|
5783
|
+
logger.warn(`⚠️ Failed to force kill Playwright browser process${pid}`);
|
|
5784
|
+
}
|
|
5785
|
+
} catch (error) {
|
|
5786
|
+
logger.warn(`⚠️ Failed to force kill Playwright browser process${pid}: ${error}`);
|
|
5787
|
+
}
|
|
5788
|
+
}
|
|
5536
5789
|
/**
|
|
5537
5790
|
* Closes the Playwright browser instance if it exists.
|
|
5538
5791
|
* Should be called during application shutdown.
|
|
5539
5792
|
* Attempts to close even if the browser is disconnected to ensure proper cleanup of zombie processes.
|
|
5540
5793
|
*/
|
|
5541
|
-
async closeBrowser() {
|
|
5794
|
+
async closeBrowser(reason = "shutdown") {
|
|
5542
5795
|
if (this.browser) {
|
|
5796
|
+
const browser = this.browser;
|
|
5543
5797
|
try {
|
|
5544
|
-
logger.debug(
|
|
5545
|
-
await this.
|
|
5798
|
+
logger.debug(`Closing Playwright browser instance (${reason})...`);
|
|
5799
|
+
await this.withTimeout(
|
|
5800
|
+
browser.close(),
|
|
5801
|
+
this.getPageTimeoutMs(),
|
|
5802
|
+
"Playwright browser close"
|
|
5803
|
+
);
|
|
5546
5804
|
} catch (error) {
|
|
5547
|
-
logger.warn(`⚠️ Error closing Playwright browser: ${error}`);
|
|
5805
|
+
logger.warn(`⚠️ Error closing Playwright browser (${reason}): ${error}`);
|
|
5806
|
+
this.killBrowserProcess(browser, reason);
|
|
5548
5807
|
} finally {
|
|
5549
5808
|
this.browser = null;
|
|
5550
5809
|
}
|
|
5551
5810
|
}
|
|
5552
5811
|
}
|
|
5812
|
+
async cleanupPageAndContext(page, browserContext, source) {
|
|
5813
|
+
let cleanupSucceeded = true;
|
|
5814
|
+
const timeoutMs = this.getPageTimeoutMs();
|
|
5815
|
+
if (page) {
|
|
5816
|
+
try {
|
|
5817
|
+
await this.withTimeout(
|
|
5818
|
+
page.unroute("**/*"),
|
|
5819
|
+
timeoutMs,
|
|
5820
|
+
`Playwright route cleanup for ${source}`
|
|
5821
|
+
);
|
|
5822
|
+
} catch (error) {
|
|
5823
|
+
cleanupSucceeded = false;
|
|
5824
|
+
logger.warn(`⚠️ Playwright route cleanup failed for ${source}: ${error}`);
|
|
5825
|
+
}
|
|
5826
|
+
try {
|
|
5827
|
+
await this.withTimeout(
|
|
5828
|
+
page.close(),
|
|
5829
|
+
timeoutMs,
|
|
5830
|
+
`Playwright page close for ${source}`
|
|
5831
|
+
);
|
|
5832
|
+
} catch (error) {
|
|
5833
|
+
cleanupSucceeded = false;
|
|
5834
|
+
logger.warn(`⚠️ Playwright page cleanup failed for ${source}: ${error}`);
|
|
5835
|
+
}
|
|
5836
|
+
}
|
|
5837
|
+
if (browserContext) {
|
|
5838
|
+
try {
|
|
5839
|
+
await this.withTimeout(
|
|
5840
|
+
browserContext.close(),
|
|
5841
|
+
timeoutMs,
|
|
5842
|
+
`Playwright browser context close for ${source}`
|
|
5843
|
+
);
|
|
5844
|
+
} catch (error) {
|
|
5845
|
+
cleanupSucceeded = false;
|
|
5846
|
+
logger.warn(`⚠️ Playwright context cleanup failed for ${source}: ${error}`);
|
|
5847
|
+
}
|
|
5848
|
+
}
|
|
5849
|
+
return cleanupSucceeded;
|
|
5850
|
+
}
|
|
5553
5851
|
/**
|
|
5554
5852
|
* Injects the shadow DOM extractor script into the page.
|
|
5555
5853
|
* This script performs non-invasive extraction that preserves document structure.
|
|
@@ -6194,6 +6492,8 @@ ${frame.content}
|
|
|
6194
6492
|
let page = null;
|
|
6195
6493
|
let browserContext = null;
|
|
6196
6494
|
let renderedHtml = null;
|
|
6495
|
+
let shouldResetBrowser = false;
|
|
6496
|
+
let renderFailed = false;
|
|
6197
6497
|
const { credentials, origin } = extractCredentialsAndOrigin(context.source);
|
|
6198
6498
|
const customHeaders = context.options?.headers ?? {};
|
|
6199
6499
|
try {
|
|
@@ -6248,8 +6548,11 @@ ${frame.content}
|
|
|
6248
6548
|
origin ?? void 0
|
|
6249
6549
|
);
|
|
6250
6550
|
});
|
|
6251
|
-
|
|
6252
|
-
|
|
6551
|
+
const pageTimeoutMs = this.getPageTimeoutMs();
|
|
6552
|
+
await page.goto(context.source, {
|
|
6553
|
+
waitUntil: "load",
|
|
6554
|
+
timeout: this.getBrowserTimeoutMs()
|
|
6555
|
+
});
|
|
6253
6556
|
await page.waitForSelector("body, frameset", {
|
|
6254
6557
|
timeout: pageTimeoutMs
|
|
6255
6558
|
});
|
|
@@ -6269,17 +6572,25 @@ ${frame.content}
|
|
|
6269
6572
|
`Playwright: Successfully rendered content for ${context.source} using ${method}`
|
|
6270
6573
|
);
|
|
6271
6574
|
} catch (error) {
|
|
6575
|
+
renderFailed = true;
|
|
6576
|
+
shouldResetBrowser = true;
|
|
6272
6577
|
logger.error(`❌ Playwright failed to render ${context.source}: ${error}`);
|
|
6273
6578
|
context.errors.push(
|
|
6274
6579
|
error instanceof Error ? error : new Error(`Playwright rendering failed: ${String(error)}`)
|
|
6275
6580
|
);
|
|
6276
6581
|
} finally {
|
|
6277
|
-
|
|
6278
|
-
|
|
6279
|
-
|
|
6582
|
+
const cleanupSucceeded = await this.cleanupPageAndContext(
|
|
6583
|
+
page,
|
|
6584
|
+
browserContext,
|
|
6585
|
+
context.source
|
|
6586
|
+
);
|
|
6587
|
+
const cleanupFailed = !cleanupSucceeded;
|
|
6588
|
+
if (cleanupFailed) {
|
|
6589
|
+
shouldResetBrowser = true;
|
|
6280
6590
|
}
|
|
6281
|
-
if (
|
|
6282
|
-
|
|
6591
|
+
if (shouldResetBrowser) {
|
|
6592
|
+
const resetReason = renderFailed ? cleanupFailed ? `reset after Playwright render and cleanup failure for ${context.source}` : `reset after Playwright render failure for ${context.source}` : `reset after Playwright cleanup failure for ${context.source}`;
|
|
6593
|
+
await this.closeBrowser(resetReason);
|
|
6283
6594
|
}
|
|
6284
6595
|
}
|
|
6285
6596
|
if (renderedHtml !== null) {
|
|
@@ -6565,8 +6876,15 @@ class HtmlSanitizerMiddleware {
|
|
|
6565
6876
|
await next();
|
|
6566
6877
|
}
|
|
6567
6878
|
}
|
|
6879
|
+
const maxGfmTableRows = 500;
|
|
6880
|
+
const maxGfmTableCells = 1e3;
|
|
6881
|
+
const maxGfmTableHtmlLength = 1e5;
|
|
6882
|
+
const gfmTableChunkRows = 100;
|
|
6883
|
+
const preservedTablePlaceholderAttribute = "data-docs-mcp-preserved-table-id";
|
|
6568
6884
|
class HtmlToMarkdownMiddleware {
|
|
6569
6885
|
turndownService;
|
|
6886
|
+
preservedTableHtml = /* @__PURE__ */ new Map();
|
|
6887
|
+
preservedTableSequence = 0;
|
|
6570
6888
|
constructor() {
|
|
6571
6889
|
this.turndownService = new TurndownService({
|
|
6572
6890
|
headingStyle: "atx",
|
|
@@ -6631,10 +6949,90 @@ ${text.replace(/^\n+|\n+$/g, "")}
|
|
|
6631
6949
|
return `[${normalizedContent}](${href})`;
|
|
6632
6950
|
}
|
|
6633
6951
|
});
|
|
6952
|
+
this.turndownService.addRule("preservedOversizedTable", {
|
|
6953
|
+
filter: (node) => {
|
|
6954
|
+
const element = node;
|
|
6955
|
+
return element.nodeName === "DIV" && element.hasAttribute(preservedTablePlaceholderAttribute);
|
|
6956
|
+
},
|
|
6957
|
+
replacement: (_content, node) => {
|
|
6958
|
+
const element = node;
|
|
6959
|
+
const tableId = element.getAttribute(preservedTablePlaceholderAttribute);
|
|
6960
|
+
const tableHtml = tableId ? this.preservedTableHtml.get(tableId) : void 0;
|
|
6961
|
+
return tableHtml ? `
|
|
6962
|
+
|
|
6963
|
+
${tableHtml}
|
|
6964
|
+
|
|
6965
|
+
` : "";
|
|
6966
|
+
}
|
|
6967
|
+
});
|
|
6634
6968
|
}
|
|
6635
6969
|
normalizeLinkContent(content) {
|
|
6636
6970
|
return fullTrim(content).replace(/[ \t]*[\r\n]+[ \t]*/g, " ");
|
|
6637
6971
|
}
|
|
6972
|
+
splitOversizedTables($, source) {
|
|
6973
|
+
$("table").each((_index, element) => {
|
|
6974
|
+
const $table = $(element);
|
|
6975
|
+
const rowCount = $table.find("tr").length;
|
|
6976
|
+
const cellCount = $table.find("td, th").length;
|
|
6977
|
+
const htmlLength = $.html(element).length;
|
|
6978
|
+
if (rowCount <= maxGfmTableRows && cellCount <= maxGfmTableCells && htmlLength <= maxGfmTableHtmlLength) {
|
|
6979
|
+
return;
|
|
6980
|
+
}
|
|
6981
|
+
const replacement = this.buildSplitTableHtml($, $table);
|
|
6982
|
+
if (!replacement) {
|
|
6983
|
+
const tableId = `table-${++this.preservedTableSequence}`;
|
|
6984
|
+
this.preservedTableHtml.set(tableId, $.html(element));
|
|
6985
|
+
logger.warn(
|
|
6986
|
+
`⚠️ Preserving oversized HTML table for ${source} as HTML before GFM conversion: ${rowCount} rows, ${cellCount} cells, ${htmlLength} chars`
|
|
6987
|
+
);
|
|
6988
|
+
$table.replaceWith(
|
|
6989
|
+
`<div ${preservedTablePlaceholderAttribute}="${tableId}">preserved table</div>`
|
|
6990
|
+
);
|
|
6991
|
+
return;
|
|
6992
|
+
}
|
|
6993
|
+
logger.warn(
|
|
6994
|
+
`⚠️ Splitting oversized HTML table for ${source} before GFM conversion: ${rowCount} rows, ${cellCount} cells, ${htmlLength} chars`
|
|
6995
|
+
);
|
|
6996
|
+
$table.replaceWith(replacement);
|
|
6997
|
+
});
|
|
6998
|
+
}
|
|
6999
|
+
buildSplitTableHtml($, $table) {
|
|
7000
|
+
const headerRows = this.getHeaderRows($table);
|
|
7001
|
+
const headerRowSet = new Set(headerRows);
|
|
7002
|
+
const dataRows = $table.find("tr").toArray().filter((row) => row.type === "tag" && !headerRowSet.has(row));
|
|
7003
|
+
if (dataRows.length <= gfmTableChunkRows) {
|
|
7004
|
+
return null;
|
|
7005
|
+
}
|
|
7006
|
+
const chunks = [];
|
|
7007
|
+
const headerHtml = headerRows.map((row) => $.html(row)).join("");
|
|
7008
|
+
const preservedChildHtml = this.getPreservedTableChildHtml($, $table);
|
|
7009
|
+
for (let index = 0; index < dataRows.length; index += gfmTableChunkRows) {
|
|
7010
|
+
const rowsHtml = dataRows.slice(index, index + gfmTableChunkRows).map((row) => $.html(row)).join("");
|
|
7011
|
+
const tableParts = ["<table>", preservedChildHtml];
|
|
7012
|
+
if (headerHtml) {
|
|
7013
|
+
tableParts.push("<thead>", headerHtml, "</thead>");
|
|
7014
|
+
}
|
|
7015
|
+
tableParts.push("<tbody>", rowsHtml, "</tbody></table>");
|
|
7016
|
+
chunks.push(tableParts.join(""));
|
|
7017
|
+
}
|
|
7018
|
+
return chunks.join("\n");
|
|
7019
|
+
}
|
|
7020
|
+
getPreservedTableChildHtml($, $table) {
|
|
7021
|
+
return $table.children("caption, colgroup").toArray().filter((child) => child.type === "tag").map((child) => $.html(child)).join("");
|
|
7022
|
+
}
|
|
7023
|
+
getHeaderRows($table) {
|
|
7024
|
+
const theadRows = $table.children("thead").find("tr").toArray().filter((row) => row.type === "tag");
|
|
7025
|
+
if (theadRows.length > 0) {
|
|
7026
|
+
return theadRows;
|
|
7027
|
+
}
|
|
7028
|
+
const firstRow = $table.find("tr").first();
|
|
7029
|
+
if (firstRow.length === 0) {
|
|
7030
|
+
return [];
|
|
7031
|
+
}
|
|
7032
|
+
const cells = firstRow.children("th, td").toArray();
|
|
7033
|
+
const isHeaderRow = cells.length > 0 && cells.every((cell) => cell.type === "tag" && cell.tagName === "th");
|
|
7034
|
+
return isHeaderRow ? firstRow.toArray() : [];
|
|
7035
|
+
}
|
|
6638
7036
|
/**
|
|
6639
7037
|
* Processes the context to convert the sanitized HTML body node to Markdown.
|
|
6640
7038
|
* @param context The current processing context.
|
|
@@ -6651,6 +7049,8 @@ ${text.replace(/^\n+|\n+$/g, "")}
|
|
|
6651
7049
|
}
|
|
6652
7050
|
try {
|
|
6653
7051
|
logger.debug(`Converting HTML content to Markdown for ${context.source}`);
|
|
7052
|
+
this.preservedTableHtml.clear();
|
|
7053
|
+
this.splitOversizedTables($, context.source);
|
|
6654
7054
|
const htmlToConvert = $("body").html() || $.html();
|
|
6655
7055
|
const markdown = this.turndownService.turndown(htmlToConvert).trim();
|
|
6656
7056
|
if (!markdown) {
|
|
@@ -6671,6 +7071,8 @@ ${text.replace(/^\n+|\n+$/g, "")}
|
|
|
6671
7071
|
`Failed to convert HTML to Markdown: ${error instanceof Error ? error.message : String(error)}`
|
|
6672
7072
|
)
|
|
6673
7073
|
);
|
|
7074
|
+
} finally {
|
|
7075
|
+
this.preservedTableHtml.clear();
|
|
6674
7076
|
}
|
|
6675
7077
|
await next();
|
|
6676
7078
|
}
|
|
@@ -10038,7 +10440,7 @@ function isActiveStatus(status) {
|
|
|
10038
10440
|
class DocumentStore {
|
|
10039
10441
|
config;
|
|
10040
10442
|
db;
|
|
10041
|
-
embeddings;
|
|
10443
|
+
embeddings = null;
|
|
10042
10444
|
dbDimension;
|
|
10043
10445
|
searchWeightVec;
|
|
10044
10446
|
searchWeightFts;
|
|
@@ -10048,7 +10450,7 @@ class DocumentStore {
|
|
|
10048
10450
|
embeddingBatchSize;
|
|
10049
10451
|
embeddingBatchChars;
|
|
10050
10452
|
embeddingInitTimeoutMs;
|
|
10051
|
-
modelDimension;
|
|
10453
|
+
modelDimension = null;
|
|
10052
10454
|
embeddingConfig;
|
|
10053
10455
|
isVectorSearchEnabled = false;
|
|
10054
10456
|
/**
|
|
@@ -10366,6 +10768,18 @@ class DocumentStore {
|
|
|
10366
10768
|
stmt.run("embedding_model", model);
|
|
10367
10769
|
stmt.run("embedding_dimension", String(dimension));
|
|
10368
10770
|
}
|
|
10771
|
+
getStoredDimensionForCurrentModel() {
|
|
10772
|
+
const config = this.embeddingConfig;
|
|
10773
|
+
if (!config) {
|
|
10774
|
+
return null;
|
|
10775
|
+
}
|
|
10776
|
+
const stored = this.getEmbeddingMetadata();
|
|
10777
|
+
if (stored.model !== config.modelSpec || stored.dimension === null) {
|
|
10778
|
+
return null;
|
|
10779
|
+
}
|
|
10780
|
+
const dimension = Number(stored.dimension);
|
|
10781
|
+
return Number.isInteger(dimension) && dimension >= 1 ? dimension : null;
|
|
10782
|
+
}
|
|
10369
10783
|
/**
|
|
10370
10784
|
* Compares the configured embedding model and dimension against stored metadata.
|
|
10371
10785
|
* Throws EmbeddingModelChangedError if either has changed since the last run.
|
|
@@ -10386,8 +10800,8 @@ class DocumentStore {
|
|
|
10386
10800
|
if (stored.model === null) {
|
|
10387
10801
|
return;
|
|
10388
10802
|
}
|
|
10389
|
-
const currentModel = this.
|
|
10390
|
-
const currentDimension = String(this.
|
|
10803
|
+
const currentModel = this.embeddingConfig.modelSpec;
|
|
10804
|
+
const currentDimension = String(this.dbDimension);
|
|
10391
10805
|
const modelChanged = stored.model !== currentModel;
|
|
10392
10806
|
const dimensionChanged = stored.dimension !== null && stored.dimension !== currentDimension;
|
|
10393
10807
|
if (modelChanged || dimensionChanged) {
|
|
@@ -10457,72 +10871,153 @@ class DocumentStore {
|
|
|
10457
10871
|
return;
|
|
10458
10872
|
}
|
|
10459
10873
|
try {
|
|
10460
|
-
this.embeddings
|
|
10461
|
-
|
|
10462
|
-
vectorDimension: this.dbDimension
|
|
10463
|
-
});
|
|
10464
|
-
if (config.dimensions !== null) {
|
|
10465
|
-
this.modelDimension = config.dimensions;
|
|
10466
|
-
} else {
|
|
10467
|
-
const testPromise = this.embeddings.embedQuery("test");
|
|
10468
|
-
let timeoutId;
|
|
10469
|
-
const timeoutPromise = new Promise((_, reject) => {
|
|
10470
|
-
timeoutId = setTimeout(() => {
|
|
10471
|
-
reject(
|
|
10472
|
-
new Error(
|
|
10473
|
-
`Embedding service connection timed out after ${this.embeddingInitTimeoutMs / 1e3} seconds`
|
|
10474
|
-
)
|
|
10475
|
-
);
|
|
10476
|
-
}, this.embeddingInitTimeoutMs);
|
|
10477
|
-
});
|
|
10478
|
-
try {
|
|
10479
|
-
const testVector = await Promise.race([testPromise, timeoutPromise]);
|
|
10480
|
-
this.modelDimension = testVector.length;
|
|
10481
|
-
} finally {
|
|
10482
|
-
if (timeoutId !== void 0) {
|
|
10483
|
-
clearTimeout(timeoutId);
|
|
10484
|
-
}
|
|
10485
|
-
}
|
|
10486
|
-
EmbeddingConfig.setKnownModelDimensions(config.model, this.modelDimension);
|
|
10874
|
+
if (this.embeddings === null) {
|
|
10875
|
+
this.embeddings = this.createEmbeddingClient(this.dbDimension);
|
|
10487
10876
|
}
|
|
10877
|
+
const modelDimension = this.modelDimension ?? this.dbDimension;
|
|
10488
10878
|
if (this.embeddings instanceof FixedDimensionEmbeddings && this.embeddings.allowTruncate) {
|
|
10489
|
-
this.modelDimension = Math.min(
|
|
10879
|
+
this.modelDimension = Math.min(modelDimension, this.dbDimension);
|
|
10880
|
+
} else {
|
|
10881
|
+
this.modelDimension = modelDimension;
|
|
10490
10882
|
}
|
|
10491
10883
|
if (this.modelDimension > this.dbDimension) {
|
|
10492
10884
|
throw new DimensionError(config.modelSpec, this.modelDimension, this.dbDimension);
|
|
10493
10885
|
}
|
|
10494
10886
|
this.isVectorSearchEnabled = true;
|
|
10495
10887
|
logger.debug(
|
|
10496
|
-
`Embeddings initialized: ${config.provider}:${config.model} (${this.
|
|
10888
|
+
`Embeddings initialized: ${config.provider}:${config.model} (${this.dbDimension}d)`
|
|
10497
10889
|
);
|
|
10498
10890
|
this.setEmbeddingMetadata(config.modelSpec, this.dbDimension);
|
|
10499
10891
|
} catch (error) {
|
|
10500
|
-
|
|
10501
|
-
|
|
10502
|
-
|
|
10503
|
-
|
|
10504
|
-
|
|
10505
|
-
|
|
10892
|
+
this.throwEmbeddingInitializationError(error, config);
|
|
10893
|
+
}
|
|
10894
|
+
}
|
|
10895
|
+
createEmbeddingClient(vectorDimension) {
|
|
10896
|
+
const config = this.embeddingConfig;
|
|
10897
|
+
if (!config) {
|
|
10898
|
+
throw new StoreError("Cannot create embedding client without configuration");
|
|
10899
|
+
}
|
|
10900
|
+
return createEmbeddingModel(config.modelSpec, {
|
|
10901
|
+
requestTimeoutMs: this.config.embeddings.requestTimeoutMs,
|
|
10902
|
+
vectorDimension
|
|
10903
|
+
});
|
|
10904
|
+
}
|
|
10905
|
+
async detectEmbeddingDimension(embeddings) {
|
|
10906
|
+
const testPromise = embeddings.embedQuery("test");
|
|
10907
|
+
let timeoutId;
|
|
10908
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
10909
|
+
timeoutId = setTimeout(() => {
|
|
10910
|
+
reject(
|
|
10911
|
+
new Error(
|
|
10912
|
+
`Embedding service connection timed out after ${this.embeddingInitTimeoutMs / 1e3} seconds`
|
|
10913
|
+
)
|
|
10914
|
+
);
|
|
10915
|
+
}, this.embeddingInitTimeoutMs);
|
|
10916
|
+
});
|
|
10917
|
+
try {
|
|
10918
|
+
const testVector = await Promise.race([testPromise, timeoutPromise]);
|
|
10919
|
+
return testVector.length;
|
|
10920
|
+
} finally {
|
|
10921
|
+
if (timeoutId !== void 0) {
|
|
10922
|
+
clearTimeout(timeoutId);
|
|
10923
|
+
}
|
|
10924
|
+
}
|
|
10925
|
+
}
|
|
10926
|
+
async resolveEffectiveEmbeddingDimension(options = {}) {
|
|
10927
|
+
this.validateVectorDimension(this.dbDimension);
|
|
10928
|
+
if (this.embeddingConfig === null || this.embeddingConfig === void 0) {
|
|
10929
|
+
return;
|
|
10930
|
+
}
|
|
10931
|
+
const config = this.embeddingConfig;
|
|
10932
|
+
if (!areCredentialsAvailable(config.provider)) {
|
|
10933
|
+
return;
|
|
10934
|
+
}
|
|
10935
|
+
try {
|
|
10936
|
+
const storedDimension = options.ignoreStoredMetadata ? null : this.getStoredDimensionForCurrentModel();
|
|
10937
|
+
if (storedDimension !== null) {
|
|
10938
|
+
if (!isVectorDimensionExplicit(this.config)) {
|
|
10939
|
+
this.dbDimension = storedDimension;
|
|
10940
|
+
}
|
|
10941
|
+
this.modelDimension = this.dbDimension;
|
|
10942
|
+
logger.debug(
|
|
10943
|
+
`Vector dimension loaded from metadata: ${this.dbDimension} for ${config.provider}:${config.model}`
|
|
10944
|
+
);
|
|
10945
|
+
return;
|
|
10946
|
+
}
|
|
10947
|
+
const stored = this.getEmbeddingMetadata();
|
|
10948
|
+
if (!options.ignoreStoredMetadata && stored.model !== null && stored.model !== config.modelSpec) {
|
|
10949
|
+
if (!isVectorDimensionExplicit(this.config) && config.dimensions !== null) {
|
|
10950
|
+
this.validateDetectedVectorDimension(
|
|
10951
|
+
config.dimensions,
|
|
10952
|
+
"known model dimension lookup"
|
|
10506
10953
|
);
|
|
10954
|
+
this.dbDimension = config.dimensions;
|
|
10955
|
+
this.modelDimension = config.dimensions;
|
|
10507
10956
|
}
|
|
10508
|
-
|
|
10509
|
-
|
|
10510
|
-
|
|
10957
|
+
return;
|
|
10958
|
+
}
|
|
10959
|
+
let nativeDimension = config.dimensions;
|
|
10960
|
+
let nativeDimensionSource = "known model dimension lookup";
|
|
10961
|
+
if (nativeDimension === null) {
|
|
10962
|
+
this.embeddings = this.createEmbeddingClient(this.dbDimension);
|
|
10963
|
+
nativeDimension = await this.detectEmbeddingDimension(this.embeddings);
|
|
10964
|
+
nativeDimensionSource = "embedding provider probe";
|
|
10965
|
+
}
|
|
10966
|
+
this.validateDetectedVectorDimension(nativeDimension, nativeDimensionSource);
|
|
10967
|
+
if (config.dimensions === null) {
|
|
10968
|
+
EmbeddingConfig.setKnownModelDimensions(config.model, nativeDimension);
|
|
10969
|
+
}
|
|
10970
|
+
this.modelDimension = nativeDimension;
|
|
10971
|
+
if (!isVectorDimensionExplicit(this.config)) {
|
|
10972
|
+
this.dbDimension = nativeDimension;
|
|
10973
|
+
logger.info(
|
|
10974
|
+
`📐 Vector dimension auto-resolved to ${this.dbDimension} for ${config.provider}:${config.model}`
|
|
10975
|
+
);
|
|
10976
|
+
}
|
|
10977
|
+
} catch (error) {
|
|
10978
|
+
this.throwEmbeddingInitializationError(error, config);
|
|
10979
|
+
}
|
|
10980
|
+
}
|
|
10981
|
+
validateVectorDimension(dim) {
|
|
10982
|
+
if (typeof dim !== "number" || !Number.isInteger(dim) || dim < 1) {
|
|
10983
|
+
throw new StoreError(
|
|
10984
|
+
`Invalid embeddings.vectorDimension: ${dim}. Must be a positive integer.`
|
|
10985
|
+
);
|
|
10986
|
+
}
|
|
10987
|
+
}
|
|
10988
|
+
validateDetectedVectorDimension(dim, source) {
|
|
10989
|
+
if (typeof dim !== "number" || !Number.isInteger(dim) || dim < 1) {
|
|
10990
|
+
throw new StoreError(
|
|
10991
|
+
`Invalid detected embedding dimension from ${source}: ${dim}. Must be a positive integer.`
|
|
10992
|
+
);
|
|
10993
|
+
}
|
|
10994
|
+
}
|
|
10995
|
+
throwEmbeddingInitializationError(error, config) {
|
|
10996
|
+
if (error instanceof Error) {
|
|
10997
|
+
if (error.message.includes("does not exist") || error.message.includes("MODEL_NOT_FOUND")) {
|
|
10998
|
+
throw new ModelConfigurationError(
|
|
10999
|
+
`Invalid embedding model: ${config.model}
|
|
11000
|
+
The model "${config.model}" is not available or you don't have access to it.
|
|
11001
|
+
See README.md for supported models or run with --help for more details.`
|
|
11002
|
+
);
|
|
11003
|
+
}
|
|
11004
|
+
if (error.message.includes("API key") || error.message.includes("401") || error.message.includes("authentication")) {
|
|
11005
|
+
throw new ModelConfigurationError(
|
|
11006
|
+
`Authentication failed for ${config.provider} embedding provider
|
|
10511
11007
|
Please check your API key configuration.
|
|
10512
11008
|
See README.md for configuration options or run with --help for more details.`
|
|
10513
|
-
|
|
10514
|
-
|
|
10515
|
-
|
|
10516
|
-
|
|
10517
|
-
|
|
11009
|
+
);
|
|
11010
|
+
}
|
|
11011
|
+
if (error.message.includes("timed out") || error.message.includes("ECONNREFUSED") || error.message.includes("ENOTFOUND") || error.message.includes("ETIMEDOUT") || error.message.includes("ECONNRESET") || error.message.includes("network") || error.message.includes("fetch failed")) {
|
|
11012
|
+
throw new ModelConfigurationError(
|
|
11013
|
+
`Failed to connect to ${config.provider} embedding service
|
|
10518
11014
|
${error.message}
|
|
10519
11015
|
Please check that the embedding service is running and accessible.
|
|
10520
11016
|
If using a local model (e.g., Ollama), ensure the service is started.`
|
|
10521
|
-
|
|
10522
|
-
}
|
|
11017
|
+
);
|
|
10523
11018
|
}
|
|
10524
|
-
throw error;
|
|
10525
11019
|
}
|
|
11020
|
+
throw error;
|
|
10526
11021
|
}
|
|
10527
11022
|
/**
|
|
10528
11023
|
* Generates a safe FTS query by tokenizing the input and escaping for FTS5.
|
|
@@ -10601,6 +11096,7 @@ class DocumentStore {
|
|
|
10601
11096
|
maxRetries: this.config.db.migrationMaxRetries,
|
|
10602
11097
|
retryDelayMs: this.config.db.migrationRetryDelayMs
|
|
10603
11098
|
});
|
|
11099
|
+
await this.resolveEffectiveEmbeddingDimension();
|
|
10604
11100
|
this.checkEmbeddingModelChange();
|
|
10605
11101
|
this.ensureVectorTable();
|
|
10606
11102
|
this.prepareStatements();
|
|
@@ -10621,8 +11117,9 @@ class DocumentStore {
|
|
|
10621
11117
|
* completed here after invalidation.
|
|
10622
11118
|
*/
|
|
10623
11119
|
async resolveModelChange() {
|
|
11120
|
+
await this.resolveEffectiveEmbeddingDimension({ ignoreStoredMetadata: true });
|
|
10624
11121
|
const currentModel = this.config.app.embeddingModel;
|
|
10625
|
-
const currentDimension = this.
|
|
11122
|
+
const currentDimension = this.dbDimension;
|
|
10626
11123
|
this.invalidateAllVectors(currentModel, currentDimension);
|
|
10627
11124
|
this.ensureVectorTable();
|
|
10628
11125
|
this.prepareStatements();
|
|
@@ -10647,12 +11144,8 @@ class DocumentStore {
|
|
|
10647
11144
|
* and are handled by the model change detection system (checkEmbeddingModelChange).
|
|
10648
11145
|
*/
|
|
10649
11146
|
ensureVectorTable() {
|
|
10650
|
-
const dim = this.
|
|
10651
|
-
|
|
10652
|
-
throw new StoreError(
|
|
10653
|
-
`Invalid embeddings.vectorDimension: ${dim}. Must be a positive integer.`
|
|
10654
|
-
);
|
|
10655
|
-
}
|
|
11147
|
+
const dim = this.dbDimension;
|
|
11148
|
+
this.validateVectorDimension(dim);
|
|
10656
11149
|
const existingSql = this.db.prepare(
|
|
10657
11150
|
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'documents_vec';"
|
|
10658
11151
|
).get();
|
|
@@ -10970,7 +11463,11 @@ class DocumentStore {
|
|
|
10970
11463
|
return [];
|
|
10971
11464
|
}
|
|
10972
11465
|
try {
|
|
10973
|
-
|
|
11466
|
+
const embeddings = this.embeddings;
|
|
11467
|
+
if (embeddings === null) {
|
|
11468
|
+
throw new StoreError("Embeddings are not initialized");
|
|
11469
|
+
}
|
|
11470
|
+
return await embeddings.embedDocuments(texts);
|
|
10974
11471
|
} catch (error) {
|
|
10975
11472
|
if (this.isInputSizeError(error)) {
|
|
10976
11473
|
if (texts.length > 1) {
|
|
@@ -11290,7 +11787,7 @@ class DocumentStore {
|
|
|
11290
11787
|
return [];
|
|
11291
11788
|
}
|
|
11292
11789
|
const { id: versionId } = versionRow;
|
|
11293
|
-
if (this.isVectorSearchEnabled) {
|
|
11790
|
+
if (this.isVectorSearchEnabled && this.embeddings !== null) {
|
|
11294
11791
|
const rawEmbedding = await this.embeddings.embedQuery(query);
|
|
11295
11792
|
const embedding = this.padVector(rawEmbedding);
|
|
11296
11793
|
const overfetchLimit = Math.max(1, limit * this.searchOverfetchFactor);
|
|
@@ -12812,7 +13309,7 @@ const Layout = ({
|
|
|
12812
13309
|
children,
|
|
12813
13310
|
eventClientConfig
|
|
12814
13311
|
}) => {
|
|
12815
|
-
const versionString = version || "2.4.
|
|
13312
|
+
const versionString = version || "2.4.2";
|
|
12816
13313
|
const versionInitializer = `versionUpdate({ currentVersion: ${`'${versionString}'`} })`;
|
|
12817
13314
|
return /* @__PURE__ */ jsxs("html", { lang: "en", children: [
|
|
12818
13315
|
/* @__PURE__ */ jsxs("head", { children: [
|
|
@@ -15098,7 +15595,7 @@ class AppServer {
|
|
|
15098
15595
|
try {
|
|
15099
15596
|
if (telemetry.isEnabled()) {
|
|
15100
15597
|
telemetry.setGlobalContext({
|
|
15101
|
-
appVersion: "2.4.
|
|
15598
|
+
appVersion: "2.4.2",
|
|
15102
15599
|
appPlatform: process.platform,
|
|
15103
15600
|
appNodeVersion: process.version,
|
|
15104
15601
|
appServicesEnabled: this.getActiveServicesList(),
|
|
@@ -15133,7 +15630,7 @@ class AppServer {
|
|
|
15133
15630
|
}
|
|
15134
15631
|
await this.setupServer();
|
|
15135
15632
|
try {
|
|
15136
|
-
|
|
15633
|
+
await this.server.listen({
|
|
15137
15634
|
port: this.serverConfig.port,
|
|
15138
15635
|
host: this.appConfig.server.host
|
|
15139
15636
|
});
|
|
@@ -15143,7 +15640,7 @@ class AppServer {
|
|
|
15143
15640
|
if (this.remoteEventProxy) {
|
|
15144
15641
|
this.remoteEventProxy.connect();
|
|
15145
15642
|
}
|
|
15146
|
-
this.logStartupInfo(
|
|
15643
|
+
this.logStartupInfo(this.getCanonicalOrigin());
|
|
15147
15644
|
return this.server;
|
|
15148
15645
|
} catch (error) {
|
|
15149
15646
|
logger.error(`❌ Failed to start AppServer: ${error}`);
|
|
@@ -15419,10 +15916,18 @@ class AppServer {
|
|
|
15419
15916
|
if (!this.authManager) {
|
|
15420
15917
|
return;
|
|
15421
15918
|
}
|
|
15422
|
-
const baseUrl = new URL(
|
|
15919
|
+
const baseUrl = new URL(this.getCanonicalOrigin());
|
|
15423
15920
|
this.authManager.registerRoutes(this.server, baseUrl);
|
|
15921
|
+
if (!this.appConfig.server.publicOrigin && isWildcardBindHost(this.appConfig.server.host)) {
|
|
15922
|
+
logger.warn(
|
|
15923
|
+
"⚠️ Authentication is enabled with a wildcard bind host and no public origin. Configure server.publicOrigin or --public-origin for remote OAuth clients."
|
|
15924
|
+
);
|
|
15925
|
+
}
|
|
15424
15926
|
logger.debug("OAuth2 proxy endpoints registered");
|
|
15425
15927
|
}
|
|
15928
|
+
getCanonicalOrigin() {
|
|
15929
|
+
return getCanonicalServerOrigin(this.appConfig, this.serverConfig.port);
|
|
15930
|
+
}
|
|
15426
15931
|
/**
|
|
15427
15932
|
* Log startup information showing which services are enabled.
|
|
15428
15933
|
*/
|
|
@@ -18660,6 +19165,10 @@ function createDefaultAction(cli) {
|
|
|
18660
19165
|
}).option("host", {
|
|
18661
19166
|
type: "string",
|
|
18662
19167
|
description: "Host to bind the server to"
|
|
19168
|
+
}).option("public-origin", {
|
|
19169
|
+
type: "string",
|
|
19170
|
+
description: "Public origin advertised to clients (e.g., https://docs.example.com)",
|
|
19171
|
+
alias: "publicOrigin"
|
|
18663
19172
|
}).option("embedding-model", {
|
|
18664
19173
|
type: "string",
|
|
18665
19174
|
description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
|
|
@@ -18951,6 +19460,10 @@ function createMcpCommand(cli) {
|
|
|
18951
19460
|
}).option("host", {
|
|
18952
19461
|
type: "string",
|
|
18953
19462
|
description: "Host to bind the MCP server to"
|
|
19463
|
+
}).option("public-origin", {
|
|
19464
|
+
type: "string",
|
|
19465
|
+
description: "Public origin advertised to clients (e.g., https://docs.example.com)",
|
|
19466
|
+
alias: "publicOrigin"
|
|
18954
19467
|
}).option("embedding-model", {
|
|
18955
19468
|
type: "string",
|
|
18956
19469
|
description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
|
|
@@ -19555,6 +20068,10 @@ function createWebCommand(cli) {
|
|
|
19555
20068
|
}).option("host", {
|
|
19556
20069
|
type: "string",
|
|
19557
20070
|
description: "Host to bind the web interface to"
|
|
20071
|
+
}).option("public-origin", {
|
|
20072
|
+
type: "string",
|
|
20073
|
+
description: "Public origin advertised to clients (e.g., https://docs.example.com)",
|
|
20074
|
+
alias: "publicOrigin"
|
|
19558
20075
|
}).option("embedding-model", {
|
|
19559
20076
|
type: "string",
|
|
19560
20077
|
description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
|
|
@@ -19645,6 +20162,10 @@ function createWorkerCommand(cli) {
|
|
|
19645
20162
|
}).option("host", {
|
|
19646
20163
|
type: "string",
|
|
19647
20164
|
description: "Host to bind the worker API to"
|
|
20165
|
+
}).option("public-origin", {
|
|
20166
|
+
type: "string",
|
|
20167
|
+
description: "Public origin advertised to clients (e.g., https://docs.example.com)",
|
|
20168
|
+
alias: "publicOrigin"
|
|
19648
20169
|
}).option("embedding-model", {
|
|
19649
20170
|
type: "string",
|
|
19650
20171
|
description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
|
|
@@ -19723,7 +20244,7 @@ function createCli(argv) {
|
|
|
19723
20244
|
let globalEventBus = null;
|
|
19724
20245
|
let globalTelemetryService = null;
|
|
19725
20246
|
const commandStartTimes = /* @__PURE__ */ new Map();
|
|
19726
|
-
const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.4.
|
|
20247
|
+
const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.4.2").option("verbose", {
|
|
19727
20248
|
type: "boolean",
|
|
19728
20249
|
description: "Enable verbose (debug) logging",
|
|
19729
20250
|
default: false
|
|
@@ -19784,7 +20305,7 @@ function createCli(argv) {
|
|
|
19784
20305
|
if (shouldEnableTelemetry() && telemetry.isEnabled()) {
|
|
19785
20306
|
const commandName = argv2._[0]?.toString() || "default";
|
|
19786
20307
|
telemetry.setGlobalContext({
|
|
19787
|
-
appVersion: "2.4.
|
|
20308
|
+
appVersion: "2.4.2",
|
|
19788
20309
|
appPlatform: process.platform,
|
|
19789
20310
|
appNodeVersion: process.version,
|
|
19790
20311
|
appInterface: "cli",
|
|
@@ -19930,4 +20451,4 @@ export {
|
|
|
19930
20451
|
cleanupCliCommand,
|
|
19931
20452
|
runCli
|
|
19932
20453
|
};
|
|
19933
|
-
//# sourceMappingURL=main-
|
|
20454
|
+
//# sourceMappingURL=main-WZKPkgC6.js.map
|