nain-mcp-validator 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 naindev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: nain-mcp-validator
3
+ Version: 0.1.0
4
+ Summary: Deterministic 3D asset validation and content integrity server for the Model Context Protocol (MCP).
5
+ Author-email: Aitor Nain Mendoza Vallejo <contact@naindev.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://mcp.naindev.com/
8
+ Project-URL: Repository, https://github.com/Nain9Dev/nain-mcp-validator
9
+ Keywords: mcp,model-context-protocol,3d,mesh-validation,gltf,deterministic
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Topic :: Scientific/Engineering
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: pydantic>=2.0.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
19
+ Requires-Dist: mypy>=1.10.0; extra == "dev"
20
+ Requires-Dist: ruff>=0.4.0; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ <picture>
24
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/banner-dark.svg">
25
+ <source media="(prefers-color-scheme: light)" srcset="docs/assets/banner-light.svg">
26
+ <img alt="nain-mcp-validator Architectural Blueprint" src="docs/assets/banner-dark.svg" width="100%">
27
+ </picture>
28
+
29
+ # nain-mcp-validator
30
+
31
+ > Standalone Model Context Protocol (MCP) server providing deterministic 3D asset validation (checks C1-C10), content-addressed artifact verification (SHA-256), and fail-closed conformance reporting for AI engineering agents.
32
+
33
+ [![Language: English](https://img.shields.io/badge/Language-English-blue.svg)](#)
34
+ [![Versión en Español](https://img.shields.io/badge/Versión-Español-red.svg)](README.es.md)
35
+ [![Protocol](https://img.shields.io/badge/MCP-2024--11--05-0047AB)](https://modelcontextprotocol.io/)
36
+ [![Python](https://img.shields.io/badge/Python-3.11+-3776AB)](https://www.python.org/)
37
+ [![Validation](https://img.shields.io/badge/Checks-C1_to_C10-22c55e)](docs/01-requirements.md)
38
+ [![License](https://img.shields.io/badge/License-MIT-gray)](LICENSE)
39
+
40
+ mcp-name: io.github.Nain9Dev/nain-mcp-validator
41
+
42
+ ---
43
+
44
+ ## Install and run
45
+
46
+ The server speaks JSON-RPC over stdio and has no network access. Once the package is on PyPI:
47
+
48
+ ```bash
49
+ uvx nain-mcp-validator
50
+ ```
51
+
52
+ Until then, run it straight from the repository:
53
+
54
+ ```bash
55
+ uvx --from git+https://github.com/Nain9Dev/nain-mcp-validator nain-mcp-validator
56
+ ```
57
+
58
+ MCP client configuration:
59
+
60
+ ```json
61
+ {
62
+ "mcpServers": {
63
+ "nain-mcp-validator": {
64
+ "command": "uvx",
65
+ "args": ["nain-mcp-validator"]
66
+ }
67
+ }
68
+ }
69
+ ```
70
+
71
+ ## 1. Overview
72
+
73
+ `nain-mcp-validator` solves the reliability gap when AI agents generate CAD geometry, meshes, or engineering specifications. Instead of relying on probabilistic text inspection, it equips agents with deterministic validation tools:
74
+
75
+ - `validate_mesh_invariants`: Topological validation enforcing watertight closure, 2-manifold boundaries, outward normal consistency, and the quantum sliver threshold ($10^{-12}\text{ m}^2$).
76
+ - `verify_content_digest`: Cryptographic verification of SHA-256 content hashes.
77
+ - `generate_conformance_report`: Produces standardized markdown conformance audits with a fail-closed verdict.
78
+
79
+ ## 2. Quickstart & Testing
80
+
81
+ ```bash
82
+ # Run pytest verification suite
83
+ pytest -v
84
+ ```
85
+
86
+ ## 3. Integration with AI Clients
87
+
88
+ Add the server to your Claude Desktop or Cursor configuration:
89
+
90
+ ```json
91
+ {
92
+ "mcpServers": {
93
+ "nain-validator": {
94
+ "command": "python",
95
+ "args": ["-m", "nain_mcp_validator.server"],
96
+ "cwd": "/path/to/nain-mcp-validator"
97
+ }
98
+ }
99
+ }
100
+ ```
101
+
102
+ ---
103
+
104
+ **Author**: Aitor Nain Mendoza Vallejo
105
+ **Standards**: [NainDev Engineering Handbook](https://github.com/Nain9Dev/engineering-handbook)
@@ -0,0 +1,83 @@
1
+ <picture>
2
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/banner-dark.svg">
3
+ <source media="(prefers-color-scheme: light)" srcset="docs/assets/banner-light.svg">
4
+ <img alt="nain-mcp-validator Architectural Blueprint" src="docs/assets/banner-dark.svg" width="100%">
5
+ </picture>
6
+
7
+ # nain-mcp-validator
8
+
9
+ > Standalone Model Context Protocol (MCP) server providing deterministic 3D asset validation (checks C1-C10), content-addressed artifact verification (SHA-256), and fail-closed conformance reporting for AI engineering agents.
10
+
11
+ [![Language: English](https://img.shields.io/badge/Language-English-blue.svg)](#)
12
+ [![Versión en Español](https://img.shields.io/badge/Versión-Español-red.svg)](README.es.md)
13
+ [![Protocol](https://img.shields.io/badge/MCP-2024--11--05-0047AB)](https://modelcontextprotocol.io/)
14
+ [![Python](https://img.shields.io/badge/Python-3.11+-3776AB)](https://www.python.org/)
15
+ [![Validation](https://img.shields.io/badge/Checks-C1_to_C10-22c55e)](docs/01-requirements.md)
16
+ [![License](https://img.shields.io/badge/License-MIT-gray)](LICENSE)
17
+
18
+ mcp-name: io.github.Nain9Dev/nain-mcp-validator
19
+
20
+ ---
21
+
22
+ ## Install and run
23
+
24
+ The server speaks JSON-RPC over stdio and has no network access. Once the package is on PyPI:
25
+
26
+ ```bash
27
+ uvx nain-mcp-validator
28
+ ```
29
+
30
+ Until then, run it straight from the repository:
31
+
32
+ ```bash
33
+ uvx --from git+https://github.com/Nain9Dev/nain-mcp-validator nain-mcp-validator
34
+ ```
35
+
36
+ MCP client configuration:
37
+
38
+ ```json
39
+ {
40
+ "mcpServers": {
41
+ "nain-mcp-validator": {
42
+ "command": "uvx",
43
+ "args": ["nain-mcp-validator"]
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ ## 1. Overview
50
+
51
+ `nain-mcp-validator` solves the reliability gap when AI agents generate CAD geometry, meshes, or engineering specifications. Instead of relying on probabilistic text inspection, it equips agents with deterministic validation tools:
52
+
53
+ - `validate_mesh_invariants`: Topological validation enforcing watertight closure, 2-manifold boundaries, outward normal consistency, and the quantum sliver threshold ($10^{-12}\text{ m}^2$).
54
+ - `verify_content_digest`: Cryptographic verification of SHA-256 content hashes.
55
+ - `generate_conformance_report`: Produces standardized markdown conformance audits with a fail-closed verdict.
56
+
57
+ ## 2. Quickstart & Testing
58
+
59
+ ```bash
60
+ # Run pytest verification suite
61
+ pytest -v
62
+ ```
63
+
64
+ ## 3. Integration with AI Clients
65
+
66
+ Add the server to your Claude Desktop or Cursor configuration:
67
+
68
+ ```json
69
+ {
70
+ "mcpServers": {
71
+ "nain-validator": {
72
+ "command": "python",
73
+ "args": ["-m", "nain_mcp_validator.server"],
74
+ "cwd": "/path/to/nain-mcp-validator"
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ ---
81
+
82
+ **Author**: Aitor Nain Mendoza Vallejo
83
+ **Standards**: [NainDev Engineering Handbook](https://github.com/Nain9Dev/engineering-handbook)
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "nain-mcp-validator"
3
+ version = "0.1.0"
4
+ description = "Deterministic 3D asset validation and content integrity server for the Model Context Protocol (MCP)."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = { text = "MIT" }
8
+ keywords = ["mcp", "model-context-protocol", "3d", "mesh-validation", "gltf", "deterministic"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "License :: OSI Approved :: MIT License",
12
+ "Topic :: Scientific/Engineering",
13
+ ]
14
+ authors = [
15
+ { name = "Aitor Nain Mendoza Vallejo", email = "contact@naindev.com" }
16
+ ]
17
+ dependencies = [
18
+ "pydantic>=2.0.0",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://mcp.naindev.com/"
23
+ Repository = "https://github.com/Nain9Dev/nain-mcp-validator"
24
+
25
+ [project.scripts]
26
+ nain-mcp-validator = "nain_mcp_validator.server:run_server"
27
+
28
+ [project.optional-dependencies]
29
+ dev = [
30
+ "pytest>=8.0.0",
31
+ "mypy>=1.10.0",
32
+ "ruff>=0.4.0",
33
+ ]
34
+
35
+ [build-system]
36
+ requires = ["setuptools>=61.0"]
37
+ build-backend = "setuptools.build_meta"
38
+
39
+ [tool.ruff]
40
+ line-length = 100
41
+ target-version = "py312"
42
+
43
+ [tool.mypy]
44
+ strict = true
45
+ python_version = "3.12"
46
+
47
+ [tool.pytest.ini_options]
48
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Nain MCP Validator: Deterministic 3D asset and artifact validation server."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,142 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections.abc import Sequence
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+ QUANTUM_AREA_THRESHOLD: float = 1e-12 # m^2 threshold for micro-degeneracy
9
+
10
+ class Point3D(BaseModel):
11
+ x: float
12
+ y: float
13
+ z: float
14
+
15
+ class MeshValidationResult(BaseModel):
16
+ is_conforming: bool
17
+ vertex_count: int
18
+ face_count: int
19
+ edge_count: int
20
+ euler_characteristic: int
21
+ c1_buffer_integrity: bool
22
+ c2_degenerate_faces: int
23
+ c3_is_manifold: bool
24
+ c4_is_watertight: bool
25
+ c5_is_winding_consistent: bool
26
+ errors: list[str] = Field(default_factory=list)
27
+
28
+ def _triangle_area(p0: Point3D, p1: Point3D, p2: Point3D) -> float:
29
+ # Cross product of (p1 - p0) and (p2 - p0)
30
+ v1x, v1y, v1z = p1.x - p0.x, p1.y - p0.y, p1.z - p0.z
31
+ v2x, v2y, v2z = p2.x - p0.x, p2.y - p0.y, p2.z - p0.z
32
+
33
+ cx = v1y * v2z - v1z * v2y
34
+ cy = v1z * v2x - v1x * v2z
35
+ cz = v1x * v2y - v1y * v2x
36
+
37
+ cross_norm = math.sqrt(cx * cx + cy * cy + cz * cz)
38
+ return 0.5 * cross_norm
39
+
40
+ def validate_triangular_mesh(
41
+ vertices: Sequence[Point3D | tuple[float, float, float]],
42
+ faces: Sequence[tuple[int, int, int]],
43
+ bodies: int = 1,
44
+ genus: int = 0,
45
+ ) -> MeshValidationResult:
46
+ errors: list[str] = []
47
+
48
+ # Normalize vertices to Point3D
49
+ pts: list[Point3D] = []
50
+ for i, v in enumerate(vertices):
51
+ if isinstance(v, Point3D):
52
+ p = v
53
+ else:
54
+ p = Point3D(x=v[0], y=v[1], z=v[2])
55
+ if math.isnan(p.x) or math.isnan(p.y) or math.isnan(p.z):
56
+ errors.append(f"C1: Vertex {i} contains NaN coordinates")
57
+ pts.append(p)
58
+
59
+ vertex_count = len(pts)
60
+ face_count = len(faces)
61
+
62
+ # C1: Buffer integrity & index bounds
63
+ c1_pass = True
64
+ for f_idx, (i0, i1, i2) in enumerate(faces):
65
+ if i0 < 0 or i0 >= vertex_count or i1 < 0 or i1 >= vertex_count or i2 < 0 or i2 >= vertex_count:
66
+ errors.append(f"C1: Face {f_idx} references out-of-bounds vertex index ({i0}, {i1}, {i2})")
67
+ c1_pass = False
68
+
69
+ # C2: Quantum threshold degenerate faces
70
+ degenerate_count = 0
71
+ if c1_pass:
72
+ for f_idx, (i0, i1, i2) in enumerate(faces):
73
+ area = _triangle_area(pts[i0], pts[i1], pts[i2])
74
+ if area < QUANTUM_AREA_THRESHOLD:
75
+ degenerate_count += 1
76
+ errors.append(f"C2: Face {f_idx} area ({area:.2e} m²) is below quantum threshold ({QUANTUM_AREA_THRESHOLD:.0e} m²)")
77
+
78
+ # Build directed and undirected edge maps
79
+ # Directed edge: (u, v) -> count
80
+ # Undirected edge: (min(u, v), max(u, v)) -> list of faces
81
+ edge_face_count: dict[tuple[int, int], int] = {}
82
+ directed_edges: dict[tuple[int, int], int] = {}
83
+
84
+ for f_idx, (i0, i1, i2) in enumerate(faces):
85
+ tri_edges = [(i0, i1), (i1, i2), (i2, i0)]
86
+ for u_idx, v_idx in tri_edges:
87
+ directed_edges[(u_idx, v_idx)] = directed_edges.get((u_idx, v_idx), 0) + 1
88
+ undirected = (min(u_idx, v_idx), max(u_idx, v_idx))
89
+ edge_face_count[undirected] = edge_face_count.get(undirected, 0) + 1
90
+
91
+ edge_count = len(edge_face_count)
92
+
93
+ # C3: 2-Manifold check (each undirected edge shared by at most 2 faces)
94
+ c3_manifold = True
95
+ non_manifold_edges = [edge for edge, count in edge_face_count.items() if count > 2]
96
+ if non_manifold_edges:
97
+ c3_manifold = False
98
+ errors.append(f"C3: Found {len(non_manifold_edges)} non-manifold edges shared by > 2 faces")
99
+
100
+ # C4: Watertight closure (every undirected edge shared by exactly 2 faces)
101
+ c4_watertight = True
102
+ boundary_edges = [edge for edge, count in edge_face_count.items() if count == 1]
103
+ if boundary_edges:
104
+ c4_watertight = False
105
+ errors.append(f"C4: Mesh has {len(boundary_edges)} boundary edges (open mesh / not watertight)")
106
+
107
+ # C5: Normal / Winding consistency (opposing directed edges)
108
+ c5_winding = True
109
+ for (u_node, v_node), count in directed_edges.items():
110
+ if count > 1:
111
+ c5_winding = False
112
+ errors.append(f"C5: Directed edge ({u_node}, {v_node}) appears {count} times (inconsistent face winding)")
113
+ break
114
+
115
+ # C10: Euler-Poincaré invariant: chi = V - E + F = 2 * (bodies - genus)
116
+ expected_chi = 2 * (bodies - genus)
117
+ actual_chi = vertex_count - edge_count + face_count
118
+ if c4_watertight and actual_chi != expected_chi:
119
+ errors.append(f"C10: Euler characteristic mismatch: V - E + F = {actual_chi}, expected {expected_chi}")
120
+
121
+ is_conforming = (
122
+ c1_pass
123
+ and degenerate_count == 0
124
+ and c3_manifold
125
+ and c4_watertight
126
+ and c5_winding
127
+ and len(errors) == 0
128
+ )
129
+
130
+ return MeshValidationResult(
131
+ is_conforming=is_conforming,
132
+ vertex_count=vertex_count,
133
+ face_count=face_count,
134
+ edge_count=edge_count,
135
+ euler_characteristic=actual_chi,
136
+ c1_buffer_integrity=c1_pass,
137
+ c2_degenerate_faces=degenerate_count,
138
+ c3_is_manifold=c3_manifold,
139
+ c4_is_watertight=c4_watertight,
140
+ c5_is_winding_consistent=c5_winding,
141
+ errors=errors,
142
+ )
@@ -0,0 +1,26 @@
1
+ import hashlib
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class DigestVerificationResult(BaseModel):
7
+ is_valid: bool
8
+ computed_digest: str
9
+ expected_digest: str
10
+ payload_byte_size: int
11
+
12
+ def verify_sha256(data: bytes | str, expected_sha256: str) -> DigestVerificationResult:
13
+ if isinstance(data, str):
14
+ payload_bytes = data.encode("utf-8")
15
+ else:
16
+ payload_bytes = data
17
+
18
+ computed = hashlib.sha256(payload_bytes).hexdigest()
19
+ is_valid = computed.lower() == expected_sha256.lower().strip()
20
+
21
+ return DigestVerificationResult(
22
+ is_valid=is_valid,
23
+ computed_digest=computed,
24
+ expected_digest=expected_sha256.strip(),
25
+ payload_byte_size=len(payload_bytes),
26
+ )
@@ -0,0 +1,37 @@
1
+ from nain_mcp_validator.domain.checks import MeshValidationResult
2
+
3
+
4
+ def generate_markdown_report(asset_name: str, result: MeshValidationResult) -> str:
5
+ verdict_badge = "**PASSED (Conforming)**" if result.is_conforming else "**FAILED (Non-Conforming)**"
6
+
7
+ report_lines = [
8
+ f"# Deterministic 3D Conformance Report: {asset_name}",
9
+ "",
10
+ f"- **Verdict**: {verdict_badge}",
11
+ f"- **Euler Characteristic**: $\\chi = {result.euler_characteristic}$ (V={result.vertex_count}, E={result.edge_count}, F={result.face_count})",
12
+ "",
13
+ "## Invariant Validation Matrix",
14
+ "",
15
+ "| Check Code | Invariant Target | Result | Details |",
16
+ "| :--- | :--- | :---: | :--- |",
17
+ f"| **C1** | Buffer Integrity & Bounds | {'PASS' if result.c1_buffer_integrity else 'FAIL'} | 0 NaN or out-of-bound indices |",
18
+ f"| **C2** | Quantum Threshold ($10^{{-12}}\\text{{ m}}^2$) | {'PASS' if result.c2_degenerate_faces == 0 else 'FAIL'} | {result.c2_degenerate_faces} degenerate faces detected |",
19
+ f"| **C3** | 2-Manifold Topology | {'PASS' if result.c3_is_manifold else 'FAIL'} | Edge-to-face adjacency bound <= 2 |",
20
+ f"| **C4** | Watertight Closure | {'PASS' if result.c4_is_watertight else 'FAIL'} | Closed boundary envelope |",
21
+ f"| **C5** | Winding & Normal Consistency | {'PASS' if result.c5_is_winding_consistent else 'FAIL'} | Coherent half-edge orientations |",
22
+ "",
23
+ ]
24
+
25
+ if result.errors:
26
+ report_lines.append("## Gating Discrepancies & Violations")
27
+ report_lines.append("")
28
+ for err in result.errors:
29
+ report_lines.append(f"- `{err}`")
30
+ report_lines.append("")
31
+ else:
32
+ report_lines.append("## Gate Verdict")
33
+ report_lines.append("")
34
+ report_lines.append("All deterministic invariants satisfied. Asset cleared for downstream manufacturing / 3D rendering pipeline.")
35
+ report_lines.append("")
36
+
37
+ return "\n".join(report_lines)
@@ -0,0 +1,243 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ from typing import Any
6
+
7
+ from nain_mcp_validator.domain.checks import Point3D, validate_triangular_mesh
8
+ from nain_mcp_validator.domain.digest import verify_sha256
9
+ from nain_mcp_validator.domain.reporter import generate_markdown_report
10
+
11
+ TOOLS_DEFINITIONS = [
12
+ {
13
+ "name": "validate_mesh_invariants",
14
+ "description": "Deterministic validation of 3D triangular mesh invariants (checks C1-C10) including watertightness, 2-manifoldness, quantum sliver threshold, and normal winding.",
15
+ "inputSchema": {
16
+ "type": "object",
17
+ "properties": {
18
+ "vertices": {
19
+ "type": "array",
20
+ "items": {
21
+ "type": "array",
22
+ "items": {"type": "number"},
23
+ "minItems": 3,
24
+ "maxItems": 3,
25
+ },
26
+ "description": "List of [x, y, z] coordinate triplets.",
27
+ },
28
+ "faces": {
29
+ "type": "array",
30
+ "items": {
31
+ "type": "array",
32
+ "items": {"type": "integer"},
33
+ "minItems": 3,
34
+ "maxItems": 3,
35
+ },
36
+ "description": "List of [i0, i1, i2] vertex index triplets.",
37
+ },
38
+ "bodies": {
39
+ "type": "integer",
40
+ "default": 1,
41
+ "description": "Expected number of disjoint bodies (default: 1).",
42
+ },
43
+ "genus": {
44
+ "type": "integer",
45
+ "default": 0,
46
+ "description": "Expected genus/through-holes (default: 0).",
47
+ },
48
+ },
49
+ "required": ["vertices", "faces"],
50
+ },
51
+ },
52
+ {
53
+ "name": "verify_content_digest",
54
+ "description": "Cryptographic content-addressing validation ensuring an artifact or specification matches its immutable SHA-256 digest.",
55
+ "inputSchema": {
56
+ "type": "object",
57
+ "properties": {
58
+ "content": {
59
+ "type": "string",
60
+ "description": "UTF-8 content string to hash and verify.",
61
+ },
62
+ "expected_sha256": {
63
+ "type": "string",
64
+ "description": "64-character hexadecimal SHA-256 digest to compare against.",
65
+ },
66
+ },
67
+ "required": ["content", "expected_sha256"],
68
+ },
69
+ },
70
+ {
71
+ "name": "generate_conformance_report",
72
+ "description": "Generates a standardized Markdown dual-contract conformance report from mesh validation results with fail-closed summary.",
73
+ "inputSchema": {
74
+ "type": "object",
75
+ "properties": {
76
+ "asset_name": {
77
+ "type": "string",
78
+ "description": "Identifier or filename of the asset.",
79
+ },
80
+ "vertices": {
81
+ "type": "array",
82
+ "items": {
83
+ "type": "array",
84
+ "items": {"type": "number"},
85
+ "minItems": 3,
86
+ "maxItems": 3,
87
+ },
88
+ },
89
+ "faces": {
90
+ "type": "array",
91
+ "items": {
92
+ "type": "array",
93
+ "items": {"type": "integer"},
94
+ "minItems": 3,
95
+ "maxItems": 3,
96
+ },
97
+ },
98
+ },
99
+ "required": ["asset_name", "vertices", "faces"],
100
+ },
101
+ },
102
+ ]
103
+
104
+ def handle_tool_call(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
105
+ if name == "validate_mesh_invariants":
106
+ raw_verts = arguments.get("vertices", [])
107
+ raw_faces: list[tuple[int, int, int]] = [
108
+ (int(f[0]), int(f[1]), int(f[2])) for f in arguments.get("faces", [])
109
+ ]
110
+ bodies = arguments.get("bodies", 1)
111
+ genus = arguments.get("genus", 0)
112
+
113
+ pts = [Point3D(x=float(v[0]), y=float(v[1]), z=float(v[2])) for v in raw_verts]
114
+ result = validate_triangular_mesh(pts, raw_faces, bodies=bodies, genus=genus)
115
+ return {
116
+ "content": [
117
+ {
118
+ "type": "text",
119
+ "text": json.dumps(result.model_dump(), indent=2),
120
+ }
121
+ ],
122
+ "isError": not result.is_conforming,
123
+ }
124
+
125
+ elif name == "verify_content_digest":
126
+ content = arguments.get("content", "")
127
+ expected_sha256 = arguments.get("expected_sha256", "")
128
+ res = verify_sha256(content, expected_sha256)
129
+ return {
130
+ "content": [
131
+ {
132
+ "type": "text",
133
+ "text": json.dumps(res.model_dump(), indent=2),
134
+ }
135
+ ],
136
+ "isError": not res.is_valid,
137
+ }
138
+
139
+ elif name == "generate_conformance_report":
140
+ asset_name = arguments.get("asset_name", "UnknownAsset")
141
+ raw_verts = arguments.get("vertices", [])
142
+ raw_faces = [
143
+ (int(f[0]), int(f[1]), int(f[2])) for f in arguments.get("faces", [])
144
+ ]
145
+ pts = [Point3D(x=float(v[0]), y=float(v[1]), z=float(v[2])) for v in raw_verts]
146
+ result = validate_triangular_mesh(pts, raw_faces)
147
+ report_md = generate_markdown_report(asset_name, result)
148
+ return {
149
+ "content": [
150
+ {
151
+ "type": "text",
152
+ "text": report_md,
153
+ }
154
+ ],
155
+ "isError": not result.is_conforming,
156
+ }
157
+
158
+ raise ValueError(f"Unknown tool: {name}")
159
+
160
+ def handle_json_rpc(request: dict[str, Any]) -> dict[str, Any] | None:
161
+ req_id = request.get("id")
162
+ method = request.get("method")
163
+ params = request.get("params", {})
164
+
165
+ if method == "initialize":
166
+ return {
167
+ "jsonrpc": "2.0",
168
+ "id": req_id,
169
+ "result": {
170
+ "protocolVersion": "2024-11-05",
171
+ "capabilities": {
172
+ "tools": {},
173
+ },
174
+ "serverInfo": {
175
+ "name": "nain-mcp-validator",
176
+ "version": "0.1.0",
177
+ },
178
+ },
179
+ }
180
+
181
+ elif method == "notifications/initialized":
182
+ return None
183
+
184
+ elif method == "tools/list":
185
+ return {
186
+ "jsonrpc": "2.0",
187
+ "id": req_id,
188
+ "result": {
189
+ "tools": TOOLS_DEFINITIONS,
190
+ },
191
+ }
192
+
193
+ elif method == "tools/call":
194
+ tool_name = params.get("name", "")
195
+ arguments = params.get("arguments", {})
196
+ try:
197
+ call_result = handle_tool_call(tool_name, arguments)
198
+ return {
199
+ "jsonrpc": "2.0",
200
+ "id": req_id,
201
+ "result": call_result,
202
+ }
203
+ except Exception as e: # noqa: BLE001
204
+ return {
205
+ "jsonrpc": "2.0",
206
+ "id": req_id,
207
+ "error": {
208
+ "code": -32603,
209
+ "message": str(e),
210
+ },
211
+ }
212
+
213
+ return {
214
+ "jsonrpc": "2.0",
215
+ "id": req_id,
216
+ "error": {
217
+ "code": -32601,
218
+ "message": f"Method not found: {method}",
219
+ },
220
+ }
221
+
222
+ def run_server() -> None:
223
+ for line in sys.stdin:
224
+ line = line.strip()
225
+ if not line:
226
+ continue
227
+ try:
228
+ req = json.loads(line)
229
+ resp = handle_json_rpc(req)
230
+ if resp is not None:
231
+ sys.stdout.write(json.dumps(resp) + "\n")
232
+ sys.stdout.flush()
233
+ except Exception as err: # noqa: BLE001
234
+ err_resp = {
235
+ "jsonrpc": "2.0",
236
+ "id": None,
237
+ "error": {"code": -32700, "message": f"Parse error: {err}"},
238
+ }
239
+ sys.stdout.write(json.dumps(err_resp) + "\n")
240
+ sys.stdout.flush()
241
+
242
+ if __name__ == "__main__":
243
+ run_server()
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: nain-mcp-validator
3
+ Version: 0.1.0
4
+ Summary: Deterministic 3D asset validation and content integrity server for the Model Context Protocol (MCP).
5
+ Author-email: Aitor Nain Mendoza Vallejo <contact@naindev.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://mcp.naindev.com/
8
+ Project-URL: Repository, https://github.com/Nain9Dev/nain-mcp-validator
9
+ Keywords: mcp,model-context-protocol,3d,mesh-validation,gltf,deterministic
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Topic :: Scientific/Engineering
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: pydantic>=2.0.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
19
+ Requires-Dist: mypy>=1.10.0; extra == "dev"
20
+ Requires-Dist: ruff>=0.4.0; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ <picture>
24
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/banner-dark.svg">
25
+ <source media="(prefers-color-scheme: light)" srcset="docs/assets/banner-light.svg">
26
+ <img alt="nain-mcp-validator Architectural Blueprint" src="docs/assets/banner-dark.svg" width="100%">
27
+ </picture>
28
+
29
+ # nain-mcp-validator
30
+
31
+ > Standalone Model Context Protocol (MCP) server providing deterministic 3D asset validation (checks C1-C10), content-addressed artifact verification (SHA-256), and fail-closed conformance reporting for AI engineering agents.
32
+
33
+ [![Language: English](https://img.shields.io/badge/Language-English-blue.svg)](#)
34
+ [![Versión en Español](https://img.shields.io/badge/Versión-Español-red.svg)](README.es.md)
35
+ [![Protocol](https://img.shields.io/badge/MCP-2024--11--05-0047AB)](https://modelcontextprotocol.io/)
36
+ [![Python](https://img.shields.io/badge/Python-3.11+-3776AB)](https://www.python.org/)
37
+ [![Validation](https://img.shields.io/badge/Checks-C1_to_C10-22c55e)](docs/01-requirements.md)
38
+ [![License](https://img.shields.io/badge/License-MIT-gray)](LICENSE)
39
+
40
+ mcp-name: io.github.Nain9Dev/nain-mcp-validator
41
+
42
+ ---
43
+
44
+ ## Install and run
45
+
46
+ The server speaks JSON-RPC over stdio and has no network access. Once the package is on PyPI:
47
+
48
+ ```bash
49
+ uvx nain-mcp-validator
50
+ ```
51
+
52
+ Until then, run it straight from the repository:
53
+
54
+ ```bash
55
+ uvx --from git+https://github.com/Nain9Dev/nain-mcp-validator nain-mcp-validator
56
+ ```
57
+
58
+ MCP client configuration:
59
+
60
+ ```json
61
+ {
62
+ "mcpServers": {
63
+ "nain-mcp-validator": {
64
+ "command": "uvx",
65
+ "args": ["nain-mcp-validator"]
66
+ }
67
+ }
68
+ }
69
+ ```
70
+
71
+ ## 1. Overview
72
+
73
+ `nain-mcp-validator` solves the reliability gap when AI agents generate CAD geometry, meshes, or engineering specifications. Instead of relying on probabilistic text inspection, it equips agents with deterministic validation tools:
74
+
75
+ - `validate_mesh_invariants`: Topological validation enforcing watertight closure, 2-manifold boundaries, outward normal consistency, and the quantum sliver threshold ($10^{-12}\text{ m}^2$).
76
+ - `verify_content_digest`: Cryptographic verification of SHA-256 content hashes.
77
+ - `generate_conformance_report`: Produces standardized markdown conformance audits with a fail-closed verdict.
78
+
79
+ ## 2. Quickstart & Testing
80
+
81
+ ```bash
82
+ # Run pytest verification suite
83
+ pytest -v
84
+ ```
85
+
86
+ ## 3. Integration with AI Clients
87
+
88
+ Add the server to your Claude Desktop or Cursor configuration:
89
+
90
+ ```json
91
+ {
92
+ "mcpServers": {
93
+ "nain-validator": {
94
+ "command": "python",
95
+ "args": ["-m", "nain_mcp_validator.server"],
96
+ "cwd": "/path/to/nain-mcp-validator"
97
+ }
98
+ }
99
+ }
100
+ ```
101
+
102
+ ---
103
+
104
+ **Author**: Aitor Nain Mendoza Vallejo
105
+ **Standards**: [NainDev Engineering Handbook](https://github.com/Nain9Dev/engineering-handbook)
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/nain_mcp_validator/__init__.py
5
+ src/nain_mcp_validator/server.py
6
+ src/nain_mcp_validator.egg-info/PKG-INFO
7
+ src/nain_mcp_validator.egg-info/SOURCES.txt
8
+ src/nain_mcp_validator.egg-info/dependency_links.txt
9
+ src/nain_mcp_validator.egg-info/entry_points.txt
10
+ src/nain_mcp_validator.egg-info/requires.txt
11
+ src/nain_mcp_validator.egg-info/top_level.txt
12
+ src/nain_mcp_validator/domain/checks.py
13
+ src/nain_mcp_validator/domain/digest.py
14
+ src/nain_mcp_validator/domain/reporter.py
15
+ tests/test_checks.py
16
+ tests/test_digest.py
17
+ tests/test_packaging.py
18
+ tests/test_server.py
19
+ tests/test_site_install.py
20
+ tests/test_site_seo.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nain-mcp-validator = nain_mcp_validator.server:run_server
@@ -0,0 +1,6 @@
1
+ pydantic>=2.0.0
2
+
3
+ [dev]
4
+ pytest>=8.0.0
5
+ mypy>=1.10.0
6
+ ruff>=0.4.0
@@ -0,0 +1 @@
1
+ nain_mcp_validator
@@ -0,0 +1,81 @@
1
+ from nain_mcp_validator.domain.checks import (
2
+ Point3D,
3
+ validate_triangular_mesh,
4
+ )
5
+
6
+
7
+ def test_closed_tetrahedron_is_conforming() -> None:
8
+ # Regular tetrahedron (4 vertices, 4 faces)
9
+ vertices = [
10
+ Point3D(x=1.0, y=1.0, z=1.0),
11
+ Point3D(x=-1.0, y=-1.0, z=1.0),
12
+ Point3D(x=-1.0, y=1.0, z=-1.0),
13
+ Point3D(x=1.0, y=-1.0, z=-1.0),
14
+ ]
15
+ # Outward winding
16
+ faces = [
17
+ (0, 1, 2),
18
+ (0, 3, 1),
19
+ (0, 2, 3),
20
+ (1, 3, 2),
21
+ ]
22
+
23
+ result = validate_triangular_mesh(vertices, faces, bodies=1, genus=0)
24
+ assert result.is_conforming is True
25
+ assert result.c1_buffer_integrity is True
26
+ assert result.c2_degenerate_faces == 0
27
+ assert result.c3_is_manifold is True
28
+ assert result.c4_is_watertight is True
29
+ assert result.c5_is_winding_consistent is True
30
+ assert result.euler_characteristic == 2 # V=4, E=6, F=4 -> 4 - 6 + 4 = 2
31
+
32
+
33
+ def test_degenerate_micro_face_fails_quantum_threshold() -> None:
34
+ # Triangle with collinear vertices (area = 0.0)
35
+ vertices = [
36
+ Point3D(x=0.0, y=0.0, z=0.0),
37
+ Point3D(x=1.0, y=0.0, z=0.0),
38
+ Point3D(x=2.0, y=0.0, z=0.0), # Collinear!
39
+ ]
40
+ faces = [(0, 1, 2)]
41
+
42
+ result = validate_triangular_mesh(vertices, faces)
43
+ assert result.is_conforming is False
44
+ assert result.c2_degenerate_faces == 1
45
+ assert any("C2:" in err for err in result.errors)
46
+
47
+
48
+ def test_open_mesh_fails_watertight_check() -> None:
49
+ # Single triangle is open (3 boundary edges)
50
+ vertices = [
51
+ Point3D(x=0.0, y=0.0, z=0.0),
52
+ Point3D(x=1.0, y=0.0, z=0.0),
53
+ Point3D(x=0.0, y=1.0, z=0.0),
54
+ ]
55
+ faces = [(0, 1, 2)]
56
+
57
+ result = validate_triangular_mesh(vertices, faces)
58
+ assert result.is_conforming is False
59
+ assert result.c4_is_watertight is False
60
+ assert any("C4:" in err for err in result.errors)
61
+
62
+
63
+ def test_non_manifold_mesh_fails_manifold_check() -> None:
64
+ # 3 triangles sharing edge (0, 1) -> non-manifold book fold
65
+ vertices = [
66
+ Point3D(x=0.0, y=0.0, z=0.0),
67
+ Point3D(x=0.0, y=1.0, z=0.0),
68
+ Point3D(x=1.0, y=0.0, z=0.0),
69
+ Point3D(x=-1.0, y=0.0, z=0.0),
70
+ Point3D(x=0.0, y=0.0, z=1.0),
71
+ ]
72
+ faces = [
73
+ (0, 1, 2),
74
+ (1, 0, 3),
75
+ (0, 1, 4), # Third face on edge (0, 1)
76
+ ]
77
+
78
+ result = validate_triangular_mesh(vertices, faces)
79
+ assert result.is_conforming is False
80
+ assert result.c3_is_manifold is False
81
+ assert any("C3:" in err for err in result.errors)
@@ -0,0 +1,22 @@
1
+ import hashlib
2
+
3
+ from nain_mcp_validator.domain.digest import verify_sha256
4
+
5
+
6
+ def test_verify_sha256_matches_exact_digest() -> None:
7
+ content = "deterministic-cad-specification-v1"
8
+ digest = hashlib.sha256(content.encode("utf-8")).hexdigest()
9
+
10
+ result = verify_sha256(content, digest)
11
+ assert result.is_valid is True
12
+ assert result.computed_digest == digest
13
+ assert result.payload_byte_size == len(content.encode("utf-8"))
14
+
15
+
16
+ def test_verify_sha256_detects_mismatch() -> None:
17
+ content = "actual-content"
18
+ tampered_digest = "0000000000000000000000000000000000000000000000000000000000000000"
19
+
20
+ result = verify_sha256(content, tampered_digest)
21
+ assert result.is_valid is False
22
+ assert result.expected_digest == tampered_digest
@@ -0,0 +1,85 @@
1
+ """REQ-PKG-01 to REQ-PKG-03: the server can be installed and listed in the official MCP Registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import subprocess
8
+ import sys
9
+ import tomllib
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ NAME = "io.github.Nain9Dev/nain-mcp-validator"
15
+
16
+
17
+ def _pyproject() -> dict[str, Any]:
18
+ return tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))
19
+
20
+
21
+ def test_console_script_starts_the_stdio_server() -> None:
22
+ """REQ-PKG-01: `nain-mcp-validator` is a console script that runs the stdio loop."""
23
+ scripts = _pyproject()["project"]["scripts"]
24
+ assert scripts["nain-mcp-validator"] == "nain_mcp_validator.server:run_server"
25
+
26
+
27
+ def test_server_json_matches_the_package() -> None:
28
+ """REQ-PKG-02: server.json names the same server, version and PyPI package."""
29
+ server = json.loads((ROOT / "server.json").read_text(encoding="utf-8"))
30
+ project = _pyproject()["project"]
31
+ assert server["name"] == NAME
32
+ assert server["version"] == project["version"]
33
+ assert server["repository"]["url"] == "https://github.com/Nain9Dev/nain-mcp-validator"
34
+ (package,) = server["packages"]
35
+ assert package["registryType"] == "pypi"
36
+ assert package["identifier"] == project["name"]
37
+ assert package["version"] == project["version"]
38
+ assert package["transport"] == {"type": "stdio"}
39
+ assert len(server["description"]) <= 100
40
+
41
+
42
+ def test_readme_carries_the_pypi_ownership_marker() -> None:
43
+ """REQ-PKG-03: the registry verifies a PyPI package through `mcp-name:` in the README."""
44
+ readme = (ROOT / "README.md").read_text(encoding="utf-8")
45
+ assert f"mcp-name: {NAME}" in readme
46
+
47
+
48
+ def _publish_workflow() -> str:
49
+ return (ROOT / ".github" / "workflows" / "publish.yml").read_text(encoding="utf-8")
50
+
51
+
52
+ def test_publish_workflow_runs_on_version_tags_only() -> None:
53
+ """REQ-PKG-04: publishing starts from a `v*` tag, never from a branch push."""
54
+ workflow = _publish_workflow()
55
+ assert 'tags: ["v*"]' in workflow
56
+ assert "branches:" not in workflow
57
+
58
+
59
+ def test_publish_workflow_uses_oidc_and_no_secrets() -> None:
60
+ """REQ-PKG-04: PyPI trusted publishing and the registry login use OIDC, not stored tokens."""
61
+ workflow = _publish_workflow()
62
+ assert "secrets." not in workflow
63
+ assert "mcp-publisher login github-oidc" in workflow
64
+ assert "pypa/gh-action-pypi-publish@" in workflow
65
+ # id-token is granted per job, never for the whole workflow.
66
+ assert workflow.count("id-token: write") == 2
67
+
68
+
69
+ def test_publish_workflow_checks_the_tag_against_the_versions() -> None:
70
+ """REQ-PKG-04: a tag that differs from pyproject.toml or server.json stops the release."""
71
+ assert "scripts/check_release_version.py" in _publish_workflow()
72
+ guard = [sys.executable, str(ROOT / "scripts" / "check_release_version.py")]
73
+ ok = subprocess.run([*guard, "v0.1.0"], capture_output=True, text=True, check=False)
74
+ assert ok.returncode == 0, ok.stderr
75
+ bad = subprocess.run([*guard, "v9.9.9"], capture_output=True, text=True, check=False)
76
+ assert bad.returncode == 1
77
+ assert "version mismatch" in bad.stderr
78
+
79
+
80
+ def test_publish_workflow_pins_every_action_to_a_commit() -> None:
81
+ """REQ-PKG-04: third-party actions are pinned by full commit SHA."""
82
+ uses = re.findall(r"uses:\s*(\S+)", _publish_workflow())
83
+ assert uses
84
+ for reference in uses:
85
+ assert re.search(r"@[0-9a-f]{40}$", reference), reference
@@ -0,0 +1,61 @@
1
+ import json
2
+
3
+ from nain_mcp_validator.server import handle_json_rpc
4
+
5
+
6
+ def test_mcp_initialize() -> None:
7
+ req = {
8
+ "jsonrpc": "2.0",
9
+ "id": 1,
10
+ "method": "initialize",
11
+ "params": {},
12
+ }
13
+ resp = handle_json_rpc(req)
14
+ assert resp is not None
15
+ assert resp["id"] == 1
16
+ assert resp["result"]["serverInfo"]["name"] == "nain-mcp-validator"
17
+
18
+
19
+ def test_mcp_tools_list() -> None:
20
+ req = {
21
+ "jsonrpc": "2.0",
22
+ "id": 2,
23
+ "method": "tools/list",
24
+ }
25
+ resp = handle_json_rpc(req)
26
+ assert resp is not None
27
+ tools = resp["result"]["tools"]
28
+ tool_names = [t["name"] for t in tools]
29
+ assert "validate_mesh_invariants" in tool_names
30
+ assert "verify_content_digest" in tool_names
31
+ assert "generate_conformance_report" in tool_names
32
+
33
+
34
+ def test_mcp_tools_call_validate_mesh() -> None:
35
+ req = {
36
+ "jsonrpc": "2.0",
37
+ "id": 3,
38
+ "method": "tools/call",
39
+ "params": {
40
+ "name": "validate_mesh_invariants",
41
+ "arguments": {
42
+ "vertices": [
43
+ [1.0, 1.0, 1.0],
44
+ [-1.0, -1.0, 1.0],
45
+ [-1.0, 1.0, -1.0],
46
+ [1.0, -1.0, -1.0],
47
+ ],
48
+ "faces": [
49
+ [0, 1, 2],
50
+ [0, 3, 1],
51
+ [0, 2, 3],
52
+ [1, 3, 2],
53
+ ],
54
+ },
55
+ },
56
+ }
57
+ resp = handle_json_rpc(req)
58
+ assert resp is not None
59
+ assert "result" in resp
60
+ content = json.loads(resp["result"]["content"][0]["text"])
61
+ assert content["is_conforming"] is True
@@ -0,0 +1,120 @@
1
+ """Install contract of the project page: manifest, icons and head tags (REQ-PWA-01)."""
2
+
3
+ import json
4
+ import re
5
+ import struct
6
+ import zlib
7
+ from pathlib import Path
8
+
9
+ SITE = Path(__file__).resolve().parents[1] / "site"
10
+ PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
11
+ EXPECTED_ICONS = [
12
+ ("./icons/icon-192.png", "192x192", "any"),
13
+ ("./icons/icon-512.png", "512x512", "any"),
14
+ ("./icons/icon-maskable-512.png", "512x512", "maskable"),
15
+ ]
16
+
17
+
18
+ def _html() -> str:
19
+ return (SITE / "index.html").read_text(encoding="utf-8")
20
+
21
+
22
+ def _manifest() -> dict[str, object]:
23
+ manifest: dict[str, object] = json.loads(
24
+ (SITE / "manifest.webmanifest").read_text(encoding="utf-8")
25
+ )
26
+ return manifest
27
+
28
+
29
+ def _meta(html: str, name: str) -> list[str]:
30
+ return re.findall(rf'<meta\s+name="{re.escape(name)}"\s+content="([^"]*)"', html)
31
+
32
+
33
+ def _png_size(path: Path) -> tuple[int, int, int]:
34
+ """Return (width, height, colour type) read from the IHDR chunk of a PNG file."""
35
+ header = path.read_bytes()[:26]
36
+ assert header[:8] == PNG_SIGNATURE, f"{path.name} is not a PNG file"
37
+ width, height = struct.unpack(">II", header[16:24])
38
+ return width, height, header[25]
39
+
40
+
41
+ def _is_opaque(path: Path) -> bool:
42
+ """Decode an 8-bit RGB or RGBA PNG and report whether every pixel is fully opaque."""
43
+ data = path.read_bytes()
44
+ _, _, colour_type = _png_size(path)
45
+ if colour_type == 2:
46
+ return True
47
+ assert colour_type == 6 and data[24] == 8, f"{path.name}: expected 8-bit RGB or RGBA"
48
+ width = struct.unpack(">I", data[16:20])[0]
49
+ idat, at = b"", 8
50
+ while at < len(data):
51
+ length, kind = struct.unpack(">I4s", data[at : at + 8])
52
+ if kind == b"IDAT":
53
+ idat += data[at + 8 : at + 8 + length]
54
+ at += 12 + length
55
+ raw, stride, previous = zlib.decompress(idat), width * 4, bytearray(width * 4)
56
+ for start in range(0, len(raw), stride + 1):
57
+ filter_type, line = raw[start], bytearray(raw[start + 1 : start + 1 + stride])
58
+ for i in range(stride):
59
+ left = line[i - 4] if i >= 4 else 0
60
+ up, up_left = previous[i], (previous[i - 4] if i >= 4 else 0)
61
+ if filter_type == 1:
62
+ line[i] = (line[i] + left) & 255
63
+ elif filter_type == 2:
64
+ line[i] = (line[i] + up) & 255
65
+ elif filter_type == 3:
66
+ line[i] = (line[i] + (left + up) // 2) & 255
67
+ elif filter_type == 4:
68
+ p = left + up - up_left
69
+ best = min((abs(p - left), left), (abs(p - up), up), (abs(p - up_left), up_left))
70
+ line[i] = (line[i] + best[1]) & 255
71
+ if any(a != 255 for a in line[3::4]):
72
+ return False
73
+ previous = line
74
+ return True
75
+
76
+
77
+ def test_manifest_names_the_app_and_opens_it_standalone() -> None:
78
+ manifest = _manifest()
79
+ assert manifest["name"] == "Nain MCP Validator"
80
+ assert manifest["short_name"] == "Nain MCP"
81
+ assert manifest["description"] == _meta(_html(), "description")[0]
82
+ assert manifest["lang"] == "en"
83
+ assert manifest["dir"] == "ltr"
84
+ assert manifest["id"] == manifest["start_url"] == manifest["scope"] == "./"
85
+ assert manifest["display"] == "standalone"
86
+ assert manifest["theme_color"] == manifest["background_color"] == "#EDF1F6"
87
+ assert _meta(_html(), "theme-color") == ["#EDF1F6"]
88
+ assert "prefer_related_applications" not in manifest
89
+
90
+
91
+ def test_manifest_icons_exist_at_their_declared_size() -> None:
92
+ manifest = _manifest()
93
+ icons = manifest["icons"]
94
+ assert isinstance(icons, list)
95
+ assert [(i["src"], i["sizes"], i["purpose"]) for i in icons] == EXPECTED_ICONS
96
+ for icon in icons:
97
+ assert icon["type"] == "image/png"
98
+ width, height, _ = _png_size(SITE / icon["src"])
99
+ assert f"{width}x{height}" == icon["sizes"], icon["src"]
100
+
101
+
102
+ def test_maskable_and_apple_icons_are_opaque() -> None:
103
+ # A transparent pixel would be filled by the launcher with its own colour.
104
+ assert _is_opaque(SITE / "icons" / "icon-maskable-512.png")
105
+ assert _png_size(SITE / "icons" / "apple-touch-icon.png")[:2] == (180, 180)
106
+ assert _is_opaque(SITE / "icons" / "apple-touch-icon.png")
107
+
108
+
109
+ def test_page_links_manifest_and_carries_ios_tags() -> None:
110
+ html = _html()
111
+ assert re.findall(r'<link\s+rel="manifest"\s+href="([^"]*)"', html) == [
112
+ "./manifest.webmanifest"
113
+ ]
114
+ assert re.findall(r'<link\s+rel="apple-touch-icon"\s+href="([^"]*)"', html) == [
115
+ "./icons/apple-touch-icon.png"
116
+ ]
117
+ assert _meta(html, "mobile-web-app-capable") == ["yes"]
118
+ assert _meta(html, "apple-mobile-web-app-capable") == ["yes"]
119
+ assert _meta(html, "apple-mobile-web-app-title") == ["Nain MCP"]
120
+ assert _meta(html, "apple-mobile-web-app-status-bar-style") == ["default"]
@@ -0,0 +1,81 @@
1
+ """Search and AI-engine discoverability baseline for the public project page (REQ-SEO-01)."""
2
+
3
+ import json
4
+ import re
5
+ from pathlib import Path
6
+
7
+ SITE = Path(__file__).resolve().parents[1] / "site"
8
+ HOST_ROOT = "https://mcp.naindev.com/"
9
+ AUTHOR_ID = "https://www.naindev.com/#person"
10
+
11
+
12
+ def _html() -> str:
13
+ return (SITE / "index.html").read_text(encoding="utf-8")
14
+
15
+
16
+ def _meta(html: str, key: str, value: str) -> list[str]:
17
+ pattern = rf'<meta\s+{key}="{re.escape(value)}"\s+content="([^"]*)"'
18
+ return re.findall(pattern, html)
19
+
20
+
21
+ def test_single_canonical_equals_host_root() -> None:
22
+ hrefs = re.findall(r'<link\s+rel="canonical"\s+href="([^"]*)"', _html())
23
+ assert hrefs == [HOST_ROOT]
24
+
25
+
26
+ def test_single_description_has_sensible_length() -> None:
27
+ descriptions = _meta(_html(), "name", "description")
28
+ assert len(descriptions) == 1
29
+ assert 70 <= len(descriptions[0]) <= 160
30
+
31
+
32
+ def test_open_graph_and_twitter_cards() -> None:
33
+ html = _html()
34
+ assert _meta(html, "property", "og:type") == ["website"]
35
+ assert _meta(html, "property", "og:url") == [HOST_ROOT]
36
+ assert _meta(html, "property", "og:site_name") == ["nain-mcp-validator"]
37
+ assert len(_meta(html, "property", "og:title")) == 1
38
+ assert _meta(html, "property", "og:description") == _meta(html, "name", "description")
39
+ images = _meta(html, "property", "og:image")
40
+ assert len(images) == 1 and images[0].startswith("https://")
41
+ assert _meta(html, "name", "twitter:card") == ["summary_large_image"]
42
+ assert _meta(html, "name", "twitter:image") == images
43
+
44
+
45
+ def test_author_link_and_single_h1() -> None:
46
+ html = _html()
47
+ assert '<link rel="author" href="https://www.naindev.com/">' in html
48
+ assert len(re.findall(r"<h1[\s>]", html)) == 1
49
+
50
+
51
+ def test_json_ld_software_application() -> None:
52
+ blocks = re.findall(
53
+ r'<script type="application/ld\+json">(.*?)</script>', _html(), flags=re.DOTALL
54
+ )
55
+ assert len(blocks) == 1
56
+ assert "<" not in blocks[0]
57
+ data = json.loads(blocks[0])
58
+ assert data["@type"] == "SoftwareApplication"
59
+ assert data["url"] == HOST_ROOT
60
+ assert data["author"]["@id"] == AUTHOR_ID
61
+ assert data["isAccessibleForFree"] is True
62
+ assert data["operatingSystem"] == "Web"
63
+
64
+
65
+ def test_robots_advertises_sitemap() -> None:
66
+ robots = (SITE / "robots.txt").read_text(encoding="utf-8").splitlines()
67
+ assert "User-agent: *" in robots
68
+ assert "Allow: /" in robots
69
+ assert f"Sitemap: {HOST_ROOT}sitemap.xml" in robots
70
+ assert not any(line.startswith("Disallow: /") for line in robots)
71
+
72
+
73
+ def test_sitemap_lists_canonical_root() -> None:
74
+ sitemap = (SITE / "sitemap.xml").read_text(encoding="utf-8")
75
+ assert re.findall(r"<loc>([^<]*)</loc>", sitemap) == [HOST_ROOT]
76
+
77
+
78
+ def test_llms_txt_starts_with_h1() -> None:
79
+ text = (SITE / "llms.txt").read_text(encoding="utf-8")
80
+ assert text.startswith("# ")
81
+ assert "\n> " in text