@amazon-devices/amazon-devices-buildertools-mcp 0.1.26 → 0.1.29
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 +0 -4
- package/README.md +57 -5
- package/dist/171.startserver +1 -0
- package/dist/assets/vega-developer-context.db +0 -0
- package/dist/startserver +3 -3
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -36,10 +36,6 @@ Amazon Devices Builder Tools MCPは以下の機能をサポートしています
|
|
|
36
36
|
|
|
37
37
|
[](https://cursor.com/en-US/install-mcp?name=amazon-devices-buildertools-mcp&config=eyJjb21tYW5kIjoibnB4IC15IEBhbWF6b24tZGV2aWNlcy9hbWF6b24tZGV2aWNlcy1idWlsZGVydG9vbHMtbWNwQGxhdGVzdCJ9)
|
|
38
38
|
|
|
39
|
-
### VSCodeにMCPをインストール
|
|
40
|
-
|
|
41
|
-
[Add to VSCode](vscode:mcp/install?%7B%22name%22%3A%22amazon-devices-buildertools-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40amazon-devices%2Famazon-devices-buildertools-mcp%40latest%22%5D%7D)
|
|
42
|
-
|
|
43
39
|
|
|
44
40
|
## スクリプトによるインストール
|
|
45
41
|
|
package/README.md
CHANGED
|
@@ -36,10 +36,6 @@ Some of the popular AI Agents support installing MCP servers with a single click
|
|
|
36
36
|
|
|
37
37
|
[](https://cursor.com/en-US/install-mcp?name=amazon-devices-buildertools-mcp&config=eyJjb21tYW5kIjoibnB4IC15IEBhbWF6b24tZGV2aWNlcy9hbWF6b24tZGV2aWNlcy1idWlsZGVydG9vbHMtbWNwQGxhdGVzdCJ9)
|
|
38
38
|
|
|
39
|
-
### Install MCP on VSCode
|
|
40
|
-
|
|
41
|
-
[Add to VSCode](vscode:mcp/install?%7B%22name%22%3A%22amazon-devices-buildertools-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40amazon-devices%2Famazon-devices-buildertools-mcp%40latest%22%5D%7D)
|
|
42
|
-
|
|
43
39
|
## Installation with script
|
|
44
40
|
|
|
45
41
|
Run the following command to **automatically** install Amazon Devices Builder Tools MCP in your AI Agent and add Vega-specific context document to your project to guide AI agents:
|
|
@@ -234,6 +230,9 @@ You should see a response that includes the following tools:
|
|
|
234
230
|
- get_app_hot_functions
|
|
235
231
|
- read_document
|
|
236
232
|
- list_documents
|
|
233
|
+
- search_documents
|
|
234
|
+
- execute_query
|
|
235
|
+
- get_database_schema
|
|
237
236
|
- read_asset
|
|
238
237
|
|
|
239
238
|
## MCP Tools
|
|
@@ -318,7 +317,60 @@ or with time window filtering:
|
|
|
318
317
|
Analyze hot functions in /path/to/trace.json from 5 to 15 seconds with a limit of 20 functions
|
|
319
318
|
```
|
|
320
319
|
|
|
321
|
-
### 5. `
|
|
320
|
+
### 5. `search_documents`
|
|
321
|
+
|
|
322
|
+
Search Vega development documentation using full-text search. Returns document IDs and relevant snippets matching the query. Use `read_document` with the returned ID to get full content.
|
|
323
|
+
|
|
324
|
+
**Parameters:**
|
|
325
|
+
|
|
326
|
+
- `query` (required): Search query string to find relevant documents
|
|
327
|
+
- `snippet_tokens` (optional): Maximum tokens in returned snippets (default: 32)
|
|
328
|
+
|
|
329
|
+
**Example usage:**
|
|
330
|
+
|
|
331
|
+
```
|
|
332
|
+
Search for documents about "performance optimization"
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
or with custom snippet length:
|
|
336
|
+
|
|
337
|
+
```
|
|
338
|
+
Search for "React Native best practices" with 64 token snippets
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
### 6. `get_database_schema`
|
|
342
|
+
|
|
343
|
+
Get the schema for the Vega documentation database. Call this before using `execute_query` to understand available tables, columns, and FTS5 syntax.
|
|
344
|
+
|
|
345
|
+
**Parameters:** None
|
|
346
|
+
|
|
347
|
+
**Example usage:**
|
|
348
|
+
|
|
349
|
+
```
|
|
350
|
+
Get the database schema for Vega documentation
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### 7. `execute_query`
|
|
354
|
+
|
|
355
|
+
Execute a SQL query against the Vega documentation database. Use this tool for more complex queries when `search_documents` is insufficient. Use `get_database_schema` first to understand available tables and FTS5 syntax. The database is read-only.
|
|
356
|
+
|
|
357
|
+
**Parameters:**
|
|
358
|
+
|
|
359
|
+
- `sql_query` (required): SQL query to execute against the documentation database
|
|
360
|
+
|
|
361
|
+
**Example usage:**
|
|
362
|
+
|
|
363
|
+
```
|
|
364
|
+
Execute query to search for "performance OR optimization" with custom snippets
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
or with a specific SQL query:
|
|
368
|
+
|
|
369
|
+
```
|
|
370
|
+
Execute query: SELECT dc.id, snippet(document_content_fts, 0, "<b>", "</b>", "...", 64) FROM document_content_fts JOIN document_content dc ON document_content_fts.rowid = dc.rowid WHERE document_content_fts MATCH "performance OR optimization" ORDER BY rank LIMIT 10
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
### 8. `read_asset`
|
|
322
374
|
|
|
323
375
|
Read assets referenced in Vega documentation. Assets are saved to a temporary location and the path is returned. Images can be viewed with
|
|
324
376
|
`fs_read` and scripts executed with the appropriate interpreter (e.g., `python3`)
|
|
@@ -0,0 +1 @@
|
|
|
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=""}}}}};
|
|
Binary file
|