feat: v1.7.0 — AI-readability suite, form engine & boilerplate helpers
AI / GEO: - feat(content): lexicalToMarkdown, blocksToMarkdown, createMarkdownRenderer (+markdownResponse) — per-page Markdown for AI agents - feat(content): markdown content negotiation + discovery (prefersMarkdown, markdownHref) - feat(seo): buildRobots aiBots policy (allow/block-training/disallow) - feat(seo): llms-full.txt mode in buildLlmsTxt/createLlmsTxtRoute - feat(mcp): createMcpRoute — read-only MCP server (search_content, get_page) - feat(content): searchContent + createSearchRoute — shared JSON search - feat(seo): buildSpeakableJsonLd + buildSummaryField (aiSummary, auto-fill) Forms: - feat(forms): useForm/useContactForm + validators (logic-only, no markup) - feat(forms): honeypot anti-spam (honeypotInputProps, isHoneypotTripped) Helpers / hardening: - feat(i18n): resolveLocalized — replaces ad-hoc getSafeString - feat(hooks): buildCrossLocaleFieldSync — locales from config, no hardcoded list - feat(seo): buildNoindexField — checkbox → meta.noindex, no - feat(content): resolveRedirect — 301/308 from slugHistory - feat(env): assertEnv + ipalEnvRules — fail-fast env validation - feat(consent): ConsentScript — load third-party only after consent - feat(health): createHealthRoute — Coolify/Docker DB liveness Fixes: - fix(seo): wrap getCachedPayload in try/catch in createManifestHandler (Docker/CI build no longer crashes when DB unreachable) docs: migration.md (20 sections), new env.md/mcp.md, updated agents.md, AGENTS-TEMPLATE.md, forms/hooks/content/seo/consent/deployment/richtext
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { ContentOption } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { createMarkdownRenderer, searchContent } from '../content/index.js'
|
||||
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
|
||||
|
||||
/**
|
||||
* A read-only MCP (Model Context Protocol) server for the client site, as a Next
|
||||
* route handler. Lets Claude / any MCP client CONNECT to the site and query it
|
||||
* directly — search content, fetch a page as Markdown — instead of scraping
|
||||
* HTML. This is the "better integration" layer on top of the Markdown/llms work.
|
||||
*
|
||||
* Dependency-free on purpose: it does NOT pull in @modelcontextprotocol/sdk
|
||||
* (that would be an imposed dependency, and its API moves). It implements the
|
||||
* minimal JSON-RPC surface a read-only server needs over the Streamable-HTTP
|
||||
* transport: initialize, tools/list, tools/call, ping. Uses the global
|
||||
* Request/Response — no next/server import.
|
||||
*
|
||||
* Exposes two tools:
|
||||
* - search_content({ query, locale?, limit? }) → matching pages (title, url, description)
|
||||
* - get_page({ path }) → that page as Markdown
|
||||
*
|
||||
* // app/api/mcp/route.ts
|
||||
* import { createMcpRoute } from '@intecion/ipal-kit'
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: 'acme-site' })
|
||||
* export const POST = mcp.POST
|
||||
* export const GET = mcp.GET
|
||||
*
|
||||
* Add it in Claude as a custom connector pointing at https://site/api/mcp.
|
||||
*/
|
||||
|
||||
const DEFAULT_PROTOCOL = '2025-06-18'
|
||||
|
||||
type CreateMcpRouteArgs = {
|
||||
/** Absolute origin for building result URLs. */
|
||||
baseUrl?: string
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string
|
||||
config: I18nConfig
|
||||
/** Archive-backed collections (same as the plugin option) for get_page. */
|
||||
content?: ContentOption
|
||||
getCachedPayload: () => Promise<BasePayload>
|
||||
/** Server name advertised in `initialize`. Default 'ipal-site'. */
|
||||
serverName?: string
|
||||
/** Server version advertised in `initialize`. Default '1.0.0'. */
|
||||
serverVersion?: string
|
||||
/** SiteSettings slug. Default 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */
|
||||
summaryField?: string
|
||||
}
|
||||
|
||||
type JsonRpcId = null | number | string
|
||||
type JsonRpcRequest = { id?: JsonRpcId; jsonrpc?: string; method?: string; params?: unknown }
|
||||
|
||||
function rpcResult(id: JsonRpcId, result: unknown) {
|
||||
return { id, jsonrpc: '2.0', result }
|
||||
}
|
||||
function rpcError(id: JsonRpcId, code: number, message: string) {
|
||||
return { id, error: { code, message }, jsonrpc: '2.0' }
|
||||
}
|
||||
|
||||
function toolText(text: string, isError = false) {
|
||||
return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) }
|
||||
}
|
||||
|
||||
export function createMcpRoute(args: CreateMcpRouteArgs) {
|
||||
const {
|
||||
baseUrl,
|
||||
collection = 'pages',
|
||||
config,
|
||||
content,
|
||||
getCachedPayload,
|
||||
serverName = 'ipal-site',
|
||||
serverVersion = '1.0.0',
|
||||
settingsSlug = 'site-settings',
|
||||
summaryField,
|
||||
} = args
|
||||
|
||||
const origin = baseUrl?.replace(/\/$/, '') ?? ''
|
||||
const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'search_content',
|
||||
description:
|
||||
'Search the site content by keyword. Returns matching pages with title, URL and description.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'number', description: 'Max results (default 10)' },
|
||||
locale: { type: 'string', description: `Locale code (default ${config.defaultLocale})` },
|
||||
query: { type: 'string', description: 'Search keywords' },
|
||||
},
|
||||
required: ['query'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'get_page',
|
||||
description:
|
||||
'Fetch a single page rendered as clean Markdown. `path` is the page path, e.g. /pl/o-nas.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
path: { type: 'string', description: 'Page path, e.g. /pl/o-nas or /en/about' },
|
||||
},
|
||||
required: ['path'],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
async function runSearch(params: Record<string, unknown>): Promise<string> {
|
||||
const query = typeof params.query === 'string' ? params.query.trim() : ''
|
||||
if (!query) {return 'No query provided.'}
|
||||
const locale =
|
||||
typeof params.locale === 'string' && isValidLocale(params.locale, config)
|
||||
? params.locale
|
||||
: getDefaultLocale(config)
|
||||
const limit = typeof params.limit === 'number' ? params.limit : 10
|
||||
|
||||
const payload = await getCachedPayload()
|
||||
// Shared with the JSON search route — one ranking everywhere.
|
||||
const results = await searchContent({
|
||||
baseUrl: origin,
|
||||
collection,
|
||||
config,
|
||||
limit,
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
summaryField,
|
||||
})
|
||||
if (results.length === 0) {return `No pages matched "${query}".`}
|
||||
return results
|
||||
.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`)
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
async function getPage(params: Record<string, unknown>): Promise<string> {
|
||||
const raw = typeof params.path === 'string' ? params.path.trim() : ''
|
||||
if (!raw) {return 'No path provided.'}
|
||||
const segments = raw
|
||||
.replace(/^\/+|\/+$/g, '')
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
let locale = getDefaultLocale(config)
|
||||
let slug = segments
|
||||
if (segments.length && isValidLocale(segments[0], config)) {
|
||||
locale = segments[0]
|
||||
slug = segments.slice(1)
|
||||
}
|
||||
const payload = await getCachedPayload()
|
||||
const md = await renderMarkdown({ slug, locale, payload })
|
||||
return md ?? `No page found at ${raw}.`
|
||||
}
|
||||
|
||||
async function handleOne(msg: JsonRpcRequest): Promise<null | object> {
|
||||
const { id = null, method, params } = msg
|
||||
|
||||
// Notifications (no id) get no response body.
|
||||
if (id === null && typeof method === 'string' && method.startsWith('notifications/')) {
|
||||
return null
|
||||
}
|
||||
|
||||
switch (method) {
|
||||
case 'initialize': {
|
||||
const requested = (params as { protocolVersion?: string } | undefined)?.protocolVersion
|
||||
return rpcResult(id, {
|
||||
capabilities: { tools: { listChanged: false } },
|
||||
protocolVersion: requested || DEFAULT_PROTOCOL,
|
||||
serverInfo: { name: serverName, version: serverVersion },
|
||||
})
|
||||
}
|
||||
case 'ping':
|
||||
return rpcResult(id, {})
|
||||
case 'tools/call': {
|
||||
const p = (params ?? {}) as { arguments?: Record<string, unknown>; name?: string }
|
||||
const toolArgs = p.arguments ?? {}
|
||||
try {
|
||||
if (p.name === 'search_content') {return rpcResult(id, toolText(await runSearch(toolArgs)))}
|
||||
if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}
|
||||
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))
|
||||
} catch (err) {
|
||||
return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true))
|
||||
}
|
||||
}
|
||||
case 'tools/list':
|
||||
return rpcResult(id, { tools: TOOLS })
|
||||
default:
|
||||
if (id === null) {return null} // unknown notification
|
||||
return rpcError(id, -32601, `Method not found: ${method}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function POST(req: Request): Promise<Response> {
|
||||
let body: unknown
|
||||
try {
|
||||
body = await req.json()
|
||||
} catch {
|
||||
return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })
|
||||
}
|
||||
|
||||
// Batch or single.
|
||||
if (Array.isArray(body)) {
|
||||
const out = (await Promise.all(body.map((m) => handleOne(m as JsonRpcRequest)))).filter(
|
||||
(r): r is object => r !== null,
|
||||
)
|
||||
if (out.length === 0) {return new Response(null, { status: 202 })}
|
||||
return Response.json(out, { headers: { 'cache-control': 'no-store' } })
|
||||
}
|
||||
|
||||
const res = await handleOne(body as JsonRpcRequest)
|
||||
if (res === null) {return new Response(null, { status: 202 })}
|
||||
return Response.json(res, { headers: { 'cache-control': 'no-store' } })
|
||||
}
|
||||
|
||||
// No server→client SSE stream in this read-only server.
|
||||
async function GET(): Promise<Response> {
|
||||
return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
|
||||
headers: { allow: 'POST' },
|
||||
status: 405,
|
||||
})
|
||||
}
|
||||
|
||||
return { GET, POST }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { createMcpRoute } from './createMcpRoute.js'
|
||||
Reference in New Issue
Block a user