doccupine 0.0.143 → 0.0.145
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 +1 -1
- package/dist/cli.d.ts +6 -0
- package/dist/cli.js +130 -22
- package/dist/generator/api-reference-generator.d.ts +22 -0
- package/dist/generator/api-reference-generator.js +96 -0
- package/dist/generator/app-scaffolder.d.ts +18 -0
- package/dist/generator/app-scaffolder.js +49 -0
- package/dist/generator/generated-route-manager.d.ts +18 -0
- package/dist/generator/generated-route-manager.js +114 -0
- package/dist/generator/page-catalog.d.ts +21 -0
- package/dist/generator/page-catalog.js +75 -0
- package/dist/generator/page-renderer.d.ts +31 -0
- package/dist/generator/page-renderer.js +248 -0
- package/dist/generator/project-config-repository.d.ts +33 -0
- package/dist/generator/project-config-repository.js +191 -0
- package/dist/generator/public-asset-manager.d.ts +20 -0
- package/dist/generator/public-asset-manager.js +225 -0
- package/dist/generator/section-resolver.d.ts +13 -0
- package/dist/generator/section-resolver.js +150 -0
- package/dist/generator/secure-source-fs.d.ts +31 -0
- package/dist/generator/secure-source-fs.js +470 -0
- package/dist/generator/site-artifacts.d.ts +23 -0
- package/dist/generator/site-artifacts.js +156 -0
- package/dist/generator/watch-coordinator.d.ts +58 -0
- package/dist/generator/watch-coordinator.js +456 -0
- package/dist/lib/config-manager.d.ts +1 -0
- package/dist/lib/config-manager.js +194 -12
- package/dist/lib/generated-artifacts.d.ts +11 -2
- package/dist/lib/generated-artifacts.js +52 -7
- package/dist/lib/layout.d.ts +1 -17
- package/dist/lib/layout.js +5 -4
- package/dist/lib/openapi.d.ts +4 -0
- package/dist/lib/openapi.js +36 -4
- package/dist/lib/project-config.d.ts +3 -0
- package/dist/lib/project-config.js +110 -0
- package/dist/lib/types.d.ts +14 -1
- package/dist/mdx-to-nextjs-generator.d.ts +50 -34
- package/dist/mdx-to-nextjs-generator.js +760 -1740
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +2 -1
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +2 -1
- package/dist/templates/components/layout/Accordion.d.ts +1 -1
- package/dist/templates/components/layout/Accordion.js +2 -3
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/api-playground.mdx.js +11 -2
- package/dist/templates/mdx/commands.mdx.d.ts +1 -1
- package/dist/templates/mdx/commands.mdx.js +26 -1
- package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
- package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
- package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
- package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
- package/dist/templates/mdx/space.mdx.d.ts +1 -1
- package/dist/templates/mdx/space.mdx.js +1 -5
- package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
- package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
- package/dist/templates/next.config.js +2 -2
- package/dist/templates/package.js +3 -3
- package/dist/templates/proxy.js +1 -1
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +2 -12
- package/package.json +3 -3
|
@@ -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\"\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\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\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 whenever the CLI generates the site. In watch mode, saved MDX and OpenAPI changes become available to MCP automatically. 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-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\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\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.";
|
|
@@ -2,6 +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
6
|
category: "AI & Integrations"
|
|
6
7
|
categoryOrder: 3
|
|
7
8
|
order: 2
|
|
@@ -332,7 +333,7 @@ See the [AI Assistant documentation](/ai-assistant) for configuration details.
|
|
|
332
333
|
|
|
333
334
|
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.
|
|
334
335
|
|
|
335
|
-
The manifest is refreshed
|
|
336
|
+
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.
|
|
336
337
|
|
|
337
338
|
## Troubleshooting
|
|
338
339
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformApiPlaygroundMdxTemplate = "---\ntitle: \"API Playground\"\ndescription: \"Register an OpenAPI spec and turn it into an interactive API reference with a live request playground.\"\ndate: \"2026-07-26\"\nupdated: \"2026-07-
|
|
1
|
+
export declare const platformApiPlaygroundMdxTemplate = "---\ntitle: \"API Playground\"\ndescription: \"Register an OpenAPI spec and turn it into an interactive API reference with a live request playground.\"\ndate: \"2026-07-26\"\nupdated: \"2026-07-31\"\ncategory: \"AI & Integrations\"\ncategoryOrder: 3\norder: 2\nsection: \"Platform\"\n---\n# API Playground\n\nThe API Playground settings page turns an OpenAPI spec in your repository into an interactive API reference. Any page can embed a live \"try it\" playground for a single endpoint, and you can generate a full reference with one page per operation.\n\n## Registering a spec\n\nOpen the **API Playground** settings page and choose your OpenAPI file with the **OpenAPI spec file** picker. It searches your repository for YAML and JSON files - start typing to filter, or type a path to use one that is not listed yet. The path is stored, relative to `doccupine.json`, as the `openapi` field:\n\n```json\n{\n \"openapi\": \"openapi.yaml\"\n}\n```\n\nPress **Save Configuration**, then commit the change. Both YAML and JSON specs (OpenAPI 3.0 and 3.1) are supported.\n\n> For multiple specs, edit the `openapi` array in `doccupine.json` directly - the settings page manages a single spec.\n\n<Callout type=\"warning\">\n The root spec and every local `$ref` dependency must exist in the repository after publishing. References must stay beneath the directory containing the root spec, use `.json`, `.yaml`, or `.yml`, and cannot target remote URLs, dotfiles, or dot-directories. Publish the configuration, root spec, and all referenced files together. Doccupine [checks this before publishing](/platform/publishing) rather than letting the deploy fail.\n</Callout>\n\n## Embedding a playground on a page\n\nAdd an `openapi` field to any page's frontmatter to render the interactive playground for that operation above the page content. The value is either `\"METHOD /path\"` or an `operationId`:\n\n```mdx\n---\ntitle: \"Create a post\"\nopenapi: \"POST /posts\"\n---\n\nPosts are created for a user. The playground above is live - fill in the fields and press **Send**.\n```\n\nThe playground resolves the operation from your configured spec, so its parameters, request body, and responses always match the source of truth.\n\n## Generating an API reference\n\nPress **Generate API pages** to create one page per operation from your spec. Each generated page:\n\n- carries an `openapi:` frontmatter reference, so it renders the live playground,\n- is placed under an **API Reference** section, grouped by tag,\n- documents every parameter, the request body, and each response,\n- is staged as a pending change for you to review and commit.\n\nAlongside them you get an **API Reference** landing page at the section root, listing every endpoint as a card with its method and path. It is a normal page like any other, so you can edit it, add an introduction, or delete it if you would rather write your own.\n\nGeneration reads the committed spec, so save and commit your configuration first. Endpoints are shown with a colored HTTP-method badge so they are easy to scan in the file list.\n\n## Sending requests\n\nInside the playground, **Try it** opens the request editor. Fill in parameters, authentication, and the body, then press **Send**:\n\n- **Proxy** mode runs the request from the server, so endpoints that block cross-origin browser calls still work. Requests are restricted to the servers declared in your spec.\n- **Direct** mode calls the API straight from the browser.\n\nSecrets you enter are never logged, and appear as `<YOUR_CREDENTIALS>` in the generated code snippets unless you choose to reveal them.\n";
|
|
@@ -2,7 +2,7 @@ export const platformApiPlaygroundMdxTemplate = `---
|
|
|
2
2
|
title: "API Playground"
|
|
3
3
|
description: "Register an OpenAPI spec and turn it into an interactive API reference with a live request playground."
|
|
4
4
|
date: "2026-07-26"
|
|
5
|
-
updated: "2026-07-
|
|
5
|
+
updated: "2026-07-31"
|
|
6
6
|
category: "AI & Integrations"
|
|
7
7
|
categoryOrder: 3
|
|
8
8
|
order: 2
|
|
@@ -27,7 +27,7 @@ Press **Save Configuration**, then commit the change. Both YAML and JSON specs (
|
|
|
27
27
|
> For multiple specs, edit the \`openapi\` array in \`doccupine.json\` directly - the settings page manages a single spec.
|
|
28
28
|
|
|
29
29
|
<Callout type="warning">
|
|
30
|
-
The spec
|
|
30
|
+
The root spec and every local \`$ref\` dependency must exist in the repository after publishing. References must stay beneath the directory containing the root spec, use \`.json\`, \`.yaml\`, or \`.yml\`, and cannot target remote URLs, dotfiles, or dot-directories. Publish the configuration, root spec, and all referenced files together. Doccupine [checks this before publishing](/platform/publishing) rather than letting the deploy fail.
|
|
31
31
|
</Callout>
|
|
32
32
|
|
|
33
33
|
## Embedding a playground on a page
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformPublishingMdxTemplate = "---\ntitle: \"Publishing Changes\"\ndescription: \"Commit your edits to GitHub and deploy your documentation site with one click.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-
|
|
1
|
+
export declare const platformPublishingMdxTemplate = "---\ntitle: \"Publishing Changes\"\ndescription: \"Commit your edits to GitHub and deploy your documentation site with one click.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-31\"\ncategory: \"Editing\"\ncategoryOrder: 1\norder: 1\nsection: \"Platform\"\n---\n# Publishing Changes\n\nWhen you edit files in Doccupine, your changes are staged as pending. Nothing goes live until you explicitly publish.\n\n## The publish workflow\n\n1. Make edits to your files using the file editor.\n2. Click the **Publish** button in the project header. It appears as soon as anything is staged, with a badge showing the number of pending changes.\n3. Review the change set in the publish modal. Each file expands into a diff of what you actually changed, line by line, against what is currently in your repository.\n4. Optionally tick **Custom commit message** and write your own. Without one, the message is built from the files you are committing, like `Update docs/guide.mdx`.\n5. Click **Deploy**.\n\nDoccupine then:\n\n- Commits all pending changes to your GitHub repository\n- Triggers a new deployment\n- Clears all pending changes from the staging area\n\n<Callout type=\"note\">\n The deployment status badge next to the project name updates as your site builds. It cycles through **Queued**, **Building**, and **Ready** (or **Error** if something went wrong).\n</Callout>\n\n## Checks before a publish\n\nA few kinds of mistake do not break one page, they stop the whole site from building. Doccupine checks for those before committing anything and refuses the publish with a message naming the file to fix, so you find out in the publish modal instead of in a failed deploy.\n\n### An OpenAPI source that will not be there\n\nIf `doccupine.json` names an OpenAPI spec, the root document and every recursively referenced local file must exist after the publish. Publish all of those files with the configuration change. Moving or deleting any document in the reference graph requires updating the relevant `$ref` or `openapi` path in the same change set.\n\n### Two pages on the same URL\n\nTwo files that resolve to the same route - `guide.mdx` and `guide/index.mdx`, for instance - are a duplicate page, and the build stops rather than guessing which one you meant. Rename or delete one of them.\n\n### Section names that become the same URL\n\nSection URLs come from section names, so \"API Reference\" and \"api-reference\" both become `/api-reference`. Pick one spelling and use it in the `section` field of both pages.\n\n<Callout type=\"note\">\n These checks look at the repository as it will be **after** your publish, so a file you are deleting in the same change set counts as gone. If a check cannot run - GitHub is unreachable, say - the publish goes ahead and the build remains the backstop.\n</Callout>\n\n## Discarding changes\n\nYou can throw away as much or as little as you like:\n\n- **A single line** - **Discard this line** on that line of the diff. The rest of the file stays staged. Line numbers do not drift as you go, so you can pick off several in a row. A deleted file has no lines to pick from, and a diff too large to show in full does not offer the control.\n- **A whole file** - **Discard this file's change** on its row in the change set returns the file to whatever is in your repository.\n- **Everything** - **Discard all**, above the change set, clears the staging area without committing anything.\n\nIf discarding leaves a file identical to what is already committed, it drops out of the change set on its own.\n\n<Callout type=\"note\">\n Discarding a line here counts as a hand edit, exactly like editing the page in the editor would. That matters if the page is tracked by [Agent Sync](/platform/self-updating-docs): a page you have touched by hand is always routed to review rather than being rewritten automatically.\n</Callout>\n\n## File status badges\n\nIn the publish modal, every row in the change set carries a badge for what happened to the file, alongside a count of the lines added and removed:\n\n- **created** - the file is new\n- **updated** - the file already exists and was edited\n- **deleted** - the file is being removed\n\nIf the diffs cannot be loaded, the modal falls back to a plain file list whose badges read **mod**, **del**, or **bin** - the last for a binary asset such as an image or a font, which has no text diff to show.\n\n## Auto-deploy from GitHub\n\nIf you're using a user-connected GitHub repository and push changes directly (outside of Doccupine), the webhook triggers an automatic redeploy. This means you can use Doccupine's editor and Git-based workflows interchangeably.";
|
|
@@ -2,7 +2,7 @@ export const platformPublishingMdxTemplate = `---
|
|
|
2
2
|
title: "Publishing Changes"
|
|
3
3
|
description: "Commit your edits to GitHub and deploy your documentation site with one click."
|
|
4
4
|
date: "2026-02-19"
|
|
5
|
-
updated: "2026-07-
|
|
5
|
+
updated: "2026-07-31"
|
|
6
6
|
category: "Editing"
|
|
7
7
|
categoryOrder: 1
|
|
8
8
|
order: 1
|
|
@@ -34,9 +34,9 @@ Doccupine then:
|
|
|
34
34
|
|
|
35
35
|
A few kinds of mistake do not break one page, they stop the whole site from building. Doccupine checks for those before committing anything and refuses the publish with a message naming the file to fix, so you find out in the publish modal instead of in a failed deploy.
|
|
36
36
|
|
|
37
|
-
###
|
|
37
|
+
### An OpenAPI source that will not be there
|
|
38
38
|
|
|
39
|
-
If
|
|
39
|
+
If \`doccupine.json\` names an OpenAPI spec, the root document and every recursively referenced local file must exist after the publish. Publish all of those files with the configuration change. Moving or deleting any document in the reference graph requires updating the relevant \`$ref\` or \`openapi\` path in the same change set.
|
|
40
40
|
|
|
41
41
|
### Two pages on the same URL
|
|
42
42
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const spaceMdxTemplate = "---\ntitle: \"Space\"\ndescription: \"Add a precise vertical or horizontal gap between blocks, with per-breakpoint control.\"\ndate: \"2026-07-30\"\ncategory: \"Components\"\ncategoryOrder: 1\norder: 24\n---\n# Space\n\nInsert a fixed gap between two blocks.\n\nMarkdown already spaces paragraphs, headings, lists, and tables for you, and that default rhythm is the right choice almost everywhere. Reach for `Space` when you need a specific gap the defaults do not give you: separating a dense table from the heading that follows it, opening up a landing page, or tightening a stack of cards on small screens.\n\n<Callout type=\"note\">\n If you find yourself adding a `Space` after every section, the page is telling you it wants a different structure - try `Steps`, `Columns`, or a heading instead.\n</Callout>\n\n## Space Usage\n\nSet `size` to the gap you want, in pixels.\n\n```html\nText above the gap.\n\n<Space size={60} />\n\nText below the gap.\n```\n\nText above the gap.\n\n<Space size={60} />\n\nText below the gap.\n\n## Responsive sizing\n\nA gap that looks right on a wide screen is often too large on a phone. Each breakpoint has its own prop, so you can grow the gap as the viewport widens.\n\n```html\n<Space size={20} md={40} xl={80} />\n```\n\nThat renders a 20px gap by default, 40px from the `md` breakpoint up, and 80px from `xl` up.\n\nEvery breakpoint prop is a `min-width` media query, so a value applies at that width and every width above it until a larger breakpoint overrides it:\n\n| Prop | Applies from |\n| ------ | ------------ |\n| `xs` | 0px |\n| `sm` | 576px |\n| `md` | 768px |\n| `lg` | 992px |\n| `xl` | 1200px |\n| `xxl` | 1440px |\n| `xxxl` | 1920px |\n\n`size` sets the gap at every width. Use it alone for a constant gap, or as the base that the breakpoint props build on.\n\n## Removing the space at a breakpoint\n\nPass `\"none\"` instead of a number to drop the gap entirely at that width. This is the usual way to add breathing room on desktop without wasting vertical space on a phone.\n\n```html\n<Space size=\"none\" lg={64} />\n```\n\nHere there is no gap at all below the `lg` breakpoint, and a 64px gap from `lg` up.\n\n## Horizontal spacing\n\nAdd `horizontal` to space things apart along the inline axis instead of the block axis. The size props then control width rather than height.\n\nIt belongs inside a line of inline content, where a gap along that axis has something to sit between. Dropping one into a button widens the distance between the label and the icon by the size you give it, on top of the spacing the button already applies:\n\n```html\n<Button icon=\"arrow-right\" iconPosition=\"right\">\n Get started\n <Space size={24} horizontal />\n</Button>\n```\n\n<Button icon=\"arrow-right\" iconPosition=\"right\">\n Get started\n <Space size={24} horizontal />\n</Button>\n\n## Properties\n\n<Field value=\"size\" type=\"number | 'none'\">\n The gap at every viewport width, in pixels. Pass `\"none\"` to render nothing.\n</Field>\n\n<Field value=\"xs\" type=\"number | 'none'\">\n Overrides the gap from 0px up.\n</Field>\n\n<Field value=\"sm\" type=\"number | 'none'\">\n Overrides the gap from 576px up.\n</Field>\n\n<Field value=\"md\" type=\"number | 'none'\">\n Overrides the gap from 768px up.\n</Field>\n\n<Field value=\"lg\" type=\"number | 'none'\">\n Overrides the gap from 992px up.\n</Field>\n\n<Field value=\"xl\" type=\"number | 'none'\">\n Overrides the gap from 1200px up.\n</Field>\n\n<Field value=\"xxl\" type=\"number | 'none'\">\n Overrides the gap from 1440px up.\n</Field>\n\n<Field value=\"xxxl\" type=\"number | 'none'\">\n Overrides the gap from 1920px up.\n</Field>\n\n<Field value=\"horizontal\" type=\"boolean\">\n Spaces along the inline axis instead of the block axis, so the size props control width. Defaults to false.\n</Field
|
|
1
|
+
export declare const spaceMdxTemplate = "---\ntitle: \"Space\"\ndescription: \"Add a precise vertical or horizontal gap between blocks, with per-breakpoint control.\"\ndate: \"2026-07-30\"\ncategory: \"Components\"\ncategoryOrder: 1\norder: 24\n---\n# Space\n\nInsert a fixed gap between two blocks.\n\nMarkdown already spaces paragraphs, headings, lists, and tables for you, and that default rhythm is the right choice almost everywhere. Reach for `Space` when you need a specific gap the defaults do not give you: separating a dense table from the heading that follows it, opening up a landing page, or tightening a stack of cards on small screens.\n\n<Callout type=\"note\">\n If you find yourself adding a `Space` after every section, the page is telling you it wants a different structure - try `Steps`, `Columns`, or a heading instead.\n</Callout>\n\n## Space Usage\n\nSet `size` to the gap you want, in pixels.\n\n```html\nText above the gap.\n\n<Space size={60} />\n\nText below the gap.\n```\n\nText above the gap.\n\n<Space size={60} />\n\nText below the gap.\n\n## Responsive sizing\n\nA gap that looks right on a wide screen is often too large on a phone. Each breakpoint has its own prop, so you can grow the gap as the viewport widens.\n\n```html\n<Space size={20} md={40} xl={80} />\n```\n\nThat renders a 20px gap by default, 40px from the `md` breakpoint up, and 80px from `xl` up.\n\nEvery breakpoint prop is a `min-width` media query, so a value applies at that width and every width above it until a larger breakpoint overrides it:\n\n| Prop | Applies from |\n| ------ | ------------ |\n| `xs` | 0px |\n| `sm` | 576px |\n| `md` | 768px |\n| `lg` | 992px |\n| `xl` | 1200px |\n| `xxl` | 1440px |\n| `xxxl` | 1920px |\n\n`size` sets the gap at every width. Use it alone for a constant gap, or as the base that the breakpoint props build on.\n\n## Removing the space at a breakpoint\n\nPass `\"none\"` instead of a number to drop the gap entirely at that width. This is the usual way to add breathing room on desktop without wasting vertical space on a phone.\n\n```html\n<Space size=\"none\" lg={64} />\n```\n\nHere there is no gap at all below the `lg` breakpoint, and a 64px gap from `lg` up.\n\n## Horizontal spacing\n\nAdd `horizontal` to space things apart along the inline axis instead of the block axis. The size props then control width rather than height.\n\nIt belongs inside a line of inline content, where a gap along that axis has something to sit between. Dropping one into a button widens the distance between the label and the icon by the size you give it, on top of the spacing the button already applies:\n\n```html\n<Button icon=\"arrow-right\" iconPosition=\"right\">\n Get started\n <Space size={24} horizontal />\n</Button>\n```\n\n<Button icon=\"arrow-right\" iconPosition=\"right\">\n Get started\n <Space size={24} horizontal />\n</Button>\n\n## Properties\n\n<Field value=\"size\" type=\"number | 'none'\">\n The gap at every viewport width, in pixels. Pass `\"none\"` to render nothing.\n</Field>\n\n<Field value=\"xs\" type=\"number | 'none'\">\n Overrides the gap from 0px up.\n</Field>\n\n<Field value=\"sm\" type=\"number | 'none'\">\n Overrides the gap from 576px up.\n</Field>\n\n<Field value=\"md\" type=\"number | 'none'\">\n Overrides the gap from 768px up.\n</Field>\n\n<Field value=\"lg\" type=\"number | 'none'\">\n Overrides the gap from 992px up.\n</Field>\n\n<Field value=\"xl\" type=\"number | 'none'\">\n Overrides the gap from 1200px up.\n</Field>\n\n<Field value=\"xxl\" type=\"number | 'none'\">\n Overrides the gap from 1440px up.\n</Field>\n\n<Field value=\"xxxl\" type=\"number | 'none'\">\n Overrides the gap from 1920px up.\n</Field>\n\n<Field value=\"horizontal\" type=\"boolean\">\n Spaces along the inline axis instead of the block axis, so the size props control width. Defaults to false.\n</Field>";
|
|
@@ -122,8 +122,4 @@ It belongs inside a line of inline content, where a gap along that axis has some
|
|
|
122
122
|
|
|
123
123
|
<Field value="horizontal" type="boolean">
|
|
124
124
|
Spaces along the inline axis instead of the block axis, so the size props control width. Defaults to false.
|
|
125
|
-
</Field
|
|
126
|
-
|
|
127
|
-
<Callout type="note">
|
|
128
|
-
Pages written before these names existed pass the same props with a \`$\` prefix (\`$size\`, \`$md\`, \`$horizontal\`). Those still render, so nothing breaks on upgrade, but the unprefixed names above are the supported form - the \`$\` prefix belongs to the styling library underneath, not to the components you author with.
|
|
129
|
-
</Callout>`;
|
|
125
|
+
</Field>`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const whatIsDoccupineMdxTemplate = "---\ntitle: \"What is Doccupine\"\ndescription: \"Doccupine is a CLI that turns a directory of MDX files into a complete, production-ready documentation website - no frontend work required.\"\ndate: \"2026-02-19\"\ncategory: \"Getting Started\"\ncategoryOrder: 0\norder: 1\n---\n# What is Doccupine\n\n**Doccupine** is a CLI tool that turns a directory of MDX files into a complete Next.js documentation website. It is less of a framework you assemble and more of a tool that does the assembling for you - you bring the content, Doccupine builds the site.\n\n```bash\nnpx doccupine\n```\n\n## Philosophy\n\nDoccupine was built on a simple belief: writing documentation should feel like writing, not like building a web app. Most docs frameworks hand you a pile of libraries and configuration and expect you to wire up rendering, navigation, theming, and search yourself. Doccupine makes those decisions for you and gets out of the way, so the only thing left to do is write.\n\n## Content first\n\nYou write standard Markdown and MDX. No React, no build configuration, no component wiring. Your navigation, theming, and search are all derived from your files and a handful of JSON config files. If you can write a Markdown file, you can ship a documentation site.\n\n## Batteries included\n\nEverything you expect from a great docs site works the moment you run the command - MDX rendering, an auto-generated sidebar, dark and light themes, 14+ built-in components, full-text search, an AI chat assistant, and an MCP server. Nothing to install, nothing to opt into.\n\n<Callout type=\"info\">\n Every element on this page - this callout, the cards below, the code block above - is a live example of what your docs get out of the box, with zero setup.\n</Callout>\n\n## You
|
|
1
|
+
export declare const whatIsDoccupineMdxTemplate = "---\ntitle: \"What is Doccupine\"\ndescription: \"Doccupine is a CLI that turns a directory of MDX files into a complete, production-ready documentation website - no frontend work required.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-31\"\ncategory: \"Getting Started\"\ncategoryOrder: 0\norder: 1\n---\n# What is Doccupine\n\n**Doccupine** is a CLI tool that turns a directory of MDX files into a complete Next.js documentation website. It is less of a framework you assemble and more of a tool that does the assembling for you - you bring the content, Doccupine builds the site.\n\n```bash\nnpx doccupine\n```\n\n## Philosophy\n\nDoccupine was built on a simple belief: writing documentation should feel like writing, not like building a web app. Most docs frameworks hand you a pile of libraries and configuration and expect you to wire up rendering, navigation, theming, and search yourself. Doccupine makes those decisions for you and gets out of the way, so the only thing left to do is write.\n\n## Content first\n\nYou write standard Markdown and MDX. No React, no build configuration, no component wiring. Your navigation, theming, and search are all derived from your files and a handful of JSON config files. If you can write a Markdown file, you can ship a documentation site.\n\n## Batteries included\n\nEverything you expect from a great docs site works the moment you run the command - MDX rendering, an auto-generated sidebar, dark and light themes, 14+ built-in components, full-text search, an AI chat assistant, and an MCP server. Nothing to install, nothing to opt into.\n\n<Callout type=\"info\">\n Every element on this page - this callout, the cards below, the code block above - is a live example of what your docs get out of the box, with zero setup.\n</Callout>\n\n## You control the output\n\nDoccupine generates a real Next.js 16 app that you can inspect, deploy anywhere, or fork into a separately maintained application. While you continue using Doccupine, its registered output paths remain generator-managed: every fresh run recreates `app` and may rewrite generated components, services, configuration, and manifests.\n\nKeep durable customizations in MDX, project-root JSON configuration, and `public`. If you want to modify the generated implementation directly, fork the app or stop regenerating it first.\n\n## Instant feedback\n\nRun `npx doccupine` to watch MDX, supported project-root configuration, public assets, and configured OpenAPI sources. Doccupine reconciles edits made during startup and keeps the last successful site when a watch refresh fails.\n\nFiles such as `theme.json`, `navigation.json`, `sections.json`, `fonts.json`, and `analytics.json` update live. Within `doccupine.json`, the `openapi` field updates live, while `watchDir`, `outputDir`, `port`, and `packageManager` require a restart.\n\n## AI-native\n\nDocumentation is not only read by people anymore. Doccupine ships a RAG-powered chat assistant so readers can ask questions in natural language, and an MCP server so AI tools and agents can search your documentation directly. Your content is ready for both audiences from day one.\n\n## Opinionated, on purpose\n\nDoccupine makes the boring decisions - layout, typography, color, navigation structure - so you can spend your time on the words that matter. When you are ready to customize, simple JSON files let you adjust site metadata, navigation, theme, and fonts without touching a line of code.\n\n## When to use Doccupine\n\nDoccupine is built for anyone who needs a polished documentation site without becoming a frontend engineer.\n\n- Product and API documentation\n- Developer guides and tutorials\n- Internal knowledge bases and runbooks\n- Design systems and component references\n\nThere are two ways to run it:\n\n<Columns cols={2}>\n <Card title=\"Local CLI\" icon=\"terminal\" href=\"/\">\n `npx doccupine` scaffolds and serves the site on your machine, and you self-host the generated Next.js app anywhere.\n </Card>\n <Card title=\"Doccupine Platform\" icon=\"cloud\" href=\"/platform\">\n A managed, browser-based experience with a visual editor, one-click publishing, custom domains, and team collaboration - no local setup.\n </Card>\n</Columns>";
|
|
@@ -2,6 +2,7 @@ export const whatIsDoccupineMdxTemplate = `---
|
|
|
2
2
|
title: "What is Doccupine"
|
|
3
3
|
description: "Doccupine is a CLI that turns a directory of MDX files into a complete, production-ready documentation website - no frontend work required."
|
|
4
4
|
date: "2026-02-19"
|
|
5
|
+
updated: "2026-07-31"
|
|
5
6
|
category: "Getting Started"
|
|
6
7
|
categoryOrder: 0
|
|
7
8
|
order: 1
|
|
@@ -30,13 +31,17 @@ Everything you expect from a great docs site works the moment you run the comman
|
|
|
30
31
|
Every element on this page - this callout, the cards below, the code block above - is a live example of what your docs get out of the box, with zero setup.
|
|
31
32
|
</Callout>
|
|
32
33
|
|
|
33
|
-
## You
|
|
34
|
+
## You control the output
|
|
34
35
|
|
|
35
|
-
Doccupine generates a real Next.js 16 app
|
|
36
|
+
Doccupine generates a real Next.js 16 app that you can inspect, deploy anywhere, or fork into a separately maintained application. While you continue using Doccupine, its registered output paths remain generator-managed: every fresh run recreates \`app\` and may rewrite generated components, services, configuration, and manifests.
|
|
37
|
+
|
|
38
|
+
Keep durable customizations in MDX, project-root JSON configuration, and \`public\`. If you want to modify the generated implementation directly, fork the app or stop regenerating it first.
|
|
36
39
|
|
|
37
40
|
## Instant feedback
|
|
38
41
|
|
|
39
|
-
Run \`npx doccupine\`
|
|
42
|
+
Run \`npx doccupine\` to watch MDX, supported project-root configuration, public assets, and configured OpenAPI sources. Doccupine reconciles edits made during startup and keeps the last successful site when a watch refresh fails.
|
|
43
|
+
|
|
44
|
+
Files such as \`theme.json\`, \`navigation.json\`, \`sections.json\`, \`fonts.json\`, and \`analytics.json\` update live. Within \`doccupine.json\`, the \`openapi\` field updates live, while \`watchDir\`, \`outputDir\`, \`port\`, and \`packageManager\` require a restart.
|
|
40
45
|
|
|
41
46
|
## AI-native
|
|
42
47
|
|
|
@@ -69,11 +69,11 @@ const nextConfig: NextConfig = {
|
|
|
69
69
|
},
|
|
70
70
|
{
|
|
71
71
|
source: "/ingest/static/:path*",
|
|
72
|
-
destination:
|
|
72
|
+
destination: ${JSON.stringify(`${assetsHost}/static/:path*`)},
|
|
73
73
|
},
|
|
74
74
|
{
|
|
75
75
|
source: "/ingest/:path*",
|
|
76
|
-
destination:
|
|
76
|
+
destination: ${JSON.stringify(`${host}/:path*`)},
|
|
77
77
|
},
|
|
78
78
|
];
|
|
79
79
|
},
|
|
@@ -12,7 +12,7 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
12
12
|
},
|
|
13
13
|
dependencies: {
|
|
14
14
|
"@langchain/anthropic": "^1.5.2",
|
|
15
|
-
"@langchain/core": "^1.2.
|
|
15
|
+
"@langchain/core": "^1.2.4",
|
|
16
16
|
"@langchain/google-genai": "^2.2.0",
|
|
17
17
|
"@langchain/openai": "^1.5.5",
|
|
18
18
|
"@mdx-js/react": "^3.1.1",
|
|
@@ -24,8 +24,8 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
24
24
|
minisearch: "^7.2.0",
|
|
25
25
|
next: "16.2.12",
|
|
26
26
|
"next-mdx-remote": "^6.0.0",
|
|
27
|
-
"posthog-js": "^1.
|
|
28
|
-
"posthog-node": "^5.
|
|
27
|
+
"posthog-js": "^1.409.0",
|
|
28
|
+
"posthog-node": "^5.47.0",
|
|
29
29
|
react: "19.2.8",
|
|
30
30
|
"react-dom": "19.2.8",
|
|
31
31
|
"rehype-highlight": "^7.0.2",
|
package/dist/templates/proxy.js
CHANGED
|
@@ -118,7 +118,7 @@ function resolveTrackingIdentity(req: NextRequest): TrackingIdentity {
|
|
|
118
118
|
let deviceId: string | undefined;
|
|
119
119
|
|
|
120
120
|
const phCookie = req.cookies.get(
|
|
121
|
-
|
|
121
|
+
${JSON.stringify(`ph_${analyticsConfig.posthog.key}_posthog`)},
|
|
122
122
|
)?.value;
|
|
123
123
|
if (phCookie) {
|
|
124
124
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, isLLMAvailable, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built once at server startup since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n// Eagerly start building the index on server startup if LLM is configured\nif (isLLMAvailable()) {\n const initialBuild = buildDocsIndex();\n indexReady = initialBuild;\n // A failed eager build (e.g. a missing prebuilt index on a large doc set) must\n // not surface as an unhandledRejection at startup; the first request retries\n // via ensureDocsIndex and returns a real error to the client.\n void initialBuild.catch(() => {});\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register documentation as resources\n server.resource(\"docs://list\", \"docs://list\", async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n });\n\n return server;\n}\n";
|
|
1
|
+
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register documentation as resources\n server.resource(\"docs://list\", \"docs://list\", async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n });\n\n return server;\n}\n";
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
getAllDocsChunks,
|
|
9
9
|
DOCS_TOOLS,
|
|
10
10
|
} from "@/services/mcp/tools";
|
|
11
|
-
import { getLLMConfig,
|
|
11
|
+
import { getLLMConfig, createEmbeddings } from "@/services/llm";
|
|
12
12
|
import {
|
|
13
13
|
reduceDims,
|
|
14
14
|
quantizeInt8,
|
|
@@ -91,7 +91,7 @@ const RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();
|
|
|
91
91
|
|
|
92
92
|
/**
|
|
93
93
|
* In-memory cache for document embeddings.
|
|
94
|
-
* Built
|
|
94
|
+
* Built lazily on first use since docs are static.
|
|
95
95
|
*/
|
|
96
96
|
let docsIndex: {
|
|
97
97
|
ready: boolean;
|
|
@@ -349,16 +349,6 @@ function resourceText(value: unknown): string {
|
|
|
349
349
|
return serializeMCPResult(value).text;
|
|
350
350
|
}
|
|
351
351
|
|
|
352
|
-
// Eagerly start building the index on server startup if LLM is configured
|
|
353
|
-
if (isLLMAvailable()) {
|
|
354
|
-
const initialBuild = buildDocsIndex();
|
|
355
|
-
indexReady = initialBuild;
|
|
356
|
-
// A failed eager build (e.g. a missing prebuilt index on a large doc set) must
|
|
357
|
-
// not surface as an unhandledRejection at startup; the first request retries
|
|
358
|
-
// via ensureDocsIndex and returns a real error to the client.
|
|
359
|
-
void initialBuild.catch(() => {});
|
|
360
|
-
}
|
|
361
|
-
|
|
362
352
|
/** Cached embeddings instance for search queries */
|
|
363
353
|
let cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;
|
|
364
354
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doccupine",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.145",
|
|
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": {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"type": "module",
|
|
10
10
|
"engines": {
|
|
11
|
-
"node": ">=22"
|
|
11
|
+
"node": ">=22.12.0"
|
|
12
12
|
},
|
|
13
13
|
"packageManager": "pnpm@11.18.0",
|
|
14
14
|
"scripts": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"author": "Luan Gjokaj",
|
|
43
43
|
"license": "SEE LICENSE IN LICENSE",
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@readme/openapi-parser": "^6.3.
|
|
45
|
+
"@readme/openapi-parser": "^6.3.1",
|
|
46
46
|
"chalk": "^6.0.0",
|
|
47
47
|
"chokidar": "^5.0.0",
|
|
48
48
|
"commander": "^15.0.0",
|