import type { BasePayload } from 'payload' import type { PathVisibility } from '../construction/visibility.js' import type { ContentOption } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' import type { ClientIpOptions } from '../shared/rateLimit.js' import { pathOf } from '../construction/visibility.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' export 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 /** * Hide pages the site hides (construction mode): filtered out of list_pages * and search_content, "not found" in get_page. createContentHelpers passes it. */ isPathVisible?: PathVisibility /** 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, isPathVisible, 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 => typeof params.locale === 'string' && isValidLocale(params.locale, config) ? params.locale : getDefaultLocale(config) /** Drops results whose page is hidden right now (construction mode). */ async function visible(items: T[], locale: string): Promise { if (!isPathVisible) {return items} const keep = await Promise.all(items.map((item) => isPathVisible(pathOf(item.url), locale))) return items.filter((_, i) => keep[i]) } 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): Promise { 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): Promise { 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 visible(await collectSiteIndex({ baseUrl: origin, config, content, limit: 1000, // list_pages shows at most 200 — no need to read a huge site whole locales: [locale], pagesSlug: collection, payload, settingsSlug, summaryField, }), locale) 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): Promise { 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 visible(await searchContent({ baseUrl: origin, collection, config, homeSlug: meta?.homeSlug, limit, locale, payload, query, settingsSlug, summaryField, }), locale) if (results.length === 0) {return `No pages matched "${query}".`} return formatResults(results) } async function getPage(params: Record): Promise { 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) } if (isPathVisible) { const path = `/${[...(config.locales.length > 1 ? [locale] : []), ...slug].join('/')}` if (!(await isPathVisible(path, locale))) {return `No page found at ${raw}.`} } 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`, a number, a string… is not a JSON-RPC request — answer, don't crash. if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {return rpcError(null, -32600, 'Invalid Request')} 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; 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('[iapl] 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 { 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 { return Promise.resolve( new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', { headers: { allow: 'POST' }, status: 405, }), ) } return { GET, POST } }