doccupine 0.0.140 → 0.0.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +14 -7
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +191 -0
  4. package/dist/index.d.ts +3 -7
  5. package/dist/index.js +5 -1894
  6. package/dist/lib/config-manager.d.ts +1 -0
  7. package/dist/lib/config-manager.js +63 -3
  8. package/dist/lib/generated-artifacts.d.ts +26 -0
  9. package/dist/lib/generated-artifacts.js +147 -0
  10. package/dist/lib/layout.js +30 -30
  11. package/dist/lib/metadata.js +58 -30
  12. package/dist/lib/openapi-types.d.ts +2 -2
  13. package/dist/lib/openapi.d.ts +6 -3
  14. package/dist/lib/openapi.js +330 -50
  15. package/dist/lib/output-safety.d.ts +15 -0
  16. package/dist/lib/output-safety.js +428 -0
  17. package/dist/lib/structures.js +11 -0
  18. package/dist/lib/utils.d.ts +10 -5
  19. package/dist/lib/utils.js +108 -5
  20. package/dist/mdx-to-nextjs-generator.d.ts +166 -0
  21. package/dist/mdx-to-nextjs-generator.js +2229 -0
  22. package/dist/templates/app/api/gate/route.d.ts +1 -1
  23. package/dist/templates/app/api/gate/route.js +18 -6
  24. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  25. package/dist/templates/app/api/mcp/route.js +181 -111
  26. package/dist/templates/app/api/playground/route.d.ts +1 -1
  27. package/dist/templates/app/api/playground/route.js +45 -13
  28. package/dist/templates/app/api/rag/route.d.ts +1 -1
  29. package/dist/templates/app/api/rag/route.js +72 -20
  30. package/dist/templates/app/api/search/route.d.ts +1 -1
  31. package/dist/templates/app/api/search/route.js +5 -0
  32. package/dist/templates/app/robots.d.ts +1 -1
  33. package/dist/templates/app/robots.js +1 -26
  34. package/dist/templates/app/theme.d.ts +1 -1
  35. package/dist/templates/app/theme.js +31 -19
  36. package/dist/templates/components/Chat.d.ts +1 -1
  37. package/dist/templates/components/Chat.js +342 -34
  38. package/dist/templates/components/SearchDocs.d.ts +1 -1
  39. package/dist/templates/components/SearchDocs.js +63 -11
  40. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  41. package/dist/templates/components/SearchModalContent.js +191 -49
  42. package/dist/templates/components/SideBar.d.ts +1 -1
  43. package/dist/templates/components/SideBar.js +8 -2
  44. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  45. package/dist/templates/components/layout/Accordion.js +26 -3
  46. package/dist/templates/components/layout/Badge.d.ts +1 -1
  47. package/dist/templates/components/layout/Badge.js +1 -1
  48. package/dist/templates/components/layout/Button.d.ts +1 -1
  49. package/dist/templates/components/layout/Button.js +4 -4
  50. package/dist/templates/components/layout/Callout.d.ts +1 -1
  51. package/dist/templates/components/layout/Callout.js +6 -6
  52. package/dist/templates/components/layout/Card.d.ts +1 -1
  53. package/dist/templates/components/layout/Card.js +9 -4
  54. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  55. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  56. package/dist/templates/components/layout/Code.d.ts +1 -1
  57. package/dist/templates/components/layout/Code.js +5 -5
  58. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  59. package/dist/templates/components/layout/CopyButton.js +1 -1
  60. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  61. package/dist/templates/components/layout/DemoTheme.js +8 -28
  62. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  63. package/dist/templates/components/layout/DocsComponents.js +57 -6
  64. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  65. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  66. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  67. package/dist/templates/components/layout/Prompt.js +4 -7
  68. package/dist/templates/components/layout/Steps.d.ts +1 -1
  69. package/dist/templates/components/layout/Steps.js +7 -1
  70. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  71. package/dist/templates/components/layout/Tabs.js +108 -19
  72. package/dist/templates/env.example.d.ts +1 -1
  73. package/dist/templates/env.example.js +11 -0
  74. package/dist/templates/eslint.config.d.ts +1 -1
  75. package/dist/templates/eslint.config.js +20 -0
  76. package/dist/templates/gitignore.d.ts +1 -1
  77. package/dist/templates/gitignore.js +4 -3
  78. package/dist/templates/lib/access.d.ts +1 -0
  79. package/dist/templates/lib/access.js +41 -0
  80. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  81. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  82. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  83. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  84. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/authentication.mdx.js +5 -3
  86. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/commands.mdx.js +20 -6
  88. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/components.mdx.js +3 -0
  90. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  92. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/globals.mdx.js +14 -11
  94. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  96. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  98. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  100. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  101. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  102. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  104. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  105. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  106. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  108. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  110. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  112. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  114. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/sections.mdx.js +4 -0
  116. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  117. package/dist/templates/mdx/space.mdx.js +125 -0
  118. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/tabs.mdx.js +4 -0
  120. package/dist/templates/next.config.js +20 -8
  121. package/dist/templates/package.js +3 -3
  122. package/dist/templates/prettierignore.d.ts +1 -1
  123. package/dist/templates/prettierignore.js +1 -0
  124. package/dist/templates/proxy.js +47 -19
  125. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  126. package/dist/templates/scripts/build-docs-index.js +1 -0
  127. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  128. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  129. package/dist/templates/services/mcp/server.d.ts +1 -1
  130. package/dist/templates/services/mcp/server.js +140 -83
  131. package/dist/templates/services/mcp/tools.d.ts +1 -1
  132. package/dist/templates/services/mcp/tools.js +65 -137
  133. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  134. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  135. package/dist/templates/utils/rateLimit.d.ts +1 -1
  136. package/dist/templates/utils/rateLimit.js +40 -3
  137. package/dist/templates/utils/requestBody.d.ts +1 -0
  138. package/dist/templates/utils/requestBody.js +56 -0
  139. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  140. package/dist/templates/utils/ssrfGuard.js +138 -33
  141. package/package.json +14 -9
  142. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  143. package/dist/lib/mdxToMarkdown.js +0 -134
  144. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  145. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
