modio-mcp 1.0.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.
modio_mcp/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Read-only mod.io MCP server."""
modio_mcp/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .server import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
modio_mcp/client.py ADDED
@@ -0,0 +1,374 @@
1
+ """Read-only HTTP client for the mod.io v1 API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ import re
9
+ import time
10
+ from collections.abc import AsyncIterator, Mapping
11
+ from contextlib import AsyncExitStack, asynccontextmanager
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+ from urllib.parse import parse_qsl, quote, quote_plus, urlsplit
15
+
16
+ import httpx
17
+ from pydantic import BaseModel, ConfigDict
18
+ from typing_extensions import TypedDict
19
+
20
+ JsonObject = dict[str, Any]
21
+ _API_HOST = r"(?:[gu]-[0-9]+\.(?:modapi\.io|test\.mod\.io)|api\.(?:test\.)?mod\.io)"
22
+ _BASE_URL = re.compile(rf"https://{_API_HOST}(?::443)?/v1/?", re.ASCII | re.IGNORECASE)
23
+ _API_DOWNLOAD_HOST = re.compile(_API_HOST, re.ASCII | re.IGNORECASE)
24
+ _CREDENTIAL = re.compile(r"[\x21-\x7e]+", re.ASCII)
25
+ _MAX_RESPONSE_BYTES = 8 * 1024 * 1024
26
+
27
+
28
+ class ModioError(Exception):
29
+ """An error whose message is safe to return to an MCP client."""
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Settings:
34
+ base_url: str
35
+ api_key: str = field(default="", repr=False)
36
+ access_token: str = field(default="", repr=False)
37
+
38
+ def __post_init__(self) -> None:
39
+ base_url = self.base_url.strip()
40
+ api_key, access_token = self.api_key.strip(), self.access_token.strip()
41
+ if not (api_key or access_token):
42
+ raise ModioError("Set MODIO_API_BASE_URL and MODIO_API_KEY or MODIO_ACCESS_TOKEN.")
43
+ if not _BASE_URL.fullmatch(base_url):
44
+ raise ModioError(
45
+ "Set MODIO_API_BASE_URL to the HTTPS v1 API path from your mod.io dashboard "
46
+ "(g-/u- hosts on modapi.io or test.mod.io; see README for legacy paths)."
47
+ )
48
+ if not _CREDENTIAL.fullmatch(access_token or api_key):
49
+ raise ModioError("The mod.io credential must be a single printable ASCII token.")
50
+ object.__setattr__(
51
+ self, "base_url", base_url.lower().removesuffix("/").replace(":443/", "/")
52
+ )
53
+ object.__setattr__(self, "api_key", api_key)
54
+ object.__setattr__(self, "access_token", access_token)
55
+
56
+ @classmethod
57
+ def from_env(cls) -> Settings:
58
+ return cls(
59
+ base_url=os.environ.get("MODIO_API_BASE_URL", ""),
60
+ api_key=os.environ.get("MODIO_API_KEY", ""),
61
+ access_token=os.environ.get("MODIO_ACCESS_TOKEN", ""),
62
+ )
63
+
64
+
65
+ class Page(BaseModel):
66
+ model_config = ConfigDict(extra="allow")
67
+
68
+ data: list[JsonObject]
69
+ result_count: int
70
+ result_limit: int
71
+ result_offset: int
72
+ result_total: int
73
+ next_offset: int | None
74
+
75
+
76
+ class Download(TypedDict):
77
+ game_id: int
78
+ mod_id: int
79
+ file_id: int
80
+ binary_url: str
81
+ date_expires: int | None
82
+
83
+
84
+ class ModioClient:
85
+ def __init__(
86
+ self, settings: Settings, *, transport: httpx.AsyncBaseTransport | None = None
87
+ ) -> None:
88
+ self._settings = settings
89
+ # API keys must be query parameters, so don't follow redirects, use env proxies, or
90
+ # propagate the raw httpx response/exception to a caller.
91
+ self._stack = AsyncExitStack()
92
+ self._http = httpx.AsyncClient(
93
+ base_url=settings.base_url + "/",
94
+ headers={"Accept": "application/json", "User-Agent": "modio-mcp"},
95
+ follow_redirects=False,
96
+ trust_env=False,
97
+ timeout=httpx.Timeout(15.0, connect=5.0),
98
+ transport=transport,
99
+ )
100
+ self._stack.push_async_callback(self._http.aclose)
101
+ self._transfer = httpx.AsyncClient(
102
+ headers={"User-Agent": "modio-mcp", "Accept-Encoding": "identity"},
103
+ follow_redirects=False,
104
+ trust_env=False,
105
+ timeout=httpx.Timeout(30.0, connect=5.0),
106
+ transport=transport,
107
+ )
108
+ self._stack.push_async_callback(self._transfer.aclose)
109
+ self._blocked_until = 0.0
110
+ self._route_blocks: dict[str, float] = {}
111
+ self._secret_forms = sorted(
112
+ {
113
+ value
114
+ for secret in (settings.api_key, settings.access_token)
115
+ if secret
116
+ for value in (secret, quote(secret, safe=""), quote_plus(secret, safe=""))
117
+ },
118
+ key=len,
119
+ reverse=True,
120
+ )
121
+
122
+ async def __aenter__(self) -> ModioClient:
123
+ return self
124
+
125
+ async def __aexit__(self, *_: object) -> None:
126
+ await self._stack.aclose()
127
+
128
+ def _redact(self, value: Any) -> Any:
129
+ if isinstance(value, str):
130
+ for secret in self._secret_forms:
131
+ value = value.replace(secret, "[redacted]")
132
+ return value
133
+ if isinstance(value, list):
134
+ return [self._redact(item) for item in value]
135
+ if isinstance(value, dict):
136
+ return {self._redact(key): self._redact(item) for key, item in value.items()}
137
+ return value
138
+
139
+ async def _get(
140
+ self,
141
+ path: str,
142
+ *,
143
+ params: Mapping[str, str | int] | None = None,
144
+ platform: str | None = None,
145
+ ) -> JsonObject:
146
+ # mod.io endpoint cooldowns apply across IDs for the same route.
147
+ route = re.sub(r"/[0-9]+(?=/|$)", "/:id", path)
148
+ wait = math.ceil(
149
+ max(self._blocked_until, self._route_blocks.get(route, 0)) - time.monotonic()
150
+ )
151
+ if wait > 0:
152
+ raise ModioError(f"mod.io HTTP 429: wait {wait} seconds before retrying.")
153
+
154
+ query = dict(params or {})
155
+ headers: dict[str, str] = {}
156
+ if self._settings.access_token:
157
+ headers["Authorization"] = f"Bearer {self._settings.access_token}"
158
+ else:
159
+ query["api_key"] = self._settings.api_key
160
+ if platform is not None:
161
+ headers["X-Modio-Platform"] = platform
162
+
163
+ try:
164
+ async with self._http.stream("GET", path, params=query, headers=headers) as response:
165
+ status = response.status_code
166
+ retry_header = response.headers.get("retry-after", "").strip()
167
+ body = bytearray()
168
+ async for chunk in response.aiter_bytes():
169
+ if len(body) + len(chunk) > _MAX_RESPONSE_BYTES:
170
+ if status == 200:
171
+ raise ModioError("mod.io response is too large; try a smaller limit.")
172
+ body.clear()
173
+ break
174
+ body.extend(chunk)
175
+ except httpx.TimeoutException:
176
+ raise ModioError("mod.io request timed out; please retry.") from None
177
+ except httpx.RequestError:
178
+ raise ModioError(
179
+ "Could not connect to mod.io; check your network and API path."
180
+ ) from None
181
+
182
+ try:
183
+ payload = json.loads(body)
184
+ except (ValueError, RecursionError):
185
+ payload = None
186
+
187
+ if status != 200:
188
+ error = payload.get("error") if isinstance(payload, dict) else None
189
+ ref = error.get("error_ref") if isinstance(error, dict) else None
190
+ context = f" (error_ref={ref})" if type(ref) is int and 0 < ref <= 999999 else ""
191
+ message = {
192
+ 400: "check request parameters and the API path.",
193
+ 401: "credential invalid, revoked or expired; check the credential and its API path.",
194
+ 403: "access denied; check the read scope and game/content permissions.",
195
+ 404: "resource not found or not visible; check the game, mod or file ID.",
196
+ 422: "mod.io rejected the request parameters.",
197
+ }.get(status, "unexpected response from mod.io.")
198
+ if status == 429:
199
+ wait = (
200
+ (int(retry_header) or 60) if re.fullmatch(r"[0-9]{1,10}", retry_header) else 60
201
+ )
202
+ deadline = time.monotonic() + wait
203
+ if ref == 11009:
204
+ self._route_blocks[route] = max(self._route_blocks.get(route, 0), deadline)
205
+ else:
206
+ self._blocked_until = max(self._blocked_until, deadline)
207
+ message = f"rate limited; wait {wait} seconds before retrying."
208
+ elif 300 <= status < 400:
209
+ message = "redirect refused; check the dashboard API path."
210
+ elif 500 <= status < 600:
211
+ message = "mod.io is temporarily unavailable; please retry later."
212
+ raise ModioError(f"mod.io HTTP {status}{context}: {message}")
213
+
214
+ if not isinstance(payload, dict) or "error" in payload:
215
+ raise ModioError("mod.io returned an invalid JSON object.")
216
+ try:
217
+ return self._redact(payload)
218
+ except RecursionError:
219
+ raise ModioError("mod.io response has excessively nested data.") from None
220
+
221
+ async def page(
222
+ self,
223
+ path: str,
224
+ *,
225
+ limit: int,
226
+ offset: int,
227
+ params: Mapping[str, str | int] | None = None,
228
+ platform: str | None = None,
229
+ ) -> Page:
230
+ payload = await self._get(
231
+ path, params={**(params or {}), "_limit": limit, "_offset": offset}, platform=platform
232
+ )
233
+ data = payload.get("data")
234
+ count, size, start, total = (
235
+ payload.get(f"result_{name}") for name in ("count", "limit", "offset", "total")
236
+ )
237
+ if (
238
+ not isinstance(data, list)
239
+ or any(not isinstance(item, dict) for item in data)
240
+ or any(type(value) is not int or value < 0 for value in (count, size, start, total))
241
+ or count != len(data)
242
+ or count > size
243
+ ):
244
+ raise ModioError("mod.io returned invalid pagination metadata.")
245
+ end = start + count
246
+ return Page.model_validate(
247
+ {**payload, "next_offset": end if count and end < total else None}
248
+ )
249
+
250
+ async def object(
251
+ self, path: str, *, expected_id: int, platform: str | None = None
252
+ ) -> JsonObject:
253
+ obj = await self._get(path, platform=platform)
254
+ if type(obj.get("id")) is not int or obj["id"] != expected_id:
255
+ raise ModioError("mod.io returned an object with a missing or unexpected ID.")
256
+ return obj
257
+
258
+ async def modfile(
259
+ self, game_id: int, mod_id: int, file_id: int, *, platform: str | None = None
260
+ ) -> JsonObject:
261
+ obj = await self.object(
262
+ f"games/{game_id}/mods/{mod_id}/files/{file_id}", expected_id=file_id, platform=platform
263
+ )
264
+ if type(obj.get("mod_id")) is not int or obj["mod_id"] != mod_id:
265
+ raise ModioError("mod.io returned a file with a missing or unexpected mod ID.")
266
+ return obj
267
+
268
+ async def active_file_id(self, game_id: int, mod_id: int, platform: str | None) -> int:
269
+ mod = await self.object(
270
+ f"games/{game_id}/mods/{mod_id}", expected_id=mod_id, platform=platform
271
+ )
272
+ active = mod.get("modfile")
273
+ file_id = active.get("id") if isinstance(active, dict) else None
274
+ if type(file_id) is not int or file_id < 1:
275
+ raise ModioError("No active modfile for this mod and platform; specify a file ID.")
276
+ return file_id
277
+
278
+ async def fresh_download(
279
+ self, game_id: int, mod_id: int, file_id: int, platform: str | None
280
+ ) -> tuple[JsonObject, Download]:
281
+ path = f"/v1/games/{game_id}/mods/{mod_id}/files/{file_id}/download"
282
+ # Even if the mod object includes a URL, fetch the exact file. A stale
283
+ # metadata response can occur at the expiry boundary; retry it once.
284
+ for _ in range(2):
285
+ file = await self.modfile(game_id, mod_id, file_id, platform=platform)
286
+ download = file.get("download")
287
+ if not isinstance(download, dict):
288
+ raise ModioError("mod.io did not provide download metadata for this file.")
289
+ url = download.get("binary_url")
290
+ self._validate_download_url(url, path)
291
+ expires = download.get("date_expires")
292
+ if expires is not None and (type(expires) is not int or expires < 0):
293
+ raise ModioError("mod.io returned an invalid download expiry timestamp.")
294
+ if not expires or expires > time.time():
295
+ return file, Download(
296
+ game_id=game_id,
297
+ mod_id=mod_id,
298
+ file_id=file_id,
299
+ binary_url=url,
300
+ date_expires=expires or None,
301
+ )
302
+ raise ModioError("mod.io returned an already expired download URL; retry later.")
303
+
304
+ def _validate_download_url(self, url: Any, api_path: str) -> bool:
305
+ """Reject off-list destinations; return true only for the configured API origin."""
306
+ error = ModioError("mod.io did not provide a usable HTTPS download URL for this file.")
307
+ if not isinstance(url, str) or re.search(r"[\x00-\x20\x7f\\]", url):
308
+ raise error
309
+ if "[redacted]" in url or any(secret in url for secret in self._secret_forms):
310
+ raise error
311
+ try:
312
+ parsed = urlsplit(url)
313
+ host = parsed.hostname or ""
314
+ if (
315
+ parsed.scheme != "https"
316
+ or not host
317
+ or parsed.username is not None
318
+ or parsed.password is not None
319
+ or parsed.port not in (None, 443)
320
+ or parsed.fragment
321
+ or any(
322
+ key.lower() in {"api_key", "access_token"} for key, _ in parse_qsl(parsed.query)
323
+ )
324
+ ):
325
+ raise error
326
+ except ValueError:
327
+ raise error from None
328
+
329
+ if _API_DOWNLOAD_HOST.fullmatch(host):
330
+ base_host = urlsplit(self._settings.base_url).hostname or ""
331
+ if host.endswith(".test.mod.io") != base_host.endswith(
332
+ ".test.mod.io"
333
+ ) or not re.fullmatch(rf"{api_path}(?:/[A-Za-z0-9_-]+)?/?", parsed.path):
334
+ raise error
335
+ return host == base_host
336
+ if host == "cdn.mod.io" or re.fullmatch(r"(?:[a-z0-9-]+\.)*modcdn\.io", host, re.ASCII):
337
+ return False
338
+ raise ModioError("mod.io download host is not allowlisted; no connection was made to it.")
339
+
340
+ @asynccontextmanager
341
+ async def stream_download(
342
+ self, url: str, api_path: str, *, platform: str | None = None
343
+ ) -> AsyncIterator[httpx.Response]:
344
+ # Authenticate the exact same-origin download endpoint, but never forward API
345
+ # credentials (including cookies or query parameters) to a different origin.
346
+ allow_auth = True
347
+ for _ in range(6):
348
+ allow_auth = self._validate_download_url(url, api_path) and allow_auth
349
+ target = httpx.URL(url)
350
+ headers: dict[str, str] = {}
351
+ if allow_auth:
352
+ if platform is not None:
353
+ headers["X-Modio-Platform"] = platform
354
+ if self._settings.access_token:
355
+ headers["Authorization"] = f"Bearer {self._settings.access_token}"
356
+ else:
357
+ auth = str(httpx.QueryParams(api_key=self._settings.api_key)).encode("ascii")
358
+ target = target.copy_with(query=b"&".join(filter(None, (target.query, auth))))
359
+
360
+ # Construct directly so AsyncClient cannot merge cookies from a prior origin.
361
+ request = httpx.Request("GET", target, headers={**self._transfer.headers, **headers})
362
+ response = await self._transfer.send(request, stream=True)
363
+ try:
364
+ if response.status_code not in (301, 302, 303, 307, 308):
365
+ yield response
366
+ return
367
+ location = response.headers.get("location")
368
+ if not location or re.search(r"[\x00-\x20\x7f\\]", location):
369
+ raise ModioError("mod.io download redirect has an invalid destination.")
370
+ # Resolve relative redirects against the URL before adding any API key.
371
+ url = str(httpx.URL(url).join(location))
372
+ finally:
373
+ await response.aclose()
374
+ raise ModioError("mod.io download exceeded the redirect limit.")
modio_mcp/download.py ADDED
@@ -0,0 +1,173 @@
1
+ """Stream an authorized modfile into a new file, without overwrites."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import httpx
13
+ from typing_extensions import TypedDict
14
+
15
+ from .client import ModioClient, ModioError
16
+
17
+ _WINDOWS_DEVICE = re.compile(
18
+ r"(?:CON|PRN|AUX|NUL|COM[0-9¹²³]|LPT[0-9¹²³]|CONIN\$|CONOUT\$)", re.IGNORECASE
19
+ )
20
+
21
+
22
+ class SavedDownload(TypedDict):
23
+ game_id: int
24
+ mod_id: int
25
+ file_id: int
26
+ path: str
27
+ bytes_written: int
28
+ sha256: str
29
+
30
+
31
+ def _destination_dir() -> Path:
32
+ value = os.environ.get("MODIO_DOWNLOAD_DIR", "").strip()
33
+ try:
34
+ directory = Path(value) if value else Path.home() / "Downloads" / "mod.io"
35
+ if not directory.is_absolute():
36
+ raise ModioError("MODIO_DOWNLOAD_DIR must be an absolute path.")
37
+ directory.mkdir(parents=True, exist_ok=True)
38
+ return directory.resolve(strict=True)
39
+ except (OSError, RuntimeError, ValueError):
40
+ raise ModioError("Could not create or access the download directory.") from None
41
+
42
+
43
+ def _filename(value: Any) -> str:
44
+ if (
45
+ not isinstance(value, str)
46
+ or not value
47
+ or value[0].isspace()
48
+ or value.endswith((".", " "))
49
+ or re.search(r'[\x00-\x1f\x7f<>:"/\\|?*]', value)
50
+ or _WINDOWS_DEVICE.fullmatch(value.split(".", 1)[0].rstrip(" "))
51
+ ):
52
+ raise ModioError("Use a safe filename (one name with no path separators or device names).")
53
+ try:
54
+ length = len(value.encode("utf-8"))
55
+ except UnicodeError:
56
+ raise ModioError("The download filename is not valid Unicode.") from None
57
+ if length > 240:
58
+ raise ModioError("The download filename is too long; specify a shorter name.")
59
+ return value
60
+
61
+
62
+ async def save_download(
63
+ client: ModioClient,
64
+ game_id: int,
65
+ mod_id: int,
66
+ file_id: int | None,
67
+ *,
68
+ filename: str | None,
69
+ platform: str | None,
70
+ ) -> SavedDownload:
71
+ if filename is not None:
72
+ filename = _filename(filename)
73
+ directory = _destination_dir()
74
+ if file_id is None:
75
+ file_id = await client.active_file_id(game_id, mod_id, platform)
76
+ api_path = f"/v1/games/{game_id}/mods/{mod_id}/files/{file_id}/download"
77
+
78
+ for attempt in range(2):
79
+ file, download = await client.fresh_download(game_id, mod_id, file_id, platform)
80
+ destination = directory / (
81
+ filename if filename is not None else _filename(file.get("filename"))
82
+ )
83
+ size = file.get("filesize")
84
+ if size is not None and (type(size) is not int or size < 0):
85
+ raise ModioError(
86
+ "mod.io returned an invalid modfile size; the file was not downloaded."
87
+ )
88
+ filehash = file.get("filehash")
89
+ expected_md5 = filehash.get("md5") if isinstance(filehash, dict) else None
90
+ if expected_md5 == "":
91
+ expected_md5 = None
92
+ if expected_md5 is not None and (
93
+ not isinstance(expected_md5, str) or not re.fullmatch(r"[a-fA-F0-9]{32}", expected_md5)
94
+ ):
95
+ raise ModioError("mod.io returned an invalid MD5 in the file metadata.")
96
+
97
+ tmp_path: Path | None = None
98
+ try:
99
+ if os.path.lexists(destination):
100
+ raise FileExistsError
101
+ async with client.stream_download(
102
+ download["binary_url"], api_path, platform=platform
103
+ ) as response:
104
+ if response.status_code in (401, 403, 410) and attempt == 0:
105
+ # A short-lived URL may expire after metadata is fetched, before transfer.
106
+ continue
107
+ if response.status_code != 200:
108
+ raise ModioError(f"mod.io download HTTP {response.status_code}; no file saved.")
109
+ encoding = response.headers.get("Content-Encoding", "identity").strip().lower()
110
+ if encoding != "identity":
111
+ raise ModioError("mod.io download used an unexpected content encoding.")
112
+ content_length = response.headers.get("Content-Length")
113
+ expected_size = size
114
+ if content_length is not None:
115
+ if not re.fullmatch(r"[0-9]{1,19}", content_length):
116
+ raise ModioError("mod.io download used an invalid Content-Length.")
117
+ length = int(content_length)
118
+ if size is not None and size != length:
119
+ raise ModioError(
120
+ "The download Content-Length did not match its modfile size."
121
+ )
122
+ expected_size = length
123
+ sha256 = hashlib.sha256()
124
+ md5 = hashlib.md5(usedforsecurity=False) if expected_md5 else None
125
+ written = 0
126
+ with tempfile.NamedTemporaryFile(
127
+ mode="wb", dir=directory, prefix=".modio-", suffix=".part", delete=False
128
+ ) as temp:
129
+ tmp_path = Path(temp.name)
130
+ async for chunk in response.aiter_bytes():
131
+ written += len(chunk)
132
+ if expected_size is not None and written > expected_size:
133
+ raise ModioError("The download exceeded its declared size.")
134
+ temp.write(chunk)
135
+ sha256.update(chunk)
136
+ if md5 is not None:
137
+ md5.update(chunk)
138
+ if (expected_size is not None and written != expected_size) or (
139
+ md5 is not None and md5.hexdigest() != expected_md5.lower()
140
+ ):
141
+ raise ModioError("The download did not match its modfile size or MD5.")
142
+ temp.flush()
143
+ os.fsync(temp.fileno())
144
+
145
+ # Linking the completed temporary file is an atomic, no-overwrite publish.
146
+ # The early existence check avoids downloading most conflicts; os.link also
147
+ # protects against races, including a symlink created during the transfer.
148
+ os.link(tmp_path, destination)
149
+ return SavedDownload(
150
+ game_id=game_id,
151
+ mod_id=mod_id,
152
+ file_id=file_id,
153
+ path=str(destination),
154
+ bytes_written=written,
155
+ sha256=sha256.hexdigest(),
156
+ )
157
+ except FileExistsError:
158
+ raise ModioError(
159
+ "A file with that name already exists; choose another filename."
160
+ ) from None
161
+ except (httpx.RequestError, httpx.InvalidURL):
162
+ raise ModioError(
163
+ "mod.io download was interrupted or unreachable; no file saved."
164
+ ) from None
165
+ except OSError:
166
+ raise ModioError(
167
+ "Could not save the file; check disk space, permissions and hard-link support."
168
+ ) from None
169
+ finally:
170
+ if tmp_path is not None:
171
+ tmp_path.unlink(missing_ok=True)
172
+
173
+ raise ModioError("mod.io download could not be refreshed.")
modio_mcp/server.py ADDED
@@ -0,0 +1,244 @@
1
+ """Official Python MCP SDK tools for mod.io (stdio only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import AsyncIterator
7
+ from contextlib import asynccontextmanager
8
+ from dataclasses import dataclass
9
+ from typing import Annotated, Literal
10
+
11
+ import httpx
12
+ from mcp.server.fastmcp import Context, FastMCP
13
+ from mcp.types import ToolAnnotations
14
+ from pydantic import Field, StringConstraints
15
+
16
+ from .client import Download, JsonObject, ModioClient, ModioError, Page, Settings
17
+ from .download import SavedDownload, save_download
18
+
19
+ Identifier = Annotated[int, Field(strict=True, gt=0, le=2**63 - 1)]
20
+ Limit = Annotated[int, Field(strict=True, ge=1, le=100)]
21
+ Offset = Annotated[int, Field(strict=True, ge=0, le=2**63 - 1)]
22
+ Query = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=200)]
23
+ Slug = Annotated[str, StringConstraints(pattern=r"^[a-z0-9][a-z0-9-]{0,99}$")]
24
+ Tag = Annotated[
25
+ str, StringConstraints(strip_whitespace=True, min_length=1, max_length=100, pattern=r"^[^,]+$")
26
+ ]
27
+ Tags = Annotated[list[Tag], Field(min_length=1, max_length=20)]
28
+ Platform = Literal[
29
+ "source",
30
+ "windows",
31
+ "mac",
32
+ "linux",
33
+ "android",
34
+ "ios",
35
+ "xboxone",
36
+ "xboxseriesx",
37
+ "ps4",
38
+ "ps5",
39
+ "switch",
40
+ "switch2",
41
+ "oculus",
42
+ "windowsserver",
43
+ "linuxserver",
44
+ ]
45
+ TagMatch = Literal["all", "any"]
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class _App:
50
+ client: ModioClient | None = None
51
+ config_error: str | None = None
52
+
53
+
54
+ def _client(ctx: Context) -> ModioClient:
55
+ app: _App = ctx.request_context.lifespan_context
56
+ if app.client is None:
57
+ raise ModioError(app.config_error or "mod.io client not configured.")
58
+ return app.client
59
+
60
+
61
+ def create_server(
62
+ *, settings: Settings | None = None, transport: httpx.AsyncBaseTransport | None = None
63
+ ) -> FastMCP:
64
+ @asynccontextmanager
65
+ async def lifespan(_: FastMCP) -> AsyncIterator[_App]:
66
+ try:
67
+ config = settings if settings is not None else Settings.from_env()
68
+ except ModioError as exc:
69
+ # MCP initialization and tools/list still work without a credential.
70
+ yield _App(config_error=str(exc))
71
+ return
72
+ async with ModioClient(config, transport=transport) as client:
73
+ yield _App(client=client)
74
+
75
+ server = FastMCP(
76
+ "mod.io",
77
+ instructions=(
78
+ "Read-only mod.io API. Always select a game before looking up mods. "
79
+ "Use get_download_url for a short-lived link, or download_file to save it locally."
80
+ ),
81
+ lifespan=lifespan,
82
+ )
83
+
84
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
85
+ async def check_auth(ctx: Context) -> dict[str, bool]:
86
+ """Check the configured credential against the authenticated games endpoint."""
87
+ await _client(ctx).page("games", limit=1, offset=0)
88
+ return {"authenticated": True}
89
+
90
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
91
+ async def search_games(
92
+ ctx: Context,
93
+ query: Query | None = None,
94
+ slug: Slug | None = None,
95
+ limit: Limit = 20,
96
+ offset: Offset = 0,
97
+ ) -> Page:
98
+ """List games, optionally searching by name or filtering exact URL slug (name_id)."""
99
+ params: dict[str, str] = {}
100
+ if query is not None:
101
+ params["_q"] = query
102
+ if slug is not None:
103
+ params["name_id"] = slug
104
+ return await _client(ctx).page("games", limit=limit, offset=offset, params=params)
105
+
106
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
107
+ async def get_game(ctx: Context, game_id: Identifier) -> JsonObject:
108
+ """Get one game's details by numeric game ID."""
109
+ return await _client(ctx).object(f"games/{game_id}", expected_id=game_id)
110
+
111
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
112
+ async def list_game_tags(
113
+ ctx: Context,
114
+ game_id: Identifier,
115
+ limit: Limit = 20,
116
+ offset: Offset = 0,
117
+ platform: Platform | None = None,
118
+ ) -> Page:
119
+ """List a game's tag options/categories, optionally targeting a platform."""
120
+ return await _client(ctx).page(
121
+ f"games/{game_id}/tags", limit=limit, offset=offset, platform=platform
122
+ )
123
+
124
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
125
+ async def search_mods(
126
+ ctx: Context,
127
+ game_id: Identifier,
128
+ query: Query | None = None,
129
+ slug: Slug | None = None,
130
+ tags: Tags | None = None,
131
+ tag_match: TagMatch = "all",
132
+ platform: Platform | None = None,
133
+ limit: Limit = 20,
134
+ offset: Offset = 0,
135
+ ) -> Page:
136
+ """Search mods within one game by keyword, slug, tags, or X-Modio-Platform."""
137
+ params: dict[str, str] = {}
138
+ if query is not None:
139
+ params["_q"] = query
140
+ if slug is not None:
141
+ params["name_id"] = slug
142
+ if tags is not None:
143
+ params["tags" if tag_match == "all" else "tags-in"] = ",".join(dict.fromkeys(tags))
144
+ return await _client(ctx).page(
145
+ f"games/{game_id}/mods", limit=limit, offset=offset, params=params, platform=platform
146
+ )
147
+
148
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
149
+ async def get_mod(
150
+ ctx: Context, game_id: Identifier, mod_id: Identifier, platform: Platform | None = None
151
+ ) -> JsonObject:
152
+ """Get mod details, including metadata, submitter and the active modfile if available."""
153
+ return await _client(ctx).object(
154
+ f"games/{game_id}/mods/{mod_id}", expected_id=mod_id, platform=platform
155
+ )
156
+
157
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
158
+ async def get_mod_team(
159
+ ctx: Context, game_id: Identifier, mod_id: Identifier, limit: Limit = 20, offset: Offset = 0
160
+ ) -> Page:
161
+ """List the mod's team entries and their roles; the submitter is not the whole team."""
162
+ return await _client(ctx).page(
163
+ f"games/{game_id}/mods/{mod_id}/team", limit=limit, offset=offset
164
+ )
165
+
166
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
167
+ async def get_mod_dependencies(
168
+ ctx: Context,
169
+ game_id: Identifier,
170
+ mod_id: Identifier,
171
+ recursive: Annotated[bool, Field(strict=True)] = False,
172
+ limit: Limit = 20,
173
+ offset: Offset = 0,
174
+ ) -> Page:
175
+ """List direct dependencies, or ask mod.io to expand them recursively."""
176
+ return await _client(ctx).page(
177
+ f"games/{game_id}/mods/{mod_id}/dependencies",
178
+ limit=limit,
179
+ offset=offset,
180
+ params={"recursive": "true" if recursive else "false"},
181
+ )
182
+
183
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
184
+ async def list_mod_files(
185
+ ctx: Context,
186
+ game_id: Identifier,
187
+ mod_id: Identifier,
188
+ platform: Platform | None = None,
189
+ limit: Limit = 20,
190
+ offset: Offset = 0,
191
+ ) -> Page:
192
+ """List modfile metadata for a mod, optionally restricted by the platform header."""
193
+ return await _client(ctx).page(
194
+ f"games/{game_id}/mods/{mod_id}/files", limit=limit, offset=offset, platform=platform
195
+ )
196
+
197
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
198
+ async def get_mod_file(
199
+ ctx: Context,
200
+ game_id: Identifier,
201
+ mod_id: Identifier,
202
+ file_id: Identifier,
203
+ platform: Platform | None = None,
204
+ ) -> JsonObject:
205
+ """Get one modfile's metadata, including version, size, filehash and platform status."""
206
+ return await _client(ctx).modfile(game_id, mod_id, file_id, platform=platform)
207
+
208
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True))
209
+ async def get_download_url(
210
+ ctx: Context,
211
+ game_id: Identifier,
212
+ mod_id: Identifier,
213
+ file_id: Identifier | None = None,
214
+ platform: Platform | None = None,
215
+ ) -> Download:
216
+ """Fetch a fresh CDN URL from modfile metadata; default to the platform's active file."""
217
+ client = _client(ctx)
218
+ if file_id is None:
219
+ file_id = await client.active_file_id(game_id, mod_id, platform)
220
+ _, download = await client.fresh_download(game_id, mod_id, file_id, platform)
221
+ return download
222
+
223
+ @server.tool(annotations=ToolAnnotations(destructiveHint=False, openWorldHint=True))
224
+ async def download_file(
225
+ ctx: Context,
226
+ game_id: Identifier,
227
+ mod_id: Identifier,
228
+ file_id: Identifier | None = None,
229
+ filename: str | None = None,
230
+ platform: Platform | None = None,
231
+ ) -> SavedDownload:
232
+ """Stream a verified modfile into the download directory; never overwrite an existing file."""
233
+ return await save_download(
234
+ _client(ctx), game_id, mod_id, file_id, filename=filename, platform=platform
235
+ )
236
+
237
+ return server
238
+
239
+
240
+ def main() -> None:
241
+ # httpx logs request URLs at INFO, which contain the API key in key mode.
242
+ logging.getLogger("httpx").setLevel(logging.WARNING)
243
+ logging.getLogger("httpcore").setLevel(logging.WARNING)
244
+ create_server().run(transport="stdio")
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.5
2
+ Name: modio-mcp
3
+ Version: 1.0.0
4
+ Summary: Read-only mod.io REST API server for the Model Context Protocol
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: httpx<1,>=0.28
7
+ Requires-Dist: mcp<2,>=1.28
8
+ Requires-Dist: pydantic<3,>=2.11
9
+ Requires-Dist: typing-extensions<5,>=4.12
10
+ Description-Content-Type: text/markdown
11
+
12
+ # mod.io MCP - mod.io REST API MCP 服务器
13
+
14
+ <div align="center">
15
+
16
+ [![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-blue.svg)](https://www.python.org/) [![MCP 1.x](https://img.shields.io/badge/MCP-1.x-green.svg)](https://modelcontextprotocol.io/)
17
+
18
+ **按游戏、标签和平台查 Mod,查看团队与前置,下载指定版本。**
19
+
20
+ </div>
21
+
22
+ ---
23
+
24
+ ## ✨ 项目简介
25
+
26
+ 这个非官方本地 stdio 服务使用 mod.io REST API。每次查询 Mod 都带上所属游戏的 `game_id`,可取得项目主页、介绍、媒体、提交者、团队及可访问的文件。仓库名为 `mod.io-mcp`,Python 包的安装名和启动命令均为 `modio-mcp`。
27
+
28
+ ## ⚡ 快速开始
29
+
30
+ ### 前置条件
31
+
32
+ - Python 3.11 或更高版本,以及 [uv](https://docs.astral.sh/uv/)。
33
+ - 从 [mod.io API Access](https://mod.io/me/access) 或游戏管理面板取得 API path,并准备同一环境的 API Key 或访问令牌。
34
+
35
+ ### 安装与更新
36
+
37
+ 在 `mod.io-mcp` 仓库根目录执行:
38
+
39
+ ```sh
40
+ uv sync --python 3.11
41
+ ```
42
+
43
+ 更新仓库源码后,重新执行上面的命令并重启客户端中的服务。若使用已有的 Python 虚拟环境,也可以用 `python -m pip install --upgrade .` 安装或更新,启动命令为 `modio-mcp`。
44
+
45
+ ### 配置客户端
46
+
47
+ 在仓库根目录的 `.env` 中填写面板给出的完整 HTTPS `/v1` 地址。下面以游戏级地址为例;用户级地址可形如 `https://u-12345.modapi.io/v1`。
48
+
49
+ ```dotenv
50
+ MODIO_API_BASE_URL=https://g-12345.modapi.io/v1
51
+ MODIO_API_KEY='替换为你的 API Key'
52
+ # 可选;默认目录为 ~/Downloads/mod.io
53
+ # MODIO_DOWNLOAD_DIR=E:/Downloads/mod.io
54
+ ```
55
+
56
+ 使用 OAuth 或个人访问令牌时,改设 `MODIO_ACCESS_TOKEN`。两种凭据都存在时,服务使用访问令牌。
57
+
58
+ 将以下条目加入使用 `mcpServers` 格式的客户端,把 `--directory` 后的示例路径替换为本仓库的绝对路径。使用 VS Code 的 `.vscode/mcp.json` 时,顶层键使用 `servers`。
59
+
60
+ ```json
61
+ {
62
+ "mcpServers": {
63
+ "modio-mcp": {
64
+ "type": "stdio",
65
+ "command": "uv",
66
+ "args": ["--directory", "E:/GitHub/mcp/mod.io-mcp", "run", "--no-sync", "--env-file", ".env", "modio-mcp"]
67
+ }
68
+ }
69
+ }
70
+ ```
71
+
72
+ ### 第一次调用
73
+
74
+ 先运行 `check_auth()`。返回 `authenticated: true` 后,试试「查找 SnowRunner,列出它的 Mod 标签,再选一个 Mod 查看作者团队和当前版本」。后续查询沿用 `search_games` 返回的 `id`。
75
+
76
+ ## 🧰 工具列表
77
+
78
+ | 工具 | 主要参数 | 用途 |
79
+ | --- | --- | --- |
80
+ | `check_auth` | 无 | 读取受鉴权的游戏列表,检查当前 API 地址及凭据。 |
81
+ | `search_games` | 可选 `query`、`slug`、`limit`、`offset` | 列出可访问的游戏,按关键词搜索或按 `name_id` 精确筛选。 |
82
+ | `get_game` | `game_id` | 读取游戏详情。 |
83
+ | `list_game_tags` | `game_id`;可选 `platform` 和分页参数 | 取得游戏的标签分类和选项,供 Mod 筛选使用。 |
84
+ | `search_mods` | `game_id`;可选 `query`、`slug`、`tags`、`tag_match`、`platform` | 搜索游戏内的 Mod。`tag_match=all` 匹配全部标签,`any` 匹配任意标签。 |
85
+ | `get_mod` | `game_id`、`mod_id`;可选 `platform` | 取得项目资料、主页、媒体、提交者和上游提供的活跃文件。 |
86
+ | `get_mod_team` | `game_id`、`mod_id`;可选分页参数 | 列出该项目的团队成员与角色。 |
87
+ | `get_mod_dependencies` | `game_id`、`mod_id`;可选 `recursive` 和分页参数 | 默认查询直接前置,传 `recursive=true` 由站点递归展开。 |
88
+ | `list_mod_files` | `game_id`、`mod_id`;可选 `platform` 和分页参数 | 列出文件版本、大小、哈希及平台可用性。 |
89
+ | `get_mod_file` | `game_id`、`mod_id`、`file_id`;可选 `platform` | 取得指定文件的原始元数据。 |
90
+ | `get_download_url` | `game_id`、`mod_id`;可选 `file_id`、`platform` | 刷新文件元数据,返回 `binary_url` 和可用的过期时间。省略文件 ID 时选择活跃文件。 |
91
+ | `download_file` | `game_id`、`mod_id`;可选 `file_id`、`platform`、`filename` | 流式保存所选或活跃文件;可指定本地文件名,返回路径、字节数、SHA-256 和文件 ID。 |
92
+
93
+ **分页与平台。** 列表支持 `limit`(1–100,默认 20)和 `offset`;还有下一页时使用返回的 `next_offset`。`platform` 会传给站点作为 `X-Modio-Platform`,可用平台和活跃文件由游戏配置决定。
94
+
95
+ **下载与校验。** `binary_url` 可能是临时 CDN 地址,也可能是需要鉴权的同源下载端点。`download_file` 会处理同源鉴权、跨域跳转和短期链接刷新,核对可用的大小及 `filehash.md5`,并计算 SHA-256。目标目录可用 `MODIO_DOWNLOAD_DIR` 指定绝对路径,目录缺失时会创建。最终文件通过硬链接发布,因此目录所在文件系统须支持硬链接(如 NTFS);同名时可换一个 `filename`。
96
+
97
+ ## 测试
98
+
99
+ ```sh
100
+ uv run --locked pytest -q
101
+ uv run --locked ruff check .
102
+ ```
103
+
104
+ 默认测试用模拟 API 和真实 stdio 子进程检查工具及下载。带凭据检查实站鉴权可运行 `uv run --locked --env-file .env pytest -q -k test_live_authenticated_stdio`;若还要读取特定游戏,可设置 `MODIO_TEST_GAME_ID`。
105
+
106
+ ## 构建与发布到 PyPI
107
+
108
+ 首次发布前,在 PyPI 为 `modio-mcp` 登记 GitHub Trusted Publisher。仓库所有者填 `GlossMod`,仓库名填 `mod.io-mcp`,工作流文件填 `publish.yml`,环境填 `pypi`。新项目可在 [PyPI Publishing](https://pypi.org/manage/account/publishing/) 预先登记。
109
+
110
+ 在 `GlossMod/mod.io-mcp` 的 GitHub Releases 页面为目标提交选择新标签,点击 **Publish release**。例如,`v0.2.0` 会发布 `modio-mcp==0.2.0`,`v0.2.0rc1` 会发布候选版。GitHub Actions 从标签取版本,构建并校验 wheel 和源码包,然后发布到 PyPI。可在本地运行 `uv build` 检查开发版本的构建产物。
111
+
112
+ 参考:[mod.io REST API](https://docs.mod.io/restapi/introduction) · [平台请求头](https://docs.mod.io/restapi/platforms) · [依赖查询](https://docs.mod.io/restapi/docs/get-mod-dependencies)
@@ -0,0 +1,9 @@
1
+ modio_mcp/__init__.py,sha256=i2et0elqnYaJhh25-SU8fUB6wrGo1GIPYmnBYZACyBk,35
2
+ modio_mcp/__main__.py,sha256=9it1my_mM7xBpDh79QSi7FAvZD3Vki3GQFPJIDZw_zs,64
3
+ modio_mcp/client.py,sha256=gvG_KwYFeGfij1C0HzOoY_hI5A4Pib5gdVkiZBYXNTQ,16071
4
+ modio_mcp/download.py,sha256=eHAK4LO1upaJiLBH_nf6WTjr3Ax_sl5r-afY5pBYdDI,7126
5
+ modio_mcp/server.py,sha256=eM7PFPw5vcCTu7PQZ_JYxdIzrUx6k2RlB8DBHMFjDYA,9372
6
+ modio_mcp-1.0.0.dist-info/METADATA,sha256=t822qE5uL3yboe30tQxijE-09ERxVbFU67BtIB_w3yg,6437
7
+ modio_mcp-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ modio_mcp-1.0.0.dist-info/entry_points.txt,sha256=FYZnWYmWkHZ9v9qtiMYueG5z3ijKNr0gvVnDkINq9Lc,52
9
+ modio_mcp-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ modio-mcp = modio_mcp.server:main