# AI (https://press.fumadocs.dev/docs/plugins/ai)

Use any of these three features:

- [llms.txt](#llmstxt) gives AI tools your docs as Markdown. It is on by default.
- [AI Chat](#ai-chat) answers your readers on your site.
- [MCP](#mcp) lets tools like code editors search your docs.

## llms.txt [#llmstxt]

A new site already has these files:

- `/llms.txt`: an index of your pages, with a link to the Markdown of each page.
- `/llms-full.txt`: the text of all pages in one file.
- `<page>.md`: a Markdown version of each page, like `/docs/install.md`. The root page is `/index.md`.
- `<section>/llms-full.txt`: the text of all pages of a [section](#sections), like `/docs/llms-full.txt`.

Pass its options to `recommendedPreset()`:

```tsx title="press.config.tsx"
import { createPress, recommendedPreset } from "fumapress";

createPress(content).config({
  preset: recommendedPreset({ llms: { autoRedirect: false } }),
});
```

<Callout type="warn">
Keep [`includeProcessedMarkdown`](/docs/content-sources/fumadocs-mdx#setup) on your Fumadocs MDX
collection. This plugin reads the text of pages from the processed Markdown.
</Callout>

### Page Text [#page-text]

Return the Markdown of a page from `getLLMText`:

```tsx title="press.config.tsx"
recommendedPreset({
  llms: {
    async getLLMText(page) {
      return `# ${page.data.title} (${this.absoluteUrl(page.url)})

${await this.getPageText(page)}`;
    },
  },
});
```

### Leaving Pages Out [#leaving-pages-out]

Return `false` from `filter` to give a page no Markdown version:

```tsx title="press.config.tsx"
recommendedPreset({
  llms: {
    filter: (page) => !page.path.startsWith("internal/"),
  },
});
```

A page with [`noindex`](/docs/plugins/seo#leaving-pages-out) is left out too, but keeps its Markdown version:

| Page                | `<page>.md` | `llms-full.txt` | Link in `/llms.txt` |
| ------------------- | ----------- | --------------- | ------------------- |
| Removed by `filter` | None        | Left out        | The page itself     |
| With `noindex`      | Kept        | Left out        | Its `<page>.md`     |

### Sections [#sections]

A section is a folder with its own `llms-full.txt`, so an AI agent can read a large site one part at a time. Every [root folder](https://fumadocs.dev/docs/page-conventions#root-folder) is a section by default, and its line in `/llms.txt` links to the `llms-full.txt` of the section.

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

```tsx title="press.config.tsx"
recommendedPreset({
  llms: {
    // every folder with an index page
    section: (folder) => folder.index !== undefined,
  },
});
```

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

```tsx title="press.config.tsx"
recommendedPreset({
  llms: {
    section: (folder) => (folder.root ? { collapse: true } : false),
  },
});
```

The files of a section are under the URL of the index page of its folder, or under the URL directory of its pages when the folder has no index page.

### Content Negotiation [#content-negotiation]

An AI agent can ask for Markdown at the URL of a page, without knowing about `<page>.md`:

```bash
curl -H "Accept: text/markdown" https://docs.example.com/docs/install
```

Turn it off with `autoRedirect: false`.

<Callout>
This needs a server, and a static build doesn't add one for it. On Vercel, Netlify and Cloudflare,
it only applies to pages rendered on demand, because these platforms serve prerendered pages
without your server.
</Callout>

The `<head>` of a page also links to its Markdown, for AI agents that read the HTML:

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

### Custom Pages [#custom-pages]

Set `routes: "all"`, then return Markdown from the page. This page gets a `/index.md`, and an entry in `/llms.txt`:

```tsx tab="src/pages/index.tsx"
import { asMarkdown, md } from "fumapress/markdown";

export default function Page() {
  if (asMarkdown()) {
    return md`
# My Site

Welcome! Read the [docs](/docs).
    `;
  }

  return <main>...</main>;
}
```

```tsx tab="press.config.tsx"
recommendedPreset({ llms: { routes: "all" } });
```

<Callout type="warn">
The Markdown renders without your layouts, so an access check in a layout doesn't cover it. Put the check in the page, or in middleware that also covers `<page>.md`.
</Callout>

Only server components that call `asMarkdown()` are converted to Markdown. Other components stay as JSX in the output, like `<Card title="...">...</Card>`. To give a client component a Markdown version, wrap it in a server component:

```tsx
import { asMarkdown, md } from "fumapress/markdown";

function Callout({ title, children }) {
  if (asMarkdown()) return md.linePrefix("> ")`**${title}**\n${children}`;

  return <div className="callout">...</div>;
}
```

To render a React tree to Markdown yourself, use `renderToMarkdown(<Page />)`.

### llms.txt Options [#llmstxt-options]

### LLMsOptions

| Prop            | Type                                                                                                   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| --------------- | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `autoRedirect?` | `boolean \| undefined`                                                                                 | Serve the Markdown of a page to requests preferring it (`Accept: text/markdown`), on pages your server handles: hosts serving prerendered pages before it, like Vercel, Netlify and Cloudflare, only negotiate pages rendered on demand. Default: `true`                                                                                                                                                                                                                                                                                                                                        |
| `getLLMText?`   | `((this: Context<C>, page: C["page"]) => Awaitable<string \| undefined>) \| undefined`                 | The Markdown of a page, pages without it or with `noindex` in their page data are left out of the `llms-full.txt` files. By default, the text of content sources under a heading with the title and URL of the page.                                                                                                                                                                                                                                                                                                                                                                            |
| `filter?`       | `((page: C["page"]) => boolean) \| undefined`                                                          | The pages with a Markdown version, every page of your content sources by default. A page left out has no `<page>.md`, isn't in the `llms-full.txt` files, and `llms.txt` links to the page itself.                                                                                                                                                                                                                                                                                                                                                                                              |
| `section?`      | `((folder: Folder, ctx: Context) => boolean \| { asPath?: string; collapse?: boolean; }) \| undefined` | Whether a folder is a section: a folder with its own `llms-full.txt`, like `/docs/llms-full.txt`, that its line in `llms.txt` links to. Root folders are sections by default. - `collapse`: list the section in `llms.txt` as one link to its own `llms.txt`, which lists its pages. - `asPath`: the path of its files, instead of the URL of the folder's index page.                                                                                                                                                                                                                          |
| `routes?`       | `"all" \| "content" \| undefined`                                                                      | Which pages get a Markdown version (`/page.md`, `/index.md` for the root): - `"content"`: the pages of your content sources. - `"all"`: also the page routes whose `markdown()` gives text, like pages calling `asMarkdown()`. Static pages are prerendered, pages rendered on demand render it on demand. The Markdown renders the page without its layouts: access checks of a page belong in the page itself, or in middleware that covers its `<page>.md` too. Static pages render while the routes are created, they can read `getPageRoutes()` and the layout props. Default: `"content"` |

## AI Chat [#ai-chat]

The chat searches your pages to answer questions, and cites them as links. Its endpoint renders on demand, so the site [needs a server](/docs/deployment#what-needs-a-server).

### Install [step] [#install]

```npm
npm i @fumapress/ai
```

### Add the Plugin [step] [#add-the-plugin]

Pass a model: an [AI Gateway](https://ai-sdk.dev/docs/ai-sdk-core/settings#setting-the-model) model ID, or a model from a [provider package](https://ai-sdk.dev/docs/foundations/providers-and-models).

```tsx tab="AI Gateway" title="press.config.tsx"
import { aiPlugin } from "@fumapress/ai";

export default createPress(content).plugins(aiPlugin({ model: "openai/gpt-5" }));
```

```tsx tab="Provider Package" title="press.config.tsx"
import { aiPlugin } from "@fumapress/ai";
import { openai } from "@ai-sdk/openai";

export default createPress(content).plugins(aiPlugin({ model: openai("gpt-5") }));
```

### Add the Styles [step] [#add-the-styles]

Add this after the imports in your stylesheet:

```css title="src/app.css"
@import "@fumapress/ai/css/preset.css";
```

Now the Docs Layout docks the chat, and a floating "Ask AI" button opens it. `Ctrl + /` opens it too.

### Rate Limiting [#rate-limiting]

<Callout type="warn">
The endpoint calls your model provider, and has no limit on body size or message count. Anyone who
can reach it can spend your budget, so add rate limiting before you go live.
</Callout>

Return a `Response` from `beforeRequest` to reject a request:

```tsx title="press.config.tsx"
aiPlugin({
  model: "openai/gpt-5",
  async beforeRequest(req) {
    if (await isRateLimited(req)) {
      return new Response("Too Many Requests", { status: 429 });
    }
  },
});
```

### System Prompt [#system-prompt]

```tsx title="press.config.tsx"
aiPlugin({
  model: "openai/gpt-5",
  systemPrompt: "You are the assistant for the Acme docs. Keep answers short, with links.",
});
```

### Custom Layout [#custom-layout]

The plugin passes the chat to layouts as the `aiChat` prop, through `useLayoutProps()`. The default layout reads it for you.

In a [custom layout](/docs/layouts#custom-layouts), read it in a client component around the layout:

```tsx tab="src/components/layout.tsx"
"use client";
import { DocsLayout, type DocsLayoutProps } from "fumadocs-ui/layouts/notebook";
import { useLayoutProps } from "fumapress/client";

export function Layout(props: DocsLayoutProps) {
  return <DocsLayout {...props} {...useLayoutProps()} />;
}
```

```tsx tab="src/ui/layout.tsx"
import { DocsBody, DocsPage, DocsTitle } from "fumadocs-ui/layouts/notebook/page";
import { Layout } from "../components/layout";

function Docs({ layoutProps, pageData, toc, body }: RenderPageProps<typeof app, "docs">) {
  return (
    <Layout {...layoutProps}>
      <DocsPage toc={toc}>
        <DocsTitle>{pageData.title}</DocsTitle>
        <DocsBody>{body}</DocsBody>
      </DocsPage>
    </Layout>
  );
}
```

The Docs and Notebook layouts open the chat with a floating "Ask AI" button. The Glass and Spacious layouts show their own button.

### Chat Options [#chat-options]

`pageToIndex` controls which pages the model can search, as in [MCP](#filtering-pages). To keep the endpoint without the chat UI, set `configureUI: false`.

### AIOptions

| Prop             | Type                                                                                    | Description                                                                                       |
| ---------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `configureUI?`   | `boolean \| undefined`                                                                  | add the chat around every page, docked by every layout reading `useLayoutProps()` Default: `true` |
| `model`          | `LanguageModel`                                                                         |                                                                                                   |
| `systemPrompt?`  | `string \| undefined`                                                                   |                                                                                                   |
| `beforeRequest?` | `((request: Request) => Awaitable<Response \| undefined>) \| undefined`                 | you can add logic for ratelimiting, validation etc.                                               |
| `pageToIndex?`   | `((this: Context<C>, page: C["page"]) => Awaitable<PageDocument \| null>) \| undefined` |                                                                                                   |

## MCP [#mcp]

An [MCP](https://modelcontextprotocol.io) client, like a code editor, can search your docs through an endpoint on your site. The endpoint renders on demand, so the site [needs a server](/docs/deployment#what-needs-a-server).

```tsx title="press.config.tsx"
import { mcpPlugin } from "@fumapress/ai";

export default createPress(content).plugins(mcpPlugin());
```

Then point your client at `/mcp` on your site, like `https://docs.example.com/mcp`, over [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http). The client gets three tools:

- `search`, which also takes a `locale` with [internationalization](/docs/internationalization).
- `get_page`, which returns the text of a page.
- `list_pages`, which lists your pages.

### Filtering Pages [#filtering-pages]

Return `null` from `pageToIndex` to leave a page out:

```tsx title="press.config.tsx"
mcpPlugin({
  async pageToIndex(page) {
    if (page.path.startsWith("internal/")) return null;

    return {
      title: page.data.title ?? "",
      description: page.data.description ?? "",
      url: page.url,
      content: (await this.getPageText(page)) ?? "",
      locale: page.locale ?? "",
    };
  },
});
```

### Custom Tools [#custom-tools]

`tools` receives the `McpServer` of [`@modelcontextprotocol/server`](https://www.npmjs.com/package/@modelcontextprotocol/server):

```tsx title="press.config.tsx"
import { mcpPlugin } from "@fumapress/ai";
import { z } from "zod";

mcpPlugin({
  tools(server) {
    server.registerTool(
      "get_site_name",
      {
        title: "Get Site Name",
        description: "Return the site name from the config",
        inputSchema: z.object({}),
      },
      async () => ({
        content: [{ type: "text", text: this.siteConfig.name }],
      }),
    );
  },
});
```

### MCP Options [#mcp-options]

### McpOptions

| Prop           | Type                                                                                                                                                                                                                                                                                                         | Description                                  |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------- |
| `path?`        | `string \| undefined`                                                                                                                                                                                                                                                                                        | Base path for MCP routes. Default: `"/mcp"`  |
| `server?`      | `Partial<{ version: string; websiteUrl?: string \| undefined; description?: string \| undefined; icons?: { src: string; mimeType?: string \| undefined; sizes?: string[] \| undefined; theme?: "dark" \| "light" \| undefined; }[] \| undefined; name: string; title?: string \| undefined; }> \| undefined` |                                              |
| `tools?`       | `((this: Context<C>, server: McpServer) => void \| Promise<void>) \| undefined`                                                                                                                                                                                                                              | Register additional tools on the MCP server. |
| `pageToIndex?` | `((this: Context<C>, page: C["page"]) => Awaitable<PageDocument \| null>) \| undefined`                                                                                                                                                                                                                      |                                              |