mcp-web-validator 1.2.0 → 1.2.1

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/CHANGELOG.md CHANGED
@@ -4,6 +4,22 @@ All notable changes to this project are documented here. The project follows [Se
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.2.1] - 2026-09-19
8
+
9
+ ### Changed
10
+
11
+ - Added current Gemini CLI and GitHub Copilot CLI setup guidance for the local stdio package.
12
+ - Migrated the hosted stateless MCP handler to the supported Agents SDK v2 server-factory path and refreshed current minor/patch dependency resolutions.
13
+
14
+ ### Fixed
15
+
16
+ - Rejected malformed Nu HTML Checker responses that omit the required `messages` member in both local and hosted validation paths.
17
+ - Rejected malformed non-empty W3C CSS Validator JSON that omits the expected `cssvalidation` envelope.
18
+ - Rejected successful non-HTML responses from local URL validation instead of forwarding arbitrary content to the HTML checker.
19
+ - Removed unsupported exact-one-H1 SEO penalties while retaining heading-structure guidance.
20
+ - Resolved relative links from the document's first valid public `<base href>` when no explicit link-check base URL is provided.
21
+ - Recognized parameterized `application/ld+json` media types, including the standards-defined `profile` parameter, in both local and hosted schema scans.
22
+
7
23
  ## [1.2.0] - 2026-09-19
8
24
 
9
25
  ### Added
package/README.md CHANGED
@@ -119,6 +119,29 @@ Marketplace or add the repository from Cursor's plugin UI. The plugin bundles
119
119
  the same local stdio server and does not require API keys or environment
120
120
  variables.
121
121
 
122
+ ### Gemini CLI
123
+
124
+ Gemini CLI supports local stdio MCP servers. Add the published package with:
125
+
126
+ ```bash
127
+ gemini mcp add mcp-web-validator npx -y mcp-web-validator
128
+ ```
129
+
130
+ This writes the server definition to Gemini CLI's MCP configuration. No API
131
+ keys or environment variables are required by Web Validator.
132
+
133
+ ### GitHub Copilot CLI
134
+
135
+ Add the published local stdio server with:
136
+
137
+ ```bash
138
+ copilot mcp add mcp-web-validator -- npx -y mcp-web-validator
139
+ ```
140
+
141
+ When Copilot CLI is started inside a clone of this repository, it can also
142
+ discover the checked-in root `.mcp.json`, which already points
143
+ `mcp-web-validator` at `npx -y mcp-web-validator`.
144
+
122
145
  ### Kiro
123
146
 
