mcp-server-paperless 0.2.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.
Files changed (110) hide show
  1. mcp_server_paperless/__init__.py +6 -0
  2. mcp_server_paperless/__main__.py +5 -0
  3. mcp_server_paperless/app.py +505 -0
  4. mcp_server_paperless/cli.py +86 -0
  5. mcp_server_paperless/domain/__init__.py +4 -0
  6. mcp_server_paperless/domain/admin.py +444 -0
  7. mcp_server_paperless/domain/ai.py +94 -0
  8. mcp_server_paperless/domain/bulk.py +353 -0
  9. mcp_server_paperless/domain/credentials.py +25 -0
  10. mcp_server_paperless/domain/documents.py +654 -0
  11. mcp_server_paperless/domain/errors.py +144 -0
  12. mcp_server_paperless/domain/instance.py +86 -0
  13. mcp_server_paperless/domain/mail.py +409 -0
  14. mcp_server_paperless/domain/pdf.py +153 -0
  15. mcp_server_paperless/domain/permissions.py +206 -0
  16. mcp_server_paperless/domain/ports.py +1289 -0
  17. mcp_server_paperless/domain/raw.py +51 -0
  18. mcp_server_paperless/domain/sharing.py +156 -0
  19. mcp_server_paperless/domain/tasks.py +72 -0
  20. mcp_server_paperless/domain/taxonomy.py +176 -0
  21. mcp_server_paperless/domain/taxonomy_edits.py +49 -0
  22. mcp_server_paperless/domain/toolsets.py +6 -0
  23. mcp_server_paperless/domain/trash.py +91 -0
  24. mcp_server_paperless/domain/versions.py +142 -0
  25. mcp_server_paperless/domain/views.py +209 -0
  26. mcp_server_paperless/domain/workflows.py +526 -0
  27. mcp_server_paperless/observability.py +176 -0
  28. mcp_server_paperless/paperless/__init__.py +1 -0
  29. mcp_server_paperless/paperless/admin.py +594 -0
  30. mcp_server_paperless/paperless/ai.py +139 -0
  31. mcp_server_paperless/paperless/auth.py +27 -0
  32. mcp_server_paperless/paperless/bulk.py +174 -0
  33. mcp_server_paperless/paperless/client.py +466 -0
  34. mcp_server_paperless/paperless/disposition.py +66 -0
  35. mcp_server_paperless/paperless/documents.py +702 -0
  36. mcp_server_paperless/paperless/errors.py +143 -0
  37. mcp_server_paperless/paperless/instance.py +144 -0
  38. mcp_server_paperless/paperless/mail.py +509 -0
  39. mcp_server_paperless/paperless/pagination.py +91 -0
  40. mcp_server_paperless/paperless/pdf.py +383 -0
  41. mcp_server_paperless/paperless/permissions.py +228 -0
  42. mcp_server_paperless/paperless/queued.py +156 -0
  43. mcp_server_paperless/paperless/raw.py +54 -0
  44. mcp_server_paperless/paperless/sharing.py +300 -0
  45. mcp_server_paperless/paperless/tasks.py +73 -0
  46. mcp_server_paperless/paperless/taxonomy.py +260 -0
  47. mcp_server_paperless/paperless/trash.py +122 -0
  48. mcp_server_paperless/paperless/views.py +131 -0
  49. mcp_server_paperless/paperless/workflows.py +153 -0
  50. mcp_server_paperless/server.py +488 -0
  51. mcp_server_paperless/services/__init__.py +1 -0
  52. mcp_server_paperless/services/admin_accounts.py +486 -0
  53. mcp_server_paperless/services/admin_system.py +354 -0
  54. mcp_server_paperless/services/ai.py +97 -0
  55. mcp_server_paperless/services/bulk_documents.py +620 -0
  56. mcp_server_paperless/services/bulk_taxonomy.py +237 -0
  57. mcp_server_paperless/services/custom_values.py +236 -0
  58. mcp_server_paperless/services/document_edits.py +427 -0
  59. mcp_server_paperless/services/documents.py +347 -0
  60. mcp_server_paperless/services/files.py +138 -0
  61. mcp_server_paperless/services/filter_rules.py +310 -0
  62. mcp_server_paperless/services/instance.py +42 -0
  63. mcp_server_paperless/services/mail.py +855 -0
  64. mcp_server_paperless/services/notes.py +81 -0
  65. mcp_server_paperless/services/page_ranges.py +87 -0
  66. mcp_server_paperless/services/pdf.py +598 -0
  67. mcp_server_paperless/services/permissions.py +613 -0
  68. mcp_server_paperless/services/principals.py +73 -0
  69. mcp_server_paperless/services/raw.py +287 -0
  70. mcp_server_paperless/services/removal.py +58 -0
  71. mcp_server_paperless/services/sharing.py +460 -0
  72. mcp_server_paperless/services/tag_hierarchy.py +57 -0
  73. mcp_server_paperless/services/task_outcome.py +77 -0
  74. mcp_server_paperless/services/tasks.py +78 -0
  75. mcp_server_paperless/services/taxonomy.py +150 -0
  76. mcp_server_paperless/services/taxonomy_edits.py +385 -0
  77. mcp_server_paperless/services/trash.py +263 -0
  78. mcp_server_paperless/services/upload_source.py +235 -0
  79. mcp_server_paperless/services/upload_types.py +138 -0
  80. mcp_server_paperless/services/uploads.py +198 -0
  81. mcp_server_paperless/services/version_uploads.py +121 -0
  82. mcp_server_paperless/services/versions.py +296 -0
  83. mcp_server_paperless/services/views.py +304 -0
  84. mcp_server_paperless/services/workflows.py +703 -0
  85. mcp_server_paperless/settings.py +430 -0
  86. mcp_server_paperless/tools/__init__.py +1 -0
  87. mcp_server_paperless/tools/_shared.py +959 -0
  88. mcp_server_paperless/tools/admin.py +569 -0
  89. mcp_server_paperless/tools/ai.py +67 -0
  90. mcp_server_paperless/tools/bulk.py +120 -0
  91. mcp_server_paperless/tools/core.py +792 -0
  92. mcp_server_paperless/tools/mail.py +529 -0
  93. mcp_server_paperless/tools/pdf.py +326 -0
  94. mcp_server_paperless/tools/permissions.py +181 -0
  95. mcp_server_paperless/tools/prompts.py +211 -0
  96. mcp_server_paperless/tools/raw.py +49 -0
  97. mcp_server_paperless/tools/selection.py +84 -0
  98. mcp_server_paperless/tools/sharing.py +245 -0
  99. mcp_server_paperless/tools/trash.py +115 -0
  100. mcp_server_paperless/tools/upload.py +126 -0
  101. mcp_server_paperless/tools/upload_stdio.py +107 -0
  102. mcp_server_paperless/tools/versions.py +201 -0
  103. mcp_server_paperless/tools/versions_stdio.py +86 -0
  104. mcp_server_paperless/tools/views.py +206 -0
  105. mcp_server_paperless/tools/workflows.py +174 -0
  106. mcp_server_paperless-0.2.0.dist-info/METADATA +317 -0
  107. mcp_server_paperless-0.2.0.dist-info/RECORD +110 -0
  108. mcp_server_paperless-0.2.0.dist-info/WHEEL +4 -0
  109. mcp_server_paperless-0.2.0.dist-info/entry_points.txt +5 -0
  110. mcp_server_paperless-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,6 @@