@@ -0,0 +1,125 @@
1
+ export const spaceMdxTemplate = `---
2
+ title: "Space"
3
+ description: "Add a precise vertical or horizontal gap between blocks, with per-breakpoint control."
4
+ date: "2026-07-30"
5
+ category: "Components"
6
+ categoryOrder: 1
7
+ order: 24
8
+ ---
9
+ # Space
10
+
11
+ Insert a fixed gap between two blocks.
12
+
13
+ Markdown already spaces paragraphs, headings, lists, and tables for you, and that default rhythm is the right choice almost everywhere. Reach for \`Space\` when you need a specific gap the defaults do not give you: separating a dense table from the heading that follows it, opening up a landing page, or tightening a stack of cards on small screens.
14
+
15
+ <Callout type="note">
16
+ If you find yourself adding a \`Space\` after every section, the page is telling you it wants a different structure - try \`Steps\`, \`Columns\`, or a heading instead.
17
+ </Callout>
18
+
19
+ ## Space Usage
20
+
21
+ Set \`$size\` to the gap you want, in pixels.
22
+
23
+ \`\`\`html
24
+ Text above the gap.
25
+
26
+ <Space $size={60} />
27
+
28
+ Text below the gap.
29
+ \`\`\`
30
+
31
+ Text above the gap.
32
+
33
+ <Space $size={60} />
34
+
35
+ Text below the gap.
36
+
37
+ ## Responsive sizing
38
+
39
+ A gap that looks right on a wide screen is often too large on a phone. Each breakpoint has its own prop, so you can grow the gap as the viewport widens.
40
+
41
+ \`\`\`html
42
+ <Space $size={20} $md={40} $xl={80} />
43
+ \`\`\`
44
+
45
+ That renders a 20px gap by default, 40px from the \`md\` breakpoint up, and 80px from \`xl\` up.
46
+
47
+ Every breakpoint prop is a \`min-width\` media query, so a value applies at that width and every width above it until a larger breakpoint overrides it:
48
+
49
+ | Prop | Applies from |
50
+ | -------- | ------------ |
51
+ | \`$xs\` | 0px |
52
+ | \`$sm\` | 576px |
53
+ | \`$md\` | 768px |
54
+ | \`$lg\` | 992px |
55
+ | \`$xl\` | 1200px |
56
+ | \`$xxl\` | 1440px |
57
+ | \`$xxxl\` | 1920px |
58
+
59
+ \`$size\` sets the gap at every width. Use it alone for a constant gap, or as the base that the breakpoint props build on.
60
+
61
+ ## Removing the space at a breakpoint
62
+
63
+ Pass \`"none"\` instead of a number to drop the gap entirely at that width. This is the usual way to add breathing room on desktop without wasting vertical space on a phone.
64
+
65
+ \`\`\`html
66
+ <Space $size="none" $lg={64} />
67
+ \`\`\`
68
+
69
+ Here there is no gap at all below the \`lg\` breakpoint, and a 64px gap from \`lg\` up.
70
+
71
+ ## Horizontal spacing
72
+
73
+ Add \`$horizontal\` to space things apart along the inline axis instead of the block axis. The size prop then controls width rather than height.
74
+
75
+ It belongs inside a line of inline content, where a gap along that axis has something to sit between. Dropping one into a button widens the distance between the label and the icon by the size you give it, on top of the spacing the button already applies:
76
+
77
+ \`\`\`html
78
+ <Button icon="arrow-right" iconPosition="right">
79
+ Get started
80
+ <Space $size={24} $horizontal />
81
+ </Button>
82
+ \`\`\`
83
+
84
+ <Button icon="arrow-right" iconPosition="right">
85
+ Get started
86
+ <Space $size={24} $horizontal />
87
+ </Button>
88
+
89
+ ## Properties
90
+
91
+ <Field value="$size" type="number | 'none'">
92
+ The gap at every viewport width, in pixels. Pass \`"none"\` to render nothing.
93
+ </Field>
94
+
95
+ <Field value="$xs" type="number | 'none'">
96
+ Overrides the gap from 0px up.
97
+ </Field>
98
+
99
+ <Field value="$sm" type="number | 'none'">
100
+ Overrides the gap from 576px up.
101
+ </Field>
102
+
103
+ <Field value="$md" type="number | 'none'">
104
+ Overrides the gap from 768px up.
105
+ </Field>
106
+
107
+ <Field value="$lg" type="number | 'none'">
108
+ Overrides the gap from 992px up.
109
+ </Field>
110
+
111
+ <Field value="$xl" type="number | 'none'">
112
+ Overrides the gap from 1200px up.
113
+ </Field>
114
+
115
+ <Field value="$xxl" type="number | 'none'">
116
+ Overrides the gap from 1440px up.
117
+ </Field>
118
+
119
+ <Field value="$xxxl" type="number | 'none'">
120
+ Overrides the gap from 1920px up.
121
+ </Field>
122
+
123
+ <Field value="$horizontal" type="boolean">
124
+ Spaces along the inline axis instead of the block axis, so the size props control width. Defaults to false.
125
+ </Field>`;
@@ -1 +1 @@
1
- export declare const tabsMdxTemplate = "---\ntitle: \"Tabs\"\ndescription: \"Use the Tabs component to display different content sections in a switchable panel layout.\"\ndate: \"2026-02-19\"\ncategory: \"Components\"\ncategoryOrder: 1\norder: 7\n---\n# Tabs\n\nUse the Tabs component to display different content sections in a switchable panel layout.\n\nTabs are useful for grouping related information while keeping the interface tidy. You can create as many tabs as needed, and each one can hold other components, text, or code snippets.\n\n## Tabs Usage\n\nYou can use the Tabs component directly within your MDX files without any import. The following example shows a basic usage:\n\n````html\n<Tabs>\n <TabContent title=\"First tab\" icon=\"code\">\n \u261D\uFE0F This is the content shown only when the first tab is active.\n\n Tabs can include all kinds of components. For example, a simple Java program:\n ```java\n class HelloWorld {\n public static void main(String[] args) {\n System.out.println(\"Hello, World!\");\n }\n }\n ```\n </TabContent>\n <TabContent title=\"Second tab\" icon=\"book-open\">\n \u270C\uFE0F Content inside this second tab is separate from the first.\n </TabContent>\n <TabContent title=\"Third tab\" icon=\"rocket\">\n \uD83D\uDCAA This third tab contains its own unique content.\n </TabContent>\n</Tabs>\n````\n\n<Tabs>\n <TabContent title=\"First tab\" icon=\"code\">\n \u261D\uFE0F This is the content shown only when the first tab is active.\n\n Tabs can include all kinds of components. For example, a simple Java program:\n ```java\n class HelloWorld {\n public static void main(String[] args) {\n System.out.println(\"Hello, World!\");\n }\n }\n ```\n </TabContent>\n <TabContent title=\"Second tab\" icon=\"book-open\">\n \u270C\uFE0F Content inside this second tab is separate from the first.\n </TabContent>\n <TabContent title=\"Third tab\" icon=\"rocket\">\n \uD83D\uDCAA This third tab contains its own unique content.\n </TabContent>\n</Tabs>\n\nEach tab also accepts an optional `icon` - any [Lucide](https://lucide.dev/icons) icon name - rendered before its title, as shown above.\n\n## Properties\n\n<Field value=\"title\" type=\"string\">\n The title of the tab.\n</Field>\n\n<Field value=\"icon\" type=\"string\">\n Optional [Lucide](https://lucide.dev/icons) icon name (kebab-case, e.g.\n `rocket`) shown next to the tab title.\n</Field>\n\n<Field value=\"children\" type=\"node\" required>\n The content of the tabs.\n</Field>";
1
+ export declare const tabsMdxTemplate = "---\ntitle: \"Tabs\"\ndescription: \"Use the Tabs component to display different content sections in a switchable panel layout.\"\ndate: \"2026-02-19\"\ncategory: \"Components\"\ncategoryOrder: 1\norder: 7\n---\n# Tabs\n\nUse the Tabs component to display different content sections in a switchable panel layout.\n\nTabs are useful for grouping related information while keeping the interface tidy. You can create as many tabs as needed, and each one can hold other components, text, or code snippets.\n\n## Tabs Usage\n\nYou can use the Tabs component directly within your MDX files without any import. The following example shows a basic usage:\n\n````html\n<Tabs>\n <TabContent title=\"First tab\" icon=\"code\">\n \u261D\uFE0F This is the content shown only when the first tab is active.\n\n Tabs can include all kinds of components. For example, a simple Java program:\n ```java\n class HelloWorld {\n public static void main(String[] args) {\n System.out.println(\"Hello, World!\");\n }\n }\n ```\n </TabContent>\n <TabContent title=\"Second tab\" icon=\"book-open\">\n \u270C\uFE0F Content inside this second tab is separate from the first.\n </TabContent>\n <TabContent title=\"Third tab\" icon=\"rocket\">\n \uD83D\uDCAA This third tab contains its own unique content.\n </TabContent>\n</Tabs>\n````\n\n<Tabs>\n <TabContent title=\"First tab\" icon=\"code\">\n \u261D\uFE0F This is the content shown only when the first tab is active.\n\n Tabs can include all kinds of components. For example, a simple Java program:\n ```java\n class HelloWorld {\n public static void main(String[] args) {\n System.out.println(\"Hello, World!\");\n }\n }\n ```\n </TabContent>\n <TabContent title=\"Second tab\" icon=\"book-open\">\n \u270C\uFE0F Content inside this second tab is separate from the first.\n </TabContent>\n <TabContent title=\"Third tab\" icon=\"rocket\">\n \uD83D\uDCAA This third tab contains its own unique content.\n </TabContent>\n</Tabs>\n\nEach tab also accepts an optional `icon` - any [Lucide](https://lucide.dev/icons) icon name - rendered before its title, as shown above.\n\n## Keyboard navigation\n\nTabs use the standard horizontal keyboard pattern. Press **Left Arrow** or **Right Arrow** to move between tabs, and **Home** or **End** to jump to the first or last tab. **Up Arrow** and **Down Arrow** continue to scroll the page and are not captured by the tab list.\n\n## Properties\n\n<Field value=\"title\" type=\"string\">\n The title of the tab.\n</Field>\n\n<Field value=\"icon\" type=\"string\">\n Optional [Lucide](https://lucide.dev/icons) icon name (kebab-case, e.g.\n `rocket`) shown next to the tab title.\n</Field>\n\n<Field value=\"children\" type=\"node\" required>\n The content of the tabs.\n</Field>";
@@ -62,6 +62,10 @@ You can use the Tabs component directly within your MDX files without any import
62
62
 
