libscanner-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.
- libscanner_mcp/__init__.py +7 -0
- libscanner_mcp/api.py +169 -0
- libscanner_mcp/cli.py +76 -0
- libscanner_mcp/limits.py +111 -0
- libscanner_mcp/server.py +449 -0
- libscanner_mcp-0.1.0.dist-info/METADATA +178 -0
- libscanner_mcp-0.1.0.dist-info/RECORD +10 -0
- libscanner_mcp-0.1.0.dist-info/WHEEL +4 -0
- libscanner_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- libscanner_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
libscanner_mcp/api.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Thin client for the libscanner HTTP API (https://api.libscanner.com/v1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import http.cookiejar
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx2
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
|
|
15
|
+
DEFAULT_API_URL = "https://api.libscanner.com"
|
|
16
|
+
USER_AGENT = f"libscanner-mcp/{__version__}"
|
|
17
|
+
|
|
18
|
+
# The API accepts JPEG and PNG up to 8 MB.
|
|
19
|
+
MAX_IMAGE_BYTES = 8_000_000
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _no_cookies() -> http.cookiejar.CookieJar:
|
|
23
|
+
return http.cookiejar.CookieJar(policy=http.cookiejar.DefaultCookiePolicy(allowed_domains=[]))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ApiError(Exception):
|
|
27
|
+
"""An error answer of the API, or no answer at all.
|
|
28
|
+
|
|
29
|
+
`code` is the stable machine-readable code of the API (INVALID_KEY,
|
|
30
|
+
DAY_LIMIT, IMAGE_TOO_LARGE ...); NETWORK when the API did not answer.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, status: int, code: str, message: str, *, retry_after: int | None = None,
|
|
34
|
+
usage: dict[str, Any] | None = None) -> None:
|
|
35
|
+
super().__init__(message)
|
|
36
|
+
self.status = status
|
|
37
|
+
self.code = code
|
|
38
|
+
self.message = message
|
|
39
|
+
self.retry_after = retry_after
|
|
40
|
+
self.usage = usage
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class GeneratedCode:
|
|
45
|
+
png: bytes
|
|
46
|
+
width: int | None
|
|
47
|
+
height: int | None
|
|
48
|
+
# Symbol size in modules, rows x columns ("26x26"); None when unknown.
|
|
49
|
+
size: str | None
|
|
50
|
+
usage: dict[str, Any] | None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class LibscannerApi:
|
|
54
|
+
"""One instance per server; the API key is passed with every call.
|
|
55
|
+
|
|
56
|
+
The key is never stored on the instance: in the cloud server each request
|
|
57
|
+
carries the key of its own user.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, base_url: str = DEFAULT_API_URL, *, transport: httpx2.AsyncBaseTransport | None = None,
|
|
61
|
+
timeout: float = 40.0) -> None:
|
|
62
|
+
self._base_url = base_url.rstrip("/")
|
|
63
|
+
self._transport = transport
|
|
64
|
+
self._timeout = timeout
|
|
65
|
+
# One connection pool for all calls (keep-alive: no new TLS handshake
|
|
66
|
+
# per tool call). A client belongs to an event loop, so it is created
|
|
67
|
+
# lazily in the loop that uses it and re-created if the loop changes.
|
|
68
|
+
self._http: httpx2.AsyncClient | None = None
|
|
69
|
+
self._http_loop: asyncio.AbstractEventLoop | None = None
|
|
70
|
+
|
|
71
|
+
def _client(self) -> httpx2.AsyncClient:
|
|
72
|
+
loop = asyncio.get_running_loop()
|
|
73
|
+
if self._http is None or self._http.is_closed or self._http_loop is not loop:
|
|
74
|
+
self._http = httpx2.AsyncClient(
|
|
75
|
+
base_url=self._base_url,
|
|
76
|
+
transport=self._transport,
|
|
77
|
+
timeout=self._timeout,
|
|
78
|
+
headers={"User-Agent": USER_AGENT},
|
|
79
|
+
# The client is shared by every user of the cloud server: a cookie
|
|
80
|
+
# set in an answer to one user (by the API or a proxy in front of
|
|
81
|
+
# it) must never travel with the requests of another. The jar
|
|
82
|
+
# accepts nothing and sends nothing.
|
|
83
|
+
cookies=_no_cookies(),
|
|
84
|
+
)
|
|
85
|
+
self._http_loop = loop
|
|
86
|
+
return self._http
|
|
87
|
+
|
|
88
|
+
async def aclose(self) -> None:
|
|
89
|
+
"""Close the connection pool (server shutdown)."""
|
|
90
|
+
if self._http is not None:
|
|
91
|
+
await self._http.aclose()
|
|
92
|
+
self._http = None
|
|
93
|
+
|
|
94
|
+
async def _send(self, key: str, method: str, path: str, **kwargs: Any) -> httpx2.Response:
|
|
95
|
+
# The key goes with the request, never onto the shared client.
|
|
96
|
+
headers = {**kwargs.pop("headers", {}), "Authorization": f"Bearer {key}"}
|
|
97
|
+
try:
|
|
98
|
+
response = await self._client().request(method, path, headers=headers, **kwargs)
|
|
99
|
+
except httpx2.HTTPError as exc:
|
|
100
|
+
# The text of the exception may contain the URL but never the key
|
|
101
|
+
# (the key travels in a header).
|
|
102
|
+
raise ApiError(0, "NETWORK", f"The libscanner API did not answer: {type(exc).__name__}") from exc
|
|
103
|
+
if response.status_code >= 400:
|
|
104
|
+
raise _error_from(response)
|
|
105
|
+
return response
|
|
106
|
+
|
|
107
|
+
async def decode(self, key: str, *, image: bytes | None = None, image_url: str | None = None,
|
|
108
|
+
mode: str = "single", symbologies: str | None = None, gs1: bool = True,
|
|
109
|
+
lang: str = "en") -> dict[str, Any]:
|
|
110
|
+
"""POST /v1/decode: exactly one of `image` (JPEG/PNG bytes) and `image_url`."""
|
|
111
|
+
if (image is None) == (image_url is None):
|
|
112
|
+
raise ValueError("pass exactly one of image and image_url")
|
|
113
|
+
params: dict[str, Any] = {"mode": mode, "gs1": "true" if gs1 else "false", "lang": lang}
|
|
114
|
+
if symbologies:
|
|
115
|
+
params["symbologies"] = symbologies
|
|
116
|
+
if image is not None:
|
|
117
|
+
response = await self._send(key, "POST", "/v1/decode", params=params, content=image,
|
|
118
|
+
headers={"Content-Type": "application/octet-stream"})
|
|
119
|
+
else:
|
|
120
|
+
response = await self._send(key, "POST", "/v1/decode", json={**params, "image_url": image_url,
|
|
121
|
+
"gs1": gs1})
|
|
122
|
+
return response.json()
|
|
123
|
+
|
|
124
|
+
async def generate(self, key: str, *, data: str, symbology: str = "datamatrix", gs1: str = "off",
|
|
125
|
+
ecc: str | None = None, module_px: int | None = None, lang: str = "en") -> GeneratedCode:
|
|
126
|
+
"""POST /v1/generate: the PNG image of the code with its dimensions."""
|
|
127
|
+
body: dict[str, Any] = {"data": data, "symbology": symbology, "gs1": gs1, "lang": lang}
|
|
128
|
+
if ecc is not None:
|
|
129
|
+
body["ecc"] = ecc
|
|
130
|
+
if module_px is not None:
|
|
131
|
+
body["module_px"] = module_px
|
|
132
|
+
response = await self._send(key, "POST", "/v1/generate", json=body, headers={"Accept": "application/json"})
|
|
133
|
+
answer = response.json()
|
|
134
|
+
return GeneratedCode(
|
|
135
|
+
png=base64.b64decode(answer["image_base64"]),
|
|
136
|
+
width=answer.get("width"),
|
|
137
|
+
height=answer.get("height"),
|
|
138
|
+
size=answer.get("size"),
|
|
139
|
+
usage=answer.get("usage"),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
async def parse(self, key: str, *, code: str, lang: str = "en") -> dict[str, Any]:
|
|
143
|
+
"""POST /v1/gs1/parse: GS1 fields and a structure check of the code string."""
|
|
144
|
+
response = await self._send(key, "POST", "/v1/gs1/parse", json={"code": code, "lang": lang})
|
|
145
|
+
return response.json()
|
|
146
|
+
|
|
147
|
+
async def usage(self, key: str) -> dict[str, Any]:
|
|
148
|
+
"""GET /v1/usage: the plan and the remaining limits."""
|
|
149
|
+
response = await self._send(key, "GET", "/v1/usage")
|
|
150
|
+
return response.json()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _error_from(response: httpx2.Response) -> ApiError:
|
|
154
|
+
code = f"HTTP_{response.status_code}"
|
|
155
|
+
message = f"The libscanner API answered {response.status_code}"
|
|
156
|
+
usage = None
|
|
157
|
+
try:
|
|
158
|
+
body = response.json()
|
|
159
|
+
error = body.get("error") or {}
|
|
160
|
+
code = str(error.get("code") or code)
|
|
161
|
+
message = str(error.get("message") or message)
|
|
162
|
+
usage = body.get("usage")
|
|
163
|
+
except (ValueError, AttributeError):
|
|
164
|
+
pass # not JSON (a proxy error page) - the status is all we know
|
|
165
|
+
retry_after = None
|
|
166
|
+
header = response.headers.get("Retry-After", "")
|
|
167
|
+
if header.isdigit():
|
|
168
|
+
retry_after = int(header)
|
|
169
|
+
return ApiError(response.status_code, code, message, retry_after=retry_after, usage=usage)
|
libscanner_mcp/cli.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Command line: `libscanner-mcp` (local, stdio) or `libscanner-mcp --http` (cloud)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import logging
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .server import KEYS_URL, Settings, build_server
|
|
11
|
+
|
|
12
|
+
# Loggers that at INFO write what the callers sent: the SDK logs the text of every
|
|
13
|
+
# failed tool call (the API messages quote GS1 data, the host of image_url), the
|
|
14
|
+
# HTTP client - every request URL. The cloud server keeps warnings only; who
|
|
15
|
+
# called and how it ended is in the access log of uvicorn (address, path, status).
|
|
16
|
+
QUIET_LOGGERS = ("mcp", "httpx", "httpx2")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_http_app(settings: Settings, **overrides):
|
|
20
|
+
"""The ASGI application of the cloud server (Streamable HTTP at /mcp).
|
|
21
|
+
|
|
22
|
+
`overrides` go to build_server (tests replace the API client).
|
|
23
|
+
"""
|
|
24
|
+
from mcp.server.transport_security import TransportSecuritySettings
|
|
25
|
+
from starlette.responses import JSONResponse
|
|
26
|
+
|
|
27
|
+
mcp = build_server(settings, **overrides)
|
|
28
|
+
for name in QUIET_LOGGERS:
|
|
29
|
+
logging.getLogger(name).setLevel(logging.WARNING)
|
|
30
|
+
|
|
31
|
+
@mcp.custom_route("/healthz", methods=["GET"])
|
|
32
|
+
async def healthz(_request):
|
|
33
|
+
return JSONResponse({"status": "ok", "version": __version__})
|
|
34
|
+
|
|
35
|
+
# Behind a real host name every request is rejected until the name is
|
|
36
|
+
# listed: the default accepts only localhost (DNS rebinding protection).
|
|
37
|
+
security = None
|
|
38
|
+
if settings.allowed_hosts:
|
|
39
|
+
hosts = [h for host in settings.allowed_hosts for h in (host, f"{host}:*")]
|
|
40
|
+
security = TransportSecuritySettings(allowed_hosts=hosts)
|
|
41
|
+
# json_response: one JSON answer per request, no event stream - the tools
|
|
42
|
+
# answer at once and keep no state between calls.
|
|
43
|
+
return mcp.streamable_http_app(json_response=True, stateless_http=True, transport_security=security)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def main(argv: list[str] | None = None) -> int:
|
|
47
|
+
parser = argparse.ArgumentParser(
|
|
48
|
+
prog="libscanner-mcp",
|
|
49
|
+
description="MCP server for libscanner.com: read and generate DataMatrix, QR and barcodes, parse GS1 codes.",
|
|
50
|
+
epilog=f"Local use: set LIBSCANNER_API_KEY (get a key at {KEYS_URL}) and run without arguments.",
|
|
51
|
+
)
|
|
52
|
+
parser.add_argument("--version", action="version", version=f"libscanner-mcp {__version__}")
|
|
53
|
+
parser.add_argument("--http", action="store_true",
|
|
54
|
+
help="serve Streamable HTTP (the cloud flavour: the key comes with every request)")
|
|
55
|
+
parser.add_argument("--host", default="127.0.0.1", help="address to listen on with --http (default 127.0.0.1)")
|
|
56
|
+
parser.add_argument("--port", type=int, default=8000, help="port to listen on with --http (default 8000)")
|
|
57
|
+
args = parser.parse_args(argv)
|
|
58
|
+
|
|
59
|
+
if args.http:
|
|
60
|
+
import uvicorn
|
|
61
|
+
|
|
62
|
+
app = build_http_app(Settings.from_env("cloud"))
|
|
63
|
+
# proxy_headers: TLS ends at the reverse proxy in front of the server.
|
|
64
|
+
uvicorn.run(app, host=args.host, port=args.port, proxy_headers=True, log_level="info")
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
settings = Settings.from_env("local")
|
|
68
|
+
if not settings.api_key:
|
|
69
|
+
# Not fatal: the client still lists the tools, and a call explains what to set.
|
|
70
|
+
print(f"libscanner-mcp: LIBSCANNER_API_KEY is not set - get a key at {KEYS_URL}", file=sys.stderr)
|
|
71
|
+
build_server(settings).run("stdio")
|
|
72
|
+
return 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
sys.exit(main())
|
libscanner_mcp/limits.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Daily limit for calls without sign-in (the cloud server)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Callable, Sequence
|
|
8
|
+
from datetime import UTC, datetime, timedelta
|
|
9
|
+
|
|
10
|
+
# The day of the limits starts at 00:00 Moscow time, like the day of the API.
|
|
11
|
+
_MOSCOW = timedelta(hours=3)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _today() -> str:
|
|
15
|
+
return (datetime.now(UTC) + _MOSCOW).strftime("%Y-%m-%d")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AnonymousLimiter:
|
|
19
|
+
"""Calls a day without sign-in, kept in memory.
|
|
20
|
+
|
|
21
|
+
Every call counts against its address (IPv6: its /64) and against the
|
|
22
|
+
address's network (IPv4 /24, IPv6 /48): a /48 holds 65 536 networks /64, so
|
|
23
|
+
the per-address allowance alone would let one IPv6 holder take a million
|
|
24
|
+
calls a day. On top of that one ceiling for all calls of the day caps what
|
|
25
|
+
the service key can spend.
|
|
26
|
+
|
|
27
|
+
Requests of some clients (claude.ai) come from the addresses of the
|
|
28
|
+
provider, not of the user: for these networks the limit is one shared
|
|
29
|
+
counter with its own, larger value (not part of the ceiling).
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, per_address: int, *, per_network: int | None = None, total: int | None = None,
|
|
33
|
+
shared_networks: Sequence[str] = (), shared_limit: int = 0,
|
|
34
|
+
today: Callable[[], str] = _today, max_addresses: int = 100_000) -> None:
|
|
35
|
+
self._per_address = per_address
|
|
36
|
+
self._per_network = per_network if per_network is not None else per_address * 10
|
|
37
|
+
self._total = total
|
|
38
|
+
self._shared_networks = [ipaddress.ip_network(n) for n in shared_networks]
|
|
39
|
+
self._shared_limit = shared_limit
|
|
40
|
+
self._today = today
|
|
41
|
+
self._max_addresses = max_addresses
|
|
42
|
+
self._lock = threading.Lock()
|
|
43
|
+
self._day = ""
|
|
44
|
+
self._counts: dict[str, int] = {}
|
|
45
|
+
self._used = 0
|
|
46
|
+
|
|
47
|
+
def _buckets(self, address: str) -> tuple[list[tuple[str, int]], bool]:
|
|
48
|
+
"""The counters this call takes from, and whether it is within the daily ceiling."""
|
|
49
|
+
try:
|
|
50
|
+
ip = ipaddress.ip_address(address)
|
|
51
|
+
except ValueError:
|
|
52
|
+
# No usable address (a proxy that did not set the header): all such
|
|
53
|
+
# callers share one ordinary allowance instead of getting no limit.
|
|
54
|
+
return [("unknown", self._per_address)], True
|
|
55
|
+
for network in self._shared_networks:
|
|
56
|
+
if ip.version == network.version and ip in network:
|
|
57
|
+
return [(f"shared:{network}", self._shared_limit)], False
|
|
58
|
+
if ip.version == 6:
|
|
59
|
+
# A single host owns a whole /64; a customer usually gets a /48.
|
|
60
|
+
own = str(ipaddress.ip_network(f"{ip}/64", strict=False))
|
|
61
|
+
net = str(ipaddress.ip_network(f"{ip}/48", strict=False))
|
|
62
|
+
else:
|
|
63
|
+
own = str(ip)
|
|
64
|
+
net = str(ipaddress.ip_network(f"{ip}/24", strict=False))
|
|
65
|
+
return [(own, self._per_address), (f"net:{net}", self._per_network)], True
|
|
66
|
+
|
|
67
|
+
def take(self, address: str) -> bool:
|
|
68
|
+
"""Counts one call. False - an allowance (address, network or the day) is used up."""
|
|
69
|
+
buckets, in_total = self._buckets(address)
|
|
70
|
+
day = self._today()
|
|
71
|
+
with self._lock:
|
|
72
|
+
if day != self._day:
|
|
73
|
+
self._day = day
|
|
74
|
+
self._counts.clear()
|
|
75
|
+
self._used = 0
|
|
76
|
+
if in_total and self._total is not None and self._used >= self._total:
|
|
77
|
+
return False
|
|
78
|
+
if any(self._counts.get(key, 0) >= limit for key, limit in buckets):
|
|
79
|
+
return False
|
|
80
|
+
# A flood of distinct addresses must not grow the table without
|
|
81
|
+
# bound: once it is full, new addresses are refused for the day. The
|
|
82
|
+
# network allowance makes filling it take hundreds of networks.
|
|
83
|
+
new = sum(1 for key, _ in buckets if key not in self._counts)
|
|
84
|
+
if new and len(self._counts) + new > self._max_addresses:
|
|
85
|
+
return False
|
|
86
|
+
for key, _ in buckets:
|
|
87
|
+
self._counts[key] = self._counts.get(key, 0) + 1
|
|
88
|
+
if in_total:
|
|
89
|
+
self._used += 1
|
|
90
|
+
return True
|
|
91
|
+
|
|
92
|
+
def give_back(self, address: str) -> None:
|
|
93
|
+
"""Returns a call counted by take() that the API did not serve.
|
|
94
|
+
|
|
95
|
+
All anonymous calls go out with one service key, so the per-key rate
|
|
96
|
+
limit of the API or a failure on our side refuses callers who did
|
|
97
|
+
nothing wrong: such a call must not use up their allowance. A call of
|
|
98
|
+
the previous day is not returned (the counters are already reset).
|
|
99
|
+
"""
|
|
100
|
+
buckets, in_total = self._buckets(address)
|
|
101
|
+
with self._lock:
|
|
102
|
+
if self._day != self._today():
|
|
103
|
+
return
|
|
104
|
+
for key, _ in buckets:
|
|
105
|
+
left = self._counts.get(key, 0) - 1
|
|
106
|
+
if left > 0:
|
|
107
|
+
self._counts[key] = left
|
|
108
|
+
else:
|
|
109
|
+
self._counts.pop(key, None)
|
|
110
|
+
if in_total and self._used > 0:
|
|
111
|
+
self._used -= 1
|
libscanner_mcp/server.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""The MCP server: four tools over the libscanner HTTP API.
|
|
2
|
+
|
|
3
|
+
Two flavours with the same tools:
|
|
4
|
+
|
|
5
|
+
* local (stdio) - runs on the user's machine, the API key comes from the
|
|
6
|
+
environment; `decode_code` can read an image file from disk (`image_path`)
|
|
7
|
+
and `generate_code` can save the PNG (`output_path`);
|
|
8
|
+
* cloud (Streamable HTTP) - https://mcp.libscanner.com/mcp; the key comes with
|
|
9
|
+
every request (`Authorization: Bearer lsk_live_...` or `X-API-Key`).
|
|
10
|
+
`parse_gs1` and `generate_code` also work without a key, with a small daily
|
|
11
|
+
limit per client address.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import base64
|
|
17
|
+
import binascii
|
|
18
|
+
import os
|
|
19
|
+
from collections.abc import Mapping
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Annotated, Any, Literal
|
|
23
|
+
|
|
24
|
+
from mcp.server import MCPServer
|
|
25
|
+
from mcp.server.mcpserver import Context, Image
|
|
26
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
27
|
+
from mcp.types import ToolAnnotations
|
|
28
|
+
from pydantic import Field
|
|
29
|
+
|
|
30
|
+
from .api import DEFAULT_API_URL, MAX_IMAGE_BYTES, ApiError, LibscannerApi
|
|
31
|
+
from .limits import AnonymousLimiter
|
|
32
|
+
|
|
33
|
+
KEYS_URL = "https://libscanner.com/cabinet/api"
|
|
34
|
+
DOCS_URL = "https://libscanner.com/api/"
|
|
35
|
+
|
|
36
|
+
# A model writes tool arguments character by character, so base64 is only
|
|
37
|
+
# good for tiny images; a photo goes by URL or, locally, by file path.
|
|
38
|
+
MAX_BASE64_IMAGE_BYTES = 64 * 1024
|
|
39
|
+
|
|
40
|
+
Symbology = Literal["datamatrix", "qr", "code128", "gs1-128", "ean"]
|
|
41
|
+
Lang = Literal["en", "ru"]
|
|
42
|
+
|
|
43
|
+
INSTRUCTIONS = (
|
|
44
|
+
"Tools of libscanner.com for 2D and linear barcodes. "
|
|
45
|
+
"decode_code reads DataMatrix, QR, Code 128, GS1-128 and EAN/UPC codes in a JPEG or PNG image and returns the "
|
|
46
|
+
"exact text of each code, its GS1 fields and a structure check. "
|
|
47
|
+
"parse_gs1 does the same check for a code string without an image: GS1 application identifiers, the GTIN check "
|
|
48
|
+
"digit, the Chestny ZNAK («Честный знак») verification fields, missing GS separators. "
|
|
49
|
+
"generate_code creates a DataMatrix image, optionally validated as GS1 or as a Chestny ZNAK marking code, or a "
|
|
50
|
+
"QR Code for links and text. "
|
|
51
|
+
"The tools check the format of a code; they do not query the status of an item in a government marking system."
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Settings:
|
|
57
|
+
mode: Literal["local", "cloud"] = "local"
|
|
58
|
+
api_url: str = DEFAULT_API_URL
|
|
59
|
+
# local: the key of the user (LIBSCANNER_API_KEY).
|
|
60
|
+
api_key: str | None = None
|
|
61
|
+
# cloud: the service key used for calls without sign-in (parse_gs1,
|
|
62
|
+
# generate_code). Not set - such calls are refused.
|
|
63
|
+
anonymous_api_key: str | None = None
|
|
64
|
+
anonymous_daily_limit: int = 20
|
|
65
|
+
# ...per network (IPv4 /24, IPv6 /48) and for all anonymous calls of the day.
|
|
66
|
+
anonymous_network_daily_limit: int = 200
|
|
67
|
+
anonymous_total_daily_limit: int = 5000
|
|
68
|
+
# Networks whose requests come from the provider's addresses, not the
|
|
69
|
+
# user's (claude.ai): one shared counter with its own limit.
|
|
70
|
+
shared_networks: tuple[str, ...] = ("160.79.104.0/21",)
|
|
71
|
+
shared_daily_limit: int = 2000
|
|
72
|
+
# cloud: the header in which the reverse proxy passes the client address.
|
|
73
|
+
# The proxy must set it itself, overwriting whatever the client sent.
|
|
74
|
+
client_address_header: str = "x-real-ip"
|
|
75
|
+
# cloud: public host names of the server (DNS rebinding protection).
|
|
76
|
+
allowed_hosts: tuple[str, ...] = field(default_factory=tuple)
|
|
77
|
+
|
|
78
|
+
@staticmethod
|
|
79
|
+
def from_env(mode: Literal["local", "cloud"], env: Mapping[str, str] | None = None) -> Settings:
|
|
80
|
+
env = os.environ if env is None else env
|
|
81
|
+
hosts = tuple(h.strip() for h in env.get("LIBSCANNER_MCP_ALLOWED_HOSTS", "").split(",") if h.strip())
|
|
82
|
+
return Settings(
|
|
83
|
+
mode=mode,
|
|
84
|
+
api_url=env.get("LIBSCANNER_API_URL", DEFAULT_API_URL),
|
|
85
|
+
api_key=env.get("LIBSCANNER_API_KEY") or None,
|
|
86
|
+
anonymous_api_key=env.get("LIBSCANNER_MCP_ANONYMOUS_API_KEY") or None,
|
|
87
|
+
anonymous_daily_limit=int(env.get("LIBSCANNER_MCP_ANONYMOUS_DAILY_LIMIT", "20")),
|
|
88
|
+
anonymous_network_daily_limit=int(env.get("LIBSCANNER_MCP_ANONYMOUS_NETWORK_DAILY_LIMIT", "200")),
|
|
89
|
+
anonymous_total_daily_limit=int(env.get("LIBSCANNER_MCP_ANONYMOUS_TOTAL_DAILY_LIMIT", "5000")),
|
|
90
|
+
shared_daily_limit=int(env.get("LIBSCANNER_MCP_SHARED_DAILY_LIMIT", "2000")),
|
|
91
|
+
allowed_hosts=hosts,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True)
|
|
96
|
+
class Caller:
|
|
97
|
+
key: str
|
|
98
|
+
anonymous: bool
|
|
99
|
+
# anonymous: the client address the call was counted against.
|
|
100
|
+
address: str = ""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def key_from_headers(headers: Mapping[str, str] | None) -> str | None:
|
|
104
|
+
"""The API key of the request: `Authorization: Bearer <key>` or `X-API-Key`."""
|
|
105
|
+
if not headers:
|
|
106
|
+
return None
|
|
107
|
+
lowered = {name.lower(): value for name, value in headers.items()}
|
|
108
|
+
authorization = lowered.get("authorization", "").strip()
|
|
109
|
+
if authorization:
|
|
110
|
+
scheme, _, value = authorization.partition(" ")
|
|
111
|
+
return value.strip() or None if scheme.lower() == "bearer" else None
|
|
112
|
+
return lowered.get("x-api-key", "").strip() or None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def is_png_or_jpeg(data: bytes) -> bool:
|
|
116
|
+
return data.startswith(b"\x89PNG\r\n\x1a\n") or data.startswith(b"\xff\xd8\xff")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _tool_error(error: ApiError, *, anonymous: bool = False) -> ToolError:
|
|
120
|
+
text = f"{error.code}: {error.message}"
|
|
121
|
+
if error.code == "INVALID_KEY" and not anonymous:
|
|
122
|
+
text += f". Create or check the API key at {KEYS_URL}"
|
|
123
|
+
# The usage of the service key that pays for anonymous calls is not the
|
|
124
|
+
# caller's business.
|
|
125
|
+
if error.usage and not anonymous:
|
|
126
|
+
usage = error.usage
|
|
127
|
+
text += (f". Used today {usage.get('day')} of {usage.get('day_limit')}, "
|
|
128
|
+
f"this period {usage.get('month')} of {usage.get('month_limit')}")
|
|
129
|
+
if error.retry_after:
|
|
130
|
+
text += f". Retry in {error.retry_after} s"
|
|
131
|
+
return ToolError(text)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def build_server(settings: Settings, *, api: LibscannerApi | None = None,
|
|
135
|
+
limiter: AnonymousLimiter | None = None) -> MCPServer:
|
|
136
|
+
"""Builds the server. `api` and `limiter` are replaced in tests."""
|
|
137
|
+
api = api or LibscannerApi(settings.api_url)
|
|
138
|
+
limiter = limiter or AnonymousLimiter(settings.anonymous_daily_limit,
|
|
139
|
+
per_network=settings.anonymous_network_daily_limit,
|
|
140
|
+
total=settings.anonymous_total_daily_limit,
|
|
141
|
+
shared_networks=settings.shared_networks,
|
|
142
|
+
shared_limit=settings.shared_daily_limit)
|
|
143
|
+
local = settings.mode == "local"
|
|
144
|
+
mcp = MCPServer(
|
|
145
|
+
"libscanner",
|
|
146
|
+
title="libscanner: DataMatrix, QR and barcodes",
|
|
147
|
+
instructions=INSTRUCTIONS,
|
|
148
|
+
website_url="https://libscanner.com/docs/api/?lang=mcp",
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def caller(ctx: Context, *, anonymous_allowed: bool) -> Caller:
|
|
152
|
+
"""Whose key pays for this call."""
|
|
153
|
+
if local:
|
|
154
|
+
if not settings.api_key:
|
|
155
|
+
raise ToolError(f"No API key: set the LIBSCANNER_API_KEY environment variable. Get a key at {KEYS_URL}")
|
|
156
|
+
return Caller(settings.api_key, anonymous=False)
|
|
157
|
+
key = key_from_headers(ctx.headers)
|
|
158
|
+
if key:
|
|
159
|
+
return Caller(key, anonymous=False)
|
|
160
|
+
if not anonymous_allowed or not settings.anonymous_api_key:
|
|
161
|
+
raise ToolError(
|
|
162
|
+
"This tool needs a libscanner API key: connect the server with the header "
|
|
163
|
+
f"'Authorization: Bearer lsk_live_...'. Get a free key at {KEYS_URL}")
|
|
164
|
+
address = {name.lower(): value for name, value in (ctx.headers or {}).items()}.get(
|
|
165
|
+
settings.client_address_header, "")
|
|
166
|
+
address = address.strip()
|
|
167
|
+
if not limiter.take(address):
|
|
168
|
+
raise ToolError(
|
|
169
|
+
"The daily limit of calls without an API key is used up. Connect the server with a free key "
|
|
170
|
+
f"({KEYS_URL}) to continue: 300 requests a month.")
|
|
171
|
+
return Caller(settings.anonymous_api_key, anonymous=True, address=address)
|
|
172
|
+
|
|
173
|
+
def failed(who: Caller, error: ApiError) -> ToolError:
|
|
174
|
+
"""The tool error of a failed API call.
|
|
175
|
+
|
|
176
|
+
An anonymous call the API did not serve - the rate or plan limit of the
|
|
177
|
+
shared service key (429), a failure on our side (5xx, no answer) - goes
|
|
178
|
+
back to the caller's allowance, and the text speaks of the service, not
|
|
179
|
+
of a key the caller does not have.
|
|
180
|
+
"""
|
|
181
|
+
if who.anonymous and (error.status in (0, 429) or error.status >= 500):
|
|
182
|
+
limiter.give_back(who.address)
|
|
183
|
+
text = f"Calls without an API key are not available at the moment ({error.code})"
|
|
184
|
+
if error.retry_after:
|
|
185
|
+
text += f". Retry in {error.retry_after} s"
|
|
186
|
+
return ToolError(f"{text} or connect the server with a free key: {KEYS_URL}")
|
|
187
|
+
return _tool_error(error, anonymous=who.anonymous)
|
|
188
|
+
|
|
189
|
+
read_only = ToolAnnotations(read_only_hint=True, open_world_hint=True)
|
|
190
|
+
|
|
191
|
+
# --- decode_code --------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
decode_description = (
|
|
194
|
+
"Read the codes in an image: DataMatrix, QR Code, Code 128, GS1-128, EAN/UPC. Returns the text of every code "
|
|
195
|
+
"(the GS1 group separator, GS, is the real character U+001D), its symbology, the corners in the image and, "
|
|
196
|
+
"for GS1 codes, the parsed application identifiers and a structure check: GTIN check digit, serial number, "
|
|
197
|
+
"Chestny ZNAK («Честный знак», код маркировки) verification fields 91/92/93, missing separators, expiry "
|
|
198
|
+
"date. status is 'ok' (read), 'not_found' (no code in the image) or 'not_decoded' (found but unreadable). "
|
|
199
|
+
"The image must be JPEG or PNG, up to 8 MB. "
|
|
200
|
+
+ ("Pass image_path for a file on this machine, or image_url for a public http(s) link. "
|
|
201
|
+
if local else
|
|
202
|
+
"Pass image_url: a public http(s) link to the image. A file attached to the chat is not reachable from "
|
|
203
|
+
"here - ask for a link to it. ")
|
|
204
|
+
+ "image_base64 is only for tiny images (up to 64 KB)."
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
async def run_decode(ctx: Context, *, image_url: str | None, image_path: str | None, image_base64: str | None,
|
|
208
|
+
mode: str, symbologies: list[str] | None, lang: str) -> dict[str, Any]:
|
|
209
|
+
given = [name for name, value in (("image_url", image_url), ("image_path", image_path),
|
|
210
|
+
("image_base64", image_base64)) if value]
|
|
211
|
+
if len(given) != 1:
|
|
212
|
+
options = "image_path, image_url or image_base64" if local else "image_url or image_base64"
|
|
213
|
+
raise ToolError(f"Pass exactly one of {options}")
|
|
214
|
+
image: bytes | None = None
|
|
215
|
+
if image_path:
|
|
216
|
+
image = _read_image_file(image_path)
|
|
217
|
+
elif image_base64:
|
|
218
|
+
image = _decode_base64_image(image_base64)
|
|
219
|
+
who = caller(ctx, anonymous_allowed=False)
|
|
220
|
+
try:
|
|
221
|
+
return await api.decode(who.key, image=image, image_url=image_url if image is None else None,
|
|
222
|
+
mode=mode, symbologies=",".join(symbologies) if symbologies else None,
|
|
223
|
+
gs1=True, lang=lang)
|
|
224
|
+
except ApiError as error:
|
|
225
|
+
raise _tool_error(error) from None
|
|
226
|
+
|
|
227
|
+
if local:
|
|
228
|
+
@mcp.tool(name="decode_code", title="Read barcodes in an image", description=decode_description,
|
|
229
|
+
annotations=read_only)
|
|
230
|
+
async def decode_code_local(
|
|
231
|
+
ctx: Context,
|
|
232
|
+
image_path: Annotated[str | None, Field(description="Path to a JPEG or PNG file on this machine.")] = None,
|
|
233
|
+
image_url: Annotated[str | None, Field(description="Public http(s) URL of the image.")] = None,
|
|
234
|
+
image_base64: Annotated[str | None, Field(description="The image file in base64, up to 64 KB.")] = None,
|
|
235
|
+
mode: Annotated[Literal["single", "multi"],
|
|
236
|
+
Field(description="single - the first code found, fast; multi - every code, up to 64.")] = "single",
|
|
237
|
+
symbologies: Annotated[list[Symbology] | None,
|
|
238
|
+
Field(description="What to look for; everything by default.")] = None,
|
|
239
|
+
lang: Annotated[Lang, Field(description="Language of field names and check messages.")] = "en",
|
|
240
|
+
) -> dict[str, Any]:
|
|
241
|
+
return await run_decode(ctx, image_url=image_url, image_path=image_path, image_base64=image_base64,
|
|
242
|
+
mode=mode, symbologies=list(symbologies) if symbologies else None, lang=lang)
|
|
243
|
+
else:
|
|
244
|
+
@mcp.tool(name="decode_code", title="Read barcodes in an image", description=decode_description,
|
|
245
|
+
annotations=read_only)
|
|
246
|
+
async def decode_code_cloud(
|
|
247
|
+
ctx: Context,
|
|
248
|
+
image_url: Annotated[str | None, Field(description="Public http(s) URL of the image.")] = None,
|
|
249
|
+
image_base64: Annotated[str | None, Field(description="The image file in base64, up to 64 KB.")] = None,
|
|
250
|
+
mode: Annotated[Literal["single", "multi"],
|
|
251
|
+
Field(description="single - the first code found, fast; multi - every code, up to 64.")] = "single",
|
|
252
|
+
symbologies: Annotated[list[Symbology] | None,
|
|
253
|
+
Field(description="What to look for; everything by default.")] = None,
|
|
254
|
+
lang: Annotated[Lang, Field(description="Language of field names and check messages.")] = "en",
|
|
255
|
+
) -> dict[str, Any]:
|
|
256
|
+
return await run_decode(ctx, image_url=image_url, image_path=None, image_base64=image_base64,
|
|
257
|
+
mode=mode, symbologies=list(symbologies) if symbologies else None, lang=lang)
|
|
258
|
+
|
|
259
|
+
# --- parse_gs1 ----------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
@mcp.tool(
|
|
262
|
+
title="Parse and check a GS1 / Chestny ZNAK code string",
|
|
263
|
+
description=(
|
|
264
|
+
"Parse a code string as GS1 and check its structure without an image: application identifiers (01 GTIN, "
|
|
265
|
+
"21 serial number, 17 expiry date, 10 batch ...), the GTIN check digit, the Chestny ZNAK («Честный знак», "
|
|
266
|
+
"код маркировки) verification key and code (91 + 92 or 93), a missing GS separator (FNC1), an expired "
|
|
267
|
+
"date. The separator in the string may be the character U+001D or the text <GS>. is_gs1 is false when "
|
|
268
|
+
"the string is not GS1. Checks the format only, not the status of the item in the marking system."),
|
|
269
|
+
annotations=read_only,
|
|
270
|
+
)
|
|
271
|
+
async def parse_gs1(
|
|
272
|
+
ctx: Context,
|
|
273
|
+
code: Annotated[str, Field(description="The code string as read from the symbol.", max_length=4096)],
|
|
274
|
+
lang: Annotated[Lang, Field(description="Language of field names and check messages.")] = "en",
|
|
275
|
+
) -> dict[str, Any]:
|
|
276
|
+
who = caller(ctx, anonymous_allowed=True)
|
|
277
|
+
try:
|
|
278
|
+
return await api.parse(who.key, code=code, lang=lang)
|
|
279
|
+
except ApiError as error:
|
|
280
|
+
raise failed(who, error) from None
|
|
281
|
+
|
|
282
|
+
# --- generate_code ------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
generate_description = (
|
|
285
|
+
"Create a code image (PNG) from a string: a DataMatrix (default) or, with symbology='qr', a QR Code for "
|
|
286
|
+
"links and text. For DataMatrix, gs1='gs1' validates the data against the GS1 General Specifications and "
|
|
287
|
+
"encodes it as GS1 DataMatrix; gs1='cz' adds the Chestny ZNAK («Честный знак», код маркировки) profile. GS1 "
|
|
288
|
+
"data may be written in bracketed form, '(01)04601234567893(21)5Abc(93)dGVz', or raw with the separator as "
|
|
289
|
+
"<GS>. Marking codes are printed as DataMatrix: gs1 is not available for QR. Invalid data is rejected with "
|
|
290
|
+
"an explanation of what is wrong."
|
|
291
|
+
+ (" Pass output_path to save the PNG to a new file on this machine." if local else "")
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
async def run_generate(ctx: Context, *, data: str, symbology: str, gs1: str, ecc: str, module_px: int, lang: str,
|
|
295
|
+
output_path: str | None) -> list[Any]:
|
|
296
|
+
qr = symbology == "qr"
|
|
297
|
+
if qr and gs1 != "off":
|
|
298
|
+
raise ToolError("gs1 is available for datamatrix only: marking codes are DataMatrix, QR is for links and text")
|
|
299
|
+
if not qr and len(data.encode()) > 3116:
|
|
300
|
+
raise ToolError("data is longer than 3116 bytes and does not fit into a DataMatrix symbol")
|
|
301
|
+
target = _check_output_path(output_path) if output_path else None
|
|
302
|
+
who = caller(ctx, anonymous_allowed=True)
|
|
303
|
+
try:
|
|
304
|
+
generated = await api.generate(who.key, data=data, symbology=symbology, gs1=gs1,
|
|
305
|
+
ecc=ecc if qr else None, module_px=module_px, lang=lang)
|
|
306
|
+
except ApiError as error:
|
|
307
|
+
raise failed(who, error) from None
|
|
308
|
+
note = "QR Code" if qr else "DataMatrix"
|
|
309
|
+
if generated.size:
|
|
310
|
+
note += f" {generated.size} modules"
|
|
311
|
+
if generated.width and generated.height:
|
|
312
|
+
note += f", {generated.width}x{generated.height} px"
|
|
313
|
+
if target is not None:
|
|
314
|
+
# "x": never overwrite a file that appeared in the meantime.
|
|
315
|
+
with open(target, "xb") as out:
|
|
316
|
+
out.write(generated.png)
|
|
317
|
+
note += f", saved to {target}"
|
|
318
|
+
return [Image(data=generated.png, format="png"), note]
|
|
319
|
+
|
|
320
|
+
if local:
|
|
321
|
+
# structured_output=False: the result is content blocks (the image and a
|
|
322
|
+
# line of text), not a JSON object.
|
|
323
|
+
@mcp.tool(name="generate_code", title="Create a DataMatrix or QR Code image", description=generate_description,
|
|
324
|
+
annotations=ToolAnnotations(read_only_hint=False, destructive_hint=False, open_world_hint=True),
|
|
325
|
+
structured_output=False)
|
|
326
|
+
async def generate_code_local(
|
|
327
|
+
ctx: Context,
|
|
328
|
+
data: Annotated[str, Field(description="The string to encode: up to 3116 bytes for DataMatrix, 7089 for QR.",
|
|
329
|
+
min_length=1, max_length=7089)],
|
|
330
|
+
symbology: Annotated[Literal["datamatrix", "qr"],
|
|
331
|
+
Field(description="datamatrix (default) or qr.")] = "datamatrix",
|
|
332
|
+
gs1: Annotated[Literal["off", "gs1", "cz"],
|
|
333
|
+
Field(description="DataMatrix only. off - any text; gs1 - GS1 DataMatrix; cz - GS1 with the Chestny ZNAK profile.")] = "off",
|
|
334
|
+
ecc: Annotated[Literal["L", "M", "Q", "H"],
|
|
335
|
+
Field(description="QR only: error correction level, H (highest) by default.")] = "H",
|
|
336
|
+
module_px: Annotated[int, Field(description="Pixels per module.", ge=1, le=40)] = 8,
|
|
337
|
+
lang: Annotated[Lang, Field(description="Language of the validation message.")] = "en",
|
|
338
|
+
output_path: Annotated[str | None,
|
|
339
|
+
Field(description="Where to save the PNG: a path ending in .png that does not exist yet.")] = None,
|
|
340
|
+
) -> list[Any]:
|
|
341
|
+
return await run_generate(ctx, data=data, symbology=symbology, gs1=gs1, ecc=ecc, module_px=module_px,
|
|
342
|
+
lang=lang, output_path=output_path)
|
|
343
|
+
else:
|
|
344
|
+
@mcp.tool(name="generate_code", title="Create a DataMatrix or QR Code image", description=generate_description,
|
|
345
|
+
annotations=read_only, structured_output=False)
|
|
346
|
+
async def generate_code_cloud(
|
|
347
|
+
ctx: Context,
|
|
348
|
+
data: Annotated[str, Field(description="The string to encode: up to 3116 bytes for DataMatrix, 7089 for QR.",
|
|
349
|
+
min_length=1, max_length=7089)],
|
|
350
|
+
symbology: Annotated[Literal["datamatrix", "qr"],
|
|
351
|
+
Field(description="datamatrix (default) or qr.")] = "datamatrix",
|
|
352
|
+
gs1: Annotated[Literal["off", "gs1", "cz"],
|
|
353
|
+
Field(description="DataMatrix only. off - any text; gs1 - GS1 DataMatrix; cz - GS1 with the Chestny ZNAK profile.")] = "off",
|
|
354
|
+
ecc: Annotated[Literal["L", "M", "Q", "H"],
|
|
355
|
+
Field(description="QR only: error correction level, H (highest) by default.")] = "H",
|
|
356
|
+
module_px: Annotated[int, Field(description="Pixels per module.", ge=1, le=40)] = 8,
|
|
357
|
+
lang: Annotated[Lang, Field(description="Language of the validation message.")] = "en",
|
|
358
|
+
) -> list[Any]:
|
|
359
|
+
return await run_generate(ctx, data=data, symbology=symbology, gs1=gs1, ecc=ecc, module_px=module_px,
|
|
360
|
+
lang=lang, output_path=None)
|
|
361
|
+
|
|
362
|
+
# --- get_usage ----------------------------------------------------------
|
|
363
|
+
|
|
364
|
+
@mcp.tool(
|
|
365
|
+
title="Remaining libscanner API limits",
|
|
366
|
+
description=("The plan of the API key and what is left: requests used today and in the current period, the "
|
|
367
|
+
"limits and when they reset. Not counted against the limits."),
|
|
368
|
+
annotations=read_only,
|
|
369
|
+
)
|
|
370
|
+
async def get_usage(ctx: Context) -> dict[str, Any]:
|
|
371
|
+
who = caller(ctx, anonymous_allowed=False)
|
|
372
|
+
try:
|
|
373
|
+
return await api.usage(who.key)
|
|
374
|
+
except ApiError as error:
|
|
375
|
+
raise _tool_error(error) from None
|
|
376
|
+
|
|
377
|
+
return mcp
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _local_path(text: str, what: str) -> Path:
|
|
381
|
+
"""A path on a local disk.
|
|
382
|
+
|
|
383
|
+
Network paths are refused before anything touches them: on Windows even
|
|
384
|
+
checking whether \\\\host\\share\\a.png exists makes the system
|
|
385
|
+
authenticate to that host and hand it the user's NTLM hash - an injected
|
|
386
|
+
instruction could ask for exactly that.
|
|
387
|
+
"""
|
|
388
|
+
if text.startswith(("\\\\", "//")):
|
|
389
|
+
raise ToolError(f"{what} must be a file on this machine, not a network path")
|
|
390
|
+
path = Path(text).expanduser()
|
|
391
|
+
if str(path).startswith(("\\\\", "//")) or path.drive.startswith("\\\\"):
|
|
392
|
+
raise ToolError(f"{what} must be a file on this machine, not a network path")
|
|
393
|
+
return path
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _read_image_file(image_path: str) -> bytes:
|
|
397
|
+
"""Reads a local image for decode_code.
|
|
398
|
+
|
|
399
|
+
Only JPEG and PNG files are sent to the API: checking the signature keeps
|
|
400
|
+
an injected instruction from uploading an arbitrary file (a key, a
|
|
401
|
+
config) under the name of an image.
|
|
402
|
+
"""
|
|
403
|
+
path = _local_path(image_path, "image_path")
|
|
404
|
+
try:
|
|
405
|
+
if not path.is_file():
|
|
406
|
+
raise ToolError(f"No such file: {image_path}")
|
|
407
|
+
# The size is checked on what is actually read: the file may change
|
|
408
|
+
# between stat() and reading.
|
|
409
|
+
with path.open("rb") as f:
|
|
410
|
+
data = f.read(MAX_IMAGE_BYTES + 1)
|
|
411
|
+
if len(data) > MAX_IMAGE_BYTES:
|
|
412
|
+
raise ToolError(f"The image is larger than {MAX_IMAGE_BYTES // 1_000_000} MB: {image_path}")
|
|
413
|
+
except OSError as error:
|
|
414
|
+
raise ToolError(f"Cannot read {image_path}: {error.strerror or type(error).__name__}") from None
|
|
415
|
+
if not is_png_or_jpeg(data):
|
|
416
|
+
raise ToolError(f"Not a JPEG or PNG image: {image_path}")
|
|
417
|
+
return data
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _decode_base64_image(text: str) -> bytes:
|
|
421
|
+
if text.startswith("data:"):
|
|
422
|
+
text = text.partition(",")[2]
|
|
423
|
+
# 4 base64 characters carry 3 bytes: refuse an oversized string before decoding it.
|
|
424
|
+
if len(text) > MAX_BASE64_IMAGE_BYTES * 4 // 3 + 16:
|
|
425
|
+
raise ToolError("image_base64 is limited to 64 KB; pass a larger image by image_url")
|
|
426
|
+
try:
|
|
427
|
+
data = base64.b64decode(text, validate=False)
|
|
428
|
+
except (binascii.Error, ValueError):
|
|
429
|
+
raise ToolError("image_base64 is not valid base64") from None
|
|
430
|
+
if len(data) > MAX_BASE64_IMAGE_BYTES:
|
|
431
|
+
raise ToolError("image_base64 is limited to 64 KB; pass a larger image by image_url")
|
|
432
|
+
if not is_png_or_jpeg(data):
|
|
433
|
+
raise ToolError("image_base64 is not a JPEG or PNG image")
|
|
434
|
+
return data
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _check_output_path(output_path: str) -> Path:
|
|
438
|
+
"""Where generate_code may save: a new .png file in an existing folder."""
|
|
439
|
+
path = _local_path(output_path, "output_path")
|
|
440
|
+
# "a.txt:x.png" on NTFS is a stream inside a.txt, not a new .png file.
|
|
441
|
+
if ":" in path.name:
|
|
442
|
+
raise ToolError("output_path must not contain ':' in the file name")
|
|
443
|
+
if path.suffix.lower() != ".png":
|
|
444
|
+
raise ToolError("output_path must end in .png")
|
|
445
|
+
if path.exists():
|
|
446
|
+
raise ToolError(f"The file already exists and is not overwritten: {output_path}")
|
|
447
|
+
if not path.parent.is_dir():
|
|
448
|
+
raise ToolError(f"No such folder: {path.parent}")
|
|
449
|
+
return path
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: libscanner-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server for libscanner: read and generate DataMatrix, QR and barcodes, parse GS1 and Chestny ZNAK marking codes
|
|
5
|
+
Project-URL: Homepage, https://libscanner.com/api/
|
|
6
|
+
Project-URL: Documentation, https://libscanner.com/docs/api/?lang=mcp
|
|
7
|
+
Author-email: libscanner <libscanner@yandex.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: barcode,chestny-znak,datamatrix,gs1,mcp,model-context-protocol,qr
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Multimedia :: Graphics :: Capture :: Scanners
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: httpx2<3,>=2.16
|
|
21
|
+
Requires-Dist: mcp<3,>=2.3
|
|
22
|
+
Provides-Extra: cloud
|
|
23
|
+
Requires-Dist: mcp[cli]<3,>=2.3; extra == 'cloud'
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: anyio>=4; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# libscanner MCP server
|
|
30
|
+
|
|
31
|
+
<!-- mcp-name: com.libscanner/barcode -->
|
|
32
|
+
|
|
33
|
+
An [MCP](https://modelcontextprotocol.io) server that lets Claude, ChatGPT and coding agents read and
|
|
34
|
+
create barcodes through the [libscanner API](https://libscanner.com/api/):
|
|
35
|
+
|
|
36
|
+
| Tool | What it does |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `decode_code` | Reads DataMatrix, QR Code, Code 128, GS1-128 and EAN/UPC codes in a JPEG or PNG image. Returns the exact text of every code (the GS separator is the real character U+001D), its symbology and corners, the GS1 fields and a structure check |
|
|
39
|
+
| `parse_gs1` | Parses a code string as GS1 and checks its structure without an image: application identifiers, the GTIN check digit, Chestny ZNAK («Честный знак») verification fields 91/92/93, a missing GS separator, an expired date |
|
|
40
|
+
| `generate_code` | Creates a DataMatrix image (PNG), optionally validated as GS1 DataMatrix or as a Chestny ZNAK marking code, or a QR Code for links and text |
|
|
41
|
+
| `get_usage` | The plan of the API key and the remaining limits |
|
|
42
|
+
|
|
43
|
+
Documentation: <https://libscanner.com/docs/api/?lang=mcp>.
|
|
44
|
+
|
|
45
|
+
The server contains no recognition logic. Every tool is one call to `https://api.libscanner.com/v1`
|
|
46
|
+
([OpenAPI](https://api.libscanner.com/openapi.json)); the readers are the same ones that are sold as the
|
|
47
|
+
[dmr and unir libraries](https://libscanner.com/).
|
|
48
|
+
|
|
49
|
+
The tools check the *format* of a marking code. They do not query the status of an item in a government
|
|
50
|
+
marking system.
|
|
51
|
+
|
|
52
|
+
## API key
|
|
53
|
+
|
|
54
|
+
Create a free key at <https://libscanner.com/cabinet/api> (300 requests a month, 30 a day). Paid plans and
|
|
55
|
+
limits are on the [API page](https://libscanner.com/api/#pricing).
|
|
56
|
+
|
|
57
|
+
## Local server (stdio)
|
|
58
|
+
|
|
59
|
+
The local server runs on your machine, so `decode_code` can read an image **file** (`image_path`) and
|
|
60
|
+
`generate_code` can save the PNG (`output_path`). This is the way to use it from coding agents.
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
LIBSCANNER_API_KEY=lsk_live_... uvx libscanner-mcp
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
**Claude Code**
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
claude mcp add libscanner --env LIBSCANNER_API_KEY=lsk_live_... -- uvx libscanner-mcp
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Claude Desktop, Cursor** (`claude_desktop_config.json`, `.cursor/mcp.json`)
|
|
73
|
+
|
|
74
|
+
```json
|
|
75
|
+
{
|
|
76
|
+
"mcpServers": {
|
|
77
|
+
"libscanner": {
|
|
78
|
+
"command": "uvx",
|
|
79
|
+
"args": ["libscanner-mcp"],
|
|
80
|
+
"env": { "LIBSCANNER_API_KEY": "lsk_live_..." }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**VS Code** (`.vscode/mcp.json`)
|
|
87
|
+
|
|
88
|
+
```json
|
|
89
|
+
{
|
|
90
|
+
"servers": {
|
|
91
|
+
"libscanner": {
|
|
92
|
+
"type": "stdio",
|
|
93
|
+
"command": "uvx",
|
|
94
|
+
"args": ["libscanner-mcp"],
|
|
95
|
+
"env": { "LIBSCANNER_API_KEY": "${input:libscanner-key}" }
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
"inputs": [{ "id": "libscanner-key", "type": "promptString", "description": "libscanner API key", "password": true }]
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Safety of the file parameters:
|
|
103
|
+
|
|
104
|
+
- `image_path` is sent to the API only if the file is a JPEG or PNG (checked by its signature) of at most 8 MB.
|
|
105
|
+
Any other file is refused before anything leaves the machine.
|
|
106
|
+
- `output_path` must end in `.png`, must not exist yet (nothing is overwritten) and its folder must exist.
|
|
107
|
+
- Both must be paths on this machine: network paths (`\\host\share\…`, `//host/…`) are refused before they are
|
|
108
|
+
touched — on Windows merely opening one sends the user's NTLM hash to that host.
|
|
109
|
+
|
|
110
|
+
## Cloud server (Streamable HTTP)
|
|
111
|
+
|
|
112
|
+
`https://mcp.libscanner.com/mcp` — nothing to install. The API key travels in a header:
|
|
113
|
+
|
|
114
|
+
```sh
|
|
115
|
+
claude mcp add --transport http libscanner https://mcp.libscanner.com/mcp --header "Authorization: Bearer lsk_live_..."
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
{
|
|
120
|
+
"mcpServers": {
|
|
121
|
+
"libscanner": {
|
|
122
|
+
"url": "https://mcp.libscanner.com/mcp",
|
|
123
|
+
"headers": { "Authorization": "Bearer lsk_live_..." }
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Without a key `parse_gs1` and `generate_code` still work, with a small daily limit per address — enough to
|
|
130
|
+
try the server.
|
|
131
|
+
|
|
132
|
+
The cloud server cannot see files attached to a chat: `decode_code` takes a public link (`image_url`).
|
|
133
|
+
`image_base64` exists only for tiny images (up to 64 KB), because a model writes tool arguments character
|
|
134
|
+
by character.
|
|
135
|
+
|
|
136
|
+
## Images and storage
|
|
137
|
+
|
|
138
|
+
JPEG and PNG up to 8 MB, 4096 px on a side and 16 megapixels. On paid plans images are not stored. On the
|
|
139
|
+
free plan images in which no code was read are kept for up to a year to improve recognition. Decoded codes
|
|
140
|
+
are never stored. Details: <https://libscanner.com/api/#storage>.
|
|
141
|
+
|
|
142
|
+
## Running the cloud flavour yourself
|
|
143
|
+
|
|
144
|
+
```sh
|
|
145
|
+
pip install "libscanner-mcp[cloud]"
|
|
146
|
+
LIBSCANNER_MCP_ALLOWED_HOSTS=mcp.example.com libscanner-mcp --http --host 0.0.0.0 --port 8000
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
| Variable | Meaning |
|
|
150
|
+
|---|---|
|
|
151
|
+
| `LIBSCANNER_API_URL` | API address, `https://api.libscanner.com` by default |
|
|
152
|
+
| `LIBSCANNER_API_KEY` | local server: the key of the user |
|
|
153
|
+
| `LIBSCANNER_MCP_ALLOWED_HOSTS` | cloud: public host names of the server, comma-separated. Requests under any other `Host` are rejected (DNS rebinding protection) |
|
|
154
|
+
| `LIBSCANNER_MCP_ANONYMOUS_API_KEY` | cloud: the key that pays for calls without sign-in (`parse_gs1`, `generate_code`). Not set — such calls are refused |
|
|
155
|
+
| `LIBSCANNER_MCP_ANONYMOUS_DAILY_LIMIT` | cloud: calls without sign-in per client address (IPv6: per /64) a day, 20 by default |
|
|
156
|
+
| `LIBSCANNER_MCP_ANONYMOUS_NETWORK_DAILY_LIMIT` | cloud: the same per network — IPv4 /24, IPv6 /48 — 200 by default |
|
|
157
|
+
| `LIBSCANNER_MCP_ANONYMOUS_TOTAL_DAILY_LIMIT` | cloud: all calls without sign-in a day (except the shared counter below), 5000 by default |
|
|
158
|
+
| `LIBSCANNER_MCP_SHARED_DAILY_LIMIT` | cloud: one shared daily counter for clients whose requests come from the provider's addresses (claude.ai), 2000 by default |
|
|
159
|
+
|
|
160
|
+
The reverse proxy in front of the server must pass the client address in `X-Real-IP`, overwriting whatever
|
|
161
|
+
the client sent: the limit of calls without sign-in is counted by it. A call without sign-in that the API
|
|
162
|
+
did not serve — the rate or plan limit of the service key, a failure on the API side — is not counted.
|
|
163
|
+
The service key needs the `generate` scope only (`parse_gs1` needs none); give it a plan of its own, since
|
|
164
|
+
the per-key rate limit of the API applies to all calls without sign-in together.
|
|
165
|
+
|
|
166
|
+
The cloud server logs warnings and the access log only (address, path, status): at the INFO level the SDK
|
|
167
|
+
would log the text of failed tool calls, which may quote the caller's data.
|
|
168
|
+
|
|
169
|
+
## Development
|
|
170
|
+
|
|
171
|
+
```sh
|
|
172
|
+
uv venv && uv pip install -e ".[cloud,dev]"
|
|
173
|
+
pytest
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## License
|
|
177
|
+
|
|
178
|
+
MIT. Chestny ZNAK («Честный знак») and GS1 are trademarks of their respective owners.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
libscanner_mcp/__init__.py,sha256=8JZmstv-Ti4kIwCZY-yJd6zeg9neEP-0c87QH6KV2Wk,238
|
|
2
|
+
libscanner_mcp/api.py,sha256=sEXUVP1zKaJwyDcPHmpq0will67XpNe9pl7UQAOc5mw,7262
|
|
3
|
+
libscanner_mcp/cli.py,sha256=xKsx2lpDLSNjFrzJpzaL5UcgsMWDEsJaLHdjs2BmPXI,3354
|
|
4
|
+
libscanner_mcp/limits.py,sha256=RlMZgs8q8jfBtp6Gf2AECNDrYGDrQ5R6lE8B_4op3BY,4979
|
|
5
|
+
libscanner_mcp/server.py,sha256=63-m_GgUQ-6pcM7QMyhMmyuclzaqZKOPIaLFgENdffA,24411
|
|
6
|
+
libscanner_mcp-0.1.0.dist-info/METADATA,sha256=O7CFfJLOYGInn5BzIJBKHDiMKcvUYN0XRFirvCWSg7k,7559
|
|
7
|
+
libscanner_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
libscanner_mcp-0.1.0.dist-info/entry_points.txt,sha256=IxXZNbXQlTqTasM1CSre2ABzsLypoGzfKcNfdU-e6Uc,59
|
|
9
|
+
libscanner_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=mU1husKoLcRR-ZYb2gIabdtT97qNB0dDHQGTM77C5bc,1067
|
|
10
|
+
libscanner_mcp-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 libscanner
|
|
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.
|