doccupine 0.0.162 → 0.0.164

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 CHANGED
@@ -11,354 +11,61 @@
11
11
 
12
12
  # Doccupine
13
13
 
14
- [Doccupine](https://doccupine.com) is an open-source CLI that turns a directory of MDX files into a full-featured Next.js documentation website. Write your docs in Markdown, and Doccupine watches for changes, generates pages, and starts a live dev server automatically.
15
-
16
- ## Features
17
-
18
- - **Live preview** - watches your MDX files and regenerates pages on every save
19
- - **Auto-generated navigation** - sidebar built from frontmatter (`category`, `order`)
20
- - **Sections** - organize docs into tabbed sections via frontmatter or `sections.json`
21
- - **API reference** - point at an OpenAPI spec to generate interactive endpoint pages with a live playground
22
- - **Subscribable changelogs** - pages using the `Update` component publish an RSS feed at `{page-url}/rss.xml`
23
- - **Theming** - dark/light mode with customizable theme via `theme.json`
24
- - **AI chat assistant** - built-in RAG-powered chat (OpenAI, Anthropic, or Google)
25
- - **MCP server** - exposes `search_docs`, `get_doc`, and `list_docs` tools for AI agents
26
- - **Custom fonts** - Google Fonts or local fonts via `fonts.json`
27
- - **Static assets** - `public/` directory is watched and synced to the generated app
28
- - **Lean icons** - only the Lucide glyphs your pages, navigation, footer links, and components use are bundled; an unknown icon name warns when the site is generated and renders nothing
29
- - **Password protection** - gate the whole site behind a shared password with `SITE_PASSWORD`
30
- - **Zero config to start** - `npx doccupine` scaffolds everything and starts the server
31
-
32
- ## Quick Start
33
-
34
- Make sure you have [Node.js](https://nodejs.org) (v22.12.0+) installed.
14
+ Turn a folder of MDX files into a fast, good-looking documentation site, with AI chat and an MCP server built in. One command, no config to start.
35
15
 
36
16
  ```bash
37
17
  npx doccupine
38
18
  ```
39
19
 
40
- Doccupine will prompt you for:
41
-
42
- 1. A directory to store your MDX files (default: `docs`)
43
- 2. An output directory for the generated Next.js app (default: `nextjs-app`)
44
- 3. An optional path to an OpenAPI spec for an API reference (blank to skip)
45
-
46
- It then scaffolds the app, installs dependencies, and starts the dev server. Open http://localhost:3000 to view your docs.
47
-
48
- The source and output directories must not overlap. To prevent accidental data loss, Doccupine only claims an empty output directory, one containing harmless local metadata such as `.DS_Store` or `.env.local`, or an existing Doccupine-generated app. Run `doccupine config --reset` if an older configuration no longer passes validation.
49
-
50
- ## CLI Commands
20
+ Doccupine asks where your MDX files live (default `docs`) and where to put the generated Next.js app (default `nextjs-app`), then installs everything and starts a live preview at http://localhost:3000. Edit a file, and the page updates. Requires [Node.js](https://nodejs.org) 22.12 or later.
21
+
22
+ **[Read the full documentation →](https://docs.doccupine.com)**
23
+
24
+ ## What you get
25
+
26
+ - **Live preview.** Pages regenerate on every save.
27
+ - [Commands](https://docs.doccupine.com/commands)
28
+ - **Navigation and sections.** The sidebar comes from your frontmatter, and sections split the docs into tabs.
29
+ - [Navigation](https://docs.doccupine.com/navigation) · [Sections](https://docs.doccupine.com/sections)
30
+ - **Components.** Callouts, tabs, steps, cards, code blocks, Mermaid diagrams and more, ready to use in MDX.
31
+ - [Components](https://docs.doccupine.com/components)
32
+ - **API reference.** Point it at an OpenAPI spec and get a page per endpoint with a live playground.
33
+ - [API Playground](https://docs.doccupine.com/api-playground)
34
+ - **AI chat assistant.** Visitors ask questions and get answers from your docs, using OpenAI, Anthropic or Google.
35
+ - [AI Assistant](https://docs.doccupine.com/ai-assistant)
36
+ - **MCP server.** AI tools like Claude, Cursor and VS Code can search your docs directly.
37
+ - [Model Context Protocol](https://docs.doccupine.com/model-context-protocol)
38
+ - **Languages and versions.** Translate your docs and keep older releases online.
39
+ - [Languages](https://docs.doccupine.com/languages) · [Versions](https://docs.doccupine.com/versions)
40
+ - **Theming.** Light and dark mode, your colors and fonts.
41
+ - [Theme](https://docs.doccupine.com/theme) · [Fonts](https://docs.doccupine.com/fonts)
42
+ - **Password protection.** Gate the whole site behind a shared password.
43
+ - [Authentication](https://docs.doccupine.com/authentication)
44
+ - **Built for search engines and AI.** Sitemap, `robots.txt`, `llms.txt` and a Markdown copy of every page are generated for you.
45
+ - **Changelogs with RSS.** Publish release notes that readers can subscribe to.
46
+ - [Update component](https://docs.doccupine.com/update)
47
+
48
+ ## Commands
51
49
 
52
50
  ```bash
53
- doccupine watch [options] # Default. Watch MDX files and start dev server
54
- doccupine build [options] # Generate the site without installing or serving it
55
- doccupine generate [options] # Alias for build
56
- doccupine config --show # Show current configuration
57
- doccupine config --reset # Re-prompt for configuration
58
- ```
59
-
60
- ### Options
61
-
62
- `watch` (default):
63
-
64
- | Flag | Description |
65
- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
66
- | `--port <port>` | Port for the dev server (default: `3000`). Auto-increments if taken. |
67
- | `--verbose` | Show all Next.js output including compilation details |
68
- | `--reset` | Re-prompt for watch/output directories |
69
- | `--skip-install` | Generate and serve without running the dependency installer (installs are skipped automatically when `package.json` is unchanged) |
70
- | `--package-manager <name>` | Package manager for the generated app: `pnpm` or `npm` (default: auto-detect). Overrides the `packageManager` field in `doccupine.json`. |
71
-
72
- `build`:
73
-
74
- | Flag | Description |
75
- | --------- | -------------------------------------- |
76
- | `--reset` | Re-prompt for watch/output directories |
77
-
78
- `config`:
79
-
80
- | Flag | Description |
81
- | --------- | ---------------------------------------- |
82
- | `--show` | Print the current configuration and exit |
83
- | `--reset` | Re-prompt for watch/output directories |
84
-
85
- ## MDX Frontmatter
86
-
87
- Each MDX file supports these frontmatter fields:
88
-
89
- ```yaml
90
- ---
91
- title: "Page Title"
92
- description: "Page description for SEO"
93
- category: "Getting Started"
94
- categoryOrder: 0 # Sort order for the category group
95
- order: 1 # Sort order within the category
96
- navIcon: "book-open" # Lucide icon name shown next to the page in the sidebar
97
- categoryIcon: "rocket" # Lucide icon name shown next to the category group
98
- name: "My Docs" # Override site name in title suffix
99
- icon: "https://..." # Page favicon URL
100
- image: "https://..." # OpenGraph image URL
101
- date: "2025-01-01" # Page date metadata
102
- updated: "2025-02-01" # Last-modified date (JSON-LD dateModified)
103
- section: "API Reference" # Section this page belongs to
104
- sectionOrder: 1 # Sort order for the section in the tab bar
105
- openapi: "GET /users/{id}" # Embed an API playground for this endpoint (see API Reference)
106
- rss: true # Show an RSS button linking to the page's feed (pages with Update components)
107
- ---
108
- ```
109
-
110
- Navigation is auto-generated from `category`, `categoryOrder`, and `order`. Pages without a category appear ungrouped.
111
-
112
- Use `sectionLabel` on your root `index.mdx` to rename the default "Docs" tab:
113
-
114
- ```yaml
115
- ---
116
- title: "Welcome"
117
- sectionLabel: "Guides"
118
- ---
119
- ```
120
-
121
- ## Sections
122
-
123
- Sections let you split your docs into separate tabbed groups (e.g. "Docs", "API Reference", "SDKs"). There are two ways to configure them:
124
-
125
- ### Via frontmatter
126
-
127
- Add a `section` field to your MDX files. The section slug is derived from the label automatically. Use `sectionOrder` to control tab order (lower numbers appear first):
128
-
129
- ```yaml
130
- ---
131
- title: "Authentication"
132
- section: "API Reference"
133
- sectionOrder: 1
134
- ---
135
- ```
136
-
137
- Pages without a `section` field stay at the root URL under the default "Docs" tab.
138
-
139
- ### Via `sections.json`
140
-
141
- For full control, create a `sections.json` file in your project root:
142
-
143
- ```json
144
- [
145
- { "label": "Docs", "slug": "" },
146
- { "label": "API Reference", "slug": "api" },
147
- { "label": "SDKs", "slug": "sdks" }
148
- ]
149
- ```
150
-
151
- Each entry has:
152
-
153
- - `label` - display name shown in the section bar
154
- - `slug` - URL prefix for this section (use `""` for the root section)
155
- - `directory` (optional) - subdirectory containing this section's MDX files, only needed when the directory name differs from the slug
156
-
157
- ```json
158
- [
159
- { "label": "Guides", "slug": "", "directory": "guides" },
160
- { "label": "API Reference", "slug": "api", "directory": "api-reference" }
161
- ]
162
- ```
163
-
164
- ## Languages
165
-
166
- Translate your docs by adding a `languages.json` file in your project root and one folder per language inside the docs directory. The default language stays at the docs root with unprefixed URLs; every other language lives in a folder named after its code, which is also its URL prefix:
167
-
168
- ```json
169
- [
170
- { "code": "en", "label": "English", "default": true },
171
- { "code": "de", "label": "Deutsch" }
172
- ]
173
- ```
174
-
175
- ```text
176
- docs/
177
- guides/intro.mdx -> /guides/intro
178
- de/guides/intro.mdx -> /de/guides/intro
179
- ```
180
-
181
- - `code` - a lowercase URL segment (`en`, `de`, `pt-br`); the folder name, the URL prefix, and the `lang`/`hreflang` value
182
- - `label` - the name shown in the sidebar's language dropdown, on the footer row with the focus-mode and theme toggles
183
- - `default` - exactly one entry; its pages live at the docs root
184
- - `strings` (optional) - overrides for the generated site's own labels in that language (search box, sidebar, "On this page", previous/next, action bar, code blocks, AI chat, footer); the key list is documented on the generated site's Languages page
185
-
186
- Only translated pages exist in a language (an untranslated page is a 404 under that prefix, and the switcher falls back to the language's home). The sidebar, search, AI chat, and `llms.txt` are scoped to the current language; translated pages carry `hreflang` alternates with an `x-default`, and the sitemap lists them. A language code must not collide with a section slug, a version slug, or the reserved segments `api`, `gate`, `mcp`, and `ingest`.
187
-
188
- ## Versions
189
-
190
- Keep older releases online by adding a `versions.json` file in your project root and one folder per older version. The default version is the docs root; every other version is a folder named after its slug holding a full copy of the docs as they were:
191
-
192
- ```json
193
- [
194
- { "label": "v2.0", "default": true },
195
- { "slug": "v1", "label": "v1.0" }
196
- ]
197
- ```
198
-
199
- ```text
200
- docs/
201
- guides/intro.mdx -> /guides/intro
202
- v1/guides/intro.mdx -> /v1/guides/intro
203
- de/v1/guides/intro.mdx -> /de/v1/guides/intro
204
- ```
205
-
206
- The default entry has no `slug`. Versions combine with languages; the language folder comes first. The sidebar shows a version dropdown on the footer row with the focus-mode and theme toggles, and the sidebar, search, AI chat, and `llms.txt` are scoped to the current version. The API reference generated from an OpenAPI spec is published in the default language and version only.
207
-
208
- For both features, `navigation.json` in object form is keyed by URL prefix: `""`, `"api"`, `"de"`, `"de/api"`, `"v1"`, `"de/v1/api"`. Existing files keyed by section slug keep working.
209
-
210
- ## API Reference
211
-
212
- Point Doccupine at an OpenAPI document (`.json`, `.yaml`, or `.yml`, OpenAPI 3.0/3.1) and it generates an interactive API reference: a directory at `/api-reference` linking every operation, plus one page per operation with a live playground for sending requests. Set the `openapi` field in `doccupine.json`:
213
-
214
- ```json
215
- {
216
- "openapi": "openapi.json"
217
- }
218
- ```
219
-
220
- The endpoint pages are grouped into their own "API Reference" tab, and your hand-written docs move under a "Documentation" tab. The spec file is watched, so edits regenerate the reference live.
221
-
222
- You can pass multiple specs as an array of paths, or name them explicitly:
223
-
224
- ```json
225
- {
226
- "openapi": [
227
- { "name": "Public API", "file": "openapi.json" },
228
- { "name": "Admin API", "file": "admin-openapi.yaml" }
229
- ]
230
- }
231
- ```
232
-
233
- To embed a single endpoint's playground inline within a hand-written page, add an `openapi` frontmatter field set to `"METHOD /path"` (or the operation's `operationId`):
234
-
235
- ```yaml
236
- ---
237
- title: "Fetch a User"
238
- openapi: "GET /users/{id}"
239
- ---
51
+ doccupine # watch your docs and run the live preview (same as `doccupine watch`)
52
+ doccupine build # generate the site once, for CI or deployment
53
+ doccupine config --show # show the saved configuration
54
+ doccupine config --reset # reset the saved configuration
240
55
  ```
241
56
 
242
- ## Configuration Files
243
-
244
- Place these JSON files in your project root (where you run `doccupine`). They are auto-copied to the generated app and watched for changes.
245
-
246
- | File | Purpose |
247
- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
248
- | `doccupine.json` | CLI config (`watchDir`, `outputDir`, `port`, `packageManager`, `openapi`). Auto-generated on first run. Paths are stored relative to the project root, so the file is safe to commit. |
249
- | `config.json` | Site metadata: `name`, `description`, `icon`, `image`, `url` (public site URL for sitemap/robots) |
250
- | `theme.json` | Theme overrides for [cherry-styled-components](https://github.com/cherry-design-system/styled-components) |
251
- | `navigation.json` | Manual navigation structure (overrides auto-generated) |
252
- | `links.json` | Static header/footer links |
253
- | `fonts.json` | Font configuration (Google Fonts or local) |
254
- | `sections.json` | Section definitions for tabbed doc groups (see [Sections](#sections)) |
255
- | `languages.json` | Languages and their folders (see [Languages](#languages)) |
256
- | `versions.json` | Documentation versions and their folders (see [Versions](#versions)) |
257
- | `analytics.json` | Analytics provider configuration (PostHog supported) |
258
-
259
- ## Public Directory
260
-
261
- Place static assets (images, favicons, etc.) in a `public/` directory at your project root. Doccupine copies it to the generated Next.js app on startup and watches for changes, so added, modified, or deleted files are synced automatically.
262
-
263
- ## Sitemap and robots.txt
264
-
265
- Doccupine generates `robots.ts` automatically for every site. When you set a `url` in `config.json`, it also generates `sitemap.ts` covering every page (across all sections) and links the sitemap from `robots.txt`.
266
-
267
- ```json
268
- {
269
- "name": "My Docs",
270
- "url": "https://docs.example.com"
271
- }
272
- ```
273
-
274
- You can override the URL at deploy time by setting the `NEXT_PUBLIC_SITE_URL` environment variable. When no URL is configured, `/sitemap.xml` is still served but stays empty, and `robots.txt` omits its sitemap reference until a public URL is available. The variable is baked in at build time, so changing it needs a redeploy.
275
-
276
- ## llms.txt
277
-
278
- Doccupine generates [llms.txt](https://llmstxt.org) artifacts so AI agents can discover and ingest your docs. On every regeneration, the following files are written to the generated app's `public/` directory:
279
-
280
- | File | Contents |
281
- | ------------------ | --------------------------------------------------------------------------------------- |
282
- | `llms.txt` | Index of every page (title, description, URL), grouped by section and category |
283
- | `llms-full.txt` | Full-text bundle: every page's body concatenated for one-shot ingestion |
284
- | `public/<slug>.md` | Per-page Markdown mirror of each MDX page, suitable for direct fetching at `/<slug>.md` |
57
+ All options are in the [Commands](https://docs.doccupine.com/commands) docs.
285
58
 
286
- With [languages](#languages) or [versions](#versions) configured, the root `llms.txt` and `llms-full.txt` describe the default language and version and link to the other variants, each of which has its own pair under its URL prefix (`/de/llms.txt`, `/v1/llms-full.txt`).
287
-
288
- The site name and description used in `llms.txt` come from `config.json` (`name`, `description`). Page URLs are absolute when `url` is set in `config.json` (or via `NEXT_PUBLIC_SITE_URL`), and root-relative otherwise.
289
-
290
- A `.doccupine-artifacts.json` file in the generated app tracks generated route ownership and per-page mirrors so renamed or deleted sources clean up only their own outputs. Don't commit this file; it is regenerated automatically.
291
-
292
- ## AI Chat Setup
293
-
294
- The generated app includes an AI chat assistant. To enable it, create a `.env` file in the generated app directory:
295
-
296
- ```env
297
- LLM_PROVIDER=openai # openai | anthropic | google
298
-
299
- # API Keys (set the one matching your provider)
300
- OPENAI_API_KEY=sk-...
301
- ANTHROPIC_API_KEY=sk-ant-...
302
- GOOGLE_API_KEY=...
303
- ```
304
-
305
- If `LLM_PROVIDER` is not set, the chat component is hidden automatically.
306
-
307
- > **Note:** Anthropic does not provide an embeddings API. When using `anthropic` as your provider, you must also set `OPENAI_API_KEY` for embeddings to work.
308
-
309
- ### Optional overrides
310
-
311
- ```env
312
- LLM_CHAT_MODEL=gpt-6-luna # Override the default chat model
313
- LLM_EMBEDDING_MODEL=text-embedding-3-small # Override the default embedding model
314
- LLM_TEMPERATURE=0 # Set temperature (default: 0; "default" sends none)
315
- LLM_EMBEDDING_DIMS=512 # Dimensions for the prebuilt search index (default: 512)
316
- RAG_RUNTIME_EMBED_MAX_CHUNKS=400 # Max chunks embedded on demand in production (default: 400; 0 requires a prebuilt index)
317
- # RAG_API_KEY=... # Optional bearer auth for direct /api/rag requests
318
- ```
319
-
320
- `LLM_TEMPERATURE` accepts 0 to 2; an invalid value is ignored with a warning. It only applies to models that still take a custom temperature, such as `gpt-4.1` or `gemini-2.5-flash`, so none of the default models gets one. No temperature is sent to Anthropic, whose current API version rejects it on every model, to OpenAI's reasoning models (`o3`, `o4-mini`) and its GPT-5 models onwards, or to Gemini 3.5 models onwards, which ignore it.
321
-
322
- `LLM_EMBEDDING_DIMS` Matryoshka-truncates document vectors so the prebuilt search index stays small; lower values shrink the index at a slight cost to recall. `RAG_RUNTIME_EMBED_MAX_CHUNKS` caps how many chunks the chat will embed on demand in production before requiring a prebuilt index (it's unlimited under `next dev`).
323
-
324
- Public documentation leaves browser chat available by default. Setting `RAG_API_KEY` requires a bearer token for `/api/rag` and is intended for server-to-server use; the built-in browser cannot safely hold that secret. Use `SITE_PASSWORD` instead when authenticated browser visitors should retain chat access.
325
-
326
- Default models per provider:
327
-
328
- | Provider | Chat model | Embedding model |
329
- | --------- | ----------------------- | ------------------------ |
330
- | OpenAI | `gpt-6-luna` | `text-embedding-3-small` |
331
- | Anthropic | `claude-haiku-5-5` | OpenAI fallback |
332
- | Google | `gemini-3.5-flash-lite` | `gemini-embedding-001` |
333
-
334
- ## MCP Server
335
-
336
- The generated app exposes an MCP endpoint at `/api/mcp` with three tools:
337
-
338
- - `search_docs` - semantic search across all documentation
339
- - `get_doc` - retrieve a specific document by path
340
- - `list_docs` - list all available documents
341
-
342
- This lets AI agents (Claude, ChatGPT, etc.) query your docs programmatically. Semantic `search_docs` requires the AI setup above for embeddings; `get_doc` and `list_docs` work from the generated content manifest without an embedding provider. On a site with [languages](#languages) or [versions](#versions), `search_docs` and `list_docs` accept optional `language` and `version` parameters and default to the default language and version; the `docs://list` resource lists every variant.
343
-
344
- ## Password Protection
345
-
346
- Gate your entire documentation site behind a shared password by setting `SITE_PASSWORD` in the generated app's environment - add it to `.env` for local development, or your host's environment variables in production:
347
-
348
- ```env
349
- SITE_PASSWORD=choose-a-strong-shared-password
350
- ```
59
+ ## Deploy
351
60
 
352
- When set, every visitor sees a login screen until they enter the password. Protection is enforced across three layers:
61
+ The generated app is a standard Next.js project, so it runs anywhere Next.js does. See [Deployment & Hosting](https://docs.doccupine.com/deployment-and-hosting).
353
62
 
354
- - **Pages** are gated behind the login screen.
355
- - **Content APIs** (`/api/rag` chat, `/api/search`, and the `/api/playground` proxy) return `401` without a valid session, so the docs can't be scraped and the proxy can't relay anonymous requests around the login. Each route re-checks the session itself, not just the middleware.
356
- - **Search engines and crawlers** are blocked: `robots.txt` disallows everything, pages carry a `noindex, nofollow` tag, and responses include an `X-Robots-Tag` header.
63
+ Prefer not to host it yourself? [Doccupine](https://doccupine.com) builds, hosts and updates your docs site for you.
357
64
 
358
- A successful login sets a signed, `httpOnly` cookie that lasts 30 days. The cookie stores an HMAC of the password, never the password itself. Leave `SITE_PASSWORD` unset (the default) to keep the site fully public. Documentation pages stay statically rendered either way - the gate is enforced in middleware.
65
+ ## Contributing
359
66
 
360
- > **Note:** The [MCP endpoint](#mcp-server) uses `DOCS_API_KEY` bearer authentication when configured. Without an API key, a password-protected site requires the normal gate session for MCP as well.
67
+ Bug reports and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md), and report security issues as described in [SECURITY.md](SECURITY.md).
361
68
 
362
69
  ## License
363
70
 
364
- This project is licensed under a modified MIT license with a SaaS restriction. See [LICENSE](LICENSE) for details.
71
+ Modified MIT license with a SaaS restriction. See [LICENSE](LICENSE).
@@ -1 +1 @@
1
- export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n createMCPServer,\n searchDocs,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n MCP_MAX_REQUEST_BYTES,\n MCP_MAX_TOOL_ARGUMENT_BYTES,\n searchDocsArgsSchema,\n getDocArgsSchema,\n listDocsArgsSchema,\n resolveDocsFilter,\n serializeMCPResult,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { isMcpRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_PROTOCOL_MESSAGES = 20;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction jsonByteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value) ?? \"null\").byteLength;\n}\n\nfunction protocolToolCallError(body: unknown): string | null {\n const messages = Array.isArray(body) ? body : [body];\n if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {\n return \"Invalid protocol batch\";\n }\n\n let toolCallCount = 0;\n for (const message of messages) {\n if (!isRecord(message) || message.method !== \"tools/call\") continue;\n toolCallCount++;\n if (toolCallCount > 1) {\n return \"Only one tools/call is allowed per request\";\n }\n if (!isRecord(message.params) || typeof message.params.name !== \"string\") {\n return \"Invalid tool call\";\n }\n\n const args = message.params.arguments ?? {};\n if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return \"Tool arguments exceed the maximum size\";\n }\n\n let valid = true;\n switch (message.params.name) {\n case \"search_docs\":\n valid = searchDocsArgsSchema.safeParse(args).success;\n break;\n case \"get_doc\":\n valid = getDocArgsSchema.safeParse(args).success;\n break;\n case \"list_docs\":\n valid = listDocsArgsSchema.safeParse(args).success;\n break;\n }\n if (!valid) return \"Invalid tool arguments\";\n }\n return null;\n}\n\nfunction protocolError(message: string, status = 400): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: status === 500 ? -32603 : -32602, message },\n id: null,\n },\n { status },\n );\n}\n\nfunction createTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n}\n\nasync function handleMCPRequest(req: Request, parsedBody?: unknown) {\n const transport = createTransport();\n const server = createMCPServer();\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n void Promise.allSettled([transport.close(), server.close()]);\n };\n req.signal.addEventListener(\"abort\", close, { once: true });\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(\n req,\n parsedBody === undefined ? undefined : { parsedBody },\n );\n\n const body = response.clone().body;\n if (body) {\n void body\n .pipeTo(new WritableStream())\n .catch(() => {})\n .finally(close);\n } else {\n close();\n }\n return response;\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP protocol request failed:\", error);\n close();\n return protocolError(\"Internal server error\", 500);\n }\n}\n\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: unknown;\n}\n\nfunction toolResponse(value: unknown): Response {\n const result = serializeMCPResult(value);\n if (result.tooLarge) {\n return NextResponse.json(\n { error: \"Tool result exceeds the maximum response size\" },\n { status: 413 },\n );\n }\n return new Response(result.text, {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nasync function handleRESTRequest(req: Request, body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n req.signal,\n resolveDocsFilter({\n language: parsed.data.language,\n version: parsed.data.version,\n }),\n );\n return toolResponse({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n ...(chunk.locale !== undefined ? { language: chunk.locale } : {}),\n ...(chunk.version !== undefined ? { version: chunk.version } : {}),\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const doc = await getDoc({ path: parsed.data.path });\n req.signal.throwIfAborted();\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return toolResponse({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const docs = await listDocs({\n directory: parsed.data.directory,\n language: parsed.data.language,\n version: parsed.data.version,\n });\n req.signal.throwIfAborted();\n return toolResponse({\n content: docs.map((doc) => ({\n name: doc.name,\n path: doc.path,\n uri: doc.uri,\n ...(doc.locale !== undefined ? { language: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n })),\n });\n }\n\n default:\n return NextResponse.json({ error: \"Unknown tool\" }, { status: 400 });\n }\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP REST tool failed:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n\nexport async function POST(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let body: unknown;\n try {\n body = await readJsonBody(req, MCP_MAX_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n if (Array.isArray(body) || (isRecord(body) && \"jsonrpc\" in body)) {\n const validationError = protocolToolCallError(body);\n if (validationError) return protocolError(validationError);\n return handleMCPRequest(req, body);\n }\n\n if (isRecord(body) && typeof body.tool === \"string\") {\n if (jsonByteLength(body.params ?? {}) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return NextResponse.json(\n { error: \"Tool arguments exceed the maximum size\" },\n { status: 413 },\n );\n }\n return handleRESTRequest(req, {\n tool: body.tool as MCPToolName,\n params: body.params ?? {},\n });\n }\n\n return NextResponse.json(\n { error: \"Invalid request format\" },\n { status: 400 },\n );\n}\n\nexport async function GET(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n tools: DOCS_TOOLS,\n index: { ready: status.ready, chunkCount: status.chunkCount },\n });\n}\n\nexport async function DELETE(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n return handleMCPRequest(req);\n}\n";
1
+ export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport {\n createMcpHandler,\n isLegacyRequest,\n WebStandardStreamableHTTPServerTransport,\n} from \"@modelcontextprotocol/server\";\nimport {\n createMCPServer,\n searchDocs,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n MCP_MAX_REQUEST_BYTES,\n MCP_MAX_TOOL_ARGUMENT_BYTES,\n searchDocsArgsSchema,\n getDocArgsSchema,\n listDocsArgsSchema,\n resolveDocsFilter,\n serializeMCPResult,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { isMcpRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_PROTOCOL_MESSAGES = 20;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction jsonByteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value) ?? \"null\").byteLength;\n}\n\nfunction protocolToolCallError(body: unknown): string | null {\n const messages = Array.isArray(body) ? body : [body];\n if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {\n return \"Invalid protocol batch\";\n }\n\n let toolCallCount = 0;\n for (const message of messages) {\n if (!isRecord(message) || message.method !== \"tools/call\") continue;\n toolCallCount++;\n if (toolCallCount > 1) {\n return \"Only one tools/call is allowed per request\";\n }\n if (!isRecord(message.params) || typeof message.params.name !== \"string\") {\n return \"Invalid tool call\";\n }\n\n const args = message.params.arguments ?? {};\n if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return \"Tool arguments exceed the maximum size\";\n }\n\n let valid = true;\n switch (message.params.name) {\n case \"search_docs\":\n valid = searchDocsArgsSchema.safeParse(args).success;\n break;\n case \"get_doc\":\n valid = getDocArgsSchema.safeParse(args).success;\n break;\n case \"list_docs\":\n valid = listDocsArgsSchema.safeParse(args).success;\n break;\n }\n if (!valid) return \"Invalid tool arguments\";\n }\n return null;\n}\n\nfunction protocolError(message: string, status = 400): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: status === 500 ? -32603 : -32602, message },\n id: null,\n },\n { status },\n );\n}\n\nfunction reportProtocolError(error: unknown) {\n console.error(\"[doccupine] MCP protocol request failed:\", error);\n}\n\n// Clients on the 2026-07-28 revision send self-contained requests: no\n// initialize handshake and no session. A fresh server answers each one; the\n// tools send nothing before their result, so the answer is a single JSON body.\nconst modernHandler = createMcpHandler(() => createMCPServer(), {\n legacy: \"reject\",\n maxRequestBodySize: MCP_MAX_REQUEST_BYTES,\n onerror: reportProtocolError,\n});\n\n// 2025-era clients (initialize handshake) keep the stateless transport they\n// used before, answered with JSON rather than an SSE stream.\nfunction createLegacyTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n}\n\nasync function handleLegacyRequest(req: Request, parsedBody?: unknown) {\n const transport = createLegacyTransport();\n const server = createMCPServer();\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n void Promise.allSettled([transport.close(), server.close()]);\n };\n req.signal.addEventListener(\"abort\", close, { once: true });\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(\n req,\n parsedBody === undefined ? undefined : { parsedBody },\n );\n\n const body = response.clone().body;\n if (body) {\n void body\n .pipeTo(new WritableStream())\n .catch(() => {})\n .finally(close);\n } else {\n close();\n }\n return response;\n } catch (error: unknown) {\n reportProtocolError(error);\n close();\n return protocolError(\"Internal server error\", 500);\n }\n}\n\nasync function handleMCPRequest(req: Request, parsedBody: unknown) {\n if (await isLegacyRequest(req, parsedBody)) {\n return handleLegacyRequest(req, parsedBody);\n }\n return modernHandler.fetch(req, { parsedBody });\n}\n\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: unknown;\n}\n\nfunction toolResponse(value: unknown): Response {\n const result = serializeMCPResult(value);\n if (result.tooLarge) {\n return NextResponse.json(\n { error: \"Tool result exceeds the maximum response size\" },\n { status: 413 },\n );\n }\n return new Response(result.text, {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nasync function handleRESTRequest(req: Request, body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n req.signal,\n resolveDocsFilter({\n language: parsed.data.language,\n version: parsed.data.version,\n }),\n );\n return toolResponse({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n ...(chunk.locale !== undefined ? { language: chunk.locale } : {}),\n ...(chunk.version !== undefined ? { version: chunk.version } : {}),\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const doc = await getDoc({ path: parsed.data.path });\n req.signal.throwIfAborted();\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return toolResponse({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const docs = await listDocs({\n directory: parsed.data.directory,\n language: parsed.data.language,\n version: parsed.data.version,\n });\n req.signal.throwIfAborted();\n return toolResponse({\n content: docs.map((doc) => ({\n name: doc.name,\n path: doc.path,\n uri: doc.uri,\n ...(doc.locale !== undefined ? { language: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n })),\n });\n }\n\n default:\n return NextResponse.json({ error: \"Unknown tool\" }, { status: 400 });\n }\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP REST tool failed:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n\nexport async function POST(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let body: unknown;\n try {\n body = await readJsonBody(req, MCP_MAX_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n if (Array.isArray(body) || (isRecord(body) && \"jsonrpc\" in body)) {\n const validationError = protocolToolCallError(body);\n if (validationError) return protocolError(validationError);\n return handleMCPRequest(req, body);\n }\n\n if (isRecord(body) && typeof body.tool === \"string\") {\n if (jsonByteLength(body.params ?? {}) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return NextResponse.json(\n { error: \"Tool arguments exceed the maximum size\" },\n { status: 413 },\n );\n }\n return handleRESTRequest(req, {\n tool: body.tool as MCPToolName,\n params: body.params ?? {},\n });\n }\n\n return NextResponse.json(\n { error: \"Invalid request format\" },\n { status: 400 },\n );\n}\n\nexport async function GET(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n tools: DOCS_TOOLS,\n index: { ready: status.ready, chunkCount: status.chunkCount },\n });\n}\n\nexport async function DELETE(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n return handleLegacyRequest(req);\n}\n";
@@ -1,5 +1,9 @@
1
1
  export const mcpRoutesTemplate = `import { NextResponse } from "next/server";
2
- import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
2
+ import {
3
+ createMcpHandler,
4
+ isLegacyRequest,
5
+ WebStandardStreamableHTTPServerTransport,
6
+ } from "@modelcontextprotocol/server";
3
7
  import {
4
8
  createMCPServer,
5
9
  searchDocs,
@@ -80,15 +84,30 @@ function protocolError(message: string, status = 400): Response {
80
84
  );
81
85
  }
82
86
 
83
- function createTransport() {
87
+ function reportProtocolError(error: unknown) {
88
+ console.error("[doccupine] MCP protocol request failed:", error);
89
+ }
90
+
91
+ // Clients on the 2026-07-28 revision send self-contained requests: no
92
+ // initialize handshake and no session. A fresh server answers each one; the
93
+ // tools send nothing before their result, so the answer is a single JSON body.
94
+ const modernHandler = createMcpHandler(() => createMCPServer(), {
95
+ legacy: "reject",
96
+ maxRequestBodySize: MCP_MAX_REQUEST_BYTES,
97
+ onerror: reportProtocolError,
98
+ });
99
+
100
+ // 2025-era clients (initialize handshake) keep the stateless transport they
101
+ // used before, answered with JSON rather than an SSE stream.
102
+ function createLegacyTransport() {
84
103
  return new WebStandardStreamableHTTPServerTransport({
85
104
  sessionIdGenerator: undefined,
86
105
  enableJsonResponse: true,
87
106
  });
88
107
  }
89
108
 
90
- async function handleMCPRequest(req: Request, parsedBody?: unknown) {
91
- const transport = createTransport();
109
+ async function handleLegacyRequest(req: Request, parsedBody?: unknown) {
110
+ const transport = createLegacyTransport();
92
111
  const server = createMCPServer();
93
112
  let closed = false;
94
113
  const close = () => {
@@ -116,12 +135,19 @@ async function handleMCPRequest(req: Request, parsedBody?: unknown) {
116
135
  }
117
136
  return response;
118
137
  } catch (error: unknown) {
119
- console.error("[doccupine] MCP protocol request failed:", error);
138
+ reportProtocolError(error);
120
139
  close();
121
140
  return protocolError("Internal server error", 500);
122
141
  }
123
142
  }
124
143
 
144
+ async function handleMCPRequest(req: Request, parsedBody: unknown) {
145
+ if (await isLegacyRequest(req, parsedBody)) {
146
+ return handleLegacyRequest(req, parsedBody);
147
+ }
148
+ return modernHandler.fetch(req, { parsedBody });
149
+ }
150
+
125
151
  interface ToolCallRequest {
126
152
  tool: MCPToolName;
127
153
  params: unknown;
@@ -303,6 +329,6 @@ export async function DELETE(req: Request) {
303
329
  if (!(await isMcpRequestAuthorized(req))) {
304
330
  return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
305
331
  }
306
- return handleMCPRequest(req);
332
+ return handleLegacyRequest(req);
307
333
  }
308
334
  `;
@@ -1 +1 @@
1
- export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel, chunkText } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { resolveDocsFilter } from \"@/services/mcp/tools\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\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\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history, locale, version } = parsed.data;\n // Retrieval stays inside the language/version the reader is looking at.\n const docsFilter = resolveDocsFilter({ language: locale, version });\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal, docsFilter);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunkText(chunk);\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
1
+ export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel, chunkText } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { resolveDocsFilter } from \"@/services/mcp/tools\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\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\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Never Mention the Context\nThe context is retrieved behind the scenes; the user never sees it and does not know it exists. Speak as if you simply know the documentation.\n- Never refer to \"the context\", \"the provided context\", \"the excerpts\", \"the chunks\", \"the sources I was given\" or similar. Phrases like \"The context also describes...\" or \"Based on the provided context...\" are forbidden.\n- Never comment on what you were or were not given, how the information reached you, or how you work internally.\n- Refer to the material as \"the documentation\" or \"the docs\", or just state the facts directly.\n- When something isn't covered, say \"The documentation doesn't cover that\" rather than \"That isn't in the context\".\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history, locale, version } = parsed.data;\n // Retrieval stays inside the language/version the reader is looking at.\n const docsFilter = resolveDocsFilter({ language: locale, version });\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal, docsFilter);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunkText(chunk);\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
@@ -66,6 +66,13 @@ const systemContext = \`You are AI Assistant, a documentation assistant for \${p
66
66
  2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.
67
67
  3. If the question is ambiguous, ask a brief clarifying question before answering.
68
68
 
69
+ ## Never Mention the Context
70
+ The context is retrieved behind the scenes; the user never sees it and does not know it exists. Speak as if you simply know the documentation.
71
+ - Never refer to "the context", "the provided context", "the excerpts", "the chunks", "the sources I was given" or similar. Phrases like "The context also describes..." or "Based on the provided context..." are forbidden.
72
+ - Never comment on what you were or were not given, how the information reached you, or how you work internally.
73
+ - Refer to the material as "the documentation" or "the docs", or just state the facts directly.
74
+ - When something isn't covered, say "The documentation doesn't cover that" rather than "That isn't in the context".
75
+
69
76
  ## Response Style
70
77
  - Be concise and direct. Lead with the answer, then provide details if needed.
71
78
  - Use code examples from the context when relevant.
@@ -1 +1 @@
1
- export declare const mcpMdxTemplate = "---\ntitle: \"Model Context Protocol\"\ndescription: \"Connect your Doccupine documentation to AI tools with an MCP server for enhanced AI-powered documentation search.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-31\"\ncategory: \"AI & Integrations\"\ncategoryOrder: 3\norder: 2\n---\n# Model Context Protocol\n\nConnect your documentation to AI tools with a hosted MCP server.\n\nDoccupine automatically generates a Model Context Protocol (MCP) server from your documentation, making your content accessible to AI applications like Claude, Cursor, VS Code, and other MCP-compatible tools. Your MCP server exposes semantic search capabilities, allowing AI tools to query your documentation directly and provide accurate, context-aware answers.\n\n<Callout type=\"warning\">\n Semantic `search_docs` requires the [AI Assistant](/ai-assistant) embedding\n provider to be configured. `get_doc` and `list_docs` can retrieve the generated\n content manifest without an embedding provider.\n</Callout>\n\n## About MCP servers\n\nThe Model Context Protocol (MCP) is an open protocol that creates standardized connections between AI applications and external services, like documentation. Doccupine generates an MCP server from your documentation, preparing your content for the broader AI ecosystem where any MCP client can connect to your documentation.\n\nYour MCP server exposes search and retrieval tools for AI applications to query your documentation. Your users must connect your MCP server to their preferred AI tools to access your documentation.\n\n### How MCP servers work\n\nWhen an AI tool has your documentation MCP server connected, the AI tool can search your documentation directly instead of making a generic web search in response to a user's prompt. Your MCP server provides access to all indexed content from your documentation site.\n\n- The LLM can proactively search your documentation while generating a response, not just when explicitly asked.\n- The LLM determines when to use the search tool based on the context of the conversation and the relevance of your documentation.\n- Each tool call happens during the generation process, so the LLM searches up-to-date information from your documentation to generate its response.\n\n### MCP compared to web search\n\nAI tools can search the web, but MCP provides distinct advantages for documentation.\n\n- **Direct source access**: Web search depends on what search engines have indexed, which may be stale or incomplete. MCP searches your current indexed documentation directly.\n- **Integrated workflow**: MCP allows the AI to search during response generation rather than performing a separate web search.\n- **Semantic search**: MCP uses vector embeddings for semantic similarity search, providing more relevant results than keyword-based web search.\n- **No search noise**: SEO and ranking algorithms influence web search results. MCP goes straight to your documentation content.\n\n## Access your MCP server\n\nDoccupine automatically generates an MCP server for your documentation and hosts it at your documentation URL with the `/api/mcp` path. For example, if your documentation is hosted at `https://example.com`, your MCP server is available at `https://example.com/api/mcp`.\n\nThe MCP server provides both a GET endpoint to discover available tools and a POST endpoint to execute tool calls.\n\n### Authentication\n\nYou can optionally protect your MCP server with an API key by setting the `DOCS_API_KEY` environment variable in your `.env` file:\n\n```bash\nDOCS_API_KEY=your-secret-key\n```\n\nWhen `DOCS_API_KEY` is set, all requests to `/api/mcp` must include an `Authorization` header with a Bearer token:\n\n```text\nAuthorization: Bearer your-secret-key\n```\n\nRequests without a valid token receive a `401 Unauthorized` response. When `DOCS_API_KEY` is not set, the MCP server follows the site's access mode: it is public on a public site and requires the normal gate session when `SITE_PASSWORD` is configured.\n\n<Callout type=\"note\">\n `DOCS_API_KEY` applies to `/api/mcp` and its `/mcp` discovery alias; it does not grant access to the chat, search, or playground APIs. To gate the entire site behind a shared password, see the [Authentication](/authentication) documentation.\n</Callout>\n\n### Rate limiting\n\nTool calls to `POST /api/mcp` are rate limited per client IP when the generated app runs on a recognized platform that supplies a trusted client-address header. Unknown or self-hosted proxy setups use one conservative shared bucket instead of trusting spoofable forwarding headers. When the limit is exceeded, the server responds with `429 Too Many Requests` and a `Retry-After` header indicating how many seconds to wait before retrying.\n\nThe included limiter is intentionally lightweight and scoped to each running server instance. For a globally consistent limit across multiple serverless instances or regions, or accurate per-client limits behind a custom reverse proxy, configure rate limiting at your trusted hosting edge or use a shared external rate-limit store.\n\nRequests are bounded before tool execution: request bodies, protocol batches, tool arguments, search result counts, and serialized responses all have fixed limits. A protocol body may contain at most one `tools/call` message, so one rate-limited request cannot execute multiple paid tools; batches containing only non-tool protocol messages remain compatible. Internal provider errors are logged on the server and returned to clients as generic failures so deployment details are not exposed.\n\n### API Endpoints\n\n#### GET /api/mcp\n\nReturns information about available tools and the current index status.\n\n**Response:**\n\n```json\n{\n \"tools\": [\n {\n \"name\": \"search_docs\",\n \"description\": \"Search through the documentation content using semantic search...\",\n \"inputSchema\": { ... }\n },\n ...\n ],\n \"index\": {\n \"ready\": true,\n \"chunkCount\": 150\n }\n}\n```\n\n#### POST /api/mcp\n\nExecutes an MCP tool call.\n\n**Request Body:**\n\n```json\n{\n \"tool\": \"search_docs\",\n \"params\": {\n \"query\": \"how to deploy\",\n \"limit\": 6\n }\n}\n```\n\n**Response:**\n\n```json\n{\n \"content\": [\n {\n \"path\": \"app/deployment-and-hosting/page.tsx\",\n \"uri\": \"docs://deployment-and-hosting\",\n \"score\": \"0.892\",\n \"text\": \"Deploy your Doccupine site as a Next.js application...\"\n },\n ...\n ]\n}\n```\n\n## Available Tools\n\nYour MCP server exposes three tools for interacting with your documentation:\n\n### search_docs\n\nSearch through the documentation content using semantic search. Returns relevant chunks of documentation based on the query using vector embeddings and cosine similarity.\n\n**Parameters:**\n\n- `query` (required): The search query to find relevant documentation\n- `limit` (optional): Maximum number of results to return (default: 6)\n- `language` (optional): Language code to search on a site with [languages](/languages); defaults to the site's default language\n- `version` (optional): Version slug to search on a site with [versions](/versions); defaults to the current version\n\n**Example:**\n\n```json\n{\n \"tool\": \"search_docs\",\n \"params\": {\n \"query\": \"how to configure AI assistant\",\n \"limit\": 5\n }\n}\n```\n\n### get_doc\n\nGet the full content of a specific documentation page by its path.\n\n**Parameters:**\n\n- `path` (required): The file path to the documentation page (e.g., `app/getting-started/page.tsx`)\n\n**Example:**\n\n```json\n{\n \"tool\": \"get_doc\",\n \"params\": {\n \"path\": \"app/deployment-and-hosting/page.tsx\"\n }\n}\n```\n\n### list_docs\n\nList all available documentation pages, optionally filtered by directory.\n\n**Parameters:**\n\n- `directory` (optional): Optional directory to filter results (e.g., `components`)\n- `language` (optional): Language code to list on a site with [languages](/languages); defaults to the site's default language\n- `version` (optional): Version slug to list on a site with [versions](/versions); defaults to the current version\n\nResults carry the page's `language` and `version` on such a site, and the `docs://list` resource lists every language and version at once.\n\n**Example:**\n\n```json\n{\n \"tool\": \"list_docs\",\n \"params\": {\n \"directory\": \"configuration\"\n }\n}\n```\n\n## How it works\n\nDoccupine's MCP server uses semantic search powered by vector embeddings to provide accurate, context-aware search results.\n\n### Indexing Process\n\nDoccupine runs this pipeline at build time and ships the resulting vectors with your site, so the server loads a ready-made index instead of re-embedding your docs on every cold start.\n\n1. **Content Manifest**: During generation, Doccupine writes the source MDX and generated API-reference content to `services/mcp/docs-content.json`.\n2. **Runtime Loading**: The build traces that manifest into the MCP and RAG functions, which read it from one fixed path without inlining the corpus into their JavaScript bundles.\n3. **Chunking**: Large documents are split into chunks of approximately 800 characters with 100 character overlap for better context preservation.\n4. **Embedding Generation**: Each chunk is converted to a vector embedding using your configured LLM provider's embedding model.\n5. **Compaction**: Each vector is truncated to `LLM_EMBEDDING_DIMS` dimensions (default 512) and quantized to int8, keeping the index roughly 20x smaller than raw floats so large doc sets don't stall the chat on cold start.\n6. **Index Building**: The compact embeddings are written to `services/mcp/docs-index.json`, traced into your serverless functions as a data file, and loaded into memory at runtime for fast similarity search.\n\n### Search Process\n\n1. **Query Embedding**: The search query is converted to a vector embedding using the same embedding model.\n2. **Similarity Calculation**: Cosine similarity is calculated between the query embedding and all document chunk embeddings.\n3. **Ranking**: Results are sorted by similarity score (highest first).\n4. **Response**: The top N results (based on the limit parameter) are returned with their paths, URIs, scores, and text content.\n\n<Callout type=\"note\">\n Embeddings are precomputed at build time and shipped as a traced data file, so the server loads the ready-made index into memory on startup instead of re-embedding your docs on every cold start. It only embeds at runtime when the precomputed index is missing or was built with a different provider or model. When you update your documentation, regenerate and rebuild or redeploy your site to refresh both the content manifest and index.\n</Callout>\n\n## Use your MCP server\n\nYour users must connect your MCP server to their preferred AI tools.\n\n1. Make your MCP server URL publicly available.\n2. Users copy your MCP server URL and add it to their tools.\n3. Users access your documentation through their tools.\n\nThese are some of the ways you can help your users connect to your MCP server:\n\n<Tabs>\n <TabContent title=\"Claude\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the steps to connect it to Claude.\n 1. Navigate to the [Connectors](https://claude.ai/settings/connectors) page in the Claude settings.\n 2. Select **Add custom connector**.\n 3. Add your MCP server name and URL.\n 4. Select **Add**.\n 5. When using Claude, select the attachments button (the plus icon).\n 6. Select your MCP server.\n </Step>\n </Steps>\n See the [Model Context Protocol documentation](https://modelcontextprotocol.io/docs/tutorials/use-remote-mcp-server#connecting-to-a-remote-mcp-server) for more details.\n </TabContent>\n <TabContent title=\"Claude Code\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the command to connect it to Claude Code.\n ```bash\n claude mcp add --transport http <name> <url>\n ```\n </Step>\n </Steps>\n See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/mcp#installing-mcp-servers) for more details.\n </TabContent>\n <TabContent title=\"Cursor\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the steps to connect it to Cursor.\n 1. Use <kbd>Command</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> on Windows) to open the command palette.\n 2. Search for \"Open MCP settings\".\n 3. Select **Add custom MCP**. This opens the `mcp.json` file.\n 4. In `mcp.json`, configure your server:\n ```json\n {\n \"mcpServers\": {\n \"<your-mcp-server-name>\": {\n \"url\": \"<your-mcp-server-url>\"\n }\n }\n }\n ```\n </Step>\n </Steps>\n See the [Cursor documentation](https://docs.cursor.com/en/context/mcp#installing-mcp-servers) for more details.\n </TabContent>\n <TabContent title=\"VS Code\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the steps to connect it to VS Code.\n 1. Create a `.vscode/mcp.json` file.\n 2. In `mcp.json`, configure your server:\n ```json\n {\n \"servers\": {\n \"<your-mcp-server-name>\": {\n \"type\": \"http\",\n \"url\": \"<your-mcp-server-url>\"\n }\n }\n }\n ```\n </Step>\n </Steps>\n See the [VS Code documentation](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) for more details.\n </TabContent>\n</Tabs>\n\n## Requirements\n\nTo use the MCP server, you need to have the AI Assistant configured. The MCP server uses the same LLM configuration for generating embeddings.\n\n| Variable | Required | Description |\n| -------------- | -------- | ------------------------------------------------------------ |\n| `LLM_PROVIDER` | Yes | Your LLM provider (`openai`, `anthropic`, or `google`) |\n| `DOCS_API_KEY` | No | When set, requires Bearer token authentication on `/api/mcp` |\n\n<Callout type=\"warning\">\n The `search_docs` tool requires an LLM provider for query embeddings. Configure\n the AI Assistant with a valid API key before using semantic search.\n</Callout>\n\nSee the [AI Assistant documentation](/ai-assistant) for configuration details.\n\n## Content indexing\n\nDoccupine builds a `services/mcp/docs-content.json` manifest from your source MDX and generated API-reference pages. The deployed MCP and RAG routes load that traced data file at runtime, so the documentation corpus is not inlined into the server function's JavaScript bundle and the server never scans user-controlled paths.\n\nThe manifest is refreshed after each successful generation. In watch mode, successful MDX and OpenAPI refreshes, including changes to watched local `$ref` files, become available to MCP automatically. If a refresh fails, the manifest continues to contain the last successfully generated corpus. For a one-time workflow, run `doccupine build` or `doccupine generate` before building and deploying the generated Next.js app.\n\n## Troubleshooting\n\n### Index not building\n\nIf the index is not building, check:\n\n- Your LLM provider is configured correctly in your `.env` file\n- You have a valid API key set\n- `services/mcp/docs-content.json` exists in the generated app\n- The latest Doccupine generation completed successfully before deployment\n\n### No search results\n\nIf searches return no results:\n\n- Verify that your source MDX files are inside the configured `watchDir`\n- Regenerate the app so `docs-content.json` contains the latest pages\n- Ensure the index has been built (check the `index.ready` status via GET `/api/mcp`)\n\n### Slow search performance\n\nSearches use the precomputed in-memory index and are fast. The first search is only slow when the app has to embed your docs at runtime, which happens when the precomputed index is missing or was built with a different provider or model. If performance is consistently slow:\n\n- Confirm the build ran the doc-index precompute step (the `build` script runs it before `next build`) with a valid API key\n- Check your embedding API response times\n- Consider reducing the number of documentation pages\n- Verify your server has sufficient memory\n\n### Cloudflare blocking MCP requests\n\nIf you use Cloudflare as a proxy in front of your documentation site, Cloudflare's bot protection may block server-to-server requests from AI tools like Claude.ai. This can cause MCP connections to fail silently or return errors.\n\nThere are two ways to resolve this:\n\n**Option 1: Disable the Cloudflare proxy (simplest)**\n\nIn your Cloudflare DNS settings, click the orange cloud icon next to your domain record to switch it to \"DNS only\" (grey cloud). This disables Cloudflare's proxy and bot protection for your domain, allowing MCP requests to reach your server directly.\n\n**Option 2: Add a Cloudflare WAF exception (keeps your custom domain proxied)**\n\nIn Cloudflare dashboard:\n\n1. Go to **Security > WAF**.\n2. Click **Create rule**.\n3. Set it up as:\n - **Rule name**: Allow MCP API\n - **Field**: URI Path\n - **Operator**: starts with\n - **Value**: `/api/mcp`\n - **Action**: Skip -- then check all remaining custom rules, Rate limiting rules, and Bot Fight Mode / Super Bot Fight Mode.\n4. Deploy the rule and make sure it is ordered first (above other rules).\n\n<Callout type=\"warning\">\n Also check **Security > Bots** in your Cloudflare dashboard. If \"Bot Fight Mode\" or \"Super Bot Fight Mode\" is enabled, that is very likely what is blocking server-to-server requests from AI tools.\n</Callout>\n\n## Best practices\n\n- **Keep content up-to-date**: Rebuild or redeploy your site after updating documentation to regenerate the index with fresh content.\n- **Use descriptive queries**: More specific queries yield better semantic search results.\n- **Monitor index status**: Use the GET endpoint to check if your index is ready before performing searches.\n- **Optimize content structure**: Well-structured markdown with clear headings improves search relevance.";
1
+ export declare const mcpMdxTemplate = "---\ntitle: \"Model Context Protocol\"\ndescription: \"Connect your Doccupine documentation to AI tools with an MCP server for enhanced AI-powered documentation search.\"\ndate: \"2026-02-19\"\nupdated: \"2026-11-15\"\ncategory: \"AI & Integrations\"\ncategoryOrder: 3\norder: 2\n---\n# Model Context Protocol\n\nConnect your documentation to AI tools with a hosted MCP server.\n\nDoccupine automatically generates a Model Context Protocol (MCP) server from your documentation. AI tools like Claude, Cursor, and VS Code connect to it and search your docs directly, so they answer questions about your product with accurate, current information.\n\n## Why use MCP\n\n- **Current answers**: AI tools read your latest docs instead of web search results, which may be stale or incomplete.\n- **Used when relevant**: The AI searches your docs on its own while it answers, whenever the conversation calls for them.\n- **Better matches**: Search finds pages by meaning, not just keywords, without the noise of web search rankings.\n\n## Access your MCP server\n\nYour MCP server is hosted at your documentation URL with the `/api/mcp` path. For example, if your documentation is hosted at `https://example.com`, your MCP server is available at `https://example.com/api/mcp`.\n\n<Callout type=\"note\">\n The `search_docs` tool needs the [AI Assistant](/ai-assistant) to be configured,\n because it searches with the same provider. `get_doc` and `list_docs` work\n without it.\n</Callout>\n\n### Authentication\n\nYou can optionally protect your MCP server with an API key by setting the `DOCS_API_KEY` environment variable in your `.env` file:\n\n```bash\nDOCS_API_KEY=your-secret-key\n```\n\nWhen `DOCS_API_KEY` is set, all requests to `/api/mcp` must include an `Authorization` header with a Bearer token:\n\n```text\nAuthorization: Bearer your-secret-key\n```\n\nRequests without a valid token receive a `401 Unauthorized` response. When `DOCS_API_KEY` is not set, the MCP server follows the site's access mode: it is public on a public site and requires the normal gate session when `SITE_PASSWORD` is configured.\n\n<Callout type=\"note\">\n `DOCS_API_KEY` applies to `/api/mcp` and its `/mcp` discovery alias; it does not grant access to the chat, search, or playground APIs. To gate the entire site behind a shared password, see the [Authentication](/authentication) documentation.\n</Callout>\n\n### Rate limiting\n\nTool calls to `POST /api/mcp` are rate limited. When the limit is exceeded, the server responds with `429 Too Many Requests` and a `Retry-After` header with the number of seconds to wait.\n\nThe built-in limit is lightweight and applies to each running server instance. For a strict limit across all instances, configure rate limiting on your hosting platform.\n\n### API Endpoints\n\n#### GET /api/mcp\n\nReturns information about available tools and the current index status.\n\n**Response:**\n\n```json\n{\n \"tools\": [\n {\n \"name\": \"search_docs\",\n \"description\": \"Search through the documentation content using semantic search...\",\n \"inputSchema\": { ... }\n },\n ...\n ],\n \"index\": {\n \"ready\": true,\n \"chunkCount\": 150\n }\n}\n```\n\n#### POST /api/mcp\n\nExecutes an MCP tool call.\n\n**Request Body:**\n\n```json\n{\n \"tool\": \"search_docs\",\n \"params\": {\n \"query\": \"how to deploy\",\n \"limit\": 6\n }\n}\n```\n\n**Response:**\n\n```json\n{\n \"content\": [\n {\n \"path\": \"app/deployment-and-hosting/page.tsx\",\n \"uri\": \"docs://deployment-and-hosting\",\n \"score\": \"0.892\",\n \"text\": \"Deploy your Doccupine site as a Next.js application...\"\n },\n ...\n ]\n}\n```\n\n## Available Tools\n\nYour MCP server exposes three tools for interacting with your documentation:\n\n### search_docs\n\nSearch through the documentation content using semantic search. Returns relevant chunks of documentation based on the query using vector embeddings and cosine similarity.\n\n**Parameters:**\n\n- `query` (required): The search query to find relevant documentation\n- `limit` (optional): Maximum number of results to return (default: 6)\n- `language` (optional): Language code to search on a site with [languages](/languages); defaults to the site's default language\n- `version` (optional): Version slug to search on a site with [versions](/versions); defaults to the current version\n\n**Example:**\n\n```json\n{\n \"tool\": \"search_docs\",\n \"params\": {\n \"query\": \"how to configure AI assistant\",\n \"limit\": 5\n }\n}\n```\n\n### get_doc\n\nGet the full content of a specific documentation page by its path.\n\n**Parameters:**\n\n- `path` (required): The file path to the documentation page (e.g., `app/getting-started/page.tsx`)\n\n**Example:**\n\n```json\n{\n \"tool\": \"get_doc\",\n \"params\": {\n \"path\": \"app/deployment-and-hosting/page.tsx\"\n }\n}\n```\n\n### list_docs\n\nList all available documentation pages, optionally filtered by directory.\n\n**Parameters:**\n\n- `directory` (optional): Optional directory to filter results (e.g., `components`)\n- `language` (optional): Language code to list on a site with [languages](/languages); defaults to the site's default language\n- `version` (optional): Version slug to list on a site with [versions](/versions); defaults to the current version\n\nResults carry the page's `language` and `version` on such a site, and the `docs://list` resource lists every language and version at once.\n\n**Example:**\n\n```json\n{\n \"tool\": \"list_docs\",\n \"params\": {\n \"directory\": \"configuration\"\n }\n}\n```\n\n## Keep your docs up to date\n\nDoccupine indexes your docs when you build the site, so searches are fast from the first request. After you change your docs, rebuild or redeploy your site so AI tools see the latest content.\n\n## Use your MCP server\n\nYour users must connect your MCP server to their preferred AI tools.\n\n1. Make your MCP server URL publicly available.\n2. Users copy your MCP server URL and add it to their tools.\n3. Users access your documentation through their tools.\n\nThese are some of the ways you can help your users connect to your MCP server:\n\n<Tabs>\n <TabContent title=\"Claude\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the steps to connect it to Claude.\n 1. Navigate to the [Connectors](https://claude.ai/settings/connectors) page in the Claude settings.\n 2. Select **Add custom connector**.\n 3. Add your MCP server name and URL.\n 4. Select **Add**.\n 5. When using Claude, select the attachments button (the plus icon).\n 6. Select your MCP server.\n </Step>\n </Steps>\n See the [Model Context Protocol documentation](https://modelcontextprotocol.io/docs/tutorials/use-remote-mcp-server#connecting-to-a-remote-mcp-server) for more details.\n </TabContent>\n <TabContent title=\"Claude Code\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the command to connect it to Claude Code.\n ```bash\n claude mcp add --transport http <name> <url>\n ```\n </Step>\n </Steps>\n See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/mcp#installing-mcp-servers) for more details.\n </TabContent>\n <TabContent title=\"Cursor\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the steps to connect it to Cursor.\n 1. Use <kbd>Command</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> on Windows) to open the command palette.\n 2. Search for \"Open MCP settings\".\n 3. Select **Add custom MCP**. This opens the `mcp.json` file.\n 4. In `mcp.json`, configure your server:\n ```json\n {\n \"mcpServers\": {\n \"<your-mcp-server-name>\": {\n \"url\": \"<your-mcp-server-url>\"\n }\n }\n }\n ```\n </Step>\n </Steps>\n See the [Cursor documentation](https://docs.cursor.com/en/context/mcp#installing-mcp-servers) for more details.\n </TabContent>\n <TabContent title=\"VS Code\">\n <Steps>\n <Step title=\"Get your MCP server URL.\">\n Your MCP server URL is available at `https://your-domain.com/api/mcp`.\n </Step>\n <Step title=\"Publish your MCP server URL for your users.\">\n Create a guide for your users that includes your MCP server URL and the steps to connect it to VS Code.\n 1. Create a `.vscode/mcp.json` file.\n 2. In `mcp.json`, configure your server:\n ```json\n {\n \"servers\": {\n \"<your-mcp-server-name>\": {\n \"type\": \"http\",\n \"url\": \"<your-mcp-server-url>\"\n }\n }\n }\n ```\n </Step>\n </Steps>\n See the [VS Code documentation](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) for more details.\n </TabContent>\n</Tabs>\n\n## Requirements\n\n| Variable | Required | Description |\n| -------------- | ------------------- | ------------------------------------------------------------ |\n| `LLM_PROVIDER` | For `search_docs` | Your LLM provider (`openai`, `anthropic`, or `google`) |\n| `DOCS_API_KEY` | No | When set, requires Bearer token authentication on `/api/mcp` |\n\nSee the [AI Assistant documentation](/ai-assistant) for configuration details.\n\n## Troubleshooting\n\n### Index not building\n\nIf the index is not building, check:\n\n- Your LLM provider is configured correctly in your `.env` file\n- You have a valid API key set\n- `services/mcp/docs-content.json` exists in the generated app\n- The latest Doccupine generation completed successfully before deployment\n\n### No search results\n\nIf searches return no results:\n\n- Verify that your source MDX files are inside the configured `watchDir`\n- Regenerate the app so `docs-content.json` contains the latest pages\n- Ensure the index has been built (check the `index.ready` status via GET `/api/mcp`)\n\n### Slow search performance\n\nSearches use the precomputed in-memory index and are fast. The first search is only slow when the app has to embed your docs at runtime, which happens when the precomputed index is missing or was built with a different provider or model. If performance is consistently slow:\n\n- Confirm the build ran the doc-index precompute step (the `build` script runs it before `next build`) with a valid API key\n- Check your embedding API response times\n- Consider reducing the number of documentation pages\n- Verify your server has sufficient memory\n\n### Cloudflare blocking MCP requests\n\nIf you use Cloudflare as a proxy in front of your documentation site, Cloudflare's bot protection may block server-to-server requests from AI tools like Claude.ai. This can cause MCP connections to fail silently or return errors.\n\nThere are two ways to resolve this:\n\n**Option 1: Disable the Cloudflare proxy (simplest)**\n\nIn your Cloudflare DNS settings, click the orange cloud icon next to your domain record to switch it to \"DNS only\" (grey cloud). This disables Cloudflare's proxy and bot protection for your domain, allowing MCP requests to reach your server directly.\n\n**Option 2: Add a Cloudflare WAF exception (keeps your custom domain proxied)**\n\nIn Cloudflare dashboard:\n\n1. Go to **Security > WAF**.\n2. Click **Create rule**.\n3. Set it up as:\n - **Rule name**: Allow MCP API\n - **Field**: URI Path\n - **Operator**: starts with\n - **Value**: `/api/mcp`\n - **Action**: Skip -- then check all remaining custom rules, Rate limiting rules, and Bot Fight Mode / Super Bot Fight Mode.\n4. Deploy the rule and make sure it is ordered first (above other rules).\n\n<Callout type=\"warning\">\n Also check **Security > Bots** in your Cloudflare dashboard. If \"Bot Fight Mode\" or \"Super Bot Fight Mode\" is enabled, that is very likely what is blocking server-to-server requests from AI tools.\n</Callout>\n\n## Best practices\n\n- **Use descriptive queries**: More specific queries yield better semantic search results.\n- **Monitor index status**: Use the GET endpoint to check if your index is ready before performing searches.\n- **Optimize content structure**: Well-structured markdown with clear headings improves search relevance.";
@@ -2,7 +2,7 @@ export const mcpMdxTemplate = `---
2
2
  title: "Model Context Protocol"
3
3
  description: "Connect your Doccupine documentation to AI tools with an MCP server for enhanced AI-powered documentation search."
4
4
  date: "2026-02-19"
5
- updated: "2026-07-31"
5
+ updated: "2026-11-15"
6
6
  category: "AI & Integrations"
7
7
  categoryOrder: 3
8
8
  order: 2
@@ -11,42 +11,23 @@ order: 2
11
11
 
12
12
  Connect your documentation to AI tools with a hosted MCP server.
13
13
 
14
- Doccupine automatically generates a Model Context Protocol (MCP) server from your documentation, making your content accessible to AI applications like Claude, Cursor, VS Code, and other MCP-compatible tools. Your MCP server exposes semantic search capabilities, allowing AI tools to query your documentation directly and provide accurate, context-aware answers.
14
+ Doccupine automatically generates a Model Context Protocol (MCP) server from your documentation. AI tools like Claude, Cursor, and VS Code connect to it and search your docs directly, so they answer questions about your product with accurate, current information.
15
15
 
16
- <Callout type="warning">
17
- Semantic \`search_docs\` requires the [AI Assistant](/ai-assistant) embedding
18
- provider to be configured. \`get_doc\` and \`list_docs\` can retrieve the generated
19
- content manifest without an embedding provider.
20
- </Callout>
21
-
22
- ## About MCP servers
23
-
24
- The Model Context Protocol (MCP) is an open protocol that creates standardized connections between AI applications and external services, like documentation. Doccupine generates an MCP server from your documentation, preparing your content for the broader AI ecosystem where any MCP client can connect to your documentation.
25
-
26
- Your MCP server exposes search and retrieval tools for AI applications to query your documentation. Your users must connect your MCP server to their preferred AI tools to access your documentation.
27
-
28
- ### How MCP servers work
29
-
30
- When an AI tool has your documentation MCP server connected, the AI tool can search your documentation directly instead of making a generic web search in response to a user's prompt. Your MCP server provides access to all indexed content from your documentation site.
16
+ ## Why use MCP
31
17
 
32
- - The LLM can proactively search your documentation while generating a response, not just when explicitly asked.
33
- - The LLM determines when to use the search tool based on the context of the conversation and the relevance of your documentation.
34
- - Each tool call happens during the generation process, so the LLM searches up-to-date information from your documentation to generate its response.
35
-
36
- ### MCP compared to web search
37
-
38
- AI tools can search the web, but MCP provides distinct advantages for documentation.
39
-
40
- - **Direct source access**: Web search depends on what search engines have indexed, which may be stale or incomplete. MCP searches your current indexed documentation directly.
41
- - **Integrated workflow**: MCP allows the AI to search during response generation rather than performing a separate web search.
42
- - **Semantic search**: MCP uses vector embeddings for semantic similarity search, providing more relevant results than keyword-based web search.
43
- - **No search noise**: SEO and ranking algorithms influence web search results. MCP goes straight to your documentation content.
18
+ - **Current answers**: AI tools read your latest docs instead of web search results, which may be stale or incomplete.
19
+ - **Used when relevant**: The AI searches your docs on its own while it answers, whenever the conversation calls for them.
20
+ - **Better matches**: Search finds pages by meaning, not just keywords, without the noise of web search rankings.
44
21
 
45
22
  ## Access your MCP server
46
23
 
47
- Doccupine automatically generates an MCP server for your documentation and hosts it at your documentation URL with the \`/api/mcp\` path. For example, if your documentation is hosted at \`https://example.com\`, your MCP server is available at \`https://example.com/api/mcp\`.
24
+ Your MCP server is hosted at your documentation URL with the \`/api/mcp\` path. For example, if your documentation is hosted at \`https://example.com\`, your MCP server is available at \`https://example.com/api/mcp\`.
48
25
 
49
- The MCP server provides both a GET endpoint to discover available tools and a POST endpoint to execute tool calls.
26
+ <Callout type="note">
27
+ The \`search_docs\` tool needs the [AI Assistant](/ai-assistant) to be configured,
28
+ because it searches with the same provider. \`get_doc\` and \`list_docs\` work
29
+ without it.
30
+ </Callout>
50
31
 
51
32
  ### Authentication
52
33
 
@@ -70,11 +51,9 @@ Requests without a valid token receive a \`401 Unauthorized\` response. When \`D
70
51
 
71
52
  ### Rate limiting
72
53
 
73
- Tool calls to \`POST /api/mcp\` are rate limited per client IP when the generated app runs on a recognized platform that supplies a trusted client-address header. Unknown or self-hosted proxy setups use one conservative shared bucket instead of trusting spoofable forwarding headers. When the limit is exceeded, the server responds with \`429 Too Many Requests\` and a \`Retry-After\` header indicating how many seconds to wait before retrying.
74
-
75
- The included limiter is intentionally lightweight and scoped to each running server instance. For a globally consistent limit across multiple serverless instances or regions, or accurate per-client limits behind a custom reverse proxy, configure rate limiting at your trusted hosting edge or use a shared external rate-limit store.
54
+ Tool calls to \`POST /api/mcp\` are rate limited. When the limit is exceeded, the server responds with \`429 Too Many Requests\` and a \`Retry-After\` header with the number of seconds to wait.
76
55
 
77
- Requests are bounded before tool execution: request bodies, protocol batches, tool arguments, search result counts, and serialized responses all have fixed limits. A protocol body may contain at most one \`tools/call\` message, so one rate-limited request cannot execute multiple paid tools; batches containing only non-tool protocol messages remain compatible. Internal provider errors are logged on the server and returned to clients as generic failures so deployment details are not exposed.
56
+ The built-in limit is lightweight and applies to each running server instance. For a strict limit across all instances, configure rate limiting on your hosting platform.
78
57
 
79
58
  ### API Endpoints
80
59
 
@@ -202,31 +181,9 @@ Results carry the page's \`language\` and \`version\` on such a site, and the \`
202
181
  }
203
182
  \`\`\`
204
183
 
205
- ## How it works
206
-
207
- Doccupine's MCP server uses semantic search powered by vector embeddings to provide accurate, context-aware search results.
184
+ ## Keep your docs up to date
208
185
 
209
- ### Indexing Process
210
-
211
- Doccupine runs this pipeline at build time and ships the resulting vectors with your site, so the server loads a ready-made index instead of re-embedding your docs on every cold start.
212
-
213
- 1. **Content Manifest**: During generation, Doccupine writes the source MDX and generated API-reference content to \`services/mcp/docs-content.json\`.
214
- 2. **Runtime Loading**: The build traces that manifest into the MCP and RAG functions, which read it from one fixed path without inlining the corpus into their JavaScript bundles.
215
- 3. **Chunking**: Large documents are split into chunks of approximately 800 characters with 100 character overlap for better context preservation.
216
- 4. **Embedding Generation**: Each chunk is converted to a vector embedding using your configured LLM provider's embedding model.
217
- 5. **Compaction**: Each vector is truncated to \`LLM_EMBEDDING_DIMS\` dimensions (default 512) and quantized to int8, keeping the index roughly 20x smaller than raw floats so large doc sets don't stall the chat on cold start.
218
- 6. **Index Building**: The compact embeddings are written to \`services/mcp/docs-index.json\`, traced into your serverless functions as a data file, and loaded into memory at runtime for fast similarity search.
219
-
220
- ### Search Process
221
-
222
- 1. **Query Embedding**: The search query is converted to a vector embedding using the same embedding model.
223
- 2. **Similarity Calculation**: Cosine similarity is calculated between the query embedding and all document chunk embeddings.
224
- 3. **Ranking**: Results are sorted by similarity score (highest first).
225
- 4. **Response**: The top N results (based on the limit parameter) are returned with their paths, URIs, scores, and text content.
226
-
227
- <Callout type="note">
228
- Embeddings are precomputed at build time and shipped as a traced data file, so the server loads the ready-made index into memory on startup instead of re-embedding your docs on every cold start. It only embeds at runtime when the precomputed index is missing or was built with a different provider or model. When you update your documentation, regenerate and rebuild or redeploy your site to refresh both the content manifest and index.
229
- </Callout>
186
+ Doccupine indexes your docs when you build the site, so searches are fast from the first request. After you change your docs, rebuild or redeploy your site so AI tools see the latest content.
230
187
 
231
188
  ## Use your MCP server
232
189
 
@@ -321,26 +278,13 @@ These are some of the ways you can help your users connect to your MCP server:
321
278
 
322
279
  ## Requirements
323
280
 
324
- To use the MCP server, you need to have the AI Assistant configured. The MCP server uses the same LLM configuration for generating embeddings.
325
-
326
- | Variable | Required | Description |
327
- | -------------- | -------- | ------------------------------------------------------------ |
328
- | \`LLM_PROVIDER\` | Yes | Your LLM provider (\`openai\`, \`anthropic\`, or \`google\`) |
329
- | \`DOCS_API_KEY\` | No | When set, requires Bearer token authentication on \`/api/mcp\` |
330
-
331
- <Callout type="warning">
332
- The \`search_docs\` tool requires an LLM provider for query embeddings. Configure
333
- the AI Assistant with a valid API key before using semantic search.
334
- </Callout>
281
+ | Variable | Required | Description |
282
+ | -------------- | ------------------- | ------------------------------------------------------------ |
283
+ | \`LLM_PROVIDER\` | For \`search_docs\` | Your LLM provider (\`openai\`, \`anthropic\`, or \`google\`) |
284
+ | \`DOCS_API_KEY\` | No | When set, requires Bearer token authentication on \`/api/mcp\` |
335
285
 
336
286
  See the [AI Assistant documentation](/ai-assistant) for configuration details.
337
287
 
338
- ## Content indexing
339
-
340
- Doccupine builds a \`services/mcp/docs-content.json\` manifest from your source MDX and generated API-reference pages. The deployed MCP and RAG routes load that traced data file at runtime, so the documentation corpus is not inlined into the server function's JavaScript bundle and the server never scans user-controlled paths.
341
-
342
- The manifest is refreshed after each successful generation. In watch mode, successful MDX and OpenAPI refreshes, including changes to watched local \`$ref\` files, become available to MCP automatically. If a refresh fails, the manifest continues to contain the last successfully generated corpus. For a one-time workflow, run \`doccupine build\` or \`doccupine generate\` before building and deploying the generated Next.js app.
343
-
344
288
  ## Troubleshooting
345
289
 
346
290
  ### Index not building
@@ -399,7 +343,6 @@ In Cloudflare dashboard:
399
343
 
400
344
  ## Best practices
401
345
 
402
- - **Keep content up-to-date**: Rebuild or redeploy your site after updating documentation to regenerate the index with fresh content.
403
346
  - **Use descriptive queries**: More specific queries yield better semantic search results.
404
347
  - **Monitor index status**: Use the GET endpoint to check if your index is ready before performing searches.
405
348
  - **Optimize content structure**: Well-structured markdown with clear headings improves search relevance.`;
@@ -17,7 +17,7 @@ export const packageJsonTemplate = JSON.stringify({
17
17
  "@langchain/google-genai": "^2.3.6",
18
18
  "@langchain/openai": "^1.8.4",
19
19
  "@mdx-js/react": "^3.1.1",
20
- "@modelcontextprotocol/sdk": "^1.32.2",
20
+ "@modelcontextprotocol/server": "^2.4.0",
21
21
  "beautiful-mermaid": "^1.1.3",
22
22
  "cherry-styled-components": "^0.2.22",
23
23
  langchain: "^1.6.6",
@@ -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 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";
1
+ export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport {\n McpServer,\n ResourceNotFoundError,\n ResourceTemplate,\n} from \"@modelcontextprotocol/server\";\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 // The docs are fixed for the life of a deployment, so the tool and resource\n // lists never change and there is nothing to notify clients about.\n const server = new McpServer(\n { name: \"docs-server\", version: \"1.0.0\" },\n {\n capabilities: {\n tools: { listChanged: false },\n resources: { listChanged: false },\n },\n },\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 }, ctx) => {\n const { signal } = ctx.mcpReq;\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 }, ctx) => {\n const { signal } = ctx.mcpReq;\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 }, ctx) => {\n const { signal } = ctx.mcpReq;\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, ctx) => {\n const { signal } = ctx.mcpReq;\n signal.throwIfAborted();\n const doc = await getDoc({ path: uri.href });\n signal.throwIfAborted();\n if (!doc) {\n throw new ResourceNotFoundError(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";
@@ -2,8 +2,9 @@ export const mcpServerTemplate = `import path from "node:path";
2
2
  import fs from "node:fs";
3
3
  import {
4
4
  McpServer,
5
+ ResourceNotFoundError,
5
6
  ResourceTemplate,
6
- } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ } from "@modelcontextprotocol/server";
7
8
  import { z } from "zod";
8
9
  import {
9
10
  listAllDocs,
@@ -439,10 +440,17 @@ export function getIndexStatus(): {
439
440
  * Create and configure the MCP server with documentation tools
440
441
  */
441
442
  export function createMCPServer(): McpServer {
442
- const server = new McpServer({
443
- name: "docs-server",
444
- version: "1.0.0",
445
- });
443
+ // The docs are fixed for the life of a deployment, so the tool and resource
444
+ // lists never change and there is nothing to notify clients about.
445
+ const server = new McpServer(
446
+ { name: "docs-server", version: "1.0.0" },
447
+ {
448
+ capabilities: {
449
+ tools: { listChanged: false },
450
+ resources: { listChanged: false },
451
+ },
452
+ },
453
+ );
446
454
 
447
455
  // Register the search_docs tool
448
456
  server.registerTool(
@@ -451,7 +459,8 @@ export function createMCPServer(): McpServer {
451
459
  description: DOCS_TOOLS[0].description,
452
460
  inputSchema: searchDocsArgsSchema,
453
461
  },
454
- async ({ query, limit, language, version }, { signal }) => {
462
+ async ({ query, limit, language, version }, ctx) => {
463
+ const { signal } = ctx.mcpReq;
455
464
  const results = await searchDocs(
456
465
  query,
457
466
  limit ?? 6,
@@ -477,7 +486,8 @@ export function createMCPServer(): McpServer {
477
486
  description: DOCS_TOOLS[1].description,
478
487
  inputSchema: getDocArgsSchema,
479
488
  },
480
- async ({ path }, { signal }) => {
489
+ async ({ path }, ctx) => {
490
+ const { signal } = ctx.mcpReq;
481
491
  signal.throwIfAborted();
482
492
  const doc = await getDoc({ path });
483
493
  signal.throwIfAborted();
@@ -495,7 +505,8 @@ export function createMCPServer(): McpServer {
495
505
  description: DOCS_TOOLS[2].description,
496
506
  inputSchema: listDocsArgsSchema,
497
507
  },
498
- async ({ directory, language, version }, { signal }) => {
508
+ async ({ directory, language, version }, ctx) => {
509
+ const { signal } = ctx.mcpReq;
499
510
  signal.throwIfAborted();
500
511
  const docs = await listDocs({ directory, language, version });
501
512
  signal.throwIfAborted();
@@ -555,12 +566,13 @@ export function createMCPServer(): McpServer {
555
566
  "The Markdown content of one documentation page, addressed by the docs:// URI from the docs://list index",
556
567
  mimeType: "text/markdown",
557
568
  },
558
- async (uri, _variables, { signal }) => {
569
+ async (uri, _variables, ctx) => {
570
+ const { signal } = ctx.mcpReq;
559
571
  signal.throwIfAborted();
560
572
  const doc = await getDoc({ path: uri.href });
561
573
  signal.throwIfAborted();
562
574
  if (!doc) {
563
- throw new Error(\`Document not found: \${uri.href}\`);
575
+ throw new ResourceNotFoundError(uri.href);
564
576
  }
565
577
  return {
566
578
  contents: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doccupine",
3
- "version": "0.0.162",
3
+ "version": "0.0.164",
4
4
  "description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -56,6 +56,8 @@
56
56
  },
57
57
  "devDependencies": {
58
58
  "@langchain/core": "^1.4.1",
59
+ "@modelcontextprotocol/client": "^2.4.0",
60
+ "@modelcontextprotocol/sdk": "^1.32.2",
59
61
  "@types/fs-extra": "^11.0.4",
60
62
  "@types/node": "^26.6.6",
61
63
  "@types/prompts": "^2.4.9",