@amazon-devices/amazon-devices-buildertools-mcp 0.1.29 → 0.1.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +55 -0
- package/README.md +58 -3
- package/dist/assets/vega-developer-context.db +0 -0
- package/dist/startserver +5 -5
- package/package.json +1 -1
- package/dist/171.startserver +0 -1
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name": "@amazon-devices/amazon-devices-buildertools-mcp", "version": "0.1.
|
|
1
|
+
{"name": "@amazon-devices/amazon-devices-buildertools-mcp", "version": "0.1.30", "license": "See license in LICENSE", "engines": {"node": ">=16"}, "type": "commonjs", "bin": {"amazon-devices-buildertools-mcp": "./dist/startserver"}, "files": ["dist/", "docs/", "THIRD_PARTY_NOTICES.txt"], "npm-pretty-much": {"allowUnsafeName": "maintain consistency with vega external packages", "runTest": "never"}, "lint-staged": {"!package.json": [], "*.{js,jsx,mjs,cjs,ts,tsx}": ["prettier --write"]}, "devDependencies": {"@eslint/compat": "^1.2.5", "@eslint/js": "^9.20.0", "@modelcontextprotocol/inspector": "^0.4.1", "@tsconfig/node16": "16.1.3", "@types/jest": "^29.5.12", "@types/node": "^22.7.5", "ajv": "^8.17.1", "copy-webpack-plugin": "^12.0.0", "crypto": "^1.0.1", "fast-check": "^3.23.2", "globals": "^15.7.0", "gts": "^6.0.2", "husky": "^9.1.7", "jest": "^29.7.0", "lint-staged": "^15.4.3", "npm-run-all": "^4.1.5", "prettier": "^3.5", "terser-webpack-plugin": "^5.3.11", "ts-jest": "^29.2.4", "ts-loader": "^9.5.2", "typescript": "~5.4.5", "typescript-eslint": "^8.24.1", "typescript-transform-paths": "3.4.4", "webpack": "^5.98.0", "webpack-cli": "^6.0.1", "webpack-shebang-plugin": "^1.1.8", "yargs": "17.6.0"}, "overrides": {"eslint": "^9.20.1", "eslint-config-prettier": "^10.0.1", "eslint-import-resolver-typescript": "^3.8.2", "typescript": "~5.4.5", "typescript-eslint": "^8.24.1", "@modelcontextprotocol/inspector": "$@modelcontextprotocol/inspector"}, "dependencies": {"sqlite3": "^5.1.7"}}
|
package/dist/171.startserver
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";exports.id=171,exports.ids=[171],exports.modules={5744:function(t,e,r){var i=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.UnauthorizedError=void 0,e.auth=async function(t,{serverUrl:e,authorizationCode:r}){const i=await c(e);let o=await Promise.resolve(t.clientInformation());if(!o){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const n=await d(e,{metadata:i,clientMetadata:t.clientMetadata});await t.saveClientInformation(n),o=n}if(void 0!==r){const n=await t.codeVerifier(),s=await u(e,{metadata:i,clientInformation:o,authorizationCode:r,codeVerifier:n,redirectUri:t.redirectUrl});return await t.saveTokens(s),"AUTHORIZED"}const n=await t.tokens();if(null==n?void 0:n.refresh_token)try{const r=await h(e,{metadata:i,clientInformation:o,refreshToken:n.refresh_token});return await t.saveTokens(r),"AUTHORIZED"}catch(t){}const{authorizationUrl:s,codeVerifier:a}=await l(e,{metadata:i,clientInformation:o,redirectUrl:t.redirectUrl});return await t.saveCodeVerifier(a),await t.redirectToAuthorization(s),"REDIRECT"},e.discoverOAuthMetadata=c,e.startAuthorization=l,e.exchangeAuthorization=u,e.refreshAuthorization=h,e.registerClient=d;const o=i(r(70080)),n=r(72143),s=r(27570);class a extends Error{constructor(t){super(null!=t?t:"Unauthorized")}}async function c(t,e){var r;const i=new URL("/.well-known/oauth-authorization-server",t);let o;try{o=await fetch(i,{headers:{"MCP-Protocol-Version":null!==(r=null==e?void 0:e.protocolVersion)&&void 0!==r?r:n.LATEST_PROTOCOL_VERSION}})}catch(t){if(!(t instanceof TypeError))throw t;o=await fetch(i)}if(404!==o.status){if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth metadata`);return s.OAuthMetadataSchema.parse(await o.json())}}async function l(t,{metadata:e,clientInformation:r,redirectUrl:i}){let n;if(e){if(n=new URL(e.authorization_endpoint),!e.response_types_supported.includes("code"))throw new Error("Incompatible auth server: does not support response type code");if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes("S256"))throw new Error("Incompatible auth server: does not support code challenge method S256")}else n=new URL("/authorize",t);const s=await(0,o.default)(),a=s.code_verifier,c=s.code_challenge;return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",r.client_id),n.searchParams.set("code_challenge",c),n.searchParams.set("code_challenge_method","S256"),n.searchParams.set("redirect_uri",String(i)),{authorizationUrl:n,codeVerifier:a}}async function u(t,{metadata:e,clientInformation:r,authorizationCode:i,codeVerifier:o,redirectUri:n}){const a="authorization_code";let c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support grant type ${a}`)}else c=new URL("/token",t);const l=new URLSearchParams({grant_type:a,client_id:r.client_id,code:i,code_verifier:o,redirect_uri:String(n)});r.client_secret&&l.set("client_secret",r.client_secret);const u=await fetch(c,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l});if(!u.ok)throw new Error(`Token exchange failed: HTTP ${u.status}`);return s.OAuthTokensSchema.parse(await u.json())}async function h(t,{metadata:e,clientInformation:r,refreshToken:i}){let o;if(e){if(o=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes("refresh_token"))throw new Error("Incompatible auth server: does not support grant type refresh_token")}else o=new URL("/token",t);const n=new URLSearchParams({grant_type:"refresh_token",client_id:r.client_id,refresh_token:i});r.client_secret&&n.set("client_secret",r.client_secret);const a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n});if(!a.ok)throw new Error(`Token refresh failed: HTTP ${a.status}`);return s.OAuthTokensSchema.parse(await a.json())}async function d(t,{metadata:e,clientMetadata:r}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);const o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: HTTP ${o.status}`);return s.OAuthClientInformationFullSchema.parse(await o.json())}e.UnauthorizedError=a},27570:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OAuthTokenRevocationRequestSchema=e.OAuthClientRegistrationErrorSchema=e.OAuthClientInformationFullSchema=e.OAuthClientInformationSchema=e.OAuthClientMetadataSchema=e.OAuthErrorResponseSchema=e.OAuthTokensSchema=e.OAuthMetadataSchema=void 0;const i=r(68547);e.OAuthMetadataSchema=i.z.object({issuer:i.z.string(),authorization_endpoint:i.z.string(),token_endpoint:i.z.string(),registration_endpoint:i.z.string().optional(),scopes_supported:i.z.array(i.z.string()).optional(),response_types_supported:i.z.array(i.z.string()),response_modes_supported:i.z.array(i.z.string()).optional(),grant_types_supported:i.z.array(i.z.string()).optional(),token_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),service_documentation:i.z.string().optional(),revocation_endpoint:i.z.string().optional(),revocation_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),introspection_endpoint:i.z.string().optional(),introspection_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),code_challenge_methods_supported:i.z.array(i.z.string()).optional()}).passthrough(),e.OAuthTokensSchema=i.z.object({access_token:i.z.string(),token_type:i.z.string(),expires_in:i.z.number().optional(),scope:i.z.string().optional(),refresh_token:i.z.string().optional()}).strip(),e.OAuthErrorResponseSchema=i.z.object({error:i.z.string(),error_description:i.z.string().optional(),error_uri:i.z.string().optional()}),e.OAuthClientMetadataSchema=i.z.object({redirect_uris:i.z.array(i.z.string()).refine((t=>t.every((t=>URL.canParse(t)))),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:i.z.string().optional(),grant_types:i.z.array(i.z.string()).optional(),response_types:i.z.array(i.z.string()).optional(),client_name:i.z.string().optional(),client_uri:i.z.string().optional(),logo_uri:i.z.string().optional(),scope:i.z.string().optional(),contacts:i.z.array(i.z.string()).optional(),tos_uri:i.z.string().optional(),policy_uri:i.z.string().optional(),jwks_uri:i.z.string().optional(),jwks:i.z.any().optional(),software_id:i.z.string().optional(),software_version:i.z.string().optional()}).strip(),e.OAuthClientInformationSchema=i.z.object({client_id:i.z.string(),client_secret:i.z.string().optional(),client_id_issued_at:i.z.number().optional(),client_secret_expires_at:i.z.number().optional()}).strip(),e.OAuthClientInformationFullSchema=e.OAuthClientMetadataSchema.merge(e.OAuthClientInformationSchema),e.OAuthClientRegistrationErrorSchema=i.z.object({error:i.z.string(),error_description:i.z.string().optional()}).strip(),e.OAuthTokenRevocationRequestSchema=i.z.object({token:i.z.string(),token_type_hint:i.z.string().optional()}).strip()},33205:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0});var i=r(93119);class o extends TransformStream{constructor({onError:t,onRetry:e,onComment:r}={}){let o;super({start(n){o=i.createParser({onEvent:t=>{n.enqueue(t)},onError(e){"terminate"===t?n.error(e):"function"==typeof t&&t(e)},onRetry:e,onComment:r})},transform(t){o.feed(t)}})}}e.ParseError=i.ParseError,e.EventSourceParserStream=o},41268:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Client=void 0;const i=r(42312),o=r(72143);class n extends i.Protocol{constructor(t,e){var r;super(e),this._clientInfo=t,this._capabilities=null!==(r=null==e?void 0:e.capabilities)&&void 0!==r?r:{}}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=(0,i.mergeCapabilities)(this._capabilities,t)}assertCapability(t,e){var r;if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r[t]))throw new Error(`Server does not support ${t} (required for ${e})`)}async connect(t,e){if(await super.connect(t),void 0===t.sessionId)try{const t=await this.request({method:"initialize",params:{protocolVersion:o.LATEST_PROTOCOL_VERSION,capabilities:this._capabilities,clientInfo:this._clientInfo}},o.InitializeResultSchema,e);if(void 0===t)throw new Error(`Server sent invalid initialize result: ${t}`);if(!o.SUPPORTED_PROTOCOL_VERSIONS.includes(t.protocolVersion))throw new Error(`Server's protocol version is not supported: ${t.protocolVersion}`);this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,this._instructions=t.instructions,await this.notification({method:"notifications/initialized"})}catch(t){throw this.close(),t}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var e,r,i,o,n;switch(t){case"logging/setLevel":if(!(null===(e=this._serverCapabilities)||void 0===e?void 0:e.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r.prompts))throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null===(i=this._serverCapabilities)||void 0===i?void 0:i.resources))throw new Error(`Server does not support resources (required for ${t})`);if("resources/subscribe"===t&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!(null===(o=this._serverCapabilities)||void 0===o?void 0:o.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!(null===(n=this._serverCapabilities)||void 0===n?void 0:n.completions))throw new Error(`Server does not support completions (required for ${t})`)}}assertNotificationCapability(t){var e;if("notifications/roots/list_changed"===t&&!(null===(e=this._capabilities.roots)||void 0===e?void 0:e.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${t})`)}assertRequestHandlerCapability(t){switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`)}}async ping(t){return this.request({method:"ping"},o.EmptyResultSchema,t)}async complete(t,e){return this.request({method:"completion/complete",params:t},o.CompleteResultSchema,e)}async setLoggingLevel(t,e){return this.request({method:"logging/setLevel",params:{level:t}},o.EmptyResultSchema,e)}async getPrompt(t,e){return this.request({method:"prompts/get",params:t},o.GetPromptResultSchema,e)}async listPrompts(t,e){return this.request({method:"prompts/list",params:t},o.ListPromptsResultSchema,e)}async listResources(t,e){return this.request({method:"resources/list",params:t},o.ListResourcesResultSchema,e)}async listResourceTemplates(t,e){return this.request({method:"resources/templates/list",params:t},o.ListResourceTemplatesResultSchema,e)}async readResource(t,e){return this.request({method:"resources/read",params:t},o.ReadResourceResultSchema,e)}async subscribeResource(t,e){return this.request({method:"resources/subscribe",params:t},o.EmptyResultSchema,e)}async unsubscribeResource(t,e){return this.request({method:"resources/unsubscribe",params:t},o.EmptyResultSchema,e)}async callTool(t,e=o.CallToolResultSchema,r){return this.request({method:"tools/call",params:t},e,r)}async listTools(t,e){return this.request({method:"tools/list",params:t},o.ListToolsResultSchema,e)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}e.Client=n},42171:(t,e,r)=>{e.MCPRemoteEndpointClient=void 0;const i=r(41268),o=r(60922),n=r(81747),s=r(22982);var a;!function(t){t.CLOSED="CLOSED",t.OPEN="OPEN",t.HALF_OPEN="HALF_OPEN"}(a||(a={}));e.MCPRemoteEndpointClient=class{constructor(t){this.circuitState=a.CLOSED,this.consecutiveFailures=0,this.circuitOpenedAt=0,this.activeRequests=0,this.requestQueue=[],this.endpointUrl=t.endpointUrl,this.onRetry=t.onRetry,this.onCircuitStateChange=t.onCircuitStateChange}async healthCheck(){try{const t=await this.getClient();await t.listTools(),(0,s.getLogger)().info("Remote endpoint health check passed",{url:this.endpointUrl})}catch(t){(0,s.getLogger)().warn("Remote endpoint health check failed, circuit breaker starting open",{url:this.endpointUrl,error:t instanceof Error?t.message:String(t)}),this.transitionCircuit(a.OPEN,"health_check_failure")}}async invoke(t){if(this.circuitState===a.OPEN){if(!(Date.now()-this.circuitOpenedAt>=n.CIRCUIT_BREAKER_COOLDOWN_MS))throw new n.RemoteEndpointError("Circuit breaker is open",this.endpointUrl,"circuit_open",0);this.transitionCircuit(a.HALF_OPEN,"cooldown_expired")}await this.acquireSlot();try{return await this.invokeWithRetry(t)}finally{this.releaseSlot()}}async dispose(){if(this.client){try{await this.client.close()}catch{}this.client=void 0,this.connecting=void 0}}async invokeWithRetry(t){var e;const r=Date.now()+n.TOTAL_TIMEOUT_MS;let i;for(let o=1;o<=n.MAX_RETRY_ATTEMPTS;o++){const a=r-Date.now();if(a<=0)break;const c=Date.now();try{const e=await this.getClient(),r=await Promise.race([e.callTool({name:t.operation,arguments:t.params}),this.timeoutPromise(a)]);return this.onSuccess(),{data:this.extractContent(r)}}catch(t){const a=Date.now()-c,l=this.classifyError(t);if(i=t instanceof Error?t:new Error(String(t)),"network"===l||"timeout"===l){const t=this.client;this.client=void 0,this.connecting=void 0,Promise.resolve(null==t?void 0:t.close()).catch((()=>{}))}if(null===(e=this.onRetry)||void 0===e||e.call(this,{attemptNumber:o,latencyMs:a,errorType:l,remainingBudgetMs:Math.max(0,r-Date.now())}),(0,s.getLogger)().debug("Remote endpoint retry",{attempt:o,errorType:l,latencyMs:a,remainingBudgetMs:Math.max(0,r-Date.now())}),o===n.MAX_RETRY_ATTEMPTS)break;const u=Math.min(200*Math.pow(2,o-1),Math.max(0,r-Date.now()));u>0&&await this.sleep(u)}}this.onFailure();const o=n.TOTAL_TIMEOUT_MS-Math.max(0,r-Date.now());throw new n.RemoteEndpointError(`Remote operation '${t.operation}' failed after ${n.MAX_RETRY_ATTEMPTS} attempts`,this.endpointUrl,this.classifyError(i),o,i)}async getClient(){if(this.client)return this.client;if(this.connecting)return this.connecting;this.connecting=this.createClient();try{return this.client=await this.connecting,this.client}catch(t){throw this.connecting=void 0,t}}async createClient(){const t=new o.StreamableHTTPClientTransport(new URL(this.endpointUrl)),e=new i.Client({name:"amazon-devices-buildertools-mcp",version:"0.1.0"});return await e.connect(t),e}extractContent(t){if(t&&"object"==typeof t&&"content"in t){const e=t.content;if(Array.isArray(e)&&e.length>0&&e[0].text)return e[0].text}return t}classifyError(t){if(!t)return"unknown";const e=t instanceof Error?t.message:String(t);return e.includes("timeout")||e.includes("TIMEOUT")?"timeout":e.includes("ECONNREFUSED")||e.includes("ENOTFOUND")||e.includes("fetch failed")?"network":e.includes("401")||e.includes("403")||e.includes("Unauthorized")||e.includes("Forbidden")?"auth":e.includes("429")||/\b[45]\d{2}\b/.test(e)?"http":"network"}timeoutPromise(t){return new Promise(((e,r)=>setTimeout((()=>r(new Error("timeout"))),t)))}sleep(t){return new Promise((e=>setTimeout(e,t)))}onSuccess(){this.consecutiveFailures=0,this.circuitState===a.HALF_OPEN&&this.transitionCircuit(a.CLOSED,"probe_success")}onFailure(){this.consecutiveFailures++,this.circuitState===a.HALF_OPEN?this.transitionCircuit(a.OPEN,"probe_failure"):this.consecutiveFailures>=n.CIRCUIT_BREAKER_THRESHOLD&&this.transitionCircuit(a.OPEN,`consecutive_failures_${this.consecutiveFailures}`)}transitionCircuit(t,e){var r;const i=this.circuitState;this.circuitState=t,t===a.OPEN&&(this.circuitOpenedAt=Date.now()),(0,s.getLogger)().warn("Circuit breaker state change",{previousState:i,newState:t,trigger:e}),null===(r=this.onCircuitStateChange)||void 0===r||r.call(this,{previousState:i,newState:t,trigger:e})}async acquireSlot(){if(!(this.activeRequests<n.MAX_CONCURRENT_REQUESTS))return new Promise((t=>{this.requestQueue.push({resolve:()=>{this.activeRequests++,t()}})}));this.activeRequests++}releaseSlot(){this.activeRequests--;const t=this.requestQueue.shift();t&&t.resolve()}}},60922:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.StreamableHTTPClientTransport=e.StreamableHTTPError=void 0;const i=r(72143),o=r(5744),n=r(33205),s={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class a extends Error{constructor(t,e){super(`Streamable HTTP error: ${e}`),this.code=t}}e.StreamableHTTPError=a;e.StreamableHTTPClientTransport=class{constructor(t,e){var r;this._url=t,this._requestInit=null==e?void 0:e.requestInit,this._authProvider=null==e?void 0:e.authProvider,this._sessionId=null==e?void 0:e.sessionId,this._reconnectionOptions=null!==(r=null==e?void 0:e.reconnectionOptions)&&void 0!==r?r:s}async _authThenStart(){var t;if(!this._authProvider)throw new o.UnauthorizedError("No auth provider");let e;try{e=await(0,o.auth)(this._authProvider,{serverUrl:this._url})}catch(e){throw null===(t=this.onerror)||void 0===t||t.call(this,e),e}if("AUTHORIZED"!==e)throw new o.UnauthorizedError;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}return this._sessionId&&(e["mcp-session-id"]=this._sessionId),new Headers({...e,...null===(t=this._requestInit)||void 0===t?void 0:t.headers})}async _startOrAuthSse(t){var e,r;const{resumptionToken:i}=t;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),i&&r.set("last-event-id",i);const o=await fetch(this._url,{method:"GET",headers:r,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal});if(!o.ok){if(401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new a(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t)}catch(t){throw null===(r=this.onerror)||void 0===r||r.call(this,t),t}}_getNextReconnectionDelay(t){const e=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(e*Math.pow(r,t),i)}_scheduleReconnection(t,e=0){var r;const i=this._reconnectionOptions.maxRetries;if(i>0&&e>=i)return void(null===(r=this.onerror)||void 0===r||r.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`)));const o=this._getNextReconnectionDelay(e);setTimeout((()=>{this._startOrAuthSse(t).catch((r=>{var i;null===(i=this.onerror)||void 0===i||i.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(t,e+1)}))}),o)}_handleSseStream(t,e){if(!t)return;const{onresumptiontoken:r,replayMessageId:o}=e;let s;(async()=>{var e,a,c,l;try{const c=t.pipeThrough(new TextDecoderStream).pipeThrough(new n.EventSourceParserStream).getReader();for(;;){const{value:t,done:n}=await c.read();if(n)break;if(t.id&&(s=t.id,null==r||r(t.id)),!t.event||"message"===t.event)try{const r=i.JSONRPCMessageSchema.parse(JSON.parse(t.data));void 0!==o&&(0,i.isJSONRPCResponse)(r)&&(r.id=o),null===(e=this.onmessage)||void 0===e||e.call(this,r)}catch(t){null===(a=this.onerror)||void 0===a||a.call(this,t)}}}catch(t){if(null===(c=this.onerror)||void 0===c||c.call(this,new Error(`SSE stream disconnected: ${t}`)),this._abortController&&!this._abortController.signal.aborted&&void 0!==s)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:o},0)}catch(t){null===(l=this.onerror)||void 0===l||l.call(this,new Error(`Failed to reconnect: ${t instanceof Error?t.message:String(t)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new o.UnauthorizedError("No auth provider");if("AUTHORIZED"!==await(0,o.auth)(this._authProvider,{serverUrl:this._url,authorizationCode:t}))throw new o.UnauthorizedError("Failed to authorize")}async close(){var t,e;null===(t=this._abortController)||void 0===t||t.abort(),null===(e=this.onclose)||void 0===e||e.call(this)}async send(t,e){var r,n,s;try{const{resumptionToken:s,onresumptiontoken:c}=e||{};if(s)return void this._startOrAuthSse({resumptionToken:s,replayMessageId:(0,i.isJSONRPCRequest)(t)?t.id:void 0}).catch((t=>{var e;return null===(e=this.onerror)||void 0===e?void 0:e.call(this,t)}));const l=await this._commonHeaders();l.set("content-type","application/json"),l.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:l,body:JSON.stringify(t),signal:null===(r=this._abortController)||void 0===r?void 0:r.signal},h=await fetch(this._url,u),d=h.headers.get("mcp-session-id");if(d&&(this._sessionId=d),!h.ok){if(401===h.status&&this._authProvider){if("AUTHORIZED"!==await(0,o.auth)(this._authProvider,{serverUrl:this._url}))throw new o.UnauthorizedError;return this.send(t)}const e=await h.text().catch((()=>null));throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${e}`)}if(202===h.status)return void((0,i.isInitializedNotification)(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch((t=>{var e;return null===(e=this.onerror)||void 0===e?void 0:e.call(this,t)})));const p=(Array.isArray(t)?t:[t]).filter((t=>"method"in t&&"id"in t&&void 0!==t.id)).length>0,m=h.headers.get("content-type");if(p)if(null==m?void 0:m.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:c});else{if(!(null==m?void 0:m.includes("application/json")))throw new a(-1,`Unexpected content type: ${m}`);{const t=await h.json(),e=Array.isArray(t)?t.map((t=>i.JSONRPCMessageSchema.parse(t))):[i.JSONRPCMessageSchema.parse(t)];for(const t of e)null===(n=this.onmessage)||void 0===n||n.call(this,t)}}}catch(t){throw null===(s=this.onerror)||void 0===s||s.call(this,t),t}}get sessionId(){return this._sessionId}async terminateSession(){var t,e;if(this._sessionId)try{const e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:null===(t=this._abortController)||void 0===t?void 0:t.signal},i=await fetch(this._url,r);if(!i.ok&&405!==i.status)throw new a(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(t){throw null===(e=this.onerror)||void 0===e||e.call(this,t),t}}}},70080:(t,e,r)=>{let i;async function o(t){return(await i).getRandomValues(new Uint8Array(t))}async function n(t){const e=await(await i).subtle.digest("SHA-256",(new TextEncoder).encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}Object.defineProperty(e,"__esModule",{value:!0}),e.generateChallenge=n,e.default=async function(t){t||(t=43);if(t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await async function(t){return await async function(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let i="";for(;i.length<t;){const n=await o(t-i.length);for(const t of n)t<r&&(i+=e[t%e.length])}return i}(t)}(t),r=await n(e);return{code_verifier:e,code_challenge:r}},e.verifyChallenge=async function(t,e){return await n(t)===e},i=globalThis.crypto?.webcrypto??globalThis.crypto??Promise.resolve().then(r.t.bind(r,77598,23)).then((t=>t.webcrypto))},93119:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});var r=Object.defineProperty,i=(t,e,i)=>((t,e,i)=>e in t?r(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i);class o extends Error{constructor(t,e){super(t),i(this,"type"),i(this,"field"),i(this,"value"),i(this,"line"),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function n(t){}e.ParseError=o,e.createParser=function(t){const{onEvent:e=n,onError:r=n,onRetry:i=n,onComment:s}=t;let a,c="",l=!0,u="",h="";function d(t){if(""===t)return u.length>0&&e({id:a,event:h||void 0,data:u.endsWith("\n")?u.slice(0,-1):u}),a=void 0,u="",void(h="");if(t.startsWith(":"))return void(s&&s(t.slice(t.startsWith(": ")?2:1)));const r=t.indexOf(":");if(-1===r)p(t,"",t);else{const e=t.slice(0,r),i=" "===t[r+1]?2:1;p(e,t.slice(r+i),t)}}function p(t,e,n){switch(t){case"event":h=e;break;case"data":u=`${u}${e}\n`;break;case"id":a=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?i(parseInt(e,10)):r(new o(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:n}));break;default:r(new o(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:n}))}}return{feed:function(t){const e=l?t.replace(/^\xEF\xBB\xBF/,""):t,[r,i]=function(t){const e=[];let r="";const i=t.length;for(let o=0;o<i;o++){const i=t[o];"\r"===i&&"\n"===t[o+1]?(e.push(r),r="",o++):"\r"===i||"\n"===i?(e.push(r),r=""):r+=i}return[e,r]}(`${c}${e}`);for(const t of r)d(t);c=i,l=!1},reset:function(t={}){c&&t.consume&&d(c),a=void 0,u="",h="",c=""}}}}};
|