docprov-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.
- docprov_mcp/__init__.py +22 -0
- docprov_mcp/cli.py +232 -0
- docprov_mcp/loader.py +160 -0
- docprov_mcp/models.py +116 -0
- docprov_mcp/server.py +119 -0
- docprov_mcp/verifier.py +599 -0
- docprov_mcp-0.1.0.dist-info/METADATA +202 -0
- docprov_mcp-0.1.0.dist-info/RECORD +11 -0
- docprov_mcp-0.1.0.dist-info/WHEEL +4 -0
- docprov_mcp-0.1.0.dist-info/entry_points.txt +3 -0
- docprov_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
docprov_mcp/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""docprov-mcp: Deterministic citation provenance verification for PDF & Markdown."""
|
|
2
|
+
|
|
3
|
+
from docprov_mcp.loader import load_document
|
|
4
|
+
from docprov_mcp.verifier import (
|
|
5
|
+
audit_citations,
|
|
6
|
+
extract_pages,
|
|
7
|
+
format_report_markdown,
|
|
8
|
+
search_document,
|
|
9
|
+
verify_citation,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"__version__",
|
|
16
|
+
"load_document",
|
|
17
|
+
"extract_pages",
|
|
18
|
+
"search_document",
|
|
19
|
+
"verify_citation",
|
|
20
|
+
"audit_citations",
|
|
21
|
+
"format_report_markdown",
|
|
22
|
+
]
|
docprov_mcp/cli.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Command-line interface for docprov-mcp."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from docprov_mcp import __version__
|
|
12
|
+
from docprov_mcp.loader import load_document
|
|
13
|
+
from docprov_mcp.verifier import (
|
|
14
|
+
audit_citations,
|
|
15
|
+
extract_pages,
|
|
16
|
+
format_report_markdown,
|
|
17
|
+
search_document,
|
|
18
|
+
verify_citation,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _parse_page_range(raw: str) -> tuple[int, int]:
|
|
23
|
+
text = raw.strip()
|
|
24
|
+
if "-" in text:
|
|
25
|
+
parts = text.split("-", 1)
|
|
26
|
+
start = int(parts[0].strip())
|
|
27
|
+
end = int(parts[1].strip())
|
|
28
|
+
return start, end
|
|
29
|
+
page = int(text)
|
|
30
|
+
return page, page
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _print_json(data: Any) -> None:
|
|
34
|
+
print(json.dumps(data, indent=2, ensure_ascii=False))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
38
|
+
parser = argparse.ArgumentParser(
|
|
39
|
+
prog="docprov",
|
|
40
|
+
description="Deterministic PDF & Markdown citation provenance verification CLI.",
|
|
41
|
+
)
|
|
42
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
43
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
44
|
+
|
|
45
|
+
# inspect
|
|
46
|
+
p_inspect = subparsers.add_parser("inspect", help="Inspect document metadata and pages.")
|
|
47
|
+
p_inspect.add_argument("path", help="Path to PDF, Markdown, or text file.")
|
|
48
|
+
p_inspect.add_argument("--json", action="store_true", help="Output JSON.")
|
|
49
|
+
|
|
50
|
+
# extract
|
|
51
|
+
p_extract = subparsers.add_parser("extract", help="Extract text for page or page range.")
|
|
52
|
+
p_extract.add_argument("path", help="Path to document.")
|
|
53
|
+
p_extract.add_argument(
|
|
54
|
+
"--pages",
|
|
55
|
+
required=True,
|
|
56
|
+
help="1-based page number or inclusive range (e.g., 3 or 2-5).",
|
|
57
|
+
)
|
|
58
|
+
p_extract.add_argument("--json", action="store_true", help="Output JSON.")
|
|
59
|
+
|
|
60
|
+
# search
|
|
61
|
+
p_search = subparsers.add_parser("search", help="Search document for matching pages.")
|
|
62
|
+
p_search.add_argument("path", help="Path to document.")
|
|
63
|
+
p_search.add_argument("query", help="Search query string.")
|
|
64
|
+
p_search.add_argument("--top-k", type=int, default=5, help="Maximum matches to return.")
|
|
65
|
+
p_search.add_argument("--json", action="store_true", help="Output JSON.")
|
|
66
|
+
|
|
67
|
+
# verify
|
|
68
|
+
p_verify = subparsers.add_parser("verify", help="Verify a single claim and optional page.")
|
|
69
|
+
p_verify.add_argument("path", help="Path to document.")
|
|
70
|
+
p_verify.add_argument("--claim", required=True, help="Claim text to verify.")
|
|
71
|
+
p_verify.add_argument("--page", type=int, default=None, help="Cited 1-based page number.")
|
|
72
|
+
p_verify.add_argument(
|
|
73
|
+
"--min-confidence",
|
|
74
|
+
type=float,
|
|
75
|
+
default=0.65,
|
|
76
|
+
help="Minimum confidence threshold (default: 0.65).",
|
|
77
|
+
)
|
|
78
|
+
p_verify.add_argument("--json", action="store_true", help="Output JSON.")
|
|
79
|
+
|
|
80
|
+
# audit
|
|
81
|
+
p_audit = subparsers.add_parser("audit", help="Audit a JSON file of citations.")
|
|
82
|
+
p_audit.add_argument("path", help="Path to document.")
|
|
83
|
+
p_audit.add_argument(
|
|
84
|
+
"--citations",
|
|
85
|
+
required=True,
|
|
86
|
+
help="Path to JSON file containing a list of {'claim', 'cited_page'} items.",
|
|
87
|
+
)
|
|
88
|
+
p_audit.add_argument(
|
|
89
|
+
"--min-confidence",
|
|
90
|
+
type=float,
|
|
91
|
+
default=0.65,
|
|
92
|
+
help="Minimum confidence threshold (default: 0.65).",
|
|
93
|
+
)
|
|
94
|
+
p_audit.add_argument(
|
|
95
|
+
"--format",
|
|
96
|
+
choices=["markdown", "json"],
|
|
97
|
+
default="markdown",
|
|
98
|
+
help="Output format (default: markdown).",
|
|
99
|
+
)
|
|
100
|
+
p_audit.add_argument(
|
|
101
|
+
"--strict",
|
|
102
|
+
action="store_true",
|
|
103
|
+
help="Exit with code 2 if any citation is not verified.",
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# serve
|
|
107
|
+
subparsers.add_parser("serve", help="Run the docprov-mcp stdio MCP server.")
|
|
108
|
+
|
|
109
|
+
return parser
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main(argv: list[str] | None = None) -> int:
|
|
113
|
+
"""Entry point for the `docprov` CLI."""
|
|
114
|
+
parser = _build_parser()
|
|
115
|
+
args = parser.parse_args(argv)
|
|
116
|
+
|
|
117
|
+
if args.command == "serve":
|
|
118
|
+
from docprov_mcp.server import main as serve_main
|
|
119
|
+
|
|
120
|
+
serve_main()
|
|
121
|
+
return 0
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
if args.command == "inspect":
|
|
125
|
+
index = load_document(args.path)
|
|
126
|
+
if args.json:
|
|
127
|
+
_print_json(index.to_dict(include_text=False))
|
|
128
|
+
else:
|
|
129
|
+
print(f"File: {index.source_path}")
|
|
130
|
+
print(f"Type: {index.file_type} | Pages: {index.total_pages}")
|
|
131
|
+
print(f"SHA-256: {index.sha256}")
|
|
132
|
+
for p in index.pages:
|
|
133
|
+
printed = f" (printed={p.printed_page})" if p.printed_page else ""
|
|
134
|
+
print(f" - Page {p.pdf_page}{printed}: {p.char_count} chars")
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
if args.command == "extract":
|
|
138
|
+
index = load_document(args.path)
|
|
139
|
+
start_page, end_page = _parse_page_range(args.pages)
|
|
140
|
+
pages = extract_pages(index, start_page=start_page, end_page=end_page)
|
|
141
|
+
if args.json:
|
|
142
|
+
_print_json(
|
|
143
|
+
{
|
|
144
|
+
"source_path": index.source_path,
|
|
145
|
+
"sha256": index.sha256,
|
|
146
|
+
"pages": [p.to_dict() for p in pages],
|
|
147
|
+
}
|
|
148
|
+
)
|
|
149
|
+
else:
|
|
150
|
+
for p in pages:
|
|
151
|
+
printed = f" (printed={p.printed_page})" if p.printed_page else ""
|
|
152
|
+
print(f"=== Page {p.pdf_page}{printed} ===")
|
|
153
|
+
print(p.text)
|
|
154
|
+
print()
|
|
155
|
+
return 0
|
|
156
|
+
|
|
157
|
+
if args.command == "search":
|
|
158
|
+
index = load_document(args.path)
|
|
159
|
+
matches = search_document(index, query=args.query, top_k=args.top_k)
|
|
160
|
+
if args.json:
|
|
161
|
+
_print_json(
|
|
162
|
+
{
|
|
163
|
+
"source_path": index.source_path,
|
|
164
|
+
"query": args.query,
|
|
165
|
+
"matches": [m.to_dict() for m in matches],
|
|
166
|
+
}
|
|
167
|
+
)
|
|
168
|
+
else:
|
|
169
|
+
if not matches:
|
|
170
|
+
print("No matches found.")
|
|
171
|
+
for m in matches:
|
|
172
|
+
printed = f" (printed={m.printed_page})" if m.printed_page else ""
|
|
173
|
+
print(
|
|
174
|
+
f"[Page {m.pdf_page}{printed}] score={m.score:.4f} terms={m.matched_terms}"
|
|
175
|
+
)
|
|
176
|
+
print(f" {m.snippet}")
|
|
177
|
+
return 0
|
|
178
|
+
|
|
179
|
+
if args.command == "verify":
|
|
180
|
+
index = load_document(args.path)
|
|
181
|
+
res = verify_citation(
|
|
182
|
+
index,
|
|
183
|
+
claim=args.claim,
|
|
184
|
+
cited_page=args.page,
|
|
185
|
+
min_confidence=args.min_confidence,
|
|
186
|
+
)
|
|
187
|
+
if args.json:
|
|
188
|
+
_print_json(res.to_dict())
|
|
189
|
+
else:
|
|
190
|
+
print(f"Status: {res.status} (confidence={res.confidence:.2f})")
|
|
191
|
+
print(f"Reason: {res.reason}")
|
|
192
|
+
if res.matched_page is not None:
|
|
193
|
+
print(f"Matched Page: {res.matched_page}")
|
|
194
|
+
if res.missing_numbers:
|
|
195
|
+
print(f"Missing Numbers: {', '.join(res.missing_numbers)}")
|
|
196
|
+
if res.evidence_snippet:
|
|
197
|
+
print(f"Evidence: {res.evidence_snippet}")
|
|
198
|
+
return 0 if res.status == "verified" else 2
|
|
199
|
+
|
|
200
|
+
if args.command == "audit":
|
|
201
|
+
index = load_document(args.path)
|
|
202
|
+
citations_path = Path(args.citations)
|
|
203
|
+
raw_data = json.loads(citations_path.read_text(encoding="utf-8"))
|
|
204
|
+
if isinstance(raw_data, dict) and "citations" in raw_data:
|
|
205
|
+
citations_list = raw_data["citations"]
|
|
206
|
+
elif isinstance(raw_data, list):
|
|
207
|
+
citations_list = raw_data
|
|
208
|
+
else:
|
|
209
|
+
raise ValueError(
|
|
210
|
+
"Citations JSON must be a list or an object containing a 'citations' list."
|
|
211
|
+
)
|
|
212
|
+
report = audit_citations(
|
|
213
|
+
index,
|
|
214
|
+
citations=citations_list,
|
|
215
|
+
min_confidence=args.min_confidence,
|
|
216
|
+
)
|
|
217
|
+
if args.format == "json":
|
|
218
|
+
_print_json(report.to_dict())
|
|
219
|
+
else:
|
|
220
|
+
print(format_report_markdown(report))
|
|
221
|
+
if args.strict and report.verified_count < report.total_claims:
|
|
222
|
+
return 2
|
|
223
|
+
return 0
|
|
224
|
+
except (FileNotFoundError, ValueError, json.JSONDecodeError) as exc:
|
|
225
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
226
|
+
return 1
|
|
227
|
+
|
|
228
|
+
return 1
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
if __name__ == "__main__":
|
|
232
|
+
raise SystemExit(main())
|
docprov_mcp/loader.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Document loaders for PDF, Markdown, and plain text sources."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from pypdf import PdfReader
|
|
10
|
+
|
|
11
|
+
from docprov_mcp.models import DocumentIndex, PageRecord
|
|
12
|
+
|
|
13
|
+
SUPPORTED_EXTENSIONS = {".pdf", ".md", ".markdown", ".txt"}
|
|
14
|
+
|
|
15
|
+
_PAGE_HEADER_FOOTER_RE = re.compile(
|
|
16
|
+
r"^(?:page|halaman|p\.?)\s+([0-9]+|[ivxlcdm]+)$|^[-–|]\s*([0-9]+)\s*[-–|]$|^([0-9]{1,4})$",
|
|
17
|
+
re.IGNORECASE,
|
|
18
|
+
)
|
|
19
|
+
_MD_PAGE_COMMENT_RE = re.compile(r"<!--\s*page:\s*([^\s>]+)\s*-->", re.IGNORECASE)
|
|
20
|
+
_FRONTMATTER_RE = re.compile(r"\A---\r?\n.*?\r?\n---\r?\n", re.DOTALL)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _detect_printed_page(text: str) -> str | None:
|
|
24
|
+
"""Heuristically extract a printed page label from the first or last lines of a page."""
|
|
25
|
+
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
|
26
|
+
if not lines:
|
|
27
|
+
return None
|
|
28
|
+
candidates = [lines[0]]
|
|
29
|
+
if len(lines) > 1:
|
|
30
|
+
candidates.append(lines[-1])
|
|
31
|
+
for candidate in candidates:
|
|
32
|
+
match = _PAGE_HEADER_FOOTER_RE.match(candidate)
|
|
33
|
+
if match:
|
|
34
|
+
for group in match.groups():
|
|
35
|
+
if group:
|
|
36
|
+
return group.strip()
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _load_pdf(path: Path, sha256: str) -> DocumentIndex:
|
|
41
|
+
reader = PdfReader(str(path))
|
|
42
|
+
has_explicit_labels = False
|
|
43
|
+
labels: list[str] = []
|
|
44
|
+
try:
|
|
45
|
+
root = reader.trailer.get("/Root", {})
|
|
46
|
+
if hasattr(root, "get_object"):
|
|
47
|
+
root = root.get_object()
|
|
48
|
+
has_explicit_labels = "/PageLabels" in root
|
|
49
|
+
labels = list(reader.page_labels)
|
|
50
|
+
except Exception:
|
|
51
|
+
has_explicit_labels = False
|
|
52
|
+
labels = []
|
|
53
|
+
|
|
54
|
+
pages: list[PageRecord] = []
|
|
55
|
+
for idx, page in enumerate(reader.pages, start=1):
|
|
56
|
+
raw_text = page.extract_text() or ""
|
|
57
|
+
text = raw_text.replace("\r\n", "\n").strip()
|
|
58
|
+
printed_page: str | None = None
|
|
59
|
+
if has_explicit_labels and idx - 1 < len(labels):
|
|
60
|
+
printed_page = str(labels[idx - 1]).strip() or None
|
|
61
|
+
if printed_page is None:
|
|
62
|
+
printed_page = _detect_printed_page(text)
|
|
63
|
+
pages.append(
|
|
64
|
+
PageRecord(
|
|
65
|
+
pdf_page=idx,
|
|
66
|
+
printed_page=printed_page,
|
|
67
|
+
text=text,
|
|
68
|
+
char_count=len(text),
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
return DocumentIndex(
|
|
73
|
+
source_path=str(path.resolve()),
|
|
74
|
+
sha256=sha256,
|
|
75
|
+
file_type="pdf",
|
|
76
|
+
total_pages=len(pages),
|
|
77
|
+
pages=pages,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _split_text_pages(raw_text: str) -> list[tuple[str | None, str]]:
|
|
82
|
+
normalized = raw_text.replace("\r\n", "\n")
|
|
83
|
+
|
|
84
|
+
if "\f" in normalized:
|
|
85
|
+
chunks = normalized.split("\f")
|
|
86
|
+
result: list[tuple[str | None, str]] = []
|
|
87
|
+
for chunk in chunks:
|
|
88
|
+
cleaned = chunk.strip()
|
|
89
|
+
if not cleaned:
|
|
90
|
+
continue
|
|
91
|
+
marker = _MD_PAGE_COMMENT_RE.search(cleaned)
|
|
92
|
+
printed = marker.group(1).strip() if marker else _detect_printed_page(cleaned)
|
|
93
|
+
body = _MD_PAGE_COMMENT_RE.sub("", cleaned).strip()
|
|
94
|
+
result.append((printed, body))
|
|
95
|
+
return result or [(None, "")]
|
|
96
|
+
|
|
97
|
+
markers = list(_MD_PAGE_COMMENT_RE.finditer(normalized))
|
|
98
|
+
if markers:
|
|
99
|
+
pages: list[tuple[str | None, str]] = []
|
|
100
|
+
prefix = normalized[: markers[0].start()].strip()
|
|
101
|
+
if prefix:
|
|
102
|
+
pages.append((_detect_printed_page(prefix), prefix))
|
|
103
|
+
for i, match in enumerate(markers):
|
|
104
|
+
start = match.end()
|
|
105
|
+
end = markers[i + 1].start() if i + 1 < len(markers) else len(normalized)
|
|
106
|
+
section = normalized[start:end].strip()
|
|
107
|
+
pages.append((match.group(1).strip(), section))
|
|
108
|
+
return pages
|
|
109
|
+
|
|
110
|
+
body_without_fm = normalized
|
|
111
|
+
fm_match = _FRONTMATTER_RE.match(normalized)
|
|
112
|
+
if fm_match:
|
|
113
|
+
body_without_fm = normalized[fm_match.end() :]
|
|
114
|
+
|
|
115
|
+
hr_chunks = re.split(r"\n-{3,}\n", body_without_fm)
|
|
116
|
+
non_empty_hr = [c.strip() for c in hr_chunks if c.strip()]
|
|
117
|
+
if len(non_empty_hr) > 1:
|
|
118
|
+
return [(_detect_printed_page(c), c) for c in non_empty_hr]
|
|
119
|
+
|
|
120
|
+
whole = normalized.strip()
|
|
121
|
+
return [(_detect_printed_page(whole), whole)]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _load_text_document(path: Path, sha256: str, file_type: str) -> DocumentIndex:
|
|
125
|
+
raw_text = path.read_text(encoding="utf-8-sig", errors="replace").lstrip("\ufeff")
|
|
126
|
+
parsed_pages = _split_text_pages(raw_text)
|
|
127
|
+
pages = [
|
|
128
|
+
PageRecord(
|
|
129
|
+
pdf_page=idx,
|
|
130
|
+
printed_page=printed,
|
|
131
|
+
text=text,
|
|
132
|
+
char_count=len(text),
|
|
133
|
+
)
|
|
134
|
+
for idx, (printed, text) in enumerate(parsed_pages, start=1)
|
|
135
|
+
]
|
|
136
|
+
return DocumentIndex(
|
|
137
|
+
source_path=str(path.resolve()),
|
|
138
|
+
sha256=sha256,
|
|
139
|
+
file_type=file_type,
|
|
140
|
+
total_pages=len(pages),
|
|
141
|
+
pages=pages,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def load_document(path: str | Path) -> DocumentIndex:
|
|
146
|
+
"""Load and index a PDF, Markdown, or plain text document by page/section."""
|
|
147
|
+
doc_path = Path(path)
|
|
148
|
+
if not doc_path.exists() or not doc_path.is_file():
|
|
149
|
+
raise FileNotFoundError(f"Document not found: {doc_path}")
|
|
150
|
+
|
|
151
|
+
suffix = doc_path.suffix.lower()
|
|
152
|
+
if suffix not in SUPPORTED_EXTENSIONS:
|
|
153
|
+
supported = ", ".join(sorted(SUPPORTED_EXTENSIONS))
|
|
154
|
+
raise ValueError(f"Unsupported file extension '{suffix}'. Supported: {supported}")
|
|
155
|
+
|
|
156
|
+
sha256 = hashlib.sha256(doc_path.read_bytes()).hexdigest()
|
|
157
|
+
if suffix == ".pdf":
|
|
158
|
+
return _load_pdf(doc_path, sha256)
|
|
159
|
+
file_type = "markdown" if suffix in {".md", ".markdown"} else "text"
|
|
160
|
+
return _load_text_document(doc_path, sha256, file_type)
|
docprov_mcp/models.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Data models for document provenance indexing and citation verification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class PageRecord:
|
|
11
|
+
"""Extracted text and page metadata for a single page or section."""
|
|
12
|
+
|
|
13
|
+
pdf_page: int
|
|
14
|
+
printed_page: str | None
|
|
15
|
+
text: str
|
|
16
|
+
char_count: int
|
|
17
|
+
|
|
18
|
+
def to_dict(self) -> dict[str, Any]:
|
|
19
|
+
"""Serialize the page record to a plain dictionary."""
|
|
20
|
+
return asdict(self)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class DocumentIndex:
|
|
25
|
+
"""In-memory indexed representation of a loaded source document."""
|
|
26
|
+
|
|
27
|
+
source_path: str
|
|
28
|
+
sha256: str
|
|
29
|
+
file_type: str
|
|
30
|
+
total_pages: int
|
|
31
|
+
pages: list[PageRecord]
|
|
32
|
+
|
|
33
|
+
def to_dict(self, include_text: bool = False) -> dict[str, Any]:
|
|
34
|
+
"""Serialize document metadata (and optionally page texts) to a dictionary."""
|
|
35
|
+
pages_data = [
|
|
36
|
+
p.to_dict()
|
|
37
|
+
if include_text
|
|
38
|
+
else {
|
|
39
|
+
"pdf_page": p.pdf_page,
|
|
40
|
+
"printed_page": p.printed_page,
|
|
41
|
+
"char_count": p.char_count,
|
|
42
|
+
}
|
|
43
|
+
for p in self.pages
|
|
44
|
+
]
|
|
45
|
+
return {
|
|
46
|
+
"source_path": self.source_path,
|
|
47
|
+
"sha256": self.sha256,
|
|
48
|
+
"file_type": self.file_type,
|
|
49
|
+
"total_pages": self.total_pages,
|
|
50
|
+
"pages": pages_data,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class SearchMatch:
|
|
56
|
+
"""Ranked search match inside a source document."""
|
|
57
|
+
|
|
58
|
+
pdf_page: int
|
|
59
|
+
printed_page: str | None
|
|
60
|
+
score: float
|
|
61
|
+
snippet: str
|
|
62
|
+
matched_terms: list[str]
|
|
63
|
+
char_start: int
|
|
64
|
+
char_end: int
|
|
65
|
+
|
|
66
|
+
def to_dict(self) -> dict[str, Any]:
|
|
67
|
+
"""Serialize the search match to a plain dictionary."""
|
|
68
|
+
return asdict(self)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class CitationVerification:
|
|
73
|
+
"""Verification verdict for a single claim against a source document."""
|
|
74
|
+
|
|
75
|
+
claim: str
|
|
76
|
+
cited_page: int | None
|
|
77
|
+
status: str
|
|
78
|
+
confidence: float
|
|
79
|
+
matched_page: int | None
|
|
80
|
+
printed_page: str | None
|
|
81
|
+
evidence_snippet: str | None
|
|
82
|
+
missing_numbers: list[str]
|
|
83
|
+
reason: str
|
|
84
|
+
|
|
85
|
+
def to_dict(self) -> dict[str, Any]:
|
|
86
|
+
"""Serialize the verification result to a plain dictionary."""
|
|
87
|
+
return asdict(self)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class ProvenanceReport:
|
|
92
|
+
"""Aggregated audit report across a batch of claims and page citations."""
|
|
93
|
+
|
|
94
|
+
source_path: str
|
|
95
|
+
sha256: str
|
|
96
|
+
total_claims: int
|
|
97
|
+
verified_count: int
|
|
98
|
+
page_mismatch_count: int
|
|
99
|
+
partial_count: int
|
|
100
|
+
not_found_count: int
|
|
101
|
+
pass_rate: float
|
|
102
|
+
results: list[CitationVerification]
|
|
103
|
+
|
|
104
|
+
def to_dict(self) -> dict[str, Any]:
|
|
105
|
+
"""Serialize the provenance report to a plain dictionary."""
|
|
106
|
+
return {
|
|
107
|
+
"source_path": self.source_path,
|
|
108
|
+
"sha256": self.sha256,
|
|
109
|
+
"total_claims": self.total_claims,
|
|
110
|
+
"verified_count": self.verified_count,
|
|
111
|
+
"page_mismatch_count": self.page_mismatch_count,
|
|
112
|
+
"partial_count": self.partial_count,
|
|
113
|
+
"not_found_count": self.not_found_count,
|
|
114
|
+
"pass_rate": self.pass_rate,
|
|
115
|
+
"results": [r.to_dict() for r in self.results],
|
|
116
|
+
}
|
docprov_mcp/server.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""MCP server exposing deterministic document provenance and citation tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from mcp.server.mcpserver import MCPServer
|
|
9
|
+
except ImportError: # pragma: no cover - fallback for mcp 1.x
|
|
10
|
+
from mcp.server.fastmcp import FastMCP as MCPServer
|
|
11
|
+
|
|
12
|
+
from docprov_mcp.loader import load_document
|
|
13
|
+
from docprov_mcp.verifier import (
|
|
14
|
+
audit_citations as run_audit_citations,
|
|
15
|
+
)
|
|
16
|
+
from docprov_mcp.verifier import (
|
|
17
|
+
extract_pages as run_extract_pages,
|
|
18
|
+
)
|
|
19
|
+
from docprov_mcp.verifier import (
|
|
20
|
+
search_document as run_search_document,
|
|
21
|
+
)
|
|
22
|
+
from docprov_mcp.verifier import (
|
|
23
|
+
verify_citation as run_verify_citation,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
mcp = MCPServer("docprov-mcp")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@mcp.tool()
|
|
30
|
+
def inspect_document(path: str) -> dict[str, Any]:
|
|
31
|
+
"""Inspect a PDF, Markdown, or text document's metadata, SHA-256, and page inventory."""
|
|
32
|
+
index = load_document(path)
|
|
33
|
+
return index.to_dict(include_text=False)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@mcp.tool()
|
|
37
|
+
def extract_pages(
|
|
38
|
+
path: str,
|
|
39
|
+
start_page: int = 1,
|
|
40
|
+
end_page: int | None = None,
|
|
41
|
+
) -> dict[str, Any]:
|
|
42
|
+
"""Extract verbatim text and page metadata for a 1-based inclusive page range."""
|
|
43
|
+
index = load_document(path)
|
|
44
|
+
pages = run_extract_pages(index, start_page=start_page, end_page=end_page)
|
|
45
|
+
return {
|
|
46
|
+
"source_path": index.source_path,
|
|
47
|
+
"sha256": index.sha256,
|
|
48
|
+
"total_pages": index.total_pages,
|
|
49
|
+
"pages": [p.to_dict() for p in pages],
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@mcp.tool()
|
|
54
|
+
def search_document(path: str, query: str, top_k: int = 5) -> dict[str, Any]:
|
|
55
|
+
"""Search a document using BM25-inspired ranking and return page-anchored snippets."""
|
|
56
|
+
index = load_document(path)
|
|
57
|
+
matches = run_search_document(index, query=query, top_k=top_k)
|
|
58
|
+
return {
|
|
59
|
+
"source_path": index.source_path,
|
|
60
|
+
"sha256": index.sha256,
|
|
61
|
+
"query": query,
|
|
62
|
+
"total_matches": len(matches),
|
|
63
|
+
"matches": [m.to_dict() for m in matches],
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@mcp.tool()
|
|
68
|
+
def verify_citation(
|
|
69
|
+
path: str,
|
|
70
|
+
claim: str,
|
|
71
|
+
cited_page: int | None = None,
|
|
72
|
+
min_confidence: float = 0.65,
|
|
73
|
+
) -> dict[str, Any]:
|
|
74
|
+
"""Verify whether a claim is supported on the cited page or elsewhere in the document."""
|
|
75
|
+
index = load_document(path)
|
|
76
|
+
result = run_verify_citation(
|
|
77
|
+
index,
|
|
78
|
+
claim=claim,
|
|
79
|
+
cited_page=cited_page,
|
|
80
|
+
min_confidence=min_confidence,
|
|
81
|
+
)
|
|
82
|
+
return result.to_dict()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@mcp.tool()
|
|
86
|
+
def audit_citations(
|
|
87
|
+
path: str,
|
|
88
|
+
citations: list[dict[str, Any]],
|
|
89
|
+
min_confidence: float = 0.65,
|
|
90
|
+
) -> dict[str, Any]:
|
|
91
|
+
"""Audit a batch of {'claim': ..., 'cited_page'?: ...} citations against a document."""
|
|
92
|
+
index = load_document(path)
|
|
93
|
+
report = run_audit_citations(index, citations=citations, min_confidence=min_confidence)
|
|
94
|
+
return report.to_dict()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@mcp.prompt()
|
|
98
|
+
def grounded_qa_workflow(path: str, question: str) -> str:
|
|
99
|
+
"""Guide an AI agent to answer a question strictly from verified document pages."""
|
|
100
|
+
return (
|
|
101
|
+
f"Answer the question using only verifiable evidence from `{path}`.\n\n"
|
|
102
|
+
f"Question: {question}\n\n"
|
|
103
|
+
"Required steps:\n"
|
|
104
|
+
f"1. Call `inspect_document(path={path!r})` to review total pages and SHA-256.\n"
|
|
105
|
+
f"2. Call `search_document(path={path!r}, query=...)` to locate candidate pages.\n"
|
|
106
|
+
f"3. Call `extract_pages(...)` to read the full context around candidate pages.\n"
|
|
107
|
+
"4. Draft your answer with explicit page citations `[p. N]`.\n"
|
|
108
|
+
f"5. Before responding to the user, call `audit_citations(path={path!r}, citations=...)` "
|
|
109
|
+
"and confirm every factual claim and number returns status `verified`."
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main() -> None:
|
|
114
|
+
"""Run the docprov-mcp server over stdio transport."""
|
|
115
|
+
mcp.run()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
if __name__ == "__main__":
|
|
119
|
+
main()
|