mcp-web-validator 1.3.48 → 1.3.50

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,32 @@ All notable changes to this project are documented here. The project follows [Se
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.3.50] - 2026-11-18
8
+
9
+ ### Fixed
10
+
11
+ - Bound the local MCP structured diagnostic issue arrays by UTF-8 byte size for `seo.metadata` and `schema.markup`. This prevents Codexify gateways from rejecting large issue floods while retaining exact totals, severity counts, and truncation signals.
12
+ - Accept an optional UTF-8 byte-order mark at the beginning of a JSON-LD script block without accepting malformed JSON.
13
+
14
+ ### Validation
15
+
16
+ - Extended real-stdio regression tests for hundreds of malformed JSON-LD blocks, oversized image attributes, and BOM-prefixed JSON-LD.
17
+
18
+ ## [1.3.49] - 2026-11-18
19
+
20
+ ### Added
21
+
22
+ - Added opt-in `audit.history` to the local MCP server: one compact JSON file, at most 10 versioned site-audit snapshots, with automatic oldest-first eviction and no background process.
23
+
24
+ ### Security
25
+
26
+ - Hosted MCP now uses the official stateless `@modelcontextprotocol/server` HTTP handler directly, eliminating the production `agents` dependency chain flagged for a transitive picomatch ReDoS advisory.
27
+
28
+ ### Hosted app
29
+
30
+ - Added sampled cross-page indexability signals and graph to bounded `audit_public_site` output.
31
+ - Added offline `compare_site_audits` for evidence-aware before/after comparisons with explicit coverage limitations.
32
+
7
33
  ## [1.3.48] - 2026-10-28
8
34
 
9
35
  ### Security
package/README.md CHANGED
@@ -56,6 +56,7 @@ The npm package exposes these exact runtime tool names:
56
56
  | `links.broken` | Check links extracted from supplied HTML. | Sends bounded HTTP requests to eligible public links. |
57
57
  | `schema.markup` | Parse JSON-LD blocks and report JSON syntax errors. | Processes supplied HTML locally. |
58
58
  | `report.validation` | Combine HTML/XHTML, optional CSS, SEO, JSON-LD, and bounded link checks in a Markdown report. | Reads selected files, contacts the validators, and checks eligible public links found in the markup; `.xhtml` inputs use XHTML parsing semantics for Nu validation. |
59
+ | `audit.history` | Opt-in local site-audit snapshot history: `save`, `list`, or `get` by ID. | Stores comparison-relevant fields only in one local JSON file, with a hard cap of 10 versions (oldest automatically evicted). No database or network access. |
59
60
  | `screenshot.capture` | Capture desktop, tablet, mobile, or custom viewport screenshots. | Opens a selected local file or eligible public URL and writes PNG files to the selected output directory; existing matching files may be replaced. |
60
61
 
61
62
  For direct Node.js integrations, `auditSeoMetadata(html, xRobotsTag)` and
@@ -66,12 +67,13 @@ fetches headers; the MCP `seo.metadata` tool still analyzes supplied HTML only.
66
67
 
67
68
  ## Hosted app tools
68
69
 
69
- The hosted app exposes eight tools:
70
+ The hosted app exposes nine tools:
70
71
 
71
72
  | Tool | Purpose |
72
73
  | --- | --- |
73
74
  | `audit_public_webpage` | Fetch one authorized public HTML page and run the combined HTML, SEO/accessibility-signal, and JSON-LD syntax audit. Link checks are optional. |
74
- | `audit_public_site` | Run a bounded sitemap-first audit of up to eight authorized, same-origin public pages. It respects `robots.txt`, returns compact page coverage and deduplicated findings, and does not run site-wide link checks. |
75
+ | `audit_public_site` | Run a bounded sitemap-first audit of up to eight authorized, same-origin public pages. It respects `robots.txt`, returns compact page coverage and deduplicated findings, **plus a sampled cross-page indexability evidence graph** for canonical loops/chains, sitemap/noindex conflicts, duplicate titles, and hreflang return links. No site-wide link checks. |
76
+ | `compare_site_audits` | Offline before/after comparison of two saved `audit_public_site` structured results. Flags per-page regressions, coverage loss, and sitemap drift; reports newly observed or no-longer observed grouped findings only for an identical, fully checked page sample; partial sitemap coverage never proves a site-wide fix. No network calls or retained history. |
75
77
  | `validate_html` | Validate raw HTML markup already supplied in the conversation. |
76
78
  | `validate_css` | Parse supplied CSS for syntax errors inside the Worker. |
77
79
  | `audit_seo_metadata` | Audit supplied HTML for covered on-page SEO, robots noindex, and accessibility signals. |
@@ -81,6 +83,40 @@ The hosted app exposes eight tools:
81
83
 
82
84
  `audit_public_webpage` follows at most three validated redirects, accepts a bounded `text/html` response, and records the final URL. It does not crawl additional pages, execute JavaScript, authenticate, or fetch linked stylesheets and assets. `audit_public_site` first locks the final public origin, then reads bounded `robots.txt` plus same-origin XML Sitemap, RSS 2.0, Atom 1.0, and plain-text sitemap representations before auditing at most eight eligible sitemap pages in one call. Robots discovery may follow up to five validated public redirects across authorities, as defined by the robots protocol; the resulting rules and relative Sitemap directives are still interpreted for the originally audited authority. Sitemap entries and audited pages remain same-origin, and private/reserved destinations, credentials, custom ports, service self-fetches, and HTTPS-to-HTTP redirect downgrades are rejected. The tool never follows HTML links or external sitemap entries; use `page_offset` when the response says more eligible pages remain. The fetched HTML is sent to `https://html5.validator.nu/`, the same external Nu HTML Checker used by `validate_html` and the report tool. CSS parsing, SEO analysis, and JSON-LD parsing run inside the DigestSEO Worker. Optional link checks make capped `HEAD` requests, with a bounded `GET` fallback where necessary, to eligible public HTTP(S) URLs; link redirects are reported but not followed. The site tool intentionally does not perform site-wide link checking. The hosted app does not retain tool inputs, fetched HTML, or results.