124
147
  [![Add to Kiro](https://kiro.dev/images/add-to-kiro.svg)](https://kiro.dev/launch/mcp/add?name=mcp-web-validator&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22mcp-web-validator%22%5D%2C%22disabled%22%3Afalse%2C%22autoApprove%22%3A%5B%5D%7D)
@@ -169,4 +192,4 @@ For agent-assisted installation, see [llms-install.md](llms-install.md).
169
192
 
170
193
  ## License
171
194
 
172
- Licensed under the [MIT License](LICENSE).
195
+ Licensed under the [MIT License](LICENSE).
package/dist/index.js CHANGED
@@ -226,8 +226,9 @@ export function createServer() {
226
226
  maxBytes: HTML_MAX_BYTES,
227
227
  timeoutMs: 15_000,
228
228
  maxRedirects: 3,
229
+ acceptedContentTypes: ["text/html", "application/xhtml+xml"],
229
230
  headers: {
230
- accept: "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.5",
231
+ accept: "text/html,application/xhtml+xml;q=0.9",
231
232
  "user-agent": `DigestSEO-Web-Validator/${SERVER_VERSION} (+https://digestseo.com/validator-mcp/)`,
232
233
  },
233
234
  });
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,gBAAgB,EAChB,oBAAoB,EACpB,4B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AwB,CAAC,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAC9D,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,KAAK,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;YACrC,OAAO,MAAM,CACX,EAAE,WAAW,EAAE,EAAE,EAAE,eAAe,EAAE,KAAK,EAAE,EAC3C,cAAc,CACZ,oBAAoB,EACpB,KAAK,EACL,+FAA+F,CAChG,EACD,IAAI,CACL,CAAC;QACJ,CAAC;IACH,CAAC,CACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,GAAG;IACvB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAC9B,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACjD,OAAO,CAAC,KAAK,CAAC,qBAAqB,cAAc,mBAAmB,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACpG,IAAI,WAAW,KAAK,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;IACpC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC7B,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACjF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { captureScreenshots } from \"./screenshot.js\";\nimport {\n auditSeoMetadata,\n auditSeoMetadataDetailed,\n checkBrokenLinks,\n validateSchemaMarkup,\n validateSchemaMarkupDetailed,\n} from \"./seo-auditor.js\";\nimport {\n createValidationReport,\n type ValidationReport,\n type ValidationReportCheck,\n validationReportChecks,\n} from \"./report.js\";\nimport { fetchPublicText, getErrorMessage, readTextFile } from \"./network.js\";\nimport {\n cssValidationContent,\n failureContent,\n htmlValidationContent,\n linkCheckContent,\n reportContent,\n schemaValidationContent,\n screenshotCaptureContent,\n seoAuditContent,\n} from \"./presentation.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\nimport {\n MAX_CSS_VALIDATION_BYTES,\n validateCssContent,\n validateHtmlContent,\n} from \"./w3c-validator.js\";\n\nexport const SERVER_VERSION = PACKAGE_VERSION;\n\nconst HTML_MAX_BYTES = 2_000_000;\nconst CSS_MAX_BYTES = MAX_CSS_VALIDATION_BYTES;\nconst PATH_MAX_LENGTH = 4_096;\nconst MAX_VIEWPORTS = 8;\n\nconst filePathSchema = z.string().trim().min(1).max(PATH_MAX_LENGTH);\nconst htmlContentSchema = z.string().min(1).max(HTML_MAX_BYTES);\nconst publicUrlSchema = z\n .string()\n .url()\n .refine((value) => {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n }, \"URL must use HTTP or HTTPS.\");\n\nconst w3cMessageSchema = z.object({\n type: z.string(),\n message: z.string(),\n lastLine: z.number().int().optional(),\n lastColumn: z.number().int().optional(),\n firstLine: z.number().int().optional(),\n firstColumn: z.number().int().optional(),\n extract: z.string().optional(),\n});\n\nconst cssMessageSchema = z.object({\n line: z.number().int(),\n type: z.string(),\n message: z.string(),\n context: z.string().optional(),\n});\n\nconst seoIssueSchema = z.object({\n severity: z.enum([\"error\", \"warning\", \"info\"]),\n category: z.enum([\"SEO\", \"Schema\", \"BrokenLinks\", \"Accessibility\"]),\n message: z.string(),\n element: z.string().optional(),\n});\n\nconst linkStatusSchema = z.object({\n url: z.string(),\n status: z.union([z.number().int(), z.enum([\"blocked\", \"failed\"])]),\n ok: z.boolean(),\n message: z.string().optional(),\n});\n\nconst screenshotSchema = z.object({\n viewportName: z.string(),\n width: z.number().int(),\n height: z.number().int(),\n outputPath: z.string(),\n});\n\nconst reportSummarySchema = z.object({\n overallScore: z.number().int().min(0).max(100).nullable(),\n htmlScore: z.number().int().min(0).max(100).nullable(),\n cssScore: z.number().int().min(0).max(100).nullable(),\n seoScore: z.number().int().min(0).max(100).nullable(),\n linkScore: z.number().int().min(0).max(100).nullable(),\n htmlErrors: z.number().int().nonnegative(),\n htmlWarnings: z.number().int().nonnegative(),\n cssErrors: z.number().int().nonnegative(),\n seoErrors: z.number().int().nonnegative(),\n seoWarnings: z.number().int().nonnegative(),\n schemaErrors: z.number().int().nonnegative(),\n linksChecked: z.number().int().nonnegative(),\n brokenLinks: z.number().int().nonnegative(),\n});\n\nconst externalReadOnlyAnnotations = {\n // These calls contact external recipients but do not modify external state.\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n} as const;\n\nconst localReadOnlyAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nfunction result<T extends object>(\n structuredContent: T,\n content: string,\n isError = false,\n): CallToolResult {\n return {\n structuredContent: structuredContent as Record<string, unknown>,\n content: [\n {\n type: \"text\",\n text: content,\n },\n ],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction failedReport(filePath: string, error: string): ValidationReport {\n return {\n report: `Validation report could not be generated: ${error}`,\n summary: {\n overallScore: null,\n htmlScore: null,\n cssScore: null,\n seoScore: null,\n linkScore: null,\n htmlErrors: 0,\n htmlWarnings: 0,\n cssErrors: 0,\n seoErrors: 0,\n seoWarnings: 0,\n schemaErrors: 0,\n linksChecked: 0,\n brokenLinks: 0,\n },\n htmlMessages: [],\n cssMessages: [],\n seoIssues: [],\n schemaIssues: [],\n links: [],\n failedChecks: [\"input\"],\n errors: [`${path.basename(filePath || \"document\")}: ${error}`],\n };\n}\n\ninterface ValidationReportDependencies {\n readTextFile: typeof readTextFile;\n validateHtmlContent: typeof validateHtmlContent;\n validateCssContent: typeof validateCssContent;\n auditSeoMetadata: typeof auditSeoMetadata;\n validateSchemaMarkup: typeof validateSchemaMarkup;\n checkBrokenLinks: typeof checkBrokenLinks;\n}\n\nconst validationReportDependencies: ValidationReportDependencies = {\n readTextFile,\n validateHtmlContent,\n validateCssContent,\n auditSeoMetadata,\n validateSchemaMarkup,\n checkBrokenLinks,\n};\n\nexport interface GenerateValidationReportOptions {\n htmlFilePath: string;\n cssFilePath?: string;\n baseUrl?: string;\n}\n\n/** Runs independent validation checks without discarding successful results when another check fails. */\nexport async function generateValidationReport(\n { htmlFilePath, cssFilePath, baseUrl }: GenerateValidationReportOptions,\n dependencies: ValidationReportDependencies = validationReportDependencies,\n): Promise<ValidationReport> {\n const html = await dependencies.readTextFile(htmlFilePath, HTML_MAX_BYTES);\n const failedChecks: ValidationReportCheck[] = [];\n const errors: string[] = [];\n const recordFailure = (check: ValidationReportCheck, label: string, cause: unknown): void => {\n if (!failedChecks.includes(check)) {\n failedChecks.push(check);\n }\n errors.push(`${label} was unavailable: ${getErrorMessage(cause)}`);\n };\n\n let css: string | undefined;\n if (cssFilePath) {\n try {\n css = await dependencies.readTextFile(cssFilePath, CSS_MAX_BYTES);\n } catch (cause) {\n recordFailure(\"css\", \"CSS validation\", cause);\n }\n }\n\n const [htmlResult, cssResult, seoResult, schemaResult, linksResult] = await Promise.allSettled([\n dependencies.validateHtmlContent(html),\n css === undefined ? Promise.resolve([]) : dependencies.validateCssContent(css),\n Promise.resolve().then(() => dependencies.auditSeoMetadata(html)),\n Promise.resolve().then(() => dependencies.validateSchemaMarkup(html)),\n dependencies.checkBrokenLinks(html, baseUrl, 25),\n ]);\n\n if (htmlResult.status === \"rejected\") recordFailure(\"html\", \"HTML validation\", htmlResult.reason);\n if (cssResult.status === \"rejected\") recordFailure(\"css\", \"CSS validation\", cssResult.reason);\n if (seoResult.status === \"rejected\") recordFailure(\"seo\", \"SEO analysis\", seoResult.reason);\n if (schemaResult.status === \"rejected\") recordFailure(\"schema\", \"JSON-LD analysis\", schemaResult.reason);\n if (linksResult.status === \"rejected\") recordFailure(\"links\", \"Link checking\", linksResult.reason);\n\n return createValidationReport({\n htmlFilePath,\n cssAudited: css !== undefined,\n htmlMessages: htmlResult.status === \"fulfilled\" ? htmlResult.value : [],\n cssMessages: cssResult.status === \"fulfilled\" ? cssResult.value : [],\n seoIssues: seoResult.status === \"fulfilled\" ? seoResult.value.slice(0, 200) : [],\n schemaIssues: schemaResult.status === \"fulfilled\" ? schemaResult.value.slice(0, 200) : [],\n links: linksResult.status === \"fulfilled\" ? linksResult.value : [],\n failedChecks,\n errors,\n });\n}\n\nexport function createServer(): McpServer {\n const server = new McpServer(\n { name: \"mcp-web-validator\", version: SERVER_VERSION },\n {\n instructions:\n \"Validate only files, markup, and public URLs the user owns or is authorized to inspect. HTML and CSS validation send supplied content to W3C-operated validators. Link checks contact public links without following redirects. Screenshot capture executes page content in a sandboxed local browser and writes PNG files.\",\n },\n );\n\n server.registerTool(\n \"html.local\",\n {\n title: \"Validate local HTML\",\n description:\n \"Reads a bounded local HTML file and sends its markup to the W3C Nu HTML Checker. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to an HTML file.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const html = await readTextFile(filePath, HTML_MAX_BYTES);\n const errors = await validateHtmlContent(html);\n return result({ errors }, htmlValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"HTML validation\",\n error,\n \"Confirm the file exists and is readable, then retry. If the W3C service is unavailable, try again later.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"html.url\",\n {\n title: \"Validate a public URL\",\n description:\n \"Fetches a bounded public HTTP(S) page, then sends its markup to the W3C Nu HTML Checker. Private, reserved, credentialed, and nonstandard-port destinations are rejected.\",\n inputSchema: {\n url: publicUrlSchema.describe(\"Public HTTP(S) URL on port 80 or 443.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n fetchedUrl: z.string().optional(),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ url }) => {\n try {\n const fetched = await fetchPublicText(url, {\n maxBytes: HTML_MAX_BYTES,\n timeoutMs: 15_000,\n maxRedirects: 3,\n headers: {\n accept: \"text/html,application/xhtml+xml;q=0.9,text/plain;q=0.5\",\n \"user-agent\": `DigestSEO-Web-Validator/${SERVER_VERSION} (+https://digestseo.com/validator-mcp/)`,\n },\n });\n if (fetched.status < 200 || fetched.status >= 300) {\n throw new Error(`Target URL returned HTTP ${fetched.status}.`);\n }\n const errors = await validateHtmlContent(fetched.text);\n return result(\n { errors, fetchedUrl: fetched.url },\n htmlValidationContent(errors, fetched.url),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"URL validation\",\n error,\n \"Confirm the URL is public, uses HTTP or HTTPS on a standard port, and returns HTML, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"css.local\",\n {\n title: \"Validate local CSS\",\n description:\n \"Reads a bounded local CSS file and sends it to the W3C Jigsaw CSS Validator. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to a CSS file.\"),\n },\n outputSchema: {\n errors: z.array(cssMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const css = await readTextFile(filePath, CSS_MAX_BYTES);\n const errors = await validateCssContent(css);\n return result({ errors }, cssValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"CSS validation\",\n error,\n \"Confirm the file exists, is readable, and is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"seo.metadata\",\n {\n title: \"Audit SEO metadata\",\n description:\n \"Analyzes supplied HTML locally for metadata, heading structure, viewport configuration, image alternatives, and Open Graph fields.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup to inspect locally.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = auditSeoMetadataDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n seoAuditContent(issues, totalIssues, truncated),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"SEO audit\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"links.broken\",\n {\n title: \"Check public links\",\n description:\n \"Resolves and checks up to 25 public HTTP(S) links in supplied HTML. Redirects are reported but not followed, and response bodies are discarded.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup containing links to check.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n maxLinks: z\n .number()\n .int()\n .min(1)\n .max(25)\n .default(25)\n .describe(\"Maximum number of public HTTP(S) links to check, from 1 to 25.\"),\n },\n outputSchema: {\n links: z.array(linkStatusSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlContent, baseUrl, maxLinks }) => {\n try {\n const links = await checkBrokenLinks(htmlContent, baseUrl, maxLinks);\n return result({ links }, linkCheckContent(links, baseUrl));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { links: [], error },\n failureContent(\n \"Link check\",\n error,\n \"Confirm the base URL is public and the supplied HTML is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"schema.markup\",\n {\n title: \"Validate JSON-LD syntax\",\n description:\n \"Parses JSON-LD blocks in supplied HTML locally and reports empty blocks or JSON syntax errors. It does not validate vocabulary semantics.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML containing JSON-LD script blocks.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = validateSchemaMarkupDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n schemaValidationContent(issues, totalIssues, truncated, htmlContent),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"JSON-LD syntax\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"report.validation\",\n {\n title: \"Generate a validation report\",\n description:\n \"Combines W3C HTML/CSS validation, local SEO/accessibility checks, JSON-LD syntax checks, and a bounded public-link check into a Markdown and structured report.\",\n inputSchema: {\n htmlFilePath: filePathSchema.describe(\"Absolute or workspace-relative HTML file path.\"),\n cssFilePath: filePathSchema\n .optional()\n .describe(\"Optional absolute or workspace-relative CSS file path.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n },\n outputSchema: {\n report: z.string(),\n summary: reportSummarySchema,\n htmlMessages: z.array(w3cMessageSchema),\n cssMessages: z.array(cssMessageSchema),\n seoIssues: z.array(seoIssueSchema),\n schemaIssues: z.array(seoIssueSchema),\n links: z.array(linkStatusSchema),\n failedChecks: z.array(z.enum(validationReportChecks)),\n errors: z.array(z.string()).optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlFilePath, cssFilePath, baseUrl }) => {\n try {\n const reportData = await generateValidationReport({\n htmlFilePath,\n cssFilePath,\n baseUrl,\n });\n return result(reportData, reportContent(reportData));\n } catch (cause) {\n const error = getErrorMessage(cause);\n const reportData = failedReport(htmlFilePath, error);\n return result(\n reportData,\n failureContent(\n \"Validation report\",\n error,\n \"Confirm the input paths are readable and any base URL is public, then regenerate the report.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"screenshot.capture\",\n {\n title: \"Capture responsive screenshots\",\n description:\n \"Renders a local HTML file or HTTP(S) URL in a sandboxed local Chromium browser and writes PNG screenshots to the requested directory. Existing matching files may be replaced.\",\n inputSchema: {\n targetPath: z\n .string()\n .trim()\n .min(1)\n .max(PATH_MAX_LENGTH)\n .describe(\"Local HTML path or HTTP(S) URL to render.\"),\n outputDir: filePathSchema\n .optional()\n .default(\".mcp-validator/screenshots\")\n .describe(\"Directory where PNG screenshots will be written.\"),\n viewports: z\n .array(\n z.object({\n name: z\n .string()\n .regex(/^[A-Za-z0-9_-]{1,50}$/)\n .describe(\"Safe filename label for this screenshot viewport.\"),\n width: z\n .number()\n .int()\n .min(200)\n .max(3_840)\n .describe(\"Viewport width in CSS pixels, from 200 to 3840.\"),\n height: z\n .number()\n .int()\n .min(200)\n .max(4_320)\n .describe(\"Viewport height in CSS pixels, from 200 to 4320.\"),\n }),\n )\n .min(1)\n .max(MAX_VIEWPORTS)\n .optional()\n .describe(\"Optional viewport definitions; defaults to desktop, tablet, and mobile sizes.\"),\n },\n outputSchema: {\n screenshots: z.array(screenshotSchema),\n outputDirectory: z.string(),\n error: z.string().optional(),\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async ({ targetPath, outputDir, viewports }) => {\n const outputDirectory = path.resolve(outputDir);\n try {\n const screenshots = await captureScreenshots(targetPath, outputDirectory, viewports);\n return result(\n { screenshots, outputDirectory },\n screenshotCaptureContent(screenshots.length, outputDirectory),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { screenshots: [], outputDirectory, error },\n failureContent(\n \"Screenshot capture\",\n error,\n \"Confirm the target is reachable or readable and the output directory is writable, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n return server;\n}\n\nexport async function run(): Promise<void> {\n const server = createServer();\n await server.connect(new StdioServerTransport());\n console.error(`mcp-web-validator ${SERVER_VERSION} started on stdio`);\n}\n\nconst invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : undefined;\nif (invokedPath === import.meta.url) {\n run().catch((cause: unknown) => {\n console.error(\"Fatal error starting mcp-web-validator:\", getErrorMessage(cause));\n process.exitCode = 1;\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,gBAAgB,EAChB,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,sBAAsB,EAGtB,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,qBA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AAO,MAAM,CACX,EAAE,WAAW,EAAE,EAAE,EAAE,eAAe,EAAE,KAAK,EAAE,EAC3C,cAAc,CACZ,oBAAoB,EACpB,KAAK,EACL,+FAA+F,CAChG,EACD,IAAI,CACL,CAAC;QACJ,CAAC;IACH,CAAC,CACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,GAAG;IACvB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAC9B,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACjD,OAAO,CAAC,KAAK,CAAC,qBAAqB,cAAc,mBAAmB,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACpG,IAAI,WAAW,KAAK,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;IACpC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC7B,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACjF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { captureScreenshots } from \"./screenshot.js\";\nimport {\n auditSeoMetadata,\n auditSeoMetadataDetailed,\n checkBrokenLinks,\n validateSchemaMarkup,\n validateSchemaMarkupDetailed,\n} from \"./seo-auditor.js\";\nimport {\n createValidationReport,\n type ValidationReport,\n type ValidationReportCheck,\n validationReportChecks,\n} from \"./report.js\";\nimport { fetchPublicText, getErrorMessage, readTextFile } from \"./network.js\";\nimport {\n cssValidationContent,\n failureContent,\n htmlValidationContent,\n linkCheckContent,\n reportContent,\n schemaValidationContent,\n screenshotCaptureContent,\n seoAuditContent,\n} from \"./presentation.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\nimport {\n MAX_CSS_VALIDATION_BYTES,\n validateCssContent,\n validateHtmlContent,\n} from \"./w3c-validator.js\";\n\nexport const SERVER_VERSION = PACKAGE_VERSION;\n\nconst HTML_MAX_BYTES = 2_000_000;\nconst CSS_MAX_BYTES = MAX_CSS_VALIDATION_BYTES;\nconst PATH_MAX_LENGTH = 4_096;\nconst MAX_VIEWPORTS = 8;\n\nconst filePathSchema = z.string().trim().min(1).max(PATH_MAX_LENGTH);\nconst htmlContentSchema = z.string().min(1).max(HTML_MAX_BYTES);\nconst publicUrlSchema = z\n .string()\n .url()\n .refine((value) => {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n }, \"URL must use HTTP or HTTPS.\");\n\nconst w3cMessageSchema = z.object({\n type: z.string(),\n message: z.string(),\n lastLine: z.number().int().optional(),\n lastColumn: z.number().int().optional(),\n firstLine: z.number().int().optional(),\n firstColumn: z.number().int().optional(),\n extract: z.string().optional(),\n});\n\nconst cssMessageSchema = z.object({\n line: z.number().int(),\n type: z.string(),\n message: z.string(),\n context: z.string().optional(),\n});\n\nconst seoIssueSchema = z.object({\n severity: z.enum([\"error\", \"warning\", \"info\"]),\n category: z.enum([\"SEO\", \"Schema\", \"BrokenLinks\", \"Accessibility\"]),\n message: z.string(),\n element: z.string().optional(),\n});\n\nconst linkStatusSchema = z.object({\n url: z.string(),\n status: z.union([z.number().int(), z.enum([\"blocked\", \"failed\"])]),\n ok: z.boolean(),\n message: z.string().optional(),\n});\n\nconst screenshotSchema = z.object({\n viewportName: z.string(),\n width: z.number().int(),\n height: z.number().int(),\n outputPath: z.string(),\n});\n\nconst reportSummarySchema = z.object({\n overallScore: z.number().int().min(0).max(100).nullable(),\n htmlScore: z.number().int().min(0).max(100).nullable(),\n cssScore: z.number().int().min(0).max(100).nullable(),\n seoScore: z.number().int().min(0).max(100).nullable(),\n linkScore: z.number().int().min(0).max(100).nullable(),\n htmlErrors: z.number().int().nonnegative(),\n htmlWarnings: z.number().int().nonnegative(),\n cssErrors: z.number().int().nonnegative(),\n seoErrors: z.number().int().nonnegative(),\n seoWarnings: z.number().int().nonnegative(),\n schemaErrors: z.number().int().nonnegative(),\n linksChecked: z.number().int().nonnegative(),\n brokenLinks: z.number().int().nonnegative(),\n});\n\nconst externalReadOnlyAnnotations = {\n // These calls contact external recipients but do not modify external state.\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n} as const;\n\nconst localReadOnlyAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nfunction result<T extends object>(\n structuredContent: T,\n content: string,\n isError = false,\n): CallToolResult {\n return {\n structuredContent: structuredContent as Record<string, unknown>,\n content: [\n {\n type: \"text\",\n text: content,\n },\n ],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction failedReport(filePath: string, error: string): ValidationReport {\n return {\n report: `Validation report could not be generated: ${error}`,\n summary: {\n overallScore: null,\n htmlScore: null,\n cssScore: null,\n seoScore: null,\n linkScore: null,\n htmlErrors: 0,\n htmlWarnings: 0,\n cssErrors: 0,\n seoErrors: 0,\n seoWarnings: 0,\n schemaErrors: 0,\n linksChecked: 0,\n brokenLinks: 0,\n },\n htmlMessages: [],\n cssMessages: [],\n seoIssues: [],\n schemaIssues: [],\n links: [],\n failedChecks: [\"input\"],\n errors: [`${path.basename(filePath || \"document\")}: ${error}`],\n };\n}\n\ninterface ValidationReportDependencies {\n readTextFile: typeof readTextFile;\n validateHtmlContent: typeof validateHtmlContent;\n validateCssContent: typeof validateCssContent;\n auditSeoMetadata: typeof auditSeoMetadata;\n validateSchemaMarkup: typeof validateSchemaMarkup;\n checkBrokenLinks: typeof checkBrokenLinks;\n}\n\nconst validationReportDependencies: ValidationReportDependencies = {\n readTextFile,\n validateHtmlContent,\n validateCssContent,\n auditSeoMetadata,\n validateSchemaMarkup,\n checkBrokenLinks,\n};\n\nexport interface GenerateValidationReportOptions {\n htmlFilePath: string;\n cssFilePath?: string;\n baseUrl?: string;\n}\n\n/** Runs independent validation checks without discarding successful results when another check fails. */\nexport async function generateValidationReport(\n { htmlFilePath, cssFilePath, baseUrl }: GenerateValidationReportOptions,\n dependencies: ValidationReportDependencies = validationReportDependencies,\n): Promise<ValidationReport> {\n const html = await dependencies.readTextFile(htmlFilePath, HTML_MAX_BYTES);\n const failedChecks: ValidationReportCheck[] = [];\n const errors: string[] = [];\n const recordFailure = (check: ValidationReportCheck, label: string, cause: unknown): void => {\n if (!failedChecks.includes(check)) {\n failedChecks.push(check);\n }\n errors.push(`${label} was unavailable: ${getErrorMessage(cause)}`);\n };\n\n let css: string | undefined;\n if (cssFilePath) {\n try {\n css = await dependencies.readTextFile(cssFilePath, CSS_MAX_BYTES);\n } catch (cause) {\n recordFailure(\"css\", \"CSS validation\", cause);\n }\n }\n\n const [htmlResult, cssResult, seoResult, schemaResult, linksResult] = await Promise.allSettled([\n dependencies.validateHtmlContent(html),\n css === undefined ? Promise.resolve([]) : dependencies.validateCssContent(css),\n Promise.resolve().then(() => dependencies.auditSeoMetadata(html)),\n Promise.resolve().then(() => dependencies.validateSchemaMarkup(html)),\n dependencies.checkBrokenLinks(html, baseUrl, 25),\n ]);\n\n if (htmlResult.status === \"rejected\") recordFailure(\"html\", \"HTML validation\", htmlResult.reason);\n if (cssResult.status === \"rejected\") recordFailure(\"css\", \"CSS validation\", cssResult.reason);\n if (seoResult.status === \"rejected\") recordFailure(\"seo\", \"SEO analysis\", seoResult.reason);\n if (schemaResult.status === \"rejected\") recordFailure(\"schema\", \"JSON-LD analysis\", schemaResult.reason);\n if (linksResult.status === \"rejected\") recordFailure(\"links\", \"Link checking\", linksResult.reason);\n\n return createValidationReport({\n htmlFilePath,\n cssAudited: css !== undefined,\n htmlMessages: htmlResult.status === \"fulfilled\" ? htmlResult.value : [],\n cssMessages: cssResult.status === \"fulfilled\" ? cssResult.value : [],\n seoIssues: seoResult.status === \"fulfilled\" ? seoResult.value.slice(0, 200) : [],\n schemaIssues: schemaResult.status === \"fulfilled\" ? schemaResult.value.slice(0, 200) : [],\n links: linksResult.status === \"fulfilled\" ? linksResult.value : [],\n failedChecks,\n errors,\n });\n}\n\nexport function createServer(): McpServer {\n const server = new McpServer(\n { name: \"mcp-web-validator\", version: SERVER_VERSION },\n {\n instructions:\n \"Validate only files, markup, and public URLs the user owns or is authorized to inspect. HTML and CSS validation send supplied content to W3C-operated validators. Link checks contact public links without following redirects. Screenshot capture executes page content in a sandboxed local browser and writes PNG files.\",\n },\n );\n\n server.registerTool(\n \"html.local\",\n {\n title: \"Validate local HTML\",\n description:\n \"Reads a bounded local HTML file and sends its markup to the W3C Nu HTML Checker. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to an HTML file.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const html = await readTextFile(filePath, HTML_MAX_BYTES);\n const errors = await validateHtmlContent(html);\n return result({ errors }, htmlValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"HTML validation\",\n error,\n \"Confirm the file exists and is readable, then retry. If the W3C service is unavailable, try again later.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"html.url\",\n {\n title: \"Validate a public URL\",\n description:\n \"Fetches a bounded public HTTP(S) page, then sends its markup to the W3C Nu HTML Checker. Private, reserved, credentialed, and nonstandard-port destinations are rejected.\",\n inputSchema: {\n url: publicUrlSchema.describe(\"Public HTTP(S) URL on port 80 or 443.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n fetchedUrl: z.string().optional(),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ url }) => {\n try {\n const fetched = await fetchPublicText(url, {\n maxBytes: HTML_MAX_BYTES,\n timeoutMs: 15_000,\n maxRedirects: 3,\n acceptedContentTypes: [\"text/html\", \"application/xhtml+xml\"],\n headers: {\n accept: \"text/html,application/xhtml+xml;q=0.9\",\n \"user-agent\": `DigestSEO-Web-Validator/${SERVER_VERSION} (+https://digestseo.com/validator-mcp/)`,\n },\n });\n if (fetched.status < 200 || fetched.status >= 300) {\n throw new Error(`Target URL returned HTTP ${fetched.status}.`);\n }\n const errors = await validateHtmlContent(fetched.text);\n return result(\n { errors, fetchedUrl: fetched.url },\n htmlValidationContent(errors, fetched.url),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"URL validation\",\n error,\n \"Confirm the URL is public, uses HTTP or HTTPS on a standard port, and returns HTML, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"css.local\",\n {\n title: \"Validate local CSS\",\n description:\n \"Reads a bounded local CSS file and sends it to the W3C Jigsaw CSS Validator. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to a CSS file.\"),\n },\n outputSchema: {\n errors: z.array(cssMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const css = await readTextFile(filePath, CSS_MAX_BYTES);\n const errors = await validateCssContent(css);\n return result({ errors }, cssValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"CSS validation\",\n error,\n \"Confirm the file exists, is readable, and is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"seo.metadata\",\n {\n title: \"Audit SEO metadata\",\n description:\n \"Analyzes supplied HTML locally for metadata, heading structure, viewport configuration, image alternatives, and Open Graph fields.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup to inspect locally.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = auditSeoMetadataDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n seoAuditContent(issues, totalIssues, truncated),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"SEO audit\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"links.broken\",\n {\n title: \"Check public links\",\n description:\n \"Resolves and checks up to 25 public HTTP(S) links in supplied HTML. Redirects are reported but not followed, and response bodies are discarded.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup containing links to check.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n maxLinks: z\n .number()\n .int()\n .min(1)\n .max(25)\n .default(25)\n .describe(\"Maximum number of public HTTP(S) links to check, from 1 to 25.\"),\n },\n outputSchema: {\n links: z.array(linkStatusSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlContent, baseUrl, maxLinks }) => {\n try {\n const links = await checkBrokenLinks(htmlContent, baseUrl, maxLinks);\n return result({ links }, linkCheckContent(links, baseUrl));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { links: [], error },\n failureContent(\n \"Link check\",\n error,\n \"Confirm the base URL is public and the supplied HTML is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"schema.markup\",\n {\n title: \"Validate JSON-LD syntax\",\n description:\n \"Parses JSON-LD blocks in supplied HTML locally and reports empty blocks or JSON syntax errors. It does not validate vocabulary semantics.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML containing JSON-LD script blocks.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = validateSchemaMarkupDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n schemaValidationContent(issues, totalIssues, truncated, htmlContent),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"JSON-LD syntax\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"report.validation\",\n {\n title: \"Generate a validation report\",\n description:\n \"Combines W3C HTML/CSS validation, local SEO/accessibility checks, JSON-LD syntax checks, and a bounded public-link check into a Markdown and structured report.\",\n inputSchema: {\n htmlFilePath: filePathSchema.describe(\"Absolute or workspace-relative HTML file path.\"),\n cssFilePath: filePathSchema\n .optional()\n .describe(\"Optional absolute or workspace-relative CSS file path.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n },\n outputSchema: {\n report: z.string(),\n summary: reportSummarySchema,\n htmlMessages: z.array(w3cMessageSchema),\n cssMessages: z.array(cssMessageSchema),\n seoIssues: z.array(seoIssueSchema),\n schemaIssues: z.array(seoIssueSchema),\n links: z.array(linkStatusSchema),\n failedChecks: z.array(z.enum(validationReportChecks)),\n errors: z.array(z.string()).optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlFilePath, cssFilePath, baseUrl }) => {\n try {\n const reportData = await generateValidationReport({\n htmlFilePath,\n cssFilePath,\n baseUrl,\n });\n return result(reportData, reportContent(reportData));\n } catch (cause) {\n const error = getErrorMessage(cause);\n const reportData = failedReport(htmlFilePath, error);\n return result(\n reportData,\n failureContent(\n \"Validation report\",\n error,\n \"Confirm the input paths are readable and any base URL is public, then regenerate the report.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"screenshot.capture\",\n {\n title: \"Capture responsive screenshots\",\n description:\n \"Renders a local HTML file or HTTP(S) URL in a sandboxed local Chromium browser and writes PNG screenshots to the requested directory. Existing matching files may be replaced.\",\n inputSchema: {\n targetPath: z\n .string()\n .trim()\n .min(1)\n .max(PATH_MAX_LENGTH)\n .describe(\"Local HTML path or HTTP(S) URL to render.\"),\n outputDir: filePathSchema\n .optional()\n .default(\".mcp-validator/screenshots\")\n .describe(\"Directory where PNG screenshots will be written.\"),\n viewports: z\n .array(\n z.object({\n name: z\n .string()\n .regex(/^[A-Za-z0-9_-]{1,50}$/)\n .describe(\"Safe filename label for this screenshot viewport.\"),\n width: z\n .number()\n .int()\n .min(200)\n .max(3_840)\n .describe(\"Viewport width in CSS pixels, from 200 to 3840.\"),\n height: z\n .number()\n .int()\n .min(200)\n .max(4_320)\n .describe(\"Viewport height in CSS pixels, from 200 to 4320.\"),\n }),\n )\n .min(1)\n .max(MAX_VIEWPORTS)\n .optional()\n .describe(\"Optional viewport definitions; defaults to desktop, tablet, and mobile sizes.\"),\n },\n outputSchema: {\n screenshots: z.array(screenshotSchema),\n outputDirectory: z.string(),\n error: z.string().optional(),\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async ({ targetPath, outputDir, viewports }) => {\n const outputDirectory = path.resolve(outputDir);\n try {\n const screenshots = await captureScreenshots(targetPath, outputDirectory, viewports);\n return result(\n { screenshots, outputDirectory },\n screenshotCaptureContent(screenshots.length, outputDirectory),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { screenshots: [], outputDirectory, error },\n failureContent(\n \"Screenshot capture\",\n error,\n \"Confirm the target is reachable or readable and the output directory is writable, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n return server;\n}\n\nexport async function run(): Promise<void> {\n const server = createServer();\n await server.connect(new StdioServerTransport());\n console.error(`mcp-web-validator ${SERVER_VERSION} started on stdio`);\n}\n\nconst invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : undefined;\nif (invokedPath === import.meta.url) {\n run().catch((cause: unknown) => {\n console.error(\"Fatal error starting mcp-web-validator:\", getErrorMessage(cause));\n process.exitCode = 1;\n });\n}\n"]}
package/dist/network.d.ts CHANGED
@@ -6,6 +6,7 @@ export interface PublicFetchOptions {
6
6
  }
