mcp-papra 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.
- mcp_papra-0.1.0/.gitignore +44 -0
- mcp_papra-0.1.0/LICENSE +21 -0
- mcp_papra-0.1.0/NOTES-FR.md +34 -0
- mcp_papra-0.1.0/PKG-INFO +80 -0
- mcp_papra-0.1.0/README.md +63 -0
- mcp_papra-0.1.0/pyproject.toml +33 -0
- mcp_papra-0.1.0/src/papra_mcp/__init__.py +3 -0
- mcp_papra-0.1.0/src/papra_mcp/client.py +156 -0
- mcp_papra-0.1.0/src/papra_mcp/demo.py +81 -0
- mcp_papra-0.1.0/src/papra_mcp/server.py +162 -0
- mcp_papra-0.1.0/tests/test_papra.py +151 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
*.so
|
|
6
|
+
|
|
7
|
+
# Packaging
|
|
8
|
+
build/
|
|
9
|
+
dist/
|
|
10
|
+
*.egg-info/
|
|
11
|
+
.eggs/
|
|
12
|
+
wheels/
|
|
13
|
+
|
|
14
|
+
# Environnements virtuels
|
|
15
|
+
.venv/
|
|
16
|
+
venv/
|
|
17
|
+
env/
|
|
18
|
+
|
|
19
|
+
# Tests et outils
|
|
20
|
+
.pytest_cache/
|
|
21
|
+
.coverage
|
|
22
|
+
htmlcov/
|
|
23
|
+
.mypy_cache/
|
|
24
|
+
.ruff_cache/
|
|
25
|
+
.tox/
|
|
26
|
+
|
|
27
|
+
# Secrets et configuration locale
|
|
28
|
+
.env
|
|
29
|
+
.env.*
|
|
30
|
+
*.pem
|
|
31
|
+
*.key
|
|
32
|
+
|
|
33
|
+
# Radar : configuration réelle et sorties (seul radar.example.toml est versionné)
|
|
34
|
+
radar.toml
|
|
35
|
+
*.csv
|
|
36
|
+
rapport*.html
|
|
37
|
+
|
|
38
|
+
# Éditeurs et système
|
|
39
|
+
.vscode/
|
|
40
|
+
.idea/
|
|
41
|
+
.DS_Store
|
|
42
|
+
Thumbs.db
|
|
43
|
+
radar-data/
|
|
44
|
+
radar-out/
|
mcp_papra-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jérémie
|
|
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,34 @@
|
|
|
1
|
+
# papra-mcp — notes pour Jérémie
|
|
2
|
+
|
|
3
|
+
## Ce qui a été fait
|
|
4
|
+
- Serveur MCP (FastMCP) avec 5 outils : `search_documents`, `get_document`, `summarize_by_tag` (lecture) ; `upload_document`, `tag_document` (écriture, seulement si `PAPRA_ALLOW_WRITE=1`).
|
|
5
|
+
- Mode démo `PAPRA_DEMO=1` : 5 documents fictifs, sans clé ni réseau.
|
|
6
|
+
- Tests avec réponses HTTP simulées (respx) : recherche, document tronqué, 403, organisation introuvable/ambiguë, recherche vide, écritures, démo. Aucun réseau.
|
|
7
|
+
- README en anglais, licence MIT.
|
|
8
|
+
|
|
9
|
+
## À tester avec un vrai compte
|
|
10
|
+
1. Compte sur papra.app (ou demo.papra.app), clé API avec `documents:read` et `tags:read`.
|
|
11
|
+
2. `claude mcp add papra --env PAPRA_API_KEY=... -- uvx --from ./projets/papra-mcp papra-mcp`, puis une recherche et une lecture.
|
|
12
|
+
3. Avec `PAPRA_ALLOW_WRITE=1` et les permissions `documents:create`, `tags:create`, `documents:update` : un envoi et un étiquetage.
|
|
13
|
+
|
|
14
|
+
## Testé sur un vrai compte (20/11/2026)
|
|
15
|
+
- Formes JSON confirmées : `apiKey.permissions`, `organizations`, `documents` + `documentsCount`, `document`, `tags`.
|
|
16
|
+
- Écart corrigé : la liste des documents ne contient PAS le texte (`content`), seulement `GET /documents/:id`. La recherche renvoie donc les métadonnées (nom, dates, type, étiquettes) ; `summarize_by_tag` ouvre chaque document pour l'extrait.
|
|
17
|
+
- `searchQuery` filtre bien (requête absurde → 0 ; mot du nom → 1). Lecture d'un document : texte complet.
|
|
18
|
+
- Écritures (envoi, étiquetage) non testées en réel ; création d'étiquette envoyée en JSON.
|
|
19
|
+
|
|
20
|
+
## Points de vigilance
|
|
21
|
+
- **Formes des réponses JSON non vérifiées** : je n'ai pas pu appeler l'API réelle. J'ai supposé `{"documents": [...]}`, `{"document": {...}}`, `{"tags": [...]}`, `{"organizations": [...]}`, et pour `GET /api/api-keys/current` `{"apiKey": {"permissions": [...]}}` (ou `permissions` à la racine). Le texte extrait est lu dans le champ `content` ; l'étiquette dans `tags[].name`. À confirmer au premier essai, c'est le risque principal.
|
|
22
|
+
- Les écritures vérifient les permissions de la clé via `/api/api-keys/current` ; si cette route répond autrement, l'écriture échoue avec une erreur claire plutôt que de passer en silence.
|
|
23
|
+
- `get_document` renvoie le texte extrait, pas le fichier brut (`/file` non exposé, volontairement).
|
|
24
|
+
- Le SDK `mcp` 2.x a renommé FastMCP en `MCPServer` : j'ai épinglé `mcp>=1.2,<2`. Migration à prévoir plus tard.
|
|
25
|
+
- Risque produit : le mainteneur de Papra avait annoncé un MCP officiel (ticket #400). Concurrent `Rigare/papra-mcp` (même nom, non publié sur PyPI) : publier vite. Nom `papra-mcp` libre sur PyPI (vérifié le 13/11/2026, y compris `papramcp`).
|
|
26
|
+
- Projet non affilié à Papra : mentionné dans le README.
|
|
27
|
+
|
|
28
|
+
## Publication (après relecture)
|
|
29
|
+
```bash
|
|
30
|
+
cd projets/papra-mcp && python -m build && twine upload dist/* # paquet mcp-papra
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Nom PyPI
|
|
34
|
+
Le 20/11/2026 à 08:15 UTC, Rigare a publié `papra-mcp` 0.2.0 sur PyPI. Notre paquet s'appelle donc **`mcp-papra`** (commande `mcp-papra`, module `papra_mcp` inchangé). Le dossier du dépôt garde le nom `projets/papra-mcp`.
|
mcp_papra-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mcp-papra
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server for Papra: search, read and tag your documents from Claude. Read-only by default.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: documents,mcp,model-context-protocol,papra
|
|
8
|
+
Classifier: Environment :: Console
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Requires-Dist: httpx>=0.27
|
|
12
|
+
Requires-Dist: mcp<2,>=1.2
|
|
13
|
+
Provides-Extra: test
|
|
14
|
+
Requires-Dist: pytest; extra == 'test'
|
|
15
|
+
Requires-Dist: respx; extra == 'test'
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# mcp-papra
|
|
19
|
+
|
|
20
|
+
An MCP server that lets Claude search, read and tag the documents in your [Papra](https://papra.app) instance — read-only by default.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install mcp-papra # or run it without installing: uvx mcp-papra
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Create an API key in Papra (read permissions are enough), then set:
|
|
29
|
+
|
|
30
|
+
| Variable | Meaning |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `PAPRA_API_KEY` | API key (required unless demo mode) |
|
|
33
|
+
| `PAPRA_URL` | Papra API URL (default `https://api.papra.app`; use your own for self-hosted) |
|
|
34
|
+
| `PAPRA_ORGANIZATION_ID` | Organization id (optional if the key only sees one) |
|
|
35
|
+
| `PAPRA_ALLOW_WRITE=1` | Also expose `upload_document` and `tag_document` |
|
|
36
|
+
| `PAPRA_DEMO=1` | Fictional documents, no key and no network |
|
|
37
|
+
|
|
38
|
+
## Use with Claude Code
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
claude mcp add papra --env PAPRA_API_KEY=your_key -- uvx mcp-papra
|
|
42
|
+
# try it without any account:
|
|
43
|
+
claude mcp add papra-demo --env PAPRA_DEMO=1 -- uvx mcp-papra
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Use with Claude Desktop
|
|
47
|
+
|
|
48
|
+
In `claude_desktop_config.json`:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"mcpServers": {
|
|
53
|
+
"papra": {
|
|
54
|
+
"command": "uvx",
|
|
55
|
+
"args": ["mcp-papra"],
|
|
56
|
+
"env": { "PAPRA_API_KEY": "your_key" }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Tools
|
|
63
|
+
|
|
64
|
+
| Tool | Mode | What it does |
|
|
65
|
+
|---|---|---|
|
|
66
|
+
| `search_documents(query, limit)` | read | Search with Papra's advanced syntax (`tag:contract AND created:>2024`, `-has:tags`, …); returns metadata, not text |
|
|
67
|
+
| `get_document(document_id, max_chars)` | read | Metadata and extracted text, truncated to `max_chars` |
|
|
68
|
+
| `summarize_by_tag(tag, limit)` | read | Name and excerpt of each document with a tag (Papra has tags, not folders); Claude writes the summary |
|
|
69
|
+
| `upload_document(path, ocr_languages)` | write | Upload a local file |
|
|
70
|
+
| `tag_document(document_id, tag_name)` | write | Attach a tag, creating it if needed |
|
|
71
|
+
|
|
72
|
+
Write tools exist only when `PAPRA_ALLOW_WRITE=1`. This is an unofficial project, not affiliated with Papra.
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install -e ".[test]" && pytest # no network needed
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
MIT licensed.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# mcp-papra
|
|
2
|
+
|
|
3
|
+
An MCP server that lets Claude search, read and tag the documents in your [Papra](https://papra.app) instance — read-only by default.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install mcp-papra # or run it without installing: uvx mcp-papra
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Create an API key in Papra (read permissions are enough), then set:
|
|
12
|
+
|
|
13
|
+
| Variable | Meaning |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `PAPRA_API_KEY` | API key (required unless demo mode) |
|
|
16
|
+
| `PAPRA_URL` | Papra API URL (default `https://api.papra.app`; use your own for self-hosted) |
|
|
17
|
+
| `PAPRA_ORGANIZATION_ID` | Organization id (optional if the key only sees one) |
|
|
18
|
+
| `PAPRA_ALLOW_WRITE=1` | Also expose `upload_document` and `tag_document` |
|
|
19
|
+
| `PAPRA_DEMO=1` | Fictional documents, no key and no network |
|
|
20
|
+
|
|
21
|
+
## Use with Claude Code
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
claude mcp add papra --env PAPRA_API_KEY=your_key -- uvx mcp-papra
|
|
25
|
+
# try it without any account:
|
|
26
|
+
claude mcp add papra-demo --env PAPRA_DEMO=1 -- uvx mcp-papra
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Use with Claude Desktop
|
|
30
|
+
|
|
31
|
+
In `claude_desktop_config.json`:
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"mcpServers": {
|
|
36
|
+
"papra": {
|
|
37
|
+
"command": "uvx",
|
|
38
|
+
"args": ["mcp-papra"],
|
|
39
|
+
"env": { "PAPRA_API_KEY": "your_key" }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Tools
|
|
46
|
+
|
|
47
|
+
| Tool | Mode | What it does |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| `search_documents(query, limit)` | read | Search with Papra's advanced syntax (`tag:contract AND created:>2024`, `-has:tags`, …); returns metadata, not text |
|
|
50
|
+
| `get_document(document_id, max_chars)` | read | Metadata and extracted text, truncated to `max_chars` |
|
|
51
|
+
| `summarize_by_tag(tag, limit)` | read | Name and excerpt of each document with a tag (Papra has tags, not folders); Claude writes the summary |
|
|
52
|
+
| `upload_document(path, ocr_languages)` | write | Upload a local file |
|
|
53
|
+
| `tag_document(document_id, tag_name)` | write | Attach a tag, creating it if needed |
|
|
54
|
+
|
|
55
|
+
Write tools exist only when `PAPRA_ALLOW_WRITE=1`. This is an unofficial project, not affiliated with Papra.
|
|
56
|
+
|
|
57
|
+
## Development
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install -e ".[test]" && pytest # no network needed
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
MIT licensed.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mcp-papra"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "MCP server for Papra: search, read and tag your documents from Claude. Read-only by default."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = ["mcp>=1.2,<2", "httpx>=0.27"]
|
|
14
|
+
keywords = ["mcp", "papra", "documents", "model-context-protocol"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
test = ["pytest", "respx"]
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
mcp-papra = "papra_mcp.server:main"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/papra_mcp"]
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.sdist]
|
|
30
|
+
include = ["src", "tests", "README.md", "LICENSE", "NOTES-FR.md"]
|
|
31
|
+
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Thin HTTP client for the Papra REST API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import mimetypes
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
DEFAULT_URL = "https://api.papra.app"
|
|
14
|
+
DEFAULT_TAG_COLOR = "#6b7280"
|
|
15
|
+
|
|
16
|
+
# httpx logs every request at INFO (with the organization id): keep it quiet.
|
|
17
|
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PapraError(Exception):
|
|
21
|
+
"""Error with a message that is safe and clear to show to the agent."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PapraClient:
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
api_key: str,
|
|
28
|
+
base_url: str = DEFAULT_URL,
|
|
29
|
+
organization_id: str | None = None,
|
|
30
|
+
transport: httpx.BaseTransport | None = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
if not api_key:
|
|
33
|
+
raise PapraError(
|
|
34
|
+
"PAPRA_API_KEY is not set. Create an API key in Papra "
|
|
35
|
+
"(or set PAPRA_DEMO=1 to try the demo mode)."
|
|
36
|
+
)
|
|
37
|
+
self._org = organization_id or None
|
|
38
|
+
self._permissions: set[str] | None = None
|
|
39
|
+
self._http = httpx.Client(
|
|
40
|
+
base_url=base_url.rstrip("/"),
|
|
41
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
42
|
+
timeout=30.0,
|
|
43
|
+
transport=transport,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# -- low level -------------------------------------------------------
|
|
47
|
+
def _request(self, method: str, path: str, **kw: Any) -> httpx.Response:
|
|
48
|
+
try:
|
|
49
|
+
resp = self._http.request(method, path, **kw)
|
|
50
|
+
except httpx.HTTPError as exc:
|
|
51
|
+
raise PapraError(f"Cannot reach Papra: {exc.__class__.__name__}") from exc
|
|
52
|
+
if resp.status_code == 401:
|
|
53
|
+
raise PapraError("Papra rejected the API key (401). Check PAPRA_API_KEY.")
|
|
54
|
+
if resp.status_code == 403:
|
|
55
|
+
raise PapraError(
|
|
56
|
+
"Permission denied (403). The API key lacks the permission needed "
|
|
57
|
+
"for this action (e.g. documents:read, documents:create, tags:create)."
|
|
58
|
+
)
|
|
59
|
+
if resp.status_code == 404:
|
|
60
|
+
raise PapraError("Not found (404): wrong organization, document or tag id.")
|
|
61
|
+
if resp.status_code >= 400:
|
|
62
|
+
raise PapraError(f"Papra API error {resp.status_code}.")
|
|
63
|
+
return resp
|
|
64
|
+
|
|
65
|
+
def _json(self, method: str, path: str, **kw: Any) -> Any:
|
|
66
|
+
resp = self._request(method, path, **kw)
|
|
67
|
+
if not resp.content:
|
|
68
|
+
return {}
|
|
69
|
+
return resp.json()
|
|
70
|
+
|
|
71
|
+
# -- organization ----------------------------------------------------
|
|
72
|
+
def organization_id(self) -> str:
|
|
73
|
+
if self._org:
|
|
74
|
+
return self._org
|
|
75
|
+
data = self._json("GET", "/api/organizations")
|
|
76
|
+
orgs = data.get("organizations", [])
|
|
77
|
+
if len(orgs) == 1:
|
|
78
|
+
self._org = orgs[0]["id"]
|
|
79
|
+
return self._org
|
|
80
|
+
if not orgs:
|
|
81
|
+
raise PapraError("This API key has access to no organization.")
|
|
82
|
+
names = ", ".join(f"{o.get('name', '?')} ({o['id']})" for o in orgs)
|
|
83
|
+
raise PapraError(
|
|
84
|
+
f"Several organizations found: {names}. Set PAPRA_ORGANIZATION_ID."
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def _org_path(self, suffix: str) -> str:
|
|
88
|
+
return f"/api/organizations/{self.organization_id()}{suffix}"
|
|
89
|
+
|
|
90
|
+
# -- permissions -----------------------------------------------------
|
|
91
|
+
def permissions(self) -> set[str]:
|
|
92
|
+
if self._permissions is None:
|
|
93
|
+
data = self._json("GET", "/api/api-keys/current")
|
|
94
|
+
key = data.get("apiKey", data)
|
|
95
|
+
self._permissions = set(key.get("permissions", []))
|
|
96
|
+
return self._permissions
|
|
97
|
+
|
|
98
|
+
def require(self, permission: str) -> None:
|
|
99
|
+
if permission not in self.permissions():
|
|
100
|
+
raise PapraError(
|
|
101
|
+
f"The API key does not have the '{permission}' permission. "
|
|
102
|
+
"Create a key with it in Papra."
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# -- documents -------------------------------------------------------
|
|
106
|
+
def search_documents(self, query: str, limit: int) -> list[dict]:
|
|
107
|
+
params: dict[str, Any] = {"pageIndex": 0, "pageSize": limit}
|
|
108
|
+
if query.strip():
|
|
109
|
+
params["searchQuery"] = query
|
|
110
|
+
data = self._json("GET", self._org_path("/documents"), params=params)
|
|
111
|
+
return data.get("documents", [])
|
|
112
|
+
|
|
113
|
+
def get_document(self, document_id: str) -> dict:
|
|
114
|
+
data = self._json("GET", self._org_path(f"/documents/{document_id}"))
|
|
115
|
+
return data.get("document", data)
|
|
116
|
+
|
|
117
|
+
def upload_document(self, path: str, ocr_languages: list[str] | None) -> dict:
|
|
118
|
+
p = Path(path).expanduser()
|
|
119
|
+
if not p.is_file():
|
|
120
|
+
raise PapraError(f"File not found: {path}")
|
|
121
|
+
mime = mimetypes.guess_type(p.name)[0] or "application/octet-stream"
|
|
122
|
+
data = {"ocrLanguages": ",".join(ocr_languages)} if ocr_languages else None
|
|
123
|
+
with p.open("rb") as fh:
|
|
124
|
+
result = self._json(
|
|
125
|
+
"POST",
|
|
126
|
+
self._org_path("/documents"),
|
|
127
|
+
files={"file": (p.name, fh, mime)},
|
|
128
|
+
data=data,
|
|
129
|
+
)
|
|
130
|
+
return result.get("document", result)
|
|
131
|
+
|
|
132
|
+
# -- tags ------------------------------------------------------------
|
|
133
|
+
def list_tags(self) -> list[dict]:
|
|
134
|
+
return self._json("GET", self._org_path("/tags")).get("tags", [])
|
|
135
|
+
|
|
136
|
+
def create_tag(self, name: str, color: str = DEFAULT_TAG_COLOR) -> dict:
|
|
137
|
+
data = self._json(
|
|
138
|
+
"POST", self._org_path("/tags"), json={"name": name, "color": color}
|
|
139
|
+
)
|
|
140
|
+
return data.get("tag", data)
|
|
141
|
+
|
|
142
|
+
def add_tag(self, document_id: str, tag_id: str) -> None:
|
|
143
|
+
self._request(
|
|
144
|
+
"POST",
|
|
145
|
+
self._org_path(f"/documents/{document_id}/tags"),
|
|
146
|
+
json={"tagId": tag_id},
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def client_from_env(env: dict[str, str] | None = None) -> PapraClient:
|
|
151
|
+
env = os.environ if env is None else env
|
|
152
|
+
return PapraClient(
|
|
153
|
+
api_key=env.get("PAPRA_API_KEY", ""),
|
|
154
|
+
base_url=env.get("PAPRA_URL", DEFAULT_URL),
|
|
155
|
+
organization_id=env.get("PAPRA_ORGANIZATION_ID"),
|
|
156
|
+
)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""In-memory fake backend for PAPRA_DEMO=1 (fictional documents, no network)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from .client import DEFAULT_TAG_COLOR, PapraError
|
|
8
|
+
|
|
9
|
+
_DOCS = [
|
|
10
|
+
{"id": "doc_demo_1", "name": "Invoice ACME 2025-03.pdf", "createdAt": "2025-03-04",
|
|
11
|
+
"tags": ["invoice"], "content": "Invoice 2025-03 from ACME Corp. Total due: 1,200.00 EUR. Payment within 30 days."},
|
|
12
|
+
{"id": "doc_demo_2", "name": "Invoice Globex 2025-04.pdf", "createdAt": "2025-04-11",
|
|
13
|
+
"tags": ["invoice"], "content": "Invoice 2025-04 from Globex. Total due: 480.00 EUR. Bank transfer."},
|
|
14
|
+
{"id": "doc_demo_3", "name": "Service contract Initech.pdf", "createdAt": "2024-09-01",
|
|
15
|
+
"tags": ["contract"], "content": "Service contract with Initech. Duration: 12 months, renewable. Notice period: 3 months."},
|
|
16
|
+
{"id": "doc_demo_4", "name": "Office lease.pdf", "createdAt": "2023-01-15",
|
|
17
|
+
"tags": ["contract"], "content": "Commercial lease for the office. Monthly rent: 900 EUR. Term: 3 years."},
|
|
18
|
+
{"id": "doc_demo_5", "name": "Meeting notes.txt", "createdAt": "2025-05-02",
|
|
19
|
+
"tags": [], "content": "Notes of the May meeting: budget review, hiring plan, tool migration."},
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class DemoClient:
|
|
24
|
+
def __init__(self) -> None:
|
|
25
|
+
self._docs = [dict(d, tags=list(d["tags"])) for d in _DOCS]
|
|
26
|
+
self._tags = {"invoice": "tag_1", "contract": "tag_2"}
|
|
27
|
+
|
|
28
|
+
def permissions(self) -> set[str]:
|
|
29
|
+
return {"documents:read", "tags:read", "documents:create", "tags:create", "documents:update"}
|
|
30
|
+
|
|
31
|
+
def require(self, permission: str) -> None:
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
@staticmethod
|
|
35
|
+
def _public(d: dict) -> dict:
|
|
36
|
+
return {k: v for k, v in d.items()}
|
|
37
|
+
|
|
38
|
+
def search_documents(self, query: str, limit: int) -> list[dict]:
|
|
39
|
+
words = [w.lower() for w in re.sub(r'(\w+:)\s*"([^"]*)"', r"\1\2", query).replace('"', " ").split()
|
|
40
|
+
if w.upper() not in {"AND", "OR", "NOT"}]
|
|
41
|
+
out = []
|
|
42
|
+
for d in self._docs:
|
|
43
|
+
hay = (d["name"] + " " + d["content"] + " " + " ".join(d["tags"])).lower()
|
|
44
|
+
ok = True
|
|
45
|
+
for w in words:
|
|
46
|
+
if w.startswith("tag:"):
|
|
47
|
+
ok = ok and w[4:] in [t.lower() for t in d["tags"]]
|
|
48
|
+
elif ":" in w:
|
|
49
|
+
w = w.split(":", 1)[1]
|
|
50
|
+
ok = ok and w in hay
|
|
51
|
+
else:
|
|
52
|
+
ok = ok and w in hay
|
|
53
|
+
if ok:
|
|
54
|
+
# Like the real API, the list carries no extracted text.
|
|
55
|
+
out.append({k: v for k, v in d.items() if k != "content"})
|
|
56
|
+
return out[:limit]
|
|
57
|
+
|
|
58
|
+
def get_document(self, document_id: str) -> dict:
|
|
59
|
+
for d in self._docs:
|
|
60
|
+
if d["id"] == document_id:
|
|
61
|
+
return self._public(d)
|
|
62
|
+
raise PapraError("Not found (404): wrong organization, document or tag id.")
|
|
63
|
+
|
|
64
|
+
def upload_document(self, path: str, ocr_languages: list[str] | None) -> dict:
|
|
65
|
+
raise PapraError("Upload is disabled in demo mode.")
|
|
66
|
+
|
|
67
|
+
def list_tags(self) -> list[dict]:
|
|
68
|
+
return [{"id": i, "name": n} for n, i in self._tags.items()]
|
|
69
|
+
|
|
70
|
+
def create_tag(self, name: str, color: str = DEFAULT_TAG_COLOR) -> dict:
|
|
71
|
+
tag_id = f"tag_{len(self._tags) + 1}"
|
|
72
|
+
self._tags[name] = tag_id
|
|
73
|
+
return {"id": tag_id, "name": name}
|
|
74
|
+
|
|
75
|
+
def add_tag(self, document_id: str, tag_id: str) -> None:
|
|
76
|
+
name = next((n for n, i in self._tags.items() if i == tag_id), None)
|
|
77
|
+
doc = next((d for d in self._docs if d["id"] == document_id), None)
|
|
78
|
+
if doc is None or name is None:
|
|
79
|
+
raise PapraError("Not found (404): wrong organization, document or tag id.")
|
|
80
|
+
if name not in doc["tags"]:
|
|
81
|
+
doc["tags"].append(name)
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""FastMCP server exposing a small, well-described set of Papra tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from mcp.server.fastmcp import FastMCP
|
|
9
|
+
|
|
10
|
+
from .client import PapraClient, PapraError, client_from_env
|
|
11
|
+
from .demo import DemoClient
|
|
12
|
+
|
|
13
|
+
SNIPPET_CHARS = 300
|
|
14
|
+
|
|
15
|
+
SEARCH_SYNTAX = (
|
|
16
|
+
"Advanced syntax: plain words search names and content; "
|
|
17
|
+
"name:invoice, content:\"unpaid\", tag:contract, created:>2024, date:>2024-06, "
|
|
18
|
+
"has:tags, -has:tags (no tag); combine with AND, OR, NOT and double quotes "
|
|
19
|
+
"for exact phrases. Empty query lists the most recent documents."
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _truthy(value: str | None) -> bool:
|
|
24
|
+
return (value or "").strip().lower() in {"1", "true", "yes", "on"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _tag_names(doc: dict) -> list[str]:
|
|
28
|
+
return [t["name"] if isinstance(t, dict) else str(t) for t in doc.get("tags", [])]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _snippet(doc: dict, size: int = SNIPPET_CHARS) -> str:
|
|
32
|
+
text = " ".join((doc.get("content") or "").split())
|
|
33
|
+
return text[:size] + ("…" if len(text) > size else "")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _summary(doc: dict) -> dict:
|
|
37
|
+
# Papra's document list carries no extracted text; get_document returns it.
|
|
38
|
+
out = {
|
|
39
|
+
"id": doc.get("id"),
|
|
40
|
+
"name": doc.get("name"),
|
|
41
|
+
"created_at": doc.get("createdAt"),
|
|
42
|
+
"document_date": doc.get("documentDate"),
|
|
43
|
+
"mime_type": doc.get("mimeType"),
|
|
44
|
+
"tags": _tag_names(doc),
|
|
45
|
+
}
|
|
46
|
+
if doc.get("content"):
|
|
47
|
+
out["snippet"] = _snippet(doc)
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def build_server(client: Any, allow_write: bool = False) -> FastMCP:
|
|
52
|
+
mcp = FastMCP("papra")
|
|
53
|
+
|
|
54
|
+
@mcp.tool(
|
|
55
|
+
description="Search Papra documents. " + SEARCH_SYNTAX
|
|
56
|
+
+ " Returns id, name, dates, file type and tags (no text: call get_document"
|
|
57
|
+
" for a document's text). Read-only."
|
|
58
|
+
)
|
|
59
|
+
def search_documents(query: str = "", limit: int = 10) -> list[dict] | dict:
|
|
60
|
+
try:
|
|
61
|
+
limit = max(1, min(limit, 50))
|
|
62
|
+
docs = client.search_documents(query, limit)
|
|
63
|
+
except PapraError as exc:
|
|
64
|
+
return {"error": str(exc)}
|
|
65
|
+
if not docs:
|
|
66
|
+
return {"results": [], "message": "No document matches this query."}
|
|
67
|
+
return [_summary(d) for d in docs]
|
|
68
|
+
|
|
69
|
+
@mcp.tool()
|
|
70
|
+
def get_document(document_id: str, max_chars: int = 5000) -> dict:
|
|
71
|
+
"""Get one document's metadata and extracted text, truncated to max_chars
|
|
72
|
+
characters (a `truncated` flag tells if text was cut). Read-only."""
|
|
73
|
+
try:
|
|
74
|
+
doc = client.get_document(document_id)
|
|
75
|
+
except PapraError as exc:
|
|
76
|
+
return {"error": str(exc)}
|
|
77
|
+
max_chars = max(100, max_chars)
|
|
78
|
+
text = doc.get("content") or ""
|
|
79
|
+
return {
|
|
80
|
+
"id": doc.get("id"),
|
|
81
|
+
"name": doc.get("name"),
|
|
82
|
+
"created_at": doc.get("createdAt"),
|
|
83
|
+
"tags": _tag_names(doc),
|
|
84
|
+
"text": text[:max_chars],
|
|
85
|
+
"truncated": len(text) > max_chars,
|
|
86
|
+
"total_chars": len(text),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
@mcp.tool()
|
|
90
|
+
def summarize_by_tag(tag: str, limit: int = 10) -> dict:
|
|
91
|
+
"""List the documents carrying a tag (Papra has no folders, tags are the
|
|
92
|
+
way to group documents): name and text excerpt of each. This server calls
|
|
93
|
+
no model: summarize the excerpts yourself. Read-only."""
|
|
94
|
+
try:
|
|
95
|
+
limit = max(1, min(limit, 30))
|
|
96
|
+
safe = tag.replace('"', "")
|
|
97
|
+
docs = client.search_documents(f'tag:"{safe}"', limit)
|
|
98
|
+
# The list has no text: fetch each document for its excerpt.
|
|
99
|
+
docs = [d if d.get("content") else client.get_document(d["id"]) for d in docs]
|
|
100
|
+
except PapraError as exc:
|
|
101
|
+
return {"error": str(exc)}
|
|
102
|
+
return {
|
|
103
|
+
"tag": tag,
|
|
104
|
+
"count": len(docs),
|
|
105
|
+
"documents": [
|
|
106
|
+
{"id": d.get("id"), "name": d.get("name"), "excerpt": _snippet(d, 600)}
|
|
107
|
+
for d in docs
|
|
108
|
+
],
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if allow_write:
|
|
112
|
+
|
|
113
|
+
@mcp.tool()
|
|
114
|
+
def upload_document(path: str, ocr_languages: list[str] | None = None) -> dict:
|
|
115
|
+
"""WRITE. Upload a local file to Papra (path on the machine running
|
|
116
|
+
this server). ocr_languages is optional, e.g. ["eng", "fra"]."""
|
|
117
|
+
try:
|
|
118
|
+
client.require("documents:create")
|
|
119
|
+
doc = client.upload_document(path, ocr_languages)
|
|
120
|
+
except PapraError as exc:
|
|
121
|
+
return {"error": str(exc)}
|
|
122
|
+
return {"uploaded": True, "id": doc.get("id"), "name": doc.get("name")}
|
|
123
|
+
|
|
124
|
+
@mcp.tool()
|
|
125
|
+
def tag_document(document_id: str, tag_name: str) -> dict:
|
|
126
|
+
"""WRITE. Attach a tag to a document; the tag is created (grey) if it
|
|
127
|
+
does not exist yet."""
|
|
128
|
+
try:
|
|
129
|
+
tags = client.list_tags()
|
|
130
|
+
tag = next((t for t in tags if t["name"].lower() == tag_name.lower()), None)
|
|
131
|
+
created = False
|
|
132
|
+
if tag is None:
|
|
133
|
+
client.require("tags:create")
|
|
134
|
+
tag = client.create_tag(tag_name)
|
|
135
|
+
created = True
|
|
136
|
+
client.add_tag(document_id, tag["id"])
|
|
137
|
+
except PapraError as exc:
|
|
138
|
+
return {"error": str(exc)}
|
|
139
|
+
return {"tagged": True, "document_id": document_id,
|
|
140
|
+
"tag": tag["name"], "tag_created": created}
|
|
141
|
+
|
|
142
|
+
return mcp
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def create_app(env: dict[str, str] | None = None) -> FastMCP:
|
|
146
|
+
env = dict(os.environ) if env is None else env
|
|
147
|
+
if _truthy(env.get("PAPRA_DEMO")):
|
|
148
|
+
return build_server(DemoClient(), allow_write=_truthy(env.get("PAPRA_ALLOW_WRITE")))
|
|
149
|
+
client: PapraClient = client_from_env(env)
|
|
150
|
+
return build_server(client, allow_write=_truthy(env.get("PAPRA_ALLOW_WRITE")))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def main() -> None:
|
|
154
|
+
try:
|
|
155
|
+
app = create_app()
|
|
156
|
+
except PapraError as exc:
|
|
157
|
+
raise SystemExit(str(exc))
|
|
158
|
+
app.run()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
if __name__ == "__main__":
|
|
162
|
+
main()
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
import pytest
|
|
6
|
+
import respx
|
|
7
|
+
|
|
8
|
+
from papra_mcp.client import PapraClient, PapraError
|
|
9
|
+
from papra_mcp.demo import DemoClient
|
|
10
|
+
from papra_mcp.server import build_server, create_app
|
|
11
|
+
|
|
12
|
+
BASE = "https://papra.test"
|
|
13
|
+
ORG = f"{BASE}/api/organizations/org1"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def client(**kw):
|
|
17
|
+
return PapraClient("key", BASE, organization_id=kw.pop("org", "org1"), **kw)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def call(server, name, **args):
|
|
21
|
+
result = asyncio.run(server.call_tool(name, args))
|
|
22
|
+
content = result[0] if isinstance(result, tuple) else result
|
|
23
|
+
if isinstance(result, tuple):
|
|
24
|
+
return result[1].get("result", result[1])
|
|
25
|
+
return json.loads(content[0].text)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def tool_names(server):
|
|
29
|
+
return {t.name for t in asyncio.run(server.list_tools())}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
DOC = {"id": "d1", "name": "a.pdf", "createdAt": "2025-01-01",
|
|
33
|
+
"tags": [{"id": "t1", "name": "invoice"}], "content": "hello " * 2000}
|
|
34
|
+
# The real list endpoint returns documents without their extracted text.
|
|
35
|
+
LISTED = {k: v for k, v in DOC.items() if k != "content"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@respx.mock
|
|
39
|
+
def test_search_returns_summaries_and_sends_query():
|
|
40
|
+
route = respx.get(f"{ORG}/documents").respond(200, json={"documents": [LISTED]})
|
|
41
|
+
out = call(build_server(client()), "search_documents", query="tag:invoice", limit=5)
|
|
42
|
+
assert route.calls[0].request.url.params["searchQuery"] == "tag:invoice"
|
|
43
|
+
assert out[0]["id"] == "d1" and out[0]["tags"] == ["invoice"]
|
|
44
|
+
assert "snippet" not in out[0]
|
|
45
|
+
assert respx.calls[0].request.headers["authorization"] == "Bearer key"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@respx.mock
|
|
49
|
+
def test_empty_search():
|
|
50
|
+
respx.get(f"{ORG}/documents").respond(200, json={"documents": []})
|
|
51
|
+
out = call(build_server(client()), "search_documents", query="zzz")
|
|
52
|
+
assert out["results"] == []
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@respx.mock
|
|
56
|
+
def test_get_document_truncated():
|
|
57
|
+
respx.get(f"{ORG}/documents/d1").respond(200, json={"document": DOC})
|
|
58
|
+
out = call(build_server(client()), "get_document", document_id="d1", max_chars=200)
|
|
59
|
+
assert out["truncated"] is True and len(out["text"]) == 200
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@respx.mock
|
|
63
|
+
def test_403_gives_clear_error():
|
|
64
|
+
respx.get(f"{ORG}/documents").respond(403)
|
|
65
|
+
out = call(build_server(client()), "search_documents", query="x")
|
|
66
|
+
assert "403" in out["error"] and "permission" in out["error"].lower()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@respx.mock
|
|
70
|
+
def test_unknown_organization():
|
|
71
|
+
respx.get(f"{BASE}/api/organizations/nope/documents").respond(404)
|
|
72
|
+
out = call(build_server(client(org="nope")), "search_documents")
|
|
73
|
+
assert "404" in out["error"]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@respx.mock
|
|
77
|
+
def test_organization_auto_detected_and_ambiguous():
|
|
78
|
+
respx.get(f"{BASE}/api/organizations").respond(200, json={"organizations": [{"id": "org1", "name": "A"}]})
|
|
79
|
+
assert PapraClient("k", BASE).organization_id() == "org1"
|
|
80
|
+
respx.get(f"{BASE}/api/organizations").respond(
|
|
81
|
+
200, json={"organizations": [{"id": "o1", "name": "A"}, {"id": "o2", "name": "B"}]})
|
|
82
|
+
with pytest.raises(PapraError, match="PAPRA_ORGANIZATION_ID"):
|
|
83
|
+
PapraClient("k", BASE).organization_id()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@respx.mock
|
|
87
|
+
def test_summarize_by_tag():
|
|
88
|
+
route = respx.get(f"{ORG}/documents").respond(200, json={"documents": [LISTED]})
|
|
89
|
+
respx.get(f"{ORG}/documents/d1").respond(200, json={"document": DOC})
|
|
90
|
+
out = call(build_server(client()), "summarize_by_tag", tag="invoice")
|
|
91
|
+
assert route.calls[0].request.url.params["searchQuery"] == 'tag:"invoice"'
|
|
92
|
+
assert out["count"] == 1 and out["documents"][0]["name"] == "a.pdf"
|
|
93
|
+
assert out["documents"][0]["excerpt"].startswith("hello")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_read_only_by_default():
|
|
97
|
+
names = tool_names(build_server(client()))
|
|
98
|
+
assert names == {"search_documents", "get_document", "summarize_by_tag"}
|
|
99
|
+
assert tool_names(build_server(client(), allow_write=True)) >= {"upload_document", "tag_document"}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@respx.mock
|
|
103
|
+
def test_tag_document_creates_missing_tag():
|
|
104
|
+
respx.get(f"{BASE}/api/api-keys/current").respond(200, json={"apiKey": {"permissions": ["tags:create"]}})
|
|
105
|
+
respx.get(f"{ORG}/tags").respond(200, json={"tags": []})
|
|
106
|
+
create = respx.post(f"{ORG}/tags").respond(200, json={"tag": {"id": "t9", "name": "new"}})
|
|
107
|
+
link = respx.post(f"{ORG}/documents/d1/tags").respond(204)
|
|
108
|
+
out = call(build_server(client(), allow_write=True), "tag_document", document_id="d1", tag_name="new")
|
|
109
|
+
assert out["tag_created"] is True
|
|
110
|
+
assert b"color" in create.calls[0].request.content
|
|
111
|
+
assert json.loads(link.calls[0].request.content) == {"tagId": "t9"}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@respx.mock
|
|
115
|
+
def test_tag_document_without_permission():
|
|
116
|
+
respx.get(f"{BASE}/api/api-keys/current").respond(200, json={"apiKey": {"permissions": ["tags:read"]}})
|
|
117
|
+
respx.get(f"{ORG}/tags").respond(200, json={"tags": []})
|
|
118
|
+
out = call(build_server(client(), allow_write=True), "tag_document", document_id="d1", tag_name="new")
|
|
119
|
+
assert "tags:create" in out["error"]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@respx.mock
|
|
123
|
+
def test_upload(tmp_path):
|
|
124
|
+
f = tmp_path / "x.txt"
|
|
125
|
+
f.write_text("hi")
|
|
126
|
+
respx.get(f"{BASE}/api/api-keys/current").respond(200, json={"permissions": ["documents:create"]})
|
|
127
|
+
respx.post(f"{ORG}/documents").respond(200, json={"document": {"id": "n1", "name": "x.txt"}})
|
|
128
|
+
out = call(build_server(client(), allow_write=True), "upload_document", path=str(f))
|
|
129
|
+
assert out == {"uploaded": True, "id": "n1", "name": "x.txt"}
|
|
130
|
+
out = call(build_server(client(), allow_write=True), "upload_document", path=str(tmp_path / "no"))
|
|
131
|
+
assert "not found" in out["error"].lower()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_demo_mode_no_key_no_network():
|
|
135
|
+
app = create_app({"PAPRA_DEMO": "1"})
|
|
136
|
+
out = call(app, "search_documents", query="tag:contract")
|
|
137
|
+
assert {d["id"] for d in out} == {"doc_demo_3", "doc_demo_4"}
|
|
138
|
+
assert call(app, "get_document", document_id="doc_demo_1")["text"].startswith("Invoice")
|
|
139
|
+
assert call(app, "summarize_by_tag", tag="invoice")["count"] == 2
|
|
140
|
+
assert tool_names(app) == {"search_documents", "get_document", "summarize_by_tag"}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_demo_write_mode():
|
|
144
|
+
app = create_app({"PAPRA_DEMO": "1", "PAPRA_ALLOW_WRITE": "1"})
|
|
145
|
+
assert call(app, "tag_document", document_id="doc_demo_5", tag_name="notes")["tagged"]
|
|
146
|
+
assert call(app, "summarize_by_tag", tag="notes")["count"] == 1
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def test_missing_key_error():
|
|
150
|
+
with pytest.raises(PapraError, match="PAPRA_API_KEY"):
|
|
151
|
+
create_app({})
|