83
85
 
86
+ ### Sampled indexability evidence graph
87
+
88
+ The hosted `audit_public_site` result now includes per-page `indexability` static signals (canonical state/target, an **observed** noindex directive, bounded page title, and bounded hreflang declarations) and a new `indexability_graph` section. Findings are derived only from the HTML/headers already requested by the site audit: **zero additional page requests, no JavaScript execution, no stored audit history, and no extra recipients**.
89
+
90
+ The graph identifies evidence-supported canonical cycles and chains between sampled pages, sampled sitemap URLs observed with noindex, sampled canonicals pointing to other sampled noindex pages, potential duplicate titles for distinct canonical destinations, and missing sampled hreflang return links. `coverage_limited` and `limitations` explain why partial results cannot establish a site-wide pass.
91
+
92
+ A cross-page finding is not proof of deindexing, Google's selected canonical, a search ranking signal, or a traffic-change cause. Query-bearing/credentialed canonical and alternate URLs are **not echoed** and are excluded from cross-page assertions rather than incorrectly normalized to a different page. The graph does not follow canonical or hreflang links: targets must already be inside the bounded audited sample.
93
+
94
+ ### Before/after site regression checks
95
+
96
+ 1. Run `audit_public_site` on an authorized website and preserve the returned **structured result** as a baseline.
97
+ 2. After a release or repair, rerun `audit_public_site` using the same website and page-selection settings. If continuing paginated audits, use the fingerprint supplied by that run; do not reuse a stale continuation.
98
+ 3. Pass both structured results to `compare_site_audits` as `baseline` and `current`. Check `status`, `page_changes`, `limitations`, and `issue_group_comparison_available` before deciding whether a change is safe.
99
+
100
+ The comparison never fetches pages or keeps audit history. It separately reports failures and incomplete coverage. When both snapshots contain the same fully checked selected URLs and the same discovery fingerprint, grouped findings may be compared *within that sample*, even if the whole sitemap was not audited; this is **not** a verified site-wide fix. It cannot determine Google indexing or ranking changes, prove why traffic changed, or replace a complete accessibility audit. The `health_score_delta` is a heuristic within this tool, not a Google ranking metric.
101
+
102
+ ### Optional local history: maximum 10 versions
103
+
104
+ The hosted app deliberately retains **nothing**. If you use the local npm/stdio MCP, `audit.history` can save the JSON `structuredContent` from `audit_public_site` on your own computer. Choose `action: "save"` and supply `snapshotJson` as a JSON string; use `list` to see saved version IDs and `get` with an ID to retrieve its compact JSON. You can then pass two retrieved snapshots to `compare_site_audits`. Saving is always opt-in; audits do not silently create history.
105
+
106
+ One compact `audit-history.json` file lives at `~/.mcp-validator/audit-history.json`; when `MCP_WEB_VALIDATOR_WORKSPACE_ROOT` is configured, the file instead lives in that root's `.mcp-validator/` directory. It stores **up to 10 total versions**, newest first when listed. Saving the eleventh automatically deletes the oldest. Each source snapshot is limited to 60 KB and is reduced to comparison-relevant fields (no raw HTML, browser screenshots, widget state, or full indexability graph). The history file has a 660 KB cap. There are no database services, background processes, or network calls. Files stay on the user's computer and are readable only with local filesystem access.
107
+
108
+ **Security:** Do not save secrets in page diagnostics. URL fields containing query strings, credentials, or fragments are rejected; audit-history file symlinks and oversized or corrupt files fail closed. Concurrent saves from one local process are serialized. Separate concurrently running MCP processes should use separate workspace roots to avoid writing the same file.
109
+
110
+ #### Test the storage boundary
111
+
112
+ Run `npm test` to exercise the local history implementation **through a real stdio MCP client**: saving 11 versions, evicting only the oldest, retrieving a snapshot after the MCP process restarts, and isolating two different workspace roots. The hosted Worker test suite separately verifies that multiple ChatGPT-style HTTP clients can connect with no session cookie, that comparisons stay request-local, and that the hosted tool list **does not** expose `audit.history`.
113
+
114
+ Run `npm run smoke:hosted` to verify the **actually deployed** public MCP endpoint using read-only `initialize`, `tools/list`, and one offline JSON-LD check. This intentionally makes three small requests to the live service and does not crawl websites or save data. It fails if deployment still exposes an older tool catalog, even when repository CI is green. An HTTPS preview URL can be selected with `MCP_WEB_VALIDATOR_HOSTED_URL`. Do not mistake green source tests for a published deployment.
115
+
116
+ For a separately **opt-in live cross-surface smoke test**, from a repository checkout with dependencies installed, set `MCP_AUDIT_TARGET_URL` to the HTTPS root of a site you own or are authorized to inspect and run `npm run smoke:interop`. For example, in PowerShell: `$env:MCP_AUDIT_TARGET_URL = 'https://digestseo.com/'` followed by `npm run smoke:interop`. This makes **one** bounded, single-page hosted `audit_public_site` call, then checks local `audit.history` save/get and hosted `compare_site_audits` against the same snapshot. It saves only into a disposable temporary directory, cleans it up, and never creates cloud storage. Set `MCP_WEB_VALIDATOR_LOCAL_ENTRYPOINT` to an absolute path to test a separate installed stdio package rather than the repository build. A `partial` audit remains `partial`: the script reports validator coverage instead of claiming a site-wide clean bill of health. This check contacts the public site and W3C validator, so **it is not run by CI automatically**.
117
+
118
+ Local history is **not** a per-user cloud history system. ChatGPT users invoking the hosted MCP cannot retrieve local snapshots; cloud-side per-user persistence would require separately implemented authentication and storage. These tests prove the existing stateless architecture, not that unimplemented feature.
119
+
84
120
  ## Privacy Policy