1
+ """MCP server for paperless-ngx 3.x."""
2
+
3
+ import importlib.metadata
4
+
5
+ # The distribution is mcp-server-paperless on PyPI; paperless-mcp there is another project.
6
+ __version__ = importlib.metadata.version("mcp-server-paperless")
@@ -0,0 +1,5 @@
1
+ """Entrypoint for ``python -m mcp_server_paperless``."""
2
+
3
+ from mcp_server_paperless.cli import main
4
+
5
+ main()
@@ -0,0 +1,505 @@
1
+ """ASGI entrypoint for HTTP deployments: secure by default (decision-27, decision-31).
2
+
3
+ ``check_startup`` refuses a configuration that would expose the server without authentication;
4
+ ``authenticator`` builds the authentication (static bearer tokens, the optional OIDC layer, or
5
+ both); ``build_app`` wraps a server in the ASGI app with that authentication, the host and origin
6
+ guard, a request id and a body limit.
7
+ """
8
+
9
+ import hashlib
10
+ import hmac
11
+ import ipaddress
12
+ import json
13
+ import os
14
+ import socket
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, cast, override
17
+
18
+ import uvicorn
19
+ from cryptography.fernet import Fernet
20
+ from fastmcp.server.auth import AccessToken, AuthProvider, MultiAuth, TokenVerifier
21
+ from fastmcp.server.auth.jwt_issuer import derive_jwt_key
22
+ from fastmcp.server.auth.oidc_proxy import OIDCConfiguration, OIDCProxy
23
+ from key_value.aio.stores.filetree import (
24
+ FileTreeStore,
25
+ FileTreeV1CollectionSanitizationStrategy,
26
+ FileTreeV1KeySanitizationStrategy,
27
+ )
28
+ from key_value.aio.stores.memory import MemoryStore
29
+ from key_value.aio.wrappers.encryption import FernetEncryptionWrapper
30
+ from pydantic import AnyHttpUrl, ValidationError
31
+
32
+ from mcp_server_paperless.domain.errors import InvalidConfiguration
33
+ from mcp_server_paperless.observability import RequestContext, request_header
34
+ from mcp_server_paperless.server import create_server
35
+
36
+ if TYPE_CHECKING:
37
+ from collections.abc import Callable, Sequence
38
+
39
+ from fastmcp import FastMCP
40
+ from key_value.aio.protocols import AsyncKeyValue
41
+ from pydantic import HttpUrl, SecretStr
42
+ from starlette.applications import Starlette
43
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
44
+
45
+ from mcp_server_paperless.settings import (
46
+ HttpSettings,
47
+ OidcSettings,
48
+ PaperlessSettings,
49
+ ServerSettings,
50
+ )
51
+
52
+ type Resolver = Callable[[str], Sequence[str]]
53
+
54
+
55
+ def resolve_addresses(host: str) -> list[str]:
56
+ """The addresses ``host`` resolves to (``OSError`` when it does not)."""
57
+ return [str(info[4][0]) for info in socket.getaddrinfo(host, None)]
58
+
59
+
60
+ def _loopback_address(text: str) -> bool:
61
+ try:
62
+ address = ipaddress.ip_address(text.split("%", 1)[0])
63
+ except ValueError:
64
+ return False
65
+ # An IPv4-mapped address is as loopback as the IPv4 address inside it.
66
+ mapped = getattr(address, "ipv4_mapped", None)
67
+ return (mapped or address).is_loopback
68
+
69
+
70
+ def is_loopback(host: str, resolve: Resolver = resolve_addresses) -> bool:
71
+ """Whether binding ``host`` reaches the local machine only.
72
+
73
+ An IP address is judged by itself (IPv4-mapped IPv6 included); a name only if every address
74
+ it resolves to is loopback. A name that does not resolve, the empty string and the
75
+ unspecified addresses (0.0.0.0, ::) are remote.
76
+ """
77
+ bare = host.strip().removeprefix("[").removesuffix("]")
78
+ if not bare:
79
+ return False
80
+ try:
81
+ _ = ipaddress.ip_address(bare.split("%", 1)[0])
82
+ except ValueError:
83
+ try:
84
+ addresses = resolve(bare.lower())
85
+ except OSError:
86
+ return False
87
+ return bool(addresses) and all(_loopback_address(a) for a in addresses)
88
+ return _loopback_address(bare)
89
+
90
+
91
+ def check_startup(
92
+ http: HttpSettings, resolve: Resolver = resolve_addresses, *, oidc: OidcSettings | None = None
93
+ ) -> None:
94
+ """Refuse to start an HTTP server that would be open to anyone who can reach it.
95
+
96
+ Raises:
97
+ InvalidConfiguration: The OIDC layer is configured but incomplete, its base URL names a
98
+ host that is not allowed or its storage directory cannot be written; neither tokens
99
+ nor the OIDC layer are configured and the bind is not loopback with the explicit
100
+ flag; or a remote bind names no allowed hosts.
101
+ """
102
+ loopback = is_loopback(http.host, resolve)
103
+ with_oidc = oidc is not None and oidc.configured
104
+ if oidc is not None and (missing := oidc.missing()):
105
+ message = (
106
+ f"the OIDC layer is incomplete: set {', '.join(missing)}, or unset every "
107
+ "PAPERLESS_MCP_OIDC_* variable to serve with bearer tokens alone."
108
+ )
109
+ raise InvalidConfiguration(message)
110
+ if not http.auth_tokens and not with_oidc:
111
+ if not loopback:
112
+ message = (
113
+ f"refusing to serve {http.host!r} without authentication: set "
114
+ "PAPERLESS_MCP_HTTP_AUTH_TOKENS or the PAPERLESS_MCP_OIDC_* variables. The "
115
+ "unauthenticated mode is only for a loopback bind, and this bind is not loopback."
116
+ )
117
+ raise InvalidConfiguration(message, hint="Generate a token with: openssl rand -hex 32")
118
+ if not http.allow_unauthenticated_loopback:
119
+ message = (
120
+ "refusing to start without authentication: set PAPERLESS_MCP_HTTP_AUTH_TOKENS or "
121
+ "the PAPERLESS_MCP_OIDC_* variables, or "
122
+ "PAPERLESS_MCP_HTTP_ALLOW_UNAUTHENTICATED_LOOPBACK=true to serve "
123
+ f"{http.host!r} without it (loopback only)."
124
+ )
125
+ raise InvalidConfiguration(message)
126
+ if not loopback and not http.allowed_hosts:
127
+ message = (
128
+ f"{http.host!r} is not a loopback address: name the host names clients use in "
129
+ "PAPERLESS_MCP_HTTP_ALLOWED_HOSTS."
130
+ )
131
+ raise InvalidConfiguration(message)
132
+ if with_oidc:
133
+ _check_oidc(http, cast("OidcSettings", oidc))
134
+
135
+
136
+ # The host names the host and origin guard always lets through (FastMCP's DEFAULT_HOSTS).
137
+ LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "[::1]", "::1"})
138
+
139
+
140
+ def _check_oidc(http: HttpSettings, oidc: OidcSettings) -> None:
141
+ host = (cast("HttpUrl", oidc.base_url).host or "").lower()
142
+ if host not in LOOPBACK_HOSTS and host not in http.allowed_hosts:
143
+ message = (
144
+ f"the OIDC base URL names {host!r}, which is not an allowed host: add it to "
145
+ "PAPERLESS_MCP_HTTP_ALLOWED_HOSTS, or browsers and clients get 421 from every route."
146
+ )
147
+ raise InvalidConfiguration(message)
148
+ directory = oidc.storage_dir
149
+ if directory is not None and not (
150
+ Path(directory).is_dir() and os.access(directory, os.W_OK | os.X_OK)
151
+ ):
152
+ message = (
153
+ f"PAPERLESS_MCP_OIDC_STORAGE_DIR {directory!r} is not a writable directory: create "
154
+ "it (a volume in a container) or unset the variable to keep the OAuth state in memory."
155
+ )
156
+ raise InvalidConfiguration(message)
157
+
158
+
159
+ class StaticBearerVerifier(TokenVerifier):
160
+ """Accepts a bearer token that equals one of the configured tokens.
161
+
162
+ Only SHA-256 digests are kept, and a presented token is compared with every digest in
163
+ constant time (``hmac.compare_digest`` on fixed-length digests, no early exit), so neither
164
+ the length of a token nor the position of the first differing byte shows in the timing.
165
+ The ``AccessToken`` carries a label, never the token.
166
+ """
167
+
168
+ def __init__(self, tokens: Sequence[SecretStr]) -> None:
169
+ """Keep the digests of ``tokens``."""
170
+ super().__init__()
171
+ self._digests: tuple[bytes, ...] = tuple(
172
+ hashlib.sha256(token.get_secret_value().encode()).digest() for token in tokens
173
+ )
174
+
175
+ @override
176
+ async def verify_token(self, token: str) -> AccessToken | None:
177
+ """The access of the matching token, or None."""
178
+ digest = hashlib.sha256(token.encode()).digest()
179
+ matched: int | None = None
180
+ for index, known in enumerate(self._digests):
181
+ if hmac.compare_digest(digest, known):
182
+ matched = index
183
+ if matched is None:
184
+ return None
185
+ return AccessToken(
186
+ token=f"static-token-{matched}", client_id=f"static-token-{matched}", scopes=[]
187
+ )
188
+
189
+
190
+ # Seconds the discovery request may take at startup (FastMCP's default).
191
+ DISCOVERY_TIMEOUT = 10
192
+ # The one scope the identity provider is asked for: it returns the ID token this server checks.
193
+ OIDC_SCOPES = ["openid"]
194
+
195
+
196
+ # Most entries the in-memory store keeps per collection (registrations, transactions, codes,
197
+ # tokens); beyond it the oldest are dropped. /register and /authorize need no authentication, so
198
+ # without a cap a flood of them would grow memory without bound (decision-31).
199
+ MEMORY_ENTRIES = 10_000
200
+ STORAGE_SALT = "paperless-mcp-oauth-storage"
201
+
202
+
203
+ def oauth_storage(oidc: OidcSettings) -> AsyncKeyValue:
204
+ """Where the OIDC layer keeps client registrations, sessions and upstream tokens.
205
+
206
+ In memory without ``storage_dir`` (capped per collection); else files there, with FastMCP's
207
+ file-name sanitising (any key stays inside its collection directory) and encrypted with a
208
+ Fernet key stretched from the signing key by PBKDF2, as FastMCP stretches a string signing
209
+ key. FastMCP's own default store lives in a home directory the container does not have.
210
+ """
211
+ if oidc.storage_dir is None:
212
+ return MemoryStore(max_entries_per_collection=MEMORY_ENTRIES)
213
+ signing_key = cast("SecretStr", oidc.jwt_signing_key).get_secret_value()
214
+ fernet_key = derive_jwt_key(low_entropy_material=signing_key, salt=STORAGE_SALT)
215
+ directory = Path(oidc.storage_dir)
216
+ files = FileTreeStore(
217
+ data_directory=directory,
218
+ key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(directory),
219
+ collection_sanitization_strategy=FileTreeV1CollectionSanitizationStrategy(directory),
220
+ )
221
+ # A key that no longer decrypts (a new signing key) is a miss: clients register again.
222
+ return FernetEncryptionWrapper(
223
+ key_value=files, fernet=Fernet(key=fernet_key), raise_on_decryption_error=False
224
+ )
225
+
226
+
227
+ def oidc_proxy(oidc: OidcSettings) -> OIDCProxy:
228
+ """FastMCP's OIDC proxy in front of the configured identity provider (decision-31).
229
+
230
+ It reads the discovery document now. The identity is the provider's ID token (audience: the
231
+ client id), which every OIDC provider issues as a signed JWT, whatever its access tokens are.
232
+ The consent page stays on, CIMD and dynamic registration are offered, and clients may only
233
+ register the allowed callbacks.
234
+
235
+ Raises:
236
+ InvalidConfiguration: The discovery document cannot be read or lacks an endpoint.
237
+ """
238
+ config_url = str(oidc.config_url)
239
+ # Discovery first, on its own: FastMCP caches the document briefly, so the proxy below
240
+ # reuses it. It fails with httpx2's errors (this module may not import httpx2) or with
241
+ # pydantic's for a malformed document; the messages name the type only.
242
+ try:
243
+ _ = OIDCConfiguration.get_oidc_configuration(
244
+ AnyHttpUrl(config_url), strict=None, timeout_seconds=DISCOVERY_TIMEOUT
245
+ )
246
+ except ValidationError:
247
+ message = (
248
+ f"the document at {config_url} is no valid OpenID Connect discovery document "
249
+ "(ValidationError): it must name the issuer, an authorization and a token endpoint "
250
+ "and the signing keys (jwks_uri). Check PAPERLESS_MCP_OIDC_CONFIG_URL."
251
+ )
252
+ raise InvalidConfiguration(message) from None
253
+ except Exception as error: # noqa: BLE001 -- see above
254
+ message = (
255
+ f"could not read the OIDC discovery document at {config_url} "
256
+ f"({type(error).__name__}): check PAPERLESS_MCP_OIDC_CONFIG_URL and that the "
257
+ "identity provider is reachable from this server."
258
+ )
259
+ raise InvalidConfiguration(message) from None
260
+ try:
261
+ return OIDCProxy(
262
+ config_url=config_url,
263
+ client_id=cast("str", oidc.client_id),
264
+ client_secret=cast("SecretStr", oidc.client_secret).get_secret_value(),
265
+ base_url=str(oidc.base_url).rstrip("/"),
266
+ jwt_signing_key=cast("SecretStr", oidc.jwt_signing_key).get_secret_value(),
267
+ timeout_seconds=DISCOVERY_TIMEOUT,
268
+ verify_id_token=True,
269
+ required_scopes=OIDC_SCOPES,
270
+ allowed_client_redirect_uris=list(oidc.allowed_redirect_uris),
271
+ client_storage=oauth_storage(oidc),
272
+ require_authorization_consent=True,
273
+ enable_cimd=True,
274
+ )
275
+ except Exception as error: # noqa: BLE001 -- FastMCP raises ValueError and others
276
+ message = (
277
+ f"could not set up the OIDC proxy from the discovery document at {config_url} "
278
+ f"({type(error).__name__}): check the client id, secret and signing key."
279
+ )
280
+ raise InvalidConfiguration(message) from None
281
+
282
+
283
+ def authenticator(http: HttpSettings, oidc: OidcSettings | None = None) -> AuthProvider | None:
284
+ """The authentication of the endpoint (decision-31).
285
+
286
+ Static bearer tokens alone; with the OIDC layer, FastMCP's ``MultiAuth`` with the OIDC proxy
287
+ first and the bearer tokens, if any, after it; None while neither is configured.
288
+
289
+ Raises:
290
+ InvalidConfiguration: See ``oidc_proxy``.
291
+ """
292
+ bearer = StaticBearerVerifier(http.auth_tokens) if http.auth_tokens else None
293
+ if oidc is None or not oidc.configured:
294
+ return bearer
295
+ # required_scopes=[]: the proxy checks the openid scope of its own sessions; the bearer
296
+ # tokens carry no scopes and must not be asked for one.
297
+ return MultiAuth(
298
+ server=oidc_proxy(oidc),
299
+ verifiers={"static-bearer": bearer} if bearer is not None else {},
300
+ required_scopes=[],
301
+ )
302
+
303
+
304
+ # Room for the JSON-RPC envelope and the other arguments around base64 content.
305
+ ENVELOPE_BYTES = 64 * 1024
306
+
307
+
308
+ def body_limit(max_upload_bytes: int) -> int:
309
+ """Most bytes of a request body: the base64 text of the largest upload plus the envelope.
310
+
311
+ The tools check the size of base64 content themselves, but only after the body was read and
312
+ parsed; this bounds what is read first.
313
+ """
314
+ return -(-max_upload_bytes // 3) * 4 + ENVELOPE_BYTES
315
+
316
+
317
+ async def _reply(send: Send, status: int, text: str) -> None:
318
+ body = json.dumps({"error": text}).encode()
319
+ headers = [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]
320
+ await send({"type": "http.response.start", "status": status, "headers": headers})
321
+ await send({"type": "http.response.body", "body": body})
322
+
323
+
324
+ class BodyTooLargeError(Exception):
325
+ """The request body went past the limit while the app was reading it."""
326
+
327
+
328
+ class BodyLimit:
329
+ """ASGI middleware: refuses a request body larger than ``limit`` bytes with 413.
330
+
331
+ A declared ``Content-Length`` over the limit is refused without reading anything; a body
332
+ without one (chunked) is cut off as soon as it passes the limit.
333
+ """
334
+
335
+ def __init__(self, app: ASGIApp, limit: int) -> None:
336
+ """Wrap ``app``; ``limit`` is the most body bytes it may receive."""
337
+ self.app: ASGIApp = app
338
+ self.limit: int = limit
339
+
340
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
341
+ """Serve one ASGI connection."""
342
+ if scope["type"] != "http":
343
+ await self.app(scope, receive, send)
344
+ return
345
+ declared = request_header(scope, b"content-length") or b"0"
346
+ if declared.isdigit() and int(declared) > self.limit:
347
+ await _reply(send, 413, "request body too large")
348
+ return
349
+ received = 0
350
+ started = False
351
+
352
+ async def counted() -> Message:
353
+ nonlocal received
354
+ message = await receive()
355
+ if message["type"] == "http.request":
356
+ received += len(cast("bytes", message.get("body", b"")))
357
+ if received > self.limit:
358
+ raise BodyTooLargeError
359
+ return message
360
+
361
+ async def watched(message: Message) -> None:
362
+ nonlocal started
363
+ started = started or message["type"] == "http.response.start"
364
+ await send(message)
365
+
366
+ try:
367
+ await self.app(scope, counted, watched)
368
+ except BodyTooLargeError:
369
+ if started:
370
+ raise
371
+ await _reply(send, 413, "request body too large")
372
+
373
+
374
+ PROXY_HEADERS = (b"forwarded", b"x-forwarded-for", b"x-forwarded-host", b"x-real-ip")
375
+
376
+
377
+ class LoopbackOnly:
378
+ """ASGI middleware for the unauthenticated mode: answers only on a loopback address.
379
+
380
+ ``check_startup`` already refuses a configuration that binds elsewhere; this stops an app
381
+ that is started by other means (uvicorn on the command line with another ``--host``).
382
+ Only an IP literal counts (uvicorn reports one; a name is never looked up per request).
383
+ A request that carries proxy headers is refused too: behind a local reverse proxy every
384
+ client would look like loopback, so this mode must never sit behind one.
385
+ """
386
+
387
+ def __init__(self, app: ASGIApp) -> None:
388
+ """Wrap ``app``."""
389
+ self.app: ASGIApp = app
390
+
391
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
392
+ """Serve one ASGI connection."""
393
+ if scope["type"] == "http":
394
+ server = cast("tuple[str, int | None] | None", scope.get("server"))
395
+ if not (server and _loopback_address(server[0])):
396
+ message = "no authentication is configured: this app answers on loopback only"
397
+ await _reply(send, 403, message)
398
+ return
399
+ if any(request_header(scope, name) is not None for name in PROXY_HEADERS):
400
+ message = "no authentication is configured: this app does not sit behind a proxy"
401
+ await _reply(send, 403, message)
402
+ return
403
+ await self.app(scope, receive, send)
404
+
405
+
406
+ DEFAULT_PORTS = {"http": 80, "https": 443}
407
+
408
+
409
+ def public_origin(oidc: OidcSettings) -> str:
410
+ """The browser origin of the OIDC base URL: without a port only when it is the scheme's own."""
411
+ url = cast("HttpUrl", oidc.base_url)
412
+ port = "" if url.port in {None, DEFAULT_PORTS[url.scheme]} else f":{url.port}"
413
+ return f"{url.scheme}://{url.host}{port}"
414
+
415
+
416
+ def build_app(
417
+ server: FastMCP,
418
+ http: HttpSettings,
419
+ *,
420
+ max_upload_bytes: int,
421
+ oidc: OidcSettings | None = None,
422
+ ) -> Starlette:
423
+ """The ASGI app of ``server``: authentication, host and origin guard, body limit.
424
+
425
+ With the OIDC layer the only browser origin allowed is the server's own public origin (its
426
+ consent form posts there; behind a TLS proxy the request itself arrives as plain http).
427
+
428
+ Raises:
429
+ InvalidConfiguration: ``server`` was built without the authentication the settings ask
430
+ for, or with authentication they do not ask for.
431
+ """
432
+ with_oidc = oidc is not None and oidc.configured
433
+ authenticated = bool(http.auth_tokens) or with_oidc
434
+ if (server.auth is None) == authenticated or with_oidc != isinstance(server.auth, MultiAuth):
435
+ message = "the server's authentication does not match the HTTP settings"
436
+ raise InvalidConfiguration(message)
437
+ origins = [public_origin(cast("OidcSettings", oidc))] if with_oidc else []
438
+ # Every option is explicit: FASTMCP_* environment variables must not loosen the app (a
439
+ # wildcard origin, debug tracebacks, stateless routes, no session expiry).
440
+ app = server.http_app(
441
+ path=http.path,
442
+ json_response=False,
443
+ stateless_http=False,
444
+ host_origin_protection=True,
445
+ allowed_hosts=list(http.allowed_hosts),
446
+ allowed_origins=origins,
447
+ session_idle_timeout="auto",
448
+ )
449
+ app.debug = False
450
+ # /mcp/ is not /mcp: a redirect would be answered before authentication, and with the
451
+ # wrong port and scheme behind a proxy.
452
+ app.router.redirect_slashes = False
453
+ app.add_middleware(BodyLimit, limit=body_limit(max_upload_bytes))
454
+ if not authenticated:
455
+ app.add_middleware(LoopbackOnly)
456
+ # Outermost, so that a refusal by the host guard or the authentication has an id and a record.
457
+ app.add_middleware(RequestContext)
458
+ return app
459
+
460
+
461
+ def create_app(
462
+ paperless: PaperlessSettings,
463
+ settings: ServerSettings,
464
+ http: HttpSettings,
465
+ *,
466
+ oidc: OidcSettings | None = None,
467
+ resolve: Resolver = resolve_addresses,
468
+ ) -> Starlette:
469
+ """The ASGI app of the paperless-mcp server (``paperless-mcp-http``).
470
+
471
+ Never offers a path parameter: HTTP callers upload base64 content (decision-7).
472
+
473
+ Raises:
474
+ InvalidConfiguration: See ``check_startup`` and ``oidc_proxy``, or the selection leaves
475
+ no tool.
476
+ """
477
+ check_startup(http, resolve, oidc=oidc)
478
+ server = create_server(paperless, settings, stdio=False, auth=authenticator(http, oidc))
479
+ return build_app(server, http, max_upload_bytes=settings.max_upload_bytes, oidc=oidc)
480
+
481
+
482
+ def uvicorn_server(app: Starlette, http: HttpSettings) -> uvicorn.Server:
483
+ """A uvicorn server for ``app`` bound to ``http.host`` and ``http.port``.
484
+
485
+ No access log (it prints query strings; ``RequestContext`` logs each request without them),
486
+ no trust in forwarded headers, no server banner and no WebSocket support (uvicorn logs a
487
+ handshake with its query string; there is no WebSocket route); its loggers use the root handler.
488
+ """
489
+ config = uvicorn.Config(
490
+ app,
491
+ host=http.host,
492
+ port=http.port,
493
+ log_config=None,
494
+ access_log=False,
495
+ proxy_headers=False,
496
+ server_header=False,
497
+ ws="none",
498
+ )
499
+ return uvicorn.Server(config)
500
+
501
+
502
+ def run_server(server: uvicorn.Server) -> bool:
503
+ """Serve until stopped; whether the server came up at all."""
504
+ server.run()
505
+ return server.started
@@ -0,0 +1,86 @@
1
+ """Command-line entrypoints: ``paperless-mcp`` (stdio) and ``paperless-mcp-http`` (HTTP).
2
+
3
+ Configuration errors and a Paperless that rejects the token or API version end the process
4
+ with exit code 1 and one line on stderr, without a traceback.
5
+ """
6
+
7
+ import sys
8
+ from typing import TYPE_CHECKING, NoReturn
9
+
10
+ from pydantic import ValidationError
11
+ from pydantic_settings import BaseSettings
12
+
13
+ from mcp_server_paperless.app import create_app, run_server, uvicorn_server
14
+ from mcp_server_paperless.domain.errors import PaperlessMcpError
15
+ from mcp_server_paperless.observability import configure_logging
16
+ from mcp_server_paperless.server import create_server
17
+ from mcp_server_paperless.settings import (
18
+ HttpSettings,
19
+ OidcSettings,
20
+ PaperlessSettings,
21
+ ServerSettings,
22
+ )
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Callable
26
+
27
+ import uvicorn
28
+
29
+
30
+ def _fail(message: str) -> NoReturn:
31
+ print(f"paperless-mcp: {message}", file=sys.stderr) # noqa: T201 -- the user-facing exit message
32
+ raise SystemExit(1)
33
+
34
+
35
+ def _load[S: BaseSettings](kind: type[S], problems: list[str]) -> S | None:
36
+ """The settings from the environment, or None with one line per invalid variable."""
37
+ try:
38
+ return kind.model_validate({})
39
+ except ValidationError as error:
40
+ prefix = kind.model_config.get("env_prefix") or ""
41
+ # Only the variable and the reason: the input may be a token.
42
+ problems.extend(
43
+ f"{prefix}{'_'.join(map(str, problem['loc'])).upper()}: {problem['msg']}"
44
+ for problem in error.errors()
45
+ )
46
+ return None
47
+
48
+
49
+ def main() -> None:
50
+ """Run the server over stdio."""
51
+ problems: list[str] = []
52
+ paperless = _load(PaperlessSettings, problems)
53
+ settings = _load(ServerSettings, problems)
54
+ if paperless is None or settings is None:
55
+ _fail("invalid configuration: " + "; ".join(problems))
56
+ configure_logging(settings.log_level)
57
+ try:
58
+ # No banner: it is noise on stderr and would check PyPI for updates (decision-7).
59
+ create_server(paperless, settings, stdio=True).run(transport="stdio", show_banner=False)
60
+ except PaperlessMcpError as error:
61
+ _fail(error.describe())
62
+
63
+
64
+ def main_http(run: Callable[[uvicorn.Server], bool] = run_server) -> None:
65
+ """Run the server over Streamable HTTP; refuses to start without authentication.
66
+
67
+ Authentication is static bearer tokens, the optional OIDC layer (``PAPERLESS_MCP_OIDC_*``),
68
+ or both (decision-31).
69
+
70
+ Args:
71
+ run: Serves the uvicorn server and says whether it came up; tests pass a fake.
72
+ """
73
+ problems: list[str] = []
74
+ paperless = _load(PaperlessSettings, problems)
75
+ settings = _load(ServerSettings, problems)
76
+ http = _load(HttpSettings, problems)
77
+ oidc = _load(OidcSettings, problems)
78
+ if paperless is None or settings is None or http is None or oidc is None:
79
+ _fail("invalid configuration: " + "; ".join(problems))
80
+ configure_logging(settings.log_level)
81
+ try:
82
+ app = create_app(paperless, settings, http, oidc=oidc)
83
+ except PaperlessMcpError as error:
84
+ _fail(error.describe())
85
+ if not run(uvicorn_server(app, http)):
86
+ _fail("the HTTP server did not start; see the log above")
@@ -0,0 +1,4 @@
1
+ """Domain layer: models, value objects, errors and ports (Protocols).
2
+
3
+ Imports nothing else from the package and no I/O or MCP library.
4
+ """