cups-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,124 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cups-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server for printing (CUPS) and file uploads (S3-compatible storage), for any MCP client
|
|
5
|
+
Author: ispb88
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ispb88/cups-mcp
|
|
8
|
+
Project-URL: Issues, https://github.com/ispb88/cups-mcp/issues
|
|
9
|
+
Keywords: mcp,cups,printing,printer,ipp
|
|
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 :: Printing
|
|
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: pycups>=2.0
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# cups-mcp
|
|
25
|
+
|
|
26
|
+
An MCP server that lets an AI assistant (any MCP client) print on your network through CUPS.
|
|
27
|
+
|
|
28
|
+
## Why this one?
|
|
29
|
+
|
|
30
|
+
Most printer MCP servers print a file *path* on the server, which only works when the AI runs on the
|
|
31
|
+
same machine. This one also works for assistants that run elsewhere, such as web or mobile clients:
|
|
32
|
+
|
|
33
|
+
- **Secure file transfer.** The client gets a one-time upload link, valid for 15 minutes, uploads the file
|
|
34
|
+
straight to *your* private S3-compatible bucket, and prints it by id. Files never pass through the
|
|
35
|
+
conversation, the server never reads arbitrary paths on your machine, and uploads are deleted after
|
|
36
|
+
printing.
|
|
37
|
+
- **Real printer options.** Files go to CUPS unchanged (PDF, PostScript, PNG, JPEG, TIFF, plain text). Every
|
|
38
|
+
print tool takes scaling, resolution, duplex, page ranges, paper and quality, plus any option the printer
|
|
39
|
+
itself offers (tray, media type, pages per sheet, ...), checked against what that printer supports.
|
|
40
|
+
|
|
41
|
+
Formatted documents (HTML, Markdown, Word) aren't converted: the client makes a PDF and prints that.
|
|
42
|
+
|
|
43
|
+
## Tools
|
|
44
|
+
|
|
45
|
+
| Tool | What it does |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `list_printers`, `print_queue`, `cancel_job` | Printer status and jobs |
|
|
48
|
+
| `printer_options` | What a printer accepts, with allowed values |
|
|
49
|
+
| `print_text` | Print plain text |
|
|
50
|
+
| `get_upload_link`, `list_uploads`, `print_file` | Upload a file, then print it by id |
|
|
51
|
+
| `print_file_data` | Print a small file sent inline (tiny files only) |
|
|
52
|
+
|
|
53
|
+
Every print tool takes the same options: `copies`, `duplex`, `page_ranges`, `paper`, `quality`,
|
|
54
|
+
`scaling` (`auto`, `fit`, `fill`, `none`), `ppi`, and `options` for anything else the printer accepts.
|
|
55
|
+
|
|
56
|
+
## Install
|
|
57
|
+
|
|
58
|
+
Needs Linux with CUPS, and Python 3.11+. Installing builds `pycups`, so it also needs a C compiler and the CUPS
|
|
59
|
+
development headers (`libcups2-dev` on Debian/Ubuntu; included with the `cups` package on Arch).
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
pipx install cups-mcp # or: uv tool install cups-mcp
|
|
63
|
+
cups-mcp # stdio, for local clients
|
|
64
|
+
cups-mcp --http # HTTP on 127.0.0.1:8710/mcp
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
For a local client that starts servers itself:
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
{
|
|
71
|
+
"mcpServers": {
|
|
72
|
+
"printer": {
|
|
73
|
+
"command": "cups-mcp",
|
|
74
|
+
"env": { "MCP_PRINTER": "Office_Printer" }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
To run it permanently over HTTP, see `examples/cups-mcp.service` and "Connecting remote clients" below.
|
|
81
|
+
|
|
82
|
+
## Settings (environment variables)
|
|
83
|
+
|
|
84
|
+
| Variable | Default | |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| `MCP_PORT`, `MCP_PATH` | `8710`, `/mcp` | HTTP listener (always 127.0.0.1) |
|
|
87
|
+
| `MCP_PUBLIC_HOST` | – | Public hostname(s) in front of it, comma-separated |
|
|
88
|
+
| `MCP_ALLOWED_ORIGINS` | – | Extra browser origins allowed to call it, comma-separated, e.g. `https://app.example.com` |
|
|
89
|
+
| `MCP_PRINTER` | CUPS default, else first printer | |
|
|
90
|
+
| `CUPS_SERVER` | local CUPS | A CUPS server on another machine, e.g. `printserver.lan:631` (also `CUPS_USER`, `CUPS_ENCRYPTION`) |
|
|
91
|
+
| `MCP_CUPS_PASSWORD` | – | Password for a CUPS server that asks for one (with `CUPS_USER`) |
|
|
92
|
+
| `MCP_MAX_MB` | `32` | Largest file accepted for printing, in MiB |
|
|
93
|
+
| `MCP_MAX_COPIES` | `10` | Most copies allowed in one print job |
|
|
94
|
+
| `S3_ENDPOINT_URL`, `S3_REGION`, `S3_BUCKET`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ADDRESSING_STYLE` | – , `us-east-1`, …, `auto` | Upload storage; see `examples/s3.env.example` |
|
|
95
|
+
|
|
96
|
+
To print through CUPS on another machine, that server must accept remote clients (`cupsctl --remote-any`,
|
|
97
|
+
or `Listen`/`Allow` in `cupsd.conf`). If it requires a login, set `CUPS_USER` and `MCP_CUPS_PASSWORD`
|
|
98
|
+
(preferably with `CUPS_ENCRYPTION=Required`).
|
|
99
|
+
|
|
100
|
+
## Connecting remote clients
|
|
101
|
+
|
|
102
|
+
Remote (web) clients need a public HTTPS URL. **The server has no authentication of its own**: put it
|
|
103
|
+
behind a reverse proxy or tunnel that does (for example an OAuth-capable proxy or a zero-trust tunnel), and
|
|
104
|
+
set `MCP_PUBLIC_HOST` to that hostname. If the client calls it from a browser page, add that page's origin
|
|
105
|
+
to `MCP_ALLOWED_ORIGINS`. For uploads, the client must be able to reach your bucket's endpoint.
|
|
106
|
+
|
|
107
|
+
## Security
|
|
108
|
+
|
|
109
|
+
- Run it as a dedicated user; `examples/cups-mcp.service` shows a sandboxed systemd unit.
|
|
110
|
+
- Use a storage key limited to the one bucket, and a lifecycle rule that deletes old objects.
|
|
111
|
+
- The client can upload but never gets a link to read an upload back, and the server never downloads
|
|
112
|
+
from URLs it's given.
|
|
113
|
+
|
|
114
|
+
## Known issues
|
|
115
|
+
|
|
116
|
+
- **Blank pages from some PDFs.** libcupsfilters 2.2.x with PDFio 1.6.6 or older prints PDFs with chained
|
|
117
|
+
stream filters (e.g. `[/ASCII85Decode /FlateDecode]`, ReportLab's default) as blank pages, while reporting
|
|
118
|
+
success. Fixed in PDFio 1.6.7 ([libcupsfilters#301](https://github.com/OpenPrinting/libcupsfilters/issues/301)):
|
|
119
|
+
update PDFio, or re-save such PDFs with Flate only (e.g. `qpdf --decode-level=generalized`).
|
|
120
|
+
- **Linux only.**
|
|
121
|
+
|
|
122
|
+
## Licence
|
|
123
|
+
|
|
124
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
cups_mcp.py,sha256=1hZ-eXXSmDwzUgVBwnkfv1IBAJJCh6NZvt0XXwA3Awk,21920
|
|
2
|
+
cups_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=SbQW_Wy5b4IRebNGTwO-3FSc6LIbSevMPrbF0tJKssk,1063
|
|
3
|
+
cups_mcp-0.1.0.dist-info/METADATA,sha256=-_0_rkzmVVQW-4BvSTiCh1ylhHAqvx_ehdmY1qvwmpI,5659
|
|
4
|
+
cups_mcp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
cups_mcp-0.1.0.dist-info/entry_points.txt,sha256=rAL2GMECyI3UELp6lXo6zsECAYxGfwNRjdazqNus984,43
|
|
6
|
+
cups_mcp-0.1.0.dist-info/top_level.txt,sha256=kKUg3W_l5VJnvG-EX7qZMWYxpWTEi7ttaL4Gz6zcw44,9
|
|
7
|
+
cups_mcp-0.1.0.dist-info/RECORD,,
|
|
@@ -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
|
+
cups_mcp
|
cups_mcp.py
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
"""cups-mcp: printing (CUPS) and file uploads (S3-compatible storage) for any MCP client.
|
|
2
|
+
|
|
3
|
+
Settings (environment): see README.md. Everything has a working default except storage (S3_*), which
|
|
4
|
+
only the upload tools need.
|
|
5
|
+
|
|
6
|
+
Run: cups-mcp -> stdio
|
|
7
|
+
cups-mcp --http -> streamable HTTP on 127.0.0.1:$MCP_PORT (default 8710) at $MCP_PATH
|
|
8
|
+
|
|
9
|
+
Files reach the printer as plain text (print_text), or by uploading them first: get_upload_link gives a presigned S3 URL, then print_file(id).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import secrets
|
|
16
|
+
import sys
|
|
17
|
+
import tempfile
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Literal
|
|
20
|
+
|
|
21
|
+
import cups
|
|
22
|
+
from mcp.server.mcpserver import MCPServer
|
|
23
|
+
from mcp.server.mcpserver.exceptions import ToolError # the only errors whose message reaches the client
|
|
24
|
+
from mcp.server.transport_security import TransportSecuritySettings
|
|
25
|
+
|
|
26
|
+
MAX_MB = float(os.environ.get("MCP_MAX_MB") or 32) # largest file accepted for printing, in MiB
|
|
27
|
+
MAX_BYTES = int(MAX_MB * 1024 * 1024)
|
|
28
|
+
SIZE_LIMIT = f"{MAX_MB:g} MiB"
|
|
29
|
+
MAX_COPIES = int(os.environ.get("MCP_MAX_COPIES") or 10) # most copies allowed in one print job
|
|
30
|
+
|
|
31
|
+
_public = [h.strip() for h in os.environ.get("MCP_PUBLIC_HOST", "").split(",") if h.strip()]
|
|
32
|
+
# Browser origins allowed to call the server, besides localhost and the public hosts (comma-separated).
|
|
33
|
+
_origins = [o.strip() for o in os.environ.get("MCP_ALLOWED_ORIGINS", "").split(",") if o.strip()]
|
|
34
|
+
mcp = MCPServer("cups-mcp")
|
|
35
|
+
# Streamable HTTP settings, used by main() --http. Always 127.0.0.1: put an authenticating proxy in front.
|
|
36
|
+
HTTP_SETTINGS = dict(
|
|
37
|
+
host="127.0.0.1",
|
|
38
|
+
port=int(os.environ.get("MCP_PORT", "8710")),
|
|
39
|
+
streamable_http_path=os.environ.get("MCP_PATH", "/mcp"),
|
|
40
|
+
stateless_http=True,
|
|
41
|
+
json_response=True,
|
|
42
|
+
transport_security=TransportSecuritySettings(
|
|
43
|
+
enable_dns_rebinding_protection=True,
|
|
44
|
+
allowed_hosts=["127.0.0.1:*", "localhost:*", *_public],
|
|
45
|
+
allowed_origins=["http://127.0.0.1:*", "http://localhost:*",
|
|
46
|
+
*[f"https://{h}" for h in _public], *_origins],
|
|
47
|
+
),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# CUPS is reached through libcups (pycups): CUPS_SERVER, CUPS_USER and CUPS_ENCRYPTION work as usual.
|
|
52
|
+
# MCP_CUPS_PASSWORD answers a password request from the server; without it, authentication is declined
|
|
53
|
+
# instead of waiting for a prompt nobody can answer.
|
|
54
|
+
cups.setPasswordCB(lambda prompt: os.environ.get("MCP_CUPS_PASSWORD", ""))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def cups_server() -> str:
|
|
58
|
+
return os.environ.get("CUPS_SERVER") or "the local CUPS"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def cups_conn() -> "cups.Connection":
|
|
62
|
+
try:
|
|
63
|
+
return cups.Connection()
|
|
64
|
+
except RuntimeError as e:
|
|
65
|
+
raise ToolError(f"can't reach the CUPS scheduler at {cups_server()}: {e}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def cups_call(fn, *args, **kwargs):
|
|
69
|
+
"""Run a pycups call, turning CUPS errors into messages for the caller."""
|
|
70
|
+
try:
|
|
71
|
+
return fn(*args, **kwargs)
|
|
72
|
+
except cups.IPPError as e:
|
|
73
|
+
status, message = (e.args + ("",))[:2]
|
|
74
|
+
raise ToolError(f"CUPS refused the request: {message or status}")
|
|
75
|
+
except RuntimeError as e:
|
|
76
|
+
raise ToolError(f"CUPS error: {e}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_printer(printer: str, conn: "cups.Connection") -> None:
|
|
80
|
+
known = {**cups_call(conn.getPrinters), **cups_call(conn.getClasses)}
|
|
81
|
+
if printer not in known:
|
|
82
|
+
raise ToolError(f"no printer named {printer!r} in {cups_server()}; available: {', '.join(sorted(known)) or 'none'}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def default_printer(conn: "cups.Connection | None" = None) -> str:
|
|
86
|
+
if os.environ.get("MCP_PRINTER"):
|
|
87
|
+
return os.environ["MCP_PRINTER"]
|
|
88
|
+
conn = conn or cups_conn()
|
|
89
|
+
name = cups_call(conn.getDefault) or next(iter(sorted(cups_call(conn.getPrinters))), None)
|
|
90
|
+
if not name:
|
|
91
|
+
raise ToolError(f"no printer configured in {cups_server()} (set MCP_PRINTER or a CUPS default)")
|
|
92
|
+
return name
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# Standard CUPS/IPP job options accepted in `options`, with the values allowed. Printer-specific
|
|
96
|
+
# options (tray, media type, ...) come from the printer's own list; see printer_options.
|
|
97
|
+
STANDARD_OPTIONS = {
|
|
98
|
+
"orientation-requested": r"[3-6]",
|
|
99
|
+
"number-up": r"1|2|4|6|9|16",
|
|
100
|
+
"number-up-layout": r"lrtb|lrbt|rltb|rlbt|tblr|tbrl|btlr|btrl",
|
|
101
|
+
"page-border": r"none|single|single-thick|double|double-thick",
|
|
102
|
+
"page-set": r"all|odd|even",
|
|
103
|
+
"outputorder": r"normal|reverse",
|
|
104
|
+
"collate": r"true|false",
|
|
105
|
+
"mirror": r"true|false",
|
|
106
|
+
"print-color-mode": r"auto|monochrome|color",
|
|
107
|
+
"sides": r"one-sided|two-sided-long-edge|two-sided-short-edge",
|
|
108
|
+
"media": r"[\w.-]{1,40}",
|
|
109
|
+
"position": r"center|top|bottom|left|right|top-left|top-right|bottom-left|bottom-right",
|
|
110
|
+
"page-left": r"\d{1,4}", "page-right": r"\d{1,4}", "page-top": r"\d{1,4}", "page-bottom": r"\d{1,4}",
|
|
111
|
+
}
|
|
112
|
+
STANDARD_HELP = {
|
|
113
|
+
"orientation-requested": "3 portrait, 4 landscape, 5 reverse landscape, 6 reverse portrait",
|
|
114
|
+
"number-up": "pages per sheet", "page-set": "print only odd or even pages",
|
|
115
|
+
"page-left": "margin in points (1/72 in); also page-right/top/bottom",
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# IPP attributes used when a queue has no driver file (driverless queues, CUPS 3): option -> attribute stem.
|
|
120
|
+
IPP_OPTIONS = {"media": "media", "media-source": "media-source", "media-type": "media-type",
|
|
121
|
+
"output-bin": "output-bin", "print-color-mode": "print-color-mode", "sides": "sides"}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def printer_specific_options(printer: str, conn: "cups.Connection | None" = None) -> dict[str, tuple[list[str], str | None]]:
|
|
125
|
+
"""{option: (allowed values, default)}: from the printer's driver (PPD), else its IPP attributes."""
|
|
126
|
+
conn = conn or cups_conn()
|
|
127
|
+
try:
|
|
128
|
+
ppd_file = conn.getPPD(printer)
|
|
129
|
+
except cups.IPPError:
|
|
130
|
+
ppd_file = None
|
|
131
|
+
opts: dict[str, tuple[list[str], str | None]] = {}
|
|
132
|
+
if ppd_file:
|
|
133
|
+
try:
|
|
134
|
+
ppd = cups.PPD(ppd_file)
|
|
135
|
+
custom = ppd.findAttr("CustomPageSize") is not None
|
|
136
|
+
for group in ppd.optionGroups:
|
|
137
|
+
for o in group.options:
|
|
138
|
+
if o.keyword == "PageRegion": # set by CUPS itself; lpoptions hides it too
|
|
139
|
+
continue
|
|
140
|
+
values = [c["choice"] for c in o.choices if c["choice"] != "Custom"]
|
|
141
|
+
if o.keyword == "PageSize" and custom:
|
|
142
|
+
values.append("Custom.WIDTHxHEIGHT")
|
|
143
|
+
opts[o.keyword] = (values, o.defchoice)
|
|
144
|
+
finally:
|
|
145
|
+
os.unlink(ppd_file)
|
|
146
|
+
return opts
|
|
147
|
+
attrs = cups_call(conn.getPrinterAttributes, printer)
|
|
148
|
+
for option, stem in IPP_OPTIONS.items():
|
|
149
|
+
values = attrs.get(f"{stem}-supported")
|
|
150
|
+
if values:
|
|
151
|
+
values = [str(v) for v in (values if isinstance(values, list) else [values])]
|
|
152
|
+
default = attrs.get(f"{stem}-default")
|
|
153
|
+
opts[option] = (values, None if default is None else str(default))
|
|
154
|
+
return opts
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def job_options(printer: str, options: dict[str, str] | None, conn: "cups.Connection") -> dict[str, str]:
|
|
158
|
+
"""Validate pass-through options against the standard list and the printer's own options."""
|
|
159
|
+
if not options:
|
|
160
|
+
return {}
|
|
161
|
+
specific = printer_specific_options(printer, conn)
|
|
162
|
+
checked: dict[str, str] = {}
|
|
163
|
+
for key, value in options.items():
|
|
164
|
+
value = str(value)
|
|
165
|
+
if key in specific:
|
|
166
|
+
allowed = specific[key][0]
|
|
167
|
+
ok = value in allowed or ("Custom.WIDTHxHEIGHT" in allowed and re.fullmatch(r"Custom\.[\d.]+x[\d.]+(mm|cm|in|pt)?", value))
|
|
168
|
+
elif key in STANDARD_OPTIONS:
|
|
169
|
+
ok = re.fullmatch(STANDARD_OPTIONS[key], value)
|
|
170
|
+
else:
|
|
171
|
+
raise ToolError(f"unknown option {key!r} for {printer}; see printer_options")
|
|
172
|
+
if not ok:
|
|
173
|
+
raise ToolError(f"value {value!r} isn't allowed for option {key!r}; see printer_options")
|
|
174
|
+
checked[key] = value
|
|
175
|
+
return checked
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def send_to_cups(path: Path, title: str, printer: str | None, copies: int, duplex: bool, page_ranges: str | None,
|
|
179
|
+
paper: str | None, quality: str | None, scaling: str | None, ppi: int | None,
|
|
180
|
+
options: dict[str, str] | None) -> str:
|
|
181
|
+
"""Submit a file to CUPS as it is; CUPS converts and scales it."""
|
|
182
|
+
if not 1 <= copies <= MAX_COPIES:
|
|
183
|
+
raise ToolError(f"copies must be 1-{MAX_COPIES}")
|
|
184
|
+
conn = cups_conn()
|
|
185
|
+
printer = printer or default_printer(conn)
|
|
186
|
+
check_printer(printer, conn)
|
|
187
|
+
opts = {"copies": str(copies)}
|
|
188
|
+
if duplex:
|
|
189
|
+
opts["sides"] = "two-sided-long-edge"
|
|
190
|
+
if page_ranges:
|
|
191
|
+
if not re.fullmatch(r"\d+(-\d+)?(,\d+(-\d+)?)*", page_ranges):
|
|
192
|
+
raise ToolError('page_ranges must look like "1-3,5"')
|
|
193
|
+
opts["page-ranges"] = page_ranges
|
|
194
|
+
if paper:
|
|
195
|
+
opts["media"] = paper
|
|
196
|
+
if quality:
|
|
197
|
+
opts["print-quality"] = str({"Draft": 3, "Normal": 4, "High": 5}[quality])
|
|
198
|
+
if scaling:
|
|
199
|
+
opts["print-scaling"] = scaling
|
|
200
|
+
if ppi:
|
|
201
|
+
if not 30 <= ppi <= 4800:
|
|
202
|
+
raise ToolError("ppi must be 30-4800")
|
|
203
|
+
opts["ppi"] = str(ppi)
|
|
204
|
+
opts.update(job_options(printer, options, conn))
|
|
205
|
+
job_id = cups_call(conn.printFile, printer, str(path), title[:100], opts)
|
|
206
|
+
return f"Sent to {printer} as job {printer}-{job_id}."
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
SUPPORTED = "PDF, PostScript, PNG, JPEG, TIFF or plain text"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def as_text(raw: bytes) -> str | None:
|
|
213
|
+
"""Decode raw as text, or None if it looks binary."""
|
|
214
|
+
for enc in ("utf-8-sig", "utf-16") if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else ("utf-8-sig", "cp1252"):
|
|
215
|
+
try:
|
|
216
|
+
text = raw.decode(enc)
|
|
217
|
+
except UnicodeDecodeError:
|
|
218
|
+
continue
|
|
219
|
+
sample = text[:8192]
|
|
220
|
+
bad = sum(1 for c in sample if ord(c) < 32 and c not in "\t\n\r\f")
|
|
221
|
+
return text if bad <= len(sample) // 100 else None
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def sniff(raw: bytes) -> str | None:
|
|
226
|
+
"""The file types CUPS prints itself, detected from the contents ("html" is reported so it can be refused)."""
|
|
227
|
+
head = raw[:16]
|
|
228
|
+
if head.startswith(b"%PDF-"):
|
|
229
|
+
return "pdf"
|
|
230
|
+
if head.startswith(b"%!"):
|
|
231
|
+
return "ps"
|
|
232
|
+
if head.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
233
|
+
return "png"
|
|
234
|
+
if head.startswith(b"\xff\xd8\xff"):
|
|
235
|
+
return "jpg"
|
|
236
|
+
if head.startswith((b"II*\x00", b"MM\x00*")):
|
|
237
|
+
return "tif"
|
|
238
|
+
text = as_text(raw)
|
|
239
|
+
if text is None:
|
|
240
|
+
return None
|
|
241
|
+
if re.match(r"(<!--.*?-->\s*)*(<!doctype html|<html|<head|<body)", text.lstrip()[:4096].lower(), re.S):
|
|
242
|
+
return "html"
|
|
243
|
+
return "txt"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def print_bytes(raw: bytes, title: str, printer: str | None, copies: int, duplex: bool, page_ranges: str | None,
|
|
247
|
+
paper: str | None, quality: str | None, scaling: str | None, ppi: int | None,
|
|
248
|
+
options: dict[str, str] | None) -> str:
|
|
249
|
+
"""The one print path: check the type, then hand the file to CUPS unchanged."""
|
|
250
|
+
kind = sniff(raw)
|
|
251
|
+
if kind == "html":
|
|
252
|
+
raise ToolError('HTML files aren\'t printed as files; make a PDF of it and print that')
|
|
253
|
+
if kind is None:
|
|
254
|
+
raise ToolError(f"unsupported file type; this server prints {SUPPORTED}")
|
|
255
|
+
with tempfile.TemporaryDirectory(prefix="mcp-print-") as d:
|
|
256
|
+
path = Path(d) / f"file.{kind}"
|
|
257
|
+
path.write_bytes(raw)
|
|
258
|
+
return send_to_cups(path, Path(title).name or path.name, printer, copies, duplex, page_ranges, paper,
|
|
259
|
+
quality, scaling, ppi, options)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
PRINT_OPTIONS_DOC = """
|
|
263
|
+
Print options (all optional): copies, duplex, page_ranges ("1-3,5"), paper, quality, printer;
|
|
264
|
+
scaling: auto (shrink only if too big), fit (fit the page, keep proportions), fill (fill the
|
|
265
|
+
page, crop overflow), none (actual size). Usually fit for photos and screenshots, and
|
|
266
|
+
left unset (printer default) for documents;
|
|
267
|
+
ppi: override an image's resolution;
|
|
268
|
+
options: other CUPS options such as {"InputSlot": "Manual", "number-up": "2"}; printer_options
|
|
269
|
+
lists what the printer accepts."""
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@mcp.tool()
|
|
273
|
+
def list_printers() -> str:
|
|
274
|
+
"""List printers and their state."""
|
|
275
|
+
conn = cups_conn()
|
|
276
|
+
printers = cups_call(conn.getPrinters)
|
|
277
|
+
if not printers:
|
|
278
|
+
return f"No printers in {cups_server()}."
|
|
279
|
+
default = os.environ.get("MCP_PRINTER") or cups_call(conn.getDefault)
|
|
280
|
+
states = {3: "idle", 4: "printing", 5: "stopped"}
|
|
281
|
+
lines = []
|
|
282
|
+
for name, a in sorted(printers.items()):
|
|
283
|
+
line = f"{name}{' (default)' if name == default else ''}: {states.get(a.get('printer-state'), 'unknown')}"
|
|
284
|
+
if not a.get("printer-is-accepting-jobs", True):
|
|
285
|
+
line += ", not accepting jobs"
|
|
286
|
+
for key in ("printer-state-message", "printer-info", "printer-location"):
|
|
287
|
+
if a.get(key) and a[key] != name:
|
|
288
|
+
line += f"; {a[key]}"
|
|
289
|
+
lines.append(line)
|
|
290
|
+
return "\n".join(lines)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
@mcp.tool()
|
|
294
|
+
def printer_options(printer: str | None = None) -> str:
|
|
295
|
+
"""Show what a printer accepts in the print tools' `options` (its own options such as tray and
|
|
296
|
+
media type, plus standard CUPS job options), with allowed values and defaults (*)."""
|
|
297
|
+
conn = cups_conn()
|
|
298
|
+
printer = printer or default_printer(conn)
|
|
299
|
+
check_printer(printer, conn)
|
|
300
|
+
lines = [f"Printer: {printer}", "", "Printer-specific options:"]
|
|
301
|
+
for key, (values, default) in printer_specific_options(printer, conn).items():
|
|
302
|
+
lines.append(f" {key}: " + " ".join(("*" + v) if v == default else v for v in values))
|
|
303
|
+
lines += ["", "Standard job options:"]
|
|
304
|
+
for key, rx in STANDARD_OPTIONS.items():
|
|
305
|
+
allowed = rx.replace("|", " ") if re.fullmatch(r"[\w| -]+", rx) else "(" + {"[3-6]": "3-6", r"\d{1,4}": "number"}.get(rx, "text") + ")"
|
|
306
|
+
lines.append(f" {key}: {allowed}" + (f" ({STANDARD_HELP[key]})" if key in STANDARD_HELP else ""))
|
|
307
|
+
lines += ["", "Also direct arguments: copies, duplex, page_ranges, paper, quality, "
|
|
308
|
+
"scaling (auto|fit|fill|none), ppi."]
|
|
309
|
+
return "\n".join(lines)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@mcp.tool()
|
|
313
|
+
def print_queue() -> str:
|
|
314
|
+
"""Show pending print jobs."""
|
|
315
|
+
conn = cups_conn()
|
|
316
|
+
jobs = cups_call(conn.getJobs, which_jobs="not-completed",
|
|
317
|
+
requested_attributes=["job-id", "job-name", "job-state", "job-printer-uri", "job-k-octets"])
|
|
318
|
+
if not jobs:
|
|
319
|
+
return "No pending jobs."
|
|
320
|
+
states = {3: "pending", 4: "held", 5: "printing", 6: "stopped"}
|
|
321
|
+
lines = []
|
|
322
|
+
for job_id, a in sorted(jobs.items()):
|
|
323
|
+
printer = str(a.get("job-printer-uri", "")).rstrip("/").rsplit("/", 1)[-1] or "?"
|
|
324
|
+
name = f"\t{a['job-name']}" if a.get("job-name") else "" # CUPS hides job names by default
|
|
325
|
+
lines.append(f"{printer}-{job_id}\t{states.get(a.get('job-state'), 'unknown')}\t{a.get('job-k-octets', '?')} KB{name}")
|
|
326
|
+
return "\n".join(lines)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@mcp.tool()
|
|
330
|
+
def cancel_job(job_id: str) -> str:
|
|
331
|
+
"""Cancel a print job by id (e.g. "Office_Printer-42" or "42", from print_queue)."""
|
|
332
|
+
m = re.fullmatch(r"(?:[\w.-]+-)?(\d+)", job_id)
|
|
333
|
+
if not m:
|
|
334
|
+
raise ToolError("job_id looks like PRINTER-NUMBER, from print_queue")
|
|
335
|
+
try:
|
|
336
|
+
cups_conn().cancelJob(int(m.group(1)))
|
|
337
|
+
except cups.IPPError as e:
|
|
338
|
+
if e.args and e.args[0] == cups.IPP_NOT_FOUND:
|
|
339
|
+
raise ToolError(f"no job {job_id} (already finished or cancelled?); see print_queue")
|
|
340
|
+
raise ToolError(f"CUPS refused the request: {(e.args + ('',))[1] or e.args[0]}")
|
|
341
|
+
return f"Cancelled {job_id}."
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
@mcp.tool(description="""Print plain text you write (notes, lists, a short letter). CUPS lays it out
|
|
345
|
+
in a monospaced font. For anything formatted (headings, tables, images), make a PDF and
|
|
346
|
+
print it with get_upload_link + print_file.""" + PRINT_OPTIONS_DOC)
|
|
347
|
+
def print_text(
|
|
348
|
+
text: str,
|
|
349
|
+
title: str = "Text",
|
|
350
|
+
copies: int = 1,
|
|
351
|
+
duplex: bool = False,
|
|
352
|
+
page_ranges: str | None = None,
|
|
353
|
+
paper: Literal["Letter", "Legal", "A4"] | None = None,
|
|
354
|
+
quality: Literal["Draft", "Normal", "High"] | None = None,
|
|
355
|
+
scaling: Literal["auto", "fit", "fill", "none"] | None = None,
|
|
356
|
+
ppi: int | None = None,
|
|
357
|
+
options: dict[str, str] | None = None,
|
|
358
|
+
printer: str | None = None,
|
|
359
|
+
) -> str:
|
|
360
|
+
raw = text.encode()
|
|
361
|
+
if len(raw) > MAX_BYTES:
|
|
362
|
+
raise ToolError("text too large")
|
|
363
|
+
if sniff(raw) != "txt":
|
|
364
|
+
raise ToolError("print_text takes plain text; for HTML or other formats, make a PDF and use print_file")
|
|
365
|
+
return print_bytes(raw, title, printer, copies, duplex, page_ranges, paper, quality, scaling, ppi, options)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
@mcp.tool(description="""Print a small file sent as base64 (only for tiny files: every byte costs
|
|
369
|
+
tokens). Prefer get_upload_link + print_file for files, or print_text for plain text.
|
|
370
|
+
Prints """ + SUPPORTED + "." + PRINT_OPTIONS_DOC)
|
|
371
|
+
def print_file_data(
|
|
372
|
+
data_base64: str,
|
|
373
|
+
filename: str = "document.pdf",
|
|
374
|
+
copies: int = 1,
|
|
375
|
+
duplex: bool = False,
|
|
376
|
+
page_ranges: str | None = None,
|
|
377
|
+
paper: Literal["Letter", "Legal", "A4"] | None = None,
|
|
378
|
+
quality: Literal["Draft", "Normal", "High"] | None = None,
|
|
379
|
+
scaling: Literal["auto", "fit", "fill", "none"] | None = None,
|
|
380
|
+
ppi: int | None = None,
|
|
381
|
+
options: dict[str, str] | None = None,
|
|
382
|
+
printer: str | None = None,
|
|
383
|
+
) -> str:
|
|
384
|
+
try:
|
|
385
|
+
raw = base64.b64decode(data_base64, validate=False)
|
|
386
|
+
except Exception as e:
|
|
387
|
+
raise ToolError(f"invalid base64: {e}")
|
|
388
|
+
if len(raw) > MAX_BYTES:
|
|
389
|
+
raise ToolError(f"file too large ({SIZE_LIMIT} max)")
|
|
390
|
+
return print_bytes(raw, filename, printer, copies, duplex, page_ranges, paper, quality, scaling, ppi, options)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
# ===================== Uploads (S3-compatible storage) =====================
|
|
394
|
+
# Settings: S3_ENDPOINT_URL (e.g. https://s3.us-east-1.amazonaws.com), S3_REGION (default us-east-1),
|
|
395
|
+
# S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY; optional S3_ADDRESSING_STYLE (path|virtual|auto).
|
|
396
|
+
# Private bucket; only this server holds a key. Clients get single-file presigned PUT
|
|
397
|
+
# URLs (15 min) and refer to uploads by id.
|
|
398
|
+
|
|
399
|
+
S3_BUCKET = os.environ.get("S3_BUCKET", "")
|
|
400
|
+
UPLOAD_TTL = 900
|
|
401
|
+
UPLOAD_PREFIX = "uploads/"
|
|
402
|
+
_s3 = None
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def s3():
|
|
406
|
+
global _s3
|
|
407
|
+
if _s3 is None:
|
|
408
|
+
endpoint, key, secret = (os.environ.get(k, "") for k in ("S3_ENDPOINT_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"))
|
|
409
|
+
if not (endpoint and key and secret and S3_BUCKET):
|
|
410
|
+
raise ToolError("uploads are not configured on this server (S3 settings missing)")
|
|
411
|
+
import boto3
|
|
412
|
+
from botocore.config import Config
|
|
413
|
+
_s3 = boto3.client("s3", endpoint_url=endpoint, aws_access_key_id=key, aws_secret_access_key=secret,
|
|
414
|
+
region_name=os.environ.get("S3_REGION") or "us-east-1",
|
|
415
|
+
config=Config(signature_version="s3v4", retries={"max_attempts": 3},
|
|
416
|
+
s3={"addressing_style": os.environ.get("S3_ADDRESSING_STYLE") or "auto"}))
|
|
417
|
+
return _s3
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _upload_key(file_id: str) -> str:
|
|
421
|
+
if not re.fullmatch(r"[0-9a-f]{16}", file_id):
|
|
422
|
+
raise ToolError("file id should be the 16-character id from get_upload_link")
|
|
423
|
+
return UPLOAD_PREFIX + file_id
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
@mcp.tool(description="""Get a one-time link for uploading ONE file (PDF, PostScript, PNG, JPEG, TIFF or text; up to """ + SIZE_LIMIT + """).
|
|
428
|
+
|
|
429
|
+
Upload it with an HTTP PUT, not by pasting its contents, e.g.:
|
|
430
|
+
curl -sS -T /path/to/file.pdf "<url>"
|
|
431
|
+
The link works for 15 minutes. Then use the returned id with print_file.
|
|
432
|
+
""")
|
|
433
|
+
def get_upload_link() -> str:
|
|
434
|
+
file_id = secrets.token_hex(8)
|
|
435
|
+
url = s3().generate_presigned_url("put_object", Params={"Bucket": S3_BUCKET, "Key": _upload_key(file_id)},
|
|
436
|
+
ExpiresIn=UPLOAD_TTL)
|
|
437
|
+
return (f"id: {file_id}\nupload_url: {url}\nexpires_in: {UPLOAD_TTL // 60} minutes\n"
|
|
438
|
+
f'upload with: curl -sS -T <file> "<upload_url>" then call print_file(id="{file_id}")')
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
@mcp.tool()
|
|
442
|
+
def list_uploads() -> str:
|
|
443
|
+
"""List files that have been uploaded and not yet printed (they are deleted after a day)."""
|
|
444
|
+
resp = s3().list_objects_v2(Bucket=S3_BUCKET, Prefix=UPLOAD_PREFIX)
|
|
445
|
+
items = resp.get("Contents", [])
|
|
446
|
+
if not items:
|
|
447
|
+
return "No uploads waiting."
|
|
448
|
+
return "\n".join(f"{o['Key'][len(UPLOAD_PREFIX):]}\t{o['LastModified']:%Y-%m-%d %H:%M}\t{o['Size'] // 1024} KB"
|
|
449
|
+
for o in sorted(items, key=lambda o: o["LastModified"], reverse=True))
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
@mcp.tool(description="""Print a file uploaded with get_upload_link, by its id. The upload is deleted
|
|
453
|
+
after printing unless keep=True (e.g. to print it again with different settings).
|
|
454
|
+
Prints """ + SUPPORTED + "." + PRINT_OPTIONS_DOC)
|
|
455
|
+
def print_file(
|
|
456
|
+
id: str,
|
|
457
|
+
keep: bool = False,
|
|
458
|
+
copies: int = 1,
|
|
459
|
+
duplex: bool = False,
|
|
460
|
+
page_ranges: str | None = None,
|
|
461
|
+
paper: Literal["Letter", "Legal", "A4"] | None = None,
|
|
462
|
+
quality: Literal["Draft", "Normal", "High"] | None = None,
|
|
463
|
+
scaling: Literal["auto", "fit", "fill", "none"] | None = None,
|
|
464
|
+
ppi: int | None = None,
|
|
465
|
+
options: dict[str, str] | None = None,
|
|
466
|
+
printer: str | None = None,
|
|
467
|
+
) -> str:
|
|
468
|
+
key = _upload_key(id)
|
|
469
|
+
client = s3()
|
|
470
|
+
try:
|
|
471
|
+
head = client.head_object(Bucket=S3_BUCKET, Key=key)
|
|
472
|
+
except Exception:
|
|
473
|
+
raise ToolError(f"no upload with id {id} (not uploaded yet, already printed, or expired)")
|
|
474
|
+
if head["ContentLength"] > MAX_BYTES:
|
|
475
|
+
client.delete_object(Bucket=S3_BUCKET, Key=key)
|
|
476
|
+
raise ToolError(f"upload too large ({SIZE_LIMIT} max); it has been deleted")
|
|
477
|
+
raw = client.get_object(Bucket=S3_BUCKET, Key=key)["Body"].read(MAX_BYTES + 1)
|
|
478
|
+
if sniff(raw) in (None, "html"):
|
|
479
|
+
client.delete_object(Bucket=S3_BUCKET, Key=key)
|
|
480
|
+
raise ToolError(f"unsupported file type (this server prints {SUPPORTED}); it has been deleted")
|
|
481
|
+
out = print_bytes(raw, f"upload-{id}", printer, copies, duplex, page_ranges, paper, quality, scaling, ppi, options)
|
|
482
|
+
if not keep:
|
|
483
|
+
client.delete_object(Bucket=S3_BUCKET, Key=key)
|
|
484
|
+
return out + ("" if keep else " Upload deleted.")
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def main() -> None:
|
|
488
|
+
if "--http" in sys.argv:
|
|
489
|
+
mcp.run("streamable-http", **HTTP_SETTINGS)
|
|
490
|
+
else:
|
|
491
|
+
mcp.run("stdio")
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
if __name__ == "__main__":
|
|
495
|
+
main()
|