85
121
 
86
122
  Only validate files, markup, and public webpages that you own or are authorized to inspect. Public page URLs can contain sensitive query values, so remove tokens and private identifiers before submitting them. Do not submit passwords, API keys, access tokens, payment data, health data, private source code, or other sensitive personal data.
@@ -0,0 +1,112 @@
1
+ import { z } from "zod";
2
+ export declare const MAX_AUDIT_HISTORY = 10;
3
+ export declare const MAX_AUDIT_SNAPSHOT_BYTES = 60000;
4
+ /**
5
+ * Keep only the fields used by compare_site_audits.
6
+ * Rich page signals, raw HTML, widget state and unrelated user-supplied fields
7
+ * are deliberately not persisted; the hosted app remains completely stateless.
8
+ */
9
+ export declare const compactAuditSnapshotSchema: z.ZodObject<{
10
+ site_url: z.ZodString;
11
+ sitemap_url: z.ZodOptional<z.ZodString>;
12
+ discovery: z.ZodEnum<{
13
+ partial: "partial";
14
+ root_only: "root_only";
15
+ sitemap: "sitemap";
16
+ }>;
17
+ discovery_error: z.ZodOptional<z.ZodEnum<{
18
+ robots_unavailable: "robots_unavailable";
19
+ sitemap_invalid: "sitemap_invalid";
20
+ sitemap_query_unsupported: "sitemap_query_unsupported";
21
+ sitemap_unavailable: "sitemap_unavailable";
22
+ }>>;
23
+ pages_discovered: z.ZodNumber;
24
+ pages_selected: z.ZodNumber;
25
+ pages_audited: z.ZodNumber;
26
+ pages_partial: z.ZodNumber;
27
+ pages_failed: z.ZodNumber;
28
+ pages_skipped_robots: z.ZodNumber;
29
+ truncated: z.ZodBoolean;
30
+ next_page_offset: z.ZodOptional<z.ZodNumber>;
31
+ discovery_fingerprint: z.ZodString;
32
+ audit_health_score: z.ZodOptional<z.ZodNumber>;
33
+ score_coverage_percent: z.ZodNumber;
34
+ pages: z.ZodArray<z.ZodObject<{
35
+ url: z.ZodString;
36
+ fetched_url: z.ZodOptional<z.ZodString>;
37
+ status: z.ZodEnum<{
38
+ failed: "failed";
39
+ needs_attention: "needs_attention";
40
+ partial: "partial";
41
+ passed: "passed";
42
+ skipped: "skipped";
43
+ }>;
44
+ http_status: z.ZodOptional<z.ZodNumber>;
45
+ redirects_followed: z.ZodOptional<z.ZodNumber>;
46
+ page_fetched: z.ZodBoolean;
47
+ html_validation_status: z.ZodEnum<{
48
+ completed: "completed";
49
+ not_run: "not_run";
50
+ timeout: "timeout";
51
+ unavailable: "unavailable";
52
+ }>;
53
+ html_errors: z.ZodNumber;
54
+ html_warnings: z.ZodNumber;
55
+ seo_errors: z.ZodNumber;
56
+ seo_warnings: z.ZodNumber;
57
+ schema_errors: z.ZodNumber;
58
+ schema_warnings: z.ZodNumber;
59
+ notes: z.ZodNumber;
60
+ health_score: z.ZodOptional<z.ZodNumber>;
61
+ failure_code: z.ZodOptional<z.ZodString>;
62
+ top_findings: z.ZodArray<z.ZodObject<{
63
+ code: z.ZodOptional<z.ZodString>;
64
+ severity: z.ZodEnum<{
65
+ error: "error";
66
+ info: "info";
67
+ warning: "warning";
68
+ }>;
69
+ category: z.ZodEnum<{
70
+ Accessibility: "Accessibility";
71
+ HTML: "HTML";
72
+ SEO: "SEO";
73
+ Schema: "Schema";
74
+ }>;
75
+ message: z.ZodString;
76
+ }, z.core.$strip>>;
77
+ }, z.core.$strip>>;
78
+ issue_groups: z.ZodArray<z.ZodObject<{
79
+ code: z.ZodOptional<z.ZodString>;
80
+ severity: z.ZodEnum<{
81
+ error: "error";
82
+ info: "info";
83
+ warning: "warning";
84
+ }>;
85
+ category: z.ZodEnum<{
86
+ Accessibility: "Accessibility";
87
+ HTML: "HTML";
88
+ SEO: "SEO";
89
+ Schema: "Schema";
90
+ }>;
91
+ message: z.ZodString;
92
+ affected_pages: z.ZodNumber;
93
+ example_urls: z.ZodArray<z.ZodString>;
94
+ }, z.core.$strip>>;
95
+ issue_groups_truncated: z.ZodBoolean;
96
+ }, z.core.$strip>;
97
+ export type CompactAuditSnapshot = z.infer<typeof compactAuditSnapshotSchema>;
98
+ export interface AuditHistoryItem {
99
+ id: string;
100
+ saved_at: string;
101
+ site_url: string;
102
+ }
103
+ export interface AuditHistoryResponse {
104
+ count: number;
105
+ items: AuditHistoryItem[];
106
+ snapshot_json?: string;
107
+ evicted_id?: string;
108
+ }
109
+ export declare function parseCompactAuditSnapshot(snapshotJson: string): CompactAuditSnapshot;
110
+ export declare function listAuditHistory(rootDirectory?: string): Promise<AuditHistoryResponse>;
111
+ export declare function getAuditHistorySnapshot(id: string, rootDirectory?: string): Promise<AuditHistoryResponse>;
112
+ export declare function saveAuditHistorySnapshot(snapshotJson: string, rootDirectory?: string): Promise<AuditHistoryResponse>;
@@ -0,0 +1,227 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { z } from "zod";
6
+ export const MAX_AUDIT_HISTORY = 10;
7
+ export const MAX_AUDIT_SNAPSHOT_BYTES = 60_000;
8
+ const MAX_HISTORY_FILE_BYTES = 660_000;
9
+ const HISTORY_DIRECTORY = ".mcp-validator";
10
+ const HISTORY_FILE = "audit-history.json";
11
+ const publicUrl = z.string().max(2_048).refine((value) => {
12
+ try {
13
+ const url = new URL(value);
14
+ return (url.protocol === "https:" || url.protocol === "http:")
15
+ && Boolean(url.hostname)
16
+ && !url.username && !url.password && !url.search && !url.hash
17
+ && !url.port;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }, "Only query-free, credential-free public HTTP(S) URLs may be saved.");
23
+ const count = z.number().int().nonnegative();
24
+ const severity = z.enum(["error", "warning", "info"]);
25
+ const category = z.enum(["HTML", "SEO", "Schema", "Accessibility"]);
26
+ const finding = z.object({
27
+ code: z.string().max(120).optional(),
28
+ severity,
29
+ category,
30
+ message: z.string().max(300),
31
+ });
32
+ const page = z.object({
33
+ url: publicUrl,
34
+ fetched_url: publicUrl.optional(),
35
+ status: z.enum(["passed", "needs_attention", "partial", "failed", "skipped"]),
36
+ http_status: z.number().int().min(200).max(299).optional(),
37
+ redirects_followed: z.number().int().min(0).max(3).optional(),
38
+ page_fetched: z.boolean(),
39
+ html_validation_status: z.enum(["completed", "timeout", "unavailable", "not_run"]),
40
+ html_errors: count,
41
+ html_warnings: count,
42
+ seo_errors: count,
43
+ seo_warnings: count,
44
+ schema_errors: count,
45
+ schema_warnings: count,
46
+ notes: count,
47
+ health_score: z.number().int().min(0).max(100).optional(),
48
+ failure_code: z.string().max(120).optional(),
49
+ top_findings: z.array(finding).max(3),
50
+ });
51
+ const issueGroup = finding.extend({
52
+ affected_pages: count,
53
+ example_urls: z.array(publicUrl).max(3),
54
+ });
55
+ /**
56
+ * Keep only the fields used by compare_site_audits.
57
+ * Rich page signals, raw HTML, widget state and unrelated user-supplied fields
58
+ * are deliberately not persisted; the hosted app remains completely stateless.
59
+ */
60
+ export const compactAuditSnapshotSchema = z.object({
61
+ site_url: publicUrl,
62
+ sitemap_url: publicUrl.optional(),
63
+ discovery: z.enum(["sitemap", "root_only", "partial"]),
64
+ discovery_error: z.enum(["robots_unavailable", "sitemap_unavailable", "sitemap_invalid", "sitemap_query_unsupported"]).optional(),
65
+ pages_discovered: count,
66
+ pages_selected: count,
67
+ pages_audited: count,
68
+ pages_partial: count,
69
+ pages_failed: count,
70
+ pages_skipped_robots: count,
71
+ truncated: z.boolean(),
72
+ next_page_offset: count.optional(),
73
+ discovery_fingerprint: z.string().regex(/^[0-9a-f]{64}$/),
74
+ audit_health_score: z.number().int().min(0).max(100).optional(),
75
+ score_coverage_percent: z.number().int().min(0).max(100),
76
+ pages: z.array(page).max(8),
77
+ issue_groups: z.array(issueGroup).max(50),
78
+ issue_groups_truncated: z.boolean(),
79
+ });
80
+ const historySchema = z.object({
81
+ version: z.literal(1),
82
+ items: z.array(z.object({
83
+ id: z.string().uuid(),
84
+ saved_at: z.string().datetime({ offset: true }),
85
+ site_url: publicUrl,
86
+ snapshot: compactAuditSnapshotSchema,
87
+ })).max(MAX_AUDIT_HISTORY),
88
+ });
89
+ const basePath = () => {
90
+ const configured = process.env.MCP_WEB_VALIDATOR_WORKSPACE_ROOT;
91
+ if (configured === undefined)
92
+ return os.homedir();
93
+ if (!path.isAbsolute(configured)) {
94
+ throw new Error("MCP_WEB_VALIDATOR_WORKSPACE_ROOT must be an absolute directory path.");
95
+ }
96
+ return configured;
97
+ };
98
+ async function historyFile(rootDirectory, create) {
99
+ const root = await fs.realpath(rootDirectory);
100
+ const dir = path.join(root, HISTORY_DIRECTORY);
101
+ if (create)
102
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
103
+ const entry = await fs.lstat(dir).catch((error) => {
104
+ if (!create && error.code === "ENOENT")
105
+ return undefined;
106
+ throw error;
107
+ });
108
+ if (!entry)
109
+ return path.join(dir, HISTORY_FILE);
110
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
111
+ throw new Error("The audit history directory must be a real directory, not a symbolic link.");
112
+ }
113
+ const realDir = await fs.realpath(dir);
114
+ if (path.dirname(realDir) !== root) {
115
+ throw new Error("Audit history directory must stay inside the configured root.");
116
+ }
117
+ return path.join(realDir, HISTORY_FILE);
118
+ }
119
+ async function readHistory(rootDirectory) {
120
+ const file = await historyFile(rootDirectory, false);
121
+ const info = await fs.lstat(file).catch((error) => {
122
+ if (error.code === "ENOENT")
123
+ return undefined;
124
+ throw error;
125
+ });
126
+ if (!info)
127
+ return [];
128
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > MAX_HISTORY_FILE_BYTES) {
129
+ throw new Error("History must be a bounded regular file, not a link or oversized file.");
130
+ }
131
+ let parsed;
132
+ try {
133
+ parsed = JSON.parse(await fs.readFile(file, "utf8"));
134
+ }
135
+ catch {
136
+ throw new Error("Audit history is unreadable or corrupt; no stored versions were modified.");
137
+ }
138
+ const result = historySchema.safeParse(parsed);
139
+ if (!result.success)
140
+ throw new Error("Audit history is invalid; no stored versions were modified.");
141
+ return result.data.items;
142
+ }
143
+ async function writeHistory(rootDirectory, items) {
144
+ const file = await historyFile(rootDirectory, true);
145
+ const contents = JSON.stringify({ version: 1, items });
146
+ if (Buffer.byteLength(contents, "utf8") > MAX_HISTORY_FILE_BYTES) {
147
+ throw new Error("The audit history file would exceed the configured size cap.");
148
+ }
149
+ const tmp = path.join(path.dirname(file), `.${HISTORY_FILE}.${randomUUID()}.tmp`);
150
+ let handle;
151
+ try {
152
+ handle = await fs.open(tmp, "wx", 0o600);
153
+ await handle.writeFile(contents, "utf8");
154
+ await handle.sync();
155
+ await handle.close();
156
+ handle = undefined;
157
+ await fs.rename(tmp, file);
158
+ }
159
+ finally {
160
+ if (handle)
161
+ await handle.close();
162
+ await fs.rm(tmp, { force: true });
163
+ }
164
+ }
165
+ function summary(items) {
166
+ return {
167
+ count: items.length,
168
+ items: items.slice().reverse().map(({ id, saved_at, site_url }) => ({ id, saved_at, site_url })),
169
+ };
170
+ }
171
+ // The stdio MCP server normally has one process. Serialize saves in-process
172
+ // so simultaneous client calls cannot overwrite one another's latest version.
173
+ let pendingSave = Promise.resolve();
174
+ export function parseCompactAuditSnapshot(snapshotJson) {
175
+ if (Buffer.byteLength(snapshotJson, "utf8") > MAX_AUDIT_SNAPSHOT_BYTES) {
176
+ throw new Error("Audit snapshot exceeds the 60 KB input limit.");
177
+ }
178
+ let candidate;
179
+ try {
180
+ candidate = JSON.parse(snapshotJson);
181
+ }
182
+ catch {
183
+ throw new Error("Audit snapshot must be valid JSON.");
184
+ }
185
+ const parsed = compactAuditSnapshotSchema.safeParse(candidate);
186
+ if (!parsed.success) {
187
+ throw new Error("Audit snapshot must be a valid bounded audit_public_site structured result without secret-bearing URLs.");
188
+ }
189
+ const compact = JSON.stringify(parsed.data);
190
+ if (Buffer.byteLength(compact, "utf8") > MAX_AUDIT_SNAPSHOT_BYTES) {
191
+ throw new Error("Compact audit snapshot exceeds the 60 KB storage limit.");
192
+ }
193
+ return parsed.data;
194
+ }
195
+ export async function listAuditHistory(rootDirectory = basePath()) {
196
+ return summary(await readHistory(rootDirectory));
197
+ }
198
+ export async function getAuditHistorySnapshot(id, rootDirectory = basePath()) {
199
+ const items = await readHistory(rootDirectory);
200
+ const found = items.find((item) => item.id === id);
201
+ if (!found)
202
+ throw new Error("The requested audit history version was not found.");
203
+ return { ...summary(items), snapshot_json: JSON.stringify(found.snapshot) };
204
+ }
205
+ export function saveAuditHistorySnapshot(snapshotJson, rootDirectory = basePath()) {
206
+ const snapshot = parseCompactAuditSnapshot(snapshotJson);
207
+ const action = async () => {
208
+ const items = await readHistory(rootDirectory);
209
+ const newItem = {
210
+ id: randomUUID(),
211
+ saved_at: new Date().toISOString(),
212
+ site_url: snapshot.site_url,
213
+ snapshot,
214
+ };
215
+ const next = [...items, newItem];
216
+ const evicted = next.length > MAX_AUDIT_HISTORY ? next.shift() : undefined;
217
+ await writeHistory(rootDirectory, next);
218
+ return {
219
+ ...summary(next),
220
+ ...(evicted ? { evicted_id: evicted.id } : {}),
221
+ };
222
+ };
223
+ const request = pendingSave.then(action, action);
224
+ pendingSave = request.catch(() => undefined);
225
+ return request;
226
+ }
227
+ //# sourceMappingURL=audit-history.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-history.js","sourceRoot":"","sources":["../src/audit-history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AACpC,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAC/C,MAAM,sBAAsB,GAAG,OAAO,CAAC;AACvC,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAC3C,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAE1C,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;IACvD,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;QAC3B,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC;eACzD,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;eACrB,CAAC,GAAG,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC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OAAO,CAAC,IAAI,CAAC;YAChB,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/C,CAAC;IACJ,CAAC,CAAC;IACF,MAAM,OAAO,GAAG,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjD,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC7C,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\n\nexport const MAX_AUDIT_HISTORY = 10;\nexport const MAX_AUDIT_SNAPSHOT_BYTES = 60_000;\nconst MAX_HISTORY_FILE_BYTES = 660_000;\nconst HISTORY_DIRECTORY = \".mcp-validator\";\nconst HISTORY_FILE = \"audit-history.json\";\n\nconst publicUrl = z.string().max(2_048).refine((value) => {\n try {\n const url = new URL(value);\n return (url.protocol === \"https:\" || url.protocol === \"http:\")\n && Boolean(url.hostname)\n && !url.username && !url.password && !url.search && !url.hash\n && !url.port;\n } catch {\n return false;\n }\n}, \"Only query-free, credential-free public HTTP(S) URLs may be saved.\");\n\nconst count = z.number().int().nonnegative();\nconst severity = z.enum([\"error\", \"warning\", \"info\"]);\nconst category = z.enum([\"HTML\", \"SEO\", \"Schema\", \"Accessibility\"]);\nconst finding = z.object({\n code: z.string().max(120).optional(),\n severity,\n category,\n message: z.string().max(300),\n});\nconst page = z.object({\n url: publicUrl,\n fetched_url: publicUrl.optional(),\n status: z.enum([\"passed\", \"needs_attention\", \"partial\", \"failed\", \"skipped\"]),\n http_status: z.number().int().min(200).max(299).optional(),\n redirects_followed: z.number().int().min(0).max(3).optional(),\n page_fetched: z.boolean(),\n html_validation_status: z.enum([\"completed\", \"timeout\", \"unavailable\", \"not_run\"]),\n html_errors: count,\n html_warnings: count,\n seo_errors: count,\n seo_warnings: count,\n schema_errors: count,\n schema_warnings: count,\n notes: count,\n health_score: z.number().int().min(0).max(100).optional(),\n failure_code: z.string().max(120).optional(),\n top_findings: z.array(finding).max(3),\n});\nconst issueGroup = finding.extend({\n affected_pages: count,\n example_urls: z.array(publicUrl).max(3),\n});\n\n/**\n * Keep only the fields used by compare_site_audits.\n * Rich page signals, raw HTML, widget state and unrelated user-supplied fields\n * are deliberately not persisted; the hosted app remains completely stateless.\n */\nexport const compactAuditSnapshotSchema = z.object({\n site_url: publicUrl,\n sitemap_url: publicUrl.optional(),\n discovery: z.enum([\"sitemap\", \"root_only\", \"partial\"]),\n discovery_error: z.enum([\"robots_unavailable\", \"sitemap_unavailable\", \"sitemap_invalid\", \"sitemap_query_unsupported\"]).optional(),\n pages_discovered: count,\n pages_selected: count,\n pages_audited: count,\n pages_partial: count,\n pages_failed: count,\n pages_skipped_robots: count,\n truncated: z.boolean(),\n next_page_offset: count.optional(),\n discovery_fingerprint: z.string().regex(/^[0-9a-f]{64}$/),\n audit_health_score: z.number().int().min(0).max(100).optional(),\n score_coverage_percent: z.number().int().min(0).max(100),\n pages: z.array(page).max(8),\n issue_groups: z.array(issueGroup).max(50),\n issue_groups_truncated: z.boolean(),\n});\n\nexport type CompactAuditSnapshot = z.infer<typeof compactAuditSnapshotSchema>;\n\nexport interface AuditHistoryItem {\n id: string;\n saved_at: string;\n site_url: string;\n}\n\ninterface PersistedItem extends AuditHistoryItem {\n snapshot: CompactAuditSnapshot;\n}\n\nconst historySchema = z.object({\n version: z.literal(1),\n items: z.array(z.object({\n id: z.string().uuid(),\n saved_at: z.string().datetime({ offset: true }),\n site_url: publicUrl,\n snapshot: compactAuditSnapshotSchema,\n })).max(MAX_AUDIT_HISTORY),\n});\n\nexport interface AuditHistoryResponse {\n count: number;\n items: AuditHistoryItem[];\n snapshot_json?: string;\n evicted_id?: string;\n}\n\nconst basePath = (): string => {\n const configured = process.env.MCP_WEB_VALIDATOR_WORKSPACE_ROOT;\n if (configured === undefined) return os.homedir();\n if (!path.isAbsolute(configured)) {\n throw new Error(\"MCP_WEB_VALIDATOR_WORKSPACE_ROOT must be an absolute directory path.\");\n }\n return configured;\n};\n\nasync function historyFile(rootDirectory: string, create: boolean): Promise<string> {\n const root = await fs.realpath(rootDirectory);\n const dir = path.join(root, HISTORY_DIRECTORY);\n if (create) await fs.mkdir(dir, { recursive: true, mode: 0o700 });\n const entry = await fs.lstat(dir).catch((error: NodeJS.ErrnoException) => {\n if (!create && error.code === \"ENOENT\") return undefined;\n throw error;\n });\n if (!entry) return path.join(dir, HISTORY_FILE);\n if (!entry.isDirectory() || entry.isSymbolicLink()) {\n throw new Error(\"The audit history directory must be a real directory, not a symbolic link.\");\n }\n const realDir = await fs.realpath(dir);\n if (path.dirname(realDir) !== root) {\n throw new Error(\"Audit history directory must stay inside the configured root.\");\n }\n return path.join(realDir, HISTORY_FILE);\n}\n\nasync function readHistory(rootDirectory: string): Promise<PersistedItem[]> {\n const file = await historyFile(rootDirectory, false);\n const info = await fs.lstat(file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") return undefined;\n throw error;\n });\n if (!info) return [];\n if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > MAX_HISTORY_FILE_BYTES) {\n throw new Error(\"History must be a bounded regular file, not a link or oversized file.\");\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(await fs.readFile(file, \"utf8\"));\n } catch {\n throw new Error(\"Audit history is unreadable or corrupt; no stored versions were modified.\");\n }\n const result = historySchema.safeParse(parsed);\n if (!result.success) throw new Error(\"Audit history is invalid; no stored versions were modified.\");\n return result.data.items;\n}\n\nasync function writeHistory(rootDirectory: string, items: PersistedItem[]): Promise<void> {\n const file = await historyFile(rootDirectory, true);\n const contents = JSON.stringify({ version: 1, items });\n if (Buffer.byteLength(contents, \"utf8\") > MAX_HISTORY_FILE_BYTES) {\n throw new Error(\"The audit history file would exceed the configured size cap.\");\n }\n const tmp = path.join(path.dirname(file), `.${HISTORY_FILE}.${randomUUID()}.tmp`);\n let handle: fs.FileHandle | undefined;\n try {\n handle = await fs.open(tmp, \"wx\", 0o600);\n await handle.writeFile(contents, \"utf8\");\n await handle.sync();\n await handle.close();\n handle = undefined;\n await fs.rename(tmp, file);\n } finally {\n if (handle) await handle.close();\n await fs.rm(tmp, { force: true });\n }\n}\n\nfunction summary(items: PersistedItem[]): AuditHistoryResponse {\n return {\n count: items.length,\n items: items.slice().reverse().map(({ id, saved_at, site_url }) => ({ id, saved_at, site_url })),\n };\n}\n\n// The stdio MCP server normally has one process. Serialize saves in-process\n// so simultaneous client calls cannot overwrite one another's latest version.\nlet pendingSave: Promise<unknown> = Promise.resolve();\n\nexport function parseCompactAuditSnapshot(snapshotJson: string): CompactAuditSnapshot {\n if (Buffer.byteLength(snapshotJson, \"utf8\") > MAX_AUDIT_SNAPSHOT_BYTES) {\n throw new Error(\"Audit snapshot exceeds the 60 KB input limit.\");\n }\n let candidate: unknown;\n try {\n candidate = JSON.parse(snapshotJson);\n } catch {\n throw new Error(\"Audit snapshot must be valid JSON.\");\n }\n const parsed = compactAuditSnapshotSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new Error(\"Audit snapshot must be a valid bounded audit_public_site structured result without secret-bearing URLs.\");\n }\n const compact = JSON.stringify(parsed.data);\n if (Buffer.byteLength(compact, \"utf8\") > MAX_AUDIT_SNAPSHOT_BYTES) {\n throw new Error(\"Compact audit snapshot exceeds the 60 KB storage limit.\");\n }\n return parsed.data;\n}\n\nexport async function listAuditHistory(rootDirectory = basePath()): Promise<AuditHistoryResponse> {\n return summary(await readHistory(rootDirectory));\n}\n\nexport async function getAuditHistorySnapshot(\n id: string,\n rootDirectory = basePath(),\n): Promise<AuditHistoryResponse> {\n const items = await readHistory(rootDirectory);\n const found = items.find((item) => item.id === id);\n if (!found) throw new Error(\"The requested audit history version was not found.\");\n return { ...summary(items), snapshot_json: JSON.stringify(found.snapshot) };\n}\n\nexport function saveAuditHistorySnapshot(\n snapshotJson: string,\n rootDirectory = basePath(),\n): Promise<AuditHistoryResponse> {\n const snapshot = parseCompactAuditSnapshot(snapshotJson);\n const action = async (): Promise<AuditHistoryResponse> => {\n const items = await readHistory(rootDirectory);\n const newItem: PersistedItem = {\n id: randomUUID(),\n saved_at: new Date().toISOString(),\n site_url: snapshot.site_url,\n snapshot,\n };\n const next = [...items, newItem];\n const evicted = next.length > MAX_AUDIT_HISTORY ? next.shift() : undefined;\n await writeHistory(rootDirectory, next);\n return {\n ...summary(next),\n ...(evicted ? { evicted_id: evicted.id } : {}),\n };\n };\n const request = pendingSave.then(action, action);\n pendingSave = request.catch(() => undefined);\n return request;\n}\n"]}
package/dist/index.js CHANGED
@@ -10,12 +10,16 @@ import { createValidationReport, validationReportChecks, } from "./report.js";
10
10
  import { fetchPublicText, getErrorMessage, readTextFile } from "./network.js";
