steam-games-mcp 0.8.0 → 0.8.1

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/CHANGELOG.md CHANGED
@@ -6,6 +6,12 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.1] - 2026-07-18
10
+
11
+ ### Changed
12
+
13
+ - Sharpen `search_games`, `get_prices`, `get_items` and `get_global_achievements`'s descriptions — cross-reference `get_items`/`get_prices` for the right batch size vs richness tradeoff, and disclose concrete parameter/return-shape facts instead of restating the schema ([d75122a](https://github.com/Grinv/steam-games-mcp/commit/d75122a), [db8c25e](https://github.com/Grinv/steam-games-mcp/commit/db8c25e), [72781e9](https://github.com/Grinv/steam-games-mcp/commit/72781e9)).
14
+
9
15
  ## [0.8.0] - 2026-07-18
10
16
 
11
17
  ### Added
package/dist/index.js CHANGED
@@ -76,7 +76,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
76
76
  `:`[${i[c]}\r
77
77
  ]`;continue}r+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return r}function Bu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,r)=>({...i,[r]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??$e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===k.ZodString&&t.keyType._def.checks?.length){let{type:i,...r}=Ku(t.keyType._def,e);return{...n,propertyNames:r}}else{if(t.keyType?._def.typeName===k.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&t.keyType._def.type._def.checks?.length){let{type:i,...r}=Hu(t.keyType._def,e);return{...n,propertyNames:r}}}return n}function Hb(t,e){if(e.mapStrategy==="record")return Bu(t,e);let n=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||$e(e),i=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||$e(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function Kb(t){let e=t.values,i=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),r=Array.from(new Set(i.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:i}}function Bb(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function Wb(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ea={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Yb(t,e){if(e.target==="openApi3")return Xb(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(i=>i._def.typeName in ea&&(!i._def.checks||!i._def.checks.length))){let i=n.reduce((r,o)=>{let a=ea[o._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:i.length>1?i:i[0]}}else if(n.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){let i=n.reduce((r,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];default:return r}},[]);if(i.length===n.length){let r=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:r.length>1?r:r[0],enum:n.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(n.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((i,r)=>[...i,...r._def.values.filter(o=>!i.includes(o))],[])};return Xb(t,e)}var Xb=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,r)=>F(i._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(i=>!!i&&(!e.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return n.length?{anyOf:n}:void 0};function Qb(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ea[t.innerType._def.typeName],nullable:!0}:{type:[ea[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let i=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function e$(t,e){let n={type:"number"};if(!t.checks)return n;for(let i of t.checks)switch(i.kind){case"int":n.type="integer",Uf(n,"type",i.message,e);break;case"min":e.target==="jsonSchema7"?i.inclusive?re(n,"minimum",i.value,i.message,e):re(n,"exclusiveMinimum",i.value,i.message,e):(i.inclusive||(n.exclusiveMinimum=!0),re(n,"minimum",i.value,i.message,e));break;case"max":e.target==="jsonSchema7"?i.inclusive?re(n,"maximum",i.value,i.message,e):re(n,"exclusiveMaximum",i.value,i.message,e):(i.inclusive||(n.exclusiveMaximum=!0),re(n,"maximum",i.value,i.message,e));break;case"multipleOf":re(n,"multipleOf",i.value,i.message,e);break}return n}function t$(t,e){let n=e.target==="openAi",i={type:"object",properties:{}},r=[],o=t.shape();for(let s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=tT(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=F(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||r.push(s))}r.length&&(i.required=r);let a=eT(t,e);return a!==void 0&&(i.additionalProperties=a),i}function eT(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function tT(t){try{return t.isOptional()}catch{return!0}}var r$=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:$e(e)},n]}:$e(e)};var n$=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let n=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),i=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function i$(t,e){return F(t.type._def,e)}function o$(t,e){let i={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&re(i,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&re(i,"maxItems",t.maxSize.value,t.maxSize.message,e),i}function a$(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,i)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,i)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function s$(t){return{not:$e(t)}}function c$(t){return $e(t)}var u$=(t,e)=>F(t.innerType._def,e);var l$=(t,e,n)=>{switch(e){case k.ZodString:return Ku(t,n);case k.ZodNumber:return e$(t,n);case k.ZodObject:return t$(t,n);case k.ZodBigInt:return Cb(t,n);case k.ZodBoolean:return Ub();case k.ZodDate:return Mf(t,n);case k.ZodUndefined:return s$(n);case k.ZodNull:return Wb(n);case k.ZodArray:return Zb(t,n);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Yb(t,n);case k.ZodIntersection:return Vb(t,n);case k.ZodTuple:return a$(t,n);case k.ZodRecord:return Bu(t,n);case k.ZodLiteral:return Gb(t,n);case k.ZodEnum:return Fb(t);case k.ZodNativeEnum:return Kb(t);case k.ZodNullable:return Qb(t,n);case k.ZodOptional:return r$(t,n);case k.ZodMap:return Hb(t,n);case k.ZodSet:return o$(t,n);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return i$(t,n);case k.ZodNaN:case k.ZodNever:return Bb(n);case k.ZodEffects:return qb(t,n);case k.ZodAny:return $e(n);case k.ZodUnknown:return c$(n);case k.ZodDefault:return Lb(t,n);case k.ZodBranded:return Hu(t,n);case k.ZodReadonly:return u$(t,n);case k.ZodCatch:return Mb(t,n);case k.ZodPipeline:return n$(t,n);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(i=>{})(e)}};function F(t,e,n=!1){let i=e.seen.get(t);if(e.override){let s=e.override?.(t,e,i,n);if(s!==Nb)return s}if(i&&!n){let s=rT(i,e);if(s!==void 0)return s}let r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);let o=l$(t,t.typeName,e),a=typeof o=="function"?F(o(),e):o;if(a&&nT(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return r.jsonSchema=a,s}return r.jsonSchema=a,a}var rT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ju(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,i)=>e.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),$e(e)):e.$refStrategy==="seen"?$e(e):void 0}},nT=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var Ff=(t,e)=>{let n=Ab(e),i=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:F(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??$e(n)}),{}):void 0,r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=F(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??$e(n),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),n.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[n.openAiAnyTypeName]||(i[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let s=r===void 0?i?{...o,[n.definitionPath]:i}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...i,[r]:o}};return n.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function iT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Vf(t,e){return lt(t)?Jr(t,{target:iT(e?.target),io:e?.pipeStrategy??"input"}):Ff(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Gf(t){let n=br(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Bc(n);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Jf(t,e){let n=_r(t,e);if(!n.success)throw n.error;return n.data}var oT=6e4,Wu=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Tu,n=>{this._oncancel(n)}),this.setNotificationHandler(Ru,n=>{this._onprogress(n)}),this.setRequestHandler(Eu,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ou,async(n,i)=>{let r=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!r)throw new A(M.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Nu,async(n,i)=>{let r=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,m=new A(d.error.code,d.error.message,d.error.data);l(m)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}let a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new A(M.InvalidParams,`Task not found: ${o}`);if(!wr(a.status))return await this._waitForTaskUpdate(o,i.signal),await r();if(wr(a.status)){let s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[xr]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(Du,async(n,i)=>{try{let{tasks:r,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,i.sessionId);return{tasks:r,nextCursor:o,_meta:{}}}catch(r){throw new A(M.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(Zu,async(n,i)=>{try{let r=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!r)throw new A(M.InvalidParams,`Task not found: ${n.params.taskId}`);if(wr(r.status))throw new A(M.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!o)throw new A(M.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(r){throw r instanceof A?r:new A(M.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,i,r,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,n),startTime:Date.now(),timeout:n,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:r})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let i=Date.now()-n.startTime;if(n.maxTotalTimeout&&i>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),A.fromError(M.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:i});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};let r=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{r?.(o,a),Go(o)||xb(o)?this._onresponse(o):Sf(o)?this._onrequest(o,a):$b(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(let i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();let n=A.fromError(M.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of e.values())i(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,n){let i=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,o=e.params?._meta?.[xr]?.taskId;if(i===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:M.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},r?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):r?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=yb(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,u={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new A(M.ConnectionClosed,"Request was cancelled");let p={...m,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let h=p.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,p)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>i(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},r?.sessionId):await r?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:M.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},r?.sessionId):await r?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...i}=e.params,r=Number(n),o=this._progressHandlers.get(r);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(c){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(c);return}o(i)}_onresponse(e){let n=Number(e.id),i=this._requestResolvers.get(n);if(i){if(this._requestResolvers.delete(n),Go(e))i(e);else{let a=new A(e.error.code,e.error.message,e.error.data);i(a)}return}let r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(Go(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,n))}}if(o||this._progressHandlers.delete(n),Go(e))r(e);else{let a=A.fromError(e.error.code,e.error.message,e.error.data);r(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,i){let{task:r}=i??{};if(!r){try{yield{type:"result",result:await this.request(e,n,i)}}catch(a){yield{type:"error",error:a instanceof A?a:new A(M.InternalError,String(a))}}return}let o;try{let a=await this.request(e,ai,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new A(M.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},wr(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)}:s.status==="failed"?yield{type:"error",error:new A(M.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new A(M.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof A?a:new A(M.InternalError,String(a))}}}request(e,n,i){let{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{let d=U=>{l(U)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(U){d(U);return}i?.signal?.throwIfAborted();let m=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[xr]:c}});let h=U=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(U)}},{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a}).catch(L=>this._onerror(new Error(`Failed to send cancellation: ${L}`)));let Z=U instanceof A?U:new A(M.RequestTimeout,String(U));l(Z)};this._responseHandlers.set(m,U=>{if(!i?.signal?.aborted){if(U instanceof Error)return l(U);try{let Z=_r(n,U.result);Z.success?u(Z.data):l(Z.error)}catch(Z){l(Z)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});let y=i?.timeout??oT,_=()=>h(A.fromError(M.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(m,y,i?.maxTotalTimeout,_,i?.resetTimeoutOnProgress??!1);let z=c?.taskId;if(z){let U=Z=>{let L=this._responseHandlers.get(m);L?L(Z):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,U),this._enqueueTaskMessage(z,{type:"request",message:p,timestamp:Date.now()}).catch(Z=>{this._cleanupTimeout(m),l(Z)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a}).catch(U=>{this._cleanupTimeout(m),l(U)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},ju,n)}async getTaskResult(e,n,i){return this.request({method:"tasks/result",params:e},n,i)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Au,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},Sb,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let i=n?.relatedTask?.taskId;if(i){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[xr]:n.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[xr]:n.relatedTask}}}),this._transport?.send(s,n).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[xr]:n.relatedTask}}}),await this._transport.send(a,n)}setRequestHandler(e,n){let i=Gf(e);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(r,o)=>{let a=Jf(e,r);return Promise.resolve(n(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let i=Gf(e);this._notificationHandlers.set(i,r=>{let o=Jf(e,r);return Promise.resolve(n(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,i,r)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(e,n);for(let r of i)if(r.type==="request"&&Sf(r.message)){let o=r.message.id,a=this._requestResolvers.get(o);a?(a(new A(M.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let i=this._options?.defaultTaskPollInterval??1e3;try{let r=await this._taskStore?.getTask(e);r?.pollInterval&&(i=r.pollInterval)}catch{}return new Promise((r,o)=>{if(n.aborted){o(new A(M.InvalidRequest,"Request cancelled"));return}let a=setTimeout(r,i);n.addEventListener("abort",()=>{clearTimeout(a),o(new A(M.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await i.createTask(r,e.id,{method:e.method,params:e.params},n)},getTask:async r=>{let o=await i.getTask(r,n);if(!o)throw new A(M.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(r,o,a)=>{await i.storeTaskResult(r,o,a,n);let s=await i.getTask(r,n);if(s){let c=Wo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),wr(s.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>i.getTaskResult(r,n),updateTaskStatus:async(r,o,a)=>{let s=await i.getTask(r,n);if(!s)throw new A(M.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(wr(s.status))throw new A(M.InvalidParams,`Cannot update task "${r}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(r,o,a,n);let c=await i.getTask(r,n);if(c){let u=Wo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),wr(c.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>i.listTasks(r,n)}}};function d$(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function m$(t,e){let n={...t};for(let i in e){let r=i,o=e[r];if(o===void 0)continue;let a=n[r];d$(a)&&d$(o)?n[r]={...a,...o}:n[r]=o}return n}var nk=tv(Og(),1),ik=tv(rk(),1);function c1(){let t=new nk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ik.default)(t),t}var Rl=class{constructor(e){this._ajv=e??c1()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Ol=class{constructor(e){this._server=e}requestStream(e,n,i){return this._server.requestStream(e,n,i)}createMessageStream(e,n){let i=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!i?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],a=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],u=c.some(l=>l.type==="tool_use");if(a){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),d=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==d.size||![...l].every(m=>d.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Qo,n)}elicitInputStream(e,n){let i=this._server.getClientCapabilities(),r=e.mode??"form";switch(r){case"url":{if(!i?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!i?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=r==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},ui,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,i){return this._server.getTaskResult({taskId:e},n,i)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function ok(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function ak(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var jl=class extends Wu{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Yo.options.map((i,r)=>[i,r])),this.isMessageIgnored=(i,r)=>{let o=this._loggingLevels.get(r);return o?this.LOG_LEVEL_SEVERITY.get(i)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Rl,this.setRequestHandler(Pf,i=>this._oninitialize(i)),this.setNotificationHandler(Tf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Af,async(i,r)=>{let o=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=i.params,s=Yo.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ol(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=m$(this._capabilities,e)}setRequestHandler(e,n){let r=br(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let o;if(lt(r)){let s=r;o=s._zod?.def?.value??s.value}else{let s=r;o=s._def?.value??s.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(c,u)=>{let l=_r(ci,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new A(M.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,m=await Promise.resolve(n(c,u));if(d.task){let h=_r(ai,m);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new A(M.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let p=_r(Vu,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new A(M.InvalidParams,`Invalid tools/call result: ${h}`)}return p.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){ak(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&ok(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:hb.includes(n)?n:wf,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Pu)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],r=Array.isArray(i.content)?i.content:[i.content],o=r.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(o){if(r.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(r.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Zf,n):this.request({method:"sampling/createMessage",params:e},Qo,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let r=e;return this.request({method:"elicitation/create",params:r},ui,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let r=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:r},ui,n);if(o.action==="accept"&&o.content&&r.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(r.requestedSchema)(o.content);if(!s.valid)throw new A(M.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof A?a:new A(M.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Cf,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var ck=Symbol.for("mcp.completable");function Mg(t){return!!t&&typeof t=="object"&&ck in t}function uk(t){return t[ck]?.complete}var sk;(function(t){t.Completable="McpCompletable"})(sk||(sk={}));var u1=/^[A-Za-z0-9._-]{1,128}$/;function l1(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!u1.test(t)){let n=t.split("").filter(i=>!/[A-Za-z0-9._-]/.test(i)).filter((i,r,o)=>o.indexOf(i)===r);return e.push(`Tool name contains invalid characters: ${n.map(i=>`"${i}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function d1(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Lg(t){let e=l1(t);return d1(t,e.warnings),e.isValid}var Nl=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,i){let r={taskSupport:"required",...n.execution};if(r.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,r,n._meta,i)}};var Dl=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new jl(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Nl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Or(Fu)),this.server.assertCanSetRequestHandler(Or(ci)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Fu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let i={name:e,title:n.title,description:n.description,inputSchema:(()=>{let r=Bn(n.inputSchema);return r?Vf(r,{strictUnions:!0,pipeStrategy:"input"}):m1})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let r=Bn(n.outputSchema);r&&(i.outputSchema=Vf(r,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(ci,async(e,n)=>{try{let i=this._registeredTools[e.params.name];if(!i)throw new A(M.InvalidParams,`Tool ${e.params.name} not found`);if(!i.enabled)throw new A(M.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,o=i.execution?.taskSupport,a="createTask"in i.handler;if((o==="required"||o==="optional")&&!a)throw new A(M.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!r)throw new A(M.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!r&&a)return await this.handleAutomaticTaskPolling(i,e,n);let s=await this.validateToolInput(i,e.params.arguments,e.params.name),c=await this.executeToolHandler(i,s,n);return r||await this.validateToolOutput(i,c,e.params.name),c}catch(i){if(i instanceof A&&i.code===M.UrlElicitationRequired)throw i;return this.createToolError(i instanceof Error?i.message:String(i))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,i){if(!e.inputSchema)return;let o=Bn(e.inputSchema)??e.inputSchema,a=await Hc(o,n);if(!a.success){let s="error"in a?a.error:"Unknown error",c=Kc(s);throw new A(M.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${c}`)}return a.data}async validateToolOutput(e,n,i){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new A(M.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let r=Bn(e.outputSchema),o=await Hc(r,n.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=Kc(a);throw new A(M.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${s}`)}}async executeToolHandler(e,n,i){let r=e.handler;if("createTask"in r){if(!i.taskStore)throw new Error("No task store provided.");let a={...i,taskStore:i.taskStore};if(e.inputSchema){let s=r;return await Promise.resolve(s.createTask(n,a))}else{let s=r;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=r;return await Promise.resolve(a(n,i))}else{let a=r;return await Promise.resolve(a(i))}}async handleAutomaticTaskPolling(e,n,i){if(!i.taskStore)throw new Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(e,n.params.arguments,n.params.name),o=e.handler,a={...i,taskStore:i.taskStore},s=r?await Promise.resolve(o.createTask(r,a)):await Promise.resolve(o.createTask(a)),c=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,l));let d=await i.taskStore.getTask(c);if(!d)throw new A(M.InternalError,`Task ${c} not found during polling`);u=d}return await i.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Or(Gu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Gu,async e=>{switch(e.params.ref.type){case"ref/prompt":return Rb(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Ob(e),this.handleResourceCompletion(e,e.params.ref);default:throw new A(M.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let i=this._registeredPrompts[n.name];if(!i)throw new A(M.InvalidParams,`Prompt ${n.name} not found`);if(!i.enabled)throw new A(M.InvalidParams,`Prompt ${n.name} disabled`);if(!i.argsSchema)return Ea;let o=br(i.argsSchema)?.[e.params.argument.name];if(!Mg(o))return Ea;let a=uk(o);if(!a)return Ea;let s=await a(e.params.argument.value,e.params.context);return dk(s)}async handleResourceCompletion(e,n){let i=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===n.uri);if(!i){if(this._registeredResources[n.uri])return Ea;throw new A(M.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=i.resourceTemplate.completeCallback(e.params.argument.name);if(!r)return Ea;let o=await r(e.params.argument.value,e.params.context);return dk(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Or(Cu)),this.server.assertCanSetRequestHandler(Or(Uu)),this.server.assertCanSetRequestHandler(Or(Mu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Cu,async(e,n)=>{let i=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),r=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(n);for(let s of a.resources)r.push({...o.metadata,...s})}return{resources:[...i,...r]}}),this.server.setRequestHandler(Uu,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,i])=>({name:n,uriTemplate:i.resourceTemplate.uriTemplate.toString(),...i.metadata}))})),this.server.setRequestHandler(Mu,async(e,n)=>{let i=new URL(e.params.uri),r=this._registeredResources[i.toString()];if(r){if(!r.enabled)throw new A(M.InvalidParams,`Resource ${i} disabled`);return r.readCallback(i,n)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(i.toString());if(a)return o.readCallback(i,a,n)}throw new A(M.InvalidParams,`Resource ${i} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Or(Lu)),this.server.assertCanSetRequestHandler(Or(qu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Lu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?p1(n.argsSchema):void 0}))})),this.server.setRequestHandler(qu,async(e,n)=>{let i=this._registeredPrompts[e.params.name];if(!i)throw new A(M.InvalidParams,`Prompt ${e.params.name} not found`);if(!i.enabled)throw new A(M.InvalidParams,`Prompt ${e.params.name} disabled`);if(i.argsSchema){let r=Bn(i.argsSchema),o=await Hc(r,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=Kc(c);throw new A(M.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=o.data,s=i.callback;return await Promise.resolve(s(a,n))}else{let r=i.callback;return await Promise.resolve(r(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...i){let r;typeof i[0]=="object"&&(r=i.shift());let o=i[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let a=this._createRegisteredResource(e,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,n,i,r){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(e,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,n,i,r,o){let a={name:e,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==i&&(delete this._registeredResources[i],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=a,a}_createRegisteredResourceTemplate(e,n,i,r,o){let a={resourceTemplate:i,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=a)),typeof u.title<"u"&&(a.title=u.title),typeof u.template<"u"&&(a.resourceTemplate=u.template),typeof u.metadata<"u"&&(a.metadata=u.metadata),typeof u.callback<"u"&&(a.readCallback=u.callback),typeof u.enabled<"u"&&(a.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!i.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,n,i,r,o){let a={title:n,description:i,argsSchema:r===void 0?void 0:Hr(r),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=Hr(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(c=>{let u=c instanceof ii?c._def?.innerType:c;return Mg(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,n,i,r,o,a,s,c,u){Lg(e);let l={title:n,description:i,inputSchema:lk(r),outputSchema:lk(o),annotations:a,execution:s,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&Lg(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Hr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hr(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let i,r,o,a;if(typeof n[0]=="string"&&(i=n.shift()),n.length>1){let c=n[0];if(qg(c))r=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!qg(n[0])&&(a=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=n.shift()}}let s=n[0];return this._createRegisteredTool(e,void 0,i,r,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,n,i){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:r,description:o,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,r,o,a,s,c,{taskSupport:"forbidden"},u,i)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let i;typeof n[0]=="string"&&(i=n.shift());let r;n.length>1&&(r=n.shift());let o=n[0],a=this._createRegisteredPrompt(e,void 0,i,r,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,n,i){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:r,description:o,argsSchema:a}=n,s=this._createRegisteredPrompt(e,r,o,a,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var m1={type:"object",properties:{}};function mk(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function pk(t){return"_def"in t||"_zod"in t||mk(t)}function qg(t){return typeof t!="object"||t===null||pk(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(mk)}function lk(t){if(t){if(qg(t))return Hr(t);if(!pk(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function p1(t){let e=br(t);return e?Object.entries(e).map(([n,i])=>{let r=e_(i),o=t_(i);return{name:n,description:r,required:!o}}):[]}function Or(t){let n=br(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Bc(n);if(typeof i=="string")return i;throw new Error("Schema method literal must be a string")}function dk(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ea={completion:{values:[],hasMore:!1}};import hk from"process";var Al=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
78
78
  `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),f1(n)}clear(){this._buffer=void 0}};function f1(t){return wb.parse(JSON.parse(t))}function fk(t){return JSON.stringify(t)+`
79
- `}var Zl=class{constructor(e=hk.stdin,n=hk.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Al,this._started=!1,this._ondata=i=>{this._readBuffer.append(i),this.processReadBuffer()},this._onerror=i=>{this.onerror?.(i)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let i=fk(e);this._stdout.write(i)?n():this._stdout.once("drain",n)})}};var h1=O.object({STEAM_API_KEY:O.string().min(1).optional(),STEAM_API_BASE_URL:O.string().url().default("https://api.steampowered.com"),STEAM_ID:O.string().min(2).optional(),STEAM_STORE_BASE_URL:O.string().url().default("https://store.steampowered.com"),STEAM_COUNTRY:O.string().min(2).max(2).default("US"),STEAM_LANGUAGE:O.string().min(2).default("english"),HTTP_TIMEOUT_MS:O.coerce.number().int().positive().default(15e3),HTTP_RETRIES:O.coerce.number().int().nonnegative().default(2),STEAM_STORE_MIN_INTERVAL_MS:O.coerce.number().int().nonnegative().default(250),STEAM_API_MIN_INTERVAL_MS:O.coerce.number().int().nonnegative().default(0),CACHE_TTL_MS:O.coerce.number().int().nonnegative().default(3e5),LOG_LEVEL:O.enum(["debug","info","warn","error","silent"]).default("info")}),g1=/^\$\{[^}]*\}$/;function gk(t=process.env){let e=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0&&i!==""&&!g1.test(i))),n=h1.parse(e);return{steamApiBaseUrl:n.STEAM_API_BASE_URL,steamApiKey:n.STEAM_API_KEY,defaultSteamId:n.STEAM_ID,steamStoreBaseUrl:n.STEAM_STORE_BASE_URL,country:n.STEAM_COUNTRY,language:n.STEAM_LANGUAGE,httpTimeoutMs:n.HTTP_TIMEOUT_MS,httpRetries:n.HTTP_RETRIES,storeMinIntervalMs:n.STEAM_STORE_MIN_INTERVAL_MS,apiMinIntervalMs:n.STEAM_API_MIN_INTERVAL_MS,cacheTtlMs:n.CACHE_TTL_MS,logLevel:n.LOG_LEVEL}}var xe=class extends Error{code;status;retryable;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="ApiError",this.code=e.code,this.status=e.status,this.retryable=e.retryable??!1}};function vk(t){return t===304?{code:"not_modified",retryable:!1}:t===401?{code:"unauthorized",retryable:!1}:t===403?{code:"forbidden",retryable:!1}:t===404?{code:"not_found",retryable:!1}:t===429?{code:"rate_limited",retryable:!0}:t===400||t===405||t===422?{code:"bad_request",retryable:!1}:t>=500?{code:"server_error",retryable:!0}:{code:"unknown",retryable:!1}}function Fg(t){return t.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,"Bearer ***").replace(/\b(access_token|refresh_token|client_secret|client_id|key)=([^&\s"]+)/gi,"$1=***")}var yk={debug:10,info:20,warn:30,error:40,silent:100};function _k(t,e){let n=yk[t];function i(r,o,a){if(yk[r]<n)return;let s=a.length?" "+Fg(a.map(u=>v1(u)).join(" ")):"",c=`${Fg(o)}${s}`;if(console.error(`[steam-games-mcp] ${r}: ${c}`),e)try{e(r,c)}catch{}}return{debug:(r,...o)=>i("debug",r,o),info:(r,...o)=>i("info",r,o),warn:(r,...o)=>i("warn",r,o),error:(r,...o)=>i("error",r,o)}}function v1(t){if(typeof t=="string")return t;if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}var Cl="0.8.0",bk=`steam-games-mcp/${Cl} (+https://github.com/Grinv/steam-games-mcp)`;var $k=8e3,Pi=class{#e;constructor(e){this.#e=e}async getJson(e,n={}){return this.requestJson(e,{...n,method:n.method??"GET"})}async requestJson(e,n={}){let i=this.#r(e,n.query),r=n.retries??this.#e.retries??2,o=n.timeoutMs??this.#e.timeoutMs??15e3,a=0;for(;;){this.#e.beforeRequest&&await this.#e.beforeRequest();try{return await this.#i(i,n,o)}catch(s){let c=s instanceof xe?s:xk(s);if(!c.retryable||a>=r)throw c;let u=b1(a,c);this.#e.logger.debug(`retrying ${i} after ${u}ms (attempt ${a+1}/${r}, ${c.code})`),await k1(u),a+=1}}}async#i(e,n,i){let r=new AbortController,o=setTimeout(()=>r.abort(),i),a=()=>r.abort();n.signal?.addEventListener("abort",a,{once:!0});let s;try{s=await fetch(e,{method:n.method??"GET",headers:{"User-Agent":bk,Accept:"application/json",...this.#e.defaultHeaders,...n.headers},...n.body===void 0?{}:{body:n.body},signal:r.signal})}catch(u){throw n.signal?.aborted?new xe({code:"network",message:"Request aborted by caller",cause:u}):r.signal.aborted?new xe({code:"timeout",message:`Request timed out after ${i}ms`,retryable:!0,cause:u}):xk(u)}finally{clearTimeout(o),n.signal?.removeEventListener("abort",a)}if(!s.ok)throw await y1(s);if(s.status===204)return;let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch(u){throw new xe({code:"unknown",message:"Upstream returned invalid JSON",cause:u})}}#r(e,n){let i=new URL(e.replace(/^\//,""),w1(this.#e.baseUrl));if(n)for(let[r,o]of Object.entries(n))o!==void 0&&i.searchParams.set(r,String(o));return i.toString()}};async function y1(t){let{code:e,retryable:n}=vk(t.status),i="";try{i=await t.text()}catch{}let r=_1(i)??i.slice(0,500),o=x1(t.headers.get("retry-after"));return new xe({code:e,status:t.status,retryable:n,message:`HTTP ${t.status} ${t.statusText}${r?`: ${r}`:""}`,...o===void 0?{}:{cause:{retryAfterMs:o}}})}function _1(t){if(t)try{let e=JSON.parse(t);if(e===null||typeof e!="object")return;let n=e;return typeof n.message=="string"?n.message:typeof n.error=="string"?n.error:void 0}catch{return}}function xk(t){return t instanceof xe?t:new xe({code:"network",message:t instanceof Error?`Network error: ${t.message}`:"Network error",retryable:!0,cause:t})}function b1(t,e){let n=e.cause?.retryAfterMs;if(typeof n=="number"&&n>0)return Math.min(n,$k);let i=Math.min($k,500*2**t);return i+Math.floor(i*.25*$1(t))}function $1(t){return t*2654435761%1e3/1e3}function x1(t){if(!t)return;let e=Number(t);if(Number.isFinite(e))return e*1e3;let n=Date.parse(t);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function w1(t){return t.endsWith("/")?t:t+"/"}function k1(t){return new Promise(e=>setTimeout(e,t))}var Ti=class{#e;#i;#r;#t=[];#o=Promise.resolve();#a=null;constructor(e,n=[]){this.#e=Math.max(0,e),this.#i=n,this.#r=n.reduce((i,r)=>Math.max(i,r.windowMs),0)}acquire(){let e=this.#o,n;return this.#o=new Promise(i=>{n=i}),e.then(async()=>{let i=this.#s();i>0&&await S1(i);let r=Date.now();this.#a=r,this.#c(r),n()})}#s(){let e=Date.now(),n=this.#a!==null?this.#a+this.#e:0;for(let i of this.#i){if(this.#t.length<i.limit)continue;let r=this.#t[this.#t.length-i.limit];n=Math.max(n,r+i.windowMs)}return Math.max(0,n-e)}#c(e){this.#t.push(e);let n=e-this.#r,i=0;for(;i<this.#t.length&&this.#t[i]<=n;)i+=1;i>0&&this.#t.splice(0,i)}};function S1(t){return new Promise(e=>setTimeout(e,t))}var Ei=class{#e;#i;#r=new Map;#t=new Map;constructor(e,n=500){this.#e=e,this.#i=n}get(e){let n=this.#r.get(e);if(n)return n.expires>Date.now()?n.value:void 0}getStale(e){return this.#r.get(e)?.value}set(e,n){if(!(this.#e<=0)){if(!this.#r.has(e)&&this.#r.size>=this.#i){let i=this.#r.keys().next().value;i!==void 0&&this.#r.delete(i)}this.#r.set(e,{value:n,expires:Date.now()+this.#e})}}async wrap(e,n){let i=this.get(e);return i!==void 0?i:this.#o(e,n)}async wrapStaleOnError(e,n){let i=this.get(e);if(i!==void 0)return i;try{return await this.#o(e,n)}catch(r){let o=this.getStale(e);if(o!==void 0)return o;throw r}}#o(e,n){let i=this.#t.get(e);if(i)return i;let r=n().then(o=>(this.set(e,o),o)).finally(()=>this.#t.delete(e));return this.#t.set(e,r),r}};function Vg(t){return(t??[]).map(e=>e.description??e.name).filter(e=>!!e)}function qt(t){return typeof t=="number"?Math.round(t/60*10)/10:null}function Ra(t){return t&&t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()||null}function Oa(t,e){if(typeof t!="number")return null;let n=(t/100).toFixed(2);return e?`${n} ${e}`:n}function Et(t){return t?new Date(t*1e3).toISOString().slice(0,10):null}function wk(t){return t?new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z"):null}function tr(t){return typeof t=="number"?`https://store.steampowered.com/app/${t}`:null}function Sk(t){return{currency:t.currency??null,final:t.final_formatted??null,initial:t.initial_formatted||t.final_formatted||null,discount_percent:t.discount_percent??0}}function z1(t,e){return e?{is_free:!0}:t?{is_free:!1,...Sk(t)}:null}function zk(t){return t?Object.entries(t).filter(([,e])=>e).map(([e])=>e):[]}function Ik(t){let e=Array.isArray(t.pc_requirements)?void 0:t.pc_requirements;return{appid:t.steam_appid,name:t.name,type:t.type??null,short_description:t.short_description||null,is_free:t.is_free??!1,price:z1(t.price_overview,t.is_free),release_date:t.release_date?.date||null,coming_soon:t.release_date?.coming_soon??!1,developers:t.developers??[],publishers:t.publishers??[],genres:Vg(t.genres),categories:Vg(t.categories),platforms:zk(t.platforms),metacritic:t.metacritic?.score??null,metacritic_url:t.metacritic?.url??null,recommendations:t.recommendations?.total??null,required_age:t.required_age??null,controller_support:t.controller_support??null,achievements_total:t.achievements?.total??null,achievements_highlighted:(t.achievements?.highlighted??[]).map(n=>n.name).filter(n=>!!n),supported_languages:Ra(t.supported_languages),dlc:t.dlc??[],demos:(t.demos??[]).map(n=>n.appid).filter(Boolean),content_descriptors:{ids:t.content_descriptors?.ids??[],notes:t.content_descriptors?.notes??null},base_game:t.fullgame?.appid?{appid:Number(t.fullgame.appid),name:t.fullgame.name??null}:null,drm_notice:t.drm_notice||null,account_notice:t.ext_user_account_notice||null,pc_requirements_min:Ra(e?.minimum),website:t.website||null,header_image:t.header_image||null,store_url:tr(t.steam_appid)}}function I1(t){if(!t||typeof t.final!="number")return null;let e=t.initial&&t.final&&t.initial>t.final?Math.round((1-t.final/t.initial)*100):0;return{currency:t.currency??null,final:Oa(t.final,t.currency),initial:Oa(t.initial,t.currency),discount_percent:e}}function Pk(t){return{total:t.total??t.items?.length??0,results:(t.items??[]).map(e=>({appid:e.id,name:e.name,type:e.type??null,price:I1(e.price),metascore:e.metascore||null,platforms:zk(e.platforms),store_url:tr(e.id)}))}}function Tk(t,e){let n=e.map(i=>{let r=t[String(i)],o=r?.data,a=o&&!Array.isArray(o)?o.price_overview:void 0;return r?.success?a?{appid:i,available:!0,is_free:!1,...Sk(a)}:{appid:i,available:!0,is_free:!0}:{appid:i,available:!1}});return{count:n.length,prices:n}}function Ek(t,e=5){let n=t.query_summary??{};return{summary:n.review_score_desc??null,total_reviews:n.total_reviews??null,total_positive:n.total_positive??null,total_negative:n.total_negative??null,positive_pct:n.total_reviews&&n.total_positive?Math.round(n.total_positive/n.total_reviews*100):null,reviews:(t.reviews??[]).slice(0,e).map(i=>({voted_up:i.voted_up??null,votes_up:i.votes_up??0,author_playtime_hours:qt(i.author?.playtime_forever),text:i.review?i.review.length>600?i.review.slice(0,600)+"\u2026":i.review:null}))}}function ja(t){return(t??[]).map(e=>({appid:e.id,name:e.name,discounted:e.discounted??!1,discount_percent:e.discount_percent??0,original_price:Oa(e.original_price,e.currency),final_price:Oa(e.final_price,e.currency),store_url:tr(e.id)}))}function Rk(t){return{specials:ja(t.specials?.items),top_sellers:ja(t.top_sellers?.items),new_releases:ja(t.new_releases?.items),coming_soon:ja(t.coming_soon?.items)}}function Ok(t){return{specials:ja(t.specials?.items)}}function kk(t){let e=t.recommendations_up??0,n=t.recommendations_down??0,i=e+n;return{date:Et(t.date),up:e,down:n,positive_pct:i?Math.round(e/i*100):null}}function jk(t){let e=t.results??{};return{rollup_type:e.rollup_type??null,history:(e.rollups??[]).slice(-24).map(kk),recent:(e.recent??[]).slice(-30).map(kk)}}var Ul=class{#e;#i;#r;#t;constructor(e,n){this.#r=e.country,this.#t=e.language;let i=new Ti(e.storeMinIntervalMs);this.#e=new Pi({baseUrl:e.steamStoreBaseUrl,logger:n,timeoutMs:e.httpTimeoutMs,retries:e.httpRetries,beforeRequest:()=>i.acquire()}),this.#i=new Ei(e.cacheTtlMs)}#o(e,n,i){return this.#e.getJson("api/storesearch/",{query:{term:e,l:i??this.#t,cc:n??this.#r}})}async searchGames(e,n,i){return Pk(await this.#o(e,n,i))}async resolveAppId(e,n,i){return(await this.#o(e,n,i)).items?.find(o=>typeof o.id=="number")?.id??null}async getGame(e,n,i){let r=n??this.#r,o=i??this.#t;return this.#i.wrapStaleOnError(`app:${e}:${r}:${o}`,async()=>{let s=(await this.#e.getJson("api/appdetails",{query:{appids:e,cc:r,l:o}}))[String(e)];if(!s?.success||!s.data)throw new xe({code:"not_found",message:`No Steam app with id ${e}`});return Ik(s.data)})}async getReviews(e,n,i="all",r="all"){let o=await this.#e.getJson(`appreviews/${e}`,{query:{json:1,num_per_page:n,language:i,review_type:r,purchase_type:"all"}});return Ek(o,n)}async getPrices(e,n){let i=n??this.#r,r=100,o={};for(let a=0;a<e.length;a+=r){let s=e.slice(a,a+r),c=await this.#e.getJson("api/appdetails",{query:{appids:s.join(","),cc:i,filters:"price_overview"}});Object.assign(o,c)}return Tk(o,e)}async getReviewHistogram(e){return this.#i.wrapStaleOnError(`hist:${e}:${this.#t}`,async()=>{let n=await this.#e.getJson(`appreviewhistogram/${e}`,{query:{l:this.#t}});return jk(n)})}#a(e,n){return this.#i.wrapStaleOnError(`featured:${e}:${n}`,async()=>await this.#e.getJson("api/featuredcategories",{query:{cc:e,l:n}}))}async getFeatured(e,n){return Rk(await this.#a(e??this.#r,n??this.#t))}async getSpecials(e,n){return Ok(await this.#a(e??this.#r,n??this.#t))}};var Nk=["offline","online","busy","away","snooze","looking to trade","looking to play"];function Dk(t,e){let n=t.response?.players?.[0];return n?{found:!0,steamid:n.steamid,name:n.personaname??null,real_name:n.realname||null,state:Nk[n.personastate??0]??"offline",visibility:n.communityvisibilitystate===3?"public":"private",country:n.loccountrycode||null,level:e??null,created:Et(n.timecreated),in_game:n.gameextrainfo||null,profile_url:n.profileurl??null,avatar:n.avatarfull??null}:{found:!1}}var Ak="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.";function Ml(t){return t.response?.game_count===void 0&&t.response?.games===void 0}function Zk(t,e=50){if(Ml(t))return{found:!1,reason:Ak,game_count:null,games:[]};let n=(t.response?.games??[]).slice().sort((i,r)=>(r.playtime_forever??0)-(i.playtime_forever??0));return{found:!0,game_count:t.response?.game_count??n.length,returned:Math.min(n.length,e),games:n.slice(0,e).map(i=>({appid:i.appid,name:i.name??null,playtime_hours:qt(i.playtime_forever),playtime_2weeks_hours:qt(i.playtime_2weeks)}))}}var P1="One or both profiles/game-details are private. Ask the owner(s) to set Steam \u2192 Privacy \u2192 Game details = Public.";function Ck(t,e,n=50){if(Ml(t)||Ml(e))return{found:!1,reason:P1};let i=new Map((t.response?.games??[]).map(a=>[a.appid,a])),r=new Map((e.response?.games??[]).map(a=>[a.appid,a])),o=[...i.keys()].filter(a=>typeof a=="number"&&r.has(a)).map(a=>{let s=i.get(a),c=r.get(a);return{appid:a,name:s.name??c.name??null,playtime_hours_a:qt(s.playtime_forever),playtime_hours_b:qt(c.playtime_forever)}}).sort((a,s)=>(s.playtime_hours_a??0)+(s.playtime_hours_b??0)-((a.playtime_hours_a??0)+(a.playtime_hours_b??0)));return{found:!0,shared_count:o.length,returned:Math.min(o.length,n),games:o.slice(0,n)}}function Uk(t){return Ml(t)?{found:!1,reason:Ak,total:0,games:[]}:{found:!0,total:t.response?.game_count??t.response?.games?.length??0,games:(t.response?.games??[]).map(e=>({appid:e.appid,name:e.name??null,playtime_2weeks_hours:qt(e.playtime_2weeks),playtime_hours:qt(e.playtime_forever)}))}}function Mk(t){let e=t.playerstats;if(!e?.success)return{found:!1,reason:e?.error??"No achievement stats"};let n=e.achievements??[],i=n.filter(r=>r.achieved===1);return{found:!0,game:e.gameName??null,total:n.length,unlocked:i.length,completion_pct:n.length?Math.round(i.length/n.length*100):null,achievements:n.map(r=>({name:r.name||r.apiname,achieved:r.achieved===1,unlocked_at:r.achieved===1?Et(r.unlocktime):null}))}}function Lk(t){let e=t.achievementpercentages?.achievements??[];return{count:e.length,achievements:e.map(n=>({name:n.name,percent:typeof n.percent=="string"?Number(n.percent):n.percent??null}))}}function qk(t,e){let n=new Map;for(let r of e.achievementpercentages?.achievements??[])r.name!=null&&n.set(r.name,typeof r.percent=="string"?Number(r.percent):r.percent??0);let i=t.game?.availableGameStats?.achievements??[];return{game:t.game?.gameName??null,total:i.length,achievements:i.map(r=>{let o=r.name!=null?n.get(r.name):void 0;return{api_name:r.name,name:r.displayName||r.name||null,description:r.description||null,hidden:r.hidden===1,global_unlock_pct:typeof o=="number"?Math.round(o*10)/10:null}})}}function Fk(t){return{items:(t.appnews?.newsitems??[]).map(e=>({title:e.title??null,date:Et(e.date),author:e.author||null,feed:e.feedlabel||null,excerpt:Ra(e.contents),url:e.url??null}))}}function Vk(t){let e=t.response;return e?.success===1&&e.steamid?{found:!0,steamid:e.steamid}:{found:!1,reason:e?.message??"No match for that vanity name"}}function Gk(t,e){return{appid:e,player_count:t.response?.player_count??null}}function Jk(t,e=100){let n=t.response?.items??[];if(n.length===0)return{found:!1,reason:"Empty wishlist, or the profile/wishlist is private.",total:0,items:[]};let i=n.toSorted((r,o)=>(r.priority??1e9)-(o.priority??1e9));return{found:!0,total:n.length,returned:Math.min(n.length,e),items:i.slice(0,e).map(r=>({appid:r.appid,store_url:tr(r.appid),priority:r.priority??null,added:Et(r.date_added)}))}}function Hk(t){let e=t.players?.[0];return e?{found:!0,steamid:e.SteamId,vac_banned:e.VACBanned??!1,vac_ban_count:e.NumberOfVACBans??0,game_ban_count:e.NumberOfGameBans??0,community_banned:e.CommunityBanned??!1,economy_ban:e.EconomyBan&&e.EconomyBan!=="none"?e.EconomyBan:null,days_since_last_ban:e.DaysSinceLastBan??null}:{found:!1}}var T1=200;function Kk(t,e,n=T1){let i=t.response?.appids??[];return i.length===0?{found:!1,reason:"No followed games, or the profile is private.",total:0,games:[]}:{found:!0,total:e.response?.followed_game_count??i.length,returned:Math.min(i.length,n),games:i.slice(0,n).map(r=>({appid:r,store_url:tr(r)}))}}function Bk(t,e,n=100){let i=t.friendslist?.friends??[];if(i.length===0)return{found:!0,total:0,returned:0,friends:[]};let r=new Map;for(let a of e.response?.players??[])a.steamid&&r.set(a.steamid,a);let o=i.toSorted((a,s)=>(s.friend_since??0)-(a.friend_since??0));return{found:!0,total:i.length,returned:Math.min(i.length,n),friends:o.slice(0,n).map(a=>{let s=a.steamid?r.get(a.steamid):void 0;return{steamid:a.steamid,name:s?.personaname??null,state:Nk[s?.personastate??0]??"offline",in_game:s?.gameextrainfo||null,profile_url:s?.profileurl??null,friends_since:Et(a.friend_since)}})}}function Gg(t,e,n,i){let r=new Map;for(let c of i.response?.players??[])c.steamid&&r.set(c.steamid,c);let o=c=>({steamid:c,name:r.get(c)?.personaname??null}),a=new Map(t.map(c=>[c,[]])),s=[];return e.forEach((c,u)=>{let l=n[u];if(!l){s.push(o(c));return}for(let d of t)l.has(d)&&a.get(d).push({...o(c),playtime_hours:qt(l.get(d))})}),{found:!0,total_friends:e.length,matches:t.map(c=>({appid:c,owners:a.get(c)??[]})),private_friends:s}}function Xk(t){let e={};for(let n of t.response?.tags??[])typeof n.tagid=="number"&&n.name&&(e[n.tagid]=n.name);return e}var E1=8;function R1(t,e){return!t||!e?[]:t.slice().sort((n,i)=>(i.weight??0)-(n.weight??0)).map(n=>n.tagid!==void 0?e[n.tagid]:void 0).filter(n=>!!n).slice(0,E1)}function O1(t,e,n){let i=new Set((t??[]).map(r=>r.tagid!==void 0?e?.[r.tagid]:void 0).filter(r=>!!r).map(r=>r.toLowerCase()));return n.every(r=>i.has(r))}var j1={0:"unknown",1:"unsupported",2:"playable",3:"verified"};function Ll(t){return j1[t??0]??"unknown"}var N1={verified:3,playable:2},D1={windows:"windows",mac:"mac",linux:"steamos_linux"};function A1(t){if(!t)return[];let e=[];return t.windows&&e.push("windows"),t.mac&&e.push("mac"),t.steamos_linux&&e.push("linux"),e}function Z1(t){let e=(t?.active_discounts??[]).map(n=>n.discount_end_date).filter(n=>typeof n=="number"&&n>0);return e.length?wk(Math.min(...e)):null}function Yk(t){return{discount_pct:t?.discount_pct??0,discount_end:Z1(t),final:t?.formatted_final_price||null,original:t?.formatted_original_price||t?.formatted_final_price||null}}function Qk(t,e){let n=t.reviews?.summary_filtered;return{appid:t.appid,name:t.name??null,store_url:tr(t.appid),review_percent:n?.percent_positive??null,review_count:n?.review_count??null,review_label:n?.review_score_label??null,platforms:A1(t.platforms),steam_deck:Ll(t.platforms?.steam_deck_compat_category),steam_os:Ll(t.platforms?.steam_os_compat_category),steam_machine:Ll(t.platforms?.steam_machine_compat_category),steam_frame:Ll(t.platforms?.steam_frame_compat_category),tags:R1(t.tags,e),release_date:Et(t.release?.steam_release_date)}}function eS(t,e){let{final:n,...i}=Yk(t.best_purchase_option);return{...Qk(t,e),...i,price:n}}var C1=[["steamDeck","steam_deck_compat_category"],["steamOs","steam_os_compat_category"],["steamMachine","steam_machine_compat_category"],["steamFrame","steam_frame_compat_category"]];function tS(t){let e=C1.map(([r,o])=>{let a=t[r];return[o,a?N1[a]:void 0]}),n=t.platform?D1[t.platform]:void 0,i=t.tags?.length?t.tags.map(r=>r.toLowerCase()):void 0;return r=>{let o=r.platforms;for(let[c,u]of e)if(u!==void 0&&(o?.[c]??0)<u)return!1;if(n&&!o?.[n]||t.releasedAfter!==void 0&&(r.release?.steam_release_date??0)<t.releasedAfter||i&&!O1(r.tags,t.tagMap,i))return!1;let a=r.reviews?.summary_filtered;if(typeof t.minReview=="number"&&(a?.percent_positive??-1)<t.minReview||typeof t.minReviews=="number"&&(a?.review_count??0)<t.minReviews)return!1;let s=r.best_purchase_option?.discount_pct??0;if(typeof t.minDiscount=="number"){if(s<t.minDiscount)return!1}else if(t.onSaleOnly&&s<=0)return!1;return!0}}function rS(t,e){let n=tS(e),i=(t.response?.store_items??[]).filter(r=>r.visible!==!1&&typeof r.appid=="number"&&n(r)).map(r=>eS(r,e.tagMap)).sort((r,o)=>o.discount_pct-r.discount_pct);return{total_matching:t.response?.metadata?.total_matching_records??null,returned:i.length,deals:i}}function nS(t,e,n){let i=new Map;for(let r of t.response?.store_items??[])typeof r.appid=="number"&&i.set(r.appid,r);return{count:e.length,items:e.map(r=>{let o=i.get(r);if(!o||!o.name&&!o.best_purchase_option&&!o.reviews)return{appid:r,available:!1};let a=o.best_purchase_option;return{...Qk(o,n),is_free:o.is_free??!1,price:a?Yk(a):o.is_free?{is_free:!0}:null,coming_soon:o.release?.is_coming_soon??!1}})}}var Wk=60;function iS(t,e,n={}){let i=t.response?.items??[];if(i.length===0)return{found:!1,reason:"Empty wishlist, or the profile/wishlist is private.",total:0,items:[]};let r=i.filter(c=>c.store_item),o=tS({...n,tagMap:e}),a=r.filter(c=>typeof c.appid=="number"&&o(c.store_item)).map(c=>({...eS(c.store_item,e),priority:c.priority??null,added:Et(c.date_added)})),s=n.onSaleOnly||typeof n.minDiscount=="number";return a.sort((c,u)=>s?u.discount_pct-c.discount_pct:(c.priority??1e9)-(u.priority??1e9)),{found:!0,total:i.length,enriched:r.length,note:r.length<i.length?`Steam only returned store data for ${r.length} of ${i.length} wishlist items; filters/matches only cover those ${r.length} \u2014 the rest have no price, reviews or tags to check.`:void 0,matched:a.length,returned:Math.min(a.length,Wk),items:a.slice(0,Wk)}}var Jg=t=>({include_basic_info:!0,include_reviews:!0,include_release:!0,include_platforms:!0,include_tag_count:t}),ql=class{#e;#i;#r;#t;constructor(e){this.#e=e.get,this.#i=e.cache,this.#r=e.language,this.#t=e.country}async#o(e){try{return await this.#i.wrapStaleOnError(`tags:${e}`,async()=>{let i=await this.#e("IStoreService/GetTagList/v1/",{language:e});return Xk(i)})}catch{return null}}#a(e,n){if(n!==null)return n;if(e?.length)throw new xe({code:"unknown",message:"could not fetch Steam's tag dictionary right now, so the `tags` filter can't be reliably applied. Retry, or drop `tags` to see unfiltered results.",retryable:!0})}async#s(e,n,i,r){let[o,a]=await Promise.all([this.#e(e,n),this.#o(i)]);return{res:o,tagMap:this.#a(r,a)}}async getItems(e,n,i){let r=i??this.#r,o={ids:e.map(c=>({appid:c})),context:{language:r,country_code:n??this.#t},data_request:Jg(15)},{res:a,tagMap:s}=await this.#s("IStoreBrowseService/GetItems/v1/",{input_json:JSON.stringify(o)},r);return nS(a,e,s)}async#c(e){let n=e.language??this.#r,i={};typeof e.minDiscount=="number"&&(i.price_filters={min_discount_percent:e.minDiscount}),e.releasedOnly&&(i.released_only=!0);let r={query:{start:e.start??0,count:e.count??50,sort:10,filters:i},context:{language:n,country_code:e.country??this.#t,steam_realm:1},data_request:Jg(20)},{res:o,tagMap:a}=await this.#s("IStoreQueryService/Query/v1/",{input_json:JSON.stringify(r)},n,e.tags);return rS(o,{minReview:e.minReview,minReviews:e.minReviews,steamDeck:e.steamDeck,steamOs:e.steamOs,steamMachine:e.steamMachine,steamFrame:e.steamFrame,platform:e.platform,releasedAfter:e.releasedAfter,tags:e.tags,tagMap:a})}async discoverGames(e){return this.#c({...e,releasedOnly:e.releasedAfter!==void 0})}async getWishlistDetailed(e,n={}){let i=n.language??this.#r,r={steamid:e,context:{language:i,country_code:n.country??this.#t,steam_realm:1},data_request:Jg(20),sort:0},{res:o,tagMap:a}=await this.#s("IWishlistService/GetWishlistSortedFiltered/v1/",{input_json:JSON.stringify(r)},i,n.tags);return iS(o,a,{onSaleOnly:n.onSaleOnly,tags:n.tags,minReview:n.minReview,minDiscount:n.minDiscount,platform:n.platform,steamDeck:n.steamDeck,steamOs:n.steamOs,steamMachine:n.steamMachine,steamFrame:n.steamFrame})}};var oS="Profile or game-details are private. Ask the owner to set Steam \u2192 Privacy \u2192 Game details = Public.",aS="Profile or friends list is private. Ask the owner to set Steam \u2192 Privacy \u2192 Friends List = Public.";function sS(t){return(t.friendslist?.friends??[]).map(e=>e.steamid).filter(e=>!!e)}var Fl=class{#e;#i;#r;#t;#o;#a;#s;#c;configured;constructor(e,n){this.#r=e.steamApiKey,this.#t=e.language,this.#o=e.country,this.#a=e.defaultSteamId,this.configured=!!e.steamApiKey;let i=new Ti(e.apiMinIntervalMs);this.#e=new Pi({baseUrl:e.steamApiBaseUrl,logger:n,timeoutMs:e.httpTimeoutMs,retries:e.httpRetries,beforeRequest:()=>i.acquire()}),this.#i=new Ei(e.cacheTtlMs),this.#s=new ql({get:this.#n.bind(this),cache:this.#i,language:this.#t,country:this.#o})}#n(e,n){return this.#e.getJson(e,{query:{key:this.#r,...n}})}async requireSteamId(e){if(e)return e;let n=this.#a;if(!n)throw new xe({code:"bad_request",message:"no steamid was given and STEAM_ID is not set. Pass a 17-digit SteamID64, or set STEAM_ID (a SteamID64 or vanity name) in the server config."});if(/^\d{17}$/.test(n))return n;if(this.#c)return this.#c;if(!this.configured)throw new xe({code:"bad_request",message:`STEAM_ID is a vanity name ("${n}") which needs a Steam Web API key to resolve. Set STEAM_API_KEY, or set STEAM_ID to a 17-digit SteamID64 instead.`});let i=await this.#n("ISteamUser/ResolveVanityURL/v1/",{vanityurl:n}),r=i.response?.steamid;if(i.response?.success!==1||!r)throw new xe({code:"bad_request",message:`could not resolve the STEAM_ID vanity name "${n}" to a SteamID64.`});return this.#c=r,r}async getPlayerSummary(e){let[n,i]=await Promise.all([this.#n("ISteamUser/GetPlayerSummaries/v2/",{steamids:e}),this.#m(e)]);return Dk(n,i)}async#m(e){try{return(await this.#i.wrapStaleOnError(`level:${e}`,async()=>({level:(await this.#n("IPlayerService/GetSteamLevel/v1/",{steamid:e})).response?.player_level??null}))).level}catch{return null}}async getPlayerBans(e){let n=await this.#n("ISteamUser/GetPlayerBans/v1/",{steamids:e});return Hk(n)}async getOwnedGames(e){let n=await this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:e,include_appinfo:!0,include_played_free_games:!0});return Zk(n)}async getRecentlyPlayed(e){let n=await this.#n("IPlayerService/GetRecentlyPlayedGames/v1/",{steamid:e});return Uk(n)}async comparePlayers(e,n){let[i,r]=await Promise.all([this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:e,include_appinfo:!0}),this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:n,include_appinfo:!0})]);return Ck(i,r)}async getPlayerAchievements(e,n,i){let r=i??this.#t;try{let o=await this.#n("ISteamUserStats/GetPlayerAchievements/v1/",{steamid:e,appid:n,l:r});return o.playerstats?.success?Mk(o):this.#u(n,r,o.playerstats?.error)}catch(o){if(o instanceof xe&&(o.code==="forbidden"||o.code==="unauthorized"))return{found:!1,reason:oS};if(o instanceof xe&&(o.code==="bad_request"||o.code==="not_found"))return this.#u(n,r);throw o}}async#u(e,n,i){if(i&&/not public|private/i.test(i))return{found:!1,reason:oS};try{return{found:!1,reason:((await this.#n("ISteamUserStats/GetSchemaForGame/v2/",{appid:e,l:n})).game?.availableGameStats?.achievements?.length??0)>0?"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."}}catch{return{found:!1,reason:i||"Achievements unavailable."}}}async resolveVanityUrl(e){let n=await this.#n("ISteamUser/ResolveVanityURL/v1/",{vanityurl:e});return Vk(n)}async#l(e){if(e.length===0)return{};let n=[];for(let r=0;r<e.length;r+=100)n.push(e.slice(r,r+100));return{response:{players:(await Promise.all(n.map(r=>this.#n("ISteamUser/GetPlayerSummaries/v2/",{steamids:r.join(",")})))).flatMap(r=>r.response?.players??[])}}}async#d(e){try{return await this.#n("ISteamUser/GetFriendList/v1/",{steamid:e,relationship:"friend"})}catch(n){if(n instanceof xe&&(n.code==="forbidden"||n.code==="unauthorized"))return null;throw n}}async getFriendList(e){let n=await this.#d(e);return n===null?{found:!1,reason:aS}:Bk(n,await this.#l(sS(n)))}async findFriendsWhoOwn(e,n){let i=await this.#d(e);if(i===null)return{found:!1,reason:aS};let r=sS(i);if(r.length===0)return Gg(n,[],[],{});let[o,a]=await Promise.all([this.#l(r),Promise.all(r.map(s=>this.#p(s,n)))]);return Gg(n,r,a,o)}async#p(e,n){let i=await this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:e,include_appinfo:!1});if(i.response?.games===void 0&&i.response?.game_count===void 0)return null;let r=new Set(n),o=new Map;for(let a of i.response?.games??[])typeof a.appid=="number"&&r.has(a.appid)&&o.set(a.appid,a.playtime_forever??0);return o}async getNews(e,n){let i=await this.#n("ISteamNews/GetNewsForApp/v2/",{appid:e,count:n,maxlength:400});return Fk(i)}async getGlobalAchievements(e){return this.#i.wrapStaleOnError(`global-ach:${e}`,async()=>{let n=await this.#n("ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/",{gameid:e});return Lk(n)})}async getCurrentPlayers(e){let n=await this.#n("ISteamUserStats/GetNumberOfCurrentPlayers/v1/",{appid:e});return Gk(n,e)}get store(){return this.#s}async#f(e){let n=await this.#n("IWishlistService/GetWishlist/v1/",{steamid:e});return Jk(n)}async getFollowedGames(e){let[n,i]=await Promise.all([this.#n("IStoreService/GetGamesFollowed/v1/",{steamid:e}),this.#h(e)]);return Kk(n,i)}async#h(e){try{return await this.#n("IStoreService/GetGamesFollowedCount/v1/",{steamid:e})}catch{return{}}}#g(e,n){return this.#s.getWishlistDetailed(e,n)}async getWishlist(e,n={}){let{includeDetails:i,onSaleOnly:r,...o}=n;return i||r||Object.values(o).some(s=>s!==void 0)?this.#g(e,{onSaleOnly:r,...o}):this.#f(e)}async getGameAchievements(e,n){let i=n??this.#t;return this.#i.wrapStaleOnError(`schema:${e}:${i}`,async()=>{let[r,o]=await Promise.all([this.#n("ISteamUserStats/GetSchemaForGame/v2/",{appid:e,l:i}),this.#n("ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/",{gameid:e})]);return qk(r,o)})}};function Vl(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}function jr(t){return{content:[{type:"text",text:t}],isError:!0}}function cS(t){return jr(U1(t))}function U1(t){switch(t.code){case"unauthorized":return"The upstream service rejected the credentials (401). They may be missing or expired \u2014 check the configured API key / token.";case"forbidden":return"The upstream service denied access (403). The credentials may lack permission.";case"not_found":return"No matching resource was found (404).";case"not_modified":return"The content has not changed since the last request (304).";case"rate_limited":return"Upstream rate limit hit (429). Please retry in a few seconds.";case"server_error":return"The upstream service returned an error (5xx). Please retry later.";case"network":return"Could not reach the upstream service (network error). Check connectivity and retry.";case"timeout":return"The upstream request timed out. Please retry.";case"bad_request":return`The request was rejected as invalid: ${t.message}`;default:return`Unexpected error talking to the upstream service: ${t.message}`}}async function Gl(t){try{return await t()}catch(e){return e instanceof xe?cS(e):jr(`Unexpected error: ${e instanceof Error?e.message:String(e)}`)}}var ye={readOnlyHint:!0,openWorldHint:!0},Rt=O.number().int().positive().describe("Steam application id (appid). Get it from search_games."),Ft=O.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(),rr=O.string().min(2).describe("Store language (e.g. english, russian); overrides STEAM_LANGUAGE for this call.").optional(),Hg=O.enum(["windows","mac","linux"]).describe("NATIVE-build filter: keep only games shipping a native build for this OS (windows/mac/linux). 'linux' = a native Linux/SteamOS port. This is NOT Proton \u2014 for games that run via Proton compatibility use steam_os / steam_deck instead. Each result's `platforms` field lists its native builds, while steam_os/steam_deck report Proton compatibility, so native vs Proton stay distinct.").optional(),Kg=O.enum(["playable","verified"]).describe("Steam Deck compatibility (runs via Proton): 'verified' = Deck-Verified only; 'playable' = Playable or Verified. Not a native Linux build \u2014 see `platform` for that.").optional(),Bg=O.enum(["playable","verified"]).describe("SteamOS compatibility \u2014 how well it runs on SteamOS in general (via Proton): 'verified' = SteamOS-Verified only; 'playable' = Playable or Verified. For a NATIVE Linux build instead, use platform:'linux'; for the Steam Machine console specifically, use steam_machine.").optional(),Wg=O.enum(["playable","verified"]).describe("Steam Machine (Valve's console) compatibility (via Proton): 'verified' = Steam-Machine-Verified only; 'playable' = Playable or Verified. Its own rating, distinct from the general steam_os one.").optional(),Xg=O.enum(["playable","verified"]).describe("Steam Frame (VR headset) compatibility: 'verified' = Frame-Verified only; 'playable' = Playable or Verified.").optional(),De=t=>Gl(async()=>Vl(await t()));function uS(t,e){t.registerTool("search_games",{title:"Search games",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.",inputSchema:{term:O.string().min(1).describe("Game title to search for."),country:Ft,language:rr},annotations:ye},({term:n,country:i,language:r})=>De(()=>e.searchGames(n,i,r))),t.registerTool("get_game",{title:"Get game details",description:"Get full store details for one game: description, price/discount, genres, platforms, release date, developers/publishers, Metacritic, age rating, DLC and PC requirements. Identify the game by appid (from search_games) OR by name \u2014 a title is resolved to the closest store match. No API key required.",inputSchema:{appid:Rt.describe("Steam appid (from search_games). Provide appid OR name.").optional(),name:O.string().min(1).describe("Game title to look up instead of an appid \u2014 resolved to the closest store match. Provide appid OR name; appid wins if both are given.").optional(),country:Ft,language:rr},annotations:ye},({appid:n,name:i,country:r,language:o})=>Gl(async()=>{let a=n;if(!a){if(!i)return jr("Provide either appid or name.");let s=await e.resolveAppId(i,r,o);if(!s)return jr(`No Steam game found matching "${i}".`);a=s}return Vl(await e.getGame(a,r,o))})),t.registerTool("get_game_reviews",{title:"Get game reviews",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.",inputSchema:{appid:Rt,limit:O.number().int().min(1).max(20).describe("How many recent reviews (1-20).").optional(),review_language:O.string().describe("Filter reviews by language, e.g. 'english'. Default 'all'.").optional(),type:O.enum(["all","positive","negative"]).describe("Only positive or negative reviews. Default 'all'.").optional()},annotations:ye},({appid:n,limit:i,review_language:r,type:o})=>De(()=>e.getReviews(n,i??5,r??"all",o??"all"))),t.registerTool("get_review_histogram",{title:"Get review trend over time",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.",inputSchema:{appid:Rt},annotations:ye},({appid:n})=>De(()=>e.getReviewHistogram(n))),t.registerTool("get_prices",{title:"Get prices for many games",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.",inputSchema:{appids:O.array(O.number().int().positive()).min(1).max(500).describe("Steam appids to price (1-500)."),country:Ft},annotations:ye},({appids:n,country:i})=>De(()=>e.getPrices(n,i))),t.registerTool("get_specials",{title:"Get current discounts",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_games with min_discount. No API key required.",inputSchema:{country:Ft,language:rr},annotations:ye},({country:n,language:i})=>De(()=>e.getSpecials(n,i))),t.registerTool("get_featured",{title:"Get featured store sections",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), all in one call \u2014 for a general 'what's on the store front page' overview. For just current discounts use get_specials (lighter), or discover_games for catalog-wide deals with filters. No API key required.",inputSchema:{country:Ft,language:rr},annotations:ye},({country:n,language:i})=>De(()=>e.getFeatured(n,i)))}var vt=O.string().regex(/^\d{17}$/,"A SteamID64 is 17 digits. Use resolve_vanity_url to convert a custom profile name.").describe("17-digit SteamID64. Omit to use the STEAM_ID configured on the server. Convert a vanity/custom URL name with resolve_vanity_url first.").optional(),Nr=(t,e,n)=>({steamid:i})=>e(async()=>n(await t.requireSteamId(i)));function lS(t,e,n){t.registerTool("get_game_news",{title:"Get game news",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.",inputSchema:{appid:Rt,limit:O.number().int().min(1).max(20).describe("How many news items (1-20).").optional()},annotations:ye},({appid:i,limit:r})=>De(()=>e.getNews(i,r??5))),t.registerTool("get_global_achievements",{title:"Get global achievement rates",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.",inputSchema:{appid:Rt},annotations:ye},({appid:i})=>De(()=>e.getGlobalAchievements(i))),t.registerTool("get_items",{title:"Batch store card for many games",description:"Get price/discount, review % (positive), hardware compatibility, popular user tags and release date for a LIST of games by appid in ONE keyless call. The efficient way to price-, rating-, tag- and compat-check a wishlist or library without a request per game. Each item carries four compatibility fields, each verified/playable/unsupported/unknown: steam_deck (Steam Deck), steam_os (SteamOS in general), steam_machine (the Steam Machine console specifically), and steam_frame (Steam Frame VR headset); a `tags` list (top user tags like 'Roguelike', 'Souls-like', most-relevant first); a clickable `store_url` to the game's Steam page; and, when on sale, `discount_end` (ISO UTC time the discount expires \u2014 for 'how long is this deal valid'). Get appids from search_games / get_wishlist / get_owned_games.",inputSchema:{appids:O.array(O.number().int().positive()).min(1).max(100).describe("Steam appids (1-100)."),country:Ft,language:rr},annotations:ye},({appids:i,country:r,language:o})=>De(()=>n.getItems(i,r,o))),t.registerTool("discover_games",{title:"Discover games (deals, new releases, Steam Deck, rating)",description:"Find games across the whole Steam catalog (keyless), filtered by ANY combination of: discount (min_discount \u2014 for 'what's on sale'), release recency (released_after / released_within_days \u2014 for 'new games'), hardware compatibility (steam_deck for Steam Deck, steam_os for SteamOS in general, steam_machine for the Steam Machine console specifically, steam_frame for the Steam Frame VR headset), native OS build (platform \u2014 windows/mac/linux), review quality (min_review / min_reviews), and user tags (tags \u2014 e.g. ['Roguelike', 'Deckbuilding'] for 'games like X'). Each result returns price/discount, review %, all four compat statuses, popular tags, a clickable store_url, discount_end (when a deal expires) and release date in one call. Examples: '>80% off with 90%+ reviews' \u2192 set min_discount + min_review; 'recent well-reviewed games that run on Steam Deck' \u2192 set released_within_days + steam_deck + min_review; 'roguelike deckbuilders on sale' \u2192 tags:['Roguelike','Deckbuilding'] + min_discount; 'games that run on the Steam Machine' \u2192 steam_machine; 'games that run on SteamOS' \u2192 steam_os. No appids needed \u2014 unlike get_items, which prices a list you already have. Note: the Steam catalog API has no release-date/tag sort or filter, so results are scanned popularity-first and the recency, compat and tag filters are applied over that window \u2014 great for popular titles; a niche match may fall outside the top `count` (raise count for stricter filters).",inputSchema:{released_after:O.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Use an ISO date, e.g. 2026-03-01.").describe("Keep only games released on/after this date (YYYY-MM-DD).").optional(),released_within_days:O.number().int().min(1).describe("Alternative to released_after: released within the last N days.").optional(),steam_deck:Kg,steam_os:Bg,steam_machine:Wg,steam_frame:Xg,platform:Hg,tags:O.array(O.string().min(1)).min(1).describe("Keep only games carrying ALL of these user tags (case-insensitive), e.g. ['Roguelike','Deckbuilding']. Use exact Steam tag names. Applied over the scanned popularity window, so raise `count` when combining niche tags.").optional(),min_review:O.number().int().min(0).max(100).describe("Minimum positive-review %, e.g. 85. Applied over the returned page.").optional(),min_reviews:O.number().int().min(0).describe("Minimum review count (filters out games with too few reviews).").optional(),min_discount:O.number().int().min(1).max(100).describe("Minimum discount %, e.g. 80 for '80%+ off' \u2014 this is the 'deals' filter. Omit to include full-price games.").optional(),count:O.number().int().min(1).max(200).describe("How many catalog entries to scan (default 50). Raise for stricter filters.").optional(),start:O.number().int().min(0).describe("Pagination offset into the catalog.").optional(),country:Ft,language:rr},annotations:ye},({released_after:i,released_within_days:r,steam_deck:o,steam_os:a,steam_machine:s,steam_frame:c,platform:u,tags:l,min_review:d,min_reviews:m,min_discount:p,count:h,start:y,country:_,language:z})=>{let U;return i?U=Math.floor(Date.parse(i)/1e3):r&&(U=Math.floor(Date.now()/1e3)-r*86400),De(()=>n.discoverGames({releasedAfter:U,steamDeck:o,steamOs:a,steamMachine:s,steamFrame:c,platform:u,tags:l,minReview:d,minReviews:m,minDiscount:p,count:h,start:y,country:_,language:z}))}),t.registerTool("get_current_players",{title:"Get current player count",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.",inputSchema:{appid:Rt},annotations:ye},({appid:i})=>De(()=>e.getCurrentPlayers(i))),t.registerTool("get_followed_games",{title:"Get a player's followed games",description:"List the games a player 'follows' on the Steam store, by SteamID64 \u2014 a lighter opt-in (get sale/update notifications) that's separate from the wishlist; many players follow more games than they wishlist. Works without a key, but only if that player's follows/profile are public \u2014 otherwise it returns found:false. Returns appids + store_url only (no price/name); pass the appids to get_items for price, review % and compat. Convert a vanity name with resolve_vanity_url first.",inputSchema:{steamid:vt},annotations:ye},Nr(e,De,i=>e.getFollowedGames(i))),t.registerTool("get_wishlist",{title:"Get a player's wishlist",description:"List a player's Steam wishlist by SteamID64. Works without a key, but only if that player's wishlist/profile is public \u2014 otherwise it returns found:false. By default returns a light list of appids (sorted by priority, no names). Set include_details for full store cards in ONE call (name, price/discount, review %, Deck/SteamOS/Machine/Frame compat, tags, release) \u2014 no need to follow up with get_items. Narrow it in the SAME call with tags (e.g. ['Metroidvania']), platform (NATIVE windows/mac/linux build), steam_deck / steam_os / steam_machine / steam_frame (Proton compatibility \u2014 distinct from a native build), min_review and min_discount / on_sale_only, or country / language (the light appid list carries no price, so setting either implies include_details too) \u2014 these are applied before the output cap, so a deeply-discounted niche match past the display cap is never hidden by it (e.g. 'top metroidvanias on my wishlist with a good discount and reviews' \u2192 tags:['Metroidvania'] + min_discount + min_review). Results ranked by discount when a discount filter is set, else by wishlist priority; `matched` reports the pre-cap count. Steam itself only attaches store data to roughly the first 100 wishlist entries per call \u2014 on a bigger wishlist, `enriched` reports how many of `total` got checked, and `note` explains when some were skipped (their filter/price data isn't available at all, not that they don't match). Convert a vanity name with resolve_vanity_url first.",inputSchema:{steamid:vt,include_details:O.boolean().describe("Return full store cards (name, price, discount, reviews, compatibility, tags) per item in one call, instead of just appids. Implied by any filter below.").optional(),on_sale_only:O.boolean().describe("Only wishlist items currently discounted, ranked by discount %. Implies include_details.").optional(),tags:O.array(O.string().min(1)).min(1).describe("Keep only wishlist items carrying ALL of these user tags (case-insensitive), e.g. ['Metroidvania']. Implies include_details.").optional(),min_review:O.number().int().min(0).max(100).describe("Keep only items with at least this positive-review %. Implies include_details.").optional(),min_discount:O.number().int().min(1).max(100).describe("Keep only items discounted at least this %, ranked by discount. Implies include_details.").optional(),platform:Hg,steam_deck:Kg,steam_os:Bg,steam_machine:Wg,steam_frame:Xg,country:Ft.describe("Country (cc) for prices; overrides STEAM_COUNTRY. Only meaningful for store cards, so setting it implies include_details \u2014 the light appid list carries no price."),language:rr.describe("Store language; overrides STEAM_LANGUAGE. Only meaningful for store cards, so setting it implies include_details \u2014 the light appid list carries no price.")},annotations:ye},({steamid:i,include_details:r,on_sale_only:o,tags:a,min_review:s,min_discount:c,platform:u,steam_deck:l,steam_os:d,steam_machine:m,steam_frame:p,country:h,language:y})=>De(async()=>{let _=await e.requireSteamId(i);return e.getWishlist(_,{includeDetails:r,onSaleOnly:o,tags:a,minReview:s,minDiscount:c,platform:u,steamDeck:l,steamOs:d,steamMachine:m,steamFrame:p,country:h,language:y})}))}function dS(t,e){let n=i=>e.configured?De(i):Promise.resolve(jr("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.)"));t.registerTool("get_game_achievements",{title:"Get a game's full achievement list",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.",inputSchema:{appid:Rt,language:O.string().min(2).describe("Language for achievement names/descriptions; overrides STEAM_LANGUAGE.").optional()},annotations:ye},({appid:i,language:r})=>n(()=>e.getGameAchievements(i,r))),t.registerTool("resolve_vanity_url",{title:"Resolve vanity URL to SteamID",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.",inputSchema:{vanity:O.string().min(1).describe("Vanity name, e.g. 'gabelogannewell' from steamcommunity.com/id/gabelogannewell.")},annotations:ye},({vanity:i})=>n(()=>e.resolveVanityUrl(i))),t.registerTool("get_friend_list",{title:"Get a player's friend list",description:"List a player's Steam friends by SteamID64: name, online state, current game and how long they've been friends, most-recently-added first. Requires STEAM_API_KEY and the friends list to be public. For 'which of my friends own game X', use find_friends_who_own instead \u2014 it checks each friend's full library, not just this list. Get the SteamID64 from resolve_vanity_url.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getFriendList(i))),t.registerTool("find_friends_who_own",{title:"Find friends who own a game",description:"Check which of a player's Steam friends own one or more games by appid, with each owner's playtime_hours \u2014 'which of my friends have Portal 2 and how long have they played'. Checks each friend's FULL library, unlike get_owned_games / get_friend_list which cap at the top 50 games by playtime \u2014 so a friend's rarely-played or unplayed copy is never missed (its playtime_hours may still be low or 0). Requires STEAM_API_KEY and the player's friends list to be public; friends with a private library are listed separately in private_friends (can't be checked) rather than silently counted as non-owners. Get appids from search_games.",inputSchema:{appids:O.array(O.number().int().positive()).min(1).max(10).describe("Steam appids to check (1-10)."),steamid:vt},annotations:ye},({appids:i,steamid:r})=>n(async()=>e.findFriendsWhoOwn(await e.requireSteamId(r),i))),t.registerTool("compare_players",{title:"Compare two players' libraries",description:"Find games two players both own, with each one's playtime \u2014 'what can my friend and I both play', 'do we have anything in common'. Checks each player's FULL library, unlike get_owned_games which caps at the top 50 by playtime. Requires STEAM_API_KEY and both profiles' game-details to be public. Omit steamid to compare against yourself (STEAM_ID).",inputSchema:{steamid:vt,other_steamid:O.string().regex(/^\d{17}$/,"A SteamID64 is 17 digits. Use resolve_vanity_url to convert a custom profile name.").describe("The other player's 17-digit SteamID64 to compare against.")},annotations:ye},({steamid:i,other_steamid:r})=>n(async()=>e.comparePlayers(await e.requireSteamId(i),r))),t.registerTool("get_player_summary",{title:"Get player profile",description:"Get a player's public profile by SteamID64: display name, online state, country, account age, Steam level, and the game they're currently in. Requires STEAM_API_KEY and a public profile. For VAC/game/trade ban status instead, use get_player_bans.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getPlayerSummary(i))),t.registerTool("get_player_bans",{title:"Get a player's ban status",description:"Check a player's VAC, game, community and economy (trade) ban status by SteamID64 \u2014 'is this player banned', useful before trading or adding a friend. Ban status is always public \u2014 this works even when the rest of the profile is private. Requires STEAM_API_KEY.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getPlayerBans(i))),t.registerTool("get_owned_games",{title:"Get owned games",description:"List the games a player owns with playtime (hours), most-played first (capped to the top 50 by playtime \u2014 a lightly-played or unplayed game may not appear, so this is NOT reliable for 'does X own game Y'; use find_friends_who_own for that). Requires STEAM_API_KEY and a public profile + game-details visibility. Get the SteamID64 from resolve_vanity_url.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getOwnedGames(i))),t.registerTool("get_recently_played",{title:"Get recently played games",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.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getRecentlyPlayed(i))),t.registerTool("get_player_achievements",{title:"Get a player's achievements",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.",inputSchema:{steamid:vt,appid:Rt,language:O.string().min(2).describe("Language for achievement names/descriptions; overrides STEAM_LANGUAGE.").optional()},annotations:ye},({steamid:i,appid:r,language:o})=>n(async()=>e.getPlayerAchievements(await e.requireSteamId(i),r,o)))}function Yg(t,e){return{description:t,messages:[{role:"user",content:{type:"text",text:e}}]}}function mS(t){t.registerPrompt("what_should_i_play",{title:"What should I play next?",description:"Recommend games from the Steam catalog based on a player's library and taste, excluding what they already own.",argsSchema:{steamid:O.string().describe("SteamID64 whose library to base taste on. Omit to use the configured STEAM_ID.").optional(),budget:O.string().describe("Max price, e.g. '$20' or 'free'. Omit for no limit.").optional(),tags:O.string().describe("Comma-separated tags to steer toward, e.g. 'Roguelike, Deckbuilding'. Omit to infer from the library.").optional()}},({steamid:e,budget:n,tags:i})=>Yg("Recommend games based on library/taste",`Recommend what I should play next.
79
+ `}var Zl=class{constructor(e=hk.stdin,n=hk.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Al,this._started=!1,this._ondata=i=>{this._readBuffer.append(i),this.processReadBuffer()},this._onerror=i=>{this.onerror?.(i)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let i=fk(e);this._stdout.write(i)?n():this._stdout.once("drain",n)})}};var h1=O.object({STEAM_API_KEY:O.string().min(1).optional(),STEAM_API_BASE_URL:O.string().url().default("https://api.steampowered.com"),STEAM_ID:O.string().min(2).optional(),STEAM_STORE_BASE_URL:O.string().url().default("https://store.steampowered.com"),STEAM_COUNTRY:O.string().min(2).max(2).default("US"),STEAM_LANGUAGE:O.string().min(2).default("english"),HTTP_TIMEOUT_MS:O.coerce.number().int().positive().default(15e3),HTTP_RETRIES:O.coerce.number().int().nonnegative().default(2),STEAM_STORE_MIN_INTERVAL_MS:O.coerce.number().int().nonnegative().default(250),STEAM_API_MIN_INTERVAL_MS:O.coerce.number().int().nonnegative().default(0),CACHE_TTL_MS:O.coerce.number().int().nonnegative().default(3e5),LOG_LEVEL:O.enum(["debug","info","warn","error","silent"]).default("info")}),g1=/^\$\{[^}]*\}$/;function gk(t=process.env){let e=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0&&i!==""&&!g1.test(i))),n=h1.parse(e);return{steamApiBaseUrl:n.STEAM_API_BASE_URL,steamApiKey:n.STEAM_API_KEY,defaultSteamId:n.STEAM_ID,steamStoreBaseUrl:n.STEAM_STORE_BASE_URL,country:n.STEAM_COUNTRY,language:n.STEAM_LANGUAGE,httpTimeoutMs:n.HTTP_TIMEOUT_MS,httpRetries:n.HTTP_RETRIES,storeMinIntervalMs:n.STEAM_STORE_MIN_INTERVAL_MS,apiMinIntervalMs:n.STEAM_API_MIN_INTERVAL_MS,cacheTtlMs:n.CACHE_TTL_MS,logLevel:n.LOG_LEVEL}}var xe=class extends Error{code;status;retryable;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="ApiError",this.code=e.code,this.status=e.status,this.retryable=e.retryable??!1}};function vk(t){return t===304?{code:"not_modified",retryable:!1}:t===401?{code:"unauthorized",retryable:!1}:t===403?{code:"forbidden",retryable:!1}:t===404?{code:"not_found",retryable:!1}:t===429?{code:"rate_limited",retryable:!0}:t===400||t===405||t===422?{code:"bad_request",retryable:!1}:t>=500?{code:"server_error",retryable:!0}:{code:"unknown",retryable:!1}}function Fg(t){return t.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,"Bearer ***").replace(/\b(access_token|refresh_token|client_secret|client_id|key)=([^&\s"]+)/gi,"$1=***")}var yk={debug:10,info:20,warn:30,error:40,silent:100};function _k(t,e){let n=yk[t];function i(r,o,a){if(yk[r]<n)return;let s=a.length?" "+Fg(a.map(u=>v1(u)).join(" ")):"",c=`${Fg(o)}${s}`;if(console.error(`[steam-games-mcp] ${r}: ${c}`),e)try{e(r,c)}catch{}}return{debug:(r,...o)=>i("debug",r,o),info:(r,...o)=>i("info",r,o),warn:(r,...o)=>i("warn",r,o),error:(r,...o)=>i("error",r,o)}}function v1(t){if(typeof t=="string")return t;if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}var Cl="0.8.1",bk=`steam-games-mcp/${Cl} (+https://github.com/Grinv/steam-games-mcp)`;var $k=8e3,Pi=class{#e;constructor(e){this.#e=e}async getJson(e,n={}){return this.requestJson(e,{...n,method:n.method??"GET"})}async requestJson(e,n={}){let i=this.#r(e,n.query),r=n.retries??this.#e.retries??2,o=n.timeoutMs??this.#e.timeoutMs??15e3,a=0;for(;;){this.#e.beforeRequest&&await this.#e.beforeRequest();try{return await this.#i(i,n,o)}catch(s){let c=s instanceof xe?s:xk(s);if(!c.retryable||a>=r)throw c;let u=b1(a,c);this.#e.logger.debug(`retrying ${i} after ${u}ms (attempt ${a+1}/${r}, ${c.code})`),await k1(u),a+=1}}}async#i(e,n,i){let r=new AbortController,o=setTimeout(()=>r.abort(),i),a=()=>r.abort();n.signal?.addEventListener("abort",a,{once:!0});let s;try{s=await fetch(e,{method:n.method??"GET",headers:{"User-Agent":bk,Accept:"application/json",...this.#e.defaultHeaders,...n.headers},...n.body===void 0?{}:{body:n.body},signal:r.signal})}catch(u){throw n.signal?.aborted?new xe({code:"network",message:"Request aborted by caller",cause:u}):r.signal.aborted?new xe({code:"timeout",message:`Request timed out after ${i}ms`,retryable:!0,cause:u}):xk(u)}finally{clearTimeout(o),n.signal?.removeEventListener("abort",a)}if(!s.ok)throw await y1(s);if(s.status===204)return;let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch(u){throw new xe({code:"unknown",message:"Upstream returned invalid JSON",cause:u})}}#r(e,n){let i=new URL(e.replace(/^\//,""),w1(this.#e.baseUrl));if(n)for(let[r,o]of Object.entries(n))o!==void 0&&i.searchParams.set(r,String(o));return i.toString()}};async function y1(t){let{code:e,retryable:n}=vk(t.status),i="";try{i=await t.text()}catch{}let r=_1(i)??i.slice(0,500),o=x1(t.headers.get("retry-after"));return new xe({code:e,status:t.status,retryable:n,message:`HTTP ${t.status} ${t.statusText}${r?`: ${r}`:""}`,...o===void 0?{}:{cause:{retryAfterMs:o}}})}function _1(t){if(t)try{let e=JSON.parse(t);if(e===null||typeof e!="object")return;let n=e;return typeof n.message=="string"?n.message:typeof n.error=="string"?n.error:void 0}catch{return}}function xk(t){return t instanceof xe?t:new xe({code:"network",message:t instanceof Error?`Network error: ${t.message}`:"Network error",retryable:!0,cause:t})}function b1(t,e){let n=e.cause?.retryAfterMs;if(typeof n=="number"&&n>0)return Math.min(n,$k);let i=Math.min($k,500*2**t);return i+Math.floor(i*.25*$1(t))}function $1(t){return t*2654435761%1e3/1e3}function x1(t){if(!t)return;let e=Number(t);if(Number.isFinite(e))return e*1e3;let n=Date.parse(t);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function w1(t){return t.endsWith("/")?t:t+"/"}function k1(t){return new Promise(e=>setTimeout(e,t))}var Ti=class{#e;#i;#r;#t=[];#o=Promise.resolve();#a=null;constructor(e,n=[]){this.#e=Math.max(0,e),this.#i=n,this.#r=n.reduce((i,r)=>Math.max(i,r.windowMs),0)}acquire(){let e=this.#o,n;return this.#o=new Promise(i=>{n=i}),e.then(async()=>{let i=this.#s();i>0&&await S1(i);let r=Date.now();this.#a=r,this.#c(r),n()})}#s(){let e=Date.now(),n=this.#a!==null?this.#a+this.#e:0;for(let i of this.#i){if(this.#t.length<i.limit)continue;let r=this.#t[this.#t.length-i.limit];n=Math.max(n,r+i.windowMs)}return Math.max(0,n-e)}#c(e){this.#t.push(e);let n=e-this.#r,i=0;for(;i<this.#t.length&&this.#t[i]<=n;)i+=1;i>0&&this.#t.splice(0,i)}};function S1(t){return new Promise(e=>setTimeout(e,t))}var Ei=class{#e;#i;#r=new Map;#t=new Map;constructor(e,n=500){this.#e=e,this.#i=n}get(e){let n=this.#r.get(e);if(n)return n.expires>Date.now()?n.value:void 0}getStale(e){return this.#r.get(e)?.value}set(e,n){if(!(this.#e<=0)){if(!this.#r.has(e)&&this.#r.size>=this.#i){let i=this.#r.keys().next().value;i!==void 0&&this.#r.delete(i)}this.#r.set(e,{value:n,expires:Date.now()+this.#e})}}async wrap(e,n){let i=this.get(e);return i!==void 0?i:this.#o(e,n)}async wrapStaleOnError(e,n){let i=this.get(e);if(i!==void 0)return i;try{return await this.#o(e,n)}catch(r){let o=this.getStale(e);if(o!==void 0)return o;throw r}}#o(e,n){let i=this.#t.get(e);if(i)return i;let r=n().then(o=>(this.set(e,o),o)).finally(()=>this.#t.delete(e));return this.#t.set(e,r),r}};function Vg(t){return(t??[]).map(e=>e.description??e.name).filter(e=>!!e)}function qt(t){return typeof t=="number"?Math.round(t/60*10)/10:null}function Ra(t){return t&&t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()||null}function Oa(t,e){if(typeof t!="number")return null;let n=(t/100).toFixed(2);return e?`${n} ${e}`:n}function Et(t){return t?new Date(t*1e3).toISOString().slice(0,10):null}function wk(t){return t?new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z"):null}function tr(t){return typeof t=="number"?`https://store.steampowered.com/app/${t}`:null}function Sk(t){return{currency:t.currency??null,final:t.final_formatted??null,initial:t.initial_formatted||t.final_formatted||null,discount_percent:t.discount_percent??0}}function z1(t,e){return e?{is_free:!0}:t?{is_free:!1,...Sk(t)}:null}function zk(t){return t?Object.entries(t).filter(([,e])=>e).map(([e])=>e):[]}function Ik(t){let e=Array.isArray(t.pc_requirements)?void 0:t.pc_requirements;return{appid:t.steam_appid,name:t.name,type:t.type??null,short_description:t.short_description||null,is_free:t.is_free??!1,price:z1(t.price_overview,t.is_free),release_date:t.release_date?.date||null,coming_soon:t.release_date?.coming_soon??!1,developers:t.developers??[],publishers:t.publishers??[],genres:Vg(t.genres),categories:Vg(t.categories),platforms:zk(t.platforms),metacritic:t.metacritic?.score??null,metacritic_url:t.metacritic?.url??null,recommendations:t.recommendations?.total??null,required_age:t.required_age??null,controller_support:t.controller_support??null,achievements_total:t.achievements?.total??null,achievements_highlighted:(t.achievements?.highlighted??[]).map(n=>n.name).filter(n=>!!n),supported_languages:Ra(t.supported_languages),dlc:t.dlc??[],demos:(t.demos??[]).map(n=>n.appid).filter(Boolean),content_descriptors:{ids:t.content_descriptors?.ids??[],notes:t.content_descriptors?.notes??null},base_game:t.fullgame?.appid?{appid:Number(t.fullgame.appid),name:t.fullgame.name??null}:null,drm_notice:t.drm_notice||null,account_notice:t.ext_user_account_notice||null,pc_requirements_min:Ra(e?.minimum),website:t.website||null,header_image:t.header_image||null,store_url:tr(t.steam_appid)}}function I1(t){if(!t||typeof t.final!="number")return null;let e=t.initial&&t.final&&t.initial>t.final?Math.round((1-t.final/t.initial)*100):0;return{currency:t.currency??null,final:Oa(t.final,t.currency),initial:Oa(t.initial,t.currency),discount_percent:e}}function Pk(t){return{total:t.total??t.items?.length??0,results:(t.items??[]).map(e=>({appid:e.id,name:e.name,type:e.type??null,price:I1(e.price),metascore:e.metascore||null,platforms:zk(e.platforms),store_url:tr(e.id)}))}}function Tk(t,e){let n=e.map(i=>{let r=t[String(i)],o=r?.data,a=o&&!Array.isArray(o)?o.price_overview:void 0;return r?.success?a?{appid:i,available:!0,is_free:!1,...Sk(a)}:{appid:i,available:!0,is_free:!0}:{appid:i,available:!1}});return{count:n.length,prices:n}}function Ek(t,e=5){let n=t.query_summary??{};return{summary:n.review_score_desc??null,total_reviews:n.total_reviews??null,total_positive:n.total_positive??null,total_negative:n.total_negative??null,positive_pct:n.total_reviews&&n.total_positive?Math.round(n.total_positive/n.total_reviews*100):null,reviews:(t.reviews??[]).slice(0,e).map(i=>({voted_up:i.voted_up??null,votes_up:i.votes_up??0,author_playtime_hours:qt(i.author?.playtime_forever),text:i.review?i.review.length>600?i.review.slice(0,600)+"\u2026":i.review:null}))}}function ja(t){return(t??[]).map(e=>({appid:e.id,name:e.name,discounted:e.discounted??!1,discount_percent:e.discount_percent??0,original_price:Oa(e.original_price,e.currency),final_price:Oa(e.final_price,e.currency),store_url:tr(e.id)}))}function Rk(t){return{specials:ja(t.specials?.items),top_sellers:ja(t.top_sellers?.items),new_releases:ja(t.new_releases?.items),coming_soon:ja(t.coming_soon?.items)}}function Ok(t){return{specials:ja(t.specials?.items)}}function kk(t){let e=t.recommendations_up??0,n=t.recommendations_down??0,i=e+n;return{date:Et(t.date),up:e,down:n,positive_pct:i?Math.round(e/i*100):null}}function jk(t){let e=t.results??{};return{rollup_type:e.rollup_type??null,history:(e.rollups??[]).slice(-24).map(kk),recent:(e.recent??[]).slice(-30).map(kk)}}var Ul=class{#e;#i;#r;#t;constructor(e,n){this.#r=e.country,this.#t=e.language;let i=new Ti(e.storeMinIntervalMs);this.#e=new Pi({baseUrl:e.steamStoreBaseUrl,logger:n,timeoutMs:e.httpTimeoutMs,retries:e.httpRetries,beforeRequest:()=>i.acquire()}),this.#i=new Ei(e.cacheTtlMs)}#o(e,n,i){return this.#e.getJson("api/storesearch/",{query:{term:e,l:i??this.#t,cc:n??this.#r}})}async searchGames(e,n,i){return Pk(await this.#o(e,n,i))}async resolveAppId(e,n,i){return(await this.#o(e,n,i)).items?.find(o=>typeof o.id=="number")?.id??null}async getGame(e,n,i){let r=n??this.#r,o=i??this.#t;return this.#i.wrapStaleOnError(`app:${e}:${r}:${o}`,async()=>{let s=(await this.#e.getJson("api/appdetails",{query:{appids:e,cc:r,l:o}}))[String(e)];if(!s?.success||!s.data)throw new xe({code:"not_found",message:`No Steam app with id ${e}`});return Ik(s.data)})}async getReviews(e,n,i="all",r="all"){let o=await this.#e.getJson(`appreviews/${e}`,{query:{json:1,num_per_page:n,language:i,review_type:r,purchase_type:"all"}});return Ek(o,n)}async getPrices(e,n){let i=n??this.#r,r=100,o={};for(let a=0;a<e.length;a+=r){let s=e.slice(a,a+r),c=await this.#e.getJson("api/appdetails",{query:{appids:s.join(","),cc:i,filters:"price_overview"}});Object.assign(o,c)}return Tk(o,e)}async getReviewHistogram(e){return this.#i.wrapStaleOnError(`hist:${e}:${this.#t}`,async()=>{let n=await this.#e.getJson(`appreviewhistogram/${e}`,{query:{l:this.#t}});return jk(n)})}#a(e,n){return this.#i.wrapStaleOnError(`featured:${e}:${n}`,async()=>await this.#e.getJson("api/featuredcategories",{query:{cc:e,l:n}}))}async getFeatured(e,n){return Rk(await this.#a(e??this.#r,n??this.#t))}async getSpecials(e,n){return Ok(await this.#a(e??this.#r,n??this.#t))}};var Nk=["offline","online","busy","away","snooze","looking to trade","looking to play"];function Dk(t,e){let n=t.response?.players?.[0];return n?{found:!0,steamid:n.steamid,name:n.personaname??null,real_name:n.realname||null,state:Nk[n.personastate??0]??"offline",visibility:n.communityvisibilitystate===3?"public":"private",country:n.loccountrycode||null,level:e??null,created:Et(n.timecreated),in_game:n.gameextrainfo||null,profile_url:n.profileurl??null,avatar:n.avatarfull??null}:{found:!1}}var Ak="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.";function Ml(t){return t.response?.game_count===void 0&&t.response?.games===void 0}function Zk(t,e=50){if(Ml(t))return{found:!1,reason:Ak,game_count:null,games:[]};let n=(t.response?.games??[]).slice().sort((i,r)=>(r.playtime_forever??0)-(i.playtime_forever??0));return{found:!0,game_count:t.response?.game_count??n.length,returned:Math.min(n.length,e),games:n.slice(0,e).map(i=>({appid:i.appid,name:i.name??null,playtime_hours:qt(i.playtime_forever),playtime_2weeks_hours:qt(i.playtime_2weeks)}))}}var P1="One or both profiles/game-details are private. Ask the owner(s) to set Steam \u2192 Privacy \u2192 Game details = Public.";function Ck(t,e,n=50){if(Ml(t)||Ml(e))return{found:!1,reason:P1};let i=new Map((t.response?.games??[]).map(a=>[a.appid,a])),r=new Map((e.response?.games??[]).map(a=>[a.appid,a])),o=[...i.keys()].filter(a=>typeof a=="number"&&r.has(a)).map(a=>{let s=i.get(a),c=r.get(a);return{appid:a,name:s.name??c.name??null,playtime_hours_a:qt(s.playtime_forever),playtime_hours_b:qt(c.playtime_forever)}}).sort((a,s)=>(s.playtime_hours_a??0)+(s.playtime_hours_b??0)-((a.playtime_hours_a??0)+(a.playtime_hours_b??0)));return{found:!0,shared_count:o.length,returned:Math.min(o.length,n),games:o.slice(0,n)}}function Uk(t){return Ml(t)?{found:!1,reason:Ak,total:0,games:[]}:{found:!0,total:t.response?.game_count??t.response?.games?.length??0,games:(t.response?.games??[]).map(e=>({appid:e.appid,name:e.name??null,playtime_2weeks_hours:qt(e.playtime_2weeks),playtime_hours:qt(e.playtime_forever)}))}}function Mk(t){let e=t.playerstats;if(!e?.success)return{found:!1,reason:e?.error??"No achievement stats"};let n=e.achievements??[],i=n.filter(r=>r.achieved===1);return{found:!0,game:e.gameName??null,total:n.length,unlocked:i.length,completion_pct:n.length?Math.round(i.length/n.length*100):null,achievements:n.map(r=>({name:r.name||r.apiname,achieved:r.achieved===1,unlocked_at:r.achieved===1?Et(r.unlocktime):null}))}}function Lk(t){let e=t.achievementpercentages?.achievements??[];return{count:e.length,achievements:e.map(n=>({name:n.name,percent:typeof n.percent=="string"?Number(n.percent):n.percent??null}))}}function qk(t,e){let n=new Map;for(let r of e.achievementpercentages?.achievements??[])r.name!=null&&n.set(r.name,typeof r.percent=="string"?Number(r.percent):r.percent??0);let i=t.game?.availableGameStats?.achievements??[];return{game:t.game?.gameName??null,total:i.length,achievements:i.map(r=>{let o=r.name!=null?n.get(r.name):void 0;return{api_name:r.name,name:r.displayName||r.name||null,description:r.description||null,hidden:r.hidden===1,global_unlock_pct:typeof o=="number"?Math.round(o*10)/10:null}})}}function Fk(t){return{items:(t.appnews?.newsitems??[]).map(e=>({title:e.title??null,date:Et(e.date),author:e.author||null,feed:e.feedlabel||null,excerpt:Ra(e.contents),url:e.url??null}))}}function Vk(t){let e=t.response;return e?.success===1&&e.steamid?{found:!0,steamid:e.steamid}:{found:!1,reason:e?.message??"No match for that vanity name"}}function Gk(t,e){return{appid:e,player_count:t.response?.player_count??null}}function Jk(t,e=100){let n=t.response?.items??[];if(n.length===0)return{found:!1,reason:"Empty wishlist, or the profile/wishlist is private.",total:0,items:[]};let i=n.toSorted((r,o)=>(r.priority??1e9)-(o.priority??1e9));return{found:!0,total:n.length,returned:Math.min(n.length,e),items:i.slice(0,e).map(r=>({appid:r.appid,store_url:tr(r.appid),priority:r.priority??null,added:Et(r.date_added)}))}}function Hk(t){let e=t.players?.[0];return e?{found:!0,steamid:e.SteamId,vac_banned:e.VACBanned??!1,vac_ban_count:e.NumberOfVACBans??0,game_ban_count:e.NumberOfGameBans??0,community_banned:e.CommunityBanned??!1,economy_ban:e.EconomyBan&&e.EconomyBan!=="none"?e.EconomyBan:null,days_since_last_ban:e.DaysSinceLastBan??null}:{found:!1}}var T1=200;function Kk(t,e,n=T1){let i=t.response?.appids??[];return i.length===0?{found:!1,reason:"No followed games, or the profile is private.",total:0,games:[]}:{found:!0,total:e.response?.followed_game_count??i.length,returned:Math.min(i.length,n),games:i.slice(0,n).map(r=>({appid:r,store_url:tr(r)}))}}function Bk(t,e,n=100){let i=t.friendslist?.friends??[];if(i.length===0)return{found:!0,total:0,returned:0,friends:[]};let r=new Map;for(let a of e.response?.players??[])a.steamid&&r.set(a.steamid,a);let o=i.toSorted((a,s)=>(s.friend_since??0)-(a.friend_since??0));return{found:!0,total:i.length,returned:Math.min(i.length,n),friends:o.slice(0,n).map(a=>{let s=a.steamid?r.get(a.steamid):void 0;return{steamid:a.steamid,name:s?.personaname??null,state:Nk[s?.personastate??0]??"offline",in_game:s?.gameextrainfo||null,profile_url:s?.profileurl??null,friends_since:Et(a.friend_since)}})}}function Gg(t,e,n,i){let r=new Map;for(let c of i.response?.players??[])c.steamid&&r.set(c.steamid,c);let o=c=>({steamid:c,name:r.get(c)?.personaname??null}),a=new Map(t.map(c=>[c,[]])),s=[];return e.forEach((c,u)=>{let l=n[u];if(!l){s.push(o(c));return}for(let d of t)l.has(d)&&a.get(d).push({...o(c),playtime_hours:qt(l.get(d))})}),{found:!0,total_friends:e.length,matches:t.map(c=>({appid:c,owners:a.get(c)??[]})),private_friends:s}}function Xk(t){let e={};for(let n of t.response?.tags??[])typeof n.tagid=="number"&&n.name&&(e[n.tagid]=n.name);return e}var E1=8;function R1(t,e){return!t||!e?[]:t.slice().sort((n,i)=>(i.weight??0)-(n.weight??0)).map(n=>n.tagid!==void 0?e[n.tagid]:void 0).filter(n=>!!n).slice(0,E1)}function O1(t,e,n){let i=new Set((t??[]).map(r=>r.tagid!==void 0?e?.[r.tagid]:void 0).filter(r=>!!r).map(r=>r.toLowerCase()));return n.every(r=>i.has(r))}var j1={0:"unknown",1:"unsupported",2:"playable",3:"verified"};function Ll(t){return j1[t??0]??"unknown"}var N1={verified:3,playable:2},D1={windows:"windows",mac:"mac",linux:"steamos_linux"};function A1(t){if(!t)return[];let e=[];return t.windows&&e.push("windows"),t.mac&&e.push("mac"),t.steamos_linux&&e.push("linux"),e}function Z1(t){let e=(t?.active_discounts??[]).map(n=>n.discount_end_date).filter(n=>typeof n=="number"&&n>0);return e.length?wk(Math.min(...e)):null}function Yk(t){return{discount_pct:t?.discount_pct??0,discount_end:Z1(t),final:t?.formatted_final_price||null,original:t?.formatted_original_price||t?.formatted_final_price||null}}function Qk(t,e){let n=t.reviews?.summary_filtered;return{appid:t.appid,name:t.name??null,store_url:tr(t.appid),review_percent:n?.percent_positive??null,review_count:n?.review_count??null,review_label:n?.review_score_label??null,platforms:A1(t.platforms),steam_deck:Ll(t.platforms?.steam_deck_compat_category),steam_os:Ll(t.platforms?.steam_os_compat_category),steam_machine:Ll(t.platforms?.steam_machine_compat_category),steam_frame:Ll(t.platforms?.steam_frame_compat_category),tags:R1(t.tags,e),release_date:Et(t.release?.steam_release_date)}}function eS(t,e){let{final:n,...i}=Yk(t.best_purchase_option);return{...Qk(t,e),...i,price:n}}var C1=[["steamDeck","steam_deck_compat_category"],["steamOs","steam_os_compat_category"],["steamMachine","steam_machine_compat_category"],["steamFrame","steam_frame_compat_category"]];function tS(t){let e=C1.map(([r,o])=>{let a=t[r];return[o,a?N1[a]:void 0]}),n=t.platform?D1[t.platform]:void 0,i=t.tags?.length?t.tags.map(r=>r.toLowerCase()):void 0;return r=>{let o=r.platforms;for(let[c,u]of e)if(u!==void 0&&(o?.[c]??0)<u)return!1;if(n&&!o?.[n]||t.releasedAfter!==void 0&&(r.release?.steam_release_date??0)<t.releasedAfter||i&&!O1(r.tags,t.tagMap,i))return!1;let a=r.reviews?.summary_filtered;if(typeof t.minReview=="number"&&(a?.percent_positive??-1)<t.minReview||typeof t.minReviews=="number"&&(a?.review_count??0)<t.minReviews)return!1;let s=r.best_purchase_option?.discount_pct??0;if(typeof t.minDiscount=="number"){if(s<t.minDiscount)return!1}else if(t.onSaleOnly&&s<=0)return!1;return!0}}function rS(t,e){let n=tS(e),i=(t.response?.store_items??[]).filter(r=>r.visible!==!1&&typeof r.appid=="number"&&n(r)).map(r=>eS(r,e.tagMap)).sort((r,o)=>o.discount_pct-r.discount_pct);return{total_matching:t.response?.metadata?.total_matching_records??null,returned:i.length,deals:i}}function nS(t,e,n){let i=new Map;for(let r of t.response?.store_items??[])typeof r.appid=="number"&&i.set(r.appid,r);return{count:e.length,items:e.map(r=>{let o=i.get(r);if(!o||!o.name&&!o.best_purchase_option&&!o.reviews)return{appid:r,available:!1};let a=o.best_purchase_option;return{...Qk(o,n),is_free:o.is_free??!1,price:a?Yk(a):o.is_free?{is_free:!0}:null,coming_soon:o.release?.is_coming_soon??!1}})}}var Wk=60;function iS(t,e,n={}){let i=t.response?.items??[];if(i.length===0)return{found:!1,reason:"Empty wishlist, or the profile/wishlist is private.",total:0,items:[]};let r=i.filter(c=>c.store_item),o=tS({...n,tagMap:e}),a=r.filter(c=>typeof c.appid=="number"&&o(c.store_item)).map(c=>({...eS(c.store_item,e),priority:c.priority??null,added:Et(c.date_added)})),s=n.onSaleOnly||typeof n.minDiscount=="number";return a.sort((c,u)=>s?u.discount_pct-c.discount_pct:(c.priority??1e9)-(u.priority??1e9)),{found:!0,total:i.length,enriched:r.length,note:r.length<i.length?`Steam only returned store data for ${r.length} of ${i.length} wishlist items; filters/matches only cover those ${r.length} \u2014 the rest have no price, reviews or tags to check.`:void 0,matched:a.length,returned:Math.min(a.length,Wk),items:a.slice(0,Wk)}}var Jg=t=>({include_basic_info:!0,include_reviews:!0,include_release:!0,include_platforms:!0,include_tag_count:t}),ql=class{#e;#i;#r;#t;constructor(e){this.#e=e.get,this.#i=e.cache,this.#r=e.language,this.#t=e.country}async#o(e){try{return await this.#i.wrapStaleOnError(`tags:${e}`,async()=>{let i=await this.#e("IStoreService/GetTagList/v1/",{language:e});return Xk(i)})}catch{return null}}#a(e,n){if(n!==null)return n;if(e?.length)throw new xe({code:"unknown",message:"could not fetch Steam's tag dictionary right now, so the `tags` filter can't be reliably applied. Retry, or drop `tags` to see unfiltered results.",retryable:!0})}async#s(e,n,i,r){let[o,a]=await Promise.all([this.#e(e,n),this.#o(i)]);return{res:o,tagMap:this.#a(r,a)}}async getItems(e,n,i){let r=i??this.#r,o={ids:e.map(c=>({appid:c})),context:{language:r,country_code:n??this.#t},data_request:Jg(15)},{res:a,tagMap:s}=await this.#s("IStoreBrowseService/GetItems/v1/",{input_json:JSON.stringify(o)},r);return nS(a,e,s)}async#c(e){let n=e.language??this.#r,i={};typeof e.minDiscount=="number"&&(i.price_filters={min_discount_percent:e.minDiscount}),e.releasedOnly&&(i.released_only=!0);let r={query:{start:e.start??0,count:e.count??50,sort:10,filters:i},context:{language:n,country_code:e.country??this.#t,steam_realm:1},data_request:Jg(20)},{res:o,tagMap:a}=await this.#s("IStoreQueryService/Query/v1/",{input_json:JSON.stringify(r)},n,e.tags);return rS(o,{minReview:e.minReview,minReviews:e.minReviews,steamDeck:e.steamDeck,steamOs:e.steamOs,steamMachine:e.steamMachine,steamFrame:e.steamFrame,platform:e.platform,releasedAfter:e.releasedAfter,tags:e.tags,tagMap:a})}async discoverGames(e){return this.#c({...e,releasedOnly:e.releasedAfter!==void 0})}async getWishlistDetailed(e,n={}){let i=n.language??this.#r,r={steamid:e,context:{language:i,country_code:n.country??this.#t,steam_realm:1},data_request:Jg(20),sort:0},{res:o,tagMap:a}=await this.#s("IWishlistService/GetWishlistSortedFiltered/v1/",{input_json:JSON.stringify(r)},i,n.tags);return iS(o,a,{onSaleOnly:n.onSaleOnly,tags:n.tags,minReview:n.minReview,minDiscount:n.minDiscount,platform:n.platform,steamDeck:n.steamDeck,steamOs:n.steamOs,steamMachine:n.steamMachine,steamFrame:n.steamFrame})}};var oS="Profile or game-details are private. Ask the owner to set Steam \u2192 Privacy \u2192 Game details = Public.",aS="Profile or friends list is private. Ask the owner to set Steam \u2192 Privacy \u2192 Friends List = Public.";function sS(t){return(t.friendslist?.friends??[]).map(e=>e.steamid).filter(e=>!!e)}var Fl=class{#e;#i;#r;#t;#o;#a;#s;#c;configured;constructor(e,n){this.#r=e.steamApiKey,this.#t=e.language,this.#o=e.country,this.#a=e.defaultSteamId,this.configured=!!e.steamApiKey;let i=new Ti(e.apiMinIntervalMs);this.#e=new Pi({baseUrl:e.steamApiBaseUrl,logger:n,timeoutMs:e.httpTimeoutMs,retries:e.httpRetries,beforeRequest:()=>i.acquire()}),this.#i=new Ei(e.cacheTtlMs),this.#s=new ql({get:this.#n.bind(this),cache:this.#i,language:this.#t,country:this.#o})}#n(e,n){return this.#e.getJson(e,{query:{key:this.#r,...n}})}async requireSteamId(e){if(e)return e;let n=this.#a;if(!n)throw new xe({code:"bad_request",message:"no steamid was given and STEAM_ID is not set. Pass a 17-digit SteamID64, or set STEAM_ID (a SteamID64 or vanity name) in the server config."});if(/^\d{17}$/.test(n))return n;if(this.#c)return this.#c;if(!this.configured)throw new xe({code:"bad_request",message:`STEAM_ID is a vanity name ("${n}") which needs a Steam Web API key to resolve. Set STEAM_API_KEY, or set STEAM_ID to a 17-digit SteamID64 instead.`});let i=await this.#n("ISteamUser/ResolveVanityURL/v1/",{vanityurl:n}),r=i.response?.steamid;if(i.response?.success!==1||!r)throw new xe({code:"bad_request",message:`could not resolve the STEAM_ID vanity name "${n}" to a SteamID64.`});return this.#c=r,r}async getPlayerSummary(e){let[n,i]=await Promise.all([this.#n("ISteamUser/GetPlayerSummaries/v2/",{steamids:e}),this.#m(e)]);return Dk(n,i)}async#m(e){try{return(await this.#i.wrapStaleOnError(`level:${e}`,async()=>({level:(await this.#n("IPlayerService/GetSteamLevel/v1/",{steamid:e})).response?.player_level??null}))).level}catch{return null}}async getPlayerBans(e){let n=await this.#n("ISteamUser/GetPlayerBans/v1/",{steamids:e});return Hk(n)}async getOwnedGames(e){let n=await this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:e,include_appinfo:!0,include_played_free_games:!0});return Zk(n)}async getRecentlyPlayed(e){let n=await this.#n("IPlayerService/GetRecentlyPlayedGames/v1/",{steamid:e});return Uk(n)}async comparePlayers(e,n){let[i,r]=await Promise.all([this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:e,include_appinfo:!0}),this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:n,include_appinfo:!0})]);return Ck(i,r)}async getPlayerAchievements(e,n,i){let r=i??this.#t;try{let o=await this.#n("ISteamUserStats/GetPlayerAchievements/v1/",{steamid:e,appid:n,l:r});return o.playerstats?.success?Mk(o):this.#u(n,r,o.playerstats?.error)}catch(o){if(o instanceof xe&&(o.code==="forbidden"||o.code==="unauthorized"))return{found:!1,reason:oS};if(o instanceof xe&&(o.code==="bad_request"||o.code==="not_found"))return this.#u(n,r);throw o}}async#u(e,n,i){if(i&&/not public|private/i.test(i))return{found:!1,reason:oS};try{return{found:!1,reason:((await this.#n("ISteamUserStats/GetSchemaForGame/v2/",{appid:e,l:n})).game?.availableGameStats?.achievements?.length??0)>0?"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."}}catch{return{found:!1,reason:i||"Achievements unavailable."}}}async resolveVanityUrl(e){let n=await this.#n("ISteamUser/ResolveVanityURL/v1/",{vanityurl:e});return Vk(n)}async#l(e){if(e.length===0)return{};let n=[];for(let r=0;r<e.length;r+=100)n.push(e.slice(r,r+100));return{response:{players:(await Promise.all(n.map(r=>this.#n("ISteamUser/GetPlayerSummaries/v2/",{steamids:r.join(",")})))).flatMap(r=>r.response?.players??[])}}}async#d(e){try{return await this.#n("ISteamUser/GetFriendList/v1/",{steamid:e,relationship:"friend"})}catch(n){if(n instanceof xe&&(n.code==="forbidden"||n.code==="unauthorized"))return null;throw n}}async getFriendList(e){let n=await this.#d(e);return n===null?{found:!1,reason:aS}:Bk(n,await this.#l(sS(n)))}async findFriendsWhoOwn(e,n){let i=await this.#d(e);if(i===null)return{found:!1,reason:aS};let r=sS(i);if(r.length===0)return Gg(n,[],[],{});let[o,a]=await Promise.all([this.#l(r),Promise.all(r.map(s=>this.#p(s,n)))]);return Gg(n,r,a,o)}async#p(e,n){let i=await this.#n("IPlayerService/GetOwnedGames/v1/",{steamid:e,include_appinfo:!1});if(i.response?.games===void 0&&i.response?.game_count===void 0)return null;let r=new Set(n),o=new Map;for(let a of i.response?.games??[])typeof a.appid=="number"&&r.has(a.appid)&&o.set(a.appid,a.playtime_forever??0);return o}async getNews(e,n){let i=await this.#n("ISteamNews/GetNewsForApp/v2/",{appid:e,count:n,maxlength:400});return Fk(i)}async getGlobalAchievements(e){return this.#i.wrapStaleOnError(`global-ach:${e}`,async()=>{let n=await this.#n("ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/",{gameid:e});return Lk(n)})}async getCurrentPlayers(e){let n=await this.#n("ISteamUserStats/GetNumberOfCurrentPlayers/v1/",{appid:e});return Gk(n,e)}get store(){return this.#s}async#f(e){let n=await this.#n("IWishlistService/GetWishlist/v1/",{steamid:e});return Jk(n)}async getFollowedGames(e){let[n,i]=await Promise.all([this.#n("IStoreService/GetGamesFollowed/v1/",{steamid:e}),this.#h(e)]);return Kk(n,i)}async#h(e){try{return await this.#n("IStoreService/GetGamesFollowedCount/v1/",{steamid:e})}catch{return{}}}#g(e,n){return this.#s.getWishlistDetailed(e,n)}async getWishlist(e,n={}){let{includeDetails:i,onSaleOnly:r,...o}=n;return i||r||Object.values(o).some(s=>s!==void 0)?this.#g(e,{onSaleOnly:r,...o}):this.#f(e)}async getGameAchievements(e,n){let i=n??this.#t;return this.#i.wrapStaleOnError(`schema:${e}:${i}`,async()=>{let[r,o]=await Promise.all([this.#n("ISteamUserStats/GetSchemaForGame/v2/",{appid:e,l:i}),this.#n("ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/",{gameid:e})]);return qk(r,o)})}};function Vl(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}function jr(t){return{content:[{type:"text",text:t}],isError:!0}}function cS(t){return jr(U1(t))}function U1(t){switch(t.code){case"unauthorized":return"The upstream service rejected the credentials (401). They may be missing or expired \u2014 check the configured API key / token.";case"forbidden":return"The upstream service denied access (403). The credentials may lack permission.";case"not_found":return"No matching resource was found (404).";case"not_modified":return"The content has not changed since the last request (304).";case"rate_limited":return"Upstream rate limit hit (429). Please retry in a few seconds.";case"server_error":return"The upstream service returned an error (5xx). Please retry later.";case"network":return"Could not reach the upstream service (network error). Check connectivity and retry.";case"timeout":return"The upstream request timed out. Please retry.";case"bad_request":return`The request was rejected as invalid: ${t.message}`;default:return`Unexpected error talking to the upstream service: ${t.message}`}}async function Gl(t){try{return await t()}catch(e){return e instanceof xe?cS(e):jr(`Unexpected error: ${e instanceof Error?e.message:String(e)}`)}}var ye={readOnlyHint:!0,openWorldHint:!0},Rt=O.number().int().positive().describe("Steam application id (appid). Get it from search_games."),Ft=O.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(),rr=O.string().min(2).describe("Store language (e.g. english, russian); overrides STEAM_LANGUAGE for this call.").optional(),Hg=O.enum(["windows","mac","linux"]).describe("NATIVE-build filter: keep only games shipping a native build for this OS (windows/mac/linux). 'linux' = a native Linux/SteamOS port. This is NOT Proton \u2014 for games that run via Proton compatibility use steam_os / steam_deck instead. Each result's `platforms` field lists its native builds, while steam_os/steam_deck report Proton compatibility, so native vs Proton stay distinct.").optional(),Kg=O.enum(["playable","verified"]).describe("Steam Deck compatibility (runs via Proton): 'verified' = Deck-Verified only; 'playable' = Playable or Verified. Not a native Linux build \u2014 see `platform` for that.").optional(),Bg=O.enum(["playable","verified"]).describe("SteamOS compatibility \u2014 how well it runs on SteamOS in general (via Proton): 'verified' = SteamOS-Verified only; 'playable' = Playable or Verified. For a NATIVE Linux build instead, use platform:'linux'; for the Steam Machine console specifically, use steam_machine.").optional(),Wg=O.enum(["playable","verified"]).describe("Steam Machine (Valve's console) compatibility (via Proton): 'verified' = Steam-Machine-Verified only; 'playable' = Playable or Verified. Its own rating, distinct from the general steam_os one.").optional(),Xg=O.enum(["playable","verified"]).describe("Steam Frame (VR headset) compatibility: 'verified' = Frame-Verified only; 'playable' = Playable or Verified.").optional(),De=t=>Gl(async()=>Vl(await t()));function uS(t,e){t.registerTool("search_games",{title:"Search games",description:"Search the Steam store by title \u2014 term can be partial or approximate, not an exact match; returns matches with their appid (needed by the other game tools), price, Metacritic score and platforms. No API key required.",inputSchema:{term:O.string().min(1).describe("Game title to search for."),country:Ft,language:rr},annotations:ye},({term:n,country:i,language:r})=>De(()=>e.searchGames(n,i,r))),t.registerTool("get_game",{title:"Get game details",description:"Get full store details for one game: description, price/discount, genres, platforms, release date, developers/publishers, Metacritic, age rating, DLC and PC requirements. Identify the game by appid (from search_games) OR by name \u2014 a title is resolved to the closest store match. No API key required.",inputSchema:{appid:Rt.describe("Steam appid (from search_games). Provide appid OR name.").optional(),name:O.string().min(1).describe("Game title to look up instead of an appid \u2014 resolved to the closest store match. Provide appid OR name; appid wins if both are given.").optional(),country:Ft,language:rr},annotations:ye},({appid:n,name:i,country:r,language:o})=>Gl(async()=>{let a=n;if(!a){if(!i)return jr("Provide either appid or name.");let s=await e.resolveAppId(i,r,o);if(!s)return jr(`No Steam game found matching "${i}".`);a=s}return Vl(await e.getGame(a,r,o))})),t.registerTool("get_game_reviews",{title:"Get game reviews",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.",inputSchema:{appid:Rt,limit:O.number().int().min(1).max(20).describe("How many recent reviews (1-20).").optional(),review_language:O.string().describe("Filter reviews by language, e.g. 'english'. Default 'all'.").optional(),type:O.enum(["all","positive","negative"]).describe("Only positive or negative reviews. Default 'all'.").optional()},annotations:ye},({appid:n,limit:i,review_language:r,type:o})=>De(()=>e.getReviews(n,i??5,r??"all",o??"all"))),t.registerTool("get_review_histogram",{title:"Get review trend over time",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.",inputSchema:{appid:Rt},annotations:ye},({appid:n})=>De(()=>e.getReviewHistogram(n))),t.registerTool("get_prices",{title:"Get prices for many games",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. Handles up to 500 appids; if you also need review %, hardware compatibility or tags, use get_items instead (max 100 appids). Rows come back in the same order as the given appids, one per id (unavailable ones marked available:false, never dropped). 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.",inputSchema:{appids:O.array(O.number().int().positive()).min(1).max(500).describe("Steam appids to price (1-500)."),country:Ft},annotations:ye},({appids:n,country:i})=>De(()=>e.getPrices(n,i))),t.registerTool("get_specials",{title:"Get current discounts",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_games with min_discount. No API key required.",inputSchema:{country:Ft,language:rr},annotations:ye},({country:n,language:i})=>De(()=>e.getSpecials(n,i))),t.registerTool("get_featured",{title:"Get featured store sections",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), all in one call \u2014 for a general 'what's on the store front page' overview. For just current discounts use get_specials (lighter), or discover_games for catalog-wide deals with filters. No API key required.",inputSchema:{country:Ft,language:rr},annotations:ye},({country:n,language:i})=>De(()=>e.getFeatured(n,i)))}var vt=O.string().regex(/^\d{17}$/,"A SteamID64 is 17 digits. Use resolve_vanity_url to convert a custom profile name.").describe("17-digit SteamID64. Omit to use the STEAM_ID configured on the server. Convert a vanity/custom URL name with resolve_vanity_url first.").optional(),Nr=(t,e,n)=>({steamid:i})=>e(async()=>n(await t.requireSteamId(i)));function lS(t,e,n){t.registerTool("get_game_news",{title:"Get game news",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.",inputSchema:{appid:Rt,limit:O.number().int().min(1).max(20).describe("How many news items (1-20).").optional()},annotations:ye},({appid:i,limit:r})=>De(()=>e.getNews(i,r??5))),t.registerTool("get_global_achievements",{title:"Get global achievement rates",description:"Get the global unlock percentage of each achievement in a game by appid \u2014 how rare each achievement is across all players. Returns each achievement's internal name and its unlock percent (no display names/descriptions \u2014 for those, use get_game_achievements). Get the appid from search_games. Works without a key.",inputSchema:{appid:Rt},annotations:ye},({appid:i})=>De(()=>e.getGlobalAchievements(i))),t.registerTool("get_items",{title:"Batch store card for many games",description:"Get price/discount, review % (positive), hardware compatibility, popular user tags and release date for a LIST of games by appid in ONE keyless call. The efficient way to price-, rating-, tag- and compat-check a wishlist or library without a request per game. For a bigger batch (up to 500 appids) when you only need price, use get_prices instead. Each item carries four compatibility fields, each verified/playable/unsupported/unknown: steam_deck (Steam Deck), steam_os (SteamOS in general), steam_machine (the Steam Machine console specifically), and steam_frame (Steam Frame VR headset); a `tags` list (top user tags like 'Roguelike', 'Souls-like', most-relevant first); a clickable `store_url` to the game's Steam page; and, when on sale, `discount_end` (ISO UTC time the discount expires \u2014 for 'how long is this deal valid'). Get appids from search_games / get_wishlist / get_owned_games.",inputSchema:{appids:O.array(O.number().int().positive()).min(1).max(100).describe("Steam appids (1-100)."),country:Ft,language:rr},annotations:ye},({appids:i,country:r,language:o})=>De(()=>n.getItems(i,r,o))),t.registerTool("discover_games",{title:"Discover games (deals, new releases, Steam Deck, rating)",description:"Find games across the whole Steam catalog (keyless), filtered by ANY combination of: discount (min_discount \u2014 for 'what's on sale'), release recency (released_after / released_within_days \u2014 for 'new games'), hardware compatibility (steam_deck for Steam Deck, steam_os for SteamOS in general, steam_machine for the Steam Machine console specifically, steam_frame for the Steam Frame VR headset), native OS build (platform \u2014 windows/mac/linux), review quality (min_review / min_reviews), and user tags (tags \u2014 e.g. ['Roguelike', 'Deckbuilding'] for 'games like X'). Each result returns price/discount, review %, all four compat statuses, popular tags, a clickable store_url, discount_end (when a deal expires) and release date in one call. Examples: '>80% off with 90%+ reviews' \u2192 set min_discount + min_review; 'recent well-reviewed games that run on Steam Deck' \u2192 set released_within_days + steam_deck + min_review; 'roguelike deckbuilders on sale' \u2192 tags:['Roguelike','Deckbuilding'] + min_discount; 'games that run on the Steam Machine' \u2192 steam_machine; 'games that run on SteamOS' \u2192 steam_os. No appids needed \u2014 unlike get_items, which prices a list you already have. Note: the Steam catalog API has no release-date/tag sort or filter, so results are scanned popularity-first and the recency, compat and tag filters are applied over that window \u2014 great for popular titles; a niche match may fall outside the top `count` (raise count for stricter filters).",inputSchema:{released_after:O.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Use an ISO date, e.g. 2026-03-01.").describe("Keep only games released on/after this date (YYYY-MM-DD).").optional(),released_within_days:O.number().int().min(1).describe("Alternative to released_after: released within the last N days.").optional(),steam_deck:Kg,steam_os:Bg,steam_machine:Wg,steam_frame:Xg,platform:Hg,tags:O.array(O.string().min(1)).min(1).describe("Keep only games carrying ALL of these user tags (case-insensitive), e.g. ['Roguelike','Deckbuilding']. Use exact Steam tag names. Applied over the scanned popularity window, so raise `count` when combining niche tags.").optional(),min_review:O.number().int().min(0).max(100).describe("Minimum positive-review %, e.g. 85. Applied over the returned page.").optional(),min_reviews:O.number().int().min(0).describe("Minimum review count (filters out games with too few reviews).").optional(),min_discount:O.number().int().min(1).max(100).describe("Minimum discount %, e.g. 80 for '80%+ off' \u2014 this is the 'deals' filter. Omit to include full-price games.").optional(),count:O.number().int().min(1).max(200).describe("How many catalog entries to scan (default 50). Raise for stricter filters.").optional(),start:O.number().int().min(0).describe("Pagination offset into the catalog.").optional(),country:Ft,language:rr},annotations:ye},({released_after:i,released_within_days:r,steam_deck:o,steam_os:a,steam_machine:s,steam_frame:c,platform:u,tags:l,min_review:d,min_reviews:m,min_discount:p,count:h,start:y,country:_,language:z})=>{let U;return i?U=Math.floor(Date.parse(i)/1e3):r&&(U=Math.floor(Date.now()/1e3)-r*86400),De(()=>n.discoverGames({releasedAfter:U,steamDeck:o,steamOs:a,steamMachine:s,steamFrame:c,platform:u,tags:l,minReview:d,minReviews:m,minDiscount:p,count:h,start:y,country:_,language:z}))}),t.registerTool("get_current_players",{title:"Get current player count",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.",inputSchema:{appid:Rt},annotations:ye},({appid:i})=>De(()=>e.getCurrentPlayers(i))),t.registerTool("get_followed_games",{title:"Get a player's followed games",description:"List the games a player 'follows' on the Steam store, by SteamID64 \u2014 a lighter opt-in (get sale/update notifications) that's separate from the wishlist; many players follow more games than they wishlist. Works without a key, but only if that player's follows/profile are public \u2014 otherwise it returns found:false. Returns appids + store_url only (no price/name); pass the appids to get_items for price, review % and compat. Convert a vanity name with resolve_vanity_url first.",inputSchema:{steamid:vt},annotations:ye},Nr(e,De,i=>e.getFollowedGames(i))),t.registerTool("get_wishlist",{title:"Get a player's wishlist",description:"List a player's Steam wishlist by SteamID64. Works without a key, but only if that player's wishlist/profile is public \u2014 otherwise it returns found:false. By default returns a light list of appids (sorted by priority, no names). Set include_details for full store cards in ONE call (name, price/discount, review %, Deck/SteamOS/Machine/Frame compat, tags, release) \u2014 no need to follow up with get_items. Narrow it in the SAME call with tags (e.g. ['Metroidvania']), platform (NATIVE windows/mac/linux build), steam_deck / steam_os / steam_machine / steam_frame (Proton compatibility \u2014 distinct from a native build), min_review and min_discount / on_sale_only, or country / language (the light appid list carries no price, so setting either implies include_details too) \u2014 these are applied before the output cap, so a deeply-discounted niche match past the display cap is never hidden by it (e.g. 'top metroidvanias on my wishlist with a good discount and reviews' \u2192 tags:['Metroidvania'] + min_discount + min_review). Results ranked by discount when a discount filter is set, else by wishlist priority; `matched` reports the pre-cap count. Steam itself only attaches store data to roughly the first 100 wishlist entries per call \u2014 on a bigger wishlist, `enriched` reports how many of `total` got checked, and `note` explains when some were skipped (their filter/price data isn't available at all, not that they don't match). Convert a vanity name with resolve_vanity_url first.",inputSchema:{steamid:vt,include_details:O.boolean().describe("Return full store cards (name, price, discount, reviews, compatibility, tags) per item in one call, instead of just appids. Implied by any filter below.").optional(),on_sale_only:O.boolean().describe("Only wishlist items currently discounted, ranked by discount %. Implies include_details.").optional(),tags:O.array(O.string().min(1)).min(1).describe("Keep only wishlist items carrying ALL of these user tags (case-insensitive), e.g. ['Metroidvania']. Implies include_details.").optional(),min_review:O.number().int().min(0).max(100).describe("Keep only items with at least this positive-review %. Implies include_details.").optional(),min_discount:O.number().int().min(1).max(100).describe("Keep only items discounted at least this %, ranked by discount. Implies include_details.").optional(),platform:Hg,steam_deck:Kg,steam_os:Bg,steam_machine:Wg,steam_frame:Xg,country:Ft.describe("Country (cc) for prices; overrides STEAM_COUNTRY. Only meaningful for store cards, so setting it implies include_details \u2014 the light appid list carries no price."),language:rr.describe("Store language; overrides STEAM_LANGUAGE. Only meaningful for store cards, so setting it implies include_details \u2014 the light appid list carries no price.")},annotations:ye},({steamid:i,include_details:r,on_sale_only:o,tags:a,min_review:s,min_discount:c,platform:u,steam_deck:l,steam_os:d,steam_machine:m,steam_frame:p,country:h,language:y})=>De(async()=>{let _=await e.requireSteamId(i);return e.getWishlist(_,{includeDetails:r,onSaleOnly:o,tags:a,minReview:s,minDiscount:c,platform:u,steamDeck:l,steamOs:d,steamMachine:m,steamFrame:p,country:h,language:y})}))}function dS(t,e){let n=i=>e.configured?De(i):Promise.resolve(jr("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.)"));t.registerTool("get_game_achievements",{title:"Get a game's full achievement list",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.",inputSchema:{appid:Rt,language:O.string().min(2).describe("Language for achievement names/descriptions; overrides STEAM_LANGUAGE.").optional()},annotations:ye},({appid:i,language:r})=>n(()=>e.getGameAchievements(i,r))),t.registerTool("resolve_vanity_url",{title:"Resolve vanity URL to SteamID",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.",inputSchema:{vanity:O.string().min(1).describe("Vanity name, e.g. 'gabelogannewell' from steamcommunity.com/id/gabelogannewell.")},annotations:ye},({vanity:i})=>n(()=>e.resolveVanityUrl(i))),t.registerTool("get_friend_list",{title:"Get a player's friend list",description:"List a player's Steam friends by SteamID64: name, online state, current game and how long they've been friends, most-recently-added first. Requires STEAM_API_KEY and the friends list to be public. For 'which of my friends own game X', use find_friends_who_own instead \u2014 it checks each friend's full library, not just this list. Get the SteamID64 from resolve_vanity_url.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getFriendList(i))),t.registerTool("find_friends_who_own",{title:"Find friends who own a game",description:"Check which of a player's Steam friends own one or more games by appid, with each owner's playtime_hours \u2014 'which of my friends have Portal 2 and how long have they played'. Checks each friend's FULL library, unlike get_owned_games / get_friend_list which cap at the top 50 games by playtime \u2014 so a friend's rarely-played or unplayed copy is never missed (its playtime_hours may still be low or 0). Requires STEAM_API_KEY and the player's friends list to be public; friends with a private library are listed separately in private_friends (can't be checked) rather than silently counted as non-owners. Get appids from search_games.",inputSchema:{appids:O.array(O.number().int().positive()).min(1).max(10).describe("Steam appids to check (1-10)."),steamid:vt},annotations:ye},({appids:i,steamid:r})=>n(async()=>e.findFriendsWhoOwn(await e.requireSteamId(r),i))),t.registerTool("compare_players",{title:"Compare two players' libraries",description:"Find games two players both own, with each one's playtime \u2014 'what can my friend and I both play', 'do we have anything in common'. Checks each player's FULL library, unlike get_owned_games which caps at the top 50 by playtime. Requires STEAM_API_KEY and both profiles' game-details to be public. Omit steamid to compare against yourself (STEAM_ID).",inputSchema:{steamid:vt,other_steamid:O.string().regex(/^\d{17}$/,"A SteamID64 is 17 digits. Use resolve_vanity_url to convert a custom profile name.").describe("The other player's 17-digit SteamID64 to compare against.")},annotations:ye},({steamid:i,other_steamid:r})=>n(async()=>e.comparePlayers(await e.requireSteamId(i),r))),t.registerTool("get_player_summary",{title:"Get player profile",description:"Get a player's public profile by SteamID64: display name, online state, country, account age, Steam level, and the game they're currently in. Requires STEAM_API_KEY and a public profile. For VAC/game/trade ban status instead, use get_player_bans.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getPlayerSummary(i))),t.registerTool("get_player_bans",{title:"Get a player's ban status",description:"Check a player's VAC, game, community and economy (trade) ban status by SteamID64 \u2014 'is this player banned', useful before trading or adding a friend. Ban status is always public \u2014 this works even when the rest of the profile is private. Requires STEAM_API_KEY.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getPlayerBans(i))),t.registerTool("get_owned_games",{title:"Get owned games",description:"List the games a player owns with playtime (hours), most-played first (capped to the top 50 by playtime \u2014 a lightly-played or unplayed game may not appear, so this is NOT reliable for 'does X own game Y'; use find_friends_who_own for that). Requires STEAM_API_KEY and a public profile + game-details visibility. Get the SteamID64 from resolve_vanity_url.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getOwnedGames(i))),t.registerTool("get_recently_played",{title:"Get recently played games",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.",inputSchema:{steamid:vt},annotations:ye},Nr(e,n,i=>e.getRecentlyPlayed(i))),t.registerTool("get_player_achievements",{title:"Get a player's achievements",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.",inputSchema:{steamid:vt,appid:Rt,language:O.string().min(2).describe("Language for achievement names/descriptions; overrides STEAM_LANGUAGE.").optional()},annotations:ye},({steamid:i,appid:r,language:o})=>n(async()=>e.getPlayerAchievements(await e.requireSteamId(i),r,o)))}function Yg(t,e){return{description:t,messages:[{role:"user",content:{type:"text",text:e}}]}}function mS(t){t.registerPrompt("what_should_i_play",{title:"What should I play next?",description:"Recommend games from the Steam catalog based on a player's library and taste, excluding what they already own.",argsSchema:{steamid:O.string().describe("SteamID64 whose library to base taste on. Omit to use the configured STEAM_ID.").optional(),budget:O.string().describe("Max price, e.g. '$20' or 'free'. Omit for no limit.").optional(),tags:O.string().describe("Comma-separated tags to steer toward, e.g. 'Roguelike, Deckbuilding'. Omit to infer from the library.").optional()}},({steamid:e,budget:n,tags:i})=>Yg("Recommend games based on library/taste",`Recommend what I should play next.
80
80
 
81
81
  1. Call get_owned_games${e?` for steamid ${e}`:""} and find the tags/genres of my most-played games (use get_items on a few top appids for their tags if needed).
82
82
  2. Call discover_games filtered by ${i?`tags: ${i}`:"the tags you found"}${n?`, priced under ${n}`:""} and a good review score (min_review 80+).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "steam-games-mcp",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "mcpName": "io.github.Grinv/steam-games-mcp",
5
5
  "description": "Enables LLMs to search and evaluate Steam games — prices, discounts, reviews and Steam Deck compatibility with no API key, plus a player's library, achievements and friends via the official Steam Web API.",
6
6
  "type": "module",