steam-games-mcp 0.2.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,1405 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/server.ts
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+
7
+ // src/config.ts
8
+ import { z } from "zod";
9
+ var EnvSchema = z.object({
10
+ // --- Steam Web API: free key (player data). https://steamcommunity.com/dev/apikey
11
+ STEAM_API_KEY: z.string().min(1).optional(),
12
+ STEAM_API_BASE_URL: z.string().url().default("https://api.steampowered.com"),
13
+ // --- Steam Storefront API: no key; game/store data. ---
14
+ STEAM_STORE_BASE_URL: z.string().url().default("https://store.steampowered.com"),
15
+ // Storefront is region/locale-aware: cc = ISO country (prices), l = language.
16
+ STEAM_COUNTRY: z.string().min(2).max(2).default("US"),
17
+ STEAM_LANGUAGE: z.string().min(2).default("english"),
18
+ // --- Generic tunables. ---
19
+ HTTP_TIMEOUT_MS: z.coerce.number().int().positive().default(15e3),
20
+ HTTP_RETRIES: z.coerce.number().int().nonnegative().default(2),
21
+ // The Storefront API is unofficial and rate-sensitive to bursts, so space its
22
+ // calls; the Web API allows ~100k/day and needs little throttling. 0 disables.
23
+ STEAM_STORE_MIN_INTERVAL_MS: z.coerce.number().int().nonnegative().default(250),
24
+ STEAM_API_MIN_INTERVAL_MS: z.coerce.number().int().nonnegative().default(0),
25
+ CACHE_TTL_MS: z.coerce.number().int().nonnegative().default(3e5),
26
+ LOG_LEVEL: z.enum(["debug", "info", "warn", "error", "silent"]).default("info")
27
+ });
28
+ function loadConfig(env = process.env) {
29
+ const cleaned = Object.fromEntries(
30
+ Object.entries(env).filter(([, v]) => v !== void 0 && v !== "")
31
+ );
32
+ const parsed = EnvSchema.parse(cleaned);
33
+ return {
34
+ steamApiBaseUrl: parsed.STEAM_API_BASE_URL,
35
+ steamApiKey: parsed.STEAM_API_KEY,
36
+ steamStoreBaseUrl: parsed.STEAM_STORE_BASE_URL,
37
+ country: parsed.STEAM_COUNTRY,
38
+ language: parsed.STEAM_LANGUAGE,
39
+ httpTimeoutMs: parsed.HTTP_TIMEOUT_MS,
40
+ httpRetries: parsed.HTTP_RETRIES,
41
+ storeMinIntervalMs: parsed.STEAM_STORE_MIN_INTERVAL_MS,
42
+ apiMinIntervalMs: parsed.STEAM_API_MIN_INTERVAL_MS,
43
+ cacheTtlMs: parsed.CACHE_TTL_MS,
44
+ logLevel: parsed.LOG_LEVEL
45
+ };
46
+ }
47
+
48
+ // src/lib/errors.ts
49
+ var ApiError = class extends Error {
50
+ code;
51
+ status;
52
+ retryable;
53
+ constructor(opts) {
54
+ super(opts.message, opts.cause === void 0 ? void 0 : { cause: opts.cause });
55
+ this.name = "ApiError";
56
+ this.code = opts.code;
57
+ this.status = opts.status;
58
+ this.retryable = opts.retryable ?? false;
59
+ }
60
+ };
61
+ function classifyStatus(status) {
62
+ if (status === 304) return { code: "not_modified", retryable: false };
63
+ if (status === 401) return { code: "unauthorized", retryable: false };
64
+ if (status === 403) return { code: "forbidden", retryable: false };
65
+ if (status === 404) return { code: "not_found", retryable: false };
66
+ if (status === 429) return { code: "rate_limited", retryable: true };
67
+ if (status === 400 || status === 405 || status === 422)
68
+ return { code: "bad_request", retryable: false };
69
+ if (status >= 500) return { code: "server_error", retryable: true };
70
+ return { code: "unknown", retryable: false };
71
+ }
72
+ function redact(input) {
73
+ return input.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer ***").replace(/\b(access_token|refresh_token|client_secret|client_id)=([^&\s"]+)/gi, "$1=***");
74
+ }
75
+
76
+ // src/lib/logger.ts
77
+ var ORDER = {
78
+ debug: 10,
79
+ info: 20,
80
+ warn: 30,
81
+ error: 40,
82
+ silent: 100
83
+ };
84
+ function createLogger(level) {
85
+ const threshold = ORDER[level];
86
+ function emit(lvl, msg, args) {
87
+ if (ORDER[lvl] < threshold) return;
88
+ const extra = args.length ? " " + redact(args.map((a) => safeString(a)).join(" ")) : "";
89
+ console.error(`[mal-mcp] ${lvl}: ${redact(msg)}${extra}`);
90
+ }
91
+ return {
92
+ debug: (m, ...a) => emit("debug", m, a),
93
+ info: (m, ...a) => emit("info", m, a),
94
+ warn: (m, ...a) => emit("warn", m, a),
95
+ error: (m, ...a) => emit("error", m, a)
96
+ };
97
+ }
98
+ function safeString(value) {
99
+ if (typeof value === "string") return value;
100
+ if (value instanceof Error) return value.message;
101
+ try {
102
+ return JSON.stringify(value);
103
+ } catch {
104
+ return String(value);
105
+ }
106
+ }
107
+
108
+ // src/version.ts
109
+ var VERSION = "0.2.0";
110
+ var USER_AGENT = `steam-games-mcp/${VERSION} (+https://github.com/Grinv/steam-games-mcp)`;
111
+
112
+ // src/lib/http.ts
113
+ var MAX_BACKOFF_MS = 8e3;
114
+ var HttpClient = class {
115
+ #opts;
116
+ constructor(opts) {
117
+ this.#opts = opts;
118
+ }
119
+ async getJson(path, options = {}) {
120
+ return this.requestJson(path, { ...options, method: options.method ?? "GET" });
121
+ }
122
+ async requestJson(path, options = {}) {
123
+ const url = this.#buildUrl(path, options.query);
124
+ const retries = options.retries ?? this.#opts.retries ?? 2;
125
+ const timeoutMs = options.timeoutMs ?? this.#opts.timeoutMs ?? 15e3;
126
+ let attempt = 0;
127
+ for (; ; ) {
128
+ if (this.#opts.beforeRequest) await this.#opts.beforeRequest();
129
+ try {
130
+ return await this.#once(url, options, timeoutMs);
131
+ } catch (err) {
132
+ const apiErr = err instanceof ApiError ? err : toNetworkError(err);
133
+ if (!apiErr.retryable || attempt >= retries) throw apiErr;
134
+ const backoff = backoffMs(attempt, apiErr);
135
+ this.#opts.logger.debug(
136
+ `retrying ${url} after ${backoff}ms (attempt ${attempt + 1}/${retries}, ${apiErr.code})`
137
+ );
138
+ await delay(backoff);
139
+ attempt += 1;
140
+ }
141
+ }
142
+ }
143
+ async #once(url, options, timeoutMs) {
144
+ const controller = new AbortController();
145
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
146
+ const onAbort = () => controller.abort();
147
+ options.signal?.addEventListener("abort", onAbort, { once: true });
148
+ let res;
149
+ try {
150
+ res = await fetch(url, {
151
+ method: options.method ?? "GET",
152
+ headers: {
153
+ "User-Agent": USER_AGENT,
154
+ Accept: "application/json",
155
+ ...this.#opts.defaultHeaders,
156
+ ...options.headers
157
+ },
158
+ ...options.body === void 0 ? {} : { body: options.body },
159
+ signal: controller.signal
160
+ });
161
+ } catch (err) {
162
+ if (options.signal?.aborted) {
163
+ throw new ApiError({ code: "network", message: "Request aborted by caller", cause: err });
164
+ }
165
+ if (controller.signal.aborted) {
166
+ throw new ApiError({
167
+ code: "timeout",
168
+ message: `Request timed out after ${timeoutMs}ms`,
169
+ retryable: true,
170
+ cause: err
171
+ });
172
+ }
173
+ throw toNetworkError(err);
174
+ } finally {
175
+ clearTimeout(timer);
176
+ options.signal?.removeEventListener("abort", onAbort);
177
+ }
178
+ if (!res.ok) throw await toHttpError(res);
179
+ if (res.status === 204) return void 0;
180
+ const text = await res.text();
181
+ if (text.length === 0) return void 0;
182
+ try {
183
+ return JSON.parse(text);
184
+ } catch (err) {
185
+ throw new ApiError({
186
+ code: "unknown",
187
+ message: "Upstream returned invalid JSON",
188
+ cause: err
189
+ });
190
+ }
191
+ }
192
+ #buildUrl(path, query) {
193
+ const url = new URL(path.replace(/^\//, ""), ensureTrailingSlash(this.#opts.baseUrl));
194
+ if (query) {
195
+ for (const [key, value] of Object.entries(query)) {
196
+ if (value !== void 0) url.searchParams.set(key, String(value));
197
+ }
198
+ }
199
+ return url.toString();
200
+ }
201
+ };
202
+ async function toHttpError(res) {
203
+ const { code, retryable } = classifyStatus(res.status);
204
+ let raw = "";
205
+ try {
206
+ raw = await res.text();
207
+ } catch {
208
+ }
209
+ const detail = parseErrorMessage(raw) ?? raw.slice(0, 500);
210
+ const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
211
+ return new ApiError({
212
+ code,
213
+ status: res.status,
214
+ retryable,
215
+ message: `HTTP ${res.status} ${res.statusText}${detail ? `: ${detail}` : ""}`,
216
+ ...retryAfter === void 0 ? {} : { cause: { retryAfterMs: retryAfter } }
217
+ });
218
+ }
219
+ function parseErrorMessage(raw) {
220
+ if (!raw) return void 0;
221
+ try {
222
+ const obj = JSON.parse(raw);
223
+ if (obj === null || typeof obj !== "object") return void 0;
224
+ const rec = obj;
225
+ if (typeof rec.message === "string") return rec.message;
226
+ if (typeof rec.error === "string") return rec.error;
227
+ return void 0;
228
+ } catch {
229
+ return void 0;
230
+ }
231
+ }
232
+ function toNetworkError(err) {
233
+ if (err instanceof ApiError) return err;
234
+ return new ApiError({
235
+ code: "network",
236
+ message: err instanceof Error ? `Network error: ${err.message}` : "Network error",
237
+ retryable: true,
238
+ cause: err
239
+ });
240
+ }
241
+ function backoffMs(attempt, err) {
242
+ const hinted = err.cause?.retryAfterMs;
243
+ if (typeof hinted === "number" && hinted > 0) return Math.min(hinted, MAX_BACKOFF_MS);
244
+ const base = Math.min(MAX_BACKOFF_MS, 500 * 2 ** attempt);
245
+ return base + Math.floor(base * 0.25 * deterministicJitter(attempt));
246
+ }
247
+ function deterministicJitter(attempt) {
248
+ return attempt * 2654435761 % 1e3 / 1e3;
249
+ }
250
+ function parseRetryAfter(header) {
251
+ if (!header) return void 0;
252
+ const seconds = Number(header);
253
+ if (Number.isFinite(seconds)) return seconds * 1e3;
254
+ const date = Date.parse(header);
255
+ if (Number.isFinite(date)) return Math.max(0, date - Date.now());
256
+ return void 0;
257
+ }
258
+ function ensureTrailingSlash(s) {
259
+ return s.endsWith("/") ? s : s + "/";
260
+ }
261
+ function delay(ms) {
262
+ return new Promise((resolve) => setTimeout(resolve, ms));
263
+ }
264
+
265
+ // src/lib/rateLimit.ts
266
+ var RateLimiter = class {
267
+ #minIntervalMs;
268
+ #rules;
269
+ #maxWindowMs;
270
+ // Ascending timestamps of granted acquisitions, pruned to the largest window.
271
+ #history = [];
272
+ #tail = Promise.resolve();
273
+ #lastStart = 0;
274
+ constructor(minIntervalMs, rules = []) {
275
+ this.#minIntervalMs = Math.max(0, minIntervalMs);
276
+ this.#rules = rules;
277
+ this.#maxWindowMs = rules.reduce((max, r) => Math.max(max, r.windowMs), 0);
278
+ }
279
+ /** Resolves when the caller is allowed to proceed. */
280
+ acquire() {
281
+ const prev = this.#tail;
282
+ let release;
283
+ this.#tail = new Promise((resolve) => {
284
+ release = resolve;
285
+ });
286
+ return prev.then(async () => {
287
+ const wait = this.#delayUntilAllowed();
288
+ if (wait > 0) await delay2(wait);
289
+ const now = Date.now();
290
+ this.#lastStart = now;
291
+ this.#record(now);
292
+ release();
293
+ });
294
+ }
295
+ /** Earliest delay (ms) before another acquisition stays within every limit. */
296
+ #delayUntilAllowed() {
297
+ const now = Date.now();
298
+ let until = this.#lastStart + this.#minIntervalMs;
299
+ for (const rule of this.#rules) {
300
+ if (this.#history.length < rule.limit) continue;
301
+ const nth = this.#history[this.#history.length - rule.limit];
302
+ until = Math.max(until, nth + rule.windowMs);
303
+ }
304
+ return Math.max(0, until - now);
305
+ }
306
+ #record(ts) {
307
+ this.#history.push(ts);
308
+ const cutoff = ts - this.#maxWindowMs;
309
+ let stale = 0;
310
+ while (stale < this.#history.length && this.#history[stale] <= cutoff) stale += 1;
311
+ if (stale > 0) this.#history.splice(0, stale);
312
+ }
313
+ };
314
+ function delay2(ms) {
315
+ return new Promise((resolve) => setTimeout(resolve, ms));
316
+ }
317
+
318
+ // src/lib/cache.ts
319
+ var TtlCache = class {
320
+ #ttlMs;
321
+ #max;
322
+ #map = /* @__PURE__ */ new Map();
323
+ constructor(ttlMs, max = 500) {
324
+ this.#ttlMs = ttlMs;
325
+ this.#max = max;
326
+ }
327
+ /** Fresh (non-expired) value, or undefined. */
328
+ get(key) {
329
+ const hit = this.#map.get(key);
330
+ if (!hit) return void 0;
331
+ return hit.expires > Date.now() ? hit.value : void 0;
332
+ }
333
+ /** Any cached value regardless of freshness — used for stale fallback. */
334
+ getStale(key) {
335
+ return this.#map.get(key)?.value;
336
+ }
337
+ set(key, value) {
338
+ if (this.#ttlMs <= 0) return;
339
+ if (!this.#map.has(key) && this.#map.size >= this.#max) {
340
+ const oldest = this.#map.keys().next().value;
341
+ if (oldest !== void 0) this.#map.delete(oldest);
342
+ }
343
+ this.#map.set(key, { value, expires: Date.now() + this.#ttlMs });
344
+ }
345
+ /** Get-or-compute, caching the resolved value. */
346
+ async wrap(key, compute) {
347
+ const cached = this.get(key);
348
+ if (cached !== void 0) return cached;
349
+ const value = await compute();
350
+ this.set(key, value);
351
+ return value;
352
+ }
353
+ /**
354
+ * Like wrap, but if `compute` throws and a previously-cached (possibly stale)
355
+ * value exists, serve that instead of failing. Lets reads degrade gracefully
356
+ * when the upstream is temporarily down.
357
+ */
358
+ async wrapStaleOnError(key, compute) {
359
+ const fresh = this.get(key);
360
+ if (fresh !== void 0) return fresh;
361
+ try {
362
+ const value = await compute();
363
+ this.set(key, value);
364
+ return value;
365
+ } catch (err) {
366
+ const stale = this.getStale(key);
367
+ if (stale !== void 0) return stale;
368
+ throw err;
369
+ }
370
+ }
371
+ };
372
+
373
+ // src/format.ts
374
+ function names(list) {
375
+ return (list ?? []).map((x) => x.description ?? x.name).filter((n) => Boolean(n));
376
+ }
377
+ function hours(minutes) {
378
+ return typeof minutes === "number" ? Math.round(minutes / 60 * 10) / 10 : null;
379
+ }
380
+ function stripHtml(s) {
381
+ if (!s) return null;
382
+ return s.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim() || null;
383
+ }
384
+ function price(p, isFree) {
385
+ if (isFree) return { is_free: true };
386
+ if (!p) return null;
387
+ return {
388
+ is_free: false,
389
+ currency: p.currency ?? null,
390
+ final: p.final_formatted ?? null,
391
+ // Steam leaves initial_formatted empty when there's no discount.
392
+ initial: p.initial_formatted || p.final_formatted || null,
393
+ discount_percent: p.discount_percent ?? 0
394
+ };
395
+ }
396
+ function platforms(p) {
397
+ if (!p) return [];
398
+ return Object.entries(p).filter(([, on]) => on).map(([os]) => os);
399
+ }
400
+ function detailApp(a) {
401
+ const reqs = Array.isArray(a.pc_requirements) ? void 0 : a.pc_requirements;
402
+ return {
403
+ appid: a.steam_appid,
404
+ name: a.name,
405
+ type: a.type ?? null,
406
+ short_description: a.short_description || null,
407
+ is_free: a.is_free ?? false,
408
+ price: price(a.price_overview, a.is_free),
409
+ release_date: a.release_date?.date || null,
410
+ coming_soon: a.release_date?.coming_soon ?? false,
411
+ developers: a.developers ?? [],
412
+ publishers: a.publishers ?? [],
413
+ genres: names(a.genres),
414
+ categories: names(a.categories),
415
+ platforms: platforms(a.platforms),
416
+ metacritic: a.metacritic?.score ?? null,
417
+ metacritic_url: a.metacritic?.url ?? null,
418
+ recommendations: a.recommendations?.total ?? null,
419
+ required_age: a.required_age ?? null,
420
+ controller_support: a.controller_support ?? null,
421
+ achievements_total: a.achievements?.total ?? null,
422
+ // A keyless sample of named achievements; use get_game_achievements for all.
423
+ achievements_highlighted: (a.achievements?.highlighted ?? []).map((h) => h.name).filter((n) => Boolean(n)),
424
+ supported_languages: stripHtml(a.supported_languages),
425
+ dlc: a.dlc ?? [],
426
+ demos: (a.demos ?? []).map((d) => d.appid).filter(Boolean),
427
+ // Content descriptor ids flag mature themes (violence/nudity/etc.); notes
428
+ // is Valve's free-text. Empty ids → no mature descriptors.
429
+ content_descriptors: {
430
+ ids: a.content_descriptors?.ids ?? [],
431
+ notes: a.content_descriptors?.notes ?? null
432
+ },
433
+ // Present only for DLC: the base game it belongs to.
434
+ base_game: a.fullgame?.appid ? { appid: Number(a.fullgame.appid), name: a.fullgame.name ?? null } : null,
435
+ drm_notice: a.drm_notice || null,
436
+ account_notice: a.ext_user_account_notice || null,
437
+ pc_requirements_min: stripHtml(reqs?.minimum),
438
+ website: a.website || null,
439
+ header_image: a.header_image || null,
440
+ store_url: a.steam_appid ? `https://store.steampowered.com/app/${a.steam_appid}` : null
441
+ };
442
+ }
443
+ function searchPrice(p) {
444
+ if (!p || typeof p.final !== "number") return null;
445
+ const discount = p.initial && p.final && p.initial > p.final ? Math.round((1 - p.final / p.initial) * 100) : 0;
446
+ return {
447
+ currency: p.currency ?? null,
448
+ final: money(p.final, p.currency),
449
+ initial: money(p.initial, p.currency),
450
+ discount_percent: discount
451
+ };
452
+ }
453
+ function summarizeSearch(r) {
454
+ return {
455
+ total: r.total ?? r.items?.length ?? 0,
456
+ results: (r.items ?? []).map((i) => ({
457
+ appid: i.id,
458
+ name: i.name,
459
+ type: i.type ?? null,
460
+ price: searchPrice(i.price),
461
+ metascore: i.metascore || null,
462
+ platforms: platforms(i.platforms),
463
+ store_url: i.id ? `https://store.steampowered.com/app/${i.id}` : null
464
+ }))
465
+ };
466
+ }
467
+ function summarizePrices(merged, appids) {
468
+ const prices = appids.map((id) => {
469
+ const entry = merged[String(id)];
470
+ const data = entry?.data;
471
+ const po = data && !Array.isArray(data) ? data.price_overview : void 0;
472
+ if (!entry?.success) return { appid: id, available: false };
473
+ if (!po) return { appid: id, available: true, is_free: true };
474
+ return {
475
+ appid: id,
476
+ available: true,
477
+ is_free: false,
478
+ currency: po.currency ?? null,
479
+ final: po.final_formatted ?? null,
480
+ initial: po.initial_formatted || po.final_formatted || null,
481
+ discount_percent: po.discount_percent ?? 0
482
+ };
483
+ });
484
+ return { count: prices.length, prices };
485
+ }
486
+ function summarizeReviews(r, max = 5) {
487
+ const q = r.query_summary ?? {};
488
+ return {
489
+ summary: q.review_score_desc ?? null,
490
+ total_reviews: q.total_reviews ?? null,
491
+ total_positive: q.total_positive ?? null,
492
+ total_negative: q.total_negative ?? null,
493
+ positive_pct: q.total_reviews && q.total_positive ? Math.round(q.total_positive / q.total_reviews * 100) : null,
494
+ reviews: (r.reviews ?? []).slice(0, max).map((x) => ({
495
+ voted_up: x.voted_up ?? null,
496
+ votes_up: x.votes_up ?? 0,
497
+ author_playtime_hours: hours(x.author?.playtime_forever),
498
+ text: x.review ? x.review.length > 600 ? x.review.slice(0, 600) + "\u2026" : x.review : null
499
+ }))
500
+ };
501
+ }
502
+ function money(cents, currency) {
503
+ if (typeof cents !== "number") return null;
504
+ const v = (cents / 100).toFixed(2);
505
+ return currency ? `${v} ${currency}` : v;
506
+ }
507
+ function featuredItems(items) {
508
+ return (items ?? []).map((i) => ({
509
+ appid: i.id,
510
+ name: i.name,
511
+ discounted: i.discounted ?? false,
512
+ discount_percent: i.discount_percent ?? 0,
513
+ original_price: money(i.original_price, i.currency),
514
+ final_price: money(i.final_price, i.currency),
515
+ store_url: i.id ? `https://store.steampowered.com/app/${i.id}` : null
516
+ }));
517
+ }
518
+ function summarizeFeatured(r) {
519
+ return {
520
+ specials: featuredItems(r.specials?.items),
521
+ top_sellers: featuredItems(r.top_sellers?.items),
522
+ new_releases: featuredItems(r.new_releases?.items),
523
+ coming_soon: featuredItems(r.coming_soon?.items)
524
+ };
525
+ }
526
+ function summarizeSpecials(r) {
527
+ return { specials: featuredItems(r.specials?.items) };
528
+ }
529
+ var PERSONA_STATES = [
530
+ "offline",
531
+ "online",
532
+ "busy",
533
+ "away",
534
+ "snooze",
535
+ "looking to trade",
536
+ "looking to play"
537
+ ];
538
+ function summarizePlayer(r) {
539
+ const p = r.response?.players?.[0];
540
+ if (!p) return { found: false };
541
+ return {
542
+ found: true,
543
+ steamid: p.steamid,
544
+ name: p.personaname ?? null,
545
+ real_name: p.realname || null,
546
+ state: PERSONA_STATES[p.personastate ?? 0] ?? "offline",
547
+ visibility: p.communityvisibilitystate === 3 ? "public" : "private",
548
+ country: p.loccountrycode || null,
549
+ created: p.timecreated ? new Date(p.timecreated * 1e3).toISOString().slice(0, 10) : null,
550
+ in_game: p.gameextrainfo || null,
551
+ profile_url: p.profileurl ?? null,
552
+ avatar: p.avatarfull ?? null
553
+ };
554
+ }
555
+ var PRIVATE_REASON = "Profile or game-details are private. Ask the owner to set Steam \u2192 Privacy \u2192 Game details = Public, or this data can't be read.";
556
+ function isPrivate(r) {
557
+ return r.response?.game_count === void 0 && r.response?.games === void 0;
558
+ }
559
+ function summarizeOwnedGames(r, max = 50) {
560
+ if (isPrivate(r)) return { found: false, reason: PRIVATE_REASON, game_count: null, games: [] };
561
+ const games = (r.response?.games ?? []).slice().sort((a, b) => (b.playtime_forever ?? 0) - (a.playtime_forever ?? 0));
562
+ return {
563
+ found: true,
564
+ game_count: r.response?.game_count ?? games.length,
565
+ returned: Math.min(games.length, max),
566
+ games: games.slice(0, max).map((g) => ({
567
+ appid: g.appid,
568
+ name: g.name ?? null,
569
+ playtime_hours: hours(g.playtime_forever),
570
+ playtime_2weeks_hours: hours(g.playtime_2weeks)
571
+ }))
572
+ };
573
+ }
574
+ function summarizeRecentlyPlayed(r) {
575
+ if (isPrivate(r)) return { found: false, reason: PRIVATE_REASON, total: 0, games: [] };
576
+ return {
577
+ found: true,
578
+ total: r.response?.game_count ?? r.response?.games?.length ?? 0,
579
+ games: (r.response?.games ?? []).map((g) => ({
580
+ appid: g.appid,
581
+ name: g.name ?? null,
582
+ playtime_2weeks_hours: hours(g.playtime_2weeks),
583
+ playtime_hours: hours(g.playtime_forever)
584
+ }))
585
+ };
586
+ }
587
+ function summarizePlayerAchievements(r) {
588
+ const ps = r.playerstats;
589
+ if (!ps?.success) return { found: false, reason: ps?.error ?? "No achievement stats" };
590
+ const all = ps.achievements ?? [];
591
+ const unlocked = all.filter((a) => a.achieved === 1);
592
+ return {
593
+ found: true,
594
+ game: ps.gameName ?? null,
595
+ total: all.length,
596
+ unlocked: unlocked.length,
597
+ completion_pct: all.length ? Math.round(unlocked.length / all.length * 100) : null,
598
+ achievements: all.map((a) => ({
599
+ name: a.name || a.apiname,
600
+ achieved: a.achieved === 1,
601
+ unlocked_at: a.achieved === 1 && a.unlocktime ? new Date(a.unlocktime * 1e3).toISOString().slice(0, 10) : null
602
+ }))
603
+ };
604
+ }
605
+ function summarizeGlobalAchievements(r) {
606
+ const a = r.achievementpercentages?.achievements ?? [];
607
+ return {
608
+ count: a.length,
609
+ achievements: a.map((x) => ({
610
+ name: x.name,
611
+ percent: typeof x.percent === "string" ? Number(x.percent) : x.percent ?? null
612
+ }))
613
+ };
614
+ }
615
+ function summarizeGameSchema(schema, global) {
616
+ const pct = /* @__PURE__ */ new Map();
617
+ for (const x of global.achievementpercentages?.achievements ?? []) {
618
+ if (x.name != null) {
619
+ pct.set(x.name, typeof x.percent === "string" ? Number(x.percent) : x.percent ?? 0);
620
+ }
621
+ }
622
+ const list = schema.game?.availableGameStats?.achievements ?? [];
623
+ return {
624
+ game: schema.game?.gameName ?? null,
625
+ total: list.length,
626
+ achievements: list.map((a) => {
627
+ const p = a.name != null ? pct.get(a.name) : void 0;
628
+ return {
629
+ api_name: a.name,
630
+ name: a.displayName || a.name || null,
631
+ description: a.description || null,
632
+ hidden: a.hidden === 1,
633
+ global_unlock_pct: typeof p === "number" ? Math.round(p * 10) / 10 : null
634
+ };
635
+ })
636
+ };
637
+ }
638
+ function summarizeNews(r) {
639
+ return {
640
+ items: (r.appnews?.newsitems ?? []).map((n) => ({
641
+ title: n.title ?? null,
642
+ date: n.date ? new Date(n.date * 1e3).toISOString().slice(0, 10) : null,
643
+ author: n.author || null,
644
+ feed: n.feedlabel || null,
645
+ excerpt: stripHtml(n.contents),
646
+ url: n.url ?? null
647
+ }))
648
+ };
649
+ }
650
+ function summarizeVanity(r) {
651
+ const v = r.response;
652
+ if (v?.success === 1 && v.steamid) return { found: true, steamid: v.steamid };
653
+ return { found: false, reason: v?.message ?? "No match for that vanity name" };
654
+ }
655
+ function summarizeCurrentPlayers(r, appid3) {
656
+ return { appid: appid3, player_count: r.response?.player_count ?? null };
657
+ }
658
+ function isoDay(ts) {
659
+ return ts ? new Date(ts * 1e3).toISOString().slice(0, 10) : null;
660
+ }
661
+ function summarizeWishlist(r, max = 100) {
662
+ const items = r.response?.items ?? [];
663
+ if (items.length === 0) {
664
+ return {
665
+ found: false,
666
+ reason: "Empty wishlist, or the profile/wishlist is private.",
667
+ total: 0,
668
+ items: []
669
+ };
670
+ }
671
+ const sorted = items.slice().sort((a, b) => (a.priority ?? 1e9) - (b.priority ?? 1e9));
672
+ return {
673
+ found: true,
674
+ total: items.length,
675
+ returned: Math.min(items.length, max),
676
+ items: sorted.slice(0, max).map((i) => ({
677
+ appid: i.appid,
678
+ priority: i.priority ?? null,
679
+ added: isoDay(i.date_added)
680
+ }))
681
+ };
682
+ }
683
+ function rollup(x) {
684
+ const up = x.recommendations_up ?? 0;
685
+ const down = x.recommendations_down ?? 0;
686
+ const total = up + down;
687
+ return {
688
+ date: isoDay(x.date),
689
+ up,
690
+ down,
691
+ positive_pct: total ? Math.round(up / total * 100) : null
692
+ };
693
+ }
694
+ function summarizeReviewHistogram(r) {
695
+ const res = r.results ?? {};
696
+ return {
697
+ rollup_type: res.rollup_type ?? null,
698
+ history: (res.rollups ?? []).slice(-24).map(rollup),
699
+ recent: (res.recent ?? []).slice(-30).map(rollup)
700
+ };
701
+ }
702
+ function storeCard(it) {
703
+ const bp = it.best_purchase_option;
704
+ const rev = it.reviews?.summary_filtered;
705
+ return {
706
+ appid: it.appid,
707
+ name: it.name ?? null,
708
+ discount_pct: bp?.discount_pct ?? 0,
709
+ price: bp?.formatted_final_price || null,
710
+ original: bp?.formatted_original_price || bp?.formatted_final_price || null,
711
+ review_percent: rev?.percent_positive ?? null,
712
+ review_count: rev?.review_count ?? null,
713
+ review_label: rev?.review_score_label ?? null,
714
+ release_date: it.release?.steam_release_date ? new Date(it.release.steam_release_date * 1e3).toISOString().slice(0, 10) : null
715
+ };
716
+ }
717
+ function summarizeDiscover(r, opts) {
718
+ let rows = (r.response?.store_items ?? []).filter((it) => it.visible !== false && typeof it.appid === "number").map(storeCard);
719
+ if (typeof opts.minReview === "number") {
720
+ rows = rows.filter((x) => (x.review_percent ?? -1) >= opts.minReview);
721
+ }
722
+ if (typeof opts.minReviews === "number") {
723
+ rows = rows.filter((x) => (x.review_count ?? 0) >= opts.minReviews);
724
+ }
725
+ rows.sort((a, b) => b.discount_pct - a.discount_pct);
726
+ return {
727
+ total_matching: r.response?.metadata?.total_matching_records ?? null,
728
+ returned: rows.length,
729
+ deals: rows
730
+ };
731
+ }
732
+ function summarizeItems(r, appids) {
733
+ const byId = /* @__PURE__ */ new Map();
734
+ for (const it of r.response?.store_items ?? [])
735
+ if (typeof it.appid === "number") byId.set(it.appid, it);
736
+ return {
737
+ count: appids.length,
738
+ items: appids.map((appid3) => {
739
+ const it = byId.get(appid3);
740
+ if (!it || !it.name && !it.best_purchase_option && !it.reviews) {
741
+ return { appid: appid3, available: false };
742
+ }
743
+ const bp = it.best_purchase_option;
744
+ const rev = it.reviews?.summary_filtered;
745
+ return {
746
+ appid: appid3,
747
+ name: it.name ?? null,
748
+ is_free: it.is_free ?? false,
749
+ price: bp ? {
750
+ final: bp.formatted_final_price || null,
751
+ original: bp.formatted_original_price || bp.formatted_final_price || null,
752
+ discount_pct: bp.discount_pct ?? 0
753
+ } : it.is_free ? { is_free: true } : null,
754
+ review_percent: rev?.percent_positive ?? null,
755
+ review_count: rev?.review_count ?? null,
756
+ review_label: rev?.review_score_label ?? null,
757
+ release_date: it.release?.steam_release_date ? new Date(it.release.steam_release_date * 1e3).toISOString().slice(0, 10) : null,
758
+ coming_soon: it.release?.is_coming_soon ?? false
759
+ };
760
+ })
761
+ };
762
+ }
763
+
764
+ // src/clients/storefront.ts
765
+ var StorefrontClient = class {
766
+ #http;
767
+ #cache;
768
+ #cc;
769
+ #l;
770
+ constructor(config, logger) {
771
+ this.#cc = config.country;
772
+ this.#l = config.language;
773
+ const limiter = new RateLimiter(config.storeMinIntervalMs);
774
+ this.#http = new HttpClient({
775
+ baseUrl: config.steamStoreBaseUrl,
776
+ logger,
777
+ timeoutMs: config.httpTimeoutMs,
778
+ retries: config.httpRetries,
779
+ beforeRequest: () => limiter.acquire()
780
+ });
781
+ this.#cache = new TtlCache(config.cacheTtlMs);
782
+ }
783
+ // country (cc) and language (l) fall back to the configured defaults; tools
784
+ // expose them as optional per-call overrides (e.g. compare prices by region).
785
+ async searchGames(term, country2, language2) {
786
+ const res = await this.#http.getJson("api/storesearch/", {
787
+ query: { term, l: language2 ?? this.#l, cc: country2 ?? this.#cc }
788
+ });
789
+ return summarizeSearch(res);
790
+ }
791
+ async getGame(appid3, country2, language2) {
792
+ const cc = country2 ?? this.#cc;
793
+ const l = language2 ?? this.#l;
794
+ return this.#cache.wrapStaleOnError(`app:${appid3}:${cc}:${l}`, async () => {
795
+ const res = await this.#http.getJson("api/appdetails", {
796
+ query: { appids: appid3, cc, l }
797
+ });
798
+ const entry = res[String(appid3)];
799
+ if (!entry?.success || !entry.data) {
800
+ throw new ApiError({ code: "not_found", message: `No Steam app with id ${appid3}` });
801
+ }
802
+ return detailApp(entry.data);
803
+ });
804
+ }
805
+ // Not cached: reviews are paginated and change as users post. `reviewLanguage`
806
+ // filters by review language ("all" = any); `reviewType` = all|positive|negative.
807
+ async getReviews(appid3, max, reviewLanguage = "all", reviewType = "all") {
808
+ const res = await this.#http.getJson(`appreviews/${appid3}`, {
809
+ query: {
810
+ json: 1,
811
+ num_per_page: max,
812
+ language: reviewLanguage,
813
+ review_type: reviewType,
814
+ purchase_type: "all"
815
+ }
816
+ });
817
+ return summarizeReviews(res, max);
818
+ }
819
+ // Batch prices for many appids in one place. appdetails accepts a comma-list
820
+ // with filters=price_overview; we chunk to keep URLs/responses bounded and
821
+ // merge. Not cached — prices change and the appid set varies per call.
822
+ async getPrices(appids, country2) {
823
+ const cc = country2 ?? this.#cc;
824
+ const CHUNK = 100;
825
+ const merged = {};
826
+ for (let i = 0; i < appids.length; i += CHUNK) {
827
+ const chunk = appids.slice(i, i + CHUNK);
828
+ const res = await this.#http.getJson("api/appdetails", {
829
+ query: { appids: chunk.join(","), cc, filters: "price_overview" }
830
+ });
831
+ Object.assign(merged, res);
832
+ }
833
+ return summarizePrices(merged, appids);
834
+ }
835
+ // Review trend over time (monthly history + recent daily). Cached briefly.
836
+ async getReviewHistogram(appid3) {
837
+ return this.#cache.wrapStaleOnError(`hist:${appid3}:${this.#l}`, async () => {
838
+ const res = await this.#http.getJson(`appreviewhistogram/${appid3}`, {
839
+ query: { l: this.#l }
840
+ });
841
+ return summarizeReviewHistogram(res);
842
+ });
843
+ }
844
+ // Featured/specials change often; cache briefly via the shared TTL.
845
+ async getFeatured(country2, language2) {
846
+ const cc = country2 ?? this.#cc;
847
+ const l = language2 ?? this.#l;
848
+ return this.#cache.wrapStaleOnError(`featured:${cc}:${l}`, async () => {
849
+ const res = await this.#http.getJson("api/featuredcategories", {
850
+ query: { cc, l }
851
+ });
852
+ return summarizeFeatured(res);
853
+ });
854
+ }
855
+ async getSpecials(country2, language2) {
856
+ const cc = country2 ?? this.#cc;
857
+ const l = language2 ?? this.#l;
858
+ return this.#cache.wrapStaleOnError(`specials:${cc}:${l}`, async () => {
859
+ const res = await this.#http.getJson("api/featuredcategories", {
860
+ query: { cc, l }
861
+ });
862
+ return summarizeSpecials(res);
863
+ });
864
+ }
865
+ };
866
+
867
+ // src/clients/web.ts
868
+ var PRIVATE_PROFILE_REASON = "Profile or game-details are private. Ask the owner to set Steam \u2192 Privacy \u2192 Game details = Public.";
869
+ var SteamWebClient = class {
870
+ #http;
871
+ #cache;
872
+ #key;
873
+ #l;
874
+ #country;
875
+ /** True when a Steam Web API key is configured; player tools short-circuit otherwise. */
876
+ configured;
877
+ constructor(config, logger) {
878
+ this.#key = config.steamApiKey;
879
+ this.#l = config.language;
880
+ this.#country = config.country;
881
+ this.configured = Boolean(config.steamApiKey);
882
+ const limiter = new RateLimiter(config.apiMinIntervalMs);
883
+ this.#http = new HttpClient({
884
+ baseUrl: config.steamApiBaseUrl,
885
+ logger,
886
+ timeoutMs: config.httpTimeoutMs,
887
+ retries: config.httpRetries,
888
+ beforeRequest: () => limiter.acquire()
889
+ });
890
+ this.#cache = new TtlCache(config.cacheTtlMs);
891
+ }
892
+ #get(path, query) {
893
+ return this.#http.getJson(path, { query: { key: this.#key, ...query } });
894
+ }
895
+ // ---- player data (key required) -------------------------------------------
896
+ async getPlayerSummary(steamid2) {
897
+ const res = await this.#get("ISteamUser/GetPlayerSummaries/v2/", {
898
+ steamids: steamid2
899
+ });
900
+ return summarizePlayer(res);
901
+ }
902
+ async getOwnedGames(steamid2) {
903
+ const res = await this.#get("IPlayerService/GetOwnedGames/v1/", {
904
+ steamid: steamid2,
905
+ include_appinfo: true,
906
+ include_played_free_games: true
907
+ });
908
+ return summarizeOwnedGames(res);
909
+ }
910
+ async getRecentlyPlayed(steamid2) {
911
+ const res = await this.#get("IPlayerService/GetRecentlyPlayedGames/v1/", {
912
+ steamid: steamid2
913
+ });
914
+ return summarizeRecentlyPlayed(res);
915
+ }
916
+ async getPlayerAchievements(steamid2, appid3) {
917
+ try {
918
+ const res = await this.#get(
919
+ "ISteamUserStats/GetPlayerAchievements/v1/",
920
+ { steamid: steamid2, appid: appid3, l: this.#l }
921
+ );
922
+ if (res.playerstats?.success) return summarizePlayerAchievements(res);
923
+ return this.#explainNoPlayerAchievements(appid3, res.playerstats?.error);
924
+ } catch (e) {
925
+ if (e instanceof ApiError && (e.code === "forbidden" || e.code === "unauthorized")) {
926
+ return { found: false, reason: PRIVATE_PROFILE_REASON };
927
+ }
928
+ if (e instanceof ApiError && (e.code === "bad_request" || e.code === "not_found")) {
929
+ return this.#explainNoPlayerAchievements(appid3);
930
+ }
931
+ throw e;
932
+ }
933
+ }
934
+ // On failure, check the game's schema: if it HAS achievements the player data
935
+ // is hidden (private/not owned); if it has none, the game simply has no
936
+ // achievements. Only runs on the failure path, so the happy path stays 1 call.
937
+ async #explainNoPlayerAchievements(appid3, apiError) {
938
+ if (apiError && /not public|private/i.test(apiError)) {
939
+ return { found: false, reason: PRIVATE_PROFILE_REASON };
940
+ }
941
+ try {
942
+ const schema = await this.#get("ISteamUserStats/GetSchemaForGame/v2/", {
943
+ appid: appid3,
944
+ l: this.#l
945
+ });
946
+ const has = (schema.game?.availableGameStats?.achievements?.length ?? 0) > 0;
947
+ return {
948
+ found: false,
949
+ reason: has ? "This game has achievements, but the player's data is hidden (private game-details, or they don't own it)." : "This game has no achievements."
950
+ };
951
+ } catch {
952
+ return { found: false, reason: apiError || "Achievements unavailable." };
953
+ }
954
+ }
955
+ async resolveVanityUrl(vanity) {
956
+ const res = await this.#get("ISteamUser/ResolveVanityURL/v1/", {
957
+ vanityurl: vanity
958
+ });
959
+ return summarizeVanity(res);
960
+ }
961
+ // ---- keyless-capable (key sent when present) ------------------------------
962
+ async getNews(appid3, count) {
963
+ const res = await this.#get("ISteamNews/GetNewsForApp/v2/", {
964
+ appid: appid3,
965
+ count,
966
+ maxlength: 400
967
+ });
968
+ return summarizeNews(res);
969
+ }
970
+ async getGlobalAchievements(appid3) {
971
+ return this.#cache.wrapStaleOnError(`global-ach:${appid3}`, async () => {
972
+ const res = await this.#get(
973
+ "ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/",
974
+ { gameid: appid3 }
975
+ );
976
+ return summarizeGlobalAchievements(res);
977
+ });
978
+ }
979
+ // Current concurrent player count for a game. Not cached — it's a live number.
980
+ async getCurrentPlayers(appid3) {
981
+ const res = await this.#get(
982
+ "ISteamUserStats/GetNumberOfCurrentPlayers/v1/",
983
+ { appid: appid3 }
984
+ );
985
+ return summarizeCurrentPlayers(res, appid3);
986
+ }
987
+ // Batch store card (price+discount, review %, release) for a list of appids in
988
+ // one keyless call via the modern store-browse service. The efficient way to
989
+ // price- and rating-check a known list (wishlist/library) without N requests.
990
+ async getItems(appids, country2, language2) {
991
+ const input = {
992
+ ids: appids.map((appid3) => ({ appid: appid3 })),
993
+ context: { language: language2 ?? this.#l, country_code: country2 ?? this.#country },
994
+ data_request: { include_basic_info: true, include_reviews: true, include_release: true }
995
+ };
996
+ const res = await this.#get("IStoreBrowseService/GetItems/v1/", {
997
+ input_json: JSON.stringify(input)
998
+ });
999
+ return summarizeItems(res, appids);
1000
+ }
1001
+ // Catalog-wide deal discovery (keyless) via the store query backend: find all
1002
+ // games at/above a minimum discount, with price + review % in the same call.
1003
+ // `minReview`/`minReviews` filter the returned page (the Query API ignores
1004
+ // review filters), so widen `count` for stricter thresholds.
1005
+ async discoverDeals(p) {
1006
+ const input = {
1007
+ query: {
1008
+ start: p.start ?? 0,
1009
+ count: p.count ?? 50,
1010
+ filters: { price_filters: { min_discount_percent: p.minDiscount } }
1011
+ },
1012
+ context: {
1013
+ language: p.language ?? this.#l,
1014
+ country_code: p.country ?? this.#country,
1015
+ steam_realm: 1
1016
+ },
1017
+ data_request: { include_basic_info: true, include_reviews: true }
1018
+ };
1019
+ const res = await this.#get("IStoreQueryService/Query/v1/", {
1020
+ input_json: JSON.stringify(input)
1021
+ });
1022
+ return summarizeDiscover(res, { minReview: p.minReview, minReviews: p.minReviews });
1023
+ }
1024
+ // A player's wishlist (needs the wishlist/profile to be public). Keyless.
1025
+ async getWishlist(steamid2) {
1026
+ const res = await this.#get("IWishlistService/GetWishlist/v1/", { steamid: steamid2 });
1027
+ return summarizeWishlist(res);
1028
+ }
1029
+ // Full achievement list for a game (GetSchemaForGame needs a key), merged with
1030
+ // the keyless global unlock % so each achievement carries its rarity. Cached.
1031
+ async getGameAchievements(appid3, language2) {
1032
+ const l = language2 ?? this.#l;
1033
+ return this.#cache.wrapStaleOnError(`schema:${appid3}:${l}`, async () => {
1034
+ const [schema, global] = await Promise.all([
1035
+ this.#get("ISteamUserStats/GetSchemaForGame/v2/", {
1036
+ appid: appid3,
1037
+ l
1038
+ }),
1039
+ this.#get(
1040
+ "ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/",
1041
+ { gameid: appid3 }
1042
+ )
1043
+ ]);
1044
+ return summarizeGameSchema(schema, global);
1045
+ });
1046
+ }
1047
+ };
1048
+
1049
+ // src/tools/storefront.ts
1050
+ import { z as z2 } from "zod";
1051
+
1052
+ // src/lib/result.ts
1053
+ function jsonResult(structured) {
1054
+ return {
1055
+ content: [{ type: "text", text: JSON.stringify(structured) }],
1056
+ structuredContent: structured
1057
+ };
1058
+ }
1059
+ function errorResult(message) {
1060
+ return { content: [{ type: "text", text: message }], isError: true };
1061
+ }
1062
+ function apiErrorToResult(err) {
1063
+ return errorResult(messageFor(err));
1064
+ }
1065
+ function messageFor(err) {
1066
+ switch (err.code) {
1067
+ case "unauthorized":
1068
+ return "The upstream service rejected the credentials (401). They may be missing or expired \u2014 check the configured API key / token.";
1069
+ case "forbidden":
1070
+ return "The upstream service denied access (403). The credentials may lack permission.";
1071
+ case "not_found":
1072
+ return "No matching resource was found (404).";
1073
+ case "not_modified":
1074
+ return "The content has not changed since the last request (304).";
1075
+ case "rate_limited":
1076
+ return "Upstream rate limit hit (429). Please retry in a few seconds.";
1077
+ case "server_error":
1078
+ return "The upstream service returned an error (5xx). Please retry later.";
1079
+ case "network":
1080
+ return "Could not reach the upstream service (network error). Check connectivity and retry.";
1081
+ case "timeout":
1082
+ return "The upstream request timed out. Please retry.";
1083
+ case "bad_request":
1084
+ return `The request was rejected as invalid: ${err.message}`;
1085
+ default:
1086
+ return `Unexpected error talking to the upstream service: ${err.message}`;
1087
+ }
1088
+ }
1089
+
1090
+ // src/tools/guard.ts
1091
+ async function guard(fn) {
1092
+ try {
1093
+ return await fn();
1094
+ } catch (err) {
1095
+ if (err instanceof ApiError) return apiErrorToResult(err);
1096
+ return errorResult(`Unexpected error: ${err instanceof Error ? err.message : String(err)}`);
1097
+ }
1098
+ }
1099
+
1100
+ // src/tools/storefront.ts
1101
+ var READ_ONLY = { readOnlyHint: true, openWorldHint: true };
1102
+ var appid = z2.number().int().positive().describe("Steam application id (appid). Get it from search_games.");
1103
+ var country = z2.string().regex(/^[A-Za-z]{2}$/, "Two-letter ISO country code, e.g. US, RU, DE.").describe("Country (cc) for prices/currency; overrides STEAM_COUNTRY for this call.").optional();
1104
+ var language = z2.string().min(2).describe("Store language (e.g. english, russian); overrides STEAM_LANGUAGE for this call.").optional();
1105
+ var reply = (fn) => guard(async () => jsonResult(await fn()));
1106
+ function registerStorefrontTools(server, store) {
1107
+ server.registerTool(
1108
+ "search_games",
1109
+ {
1110
+ title: "Search games",
1111
+ description: "Search the Steam store by title; returns matches with their appid (needed by the other game tools), price, Metacritic score and platforms. No API key required.",
1112
+ inputSchema: {
1113
+ term: z2.string().min(1).describe("Game title to search for."),
1114
+ country,
1115
+ language
1116
+ },
1117
+ annotations: READ_ONLY
1118
+ },
1119
+ ({ term, country: cc, language: l }) => reply(() => store.searchGames(term, cc, l))
1120
+ );
1121
+ server.registerTool(
1122
+ "get_game",
1123
+ {
1124
+ title: "Get game details",
1125
+ description: "Get full store details for one game by appid: description, price/discount, genres, platforms, release date, developers/publishers, Metacritic, age rating, DLC and PC requirements. Get the appid from search_games. No API key required.",
1126
+ inputSchema: { appid, country, language },
1127
+ annotations: READ_ONLY
1128
+ },
1129
+ ({ appid: id, country: cc, language: l }) => reply(() => store.getGame(id, cc, l))
1130
+ );
1131
+ server.registerTool(
1132
+ "get_game_reviews",
1133
+ {
1134
+ title: "Get game reviews",
1135
+ description: "Get the review summary (score label, positive/negative counts, %) and a few recent reviews for a game by appid. Get the appid from search_games. No API key required.",
1136
+ inputSchema: {
1137
+ appid,
1138
+ limit: z2.number().int().min(1).max(20).describe("How many recent reviews (1-20).").optional(),
1139
+ review_language: z2.string().describe("Filter reviews by language, e.g. 'english'. Default 'all'.").optional(),
1140
+ type: z2.enum(["all", "positive", "negative"]).describe("Only positive or negative reviews. Default 'all'.").optional()
1141
+ },
1142
+ annotations: READ_ONLY
1143
+ },
1144
+ ({ appid: id, limit, review_language, type }) => reply(() => store.getReviews(id, limit ?? 5, review_language ?? "all", type ?? "all"))
1145
+ );
1146
+ server.registerTool(
1147
+ "get_review_histogram",
1148
+ {
1149
+ title: "Get review trend over time",
1150
+ description: "Get how a game's reviews trend over time by appid: a long-term (monthly) history and the recent per-day breakdown, each with positive/negative counts and positive %. Good for 'are reviews improving / did an update hurt reception'. Get the appid from search_games. No key.",
1151
+ inputSchema: { appid },
1152
+ annotations: READ_ONLY
1153
+ },
1154
+ ({ appid: id }) => reply(() => store.getReviewHistogram(id))
1155
+ );
1156
+ server.registerTool(
1157
+ "get_prices",
1158
+ {
1159
+ title: "Get prices for many games",
1160
+ description: "Get current price and discount for a batch of games by appid in one call \u2014 efficient for checking a whole list (e.g. a wishlist) for deals. Each row has the final/initial price and discount_percent (or is_free). No API key required. Get appids from search_games or get_wishlist.",
1161
+ inputSchema: {
1162
+ appids: z2.array(z2.number().int().positive()).min(1).max(500).describe("Steam appids to price (1-500)."),
1163
+ country
1164
+ },
1165
+ annotations: READ_ONLY
1166
+ },
1167
+ ({ appids, country: cc }) => reply(() => store.getPrices(appids, cc))
1168
+ );
1169
+ server.registerTool(
1170
+ "get_specials",
1171
+ {
1172
+ title: "Get current discounts",
1173
+ description: "List games currently on special (discounted) on the Steam store front page, with the discount % and original/final price. For ALL catalog discounts (not just the front page), use discover_deals. No API key required.",
1174
+ inputSchema: { country, language },
1175
+ annotations: READ_ONLY
1176
+ },
1177
+ ({ country: cc, language: l }) => reply(() => store.getSpecials(cc, l))
1178
+ );
1179
+ server.registerTool(
1180
+ "get_featured",
1181
+ {
1182
+ title: "Get featured store sections",
1183
+ description: "Get the Steam store's featured sections: specials, top sellers, new releases and coming soon (each a list of games with appid and price). No API key required.",
1184
+ inputSchema: { country, language },
1185
+ annotations: READ_ONLY
1186
+ },
1187
+ ({ country: cc, language: l }) => reply(() => store.getFeatured(cc, l))
1188
+ );
1189
+ }
1190
+
1191
+ // src/tools/web.ts
1192
+ import { z as z3 } from "zod";
1193
+ var READ_ONLY2 = { readOnlyHint: true, openWorldHint: true };
1194
+ var appid2 = z3.number().int().positive().describe("Steam application id (appid). Get it from search_games.");
1195
+ var steamid = z3.string().regex(
1196
+ /^\d{17}$/,
1197
+ "A SteamID64 is 17 digits. Use resolve_vanity_url to convert a custom profile name."
1198
+ ).describe("17-digit SteamID64. Convert a vanity/custom URL name with resolve_vanity_url first.");
1199
+ var reply2 = (fn) => guard(async () => jsonResult(await fn()));
1200
+ function registerWebTools(server, web) {
1201
+ const requireKey = (fn) => {
1202
+ if (!web.configured) {
1203
+ return Promise.resolve(
1204
+ errorResult(
1205
+ "This tool needs a Steam Web API key. Set STEAM_API_KEY to a free key from https://steamcommunity.com/dev/apikey. (Note: the target profile must also be public.)"
1206
+ )
1207
+ );
1208
+ }
1209
+ return reply2(fn);
1210
+ };
1211
+ server.registerTool(
1212
+ "get_game_news",
1213
+ {
1214
+ title: "Get game news",
1215
+ description: "Get recent news / patch notes for a game by appid (title, date, author, excerpt, link). Get the appid from search_games. Works without an API key.",
1216
+ inputSchema: {
1217
+ appid: appid2,
1218
+ limit: z3.number().int().min(1).max(20).describe("How many news items (1-20).").optional()
1219
+ },
1220
+ annotations: READ_ONLY2
1221
+ },
1222
+ ({ appid: id, limit }) => reply2(() => web.getNews(id, limit ?? 5))
1223
+ );
1224
+ server.registerTool(
1225
+ "get_global_achievements",
1226
+ {
1227
+ title: "Get global achievement rates",
1228
+ description: "Get the global unlock percentage of each achievement in a game by appid \u2014 how rare each achievement is across all players. Get the appid from search_games. Works without a key.",
1229
+ inputSchema: { appid: appid2 },
1230
+ annotations: READ_ONLY2
1231
+ },
1232
+ ({ appid: id }) => reply2(() => web.getGlobalAchievements(id))
1233
+ );
1234
+ server.registerTool(
1235
+ "get_items",
1236
+ {
1237
+ title: "Batch store card for many games",
1238
+ description: "Get price/discount, review % (positive) and release date for a LIST of games by appid in ONE keyless call. The efficient way to price- and rating-check a wishlist or library without a request per game. Get appids from search_games / get_wishlist / get_owned_games.",
1239
+ inputSchema: {
1240
+ appids: z3.array(z3.number().int().positive()).min(1).max(100).describe("Steam appids (1-100)."),
1241
+ country: z3.string().regex(/^[A-Za-z]{2}$/, "Two-letter ISO country code.").describe("Country (cc) for prices; overrides STEAM_COUNTRY.").optional(),
1242
+ language: z3.string().min(2).describe("Store language; overrides STEAM_LANGUAGE.").optional()
1243
+ },
1244
+ annotations: READ_ONLY2
1245
+ },
1246
+ ({ appids, country: country2, language: language2 }) => reply2(() => web.getItems(appids, country2, language2))
1247
+ );
1248
+ server.registerTool(
1249
+ "discover_deals",
1250
+ {
1251
+ title: "Discover discounted games (catalog-wide)",
1252
+ description: "Find games currently on sale across the whole Steam catalog (keyless) \u2014 filter by minimum discount, and optionally by review quality. Each result has discount %, price, review % and release date in one call. Use for 'all games >80% off with good reviews'. No appids needed (unlike get_items, which prices a list you already have).",
1253
+ inputSchema: {
1254
+ min_discount: z3.number().int().min(1).max(100).describe("Minimum discount %, e.g. 80 for '80%+ off'."),
1255
+ min_review: z3.number().int().min(0).max(100).describe("Minimum positive-review %, e.g. 90. Applied over the returned page.").optional(),
1256
+ min_reviews: z3.number().int().min(0).describe("Minimum review count (filters shovelware with few reviews).").optional(),
1257
+ count: z3.number().int().min(1).max(200).describe("How many catalog entries to scan (default 50). Raise for stricter filters.").optional(),
1258
+ start: z3.number().int().min(0).describe("Pagination offset into the catalog.").optional(),
1259
+ country: z3.string().regex(/^[A-Za-z]{2}$/, "Two-letter ISO country code.").describe("Country (cc) for prices; overrides STEAM_COUNTRY.").optional(),
1260
+ language: z3.string().min(2).describe("Store language; overrides STEAM_LANGUAGE.").optional()
1261
+ },
1262
+ annotations: READ_ONLY2
1263
+ },
1264
+ ({ min_discount, min_review, min_reviews, count, start: start2, country: country2, language: language2 }) => reply2(
1265
+ () => web.discoverDeals({
1266
+ minDiscount: min_discount,
1267
+ minReview: min_review,
1268
+ minReviews: min_reviews,
1269
+ count,
1270
+ start: start2,
1271
+ country: country2,
1272
+ language: language2
1273
+ })
1274
+ )
1275
+ );
1276
+ server.registerTool(
1277
+ "get_current_players",
1278
+ {
1279
+ title: "Get current player count",
1280
+ description: "Get how many people are playing a game right now (live concurrent player count) by appid. Get the appid from search_games. Works without a key.",
1281
+ inputSchema: { appid: appid2 },
1282
+ annotations: READ_ONLY2
1283
+ },
1284
+ ({ appid: id }) => reply2(() => web.getCurrentPlayers(id))
1285
+ );
1286
+ server.registerTool(
1287
+ "get_wishlist",
1288
+ {
1289
+ title: "Get a player's wishlist",
1290
+ description: "List the appids on a player's Steam wishlist (sorted by their priority) by SteamID64. Works without a key, but only if that player's wishlist/profile is public \u2014 otherwise it returns found:false. Items carry no names; use get_game per appid for details. Convert a vanity name with resolve_vanity_url first.",
1291
+ inputSchema: { steamid },
1292
+ annotations: READ_ONLY2
1293
+ },
1294
+ ({ steamid: id }) => reply2(() => web.getWishlist(id))
1295
+ );
1296
+ server.registerTool(
1297
+ "get_game_achievements",
1298
+ {
1299
+ title: "Get a game's full achievement list",
1300
+ description: "List ALL achievements of a game by appid with their names, descriptions, hidden flag and global unlock % (rarity). Requires STEAM_API_KEY (the achievement schema needs a key). For just the rarity by internal id without a key, use get_global_achievements; for a few named highlights, see get_game's achievements_highlighted. Get the appid from search_games.",
1301
+ inputSchema: {
1302
+ appid: appid2,
1303
+ language: z3.string().min(2).describe("Language for achievement names/descriptions; overrides STEAM_LANGUAGE.").optional()
1304
+ },
1305
+ annotations: READ_ONLY2
1306
+ },
1307
+ ({ appid: id, language: language2 }) => requireKey(() => web.getGameAchievements(id, language2))
1308
+ );
1309
+ server.registerTool(
1310
+ "resolve_vanity_url",
1311
+ {
1312
+ title: "Resolve vanity URL to SteamID",
1313
+ description: "Convert a Steam custom (vanity) profile name \u2014 the part after /id/ in a profile URL \u2014 into the 17-digit SteamID64 that the player tools need. Requires STEAM_API_KEY.",
1314
+ inputSchema: {
1315
+ vanity: z3.string().min(1).describe(
1316
+ "Vanity name, e.g. 'gabelogannewell' from steamcommunity.com/id/gabelogannewell."
1317
+ )
1318
+ },
1319
+ annotations: READ_ONLY2
1320
+ },
1321
+ ({ vanity }) => requireKey(() => web.resolveVanityUrl(vanity))
1322
+ );
1323
+ server.registerTool(
1324
+ "get_player_summary",
1325
+ {
1326
+ title: "Get player profile",
1327
+ description: "Get a player's public profile by SteamID64: display name, online state, country, account age, and the game they're currently in. Requires STEAM_API_KEY and a public profile.",
1328
+ inputSchema: { steamid },
1329
+ annotations: READ_ONLY2
1330
+ },
1331
+ ({ steamid: id }) => requireKey(() => web.getPlayerSummary(id))
1332
+ );
1333
+ server.registerTool(
1334
+ "get_owned_games",
1335
+ {
1336
+ title: "Get owned games",
1337
+ description: "List the games a player owns with playtime (hours), most-played first. Requires STEAM_API_KEY and a public profile + game-details visibility. Get the SteamID64 from resolve_vanity_url.",
1338
+ inputSchema: { steamid },
1339
+ annotations: READ_ONLY2
1340
+ },
1341
+ ({ steamid: id }) => requireKey(() => web.getOwnedGames(id))
1342
+ );
1343
+ server.registerTool(
1344
+ "get_recently_played",
1345
+ {
1346
+ title: "Get recently played games",
1347
+ description: "List the games a player has played in the last two weeks, with recent and total playtime. Requires STEAM_API_KEY and a public profile.",
1348
+ inputSchema: { steamid },
1349
+ annotations: READ_ONLY2
1350
+ },
1351
+ ({ steamid: id }) => requireKey(() => web.getRecentlyPlayed(id))
1352
+ );
1353
+ server.registerTool(
1354
+ "get_player_achievements",
1355
+ {
1356
+ title: "Get a player's achievements",
1357
+ description: "Get a player's achievement progress for one game (unlocked count, % complete, per-achievement unlock dates) by SteamID64 + appid. Requires STEAM_API_KEY and a public profile.",
1358
+ inputSchema: { steamid, appid: appid2 },
1359
+ annotations: READ_ONLY2
1360
+ },
1361
+ ({ steamid: id, appid: app }) => requireKey(() => web.getPlayerAchievements(id, app))
1362
+ );
1363
+ }
1364
+
1365
+ // src/server.ts
1366
+ var INSTRUCTIONS = "Query Steam games and players. Store data needs no key: search_games \u2192 get_game / get_game_reviews for details, get_specials / get_featured / discover_deals for what's on sale (discover_deals finds all catalog discounts by min %, with review % included), get_items to price- and rating-check a list of appids in one call, get_game_news and get_global_achievements for a game's news and achievement rarity, get_current_players for live player counts. Player data needs a free Steam Web API key (STEAM_API_KEY): get_player_summary, get_owned_games, get_recently_played and get_player_achievements take a 17-digit SteamID64 \u2014 use resolve_vanity_url to convert a custom profile name first, and note the target profile must be public. Tools that need the key report clearly when it is unset.";
1367
+ function buildServer(config, logger) {
1368
+ const store = new StorefrontClient(config, logger);
1369
+ const web = new SteamWebClient(config, logger);
1370
+ const server = new McpServer(
1371
+ { name: "steam-games-mcp", version: VERSION },
1372
+ { instructions: INSTRUCTIONS }
1373
+ );
1374
+ registerStorefrontTools(server, store);
1375
+ registerWebTools(server, web);
1376
+ return server;
1377
+ }
1378
+ async function start() {
1379
+ const config = loadConfig();
1380
+ const logger = createLogger(config.logLevel);
1381
+ const server = buildServer(config, logger);
1382
+ await server.connect(new StdioServerTransport());
1383
+ logger.info(`steam-games-mcp ${VERSION} ready`);
1384
+ const shutdown = (signal) => {
1385
+ logger.info(`received ${signal}, shutting down`);
1386
+ void server.close().finally(() => process.exit(0));
1387
+ };
1388
+ process.on("SIGINT", () => shutdown("SIGINT"));
1389
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
1390
+ process.on("unhandledRejection", (reason) => logger.error("unhandled rejection", reason));
1391
+ process.on("uncaughtException", (err) => {
1392
+ logger.error("uncaught exception", err);
1393
+ process.exit(1);
1394
+ });
1395
+ }
1396
+
1397
+ // src/index.ts
1398
+ start().catch((err) => {
1399
+ process.stderr.write(
1400
+ `[mcp-server-template] fatal: ${err instanceof Error ? err.message : String(err)}
1401
+ `
1402
+ );
1403
+ process.exit(1);
1404
+ });
1405
+ //# sourceMappingURL=index.js.map