@innflows/ai-readiness-audit 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.mjs ADDED
@@ -0,0 +1,1403 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @innflows/ai-readiness-audit — Zero-dependency CLI & MCP Server for Generative Engine Optimization (GEO) website audits.
4
+ * Maintained by Innflows (https://www.innflows.com), a Generative Engine Optimization (GEO) platform.
5
+ */
6
+ import dns from "node:dns/promises";
7
+ import net from "node:net";
8
+ import readline from "node:readline";
9
+
10
+ export const AI_CRAWLERS = [
11
+ "OAI-SearchBot",
12
+ "GPTBot",
13
+ "ChatGPT-User",
14
+ "Googlebot",
15
+ "Google-Extended",
16
+ "ClaudeBot",
17
+ "PerplexityBot",
18
+ "Bingbot",
19
+ "Applebot-Extended",
20
+ ];
21
+
22
+ export const PROBE_USER_AGENTS = {
23
+ "Browser-Baseline":
24
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
25
+ "OAI-SearchBot": "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-SearchBot/1.0; +https://openai.com/searchbot",
26
+ GPTBot: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; GPTBot/1.1; +https://openai.com/gptbot",
27
+ "ChatGPT-User": "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot",
28
+ ClaudeBot: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)",
29
+ PerplexityBot: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot)",
30
+ "Google-Extended": "Mozilla/5.0 (compatible; Google-Extended/1.0; +http://www.google.com/bot.html)",
31
+ "Applebot-Extended": "Mozilla/5.0 (Applebot-Extended/0.3; +http://www.apple.com/go/applebot)",
32
+ };
33
+
34
+ export const PKG_VERSION = "0.3.0";
35
+
36
+ function isPrivateIp(ip) {
37
+ if (net.isIPv4(ip)) {
38
+ const parts = ip.split(".").map(Number);
39
+ if (parts[0] === 10 || parts[0] === 127 || parts[0] === 0) return true;
40
+ if (parts[0] === 169 && parts[1] === 254) return true;
41
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
42
+ if (parts[0] === 192 && parts[1] === 168) return true;
43
+ if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) return true;
44
+ return false;
45
+ }
46
+ if (net.isIPv6(ip)) {
47
+ const norm = ip.toLowerCase();
48
+ return (
49
+ norm === "::1" ||
50
+ norm === "::" ||
51
+ norm.startsWith("fc") ||
52
+ norm.startsWith("fd") ||
53
+ norm.startsWith("fe80") ||
54
+ norm.startsWith("::ffff:127.") ||
55
+ norm.startsWith("::ffff:10.") ||
56
+ norm.startsWith("::ffff:192.168.")
57
+ );
58
+ }
59
+ return false;
60
+ }
61
+
62
+ async function assertPublicHost(hostname) {
63
+ const lower = hostname.toLowerCase();
64
+ if (lower === "localhost" || lower.endsWith(".local") || lower.endsWith(".internal")) {
65
+ throw new Error(`Blocked non-public hostname: ${hostname}`);
66
+ }
67
+ if (net.isIP(hostname)) {
68
+ if (isPrivateIp(hostname)) throw new Error(`Blocked private IP: ${hostname}`);
69
+ return;
70
+ }
71
+ const addrs = await dns.lookup(hostname, { all: true });
72
+ if (!addrs.length) throw new Error(`Unable to resolve hostname: ${hostname}`);
73
+ for (const a of addrs) {
74
+ if (isPrivateIp(a.address)) {
75
+ throw new Error(`Blocked hostname resolving to private IP: ${hostname}`);
76
+ }
77
+ }
78
+ }
79
+
80
+ function normalizeUrlInput(targetUrl) {
81
+ const normalized = String(targetUrl || "").trim();
82
+ if (!normalized) throw new Error("Empty URL");
83
+ const withProto = normalized.includes("://") ? normalized : `https://${normalized}`;
84
+ const parsed = new URL(withProto);
85
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
86
+ throw new Error(`Unsupported URL protocol: ${parsed.protocol}`);
87
+ }
88
+ if (!parsed.pathname) parsed.pathname = "/";
89
+ return {
90
+ parsed,
91
+ origin: `${parsed.protocol}//${parsed.host}`,
92
+ pageUrl: parsed.toString(),
93
+ };
94
+ }
95
+
96
+ export function parseRobotsRules(robotsTxt) {
97
+ const groups = [];
98
+ let currentAgents = [];
99
+ let currentRules = [];
100
+
101
+ for (const rawLine of String(robotsTxt || "").split(/\r?\n/)) {
102
+ const line = rawLine.split("#", 1)[0].trim();
103
+ const colonIdx = line.indexOf(":");
104
+ if (!line || colonIdx === -1) continue;
105
+ const key = line.slice(0, colonIdx).trim().toLowerCase();
106
+ const val = line.slice(colonIdx + 1).trim();
107
+ if (key === "user-agent") {
108
+ if (currentRules.length > 0) {
109
+ groups.push([currentAgents, currentRules]);
110
+ currentAgents = [];
111
+ currentRules = [];
112
+ }
113
+ currentAgents.push(val.toLowerCase());
114
+ } else if (key === "allow" || key === "disallow") {
115
+ currentRules.push([key, val]);
116
+ }
117
+ }
118
+ if (currentAgents.length > 0 || currentRules.length > 0) {
119
+ groups.push([currentAgents, currentRules]);
120
+ }
121
+
122
+ function postureFor(agent) {
123
+ const al = agent.toLowerCase();
124
+ let matched = groups.filter(([agents]) => agents.includes(al)).map(([, rules]) => rules);
125
+ if (matched.length === 0) {
126
+ matched = groups.filter(([agents]) => agents.includes("*")).map(([, rules]) => rules);
127
+ }
128
+ if (matched.length === 0) return "allowed_default";
129
+ const rules = matched.flat();
130
+ const blocking = rules.some(([kind, p]) => kind === "disallow" && p === "/");
131
+ const allowing = rules.some(([kind, p]) => kind === "allow" && p === "/");
132
+ return blocking && !allowing ? "blocked" : "allowed";
133
+ }
134
+
135
+ return Object.fromEntries(AI_CRAWLERS.map((bot) => [bot, postureFor(bot)]));
136
+ }
137
+
138
+ function extractAttr(tagHtml, attrName) {
139
+ const re = new RegExp(`\\b${attrName}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i");
140
+ const m = tagHtml.match(re);
141
+ return m ? (m[1] ?? m[2] ?? m[3] ?? "").trim() : "";
142
+ }
143
+
144
+ function stripVisibleText(html) {
145
+ return String(html || "")
146
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, " ")
147
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, " ")
148
+ .replace(/<noscript\b[^>]*>[\s\S]*?<\/noscript>/gi, " ")
149
+ .replace(/<!--[\s\S]*?-->/g, " ")
150
+ .replace(/<[^>]+>/g, " ")
151
+ .replace(/\s+/g, " ")
152
+ .trim();
153
+ }
154
+
155
+ export function extractSchemaGraphFromHtml(html) {
156
+ const src = String(html || "");
157
+ const jsonLdBlocks = [];
158
+ const ldRegex = /<script\b[^>]*type\s*=\s*["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script>/gi;
159
+ let m;
160
+ while ((m = ldRegex.exec(src)) !== null) {
161
+ if (m[1] && m[1].trim()) jsonLdBlocks.push(m[1].trim());
162
+ }
163
+
164
+ const entities = [];
165
+ const definedIds = new Set();
166
+ const referencedIds = new Set();
167
+ const sameAsUrls = new Set();
168
+ let parseErrors = 0;
169
+
170
+ function walk(node, isTopEntity = true) {
171
+ if (!node) return;
172
+ if (Array.isArray(node)) {
173
+ for (const sub of node) walk(sub, isTopEntity);
174
+ return;
175
+ }
176
+ if (typeof node !== "object") return;
177
+
178
+ if (Array.isArray(node["@graph"])) {
179
+ for (const sub of node["@graph"]) walk(sub, true);
180
+ }
181
+
182
+ const rawType = node["@type"];
183
+ const types = typeof rawType === "string" ? [rawType] : Array.isArray(rawType) ? rawType.map(String) : [];
184
+ const nodeId = typeof node["@id"] === "string" ? node["@id"].trim() : "";
185
+
186
+ // Pure @id reference object (no @type and few keys)
187
+ if (nodeId && types.length === 0 && Object.keys(node).length <= 2) {
188
+ referencedIds.add(nodeId);
189
+ return;
190
+ }
191
+
192
+ if (nodeId) definedIds.add(nodeId);
193
+
194
+ if (types.length > 0) {
195
+ const sameAsRaw = node.sameAs;
196
+ const nodeSameAs = [];
197
+ if (typeof sameAsRaw === "string" && sameAsRaw.trim()) {
198
+ nodeSameAs.push(sameAsRaw.trim());
199
+ } else if (Array.isArray(sameAsRaw)) {
200
+ for (const u of sameAsRaw) {
201
+ if (typeof u === "string" && u.trim()) nodeSameAs.push(u.trim());
202
+ }
203
+ }
204
+ for (const u of nodeSameAs) sameAsUrls.add(u);
205
+
206
+ entities.push({
207
+ types,
208
+ id: nodeId || null,
209
+ name: typeof node.name === "string" ? node.name : typeof node.headline === "string" ? node.headline : null,
210
+ url: typeof node.url === "string" ? node.url : null,
211
+ sameAsCount: nodeSameAs.length,
212
+ });
213
+ }
214
+
215
+ for (const [k, v] of Object.entries(node)) {
216
+ if (k === "@graph" || k === "@context" || k === "@type" || k === "@id") continue;
217
+ if (v && typeof v === "object") {
218
+ walk(v, false);
219
+ }
220
+ }
221
+ }
222
+
223
+ for (const block of jsonLdBlocks) {
224
+ try {
225
+ walk(JSON.parse(block), true);
226
+ } catch {
227
+ parseErrors += 1;
228
+ }
229
+ }
230
+
231
+ const allTypes = entities.flatMap((e) => e.types);
232
+ const danglingIds = [...referencedIds].filter((ref) => ref.includes("#") && !definedIds.has(ref));
233
+
234
+ return {
235
+ blocks_count: jsonLdBlocks.length,
236
+ parse_errors: parseErrors,
237
+ entities,
238
+ schema_types: allTypes,
239
+ unique_types: [...new Set(allTypes)],
240
+ defined_ids: [...definedIds],
241
+ referenced_ids: [...referencedIds],
242
+ dangling_ids: danglingIds,
243
+ same_as_urls: [...sameAsUrls],
244
+ };
245
+ }
246
+
247
+ export function inspectHtmlDocument(html) {
248
+ const src = String(html || "");
249
+ const titleMatch = src.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i);
250
+ const title = titleMatch ? titleMatch[1].replace(/\s+/g, " ").trim() : "";
251
+
252
+ let metaDescription = "";
253
+ let metaRobots = "";
254
+ for (const tagMatch of src.matchAll(/<meta\b[^>]*>/gi)) {
255
+ const tag = tagMatch[0];
256
+ const name = extractAttr(tag, "name").toLowerCase();
257
+ if (name === "description" && !metaDescription) {
258
+ metaDescription = extractAttr(tag, "content");
259
+ } else if (name === "robots" && !metaRobots) {
260
+ metaRobots = extractAttr(tag, "content");
261
+ }
262
+ }
263
+
264
+ let canonical = "";
265
+ for (const linkMatch of src.matchAll(/<link\b[^>]*>/gi)) {
266
+ const tag = linkMatch[0];
267
+ const rels = extractAttr(tag, "rel").toLowerCase().split(/\s+/);
268
+ if (rels.includes("canonical") && !canonical) {
269
+ canonical = extractAttr(tag, "href");
270
+ }
271
+ }
272
+
273
+ const stripped = stripVisibleText(src);
274
+ const graph = extractSchemaGraphFromHtml(src);
275
+
276
+ return {
277
+ title,
278
+ meta_description: metaDescription,
279
+ meta_robots: metaRobots,
280
+ canonical,
281
+ visible_text_chars: stripped.length,
282
+ schema_types: graph.schema_types,
283
+ schema_ids: graph.defined_ids,
284
+ };
285
+ }
286
+
287
+ export function parseLlmsTxtDocument(content) {
288
+ const raw = String(content || "");
289
+ const trimmed = raw.trim();
290
+ const looksLikeHtml = /^<!doctype\s+html/i.test(trimmed) || /^<html\b/i.test(trimmed);
291
+ const lines = raw.split(/\r?\n/);
292
+
293
+ let h1Title = "";
294
+ let blockquoteSummary = "";
295
+ const sections = [];
296
+ const links = [];
297
+
298
+ let currentSection = "Root";
299
+ const mdLinkRe = /^\s*[-*]\s+\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)(?:\s*(?::|—|–|-)\s*(.*))?$/;
300
+ const bareLinkRe = /^\s*[-*]\s+([^:\n]+?):\s+(https?:\/\/[^\s)]+)(?:\s*(?:—|–|-)\s*(.*))?$/;
301
+
302
+ for (const line of lines) {
303
+ const t = line.trim();
304
+ if (!h1Title && /^#\s+/.test(t) && !/^##/.test(t)) {
305
+ h1Title = t.replace(/^#\s+/, "").trim();
306
+ continue;
307
+ }
308
+ if (!blockquoteSummary && /^>\s+/.test(t)) {
309
+ blockquoteSummary = t.replace(/^>\s+/, "").trim();
310
+ continue;
311
+ }
312
+ if (/^##\s+/.test(t)) {
313
+ currentSection = t.replace(/^##\s+/, "").trim();
314
+ sections.push(currentSection);
315
+ continue;
316
+ }
317
+ const lm = line.match(mdLinkRe) || line.match(bareLinkRe);
318
+ if (lm) {
319
+ links.push({
320
+ section: currentSection,
321
+ title: lm[1].replace(/^\*\*|\*\*$/g, "").trim(),
322
+ url: lm[2].trim(),
323
+ description: (lm[3] || "").trim(),
324
+ });
325
+ }
326
+ }
327
+
328
+ const issues = [];
329
+ if (!trimmed) issues.push("Empty /llms.txt body");
330
+ if (looksLikeHtml) issues.push("Response is an HTML document (SPA soft-200 fallback) instead of plain Markdown");
331
+ if (!looksLikeHtml && trimmed) {
332
+ if (!h1Title) issues.push("Missing required top-level '# Title' H1 heading");
333
+ if (!blockquoteSummary) issues.push("Missing recommended '> Summary' blockquote description");
334
+ if (sections.length === 0) issues.push("No '## Section' headings found");
335
+ if (links.length === 0) issues.push("No Markdown list links ('- [Title](https://...): description') found");
336
+ }
337
+
338
+ return {
339
+ valid_spec: !looksLikeHtml && Boolean(h1Title) && links.length > 0,
340
+ is_html_fallback: looksLikeHtml,
341
+ char_length: raw.length,
342
+ h1_title: h1Title || null,
343
+ blockquote_summary: blockquoteSummary || null,
344
+ sections,
345
+ links_count: links.length,
346
+ links,
347
+ issues,
348
+ };
349
+ }
350
+
351
+ export function detectWafChallenge(status, headers, body) {
352
+ const lower = String(body || "").slice(0, 8000).toLowerCase();
353
+ const cfMitigated = (headers["cf-mitigated"] || "").toLowerCase();
354
+ if (cfMitigated.includes("challenge")) return "cloudflare_challenge_header";
355
+ if (
356
+ (status === 403 || status === 429 || status === 503) &&
357
+ (lower.includes("just a moment...") ||
358
+ lower.includes("cf-browser-verification") ||
359
+ lower.includes("challenge-platform") ||
360
+ lower.includes("attention required! | cloudflare") ||
361
+ lower.includes("access denied") ||
362
+ lower.includes("bot verification"))
363
+ ) {
364
+ return "waf_or_bot_challenge";
365
+ }
366
+ if (status === 403) return "http_403_forbidden";
367
+ if (status === 429) return "http_429_rate_limited";
368
+ if (status === 401) return "http_401_unauthorized";
369
+ return null;
370
+ }
371
+
372
+ async function fetchResource(urlStr, timeoutSec = 12, customUserAgent = null) {
373
+ const parsed = new URL(urlStr);
374
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
375
+ throw new Error(`Unsupported URL protocol: ${parsed.protocol}`);
376
+ }
377
+ await assertPublicHost(parsed.hostname);
378
+ const controller = new AbortController();
379
+ const timer = setTimeout(() => controller.abort(), timeoutSec * 1000);
380
+ try {
381
+ const resp = await fetch(parsed.toString(), {
382
+ signal: controller.signal,
383
+ redirect: "follow",
384
+ headers: {
385
+ "User-Agent": customUserAgent || `Innflows-AI-Readiness-Audit/${PKG_VERSION} (+https://www.innflows.com)`,
386
+ Accept: "text/html,text/plain,application/xml;q=0.9,*/*;q=0.8",
387
+ },
388
+ });
389
+ const finalUrl = new URL(resp.url);
390
+ await assertPublicHost(finalUrl.hostname);
391
+ const headers = {};
392
+ resp.headers.forEach((v, k) => {
393
+ headers[k.toLowerCase()] = v;
394
+ });
395
+ const buf = await resp.arrayBuffer();
396
+ const slice = buf.byteLength > 1_500_000 ? buf.slice(0, 1_500_000) : buf;
397
+ const body = new TextDecoder("utf-8", { fatal: false }).decode(slice);
398
+ return { status: resp.status, finalUrl: finalUrl.toString(), headers, body };
399
+ } catch {
400
+ return { status: 0, finalUrl: urlStr, headers: {}, body: "" };
401
+ } finally {
402
+ clearTimeout(timer);
403
+ }
404
+ }
405
+
406
+ export async function runAudit(targetUrl, timeoutSec = 12) {
407
+ const { origin, pageUrl } = normalizeUrlInput(targetUrl);
408
+
409
+ const checks = [];
410
+ const page = await fetchResource(pageUrl, timeoutSec);
411
+ if (page.status !== 200 || !page.body) {
412
+ checks.push({
413
+ id: "http_status",
414
+ name: "Target Page Reachability",
415
+ status: "fail",
416
+ detail: `HTTP status ${page.status}`,
417
+ });
418
+ return { url: pageUrl, origin, score: 0, passed: 0, total: checks.length, checks };
419
+ }
420
+
421
+ checks.push({ id: "http_status", name: "Target Page Reachability", status: "pass", detail: "HTTP 200 OK" });
422
+ const info = inspectHtmlDocument(page.body);
423
+
424
+ const robotsCombined = `${info.meta_robots} ${page.headers["x-robots-tag"] || ""}`.toLowerCase();
425
+ if (robotsCombined.includes("noindex")) {
426
+ checks.push({
427
+ id: "indexable",
428
+ name: "Indexability Directive",
429
+ status: "fail",
430
+ detail: `Blocked by noindex (${robotsCombined.trim()})`,
431
+ });
432
+ } else {
433
+ checks.push({ id: "indexable", name: "Indexability Directive", status: "pass", detail: "Page allows search indexing" });
434
+ }
435
+
436
+ const chars = info.visible_text_chars;
437
+ if (chars >= 1200) {
438
+ checks.push({
439
+ id: "ssr_text",
440
+ name: "SSR HTML Text Extractability",
441
+ status: "pass",
442
+ detail: `${chars} visible characters in initial HTML`,
443
+ });
444
+ } else if (chars >= 300) {
445
+ checks.push({
446
+ id: "ssr_text",
447
+ name: "SSR HTML Text Extractability",
448
+ status: "warn",
449
+ detail: `Only ${chars} visible characters in initial HTML (check client-only tabs)`,
450
+ });
451
+ } else {
452
+ checks.push({
453
+ id: "ssr_text",
454
+ name: "SSR HTML Text Extractability",
455
+ status: "fail",
456
+ detail: `Only ${chars} visible characters in initial HTML (likely client-rendered shell)`,
457
+ });
458
+ }
459
+
460
+ if (info.canonical) {
461
+ checks.push({ id: "canonical", name: "Canonical URL", status: "pass", detail: info.canonical });
462
+ } else {
463
+ checks.push({ id: "canonical", name: "Canonical URL", status: "warn", detail: "Missing <link rel='canonical'>" });
464
+ }
465
+
466
+ if (info.title && info.meta_description) {
467
+ checks.push({
468
+ id: "meta_tags",
469
+ name: "Title & Meta Description",
470
+ status: "pass",
471
+ detail: `Title (${info.title.length} chars) & meta description present`,
472
+ });
473
+ } else {
474
+ checks.push({
475
+ id: "meta_tags",
476
+ name: "Title & Meta Description",
477
+ status: "warn",
478
+ detail: "Missing <title> or <meta name='description'>",
479
+ });
480
+ }
481
+
482
+ const uniqueTypes = [...new Set(info.schema_types)];
483
+ if (uniqueTypes.length > 0) {
484
+ const idNote =
485
+ info.schema_ids.length > 0
486
+ ? ` with @id (${info.schema_ids.length})`
487
+ : " (consider adding @id entity anchors)";
488
+ checks.push({
489
+ id: "json_ld",
490
+ name: "Schema.org JSON-LD",
491
+ status: "pass",
492
+ detail: `Detected ${uniqueTypes.join(", ")}${idNote}`,
493
+ });
494
+ } else {
495
+ checks.push({
496
+ id: "json_ld",
497
+ name: "Schema.org JSON-LD",
498
+ status: "warn",
499
+ detail: "No application/ld+json structured data found",
500
+ });
501
+ }
502
+
503
+ const [robotsRes, llmsRes, sitemapRes] = await Promise.all([
504
+ fetchResource(`${origin}/robots.txt`, timeoutSec),
505
+ fetchResource(`${origin}/llms.txt`, timeoutSec),
506
+ fetchResource(`${origin}/sitemap.xml`, timeoutSec),
507
+ ]);
508
+
509
+ if (robotsRes.status === 200 && robotsRes.body) {
510
+ const posture = parseRobotsRules(robotsRes.body);
511
+ const blocked = Object.entries(posture)
512
+ .filter(([, state]) => state === "blocked")
513
+ .map(([bot]) => bot);
514
+ if (blocked.length > 0) {
515
+ checks.push({
516
+ id: "ai_crawlers",
517
+ name: "AI Crawler Access (robots.txt)",
518
+ status: "warn",
519
+ detail: `Blocked crawlers: ${blocked.join(", ")}`,
520
+ });
521
+ } else {
522
+ checks.push({
523
+ id: "ai_crawlers",
524
+ name: "AI Crawler Access (robots.txt)",
525
+ status: "pass",
526
+ detail: `All ${AI_CRAWLERS.length} checked AI search/grounding crawlers allowed`,
527
+ });
528
+ }
529
+ } else {
530
+ checks.push({
531
+ id: "ai_crawlers",
532
+ name: "AI Crawler Access (robots.txt)",
533
+ status: "warn",
534
+ detail: `/robots.txt returned HTTP ${robotsRes.status}`,
535
+ });
536
+ }
537
+
538
+ if (llmsRes.status === 200 && llmsRes.body.trim().length > 80) {
539
+ const parsedLlms = parseLlmsTxtDocument(llmsRes.body);
540
+ if (parsedLlms.is_html_fallback) {
541
+ checks.push({
542
+ id: "llms_txt",
543
+ name: "llms.txt Machine Summary",
544
+ status: "warn",
545
+ detail: "/llms.txt returns HTML fallback instead of plain Markdown",
546
+ });
547
+ } else {
548
+ checks.push({
549
+ id: "llms_txt",
550
+ name: "llms.txt Machine Summary",
551
+ status: "pass",
552
+ detail: `/llms.txt present (${llmsRes.body.length} chars, ${parsedLlms.links_count} links)`,
553
+ });
554
+ }
555
+ } else {
556
+ checks.push({
557
+ id: "llms_txt",
558
+ name: "llms.txt Machine Summary",
559
+ status: "warn",
560
+ detail: "/llms.txt not found or empty",
561
+ });
562
+ }
563
+
564
+ if (sitemapRes.status === 200 && sitemapRes.body.includes("<loc>")) {
565
+ const locCount = (sitemapRes.body.match(/<loc>/g) || []).length;
566
+ checks.push({
567
+ id: "sitemap_xml",
568
+ name: "XML Sitemap",
569
+ status: "pass",
570
+ detail: `/sitemap.xml present (${locCount} URLs)`,
571
+ });
572
+ } else {
573
+ checks.push({
574
+ id: "sitemap_xml",
575
+ name: "XML Sitemap",
576
+ status: "warn",
577
+ detail: `/sitemap.xml missing or invalid (HTTP ${sitemapRes.status})`,
578
+ });
579
+ }
580
+
581
+ const passed = checks.filter((c) => c.status === "pass").length;
582
+ const score = Math.round((passed / checks.length) * 100);
583
+ return {
584
+ url: pageUrl,
585
+ origin,
586
+ score,
587
+ passed,
588
+ total: checks.length,
589
+ checks,
590
+ platform: "https://www.innflows.com/platform/website-ai-audit",
591
+ };
592
+ }
593
+
594
+ export async function probeCrawlerAccess(targetUrl, timeoutSec = 12) {
595
+ const { origin, pageUrl } = normalizeUrlInput(targetUrl);
596
+ const robotsRes = await fetchResource(`${origin}/robots.txt`, timeoutSec);
597
+ const robotsPosture = robotsRes.status === 200 && robotsRes.body ? parseRobotsRules(robotsRes.body) : {};
598
+
599
+ const entries = Object.entries(PROBE_USER_AGENTS);
600
+ const probeResults = await Promise.all(
601
+ entries.map(async ([botName, ua]) => {
602
+ const res = await fetchResource(pageUrl, timeoutSec, ua);
603
+ const visibleChars = res.body ? stripVisibleText(res.body).length : 0;
604
+ const wafReason = detectWafChallenge(res.status, res.headers, res.body);
605
+ const robotsRule = botName === "Browser-Baseline" ? "n/a" : robotsPosture[botName] || "unknown";
606
+ const silentBlock =
607
+ botName !== "Browser-Baseline" &&
608
+ robotsRule !== "blocked" &&
609
+ (res.status !== 200 || Boolean(wafReason));
610
+
611
+ return {
612
+ agent: botName,
613
+ robots_txt_posture: robotsRule,
614
+ http_status: res.status,
615
+ visible_text_chars: visibleChars,
616
+ server_header: res.headers["server"] || null,
617
+ waf_diagnosis: wafReason,
618
+ silent_waf_block: silentBlock,
619
+ };
620
+ })
621
+ );
622
+
623
+ const baseline = probeResults.find((r) => r.agent === "Browser-Baseline");
624
+ const silentBlockedAgents = probeResults.filter((r) => r.silent_waf_block).map((r) => r.agent);
625
+
626
+ return {
627
+ url: pageUrl,
628
+ origin,
629
+ robots_txt_status: robotsRes.status,
630
+ baseline_status: baseline ? baseline.http_status : 0,
631
+ baseline_visible_chars: baseline ? baseline.visible_text_chars : 0,
632
+ silent_waf_blocks_detected: silentBlockedAgents.length > 0,
633
+ silent_blocked_agents: silentBlockedAgents,
634
+ probes: probeResults,
635
+ platform: "https://www.innflows.com/platform/website-ai-audit",
636
+ };
637
+ }
638
+
639
+ function classifyPathSection(pathname) {
640
+ const seg = pathname.split("/").filter(Boolean)[0]?.toLowerCase() || "";
641
+ if (!seg) return "Core Pages";
642
+ if (["docs", "documentation", "guide", "guides", "reference", "api", "developers"].includes(seg)) return "Documentation";
643
+ if (["platform", "product", "products", "features", "solutions", "integrations", "pricing"].includes(seg)) return "Product & Pricing";
644
+ if (["blog", "research", "articles", "news", "insights", "resources"].includes(seg)) return "Research & Blog";
645
+ return "Key Pages";
646
+ }
647
+
648
+ export async function inspectOrGenerateLlmsTxt(targetUrl, options = {}) {
649
+ const mode = options.mode === "generate" ? "generate" : "validate";
650
+ const maxLinks = Math.min(Math.max(Number(options.maxLinks || 20), 5), 50);
651
+ const timeoutSec = Number(options.timeoutSec || 12);
652
+ const { parsed, origin, pageUrl } = normalizeUrlInput(targetUrl);
653
+
654
+ if (mode === "validate") {
655
+ const llmsUrl = parsed.pathname.endsWith(".txt") ? pageUrl : `${origin}/llms.txt`;
656
+ const [llmsRes, fullRes] = await Promise.all([
657
+ fetchResource(llmsUrl, timeoutSec),
658
+ fetchResource(`${origin}/llms-full.txt`, timeoutSec),
659
+ ]);
660
+
661
+ if (llmsRes.status !== 200 || !llmsRes.body) {
662
+ return {
663
+ mode: "validate",
664
+ url: llmsUrl,
665
+ origin,
666
+ http_status: llmsRes.status,
667
+ has_llms_full_txt: fullRes.status === 200 && fullRes.body.length > 80,
668
+ valid_spec: false,
669
+ issues: [`${llmsUrl} returned HTTP ${llmsRes.status}`],
670
+ hint: "Run with mode='generate' (or CLI --generate) to synthesize a starter /llms.txt from your homepage and sitemap.xml.",
671
+ };
672
+ }
673
+
674
+ const report = parseLlmsTxtDocument(llmsRes.body);
675
+ const sampleLinks = report.links.slice(0, 8);
676
+ const linkChecks = await Promise.all(
677
+ sampleLinks.map(async (item) => {
678
+ const r = await fetchResource(item.url, Math.min(timeoutSec, 8));
679
+ return { url: item.url, title: item.title, http_status: r.status, ok: r.status >= 200 && r.status < 400 };
680
+ })
681
+ );
682
+ const brokenLinks = linkChecks.filter((c) => !c.ok);
683
+ if (brokenLinks.length > 0) {
684
+ report.issues.push(`${brokenLinks.length}/${linkChecks.length} sampled links returned non-2xx/3xx status`);
685
+ }
686
+
687
+ return {
688
+ mode: "validate",
689
+ url: llmsUrl,
690
+ origin,
691
+ http_status: llmsRes.status,
692
+ has_llms_full_txt: fullRes.status === 200 && fullRes.body.length > 80 && !parseLlmsTxtDocument(fullRes.body).is_html_fallback,
693
+ ...report,
694
+ sampled_link_checks: linkChecks,
695
+ platform: "https://www.innflows.com/platform/website-ai-audit",
696
+ };
697
+ }
698
+
699
+ // mode === "generate"
700
+ const [homeRes, sitemapRes] = await Promise.all([
701
+ fetchResource(pageUrl, timeoutSec),
702
+ fetchResource(`${origin}/sitemap.xml`, timeoutSec),
703
+ ]);
704
+
705
+ const homeInfo = homeRes.body ? inspectHtmlDocument(homeRes.body) : { title: parsed.hostname, meta_description: "" };
706
+ const candidateUrls = new Set([`${origin}/`]);
707
+
708
+ if (sitemapRes.status === 200 && sitemapRes.body) {
709
+ for (const m of sitemapRes.body.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/gi)) {
710
+ try {
711
+ const u = new URL(m[1].trim());
712
+ if (u.origin === origin && !u.pathname.endsWith(".xml")) {
713
+ candidateUrls.add(u.toString());
714
+ }
715
+ } catch {
716
+ // ignore invalid URL
717
+ }
718
+ if (candidateUrls.size >= maxLinks * 3) break;
719
+ }
720
+ }
721
+
722
+ if (homeRes.body && candidateUrls.size < maxLinks) {
723
+ for (const m of homeRes.body.matchAll(/<a\b[^>]*href\s*=\s*["']([^"'#]+)["']/gi)) {
724
+ try {
725
+ const u = new URL(m[1].trim(), origin);
726
+ if (u.origin === origin && (u.protocol === "https:" || u.protocol === "http:")) {
727
+ candidateUrls.add(u.toString());
728
+ }
729
+ } catch {
730
+ // ignore
731
+ }
732
+ if (candidateUrls.size >= maxLinks * 2) break;
733
+ }
734
+ }
735
+
736
+ const selectedUrls = [...candidateUrls].slice(0, maxLinks);
737
+ const pageSummaries = await Promise.all(
738
+ selectedUrls.map(async (u) => {
739
+ if (u === pageUrl && homeRes.body) {
740
+ return {
741
+ url: u,
742
+ pathname: new URL(u).pathname,
743
+ title: homeInfo.title || parsed.hostname,
744
+ description: homeInfo.meta_description || "Official homepage",
745
+ ok: homeRes.status === 200,
746
+ };
747
+ }
748
+ const r = await fetchResource(u, Math.min(timeoutSec, 8));
749
+ if (r.status !== 200 || !r.body) return { url: u, pathname: new URL(u).pathname, ok: false };
750
+ const inf = inspectHtmlDocument(r.body);
751
+ return {
752
+ url: u,
753
+ pathname: new URL(u).pathname,
754
+ title: inf.title || new URL(u).pathname,
755
+ description: inf.meta_description || "",
756
+ ok: true,
757
+ };
758
+ })
759
+ );
760
+
761
+ const validPages = pageSummaries.filter((p) => p.ok);
762
+ const grouped = new Map();
763
+ for (const p of validPages) {
764
+ const sec = classifyPathSection(p.pathname);
765
+ if (!grouped.has(sec)) grouped.set(sec, []);
766
+ grouped.get(sec).push(p);
767
+ }
768
+
769
+ const siteTitle = homeInfo.title ? homeInfo.title.split(/\s+[|\-–—]\s+/)[0].trim() : parsed.hostname;
770
+ const summaryLine =
771
+ homeInfo.meta_description || `Machine-readable index of ${siteTitle} (${origin}) for AI search engines and LLM agents.`;
772
+
773
+ const mdLines = [`# ${siteTitle}`, "", `> ${summaryLine}`, ""];
774
+ for (const [sec, items] of grouped.entries()) {
775
+ mdLines.push(`## ${sec}`, "");
776
+ for (const item of items) {
777
+ const descSuffix = item.description ? `: ${item.description.replace(/\s+/g, " ").slice(0, 160)}` : "";
778
+ mdLines.push(`- [${item.title}](${item.url})${descSuffix}`);
779
+ }
780
+ mdLines.push("");
781
+ }
782
+
783
+ return {
784
+ mode: "generate",
785
+ origin,
786
+ pages_indexed: validPages.length,
787
+ generated_markdown: mdLines.join("\n").trim() + "\n",
788
+ platform: "https://www.innflows.com/platform/website-ai-audit",
789
+ };
790
+ }
791
+
792
+ export async function inspectSchemaEntityGraph(targetUrl, timeoutSec = 12) {
793
+ const { origin, pageUrl } = normalizeUrlInput(targetUrl);
794
+ const page = await fetchResource(pageUrl, timeoutSec);
795
+ if (page.status !== 200 || !page.body) {
796
+ return {
797
+ url: pageUrl,
798
+ origin,
799
+ http_status: page.status,
800
+ error: `Target URL returned HTTP ${page.status}`,
801
+ };
802
+ }
803
+
804
+ const info = inspectHtmlDocument(page.body);
805
+ const graph = extractSchemaGraphFromHtml(page.body);
806
+
807
+ const recommended = ["Organization", "WebSite"];
808
+ const typeSet = new Set(graph.unique_types);
809
+ const hasAppOrProductOrArticle =
810
+ typeSet.has("SoftwareApplication") ||
811
+ typeSet.has("WebApplication") ||
812
+ typeSet.has("Product") ||
813
+ typeSet.has("Article") ||
814
+ typeSet.has("BlogPosting") ||
815
+ typeSet.has("TechArticle");
816
+
817
+ const missingCore = recommended.filter((t) => !typeSet.has(t));
818
+ if (!hasAppOrProductOrArticle) {
819
+ missingCore.push("SoftwareApplication | Product | Article");
820
+ }
821
+
822
+ const sampleSameAs = graph.same_as_urls.slice(0, 8);
823
+ const sameAsChecks = await Promise.all(
824
+ sampleSameAs.map(async (u) => {
825
+ try {
826
+ const r = await fetchResource(u, Math.min(timeoutSec, 8));
827
+ return { url: u, http_status: r.status, reachable: r.status >= 200 && r.status < 405 };
828
+ } catch {
829
+ return { url: u, http_status: 0, reachable: false };
830
+ }
831
+ })
832
+ );
833
+
834
+ const starterTemplate =
835
+ missingCore.length > 0
836
+ ? {
837
+ "@context": "https://schema.org",
838
+ "@graph": [
839
+ {
840
+ "@type": "Organization",
841
+ "@id": `${origin}/#organization`,
842
+ name: info.title ? info.title.split(/\s+[|\-–—]\s+/)[0].trim() : new URL(origin).hostname,
843
+ url: origin,
844
+ sameAs: graph.same_as_urls.length > 0 ? graph.same_as_urls : [`https://github.com/YOUR_ORG`],
845
+ },
846
+ {
847
+ "@type": "WebSite",
848
+ "@id": `${origin}/#website`,
849
+ url: origin,
850
+ name: info.title || new URL(origin).hostname,
851
+ publisher: { "@id": `${origin}/#organization` },
852
+ },
853
+ ],
854
+ }
855
+ : null;
856
+
857
+ return {
858
+ url: pageUrl,
859
+ origin,
860
+ http_status: page.status,
861
+ blocks_count: graph.blocks_count,
862
+ parse_errors: graph.parse_errors,
863
+ unique_types: graph.unique_types,
864
+ defined_ids: graph.defined_ids,
865
+ dangling_id_references: graph.dangling_ids,
866
+ entities: graph.entities,
867
+ same_as_count: graph.same_as_urls.length,
868
+ sampled_same_as_checks: sameAsChecks,
869
+ missing_recommended_types: missingCore,
870
+ suggested_json_ld_template: starterTemplate,
871
+ platform: "https://www.innflows.com/platform/website-ai-audit",
872
+ };
873
+ }
874
+
875
+ export async function compareWebsites(urls, timeoutSec = 12) {
876
+ if (!Array.isArray(urls) || urls.length < 2) {
877
+ throw new Error("Please provide at least 2 URLs to compare.");
878
+ }
879
+ const capped = urls.slice(0, 5);
880
+ const reports = await Promise.all(capped.map((u) => runAudit(u, timeoutSec)));
881
+
882
+ const rows = reports.map((r) => {
883
+ const byId = Object.fromEntries((r.checks || []).map((c) => [c.id, c]));
884
+ return {
885
+ url: r.url,
886
+ score: r.score ?? 0,
887
+ passed: `${r.passed ?? 0}/${r.total ?? 0}`,
888
+ ssr_status: byId.ssr_text?.detail || "n/a",
889
+ json_ld: byId.json_ld?.detail || "n/a",
890
+ ai_crawlers: byId.ai_crawlers?.detail || "n/a",
891
+ llms_txt: byId.llms_txt?.detail || "n/a",
892
+ sitemap_xml: byId.sitemap_xml?.detail || "n/a",
893
+ };
894
+ });
895
+
896
+ const mdLines = [
897
+ "| Website | Score | Passed | SSR HTML Text | Schema.org JSON-LD | AI Crawlers (robots.txt) | /llms.txt | /sitemap.xml |",
898
+ "| :--- | :---: | :---: | :--- | :--- | :--- | :--- | :--- |",
899
+ ...rows.map(
900
+ (r) =>
901
+ `| ${r.url} | **${r.score}/100** | ${r.passed} | ${r.ssr_status} | ${r.json_ld} | ${r.ai_crawlers} | ${r.llms_txt} | ${r.sitemap_xml} |`
902
+ ),
903
+ ];
904
+
905
+ return {
906
+ compared_count: rows.length,
907
+ markdown_table: mdLines.join("\n"),
908
+ results: rows,
909
+ raw_reports: reports,
910
+ platform: "https://www.innflows.com/platform/website-ai-audit",
911
+ };
912
+ }
913
+
914
+ export function formatReportText(report) {
915
+ const icons = { pass: "[PASS]", warn: "[WARN]", fail: "[FAIL]" };
916
+ const lines = [
917
+ "",
918
+ `Website AI-Readiness Audit — ${report.url}`,
919
+ "=".repeat(68),
920
+ ];
921
+ for (const c of report.checks) {
922
+ const icon = (icons[c.status] || "[INFO]").padEnd(6, " ");
923
+ const name = String(c.name).padEnd(34, " ");
924
+ lines.push(`${icon} ${name} ${c.detail}`);
925
+ }
926
+ lines.push("-".repeat(68));
927
+ lines.push(`Summary: ${report.passed}/${report.total} checks passed (Score: ${report.score}/100).`);
928
+ lines.push("Powered by Innflows GEO (https://www.innflows.com/platform/website-ai-audit)");
929
+ lines.push("");
930
+ return lines.join("\n");
931
+ }
932
+
933
+ export function formatProbeText(probeReport) {
934
+ const lines = [
935
+ "",
936
+ `AI Crawler Live HTTP & WAF Probe — ${probeReport.url}`,
937
+ "=".repeat(78),
938
+ `${"Agent".padEnd(20)} | ${"robots.txt".padEnd(15)} | ${"HTTP".padEnd(6)} | ${"SSR Chars".padEnd(10)} | Diagnosis`,
939
+ "-".repeat(78),
940
+ ];
941
+ for (const p of probeReport.probes) {
942
+ const diag = p.silent_waf_block
943
+ ? `SILENT WAF BLOCK (${p.waf_diagnosis || `HTTP ${p.http_status}`})`
944
+ : p.waf_diagnosis || "OK";
945
+ lines.push(
946
+ `${p.agent.padEnd(20)} | ${String(p.robots_txt_posture).padEnd(15)} | ${String(p.http_status).padEnd(6)} | ${String(p.visible_text_chars).padEnd(10)} | ${diag}`
947
+ );
948
+ }
949
+ lines.push("-".repeat(78));
950
+ lines.push(
951
+ probeReport.silent_waf_blocks_detected
952
+ ? `Result: WARN — Silent WAF/CDN blocks detected for: ${probeReport.silent_blocked_agents.join(", ")}`
953
+ : "Result: PASS — Live HTTP responses match /robots.txt posture across all probed AI crawlers."
954
+ );
955
+ lines.push("");
956
+ return lines.join("\n");
957
+ }
958
+
959
+ export const MCP_TOOLS = [
960
+ {
961
+ name: "audit_website_ai_readiness",
962
+ description:
963
+ "Run a comprehensive 9-check Generative Engine Optimization (GEO / AEO) technical readiness audit on a single public webpage URL. Use this first for an overall 0-100 readiness score covering HTTP reachability, noindex directives, initial SSR HTML text extractability, canonical/meta tags, Schema.org JSON-LD presence, /robots.txt AI crawler rules, /llms.txt, and /sitemap.xml. For live WAF/Cloudflare bot-blocking tests, deep llms.txt generation, or multi-site comparisons, use the specialized tools in this server.",
964
+ inputSchema: {
965
+ type: "object",
966
+ properties: {
967
+ url: {
968
+ type: "string",
969
+ description: "Public webpage URL to audit (e.g. https://www.innflows.com/platform).",
970
+ },
971
+ timeout_seconds: {
972
+ type: "number",
973
+ description: "Per-request HTTP timeout in seconds (default: 12, range: 3-30).",
974
+ default: 12,
975
+ },
976
+ },
977
+ required: ["url"],
978
+ },
979
+ annotations: {
980
+ title: "Audit Website AI Readiness",
981
+ readOnlyHint: true,
982
+ destructiveHint: false,
983
+ idempotentHint: true,
984
+ openWorldHint: true,
985
+ },
986
+ },
987
+ {
988
+ name: "probe_ai_crawler_access",
989
+ description:
990
+ "Simulate live HTTP requests with real AI search crawler User-Agent headers (OAI-SearchBot, GPTBot, ChatGPT-User, ClaudeBot, PerplexityBot, Google-Extended, Applebot-Extended) alongside a browser baseline to detect silent WAF, CDN, or Cloudflare bot challenges that block AI retrievers even when /robots.txt allows them. Use this when diagnosing why AI search engines fail to fetch or cite an otherwise indexable page.",
991
+ inputSchema: {
992
+ type: "object",
993
+ properties: {
994
+ url: {
995
+ type: "string",
996
+ description: "Public webpage URL to probe across AI crawler User-Agents (e.g. https://www.innflows.com).",
997
+ },
998
+ timeout_seconds: {
999
+ type: "number",
1000
+ description: "Per-request HTTP timeout in seconds (default: 12).",
1001
+ default: 12,
1002
+ },
1003
+ },
1004
+ required: ["url"],
1005
+ },
1006
+ annotations: {
1007
+ title: "Probe Live AI Crawler & WAF Access",
1008
+ readOnlyHint: true,
1009
+ destructiveHint: false,
1010
+ idempotentHint: true,
1011
+ openWorldHint: true,
1012
+ },
1013
+ },
1014
+ {
1015
+ name: "inspect_or_generate_llms_txt",
1016
+ description:
1017
+ "Validate an existing /llms.txt machine-readable index against the llmstxt.org Markdown specification (checking H1 title, summary blockquote, section headings, SPA HTML soft-200 fallbacks, and dead links) OR synthesize a ready-to-publish /llms.txt file from a website's homepage and /sitemap.xml. Set mode='validate' to audit a live /llms.txt, or mode='generate' to draft one.",
1018
+ inputSchema: {
1019
+ type: "object",
1020
+ properties: {
1021
+ url: {
1022
+ type: "string",
1023
+ description: "Website root URL or direct /llms.txt URL (e.g. https://www.innflows.com).",
1024
+ },
1025
+ mode: {
1026
+ type: "string",
1027
+ enum: ["validate", "generate"],
1028
+ description: "Operation mode: 'validate' inspects the live /llms.txt and samples link health; 'generate' crawls sitemap.xml and homepage metadata to draft a compliant Markdown /llms.txt.",
1029
+ default: "validate",
1030
+ },
1031
+ max_links: {
1032
+ type: "number",
1033
+ description: "Maximum same-origin URLs to include when mode='generate' (default: 20, max: 50).",
1034
+ default: 20,
1035
+ },
1036
+ timeout_seconds: {
1037
+ type: "number",
1038
+ description: "Per-request HTTP timeout in seconds (default: 12).",
1039
+ default: 12,
1040
+ },
1041
+ },
1042
+ required: ["url"],
1043
+ },
1044
+ annotations: {
1045
+ title: "Validate or Generate llms.txt",
1046
+ readOnlyHint: true,
1047
+ destructiveHint: false,
1048
+ idempotentHint: true,
1049
+ openWorldHint: true,
1050
+ },
1051
+ },
1052
+ {
1053
+ name: "inspect_schema_entity_graph",
1054
+ description:
1055
+ "Deeply inspect all Schema.org JSON-LD blocks on a webpage, extracting @type entities, @id node anchors, dangling internal #fragment @id references, and Organization.sameAs authority links (with live HTTP reachability checks). Also generates a starter @graph JSON-LD snippet when core GEO entities (Organization, WebSite, SoftwareApplication/Product/Article) are missing.",
1056
+ inputSchema: {
1057
+ type: "object",
1058
+ properties: {
1059
+ url: {
1060
+ type: "string",
1061
+ description: "Public webpage URL whose Schema.org JSON-LD entity graph should be analyzed.",
1062
+ },
1063
+ timeout_seconds: {
1064
+ type: "number",
1065
+ description: "Per-request HTTP timeout in seconds (default: 12).",
1066
+ default: 12,
1067
+ },
1068
+ },
1069
+ required: ["url"],
1070
+ },
1071
+ annotations: {
1072
+ title: "Inspect Schema.org JSON-LD Entity Graph",
1073
+ readOnlyHint: true,
1074
+ destructiveHint: false,
1075
+ idempotentHint: true,
1076
+ openWorldHint: true,
1077
+ },
1078
+ },
1079
+ {
1080
+ name: "compare_websites_ai_readiness",
1081
+ description:
1082
+ "Benchmark 2 to 5 public websites side by side across all GEO/AEO AI-readiness dimensions (overall score, SSR visible HTML characters, Schema.org JSON-LD types, /robots.txt AI crawler rules, /llms.txt, and /sitemap.xml) and return both a ready-to-share Markdown comparison table and structured JSON results. Use this for competitive GEO benchmarking.",
1083
+ inputSchema: {
1084
+ type: "object",
1085
+ properties: {
1086
+ urls: {
1087
+ type: "array",
1088
+ items: { type: "string" },
1089
+ minItems: 2,
1090
+ maxItems: 5,
1091
+ description: "List of 2 to 5 public webpage URLs to benchmark side by side.",
1092
+ },
1093
+ timeout_seconds: {
1094
+ type: "number",
1095
+ description: "Per-request HTTP timeout in seconds (default: 12).",
1096
+ default: 12,
1097
+ },
1098
+ },
1099
+ required: ["urls"],
1100
+ },
1101
+ annotations: {
1102
+ title: "Compare Websites AI Readiness",
1103
+ readOnlyHint: true,
1104
+ destructiveHint: false,
1105
+ idempotentHint: true,
1106
+ openWorldHint: true,
1107
+ },
1108
+ },
1109
+ ];
1110
+
1111
+ export async function handleMcpRequest(msg, auditFn = runAudit) {
1112
+ if (!msg || typeof msg !== "object") return null;
1113
+ const { id, method, params } = msg;
1114
+ if (id === undefined) return null; // notification
1115
+
1116
+ if (method === "initialize") {
1117
+ return {
1118
+ jsonrpc: "2.0",
1119
+ id,
1120
+ result: {
1121
+ protocolVersion: params?.protocolVersion || "2024-11-05",
1122
+ capabilities: { tools: {} },
1123
+ serverInfo: {
1124
+ name: "@innflows/ai-readiness-audit",
1125
+ version: PKG_VERSION,
1126
+ },
1127
+ },
1128
+ };
1129
+ }
1130
+
1131
+ if (method === "ping") {
1132
+ return { jsonrpc: "2.0", id, result: {} };
1133
+ }
1134
+
1135
+ if (method === "tools/list") {
1136
+ return {
1137
+ jsonrpc: "2.0",
1138
+ id,
1139
+ result: {
1140
+ tools: MCP_TOOLS,
1141
+ },
1142
+ };
1143
+ }
1144
+
1145
+ if (method === "tools/call") {
1146
+ const toolName = params?.name;
1147
+ const args = params?.arguments || {};
1148
+ const timeoutSec = Number(args.timeout_seconds || 12);
1149
+
1150
+ try {
1151
+ if (toolName === "audit_website_ai_readiness") {
1152
+ if (!args.url || typeof args.url !== "string") {
1153
+ return { jsonrpc: "2.0", id, error: { code: -32602, message: "Missing required string parameter: url" } };
1154
+ }
1155
+ const report = await auditFn(args.url, timeoutSec);
1156
+ return {
1157
+ jsonrpc: "2.0",
1158
+ id,
1159
+ result: {
1160
+ content: [{ type: "text", text: `${formatReportText(report)}\n${JSON.stringify(report, null, 2)}` }],
1161
+ isError: false,
1162
+ },
1163
+ };
1164
+ }
1165
+
1166
+ if (toolName === "probe_ai_crawler_access") {
1167
+ if (!args.url || typeof args.url !== "string") {
1168
+ return { jsonrpc: "2.0", id, error: { code: -32602, message: "Missing required string parameter: url" } };
1169
+ }
1170
+ const report = await probeCrawlerAccess(args.url, timeoutSec);
1171
+ return {
1172
+ jsonrpc: "2.0",
1173
+ id,
1174
+ result: {
1175
+ content: [{ type: "text", text: `${formatProbeText(report)}\n${JSON.stringify(report, null, 2)}` }],
1176
+ isError: false,
1177
+ },
1178
+ };
1179
+ }
1180
+
1181
+ if (toolName === "inspect_or_generate_llms_txt") {
1182
+ if (!args.url || typeof args.url !== "string") {
1183
+ return { jsonrpc: "2.0", id, error: { code: -32602, message: "Missing required string parameter: url" } };
1184
+ }
1185
+ const report = await inspectOrGenerateLlmsTxt(args.url, {
1186
+ mode: args.mode || "validate",
1187
+ maxLinks: args.max_links || 20,
1188
+ timeoutSec,
1189
+ });
1190
+ const textOut =
1191
+ report.mode === "generate" && report.generated_markdown
1192
+ ? `${report.generated_markdown}\n---\n${JSON.stringify({ origin: report.origin, pages_indexed: report.pages_indexed }, null, 2)}`
1193
+ : JSON.stringify(report, null, 2);
1194
+ return {
1195
+ jsonrpc: "2.0",
1196
+ id,
1197
+ result: {
1198
+ content: [{ type: "text", text: textOut }],
1199
+ isError: false,
1200
+ },
1201
+ };
1202
+ }
1203
+
1204
+ if (toolName === "inspect_schema_entity_graph") {
1205
+ if (!args.url || typeof args.url !== "string") {
1206
+ return { jsonrpc: "2.0", id, error: { code: -32602, message: "Missing required string parameter: url" } };
1207
+ }
1208
+ const report = await inspectSchemaEntityGraph(args.url, timeoutSec);
1209
+ return {
1210
+ jsonrpc: "2.0",
1211
+ id,
1212
+ result: {
1213
+ content: [{ type: "text", text: JSON.stringify(report, null, 2) }],
1214
+ isError: false,
1215
+ },
1216
+ };
1217
+ }
1218
+
1219
+ if (toolName === "compare_websites_ai_readiness") {
1220
+ if (!Array.isArray(args.urls) || args.urls.length < 2) {
1221
+ return { jsonrpc: "2.0", id, error: { code: -32602, message: "Parameter 'urls' must be an array of 2 to 5 URLs" } };
1222
+ }
1223
+ const report = await compareWebsites(args.urls, timeoutSec);
1224
+ return {
1225
+ jsonrpc: "2.0",
1226
+ id,
1227
+ result: {
1228
+ content: [{ type: "text", text: `${report.markdown_table}\n\n${JSON.stringify(report.results, null, 2)}` }],
1229
+ isError: false,
1230
+ },
1231
+ };
1232
+ }
1233
+
1234
+ return {
1235
+ jsonrpc: "2.0",
1236
+ id,
1237
+ error: { code: -32601, message: `Unknown tool: ${toolName}` },
1238
+ };
1239
+ } catch (err) {
1240
+ return {
1241
+ jsonrpc: "2.0",
1242
+ id,
1243
+ result: {
1244
+ content: [{ type: "text", text: `Tool execution error: ${err.message || String(err)}` }],
1245
+ isError: true,
1246
+ },
1247
+ };
1248
+ }
1249
+ }
1250
+
1251
+ return {
1252
+ jsonrpc: "2.0",
1253
+ id,
1254
+ error: { code: -32601, message: `Method not found: ${method}` },
1255
+ };
1256
+ }
1257
+
1258
+ function startMcpStdioServer() {
1259
+ const rl = readline.createInterface({ input: process.stdin, terminal: false });
1260
+ rl.on("line", async (line) => {
1261
+ const trimmed = line.trim();
1262
+ if (!trimmed) return;
1263
+ try {
1264
+ const msg = JSON.parse(trimmed);
1265
+ const reply = await handleMcpRequest(msg);
1266
+ if (reply) {
1267
+ process.stdout.write(`${JSON.stringify(reply)}\n`);
1268
+ }
1269
+ } catch {
1270
+ process.stdout.write(
1271
+ `${JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } })}\n`
1272
+ );
1273
+ }
1274
+ });
1275
+ }
1276
+
1277
+ function printHelp() {
1278
+ console.log(
1279
+ [
1280
+ `@innflows/ai-readiness-audit v${PKG_VERSION} — GEO & AEO Website AI-Readiness Toolkit`,
1281
+ "",
1282
+ "Usage:",
1283
+ " npx @innflows/ai-readiness-audit <url> [--json] [--fail-under 80] [--timeout 12]",
1284
+ " npx @innflows/ai-readiness-audit probe-crawlers <url> [--json]",
1285
+ " npx @innflows/ai-readiness-audit llms-txt <url> [--generate] [--max-links 20] [--json]",
1286
+ " npx @innflows/ai-readiness-audit schema-graph <url> [--json]",
1287
+ " npx @innflows/ai-readiness-audit compare <url1> <url2> [url3...] [--json]",
1288
+ " npx -y @innflows/ai-readiness-audit --mcp # Start 5-tool MCP stdio server",
1289
+ "",
1290
+ "Maintained by Innflows GEO (https://www.innflows.com/platform/website-ai-audit)",
1291
+ ].join("\n")
1292
+ );
1293
+ }
1294
+
1295
+ async function main() {
1296
+ const argv = process.argv.slice(2);
1297
+ const invokedAsMcp = (process.argv[1] || "").endsWith("ai-readiness-audit-mcp");
1298
+ if (invokedAsMcp || argv.includes("--mcp")) {
1299
+ startMcpStdioServer();
1300
+ return;
1301
+ }
1302
+
1303
+ if (argv.includes("-v") || argv.includes("--version")) {
1304
+ console.log(PKG_VERSION);
1305
+ return;
1306
+ }
1307
+
1308
+ if (argv.includes("-h") || argv.includes("--help") || argv.length === 0) {
1309
+ printHelp();
1310
+ process.exit(argv.length === 0 ? 1 : 0);
1311
+ }
1312
+
1313
+ const jsonOut = argv.includes("--json");
1314
+ const getNumFlag = (flag, fallback) => {
1315
+ const idx = argv.indexOf(flag);
1316
+ return idx !== -1 && argv[idx + 1] ? Number(argv[idx + 1]) : fallback;
1317
+ };
1318
+ const timeoutSec = getNumFlag("--timeout", 12) || 12;
1319
+ const failUnder = getNumFlag("--fail-under", null);
1320
+ const maxLinks = getNumFlag("--max-links", 20) || 20;
1321
+
1322
+ const valuedFlags = new Set(["--timeout", "--fail-under", "--max-links"]);
1323
+ const positional = [];
1324
+ for (let i = 0; i < argv.length; i += 1) {
1325
+ const a = argv[i];
1326
+ if (valuedFlags.has(a)) {
1327
+ i += 1;
1328
+ continue;
1329
+ }
1330
+ if (!a.startsWith("-")) positional.push(a);
1331
+ }
1332
+
1333
+ const subcommands = new Set(["audit", "probe-crawlers", "llms-txt", "schema-graph", "compare"]);
1334
+ const cmd = subcommands.has(positional[0]) ? positional[0] : "audit";
1335
+ const targets = subcommands.has(positional[0]) ? positional.slice(1) : positional;
1336
+
1337
+ if (cmd === "compare") {
1338
+ if (targets.length < 2) {
1339
+ console.error("Error: 'compare' requires 2 to 5 URLs.");
1340
+ process.exit(1);
1341
+ }
1342
+ const cmp = await compareWebsites(targets, timeoutSec);
1343
+ console.log(jsonOut ? JSON.stringify(cmp, null, 2) : `\n${cmp.markdown_table}\n`);
1344
+ return;
1345
+ }
1346
+
1347
+ const targetUrl = targets[0];
1348
+ if (!targetUrl) {
1349
+ console.error("Error: missing <url> argument.");
1350
+ process.exit(1);
1351
+ }
1352
+
1353
+ if (cmd === "probe-crawlers") {
1354
+ const res = await probeCrawlerAccess(targetUrl, timeoutSec);
1355
+ console.log(jsonOut ? JSON.stringify(res, null, 2) : formatProbeText(res));
1356
+ if (failUnder !== null && res.silent_waf_blocks_detected) process.exit(2);
1357
+ return;
1358
+ }
1359
+
1360
+ if (cmd === "llms-txt") {
1361
+ const generate = argv.includes("--generate");
1362
+ const res = await inspectOrGenerateLlmsTxt(targetUrl, {
1363
+ mode: generate ? "generate" : "validate",
1364
+ maxLinks,
1365
+ timeoutSec,
1366
+ });
1367
+ if (jsonOut) {
1368
+ console.log(JSON.stringify(res, null, 2));
1369
+ } else if (generate) {
1370
+ process.stdout.write(res.generated_markdown);
1371
+ } else {
1372
+ console.log(JSON.stringify(res, null, 2));
1373
+ }
1374
+ return;
1375
+ }
1376
+
1377
+ if (cmd === "schema-graph") {
1378
+ const res = await inspectSchemaEntityGraph(targetUrl, timeoutSec);
1379
+ console.log(JSON.stringify(res, null, 2));
1380
+ return;
1381
+ }
1382
+
1383
+ const report = await runAudit(targetUrl, timeoutSec);
1384
+ if (jsonOut) {
1385
+ console.log(JSON.stringify(report, null, 2));
1386
+ } else {
1387
+ console.log(formatReportText(report));
1388
+ }
1389
+ if (failUnder !== null && !Number.isNaN(failUnder) && report.score < failUnder) {
1390
+ console.error(`CI Gate Failed: score ${report.score}/100 is below --fail-under ${failUnder}.`);
1391
+ process.exit(2);
1392
+ }
1393
+ }
1394
+
1395
+ const isDirectRun =
1396
+ import.meta.url === `file://${process.argv[1]}` ||
1397
+ (process.argv[1] && process.argv[1].endsWith("ai-readiness-audit")) ||
1398
+ (process.argv[1] && process.argv[1].endsWith("ai-readiness-audit-mcp")) ||
1399
+ (process.argv[1] && process.argv[1].endsWith("cli.mjs"));
1400
+
1401
+ if (isDirectRun && !process.env.AI_AUDIT_IMPORT_ONLY) {
1402
+ main();
1403
+ }