# Fumadocs (Framework Mode, Next.js): AI & LLMs
URL: /docs/next/integrations/llms
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/[framework]/integrations/llms.mdx

Integrate AI functionality to Fumadocs.

## Docs for LLM [#docs-for-llm]

Serve your docs as Markdown for LLMs and AI agents:

```package-install
npx @fumadocs/cli feature llms
```

It enables processed Markdown on your docs collection, adds `docsLlms` to `lib/source.ts`, and serves the [files](#files) below. The generated files are listed here if you prefer a manual setup.

### `docsLlms` [#docsllms]

`llms()` renders your docs for LLMs. `renderPage` turns one page into Markdown, from the processed document rather than the raw file content:

```ts title="lib/source.ts"
import { llms } from 'fumadocs-core/source';

export const docsLlms = llms(source, {
  renderPage: async (page) => `# ${page.data.title} (${page.url})

${await page.data.getText('processed')}`,
});

```

| Method         | Output                                         |
| -------------- | ---------------------------------------------- |
| `index(lang?)` | the `llms.txt` index, built from the page tree |
| `page(page)`   | one page, rendered with `renderPage`           |
| `full(lang?)`  | every page rendered with `renderPage`, joined  |
| `files()`      | the paths of the [files for agents](#files)    |
| `serve(path)`  | the response for the file at a path            |

<Callout title="renderPage is required">
`page()`, `full()`, `files()` and `serve()` are only available when you pass `renderPage`, since
Fumadocs cannot know how your content source exposes its Markdown.
</Callout>

`renderPage` reads the processed Markdown of pages, so enable `includeProcessedMarkdown`:

```ts title="source.config.ts"
import { defineDocs } from 'fumadocs-mdx/config';

export const docs = defineDocs({
  dir: 'content/docs',
  docs: { // [!code ++:5]
    postprocess: {
      includeProcessedMarkdown: true,
    },
  },
});

```

MDX components appear as JSX syntax. To render them into their [Markdown form](/docs/headless/utils/markdown#asmarkdown), [pass your MDX components](/docs/headless/mdx/remark-llms#jsx-elements) as page props.

Runtime content sources like [`@fumadocs/local-md`](/docs/next/integrations/content/local-md) resolve on demand. Pass their `getSource` and the CLI generates the same files:

```ts
export const docsLlms = llms(getSource, {
  renderPage: (page) => `# ${page.data.title} (${page.url})

${page.data.content}`,
});
```

With `getSource`, `index()` and `indexNode()` return a promise instead of a string.

### Files [#files]

The CLI serves these files for AI agents:

- `/llms.txt`: the index of your docs, with a link to the Markdown of each page.
- `/llms-full.txt`: the content of every page.
- `<page>.md`: the Markdown of a page, like `/docs/ui.md`. The page at `/` is `/index.md`.
- `<section>/llms-full.txt`: the content of a [section](#sections), like `/docs/ui/llms-full.txt`.

To leave pages out of the files, like drafts, pass `filter`. `llms.txt` still lists them, linked to their HTML page:

```ts title="lib/source.ts"
export const docsLlms = llms(source, {
  filter: (page) => page.slugs[0] !== 'drafts',
  renderPage: async (page) => `# ${page.data.title}\n\n${await page.data.getText('processed')}`,
});
```

In the files, `renderUrl` receives the path of the file that a link points to, like the `.md` file of a page.

Agents that read the HTML of a page find its Markdown through a link in the `<head>`:

```html
<link rel="alternate" type="text/markdown" href="/docs/ui.md" />
```

### Sections [#sections]

A section is a folder of the page tree with its own `llms-full.txt`, so agents can read large docs one part at a time. Every root folder is a section by default. In `llms.txt`, the line of the folder links to the `llms-full.txt` of its section.

To choose the sections, pass `section`. It receives a folder and returns whether the folder is a section:

```ts title="lib/source.ts"
export const docsLlms = llms(source, {
  // every folder with an index page
  section: (folder) => folder.index !== undefined,
  renderPage: async (page) => `# ${page.data.title}\n\n${await page.data.getText('processed')}`,
});
```

On a large site, collapse sections to keep `llms.txt` short. `llms.txt` lists a collapsed section as one link to its own `<section>/llms.txt`, which lists its pages:

```ts title="lib/source.ts"
export const docsLlms = llms(source, {
  section: (folder) => (folder.root ? { collapse: true } : false),
  renderPage: async (page) => `# ${page.data.title}\n\n${await page.data.getText('processed')}`,
});
```

The files of a section are served under the URL of its folder's index page. A folder without an index page uses the URL directory of its pages instead. When two folders share a URL, like folder groups, pass `asPath` to serve one of them at another path, like `{ asPath: '/docs/guides' }`.

### Routes [#routes]

`files()` lists the paths of the files, and `serve(path)` responds with the file at a path, so each route only passes the request path to `serve()`.

Route handlers serve `/llms.txt` and `/llms-full.txt`. The other files sit beside `app/docs/[[...slug]]`, so the Next.js config rewrites their paths to the `/llms.mdx/[...path]` route:

```ts tab="app/llms.txt/route.ts"
import { docsLlms } from '@/lib/source';

export const revalidate = false;

export async function GET() {
  return (await docsLlms.serve('/llms.txt'))!;
}

```

```ts tab="app/llms-full.txt/route.ts"
import { docsLlms } from '@/lib/source';

export const revalidate = false;

export async function GET() {
  return (await docsLlms.serve('/llms-full.txt'))!;
}

```

```ts tab="app/llms.mdx/[...path]/route.ts"
import { docsLlms } from '@/lib/source';

export const revalidate = false;
// other paths are 404s, never cached responses
export const dynamicParams = false;

export async function GET(_req: Request, { params }: RouteContext<'/llms.mdx/[...path]'>) {
  const { path } = await params;
  return (await docsLlms.serve(`/${path.join('/')}`)) ?? new Response(null, { status: 404 });
}

export async function generateStaticParams() {
  const params: { path: string[] }[] = [];
  for (const file of await docsLlms.files()) {
    // `/llms.txt` and `/llms-full.txt` have their own routes
    if (!/^\/llms(-full)?\.txt$/.test(file)) params.push({ path: decodeURI(file).slice(1).split('/') });
  }
  return params;
}

```

```ts tab="next.config.ts"
import type { NextConfig } from 'next';

const config: NextConfig = {
  reactStrictMode: true,
  async rewrites() { // [!code ++:12]
    return [
      {
        source: '/docs/:path*.md',
        destination: '/llms.mdx/docs/:path*.md',
      },
      {
        source: '/docs/:path*.txt',
        destination: '/llms.mdx/docs/:path*.txt',
      },
    ];
  },
};

export default config;

```

`serve()` returns `undefined` for a path without a file, so a middleware can pass the request on. With `hideLocale: 'always'`, URLs don't carry the locale: pass the language as the second argument of `serve()` and the first of `files()`.

#### Static Output [#static-output]

With `output: 'export'`, Next.js has no rewrites. The `/llms.mdx/[...path]` route serves the files at their prefixed paths, like `/llms.mdx/docs/ui.md`, and `renderUrl` points the links of `llms.txt` there:

```ts title="lib/source.ts"
import { llms } from 'fumadocs-core/source';

export const docsLlms = llms(source, {
  renderPage: async (page) => `# ${page.data.title} (${page.url})

${await page.data.getText('processed')}`,
  // link to the files under `/llms.mdx`
  renderUrl: (item) => (/^\/.*\.(md|txt)$/.test(item.url) ? `/llms.mdx${item.url}` : item.url),
});

```

#### `Accept` [#accept]

AI agents can ask for Markdown with the `Accept` header.

Serve the Markdown of a page when the request prefers it:

```ts title="proxy.ts"
import { NextRequest, NextResponse } from 'next/server';
import { isMarkdownPreferred, rewritePath } from 'fumadocs-core/negotiation';

const { rewrite: rewriteDocs } = rewritePath('/docs{/*path}', '/llms.mdx/docs{/*path}.md');

export default function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  // the rewrites of the Next.js config serve files like `/docs/ui.md`
  const result =
    isMarkdownPreferred(request) && !/\.(md|txt)$/.test(pathname) && rewriteDocs(pathname);

  if (result) {
    return NextResponse.rewrite(new URL(result, request.nextUrl), {
      headers: { Vary: 'Accept' }, // [!code highlight]
    });
  }

  return NextResponse.next();
}
```

The same URL now has two representations, so the response needs `Vary: Accept` to prevent cache collisions.

<Callout>
Next.js discards `Vary` on App Router page responses, so the HTML responses of docs pages can't
carry the header. Set it at your CDN if a shared cache serves your docs.
</Callout>

### Page Actions [#page-actions]

Page actions let readers copy the Markdown of a page, or open the page in AI apps. They read the [`.md` file](#files) of the page.

![AI Page Actions](/docs/ai-page-actions.png)

Render them in your docs page:

```tsx
import { MarkdownCopyButton, ViewOptionsPopover } from 'fumadocs-ui/layouts/docs/page';

const markdownUrl = `${page.url}.md`;

<div className="flex flex-row gap-2 items-center border-b pt-2 pb-6">
  <MarkdownCopyButton markdownUrl={markdownUrl} />
  <ViewOptionsPopover
    markdownUrl={markdownUrl}
    githubUrl={`https://github.com/${owner}/${repo}/blob/main/content/docs/${encodeURI(page.path)}`}
  />
</div>;
```

With static export, the URL is `` `/llms.mdx${page.url}.md` `` instead.

## MCP Server [#mcp-server]

Expose your docs to AI agents through a [MCP](https://modelcontextprotocol.io) server, with tools to list, search and read pages.

```package-install
npx @fumadocs/cli feature mcp
```

It creates a `/api/mcp` route with the streamable HTTP transport, on top of the [LLM routes](#docs-for-llm) above.

The tools come from [`fumadocs-core/mcp`](/docs/headless/utils/mcp).

```ts title="app/api/mcp/route.ts"
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { registerSearchTool, registerSourceTools } from 'fumadocs-core/mcp';
import { createFromSource } from 'fumadocs-core/search/server';
import { docsLlms, source } from '@/lib/source';

// shared by requests, the index is built on the first search
const search = createFromSource(source);

const handler = createMcpHandler(() => {
  const mcp = new McpServer(
    {
      name: 'docs',
      version: '1.0.0',
    },
    // the tools never change, a stream to watch them would hold a serverless function open
    { capabilities: { tools: { listChanged: false } } },
  );

  registerSourceTools(mcp, source, docsLlms);
  registerSearchTool(mcp, search);

  return mcp;
});

export async function GET(request: Request) {
  return handler.fetch(request);
}

export async function POST(request: Request) {
  return handler.fetch(request);
}

export async function DELETE(request: Request) {
  return handler.fetch(request);
}

```

Connect an agent to it with:

```json
{
  "mcpServers": {
    "docs": { "url": "https://your-site.com/api/mcp" }
  }
}
```

## WebMCP [#webmcp]

<Callout type="warn" title="Experimental">
[WebMCP](https://webmachinelearning.github.io/webmcp/) is an early web standard, available in
Chrome 149+ behind the `#enable-webmcp-testing` flag and an origin trial. The API may still
change.
</Callout>

Where the MCP server above serves agents connecting to your site, WebMCP exposes tools to the AI agent
of the browser, on the page the reader is viewing.

```package-install
npx @fumadocs/cli feature webmcp
```

It creates a `WebMCP` component on top of the [LLM routes](#docs-for-llm). Render it inside `<RootProvider />`.

- `search_docs` queries the search API route. You can replace `fetchClient` with [other clients](/docs/next/search).
- `read_page` fetches the Markdown of a page, from `/docs/page.md`.

## Ask AI [#ask-ai]

![AI Search](/docs/ai-search.png)

You can install the AI chat dialog using Fumadocs CLI.

<Tabs items={["AI SDK","LLMGateway","Inkeep AI"]}>
<Tab>
```npm
npx @fumadocs/cli add ai/openrouter
```

It's automatically configured for [OpenRouter](https://openrouter.ai) using Vercel AI SDK, with a `/search` tool for AI.

You can use other models by updating the `/api/chat` route.

> Fumadocs doesn't provide the AI model, it's up to you.
>
> Your AI model can use the `llms-full.txt` file generated above, or more diversified sources of information when combined with 3rd party solutions.
</Tab>

<Tab>
```npm
npx @fumadocs/cli add ai/llmgateway
```

It's automatically configured for [LLMGateway](https://llmgateway.io) using Vercel AI SDK, with a `/search` tool for AI.

LLMGateway is an open-source API gateway that proxies requests to 300+ language models, so the same route handler can switch between providers by changing the model ID.

Add your LLMGateway API key to environment variables:

```dotenv
LLM_GATEWAY_API_KEY="..."
```

By default the route uses `anthropic/claude-sonnet-5-5`. To switch to any other model supported by LLMGateway, set the `LLM_GATEWAY_MODEL` environment variable. No code change is required:

```dotenv
# any model id from https://llmgateway.io/models
LLM_GATEWAY_MODEL="openai/gpt-4o"
```
</Tab>

<Tab>
```npm
npx @fumadocs/cli add ai/inkeep
```

It's automatically configured for [Inkeep AI](https://inkeep.com) using Vercel AI SDK.

Add your Inkeep API key to environment variables:

```dotenv
INKEEP_API_KEY="..."
```
</Tab>
</Tabs>

Docs layouts render the chat from their `aiChat` option. The option takes client state, so create a client component for your layout and use it in place of the original layout:

```tsx tab="components/ai/layout.tsx"
'use client';
// or the Notebook, Glass and Spacious layouts
import { DocsLayout as Layout, type DocsLayoutProps } from 'fumadocs-ui/layouts/docs';
// the installed components
import { AIChat, AIChatPanel, useAIChat } from './search';

export function DocsLayout(props: DocsLayoutProps) {
  return (
    <AIChat>
      <ChatLayout {...props} />
    </AIChat>
  );
}

function ChatLayout(props: DocsLayoutProps) {
  const { open, setOpen } = useAIChat();

  return (
    <Layout
      {...props}
      aiChat={{ open, onOpenChange: setOpen, panel: <AIChatPanel />, trigger: true }}
    />
  );
}
```

```tsx tab="app/docs/layout.tsx"
import { DocsLayout } from 'fumadocs-ui/layouts/docs'; // [!code --]
import { DocsLayout } from '@/components/ai/layout'; // [!code ++]
```

The layout options are passed to a client component, so they have to be serializable.