docutruth-mcp 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.
- docutruth_mcp-0.1.0/.gitignore +2 -0
- docutruth_mcp-0.1.0/LICENSE +21 -0
- docutruth_mcp-0.1.0/PKG-INFO +132 -0
- docutruth_mcp-0.1.0/README.md +118 -0
- docutruth_mcp-0.1.0/pyproject.toml +36 -0
- docutruth_mcp-0.1.0/src/docutruth_mcp/__init__.py +11 -0
- docutruth_mcp-0.1.0/src/docutruth_mcp/server.py +334 -0
- docutruth_mcp-0.1.0/tests/test_server.py +278 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DocuTruth
|
|
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,132 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: docutruth-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Verify legal citations with DocuTruth from inside an AI assistant (MCP connector)
|
|
5
|
+
Project-URL: Homepage, https://docutruth.ai
|
|
6
|
+
Author: DocuTruth
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: citations,legal,mcp,verification
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Requires-Dist: httpx>=0.27.0
|
|
12
|
+
Requires-Dist: mcp>=1.0.0
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# DocuTruth MCP connector
|
|
16
|
+
|
|
17
|
+
Check the citations in a brief without leaving your assistant. Ask it to
|
|
18
|
+
verify a PDF on your machine; the connector uploads it to DocuTruth, the
|
|
19
|
+
server runs the real verification pipeline, and the flagged citations come
|
|
20
|
+
back in the conversation.
|
|
21
|
+
|
|
22
|
+
## What it can and cannot check
|
|
23
|
+
|
|
24
|
+
It checks a **PDF on your computer**. It will refuse pasted text, and that
|
|
25
|
+
refusal is the honest answer rather than a limitation: an assistant that has
|
|
26
|
+
summarised or reformatted a brief has already destroyed the exact wording
|
|
27
|
+
and page numbers that quotation and pinpoint checks depend on.
|
|
28
|
+
|
|
29
|
+
**Flags are prompts to check a citation, not findings of fact.** On the
|
|
30
|
+
public LePhantomCite benchmark DocuTruth runs at roughly **65% precision and
|
|
31
|
+
63% recall** per citation — so about one flag in three is wrong, and it
|
|
32
|
+
misses about a third of real errors. Verify each flag against the opinion
|
|
33
|
+
before relying on it, and do not treat an unflagged citation as confirmed.
|
|
34
|
+
The connector repeats this with every set of results.
|
|
35
|
+
|
|
36
|
+
Verification takes **60–90 seconds at minimum**, several minutes for a long
|
|
37
|
+
brief. It cannot finish inside a single tool call, so the flow is submit →
|
|
38
|
+
check back. The finished report is also emailed, which is usually the easier
|
|
39
|
+
way to receive it.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
You need Python 3.10+. The connector has two dependencies (`mcp`, `httpx`);
|
|
44
|
+
it does not install any part of the DocuTruth server.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install docutruth-mcp
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Get an API key
|
|
51
|
+
|
|
52
|
+
Sign in at <https://docutruth.ai>, go to **Settings → API keys**, and create
|
|
53
|
+
one. **Copy it immediately** — it is shown once and never again, because the
|
|
54
|
+
server stores only a hash of it. If you lose it, revoke it and make another.
|
|
55
|
+
|
|
56
|
+
A key carries the same access your login does. Treat it like a password, and
|
|
57
|
+
revoke it from the same page if a machine is lost.
|
|
58
|
+
|
|
59
|
+
## Configure your assistant
|
|
60
|
+
|
|
61
|
+
Claude Desktop — `claude_desktop_config.json`:
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"mcpServers": {
|
|
66
|
+
"docutruth": {
|
|
67
|
+
"command": "docutruth-mcp",
|
|
68
|
+
"env": {
|
|
69
|
+
"DOCUTRUTH_API_KEY": "dt_sk_your_key_here"
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Claude Code — add it with:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
claude mcp add docutruth --env DOCUTRUTH_API_KEY=dt_sk_your_key_here -- docutruth-mcp
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
If `docutruth-mcp` is not on your PATH, use the full path to the executable
|
|
83
|
+
(inside your virtualenv's `bin/` or `Scripts/`), or
|
|
84
|
+
`"command": "python", "args": ["-m", "docutruth_mcp.server"]`.
|
|
85
|
+
|
|
86
|
+
Restart the assistant after editing its config.
|
|
87
|
+
|
|
88
|
+
## Settings
|
|
89
|
+
|
|
90
|
+
| Variable | Default | Purpose |
|
|
91
|
+
| --- | --- | --- |
|
|
92
|
+
| `DOCUTRUTH_API_KEY` | — | Required. Issued in the web app. |
|
|
93
|
+
| `DOCUTRUTH_API_URL` | `https://api.docutruth.ai` | The API. |
|
|
94
|
+
| `DOCUTRUTH_APP_URL` | `https://docutruth.ai` | Where report links point. |
|
|
95
|
+
|
|
96
|
+
⚠️ The API and the web app are **different hosts**. Pointing
|
|
97
|
+
`DOCUTRUTH_API_URL` at `https://docutruth.ai` makes every call hit the web
|
|
98
|
+
app and fail; the connector detects that specific mistake and says so.
|
|
99
|
+
|
|
100
|
+
## Tools
|
|
101
|
+
|
|
102
|
+
| Tool | Does |
|
|
103
|
+
| --- | --- |
|
|
104
|
+
| `submit_document` | Sends a PDF. Returns a job id immediately. |
|
|
105
|
+
| `check_job` | Progress; yields a document id when finished. |
|
|
106
|
+
| `get_findings` | Flagged citations, with the accuracy caveat. |
|
|
107
|
+
| `list_recent_documents` | Recently verified documents on the account. |
|
|
108
|
+
|
|
109
|
+
## Using it
|
|
110
|
+
|
|
111
|
+
> Check the citations in ~/briefs/appellant-brief.pdf
|
|
112
|
+
|
|
113
|
+
The assistant calls `submit_document`, waits, then `get_findings`. A typical
|
|
114
|
+
answer names the flagged citations, their pages, and which check fired —
|
|
115
|
+
existence, quotation, pinpoint, or whether the cited opinion appears to
|
|
116
|
+
support the claim.
|
|
117
|
+
|
|
118
|
+
## Troubleshooting
|
|
119
|
+
|
|
120
|
+
**"No API key configured"** — `DOCUTRUTH_API_KEY` is not reaching the
|
|
121
|
+
process. It belongs in the `env` block of the assistant's MCP config, not
|
|
122
|
+
your shell profile; restart the assistant after editing.
|
|
123
|
+
|
|
124
|
+
**"DocuTruth rejected the API key"** — revoked, or a different key than you
|
|
125
|
+
think. Issue a new one under **Settings → API keys** at
|
|
126
|
+
<https://docutruth.ai/settings>.
|
|
127
|
+
|
|
128
|
+
**"answered with a web page, not the API"** — `DOCUTRUTH_API_URL` points at
|
|
129
|
+
the web app. Remove the override, or set it to `https://api.docutruth.ai`.
|
|
130
|
+
|
|
131
|
+
**"is not a PDF"** — export a `.docx` to PDF first. Pasted text cannot be
|
|
132
|
+
checked for quotations or pin cites.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# DocuTruth MCP connector
|
|
2
|
+
|
|
3
|
+
Check the citations in a brief without leaving your assistant. Ask it to
|
|
4
|
+
verify a PDF on your machine; the connector uploads it to DocuTruth, the
|
|
5
|
+
server runs the real verification pipeline, and the flagged citations come
|
|
6
|
+
back in the conversation.
|
|
7
|
+
|
|
8
|
+
## What it can and cannot check
|
|
9
|
+
|
|
10
|
+
It checks a **PDF on your computer**. It will refuse pasted text, and that
|
|
11
|
+
refusal is the honest answer rather than a limitation: an assistant that has
|
|
12
|
+
summarised or reformatted a brief has already destroyed the exact wording
|
|
13
|
+
and page numbers that quotation and pinpoint checks depend on.
|
|
14
|
+
|
|
15
|
+
**Flags are prompts to check a citation, not findings of fact.** On the
|
|
16
|
+
public LePhantomCite benchmark DocuTruth runs at roughly **65% precision and
|
|
17
|
+
63% recall** per citation — so about one flag in three is wrong, and it
|
|
18
|
+
misses about a third of real errors. Verify each flag against the opinion
|
|
19
|
+
before relying on it, and do not treat an unflagged citation as confirmed.
|
|
20
|
+
The connector repeats this with every set of results.
|
|
21
|
+
|
|
22
|
+
Verification takes **60–90 seconds at minimum**, several minutes for a long
|
|
23
|
+
brief. It cannot finish inside a single tool call, so the flow is submit →
|
|
24
|
+
check back. The finished report is also emailed, which is usually the easier
|
|
25
|
+
way to receive it.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
You need Python 3.10+. The connector has two dependencies (`mcp`, `httpx`);
|
|
30
|
+
it does not install any part of the DocuTruth server.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install docutruth-mcp
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Get an API key
|
|
37
|
+
|
|
38
|
+
Sign in at <https://docutruth.ai>, go to **Settings → API keys**, and create
|
|
39
|
+
one. **Copy it immediately** — it is shown once and never again, because the
|
|
40
|
+
server stores only a hash of it. If you lose it, revoke it and make another.
|
|
41
|
+
|
|
42
|
+
A key carries the same access your login does. Treat it like a password, and
|
|
43
|
+
revoke it from the same page if a machine is lost.
|
|
44
|
+
|
|
45
|
+
## Configure your assistant
|
|
46
|
+
|
|
47
|
+
Claude Desktop — `claude_desktop_config.json`:
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
{
|
|
51
|
+
"mcpServers": {
|
|
52
|
+
"docutruth": {
|
|
53
|
+
"command": "docutruth-mcp",
|
|
54
|
+
"env": {
|
|
55
|
+
"DOCUTRUTH_API_KEY": "dt_sk_your_key_here"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Claude Code — add it with:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
claude mcp add docutruth --env DOCUTRUTH_API_KEY=dt_sk_your_key_here -- docutruth-mcp
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
If `docutruth-mcp` is not on your PATH, use the full path to the executable
|
|
69
|
+
(inside your virtualenv's `bin/` or `Scripts/`), or
|
|
70
|
+
`"command": "python", "args": ["-m", "docutruth_mcp.server"]`.
|
|
71
|
+
|
|
72
|
+
Restart the assistant after editing its config.
|
|
73
|
+
|
|
74
|
+
## Settings
|
|
75
|
+
|
|
76
|
+
| Variable | Default | Purpose |
|
|
77
|
+
| --- | --- | --- |
|
|
78
|
+
| `DOCUTRUTH_API_KEY` | — | Required. Issued in the web app. |
|
|
79
|
+
| `DOCUTRUTH_API_URL` | `https://api.docutruth.ai` | The API. |
|
|
80
|
+
| `DOCUTRUTH_APP_URL` | `https://docutruth.ai` | Where report links point. |
|
|
81
|
+
|
|
82
|
+
⚠️ The API and the web app are **different hosts**. Pointing
|
|
83
|
+
`DOCUTRUTH_API_URL` at `https://docutruth.ai` makes every call hit the web
|
|
84
|
+
app and fail; the connector detects that specific mistake and says so.
|
|
85
|
+
|
|
86
|
+
## Tools
|
|
87
|
+
|
|
88
|
+
| Tool | Does |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `submit_document` | Sends a PDF. Returns a job id immediately. |
|
|
91
|
+
| `check_job` | Progress; yields a document id when finished. |
|
|
92
|
+
| `get_findings` | Flagged citations, with the accuracy caveat. |
|
|
93
|
+
| `list_recent_documents` | Recently verified documents on the account. |
|
|
94
|
+
|
|
95
|
+
## Using it
|
|
96
|
+
|
|
97
|
+
> Check the citations in ~/briefs/appellant-brief.pdf
|
|
98
|
+
|
|
99
|
+
The assistant calls `submit_document`, waits, then `get_findings`. A typical
|
|
100
|
+
answer names the flagged citations, their pages, and which check fired —
|
|
101
|
+
existence, quotation, pinpoint, or whether the cited opinion appears to
|
|
102
|
+
support the claim.
|
|
103
|
+
|
|
104
|
+
## Troubleshooting
|
|
105
|
+
|
|
106
|
+
**"No API key configured"** — `DOCUTRUTH_API_KEY` is not reaching the
|
|
107
|
+
process. It belongs in the `env` block of the assistant's MCP config, not
|
|
108
|
+
your shell profile; restart the assistant after editing.
|
|
109
|
+
|
|
110
|
+
**"DocuTruth rejected the API key"** — revoked, or a different key than you
|
|
111
|
+
think. Issue a new one under **Settings → API keys** at
|
|
112
|
+
<https://docutruth.ai/settings>.
|
|
113
|
+
|
|
114
|
+
**"answered with a web page, not the API"** — `DOCUTRUTH_API_URL` points at
|
|
115
|
+
the web app. Remove the override, or set it to `https://api.docutruth.ai`.
|
|
116
|
+
|
|
117
|
+
**"is not a PDF"** — export a `.docx` to PDF first. Pasted text cannot be
|
|
118
|
+
checked for quotations or pin cites.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "docutruth-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Verify legal citations with DocuTruth from inside an AI assistant (MCP connector)"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = { text = "MIT" }
|
|
8
|
+
authors = [{ name = "DocuTruth" }]
|
|
9
|
+
keywords = ["mcp", "legal", "citations", "verification"]
|
|
10
|
+
|
|
11
|
+
# TWO dependencies on purpose. This runs on a lawyer's laptop and does
|
|
12
|
+
# nothing but move a file and read results back; every lane, the
|
|
13
|
+
# corpus and the models live server-side.
|
|
14
|
+
# Floating across the 1.x/2.x boundary on purpose — server.py imports
|
|
15
|
+
# whichever name the installed SDK uses. Pinning <2 would ship a brand
|
|
16
|
+
# new package already tied to a superseded major.
|
|
17
|
+
dependencies = [
|
|
18
|
+
"mcp>=1.0.0",
|
|
19
|
+
"httpx>=0.27.0",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://docutruth.ai"
|
|
24
|
+
|
|
25
|
+
[project.scripts]
|
|
26
|
+
docutruth-mcp = "docutruth_mcp.server:main"
|
|
27
|
+
|
|
28
|
+
[build-system]
|
|
29
|
+
requires = ["hatchling"]
|
|
30
|
+
build-backend = "hatchling.build"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["src/docutruth_mcp"]
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = ["pytest>=8.0"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""DocuTruth MCP connector — citation verification inside an assistant.
|
|
2
|
+
|
|
3
|
+
A LOCAL stdio server. It is deliberately a separate distribution from
|
|
4
|
+
the DocuTruth backend: it needs httpx and the MCP SDK, nothing else,
|
|
5
|
+
while the backend pulls FastAPI, psycopg, PyMuPDF, Tesseract bindings,
|
|
6
|
+
pandas, boto3 and google-cloud. Shipping the connector inside that
|
|
7
|
+
package would make a lawyer install an entire server stack to run an
|
|
8
|
+
HTTP client.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""DocuTruth MCP server — citation verification from inside an assistant.
|
|
2
|
+
|
|
3
|
+
Runs LOCALLY over stdio, on the machine that holds the brief. That is
|
|
4
|
+
not a style choice: an MCP tool call carries structured arguments, not
|
|
5
|
+
binaries, and a hosted server cannot reach the user's filesystem. A
|
|
6
|
+
local server reads the PDF itself and makes the same multipart POST
|
|
7
|
+
the browser makes, so the document goes through the real pipeline with
|
|
8
|
+
page numbers, the vision/OCR fallback and all five lanes intact.
|
|
9
|
+
|
|
10
|
+
It is a thin adapter over the existing REST API. Nothing is verified
|
|
11
|
+
here; this process only moves a file and reads results back.
|
|
12
|
+
|
|
13
|
+
WHAT THIS DELIBERATELY DOES NOT DO: accept pasted or model-generated
|
|
14
|
+
text in place of a file. An assistant that has summarised or
|
|
15
|
+
reformatted a brief has already destroyed the thing quote and pincite
|
|
16
|
+
verification depend on — exact wording and page numbers — and the
|
|
17
|
+
failures would look like ours. If you have text and not a file, the
|
|
18
|
+
honest answer is that we cannot check quotations in it.
|
|
19
|
+
|
|
20
|
+
TIMING, which shapes the whole design: a document takes 60-90 seconds
|
|
21
|
+
minimum and several minutes for a long brief. That does not fit a
|
|
22
|
+
synchronous tool call, so the flow is submit -> job id -> check back,
|
|
23
|
+
and the finished report is emailed as it already is for web uploads.
|
|
24
|
+
|
|
25
|
+
DOCUTRUTH_API_URL default https://api.docutruth.ai (the API)
|
|
26
|
+
DOCUTRUTH_APP_URL default https://docutruth.ai (the web app)
|
|
27
|
+
DOCUTRUTH_API_KEY dt_sk_... issued in the web app
|
|
28
|
+
|
|
29
|
+
⚠️ THEY ARE DIFFERENT HOSTS and the first version of this file got it
|
|
30
|
+
wrong. Traefik routes Host(api.docutruth.ai) to the backend and
|
|
31
|
+
Host(docutruth.ai) to the frontend, so pointing the connector at the
|
|
32
|
+
apex returns the React app's 404 for every call. Links meant for a
|
|
33
|
+
person to click — a report, the key page — belong on APP_URL; every
|
|
34
|
+
request belongs on API_URL.
|
|
35
|
+
"""
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import os
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
import httpx
|
|
43
|
+
|
|
44
|
+
# The MCP SDK renamed FastMCP to MCPServer in 2.0. Both expose the
|
|
45
|
+
# .tool() decorator and .run() with the same shape at the level this
|
|
46
|
+
# file uses them, so support both rather than pinning: a fresh
|
|
47
|
+
# `pip install` resolves to 2.x today, and importing FastMCP there
|
|
48
|
+
# raises ModuleNotFoundError before the process can start. Caught by
|
|
49
|
+
# installing the wheel into a bare python:3.12-slim, which is the only
|
|
50
|
+
# place that mistake is visible — a dev environment already has 1.x.
|
|
51
|
+
try: # mcp >= 2
|
|
52
|
+
from mcp.server.mcpserver import MCPServer as _Server
|
|
53
|
+
except ModuleNotFoundError: # mcp 1.x
|
|
54
|
+
from mcp.server.fastmcp import FastMCP as _Server
|
|
55
|
+
|
|
56
|
+
API_URL = os.getenv("DOCUTRUTH_API_URL", "https://api.docutruth.ai").rstrip("/")
|
|
57
|
+
APP_URL = os.getenv("DOCUTRUTH_APP_URL", "https://docutruth.ai").rstrip("/")
|
|
58
|
+
API_KEY = os.getenv("DOCUTRUTH_API_KEY", "")
|
|
59
|
+
API_PREFIX = "/api/v1"
|
|
60
|
+
|
|
61
|
+
# A brief is a few MB; a scanned appendix can be far larger and will
|
|
62
|
+
# cost minutes of OCR. Refuse early and say so rather than upload for
|
|
63
|
+
# ten minutes and time out.
|
|
64
|
+
MAX_MB = 50
|
|
65
|
+
# Generous: the upload itself is the slow part on a domestic
|
|
66
|
+
# connection, and the endpoint returns as soon as the job is queued.
|
|
67
|
+
TIMEOUT = httpx.Timeout(120.0, connect=15.0)
|
|
68
|
+
|
|
69
|
+
mcp = _Server("docutruth")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ToolError(RuntimeError):
|
|
73
|
+
"""A message meant for the assistant to read aloud, not a stack."""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _client() -> httpx.Client:
|
|
77
|
+
if not API_KEY:
|
|
78
|
+
raise ToolError(
|
|
79
|
+
"No API key configured. Set DOCUTRUTH_API_KEY to a key issued "
|
|
80
|
+
"at " + APP_URL + "/settings (API keys tab), then restart the "
|
|
81
|
+
"connector."
|
|
82
|
+
)
|
|
83
|
+
return httpx.Client(
|
|
84
|
+
base_url=API_URL + API_PREFIX,
|
|
85
|
+
headers={"Authorization": f"Bearer {API_KEY}"},
|
|
86
|
+
timeout=TIMEOUT,
|
|
87
|
+
follow_redirects=True,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _explain(exc: httpx.HTTPStatusError) -> str:
|
|
92
|
+
"""Turn a status code into something a lawyer can act on."""
|
|
93
|
+
code = exc.response.status_code
|
|
94
|
+
if code in (401, 403):
|
|
95
|
+
return (
|
|
96
|
+
"DocuTruth rejected the API key. It may have been revoked, or "
|
|
97
|
+
"DOCUTRUTH_API_KEY may be set to something else. Issue a new "
|
|
98
|
+
"one at " + APP_URL + "/settings (API keys tab)."
|
|
99
|
+
)
|
|
100
|
+
if code == 402 or code == 429:
|
|
101
|
+
return (
|
|
102
|
+
"This account is over its plan limit for now. The web app at "
|
|
103
|
+
+ APP_URL + " shows current usage."
|
|
104
|
+
)
|
|
105
|
+
if code == 404:
|
|
106
|
+
# A 404 whose body is HTML is almost always the WEB APP
|
|
107
|
+
# answering, not the API — which means API_URL points at the
|
|
108
|
+
# wrong host. Saying "no record of that id" there sent me
|
|
109
|
+
# looking for a Traefik fault that did not exist, on a list
|
|
110
|
+
# endpoint that has no id in it.
|
|
111
|
+
ctype = exc.response.headers.get("content-type", "")
|
|
112
|
+
body = exc.response.text[:200].lstrip().lower()
|
|
113
|
+
if "html" in ctype.lower() or body.startswith(("<!doctype", "<html")):
|
|
114
|
+
return (
|
|
115
|
+
f"{API_URL} answered with a web page, not the API. That host "
|
|
116
|
+
"is probably the web app; the API is a separate host. Set "
|
|
117
|
+
f"DOCUTRUTH_API_URL (try {API_URL.replace('//', '//api.', 1)}"
|
|
118
|
+
" if you have not already)."
|
|
119
|
+
)
|
|
120
|
+
return "DocuTruth has no record of that id for this account."
|
|
121
|
+
if code >= 500:
|
|
122
|
+
return "DocuTruth returned a server error. Nothing was lost; retry."
|
|
123
|
+
detail = ""
|
|
124
|
+
try:
|
|
125
|
+
detail = str(exc.response.json().get("detail", ""))[:300]
|
|
126
|
+
except Exception: # noqa: BLE001
|
|
127
|
+
detail = exc.response.text[:300]
|
|
128
|
+
return f"DocuTruth refused the request ({code}). {detail}".strip()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _call(method: str, path: str, **kw: Any) -> Any:
|
|
132
|
+
try:
|
|
133
|
+
with _client() as c:
|
|
134
|
+
r = c.request(method, path, **kw)
|
|
135
|
+
r.raise_for_status()
|
|
136
|
+
return r.json()
|
|
137
|
+
except httpx.HTTPStatusError as e:
|
|
138
|
+
raise ToolError(_explain(e)) from e
|
|
139
|
+
except httpx.RequestError as e:
|
|
140
|
+
raise ToolError(
|
|
141
|
+
f"Could not reach DocuTruth at {API_URL} ({e.__class__.__name__}). "
|
|
142
|
+
"Check the machine is online and DOCUTRUTH_API_URL is right."
|
|
143
|
+
) from e
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@mcp.tool()
|
|
147
|
+
def submit_document(
|
|
148
|
+
file_path: str, doc_type: str = "legal", email_report: bool = True
|
|
149
|
+
) -> dict[str, Any]:
|
|
150
|
+
"""Send a document to DocuTruth to have its citations verified.
|
|
151
|
+
|
|
152
|
+
Returns IMMEDIATELY with a job id — verification takes 60-90
|
|
153
|
+
seconds at minimum and several minutes for a long brief, so it
|
|
154
|
+
cannot complete inside this call. Poll with check_job, then read
|
|
155
|
+
results with get_findings. If email_report is true the finished
|
|
156
|
+
report is emailed to the account holder, which is usually the
|
|
157
|
+
better way to receive it.
|
|
158
|
+
|
|
159
|
+
file_path must be a PDF ON THIS MACHINE. Text pasted from an
|
|
160
|
+
assistant will not do: quotation and pinpoint checks need the
|
|
161
|
+
document's exact wording and page numbers.
|
|
162
|
+
|
|
163
|
+
doc_type is "legal" for briefs and filings (enables the citation
|
|
164
|
+
lanes), "scientific", or "general".
|
|
165
|
+
"""
|
|
166
|
+
p = Path(file_path).expanduser()
|
|
167
|
+
if not p.exists() or not p.is_file():
|
|
168
|
+
raise ToolError(f"No file at {p}. Give an absolute path to a PDF.")
|
|
169
|
+
if p.suffix.lower() != ".pdf":
|
|
170
|
+
raise ToolError(
|
|
171
|
+
f"{p.name} is not a PDF. DocuTruth reads PDFs; a .docx must be "
|
|
172
|
+
"exported first, and pasted text cannot be checked for "
|
|
173
|
+
"quotations or pin cites."
|
|
174
|
+
)
|
|
175
|
+
size_mb = p.stat().st_size / 1_048_576
|
|
176
|
+
if size_mb > MAX_MB:
|
|
177
|
+
raise ToolError(
|
|
178
|
+
f"{p.name} is {size_mb:.0f} MB, over the {MAX_MB} MB limit. "
|
|
179
|
+
"Split it or upload it through the web app."
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
with p.open("rb") as fh:
|
|
183
|
+
job = _call(
|
|
184
|
+
"POST",
|
|
185
|
+
"/upload/",
|
|
186
|
+
files={"pdf_file": (p.name, fh, "application/pdf")},
|
|
187
|
+
data={
|
|
188
|
+
"doc_type": doc_type,
|
|
189
|
+
"email_report": str(bool(email_report)).lower(),
|
|
190
|
+
"prompt": "",
|
|
191
|
+
},
|
|
192
|
+
)
|
|
193
|
+
return {
|
|
194
|
+
"job_id": job.get("id"),
|
|
195
|
+
"status": job.get("status"),
|
|
196
|
+
"filename": p.name,
|
|
197
|
+
"size_mb": round(size_mb, 2),
|
|
198
|
+
"next": (
|
|
199
|
+
"Verification is running. Call check_job with this job_id in a "
|
|
200
|
+
"minute or two; a long brief can take several minutes."
|
|
201
|
+
+ (" The report will also be emailed." if email_report else "")
|
|
202
|
+
),
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@mcp.tool()
|
|
207
|
+
def check_job(job_id: str) -> dict[str, Any]:
|
|
208
|
+
"""Progress of a submitted document.
|
|
209
|
+
|
|
210
|
+
status is pending, processing, completed, partial or failed. When
|
|
211
|
+
it is completed or partial, each item carries a document_id to
|
|
212
|
+
pass to get_findings.
|
|
213
|
+
"""
|
|
214
|
+
job = _call("GET", f"/jobs/{job_id}")
|
|
215
|
+
items = [
|
|
216
|
+
{
|
|
217
|
+
"filename": it.get("filename"),
|
|
218
|
+
"status": it.get("status"),
|
|
219
|
+
"document_id": it.get("document_id"),
|
|
220
|
+
"error": it.get("error"),
|
|
221
|
+
}
|
|
222
|
+
for it in (job.get("items") or [])
|
|
223
|
+
]
|
|
224
|
+
done = job.get("status") in ("completed", "partial", "failed")
|
|
225
|
+
return {
|
|
226
|
+
"job_id": job.get("id"),
|
|
227
|
+
"status": job.get("status"),
|
|
228
|
+
"completed_items": job.get("completed_items"),
|
|
229
|
+
"failed_items": job.get("failed_items"),
|
|
230
|
+
"total_items": job.get("total_items"),
|
|
231
|
+
"items": items,
|
|
232
|
+
"next": (
|
|
233
|
+
"Finished. Call get_findings with a document_id above."
|
|
234
|
+
if done
|
|
235
|
+
else "Still running — check again shortly."
|
|
236
|
+
),
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _flagged(ref: dict[str, Any]) -> list[str]:
|
|
241
|
+
"""Why this reference is worth a human's attention, in the
|
|
242
|
+
report's own terms. Empty list means nothing was flagged."""
|
|
243
|
+
out: list[str] = []
|
|
244
|
+
status = (ref.get("verification_status") or "").lower()
|
|
245
|
+
if status in ("not_found", "address_mismatch", "not_a_case"):
|
|
246
|
+
out.append(f"existence: {status}")
|
|
247
|
+
if ref.get("safety_flagged"):
|
|
248
|
+
out.append("link flagged unsafe")
|
|
249
|
+
g = ref.get("genuineness_score")
|
|
250
|
+
if isinstance(g, int) and g <= 2:
|
|
251
|
+
out.append(f"genuineness {g}/10")
|
|
252
|
+
for q in ref.get("quotes") or []:
|
|
253
|
+
st = (q.get("status") or "").lower()
|
|
254
|
+
if st in ("not_found", "close_match", "wrong_page", "wrong_case"):
|
|
255
|
+
out.append(f"quotation: {st}")
|
|
256
|
+
for h in ref.get("holdings") or []:
|
|
257
|
+
if (h.get("verdict") or "") in ("not_supported", "no_support_found"):
|
|
258
|
+
out.append("the cited opinion may not support the claim")
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@mcp.tool()
|
|
263
|
+
def get_findings(document_id: str, flagged_only: bool = True) -> dict[str, Any]:
|
|
264
|
+
"""Citations DocuTruth flagged in a finished document.
|
|
265
|
+
|
|
266
|
+
⚠️ Read the caveat in the return value before repeating any of
|
|
267
|
+
this to a client. These are flags for a human to check, not
|
|
268
|
+
findings of fact: roughly a third of them are wrong, and the
|
|
269
|
+
checker misses some real errors. It is a reading aid.
|
|
270
|
+
"""
|
|
271
|
+
doc = _call("GET", f"/documents/{document_id}")
|
|
272
|
+
refs = doc.get("references") or []
|
|
273
|
+
rows = []
|
|
274
|
+
for r in refs:
|
|
275
|
+
reasons = _flagged(r)
|
|
276
|
+
if flagged_only and not reasons:
|
|
277
|
+
continue
|
|
278
|
+
rows.append(
|
|
279
|
+
{
|
|
280
|
+
"citation": (r.get("text") or "")[:300],
|
|
281
|
+
"page": r.get("page_number"),
|
|
282
|
+
"flags": reasons,
|
|
283
|
+
"detail": (r.get("verification_details") or "")[:300] or None,
|
|
284
|
+
}
|
|
285
|
+
)
|
|
286
|
+
return {
|
|
287
|
+
"document_id": document_id,
|
|
288
|
+
"filename": doc.get("filename"),
|
|
289
|
+
"citations_total": len(refs),
|
|
290
|
+
"citations_shown": len(rows),
|
|
291
|
+
"findings": rows,
|
|
292
|
+
"caveat": (
|
|
293
|
+
"Flags are prompts to check a citation, not conclusions. On the "
|
|
294
|
+
"public LePhantomCite benchmark this checker runs at roughly "
|
|
295
|
+
"65% precision and 63% recall per citation — so about one flag "
|
|
296
|
+
"in three is wrong, and it misses about a third of real errors. "
|
|
297
|
+
"Verify each flag against the opinion before relying on it, and "
|
|
298
|
+
"do not treat an unflagged citation as confirmed."
|
|
299
|
+
),
|
|
300
|
+
# the web app, not the API — this is a link for a person
|
|
301
|
+
"report_url": f"{APP_URL}/documents/{document_id}",
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
@mcp.tool()
|
|
306
|
+
def list_recent_documents(limit: int = 10) -> dict[str, Any]:
|
|
307
|
+
"""Documents recently verified on this account, newest first."""
|
|
308
|
+
limit = max(1, min(int(limit), 50))
|
|
309
|
+
page = _call("GET", "/documents/", params={"skip": 0, "limit": limit})
|
|
310
|
+
# Only the fields DocumentPublic actually carries. An earlier
|
|
311
|
+
# version also reported doc_type, which that response does not
|
|
312
|
+
# include — so every document came back "doc_type": null while
|
|
313
|
+
# the stored value was "legal". Reporting a field the endpoint
|
|
314
|
+
# does not return is a small lie that reads like a real one.
|
|
315
|
+
return {
|
|
316
|
+
"count": page.get("count"),
|
|
317
|
+
"documents": [
|
|
318
|
+
{
|
|
319
|
+
"document_id": d.get("id"),
|
|
320
|
+
"filename": d.get("filename"),
|
|
321
|
+
"uploaded_at": d.get("uploaded_at"),
|
|
322
|
+
"citations": d.get("reference_count"),
|
|
323
|
+
}
|
|
324
|
+
for d in (page.get("data") or [])
|
|
325
|
+
],
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def main() -> None:
|
|
330
|
+
mcp.run()
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
if __name__ == "__main__":
|
|
334
|
+
main()
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""The DocuTruth MCP server: a thin adapter over the REST API.
|
|
2
|
+
|
|
3
|
+
Nothing is verified in that process, so these tests check the things
|
|
4
|
+
that CAN go wrong in an adapter — refusing input it must refuse,
|
|
5
|
+
turning status codes into something a lawyer can act on, and never
|
|
6
|
+
dropping the caveat that the flags are not findings of fact.
|
|
7
|
+
|
|
8
|
+
The HTTP layer is mocked throughout; no network, no app database.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from unittest.mock import patch
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
import pytest
|
|
17
|
+
|
|
18
|
+
from docutruth_mcp import server as srv
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture(autouse=True)
|
|
22
|
+
def api_key(monkeypatch):
|
|
23
|
+
monkeypatch.setattr(srv, "API_KEY", "dt_sk_testkey")
|
|
24
|
+
monkeypatch.setattr(srv, "API_URL", "https://api.example.test")
|
|
25
|
+
monkeypatch.setattr(srv, "APP_URL", "https://example.test")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.fixture()
|
|
29
|
+
def pdf(tmp_path) -> Path:
|
|
30
|
+
p = tmp_path / "brief.pdf"
|
|
31
|
+
p.write_bytes(b"%PDF-1.4\n" + b"x" * 500)
|
|
32
|
+
return p
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _tool(fn):
|
|
36
|
+
"""FastMCP wraps the function; call the original."""
|
|
37
|
+
return getattr(fn, "fn", fn)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# --- input the adapter must refuse ----------------------------------
|
|
41
|
+
|
|
42
|
+
def test_a_missing_file_is_refused_before_any_upload(tmp_path):
|
|
43
|
+
with pytest.raises(srv.ToolError) as e:
|
|
44
|
+
_tool(srv.submit_document)(str(tmp_path / "nope.pdf"))
|
|
45
|
+
assert "No file at" in str(e.value)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_a_non_pdf_is_refused_and_says_why(tmp_path):
|
|
49
|
+
"""Pasted text and .docx are the two things users will try. The
|
|
50
|
+
refusal has to explain that quotations cannot be checked without
|
|
51
|
+
the document, or it reads as an arbitrary limitation."""
|
|
52
|
+
p = tmp_path / "brief.docx"
|
|
53
|
+
p.write_bytes(b"PK\x03\x04")
|
|
54
|
+
with pytest.raises(srv.ToolError) as e:
|
|
55
|
+
_tool(srv.submit_document)(str(p))
|
|
56
|
+
msg = str(e.value)
|
|
57
|
+
assert "not a PDF" in msg
|
|
58
|
+
assert "quotation" in msg.lower() or "pin cite" in msg.lower()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_an_oversized_file_is_refused_without_uploading(tmp_path, monkeypatch):
|
|
62
|
+
"""Lower the cap rather than patch Path.stat — patching it broke
|
|
63
|
+
Path.exists(), which passes follow_symlinks and the stub did not."""
|
|
64
|
+
monkeypatch.setattr(srv, "MAX_MB", 0.0001)
|
|
65
|
+
p = tmp_path / "huge.pdf"
|
|
66
|
+
p.write_bytes(b"%PDF-1.4\n" + b"x" * 5000)
|
|
67
|
+
with pytest.raises(srv.ToolError) as e:
|
|
68
|
+
_tool(srv.submit_document)(str(p))
|
|
69
|
+
assert "MB" in str(e.value) and "limit" in str(e.value)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_no_api_key_is_a_message_not_a_traceback(monkeypatch, pdf):
|
|
73
|
+
monkeypatch.setattr(srv, "API_KEY", "")
|
|
74
|
+
with pytest.raises(srv.ToolError) as e:
|
|
75
|
+
_tool(srv.submit_document)(str(pdf))
|
|
76
|
+
assert "/settings" in str(e.value)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# --- the happy path -------------------------------------------------
|
|
80
|
+
|
|
81
|
+
def test_submit_returns_a_job_and_sets_expectations(pdf):
|
|
82
|
+
with patch.object(srv, "_call", return_value={"id": "j1", "status": "pending"}):
|
|
83
|
+
out = _tool(srv.submit_document)(str(pdf))
|
|
84
|
+
assert out["job_id"] == "j1"
|
|
85
|
+
assert out["filename"] == "brief.pdf"
|
|
86
|
+
# the latency caveat is the whole reason this tool is async-shaped
|
|
87
|
+
assert "minute" in out["next"].lower()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_submit_posts_multipart_to_the_real_upload_endpoint(pdf):
|
|
91
|
+
"""Same code path as the browser — that is what preserves page
|
|
92
|
+
numbers and the OCR fallback."""
|
|
93
|
+
seen = {}
|
|
94
|
+
|
|
95
|
+
def fake(method, path, **kw):
|
|
96
|
+
seen.update(method=method, path=path, kw=kw)
|
|
97
|
+
return {"id": "j1", "status": "pending"}
|
|
98
|
+
|
|
99
|
+
with patch.object(srv, "_call", side_effect=fake):
|
|
100
|
+
_tool(srv.submit_document)(str(pdf), doc_type="legal")
|
|
101
|
+
assert seen["method"] == "POST"
|
|
102
|
+
assert seen["path"] == "/upload/"
|
|
103
|
+
assert "pdf_file" in seen["kw"]["files"]
|
|
104
|
+
assert seen["kw"]["data"]["doc_type"] == "legal"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_check_job_reports_progress_and_what_to_do_next():
|
|
108
|
+
payload = {
|
|
109
|
+
"id": "j1",
|
|
110
|
+
"status": "completed",
|
|
111
|
+
"completed_items": 1,
|
|
112
|
+
"failed_items": 0,
|
|
113
|
+
"total_items": 1,
|
|
114
|
+
"items": [{"filename": "brief.pdf", "status": "completed",
|
|
115
|
+
"document_id": "d1", "error": None}],
|
|
116
|
+
}
|
|
117
|
+
with patch.object(srv, "_call", return_value=payload):
|
|
118
|
+
out = _tool(srv.check_job)("j1")
|
|
119
|
+
assert out["items"][0]["document_id"] == "d1"
|
|
120
|
+
assert "get_findings" in out["next"]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def test_check_job_while_running_says_so():
|
|
124
|
+
with patch.object(srv, "_call", return_value={"id": "j1", "status": "processing",
|
|
125
|
+
"items": []}):
|
|
126
|
+
out = _tool(srv.check_job)("j1")
|
|
127
|
+
assert "again" in out["next"].lower()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# --- findings -------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
DOC = {
|
|
133
|
+
"filename": "brief.pdf",
|
|
134
|
+
"references": [
|
|
135
|
+
{"text": "Roe v. Wade, 410 U.S. 113 (1973)", "page_number": 3,
|
|
136
|
+
"verification_status": "match", "quotes": [], "holdings": []},
|
|
137
|
+
{"text": "Fake v. Nobody, 999 F.4th 1", "page_number": 7,
|
|
138
|
+
"verification_status": "not_found", "quotes": [], "holdings": []},
|
|
139
|
+
{"text": "Cooks, 589 F.3d 173", "page_number": 9,
|
|
140
|
+
"verification_status": "match",
|
|
141
|
+
"quotes": [{"status": "close_match"}], "holdings": []},
|
|
142
|
+
{"text": "Perry, 408 U.S. 593", "page_number": 11,
|
|
143
|
+
"verification_status": "match", "quotes": [],
|
|
144
|
+
"holdings": [{"verdict": "not_supported"}]},
|
|
145
|
+
],
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def test_findings_flags_each_lane_and_hides_the_clean_one():
|
|
150
|
+
with patch.object(srv, "_call", return_value=DOC):
|
|
151
|
+
out = _tool(srv.get_findings)("d1")
|
|
152
|
+
assert out["citations_total"] == 4
|
|
153
|
+
assert out["citations_shown"] == 3 # Roe is clean
|
|
154
|
+
flat = " ".join(f for row in out["findings"] for f in row["flags"])
|
|
155
|
+
assert "existence: not_found" in flat
|
|
156
|
+
assert "quotation: close_match" in flat
|
|
157
|
+
assert "may not support" in flat
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def test_findings_can_return_everything():
|
|
161
|
+
with patch.object(srv, "_call", return_value=DOC):
|
|
162
|
+
out = _tool(srv.get_findings)("d1", flagged_only=False)
|
|
163
|
+
assert out["citations_shown"] == 4
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def test_findings_always_carry_the_honest_caveat():
|
|
167
|
+
"""The one claim that must never be dropped. A flag is a prompt to
|
|
168
|
+
check, and the measured numbers belong next to it."""
|
|
169
|
+
with patch.object(srv, "_call", return_value=DOC):
|
|
170
|
+
out = _tool(srv.get_findings)("d1")
|
|
171
|
+
c = out["caveat"].lower()
|
|
172
|
+
assert "65%" in c and "63%" in c
|
|
173
|
+
assert "not conclusions" in c
|
|
174
|
+
assert "unflagged" in c # absence of a flag is not clearance
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# --- errors a user can act on ---------------------------------------
|
|
178
|
+
|
|
179
|
+
def _status_error(code: int) -> httpx.HTTPStatusError:
|
|
180
|
+
req = httpx.Request("GET", "https://example.test/x")
|
|
181
|
+
resp = httpx.Response(code, json={"detail": "nope"}, request=req)
|
|
182
|
+
return httpx.HTTPStatusError("boom", request=req, response=resp)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@pytest.mark.parametrize(
|
|
186
|
+
"code,needle",
|
|
187
|
+
[(401, "api key"), (403, "api key"), (429, "plan limit"),
|
|
188
|
+
(404, "no record"), (500, "server error")],
|
|
189
|
+
)
|
|
190
|
+
def test_status_codes_become_actionable_sentences(code, needle):
|
|
191
|
+
assert needle in srv._explain(_status_error(code)).lower()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def test_an_unreachable_host_names_the_url_and_the_cause():
|
|
195
|
+
req = httpx.Request("GET", "https://example.test/x")
|
|
196
|
+
with patch.object(srv, "_client") as mk:
|
|
197
|
+
mk.return_value.__enter__.return_value.request.side_effect = (
|
|
198
|
+
httpx.ConnectError("refused", request=req)
|
|
199
|
+
)
|
|
200
|
+
with pytest.raises(srv.ToolError) as e:
|
|
201
|
+
srv._call("GET", "/documents/")
|
|
202
|
+
msg = str(e.value)
|
|
203
|
+
assert "api.example.test" in msg and "ConnectError" in msg
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def test_list_recent_reports_only_fields_the_endpoint_returns():
|
|
207
|
+
"""DocumentPublic carries id, filename, uploaded_at and
|
|
208
|
+
reference_count — NOT doc_type. An earlier version reported
|
|
209
|
+
doc_type anyway, so every row came back null while the stored
|
|
210
|
+
value was "legal"."""
|
|
211
|
+
page = {
|
|
212
|
+
"count": 1,
|
|
213
|
+
"data": [{"id": "d1", "filename": "brief.pdf",
|
|
214
|
+
"uploaded_at": "2026-10-23T19:44:47", "reference_count": 11}],
|
|
215
|
+
}
|
|
216
|
+
with patch.object(srv, "_call", return_value=page):
|
|
217
|
+
out = _tool(srv.list_recent_documents)(limit=3)
|
|
218
|
+
row = out["documents"][0]
|
|
219
|
+
assert row["citations"] == 11
|
|
220
|
+
assert "doc_type" not in row
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def test_list_recent_clamps_the_limit():
|
|
224
|
+
with patch.object(srv, "_call", return_value={"count": 0, "data": []}) as c:
|
|
225
|
+
_tool(srv.list_recent_documents)(limit=9999)
|
|
226
|
+
assert c.call_args.kwargs["params"]["limit"] == 50
|
|
227
|
+
_tool(srv.list_recent_documents)(limit=0)
|
|
228
|
+
assert c.call_args.kwargs["params"]["limit"] == 1
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def test_the_api_host_and_the_app_host_are_not_the_same_by_default():
|
|
232
|
+
"""Traefik routes Host(api.docutruth.ai) to the backend and
|
|
233
|
+
Host(docutruth.ai) to the frontend. The first version of this
|
|
234
|
+
connector defaulted to the apex, so every call hit the React app
|
|
235
|
+
and 404'd."""
|
|
236
|
+
import importlib
|
|
237
|
+
import os
|
|
238
|
+
for k in ("DOCUTRUTH_API_URL", "DOCUTRUTH_APP_URL"):
|
|
239
|
+
os.environ.pop(k, None)
|
|
240
|
+
fresh = importlib.reload(srv)
|
|
241
|
+
assert fresh.API_URL == "https://api.docutruth.ai"
|
|
242
|
+
assert fresh.APP_URL == "https://docutruth.ai"
|
|
243
|
+
assert fresh.API_URL != fresh.APP_URL
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def test_links_for_a_person_point_at_the_app_not_the_api():
|
|
247
|
+
"""api.docutruth.ai/documents/<id> is neither a valid API path
|
|
248
|
+
(that is /api/v1/...) nor a web page."""
|
|
249
|
+
with patch.object(srv, "_call", return_value=DOC):
|
|
250
|
+
out = _tool(srv.get_findings)("d1")
|
|
251
|
+
assert out["report_url"].startswith("https://example.test/")
|
|
252
|
+
assert "api.example.test" not in out["report_url"]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def test_the_key_page_is_an_app_link():
|
|
256
|
+
assert "example.test/settings" in srv._explain(_status_error(403))
|
|
257
|
+
assert "api.example.test" not in srv._explain(_status_error(403))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def test_an_html_404_says_the_host_is_wrong_not_that_the_id_is_unknown():
|
|
261
|
+
"""Pointing the connector at the web app returns the React 404 for
|
|
262
|
+
every call. "No record of that id" sent me hunting a Traefik fault
|
|
263
|
+
that did not exist — on a LIST endpoint with no id in it."""
|
|
264
|
+
req = httpx.Request("GET", "https://example.test/api/v1/documents/")
|
|
265
|
+
resp = httpx.Response(404, text="<!doctype html><html>404</html>",
|
|
266
|
+
headers={"content-type": "text/html"}, request=req)
|
|
267
|
+
msg = srv._explain(httpx.HTTPStatusError("x", request=req, response=resp))
|
|
268
|
+
assert "web page" in msg and "DOCUTRUTH_API_URL" in msg
|
|
269
|
+
assert "no record" not in msg.lower()
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def test_a_json_404_still_means_the_id_is_unknown():
|
|
273
|
+
req = httpx.Request("GET", "https://api.example.test/api/v1/jobs/x")
|
|
274
|
+
resp = httpx.Response(404, json={"detail": "Job not found"},
|
|
275
|
+
headers={"content-type": "application/json"},
|
|
276
|
+
request=req)
|
|
277
|
+
msg = srv._explain(httpx.HTTPStatusError("x", request=req, response=resp))
|
|
278
|
+
assert "no record of that id" in msg
|