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'; function rpcResult(id, result) { return { id, jsonrpc: '2.0', result }; } function rpcError(id, code, message) { return { id, error: { code, message }, jsonrpc: '2.0' }; } function toolText(text, isError = false) { return { content: [ { type: 'text', text } ], ...isError ? { isError: true } : {} }; } export function createMcpRoute(args) { 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) { 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) { 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) { 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?.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 ?? {}; 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) { // 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) { let body; 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)))).filter((r)=>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); 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() { return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', { headers: { allow: 'POST' }, status: 405 }); } return { GET, POST }; } //# sourceMappingURL=createMcpRoute.js.map