Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Content lives as Markdown in your repo and is served **at request time** — par
- Docs UI built with [Nuxt UI](https://ui.nuxt.com): sidebar navigation, search (`⌘K`), TOC, prev/next links, version history panel.
- SEO out of the box: sitemap, robots, canonical URLs, OG images (Satori), JSON-LD, RSS.
- Markdown for agents through [nuxt-agent-discovery](https://github.com/benjamincanac/nuxt-agent-discovery): content negotiation on every documentation page, raw markdown mirrors (`/raw/**`), `llms.txt` / `llms-full.txt`, `sitemap.md`, `/openapi.json`, `/.well-known/api-catalog`, an MCP server (`/mcp`) with its server card, Agent Skills discovery (`/.well-known/skills/`).
- [Search for agents](https://blog.cloudflare.com/search-for-agents/): `/.well-known/search?q=` (or the HTTP `QUERY` method) returns ranked sections as Markdown, advertised by `agent:*` meta tags on every page.

## Quick start

Expand Down
15 changes: 14 additions & 1 deletion app/app.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script setup lang="ts">
import type { NavigationItem } from 'comark-content'
import { joinURL } from 'ufo'
import { useRoute } from 'vue-router'

const { seo, docs } = useAppConfig()
Expand Down Expand Up @@ -36,8 +37,20 @@ onNuxtReady(() => {
})
})

const site = useSiteConfig()

useHead({
meta: [{ name: 'viewport', content: 'width=device-width, initial-scale=1' }],
meta: [
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
// Search for agents (https://blog.cloudflare.com/search-for-agents/), served by server/routes/.well-known/search.ts.
{
name: 'agent:instructions',
content:
'Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.',
},
{ name: 'agent:endpoint', content: `${joinURL(site.url, '/.well-known/search')}?q={query}` },
{ name: 'agent:method', content: 'GET' },
],
link: [
{ rel: 'icon', href: '/favicon.ico' },
{
Expand Down
59 changes: 59 additions & 0 deletions server/routes/.well-known/search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { getAgentSiteUrl } from '#agent-discovery'
import { createError, defineEventHandler, getQuery, getRequestHeader } from 'nuxt/server'
import type { RequestEvent } from 'nuxt/server'
import { joinURL } from 'ufo'

/** A search query, not a document: anything larger is refused before it is buffered. */
const MAX_QUERY_BODY = 16 * 1024

/**
* Search for agents (https://blog.cloudflare.com/search-for-agents/): ranked documentation sections as
* Markdown, for `GET ?q=` and the HTTP `QUERY` method (RFC 10008) with a plain-text or JSON body. Reads
* production content, like the MCP `search-docs` tool, through the same index.
*/
export default defineEventHandler(async (event) => {
const method = event.req.method
if (method !== 'GET' && method !== 'QUERY') {
event.res.headers.set('allow', 'GET, QUERY')
throw createError({ status: 405, statusText: 'Method not allowed' })
}

let query = String(getQuery(event).q ?? '')
if (method === 'QUERY') {
const body = await readQueryBody(event)
const mediaType = getRequestHeader(event, 'content-type')?.split(';')[0]!.trim().toLowerCase()
try {
query = mediaType === 'application/json' ? String(JSON.parse(body).q ?? '') : body
} catch {
throw createError({ status: 400, statusText: 'Invalid JSON body' })
}
}
query = query.trim()
if (!query) throw createError({ status: 400, statusText: 'Missing `q` parameter' })

const sections = await searchDocSections(await getProdContent(), query)
const siteUrl = getAgentSiteUrl(event)
const results = sections.map((section) => {
const heading = [...section.titles, section.title].filter(Boolean).join(' > ')
return `## ${heading}\n\nURL: ${joinURL(siteUrl, section.id)}${section.content ? `\n\n${section.content}` : ''}`
})

event.res.headers.set('content-type', 'text/markdown; charset=utf-8')
if (!results.length) return `# No results for: "${query}"\n\nTry fewer or broader terms, or browse ${joinURL(siteUrl, 'sitemap.md')}.\n`
return [`# Search results for: "${query}"`, ...results].join('\n\n---\n\n') + '\n'
})

/** Read the body of a `QUERY` request, refusing it with a 413 once it outgrows {@link MAX_QUERY_BODY}. */
async function readQueryBody(event: RequestEvent): Promise<string> {
// On h3 v1, `event.req` is built without a body for methods other than PATCH, POST, PUT, and DELETE,
// so read the node request it wraps. On h3 v2, `event.req` is the request itself.
const stream = (event as { node?: { req: AsyncIterable<Uint8Array> } }).node?.req ?? event.req.body
const chunks: Uint8Array[] = []
let size = 0
for await (const chunk of stream ?? []) {
size += chunk.byteLength
if (size > MAX_QUERY_BODY) throw createError({ status: 413, statusText: 'Query body too large' })
chunks.push(chunk)
}
return Buffer.concat(chunks).toString('utf8')
}
20 changes: 18 additions & 2 deletions server/routes/openapi.json.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { agentDiscoveryOpenApi, getAgentSiteUrl } from '#agent-discovery'
*/
export default defineEventHandler((event) => {
const config = useRuntimeConfig(event)
const discovery = agentDiscoveryOpenApi(event)
const discovery = agentDiscoveryOpenApi(event, { reserved: ['searchDocs'] })
const siteName = config.public.agentDiscovery?.siteName || 'Documentation'

return {
Expand All @@ -18,7 +18,23 @@ export default defineEventHandler((event) => {
},
servers: [{ url: getAgentSiteUrl(event) }],
tags: discovery.tags,
paths: discovery.paths,
paths: {
...discovery.paths,
// server/routes/.well-known/search.ts
'/.well-known/search': {
get: {
tags: ['Discovery'],
operationId: 'searchDocs',
summary: 'Search the documentation',
description: 'Ranked documentation sections matching the query, as Markdown. Also answers the HTTP QUERY method with a plain-text or JSON (`{"q": "..."}`) body.',
parameters: [{ name: 'q', in: 'query', required: true, schema: { type: 'string' }, description: 'Keywords or a natural-language query.' }],
responses: {
200: { description: 'Matching sections, each with its heading trail, URL, and text.', content: { 'text/markdown': { schema: { type: 'string' } } } },
400: { description: 'The query is missing.' },
},
},
},
},
components: discovery.components,
}
})
12 changes: 9 additions & 3 deletions server/utils/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ interface SearchSection {
// the index survives cold starts, is shared across lambda instances in the region, and stale parser
// output is unreachable. Colon-free so it can't collide with `<source>:<path>` content keys, the
// `manifest` key, or the shared `gh:` namespace, and the SWR fallback in `cache.get`
// (`key.split(':')`) can't map it to a real source.
const SEARCH_SECTIONS_KEY = 'search-sections'
// (`key.split(':')`) can't map it to a real source. Versioned because the namespace doesn't change with
// this file: bump it when the sections it builds change, or a deploy keeps serving the old ones.
const SEARCH_SECTIONS_KEY = 'search-sections-v2'

/**
* Drop the cached index — the one case the per-SHA namespace can't cover: in dev the default
Expand Down Expand Up @@ -114,10 +115,15 @@ async function collectSearchSections(content: DocsContent): Promise<SearchSectio
return sections
}

// Containers whose children are separate cells, rows, or items: their text is joined with a space so
// `| Mode | URL |` reads `Mode URL`, not `ModeURL`.
const SPACED_CONTAINERS = new Set(['table', 'thead', 'tbody', 'tfoot', 'tr', 'ul', 'ol'])

function extractText(node: unknown): string {
if (typeof node === 'string') return node
if (!Array.isArray(node) || node[0] === null) return ''
return node.slice(2).map(extractText).filter(Boolean).join('')
const separator = SPACED_CONTAINERS.has(node[0]) ? ' ' : ''
return node.slice(2).map(extractText).filter(Boolean).join(separator)
}

function getTag(node: unknown): string {
Expand Down
43 changes: 42 additions & 1 deletion test/e2e/routes.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { baseURL, fetchPath, fetchWithFailure, INTRO_PAGE, NOT_FOUND_SLUG, SITE_URL } from './utils'
import { baseURL, fetchPath, fetchWithFailure, INTRO_PAGE, NOT_FOUND_SLUG, request, SITE_URL } from './utils'

/** Absolute URLs point at the production site: keep the path and query only. */
function toPath(url: string): string {
Expand Down Expand Up @@ -73,6 +73,47 @@ describe('agent routes', () => {
})
})

describe('search for agents', () => {
const ANCHOR = `${SITE_URL}/concepts/versioned-previews#`

it.each([
['GET', '/.well-known/search?q=versioned+previews', {}],
['QUERY with a text body', '/.well-known/search', { method: 'QUERY', body: 'versioned previews' }],
[
'QUERY with a JSON body',
'/.well-known/search',
{ method: 'QUERY', headers: { 'content-type': 'Application/JSON; charset=utf-8' }, body: '{"q":"versioned previews"}' },
],
])('%s returns ranked sections as markdown', async (_, path, init) => {
const response = await request(path, init)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/markdown')
const text = await response.text()
expect(text).toMatch(/^# Search results for: "versioned previews"/)
expect(text).toContain(`URL: ${ANCHOR}`)
})

it('separates table cells and list items', async () => {
const text = await request('/.well-known/search?q=versioned+previews').then((res) => res.text())
expect(text).toContain('Mode URL pattern Content Branch /tree/:branch/<page>')
expect(text).toContain("this keeps version-history links working). A pull request")
})

it('rejects a missing query, other methods, and oversized bodies', async () => {
expect((await request('/.well-known/search')).status).toBe(400)
const post = await request('/.well-known/search?q=previews', { method: 'POST' })
expect(post.status).toBe(405)
expect(post.headers.get('allow')).toBe('GET, QUERY')
const large = await request('/.well-known/search', { method: 'QUERY', body: 'previews '.repeat(2000) })
expect(large.status).toBe(413)
})

it('is advertised on every page', async () => {
const html = await fetchPath(INTRO_PAGE.path).then((res) => res.text())
expect(html).toContain(`<meta name="agent:endpoint" content="${SITE_URL}/.well-known/search?q={query}">`)
})
})

describe('icons', () => {
// The icon of `md` code blocks is the layer's own SVG, not an Iconify collection. @nuxt/icon caches the
// JSON error of a missing icon and then answers 200 with it, so the body is what shows it is served.
Expand Down
Loading