perigee-mcp 1.9.4 → 1.9.5

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.
@@ -62,4 +62,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
62
62
  ]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
63
63
  ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function _w(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===$.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:zw(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??JC(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:zw(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===$.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=uw(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===$.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===$.ZodBranded&&e.keyType._def.type._def.typeName===$.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=QC(e.keyType._def,t);return{...n,propertyNames:i}}return n}function vw(e,t){return t.mapStrategy===`record`?_w(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[zw(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||JC(t),zw(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||JC(t)],minItems:2,maxItems:2}}}function yw(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function bw(e){return e.target===`openAi`?void 0:{not:JC({...e,currentPath:[...e.currentPath,`not`]})}}function xw(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var Sw={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Cw(e,t){if(t.target===`openApi3`)return ww(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Sw&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Sw[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ww(e,t)}var ww=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>zw(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Tw(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Sw[e.innerType._def.typeName],nullable:!0}:{type:[Sw[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=zw(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=zw(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Ew(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,GC(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?KC(n,`minimum`,r.value,r.message,t):KC(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),KC(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?KC(n,`maximum`,r.value,r.message,t):KC(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),KC(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:KC(n,`multipleOf`,r.value,r.message,t)}return n}function Dw(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=kw(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=zw(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=Ow(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Ow(e,t){if(e.catchall._def.typeName!==`ZodNever`)return zw(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function kw(e){try{return e.isOptional()}catch{return!0}}var Aw=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return zw(e.innerType._def,t);let n=zw(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:JC(t)},n]}:JC(t)},jw=(e,t)=>{if(t.pipeStrategy===`input`)return zw(e.in._def,t);if(t.pipeStrategy===`output`)return zw(e.out._def,t);let n=zw(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,zw(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Mw(e,t){return zw(e.type._def,t)}function Nw(e,t){let n={type:`array`,uniqueItems:!0,items:zw(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&KC(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&KC(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Pw(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>zw(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:zw(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>zw(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Fw(e){return{not:JC(e)}}function Iw(e){return JC(e)}var Lw=(e,t)=>zw(e.innerType._def,t),Rw=(e,t,n)=>{switch(t){case $.ZodString:return uw(e,n);case $.ZodNumber:return Ew(e,n);case $.ZodObject:return Dw(e,n);case $.ZodBigInt:return XC(e,n);case $.ZodBoolean:return ZC();case $.ZodDate:return ew(e,n);case $.ZodUndefined:return Fw(n);case $.ZodNull:return xw(n);case $.ZodArray:return YC(e,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return Cw(e,n);case $.ZodIntersection:return ow(e,n);case $.ZodTuple:return Pw(e,n);case $.ZodRecord:return _w(e,n);case $.ZodLiteral:return sw(e,n);case $.ZodEnum:return iw(e);case $.ZodNativeEnum:return yw(e);case $.ZodNullable:return Tw(e,n);case $.ZodOptional:return Aw(e,n);case $.ZodMap:return vw(e,n);case $.ZodSet:return Nw(e,n);case $.ZodLazy:return()=>e.getter()._def;case $.ZodPromise:return Mw(e,n);case $.ZodNaN:case $.ZodNever:return bw(n);case $.ZodEffects:return rw(e,n);case $.ZodAny:return JC(n);case $.ZodUnknown:return Iw(n);case $.ZodDefault:return nw(e,n);case $.ZodBranded:return QC(e,n);case $.ZodReadonly:return Lw(e,n);case $.ZodCatch:return $C(e,n);case $.ZodPipeline:return jw(e,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(e=>void 0)(t)}};function zw(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==VC)return i}if(r&&!n){let e=Bw(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Rw(e,e.typeName,t),o=typeof a==`function`?zw(a(),t):a;if(o&&Vw(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Bw=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:qC(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),JC(t)):t.$refStrategy===`seen`?JC(t):void 0}},Vw=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Hw=(e,t)=>{let n=WC(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:zw(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??JC(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=zw(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??JC(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};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 Uw(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Ww(e,t){return kC(e)?ss(e,{target:Uw(t?.target),io:t?.pipeStrategy??`input`}):Hw(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Gw(e){let t=NC(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=zC(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Kw(e,t){let n=jC(e,t);if(!n.success)throw n.error;return n.data}var qw=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(kl,e=>{this._oncancel(e)}),this.setNotificationHandler(Gl,e=>{this._onprogress(e)}),this.setRequestHandler(Hl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(eu,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new U(H.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(nu,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(!await this._taskStore.getTask(r,t.sessionId))throw new U(H.InvalidParams,`Task not found: ${r}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new U(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new U(H.InvalidParams,`Task not found: ${r}`);if(!BC(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(BC(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[rl]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(ru,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new U(H.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(au,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new U(H.InvalidParams,`Task not found: ${e.params.taskId}`);if(BC(n.status))throw new U(H.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new U(H.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof U?e:new U(H.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),U.fromError(H.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw 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 t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Cl(e)||Tl(e)?this._onresponse(e):yl(e)?this._onrequest(e,t):xl(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=U.fromError(H.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[rl]?.taskId,a=r?.sessionId,o=this._taskStore,s=!0,c;if(i&&o&&this._taskMessageQueue&&a!==void 0&&(s=!1,c=(async()=>{if(!await o.getTask(i,a))throw new U(H.InvalidParams,`Task not found: ${i}`);s=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:H.MethodNotFound,message:`Method not found`}};if(i&&c){let e={type:`error`,message:t,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(i,e,a),()=>r?.send(t)).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let u=fl(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,f={signal:l.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(l.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(l.signal.aborted)throw new U(H.ConnectionClosed,`Request was cancelled`);let a={...r,relatedRequestId:e.id};i&&!a.relatedTask&&(a.relatedTask={taskId:i});let o=a.relatedTask?.taskId??i;return o&&d&&await d.updateTaskStatus(o,`input_required`),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new U(H.ConnectionClosed,`Request was cancelled`);u&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async t=>{if(l.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(l.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:H.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue&&s?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),Cl(e)?n(e):n(new U(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(Cl(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),Cl(e)?r(e):r(U.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof U?e:new U(H.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Zl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new U(H.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},BC(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new U(H.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new U(H.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof U?e:new U(H.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[rl]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof U?e:new U(H.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=jC(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(U.fromError(H.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},tu,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},iu,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},ou,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[rl]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.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 n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[rl]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[rl]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Gw(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Kw(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Gw(e);this._notificationHandlers.set(n,n=>{let r=Kw(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n??this._transport?.sessionId,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&yl(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new U(H.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e,n);t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted){n(new U(H.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new U(H.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new U(H.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=$l.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),BC(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new U(H.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(BC(a.status))throw new U(H.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=$l.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),BC(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Jw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yw(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Jw(a)&&Jw(i)?{...a,...i}:i}return n}var Xw=class{getValidator(){throw Error(`perigee-mcp: JSON Schema validation (elicitation) is not supported`)}},Zw=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},pd,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},Td,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function Qw(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function $w(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var eT=class extends qw{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ed.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Xw,this.setRequestHandler(Rl,e=>this._oninitialize(e)),this.setNotificationHandler(Vl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(nd,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=ed.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Zw(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Yw(this._capabilities,e)}setRequestHandler(e,t){let n=NC(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=zC(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=jC(Qu,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new U(H.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=jC(Zl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new U(H.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=jC(Xu,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new U(H.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw 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 Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw 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 Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){$w(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Qw(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nl.includes(t)?t:tl,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`},Dl)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw 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},md,t):this.request({method:`sampling/createMessage`,params:e},pd,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},Td,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},Td,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new U(H.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof U?e:new U(H.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},Fd,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))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`})}},tT=Symbol.for(`mcp.completable`);function nT(e){return!!e&&typeof e==`object`&&tT in e}function rT(e){return e[tT]?.complete}var iT;(function(e){e.Completable=`McpCompletable`})(iT||={});var aT=/^[A-Za-z0-9._-]{1,128}$/;function oT(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!aT.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function sT(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);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 cT(e){let t=oT(e);return sT(e,t.warnings),t.isValid}var lT=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}};function uT(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(typeof e==`object`&&e){if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}}return n}function dT(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var fT=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new eT(e,t),this._maxToolInputElements=dT(t?.maxToolInputElements)}get experimental(){return this._experimental||={tasks:new lT(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(yT(Ju)),this.server.assertCanSetRequestHandler(yT(Qu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ju,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=PC(t.inputSchema);return e?Ww(e,{strictUnions:!0,pipeStrategy:`input`}):pT})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=PC(t.outputSchema);e&&(n.outputSchema=Ww(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Qu,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new U(H.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new U(H.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new U(H.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof U&&e.code===H.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(this._maxToolInputElements!==void 0&&uT(t,this._maxToolInputElements)>this._maxToolInputElements)throw new U(H.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await MC(PC(e.inputSchema)??e.inputSchema,t??{});if(!r.success){let e=IC(`error`in r?r.error:`Unknown error`);throw new U(H.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new U(H.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await MC(PC(e.outputSchema),t.structuredContent);if(!r.success){let e=IC(`error`in r?r.error:`Unknown error`);throw new U(H.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new U(H.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(yT(kd)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(kd,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Ad(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return jd(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new U(H.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return xT;let r=NC(n.argsSchema)?.[e.params.argument.name];if(!nT(r))return xT;let i=rT(r);return i?bT(await i(e.params.argument.value,e.params.context)):xT}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return xT;throw new U(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?bT(await r(e.params.argument.value,e.params.context)):xT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(yT(hu)),this.server.assertCanSetRequestHandler(yT(_u)),this.server.assertCanSetRequestHandler(yT(xu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(hu,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(_u,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(xu,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new U(H.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new U(H.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(yT(Mu)),this.server.assertCanSetRequestHandler(yT(Fu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Mu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?vT(t.argsSchema):void 0}))})),this.server.setRequestHandler(Fu,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new U(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await MC(PC(n.argsSchema),e.params.arguments??{});if(!r.success){let t=IC(`error`in r?r.error:`Unknown error`);throw new U(H.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:AC(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=AC(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>nT(e instanceof kc?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){cT(e);let l={title:t,description:n,inputSchema:_T(r),outputSchema:_T(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&cT(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=AC(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=AC(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(gT(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!gT(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},pT={type:`object`,properties:{}};function mT(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function hT(e){return`_def`in e||`_zod`in e||mT(e)}function gT(e){return typeof e!=`object`||!e||hT(e)?!1:Object.keys(e).length===0||Object.values(e).some(mT)}function _T(e){if(e){if(gT(e))return AC(e);if(!hT(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function vT(e){let t=NC(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:LC(t),required:!RC(t)})):[]}function yT(e){let t=NC(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=zC(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function bT(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var xT={completion:{values:[],hasMore:!1}},ST=`perigee`,CT=`Perigee (https://perigee.info/) shows in 3D, in real time, the artificial objects orbiting the Earth, the Moon and Mars and the spacecraft crossing the solar system, for education.
64
64
  Use perigee_find to get an object's id (NORAD number, mission id, planet, "moon:<id>", "site:<id>", "launch:<id>", "star:<id>", "comet:<id>", "asteroid:<id>"; dwarf planets and candidates by name: "eris", "quaoar", "2026-ed138"), then perigee_object for facts (goals, status, sources, an image with its credit), perigee_state (with the ground point below) / perigee_orbit / perigee_distance / perigee_distance_series for computed values, perigee_passes for when a satellite can be seen from a place, perigee_sky for what is in the sky from a place, perigee_tonight for a ready summary of the night ahead from a place, perigee_sky_conjunctions for close pairings of the Moon, planets, bright stars (and a satellite) in the sky, perigee_events for Moon phases, eclipses, oppositions and mission milestones, perigee_shadow for when a satellite enters or leaves the Earth's shadow, perigee_ground_track for the path below a satellite, perigee_close_approach for the closest distance between two objects in space (education only), perigee_stats for counts of active satellites, perigee_view for a link or an embeddable live 3D view (perigee_describe_view puts one into words, e.g. for alternative text), perigee_define for student-level definitions.
65
- Always tell the student how reliable a number is: quote the provenance (model, data state, data age, typical accuracy) and the sources. Positions are for education, not navigation.`,wT=Tc([`en`,`fr`]).optional().describe(`Language of names and texts (default en).`),TT=L().optional().describe(`ISO 8601 UTC instant, e.g. 2026-12-01T00:00:00Z (default: now).`),ET=L().min(1).max(100);function DT(e){return{content:[{type:`text`,text:JSON.stringify(e,null,1)}],structuredContent:e}}function OT(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}var kT=e=>async t=>{try{return await e(t)}catch(e){return OT(e)}};function AT(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function jT(e,t){let n=new fT({name:ST,version:t.version},{instructions:CT}),r=new Map,i=n.registerTool.bind(n);n.registerTool=((e,t,n)=>{let a=i(e,t,n);return r.set(e,a),a});let a={readOnlyHint:!0,openWorldHint:!0},o=t.maxSeriesSteps??1e3,s=t.maxPassDays??10,c=t.maxEventDays??366,l=t.maxApproachDays??7,u=t.maxConjunctionDays??31,d=t.maxShadowHours??48,f=R().min(-90).max(90).describe(`Observer latitude, degrees (north positive).`),p=R().min(-180).max(360).describe(`Observer longitude, degrees (east positive).`),m=R().min(-500).max(9e3).optional().describe(`Observer height above sea level, m.`),h=L().max(64).optional().describe(`IANA time zone for local times, e.g. "Europe/Paris".`);n.registerTool(`perigee_find`,{title:`Find an object`,description:`Looks up objects by name or identifier (English or French, accents optional): planets, moons, missions beyond Earth orbit, featured science satellites, any active Earth satellite (by name, NORAD or COSPAR id), landing and launch sites, named stars. Returns ids for the other tools.`,inputSchema:{query:L().min(1).max(100),limit:R().int().min(1).max(50).optional()},annotations:a},kT(async({query:t,limit:n})=>DT({results:await e.find(t,n??10)}))),n.registerTool(`perigee_object`,{title:`Object facts`,description:`Facts about an object: name, agency, country, launch date, status, mission goals and notes, identifiers (NORAD, COSPAR, Horizons), official website, sources and verification date, a catalogue image with credit and licence, and links to its view in Perigee. include_image also returns the image itself.`,inputSchema:{id:ET,lang:wT,include_image:rc().optional()},annotations:a},kT(async({id:n,lang:r,include_image:i})=>{let a=await e.describe(n,r??`en`),o=DT(a),s=a.image;if(i&&s?.url&&t.fetchImage){let e=await t.fetchImage(s.url);o.content.push({type:`image`,data:AT(e),mimeType:`image/webp`})}return o})),n.registerTool(`perigee_state`,{title:`Position and velocity`,description:`Position (km, ICRF/J2000 equatorial axes) and velocity (km/s) of an object at a date, relative to a centre (default: the body it orbits or stands on), with distance, altitude above the centre, speed, light time, whether it is in sunlight, and provenance. Around the Earth, the Moon or Mars it also gives the ground point below it (latitude, longitude; on the Earth the country or sea, e.g. "over Brazil", "over the Indian Ocean").`,inputSchema:{id:ET,date:TT,centre:L().optional().describe(`Reference object id, e.g. "earth", "sun", "moon:moon", "mars".`)},annotations:a},kT(async({id:t,date:n,centre:r})=>DT(await e.state(t,n,r)))),n.registerTool(`perigee_orbit`,{title:`Orbit`,description:`Orbit of an object: perigee and apogee altitudes (periapsis/apoapsis), period, inclination, eccentricity, semi-major axis. Earth satellites: the mean elements of their published element set, with the orbit regime (LEO, MEO, GEO, HEO); other objects: instantaneous two-body elements around their centre at a date (default: the body they orbit; inclination on its equator, on the ecliptic around the Sun).`,inputSchema:{id:ET,date:TT,centre:L().optional().describe(`Body the orbit is around, e.g. "sun" for a planet or a probe.`)},annotations:a},kT(async({id:t,date:n,centre:r})=>DT(await e.orbit(t,n,r)))),n.registerTool(`perigee_passes`,{title:`Satellite passes over a place`,description:`When an Earth satellite (ISS = 25544, Tiangong = 48274, Hubble = 20580, or any NORAD number) passes over a place: rise, highest point and set times with direction (azimuth, compass point) and elevation, and whether it can be seen with the naked eye (sunlit satellite, dark sky) and when. Give the place's latitude and longitude (degrees, east positive) and, for local times, its IANA time zone. Up to ${s} days ahead.`,inputSchema:{id:ET,latitude:R().min(-90).max(90).describe(`Observer latitude, degrees (north positive).`),longitude:R().min(-180).max(360).describe(`Observer longitude, degrees (east positive).`),height_m:R().min(-500).max(9e3).optional().describe(`Observer height above sea level, m.`),start:TT,days:R().min(.05).max(s).optional().describe(`Search length in days (default 3).`),min_elevation:R().min(0).max(80).optional().describe(`Lowest culmination kept and lowest elevation counted as visible, degrees (default 10).`),time_zone:L().max(64).optional().describe(`IANA time zone for local times, e.g. "America/Toronto".`),lang:wT},annotations:a},kT(async({id:t,latitude:n,longitude:r,height_m:i,start:a,days:o,min_elevation:c,time_zone:l,lang:u})=>DT(await e.passes(t,{latDeg:n,lonDeg:r,...i===void 0?{}:{heightM:i},...a?{start:a}:{},...o===void 0?{}:{days:o},...c===void 0?{}:{minElevationDeg:c},...l?{timeZone:l}:{},lang:u??`en`},s)))),n.registerTool(`perigee_sky`,{title:`The sky from a place`,description:`What is in the sky from a place at a date (default: now): day, twilight or night; the Sun with its next rise, set and twilights; the Moon with its phase, illuminated share, rise and set; each planet with its altitude, direction, brightness (magnitude), constellation and whether it can be seen with the naked eye; and the bright named stars above the horizon. For "what can I see tonight", give the evening time.`,inputSchema:{latitude:f,longitude:p,height_m:m,date:TT,time_zone:h,lang:wT},annotations:{readOnlyHint:!0,openWorldHint:!1}},kT(({latitude:t,longitude:n,height_m:r,date:i,time_zone:a,lang:o})=>DT(e.sky({latDeg:t,lonDeg:n,...r===void 0?{}:{heightM:r},...i?{date:i}:{},...a?{timeZone:a}:{},lang:o??`en`})))),n.registerTool(`perigee_events`,{title:`Astronomical and mission events`,description:`Events over a period (default: the next 30 days, at most ${c}): Moon phases (super and micro full Moons), lunar perigee and apogee, lunar and solar eclipses (with a place: how they look from there), equinoxes and solstices, the Earth's perihelion and aphelion, planet oppositions, conjunctions and greatest elongations, and the next key events of the missions (flybys, arrivals, launches) from Perigee's catalogue.`,inputSchema:{start:TT,days:R().min(1).max(c).optional().describe(`Length of the period in days (default 30).`),kinds:z(Tc([`moon`,`eclipse`,`season`,`planet`,`mission`])).optional().describe(`Kinds of events to include (default: all).`),latitude:f.optional(),longitude:p.optional(),time_zone:h,lang:wT},annotations:{readOnlyHint:!0,openWorldHint:!1}},kT(({start:t,days:n,kinds:r,latitude:i,longitude:a,time_zone:o,lang:s})=>{if(i===void 0!=(a===void 0))throw Error(`Give both latitude and longitude, or neither.`);return DT(e.events({...t?{start:t}:{},...n===void 0?{}:{days:n},...r?{kinds:r}:{},lang:s??`en`,...i!==void 0&&a!==void 0?{place:{latDeg:i,lonDeg:a,...o?{timeZone:o}:{}}}:{}},c))})),n.registerTool(`perigee_tonight`,{title:`Tonight from a place`,description:`What there is to see tonight from a place (the coming night, or the current one): the night's start and end, the Moon (phase, illuminated share, rise and set), the planets visible to the naked eye, the visible passes of the ISS, Tiangong and Hubble, the close pairings of the Moon and planets, and the sky's events of the night, with short highlights ready to read. Give the place's latitude and longitude and, for local times, its IANA time zone.`,inputSchema:{latitude:f,longitude:p,height_m:m,date:TT,time_zone:h,lang:wT},annotations:a},kT(async({latitude:t,longitude:n,height_m:r,date:i,time_zone:a,lang:o})=>DT(await e.tonight({latDeg:t,lonDeg:n,...r===void 0?{}:{heightM:r},...i?{date:i}:{},...a?{timeZone:a}:{},lang:o??`en`})))),n.registerTool(`perigee_sky_conjunctions`,{title:`Close pairings in the sky`,description:`Apparent close pairings seen from a place over a period (default 7 days, at most ${u}): the Moon and the planets with each other and with the bright stars near the ecliptic (Regulus, Spica, Antares, Aldebaran, Pollux…), at their closest, with where to look and whether the pair is visible (above the horizon, dark sky). With \`satellite\` (a NORAD number), that satellite passing near them during its passes over one day.`,inputSchema:{latitude:f,longitude:p,height_m:m,start:TT,days:R().min(.05).max(u).optional().describe(`Length of the period in days (default 7; 1 with a satellite).`),max_separation:R().min(.1).max(10).optional().describe(`Widest separation kept, degrees (default 5).`),satellite:L().max(20).optional().describe(`An Earth satellite (NORAD number) to check against the Moon, planets and stars.`),time_zone:h,lang:wT},annotations:a},kT(async({latitude:t,longitude:n,height_m:r,start:i,days:a,max_separation:o,satellite:s,time_zone:c,lang:l})=>DT(await e.skyConjunctions({latDeg:t,lonDeg:n,...r===void 0?{}:{heightM:r},...i?{start:i}:{},...a===void 0?{}:{days:a},...o===void 0?{}:{maxSeparationDeg:o},...s?{satellite:s}:{},...c?{timeZone:c}:{},lang:l??`en`},u)))),n.registerTool(`perigee_shadow`,{title:`Sunlight and shadow`,description:`Whether an object is in sunlight, in the penumbra or in the umbra of the body it orbits (Earth satellites: the Earth's shadow; lunar and Martian orbiters: the Moon's or Mars'), and when it next enters and leaves the shadow (default: over two orbits, at most ${d} hours). Explains why a satellite crossing the night sky suddenly fades out.`,inputSchema:{id:ET,date:TT,hours:R().min(.1).max(d).optional().describe(`Length of the search in hours (default: two orbits).`),centre:L().optional().describe(`Body casting the shadow (default: the one the object orbits).`),time_zone:h,lang:wT},annotations:a},kT(async({id:t,date:n,hours:r,centre:i,time_zone:a,lang:o})=>DT(await e.shadow(t,{...n?{date:n}:{},...r===void 0?{}:{hours:r},...i?{centre:i}:{},...a?{timeZone:a}:{},lang:o??`en`},d)))),n.registerTool(`perigee_ground_track`,{title:`Ground track`,description:`The path on the ground below an Earth satellite over one or two orbits: a list of points (time, latitude, longitude, height) and a GeoJSON MultiLineString split at the antimeridian, ready for a map. Up to 360 points.`,inputSchema:{id:ET,start:TT,orbits:R().min(.1).max(2).optional().describe(`Number of orbits (default 1).`),points:R().int().min(10).max(360).optional().describe(`Number of points (default 180 per orbit).`),lang:wT},annotations:a},kT(async({id:t,start:n,orbits:r,points:i,lang:a})=>DT(await e.groundTrack(t,{...n?{start:n}:{},...r===void 0?{}:{orbits:r},...i===void 0?{}:{points:i},lang:a??`en`})))),n.registerTool(`perigee_close_approach`,{title:`Closest approach in space`,description:`The closest distance between two objects in space over a period (default 1 day, at most ${l}): when, how close (timed to a fraction of a second) and, for two Earth satellites, how fast they pass each other. For education only: public orbits are not precise enough for collision avoidance, and the answer says so.`,inputSchema:{from:ET.describe(`First object id.`),to:ET.describe(`Second object id.`),start:TT,days:R().min(.01).max(l).optional().describe(`Length of the search in days (default 1).`),time_zone:h,lang:wT},annotations:a},kT(async({from:t,to:n,start:r,days:i,time_zone:a,lang:o})=>DT(await e.closeApproach(t,n,{...r?{start:r}:{},...i===void 0?{}:{days:i},...a?{timeZone:a}:{},lang:o??`en`},l)))),n.registerTool(`perigee_stats`,{title:`Satellite statistics`,description:`Counts of the active satellites: total, by owner (country or organisation, e.g. US, PRC, CIS, ESA), by operator (SpaceX, OneWeb, Amazon Kuiper…), by CelesTrak group (constellations, navigation, weather…), by orbit regime (LEO, MEO, GEO, HEO), object type, launch year, recent launches and low-orbit altitude bands. owner, operator or group narrow a list to matching entries (code or name).`,inputSchema:{owner:L().max(60).optional(),operator:L().max(60).optional(),group:L().max(60).optional(),limit:R().int().min(1).max(200).optional().describe(`Largest entries listed per category (default 25).`),lang:wT},annotations:a},kT(async({owner:t,operator:n,group:r,limit:i,lang:a})=>DT(await e.stats({lang:a??`en`,...t?{owner:t}:{},...n?{operator:n}:{},...r?{group:r}:{},...i===void 0?{}:{limit:i}})))),n.registerTool(`perigee_distance`,{title:`Distance between two objects`,description:`Centre-to-centre distance between two objects at a date (km and astronomical units) and the light travel time, with the provenance of both positions. Example: from "earth" to "mars".`,inputSchema:{from:ET,to:ET,date:TT},annotations:a},kT(async({from:t,to:n,date:r})=>DT(await e.distance(t,n,r)))),n.registerTool(`perigee_distance_series`,{title:`Distance over a period`,description:`Distances between two objects sampled evenly over a period (for a table or a chart), with the closest and farthest samples. The step limits their precision: use more steps for a precise closest approach.`,inputSchema:{from:ET,to:ET,start:L().describe(`ISO 8601 UTC start.`),end:L().describe(`ISO 8601 UTC end.`),steps:R().int().min(1).max(o).optional().describe(`Number of intervals (default 50, at most ${o}).`)},annotations:a},kT(async({from:t,to:n,start:r,end:i,steps:a})=>DT(await e.series(t,n,r,i,Math.min(a??50,o))))),n.registerTool(`perigee_view`,{title:`Link or embed a 3D view`,description:"Link to Perigee showing an object (optionally at a date, paused or accelerated, followed), and an iframe snippet for a lesson page: the live 3D view without bars or panels. The embedding page can then drive the view and take PNG snapshots with postMessage (protocol perigee:v1, documented in `embedApi`). For a star, star_map opens its 3D map with the Sun instead (every named star at its real distance, the Sun–star distance drawn; compare adds a second star), alone in the iframe.",inputSchema:{id:ET,date:TT,lang:wT,rate:R().min(-1e5).max(1e5).optional().describe(`Time multiplier: 1 real time, 0 paused.`),follow:rc().optional().describe(`Follow the object (default true).`),panel:rc().optional().describe(`Keep the information panel in the embed.`),time_bar:rc().optional().describe(`Keep the time bar in the embed.`),star_map:rc().optional().describe(`Stars only (star:<id>): open the star's 3D map with the Sun, alone in the embed.`),compare:ET.optional().describe(`With star_map: another star (star:<id>) drawn with its distance to compare.`)},annotations:{readOnlyHint:!0,openWorldHint:!1}},kT(({id:t,date:n,lang:r,rate:i,follow:a,panel:o,time_bar:s,star_map:c,compare:l})=>{let u=n?new Date(n):void 0;if(u&&Number.isNaN(u.getTime()))throw Error(`Invalid date: ${n}`);let d={...u?{date:u}:{},...r?{lang:r}:{},...i===void 0?{}:{rate:i},follow:a??!0,...c?{starMap:!0,...l?{compare:l}:{}}:{}},f=new URL(e.viewUrl(t,{...d,embed:!0})),p=[o&&`panel`,s&&`time`].filter(Boolean).join(`,`);return p&&f.searchParams.set(`ui`,p),DT({url:e.viewUrl(t,d),embedUrl:f.href,iframe:`<iframe src="${f.href.replaceAll(`&`,`&amp;`)}" width="800" height="500" style="border:0" allow="fullscreen" title="Perigee"></iframe>`,embedApi:{protocol:`perigee:v1`,snapshot:`iframe.contentWindow.postMessage({ type: 'perigee:v1', id: 1, method: 'snapshot', params: { kind: 'shown' } }, '*'); the reply { type: 'perigee:v1', id: 1, ok: true, result: { dataUrl } } carries a PNG.`,methods:[`get`,`set`,`snapshot`,`ping`],events:[`ready`,`view`,`selection`,`time`],documentation:new URL(`api/interface.json`,e.data.baseUrl).href},note:`Pictures of the 3D view are taken by the browser showing the embed (snapshot); the server cannot render them.`})})),n.registerTool(`perigee_describe_view`,{title:`Describe a view`,description:`Turns a Perigee link or embed URL (from perigee_view or a shared link) into words: a one-sentence alternative text for the image or iframe, and a description for lesson notes (which view, the selected object, where it is and how reliable its position is, the date and speed of time, the frame, the filters and what is hidden). The camera framing is not in the link.`,inputSchema:{url:L().min(1).max(2e3).describe(`A Perigee URL, e.g. https://perigee.info/?view=solar&sel=mars`),lang:wT,time_zone:h},annotations:a},kT(async({url:t,lang:n,time_zone:r})=>DT(await e.describeView(t,n??`en`,r)))),n.registerTool(`perigee_define`,{title:`Define a term`,description:`Student-level definitions (secondary school) of the terms shown in Perigee: NORAD number, COSPAR id, apogee and perigee, inclination, orbital period, element epoch, ephemeris window, phase… Without a term, lists them all.`,inputSchema:{term:L().max(60).optional(),lang:wT},annotations:{readOnlyHint:!0,openWorldHint:!1}},kT(({term:t,lang:n})=>DT({definitions:e.define(t,n??`en`)}))),n.registerTool(`perigee_about`,{title:`Sources, models and accuracy`,description:`What every answer rests on: data sources and when they were fetched, the models and their typical accuracy, catalogue sizes, frame, attribution and the educational-use disclaimer.`,annotations:a},kT(async()=>DT(await e.about())));let g=`Temporarily unavailable on this server (protection against overload). The same tool works in the local server: npx -y perigee-mcp`;for(let e of MT([...r.keys()],t.disabledTools??[])){let t=r.get(e);t?.update({description:`[${g}] ${t.description??``}`,callback:(()=>OT(Error(`${e}: ${g}`)))})}return n}function MT(e,t){let n=t.map(e=>e.trim().toLowerCase()).filter(Boolean);return n.includes(`*`)?[...e]:e.filter(e=>n.some(t=>e===t||e.endsWith(`_${t}`)))}var NT=`1.9.4`,PT=process.env.PERIGEE_SITE??`https://perigee.info/`,FT=`perigee-mcp/${NT} (+https://github.com/dlamarre-dev/Perigee)`,IT=e=>fetch(e,{headers:{"User-Agent":FT}});await jT(Gx({baseUrl:PT.endsWith(`/`)?PT:`${PT}/`,fetch:IT,cache:new Jx(process.env.PERIGEE_MCP_CACHE??Kx())}),{version:NT,fetchImage:async e=>{let t=await IT(e);if(!t.ok)throw Error(`HTTP ${t.status} for ${e}`);return new Uint8Array(await t.arrayBuffer())}}).connect(new Vd);export{};
65
+ Always tell the student how reliable a number is: quote the provenance (model, data state, data age, typical accuracy) and the sources. Positions are for education, not navigation.`,wT=Tc([`en`,`fr`]).optional().describe(`Language of names and texts (default en).`),TT=L().optional().describe(`ISO 8601 UTC instant, e.g. 2026-12-01T00:00:00Z (default: now).`),ET=`NORAD number, mission id, planet, "moon:<id>", "site:<id>", "launch:<id>", "star:<id>", "comet:<id>", "asteroid:<id>" or a dwarf planet name`,DT=L().min(1).max(100).describe(`Object id from perigee_find (${ET}), e.g. "25544" for the ISS.`),OT=L().min(1).max(100).describe(`First object id from perigee_find (${ET}), e.g. "earth".`),kT=L().min(1).max(100).describe(`Second object id from perigee_find (${ET}), e.g. "mars".`);function AT(e){return{content:[{type:`text`,text:JSON.stringify(e,null,1)}],structuredContent:e}}function jT(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}var MT=e=>async t=>{try{return await e(t)}catch(e){return jT(e)}};function NT(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function PT(e,t){let n=new fT({name:ST,version:t.version},{instructions:CT}),r=new Map,i=n.registerTool.bind(n);n.registerTool=((e,t,n)=>{let a=i(e,t,n);return r.set(e,a),a});let a={readOnlyHint:!0,openWorldHint:!0},o=t.maxSeriesSteps??1e3,s=t.maxPassDays??10,c=t.maxEventDays??366,l=t.maxApproachDays??7,u=t.maxConjunctionDays??31,d=t.maxShadowHours??48,f=R().min(-90).max(90).describe(`Observer latitude, degrees (north positive).`),p=R().min(-180).max(360).describe(`Observer longitude, degrees (east positive).`),m=R().min(-500).max(9e3).optional().describe(`Observer height above sea level, m.`),h=L().max(64).optional().describe(`IANA time zone for local times, e.g. "Europe/Paris".`);n.registerTool(`perigee_find`,{title:`Find an object`,description:`Looks up objects by name or identifier (English or French, accents optional): planets, moons, missions beyond Earth orbit, featured science satellites, any active Earth satellite (by name, NORAD or COSPAR id), landing and launch sites, named stars. Returns ids for the other tools.`,inputSchema:{query:L().min(1).max(100).describe(`Name or identifier to look up, e.g. "ISS", "Voyager 1", "25544", "Mars", "Apollo 11".`),limit:R().int().min(1).max(50).optional().describe(`Maximum number of results (default 10).`)},annotations:a},MT(async({query:t,limit:n})=>AT({results:await e.find(t,n??10)}))),n.registerTool(`perigee_object`,{title:`Object facts`,description:`Facts about an object: name, agency, country, launch date, status, mission goals and notes, identifiers (NORAD, COSPAR, Horizons), official website, sources and verification date, a catalogue image with credit and licence, and links to its view in Perigee. include_image also returns the image itself.`,inputSchema:{id:DT,lang:wT,include_image:rc().optional().describe(`Also return the catalogue image itself, not only its link and credit (default false).`)},annotations:a},MT(async({id:n,lang:r,include_image:i})=>{let a=await e.describe(n,r??`en`),o=AT(a),s=a.image;if(i&&s?.url&&t.fetchImage){let e=await t.fetchImage(s.url);o.content.push({type:`image`,data:NT(e),mimeType:`image/webp`})}return o})),n.registerTool(`perigee_state`,{title:`Position and velocity`,description:`Position (km, ICRF/J2000 equatorial axes) and velocity (km/s) of an object at a date, relative to a centre (default: the body it orbits or stands on), with distance, altitude above the centre, speed, light time, whether it is in sunlight, and provenance. Around the Earth, the Moon or Mars it also gives the ground point below it (latitude, longitude; on the Earth the country or sea, e.g. "over Brazil", "over the Indian Ocean").`,inputSchema:{id:DT,date:TT,centre:L().optional().describe(`Reference object id, e.g. "earth", "sun", "moon:moon", "mars".`)},annotations:a},MT(async({id:t,date:n,centre:r})=>AT(await e.state(t,n,r)))),n.registerTool(`perigee_orbit`,{title:`Orbit`,description:`Orbit of an object: perigee and apogee altitudes (periapsis/apoapsis), period, inclination, eccentricity, semi-major axis. Earth satellites: the mean elements of their published element set, with the orbit regime (LEO, MEO, GEO, HEO); other objects: instantaneous two-body elements around their centre at a date (default: the body they orbit; inclination on its equator, on the ecliptic around the Sun).`,inputSchema:{id:DT,date:TT,centre:L().optional().describe(`Body the orbit is around, e.g. "sun" for a planet or a probe.`)},annotations:a},MT(async({id:t,date:n,centre:r})=>AT(await e.orbit(t,n,r)))),n.registerTool(`perigee_passes`,{title:`Satellite passes over a place`,description:`When an Earth satellite (ISS = 25544, Tiangong = 48274, Hubble = 20580, or any NORAD number) passes over a place: rise, highest point and set times with direction (azimuth, compass point) and elevation, and whether it can be seen with the naked eye (sunlit satellite, dark sky) and when. Give the place's latitude and longitude (degrees, east positive) and, for local times, its IANA time zone. Up to ${s} days ahead.`,inputSchema:{id:DT,latitude:R().min(-90).max(90).describe(`Observer latitude, degrees (north positive).`),longitude:R().min(-180).max(360).describe(`Observer longitude, degrees (east positive).`),height_m:R().min(-500).max(9e3).optional().describe(`Observer height above sea level, m.`),start:TT,days:R().min(.05).max(s).optional().describe(`Search length in days (default 3).`),min_elevation:R().min(0).max(80).optional().describe(`Lowest culmination kept and lowest elevation counted as visible, degrees (default 10).`),time_zone:L().max(64).optional().describe(`IANA time zone for local times, e.g. "America/Toronto".`),lang:wT},annotations:a},MT(async({id:t,latitude:n,longitude:r,height_m:i,start:a,days:o,min_elevation:c,time_zone:l,lang:u})=>AT(await e.passes(t,{latDeg:n,lonDeg:r,...i===void 0?{}:{heightM:i},...a?{start:a}:{},...o===void 0?{}:{days:o},...c===void 0?{}:{minElevationDeg:c},...l?{timeZone:l}:{},lang:u??`en`},s)))),n.registerTool(`perigee_sky`,{title:`The sky from a place`,description:`What is in the sky from a place at a date (default: now): day, twilight or night; the Sun with its next rise, set and twilights; the Moon with its phase, illuminated share, rise and set; each planet with its altitude, direction, brightness (magnitude), constellation and whether it can be seen with the naked eye; and the bright named stars above the horizon. For "what can I see tonight", give the evening time.`,inputSchema:{latitude:f,longitude:p,height_m:m,date:TT,time_zone:h,lang:wT},annotations:{readOnlyHint:!0,openWorldHint:!1}},MT(({latitude:t,longitude:n,height_m:r,date:i,time_zone:a,lang:o})=>AT(e.sky({latDeg:t,lonDeg:n,...r===void 0?{}:{heightM:r},...i?{date:i}:{},...a?{timeZone:a}:{},lang:o??`en`})))),n.registerTool(`perigee_events`,{title:`Astronomical and mission events`,description:`Events over a period (default: the next 30 days, at most ${c}): Moon phases (super and micro full Moons), lunar perigee and apogee, lunar and solar eclipses (with a place: how they look from there), equinoxes and solstices, the Earth's perihelion and aphelion, planet oppositions, conjunctions and greatest elongations, and the next key events of the missions (flybys, arrivals, launches) from Perigee's catalogue.`,inputSchema:{start:TT,days:R().min(1).max(c).optional().describe(`Length of the period in days (default 30).`),kinds:z(Tc([`moon`,`eclipse`,`season`,`planet`,`mission`])).optional().describe(`Kinds of events to include (default: all).`),latitude:f.optional(),longitude:p.optional(),time_zone:h,lang:wT},annotations:{readOnlyHint:!0,openWorldHint:!1}},MT(({start:t,days:n,kinds:r,latitude:i,longitude:a,time_zone:o,lang:s})=>{if(i===void 0!=(a===void 0))throw Error(`Give both latitude and longitude, or neither.`);return AT(e.events({...t?{start:t}:{},...n===void 0?{}:{days:n},...r?{kinds:r}:{},lang:s??`en`,...i!==void 0&&a!==void 0?{place:{latDeg:i,lonDeg:a,...o?{timeZone:o}:{}}}:{}},c))})),n.registerTool(`perigee_tonight`,{title:`Tonight from a place`,description:`What there is to see tonight from a place (the coming night, or the current one): the night's start and end, the Moon (phase, illuminated share, rise and set), the planets visible to the naked eye, the visible passes of the ISS, Tiangong and Hubble, the close pairings of the Moon and planets, and the sky's events of the night, with short highlights ready to read. Give the place's latitude and longitude and, for local times, its IANA time zone.`,inputSchema:{latitude:f,longitude:p,height_m:m,date:TT,time_zone:h,lang:wT},annotations:a},MT(async({latitude:t,longitude:n,height_m:r,date:i,time_zone:a,lang:o})=>AT(await e.tonight({latDeg:t,lonDeg:n,...r===void 0?{}:{heightM:r},...i?{date:i}:{},...a?{timeZone:a}:{},lang:o??`en`})))),n.registerTool(`perigee_sky_conjunctions`,{title:`Close pairings in the sky`,description:`Apparent close pairings seen from a place over a period (default 7 days, at most ${u}): the Moon and the planets with each other and with the bright stars near the ecliptic (Regulus, Spica, Antares, Aldebaran, Pollux…), at their closest, with where to look and whether the pair is visible (above the horizon, dark sky). With \`satellite\` (a NORAD number), that satellite passing near them during its passes over one day.`,inputSchema:{latitude:f,longitude:p,height_m:m,start:TT,days:R().min(.05).max(u).optional().describe(`Length of the period in days (default 7; 1 with a satellite).`),max_separation:R().min(.1).max(10).optional().describe(`Widest separation kept, degrees (default 5).`),satellite:L().max(20).optional().describe(`An Earth satellite (NORAD number) to check against the Moon, planets and stars.`),time_zone:h,lang:wT},annotations:a},MT(async({latitude:t,longitude:n,height_m:r,start:i,days:a,max_separation:o,satellite:s,time_zone:c,lang:l})=>AT(await e.skyConjunctions({latDeg:t,lonDeg:n,...r===void 0?{}:{heightM:r},...i?{start:i}:{},...a===void 0?{}:{days:a},...o===void 0?{}:{maxSeparationDeg:o},...s?{satellite:s}:{},...c?{timeZone:c}:{},lang:l??`en`},u)))),n.registerTool(`perigee_shadow`,{title:`Sunlight and shadow`,description:`Whether an object is in sunlight, in the penumbra or in the umbra of the body it orbits (Earth satellites: the Earth's shadow; lunar and Martian orbiters: the Moon's or Mars'), and when it next enters and leaves the shadow (default: over two orbits, at most ${d} hours). Explains why a satellite crossing the night sky suddenly fades out.`,inputSchema:{id:DT,date:TT,hours:R().min(.1).max(d).optional().describe(`Length of the search in hours (default: two orbits).`),centre:L().optional().describe(`Body casting the shadow (default: the one the object orbits).`),time_zone:h,lang:wT},annotations:a},MT(async({id:t,date:n,hours:r,centre:i,time_zone:a,lang:o})=>AT(await e.shadow(t,{...n?{date:n}:{},...r===void 0?{}:{hours:r},...i?{centre:i}:{},...a?{timeZone:a}:{},lang:o??`en`},d)))),n.registerTool(`perigee_ground_track`,{title:`Ground track`,description:`The path on the ground below an Earth satellite over one or two orbits: a list of points (time, latitude, longitude, height) and a GeoJSON MultiLineString split at the antimeridian, ready for a map. Up to 360 points.`,inputSchema:{id:DT,start:TT,orbits:R().min(.1).max(2).optional().describe(`Number of orbits (default 1).`),points:R().int().min(10).max(360).optional().describe(`Number of points (default 180 per orbit).`),lang:wT},annotations:a},MT(async({id:t,start:n,orbits:r,points:i,lang:a})=>AT(await e.groundTrack(t,{...n?{start:n}:{},...r===void 0?{}:{orbits:r},...i===void 0?{}:{points:i},lang:a??`en`})))),n.registerTool(`perigee_close_approach`,{title:`Closest approach in space`,description:`The closest distance between two objects in space over a period (default 1 day, at most ${l}): when, how close (timed to a fraction of a second) and, for two Earth satellites, how fast they pass each other. For education only: public orbits are not precise enough for collision avoidance, and the answer says so.`,inputSchema:{from:DT.describe(`First object id.`),to:DT.describe(`Second object id.`),start:TT,days:R().min(.01).max(l).optional().describe(`Length of the search in days (default 1).`),time_zone:h,lang:wT},annotations:a},MT(async({from:t,to:n,start:r,days:i,time_zone:a,lang:o})=>AT(await e.closeApproach(t,n,{...r?{start:r}:{},...i===void 0?{}:{days:i},...a?{timeZone:a}:{},lang:o??`en`},l)))),n.registerTool(`perigee_stats`,{title:`Satellite statistics`,description:`Counts of the active satellites: total, by owner (country or organisation, e.g. US, PRC, CIS, ESA), by operator (SpaceX, OneWeb, Amazon Kuiper…), by CelesTrak group (constellations, navigation, weather…), by orbit regime (LEO, MEO, GEO, HEO), object type, launch year, recent launches and low-orbit altitude bands. owner, operator or group narrow a list to matching entries (code or name).`,inputSchema:{owner:L().max(60).optional().describe(`Narrow the owner list to this SATCAT owner code or name, e.g. "US", "PRC", "ESA".`),operator:L().max(60).optional().describe(`Narrow the operator list to this operator, e.g. "SpaceX", "OneWeb".`),group:L().max(60).optional().describe(`Narrow the group list to this CelesTrak group, e.g. "starlink", "gps-ops", "weather".`),limit:R().int().min(1).max(200).optional().describe(`Largest entries listed per category (default 25).`),lang:wT},annotations:a},MT(async({owner:t,operator:n,group:r,limit:i,lang:a})=>AT(await e.stats({lang:a??`en`,...t?{owner:t}:{},...n?{operator:n}:{},...r?{group:r}:{},...i===void 0?{}:{limit:i}})))),n.registerTool(`perigee_distance`,{title:`Distance between two objects`,description:`Centre-to-centre distance between two objects at a date (km and astronomical units) and the light travel time, with the provenance of both positions. Example: from "earth" to "mars".`,inputSchema:{from:OT,to:kT,date:TT},annotations:a},MT(async({from:t,to:n,date:r})=>AT(await e.distance(t,n,r)))),n.registerTool(`perigee_distance_series`,{title:`Distance over a period`,description:`Distances between two objects sampled evenly over a period (for a table or a chart), with the closest and farthest samples. The step limits their precision: use more steps for a precise closest approach.`,inputSchema:{from:OT,to:kT,start:L().describe(`ISO 8601 UTC start.`),end:L().describe(`ISO 8601 UTC end.`),steps:R().int().min(1).max(o).optional().describe(`Number of intervals (default 50, at most ${o}).`)},annotations:a},MT(async({from:t,to:n,start:r,end:i,steps:a})=>AT(await e.series(t,n,r,i,Math.min(a??50,o))))),n.registerTool(`perigee_view`,{title:`Link or embed a 3D view`,description:"Link to Perigee showing an object (optionally at a date, paused or accelerated, followed), and an iframe snippet for a lesson page: the live 3D view without bars or panels. The embedding page can then drive the view and take PNG snapshots with postMessage (protocol perigee:v1, documented in `embedApi`). For a star, star_map opens its 3D map with the Sun instead (every named star at its real distance, the Sun–star distance drawn; compare adds a second star), alone in the iframe.",inputSchema:{id:DT,date:TT,lang:wT,rate:R().min(-1e5).max(1e5).optional().describe(`Time multiplier: 1 real time, 0 paused.`),follow:rc().optional().describe(`Follow the object (default true).`),panel:rc().optional().describe(`Keep the information panel in the embed.`),time_bar:rc().optional().describe(`Keep the time bar in the embed.`),star_map:rc().optional().describe(`Stars only (star:<id>): open the star's 3D map with the Sun, alone in the embed.`),compare:DT.optional().describe(`With star_map: another star (star:<id>) drawn with its distance to compare.`)},annotations:{readOnlyHint:!0,openWorldHint:!1}},MT(({id:t,date:n,lang:r,rate:i,follow:a,panel:o,time_bar:s,star_map:c,compare:l})=>{let u=n?new Date(n):void 0;if(u&&Number.isNaN(u.getTime()))throw Error(`Invalid date: ${n}`);let d={...u?{date:u}:{},...r?{lang:r}:{},...i===void 0?{}:{rate:i},follow:a??!0,...c?{starMap:!0,...l?{compare:l}:{}}:{}},f=new URL(e.viewUrl(t,{...d,embed:!0})),p=[o&&`panel`,s&&`time`].filter(Boolean).join(`,`);return p&&f.searchParams.set(`ui`,p),AT({url:e.viewUrl(t,d),embedUrl:f.href,iframe:`<iframe src="${f.href.replaceAll(`&`,`&amp;`)}" width="800" height="500" style="border:0" allow="fullscreen" title="Perigee"></iframe>`,embedApi:{protocol:`perigee:v1`,snapshot:`iframe.contentWindow.postMessage({ type: 'perigee:v1', id: 1, method: 'snapshot', params: { kind: 'shown' } }, '*'); the reply { type: 'perigee:v1', id: 1, ok: true, result: { dataUrl } } carries a PNG.`,methods:[`get`,`set`,`snapshot`,`ping`],events:[`ready`,`view`,`selection`,`time`],documentation:new URL(`api/interface.json`,e.data.baseUrl).href},note:`Pictures of the 3D view are taken by the browser showing the embed (snapshot); the server cannot render them.`})})),n.registerTool(`perigee_describe_view`,{title:`Describe a view`,description:`Turns a Perigee link or embed URL (from perigee_view or a shared link) into words: a one-sentence alternative text for the image or iframe, and a description for lesson notes (which view, the selected object, where it is and how reliable its position is, the date and speed of time, the frame, the filters and what is hidden). The camera framing is not in the link.`,inputSchema:{url:L().min(1).max(2e3).describe(`A Perigee URL, e.g. https://perigee.info/?view=solar&sel=mars`),lang:wT,time_zone:h},annotations:a},MT(async({url:t,lang:n,time_zone:r})=>AT(await e.describeView(t,n??`en`,r)))),n.registerTool(`perigee_define`,{title:`Define a term`,description:`Student-level definitions (secondary school) of the terms shown in Perigee: NORAD number, COSPAR id, apogee and perigee, inclination, orbital period, element epoch, ephemeris window, phase… Without a term, lists them all.`,inputSchema:{term:L().max(60).optional().describe(`Term to define, e.g. "inclination", "apogee", "NORAD" (omit to list every term).`),lang:wT},annotations:{readOnlyHint:!0,openWorldHint:!1}},MT(({term:t,lang:n})=>AT({definitions:e.define(t,n??`en`)}))),n.registerTool(`perigee_about`,{title:`Sources, models and accuracy`,description:`What every answer rests on: data sources and when they were fetched, the models and their typical accuracy, catalogue sizes, frame, attribution and the educational-use disclaimer.`,annotations:a},MT(async()=>AT(await e.about())));let g=`Temporarily unavailable on this server (protection against overload). The same tool works in the local server: npx -y perigee-mcp`;for(let e of FT([...r.keys()],t.disabledTools??[])){let t=r.get(e);t?.update({description:`[${g}] ${t.description??``}`,callback:(()=>jT(Error(`${e}: ${g}`)))})}return n}function FT(e,t){let n=t.map(e=>e.trim().toLowerCase()).filter(Boolean);return n.includes(`*`)?[...e]:e.filter(e=>n.some(t=>e===t||e.endsWith(`_${t}`)))}var IT=`1.9.5`,LT=process.env.PERIGEE_SITE??`https://perigee.info/`,RT=`perigee-mcp/${IT} (+https://github.com/dlamarre-dev/Perigee)`,zT=e=>fetch(e,{headers:{"User-Agent":RT}});await PT(Gx({baseUrl:LT.endsWith(`/`)?LT:`${LT}/`,fetch:zT,cache:new Jx(process.env.PERIGEE_MCP_CACHE??Kx())}),{version:IT,fetchImage:async e=>{let t=await zT(e);if(!t.ok)throw Error(`HTTP ${t.status} for ${e}`);return new Uint8Array(await t.arrayBuffer())}}).connect(new Vd);export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "perigee-mcp",
3
- "version": "1.9.4",
3
+ "version": "1.9.5",
4
4
  "mcpName": "io.github.dlamarre-dev/perigee",
5
5
  "description": "MCP server for Perigee: positions, distances, mission facts and embeddable 3D views of the objects orbiting the Earth, the Moon, Mars and the Sun, with provenance and accuracy, for AI teaching assistants.",
6
6
  "license": "MIT",