7
7
  export interface PublicTextOptions extends PublicFetchOptions {
8
8
  maxBytes?: number;
9
+ acceptedContentTypes?: readonly string[];
9
10
  }
10
11
  export interface PublicTextResult {
11
12
  text: string;
package/dist/network.js CHANGED
@@ -254,11 +254,18 @@ export async function fetchPublicText(input, options = {}) {
254
254
  await cancelResponseBody(response);
255
255
  throw new Error(`URL returned HTTP status ${status}`);
256
256
  }
257
+ const contentTypeHeader = response.headers.get("content-type");
258
+ const contentType = contentTypeHeader?.split(";", 1)[0]?.trim().toLowerCase() || null;
259
+ if (options.acceptedContentTypes
260
+ && !options.acceptedContentTypes.some((accepted) => accepted.trim().toLowerCase() === contentType)) {
261
+ await cancelResponseBody(response);
262
+ throw new Error(`URL returned unsupported content type ${contentType ?? "missing"}`);
263
+ }
257
264
  return {
258
265
  text: await readResponseText(response, maxBytes),
259
266
  url: url.href,
260
267
  status: response.status,
261
- contentType: response.headers.get("content-type"),
268
+ contentType: contentTypeHeader,
262
269
  };
263
270
  }
264
271
  /** Reads a UTF-8 file only when it is a regular file within the requested cap. */
