doccupine 0.0.158 → 0.0.160
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 +56 -4
- package/dist/generator/app-scaffolder.js +11 -3
- package/dist/generator/generated-page-publisher.d.ts +6 -6
- package/dist/generator/generated-page-publisher.js +7 -5
- package/dist/generator/mdx-pass-builder.d.ts +4 -4
- package/dist/generator/mdx-pass-builder.js +8 -1
- package/dist/generator/mdx-reconciliation-coordinator.d.ts +23 -9
- package/dist/generator/mdx-reconciliation-coordinator.js +63 -9
- package/dist/generator/page-catalog.d.ts +2 -4
- package/dist/generator/page-catalog.js +7 -2
- package/dist/generator/page-renderer.d.ts +15 -5
- package/dist/generator/page-renderer.js +38 -11
- package/dist/generator/project-config-repository.d.ts +4 -1
- package/dist/generator/project-config-repository.js +26 -0
- package/dist/generator/public-asset-manager.d.ts +10 -0
- package/dist/generator/public-asset-manager.js +63 -3
- package/dist/generator/section-index-generator.d.ts +10 -1
- package/dist/generator/section-index-generator.js +43 -15
- package/dist/generator/section-resolver.d.ts +8 -0
- package/dist/generator/site-artifacts.d.ts +4 -3
- package/dist/generator/site-artifacts.js +94 -9
- package/dist/generator/watch-coordinator.js +6 -1
- package/dist/lib/generated-artifacts.d.ts +3 -0
- package/dist/lib/generated-artifacts.js +36 -0
- package/dist/lib/layout.d.ts +6 -3
- package/dist/lib/layout.js +107 -4
- package/dist/lib/metadata.d.ts +7 -0
- package/dist/lib/metadata.js +33 -10
- package/dist/lib/structures.js +20 -0
- package/dist/lib/types.d.ts +28 -0
- package/dist/lib/ui-strings.d.ts +44 -0
- package/dist/lib/ui-strings.js +48 -0
- package/dist/lib/variants.d.ts +91 -0
- package/dist/lib/variants.js +411 -0
- package/dist/mdx-to-nextjs-generator.d.ts +22 -5
- package/dist/mdx-to-nextjs-generator.js +89 -10
- package/dist/templates/app/api/mcp/route.d.ts +1 -1
- package/dist/templates/app/api/mcp/route.js +14 -1
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +13 -2
- package/dist/templates/app/api/search/route.d.ts +1 -1
- package/dist/templates/app/api/search/route.js +16 -1
- package/dist/templates/app/sitemap.d.ts +2 -0
- package/dist/templates/app/sitemap.js +48 -3
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +40 -12
- package/dist/templates/components/Docs.d.ts +1 -1
- package/dist/templates/components/Docs.js +5 -2
- package/dist/templates/components/DocsSideBar.d.ts +1 -1
- package/dist/templates/components/DocsSideBar.js +3 -1
- package/dist/templates/components/SearchDocs.d.ts +1 -1
- package/dist/templates/components/SearchDocs.js +17 -3
- package/dist/templates/components/SearchModalContent.d.ts +1 -1
- package/dist/templates/components/SearchModalContent.js +22 -14
- package/dist/templates/components/SectionNavProvider.d.ts +1 -1
- package/dist/templates/components/SectionNavProvider.js +32 -20
- package/dist/templates/components/SideBar.d.ts +1 -1
- package/dist/templates/components/SideBar.js +26 -12
- package/dist/templates/components/layout/ActionBar.d.ts +1 -1
- package/dist/templates/components/layout/ActionBar.js +9 -7
- package/dist/templates/components/layout/Code.d.ts +1 -1
- package/dist/templates/components/layout/Code.js +6 -3
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +38 -5
- package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
- package/dist/templates/components/layout/DocsNavigation.js +4 -2
- package/dist/templates/components/layout/Dropdown.d.ts +1 -0
- package/dist/templates/components/layout/Dropdown.js +308 -0
- package/dist/templates/components/layout/FocusModeToggle.d.ts +1 -1
- package/dist/templates/components/layout/FocusModeToggle.js +7 -4
- package/dist/templates/components/layout/Footer.d.ts +1 -1
- package/dist/templates/components/layout/Footer.js +4 -2
- package/dist/templates/components/layout/Header.d.ts +1 -1
- package/dist/templates/components/layout/Header.js +18 -8
- package/dist/templates/components/layout/SectionBar.d.ts +1 -1
- package/dist/templates/components/layout/SectionBar.js +16 -10
- package/dist/templates/components/layout/VariantSwitchers.d.ts +1 -0
- package/dist/templates/components/layout/VariantSwitchers.js +313 -0
- package/dist/templates/components/useStrings.d.ts +1 -0
- package/dist/templates/components/useStrings.js +10 -0
- package/dist/templates/components/useVariant.d.ts +1 -0
- package/dist/templates/components/useVariant.js +13 -0
- package/dist/templates/env.example.d.ts +1 -1
- package/dist/templates/env.example.js +2 -1
- package/dist/templates/llms/llmsIndex.d.ts +13 -0
- package/dist/templates/llms/llmsIndex.js +18 -3
- package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/ai-assistant.mdx.js +9 -3
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/api-playground.mdx.js +2 -0
- package/dist/templates/mdx/commands.mdx.d.ts +1 -1
- package/dist/templates/mdx/commands.mdx.js +1 -1
- package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
- package/dist/templates/mdx/fonts.mdx.js +1 -1
- package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
- package/dist/templates/mdx/footer-links.mdx.js +1 -1
- package/dist/templates/mdx/index.mdx.d.ts +1 -1
- package/dist/templates/mdx/index.mdx.js +2 -0
- package/dist/templates/mdx/languages.mdx.d.ts +1 -0
- package/dist/templates/mdx/languages.mdx.js +94 -0
- package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
- package/dist/templates/mdx/media-and-assets.mdx.js +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.js +6 -0
- package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
- package/dist/templates/mdx/navigation.mdx.js +2 -0
- package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/ai-assistant.mdx.js +2 -0
- package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/api-playground.mdx.js +2 -0
- package/dist/templates/mdx/platform/file-editor.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/file-editor.mdx.js +2 -0
- package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/index.mdx.js +1 -1
- package/dist/templates/mdx/platform/languages.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/languages.mdx.js +50 -0
- package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/mcp.mdx.js +2 -0
- package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.js +2 -0
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +4 -0
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +2 -0
- package/dist/templates/mdx/platform/versions.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/versions.mdx.js +33 -0
- package/dist/templates/mdx/sections.mdx.d.ts +1 -1
- package/dist/templates/mdx/sections.mdx.js +1 -1
- package/dist/templates/mdx/theme.mdx.d.ts +1 -1
- package/dist/templates/mdx/theme.mdx.js +1 -1
- package/dist/templates/mdx/versions.mdx.d.ts +1 -0
- package/dist/templates/mdx/versions.mdx.js +78 -0
- package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
- package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
- package/dist/templates/package.js +20 -20
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +2 -0
- package/dist/templates/services/llm/config.d.ts +1 -1
- package/dist/templates/services/llm/config.js +50 -3
- package/dist/templates/services/llm/factory.d.ts +1 -1
- package/dist/templates/services/llm/factory.js +6 -3
- package/dist/templates/services/llm/types.d.ts +1 -1
- package/dist/templates/services/llm/types.js +2 -1
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +54 -10
- package/dist/templates/services/mcp/tools.d.ts +1 -1
- package/dist/templates/services/mcp/tools.js +81 -6
- package/dist/templates/services/mcp/types.d.ts +1 -1
- package/dist/templates/services/mcp/types.js +10 -0
- package/dist/templates/services/search.d.ts +1 -1
- package/dist/templates/services/search.js +34 -4
- package/dist/templates/utils/orderNavItems.d.ts +1 -1
- package/dist/templates/utils/orderNavItems.js +2 -0
- package/dist/templates/utils/strings.d.ts +1 -0
- package/dist/templates/utils/strings.js +27 -0
- package/dist/templates/utils/variants.d.ts +1 -0
- package/dist/templates/utils/variants.js +170 -0
- package/package.json +11 -11
|
@@ -12,48 +12,48 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
12
12
|
"type-check": "tsgo --noEmit",
|
|
13
13
|
},
|
|
14
14
|
dependencies: {
|
|
15
|
-
"@langchain/anthropic": "^1.5.
|
|
16
|
-
"@langchain/core": "^1.2.
|
|
17
|
-
"@langchain/google-genai": "^2.3.
|
|
18
|
-
"@langchain/openai": "^1.
|
|
15
|
+
"@langchain/anthropic": "^1.5.12",
|
|
16
|
+
"@langchain/core": "^1.2.14",
|
|
17
|
+
"@langchain/google-genai": "^2.3.2",
|
|
18
|
+
"@langchain/openai": "^1.6.2",
|
|
19
19
|
"@mdx-js/react": "^3.1.1",
|
|
20
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
20
|
+
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
21
21
|
"beautiful-mermaid": "^1.1.3",
|
|
22
22
|
"cherry-styled-components": "^0.2.17",
|
|
23
|
-
langchain: "^1.5.
|
|
24
|
-
"lucide-react": "^1.
|
|
23
|
+
langchain: "^1.5.15",
|
|
24
|
+
"lucide-react": "^1.52.0",
|
|
25
25
|
minisearch: "^7.2.0",
|
|
26
|
-
next: "16.3.
|
|
26
|
+
next: "16.3.8",
|
|
27
27
|
"next-mdx-remote": "^6.0.0",
|
|
28
|
-
"posthog-js": "^1.
|
|
29
|
-
"posthog-node": "^5.
|
|
30
|
-
react: "19.
|
|
31
|
-
"react-dom": "19.
|
|
28
|
+
"posthog-js": "^1.436.1",
|
|
29
|
+
"posthog-node": "^5.55.0",
|
|
30
|
+
react: "19.3.0",
|
|
31
|
+
"react-dom": "19.3.0",
|
|
32
32
|
"rehype-highlight": "^7.0.2",
|
|
33
33
|
"rehype-parse": "^9.0.1",
|
|
34
34
|
"rehype-stringify": "^10.0.1",
|
|
35
35
|
"remark-gfm": "^4.0.1",
|
|
36
36
|
"styled-components": "^6.5.3",
|
|
37
37
|
unified: "^11.0.5",
|
|
38
|
-
zod: "^4.5
|
|
38
|
+
zod: "^4.6.5",
|
|
39
39
|
},
|
|
40
40
|
devDependencies: {
|
|
41
|
-
"@next/env": "16.3.
|
|
42
|
-
"@next/eslint-plugin-next": "16.3.
|
|
41
|
+
"@next/env": "16.3.8",
|
|
42
|
+
"@next/eslint-plugin-next": "16.3.8",
|
|
43
43
|
"@types/node": "^26",
|
|
44
44
|
"@types/react": "^19",
|
|
45
45
|
"@types/react-dom": "^19",
|
|
46
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
47
|
-
"@typescript-eslint/parser": "^8.
|
|
46
|
+
"@typescript-eslint/eslint-plugin": "^8.71.1",
|
|
47
|
+
"@typescript-eslint/parser": "^8.71.1",
|
|
48
48
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|
|
49
49
|
eslint: "^10",
|
|
50
50
|
"eslint-plugin-import": "^2.32.0",
|
|
51
51
|
"eslint-plugin-jsx-a11y": "^6.10.2",
|
|
52
52
|
"eslint-plugin-react": "^7.37.5",
|
|
53
53
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
54
|
-
globals: "^17.
|
|
55
|
-
prettier: "^3.9.
|
|
56
|
-
tsx: "^4.23.
|
|
54
|
+
globals: "^17.13.0",
|
|
55
|
+
prettier: "^3.9.9",
|
|
56
|
+
tsx: "^4.23.15",
|
|
57
57
|
typescript: "npm:@typescript/typescript6@^6.0.2",
|
|
58
58
|
},
|
|
59
59
|
}, null, 2) + "\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const prettierignoreTemplate = "node_modules\nconvex/_generated\npublic\npackage.json\npackage-lock.json\npnpm-lock.yaml\npnpm-workspace.yaml\nservices/mcp/docs-index.json\n.doccupine-*\n\n# Mirrored verbatim from the project root, so their formatting is the author's\n# choice rather than generated output. Reformatting them here would also make\n# the copy differ from the source it is fingerprinted against.\nanalytics.json\nconfig.json\nfonts.json\nlinks.json\nnavigation.json\nsections.json\ntheme.json\n";
|
|
1
|
+
export declare const prettierignoreTemplate = "node_modules\nconvex/_generated\npublic\npackage.json\npackage-lock.json\npnpm-lock.yaml\npnpm-workspace.yaml\nservices/mcp/docs-index.json\n.doccupine-*\n\n# Mirrored verbatim from the project root, so their formatting is the author's\n# choice rather than generated output. Reformatting them here would also make\n# the copy differ from the source it is fingerprinted against.\nanalytics.json\nconfig.json\nfonts.json\nlanguages.json\nlinks.json\nnavigation.json\nsections.json\ntheme.json\nversions.json\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const llmConfigTemplate = "import type {\n LLMConfig,\n LLMProvider,\n ProviderDefaults,\n} from \"@/services/llm/types\";\nconst PROVIDER_DEFAULTS: ProviderDefaults = {\n openai: {\n chat: \"gpt-4.1-
|
|
1
|
+
export declare const llmConfigTemplate = "import type {\n LLMConfig,\n LLMProvider,\n ProviderDefaults,\n} from \"@/services/llm/types\";\nconst PROVIDER_DEFAULTS: ProviderDefaults = {\n openai: {\n chat: \"gpt-4.1-mini\",\n embedding: \"text-embedding-3-small\",\n },\n anthropic: {\n chat: \"claude-sonnet-4-5-20250929\",\n embedding: \"text-embedding-3-small\", // Fallback to OpenAI\n },\n google: {\n chat: \"gemini-2.5-flash-lite\",\n embedding: \"gemini-embedding-001\",\n },\n};\n// Used when LLM_TEMPERATURE is unset, for models that accept a temperature.\nconst DEFAULT_TEMPERATURE = 0;\nconst MAX_TEMPERATURE: Record<LLMProvider, number> = {\n openai: 2,\n anthropic: 1,\n google: 2,\n};\n// OpenAI's reasoning models (o1, o3, o4-mini) and its GPT-5 line onwards reject\n// a custom temperature, some of them any temperature at all. A vendor prefix\n// such as OpenRouter's \"openai/\" is ignored.\nconst NO_TEMPERATURE_MODEL = /^(?:[\\w-]+\\/)?(?:gpt-(?:[5-9]|\\d{2,})|o\\d)/;\nconst warnings = new Set<string>();\nfunction warnOnce(message: string): void {\n if (warnings.has(message)) return;\n warnings.add(message);\n console.warn(message);\n}\nfunction acceptsTemperature(provider: LLMProvider, chatModel: string): boolean {\n return provider !== \"openai\" || !NO_TEMPERATURE_MODEL.test(chatModel);\n}\n// Returns undefined when no temperature should be sent, leaving the model on\n// its own default: LLM_TEMPERATURE=default, or a model that rejects one.\nfunction resolveTemperature(\n provider: LLMProvider,\n chatModel: string,\n): number | undefined {\n const raw = process.env.LLM_TEMPERATURE?.trim() ?? \"\";\n if (raw.toLowerCase() === \"default\") return undefined;\n const accepted = acceptsTemperature(provider, chatModel);\n if (raw === \"\") return accepted ? DEFAULT_TEMPERATURE : undefined;\n const value = Number(raw);\n const max = MAX_TEMPERATURE[provider];\n if (!Number.isFinite(value) || value < 0 || value > max) {\n warnOnce(\n `Ignoring LLM_TEMPERATURE=\"${raw}\": ${provider} accepts a number from 0 to ${max}, or \"default\".`,\n );\n return accepted ? DEFAULT_TEMPERATURE : undefined;\n }\n if (!accepted) {\n warnOnce(\n `Ignoring LLM_TEMPERATURE: ${chatModel} does not accept a custom temperature.`,\n );\n return undefined;\n }\n return value;\n}\nfunction validateAPIKeys(provider: LLMProvider): void {\n const requiredKeys: Record<LLMProvider, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n };\n const keyName = requiredKeys[provider];\n const keyValue = process.env[keyName];\n if (!keyValue) {\n throw new Error(\n `Missing API key for ${provider}. Please set ${keyName} in your environment variables.`,\n );\n }\n if (provider === \"anthropic\" && !process.env.OPENAI_API_KEY) {\n throw new Error(\n \"Anthropic provider requires OPENAI_API_KEY for embeddings. Please set OPENAI_API_KEY in your environment variables.\",\n );\n }\n}\nexport function isLLMAvailable(): boolean {\n const provider = (process.env.LLM_PROVIDER || \"openai\") as LLMProvider;\n const requiredKeys: Record<LLMProvider, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n };\n const keyName = requiredKeys[provider];\n if (!keyName || !process.env[keyName]) return false;\n if (provider === \"anthropic\" && !process.env.OPENAI_API_KEY) return false;\n return true;\n}\nexport function getLLMConfig(): LLMConfig {\n const provider = (process.env.LLM_PROVIDER || \"openai\") as LLMProvider;\n if (![\"openai\", \"anthropic\", \"google\"].includes(provider)) {\n throw new Error(\n `Invalid LLM_PROVIDER: ${provider}. Must be one of: openai, anthropic, google`,\n );\n }\n validateAPIKeys(provider);\n const defaults = PROVIDER_DEFAULTS[provider];\n // Vectors are Matryoshka-truncated to this many dimensions before being\n // stored as int8, keeping the prebuilt search index small. Must match between\n // build time and runtime; a mismatch forces a re-embed. Values >= the model's\n // native dimension keep full precision (default: 512).\n const rawDims = process.env.LLM_EMBEDDING_DIMS;\n let embeddingDims = 512;\n if (rawDims !== undefined && rawDims !== \"\") {\n const parsed = parseInt(rawDims, 10);\n if (Number.isFinite(parsed) && parsed >= 0) embeddingDims = parsed;\n }\n const chatModel = process.env.LLM_CHAT_MODEL || defaults.chat;\n return {\n provider,\n chatModel,\n embeddingModel: process.env.LLM_EMBEDDING_MODEL || defaults.embedding,\n embeddingDims,\n temperature: resolveTemperature(provider, chatModel),\n };\n}\n";
|
|
@@ -5,7 +5,7 @@ export const llmConfigTemplate = `import type {
|
|
|
5
5
|
} from "@/services/llm/types";
|
|
6
6
|
const PROVIDER_DEFAULTS: ProviderDefaults = {
|
|
7
7
|
openai: {
|
|
8
|
-
chat: "gpt-4.1-
|
|
8
|
+
chat: "gpt-4.1-mini",
|
|
9
9
|
embedding: "text-embedding-3-small",
|
|
10
10
|
},
|
|
11
11
|
anthropic: {
|
|
@@ -17,6 +17,52 @@ const PROVIDER_DEFAULTS: ProviderDefaults = {
|
|
|
17
17
|
embedding: "gemini-embedding-001",
|
|
18
18
|
},
|
|
19
19
|
};
|
|
20
|
+
// Used when LLM_TEMPERATURE is unset, for models that accept a temperature.
|
|
21
|
+
const DEFAULT_TEMPERATURE = 0;
|
|
22
|
+
const MAX_TEMPERATURE: Record<LLMProvider, number> = {
|
|
23
|
+
openai: 2,
|
|
24
|
+
anthropic: 1,
|
|
25
|
+
google: 2,
|
|
26
|
+
};
|
|
27
|
+
// OpenAI's reasoning models (o1, o3, o4-mini) and its GPT-5 line onwards reject
|
|
28
|
+
// a custom temperature, some of them any temperature at all. A vendor prefix
|
|
29
|
+
// such as OpenRouter's "openai/" is ignored.
|
|
30
|
+
const NO_TEMPERATURE_MODEL = /^(?:[\\w-]+\\/)?(?:gpt-(?:[5-9]|\\d{2,})|o\\d)/;
|
|
31
|
+
const warnings = new Set<string>();
|
|
32
|
+
function warnOnce(message: string): void {
|
|
33
|
+
if (warnings.has(message)) return;
|
|
34
|
+
warnings.add(message);
|
|
35
|
+
console.warn(message);
|
|
36
|
+
}
|
|
37
|
+
function acceptsTemperature(provider: LLMProvider, chatModel: string): boolean {
|
|
38
|
+
return provider !== "openai" || !NO_TEMPERATURE_MODEL.test(chatModel);
|
|
39
|
+
}
|
|
40
|
+
// Returns undefined when no temperature should be sent, leaving the model on
|
|
41
|
+
// its own default: LLM_TEMPERATURE=default, or a model that rejects one.
|
|
42
|
+
function resolveTemperature(
|
|
43
|
+
provider: LLMProvider,
|
|
44
|
+
chatModel: string,
|
|
45
|
+
): number | undefined {
|
|
46
|
+
const raw = process.env.LLM_TEMPERATURE?.trim() ?? "";
|
|
47
|
+
if (raw.toLowerCase() === "default") return undefined;
|
|
48
|
+
const accepted = acceptsTemperature(provider, chatModel);
|
|
49
|
+
if (raw === "") return accepted ? DEFAULT_TEMPERATURE : undefined;
|
|
50
|
+
const value = Number(raw);
|
|
51
|
+
const max = MAX_TEMPERATURE[provider];
|
|
52
|
+
if (!Number.isFinite(value) || value < 0 || value > max) {
|
|
53
|
+
warnOnce(
|
|
54
|
+
\`Ignoring LLM_TEMPERATURE="\${raw}": \${provider} accepts a number from 0 to \${max}, or "default".\`,
|
|
55
|
+
);
|
|
56
|
+
return accepted ? DEFAULT_TEMPERATURE : undefined;
|
|
57
|
+
}
|
|
58
|
+
if (!accepted) {
|
|
59
|
+
warnOnce(
|
|
60
|
+
\`Ignoring LLM_TEMPERATURE: \${chatModel} does not accept a custom temperature.\`,
|
|
61
|
+
);
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
20
66
|
function validateAPIKeys(provider: LLMProvider): void {
|
|
21
67
|
const requiredKeys: Record<LLMProvider, string> = {
|
|
22
68
|
openai: "OPENAI_API_KEY",
|
|
@@ -67,12 +113,13 @@ export function getLLMConfig(): LLMConfig {
|
|
|
67
113
|
const parsed = parseInt(rawDims, 10);
|
|
68
114
|
if (Number.isFinite(parsed) && parsed >= 0) embeddingDims = parsed;
|
|
69
115
|
}
|
|
116
|
+
const chatModel = process.env.LLM_CHAT_MODEL || defaults.chat;
|
|
70
117
|
return {
|
|
71
118
|
provider,
|
|
72
|
-
chatModel
|
|
119
|
+
chatModel,
|
|
73
120
|
embeddingModel: process.env.LLM_EMBEDDING_MODEL || defaults.embedding,
|
|
74
121
|
embeddingDims,
|
|
75
|
-
temperature:
|
|
122
|
+
temperature: resolveTemperature(provider, chatModel),
|
|
76
123
|
};
|
|
77
124
|
}
|
|
78
125
|
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const llmFactoryTemplate = "import { ChatOpenAI, OpenAIEmbeddings } from \"@langchain/openai\";\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport {\n ChatGoogleGenerativeAI,\n GoogleGenerativeAIEmbeddings,\n} from \"@langchain/google-genai\";\nimport type { LLMConfig } from \"@/services/llm/types\";\n\n/**\n * Creates a chat model instance based on the provider configuration\n */\nexport function createChatModel(config: LLMConfig) {\n switch (config.provider) {\n case \"openai\":\n return new ChatOpenAI({\n model: config.chatModel,\n temperature
|
|
1
|
+
export declare const llmFactoryTemplate = "import { ChatOpenAI, OpenAIEmbeddings } from \"@langchain/openai\";\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport {\n ChatGoogleGenerativeAI,\n GoogleGenerativeAIEmbeddings,\n} from \"@langchain/google-genai\";\nimport type { LLMConfig } from \"@/services/llm/types\";\n\n/**\n * Creates a chat model instance based on the provider configuration\n */\nexport function createChatModel(config: LLMConfig) {\n // Some models reject the parameter outright, so it is sent only when set.\n const temperature =\n config.temperature === undefined ? {} : { temperature: config.temperature };\n switch (config.provider) {\n case \"openai\":\n return new ChatOpenAI({\n model: config.chatModel,\n ...temperature,\n });\n\n case \"anthropic\":\n return new ChatAnthropic({\n model: config.chatModel,\n ...temperature,\n });\n\n case \"google\":\n return new ChatGoogleGenerativeAI({\n model: config.chatModel,\n ...temperature,\n });\n\n default:\n throw new Error(`Unsupported LLM provider: ${config.provider}`);\n }\n}\n\n/**\n * Creates an embeddings instance based on the provider configuration\n * Note: Anthropic doesn't provide embeddings, so we fallback to OpenAI\n */\nexport function createEmbeddings(config: LLMConfig) {\n switch (config.provider) {\n case \"openai\":\n return new OpenAIEmbeddings({\n model: config.embeddingModel,\n });\n\n case \"google\":\n return new GoogleGenerativeAIEmbeddings({\n model: config.embeddingModel,\n });\n\n case \"anthropic\":\n // Anthropic doesn't have embeddings API\n // Fallback to OpenAI embeddings\n console.warn(\n \"Anthropic provider selected but no native embeddings available. Falling back to OpenAI embeddings.\",\n );\n return new OpenAIEmbeddings({\n model: config.embeddingModel,\n });\n\n default:\n throw new Error(\n `Unsupported LLM provider for embeddings: ${config.provider}`,\n );\n }\n}\n";
|
|
@@ -10,23 +10,26 @@ import type { LLMConfig } from "@/services/llm/types";
|
|
|
10
10
|
* Creates a chat model instance based on the provider configuration
|
|
11
11
|
*/
|
|
12
12
|
export function createChatModel(config: LLMConfig) {
|
|
13
|
+
// Some models reject the parameter outright, so it is sent only when set.
|
|
14
|
+
const temperature =
|
|
15
|
+
config.temperature === undefined ? {} : { temperature: config.temperature };
|
|
13
16
|
switch (config.provider) {
|
|
14
17
|
case "openai":
|
|
15
18
|
return new ChatOpenAI({
|
|
16
19
|
model: config.chatModel,
|
|
17
|
-
temperature
|
|
20
|
+
...temperature,
|
|
18
21
|
});
|
|
19
22
|
|
|
20
23
|
case "anthropic":
|
|
21
24
|
return new ChatAnthropic({
|
|
22
25
|
model: config.chatModel,
|
|
23
|
-
temperature
|
|
26
|
+
...temperature,
|
|
24
27
|
});
|
|
25
28
|
|
|
26
29
|
case "google":
|
|
27
30
|
return new ChatGoogleGenerativeAI({
|
|
28
31
|
model: config.chatModel,
|
|
29
|
-
temperature
|
|
32
|
+
...temperature,
|
|
30
33
|
});
|
|
31
34
|
|
|
32
35
|
default:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const llmTypesTemplate = "export type LLMProvider = \"openai\" | \"anthropic\" | \"google\";\n\nexport interface LLMConfig {\n provider: LLMProvider;\n chatModel: string;\n embeddingModel: string;\n embeddingDims: number;\n temperature
|
|
1
|
+
export declare const llmTypesTemplate = "export type LLMProvider = \"openai\" | \"anthropic\" | \"google\";\n\nexport interface LLMConfig {\n provider: LLMProvider;\n chatModel: string;\n embeddingModel: string;\n embeddingDims: number;\n /** Omitted when the model should use its own default. */\n temperature?: number;\n}\n\ninterface ProviderModels {\n chat: string;\n embedding: string;\n}\n\nexport type ProviderDefaults = Record<LLMProvider, ProviderModels>;\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport {\n McpServer,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register the documentation index as a resource\n server.registerResource(\n \"docs-list\",\n \"docs://list\",\n {\n title: \"Documentation index\",\n description:\n \"JSON index of every documentation page: name, path, and docs:// URI readable with resources/read\",\n mimeType: \"application/json\",\n },\n async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n mimeType: \"application/json\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n },\n );\n\n // Register every documentation page as a readable docs://<route> resource.\n // `{+path}` is a reserved expansion so nested routes keep their slashes.\n // The fixed docs://list resource above is matched before this template.\n server.registerResource(\n \"doc\",\n new ResourceTemplate(\"docs://{+path}\", { list: undefined }),\n {\n title: \"Documentation page\",\n description:\n \"The Markdown content of one documentation page, addressed by the docs:// URI from the docs://list index\",\n mimeType: \"text/markdown\",\n },\n async (uri, _variables, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path: uri.href });\n signal.throwIfAborted();\n if (!doc) {\n throw new Error(`Document not found: ${uri.href}`);\n }\n return {\n contents: [\n { uri: doc.uri, mimeType: \"text/markdown\", text: doc.content },\n ],\n };\n },\n );\n\n return server;\n}\n";
|
|
1
|
+
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport {\n McpServer,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listAllDocs,\n listDocs,\n getDoc,\n getAllDocsChunks,\n matchesDocsFilter,\n resolveDocsFilter,\n DOCS_TOOLS,\n type DocsFilter,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\n// A language code or version slug is a lowercase URL segment.\nconst variantTokenSchema = z\n .string()\n .regex(/^[a-z0-9-]{1,32}$/)\n .optional();\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n language: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({\n directory: z.string().max(500).optional(),\n language: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\n/** The language/version fields of a doc or chunk, for tool results. */\nfunction variantFields(doc: { locale?: string; version?: string }) {\n return {\n ...(doc.locale !== undefined ? { language: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n };\n}\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n ...(c.locale !== undefined ? { locale: c.locale } : {}),\n ...(c.version !== undefined ? { version: c.version } : {}),\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n filter: DocsFilter = resolveDocsFilter(),\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n // One index holds every language and version; the filter keeps the answer\n // inside the variant the reader is looking at.\n const scored = docsIndex.chunks\n .filter((c) => matchesDocsFilter(c, filter))\n .map(({ embedding, ...chunk }) => ({\n chunk,\n score: cosineFloatInt8(queryVector, embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit, language, version }, { signal }) => {\n const results = await searchDocs(\n query,\n limit ?? 6,\n signal,\n resolveDocsFilter({ language, version }),\n );\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n ...variantFields(chunk),\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory, language, version }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory, language, version });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n ...variantFields(d),\n })),\n );\n },\n );\n\n // Register the documentation index as a resource\n server.registerResource(\n \"docs-list\",\n \"docs://list\",\n {\n title: \"Documentation index\",\n description:\n \"JSON index of every documentation page: name, path, and docs:// URI readable with resources/read\",\n mimeType: \"application/json\",\n },\n async () => {\n // The index lists every language and version; each entry carries its\n // language/version so a client can pick the variant it wants to read.\n const docs = await listAllDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n mimeType: \"application/json\",\n text: resourceText(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n ...variantFields(d),\n })),\n ),\n },\n ],\n };\n },\n );\n\n // Register every documentation page as a readable docs://<route> resource.\n // `{+path}` is a reserved expansion so nested routes keep their slashes.\n // The fixed docs://list resource above is matched before this template.\n server.registerResource(\n \"doc\",\n new ResourceTemplate(\"docs://{+path}\", { list: undefined }),\n {\n title: \"Documentation page\",\n description:\n \"The Markdown content of one documentation page, addressed by the docs:// URI from the docs://list index\",\n mimeType: \"text/markdown\",\n },\n async (uri, _variables, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path: uri.href });\n signal.throwIfAborted();\n if (!doc) {\n throw new Error(`Document not found: ${uri.href}`);\n }\n return {\n contents: [\n { uri: doc.uri, mimeType: \"text/markdown\", text: doc.content },\n ],\n };\n },\n );\n\n return server;\n}\n";
|
|
@@ -6,10 +6,14 @@ import {
|
|
|
6
6
|
} from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import {
|
|
9
|
+
listAllDocs,
|
|
9
10
|
listDocs,
|
|
10
11
|
getDoc,
|
|
11
12
|
getAllDocsChunks,
|
|
13
|
+
matchesDocsFilter,
|
|
14
|
+
resolveDocsFilter,
|
|
12
15
|
DOCS_TOOLS,
|
|
16
|
+
type DocsFilter,
|
|
13
17
|
} from "@/services/mcp/tools";
|
|
14
18
|
import { getLLMConfig, createEmbeddings } from "@/services/llm";
|
|
15
19
|
import {
|
|
@@ -27,10 +31,18 @@ export const MCP_MAX_REQUEST_BYTES = 64 * 1024;
|
|
|
27
31
|
export const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;
|
|
28
32
|
export const MCP_MAX_RESULT_BYTES = 256 * 1024;
|
|
29
33
|
|
|
34
|
+
// A language code or version slug is a lowercase URL segment.
|
|
35
|
+
const variantTokenSchema = z
|
|
36
|
+
.string()
|
|
37
|
+
.regex(/^[a-z0-9-]{1,32}$/)
|
|
38
|
+
.optional();
|
|
39
|
+
|
|
30
40
|
export const searchDocsArgsSchema = z
|
|
31
41
|
.object({
|
|
32
42
|
query: z.string().min(1).max(2000),
|
|
33
43
|
limit: z.number().int().min(1).max(20).optional(),
|
|
44
|
+
language: variantTokenSchema,
|
|
45
|
+
version: variantTokenSchema,
|
|
34
46
|
})
|
|
35
47
|
.strict();
|
|
36
48
|
|
|
@@ -39,9 +51,21 @@ export const getDocArgsSchema = z
|
|
|
39
51
|
.strict();
|
|
40
52
|
|
|
41
53
|
export const listDocsArgsSchema = z
|
|
42
|
-
.object({
|
|
54
|
+
.object({
|
|
55
|
+
directory: z.string().max(500).optional(),
|
|
56
|
+
language: variantTokenSchema,
|
|
57
|
+
version: variantTokenSchema,
|
|
58
|
+
})
|
|
43
59
|
.strict();
|
|
44
60
|
|
|
61
|
+
/** The language/version fields of a doc or chunk, for tool results. */
|
|
62
|
+
function variantFields(doc: { locale?: string; version?: string }) {
|
|
63
|
+
return {
|
|
64
|
+
...(doc.locale !== undefined ? { language: doc.locale } : {}),
|
|
65
|
+
...(doc.version !== undefined ? { version: doc.version } : {}),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
45
69
|
export function serializeMCPResult(value: unknown): {
|
|
46
70
|
text: string;
|
|
47
71
|
tooLarge: boolean;
|
|
@@ -168,6 +192,8 @@ function loadPrecomputedIndex(): IndexedChunk[] | null {
|
|
|
168
192
|
text: c.text,
|
|
169
193
|
path: c.path,
|
|
170
194
|
uri: c.uri,
|
|
195
|
+
...(c.locale !== undefined ? { locale: c.locale } : {}),
|
|
196
|
+
...(c.version !== undefined ? { version: c.version } : {}),
|
|
171
197
|
embedding,
|
|
172
198
|
});
|
|
173
199
|
}
|
|
@@ -369,6 +395,7 @@ export async function searchDocs(
|
|
|
369
395
|
query: string,
|
|
370
396
|
limit = 6,
|
|
371
397
|
signal?: AbortSignal,
|
|
398
|
+
filter: DocsFilter = resolveDocsFilter(),
|
|
372
399
|
): Promise<{ chunk: DocsChunk; score: number }[]> {
|
|
373
400
|
await ensureDocsIndex(false, signal);
|
|
374
401
|
throwIfCancelled(signal);
|
|
@@ -379,10 +406,13 @@ export async function searchDocs(
|
|
|
379
406
|
const rawQueryVector = await embedQuery(query, signal);
|
|
380
407
|
const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);
|
|
381
408
|
|
|
409
|
+
// One index holds every language and version; the filter keeps the answer
|
|
410
|
+
// inside the variant the reader is looking at.
|
|
382
411
|
const scored = docsIndex.chunks
|
|
383
|
-
.
|
|
384
|
-
|
|
385
|
-
|
|
412
|
+
.filter((c) => matchesDocsFilter(c, filter))
|
|
413
|
+
.map(({ embedding, ...chunk }) => ({
|
|
414
|
+
chunk,
|
|
415
|
+
score: cosineFloatInt8(queryVector, embedding),
|
|
386
416
|
}))
|
|
387
417
|
.sort((a, b) => b.score - a.score)
|
|
388
418
|
.slice(0, normalizeSearchLimit(limit));
|
|
@@ -421,12 +451,18 @@ export function createMCPServer(): McpServer {
|
|
|
421
451
|
description: DOCS_TOOLS[0].description,
|
|
422
452
|
inputSchema: searchDocsArgsSchema,
|
|
423
453
|
},
|
|
424
|
-
async ({ query, limit }, { signal }) => {
|
|
425
|
-
const results = await searchDocs(
|
|
454
|
+
async ({ query, limit, language, version }, { signal }) => {
|
|
455
|
+
const results = await searchDocs(
|
|
456
|
+
query,
|
|
457
|
+
limit ?? 6,
|
|
458
|
+
signal,
|
|
459
|
+
resolveDocsFilter({ language, version }),
|
|
460
|
+
);
|
|
426
461
|
return toolResult(
|
|
427
462
|
results.map(({ chunk, score }) => ({
|
|
428
463
|
path: chunk.path,
|
|
429
464
|
uri: chunk.uri,
|
|
465
|
+
...variantFields(chunk),
|
|
430
466
|
score: score.toFixed(3),
|
|
431
467
|
text: chunk.text,
|
|
432
468
|
})),
|
|
@@ -459,15 +495,16 @@ export function createMCPServer(): McpServer {
|
|
|
459
495
|
description: DOCS_TOOLS[2].description,
|
|
460
496
|
inputSchema: listDocsArgsSchema,
|
|
461
497
|
},
|
|
462
|
-
async ({ directory }, { signal }) => {
|
|
498
|
+
async ({ directory, language, version }, { signal }) => {
|
|
463
499
|
signal.throwIfAborted();
|
|
464
|
-
const docs = await listDocs({ directory });
|
|
500
|
+
const docs = await listDocs({ directory, language, version });
|
|
465
501
|
signal.throwIfAborted();
|
|
466
502
|
return toolResult(
|
|
467
503
|
docs.map((d) => ({
|
|
468
504
|
name: d.name,
|
|
469
505
|
path: d.path,
|
|
470
506
|
uri: d.uri,
|
|
507
|
+
...variantFields(d),
|
|
471
508
|
})),
|
|
472
509
|
);
|
|
473
510
|
},
|
|
@@ -484,14 +521,21 @@ export function createMCPServer(): McpServer {
|
|
|
484
521
|
mimeType: "application/json",
|
|
485
522
|
},
|
|
486
523
|
async () => {
|
|
487
|
-
|
|
524
|
+
// The index lists every language and version; each entry carries its
|
|
525
|
+
// language/version so a client can pick the variant it wants to read.
|
|
526
|
+
const docs = await listAllDocs();
|
|
488
527
|
return {
|
|
489
528
|
contents: [
|
|
490
529
|
{
|
|
491
530
|
uri: "docs://list",
|
|
492
531
|
mimeType: "application/json",
|
|
493
532
|
text: resourceText(
|
|
494
|
-
docs.map((d) => ({
|
|
533
|
+
docs.map((d) => ({
|
|
534
|
+
name: d.name,
|
|
535
|
+
path: d.path,
|
|
536
|
+
uri: d.uri,
|
|
537
|
+
...variantFields(d),
|
|
538
|
+
})),
|
|
495
539
|
),
|
|
496
540
|
},
|
|
497
541
|
],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const mcpToolsTemplate = "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n MCPToolDefinition,\n DocsResource,\n DocsChunk,\n GetDocParams,\n ListDocsParams,\n} from \"@/services/mcp/types\";\n\n// Keep the corpus out of the function's JavaScript bundle. next.config.ts\n// traces this fixed file into the RAG/MCP functions, just like docs-index.json.\nconst DOCS_CONTENT_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-content.json\",\n);\n\nlet docsContentCache:\n { mtimeMs: number; size: number; docs: DocsResource[] } | undefined;\n\nfunction loadDocsContent(): DocsResource[] {\n try {\n // Generated content changes while `next dev` stays alive. Key the cache by\n // file metadata so watch-mode updates become visible without parsing the\n // whole corpus on every tool call.\n const stat = fs.statSync(DOCS_CONTENT_FILE);\n if (\n docsContentCache?.mtimeMs === stat.mtimeMs &&\n docsContentCache.size === stat.size\n ) {\n return docsContentCache.docs;\n }\n const parsed: unknown = JSON.parse(\n fs.readFileSync(DOCS_CONTENT_FILE, \"utf8\"),\n );\n const docs = Array.isArray(parsed) ? (parsed as DocsResource[]) : [];\n docsContentCache = { mtimeMs: stat.mtimeMs, size: stat.size, docs };\n return docs;\n } catch {\n docsContentCache = undefined;\n return [];\n }\n}\n\n/**\n * Tool definitions for MCP - these describe the available tools\n */\nexport const DOCS_TOOLS: MCPToolDefinition[] = [\n {\n name: \"search_docs\",\n description:\n \"Search through the documentation content using semantic search. Returns relevant chunks of documentation based on the query.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant documentation\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum number of results to return (default: 6)\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"get_doc\",\n description:\n \"Get the full content of a specific documentation page by its path.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"The file path to the documentation page (e.g., 'app/getting-started/page.tsx')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"list_docs\",\n description:\n \"List all available documentation pages, optionally filtered by directory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n directory: {\n type: \"string\",\n description:\n \"Optional directory to filter results (e.g., 'components')\",\n },\n },\n },\n },\n];\n\n/**\n * List
|
|
1
|
+
export declare const mcpToolsTemplate = "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n MCPToolDefinition,\n DocsResource,\n DocsChunk,\n GetDocParams,\n ListDocsParams,\n} from \"@/services/mcp/types\";\nimport {\n defaultLanguage,\n isVariantsConfigured,\n languages,\n versions,\n} from \"@/utils/variants\";\n\n/** The language/version a docs query is scoped to. Empty when the site has\n * neither configured, so every page matches. */\nexport interface DocsFilter {\n locale?: string;\n version?: string;\n}\n\n/**\n * Resolve the scope of a docs query: the requested language and version, or\n * the site's default language / default version when a request names none.\n * A language or version the site does not declare matches nothing.\n */\nexport function resolveDocsFilter(params?: {\n language?: string;\n version?: string;\n}): DocsFilter {\n if (!isVariantsConfigured()) return {};\n const filter: DocsFilter = {};\n if (languages) {\n filter.locale = params?.language ?? defaultLanguage()?.code ?? \"\";\n }\n if (versions) {\n filter.version = params?.version ?? \"\";\n }\n return filter;\n}\n\nexport function matchesDocsFilter(\n doc: { locale?: string; version?: string },\n filter: DocsFilter,\n): boolean {\n return (\n (filter.locale === undefined || doc.locale === filter.locale) &&\n (filter.version === undefined || doc.version === filter.version)\n );\n}\n\n// Keep the corpus out of the function's JavaScript bundle. next.config.ts\n// traces this fixed file into the RAG/MCP functions, just like docs-index.json.\nconst DOCS_CONTENT_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-content.json\",\n);\n\nlet docsContentCache:\n { mtimeMs: number; size: number; docs: DocsResource[] } | undefined;\n\nfunction loadDocsContent(): DocsResource[] {\n try {\n // Generated content changes while `next dev` stays alive. Key the cache by\n // file metadata so watch-mode updates become visible without parsing the\n // whole corpus on every tool call.\n const stat = fs.statSync(DOCS_CONTENT_FILE);\n if (\n docsContentCache?.mtimeMs === stat.mtimeMs &&\n docsContentCache.size === stat.size\n ) {\n return docsContentCache.docs;\n }\n const parsed: unknown = JSON.parse(\n fs.readFileSync(DOCS_CONTENT_FILE, \"utf8\"),\n );\n const docs = Array.isArray(parsed) ? (parsed as DocsResource[]) : [];\n docsContentCache = { mtimeMs: stat.mtimeMs, size: stat.size, docs };\n return docs;\n } catch {\n docsContentCache = undefined;\n return [];\n }\n}\n\n/**\n * Tool definitions for MCP - these describe the available tools\n */\nexport const DOCS_TOOLS: MCPToolDefinition[] = [\n {\n name: \"search_docs\",\n description:\n \"Search through the documentation content using semantic search. Returns relevant chunks of documentation based on the query.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant documentation\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum number of results to return (default: 6)\",\n },\n language: {\n type: \"string\",\n description:\n \"Language code to search (e.g. 'de'); defaults to the site's default language\",\n },\n version: {\n type: \"string\",\n description:\n \"Documentation version slug to search (e.g. 'v1'); defaults to the current version\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"get_doc\",\n description:\n \"Get the full content of a specific documentation page by its path.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"The file path to the documentation page (e.g., 'app/getting-started/page.tsx')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"list_docs\",\n description:\n \"List all available documentation pages, optionally filtered by directory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n directory: {\n type: \"string\",\n description:\n \"Optional directory to filter results (e.g., 'components')\",\n },\n language: {\n type: \"string\",\n description:\n \"Language code to list (e.g. 'de'); defaults to the site's default language\",\n },\n version: {\n type: \"string\",\n description:\n \"Documentation version slug to list (e.g. 'v1'); defaults to the current version\",\n },\n },\n },\n },\n];\n\n/**\n * Every documentation resource in every language and version. Indexes are\n * built from this and filtered at query time.\n */\nexport async function listAllDocs(): Promise<DocsResource[]> {\n return loadDocsContent().map((doc) => ({ ...doc }));\n}\n\n/**\n * List the documentation resources of one language/version (the default\n * variant unless the params name another), optionally under a directory.\n */\nexport async function listDocs(\n params?: ListDocsParams,\n): Promise<DocsResource[]> {\n const docsContent = loadDocsContent();\n const filterDir = params?.directory?.replace(/\\\\/g, \"/\");\n const filter = resolveDocsFilter(params);\n return docsContent\n .filter((doc) => matchesDocsFilter(doc, filter))\n .filter((doc) => !filterDir || doc.path.includes(filterDir))\n .map((doc) => ({ ...doc }));\n}\n\n/**\n * Get a specific documentation page\n */\nexport async function getDoc(\n params: GetDocParams,\n): Promise<DocsResource | null> {\n const docsContent = loadDocsContent();\n const requested = params.path.trim().replace(/\\\\/g, \"/\");\n if (!requested || requested.includes(\"\\0\")) return null;\n\n const withoutScheme = requested.replace(/^docs:\\/\\//, \"\");\n const route = withoutScheme\n .replace(/^app\\/(?:\\([^/]+\\)\\/)?/, \"\")\n .replace(/(?:^|\\/)page\\.(?:tsx?|jsx?)$/, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n\n const doc = docsContent.find((candidate) => {\n const candidateRoute = candidate.uri\n .replace(/^docs:\\/\\//, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n return (\n candidate.path === requested ||\n candidate.uri === requested ||\n candidateRoute === route\n );\n });\n\n return doc ? { ...doc } : null;\n}\n\n/**\n * Chunk text for embeddings.\n * - chunkSize=800 chars balances granularity with embedding context window limits\n * - overlap=100 chars ensures continuity so searches don't miss content at chunk boundaries\n */\nfunction chunkText(text: string, chunkSize = 800, overlap = 100): string[] {\n const chunks: string[] = [];\n let i = 0;\n while (i < text.length) {\n const end = Math.min(i + chunkSize, text.length);\n chunks.push(text.slice(i, end));\n if (end === text.length) break;\n i = end - overlap;\n if (i < 0) i = 0;\n }\n return chunks;\n}\n\n/**\n * Get all documentation chunks for indexing\n */\nexport async function getAllDocsChunks(): Promise<DocsChunk[]> {\n const allChunks: DocsChunk[] = [];\n const docs = await listAllDocs();\n\n for (const doc of docs) {\n const cleanContent = doc.content\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .slice(0, 200_000);\n\n const textChunks = chunkText(cleanContent);\n for (let i = 0; i < textChunks.length; i++) {\n allChunks.push({\n id: `${doc.path}:${i}`,\n text: textChunks[i],\n path: doc.path,\n uri: doc.uri,\n ...(doc.locale !== undefined ? { locale: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n });\n }\n }\n\n return allChunks;\n}\n";
|