sane-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: sane-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for scanning (SANE), with previews and short-lived download links (S3-compatible storage), for any MCP client
5
+ Author: ispb88
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ispb88/sane-mcp
8
+ Project-URL: Issues, https://github.com/ispb88/sane-mcp/issues
9
+ Keywords: mcp,sane,scanning,scanner
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Multimedia :: Graphics :: Capture :: Scanners
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: mcp<3,>=2.3
20
+ Requires-Dist: boto3>=1.35
21
+ Requires-Dist: python-sane>=2.9
22
+ Requires-Dist: pillow>=10.1
23
+ Dynamic: license-file
24
+
25
+ # sane-mcp
26
+
27
+ An MCP server that lets an AI assistant (any MCP client) use a scanner on your network through SANE.
28
+
29
+ ## Why this one?
30
+
31
+ It works for assistants that run elsewhere, such as web or mobile clients, as well as local ones:
32
+
33
+ - **Results the AI can see.** Feeder or flatbed, multi-page PDFs or images. The client gets small
34
+ watermarked previews to read and check.
35
+ - **No lost pages.** If nobody says where the pages are, it reads every page in the feeder, or scans the
36
+ glass when the feeder is empty.
37
+ - **Full-quality files without exposing your disk.** Scans stay on your machine. When you want the actual
38
+ file, that one file goes to *your* private S3-compatible bucket with a short-lived download link.
39
+ - **Works with quirky scanners.** The scanner, its sources and its modes are detected automatically, with
40
+ overrides for devices that name them oddly.
41
+
42
+ ## Tools
43
+
44
+ | Tool | What it does |
45
+ |---|---|
46
+ | `scan` | Scan from the feeder or the glass; returns the file name and previews |
47
+ | `list_scans`, `get_scan` | Saved scans: list, previews, download link |
48
+ | `list_scan_sources` | The scanner's sources and modes, and how the tool's names map to them |
49
+
50
+ ## Install
51
+
52
+ Needs Linux with SANE and a supported scanner, and Python 3.11+. Installing builds `python-sane`, so it
53
+ also needs a C compiler and the SANE development headers (`libsane-dev` on Debian/Ubuntu; included with the `sane` package on Arch).
54
+
55
+ ```sh
56
+ pipx install sane-mcp # or: uv tool install sane-mcp
57
+ sane-mcp # stdio, for local clients
58
+ sane-mcp --http # HTTP on 127.0.0.1:8711/mcp
59
+ ```
60
+
61
+ For a local client that starts servers itself:
62
+
63
+ ```json
64
+ {
65
+ "mcpServers": {
66
+ "scanner": {
67
+ "command": "sane-mcp",
68
+ "env": { "MCP_SCAN_DIR": "/home/me/Scans" }
69
+ }
70
+ }
71
+ }
72
+ ```
73
+
74
+ To run it permanently over HTTP, see `examples/sane-mcp.service` and "Connecting remote clients" below.
75
+
76
+ ## Settings (environment variables)
77
+
78
+ | Variable | Default | |
79
+ |---|---|---|
80
+ | `MCP_PORT`, `MCP_PATH` | `8711`, `/mcp` | HTTP listener (always 127.0.0.1) |
81
+ | `MCP_PUBLIC_HOST` | – | Public hostname(s) in front of it, comma-separated |
82
+ | `MCP_ALLOWED_ORIGINS` | – | Extra browser origins allowed to call it, comma-separated, e.g. `https://app.example.com` |
83
+ | `MCP_SCANNER` | first scanner found | SANE device name, e.g. `escl:https://192.0.2.10:443` |
84
+ | `MCP_SCAN_SOURCES`, `MCP_SCAN_MODES` | matched by name | JSON maps from the tool's names to the scanner's own, e.g. `{"adf": "ADF Front", "flatbed": "Flatbed"}` |
85
+ | `MCP_SCAN_NOTES` | – | Extra guidance for the client about your scanner's quirks |
86
+ | `MCP_SCAN_DIR` | `~/Documents/Scans` | Where scans are saved |
87
+ | `MCP_SCAN_LINK_MINUTES` | `5` | How long download links work, in minutes (up to 10080, 7 days) |
88
+ | `S3_ENDPOINT_URL`, `S3_REGION`, `S3_BUCKET`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ADDRESSING_STYLE` | – , `us-east-1`, …, `auto` | Storage for download links; see `examples/s3.env.example`. Scanning works without it |
89
+
90
+ If the automatic matching picks the wrong source or mode, `list_scan_sources` shows the scanner's own
91
+ names; `scan` accepts those too, or set `MCP_SCAN_SOURCES` / `MCP_SCAN_MODES`.
92
+
93
+ ## Connecting remote clients
94
+
95
+ Remote (web) clients need a public HTTPS URL. **The server has no authentication of its own**: put it
96
+ behind a reverse proxy or tunnel that does (for example an OAuth-capable proxy or a zero-trust tunnel), and
97
+ set `MCP_PUBLIC_HOST` to that hostname. If the client calls it from a browser page, add that page's origin
98
+ to `MCP_ALLOWED_ORIGINS`. To use download links, the client must be able to reach your bucket's endpoint.
99
+
100
+ ## Security
101
+
102
+ - Run it as a dedicated user; `examples/sane-mcp.service` shows a sandboxed systemd unit.
103
+ - Use a storage key limited to the one bucket, and a lifecycle rule that deletes old objects.
104
+ - Download links are only made for a scan the client asks for, and the server never downloads from URLs
105
+ it's given.
106
+
107
+ ## Known issues
108
+
109
+ - **Linux only.**
110
+
111
+ ## Licence
112
+
113
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,7 @@
1
+ sane_mcp.py,sha256=oiD9orueU89kNzwhPh09Q76r8qTQBXZEX5NcycxBRqs,20087
2
+ sane_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=SbQW_Wy5b4IRebNGTwO-3FSc6LIbSevMPrbF0tJKssk,1063
3
+ sane_mcp-0.1.0.dist-info/METADATA,sha256=DIiCgNRxEmkvDkVIA1_zT6pPMfww7QBCEEa6NgiaQ-c,4930
4
+ sane_mcp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ sane_mcp-0.1.0.dist-info/entry_points.txt,sha256=mPIjFoiOviG5J1WoN3l214GT-DEdt8_FIYAwpiQKcAk,43
6
+ sane_mcp-0.1.0.dist-info/top_level.txt,sha256=J9NJf6spZE3CfBTW765cZRRpPNjeqkp9c2mCl7eho8E,9
7
+ sane_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sane-mcp = sane_mcp:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ispb88
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 @@
1
+ sane_mcp
sane_mcp.py ADDED
@@ -0,0 +1,433 @@
1
+ """sane-mcp: scanning (SANE) for any MCP client, with full-quality files shared through S3-compatible storage.
2
+
3
+ Settings (environment): see README.md. Everything has a working default except storage (S3_*), which
4
+ only download links (upload=True) need.
5
+
6
+ Run: sane-mcp -> stdio
7
+ sane-mcp --http -> streamable HTTP on 127.0.0.1:$MCP_PORT (default 8711) at $MCP_PATH
8
+ """
9
+
10
+ import io
11
+ import json
12
+ import os
13
+ import re
14
+ import secrets
15
+ import sys
16
+ import threading
17
+ from contextlib import contextmanager
18
+ from datetime import datetime
19
+ from pathlib import Path
20
+ from typing import Literal
21
+
22
+ import _sane
23
+ import sane
24
+ from PIL import Image as PILImage, ImageDraw, ImageFont
25
+ from mcp.server.mcpserver import Image, MCPServer
26
+ from mcp.server.mcpserver.exceptions import ToolError # the only errors whose message reaches the client
27
+ from mcp.server.transport_security import TransportSecuritySettings
28
+
29
+ SCAN_DIR = Path(os.environ.get("MCP_SCAN_DIR") or Path.home() / "Documents" / "Scans")
30
+ # How long scan download links work, in minutes (S3 presigned links last at most 7 days).
31
+ LINK_MINUTES = int(os.environ.get("MCP_SCAN_LINK_MINUTES") or 5)
32
+ if not 1 <= LINK_MINUTES <= 7 * 24 * 60:
33
+ sys.exit("MCP_SCAN_LINK_MINUTES must be between 1 and 10080 (7 days)")
34
+ LINK_VALID = f"{LINK_MINUTES} minute{'' if LINK_MINUTES == 1 else 's'}"
35
+
36
+ _public = [h.strip() for h in os.environ.get("MCP_PUBLIC_HOST", "").split(",") if h.strip()]
37
+ # Browser origins allowed to call the server, besides localhost and the public hosts (comma-separated).
38
+ _origins = [o.strip() for o in os.environ.get("MCP_ALLOWED_ORIGINS", "").split(",") if o.strip()]
39
+ mcp = MCPServer("sane-mcp")
40
+ # Streamable HTTP settings, used by main() --http. Always 127.0.0.1: put an authenticating proxy in front.
41
+ HTTP_SETTINGS = dict(
42
+ host="127.0.0.1",
43
+ port=int(os.environ.get("MCP_PORT", "8711")),
44
+ streamable_http_path=os.environ.get("MCP_PATH", "/mcp"),
45
+ stateless_http=True,
46
+ json_response=True,
47
+ transport_security=TransportSecuritySettings(
48
+ enable_dns_rebinding_protection=True,
49
+ allowed_hosts=["127.0.0.1:*", "localhost:*", *_public],
50
+ allowed_origins=["http://127.0.0.1:*", "http://localhost:*",
51
+ *[f"https://{h}" for h in _public], *_origins],
52
+ ),
53
+ )
54
+
55
+
56
+ # ===================== Scanning =====================
57
+
58
+ # Scanning goes through libsane (python-sane); pages come back as Pillow images, which also make the
59
+ # previews and the PDFs. MCP_SCANNER: SANE device name (default: the first device found).
60
+ # MCP_SCAN_SOURCES / MCP_SCAN_MODES: optional JSON maps from the tool's names to the device's own
61
+ # option values, e.g. {"adf": "ADF Front", "flatbed": "Flatbed"}; the keys become the tool's choices.
62
+ # Without them, the device's source/mode choices are matched by name (feeder/flatbed, color/gray/lineart).
63
+ # MCP_SCAN_NOTES: optional extra guidance appended to the scan tool's description (device quirks).
64
+ PREVIEW_PX = 1200 # longest side of preview images sent to the client
65
+ PREVIEW_MAX_PAGES = 5 # per tool call; use get_scan for the rest
66
+ PREVIEW_DIR = ".previews" # inside the scans folder: one subfolder of page previews per saved file
67
+
68
+ SOURCES: dict[str, str] = json.loads(os.environ.get("MCP_SCAN_SOURCES") or "{}")
69
+ MODES: dict[str, str] = json.loads(os.environ.get("MCP_SCAN_MODES") or "{}")
70
+ SOURCE_KEYS = tuple(SOURCES) or ("adf", "flatbed", "adf_duplex")
71
+ MODE_KEYS = tuple(MODES) or ("color", "gray", "bw")
72
+ SOURCE_WORDS = {"flatbed": ("flatbed", "platen", "glass"), "adf_duplex": ("duplex",),
73
+ "adf": ("adf", "feeder", "automatic document")}
74
+ MODE_WORDS = {"color": ("color", "colour"), "gray": ("gray", "grey"),
75
+ "bw": ("lineart", "black", "binary", "halftone", "mono")}
76
+ PAPER = {"letter": (215.9, 279.4), "legal": (215.9, 355.6), "a4": (210.0, 297.0)}
77
+
78
+ _sane_lock = threading.Lock() # libsane isn't thread-safe; tools may run concurrently
79
+ _sane_ready = False
80
+ _device: str | None = os.environ.get("MCP_SCANNER") or None
81
+ _choices: dict[str, list[str]] = {}
82
+
83
+
84
+ def _sane_init() -> None:
85
+ global _sane_ready
86
+ if not _sane_ready:
87
+ sane.init()
88
+ _sane_ready = True
89
+
90
+
91
+ def sane_devices() -> list[tuple[str, str, str, str]]:
92
+ with _sane_lock:
93
+ _sane_init()
94
+ try:
95
+ return sane.get_devices()
96
+ except _sane.error as e:
97
+ raise ToolError(f"scanner error: {e}")
98
+
99
+
100
+ def scanner() -> str:
101
+ global _device
102
+ if not _device:
103
+ found = sane_devices()
104
+ if not found:
105
+ raise ToolError("no scanner found (set MCP_SCANNER to the SANE device name)")
106
+ _device = found[0][0]
107
+ return _device
108
+
109
+
110
+ @contextmanager
111
+ def open_scanner():
112
+ """The scanner, opened for exclusive use; SANE errors become messages for the caller."""
113
+ name = scanner()
114
+ with _sane_lock:
115
+ _sane_init()
116
+ try:
117
+ dev = sane.open(name)
118
+ except _sane.error as e:
119
+ raise ToolError(f"can't open scanner {name}: {e}")
120
+ try:
121
+ yield dev
122
+ except _sane.error as e:
123
+ raise ToolError(f"scanner error: {e}")
124
+ finally:
125
+ dev.close()
126
+
127
+
128
+ def option_constraints(dev) -> dict[str, object]:
129
+ """{option name: constraint} (a list of allowed values, or a (min, max, step) range)."""
130
+ return {o[1]: o[8] for o in dev.get_options() if o[1]}
131
+
132
+
133
+ def device_choices(option: str) -> list[str]:
134
+ """The device's allowed values for its source or mode option."""
135
+ if not _choices: # read once for both; an empty answer isn't cached
136
+ with open_scanner() as dev:
137
+ found = {k: list(v) for k, v in option_constraints(dev).items()
138
+ if k in ("source", "mode") and isinstance(v, list)}
139
+ if not found:
140
+ return []
141
+ _choices.update(found)
142
+ return _choices.get(option, [])
143
+
144
+
145
+ def device_value(kind: str, key: str) -> str:
146
+ """Map a tool name (adf, gray, ...) or one of the device's own values to the device's value."""
147
+ fixed, words = (SOURCES, SOURCE_WORDS) if kind == "source" else (MODES, MODE_WORDS)
148
+ if key in fixed:
149
+ return fixed[key]
150
+ choices = device_choices(kind)
151
+ if key in choices:
152
+ return key
153
+ if key not in words:
154
+ raise ToolError(f"unknown {kind} {key!r}; see list_scan_sources (this scanner offers: {', '.join(choices) or 'none listed'})")
155
+ hits = [c for c in choices if any(w in c.lower() for w in words[key])]
156
+ if key == "adf": # plain feeder: prefer a choice that isn't the duplex one
157
+ hits = [c for c in hits if "duplex" not in c.lower()] or hits
158
+ if not hits:
159
+ raise ToolError(f"this scanner has no {kind} matching {key!r}; its choices: {', '.join(choices) or 'none listed'}")
160
+ return hits[0]
161
+
162
+
163
+ def optional_source(key: str) -> str | None:
164
+ """The device's source for a tool name (adf, flatbed), or None if it has none."""
165
+ try:
166
+ return device_value("source", key)
167
+ except ToolError:
168
+ return None
169
+
170
+
171
+ def is_glass(device_source: str) -> bool:
172
+ return any(w in device_source.lower() for w in SOURCE_WORDS["flatbed"])
173
+
174
+
175
+ @mcp.tool()
176
+ def list_scan_sources() -> str:
177
+ """Show the scanner in use, its own source and mode names, and which of them the scan tool's
178
+ names (adf, flatbed, color, gray, ...) map to. scan accepts either kind of name."""
179
+ lines = [f"Scanner: {scanner()}"]
180
+ for kind, keys in (("source", SOURCE_KEYS), ("mode", MODE_KEYS)):
181
+ lines.append(f"\n{kind.capitalize()}s offered by the scanner: {', '.join(device_choices(kind)) or 'none listed'}")
182
+ for k in keys:
183
+ try:
184
+ lines.append(f" {k:<11} -> {device_value(kind, k)}")
185
+ except ToolError:
186
+ lines.append(f" {k:<11} -> (not available on this scanner)")
187
+ if not os.environ.get("MCP_SCANNER"):
188
+ found = sane_devices()
189
+ if len(found) > 1:
190
+ lines.append("\nScanners found (set MCP_SCANNER to choose): " + "; ".join(f"{d[0]} ({d[1]} {d[2]})".strip() for d in found))
191
+ return "\n".join(lines)
192
+
193
+
194
+ def make_preview(page: "PILImage.Image") -> bytes:
195
+ """Small, heavily compressed and watermarked, so nobody mistakes a preview for the scan."""
196
+ img = page.convert("RGB")
197
+ img.thumbnail((PREVIEW_PX, PREVIEW_PX))
198
+ mark = PILImage.new("RGBA", img.size, (0, 0, 0, 0))
199
+ font = ImageFont.load_default(size=max(24, min(img.size) // 5))
200
+ text = PILImage.new("RGBA", ImageDraw.Draw(mark).textbbox((0, 0), "PREVIEW", font=font)[2:], (0, 0, 0, 0))
201
+ ImageDraw.Draw(text).text((0, 0), "PREVIEW", font=font, fill=(220, 0, 0, 64))
202
+ text = text.rotate(35, expand=True)
203
+ mark.alpha_composite(text, ((img.width - text.width) // 2, (img.height - text.height) // 2))
204
+ img = PILImage.alpha_composite(img.convert("RGBA"), mark).convert("RGB")
205
+ out = io.BytesIO()
206
+ img.save(out, "JPEG", quality=25, optimize=True, progressive=True)
207
+ return out.getvalue()
208
+
209
+
210
+ def preview_folder(saved: Path) -> Path:
211
+ return SCAN_DIR / PREVIEW_DIR / saved.name
212
+
213
+
214
+ def store_previews(saved: Path, pages: list) -> None:
215
+ folder = preview_folder(saved)
216
+ folder.mkdir(parents=True, exist_ok=True)
217
+ for i, page in enumerate(pages, 1):
218
+ (folder / f"p{i:03d}.jpg").write_bytes(make_preview(page))
219
+
220
+
221
+ def show_previews(saved: Path, first: int = 1) -> list:
222
+ pages = sorted(preview_folder(saved).glob("p*.jpg"))
223
+ if not pages:
224
+ return [f"(no preview stored for {saved.name}: it wasn't scanned by this server)"]
225
+ if first > len(pages):
226
+ raise ToolError(f"{saved.name} has only {len(pages)} page(s)")
227
+ out: list = []
228
+ for i, p in enumerate(pages[first - 1:first - 1 + PREVIEW_MAX_PAGES], first):
229
+ out += [f"Page {i}:", Image(data=p.read_bytes(), format="jpeg")]
230
+ rest = len(pages) - (first - 1 + PREVIEW_MAX_PAGES)
231
+ if rest > 0:
232
+ out.append(f"({rest} more page(s) not shown; use get_scan with first_page={first + PREVIEW_MAX_PAGES}.)")
233
+ return out
234
+
235
+
236
+ def scan_file(filename: str) -> Path:
237
+ path = (SCAN_DIR / filename).resolve()
238
+ if path.parent != SCAN_DIR.resolve() or not path.is_file():
239
+ raise ToolError(f"No scan named {filename!r}; see list_scans")
240
+ return path
241
+
242
+
243
+ def unique_path(p: Path) -> Path:
244
+ n = 2
245
+ while p.exists():
246
+ p = p.with_name(f"{p.stem.rsplit('_v', 1)[0]}_v{n}{p.suffix}")
247
+ n += 1
248
+ return p
249
+
250
+
251
+ SCAN_DOC = """Scan a document. Returns the saved file name and watermarked, low-quality preview images.
252
+
253
+ source (default auto): auto tries the document feeder first and reads every page in it; if
254
+ the feeder is empty, it scans the glass instead. Use auto unless the user says where the
255
+ pages are. Otherwise one of these names, or a source name exactly as list_scan_sources
256
+ shows it (also for mode):
257
+ adf pages stacked in the document feeder: scans every page in it.
258
+ adf_duplex feeder, both sides of each page (if the scanner supports it).
259
+ flatbed ONE page lying on the glass under the lid.
260
+ Some scanners take paper from the feeder whenever it holds any, even if flatbed is
261
+ chosen, so whenever pages may be in the feeder use auto or adf.
262
+
263
+ upload=True also uploads the full-quality file and returns a download link valid
264
+ for """ + LINK_VALID + """ (only ask for it when the actual file is needed, e.g. to save or send it).
265
+
266
+ name: optional file name stem, e.g. "lease-signed".
267
+ Tool names: source """ + "|".join(SOURCE_KEYS) + ", mode " + "|".join(MODE_KEYS) + """.
268
+ """ + (("\n " + os.environ["MCP_SCAN_NOTES"]) if os.environ.get("MCP_SCAN_NOTES") else "")
269
+
270
+
271
+ @mcp.tool(description=SCAN_DOC)
272
+ def scan(
273
+ source: str = "auto",
274
+ mode: str = "gray" if "gray" in MODE_KEYS else MODE_KEYS[0],
275
+ resolution: Literal[150, 200, 300, 600] = 300,
276
+ paper: Literal["letter", "legal", "a4"] = "letter",
277
+ format: Literal["pdf", "png", "jpeg"] = "pdf",
278
+ name: str | None = None,
279
+ upload: bool = False,
280
+ ) -> list:
281
+ ts = datetime.now().strftime("%Y-%m-%d_%H%M%S")
282
+ stem = (re.sub(r"[^\w.-]+", "-", name).strip("-.") if name else "") or f"scan_{ts}"
283
+ # Device values are looked up before opening the scanner (the lookup may query the device).
284
+ mod = device_value("mode", mode)
285
+ if source == "auto":
286
+ feeder, glass = optional_source("adf"), optional_source("flatbed")
287
+ if not (feeder or glass):
288
+ raise ToolError("can't find this scanner's feeder or glass; choose a source (see list_scan_sources)")
289
+ else:
290
+ chosen = device_value("source", source)
291
+ w, h = PAPER[paper]
292
+ with open_scanner() as dev:
293
+ limits = option_constraints(dev)
294
+
295
+ def clamp(option: str, value: float) -> float:
296
+ rng = limits.get(option)
297
+ return min(value, rng[1]) if isinstance(rng, tuple) else value
298
+
299
+ def read(src: str) -> list:
300
+ """One page from the glass; from a feeder, pages until the scanner reports it empty."""
301
+ dev.source, dev.mode, dev.resolution = src, mod, resolution
302
+ dev.tl_x, dev.tl_y, dev.br_x, dev.br_y = 0.0, 0.0, clamp("br-x", w), clamp("br-y", h)
303
+ return [dev.scan()] if is_glass(src) else list(dev.multi_scan())
304
+
305
+ if source != "auto":
306
+ used, pages = chosen, read(chosen)
307
+ else:
308
+ # Unknown source: the feeder first, so no page is ever left behind; an empty feeder
309
+ # gives no pages (SANE's "no documents"), and then the glass is scanned.
310
+ used, pages = feeder, (read(feeder) if feeder else [])
311
+ if not pages and glass:
312
+ used, pages = glass, read(glass)
313
+ fell_back = source == "auto" and bool(feeder) and used == glass
314
+ if not pages:
315
+ hint = "" if is_glass(used) else " Is there paper in the feeder?"
316
+ raise ToolError(f"Scan produced no pages.{hint}")
317
+ if mode == "bw" or any(w in mod.lower() for w in MODE_WORDS["bw"]):
318
+ # Some backends send line art as 8-bit pages of pure black and white: make them 1-bit (lossless),
319
+ # so PDFs get G4 compression instead of JPEG.
320
+ pages = [p.convert("1", dither=PILImage.Dither.NONE) if p.mode != "1" else p for p in pages]
321
+
322
+ SCAN_DIR.mkdir(parents=True, exist_ok=True)
323
+ if format == "pdf":
324
+ # Pillow writes black-and-white pages with G4 compression and grey/colour pages as JPEG.
325
+ out = unique_path(SCAN_DIR / f"{stem}.pdf")
326
+ part = out.with_name(f".{out.name}.part") # renamed when complete: no half-written scans
327
+ jpeg = {} if pages[0].mode == "1" else {"quality": 85} # the G4 encoder rejects a quality setting
328
+ pages[0].save(part, "PDF", save_all=True, append_images=pages[1:], resolution=resolution, **jpeg)
329
+ part.rename(out)
330
+ store_previews(out, pages)
331
+ saved = [out]
332
+ else:
333
+ saved = []
334
+ for i, page in enumerate(pages, 1):
335
+ out = unique_path(SCAN_DIR / f"{stem}{'' if len(pages) == 1 else f'_p{i}'}.{'png' if format == 'png' else 'jpg'}")
336
+ if format == "png":
337
+ page.save(out, "PNG", dpi=(resolution, resolution))
338
+ else:
339
+ page.convert("L" if page.mode in ("1", "L") else "RGB").save(out, "JPEG", quality=90, dpi=(resolution, resolution))
340
+ store_previews(out, [page])
341
+ saved.append(out)
342
+
343
+ where = ("glass (flatbed)" if is_glass(used) else
344
+ "document feeder (both sides)" if "duplex" in used.lower() else "document feeder")
345
+ header = f"Scanned {len(pages)} page(s) from the {where}, saved as: " + ", ".join(p.name for p in saved)
346
+ if fell_back:
347
+ header += " (the feeder was empty, so the glass was scanned)"
348
+ elif is_glass(used):
349
+ header += " (the glass scans one page; if pages were in the feeder, scan again with source=auto)"
350
+ elif source == "auto" and len(pages) == 1:
351
+ header += " (some scanners scan the glass when the feeder is empty, so this page may be from the glass)"
352
+ extra = share_scan_files(saved) if upload else [offer_link([p.name for p in saved])]
353
+ shown = [p for s in saved for p in show_previews(s)] if len(saved) > 1 else show_previews(saved[0])
354
+ return [header, *extra, *shown[:3 * PREVIEW_MAX_PAGES]]
355
+
356
+
357
+ @mcp.tool()
358
+ def list_scans(limit: int = 20) -> str:
359
+ """List saved scans, newest first."""
360
+ if not SCAN_DIR.is_dir():
361
+ return "No scans yet."
362
+ files = sorted((p for p in SCAN_DIR.iterdir() if p.is_file() and not p.name.startswith(".")),
363
+ key=lambda p: p.stat().st_mtime, reverse=True)[:max(1, min(limit, 200))]
364
+ if not files:
365
+ return "No scans yet."
366
+ return "\n".join(f"{p.name}\t{datetime.fromtimestamp(p.stat().st_mtime):%Y-%m-%d %H:%M}\t"
367
+ f"{p.stat().st_size // 1024} KB" for p in files)
368
+
369
+
370
+ @mcp.tool()
371
+ def get_scan(filename: str, first_page: int = 1, upload: bool = False) -> list:
372
+ """Show a saved scan's pages as watermarked preview images (up to 5 per call, starting at
373
+ first_page). upload=True also returns a download link to the full-quality file."""
374
+ path = scan_file(filename)
375
+ total = len(list(preview_folder(path).glob("p*.jpg")))
376
+ extra = share_scan_files([path]) if upload else [offer_link([path.name])]
377
+ return [f"{path.name}" + (f" ({total} page(s))" if total else ""), *extra, *show_previews(path, max(1, first_page))]
378
+
379
+
380
+ # ===================== Download links (S3-compatible storage) =====================
381
+ # Settings: S3_ENDPOINT_URL (e.g. https://s3.us-east-1.amazonaws.com), S3_REGION (default us-east-1),
382
+ # S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY; optional S3_ADDRESSING_STYLE (path|virtual|auto).
383
+ # Private bucket; only this server holds a key. scan/get_scan(upload=True) upload the full-quality
384
+ # file and return a presigned download link (MCP_SCAN_LINK_MINUTES); nothing else is ever shared.
385
+
386
+ S3_BUCKET = os.environ.get("S3_BUCKET", "")
387
+ _s3 = None
388
+
389
+
390
+ def s3():
391
+ global _s3
392
+ if _s3 is None:
393
+ endpoint, key, secret = (os.environ.get(k, "") for k in ("S3_ENDPOINT_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"))
394
+ if not (endpoint and key and secret and S3_BUCKET):
395
+ raise ToolError("download links are not configured on this server (S3 settings missing)")
396
+ import boto3
397
+ from botocore.config import Config
398
+ _s3 = boto3.client("s3", endpoint_url=endpoint, aws_access_key_id=key, aws_secret_access_key=secret,
399
+ region_name=os.environ.get("S3_REGION") or "us-east-1",
400
+ config=Config(signature_version="s3v4", retries={"max_attempts": 3},
401
+ s3={"addressing_style": os.environ.get("S3_ADDRESSING_STYLE") or "auto"}))
402
+ return _s3
403
+
404
+
405
+ def offer_link(names: list[str]) -> str:
406
+ """The note sent with previews when no link was asked for: the full file exists, so offer it."""
407
+ return ("These are low-quality previews. The full-quality file is saved on the scanner's computer: "
408
+ "offer the user a download link to it (get_scan(filename, upload=True) gives one, valid "
409
+ "for " + LINK_VALID + ") for: " + ", ".join(names))
410
+
411
+
412
+ def share_scan_files(paths: list[Path]) -> list[str]:
413
+ """Upload saved scan files to the private bucket; return lines with download links."""
414
+ client, lines = s3(), []
415
+ for path in paths:
416
+ key = f"scans/{secrets.token_hex(8)}/{path.name}"
417
+ ctype = {".pdf": "application/pdf", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}.get(path.suffix.lower(), "application/octet-stream")
418
+ client.upload_file(str(path), S3_BUCKET, key, ExtraArgs={"ContentType": ctype})
419
+ url = client.generate_presigned_url("get_object", Params={"Bucket": S3_BUCKET, "Key": key}, ExpiresIn=LINK_MINUTES * 60)
420
+ lines.append(f"{path.name}: {url}")
421
+ return ["Full-quality file(s), download links valid for " + LINK_VALID + " "
422
+ "(download them with an HTTP client, e.g. curl -sS -o <name> \"<link>\"):", *lines]
423
+
424
+
425
+ def main() -> None:
426
+ if "--http" in sys.argv:
427
+ mcp.run("streamable-http", **HTTP_SETTINGS)
428
+ else:
429
+ mcp.run("stdio")
430
+
431
+
432
+ if __name__ == "__main__":
433
+ main()