63
63
  Each tab also accepts an optional \`icon\` - any [Lucide](https://lucide.dev/icons) icon name - rendered before its title, as shown above.
64
64
 
65
+ ## Keyboard navigation
66
+
67
+ Tabs use the standard horizontal keyboard pattern. Press **Left Arrow** or **Right Arrow** to move between tabs, and **Home** or **End** to jump to the first or last tab. **Up Arrow** and **Down Arrow** continue to scroll the page and are not captured by the tab list.
68
+
65
69
  ## Properties
66
70
 
67
71
  <Field value="title" type="string">
@@ -7,11 +7,17 @@ const nextConfig: NextConfig = {
7
7
  compiler: {
8
8
  styledComponents: true,
9
9
  },
10
- // Bundle the precomputed embeddings index into the serverless functions that
11
- // read it (a dynamic fs read is invisible to Next's file tracing).
10
+ // Trace the runtime-loaded corpus and precomputed embeddings index into the
11
+ // serverless functions (dynamic fs reads are invisible to automatic tracing).
12
12
  outputFileTracingIncludes: {
13
- "/api/rag": ["./services/mcp/docs-index.json"],
14
- "/api/mcp": ["./services/mcp/docs-index.json"],
13
+ "/api/rag": [
14
+ "./services/mcp/docs-content.json",
15
+ "./services/mcp/docs-index.json",
16
+ ],
17
+ "/api/mcp": [
18
+ "./services/mcp/docs-content.json",
19
+ "./services/mcp/docs-index.json",
20
+ ],
15
21
  },
16
22
  // Discovery alias: agents probe /mcp for an MCP server. Auth for the alias
17
23
  // is handled in the middleware, which runs before this rewrite.
@@ -40,11 +46,17 @@ const nextConfig: NextConfig = {
40
46
  compiler: {
41
47
  styledComponents: true,
42
48
  },
43
- // Bundle the precomputed embeddings index into the serverless functions that
44
- // read it (a dynamic fs read is invisible to Next's file tracing).
49
+ // Trace the runtime-loaded corpus and precomputed embeddings index into the
50
+ // serverless functions (dynamic fs reads are invisible to automatic tracing).
45
51
  outputFileTracingIncludes: {
46
- "/api/rag": ["./services/mcp/docs-index.json"],
47
- "/api/mcp": ["./services/mcp/docs-index.json"],
52
+ "/api/rag": [
53
+ "./services/mcp/docs-content.json",
54
+ "./services/mcp/docs-index.json",
55
+ ],
56
+ "/api/mcp": [
57
+ "./services/mcp/docs-content.json",
58
+ "./services/mcp/docs-index.json",
59
+ ],
48
60
  },
49
61
  // The /mcp entry is a discovery alias: agents probe /mcp for an MCP server.
50
62
  // Auth for the alias is handled in the middleware, which runs before this
@@ -18,13 +18,13 @@ export const packageJsonTemplate = JSON.stringify({
18
18
  "@mdx-js/react": "^3.1.1",
19
19
  "@modelcontextprotocol/sdk": "^1.30.0",
20
20
  "beautiful-mermaid": "^1.1.3",
21
- "cherry-styled-components": "^0.2.11",
21
+ "cherry-styled-components": "^0.2.12",
22
22
  langchain: "^1.5.4",
23
- "lucide-react": "^1.27.0",
23
+ "lucide-react": "^1.28.0",
24
24
  minisearch: "^7.2.0",
25
25
  next: "16.2.12",
26
26
  "next-mdx-remote": "^6.0.0",
27
- "posthog-js": "^1.407.8",
27
+ "posthog-js": "^1.408.3",
28
28
  "posthog-node": "^5.46.1",
29
29
  react: "19.2.8",
30
30
  "react-dom": "19.2.8",
@@ -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";
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";
@@ -6,4 +6,5 @@ package-lock.json
6
6
  pnpm-lock.yaml
7
7
  pnpm-workspace.yaml
8
8
  services/mcp/docs-index.json
9
+ .doccupine-*
9
10
  `;