@@ -1 +1 @@
1
- {"version":3,"file":"network.js","sourceRoot":"","sources":["../src/network.ts"],"names":[],"mapp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IACjD,IAAI,QAAQ,CAAC,UAAU,GAAG,QAAQ,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,gBAAgB,YAAY,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import { lookup } from \"node:dns/promises\";\nimport * as fs from \"node:fs/promises\";\nimport { BlockList, isIP } from \"node:net\";\nimport * as path from \"node:path\";\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_REDIRECTS = 5;\nconst DNS_TIMEOUT_MS = 5_000;\nconst MAX_URL_LENGTH = 8_192;\n\nconst blockedAddresses = new BlockList();\nfor (const [network, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10],\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16],\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv4\");\n}\n\nfor (const [network, prefix] of [\n [\"::\", 96],\n [\"fc00::\", 7],\n [\"fe80::\", 10],\n [\"ff00::\", 8],\n [\"2001::\", 32],\n [\"2001:2::\", 48],\n [\"2001:10::\", 28],\n [\"2001:db8::\", 32],\n [\"2002::\", 16],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv6\");\n}\n\nconst publicIpv6Addresses = new BlockList();\npublicIpv6Addresses.addSubnet(\"2000::\", 3, \"ipv6\");\n\nconst blockedHostnames = new Set([\n \"localhost\",\n \"localhost.localdomain\",\n \"ip6-localhost\",\n \"ip6-loopback\",\n]);\n\nconst blockedHostnameSuffixes = [\n \".localhost\",\n \".local\",\n \".internal\",\n \".home.arpa\",\n \".test\",\n \".invalid\",\n \".example\",\n \".onion\",\n];\n\nconst redirectStatuses = new Set([301, 302, 303, 307, 308]);\n\nexport interface PublicFetchOptions {\n method?: \"GET\" | \"HEAD\";\n headers?: Record<string, string>;\n timeoutMs?: number;\n maxRedirects?: number;\n}\n\nexport interface PublicTextOptions extends PublicFetchOptions {\n maxBytes?: number;\n}\n\nexport interface PublicTextResult {\n text: string;\n url: string;\n status: number;\n contentType: string | null;\n}\n\nexport interface PublicHttpResult {\n response: Response;\n url: URL;\n}\n\nexport class PublicUrlError extends Error {\n override readonly name = \"PublicUrlError\";\n}\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n if (error.name === \"TimeoutError\" || error.name === \"AbortError\") {\n return \"Request timed out\";\n }\n return error.message || error.name;\n }\n\n return typeof error === \"string\" && error.trim() ? error : \"Unknown error\";\n}\n\nfunction assertPositiveInteger(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${label} must be a positive integer`);\n }\n}\n\nfunction normalizeHostname(hostname: string): string {\n const withoutBrackets = hostname.startsWith(\"[\") && hostname.endsWith(\"]\")\n ? hostname.slice(1, -1)\n : hostname;\n return withoutBrackets.replace(/\\.$/, \"\").toLowerCase();\n}\n\nfunction isPublicAddress(address: string, family: number): boolean {\n if (family === 4) {\n return !blockedAddresses.check(address, \"ipv4\");\n }\n\n if (family === 6) {\n return publicIpv6Addresses.check(address, \"ipv6\")\n && !blockedAddresses.check(address, \"ipv6\");\n }\n\n return false;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n let timeout: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);\n }),\n ]);\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n}\n\n/**\n * Parses an HTTP(S) URL and rejects hostnames that resolve to local, private,\n * documentation, multicast, or otherwise non-public address space.\n */\nexport async function assertPublicHttpUrl(input: string | URL): Promise<URL> {\n const rawUrl = input instanceof URL ? input.href : input;\n if (typeof rawUrl !== \"string\" || rawUrl.length === 0 || rawUrl.length > MAX_URL_LENGTH) {\n throw new PublicUrlError(`URL must contain between 1 and ${MAX_URL_LENGTH} characters`);\n }\n\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n throw new PublicUrlError(\"URL must be an absolute HTTP or HTTPS URL\");\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new PublicUrlError(\"Only HTTP and HTTPS URLs are allowed\");\n }\n if (parsed.username || parsed.password) {\n throw new PublicUrlError(\"URLs containing credentials are not allowed\");\n }\n if (parsed.port && parsed.port !== \"80\" && parsed.port !== \"443\") {\n throw new PublicUrlError(\"Only standard HTTP ports 80 and 443 are allowed\");\n }\n\n parsed.hash = \"\";\n const hostname = normalizeHostname(parsed.hostname);\n if (!hostname) {\n throw new PublicUrlError(\"URL hostname is required\");\n }\n if (\n blockedHostnames.has(hostname)\n || blockedHostnameSuffixes.some((suffix) => hostname.endsWith(suffix))\n ) {\n throw new PublicUrlError(`URL hostname \"${hostname}\" is not public`);\n }\n\n const literalFamily = isIP(hostname);\n const resolvedAddresses = literalFamily\n ? [{ address: hostname, family: literalFamily }]\n : await withTimeout(\n lookup(hostname, { all: true, verbatim: true }),\n DNS_TIMEOUT_MS,\n \"DNS lookup\",\n ).catch((error: unknown) => {\n throw new PublicUrlError(`Unable to resolve URL hostname: ${getErrorMessage(error)}`);\n });\n\n if (resolvedAddresses.length === 0) {\n throw new PublicUrlError(\"URL hostname did not resolve to an address\");\n }\n\n for (const record of resolvedAddresses) {\n if (!isPublicAddress(record.address, record.family)) {\n throw new PublicUrlError(`URL hostname resolves to non-public address ${record.address}`);\n }\n }\n\n return parsed;\n}\n\nexport async function cancelResponseBody(response: Response): Promise<void> {\n if (!response.body) {\n return;\n }\n\n try {\n await response.body.cancel();\n } catch {\n // The stream may already be closed or consumed; there is nothing left to release.\n }\n}\n\nexport async function readResponseText(response: Response, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const declaredLength = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n await cancelResponseBody(response);\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let text = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n text += decoder.decode(value, { stream: true });\n }\n text += decoder.decode();\n return text;\n } finally {\n reader.releaseLock();\n }\n}\n\n/** Fetches a public HTTP(S) URL while validating every redirect target. */\nexport async function fetchPublicHttp(\n input: string | URL,\n options: PublicFetchOptions = {},\n): Promise<PublicHttpResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;\n assertPositiveInteger(timeoutMs, \"timeoutMs\");\n if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n throw new Error(\"maxRedirects must be an integer between 0 and 10\");\n }\n\n let currentUrl = await assertPublicHttpUrl(input);\n for (let redirectCount = 0; ; redirectCount += 1) {\n const response = await fetch(currentUrl, {\n method: options.method ?? \"GET\",\n headers: options.headers,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n\n if (!redirectStatuses.has(response.status)) {\n return { response, url: currentUrl };\n }\n\n const location = response.headers.get(\"location\");\n if (!location) {\n return { response, url: currentUrl };\n }\n\n if (redirectCount >= maxRedirects) {\n return { response, url: currentUrl };\n }\n\n await cancelResponseBody(response);\n let redirectUrl: URL;\n try {\n redirectUrl = new URL(location, currentUrl);\n } catch {\n throw new PublicUrlError(\"Redirect target is not a valid URL\");\n }\n currentUrl = await assertPublicHttpUrl(redirectUrl);\n }\n}\n\n/** Fetches bounded text from a public URL and rejects non-success responses. */\nexport async function fetchPublicText(\n input: string | URL,\n options: PublicTextOptions = {},\n): Promise<PublicTextResult> {\n const maxBytes = options.maxBytes ?? 2_000_000;\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const { response, url } = await fetchPublicHttp(input, {\n method: \"GET\",\n headers: options.headers,\n timeoutMs: options.timeoutMs,\n maxRedirects: options.maxRedirects,\n });\n\n if (!response.ok) {\n const status = response.status;\n await cancelResponseBody(response);\n throw new Error(`URL returned HTTP status ${status}`);\n }\n\n return {\n text: await readResponseText(response, maxBytes),\n url: url.href,\n status: response.status,\n contentType: response.headers.get(\"content-type\"),\n };\n}\n\n/** Reads a UTF-8 file only when it is a regular file within the requested cap. */\nexport async function readTextFile(filePath: string, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n const resolvedPath = path.resolve(filePath);\n const stats = await fs.stat(resolvedPath);\n if (!stats.isFile()) {\n throw new Error(`Path is not a regular file: ${resolvedPath}`);\n }\n if (stats.size > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n\n const contents = await fs.readFile(resolvedPath);\n if (contents.byteLength > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n return contents.toString(\"utf8\");\n}\n"]}
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../src/network.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,KAAK,IAAI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AC,MAAM,EAAE,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,+BAA+B,YAAY,EAAE,CAAC,CAAC;IACjE,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,GAAG,QAAQ,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,gBAAgB,YAAY,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;IACjD,IAAI,QAAQ,CAAC,UAAU,GAAG,QAAQ,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,gBAAgB,YAAY,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import { lookup } from \"node:dns/promises\";\nimport * as fs from \"node:fs/promises\";\nimport { BlockList, isIP } from \"node:net\";\nimport * as path from \"node:path\";\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_REDIRECTS = 5;\nconst DNS_TIMEOUT_MS = 5_000;\nconst MAX_URL_LENGTH = 8_192;\n\nconst blockedAddresses = new BlockList();\nfor (const [network, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10],\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16],\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv4\");\n}\n\nfor (const [network, prefix] of [\n [\"::\", 96],\n [\"fc00::\", 7],\n [\"fe80::\", 10],\n [\"ff00::\", 8],\n [\"2001::\", 32],\n [\"2001:2::\", 48],\n [\"2001:10::\", 28],\n [\"2001:db8::\", 32],\n [\"2002::\", 16],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv6\");\n}\n\nconst publicIpv6Addresses = new BlockList();\npublicIpv6Addresses.addSubnet(\"2000::\", 3, \"ipv6\");\n\nconst blockedHostnames = new Set([\n \"localhost\",\n \"localhost.localdomain\",\n \"ip6-localhost\",\n \"ip6-loopback\",\n]);\n\nconst blockedHostnameSuffixes = [\n \".localhost\",\n \".local\",\n \".internal\",\n \".home.arpa\",\n \".test\",\n \".invalid\",\n \".example\",\n \".onion\",\n];\n\nconst redirectStatuses = new Set([301, 302, 303, 307, 308]);\n\nexport interface PublicFetchOptions {\n method?: \"GET\" | \"HEAD\";\n headers?: Record<string, string>;\n timeoutMs?: number;\n maxRedirects?: number;\n}\n\nexport interface PublicTextOptions extends PublicFetchOptions {\n maxBytes?: number;\n acceptedContentTypes?: readonly string[];\n}\n\nexport interface PublicTextResult {\n text: string;\n url: string;\n status: number;\n contentType: string | null;\n}\n\nexport interface PublicHttpResult {\n response: Response;\n url: URL;\n}\n\nexport class PublicUrlError extends Error {\n override readonly name = \"PublicUrlError\";\n}\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n if (error.name === \"TimeoutError\" || error.name === \"AbortError\") {\n return \"Request timed out\";\n }\n return error.message || error.name;\n }\n\n return typeof error === \"string\" && error.trim() ? error : \"Unknown error\";\n}\n\nfunction assertPositiveInteger(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${label} must be a positive integer`);\n }\n}\n\nfunction normalizeHostname(hostname: string): string {\n const withoutBrackets = hostname.startsWith(\"[\") && hostname.endsWith(\"]\")\n ? hostname.slice(1, -1)\n : hostname;\n return withoutBrackets.replace(/\\.$/, \"\").toLowerCase();\n}\n\nfunction isPublicAddress(address: string, family: number): boolean {\n if (family === 4) {\n return !blockedAddresses.check(address, \"ipv4\");\n }\n\n if (family === 6) {\n return publicIpv6Addresses.check(address, \"ipv6\")\n && !blockedAddresses.check(address, \"ipv6\");\n }\n\n return false;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n let timeout: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);\n }),\n ]);\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n}\n\n/**\n * Parses an HTTP(S) URL and rejects hostnames that resolve to local, private,\n * documentation, multicast, or otherwise non-public address space.\n */\nexport async function assertPublicHttpUrl(input: string | URL): Promise<URL> {\n const rawUrl = input instanceof URL ? input.href : input;\n if (typeof rawUrl !== \"string\" || rawUrl.length === 0 || rawUrl.length > MAX_URL_LENGTH) {\n throw new PublicUrlError(`URL must contain between 1 and ${MAX_URL_LENGTH} characters`);\n }\n\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n throw new PublicUrlError(\"URL must be an absolute HTTP or HTTPS URL\");\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new PublicUrlError(\"Only HTTP and HTTPS URLs are allowed\");\n }\n if (parsed.username || parsed.password) {\n throw new PublicUrlError(\"URLs containing credentials are not allowed\");\n }\n if (parsed.port && parsed.port !== \"80\" && parsed.port !== \"443\") {\n throw new PublicUrlError(\"Only standard HTTP ports 80 and 443 are allowed\");\n }\n\n parsed.hash = \"\";\n const hostname = normalizeHostname(parsed.hostname);\n if (!hostname) {\n throw new PublicUrlError(\"URL hostname is required\");\n }\n if (\n blockedHostnames.has(hostname)\n || blockedHostnameSuffixes.some((suffix) => hostname.endsWith(suffix))\n ) {\n throw new PublicUrlError(`URL hostname \"${hostname}\" is not public`);\n }\n\n const literalFamily = isIP(hostname);\n const resolvedAddresses = literalFamily\n ? [{ address: hostname, family: literalFamily }]\n : await withTimeout(\n lookup(hostname, { all: true, verbatim: true }),\n DNS_TIMEOUT_MS,\n \"DNS lookup\",\n ).catch((error: unknown) => {\n throw new PublicUrlError(`Unable to resolve URL hostname: ${getErrorMessage(error)}`);\n });\n\n if (resolvedAddresses.length === 0) {\n throw new PublicUrlError(\"URL hostname did not resolve to an address\");\n }\n\n for (const record of resolvedAddresses) {\n if (!isPublicAddress(record.address, record.family)) {\n throw new PublicUrlError(`URL hostname resolves to non-public address ${record.address}`);\n }\n }\n\n return parsed;\n}\n\nexport async function cancelResponseBody(response: Response): Promise<void> {\n if (!response.body) {\n return;\n }\n\n try {\n await response.body.cancel();\n } catch {\n // The stream may already be closed or consumed; there is nothing left to release.\n }\n}\n\nexport async function readResponseText(response: Response, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const declaredLength = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n await cancelResponseBody(response);\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let text = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n text += decoder.decode(value, { stream: true });\n }\n text += decoder.decode();\n return text;\n } finally {\n reader.releaseLock();\n }\n}\n\n/** Fetches a public HTTP(S) URL while validating every redirect target. */\nexport async function fetchPublicHttp(\n input: string | URL,\n options: PublicFetchOptions = {},\n): Promise<PublicHttpResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;\n assertPositiveInteger(timeoutMs, \"timeoutMs\");\n if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n throw new Error(\"maxRedirects must be an integer between 0 and 10\");\n }\n\n let currentUrl = await assertPublicHttpUrl(input);\n for (let redirectCount = 0; ; redirectCount += 1) {\n const response = await fetch(currentUrl, {\n method: options.method ?? \"GET\",\n headers: options.headers,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n\n if (!redirectStatuses.has(response.status)) {\n return { response, url: currentUrl };\n }\n\n const location = response.headers.get(\"location\");\n if (!location) {\n return { response, url: currentUrl };\n }\n\n if (redirectCount >= maxRedirects) {\n return { response, url: currentUrl };\n }\n\n await cancelResponseBody(response);\n let redirectUrl: URL;\n try {\n redirectUrl = new URL(location, currentUrl);\n } catch {\n throw new PublicUrlError(\"Redirect target is not a valid URL\");\n }\n currentUrl = await assertPublicHttpUrl(redirectUrl);\n }\n}\n\n/** Fetches bounded text from a public URL and rejects non-success responses. */\nexport async function fetchPublicText(\n input: string | URL,\n options: PublicTextOptions = {},\n): Promise<PublicTextResult> {\n const maxBytes = options.maxBytes ?? 2_000_000;\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const { response, url } = await fetchPublicHttp(input, {\n method: \"GET\",\n headers: options.headers,\n timeoutMs: options.timeoutMs,\n maxRedirects: options.maxRedirects,\n });\n\n if (!response.ok) {\n const status = response.status;\n await cancelResponseBody(response);\n throw new Error(`URL returned HTTP status ${status}`);\n }\n\n const contentTypeHeader = response.headers.get(\"content-type\");\n const contentType = contentTypeHeader?.split(\";\", 1)[0]?.trim().toLowerCase() || null;\n if (\n options.acceptedContentTypes\n && !options.acceptedContentTypes.some((accepted) => accepted.trim().toLowerCase() === contentType)\n ) {\n await cancelResponseBody(response);\n throw new Error(`URL returned unsupported content type ${contentType ?? \"missing\"}`);\n }\n\n return {\n text: await readResponseText(response, maxBytes),\n url: url.href,\n status: response.status,\n contentType: contentTypeHeader,\n };\n}\n\n/** Reads a UTF-8 file only when it is a regular file within the requested cap. */\nexport async function readTextFile(filePath: string, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n const resolvedPath = path.resolve(filePath);\n const stats = await fs.stat(resolvedPath);\n if (!stats.isFile()) {\n throw new Error(`Path is not a regular file: ${resolvedPath}`);\n }\n if (stats.size > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n\n const contents = await fs.readFile(resolvedPath);\n if (contents.byteLength > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n return contents.toString(\"utf8\");\n}\n"]}
@@ -29,6 +29,9 @@ function createIssueCollector() {
29
29
  },
