verifier-mcp 0.1.0__py3-none-any.whl

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,3 @@
1
+ """VerifierMCP — an MCP server that lets any LLM check its own work."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,85 @@
1
+ """Visual playground for VerifierMCP.
2
+
3
+ A FastAPI app that calls the same tool functions the MCP server exposes, so you can *see*
4
+ each verifier catch an error in the browser:
5
+
6
+ uvicorn verifier_mcp.playground:app --port 8080 # open http://localhost:8080
7
+
8
+ This is a human-facing demo. The actual MCP server is verifier_mcp.server.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from fastapi import FastAPI
17
+ from fastapi.responses import HTMLResponse, JSONResponse
18
+ from pydantic import BaseModel, Field
19
+
20
+ from verifier_mcp import tools
21
+
22
+ WEB_DIR = Path(__file__).resolve().parent / "web"
23
+ app = FastAPI(title="VerifierMCP Playground")
24
+
25
+
26
+ @app.get("/", response_class=HTMLResponse)
27
+ def index() -> str:
28
+ f = WEB_DIR / "index.html"
29
+ return f.read_text(encoding="utf-8") if f.exists() else "<h1>VerifierMCP</h1>"
30
+
31
+
32
+ @app.get("/health")
33
+ def health() -> dict:
34
+ return {"status": "ok"}
35
+
36
+
37
+ class MathReq(BaseModel):
38
+ expression: str
39
+ claimed_result: str | None = None
40
+
41
+
42
+ class CodeReq(BaseModel):
43
+ code: str
44
+ stdin: str = ""
45
+
46
+
47
+ class SchemaReq(BaseModel):
48
+ instance: Any
49
+ json_schema: Any = Field(alias="schema_json")
50
+
51
+
52
+ class UnitsReq(BaseModel):
53
+ expression: str
54
+ expected_unit: str | None = None
55
+
56
+
57
+ class RegexReq(BaseModel):
58
+ pattern: str
59
+ cases: list[dict[str, Any]]
60
+ flags: str = ""
61
+
62
+
63
+ @app.post("/api/verify_math")
64
+ def api_math(r: MathReq) -> JSONResponse:
65
+ return JSONResponse(tools.verify_math(r.expression, r.claimed_result))
66
+
67
+
68
+ @app.post("/api/run_code")
69
+ def api_code(r: CodeReq) -> JSONResponse:
70
+ return JSONResponse(tools.run_code(r.code, stdin=r.stdin, timeout=5.0))
71
+
72
+
73
+ @app.post("/api/validate_schema")
74
+ def api_schema(r: SchemaReq) -> JSONResponse:
75
+ return JSONResponse(tools.validate_schema(r.instance, r.json_schema))
76
+
77
+
78
+ @app.post("/api/check_units")
79
+ def api_units(r: UnitsReq) -> JSONResponse:
80
+ return JSONResponse(tools.check_units(r.expression, r.expected_unit))
81
+
82
+
83
+ @app.post("/api/test_regex")
84
+ def api_regex(r: RegexReq) -> JSONResponse:
85
+ return JSONResponse(tools.test_regex(r.pattern, r.cases, r.flags))
verifier_mcp/server.py ADDED
@@ -0,0 +1,77 @@
1
+ """VerifierMCP — an MCP server that lets any LLM check its own work.
2
+
3
+ Exposes five verification tools over the Model Context Protocol, built with the official
4
+ MCP Python SDK's FastMCP. Run it two ways:
5
+
6
+ python -m verifier_mcp.server # stdio (Claude Desktop, MCP clients)
7
+ python -m verifier_mcp.server --http # streamable HTTP on :8000/mcp
8
+
9
+ The tool bodies live in verifier_mcp.tools so they are unit-testable without the protocol.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ from typing import Any
16
+
17
+ from mcp.server.fastmcp import FastMCP
18
+
19
+ from verifier_mcp import tools
20
+
21
+ mcp = FastMCP(
22
+ "verifier-mcp",
23
+ instructions=(
24
+ "Verification tools. Before stating a mathematical result, a regex, structured "
25
+ "JSON, a unit calculation, or what a code snippet outputs, call the matching tool "
26
+ "to CHECK it. Prefer verified facts over asserted ones."
27
+ ),
28
+ )
29
+
30
+
31
+ @mcp.tool(description="Verify algebra/calculus symbolically (SymPy). "
32
+ "Pass an equation with '=', or an expression plus claimed_result.")
33
+ def verify_math(expression: str, claimed_result: str | None = None) -> dict[str, Any]:
34
+ return tools.verify_math(expression, claimed_result)
35
+
36
+
37
+ @mcp.tool(description="Run a Python snippet in a sandboxed subprocess and return its "
38
+ "stdout/stderr. Use to check that code does what it claims.")
39
+ def run_code(code: str, stdin: str = "", timeout: float = 5.0) -> dict[str, Any]:
40
+ return tools.run_code(code, stdin=stdin, timeout=min(timeout, 15.0))
41
+
42
+
43
+ @mcp.tool(description="Validate a JSON instance against a JSON Schema (Draft 2020-12). "
44
+ "Returns validity and a list of errors.")
45
+ def validate_schema(instance: Any, schema: Any) -> dict[str, Any]:
46
+ return tools.validate_schema(instance, schema)
47
+
48
+
49
+ @mcp.tool(description="Dimensional analysis (Pint). Evaluate a quantity expression like "
50
+ "'5 meter / second * 2 second'; optionally check it matches expected_unit.")
51
+ def check_units(expression: str, expected_unit: str | None = None) -> dict[str, Any]:
52
+ return tools.check_units(expression, expected_unit)
53
+
54
+
55
+ @mcp.tool(description="Test a regex against labelled cases "
56
+ "[{text, should_match}]; returns per-case pass/fail and capture groups.")
57
+ def test_regex(pattern: str, cases: list[dict[str, Any]], flags: str = "") -> dict[str, Any]:
58
+ return tools.test_regex(pattern, cases, flags)
59
+
60
+
61
+ def main() -> None:
62
+ parser = argparse.ArgumentParser(description="VerifierMCP server")
63
+ parser.add_argument("--http", action="store_true", help="serve streamable HTTP instead of stdio")
64
+ parser.add_argument("--host", default="0.0.0.0")
65
+ parser.add_argument("--port", type=int, default=8000)
66
+ args = parser.parse_args()
67
+
68
+ if args.http:
69
+ mcp.settings.host = args.host
70
+ mcp.settings.port = args.port
71
+ mcp.run(transport="streamable-http")
72
+ else:
73
+ mcp.run(transport="stdio")
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
@@ -0,0 +1,16 @@
1
+ """Pure verification functions, shared by the MCP server, the playground and the tests."""
2
+
3
+ from verifier_mcp.tools.code_tools import run_code
4
+ from verifier_mcp.tools.math_tools import verify_math
5
+ from verifier_mcp.tools.regex_tools import test_regex
6
+ from verifier_mcp.tools.schema_tools import validate_schema
7
+ from verifier_mcp.tools.units_tools import check_units, units_consistent
8
+
9
+ __all__ = [
10
+ "check_units",
11
+ "run_code",
12
+ "test_regex",
13
+ "units_consistent",
14
+ "validate_schema",
15
+ "verify_math",
16
+ ]
@@ -0,0 +1,71 @@
1
+ """Sandboxed Python execution.
2
+
3
+ Runs a snippet in a fresh, isolated subprocess (`python -I -S`) with CPU, memory and
4
+ output limits and no inherited environment, so an LLM can *run* code to check that it
5
+ does what it claims rather than hallucinating the output.
6
+
7
+ NOTE: this is a lightweight sandbox suitable for a dev tool. For untrusted multi-tenant
8
+ use, run it inside a container / gVisor / Firecracker — documented in the README.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ from typing import Any
17
+
18
+ _MAX_OUTPUT = 20_000 # chars
19
+
20
+
21
+ def _limits(cpu_seconds: int, mem_mb: int):
22
+ # Applied in the child before exec (POSIX only).
23
+ def _apply():
24
+ import resource
25
+
26
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds))
27
+ mem = mem_mb * 1024 * 1024
28
+ resource.setrlimit(resource.RLIMIT_AS, (mem, mem))
29
+ resource.setrlimit(resource.RLIMIT_NPROC, (0, 0)) # no forking
30
+ resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0)) # no file writes
31
+
32
+ return _apply
33
+
34
+
35
+ def run_code(code: str, stdin: str = "", timeout: float = 5.0) -> dict[str, Any]:
36
+ """Execute a Python snippet and capture its output.
37
+
38
+ Returns {ok, return_code, stdout, stderr, timed_out}. `ok` is True when the process
39
+ exits 0 within the limits.
40
+ """
41
+ preexec = _limits(int(timeout) + 1, 256) if sys.platform != "win32" else None
42
+ try:
43
+ with tempfile.TemporaryDirectory() as cwd:
44
+ proc = subprocess.run(
45
+ [sys.executable, "-I", "-S", "-c", code],
46
+ input=stdin,
47
+ capture_output=True,
48
+ text=True,
49
+ timeout=timeout,
50
+ cwd=cwd,
51
+ env={"PYTHONHASHSEED": "0"},
52
+ preexec_fn=preexec,
53
+ check=False,
54
+ )
55
+ return {
56
+ "ok": proc.returncode == 0,
57
+ "return_code": proc.returncode,
58
+ "stdout": proc.stdout[:_MAX_OUTPUT],
59
+ "stderr": proc.stderr[:_MAX_OUTPUT],
60
+ "timed_out": False,
61
+ }
62
+ except subprocess.TimeoutExpired as exc:
63
+ return {
64
+ "ok": False, "return_code": None, "timed_out": True,
65
+ "stdout": (exc.stdout or b"").decode("utf-8", "replace")[:_MAX_OUTPUT]
66
+ if isinstance(exc.stdout, bytes) else (exc.stdout or "")[:_MAX_OUTPUT],
67
+ "stderr": f"Timed out after {timeout}s",
68
+ }
69
+ except Exception as exc: # noqa: BLE001
70
+ return {"ok": False, "return_code": None, "timed_out": False,
71
+ "stdout": "", "stderr": f"{type(exc).__name__}: {exc}"}
@@ -0,0 +1,197 @@
1
+ """Symbolic math verification with SymPy.
2
+
3
+ Lets an LLM check algebra/calculus instead of trusting its own arithmetic:
4
+ is an equation actually an identity? Does a claimed result match? What does an
5
+ expression simplify or evaluate to?
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import atexit
12
+ import builtins
13
+ import concurrent.futures as cf
14
+ import multiprocessing as mp
15
+ import re
16
+ import threading
17
+ from typing import Any
18
+
19
+ import sympy as sp
20
+ from sympy.parsing.sympy_parser import parse_expr
21
+
22
+ _MAX_LEN = 2000
23
+ # Python builtins that SymPy does not re-export (eval, exec, open, getattr, ...) are blocked.
24
+ _BLOCKED_NAMES = {n for n in dir(builtins) if not hasattr(sp, n)}
25
+ _ALLOWED_NODES = (
26
+ ast.Expression, ast.BinOp, ast.UnaryOp, ast.Call, ast.Name, ast.Load, ast.Constant,
27
+ ast.Tuple, ast.keyword, ast.Compare, ast.operator, ast.unaryop, ast.cmpop,
28
+ )
29
+
30
+
31
+ def _check_safe(expr: str) -> None:
32
+ """Reject anything that is not a plain math expression.
33
+
34
+ SymPy's parse_expr ultimately calls eval(), so untrusted input must be screened first:
35
+ no attribute access, subscripts, lambdas, strings, dunder names or dangerous builtins.
36
+ """
37
+ if len(expr) > _MAX_LEN:
38
+ raise ValueError(f"expression longer than {_MAX_LEN} characters")
39
+ if "__" in expr:
40
+ raise ValueError("double underscores are not allowed")
41
+ # SymPy accepts `n!` (factorial); strip it so Python's parser can check the rest.
42
+ candidate = re.sub(r"!(?!=)", "", expr)
43
+ try:
44
+ tree = ast.parse(candidate.strip(), mode="eval")
45
+ except SyntaxError as exc:
46
+ raise ValueError(f"invalid expression: {exc.msg}") from None
47
+ for node in ast.walk(tree):
48
+ if not isinstance(node, _ALLOWED_NODES):
49
+ raise ValueError(f"disallowed syntax: {type(node).__name__}")
50
+ if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float, complex)):
51
+ raise ValueError("only numeric literals are allowed")
52
+ if isinstance(node, ast.Name) and (node.id.startswith("_") or node.id in _BLOCKED_NAMES):
53
+ raise ValueError(f"name not allowed: {node.id}")
54
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
55
+ exp = _const_value(node.right)
56
+ if exp is not None and abs(exp) > _MAX_EXPONENT:
57
+ raise ValueError(f"exponent larger than {_MAX_EXPONENT}")
58
+ if isinstance(node, ast.Call) and not isinstance(node.func, ast.Name):
59
+ raise ValueError("only direct function calls like sin(x) are allowed")
60
+
61
+
62
+ def _const_value(node: ast.AST) -> float | None:
63
+ """Cheaply estimate a purely numeric subtree (so `9**9**9` is caught before SymPy)."""
64
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
65
+ return float(node.value)
66
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
67
+ v = _const_value(node.operand)
68
+ return None if v is None else (-v if isinstance(node.op, ast.USub) else v)
69
+ if isinstance(node, ast.BinOp):
70
+ a, b = _const_value(node.left), _const_value(node.right)
71
+ if a is None or b is None:
72
+ return None
73
+ try:
74
+ if isinstance(node.op, ast.Add):
75
+ return a + b
76
+ if isinstance(node.op, ast.Sub):
77
+ return a - b
78
+ if isinstance(node.op, ast.Mult):
79
+ return a * b
80
+ if isinstance(node.op, ast.Pow):
81
+ return float("inf") if abs(b) > _MAX_EXPONENT else float(abs(a) ** b)
82
+ except (OverflowError, ZeroDivisionError, ValueError):
83
+ return float("inf")
84
+ return None
85
+
86
+
87
+ def _parse(expr: str):
88
+ _check_safe(expr)
89
+ # No implicit multiplication surprises; standard transformations only.
90
+ return parse_expr(expr, evaluate=True)
91
+
92
+
93
+ _TIMEOUT = 10.0
94
+ _MAX_EXPONENT = 10_000
95
+ _pool: cf.ProcessPoolExecutor | None = None
96
+ _pool_lock = threading.Lock()
97
+
98
+
99
+ def _get_pool() -> cf.ProcessPoolExecutor:
100
+ global _pool
101
+ with _pool_lock:
102
+ if _pool is None:
103
+ _pool = cf.ProcessPoolExecutor(max_workers=1, mp_context=mp.get_context("spawn"))
104
+ return _pool
105
+
106
+
107
+ def _reset_pool() -> None:
108
+ global _pool
109
+ with _pool_lock:
110
+ if _pool is not None:
111
+ for proc in list(getattr(_pool, "_processes", {}).values()):
112
+ proc.kill()
113
+ _pool.shutdown(wait=False, cancel_futures=True)
114
+ _pool = None
115
+
116
+
117
+ atexit.register(_reset_pool)
118
+
119
+
120
+ def verify_math(expression: str, claimed_result: str | None = None,
121
+ timeout: float = _TIMEOUT) -> dict[str, Any]:
122
+ """Verify a mathematical statement symbolically, with a hard time limit.
123
+
124
+ SymPy runs in a separate worker process so a pathological input (e.g. ``9**9**9``)
125
+ cannot hang the server: after `timeout` seconds the worker is killed and an error
126
+ is returned. See `_verify_math` for the semantics.
127
+ """
128
+ try:
129
+ parts = [expression] if claimed_result is not None else expression.split("=", 1)
130
+ for part in [*parts, *([claimed_result] if claimed_result else [])]:
131
+ _check_safe(part)
132
+ except ValueError as exc:
133
+ return {"verified": False, "error": f"ValueError: {exc}"}
134
+ try:
135
+ return _get_pool().submit(_verify_math, expression, claimed_result).result(timeout=timeout)
136
+ except cf.TimeoutError:
137
+ _reset_pool()
138
+ return {"verified": False, "error": f"Timed out after {timeout}s"}
139
+ except cf.process.BrokenProcessPool:
140
+ _reset_pool()
141
+ return {"verified": False, "error": "worker crashed (expression too large?)"}
142
+
143
+
144
+ def _verify_math(expression: str, claimed_result: str | None = None) -> dict[str, Any]:
145
+ """Verify a mathematical statement symbolically.
146
+
147
+ - If `expression` contains '=', check whether the two sides are equal (an identity).
148
+ - Else if `claimed_result` is given, check whether expression == claimed_result.
149
+ - Else just simplify/evaluate the expression.
150
+
151
+ Returns {verified, simplified, numeric, detail}. `verified` is None when there is
152
+ nothing to prove (plain simplification).
153
+ """
154
+ try:
155
+ if "=" in expression and claimed_result is None:
156
+ lhs_s, rhs_s = expression.split("=", 1)
157
+ lhs, rhs = _parse(lhs_s), _parse(rhs_s)
158
+ diff = sp.simplify(lhs - rhs)
159
+ verified = diff == 0
160
+ return {
161
+ "verified": bool(verified),
162
+ "simplified": str(sp.simplify(lhs)),
163
+ "numeric": _num(lhs if verified else diff),
164
+ "detail": "sides are equal" if verified
165
+ else f"not equal; lhs - rhs simplifies to {diff}",
166
+ }
167
+
168
+ expr = _parse(expression)
169
+ if claimed_result is not None:
170
+ claimed = _parse(claimed_result)
171
+ diff = sp.simplify(expr - claimed)
172
+ verified = diff == 0
173
+ return {
174
+ "verified": bool(verified),
175
+ "simplified": str(sp.simplify(expr)),
176
+ "numeric": _num(expr),
177
+ "detail": f"expression equals {claimed_result}" if verified
178
+ else f"expression simplifies to {sp.simplify(expr)}, not {claimed_result}",
179
+ }
180
+
181
+ simp = sp.simplify(expr)
182
+ return {
183
+ "verified": None,
184
+ "simplified": str(simp),
185
+ "numeric": _num(simp),
186
+ "detail": "simplified (nothing to verify)",
187
+ }
188
+ except Exception as exc: # noqa: BLE001 - report parse/eval errors to the caller
189
+ return {"verified": False, "error": f"{type(exc).__name__}: {exc}"}
190
+
191
+
192
+ def _num(expr) -> float | None:
193
+ try:
194
+ val = sp.N(expr)
195
+ return float(val) if val.is_number else None
196
+ except (TypeError, ValueError):
197
+ return None
@@ -0,0 +1,44 @@
1
+ """Regex verification.
2
+
3
+ An LLM proposes a regex; this runs it against labelled cases so the pattern is proven to
4
+ match what it should and reject what it shouldn't, with capture groups surfaced.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any
11
+
12
+
13
+ def test_regex(pattern: str, cases: list[dict[str, Any]], flags: str = "") -> dict[str, Any]:
14
+ """Test a regex against labelled cases.
15
+
16
+ Each case: {"text": str, "should_match": bool}. `flags` is any subset of "imsx".
17
+ Returns {all_passed, results:[{text, expected, matched, groups, passed}]}.
18
+ """
19
+ flag_val = 0
20
+ for ch in flags.lower():
21
+ flag_val |= {"i": re.I, "m": re.M, "s": re.S, "x": re.X}.get(ch, 0)
22
+
23
+ try:
24
+ rx = re.compile(pattern, flag_val)
25
+ except re.error as exc:
26
+ return {"all_passed": False, "error": f"invalid regex: {exc}"}
27
+
28
+ results = []
29
+ all_passed = True
30
+ for case in cases:
31
+ text = case.get("text", "")
32
+ expected = bool(case.get("should_match", True))
33
+ m = rx.search(text)
34
+ matched = m is not None
35
+ passed = matched == expected
36
+ all_passed = all_passed and passed
37
+ results.append({
38
+ "text": text,
39
+ "expected": expected,
40
+ "matched": matched,
41
+ "groups": list(m.groups()) if m else [],
42
+ "passed": passed,
43
+ })
44
+ return {"all_passed": all_passed, "results": results}
@@ -0,0 +1,41 @@
1
+ """JSON-Schema validation.
2
+
3
+ Lets an LLM confirm that structured output it produced actually conforms to a schema,
4
+ instead of asserting it does.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any
11
+
12
+ from jsonschema import Draft202012Validator
13
+
14
+
15
+ def _load(value: Any) -> Any:
16
+ return json.loads(value) if isinstance(value, str) else value
17
+
18
+
19
+ def validate_schema(instance: Any, schema: Any) -> dict[str, Any]:
20
+ """Validate a JSON instance against a JSON Schema (Draft 2020-12).
21
+
22
+ `instance` and `schema` may be JSON strings or already-parsed objects.
23
+ Returns {valid, errors:[{path, message}]}.
24
+ """
25
+ try:
26
+ inst = _load(instance)
27
+ sch = _load(schema)
28
+ except json.JSONDecodeError as exc:
29
+ return {"valid": False, "errors": [{"path": "", "message": f"invalid JSON: {exc}"}]}
30
+
31
+ try:
32
+ validator = Draft202012Validator(sch)
33
+ except Exception as exc: # noqa: BLE001 - malformed schema
34
+ return {"valid": False, "errors": [{"path": "", "message": f"invalid schema: {exc}"}]}
35
+
36
+ errors = []
37
+ for err in sorted(validator.iter_errors(inst), key=lambda e: list(e.path)):
38
+ path = "/".join(str(p) for p in err.path) or "(root)"
39
+ errors.append({"path": path, "message": err.message})
40
+
41
+ return {"valid": not errors, "errors": errors}
@@ -0,0 +1,60 @@
1
+ """Dimensional analysis with Pint.
2
+
3
+ Catches the classic LLM error of mixing units or producing a physically inconsistent
4
+ equation. Evaluate a quantity expression, or check that two sides share dimensions.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ import pint
12
+
13
+ _ureg = pint.UnitRegistry()
14
+
15
+
16
+ def check_units(expression: str, expected_unit: str | None = None) -> dict[str, Any]:
17
+ """Evaluate a quantity expression (e.g. '5 meter / second * 2 second').
18
+
19
+ Returns {ok, magnitude, units, dimensionality, matches_expected}. If `expected_unit`
20
+ is given, the result is converted to it and `matches_expected` reports compatibility.
21
+ """
22
+ try:
23
+ q = _ureg.parse_expression(expression)
24
+ except Exception as exc: # noqa: BLE001
25
+ return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
26
+
27
+ magnitude = getattr(q, "magnitude", q)
28
+ units = str(getattr(q, "units", "dimensionless"))
29
+ dim = str(getattr(q, "dimensionality", "dimensionless"))
30
+
31
+ result: dict[str, Any] = {
32
+ "ok": True,
33
+ "magnitude": float(magnitude) if isinstance(magnitude, (int, float)) else str(magnitude),
34
+ "units": units,
35
+ "dimensionality": dim,
36
+ }
37
+ if expected_unit is not None:
38
+ try:
39
+ converted = q.to(expected_unit)
40
+ result["matches_expected"] = True
41
+ result["as_expected"] = f"{converted:~P}"
42
+ except Exception as exc: # noqa: BLE001 - incompatible dimensions
43
+ result["matches_expected"] = False
44
+ result["detail"] = f"cannot convert to {expected_unit}: {exc}"
45
+ return result
46
+
47
+
48
+ def units_consistent(lhs: str, rhs: str) -> dict[str, Any]:
49
+ """Check whether both sides of an equation have the same dimensionality."""
50
+ try:
51
+ ql = _ureg.parse_expression(lhs)
52
+ qr = _ureg.parse_expression(rhs)
53
+ same = ql.dimensionality == qr.dimensionality
54
+ return {
55
+ "consistent": bool(same),
56
+ "lhs_dimensionality": str(ql.dimensionality),
57
+ "rhs_dimensionality": str(qr.dimensionality),
58
+ }
59
+ except Exception as exc: # noqa: BLE001
60
+ return {"consistent": False, "error": f"{type(exc).__name__}: {exc}"}
@@ -0,0 +1,150 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>VerifierMCP</title>
7
+ <style>
8
+ :root{
9
+ --bg:#0a0c11; --panel:#12161f; --panel2:#161b26; --line:#232b3a; --ink:#e8edf6;
10
+ --muted:#8793a8; --brand:#8b7dff; --ok:#54e39b; --bad:#ff7a85; --chip:#1b2130;
11
+ --shadow:0 10px 36px rgba(0,0,0,.45); --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
12
+ }
13
+ *{box-sizing:border-box}
14
+ body{margin:0;background:radial-gradient(1100px 600px at 75% -12%,#1a1740 0%,var(--bg) 55%);
15
+ color:var(--ink);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
16
+ min-height:100vh;padding:30px 18px 70px}
17
+ .wrap{max-width:1080px;margin:0 auto}
18
+ header{display:flex;align-items:center;gap:14px}
19
+ .logo{width:42px;height:42px;border-radius:12px;background:linear-gradient(135deg,var(--brand),#5a8bff);
20
+ display:grid;place-items:center;font-size:22px;box-shadow:var(--shadow)}
21
+ h1{font-size:26px;margin:0;letter-spacing:-.4px}
22
+ .sub{color:var(--muted);margin:10px 0 18px;max-width:680px}
23
+ .sub b{color:var(--ink);font-weight:600}
24
+ .connect{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 15px;
25
+ font:12.5px/1.6 var(--mono);color:var(--muted);margin-bottom:22px;overflow:auto}
26
+ .connect b{color:var(--brand)}
27
+ .grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
28
+ .card{background:var(--panel);border:1px solid var(--line);border-radius:16px;padding:16px 17px;box-shadow:var(--shadow)}
29
+ .card h3{margin:0 0 3px;font-size:15px;display:flex;align-items:center;gap:8px}
30
+ .tag{font:11px var(--mono);color:var(--brand);background:var(--chip);border:1px solid var(--line);
31
+ border-radius:6px;padding:1px 7px}
32
+ .card p{margin:0 0 11px;color:var(--muted);font-size:12.5px}
33
+ label{display:block;font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin:8px 0 4px}
34
+ textarea,input{width:100%;background:var(--panel2);border:1px solid var(--line);color:var(--ink);
35
+ border-radius:9px;padding:8px 10px;font:13px var(--mono);resize:vertical}
36
+ .row{display:flex;gap:9px} .row>div{flex:1}
37
+ button{margin-top:11px;background:linear-gradient(135deg,var(--brand),#5a8bff);color:#0a0a16;font-weight:700;
38
+ border:0;border-radius:9px;padding:9px 16px;font-size:13.5px;cursor:pointer}
39
+ button:hover{filter:brightness(1.08)}
40
+ .result{margin-top:11px;border-radius:10px;padding:10px 12px;font:12.5px/1.5 var(--mono);
41
+ white-space:pre-wrap;word-break:break-word;border:1px solid var(--line);background:#0d1119;display:none}
42
+ .result.show{display:block}
43
+ .verdict{display:inline-flex;align-items:center;gap:6px;font-weight:700;font-family:inherit;margin-bottom:6px}
44
+ .verdict.ok{color:var(--ok)} .verdict.bad{color:var(--bad)}
45
+ .foot{color:var(--muted);font-size:12.5px;margin-top:24px;text-align:center}
46
+ @media(max-width:820px){.grid{grid-template-columns:1fr}}
47
+ </style>
48
+ </head>
49
+ <body>
50
+ <div class="wrap">
51
+ <header>
52
+ <div class="logo">✓</div>
53
+ <div><h1>VerifierMCP</h1></div>
54
+ </header>
55
+ <p class="sub">An <b>MCP server</b> that gives any LLM the power to <b>check its own work</b>.
56
+ Five verification tools — symbolic math, sandboxed code, JSON-Schema, units, regex — callable
57
+ from Claude Desktop or any MCP client. This page runs the exact same tools so you can watch
58
+ them catch errors live.</p>
59
+
60
+ <div class="connect">
61
+ <span style="color:var(--ink)"># Connect to Claude Desktop (claude_desktop_config.json)</span><br>
62
+ "mcpServers": { "<b>verifier</b>": { "command": "python", "args": ["-m", "verifier_mcp.server"] } }
63
+ </div>
64
+
65
+ <div class="grid">
66
+ <div class="card" data-ep="verify_math">
67
+ <h3>verify_math <span class="tag">SymPy</span></h3>
68
+ <p>Catches the classic (x+1)² = x²+1 mistake — checks algebra symbolically.</p>
69
+ <label>Expression</label><textarea rows="1" data-f="expression">(x+1)**2</textarea>
70
+ <label>Claimed result</label><textarea rows="1" data-f="claimed_result">x**2 + 1</textarea>
71
+ <button>Verify</button>
72
+ <div class="result"></div>
73
+ </div>
74
+
75
+ <div class="card" data-ep="run_code">
76
+ <h3>run_code <span class="tag">sandbox</span></h3>
77
+ <p>Runs Python in an isolated subprocess and returns the real output.</p>
78
+ <label>Code</label><textarea rows="2" data-f="code">print(sum(range(101)))</textarea>
79
+ <button>Run &amp; verify</button>
80
+ <div class="result"></div>
81
+ </div>
82
+
83
+ <div class="card" data-ep="validate_schema">
84
+ <h3>validate_schema <span class="tag">JSON Schema</span></h3>
85
+ <p>Confirms structured output actually conforms — here <code>age</code> must be an integer.</p>
86
+ <label>Instance</label><textarea rows="2" data-f="instance">{"name": "Ada", "age": "forty"}</textarea>
87
+ <label>Schema</label><textarea rows="2" data-f="schema_json">{"type":"object","required":["age"],"properties":{"age":{"type":"integer"}}}</textarea>
88
+ <button>Validate</button>
89
+ <div class="result"></div>
90
+ </div>
91
+
92
+ <div class="card" data-ep="check_units">
93
+ <h3>check_units <span class="tag">Pint</span></h3>
94
+ <p>Dimensional analysis — evaluate a quantity and check it matches an expected unit.</p>
95
+ <div class="row">
96
+ <div><label>Expression</label><textarea rows="1" data-f="expression">5 meter / second * 2 second</textarea></div>
97
+ <div><label>Expected</label><textarea rows="1" data-f="expected_unit">meter</textarea></div>
98
+ </div>
99
+ <button>Check</button>
100
+ <div class="result"></div>
101
+ </div>
102
+
103
+ <div class="card" data-ep="test_regex" style="grid-column:1/-1">
104
+ <h3>test_regex <span class="tag">re</span></h3>
105
+ <p>Proves a regex matches what it should and rejects what it shouldn't, with capture groups.</p>
106
+ <div class="row">
107
+ <div><label>Pattern</label><textarea rows="1" data-f="pattern">^(\d{3})-(\d{4})$</textarea></div>
108
+ <div><label>Cases (JSON)</label><textarea rows="1" data-f="cases">[{"text":"123-4567","should_match":true},{"text":"12-4567","should_match":false}]</textarea></div>
109
+ </div>
110
+ <button>Test</button>
111
+ <div class="result"></div>
112
+ </div>
113
+ </div>
114
+
115
+ <div class="foot">Model Context Protocol · stdio + streamable HTTP · deployable via Amazon Bedrock AgentCore Gateway</div>
116
+ </div>
117
+
118
+ <script>
119
+ const JSON_FIELDS = {validate_schema:["instance","schema_json"], test_regex:["cases"]};
120
+ function verdict(ep, d){
121
+ if(ep==="verify_math") return d.verified===false ? ["bad","✗ claim is FALSE"] : d.verified===true ? ["ok","✓ verified"] : ["ok","simplified"];
122
+ if(ep==="run_code") return d.ok ? ["ok","✓ ran, exit 0"] : ["bad","✗ error / timeout"];
123
+ if(ep==="validate_schema") return d.valid ? ["ok","✓ valid"] : ["bad","✗ invalid"];
124
+ if(ep==="check_units") return d.ok===false ? ["bad","✗ error"] : (d.matches_expected===false ? ["bad","✗ wrong unit"] : ["ok","✓ ok"]);
125
+ if(ep==="test_regex") return d.all_passed ? ["ok","✓ all cases pass"] : ["bad","✗ some cases fail"];
126
+ return ["ok","done"];
127
+ }
128
+ async function run(card){
129
+ const ep = card.dataset.ep, body = {};
130
+ card.querySelectorAll("[data-f]").forEach(el=>{
131
+ let v = el.value;
132
+ if((JSON_FIELDS[ep]||[]).includes(el.dataset.f)){ try{ v = JSON.parse(v); }catch(e){} }
133
+ if(v!=="" ) body[el.dataset.f] = v;
134
+ });
135
+ const box = card.querySelector(".result");
136
+ try{
137
+ const r = await fetch("/api/"+ep,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});
138
+ const d = await r.json();
139
+ const [cls,label] = verdict(ep,d);
140
+ box.innerHTML = `<div class="verdict ${cls}">${label}</div>`+JSON.stringify(d,null,2);
141
+ box.classList.add("show");
142
+ }catch(e){ box.textContent = "⚠ "+e; box.classList.add("show"); }
143
+ }
144
+ document.querySelectorAll(".card").forEach(card=>{
145
+ card.querySelector("button").addEventListener("click",()=>run(card));
146
+ run(card); // auto-run the example on load
147
+ });
148
+ </script>
149
+ </body>
150
+ </html>
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.5
2
+ Name: verifier-mcp
3
+ Version: 0.1.0
4
+ Summary: An MCP server that lets any LLM check its own work: symbolic math, sandboxed code, JSON-Schema, units and regex verification.
5
+ Project-URL: Homepage, https://github.com/Arashomranpour/Verifier_MCP
6
+ Project-URL: Repository, https://github.com/Arashomranpour/Verifier_MCP
7
+ Project-URL: Issues, https://github.com/Arashomranpour/Verifier_MCP/issues
8
+ Author: Arash Omranpour
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: agents,jsonschema,llm,mcp,model-context-protocol,sympy,verification
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Testing
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: jsonschema>=4.20
24
+ Requires-Dist: mcp<2,>=1.9
25
+ Requires-Dist: pint>=0.23
26
+ Requires-Dist: sympy>=1.12
27
+ Provides-Extra: demo
28
+ Requires-Dist: langchain-groq>=0.2; extra == 'demo'
29
+ Requires-Dist: langchain-mcp-adapters>=0.1; extra == 'demo'
30
+ Requires-Dist: langgraph>=0.2; extra == 'demo'
31
+ Provides-Extra: dev
32
+ Requires-Dist: fastapi>=0.110; extra == 'dev'
33
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
34
+ Requires-Dist: pytest>=8; extra == 'dev'
35
+ Requires-Dist: ruff>=0.5; extra == 'dev'
36
+ Requires-Dist: uvicorn>=0.29; extra == 'dev'
37
+ Provides-Extra: web
38
+ Requires-Dist: fastapi>=0.110; extra == 'web'
39
+ Requires-Dist: uvicorn>=0.29; extra == 'web'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # VerifierMCP
43
+
44
+ <!-- mcp-name: io.github.Arashomranpour/verifier-mcp -->
45
+
46
+ > An **MCP server** that gives any LLM the power to **check its own work**.
47
+ > Instead of trusting a model's arithmetic, regex, JSON or "the code prints X", the model
48
+ > can *call a tool and verify it*. Five verification tools over the
49
+ > [Model Context Protocol](https://modelcontextprotocol.io): symbolic math, sandboxed code
50
+ > execution, JSON-Schema validation, dimensional analysis, and regex testing.
51
+
52
+ <p align="center">
53
+ <img src="https://raw.githubusercontent.com/Arashomranpour/Verifier_MCP/main/docs/images/playground.png" alt="VerifierMCP playground catching errors live" width="880">
54
+ </p>
55
+
56
+ Built with the official **MCP Python SDK** (FastMCP). Works in **Claude Desktop** and any
57
+ MCP client over **stdio**, or remotely over **streamable HTTP** (e.g. behind **Amazon Bedrock
58
+ AgentCore Gateway**).
59
+
60
+ ---
61
+
62
+ ## Why it matters
63
+
64
+ LLMs are confidently wrong about exactly the things that are *mechanically checkable*:
65
+ `(x+1)² = x²+1`, a regex that doesn't quite match, JSON that violates its schema, a unit
66
+ slip, "this function returns 5050". VerifierMCP turns each of those into a tool call, so an
67
+ agent can **replace an assertion with a verified fact**.
68
+
69
+ ## The tools
70
+
71
+ | Tool | Checks | Engine |
72
+ |------|--------|--------|
73
+ | `verify_math` | Is an equation an identity? Does a claimed result hold? | SymPy |
74
+ | `run_code` | What does this Python snippet *actually* output? | sandboxed subprocess |
75
+ | `validate_schema` | Does this JSON conform to its JSON Schema? | jsonschema (Draft 2020-12) |
76
+ | `check_units` | Is this quantity/equation dimensionally correct? | Pint |
77
+ | `test_regex` | Does this regex match/reject the right cases? | `re` |
78
+
79
+ Each tool body lives in [`src/verifier_mcp/tools/`](src/verifier_mcp/tools/) as a pure
80
+ function, so it is unit-tested without the protocol and reused by the web playground.
81
+
82
+ ---
83
+
84
+ ## Quickstart
85
+
86
+ ```bash
87
+ pip install verifier-mcp # or: pip install "verifier-mcp[web]" for the playground
88
+
89
+ # Run the MCP server over stdio (what Claude Desktop launches)
90
+ verifier-mcp
91
+
92
+ # Or serve it over HTTP (MCP streamable transport on :8000/mcp)
93
+ verifier-mcp --http
94
+
95
+ # See it in action — the visual playground (needs the [web] extra)
96
+ uvicorn verifier_mcp.playground:app --port 8080 # http://localhost:8080
97
+ ```
98
+
99
+ ### Connect to Claude Desktop
100
+
101
+ Add to `claude_desktop_config.json`:
102
+
103
+ ```json
104
+ {
105
+ "mcpServers": {
106
+ "verifier": {
107
+ "command": "uvx",
108
+ "args": ["verifier-mcp"]
109
+ }
110
+ }
111
+ }
112
+ ```
113
+
114
+ Restart Claude Desktop and ask it something like *"Is (x+1)² equal to x²+1? Use the verifier."*
115
+ — it will call `verify_math` and come back with the checked answer.
116
+
117
+ ---
118
+
119
+ ## Self-checking agent demo (Groq + MCP)
120
+
121
+ [`examples/self_checking_agent.py`](examples/self_checking_agent.py) connects a **Groq** LLM to
122
+ this server over **real MCP** (via `langchain-mcp-adapters`), instructs it to *verify before
123
+ asserting*, and watches it catch its own mistake:
124
+
125
+ ```bash
126
+ pip install -r requirements-demo.txt
127
+ export GROQ_API_KEY=gsk_... # real Groq agent
128
+ python examples/self_checking_agent.py
129
+
130
+ python examples/self_checking_agent.py --offline # no key: scripted LLM, REAL MCP verification
131
+ ```
132
+
133
+ ```text
134
+ [offline] Question: Is (x+1)^2 equal to x^2 + 1? If not, what is the correct expansion?
135
+
136
+ [Assistant] draft answer: "(x+1)^2 = x**2 + 1"
137
+ → verify_math((x+1)**2, claimed_result=x**2 + 1) [real MCP call]
138
+ MCP result: verified=False — expression simplifies to (x + 1)**2, not x**2 + 1
139
+ → verify_math((x+1)**2, claimed_result=x**2 + 2*x + 1) [real MCP call]
140
+ MCP result: verified=True
141
+
142
+ [Assistant] Corrected: (x+1)^2 = x^2 + 2x + 1 — verified, not x^2 + 1.
143
+ ```
144
+
145
+ ---
146
+
147
+ ## Deploy remotely (Amazon Bedrock AgentCore Gateway)
148
+
149
+ The HTTP transport (`--http`, container in [`Dockerfile`](Dockerfile)) exposes a standard MCP
150
+ endpoint at `/mcp`. Point **AgentCore Gateway** at it to turn these verifiers into tools any
151
+ Bedrock agent can call:
152
+
153
+ ```bash
154
+ docker build -t verifier-mcp .
155
+ docker run -p 8000:8000 verifier-mcp # MCP over HTTP at http://localhost:8000/mcp
156
+ ```
157
+
158
+ ---
159
+
160
+ ## The sandbox
161
+
162
+ `run_code` executes snippets in a fresh `python -I -S` subprocess with **no inherited
163
+ environment**, a **temp working dir**, and POSIX **resource limits** (CPU, memory, no forking,
164
+ no file writes) plus a wall-clock timeout. That is appropriate for a local dev tool. For
165
+ untrusted, multi-tenant use, run the whole server inside a container / gVisor / Firecracker —
166
+ the subprocess limits are defense-in-depth, not a complete jail. On **Windows** the
167
+ CPU/memory/fork limits are not applied (only the timeout), so prefer running it in a container there.
168
+
169
+ ---
170
+
171
+ ## Tests
172
+
173
+ ```bash
174
+ pip install -e ".[dev]"
175
+ pytest -q # all pass — tool logic + MCP protocol registration/dispatch
176
+ ```
177
+
178
+ ## Tech stack
179
+
180
+ **Model Context Protocol** (FastMCP) · **SymPy** · **jsonschema** · **Pint** · **FastAPI** ·
181
+ **Docker** · **GitHub Actions** · Amazon Bedrock AgentCore Gateway–ready
182
+
183
+ ## License
184
+
185
+ MIT © Arash Omranpour
@@ -0,0 +1,15 @@
1
+ verifier_mcp/__init__.py,sha256=6jXFvhF3Bm-Jk3zzAujyfvVOkS7wrKviLPBE1Btq7IA,97
2
+ verifier_mcp/playground.py,sha256=HiA0PzES-IyHUHRFJljHQQnprURmqnCZVvgI0LB2mz0,2105
3
+ verifier_mcp/server.py,sha256=WhU4ICAUP96K9hntdpqpiN6p7e6iBNMGUPpI7IVYzl4,2975
4
+ verifier_mcp/tools/__init__.py,sha256=eDT43m__natsRTAaP3MCooqCwtI3XAtvHIKQbNhh0rY,518
5
+ verifier_mcp/tools/code_tools.py,sha256=AHQPCthgAa3BeaL93kaQwcqZfPLosI2pNsdLcJcXwnI,2616
6
+ verifier_mcp/tools/math_tools.py,sha256=Pi6DpgbcUNEtybF6IFO_WpRg8J2Mrhf6ba7WNLHuaDE,7735
7
+ verifier_mcp/tools/regex_tools.py,sha256=B0Eijkr1yYKe8CZ8PJ4z9VLrfcHAaB_RtapV24cg7OA,1419
8
+ verifier_mcp/tools/schema_tools.py,sha256=JxEOW0Ui1GaBBEEd0VWz07o1duo_TDuDTA6XreMDSZ0,1323
9
+ verifier_mcp/tools/units_tools.py,sha256=MLvCIkI8Yc2WFy6yVE4Xzhhrcrj_hidKgqrtIc-8VEA,2201
10
+ verifier_mcp/web/index.html,sha256=aYnupFgr74XLdC7jgHycAjP4lY_ZaB_D8ZWYCy_rxhg,8043
11
+ verifier_mcp-0.1.0.dist-info/METADATA,sha256=pU-3Eydqw-Q6cAs_yplhH7AXVEWKF9rPNWr5d0c7jr8,6826
12
+ verifier_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ verifier_mcp-0.1.0.dist-info/entry_points.txt,sha256=xLxt__OIK8IIeF9LPvZFoGozy0IIYU4TKWyG7f7zdEc,58
14
+ verifier_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=L-kECwSIXz9rCfEeEQQ66MJYDxOJ9Iv6AYSJPzKb-eg,1072
15
+ verifier_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ verifier-mcp = verifier_mcp.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arash Omranpour
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.