@@ -3,11 +3,13 @@ export const proxyTemplate = (analyticsConfig = null) => {
3
3
  const posthogImport = hasPostHog
4
4
  ? `import { getPostHogServerClient } from "@/lib/posthog";\n`
5
5
  : "";
6
- const gateImport = `import { GATE_COOKIE_NAME, isGateUnlocked } from "@/lib/siteGate";\n`;
6
+ const gateImport = `import {
7
+ GATE_COOKIE_NAME,
8
+ isGateUnlocked,
9
+ timingSafeEqual,
10
+ } from "@/lib/siteGate";\n`;
7
11
  const posthogPageviewFn = hasPostHog
8
12
  ? `
9
- const SKIP_PAGEVIEW_PATTERN = /^\\/(api|ingest|_next)\\//;
10
-
11
13
  /**
12
14
  * First-party anonymous id.
13
15
  *
@@ -152,7 +154,12 @@ function captureServerPageview(
152
154
  ): TrackingIdentity | null {
153
155
  const pathname = req.nextUrl.pathname;
154
156
 
155
- if (SKIP_PAGEVIEW_PATTERN.test(pathname)) return null;
157
+ if (
158
+ isPathSegment(pathname, "/api") ||
159
+ isPathSegment(pathname, "/ingest") ||
160
+ isPathSegment(pathname, "/_next")
161
+ )
162
+ return null;
156
163
 
157
164
  // A prefetch is the router speculating, not the reader acting: it neither
158
165
  // counts as a pageview nor keeps a session alive.
@@ -251,14 +258,20 @@ function applyTracking(res: NextResponse, _tracking: null): NextResponse {
251
258
  return `import { NextResponse } from "next/server";
252
259
  import type { NextRequest${eventImport} } from "next/server";
253
260
  ${gateImport}${posthogImport}${posthogPageviewFn}${applyTrackingFn}
261
+ function isPathSegment(pathname: string, segment: string): boolean {
262
+ return pathname === segment || pathname.startsWith(segment + "/");
263
+ }
264
+
254
265
  ${fnSignature} {
255
266
  ${trackingInit} const pathname = req.nextUrl.pathname;
256
267
  const sitePassword = process.env.SITE_PASSWORD;
268
+ const isMcpPath = isPathSegment(pathname, "/api/mcp") || pathname === "/mcp";
257
269
 
258
270
  // API key auth for the MCP endpoint when DOCS_API_KEY is configured. Also
259
271
  // matches /mcp, the discovery alias that next.config rewrites to /api/mcp
260
- // after the middleware has run.
261
- if (pathname.startsWith("/api/mcp") || pathname === "/mcp") {
272
+ // after the middleware has run. Without a separate API key, a protected site
273
+ // requires the normal gate cookie instead of exposing MCP around the gate.
274
+ if (isMcpPath) {
262
275
  const apiKey = process.env.DOCS_API_KEY;
263
276
  if (apiKey) {
264
277
  const authHeader = req.headers.get("authorization");
@@ -266,9 +279,17 @@ ${trackingInit} const pathname = req.nextUrl.pathname;
266
279
  ? authHeader.slice(7)
267
280
  : null;
268
281
 
269
- if (token !== apiKey) {
282
+ if (token === null || !timingSafeEqual(token, apiKey)) {
270
283
  return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
271
284
  }
285
+ } else if (
286
+ sitePassword &&
287
+ !(await isGateUnlocked(
288
+ req.cookies.get(GATE_COOKIE_NAME)?.value,
289
+ sitePassword,
290
+ ))
291
+ ) {
292
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
272
293
  }
273
294
  }
274
295
 
@@ -276,18 +297,21 @@ ${trackingInit} const pathname = req.nextUrl.pathname;
276
297
  // works even though the doc pages render statically: pages can't read the
277
298
  // request cookie, but the middleware always can. Skip Next internals so the
278
299
  // gate screen's own assets keep loading.
279
- if (sitePassword && !pathname.startsWith("/_next")) {
280
- const unlocked = await isGateUnlocked(
300
+ if (sitePassword && !isMcpPath && !isPathSegment(pathname, "/_next")) {
301
+ // Defer the HMAC until a request actually crosses the site gate. In
302
+ // particular, Next.js assets and API-key-authenticated MCP calls avoid it.
303
+ const gateUnlocked = await isGateUnlocked(
281
304
  req.cookies.get(GATE_COOKIE_NAME)?.value,
282
305
  sitePassword,
283
306
  );
284
-
285
- // Content APIs (RAG chat + search) return 401 without a valid cookie so the
286
- // docs can't be scraped around the login screen. /api/mcp keeps its own key
287
- // auth above; /api/gate stays open so the gate can unlock.
307
+ // Content APIs return 401 without a valid cookie so protected docs and the
308
+ // request playground cannot be reached around the login screen. /api/mcp
309
+ // keeps its API-key-or-gate auth above; /api/gate stays open to unlock.
288
310
  if (
289
- !unlocked &&
290
- (pathname.startsWith("/api/rag") || pathname.startsWith("/api/search"))
311
+ !gateUnlocked &&
312
+ (isPathSegment(pathname, "/api/rag") ||
313
+ isPathSegment(pathname, "/api/search") ||
314
+ isPathSegment(pathname, "/api/playground"))
291
315
  ) {
292
316
  return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
293
317
  }
@@ -295,14 +319,18 @@ ${trackingInit} const pathname = req.nextUrl.pathname;
295
319
  // Locked visitors see the gate screen. Rewrite (not redirect) so the URL is
296
320
  // preserved — after unlocking, a reload lands them back on the page they
297
321
  // asked for. API routes are never rewritten to HTML.
298
- if (!unlocked && !pathname.startsWith("/api") && pathname !== "/gate") {
322
+ if (
323
+ !gateUnlocked &&
324
+ !isPathSegment(pathname, "/api") &&
325
+ pathname !== "/gate"
326
+ ) {
299
327
  const res = NextResponse.rewrite(new URL("/gate", req.url));
300
328
  res.headers.set("X-Robots-Tag", "noindex, nofollow");
301
329
  return applyTracking(res, tracking);
302
330
  }
303
331
 
304
332
  // Unlocked visitors never need the gate screen.
305
- if (unlocked && pathname === "/gate") {
333
+ if (gateUnlocked && pathname === "/gate") {
306
334
  return applyTracking(
307
335
  NextResponse.redirect(new URL("/", req.url)),
308
336
  tracking,
@@ -320,8 +348,8 @@ ${trackingInit} const pathname = req.nextUrl.pathname;
320
348
  if (
321
349
  req.method === "GET" &&
322
350
  accept.includes("text/markdown") &&
323
- !pathname.startsWith("/api") &&
324
- !pathname.startsWith("/_next") &&
351
+ !isPathSegment(pathname, "/api") &&
352
+ !isPathSegment(pathname, "/_next") &&
325
353
  pathname !== "/gate" &&
326
354
  pathname !== "/mcp" &&
327
355
  !/\\.[a-z0-9]+$/i.test(pathname)
@@ -1 +1 @@
1
- export declare const buildDocsIndexScriptTemplate = "/**\n * Precompute document embeddings at build time.\n *\n * Runs before `next build` (wired into the \"build\" script in package.json).\n * Embeds every docs chunk once and writes services/mcp/docs-index.json, so the\n * running app loads vectors instead of re-embedding the whole doc set on every\n * serverless cold start (the main cause of slow first chats / proxy timeouts).\n *\n * Fails soft: without an API key, or on any embedding error, it leaves the\n * existing (possibly empty) index in place and exits 0 so the build proceeds.\n * The app then falls back to embedding on demand at runtime.\n */\nimport path from \"node:path\";\nimport { writeFileSync } from \"node:fs\";\n// @next/env is CommonJS; use a default import so the named export resolves\n// under tsx's ESM loader (a named import is not statically detected).\nimport nextEnv from \"@next/env\";\nimport { getAllDocsChunks } from \"../services/mcp/tools\";\nimport { getLLMConfig, isLLMAvailable } from \"../services/llm/config\";\nimport { createEmbeddings } from \"../services/llm/factory\";\nimport { reduceDims, quantizeInt8, encodeInt8 } from \"../services/mcp/vector\";\n\n// This runs as a standalone process before `next build`, so it must load\n// .env / .env.local / .env.production itself (the same way Next does). Real\n// environment variables still take precedence over .env files.\nnextEnv.loadEnvConfig(process.cwd());\n\nconst OUTPUT = path.join(process.cwd(), \"services\", \"mcp\", \"docs-index.json\");\nconst BATCH_SIZE = 10;\n\nasync function main() {\n if (!isLLMAvailable()) {\n console.warn(\n \"[doccupine] No LLM API key set - skipping embedding precompute. \" +\n \"The chat will embed docs on demand at runtime.\",\n );\n return;\n }\n\n const chunks = await getAllDocsChunks();\n if (chunks.length === 0) {\n console.warn(\"[doccupine] No docs found to embed - skipping precompute.\");\n return;\n }\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Embed in small batches to stay within provider token limits, then reduce\n // each vector to config.embeddingDims and quantize to int8. Storing raw float\n // arrays as JSON balloons to 100MB+ on large doc sets, which OOMs / stalls the\n // serverless chat on cold start; int8 base64 keeps the index ~20x smaller.\n const texts = chunks.map((c) => c.text);\n const encoded: string[] = [];\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = await embeddings.embedDocuments(\n texts.slice(i, i + BATCH_SIZE),\n );\n for (const vector of batch) {\n encoded.push(\n encodeInt8(quantizeInt8(reduceDims(vector, config.embeddingDims))),\n );\n }\n }\n\n const data = {\n provider: config.provider,\n embeddingModel: config.embeddingModel,\n dims: config.embeddingDims,\n quantization: \"int8\",\n chunks: chunks.map((c, i) => ({ ...c, embedding: encoded[i] })),\n };\n\n writeFileSync(OUTPUT, JSON.stringify(data));\n console.log(\n `[doccupine] Precomputed ${data.chunks.length} doc embeddings -> ${OUTPUT}`,\n );\n}\n\nmain()\n .then(() => process.exit(0))\n .catch((error) => {\n // Never fail the build on an embedding error - fall back to runtime embedding.\n console.warn(\n \"[doccupine] Embedding precompute failed; continuing build. \" +\n \"The chat will embed docs at runtime.\",\n error instanceof Error ? error.message : error,\n );\n process.exit(0);\n });\n";
1
+ export declare const buildDocsIndexScriptTemplate = "/**\n * Precompute document embeddings at build time.\n *\n * Runs before `next build` (wired into the \"build\" script in package.json).\n * Embeds every docs chunk once and writes services/mcp/docs-index.json, so the\n * running app loads vectors instead of re-embedding the whole doc set on every\n * serverless cold start (the main cause of slow first chats / proxy timeouts).\n *\n * Fails soft: without an API key, or on any embedding error, it leaves the\n * existing (possibly empty) index in place and exits 0 so the build proceeds.\n * The app then falls back to embedding on demand at runtime.\n */\nimport path from \"node:path\";\nimport { writeFileSync } from \"node:fs\";\n// @next/env is CommonJS; use a default import so the named export resolves\n// under tsx's ESM loader (a named import is not statically detected).\nimport nextEnv from \"@next/env\";\nimport { getAllDocsChunks } from \"../services/mcp/tools\";\nimport { getLLMConfig, isLLMAvailable } from \"../services/llm/config\";\nimport { createEmbeddings } from \"../services/llm/factory\";\nimport { reduceDims, quantizeInt8, encodeInt8 } from \"../services/mcp/vector\";\n\n// This runs as a standalone process before `next build`, so it must load\n// .env / .env.local / .env.production itself (the same way Next does). Real\n// environment variables still take precedence over .env files.\nnextEnv.loadEnvConfig(process.cwd());\n\nconst OUTPUT = path.join(process.cwd(), \"services\", \"mcp\", \"docs-index.json\");\nconst BATCH_SIZE = 10;\n\nasync function main() {\n if (!isLLMAvailable()) {\n console.warn(\n \"[doccupine] No LLM API key set - skipping embedding precompute. \" +\n \"The chat will embed docs on demand at runtime.\",\n );\n return;\n }\n\n const chunks = await getAllDocsChunks();\n if (chunks.length === 0) {\n console.warn(\"[doccupine] No docs found to embed - skipping precompute.\");\n return;\n }\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Embed in small batches to stay within provider token limits, then reduce\n // each vector to config.embeddingDims and quantize to int8. Storing raw float\n // arrays as JSON balloons to 100MB+ on large doc sets, which OOMs / stalls the\n // serverless chat on cold start; int8 base64 keeps the index ~20x smaller.\n const texts = chunks.map((c) => c.text);\n const encoded: string[] = [];\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = await embeddings.embedDocuments(\n texts.slice(i, i + BATCH_SIZE),\n );\n for (const vector of batch) {\n encoded.push(\n encodeInt8(quantizeInt8(reduceDims(vector, config.embeddingDims))),\n );\n }\n }\n\n const data = {\n provider: config.provider,\n embeddingModel: config.embeddingModel,\n dims: config.embeddingDims,\n quantization: \"int8\",\n chunks: chunks.map((c, i) => ({ ...c, embedding: encoded[i] })),\n };\n\n writeFileSync(OUTPUT, JSON.stringify(data));\n // eslint-disable-next-line no-console -- build-time progress belongs in CI logs\n console.log(\n `[doccupine] Precomputed ${data.chunks.length} doc embeddings -> ${OUTPUT}`,\n );\n}\n\nmain()\n .then(() => process.exit(0))\n .catch((error) => {\n // Never fail the build on an embedding error - fall back to runtime embedding.\n console.warn(\n \"[doccupine] Embedding precompute failed; continuing build. \" +\n \"The chat will embed docs at runtime.\",\n error instanceof Error ? error.message : error,\n );\n process.exit(0);\n });\n";
@@ -72,6 +72,7 @@ async function main() {
72
72
  };
73
73
 
74
74
  writeFileSync(OUTPUT, JSON.stringify(data));
75
+ // eslint-disable-next-line no-console -- build-time progress belongs in CI logs
75
76
  console.log(
76
77
  \`[doccupine] Precomputed \${data.chunks.length} doc embeddings -> \${OUTPUT}\`,
77
78
  );
@@ -0,0 +1 @@
1
+ export declare const docsContentStubTemplate = "[]\n";
@@ -0,0 +1 @@
1
+ export const docsContentStubTemplate = `[]\n`;
@@ -1 +1 @@
1
- export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { McpServer } 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, isLLMAvailable, 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\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 once at server startup 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(force = false): Promise<void> {\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 return indexReady;\n }\n if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n return indexReady;\n}\n\n// Eagerly start building the index on server startup if LLM is configured\nif (isLLMAvailable()) {\n const initialBuild = buildDocsIndex();\n indexReady = initialBuild;\n // A failed eager build (e.g. a missing prebuilt index on a large doc set) must\n // not surface as an unhandledRejection at startup; the first request retries\n // via ensureDocsIndex and returns a real error to the client.\n void initialBuild.catch(() => {});\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): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex();\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 getEmbeddings().embedQuery(query);\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, 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.tool(\n \"search_docs\",\n DOCS_TOOLS[0].description,\n {\n query: z\n .string()\n .describe(\"The search query to find relevant documentation\"),\n limit: z\n .number()\n .optional()\n .describe(\"Maximum number of results to return (default: 6)\"),\n },\n async ({ query, limit }) => {\n const results = await searchDocs(query, limit ?? 6);\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // Register the get_doc tool\n server.tool(\n \"get_doc\",\n DOCS_TOOLS[1].description,\n {\n path: z.string().describe(\"The file path to the documentation page\"),\n },\n async ({ path }) => {\n const doc = await getDoc({ path });\n if (!doc) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: \"Document not found\" }),\n },\n ],\n isError: true,\n };\n }\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(doc, null, 2),\n },\n ],\n };\n },\n );\n\n // Register the list_docs tool\n server.tool(\n \"list_docs\",\n DOCS_TOOLS[2].description,\n {\n directory: z\n .string()\n .optional()\n .describe(\"Optional directory to filter results\"),\n },\n async ({ directory }) => {\n const docs = await listDocs({ directory });\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n null,\n 2,\n ),\n },\n ],\n };\n },\n );\n\n // Register documentation as resources\n server.resource(\"docs://list\", \"docs://list\", async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n text: JSON.stringify(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n null,\n 2,\n ),\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 { McpServer } 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, isLLMAvailable, 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 once at server startup 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// Eagerly start building the index on server startup if LLM is configured\nif (isLLMAvailable()) {\n const initialBuild = buildDocsIndex();\n indexReady = initialBuild;\n // A failed eager build (e.g. a missing prebuilt index on a large doc set) must\n // not surface as an unhandledRejection at startup; the first request retries\n // via ensureDocsIndex and returns a real error to the client.\n void initialBuild.catch(() => {});\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 documentation as resources\n server.resource(\"docs://list\", \"docs://list\", async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n });\n\n return server;\n}\n";