30
30
  };
31
31
  }
32
+ function isJsonLdScriptType(type) {
33
+ return type?.split(";", 1)[0].trim().toLowerCase() === "application/ld+json";
34
+ }
32
35
  /**
33
36
  * Audits technical SEO and accessibility basics on HTML content using Cheerio
34
37
  */
@@ -128,16 +131,16 @@ export function auditSeoMetadataDetailed(htmlContent) {
128
131
  const h1Tags = $("h1");
129
132
  if (h1Tags.length === 0) {
130
133
  add({
131
- severity: "error",
134
+ severity: "warning",
132
135
  category: "SEO",
133
- message: "Missing <h1> tag. Every page must have exactly one <h1> representing the main topic.",
136
+ message: "No <h1> heading found. Review whether the page has a clear main heading and a meaningful heading hierarchy.",
134
137
  });
135
138
  }
136
139
  else if (h1Tags.length > 1) {
137
140
  add({
138
- severity: "warning",
141
+ severity: "info",
139
142
  category: "SEO",
140
- message: `Found multiple (${h1Tags.length}) <h1> tags. Multiple <h1> tags dilutes topic keyword focus.`,
143
+ message: `Found multiple (${h1Tags.length}) <h1> headings. Multiple H1s are not inherently an SEO error; ensure the heading hierarchy is meaningful and the main visual title is clear.`,
141
144
  });
142
145
  }
143
146
  // --- Images Alt Tags (SEO + Accessibility) ---
@@ -185,7 +188,8 @@ export function validateSchemaMarkupDetailed(htmlContent) {
185
188
  const $ = cheerio.load(htmlContent);
186
189
  const collector = createIssueCollector();
187
190
  const { add } = collector;
188
- $('script[type="application/ld+json"]').each((index, element) => {
191
+ const blocks = $("script[type]").filter((_, element) => isJsonLdScriptType($(element).attr("type")));
192
+ blocks.each((index, element) => {
189
193
  const scriptText = $(element).html() || "";
190
194
  if (scriptText.trim() === "") {
191
195
  add({
@@ -221,7 +225,20 @@ export async function checkBrokenLinks(htmlContent, baseUrl, maxLinks = MAX_LINK
221
225
  }
222
226
  const linkLimit = Math.min(maxLinks, MAX_LINKS_TO_CHECK);
223
227
  const $ = cheerio.load(htmlContent);
224
- const parsedBaseUrl = baseUrl ? await assertPublicHttpUrl(baseUrl) : undefined;
228
+ let parsedBaseUrl = baseUrl ? await assertPublicHttpUrl(baseUrl) : undefined;
229
+ if (!parsedBaseUrl) {
230
+ const documentBaseHref = $("base[href]").first().attr("href")?.trim();
231
+ if (documentBaseHref) {
232
+ try {
233
+ parsedBaseUrl = await assertPublicHttpUrl(documentBaseHref);
234
+ }
235
+ catch (error) {
236
+ if (!(error instanceof PublicUrlError)) {
237
+ throw error;
238
+ }
239
+ }
240
+ }
241
+ }
225
242
  const urls = [];
226
243
  const seenUrls = new Set();
227
244
  $("a").each((_, element) => {
@@ -1 +1 @@
1
- {"version":3,"file":"seo-auditor.js","sourceRoot":"","sources":["../src/seo-auditor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAC;AACnC,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,cAAc,GACf,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AACpC,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AACrC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,qBAAqB,GAAG,qBAAqB,eAAe,0CAA0C,CAAC;AAsB7G,SAAS,QAAQ,CAAC,MAAkB,EAAE,KAAe;IACnD,IAAI,MAAM,C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OAAO;YACT,CAAC;YACD,OAAO,CAAC,KAAK,CAAC,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,sBAAsB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAClE,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IACvE,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import * as cheerio from \"cheerio\";\nimport {\n assertPublicHttpUrl,\n cancelResponseBody,\n fetchPublicHttp,\n getErrorMessage,\n PublicUrlError,\n} from \"./network.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\n\nexport const MAX_AUDIT_ISSUES = 200;\nexport const MAX_LINKS_TO_CHECK = 25;\nconst LINK_CHECK_CONCURRENCY = 5;\nconst LINK_CHECK_TIMEOUT_MS = 5_000;\nconst LINK_CHECK_USER_AGENT = `mcp-web-validator/${PACKAGE_VERSION} (+https://digestseo.com/validator-mcp/)`;\n\nexport interface SEOIssue {\n severity: \"error\" | \"warning\" | \"info\";\n category: \"SEO\" | \"Schema\" | \"BrokenLinks\" | \"Accessibility\";\n message: string;\n element?: string;\n}\n\nexport interface LinkStatus {\n url: string;\n status: number | string;\n ok: boolean;\n message?: string;\n}\n\nexport interface AuditDetails {\n issues: SEOIssue[];\n totalIssues: number;\n truncated: boolean;\n}\n\nfunction addIssue(issues: SEOIssue[], issue: SEOIssue): void {\n if (issues.length < MAX_AUDIT_ISSUES) {\n issues.push(issue);\n }\n}\n\nfunction createIssueCollector(): {\n issues: SEOIssue[];\n add: (issue: SEOIssue) => void;\n details: () => AuditDetails;\n} {\n const issues: SEOIssue[] = [];\n let totalIssues = 0;\n return {\n issues,\n add(issue) {\n totalIssues += 1;\n addIssue(issues, issue);\n },\n details() {\n return {\n issues,\n totalIssues,\n truncated: totalIssues > issues.length,\n };\n },\n };\n}\n\n/**\n * Audits technical SEO and accessibility basics on HTML content using Cheerio\n */\nexport function auditSeoMetadataDetailed(htmlContent: string): AuditDetails {\n const $ = cheerio.load(htmlContent);\n const collector = createIssueCollector();\n const { add } = collector;\n\n // --- Title Tag Audits ---\n const titleTag = $(\"title\");\n if (titleTag.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Missing <title> tag. Add a concise, descriptive title to help represent the page in search results.\",\n });\n } else {\n const titleText = titleTag.text().trim();\n if (titleText.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"The <title> tag is empty.\",\n });\n } else if (titleText.length < 30) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Title is ${titleText.length} characters. This is shorter than the audit's common editorial range; review whether it describes the page clearly.`,\n element: `<title>${titleText}</title>`,\n });\n } else if (titleText.length > 60) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Title is ${titleText.length} characters. This is longer than the audit's common editorial range; Google title links may be shortened or rewritten depending on context and device.`,\n element: `<title>${titleText}</title>`,\n });\n }\n }\n\n // --- Meta Description Audits ---\n const metaDescription = $('meta[name=\"description\"]');\n if (metaDescription.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Missing <meta name=\\\"description\\\">. Add a concise, accurate page summary; Google may use page content or this description to generate a snippet.\",\n });\n } else {\n const descText = metaDescription.attr(\"content\")?.trim() || \"\";\n if (descText.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Meta description content attribute is empty.\",\n });\n } else if (descText.length < 120) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Meta description is ${descText.length} characters. This is shorter than the audit's common editorial range; review whether it provides a useful page summary.`,\n element: `<meta name=\"description\" content=\"${descText}\">`,\n });\n } else if (descText.length > 160) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Meta description is ${descText.length} characters. This is longer than the audit's common editorial range; displayed snippets may be shortened depending on the query and device.`,\n element: `<meta name=\"description\" content=\"${descText}\">`,\n });\n }\n }\n\n // --- Canonical Link ---\n const canonical = $('link[rel=\"canonical\"]');\n if (canonical.length === 0) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: \"Missing canonical tag (<link rel=\\\"canonical\\\">). This helps prevent duplicate content issues.\",\n });\n }\n\n // --- Viewport Meta Tag (Mobile Responsiveness) ---\n const viewport = $('meta[name=\"viewport\"]');\n if (viewport.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Missing <meta name=\\\"viewport\\\"> tag. Review mobile rendering; this tag helps browsers size and scale the page on mobile devices.\",\n });\n }\n\n // --- Heading Structure ---\n const h1Tags = $(\"h1\");\n if (h1Tags.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Missing <h1> tag. Every page must have exactly one <h1> representing the main topic.\",\n });\n } else if (h1Tags.length > 1) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Found multiple (${h1Tags.length}) <h1> tags. Multiple <h1> tags dilutes topic keyword focus.`,\n });\n }\n\n // --- Images Alt Tags (SEO + Accessibility) ---\n $(\"img\").each((_, element) => {\n const img = $(element);\n const src = img.attr(\"src\") || \"unknown-source\";\n const alt = img.attr(\"alt\");\n\n if (alt === undefined) {\n add({\n severity: \"error\",\n category: \"Accessibility\",\n message: \"Missing 'alt' attribute on image. This makes it inaccessible to screen readers.\",\n element: `<img src=\"${src}\">`,\n });\n } else if (alt.trim() === \"\") {\n // Empty alt is acceptable for purely decorative images, but worth warning\n add({\n severity: \"info\",\n category: \"Accessibility\",\n message: \"Empty 'alt' attribute found. Ensure this image is purely decorative, otherwise add descriptive text.\",\n element: `<img src=\"${src}\" alt=\"\">`,\n });\n }\n });\n\n // --- Open Graph / Social Tags ---\n const ogTitle = $('meta[property=\"og:title\"]');\n const ogImage = $('meta[property=\"og:image\"]');\n if (ogTitle.length === 0 || ogImage.length === 0) {\n add({\n severity: \"info\",\n category: \"SEO\",\n message: \"Missing Open Graph social metadata (og:title / og:image). Add these to control preview cards on platforms like LinkedIn and X.\",\n });\n }\n\n return collector.details();\n}\n\nexport function auditSeoMetadata(htmlContent: string): SEOIssue[] {\n return auditSeoMetadataDetailed(htmlContent).issues;\n}\n\n/**\n * Parses and validates JSON-LD Schema markup\n */\nexport function validateSchemaMarkupDetailed(htmlContent: string): AuditDetails {\n const $ = cheerio.load(htmlContent);\n const collector = createIssueCollector();\n const { add } = collector;\n\n $('script[type=\"application/ld+json\"]').each((index, element) => {\n const scriptText = $(element).html() || \"\";\n if (scriptText.trim() === \"\") {\n add({\n severity: \"warning\",\n category: \"Schema\",\n message: `JSON-LD block #${index + 1} is empty.`,\n });\n return;\n }\n\n try {\n JSON.parse(scriptText);\n } catch (error: unknown) {\n add({\n severity: \"error\",\n category: \"Schema\",\n message: `Invalid JSON-LD schema syntax: ${getErrorMessage(error)}`,\n element: `<script type=\"application/ld+json\">...</script>`,\n });\n }\n });\n\n return collector.details();\n}\n\nexport function validateSchemaMarkup(htmlContent: string): SEOIssue[] {\n return validateSchemaMarkupDetailed(htmlContent).issues;\n}\n\n/**\n * Extracts and tests links, treating 3xx responses as reachable redirects and 4xx/5xx as broken.\n */\nexport async function checkBrokenLinks(\n htmlContent: string,\n baseUrl?: string,\n maxLinks = MAX_LINKS_TO_CHECK,\n): Promise<LinkStatus[]> {\n if (!Number.isSafeInteger(maxLinks) || maxLinks <= 0) {\n throw new Error(\"maxLinks must be a positive integer\");\n }\n const linkLimit = Math.min(maxLinks, MAX_LINKS_TO_CHECK);\n const $ = cheerio.load(htmlContent);\n const parsedBaseUrl = baseUrl ? await assertPublicHttpUrl(baseUrl) : undefined;\n const urls: string[] = [];\n const seenUrls = new Set<string>();\n\n $(\"a\").each((_, element) => {\n if (urls.length >= linkLimit) {\n return false;\n }\n\n const href = $(element).attr(\"href\")?.trim();\n if (!href || href.startsWith(\"#\")) {\n return;\n }\n\n let resolvedUrl: URL;\n try {\n resolvedUrl = parsedBaseUrl ? new URL(href, parsedBaseUrl) : new URL(href);\n } catch {\n // Relative links require a public base URL; unsupported or malformed links are skipped.\n return;\n }\n\n if (resolvedUrl.protocol !== \"http:\" && resolvedUrl.protocol !== \"https:\") {\n return;\n }\n\n resolvedUrl.hash = \"\";\n const normalizedUrl = resolvedUrl.href;\n if (!seenUrls.has(normalizedUrl)) {\n seenUrls.add(normalizedUrl);\n urls.push(normalizedUrl);\n }\n });\n\n const results = new Array<LinkStatus>(urls.length);\n let nextIndex = 0;\n\n async function checkLink(url: string): Promise<LinkStatus> {\n try {\n const headResult = await fetchPublicHttp(url, {\n method: \"HEAD\",\n headers: { \"User-Agent\": LINK_CHECK_USER_AGENT },\n timeoutMs: LINK_CHECK_TIMEOUT_MS,\n maxRedirects: 0,\n });\n const headStatus = headResult.response.status;\n const headFinalUrl = headResult.url.href;\n await cancelResponseBody(headResult.response);\n\n // Some sites reject or do not implement HEAD even when the linked resource is available.\n if (headStatus === 405 || headStatus === 403 || headStatus === 501) {\n const getResult = await fetchPublicHttp(url, {\n method: \"GET\",\n headers: {\n Range: \"bytes=0-0\",\n \"User-Agent\": LINK_CHECK_USER_AGENT,\n },\n timeoutMs: LINK_CHECK_TIMEOUT_MS,\n maxRedirects: 0,\n });\n const status = getResult.response.status;\n const ok = status >= 200 && status < 400;\n const finalUrl = getResult.url.href;\n await cancelResponseBody(getResult.response);\n return {\n url,\n status,\n ok,\n message:\n status >= 300 && status < 400\n ? \"Redirect not followed\"\n : finalUrl !== url\n ? `Redirected to ${finalUrl}`\n : undefined,\n };\n }\n\n return {\n url,\n status: headStatus,\n ok: headStatus >= 200 && headStatus < 400,\n message:\n headStatus >= 300 && headStatus < 400\n ? \"Redirect not followed\"\n : headFinalUrl !== url\n ? `Redirected to ${headFinalUrl}`\n : undefined,\n };\n } catch (error: unknown) {\n return {\n url,\n status: error instanceof PublicUrlError ? \"blocked\" : \"failed\",\n ok: false,\n message: getErrorMessage(error),\n };\n }\n }\n\n async function worker(): Promise<void> {\n while (true) {\n const index = nextIndex;\n nextIndex += 1;\n if (index >= urls.length) {\n return;\n }\n results[index] = await checkLink(urls[index]);\n }\n }\n\n const workerCount = Math.min(LINK_CHECK_CONCURRENCY, urls.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n return results;\n}\n"]}
1
+ {"version":3,"file":"seo-auditor.js","sourceRoot":"","sources":["../src/seo-auditor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAC;AACnC,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,cAAc,GACf,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AACpC,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AACrC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,qBAAqB,GAAG,qBAAqB,eAAe,0CAA0C,CAAC;AAsB7G,SAAS,QAAQ,CAAC,MAAkB,EAAE,KAAe;IACnD,IAAI,MAAM,CAAC,MAAM,GAAG,gBAAgB,EAAE,CAAC;QACrC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACrB,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB;IAK3B,MAAM,MAAM,GAAe,EAAE,CAAC;IAC9B,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,OAAO;QACL,MAAM;QACN,GAAG,CAAC,KAAK;YACP,WAAW,IAAI,CAAC,CAAC;YACjB,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAC1B,CAAC;QACD,OAAO;YACL,OAAO;gBACL,MAAM;gBACN,WAAW;gBACX,SAAS,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM;aACvC,CAAC;QACJ,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,YAAY,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ;gBAC9D,EAAE,EAAE,KAAK;gBACT,OAAO,EAAE,eAAe,CAAC,KAAK,CAAC;aAChC,CAAC;QACJ,CAAC;IACH,CAAC;IAED,KAAK,UAAU,MAAM;QACnB,OAAO,IAAI,EAAE,CAAC;YACZ,MAAM,KAAK,GAAG,SAAS,CAAC;YACxB,SAAS,IAAI,CAAC,CAAC;YACf,IAAI,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBACzB,OAAO;YACT,CAAC;YACD,OAAO,CAAC,KAAK,CAAC,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,sBAAsB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAClE,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IACvE,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import * as cheerio from \"cheerio\";\nimport {\n assertPublicHttpUrl,\n cancelResponseBody,\n fetchPublicHttp,\n getErrorMessage,\n PublicUrlError,\n} from \"./network.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\n\nexport const MAX_AUDIT_ISSUES = 200;\nexport const MAX_LINKS_TO_CHECK = 25;\nconst LINK_CHECK_CONCURRENCY = 5;\nconst LINK_CHECK_TIMEOUT_MS = 5_000;\nconst LINK_CHECK_USER_AGENT = `mcp-web-validator/${PACKAGE_VERSION} (+https://digestseo.com/validator-mcp/)`;\n\nexport interface SEOIssue {\n severity: \"error\" | \"warning\" | \"info\";\n category: \"SEO\" | \"Schema\" | \"BrokenLinks\" | \"Accessibility\";\n message: string;\n element?: string;\n}\n\nexport interface LinkStatus {\n url: string;\n status: number | string;\n ok: boolean;\n message?: string;\n}\n\nexport interface AuditDetails {\n issues: SEOIssue[];\n totalIssues: number;\n truncated: boolean;\n}\n\nfunction addIssue(issues: SEOIssue[], issue: SEOIssue): void {\n if (issues.length < MAX_AUDIT_ISSUES) {\n issues.push(issue);\n }\n}\n\nfunction createIssueCollector(): {\n issues: SEOIssue[];\n add: (issue: SEOIssue) => void;\n details: () => AuditDetails;\n} {\n const issues: SEOIssue[] = [];\n let totalIssues = 0;\n return {\n issues,\n add(issue) {\n totalIssues += 1;\n addIssue(issues, issue);\n },\n details() {\n return {\n issues,\n totalIssues,\n truncated: totalIssues > issues.length,\n };\n },\n };\n}\n\nfunction isJsonLdScriptType(type: string | undefined): boolean {\n return type?.split(\";\", 1)[0].trim().toLowerCase() === \"application/ld+json\";\n}\n\n/**\n * Audits technical SEO and accessibility basics on HTML content using Cheerio\n */\nexport function auditSeoMetadataDetailed(htmlContent: string): AuditDetails {\n const $ = cheerio.load(htmlContent);\n const collector = createIssueCollector();\n const { add } = collector;\n\n // --- Title Tag Audits ---\n const titleTag = $(\"title\");\n if (titleTag.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Missing <title> tag. Add a concise, descriptive title to help represent the page in search results.\",\n });\n } else {\n const titleText = titleTag.text().trim();\n if (titleText.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"The <title> tag is empty.\",\n });\n } else if (titleText.length < 30) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Title is ${titleText.length} characters. This is shorter than the audit's common editorial range; review whether it describes the page clearly.`,\n element: `<title>${titleText}</title>`,\n });\n } else if (titleText.length > 60) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Title is ${titleText.length} characters. This is longer than the audit's common editorial range; Google title links may be shortened or rewritten depending on context and device.`,\n element: `<title>${titleText}</title>`,\n });\n }\n }\n\n // --- Meta Description Audits ---\n const metaDescription = $('meta[name=\"description\"]');\n if (metaDescription.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Missing <meta name=\\\"description\\\">. Add a concise, accurate page summary; Google may use page content or this description to generate a snippet.\",\n });\n } else {\n const descText = metaDescription.attr(\"content\")?.trim() || \"\";\n if (descText.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Meta description content attribute is empty.\",\n });\n } else if (descText.length < 120) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Meta description is ${descText.length} characters. This is shorter than the audit's common editorial range; review whether it provides a useful page summary.`,\n element: `<meta name=\"description\" content=\"${descText}\">`,\n });\n } else if (descText.length > 160) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: `Meta description is ${descText.length} characters. This is longer than the audit's common editorial range; displayed snippets may be shortened depending on the query and device.`,\n element: `<meta name=\"description\" content=\"${descText}\">`,\n });\n }\n }\n\n // --- Canonical Link ---\n const canonical = $('link[rel=\"canonical\"]');\n if (canonical.length === 0) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: \"Missing canonical tag (<link rel=\\\"canonical\\\">). This helps prevent duplicate content issues.\",\n });\n }\n\n // --- Viewport Meta Tag (Mobile Responsiveness) ---\n const viewport = $('meta[name=\"viewport\"]');\n if (viewport.length === 0) {\n add({\n severity: \"error\",\n category: \"SEO\",\n message: \"Missing <meta name=\\\"viewport\\\"> tag. Review mobile rendering; this tag helps browsers size and scale the page on mobile devices.\",\n });\n }\n\n // --- Heading Structure ---\n const h1Tags = $(\"h1\");\n if (h1Tags.length === 0) {\n add({\n severity: \"warning\",\n category: \"SEO\",\n message: \"No <h1> heading found. Review whether the page has a clear main heading and a meaningful heading hierarchy.\",\n });\n } else if (h1Tags.length > 1) {\n add({\n severity: \"info\",\n category: \"SEO\",\n message: `Found multiple (${h1Tags.length}) <h1> headings. Multiple H1s are not inherently an SEO error; ensure the heading hierarchy is meaningful and the main visual title is clear.`,\n });\n }\n\n // --- Images Alt Tags (SEO + Accessibility) ---\n $(\"img\").each((_, element) => {\n const img = $(element);\n const src = img.attr(\"src\") || \"unknown-source\";\n const alt = img.attr(\"alt\");\n\n if (alt === undefined) {\n add({\n severity: \"error\",\n category: \"Accessibility\",\n message: \"Missing 'alt' attribute on image. This makes it inaccessible to screen readers.\",\n element: `<img src=\"${src}\">`,\n });\n } else if (alt.trim() === \"\") {\n // Empty alt is acceptable for purely decorative images, but worth warning\n add({\n severity: \"info\",\n category: \"Accessibility\",\n message: \"Empty 'alt' attribute found. Ensure this image is purely decorative, otherwise add descriptive text.\",\n element: `<img src=\"${src}\" alt=\"\">`,\n });\n }\n });\n\n // --- Open Graph / Social Tags ---\n const ogTitle = $('meta[property=\"og:title\"]');\n const ogImage = $('meta[property=\"og:image\"]');\n if (ogTitle.length === 0 || ogImage.length === 0) {\n add({\n severity: \"info\",\n category: \"SEO\",\n message: \"Missing Open Graph social metadata (og:title / og:image). Add these to control preview cards on platforms like LinkedIn and X.\",\n });\n }\n\n return collector.details();\n}\n\nexport function auditSeoMetadata(htmlContent: string): SEOIssue[] {\n return auditSeoMetadataDetailed(htmlContent).issues;\n}\n\n/**\n * Parses and validates JSON-LD Schema markup\n */\nexport function validateSchemaMarkupDetailed(htmlContent: string): AuditDetails {\n const $ = cheerio.load(htmlContent);\n const collector = createIssueCollector();\n const { add } = collector;\n const blocks = $(\"script[type]\").filter((_, element) => isJsonLdScriptType($(element).attr(\"type\")));\n\n blocks.each((index, element) => {\n const scriptText = $(element).html() || \"\";\n if (scriptText.trim() === \"\") {\n add({\n severity: \"warning\",\n category: \"Schema\",\n message: `JSON-LD block #${index + 1} is empty.`,\n });\n return;\n }\n\n try {\n JSON.parse(scriptText);\n } catch (error: unknown) {\n add({\n severity: \"error\",\n category: \"Schema\",\n message: `Invalid JSON-LD schema syntax: ${getErrorMessage(error)}`,\n element: `<script type=\"application/ld+json\">...</script>`,\n });\n }\n });\n\n return collector.details();\n}\n\nexport function validateSchemaMarkup(htmlContent: string): SEOIssue[] {\n return validateSchemaMarkupDetailed(htmlContent).issues;\n}\n\n/**\n * Extracts and tests links, treating 3xx responses as reachable redirects and 4xx/5xx as broken.\n */\nexport async function checkBrokenLinks(\n htmlContent: string,\n baseUrl?: string,\n maxLinks = MAX_LINKS_TO_CHECK,\n): Promise<LinkStatus[]> {\n if (!Number.isSafeInteger(maxLinks) || maxLinks <= 0) {\n throw new Error(\"maxLinks must be a positive integer\");\n }\n const linkLimit = Math.min(maxLinks, MAX_LINKS_TO_CHECK);\n const $ = cheerio.load(htmlContent);\n let parsedBaseUrl = baseUrl ? await assertPublicHttpUrl(baseUrl) : undefined;\n if (!parsedBaseUrl) {\n const documentBaseHref = $(\"base[href]\").first().attr(\"href\")?.trim();\n if (documentBaseHref) {\n try {\n parsedBaseUrl = await assertPublicHttpUrl(documentBaseHref);\n } catch (error: unknown) {\n if (!(error instanceof PublicUrlError)) {\n throw error;\n }\n }\n }\n }\n const urls: string[] = [];\n const seenUrls = new Set<string>();\n\n $(\"a\").each((_, element) => {\n if (urls.length >= linkLimit) {\n return false;\n }\n\n const href = $(element).attr(\"href\")?.trim();\n if (!href || href.startsWith(\"#\")) {\n return;\n }\n\n let resolvedUrl: URL;\n try {\n resolvedUrl = parsedBaseUrl ? new URL(href, parsedBaseUrl) : new URL(href);\n } catch {\n // Relative links require a public base URL; unsupported or malformed links are skipped.\n return;\n }\n\n if (resolvedUrl.protocol !== \"http:\" && resolvedUrl.protocol !== \"https:\") {\n return;\n }\n\n resolvedUrl.hash = \"\";\n const normalizedUrl = resolvedUrl.href;\n if (!seenUrls.has(normalizedUrl)) {\n seenUrls.add(normalizedUrl);\n urls.push(normalizedUrl);\n }\n });\n\n const results = new Array<LinkStatus>(urls.length);\n let nextIndex = 0;\n\n async function checkLink(url: string): Promise<LinkStatus> {\n try {\n const headResult = await fetchPublicHttp(url, {\n method: \"HEAD\",\n headers: { \"User-Agent\": LINK_CHECK_USER_AGENT },\n timeoutMs: LINK_CHECK_TIMEOUT_MS,\n maxRedirects: 0,\n });\n const headStatus = headResult.response.status;\n const headFinalUrl = headResult.url.href;\n await cancelResponseBody(headResult.response);\n\n // Some sites reject or do not implement HEAD even when the linked resource is available.\n if (headStatus === 405 || headStatus === 403 || headStatus === 501) {\n const getResult = await fetchPublicHttp(url, {\n method: \"GET\",\n headers: {\n Range: \"bytes=0-0\",\n \"User-Agent\": LINK_CHECK_USER_AGENT,\n },\n timeoutMs: LINK_CHECK_TIMEOUT_MS,\n maxRedirects: 0,\n });\n const status = getResult.response.status;\n const ok = status >= 200 && status < 400;\n const finalUrl = getResult.url.href;\n await cancelResponseBody(getResult.response);\n return {\n url,\n status,\n ok,\n message:\n status >= 300 && status < 400\n ? \"Redirect not followed\"\n : finalUrl !== url\n ? `Redirected to ${finalUrl}`\n : undefined,\n };\n }\n\n return {\n url,\n status: headStatus,\n ok: headStatus >= 200 && headStatus < 400,\n message:\n headStatus >= 300 && headStatus < 400\n ? \"Redirect not followed\"\n : headFinalUrl !== url\n ? `Redirected to ${headFinalUrl}`\n : undefined,\n };\n } catch (error: unknown) {\n return {\n url,\n status: error instanceof PublicUrlError ? \"blocked\" : \"failed\",\n ok: false,\n message: getErrorMessage(error),\n };\n }\n }\n\n async function worker(): Promise<void> {\n while (true) {\n const index = nextIndex;\n nextIndex += 1;\n if (index >= urls.length) {\n return;\n }\n results[index] = await checkLink(urls[index]);\n }\n }\n\n const workerCount = Math.min(LINK_CHECK_CONCURRENCY, urls.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n return results;\n}\n"]}
@@ -58,7 +58,7 @@ export async function validateHtmlContent(htmlContent) {
58
58
  const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);
59
59
  const data = JSON.parse(text);
60
60
  if (data.messages === undefined) {
61
- return [];
61
+ throw new Error("W3C HTML validator returned an invalid response shape");
62
62
  }
63
63
  if (!Array.isArray(data.messages)) {
64
64
  throw new Error("W3C HTML validator returned an invalid response shape");
@@ -103,7 +103,10 @@ export async function validateCssContent(cssContent) {
103
103
  throw new Error("W3C CSS validator returned an empty response");
104
104
  }
105
105
  const data = JSON.parse(text);
106
- const errors = data.cssvalidation?.errors || [];
106
+ if (!data.cssvalidation || typeof data.cssvalidation !== "object") {
107
+ throw new Error("W3C CSS validator returned an invalid response shape");
108
+ }
109
+ const errors = data.cssvalidation.errors || [];
107
110
  return errors.slice(0, MAX_VALIDATION_MESSAGES).map(err => ({
108
111
  line: err.line || 0,
109
112
  type: "error",
@@ -1 +1 @@
1
- {"version":3,"file":"w3c-validator.js","sourceRoot":"","sources":["../src/w3c-validator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAmB/C,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,cAAc,GAAG,SAAS,CAAC;AACjC,MAAM,CAAC,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAChD,MAAM,4BAA4B,GAAG,SAAS,CAAC;AAC/C,MAAM,UAAU,GAAG,qBAAqB,eAAe,0CAA0C,CAAC;AAClG,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAE3C,SAAS,iBAAiB,CAAC,OAAe,EAAE,QAAgB,EAAE,KAAa;IACzE,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAChD,IAAI,IAAI,GAAG,QAAQ,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,gBAAgB,QAAQ,wBAAwB,CAAC,CAAC;IAC5E,CAAC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAgB;IAC3C,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;QACpD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,SAAS,GAAG,OAAkC,CAAC;IACrD,IAAI,OAAO,SAAS,CAAC,IAAI,KAA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AAC;IACN,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,0BAA0B,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import {\n cancelResponseBody,\n getErrorMessage,\n readResponseText,\n} from \"./network.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\n\nexport interface W3CMessage {\n type: string;\n lastLine?: number;\n lastColumn?: number;\n firstLine?: number;\n firstColumn?: number;\n message: string;\n extract?: string;\n}\n\nexport interface CSSMessage {\n line: number;\n type: string;\n message: string;\n context?: string;\n}\n\nconst VALIDATOR_TIMEOUT_MS = 20_000;\nconst MAX_HTML_BYTES = 2_000_000;\nexport const MAX_CSS_VALIDATION_BYTES = 128_000;\nconst MAX_VALIDATOR_RESPONSE_BYTES = 5_000_000;\nconst USER_AGENT = `mcp-web-validator/${PACKAGE_VERSION} (+https://digestseo.com/validator-mcp/)`;\nexport const MAX_VALIDATION_MESSAGES = 200;\n\nfunction assertContentSize(content: string, maxBytes: number, label: string): void {\n const size = Buffer.byteLength(content, \"utf8\");\n if (size > maxBytes) {\n throw new Error(`${label} exceeds the ${maxBytes}-byte validation limit`);\n }\n}\n\nfunction normalizeW3CMessage(message: unknown): W3CMessage | null {\n if (typeof message !== \"object\" || message === null) {\n return null;\n }\n\n const candidate = message as Record<string, unknown>;\n if (typeof candidate.type !== \"string\" || typeof candidate.message !== \"string\") {\n return null;\n }\n\n const normalized: W3CMessage = {\n type: candidate.type,\n message: candidate.message,\n };\n\n for (const field of [\"lastLine\", \"lastColumn\", \"firstLine\", \"firstColumn\"] as const) {\n if (typeof candidate[field] === \"number\" && Number.isInteger(candidate[field])) {\n normalized[field] = candidate[field];\n }\n }\n\n if (typeof candidate.extract === \"string\") {\n normalized.extract = candidate.extract;\n }\n\n return normalized;\n}\n\n/**\n * Validates HTML using the W3C Nu HTML Checker API\n */\nexport async function validateHtmlContent(htmlContent: string): Promise<W3CMessage[]> {\n const url = \"https://validator.w3.org/nu/?out=json\";\n\n try {\n assertContentSize(htmlContent, MAX_HTML_BYTES, \"HTML content\");\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"User-Agent\": USER_AGENT,\n },\n body: htmlContent,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C HTML validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n const data = JSON.parse(text) as { messages?: unknown };\n if (data.messages === undefined) {\n return [];\n }\n if (!Array.isArray(data.messages)) {\n throw new Error(\"W3C HTML validator returned an invalid response shape\");\n }\n return data.messages\n .map(normalizeW3CMessage)\n .filter((message): message is W3CMessage => message !== null)\n .slice(0, MAX_VALIDATION_MESSAGES);\n } catch (error: unknown) {\n throw new Error(`HTML validation failed: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Validates CSS using the W3C Jigsaw CSS Validator API\n */\nexport async function validateCssContent(cssContent: string): Promise<CSSMessage[]> {\n const url = \"https://jigsaw.w3.org/css-validator/validator\";\n\n try {\n assertContentSize(cssContent, MAX_CSS_VALIDATION_BYTES, \"CSS content\");\n const form = new FormData();\n form.set(\"text\", cssContent);\n form.set(\"output\", \"json\");\n form.set(\"warning\", \"0\");\n form.set(\"profile\", \"css3svg\");\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"User-Agent\": USER_AGENT,\n },\n body: form,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C CSS validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n\n // An empty upstream response is indeterminate and must never be presented as a clean result.\n if (!text || text.trim() === \"\") {\n throw new Error(\"W3C CSS validator returned an empty response\");\n }\n\n const data = JSON.parse(text) as {\n cssvalidation?: {\n errors?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n warnings?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n };\n };\n\n const errors = data.cssvalidation?.errors || [];\n return errors.slice(0, MAX_VALIDATION_MESSAGES).map(err => ({\n line: err.line || 0,\n type: \"error\",\n message: err.message ? err.message.trim() : \"Unknown CSS validation error\",\n context: err.context || undefined\n }));\n } catch (error: unknown) {\n throw new Error(`CSS validation failed: ${getErrorMessage(error)}`);\n }\n}\n"]}
1
+ {"version":3,"file":"w3c-validator.js","sourceRoot":"","sources":["../src/w3c-validator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAmB/C,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,cAAc,GAAG,SAAS,CAAC;AACjC,MAAM,CAAC,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAChD,MAAM,4BAA4B,GAAG,SAAS,CAAC;AAC/C,MAAM,UAAU,GAAG,qBAAqB,eAAe,0CAA0C,CAAC;AAClG,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAE3C,SAAS,iBAAiB,CAAC,OAAe,EAAE,QAAgB,EAAE,KAAa;IACzE,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAChD,IAAI,IAAI,GAAG,QAAQ,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,gBAAgB,QAAQ,wBAAwB,CAAC,CAAC;IAC5E,CAAC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAgB;IAC3C,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,EAA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C,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC1D,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC;YACnB,IAAI,EAAE,OAAO;YACb,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,8BAA8B;YAC1E,OAAO,EAAE,GAAG,CAAC,OAAO,IAAI,SAAS;SAClC,CAAC,CAAC,CAAC;IACN,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,0BAA0B,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import {\n cancelResponseBody,\n getErrorMessage,\n readResponseText,\n} from \"./network.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\n\nexport interface W3CMessage {\n type: string;\n lastLine?: number;\n lastColumn?: number;\n firstLine?: number;\n firstColumn?: number;\n message: string;\n extract?: string;\n}\n\nexport interface CSSMessage {\n line: number;\n type: string;\n message: string;\n context?: string;\n}\n\nconst VALIDATOR_TIMEOUT_MS = 20_000;\nconst MAX_HTML_BYTES = 2_000_000;\nexport const MAX_CSS_VALIDATION_BYTES = 128_000;\nconst MAX_VALIDATOR_RESPONSE_BYTES = 5_000_000;\nconst USER_AGENT = `mcp-web-validator/${PACKAGE_VERSION} (+https://digestseo.com/validator-mcp/)`;\nexport const MAX_VALIDATION_MESSAGES = 200;\n\nfunction assertContentSize(content: string, maxBytes: number, label: string): void {\n const size = Buffer.byteLength(content, \"utf8\");\n if (size > maxBytes) {\n throw new Error(`${label} exceeds the ${maxBytes}-byte validation limit`);\n }\n}\n\nfunction normalizeW3CMessage(message: unknown): W3CMessage | null {\n if (typeof message !== \"object\" || message === null) {\n return null;\n }\n\n const candidate = message as Record<string, unknown>;\n if (typeof candidate.type !== \"string\" || typeof candidate.message !== \"string\") {\n return null;\n }\n\n const normalized: W3CMessage = {\n type: candidate.type,\n message: candidate.message,\n };\n\n for (const field of [\"lastLine\", \"lastColumn\", \"firstLine\", \"firstColumn\"] as const) {\n if (typeof candidate[field] === \"number\" && Number.isInteger(candidate[field])) {\n normalized[field] = candidate[field];\n }\n }\n\n if (typeof candidate.extract === \"string\") {\n normalized.extract = candidate.extract;\n }\n\n return normalized;\n}\n\n/**\n * Validates HTML using the W3C Nu HTML Checker API\n */\nexport async function validateHtmlContent(htmlContent: string): Promise<W3CMessage[]> {\n const url = \"https://validator.w3.org/nu/?out=json\";\n\n try {\n assertContentSize(htmlContent, MAX_HTML_BYTES, \"HTML content\");\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"User-Agent\": USER_AGENT,\n },\n body: htmlContent,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C HTML validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n const data = JSON.parse(text) as { messages?: unknown };\n if (data.messages === undefined) {\n throw new Error(\"W3C HTML validator returned an invalid response shape\");\n }\n if (!Array.isArray(data.messages)) {\n throw new Error(\"W3C HTML validator returned an invalid response shape\");\n }\n return data.messages\n .map(normalizeW3CMessage)\n .filter((message): message is W3CMessage => message !== null)\n .slice(0, MAX_VALIDATION_MESSAGES);\n } catch (error: unknown) {\n throw new Error(`HTML validation failed: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Validates CSS using the W3C Jigsaw CSS Validator API\n */\nexport async function validateCssContent(cssContent: string): Promise<CSSMessage[]> {\n const url = \"https://jigsaw.w3.org/css-validator/validator\";\n\n try {\n assertContentSize(cssContent, MAX_CSS_VALIDATION_BYTES, \"CSS content\");\n const form = new FormData();\n form.set(\"text\", cssContent);\n form.set(\"output\", \"json\");\n form.set(\"warning\", \"0\");\n form.set(\"profile\", \"css3svg\");\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"User-Agent\": USER_AGENT,\n },\n body: form,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C CSS validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n\n // An empty upstream response is indeterminate and must never be presented as a clean result.\n if (!text || text.trim() === \"\") {\n throw new Error(\"W3C CSS validator returned an empty response\");\n }\n\n const data = JSON.parse(text) as {\n cssvalidation?: {\n errors?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n warnings?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n };\n };\n\n if (!data.cssvalidation || typeof data.cssvalidation !== \"object\") {\n throw new Error(\"W3C CSS validator returned an invalid response shape\");\n }\n\n const errors = data.cssvalidation.errors || [];\n return errors.slice(0, MAX_VALIDATION_MESSAGES).map(err => ({\n line: err.line || 0,\n type: \"error\",\n message: err.message ? err.message.trim() : \"Unknown CSS validation error\",\n context: err.context || undefined\n }));\n } catch (error: unknown) {\n throw new Error(`CSS validation failed: ${getErrorMessage(error)}`);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-web-validator",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "W3C HTML/CSS Validator and Technical SEO Audit MCP Server for AI coding assistants.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {