Files
ipal-kit/src/modules/mcp/createMcpRoute.ts
T
radoslaw.smolinskiandClaude Opus 5.5 c9a50abc33 SEO/GEO tools and project requests: site index, IndexNow, page JSON-LD, fixes
GEO / SEO
- collectSiteIndex: one list of public docs per locale (pages + archive
  entries) on sitemap rules; llms.txt/llms-full and MCP list_pages now include
  blog/content entries and every language. Fixes hard-coded "## Strony" heading
  and homepage not collapsing to the locale root in llms.txt.
- Markdown frontmatter: canonical url + updated date.
- Metadata: X/Twitter card, OG image width/height/alt, og:type article with
  published/modified times for entries.
- Fix: Site Settings "defaultShareImage" was never used — now the OG fallback.
- getPageJsonLd (createContentHelpers): WebPage/CollectionPage/BlogPosting,
  BreadcrumbList from the real route, FAQPage via a project mapper.
- IndexNow (opt-in ipalKit({ indexNow: true })): submit published URLs in all
  languages, key generated in Site Integrations or INDEXNOW_KEY, key route.
- sameAs profiles in Site Settings + sameAsUrls(); sitemap <image:image>.

From project reports
- Fix: package exports were missing ./env and ./fluid.css although the docs
  import them (TS2307); regression test checks every documented subpath.