11
11
  import { cssValidationContent, failureContent, htmlValidationContent, linkCheckContent, reportContent, schemaValidationContent, screenshotCaptureContent, screenshotPartialCaptureContent, seoAuditContent, } from "./presentation.js";
12
12
  import { PACKAGE_VERSION } from "./version.js";
13
+ import { MAX_AUDIT_HISTORY, MAX_AUDIT_SNAPSHOT_BYTES, getAuditHistorySnapshot, listAuditHistory, saveAuditHistorySnapshot, } from "./audit-history.js";
13
14
  import { getW3CMessageSeverity, MAX_CSS_VALIDATION_BYTES, validateCssContent, validateCssContentDetailed, validateHtmlContent, validateHtmlContentDetailed, } from "./w3c-validator.js";
14
15
  export const SERVER_VERSION = PACKAGE_VERSION;
15
16
  const HTML_MAX_BYTES = 2_000_000;
16
17
  const CSS_MAX_BYTES = MAX_CSS_VALIDATION_BYTES;
17
18
  const PATH_MAX_LENGTH = 4_096;
18
19
  const MAX_VIEWPORTS = 8;
20
+ // Bound machine-readable diagnostic payloads for MCP gateways with smaller result limits.
21
+ // The original issue totals and severity counts remain exact when details are clipped.
22
+ const MAX_MCP_ISSUES_JSON_BYTES = 16_000;
19
23
  function localHtmlValidationMediaType(filePath) {
20
24
  const extension = path.extname(filePath).toLowerCase();
21
25
  return extension === ".xhtml" || extension === ".xht"
@@ -104,6 +108,20 @@ const localReadOnlyAnnotations = {
104
108
  idempotentHint: true,
105
109
  openWorldHint: false,
106
110
  };
111
+ function boundedMcpIssues(details) {
112
+ let bytes = 2; // JSON array brackets.
113
+ let count = 0;
114
+ for (const issue of details.issues) {
115
+ const increment = Buffer.byteLength(JSON.stringify(issue), "utf8") + (count > 0 ? 1 : 0);
116
+ if (bytes + increment > MAX_MCP_ISSUES_JSON_BYTES)
117
+ break;
118
+ bytes += increment;
119
+ count += 1;
120
+ }
121
+ if (count === details.issues.length)
122
+ return details;
123
+ return { ...details, issues: details.issues.slice(0, count), truncated: true };
124
+ }
107
125
  function result(structuredContent, content, isError = false) {
108
126
  return {
109
127
  structuredContent: structuredContent,
@@ -400,7 +418,7 @@ export function createServer() {
400
418
  annotations: localReadOnlyAnnotations,
401
419
  }, async ({ htmlContent }) => {
402
420
  try {
403
- const { issues, totalIssues, truncated, counts } = auditSeoMetadataDetailed(htmlContent);
421
+ const { issues, totalIssues, truncated, counts } = boundedMcpIssues(auditSeoMetadataDetailed(htmlContent));
404
422
  return result({ issues, totalIssues, truncated, counts }, seoAuditContent(issues, totalIssues, truncated, counts));
405
423
  }
406
424
  catch (cause) {
@@ -455,7 +473,7 @@ export function createServer() {
455
473
  annotations: localReadOnlyAnnotations,
456
474
  }, async ({ htmlContent }) => {
457
475
  try {
458
- const { issues, totalIssues, truncated, counts } = validateSchemaMarkupDetailed(htmlContent);
476
+ const { issues, totalIssues, truncated, counts } = boundedMcpIssues(validateSchemaMarkupDetailed(htmlContent));
459
477
  return result({ issues, totalIssues, truncated, counts }, schemaValidationContent(issues, totalIssues, truncated, htmlContent));
460
478
  }
461
479
  catch (cause) {
@@ -510,6 +528,54 @@ export function createServer() {
510
528
  return result(reportData, failureContent("Validation report", error, "Confirm the input paths are readable and any base URL is public, then regenerate the report."), true);
511
529
  }
512
530
  });
531
+ server.registerTool("audit.history", {
532
+ title: "Manage local audit history",
533
+ description: "Opt-in local-only site-audit snapshot history. Save a previous hosted audit_public_site structured result as JSON, list saved IDs, or retrieve an exact version. A single compact local JSON file retains at most 10 versions; saving the 11th removes the oldest. No database, background task, or network request.",
534
+ inputSchema: {
535
+ action: z.enum(["save", "list", "get"]).describe("Save a snapshot, list versions, or retrieve one by ID."),
536
+ snapshotJson: z.string().min(1).max(MAX_AUDIT_SNAPSHOT_BYTES).optional()
537
+ .describe("For save: JSON-serialized structuredContent from hosted audit_public_site, max 60 KB. Raw HTML is not stored."),
538
+ id: z.string().uuid().optional().describe("For get: saved version ID returned by list or save."),
539
+ },
540
+ outputSchema: {
541
+ count: z.number().int().nonnegative(),
542
+ items: z.array(z.object({
543
+ id: z.string().uuid(),
544
+ saved_at: z.string(),
545
+ site_url: z.string(),
546
+ })).max(MAX_AUDIT_HISTORY),
547
+ snapshot_json: z.string().optional(),
548
+ evicted_id: z.string().uuid().optional(),
549
+ error: z.string().optional(),
550
+ },
551
+ annotations: {
552
+ readOnlyHint: false,
553
+ destructiveHint: true,
554
+ idempotentHint: false,
555
+ openWorldHint: false,
556
+ },
557
+ }, async ({ action, snapshotJson, id }) => {
558
+ try {
559
+ if (action === "save") {
560
+ if (!snapshotJson)
561
+ throw new Error("snapshotJson is required when action is save.");
562
+ const saved = await saveAuditHistorySnapshot(snapshotJson);
563
+ return result(saved, `Audit version saved locally. ${saved.count}/10 versions retained.${saved.evicted_id ? " Oldest version automatically deleted." : ""} Latest ID: ${saved.items[0]?.id}`);
564
+ }
565
+ if (action === "get") {
566
+ if (!id)
567
+ throw new Error("id is required when action is get.");
568
+ const found = await getAuditHistorySnapshot(id);
569
+ return result(found, `Retrieved audit history version ${id}. Use snapshot_json as a baseline or current result for compare_site_audits.`);
570
+ }
571
+ const listed = await listAuditHistory();
572
+ return result(listed, `Found ${listed.count} locally saved audit versions, newest first.`);
573
+ }
574
+ catch (cause) {
575
+ const error = getErrorMessage(cause);
576
+ return result({ count: 0, items: [], error }, failureContent("Audit history", error, "Review snapshot JSON or local history file permissions and retry."), true);
577
+ }
578
+ });
513
579
  server.registerTool("screenshot.capture", {
514
580
  title: "Capture responsive screenshots",
515
581
  description: "Renders a local HTML file or HTTP(S) URL in a sandboxed local Chromium browser and writes PNG screenshots to the requested directory. Downloads the pinned headless browser on first use if it is not already cached. Existing matching files may be replaced. Completed PNG paths are included if a later viewport fails.",