- Fix: plugins run before Payload adds its default users collection, so roles
  and 2FA had nothing to attach to — ipalKit injects an auth collection when
  the project has none (project's own one wins). Audit no longer errors on it.
- createMarkdownRoute, createSubmitAction (/server, headers injected).
- formatOpeningHours (PL/EN/DE text → schema.org), used by
  buildLocalBusinessJsonLd, which also takes a schema.org `type`.
- buildNavigationJsonLd straight from the header global.
- buildCsp googleMaps: full Maps JS API domain set; values de-duplicated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:19:08 +02:00

345 lines
14 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { createMarkdownRenderer, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
import { collectSiteIndex } from '../seo/siteIndex.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.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 four tools:
* - get_site_info({ locale? }) → site name, description, languages, key URLs
* - list_pages({ locale?, limit? }) → every published page (title, url, description)
* - search_content({ query, locale?, limit? }) → matching pages (title, url, description)
* - get_page({ path }) → that page as Markdown
*
* Public on purpose — it exposes exactly what the public site shows (published,
* non-noindex content), so AI assistants can browse it like any visitor.
*
* // 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
/** How to read the client IP for the rate limit — see clientIp(). */
clientIp?: ClientIpOptions
/** Pages collection. Default 'pages'. */
collection?: string
config: I18nConfig
/** Archive-backed collections (same as the plugin option) for get_page. */
content?: ContentOption
getCachedPayload: () => Promise<BasePayload>
/** Max messages in one JSON-RPC batch. Default 10. */
maxBatch?: number
/**
* Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory per instance, or the store from setRateLimitStore). Default { max: 60, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
*/
rateLimit?: { max?: number; windowMs?: number } | false
/** 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,
maxBatch = 10,
serverName = 'ipal-site',
serverVersion = '1.0.0',
settingsSlug = 'site-settings',
summaryField,
} = args
const rl = args.rateLimit === false ? null : { max: 60, windowMs: 60_000, ...args.rateLimit }
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const renderMarkdown = createMarkdownRenderer({ baseUrl: origin || undefined, collection, config, content, settingsSlug })
const localeProp = { type: 'string', description: `Locale code (default ${config.defaultLocale})` }
const TOOLS = [
{
name: 'get_site_info',
description:
'Overview of the site: name, description, available languages and key URLs. Call this first.',
inputSchema: { type: 'object', properties: { locale: localeProp } },
},
{
name: 'list_pages',
description:
'List all published pages and entries (e.g. blog posts) with title, URL and description — the table of contents. Fetch one with get_page.',
inputSchema: {
type: 'object',
properties: {
limit: { type: 'number', description: 'Max results (default 50, max 200)' },
locale: localeProp,
},
},
},
{
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: localeProp,
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'],
},
},
]
const pickLocale = (params: Record<string, unknown>): string =>
typeof params.locale === 'string' && isValidLocale(params.locale, config)
? params.locale
: getDefaultLocale(config)
const formatResults = (results: { description?: string; title: string; url: string }[]) =>
results.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`).join('\n')
async function siteMeta(payload: BasePayload, locale: string) {
try {
return await readSiteMetaConfig({ locale, pagesSlug: collection, payload, settingsSlug })
} catch {
return null
}
}
async function getSiteInfo(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params)
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
// The homepage always collapses to the language root ('/' on single-locale sites).
const home = config.locales.length === 1 ? '/' : `/${locale}`
const lines = [
`Site: ${meta?.siteName || serverName}`,
...(meta?.siteDescription ? [`Description: ${meta.siteDescription}`] : []),
`Languages: ${config.locales.map((l) => `${l.code} (${l.label})`).join(', ')} — default ${config.defaultLocale}`,
`Home: ${origin}${home}`,
...(origin ? [`Sitemap: ${origin}/sitemap.xml`] : []),
'Tools: list_pages (all pages), search_content (keyword search), get_page (one page as Markdown).',
]
return lines.join('\n')
}
async function runList(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params)
const limit = Math.min(Math.max(Math.trunc(typeof params.limit === 'number' ? params.limit : 50) || 50, 1), 200)
const payload = await getCachedPayload()
// Same index as llms.txt and the sitemap rules: pages AND archive entries (blog…).
const index = await collectSiteIndex({
baseUrl: origin,
config,
content,
locales: [locale],
pagesSlug: collection,
payload,
settingsSlug,
summaryField,
})
if (index.length === 0) {return 'No published pages.'}
const shown = index.slice(0, limit)
const lines = shown.map(
(e) => `- ${e.title} (${e.url})${e.description ? ` — ${e.description}` : ''}${e.collection === collection ? '' : ` [${e.collectionLabel}]`}`,
)
if (index.length > shown.length) {lines.push(`… ${index.length - shown.length} more — raise limit (max 200) or use search_content.`)}
return lines.join('\n')
}
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 = pickLocale(params)
const limit = typeof params.limit === 'number' ? params.limit : 10
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
// Shared with the JSON search route — one ranking everywhere.
const results = await searchContent({
baseUrl: origin,
collection,
config,
homeSlug: meta?.homeSlug,
limit,
locale,
payload,
query,
summaryField,
})
if (results.length === 0) {return `No pages matched "${query}".`}
return formatResults(results)
}
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 === 'get_site_info') {return rpcResult(id, toolText(await getSiteInfo(toolArgs)))}
if (p.name === 'list_pages') {return rpcResult(id, toolText(await runList(toolArgs)))}
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) {
// Log the real error server-side; return a GENERIC message to the
// (anonymous) caller so internal details — DB schema, host, stack —
// never leak over a public endpoint.
console.warn('[ipal] createMcpRoute: tool execution failed:', err)
return rpcResult(id, toolText('Tool execution failed.', 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 })
}
// Limits: a batch counts as many requests as it has messages, and is capped —
// otherwise one POST could carry hundreds of tool calls (DB queries).
const messages = Array.isArray(body) ? body.length : 1
if (Array.isArray(body) && body.length > maxBatch) {
return Response.json(rpcError(null, -32600, `Batch too large (max ${maxBatch})`), { status: 400 })
}
if (rl) {
const limit = await consumeRateLimit({ cost: messages, key: clientIp(req, args.clientIp), scope: 'mcp', ...rl })
if (!limit.ok) {
return tooManyRequests(limit.retryAfter, rpcError(null, -32000, 'Too many requests'))
}
}
// 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.
function GET(): Promise<Response> {
return Promise.resolve(
new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
headers: { allow: 'POST' },
status: 405,
}),
)
}
return { GET, POST }
}